JAL-3551 concatenate colour by sequence commands for all except PyMOL
[jalview.git] / src / jalview / ext / rbvi / chimera / ChimeraCommands.java
index 1b1dd35..c9dbc1d 100644 (file)
  */
 package jalview.ext.rbvi.chimera;
 
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
@@ -29,20 +37,12 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.gui.Desktop;
 import jalview.structure.AtomSpecModel;
+import jalview.structure.StructureCommand;
+import jalview.structure.StructureCommandI;
 import jalview.structure.StructureCommandsBase;
 import jalview.structure.StructureMapping;
 import jalview.structure.StructureSelectionManager;
 import jalview.util.ColorUtils;
-import jalview.util.IntRangeComparator;
-
-import java.awt.Color;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
 
 /**
  * Routines for generating Chimera commands for Jalview/Chimera binding
@@ -52,21 +52,26 @@ import java.util.Map;
  */
 public class ChimeraCommands extends StructureCommandsBase
 {
+  private static final StructureCommand SHOW_BACKBONE = new StructureCommand(
+          "~display all;~ribbon;chain @CA|P");
+
   public static final String NAMESPACE_PREFIX = "jv_";
 
-  private static final String CMD_COLOUR_BY_CHARGE = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
+  private static final StructureCommandI COLOUR_BY_CHARGE = new StructureCommand(
+          "color white;color red ::ASP,GLU;color blue ::LYS,ARG;color yellow ::CYS");
 
-  private static final String CMD_COLOUR_BY_CHAIN = "rainbow chain";
+  private static final StructureCommandI COLOUR_BY_CHAIN = new StructureCommand(
+          "rainbow chain");
 
   // Chimera clause to exclude alternate locations in atom selection
   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
 
   @Override
-  public String getColourCommand(String atomSpec, Color colour)
+  public StructureCommandI getColourCommand(String atomSpec, Color colour)
   {
     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/color.html
     String colourCode = getColourString(colour);
-    return "color " + colourCode + " " + atomSpec;
+    return new StructureCommand("color " + colourCode + " " + atomSpec);
   }
 
   /**
@@ -92,7 +97,7 @@ public class ChimeraCommands extends StructureCommandsBase
    * @return
    */
   @Override
-  public String[] setAttributesForFeatures(
+  public List<StructureCommandI> setAttributesForFeatures(
           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
           AlignmentViewPanel viewPanel)
   {
@@ -155,6 +160,7 @@ public class ChimeraCommands extends StructureCommandsBase
     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
     {
       final int modelNumber = pdbfnum + getModelStartNo();
+      String modelId = String.valueOf(modelNumber);
       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
 
       if (mapping == null || mapping.length < 1)
@@ -178,12 +184,12 @@ public class ChimeraCommands extends StructureCommandsBase
             if (!visibleFeatures.isEmpty())
             {
               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
-                      theMap, modelNumber);
+                      theMap, modelId);
             }
             if (showLinkedFeatures)
             {
               scanComplementFeatures(complementRenderer, structureMapping,
-                      seq, theMap, modelNumber);
+                      seq, theMap, modelId);
             }
           }
         }
