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