061f6d90c9c3e62612dd0a0610af2ccf2c24fdee
[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.FeatureRenderer;
24 import jalview.api.SequenceRenderer;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.StructureViewerBase;
29 import jalview.structure.StructureMapping;
30 import jalview.structure.StructureMappingcommandSet;
31 import jalview.structure.StructureSelectionManager;
32 import jalview.util.ColorUtils;
33 import jalview.util.Comparison;
34
35 import java.awt.Color;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.LinkedHashMap;
39 import java.util.List;
40 import java.util.Map;
41
42 /**
43  * Routines for generating Chimera commands for Jalview/Chimera binding
44  * 
45  * @author JimP
46  * 
47  */
48 public class ChimeraCommands
49 {
50   /**
51    * Constructs Chimera commands to colour residues as per the Jalview alignment
52    * 
53    * @param ssm
54    * @param files
55    * @param sequence
56    * @param sr
57    * @param fr
58    * @param alignment
59    * @return
60    */
61   public static StructureMappingcommandSet getColourBySequenceCommand(
62           StructureSelectionManager ssm, String[] files,
63           SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
64           AlignmentI alignment)
65   {
66     Map<Object, AtomSpecModel> colourMap = buildColoursMap(
67             ssm, files, sequence, sr, fr, alignment);
68
69     List<String> colourCommands = buildColourCommands(colourMap);
70
71     StructureMappingcommandSet cs = new StructureMappingcommandSet(
72             ChimeraCommands.class, null,
73             colourCommands.toArray(new String[colourCommands.size()]));
74
75     return cs;
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 static 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<String>();
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       sb.append("color ").append(colourCode).append(" ");
113       firstColour = false;
114       final AtomSpecModel colourData = colourMap
115               .get(colour);
116       sb.append(colourData.getAtomSpec());
117     }
118     commands.add(sb.toString());
119     return commands;
120   }
121
122   /**
123    * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
124    * builds a Chimera format atom spec
125    * 
126    * @param modelAndChainRanges
127    */
128   protected static String getAtomSpec(
129           Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
130   {
131     StringBuilder sb = new StringBuilder(128);
132     boolean firstModelForColour = true;
133     for (Integer model : modelAndChainRanges.keySet())
134     {
135       boolean firstPositionForModel = true;
136       if (!firstModelForColour)
137       {
138         sb.append("|");
139       }
140       firstModelForColour = false;
141       sb.append("#").append(model).append(":");
142
143       final Map<String, List<int[]>> modelData = modelAndChainRanges
144               .get(model);
145       for (String chain : modelData.keySet())
146       {
147         boolean hasChain = !"".equals(chain.trim());
148         for (int[] range : modelData.get(chain))
149         {
150           if (!firstPositionForModel)
151           {
152             sb.append(",");
153           }
154           if (range[0] == range[1])
155           {
156             sb.append(range[0]);
157           }
158           else
159           {
160             sb.append(range[0]).append("-").append(range[1]);
161           }
162           if (hasChain)
163           {
164             sb.append(".").append(chain);
165           }
166           firstPositionForModel = false;
167         }
168       }
169     }
170     return sb.toString();
171   }
172
173   /**
174    * <pre>
175    * Build a data structure which maps contiguous subsequences for each colour. 
176    * This generates a data structure from which we can easily generate the 
177    * Chimera command for colour by sequence.
178    * Color
179    *     Model number
180    *         Chain
181    *             list of start/end ranges
182    * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
183    * </pre>
184    */
185   protected static Map<Object, AtomSpecModel> buildColoursMap(
186           StructureSelectionManager ssm, String[] files,
187           SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
188           AlignmentI alignment)
189   {
190     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<Object, AtomSpecModel>();
191     Color lastColour = null;
192     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
193     {
194       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
195
196       if (mapping == null || mapping.length < 1)
197       {
198         continue;
199       }
200
201       int startPos = -1, lastPos = -1;
202       String lastChain = "";
203       for (int s = 0; s < sequence[pdbfnum].length; s++)
204       {
205         for (int sp, m = 0; m < mapping.length; m++)
206         {
207           final SequenceI seq = sequence[pdbfnum][s];
208           if (mapping[m].getSequence() == seq
209                   && (sp = alignment.findIndex(seq)) > -1)
210           {
211             SequenceI asp = alignment.getSequenceAt(sp);
212             for (int r = 0; r < asp.getLength(); r++)
213             {
214               // no mapping to gaps in sequence
215               if (Comparison.isGap(asp.getCharAt(r)))
216               {
217                 continue;
218               }
219               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
220
221               if (pos < 1 || pos == lastPos)
222               {
223                 continue;
224               }
225
226               Color colour = sr.getResidueColour(seq, r, fr);
227               final String chain = mapping[m].getChain();
228
229               /*
230                * Just keep incrementing the end position for this colour range
231                * _unless_ colour, PDB model or chain has changed, or there is a
232                * gap in the mapped residue sequence
233                */
234               final boolean newColour = !colour.equals(lastColour);
235               final boolean nonContig = lastPos + 1 != pos;
236               final boolean newChain = !chain.equals(lastChain);
237               if (newColour || nonContig || newChain)
238               {
239                 if (startPos != -1)
240                 {
241                   addRange(colourMap, lastColour, pdbfnum, startPos,
242                           lastPos, lastChain);
243                 }
244                 startPos = pos;
245               }
246               lastColour = colour;
247               lastPos = pos;
248               lastChain = chain;
249             }
250             // final colour range
251             if (lastColour != null)
252             {
253               addRange(colourMap, lastColour, pdbfnum, startPos,
254                       lastPos, lastChain);
255             }
256             // break;
257           }
258         }
259       }
260     }
261     return colourMap;
262   }
263
264   /**
265    * Helper method to add one contiguous colour range to the colour map.
266    * 
267    * @param map
268    * @param key
269    * @param model
270    * @param startPos
271    * @param endPos
272    * @param chain
273    */
274   protected static void addRange(Map<Object, AtomSpecModel> map,
275           Object key, int model, int startPos, int endPos, String chain)
276   {
277     /*
278      * Get/initialize map of data for the colour
279      */
280     AtomSpecModel atomSpec = map.get(key);
281     if (atomSpec == null)
282     {
283       atomSpec = new AtomSpecModel();
284       map.put(key, atomSpec);
285     }
286
287     atomSpec.addRange(model, startPos, endPos, chain);
288   }
289
290   /**
291    * Constructs and returns Chimera commands to set attributes on residues
292    * corresponding to features in Jalview. Attribute names are the Jalview
293    * feature type, with a "jv_" prefix.
294    * 
295    * @param ssm
296    * @param files
297    * @param seqs
298    * @param fr
299    * @param alignment
300    * @return
301    */
302   public static StructureMappingcommandSet getSetAttributeCommandsForFeatures(
303           StructureSelectionManager ssm, String[] files,
304           SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
305   {
306     Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
307             ssm, files, seqs, fr, alignment);
308
309     List<String> commands = buildSetAttributeCommands(featureMap);
310
311     StructureMappingcommandSet cs = new StructureMappingcommandSet(
312             ChimeraCommands.class, null,
313             commands.toArray(new String[commands.size()]));
314
315     return cs;
316   }
317
318   /**
319    * <pre>
320    * Helper method to build a map of 
321    *   { featureType, { feature value, AtomSpecModel } }
322    * </pre>
323    * 
324    * @param ssm
325    * @param files
326    * @param seqs
327    * @param fr
328    * @param alignment
329    * @return
330    */
331   protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
332           StructureSelectionManager ssm, String[] files,
333           SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
334   {
335     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<String, Map<Object, AtomSpecModel>>();
336
337     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
338     if (visibleFeatures.isEmpty())
339     {
340       return theMap;
341     }
342     
343     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
344     {
345       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
346
347       if (mapping == null || mapping.length < 1)
348       {
349         continue;
350       }
351
352       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
353       {
354         for (int m = 0; m < mapping.length; m++)
355         {
356           final SequenceI seq = seqs[pdbfnum][seqNo];
357           int sp = alignment.findIndex(seq);
358           if (mapping[m].getSequence() == seq && sp > -1)
359           {
360             /*
361              * found a sequence with a mapping to a structure;
362              * now scan its features
363              */
364             SequenceI asp = alignment.getSequenceAt(sp);
365
366             scanSequenceFeatures(visibleFeatures, mapping[m], asp, theMap,
367                     pdbfnum);
368           }
369         }
370       }
371     }
372     return theMap;
373   }
374
375   /**
376    * Inspect features on the sequence; for each feature that is visible,
377    * determine its mapped ranges in the structure (if any) according to the
378    * given mapping, 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     SequenceFeature[] sfs = seq.getSequenceFeatures();
391     if (sfs == null)
392     {
393       return;
394     }
395
396     for (SequenceFeature sf : sfs)
397     {
398       String type = sf.getType();
399
400       /*
401        * Only copy visible features, don't copy any which originated
402        * from Chimera, and suppress uninteresting ones (e.g. RESNUM)
403        */
404       boolean isFromViewer = JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
405               .equals(sf.getFeatureGroup());
406       if (isFromViewer || !visibleFeatures.contains(type))
407       {
408         continue;
409       }
410       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
411               sf.getEnd());
412
413       if (!mappedRanges.isEmpty())
414       {
415         String value = sf.getDescription();
416         if (value == null || value.length() == 0)
417         {
418           value = type;
419         }
420         float score = sf.getScore();
421         if (score != 0f && !Float.isNaN(score))
422         {
423           value = Float.toString(score);
424         }
425         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
426         if (featureValues == null)
427         {
428           featureValues = new HashMap<Object, AtomSpecModel>();
429           theMap.put(type, featureValues);
430         }
431         for (int[] range : mappedRanges)
432         {
433           addRange(featureValues, value, modelNumber, range[0], range[1],
434                   mapping.getChain());
435         }
436       }
437     }
438   }
439
440   /**
441    * Traverse the map of features/values/models/chains/positions to construct a
442    * list of 'setattr' commands (one per distinct feature type and value).
443    * <p>
444    * The format of each command is
445    * 
446    * <pre>
447    * <blockquote> setattr r <featureName> " " #modelnumber:range.chain 
448    * e.g. setattr r jv:chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
449    * </blockquote>
450    * </pre>
451    * 
452    * @param featureMap
453    * @return
454    */
455   protected static List<String> buildSetAttributeCommands(
456           Map<String, Map<Object, AtomSpecModel>> featureMap)
457   {
458     List<String> commands = new ArrayList<String>();
459     for (String featureType : featureMap.keySet())
460     {
461       String attributeName = makeAttributeName(featureType);
462
463       /*
464        * clear down existing attributes for this feature
465        */
466       // 'problem' - sets attribute to None on all residues - overkill?
467       // commands.add("~setattr r " + attributeName + " :*");
468
469       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
470       for (Object value : values.keySet())
471       {
472         /*
473          * for each distinct value recorded for this feature type,
474          * add a command to set the attribute on the mapped residues
475          */
476         StringBuilder sb = new StringBuilder(128);
477         sb.append("setattr r ").append(attributeName).append(" \"")
478                 .append(value.toString()).append("\" ");
479         sb.append(values.get(value).getAtomSpec());
480         commands.add(sb.toString());
481       }
482     }
483
484     return commands;
485   }
486
487   /**
488    * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
489    * for a 'Jalview' namespace, and any non-alphanumeric character is converted
490    * to an underscore.
491    * 
492    * @param featureType
493    * @return <pre>
494    * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
495    * </pre>
496    */
497   protected static String makeAttributeName(String featureType)
498   {
499     StringBuilder sb = new StringBuilder();
500     if (featureType != null)
501     {
502       for (char c : featureType.toCharArray())
503       {
504         sb.append(Character.isLetterOrDigit(c) ? c : '_');
505       }
506     }
507     String attName = StructureViewerBase.NAMESPACE_PREFIX + sb.toString();
508
509     /*
510      * Chimera treats an attribute name ending in 'color' as colour-valued;
511      * Jalview doesn't, so prevent this by appending an underscore
512      */
513     if (attName.toUpperCase().endsWith("COLOR"))
514     {
515       attName += "_";
516     }
517
518     return attName;
519   }
520
521 }