JAL-3518 more extraction of ChimeraX commands as overrides
[jalview.git] / src / jalview / ext / rbvi / chimera / ChimeraXCommands.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ext.rbvi.chimera;
22
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureRenderer;
26 import jalview.api.SequenceRenderer;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.MappedFeatures;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.Desktop;
33 import jalview.renderer.seqfeatures.FeatureColourFinder;
34 import jalview.structure.StructureMapping;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.ColorUtils;
37 import jalview.util.Comparison;
38
39 import java.awt.Color;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.LinkedHashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Map.Entry;
46
47 /**
48  * Routines for generating ChimeraX commands for Jalview/ChimeraX binding
49  */
50 public class ChimeraXCommands extends ChimeraCommands
51 {
52   private static final String CMD_COLOUR_BY_CHARGE = "color white;color :ASP,GLU red;color :LYS,ARG blue;color :CYS yellow";
53
54   /**
55    * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
56    * builds a ChimeraX format atom spec
57    * 
58    * @param modelAndChainRanges
59    */
60   protected static String getAtomSpec(
61           Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
62   {
63     StringBuilder sb = new StringBuilder(128);
64     boolean firstModelForColour = true;
65     for (Integer model : modelAndChainRanges.keySet())
66     {
67       boolean firstPositionForModel = true;
68       if (!firstModelForColour)
69       {
70         sb.append("|");
71       }
72       firstModelForColour = false;
73       sb.append("#").append(model).append(":");
74
75       final Map<String, List<int[]>> modelData = modelAndChainRanges
76               .get(model);
77       for (String chain : modelData.keySet())
78       {
79         boolean hasChain = !"".equals(chain.trim());
80         for (int[] range : modelData.get(chain))
81         {
82           if (!firstPositionForModel)
83           {
84             sb.append(",");
85           }
86           if (range[0] == range[1])
87           {
88             sb.append(range[0]);
89           }
90           else
91           {
92             sb.append(range[0]).append("-").append(range[1]);
93           }
94           if (hasChain)
95           {
96             sb.append(".").append(chain);
97           }
98           firstPositionForModel = false;
99         }
100       }
101     }
102     return sb.toString();
103   }
104
105   /**
106    * <pre>
107    * Build a data structure which records contiguous subsequences for each colour. 
108    * From this we can easily generate the Chimera command for colour by sequence.
109    * Color
110    *     Model number
111    *         Chain
112    *             list of start/end ranges
113    * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
114    * </pre>
115    */
116   protected static Map<Object, AtomSpecModel> buildColoursMap(
117           StructureSelectionManager ssm, String[] files,
118           SequenceI[][] sequence, SequenceRenderer sr,
119           AlignmentViewPanel viewPanel)
120   {
121     FeatureRenderer fr = viewPanel.getFeatureRenderer();
122     FeatureColourFinder finder = new FeatureColourFinder(fr);
123     AlignViewportI viewport = viewPanel.getAlignViewport();
124     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
125     AlignmentI al = viewport.getAlignment();
126     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
127     Color lastColour = null;
128
129     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
130     {
131       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
132
133       if (mapping == null || mapping.length < 1)
134       {
135         continue;
136       }
137
138       int startPos = -1, lastPos = -1;
139       String lastChain = "";
140       for (int s = 0; s < sequence[pdbfnum].length; s++)
141       {
142         for (int sp, m = 0; m < mapping.length; m++)
143         {
144           final SequenceI seq = sequence[pdbfnum][s];
145           if (mapping[m].getSequence() == seq
146                   && (sp = al.findIndex(seq)) > -1)
147           {
148             SequenceI asp = al.getSequenceAt(sp);
149             for (int r = 0; r < asp.getLength(); r++)
150             {
151               // no mapping to gaps in sequence
152               if (Comparison.isGap(asp.getCharAt(r)))
153               {
154                 continue;
155               }
156               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
157
158               if (pos < 1 || pos == lastPos)
159               {
160                 continue;
161               }
162
163               Color colour = sr.getResidueColour(seq, r, finder);
164
165               /*
166                * darker colour for hidden regions
167                */
168               if (!cs.isVisible(r))
169               {
170                 colour = Color.GRAY;
171               }
172
173               final String chain = mapping[m].getChain();
174
175               /*
176                * Just keep incrementing the end position for this colour range
177                * _unless_ colour, PDB model or chain has changed, or there is a
178                * gap in the mapped residue sequence
179                */
180               final boolean newColour = !colour.equals(lastColour);
181               final boolean nonContig = lastPos + 1 != pos;
182               final boolean newChain = !chain.equals(lastChain);
183               if (newColour || nonContig || newChain)
184               {
185                 if (startPos != -1)
186                 {
187                   addAtomSpecRange(colourMap, lastColour, pdbfnum, startPos,
188                           lastPos, lastChain);
189                 }
190                 startPos = pos;
191               }
192               lastColour = colour;
193               lastPos = pos;
194               lastChain = chain;
195             }
196             // final colour range
197             if (lastColour != null)
198             {
199               addAtomSpecRange(colourMap, lastColour, pdbfnum, startPos,
200                       lastPos, lastChain);
201             }
202             // break;
203           }
204         }
205       }
206     }
207     return colourMap;
208   }
209
210   /**
211    * <pre>
212    * Helper method to build a map of 
213    *   { featureType, { feature value, AtomSpecModel } }
214    * </pre>
215    * 
216    * @param ssm
217    * @param files
218    * @param seqs
219    * @param viewPanel
220    * @return
221    */
222   protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
223           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
224           AlignmentViewPanel viewPanel)
225   {
226     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
227
228     FeatureRenderer fr = viewPanel.getFeatureRenderer();
229     if (fr == null)
230     {
231       return theMap;
232     }
233
234     AlignViewportI viewport = viewPanel.getAlignViewport();
235     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
236
237     /*
238      * if alignment is showing features from complement, we also transfer
239      * these features to the corresponding mapped structure residues
240      */
241     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
242     List<String> complementFeatures = new ArrayList<>();
243     FeatureRenderer complementRenderer = null;
244     if (showLinkedFeatures)
245     {
246       AlignViewportI comp = fr.getViewport().getCodingComplement();
247       if (comp != null)
248       {
249         complementRenderer = Desktop.getAlignFrameFor(comp)
250                 .getFeatureRenderer();
251         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
252       }
253     }
254     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
255     {
256       return theMap;
257     }
258
259     AlignmentI alignment = viewPanel.getAlignment();
260     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
261     {
262       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
263
264       if (mapping == null || mapping.length < 1)
265       {
266         continue;
267       }
268
269       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
270       {
271         for (int m = 0; m < mapping.length; m++)
272         {
273           final SequenceI seq = seqs[pdbfnum][seqNo];
274           int sp = alignment.findIndex(seq);
275           StructureMapping structureMapping = mapping[m];
276           if (structureMapping.getSequence() == seq && sp > -1)
277           {
278             /*
279              * found a sequence with a mapping to a structure;
280              * now scan its features
281              */
282             if (!visibleFeatures.isEmpty())
283             {
284               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
285                       theMap, pdbfnum);
286             }
287             if (showLinkedFeatures)
288             {
289               scanComplementFeatures(complementRenderer, structureMapping,
290                       seq, theMap, pdbfnum);
291             }
292           }
293         }
294       }
295     }
296     return theMap;
297   }
298
299   /**
300    * Scans visible features in mapped positions of the CDS/peptide complement, and
301    * adds any found to the map of attribute values/structure positions
302    * 
303    * @param complementRenderer
304    * @param structureMapping
305    * @param seq
306    * @param theMap
307    * @param modelNumber
308    */
309   protected static void scanComplementFeatures(
310           FeatureRenderer complementRenderer,
311           StructureMapping structureMapping, SequenceI seq,
312           Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
313   {
314     /*
315      * for each sequence residue mapped to a structure position...
316      */
317     for (int seqPos : structureMapping.getMapping().keySet())
318     {
319       /*
320        * find visible complementary features at mapped position(s)
321        */
322       MappedFeatures mf = complementRenderer
323               .findComplementFeaturesAtResidue(seq, seqPos);
324       if (mf != null)
325       {
326         for (SequenceFeature sf : mf.features)
327         {
328           String type = sf.getType();
329
330           /*
331            * Don't copy features which originated from Chimera
332            */
333           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
334                   .equals(sf.getFeatureGroup()))
335           {
336             continue;
337           }
338
339           /*
340            * record feature 'value' (score/description/type) as at the
341            * corresponding structure position
342            */
343           List<int[]> mappedRanges = structureMapping
344                   .getPDBResNumRanges(seqPos, seqPos);
345
346           if (!mappedRanges.isEmpty())
347           {
348             String value = sf.getDescription();
349             if (value == null || value.length() == 0)
350             {
351               value = type;
352             }
353             float score = sf.getScore();
354             if (score != 0f && !Float.isNaN(score))
355             {
356               value = Float.toString(score);
357             }
358             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
359             if (featureValues == null)
360             {
361               featureValues = new HashMap<>();
362               theMap.put(type, featureValues);
363             }
364             for (int[] range : mappedRanges)
365             {
366               addAtomSpecRange(featureValues, value, modelNumber, range[0],
367                       range[1], structureMapping.getChain());
368             }
369           }
370         }
371       }
372     }
373   }
374
375   /**
376    * Inspect features on the sequence; for each feature that is visible, determine
377    * its mapped ranges in the structure (if any) according to the given mapping,
378    * and add them to the map.
379    * 
380    * @param visibleFeatures
381    * @param mapping
382    * @param seq
383    * @param theMap
384    * @param modelNumber
385    */
386   protected static void scanSequenceFeatures(List<String> visibleFeatures,
387           StructureMapping mapping, SequenceI seq,
388           Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
389   {
390     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
391             visibleFeatures.toArray(new String[visibleFeatures.size()]));
392     for (SequenceFeature sf : sfs)
393     {
394       String type = sf.getType();
395
396       /*
397        * Don't copy features which originated from Chimera
398        */
399       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
400               .equals(sf.getFeatureGroup()))
401       {
402         continue;
403       }
404
405       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
406               sf.getEnd());
407
408       if (!mappedRanges.isEmpty())
409       {
410         String value = sf.getDescription();
411         if (value == null || value.length() == 0)
412         {
413           value = type;
414         }
415         float score = sf.getScore();
416         if (score != 0f && !Float.isNaN(score))
417         {
418           value = Float.toString(score);
419         }
420         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
421         if (featureValues == null)
422         {
423           featureValues = new HashMap<>();
424           theMap.put(type, featureValues);
425         }
426         for (int[] range : mappedRanges)
427         {
428           addAtomSpecRange(featureValues, value, modelNumber, range[0],
429                   range[1], mapping.getChain());
430         }
431       }
432     }
433   }
434
435   /**
436    * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
437    * for a 'Jalview' namespace, and any non-alphanumeric character is converted
438    * to an underscore.
439    * 
440    * @param featureType
441    * @return
442    * 
443    *         <pre>
444    * &#64;see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
445    *         </pre>
446    */
447   protected static String makeAttributeName(String featureType)
448   {
449     StringBuilder sb = new StringBuilder();
450     if (featureType != null)
451     {
452       for (char c : featureType.toCharArray())
453       {
454         sb.append(Character.isLetterOrDigit(c) ? c : '_');
455       }
456     }
457     String attName = NAMESPACE_PREFIX + sb.toString();
458
459     /*
460      * Chimera treats an attribute name ending in 'color' as colour-valued;
461      * Jalview doesn't, so prevent this by appending an underscore
462      */
463     if (attName.toUpperCase().endsWith("COLOR"))
464     {
465       attName += "_";
466     }
467
468     return attName;
469   }
470
471   @Override
472   public String colourByCharge()
473   {
474     return CMD_COLOUR_BY_CHARGE;
475   }
476
477   @Override
478   public String colourByResidues(Map<String, Color> colours)
479   {
480     StringBuilder cmd = new StringBuilder(12 * colours.size());
481
482     /*
483      * concatenate commands like
484      * color :VAL #4949b6
485      */
486     for (Entry<String, Color> entry : colours.entrySet())
487     {
488       String colorSpec = ColorUtils.toTkCode(entry.getValue());
489       String resCode = entry.getKey();
490       cmd.append("color :").append(resCode).append(" ").append(colorSpec)
491               .append(CMD_SEPARATOR);
492     }
493     return cmd.toString();
494   }
495
496   @Override
497   public String setBackgroundColour(Color col)
498   {
499     return "set bgColor " + ColorUtils.toTkCode(col);
500   }
501
502   @Override
503   protected String getColourCommand(AtomSpecModel colourData,
504           String colourCode)
505   {
506     return "color " + colourData.getAtomSpecX() + " " + colourCode;
507   }
508
509   @Override
510   public String focusView()
511   {
512     return "view";
513   }
514
515   /**
516    * {@inheritDoc}
517    * 
518    * @return
519    */
520   protected static int getModelStartNo()
521   {
522     return 1;
523   }
524
525   /**
526    * Returns a viewer command to set the given residue attribute value on
527    * residues specified by the AtomSpecModel, for example
528    * 
529    * <pre>
530    * setattr #0/A:3-9,14-20,39-43 res jv_strand 'strand' create true
531    * </pre>
532    * 
533    * @param attributeName
534    * @param attributeValue
535    * @param atomSpecModel
536    * @return
537    */
538   @Override
539   protected String getSetAttributeCommand(String attributeName,
540           String attributeValue, AtomSpecModel atomSpecModel)
541   {
542     StringBuilder sb = new StringBuilder(128);
543     sb.append("setattr ").append(atomSpecModel.getAtomSpecX());
544     sb.append(" res ").append(attributeName).append(" '")
545             .append(attributeValue).append("'");
546     sb.append(" create true");
547     return sb.toString();
548   }
549
550 }