JAL-3551 copy Jalview features to Pymol 'p' (with pull refactoring)
[jalview.git] / src / jalview / structures / models / AAStructureBindingModel.java
index 6e926df..8aa1895 100644 (file)
@@ -42,8 +42,12 @@ import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.HiddenColumns;
+import jalview.datamodel.MappedFeatures;
 import jalview.datamodel.PDBEntry;
+import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
+import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
+import jalview.gui.Desktop;
 import jalview.gui.StructureViewer.ViewerType;
 import jalview.io.DataSourceType;
 import jalview.io.StructureFile;
@@ -1111,7 +1115,8 @@ public abstract class AAStructureBindingModel
    * @param getReply
    * @param msg
    */
-  private List<String> executeCommands(List<StructureCommandI> commands,
+  protected List<String> executeCommands(
+          List<StructureCommandI> commands,
           boolean getReply, String msg)
   {
     return executeCommands(getReply, msg,
@@ -1160,25 +1165,17 @@ public abstract class AAStructureBindingModel
   }
 
   /**
-   * colour any structures associated with sequences in the given alignment
-   * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
-   * if colourBySequence is enabled.
+   * Colours any structures associated with sequences in the given alignment as
+   * coloured in the alignment view, provided colourBySequence is enabled
    */
   public void colourBySequence(AlignmentViewPanel alignmentv)
   {
-    if (!colourBySequence || !isLoadingFinished())
+    if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
     {
       return;
     }
-    if (getSsm() == null)
-    {
-      return;
-    }
-    String[] files = getStructureFiles();
-
-    SequenceRenderer sr = getSequenceRenderer(alignmentv);
-    Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
-            sequence, sr, alignmentv);
+    Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
+            alignmentv);
 
     List<StructureCommandI> colourBySequenceCommands = commandGenerator
             .colourBySequence(colourMap);
@@ -1354,16 +1351,16 @@ public abstract class AAStructureBindingModel
    * models and chains)
    * 
    * @param ssm
-   * @param files
    * @param sequence
-   * @param sr
    * @param viewPanel
    * @return
    */
   protected Map<Object, AtomSpecModel> buildColoursMap(
-          StructureSelectionManager ssm, String[] files,
-          SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
+          StructureSelectionManager ssm, SequenceI[][] sequence,
+          AlignmentViewPanel viewPanel)
   {
+    String[] files = getStructureFiles();
+    SequenceRenderer sr = getSequenceRenderer(viewPanel);
     FeatureRenderer fr = viewPanel.getFeatureRenderer();
     FeatureColourFinder finder = new FeatureColourFinder(fr);
     AlignViewportI viewport = viewPanel.getAlignViewport();
@@ -1594,4 +1591,245 @@ public abstract class AAStructureBindingModel
     // add external viewer shutdown in overrides
     // todo - or can maybe pull up to here
   }