@@ -205,7 +211,8 @@ public class ChimeraCommands extends StructureCommandsBase
   protected static void scanComplementFeatures(
           FeatureRenderer complementRenderer,
           StructureMapping structureMapping, SequenceI seq,
-          Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
+          Map<String, Map<Object, AtomSpecModel>> theMap,
+          String modelNumber)
   {
     /*
      * for each sequence residue mapped to a structure position...
@@ -269,19 +276,19 @@ public class ChimeraCommands extends StructureCommandsBase
   }
 
   /**
-   * Inspect features on the sequence; for each feature that is visible, determine
-   * its mapped ranges in the structure (if any) according to the given mapping,
-   * and add them to the map.
+   * Inspect features on the sequence; for each feature that is visible,
+   * determine its mapped ranges in the structure (if any) according to the
+   * given mapping, and add them to the map.
    * 
    * @param visibleFeatures
    * @param mapping
    * @param seq
    * @param theMap
-   * @param modelNumber
+   * @param modelId
    */
   protected static void scanSequenceFeatures(List<String> visibleFeatures,
           StructureMapping mapping, SequenceI seq,
-          Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
+          Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
   {
     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
             visibleFeatures.toArray(new String[visibleFeatures.size()]));
@@ -321,7 +328,7 @@ public class ChimeraCommands extends StructureCommandsBase
         }
         for (int[] range : mappedRanges)
         {
-          addAtomSpecRange(featureValues, value, modelNumber, range[0],
+          addAtomSpecRange(featureValues, value, modelId, range[0],
                   range[1], mapping.getChain());
         }
       }
@@ -343,10 +350,10 @@ public class ChimeraCommands extends StructureCommandsBase
    * @param featureMap
    * @return
    */
-  protected String[] setAttributes(
+  protected List<StructureCommandI> setAttributes(
           Map<String, Map<Object, AtomSpecModel>> featureMap)
   {
-    List<String> commands = new ArrayList<>();
+    List<StructureCommandI> commands = new ArrayList<>();
     for (String featureType : featureMap.keySet())
     {
       String attributeName = makeAttributeName(featureType);
@@ -368,13 +375,13 @@ public class ChimeraCommands extends StructureCommandsBase
         AtomSpecModel atomSpecModel = values.get(value);
         String featureValue = value.toString();
         featureValue = featureValue.replaceAll("\\'", "&#39;");
-        String cmd = setAttribute(attributeName, featureValue,
+        StructureCommandI cmd = setAttribute(attributeName, featureValue,
                 atomSpecModel);
         commands.add(cmd);
       }
     }
 
-    return commands.toArray(new String[commands.size()]);
+    return commands;
   }
 
   /**
@@ -390,7 +397,7 @@ public class ChimeraCommands extends StructureCommandsBase
    * @param atomSpecModel
    * @return
    */
-  protected String setAttribute(String attributeName,
+  protected StructureCommandI setAttribute(String attributeName,
           String attributeValue,
           AtomSpecModel atomSpecModel)
   {
@@ -398,7 +405,7 @@ public class ChimeraCommands extends StructureCommandsBase
     sb.append("setattr res ").append(attributeName).append(" '")
             .append(attributeValue).append("' ");
     sb.append(getAtomSpec(atomSpecModel, false));
-    return sb.toString();
+    return new StructureCommand(sb.toString());
   }
 
   /**
@@ -435,15 +442,15 @@ public class ChimeraCommands extends StructureCommandsBase
   }
 
   @Override
-  public String colourByChain()
+  public StructureCommandI colourByChain()
   {
-    return CMD_COLOUR_BY_CHAIN;
+    return COLOUR_BY_CHAIN;
   }
 
   @Override
-  public String colourByCharge()
+  public List<StructureCommandI> colourByCharge()
   {
-    return CMD_COLOUR_BY_CHARGE;
+    return Arrays.asList(COLOUR_BY_CHARGE);
   }
 
   @Override
@@ -453,21 +460,21 @@ public class ChimeraCommands extends StructureCommandsBase
   }
 
   @Override
-  public String setBackgroundColour(Color col)
+  public StructureCommandI setBackgroundColour(Color col)
   {
     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/set.html#bgcolor
-    return "set bgColor " + ColorUtils.toTkCode(col);
+    return new StructureCommand("set bgColor " + ColorUtils.toTkCode(col));
   }
 
   @Override
-  public String focusView()
+  public StructureCommandI focusView()
   {
     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/focus.html
-    return "focus";
+    return new StructureCommand("focus");
   }
 
   @Override
-  public String showChains(List<String> toShow)
+  public List<StructureCommandI> showChains(List<String> toShow)
   {
     /*
      * Construct a chimera command like
@@ -498,48 +505,49 @@ public class ChimeraCommands extends StructureCommandsBase
      */
     final String command = "~display #*; ~ribbon #*; ribbon :"
             + cmd.toString();
-    return command;
+    return Arrays.asList(new StructureCommand(command));
   }
 
   @Override
-  public String superposeStructures(AtomSpecModel spec, AtomSpecModel ref)
+  public List<StructureCommandI> superposeStructures(AtomSpecModel ref,
+          AtomSpecModel spec)
   {
     /*
      * Form Chimera match command to match spec to ref
+     * (the first set of atoms are moved on to the second)
      * 
      * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
      * 
-     * @see
-     * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
+     * @see https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
      */
     StringBuilder cmd = new StringBuilder();
-    String atomSpec = getAtomSpec(spec, true);
-    String refSpec = getAtomSpec(ref, true);
-    cmd.append("match ").append(atomSpec).append(" ").append(refSpec);
+    String atomSpecAlphaOnly = getAtomSpec(spec, true);
+    String refSpecAlphaOnly = getAtomSpec(ref, true);
+    cmd.append("match ").append(atomSpecAlphaOnly).append(" ").append(refSpecAlphaOnly);
 
     /*
-     * show superposed residues as ribbon, others as chain
+     * show superposed residues as ribbon
      */
-    // fixme this should precede the loop over all alignments/structures
-    cmd.append(";~display all; chain @CA|P");
+    String atomSpec = getAtomSpec(spec, false);
+    String refSpec = getAtomSpec(ref, false);
     cmd.append("; ribbon ");
     cmd.append(atomSpec).append("|").append(refSpec).append("; focus");
 
-    return cmd.toString();
+    return Arrays.asList(new StructureCommand(cmd.toString()));
   }
 
   @Override
-  public String openCommandFile(String path)
+  public StructureCommandI openCommandFile(String path)
   {
     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
-    return "open cmd:" + path;
+    return new StructureCommand("open cmd:" + path);
   }
 
   @Override
-  public String saveSession(String filepath)
+  public StructureCommandI saveSession(String filepath)
   {
     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
-    return "save " + filepath;
+    return new StructureCommand("save " + filepath);
   }
 
   /**
@@ -571,7 +579,7 @@ public class ChimeraCommands extends StructureCommandsBase
   {
     StringBuilder sb = new StringBuilder(128);
     boolean firstModel = true;
-    for (Integer model : atomSpec.getModels())
+    for (String model : atomSpec.getModels())
     {
       if (!firstModel)
       {
@@ -591,7 +599,7 @@ public class ChimeraCommands extends StructureCommandsBase
    * @param atomSpec
    * @param alphaOnly
    */
-  protected void appendModel(StringBuilder sb, Integer model,
+  protected void appendModel(StringBuilder sb, String model,
           AtomSpecModel atomSpec, boolean alphaOnly)
   {
     sb.append("#").append(model).append(":");
@@ -603,46 +611,10 @@ public class ChimeraCommands extends StructureCommandsBase
       chain = " ".equals(chain) ? chain : chain.trim();
 
       List<int[]> rangeList = atomSpec.getRanges(model, chain);
-
-      /*
-       * sort ranges into ascending start position order
-       */
-      Collections.sort(rangeList, IntRangeComparator.ASCENDING);
-
-      int start = rangeList.isEmpty() ? 0 : rangeList.get(0)[0];
-      int end = rangeList.isEmpty() ? 0 : rangeList.get(0)[1];
-
-      Iterator<int[]> iterator = rangeList.iterator();
-      while (iterator.hasNext())
+      for (int[] range : rangeList)
       {
-        int[] range = iterator.next();
-        if (range[0] <= end + 1)
-        {
-          /*
-           * range overlaps or is contiguous with the last one
-           * - so just extend the end position, and carry on
-           * (unless this is the last in the list)
-           */
-          end = Math.max(end, range[1]);
-        }
-        else
-        {
-          /*
-           * we have a break so append the last range
-           */
-          appendRange(sb, start, end, chain, firstPositionForModel, false);
-          firstPositionForModel = false;
-          start = range[0];
-          end = range[1];
-        }
-      }
-
-      /*
-       * and append the last range
-       */
-      if (!rangeList.isEmpty())
-      {
-        appendRange(sb, start, end, chain, firstPositionForModel, false);
+        appendRange(sb, range[0], range[1], chain, firstPositionForModel,
+                false);
         firstPositionForModel = false;
       }
     }
@@ -652,14 +624,48 @@ public class ChimeraCommands extends StructureCommandsBase
        * restrict to alpha carbon, no alternative locations
        * (needed to ensuring matching atom counts for superposition)
        */
-      sb.append("@CA|P").append(NO_ALTLOCS);
+      // TODO @P instead if RNA - add nucleotide flag to AtomSpecModel?
+      sb.append("@CA").append(NO_ALTLOCS);
     }
   }
 
   @Override
-  public String showBackbone()
+  public List<StructureCommandI> showBackbone()
+  {
+    return Arrays.asList(SHOW_BACKBONE);
+  }
+
+  @Override
+  public StructureCommandI loadFile(String file)
   {
-    return "~display all;chain @CA|P";
+    return new StructureCommand("open " + file);
+  }
+
+  /**
+   * Overrides the default method to concatenate colour commands into one
+   */
+  @Override
+  public List<StructureCommandI> colourBySequence(
+          Map<Object, AtomSpecModel> colourMap)
+  {
+    List<StructureCommandI> commands = new ArrayList<>();
+    StringBuilder sb = new StringBuilder(colourMap.size() * 20);
+    boolean first = true;
+    for (Object key : colourMap.keySet())
+    {
+      Color colour = (Color) key;
+      final AtomSpecModel colourData = colourMap.get(colour);
+      StructureCommandI command = getColourCommand(colourData, colour);
+      if (!first)
+      {
+        sb.append(getCommandSeparator());
+      }
+      first = false;
+      sb.append(command.getCommand());
+    }
+
+    commands.add(new StructureCommand(sb.toString()));
+    return commands;
   }
 
 }