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