c355abed0db9cc01e6478e948aebfdd28075e9cb
[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.datamodel.AlignmentI;
27 import jalview.datamodel.MappedFeatures;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.Desktop;
31 import jalview.structure.AtomSpecModel;
32 import jalview.structure.StructureCommand;
33 import jalview.structure.StructureCommandI;
34 import jalview.structure.StructureCommandsBase;
35 import jalview.structure.StructureMapping;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.ColorUtils;
38
39 import java.awt.Color;
40 import java.util.ArrayList;
41 import java.util.Arrays;
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 extends StructureCommandsBase
54 {
55   private static final StructureCommand SHOW_BACKBONE = new StructureCommand(
56           "~display all;~ribbon;chain @CA|P");
57
58   public static final String NAMESPACE_PREFIX = "jv_";
59
60   private static final StructureCommandI COLOUR_BY_CHARGE = new StructureCommand(
61           "color white;color red ::ASP,GLU;color blue ::LYS,ARG;color yellow ::CYS");
62
63   private static final StructureCommandI COLOUR_BY_CHAIN = new StructureCommand(
64           "rainbow chain");
65
66   // Chimera clause to exclude alternate locations in atom selection
67   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
68
69   @Override
70   public StructureCommandI getColourCommand(String atomSpec, Color colour)
71   {
72     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/color.html
73     String colourCode = getColourString(colour);
74     return new StructureCommand("color " + colourCode + " " + atomSpec);
75   }
76
77   /**
78    * Returns a colour formatted suitable for use in viewer command syntax
79    * 
80    * @param colour
81    * @return
82    */
83   protected String getColourString(Color colour)
84   {
85     return ColorUtils.toTkCode(colour);
86   }
87
88   /**
89    * Constructs and returns Chimera commands to set attributes on residues
90    * corresponding to features in Jalview. Attribute names are the Jalview feature
91    * type, with a "jv_" prefix.
92    * 
93    * @param ssm
94    * @param files
95    * @param seqs
96    * @param viewPanel
97    * @return
98    */
99   @Override
100   public List<StructureCommandI> setAttributesForFeatures(
101           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
102           AlignmentViewPanel viewPanel)
103   {
104     Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
105             ssm, files, seqs, viewPanel);
106
107     return setAttributes(featureMap);
108   }
109
110   /**
111    * <pre>
112    * Helper method to build a map of 
113    *   { featureType, { feature value, AtomSpecModel } }
114    * </pre>
115    * 
116    * @param ssm
117    * @param files
118    * @param seqs
119    * @param viewPanel
120    * @return
121    */
122   protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
123           StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
124           AlignmentViewPanel viewPanel)
125   {
126     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
127
128     FeatureRenderer fr = viewPanel.getFeatureRenderer();
129     if (fr == null)
130     {
131       return theMap;
132     }
133
134     AlignViewportI viewport = viewPanel.getAlignViewport();
135     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
136
137     /*
138      * if alignment is showing features from complement, we also transfer
139      * these features to the corresponding mapped structure residues
140      */
141     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
142     List<String> complementFeatures = new ArrayList<>();
143     FeatureRenderer complementRenderer = null;
144     if (showLinkedFeatures)
145     {
146       AlignViewportI comp = fr.getViewport().getCodingComplement();
147       if (comp != null)
148       {
149         complementRenderer = Desktop.getAlignFrameFor(comp)
150                 .getFeatureRenderer();
151         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
152       }
153     }
154     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
155     {
156       return theMap;
157     }
158
159     AlignmentI alignment = viewPanel.getAlignment();
160     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
161     {
162       final int modelNumber = pdbfnum + getModelStartNo();
163       String modelId = String.valueOf(modelNumber);
164       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
165
166       if (mapping == null || mapping.length < 1)
167       {
168         continue;
169       }
170
171       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
172       {
173         for (int m = 0; m < mapping.length; m++)
174         {
175           final SequenceI seq = seqs[pdbfnum][seqNo];
176           int sp = alignment.findIndex(seq);
177           StructureMapping structureMapping = mapping[m];
178           if (structureMapping.getSequence() == seq && sp > -1)
179           {
180             /*
181              * found a sequence with a mapping to a structure;
182              * now scan its features
183              */
184             if (!visibleFeatures.isEmpty())
185             {
186               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
187                       theMap, modelId);
188             }
189             if (showLinkedFeatures)
190             {
191               scanComplementFeatures(complementRenderer, structureMapping,
192                       seq, theMap, modelId);
193             }
194           }
195         }
196       }
197     }
198     return theMap;
199   }
200
201   /**
202    * Scans visible features in mapped positions of the CDS/peptide complement, and
203    * adds any found to the map of attribute values/structure positions
204    * 
205    * @param complementRenderer
206    * @param structureMapping
207    * @param seq
208    * @param theMap
209    * @param modelNumber
210    */
211   protected static void scanComplementFeatures(
212           FeatureRenderer complementRenderer,
213           StructureMapping structureMapping, SequenceI seq,
214           Map<String, Map<Object, AtomSpecModel>> theMap,
215           String modelNumber)
216   {
217     /*
218      * for each sequence residue mapped to a structure position...
219      */
220     for (int seqPos : structureMapping.getMapping().keySet())
221     {
222       /*
223        * find visible complementary features at mapped position(s)
224        */
225       MappedFeatures mf = complementRenderer
226               .findComplementFeaturesAtResidue(seq, seqPos);
227       if (mf != null)
228       {
229         for (SequenceFeature sf : mf.features)
230         {
231           String type = sf.getType();
232
233           /*
234            * Don't copy features which originated from Chimera
235            */
236           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
237                   .equals(sf.getFeatureGroup()))
238           {
239             continue;
240           }
241
242           /*
243            * record feature 'value' (score/description/type) as at the
244            * corresponding structure position
245            */
246           List<int[]> mappedRanges = structureMapping
247                   .getPDBResNumRanges(seqPos, seqPos);
248
249           if (!mappedRanges.isEmpty())
250           {
251             String value = sf.getDescription();
252             if (value == null || value.length() == 0)
253             {
254               value = type;
255             }
256             float score = sf.getScore();
257             if (score != 0f && !Float.isNaN(score))
258             {
259               value = Float.toString(score);
260             }
261             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
262             if (featureValues == null)
263             {
264               featureValues = new HashMap<>();
265               theMap.put(type, featureValues);
266             }
267             for (int[] range : mappedRanges)
268             {
269               addAtomSpecRange(featureValues, value, modelNumber, range[0],
270                       range[1], structureMapping.getChain());
271             }
272           }
273         }
274       }
275     }
276   }
277
278   /**
279    * Inspect features on the sequence; for each feature that is visible,
280    * determine its mapped ranges in the structure (if any) according to the
281    * given mapping, and add them to the map.
282    * 
283    * @param visibleFeatures
284    * @param mapping
285    * @param seq
286    * @param theMap
287    * @param modelId
288    */
289   protected static void scanSequenceFeatures(List<String> visibleFeatures,
290           StructureMapping mapping, SequenceI seq,
291           Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
292   {
293     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
294             visibleFeatures.toArray(new String[visibleFeatures.size()]));
295     for (SequenceFeature sf : sfs)
296     {
297       String type = sf.getType();
298
299       /*
300        * Don't copy features which originated from Chimera
301        */
302       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
303               .equals(sf.getFeatureGroup()))
304       {
305         continue;
306       }
307
308       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
309               sf.getEnd());
310
311       if (!mappedRanges.isEmpty())
312       {
313         String value = sf.getDescription();
314         if (value == null || value.length() == 0)
315         {
316           value = type;
317         }
318         float score = sf.getScore();
319         if (score != 0f && !Float.isNaN(score))
320         {
321           value = Float.toString(score);
322         }
323         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
324         if (featureValues == null)
325         {
326           featureValues = new HashMap<>();
327           theMap.put(type, featureValues);
328         }
329         for (int[] range : mappedRanges)
330         {
331           addAtomSpecRange(featureValues, value, modelId, range[0],
332                   range[1], mapping.getChain());
333         }
334       }
335     }
336   }
337
338   /**
339    * Traverse the map of features/values/models/chains/positions to construct a
340    * list of 'setattr' commands (one per distinct feature type and value).
341    * <p>
342    * The format of each command is
343    * 
344    * <pre>
345    * <blockquote> setattr r <featureName> " " #modelnumber:range.chain 
346    * e.g. setattr r jv_chain &lt;value&gt; #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
347    * </blockquote>
348    * </pre>
349    * 
350    * @param featureMap
351    * @return
352    */
353   protected List<StructureCommandI> setAttributes(
354           Map<String, Map<Object, AtomSpecModel>> featureMap)
355   {
356     List<StructureCommandI> commands = new ArrayList<>();
357     for (String featureType : featureMap.keySet())
358     {
359       String attributeName = makeAttributeName(featureType);
360
361       /*
362        * clear down existing attributes for this feature
363        */
364       // 'problem' - sets attribute to None on all residues - overkill?
365       // commands.add("~setattr r " + attributeName + " :*");
366
367       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
368       for (Object value : values.keySet())
369       {
370         /*
371          * for each distinct value recorded for this feature type,
372          * add a command to set the attribute on the mapped residues
373          * Put values in single quotes, encoding any embedded single quotes
374          */
375         AtomSpecModel atomSpecModel = values.get(value);
376         String featureValue = value.toString();
377         featureValue = featureValue.replaceAll("\\'", "&#39;");
378         StructureCommandI cmd = setAttribute(attributeName, featureValue,
379                 atomSpecModel);
380         commands.add(cmd);
381       }
382     }
383
384     return commands;
385   }
386
387   /**
388    * Returns a viewer command to set the given residue attribute value on
389    * residues specified by the AtomSpecModel, for example
390    * 
391    * <pre>
392    * setatr res jv_chain 'primary' #1:12-34,48-55.B
393    * </pre>
394    * 
395    * @param attributeName
396    * @param attributeValue
397    * @param atomSpecModel
398    * @return
399    */
400   protected StructureCommandI setAttribute(String attributeName,
401           String attributeValue,
402           AtomSpecModel atomSpecModel)
403   {
404     StringBuilder sb = new StringBuilder(128);
405     sb.append("setattr res ").append(attributeName).append(" '")
406             .append(attributeValue).append("' ");
407     sb.append(getAtomSpec(atomSpecModel, false));
408     return new StructureCommand(sb.toString());
409   }
410
411   /**
412    * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
413    * for a 'Jalview' namespace, and any non-alphanumeric character is converted
414    * to an underscore.
415    * 
416    * @param featureType
417    * @return
418    * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
419    */
420   protected static String makeAttributeName(String featureType)
421   {
422     StringBuilder sb = new StringBuilder();
423     if (featureType != null)
424     {
425       for (char c : featureType.toCharArray())
426       {
427         sb.append(Character.isLetterOrDigit(c) ? c : '_');
428       }
429     }
430     String attName = NAMESPACE_PREFIX + sb.toString();
431
432     /*
433      * Chimera treats an attribute name ending in 'color' as colour-valued;
434      * Jalview doesn't, so prevent this by appending an underscore
435      */
436     if (attName.toUpperCase().endsWith("COLOR"))
437     {
438       attName += "_";
439     }
440
441     return attName;
442   }
443
444   @Override
445   public StructureCommandI colourByChain()
446   {
447     return COLOUR_BY_CHAIN;
448   }
449
450   @Override
451   public List<StructureCommandI> colourByCharge()
452   {
453     return Arrays.asList(COLOUR_BY_CHARGE);
454   }
455
456   @Override
457   public String getResidueSpec(String residue)
458   {
459     return "::" + residue;
460   }
461
462   @Override
463   public StructureCommandI setBackgroundColour(Color col)
464   {
465     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/set.html#bgcolor
466     return new StructureCommand("set bgColor " + ColorUtils.toTkCode(col));
467   }
468
469   @Override
470   public StructureCommandI focusView()
471   {
472     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/focus.html
473     return new StructureCommand("focus");
474   }
475
476   @Override
477   public List<StructureCommandI> showChains(List<String> toShow)
478   {
479     /*
480      * Construct a chimera command like
481      * 
482      * ~display #*;~ribbon #*;ribbon :.A,:.B
483      */
484     StringBuilder cmd = new StringBuilder(64);
485     boolean first = true;
486     for (String chain : toShow)
487     {
488       String[] tokens = chain.split(":");
489       if (tokens.length == 2)
490       {
491         String showChainCmd = tokens[0] + ":." + tokens[1];
492         if (!first)
493         {
494           cmd.append(",");
495         }
496         cmd.append(showChainCmd);
497         first = false;
498       }
499     }
500
501     /*
502      * could append ";focus" to this command to resize the display to fill the
503      * window, but it looks more helpful not to (easier to relate chains to the
504      * whole)
505      */
506     final String command = "~display #*; ~ribbon #*; ribbon :"
507             + cmd.toString();
508     return Arrays.asList(new StructureCommand(command));
509   }
510
511   @Override
512   public List<StructureCommandI> superposeStructures(AtomSpecModel ref,
513           AtomSpecModel spec)
514   {
515     /*
516      * Form Chimera match command to match spec to ref
517      * (the first set of atoms are moved on to the second)
518      * 
519      * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
520      * 
521      * @see https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
522      */
523     StringBuilder cmd = new StringBuilder();
524     String atomSpecAlphaOnly = getAtomSpec(spec, true);
525     String refSpecAlphaOnly = getAtomSpec(ref, true);
526     cmd.append("match ").append(atomSpecAlphaOnly).append(" ").append(refSpecAlphaOnly);
527
528     /*
529      * show superposed residues as ribbon
530      */
531     String atomSpec = getAtomSpec(spec, false);
532     String refSpec = getAtomSpec(ref, false);
533     cmd.append("; ribbon ");
534     cmd.append(atomSpec).append("|").append(refSpec).append("; focus");
535
536     return Arrays.asList(new StructureCommand(cmd.toString()));
537   }
538
539   @Override
540   public StructureCommandI openCommandFile(String path)
541   {
542     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
543     return new StructureCommand("open cmd:" + path);
544   }
545
546   @Override
547   public StructureCommandI saveSession(String filepath)
548   {
549     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
550     return new StructureCommand("save " + filepath);
551   }
552
553   /**
554    * Returns the range(s) modelled by {@code atomSpec} formatted as a Chimera
555    * atomspec string, e.g.
556    * 
557    * <pre>
558    * #0:15.A,28.A,54.A,70-72.A|#1:2.A,6.A,11.A,13-14.A
559    * </pre>
560    * 
561    * where
562    * <ul>
563    * <li>#0 is a model number</li>
564    * <li>15 or 70-72 is a residue number, or range of residue numbers</li>
565    * <li>.A is a chain identifier</li>
566    * <li>residue ranges are separated by comma</li>
567    * <li>atomspecs for distinct models are separated by | (or)</li>
568    * </ul>
569    * 
570    * <pre>
571    * 
572    * @param model
573    * @param alphaOnly
574    * @return
575    * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec.html
576    */
577   @Override
578   public String getAtomSpec(AtomSpecModel atomSpec, boolean alphaOnly)
579   {
580     StringBuilder sb = new StringBuilder(128);
581     boolean firstModel = true;
582     for (String model : atomSpec.getModels())
583     {
584       if (!firstModel)
585       {
586         sb.append("|");
587       }
588       firstModel = false;
589       appendModel(sb, model, atomSpec, alphaOnly);
590     }
591     return sb.toString();
592   }
593
594   /**
595    * A helper method to append an atomSpec string for atoms in the given model
596    * 
597    * @param sb
598    * @param model
599    * @param atomSpec
600    * @param alphaOnly
601    */
602   protected void appendModel(StringBuilder sb, String model,
603           AtomSpecModel atomSpec, boolean alphaOnly)
604   {
605     sb.append("#").append(model).append(":");
606
607     boolean firstPositionForModel = true;
608
609     for (String chain : atomSpec.getChains(model))
610     {
611       chain = " ".equals(chain) ? chain : chain.trim();
612
613       List<int[]> rangeList = atomSpec.getRanges(model, chain);
614       for (int[] range : rangeList)
615       {
616         appendRange(sb, range[0], range[1], chain, firstPositionForModel,
617                 false);
618         firstPositionForModel = false;
619       }
620     }
621     if (alphaOnly)
622     {
623       /*
624        * restrict to alpha carbon, no alternative locations
625        * (needed to ensuring matching atom counts for superposition)
626        */
627       // TODO @P instead if RNA - add nucleotide flag to AtomSpecModel?
628       sb.append("@CA").append(NO_ALTLOCS);
629     }
630   }
631
632   @Override
633   public List<StructureCommandI> showBackbone()
634   {
635     return Arrays.asList(SHOW_BACKBONE);
636   }
637
638   @Override
639   public StructureCommandI loadFile(String file)
640   {
641     return new StructureCommand("open " + file);
642   }
643
644 }