JAL-2295 extracted AtomSpecModel for reuse in Chimera commands
[jalview.git] / src / jalview / ext / rbvi / chimera / ChimeraCommands.java
index bece4eb..93262aa 100644 (file)
@@ -23,6 +23,7 @@ package jalview.ext.rbvi.chimera;
 import jalview.api.FeatureRenderer;
 import jalview.api.SequenceRenderer;
 import jalview.datamodel.AlignmentI;
+import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.structure.StructureMapping;
 import jalview.structure.StructureMappingcommandSet;
@@ -32,10 +33,10 @@ import jalview.util.Comparison;
 
 import java.awt.Color;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.TreeMap;
 
 /**
  * Routines for generating Chimera commands for Jalview/Chimera binding
@@ -53,21 +54,21 @@ public class ChimeraCommands
    * @returns Object[] { Object[] { <model being coloured>,
    * 
    */
-  public static StructureMappingcommandSet[] getColourBySequenceCommand(
+  public static StructureMappingcommandSet getColourBySequenceCommand(
           StructureSelectionManager ssm, String[] files,
           SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
           AlignmentI alignment)
   {
-    Map<Color, Map<Integer, Map<String, List<int[]>>>> colourMap = buildColoursMap(
+    Map<Color, AtomSpecModel> colourMap = buildColoursMap(
             ssm, files, sequence, sr, fr, alignment);
 
     List<String> colourCommands = buildColourCommands(colourMap);
 
     StructureMappingcommandSet cs = new StructureMappingcommandSet(
             ChimeraCommands.class, null,
-            colourCommands.toArray(new String[0]));
+            colourCommands.toArray(new String[colourCommands.size()]));
 
-    return new StructureMappingcommandSet[] { cs };
+    return cs;
   }
 
   /**
@@ -76,19 +77,17 @@ public class ChimeraCommands
    * is
    * 
    * <pre>
-   * <blockquote> color colorname #modelnumber:range.chain e.g. color #00ff00
-   * #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
+   * <blockquote> 
+   * color colorname #modelnumber:range.chain 
+   * e.g. color #00ff00 #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
    * </blockquote>
    * </pre>
    * 
    * @param colourMap
    * @return
-   * @see http
-   *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec
-   *      .html
    */
   protected static List<String> buildColourCommands(
-          Map<Color, Map<Integer, Map<String, List<int[]>>>> colourMap)
+          Map<Color, AtomSpecModel> colourMap)
   {
     /*
      * This version concatenates all commands into a single String (semi-colon
@@ -107,48 +106,63 @@ public class ChimeraCommands
       }
       sb.append("color ").append(colourCode).append(" ");
       firstColour = false;
-      boolean firstModelForColour = true;
-      final Map<Integer, Map<String, List<int[]>>> colourData = colourMap
+      final AtomSpecModel colourData = colourMap
               .get(colour);
-      for (Integer model : colourData.keySet())
+      sb.append(colourData.getAtomSpec());
+    }
+    commands.add(sb.toString());
+    return commands;
+  }
+
+  /**
+   * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
+   * builds a Chimera format atom spec
+   * 
+   * @param modelAndChainRanges
+   */
+  protected static String getAtomSpec(
+          Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
+  {
+    StringBuilder sb = new StringBuilder(128);
+    boolean firstModelForColour = true;
+    for (Integer model : modelAndChainRanges.keySet())
+    {
+      boolean firstPositionForModel = true;
+      if (!firstModelForColour)
       {
-        boolean firstPositionForModel = true;
-        if (!firstModelForColour)
-        {
-          sb.append("|");
-        }
-        firstModelForColour = false;
-        sb.append("#").append(model).append(":");
+        sb.append("|");
+      }
+      firstModelForColour = false;
+      sb.append("#").append(model).append(":");
 
-        final Map<String, List<int[]>> modelData = colourData.get(model);
-        for (String chain : modelData.keySet())
+      final Map<String, List<int[]>> modelData = modelAndChainRanges
+              .get(model);
+      for (String chain : modelData.keySet())
+      {
+        boolean hasChain = !"".equals(chain.trim());
+        for (int[] range : modelData.get(chain))
         {
-          boolean hasChain = !"".equals(chain.trim());
-          for (int[] range : modelData.get(chain))
+          if (!firstPositionForModel)
           {
-            if (!firstPositionForModel)
-            {
-              sb.append(",");
-            }
-            if (range[0] == range[1])
-            {
-              sb.append(range[0]);
-            }
-            else
-            {
-              sb.append(range[0]).append("-").append(range[1]);
-            }
-            if (hasChain)
-            {
-              sb.append(".").append(chain);
-            }
-            firstPositionForModel = false;
+            sb.append(",");
+          }
+          if (range[0] == range[1])
+          {
+            sb.append(range[0]);
+          }
+          else
+          {
+            sb.append(range[0]).append("-").append(range[1]);
+          }
+          if (hasChain)
+          {
+            sb.append(".").append(chain);
           }
+          firstPositionForModel = false;
         }
       }
     }
-    commands.add(sb.toString());
-    return commands;
+    return sb.toString();
   }
 
   /**
@@ -163,12 +177,12 @@ public class ChimeraCommands
    * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
    * </pre>
    */
-  protected static Map<Color, Map<Integer, Map<String, List<int[]>>>> buildColoursMap(
+  protected static Map<Color, AtomSpecModel> buildColoursMap(
           StructureSelectionManager ssm, String[] files,
           SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
           AlignmentI alignment)
   {
-    Map<Color, Map<Integer, Map<String, List<int[]>>>> colourMap = new LinkedHashMap<Color, Map<Integer, Map<String, List<int[]>>>>();
+    Map<Color, AtomSpecModel> colourMap = new LinkedHashMap<Color, AtomSpecModel>();
     Color lastColour = null;
     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
     {
@@ -253,43 +267,175 @@ public class ChimeraCommands
    * @param chain
    */
   protected static void addColourRange(
-          Map<Color, Map<Integer, Map<String, List<int[]>>>> colourMap,
+Map<Color, AtomSpecModel> colourMap,
           Color colour, int model, int startPos, int endPos, String chain)
   {
+    // refactor for reuse as addRange
     /*
      * Get/initialize map of data for the colour
      */
-    Map<Integer, Map<String, List<int[]>>> colourData = colourMap
-            .get(colour);
+    AtomSpecModel colourData = colourMap.get(colour);
     if (colourData == null)
     {
-      colourMap
-              .put(colour,
-                      colourData = new TreeMap<Integer, Map<String, List<int[]>>>());
+      colourData = new AtomSpecModel();
+      colourMap.put(colour, colourData);
     }
 
-    /*
-     * Get/initialize map of data for the colour and model
-     */
-    Map<String, List<int[]>> modelData = colourData.get(model);
-    if (modelData == null)
+    colourData.addRange(model, startPos, endPos, chain);
+  }
+
+  /**
+   * Constructs and returns a set of Chimera commands to set attributes on
+   * residues corresponding to features in Jalview.
+   * 
+   * @param ssm
+   * @param files
+   * @param seqs
+   * @param fr
+   * @param alignment
+   * @return
+   */
+  public static StructureMappingcommandSet getSetAttributeCommandsForFeatures(
+          StructureSelectionManager ssm, String[] files,
+          SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
+  {
+    Map<String, Map<Integer, Map<String, List<int[]>>>> featureMap = buildFeaturesMap(
+            ssm, files, seqs, fr, alignment);
+
+    List<String> colourCommands = buildSetAttributeCommands(featureMap);
+
+    StructureMappingcommandSet cs = new StructureMappingcommandSet(
+            ChimeraCommands.class, null,
+            colourCommands.toArray(new String[colourCommands.size()]));
+
+    return cs;
+  }
+
+  /**
+   * <pre>
+   * Helper method to build a map of 
+   * { featureType, {modelNumber, {chain, {list of from-to ranges} } } }
+   * </pre>
+   * 
+   * @param ssm
+   * @param files
+   * @param seqs
+   * @param fr
+   * @param alignment
+   * @return
+   */
+  protected static Map<String, Map<Integer, Map<String, List<int[]>>>> buildFeaturesMap(
+          StructureSelectionManager ssm, String[] files,
+          SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
+  {
+    Map<String, Map<Integer, Map<String, List<int[]>>>> theMap = new HashMap<String, Map<Integer, Map<String, List<int[]>>>>();
+
+    List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
+    if (visibleFeatures.isEmpty())
     {
-      colourData.put(model, modelData = new TreeMap<String, List<int[]>>());
+      return theMap;
     }
-
+    
     /*
-     * Get/initialize map of data for colour, model and chain
+     * traverse mappings to structures 
      */
-    List<int[]> chainData = modelData.get(chain);
-    if (chainData == null)
+    for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
     {
-      modelData.put(chain, chainData = new ArrayList<int[]>());
+      StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
+
+      if (mapping == null || mapping.length < 1)
+      {
+        continue;
+      }
+
+      int lastPos = -1;
+      for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
+      {
+        for (int m = 0; m < mapping.length; m++)
+        {
+          final SequenceI seq = seqs[pdbfnum][seqNo];
+          int sp = alignment.findIndex(seq);
+          if (mapping[m].getSequence() == seq && sp > -1)
+          {
+            SequenceI asp = alignment.getSequenceAt(sp);
+
+            /*
+             * traverse each sequence for its mapped positions
+             */
+            for (int r = 0; r < asp.getLength(); r++)
+            {
+              // no mapping to gaps in sequence
+              if (Comparison.isGap(asp.getCharAt(r)))
+              {
+                continue;
+              }
+              int residuePos = asp.findPosition(r);
+              int pos = mapping[m].getPDBResNum(residuePos);
+
+              if (pos < 1 || pos == lastPos)
+              {
+                continue;
+              }
+              final String chain = mapping[m].getChain();
+
+              /*
+               * record any features at this position, with the model, chain
+               * and residue number they map to
+               */
+              List<SequenceFeature> features = fr.findFeaturesAtRes(asp,
+                      residuePos);
+              for (SequenceFeature feature : features)
+              {
+                if (!visibleFeatures.contains(feature))
+                {
+                  continue;
+                }
+              }
+            }
+          }
+        }
+      }
+      }
+    return theMap;
+  }
+
+  /**
+   * Traverse the map of features/models/chains/positions to construct a list of
+   * 'setattr' commands (one per feature type). The format of each command is
+   * 
+   * <pre>
+   * <blockquote> setattr r <featureName> " " #modelnumber:range.chain 
+   * e.g. setattr r jv:chain " " #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
+   * </blockquote>
+   * </pre>
+   * <p>
+   * Note we are not (currently) setting attribute values, only the type
+   * (presence) of each attribute. This is to avoid overloading the Chimera REST
+   * interface by sending too many distinct commands. Analysis by feature values
+   * may still be performed in Jalview, on selections created in Chimera.
+   * 
+   * @param featureMap
+   * @return
+   * @see http 
+   *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec
+   *      .html
+   */
+  protected static List<String> buildSetAttributeCommands(
+          Map<String, Map<Integer, Map<String, List<int[]>>>> featureMap)
+  {
+    List<String> commands = new ArrayList<String>();
+    for (String featureType : featureMap.keySet())
+    {
+      StringBuilder sb = new StringBuilder(128);
+      featureType = featureType.replace(" ", "_");
+      sb.append("setattr r jv:").append(featureType).append(" \" \" ");
+      final Map<Integer, Map<String, List<int[]>>> featureData = featureMap
+              .get(featureType);
+      sb.append(getAtomSpec(featureData));
+      commands.add(sb.toString());
     }
 
-    /*
-     * Add the start/end positions
-     */
-    chainData.add(new int[] { startPos, endPos });
+    return commands;
   }
 
 }