JAL-629 Open Structure Viewer from cmdline
[jalview.git] / src / jalview / bin / Commands.java
index 420e1d1..0cdc541 100644 (file)
@@ -1,15 +1,25 @@
 package jalview.bin;
 
 import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 
 import jalview.analysis.AlignmentUtils;
+import jalview.api.AlignmentViewPanel;
 import jalview.bin.ArgParser.Arg;
 import jalview.bin.ArgParser.ArgValues;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
+import jalview.gui.AlignmentPanel;
 import jalview.gui.Desktop;
+import jalview.gui.StructureChooser;
 import jalview.io.AppletFormatAdapter;
 import jalview.io.DataSourceType;
 import jalview.io.FileFormatException;
@@ -19,6 +29,7 @@ import jalview.io.IdentifyFile;
 import jalview.util.HttpUtils;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
+import jalview.ws.dbsources.EBIAlfaFold;
 
 public class Commands
 {
@@ -34,16 +45,19 @@ public class Commands
   {
     argParser = ap;
     headless = h;
-    for (String id : argParser.linkedIds())
+    if (argParser != null && argParser.linkedIds() != null)
     {
-      Commands cmds = new Commands();
-      if (id == null)
+      for (String id : argParser.linkedIds())
       {
-        cmds.processUnlinked(id);
-      }
-      else
-      {
-        cmds.processLinked(id);
+        Commands cmds = new Commands();
+        if (id == null)
+        {
+          cmds.processUnlinked(id);
+        }
+        else
+        {
+          cmds.processLinked(id);
+        }
       }
     }
   }
@@ -67,7 +81,6 @@ public class Commands
   protected void processLinked(String id)
   {
     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
-    FileLoader fileLoader = new FileLoader(!headless);
 
     /*
     // script to execute after all loading is completed one way or another
@@ -90,7 +103,6 @@ public class Commands
       {
         if (openFile == null)
           continue OPEN;
-        Console.debug("********** id = " + id + ", openFile = " + openFile);
 
         if (first)
         {
@@ -136,12 +148,55 @@ public class Commands
         af = afMap.get(id);
         if (af == null)
         {
+          // get kind of temperature factor annotation
+          AlignmentAnnotation.TFType tempfacType = null;
+          if ((m.get(Arg.NOTEMPFAC) == null
+                  || !m.get(Arg.NOTEMPFAC).getBoolean())
+                  && m.get(Arg.TEMPFAC) != null)
+          {
+            try
+            {
+              tempfacType = AlignmentAnnotation.TFType
+                      .valueOf(m.get(Arg.TEMPFAC).getValue()
+                              .toUpperCase(Locale.ROOT));
+              Console.debug("Obtained Temperature Factor type of '"
+                      + tempfacType + "'");
+            } catch (IllegalArgumentException e)
+            {
+              StringBuilder sb = new StringBuilder().append("Cannot set --")
+                      .append(Arg.TEMPFAC.getName()).append(" to '")
+                      .append(tempfacType)
+                      .append("', ignoring.  Valid values are: ");
+              Iterator<AlignmentAnnotation.TFType> it = Arrays
+                      .stream(AlignmentAnnotation.TFType.values())
+                      .iterator();
+              while (it.hasNext())
+              {
+                sb.append(it.next().toString().toLowerCase(Locale.ROOT));
+                if (it.hasNext())
+                  sb.append(", ");
+              }
+              Console.warn(sb.toString());
+            }
+          }
+
           Console.debug(
                   "Opening '" + openFile + "' in new alignment frame");
-          af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
-                  format);
+          FileLoader fileLoader = new FileLoader(!headless);
+          af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol, format,
+                  tempfacType);
+
+          // wrap alignment?
+          if (m.get(Arg.WRAP) != null && m.get(Arg.WRAP).getBoolean())
+          {
+            af.getCurrentView().setWrapAlignment(true);
+          }
+
+          // change alignment frame title
           if (m.get(Arg.TITLE) != null)
             af.setTitle(m.get(Arg.TITLE).getValue());
+
+          // show secondary structure annotations?
           if (m.get(Arg.SSANNOTATION) != null
                   && !m.get(Arg.SSANNOTATION).getBoolean())
           {
@@ -151,19 +206,34 @@ public class Commands
                     Collections.singleton("Secondary Structure"), null,
                     false, false);
           }
+
+          // show temperature factor annotations?
           if (m.get(Arg.NOTEMPFAC) != null
                   && m.get(Arg.NOTEMPFAC).getBoolean())
           {
             // do this better (annotation types?)
+            List<String> hideThese = new ArrayList<>();
+            hideThese.add("Temperature Factor");
+            hideThese.add(MessageManager
+                    .getString("label.alphafold_reliability"));
             AlignmentUtils.showOrHideSequenceAnnotations(
-                    af.getCurrentView().getAlignment(),
-                    Collections.singleton("Temperature Factor"), null,
-                    false, false);
-            AlignmentUtils.showOrHideSequenceAnnotations(
-                    af.getCurrentView().getAlignment(),
-                    Collections.singleton("Alphafold Reliability"), null,
+                    af.getCurrentView().getAlignment(), hideThese, null,
                     false, false);
           }
+          else
+          {
+            if (m.get(Arg.TEMPFAC_LABEL) != null)
+            {
+              AlignmentAnnotation aa = AlignmentUtils
+                      .getFirstSequenceAnnotationOfType(
+                              af.getCurrentView().getAlignment(),
+                              AlignmentAnnotation.LINE_GRAPH);
+              if (aa != null)
+              {
+                aa.label = m.get(Arg.TEMPFAC_LABEL).getValue();
+              }
+            }
+          }
 
           // store the AlignFrame for this id
           afMap.put(id, af);
@@ -195,6 +265,160 @@ public class Commands
       }
 
     }
+
+    // load a pAE file if given
+    if (m.get(Arg.PAEMATRIX) != null)
+    {
+      AlignFrame af = afMap.get(id);
+      if (af != null)
+      {
+        for (String val : m.get(Arg.PAEMATRIX).getValues())
+        {
+          SubId subId = new SubId(val);
+          File paeFile = new File(subId.content);
+          EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
+                  paeFile, subId.index,
+                  "id".equals(subId.keyName) ? subId.keyValue : null);
+          // required to readjust the height and position of the pAE
+          // annotation
+          for (AlignmentViewPanel ap : af.getAlignPanels())
+          {
+            ap.adjustAnnotationHeight();
+          }
+        }
+      }
+    }
+
+    // open the structure (from same PDB file or given PDBfile)
+    if (m.get(Arg.NOSTRUCTURE) == null
+            || !m.get(Arg.NOQUESTIONNAIRE).getBoolean())
+    {
+      AlignFrame af = afMap.get(id);
+      if (m.get(Arg.STRUCTURE) != null)
+      {
+        STRUCTURE: for (String val : m.get(Arg.STRUCTURE).getValues())
+        {
+          SubId subId = new SubId(val);
+          SequenceI seq = getSpecifiedSequence(af, subId);
+          if (seq == null)
+          {
+            Console.warn("Could not find sequence for argument --"
+                    + Arg.STRUCTURE + "=" + val);
+            break STRUCTURE;
+          }
+          File structureFile = null;
+          if (subId.content != null && subId.content.length() != 0)
+          {
+            structureFile = new File(subId.content);
+            Console.debug("Using structure file (from argument) '"
+                    + structureFile.getAbsolutePath() + "'");
+          }
+          /* THIS DOESN'T WORK */
+          else if (seq.getAllPDBEntries() != null
+                  && seq.getAllPDBEntries().size() > 0)
+          {
+            structureFile = new File(
+                    seq.getAllPDBEntries().elementAt(0).getFile());
+            Console.debug("Using structure file (from sequence) '"
+                    + structureFile.getAbsolutePath() + "'");
+          }
+
+          if (structureFile == null)
+          {
+            Console.warn("Not provided structure file with '" + val + "'");
+            continue STRUCTURE;
+          }
+
+          if (!structureFile.exists())
+          {
+            Console.warn("Structure file '"
+                    + structureFile.getAbsoluteFile() + "' not found.");
+            continue STRUCTURE;
+          }
+
+          Console.debug("Using structure file "
+                  + structureFile.getAbsolutePath());
+
+          // open structure view
+          AlignmentPanel ap = af.alignPanel;
+          StructureChooser.openStructureFileForSequence(ap, seq,
+                  structureFile);
+        }
+      }
+    }
+  }
+
+  private SequenceI getSpecifiedSequence(AlignFrame af, SubId subId)
+  {
+    SequenceI seq = null;
+    SequenceI[] sequences = af.getCurrentView().getAlignment()
+            .getSequencesArray();
+    if (-1 < subId.index && subId.index < sequences.length)
+    {
+      seq = sequences[subId.index];
+    }
+    else if ("id".equals(subId.keyName))
+    {
+      for (SequenceI s : sequences)
+      {
+        if (s.getDisplayId(false).equals(subId.keyValue))
+        {
+          seq = s;
+          break;
+        }
+      }
+    }
+    return seq;
   }
 
