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