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