+  /**
+   * A helper class to parse a string of the possible forms "content"
+   * "[index]content", "[keyName=keyValue]content" and return the integer index,
+   * the strings keyName and keyValue, and the content after the square brackets
+   * (if present). Values not set will be -1 or null.
+   */
+  protected class SubId
+  {
+    protected int index = 0;
+
+    protected String keyName = null;
+
+    protected String keyValue = null;
+
+    protected String content = null;
+
+    protected SubId(String item)
+    {
+      if (item.indexOf('[') == 0 && item.indexOf(']') > 1)
+      {
+        int openBracket = item.indexOf('[');
+        int closeBracket = item.indexOf(']');
+        String indexString = item.substring(openBracket + 1, closeBracket);
+        this.content = item.substring(closeBracket + 1);
+        int equals = indexString.indexOf('=');
+        if (equals > -1)
+        {
+          this.keyName = indexString.substring(0, equals);
+          this.keyValue = indexString.substring(equals + 1);
+          this.index = -1;
+        }
+        else
+        {
+          try
+          {
+            this.index = Integer.parseInt(indexString);
+          } catch (NumberFormatException e)
+          {
+            Console.warn("Failed to obtain sequenced id or index from '"
+                    + item + "'. Setting index=0 and using content='"
+                    + content + "'.");
+          }
+        }
+      }
+      else
+      {
+        this.content = item;
+      }
+    }
+  }
 }