JAL-2422 write Jalview features to ChimeraX via command file
[jalview.git] / src / jalview / ext / rbvi / chimera / ChimeraCommands.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.StructureMappingcommandSet;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.ColorUtils;
38 import jalview.util.Comparison;
39
40 import java.awt.Color;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.LinkedHashMap;
44 import java.util.List;
45 import java.util.Map;
46
47 /**
48  * Routines for generating Chimera commands for Jalview/Chimera binding
49  * 
50  * @author JimP
51  * 
52  */
53 public class ChimeraCommands
54 {
55
56   public static final String NAMESPACE_PREFIX = "jv_";
57
58   /**
59    * Constructs Chimera commands to colour residues as per the Jalview alignment
60    * 
61    * @param ssm
62    * @param files
63    * @param sequence
64    * @param sr
65    * @param fr
66    * @param viewPanel
67    * @param isChimeraX
68    * @return
69    */
70   public static StructureMappingcommandSet[] getColourBySequenceCommand(
71           StructureSelectionManager ssm, String[] files,
72           SequenceI[][] sequence, SequenceRenderer sr,
73           AlignmentViewPanel viewPanel, boolean isChimeraX)
74   {
75     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
76             sequence, sr, viewPanel, isChimeraX);
77
78     List<String> colourCommands = buildColourCommands(colourMap,
79             isChimeraX);
80
81     StructureMappingcommandSet cs = new StructureMappingcommandSet(
82             ChimeraCommands.class, null,
83             colourCommands.toArray(new String[colourCommands.size()]));
84
85     return new StructureMappingcommandSet[] { cs };
86   }
87
88   /**
89    * Traverse the map of colours/models/chains/positions to construct a list of
90    * 'color' commands (one per distinct colour used). The format of each command
91    * is
92    * 
93    * <pre>
94    * <blockquote> 
95    * color colorname #modelnumber:range.chain 
96    * e.g. color #00ff00 #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
97    * </blockquote>
98    * </pre>
99    * 
100    * @param colourMap
101    * @param isChimeraX
102    * @return
103    */
104   protected static List<String> buildColourCommands(
105           Map<Object, AtomSpecModel> colourMap, boolean isChimeraX)
106   {
107     /*
108      * This version concatenates all commands into a single String (semi-colon
109      * delimited). If length limit issues arise, refactor to return one color
110      * command per colour.
111      */
112     List<String> commands = new ArrayList<>();
113     StringBuilder sb = new StringBuilder(256);
114     boolean firstColour = true;
115     for (Object key : colourMap.keySet())
116     {
117       Color colour = (Color) key;
118       String colourCode = ColorUtils.toTkCode(colour);
119       if (!firstColour)
120       {
121         sb.append("; ");
122       }
123       sb.append("color ");
124       firstColour = false;
125       final AtomSpecModel colourData = colourMap.get(colour);
126       if (isChimeraX)
127       {
128         sb.append(colourData.getAtomSpecX()).append(" ").append(colourCode);
129       }
130       else
131       {
132         sb.append(colourCode).append(" ").append(colourData.getAtomSpec());
133       }
134     }
135     commands.add(sb.toString());
136     return commands;
137   }
138
139   /**
140    * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
141    * builds a Chimera format atom spec
142    * 
143    * @param modelAndChainRanges
144    */
145   protected static String getAtomSpec(
146           Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
147   {
148     StringBuilder sb = new StringBuilder(128);
149     boolean firstModelForColour = true;
150     for (Integer model : modelAndChainRanges.keySet())
151     {
152       boolean firstPositionForModel = true;
153       if (!firstModelForColour)
154       {
155         sb.append("|");
156       }
157       firstModelForColour = false;
158       sb.append("#").append(model).append(":");
159
160       final Map<String, List<int[]>> modelData = modelAndChainRanges
161               .get(model);
162       for (String chain : modelData.keySet())
163       {
164         boolean hasChain = !"".equals(chain.trim());
165         for (int[] range : modelData.get(chain))
166         {
167           if (!firstPositionForModel)
168           {
169             sb.append(",");
170           }
171           if (range[0] == range[1])
172           {
173             sb.append(range[0]);
174           }
175           else
176           {
177             sb.append(range[0]).append("-").append(range[1]);
178           }
179           if (hasChain)
180           {
181             sb.append(".").append(chain);
182           }
183           firstPositionForModel = false;
184         }
185       }
186     }
187     return sb.toString();
188   }
189
190   /**
191    * <pre>
192    * Build a data structure which records contiguous subsequences for each colour. 
193    * From this we can easily generate the Chimera command for colour by sequence.
194    * Color
195    *     Model number
196    *         Chain
197    *             list of start/end ranges
198    * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
199    * </pre>
200    * 
201    * @param ssm
202    * @param files
203    * @param sequence
204    * @param sr
205    * @param viewPanel
206    * @param isChimeraX
207    * @return
208    */
209   protected static Map<Object, AtomSpecModel> buildColoursMap(
210           StructureSelectionManager ssm, String[] files,
211           SequenceI[][] sequence, SequenceRenderer sr,
212           AlignmentViewPanel viewPanel, boolean isChimeraX)
213   {
214     FeatureRenderer fr = viewPanel.getFeatureRenderer();
215     FeatureColourFinder finder = new FeatureColourFinder(fr);
216     AlignViewportI viewport = viewPanel.getAlignViewport();
217     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
218     AlignmentI al = viewport.getAlignment();
219     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
220     Color lastColour = null;
221
222     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
223     {
224       final int modelNumber = pdbfnum + (isChimeraX ? 1 : 0);
225       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
226
227       if (mapping == null || mapping.length < 1)
228       {
229         continue;
230       }
231
232       int startPos = -1, lastPos = -1;
233       String lastChain = "";
234       for (int s = 0; s < sequence[pdbfnum].length; s++)
235       {
236         for (int sp, m = 0; m < mapping.length; m++)
237         {
238           final SequenceI seq = sequence[pdbfnum][s];
239           if (mapping[m].getSequence() == seq
240                   && (sp = al.findIndex(seq)) > -1)
241           {
242             SequenceI asp = al.getSequenceAt(sp);
243             for (int r = 0; r < asp.getLength(); r++)
244             {
245               // no mapping to gaps in sequence
246               if (Comparison.isGap(asp.getCharAt(r)))
247               {
248                 continue;
249               }
250               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
251
252               if (pos < 1 || pos == lastPos)
253               {
254                 continue;
255               }
256
257               Color colour = sr.getResidueColour(seq, r, finder);
258
259               /*
260                * darker colour for hidden regions
261                */
262               if (!cs.isVisible(r))
263               {
264                 colour = Color.GRAY;
265               }
266
267               final String chain = mapping[m].getChain();
268
269               /*
270                * Just keep incrementing the end position for this colour range
271                * _unless_ colour, PDB model or chain has changed, or there is a
272                * gap in the mapped residue sequence
273                */
274               final boolean newColour = !colour.equals(lastColour);
275               final boolean nonContig = lastPos + 1 != pos;
276               final boolean newChain = !chain.equals(lastChain);
277               if (newColour || nonContig || newChain)
278               {
279                 if (startPos != -1)
280                 {
281                   addAtomSpecRange(colourMap, lastColour, modelNumber,
282                           startPos, lastPos, lastChain);
283                 }
284                 startPos = pos;
285               }
286               lastColour = colour;
287               lastPos = pos;
288               lastChain = chain;
289             }
290             // final colour range
291             if (lastColour != null)
292             {
293               addAtomSpecRange(colourMap, lastColour, modelNumber, startPos,
294                       lastPos, lastChain);
295             }
296             // break;
297           }
298         }
299       }
300     }
301     return colourMap;
302   }
303
304   /**
305    * Helper method to add one contiguous range to the AtomSpec model for the given
306    * value (creating the model if necessary). As used by Jalview, {@code value} is
307    * <ul>
308    * <li>a colour, when building a 'colour structure by sequence' command</li>
309    * <li>a feature value, when building a 'set Chimera attributes from features'
310    * command</li>
311    * </ul>
312    * 
313    * @param map
314    * @param value
315    * @param model
316    * @param startPos
317    * @param endPos
318    * @param chain
319    */
320   protected static void addAtomSpecRange(Map<Object, AtomSpecModel> map,
321           Object value, int model, int startPos, int endPos, String chain)
322   {
323     /*
324      * Get/initialize map of data for the colour
325      */
326     AtomSpecModel atomSpec = map.get(value);
327     if (atomSpec == null)
328     {
329       atomSpec = new AtomSpecModel();
330       map.put(value, atomSpec);
331     }
332
333     atomSpec.addRange(model, startPos, endPos, chain);
334   }
335
336   /**
337    * Constructs and returns Chimera commands to set attributes on residues
338    * corresponding to features in Jalview. Attribute names are the Jalview feature
339    * type, with a "jv_" prefix.
340    * 
341    * @param ssm
342    * @param files
343    * @param seqs
344    * @param viewPanel
345    * @param isChimeraX
346    * @return
347    */
348   public static StructureMappingcommandSet getSetAttributeCommandsForFeatures(
349           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
350           AlignmentViewPanel viewPanel, boolean isChimeraX)
351   {
352     Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
353             ssm, files, seqs, viewPanel, isChimeraX);
354
355     List<String> commands = buildSetAttributeCommands(featureMap,
356             isChimeraX);
357
358     StructureMappingcommandSet cs = new StructureMappingcommandSet(
359             ChimeraCommands.class, null,
360             commands.toArray(new String[commands.size()]));
361
362     return cs;
363   }
364
365   /**
366    * <pre>
367    * Helper method to build a map of 
368    *   { featureType, { feature value, AtomSpecModel } }
369    * </pre>
370    * 
371    * @param ssm
372    * @param files
373    * @param seqs
374    * @param viewPanel
375    * @param isChimeraX
376    * @return
377    */
378   protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
379           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
380           AlignmentViewPanel viewPanel, boolean isChimeraX)
381   {
382     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
383
384     FeatureRenderer fr = viewPanel.getFeatureRenderer();
385     if (fr == null)
386     {
387       return theMap;
388     }
389
390     AlignViewportI viewport = viewPanel.getAlignViewport();
391     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
392
393     /*
394      * if alignment is showing features from complement, we also transfer
395      * these features to the corresponding mapped structure residues
396      */
397     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
398     List<String> complementFeatures = new ArrayList<>();
399     FeatureRenderer complementRenderer = null;
400     if (showLinkedFeatures)
401     {
402       AlignViewportI comp = fr.getViewport().getCodingComplement();
403       if (comp != null)
404       {
405         complementRenderer = Desktop.getAlignFrameFor(comp)
406                 .getFeatureRenderer();
407         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
408       }
409     }
410     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
411     {
412       return theMap;
413     }
414
415     AlignmentI alignment = viewPanel.getAlignment();
416     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
417     {
418       final int modelNumber = pdbfnum + (isChimeraX ? 1 : 0);
419       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
420
421       if (mapping == null || mapping.length < 1)
422       {
423         continue;
424       }
425
426       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
427       {
428         for (int m = 0; m < mapping.length; m++)
429         {
430           final SequenceI seq = seqs[pdbfnum][seqNo];
431           int sp = alignment.findIndex(seq);
432           StructureMapping structureMapping = mapping[m];
433           if (structureMapping.getSequence() == seq && sp > -1)
434           {
435             /*
436              * found a sequence with a mapping to a structure;
437              * now scan its features
438              */
439             if (!visibleFeatures.isEmpty())
440             {
441               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
442                       theMap, modelNumber);
443             }
444             if (showLinkedFeatures)
445             {
446               scanComplementFeatures(complementRenderer, structureMapping,
447                       seq, theMap, modelNumber);
448             }
449           }
450         }
451       }
452     }
453     return theMap;
454   }
455
456   /**
457    * Scans visible features in mapped positions of the CDS/peptide complement, and
458    * adds any found to the map of attribute values/structure positions
459    * 
460    * @param complementRenderer
461    * @param structureMapping
462    * @param seq
463    * @param theMap
464    * @param modelNumber
465    */
466   protected static void scanComplementFeatures(
467           FeatureRenderer complementRenderer,
468           StructureMapping structureMapping, SequenceI seq,
469           Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
470   {
471     /*
472      * for each sequence residue mapped to a structure position...
473      */
474     for (int seqPos : structureMapping.getMapping().keySet())
475     {
476       /*
477        * find visible complementary features at mapped position(s)
478        */
479       MappedFeatures mf = complementRenderer
480               .findComplementFeaturesAtResidue(seq, seqPos);
481       if (mf != null)
482       {
483         for (SequenceFeature sf : mf.features)
484         {
485           String type = sf.getType();
486
487           /*
488            * Don't copy features which originated from Chimera
489            */
490           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
491                   .equals(sf.getFeatureGroup()))
492           {
493             continue;
494           }
495
496           /*
497            * record feature 'value' (score/description/type) as at the
498            * corresponding structure position
499            */
500           List<int[]> mappedRanges = structureMapping
501                   .getPDBResNumRanges(seqPos, seqPos);
502
503           if (!mappedRanges.isEmpty())
504           {
505             String value = sf.getDescription();
506             if (value == null || value.length() == 0)
507             {
508               value = type;
509             }
510             float score = sf.getScore();
511             if (score != 0f && !Float.isNaN(score))
512             {
513               value = Float.toString(score);
514             }
515             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
516             if (featureValues == null)
517             {
518               featureValues = new HashMap<>();
519               theMap.put(type, featureValues);
520             }
521             for (int[] range : mappedRanges)
522             {
523               addAtomSpecRange(featureValues, value, modelNumber, range[0],
524                       range[1], structureMapping.getChain());
525             }
526           }
527         }
528       }
529     }
530   }
531
532   /**
533    * Inspect features on the sequence; for each feature that is visible, determine
534    * its mapped ranges in the structure (if any) according to the given mapping,
535    * and add them to the map.
536    * 
537    * @param visibleFeatures
538    * @param mapping
539    * @param seq
540    * @param theMap
541    * @param modelNumber
542    */
543   protected static void scanSequenceFeatures(List<String> visibleFeatures,
544           StructureMapping mapping, SequenceI seq,
545           Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
546   {
547     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
548             visibleFeatures.toArray(new String[visibleFeatures.size()]));
549     for (SequenceFeature sf : sfs)
550     {
551       String type = sf.getType();
552
553       /*
554        * Don't copy features which originated from Chimera
555        */
556       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
557               .equals(sf.getFeatureGroup()))
558       {
559         continue;
560       }
561
562       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
563               sf.getEnd());
564
565       if (!mappedRanges.isEmpty())
566       {
567         String value = sf.getDescription();
568         if (value == null || value.length() == 0)
569         {
570           value = type;
571         }
572         float score = sf.getScore();
573         if (score != 0f && !Float.isNaN(score))
574         {
575           value = Float.toString(score);
576         }
577         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
578         if (featureValues == null)
579         {
580           featureValues = new HashMap<>();
581           theMap.put(type, featureValues);
582         }
583         for (int[] range : mappedRanges)
584         {
585           addAtomSpecRange(featureValues, value, modelNumber, range[0],
586                   range[1], mapping.getChain());
587         }
588       }
589     }
590   }
591
592   /**
593    * Traverse the map of features/values/models/chains/positions to construct a
594    * list of 'setattr' commands (one per distinct feature type and value).
595    * <p>
596    * The format of each command is
597    * 
598    * <pre>
599    * <blockquote> setattr r <featureName> " " #modelnumber:range.chain 
600    * e.g. setattr r jv:chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
601    * </blockquote>
602    * </pre>
603    * 
604    * @param featureMap
605    * @param isChimeraX
606    * @return
607    */
608   protected static List<String> buildSetAttributeCommands(
609           Map<String, Map<Object, AtomSpecModel>> featureMap,
610           boolean isChimeraX)
611   {
612     List<String> commands = new ArrayList<>();
613     for (String featureType : featureMap.keySet())
614     {
615       String attributeName = makeAttributeName(featureType);
616
617       /*
618        * clear down existing attributes for this feature
619        */
620       // 'problem' - sets attribute to None on all residues - overkill?
621       // commands.add("~setattr r " + attributeName + " :*");
622
623       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
624       for (Object value : values.keySet())
625       {
626         /*
627          * for each distinct value recorded for this feature type,
628          * add a command to set the attribute on the mapped residues
629          * Put values in single quotes, encoding any embedded single quotes
630          */
631         AtomSpecModel atomSpecModel = values.get(value);
632         StringBuilder sb = new StringBuilder(128);
633         sb.append("setattr ");
634         if (isChimeraX)
635         {
636           sb.append(atomSpecModel.getAtomSpecX());
637         }
638         String featureValue = value.toString();
639         featureValue = featureValue.replaceAll("\\'", "&#39;");
640         sb.append(" res ").append(attributeName).append(" '")
641                 .append(featureValue).append("' ");
642         if (isChimeraX)
643         {
644           sb.append(" create true");
645         }
646         else
647         {
648           sb.append(atomSpecModel.getAtomSpec());
649         }
650         commands.add(sb.toString());
651       }
652     }
653
654     return commands;
655   }
656
657   /**
658    * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
659    * for a 'Jalview' namespace, and any non-alphanumeric character is converted
660    * to an underscore.
661    * 
662    * @param featureType
663    * @return
664    * 
665    *         <pre>
666    * &#64;see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
667    *         </pre>
668    */
669   protected static String makeAttributeName(String featureType)
670   {
671     StringBuilder sb = new StringBuilder();
672     if (featureType != null)
673     {
674       for (char c : featureType.toCharArray())
675       {
676         sb.append(Character.isLetterOrDigit(c) ? c : '_');
677       }
678     }
679     String attName = NAMESPACE_PREFIX + sb.toString();
680
681     /*
682      * Chimera treats an attribute name ending in 'color' as colour-valued;
683      * Jalview doesn't, so prevent this by appending an underscore
684      */
685     if (attName.toUpperCase().endsWith("COLOR"))
686     {
687       attName += "_";
688     }
689
690     return attName;
691   }
692
693 }