+
+  /**
+   * Returns the URL of a help page for the structure viewer, or null if none is
+   * known
+   * 
+   * @return
+   */
+  public String getHelpURL()
+  {
+    return null;
+  }
+
+  /**
+   * <pre>
+   * Helper method to build a map of 
+   *   { featureType, { feature value, AtomSpecModel } }
+   * </pre>
+   * 
+   * @param viewPanel
+   * @return
+   */
+  protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
+          AlignmentViewPanel viewPanel)
+  {
+    Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
+    String[] files = getStructureFiles();
+    if (files == null)
+    {
+      return theMap;
+    }
+
+    FeatureRenderer fr = viewPanel.getFeatureRenderer();
+    if (fr == null)
+    {
+      return theMap;
+    }
+  
+    AlignViewportI viewport = viewPanel.getAlignViewport();
+    List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
+  
+    /*
+     * if alignment is showing features from complement, we also transfer
+     * these features to the corresponding mapped structure residues
+     */
+    boolean showLinkedFeatures = viewport.isShowComplementFeatures();
+    List<String> complementFeatures = new ArrayList<>();
+    FeatureRenderer complementRenderer = null;
+    if (showLinkedFeatures)
+    {
+      AlignViewportI comp = fr.getViewport().getCodingComplement();
+      if (comp != null)
+      {
+        complementRenderer = Desktop.getAlignFrameFor(comp)
+                .getFeatureRenderer();
+        complementFeatures = complementRenderer.getDisplayedFeatureTypes();
+      }
+    }
+    if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
+    {
+      return theMap;
+    }
+  
+    AlignmentI alignment = viewPanel.getAlignment();
+    SequenceI[][] seqs = getSequence();
+
+    for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+    {
+      String modelId = getModelIdForFile(files[pdbfnum]);
+      StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
+  
+      if (mapping == null || mapping.length < 1)
+      {
+        continue;
+      }
+  
+      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);
+          StructureMapping structureMapping = mapping[m];
+          if (structureMapping.getSequence() == seq && sp > -1)
+          {
+            /*
+             * found a sequence with a mapping to a structure;
+             * now scan its features
+             */
+            if (!visibleFeatures.isEmpty())
+            {
+              scanSequenceFeatures(visibleFeatures, structureMapping, seq,
+                      theMap, modelId);
+            }
+            if (showLinkedFeatures)
+            {
+              scanComplementFeatures(complementRenderer, structureMapping,
+                      seq, theMap, modelId);
+            }
+          }
+        }
+      }
+    }
+    return theMap;
+  }
+
+  /**
+   * Scans visible features in mapped positions of the CDS/peptide complement, and
+   * adds any found to the map of attribute values/structure positions
+   * 
+   * @param complementRenderer
+   * @param structureMapping
+   * @param seq
+   * @param theMap
+   * @param modelNumber
+   */
+  protected static void scanComplementFeatures(
+          FeatureRenderer complementRenderer,
+          StructureMapping structureMapping, SequenceI seq,
+          Map<String, Map<Object, AtomSpecModel>> theMap,
+          String modelNumber)
+  {
+    /*
+     * for each sequence residue mapped to a structure position...
+     */
+    for (int seqPos : structureMapping.getMapping().keySet())
+    {
+      /*
+       * find visible complementary features at mapped position(s)
+       */
+      MappedFeatures mf = complementRenderer
+              .findComplementFeaturesAtResidue(seq, seqPos);
+      if (mf != null)
+      {
+        for (SequenceFeature sf : mf.features)
+        {
+          String type = sf.getType();
+  
+          /*
+           * Don't copy features which originated from Chimera
+           */
+          if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
+                  .equals(sf.getFeatureGroup()))
+          {
+            continue;
+          }
+  
+          /*
+           * record feature 'value' (score/description/type) as at the
+           * corresponding structure position
+           */
+          List<int[]> mappedRanges = structureMapping
+                  .getPDBResNumRanges(seqPos, seqPos);
+  
+          if (!mappedRanges.isEmpty())
+          {
+            String value = sf.getDescription();
+            if (value == null || value.length() == 0)
+            {
+              value = type;
+            }
+            float score = sf.getScore();
+            if (score != 0f && !Float.isNaN(score))
+            {
+              value = Float.toString(score);
+            }
+            Map<Object, AtomSpecModel> featureValues = theMap.get(type);
+            if (featureValues == null)
+            {
+              featureValues = new HashMap<>();
+              theMap.put(type, featureValues);
+            }
+            for (int[] range : mappedRanges)
+            {
+              addAtomSpecRange(featureValues, value, modelNumber, range[0],
+                      range[1], structureMapping.getChain());
+            }
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * 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 modelId
+   */
+  protected static void scanSequenceFeatures(List<String> visibleFeatures,
+          StructureMapping mapping, SequenceI seq,
+          Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
+  {
+    List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
+            visibleFeatures.toArray(new String[visibleFeatures.size()]));
+    for (SequenceFeature sf : sfs)
+    {
+      String type = sf.getType();
+  
+      /*
+       * Don't copy features which originated from Chimera
+       */
+      if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
+              .equals(sf.getFeatureGroup()))
+      {
+        continue;
+      }
+  
+      List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
+              sf.getEnd());
+  
+      if (!mappedRanges.isEmpty())
+      {
+        String value = sf.getDescription();
+        if (value == null || value.length() == 0)
+        {
+          value = type;
+        }
+        float score = sf.getScore();
+        if (score != 0f && !Float.isNaN(score))
+        {
+          value = Float.toString(score);
+        }
+        Map<Object, AtomSpecModel> featureValues = theMap.get(type);
+        if (featureValues == null)
+        {
+          featureValues = new HashMap<>();
+          theMap.put(type, featureValues);
+        }
+        for (int[] range : mappedRanges)
+        {
+          addAtomSpecRange(featureValues, value, modelId, range[0],
+                  range[1], mapping.getChain());
+        }
+      }
+    }
+  }
 }