a4f4cffa8986ac39ada30c4bc006d05717e92a17
[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 java.awt.Color;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.Map;
28
29 import jalview.structure.AtomSpecModel;
30 import jalview.structure.StructureCommand;
31 import jalview.structure.StructureCommandI;
32 import jalview.structure.StructureCommandsBase;
33 import jalview.util.ColorUtils;
34
35 /**
36  * Routines for generating Chimera commands for Jalview/Chimera binding
37  * 
38  * @author JimP
39  * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/framecommand.html
40  * 
41  */
42 public class ChimeraCommands extends StructureCommandsBase
43 {
44   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/focus.html
45   private static final StructureCommand FOCUS_VIEW = new StructureCommand("focus");
46
47   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/listen.html#listresattr
48   private static final StructureCommand LIST_RESIDUE_ATTRIBUTES = new StructureCommand("list resattr");
49
50   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/stop.html
51   private static final StructureCommand CLOSE_CHIMERA = new StructureCommand("stop really");
52
53   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/listen.html
54   private static final StructureCommand STOP_NOTIFY_SELECTION = new StructureCommand("listen stop selection");
55
56   private static final StructureCommand STOP_NOTIFY_MODELS = new StructureCommand("listen stop models");
57
58   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/listen.html#listselection
59   private static final StructureCommand GET_SELECTION = new StructureCommand("list selection level residue");
60
61   private static final StructureCommand SHOW_BACKBONE = new StructureCommand(
62           "~display all;~ribbon;chain @CA|P");
63
64   private static final StructureCommandI COLOUR_BY_CHARGE = new StructureCommand(
65           "color white;color red ::ASP,GLU;color blue ::LYS,ARG;color yellow ::CYS");
66
67   // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/rainbow.html
68   private static final StructureCommandI COLOUR_BY_CHAIN = new StructureCommand(
69           "rainbow chain");
70
71   // Chimera clause to exclude alternate locations in atom selection
72   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
73
74   @Override
75   public StructureCommandI colourResidues(String atomSpec, Color colour)
76   {
77     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/color.html
78     String colourCode = getColourString(colour);
79     return new StructureCommand("color " + colourCode + " " + atomSpec);
80   }
81
82   /**
83    * Returns a colour formatted suitable for use in viewer command syntax
84    * 
85    * @param colour
86    * @return
87    */
88   protected String getColourString(Color colour)
89   {
90     return ColorUtils.toTkCode(colour);
91   }
92
93   /**
94    * Traverse the map of features/values/models/chains/positions to construct a
95    * list of 'setattr' commands (one per distinct feature type and value).
96    * <p>
97    * The format of each command is
98    * 
99    * <pre>
100    * <blockquote> setattr r <featureName> " " #modelnumber:range.chain 
101    * e.g. setattr r jv_chain &lt;value&gt; #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
102    * </blockquote>
103    * </pre>
104    * 
105    * @param featureMap
106    * @param binding
107    * @return
108    */
109   @Override
110   public List<StructureCommandI> setAttributes(
111           Map<String, Map<Object, AtomSpecModel>> featureMap)
112   {
113     List<StructureCommandI> commands = new ArrayList<>();
114     for (String featureType : featureMap.keySet())
115     {
116       String attributeName = makeAttributeName(featureType);
117
118       /*
119        * clear down existing attributes for this feature
120        */
121       // 'problem' - sets attribute to None on all residues - overkill?
122       // commands.add("~setattr r " + attributeName + " :*");
123
124       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
125       for (Object value : values.keySet())
126       {
127         /*
128          * for each distinct value recorded for this feature type,
129          * add a command to set the attribute on the mapped residues
130          * Put values in single quotes, encoding any embedded single quotes
131          */
132         AtomSpecModel atomSpecModel = values.get(value);
133         String featureValue = value.toString();
134         featureValue = featureValue.replaceAll("\\'", "&#39;");
135         StructureCommandI cmd = setAttribute(attributeName, featureValue,
136                 atomSpecModel);
137         commands.add(cmd);
138       }
139     }
140
141     return commands;
142   }
143
144   /**
145    * Returns a viewer command to set the given residue attribute value on
146    * residues specified by the AtomSpecModel, for example
147    * 
148    * <pre>
149    * setatr res jv_chain 'primary' #1:12-34,48-55.B
150    * </pre>
151    * 
152    * @param attributeName
153    * @param attributeValue
154    * @param atomSpecModel
155    * @return
156    */
157   protected StructureCommandI setAttribute(String attributeName,
158           String attributeValue,
159           AtomSpecModel atomSpecModel)
160   {
161     StringBuilder sb = new StringBuilder(128);
162     sb.append("setattr res ").append(attributeName).append(" '")
163             .append(attributeValue).append("' ");
164     sb.append(getAtomSpec(atomSpecModel, false));
165     return new StructureCommand(sb.toString());
166   }
167
168   /**
169    * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
170    * for a 'Jalview' namespace, and any non-alphanumeric character is converted
171    * to an underscore.
172    * 
173    * @param featureType
174    * @return
175    * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
176    */
177   @Override
178   protected String makeAttributeName(String featureType)
179   {
180     String attName = super.makeAttributeName(featureType);
181
182     /*
183      * Chimera treats an attribute name ending in 'color' as colour-valued;
184      * Jalview doesn't, so prevent this by appending an underscore
185      */
186     if (attName.toUpperCase().endsWith("COLOR"))
187     {
188       attName += "_";
189     }
190
191     return attName;
192   }
193
194   @Override
195   public StructureCommandI colourByChain()
196   {
197     return COLOUR_BY_CHAIN;
198   }
199
200   @Override
201   public List<StructureCommandI> colourByCharge()
202   {
203     return Arrays.asList(COLOUR_BY_CHARGE);
204   }
205
206   @Override
207   public String getResidueSpec(String residue)
208   {
209     return "::" + residue;
210   }
211
212   @Override
213   public StructureCommandI setBackgroundColour(Color col)
214   {
215     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/set.html#bgcolor
216     return new StructureCommand("set bgColor " + ColorUtils.toTkCode(col));
217   }
218
219   @Override
220   public StructureCommandI focusView()
221   {
222     return FOCUS_VIEW;
223   }
224
225   @Override
226   public List<StructureCommandI> superposeStructures(AtomSpecModel ref,
227           AtomSpecModel spec)
228   {
229     /*
230      * Form Chimera match command to match spec to ref
231      * (the first set of atoms are moved on to the second)
232      * 
233      * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
234      * 
235      * @see https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
236      */
237     StringBuilder cmd = new StringBuilder();
238     String atomSpecAlphaOnly = getAtomSpec(spec, true);
239     String refSpecAlphaOnly = getAtomSpec(ref, true);
240     cmd.append("match ").append(atomSpecAlphaOnly).append(" ").append(refSpecAlphaOnly);
241
242     /*
243      * show superposed residues as ribbon
244      */
245     String atomSpec = getAtomSpec(spec, false);
246     String refSpec = getAtomSpec(ref, false);
247     cmd.append("; ribbon ");
248     cmd.append(atomSpec).append("|").append(refSpec).append("; focus");
249
250     return Arrays.asList(new StructureCommand(cmd.toString()));
251   }
252
253   @Override
254   public StructureCommandI openCommandFile(String path)
255   {
256     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
257     return new StructureCommand("open cmd:" + path);
258   }
259
260   @Override
261   public StructureCommandI saveSession(String filepath)
262   {
263     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
264     return new StructureCommand("save " + filepath);
265   }
266
267   /**
268    * Returns the range(s) modelled by {@code atomSpec} formatted as a Chimera
269    * atomspec string, e.g.
270    * 
271    * <pre>
272    * #0:15.A,28.A,54.A,70-72.A|#1:2.A,6.A,11.A,13-14.A
273    * </pre>
274    * 
275    * where
276    * <ul>
277    * <li>#0 is a model number</li>
278    * <li>15 or 70-72 is a residue number, or range of residue numbers</li>
279    * <li>.A is a chain identifier</li>
280    * <li>residue ranges are separated by comma</li>
281    * <li>atomspecs for distinct models are separated by | (or)</li>
282    * </ul>
283    * 
284    * <pre>
285    * 
286    * @param model
287    * @param alphaOnly
288    * @return
289    * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec.html
290    */
291   @Override
292   public String getAtomSpec(AtomSpecModel atomSpec, boolean alphaOnly)
293   {
294     StringBuilder sb = new StringBuilder(128);
295     boolean firstModel = true;
296     for (String model : atomSpec.getModels())
297     {
298       if (!firstModel)
299       {
300         sb.append("|");
301       }
302       firstModel = false;
303       appendModel(sb, model, atomSpec, alphaOnly);
304     }
305     return sb.toString();
306   }
307
308   /**
309    * A helper method to append an atomSpec string for atoms in the given model
310    * 
311    * @param sb
312    * @param model
313    * @param atomSpec
314    * @param alphaOnly
315    */
316   protected void appendModel(StringBuilder sb, String model,
317           AtomSpecModel atomSpec, boolean alphaOnly)
318   {
319     sb.append("#").append(model).append(":");
320
321     boolean firstPositionForModel = true;
322
323     for (String chain : atomSpec.getChains(model))
324     {
325       chain = " ".equals(chain) ? chain : chain.trim();
326
327       List<int[]> rangeList = atomSpec.getRanges(model, chain);
328       for (int[] range : rangeList)
329       {
330         appendRange(sb, range[0], range[1], chain, firstPositionForModel,
331                 false);
332         firstPositionForModel = false;
333       }
334     }
335     if (alphaOnly)
336     {
337       /*
338        * restrict to alpha carbon, no alternative locations
339        * (needed to ensuring matching atom counts for superposition)
340        */
341       // TODO @P instead if RNA - add nucleotide flag to AtomSpecModel?
342       sb.append("@CA").append(NO_ALTLOCS);
343     }
344   }
345
346   @Override
347   public List<StructureCommandI> showBackbone()
348   {
349     return Arrays.asList(SHOW_BACKBONE);
350   }
351
352   @Override
353   public StructureCommandI loadFile(String file)
354   {
355     return new StructureCommand("open " + file);
356   }
357
358   /**
359    * Overrides the default method to concatenate colour commands into one
360    */
361   @Override
362   public List<StructureCommandI> colourBySequence(
363           Map<Object, AtomSpecModel> colourMap)
364   {
365     List<StructureCommandI> commands = new ArrayList<>();
366     StringBuilder sb = new StringBuilder(colourMap.size() * 20);
367     boolean first = true;
368     for (Object key : colourMap.keySet())
369     {
370       Color colour = (Color) key;
371       final AtomSpecModel colourData = colourMap.get(colour);
372       StructureCommandI command = getColourCommand(colourData, colour);
373       if (!first)
374       {
375         sb.append(getCommandSeparator());
376       }
377       first = false;
378       sb.append(command.getCommand());
379     }
380
381     commands.add(new StructureCommand(sb.toString()));
382     return commands;
383   }
384
385   @Override
386   public StructureCommandI openSession(String filepath)
387   {
388     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
389     // this version of the command has no dependency on file extension
390     return new StructureCommand("open chimera:" + filepath);
391   }
392
393   @Override
394   public StructureCommandI showStructures(AtomSpecModel restrictTo)
395   {
396     if (restrictTo == null)
397     {
398       return new StructureCommand("ribbon");
399     }
400
401     String atomSpec = getAtomSpec(restrictTo, false);
402     String cmd = "ribbon " + atomSpec;
403     return new StructureCommand(cmd);
404   }
405
406   @Override
407   public StructureCommandI hideChain(String modelId, String chainId)
408   {
409     String cmd = "~ribbon #" + modelId + ":." + chainId;
410     return new StructureCommand(cmd);
411   }
412
413   @Override
414   public StructureCommandI hideAll()
415   {
416     return new StructureCommand("~display; ~ribbon");
417   }
418   public StructureCommandI closeViewer()
419   {
420     return CLOSE_CHIMERA;
421   }
422
423   @Override
424   public List<StructureCommandI> startNotifications(String uri)
425   {
426     // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/listen.html
427     List<StructureCommandI> cmds = new ArrayList<>();
428     cmds.add(new StructureCommand("listen start models url " + uri));
429     cmds.add(new StructureCommand("listen start select prefix SelectionChanged url " + uri));
430     return cmds;
431   }
432
433   @Override
434   public List<StructureCommandI> stopNotifications()
435   {
436     List<StructureCommandI> cmds = new ArrayList<>();
437     cmds.add(STOP_NOTIFY_MODELS);
438     cmds.add(STOP_NOTIFY_SELECTION);
439     return cmds;
440   }
441
442   @Override
443   public StructureCommandI getSelectedResidues()
444   {
445     return GET_SELECTION;
446   }
447
448   @Override
449   public StructureCommandI listResidueAttributes()
450   {
451     return LIST_RESIDUE_ATTRIBUTES;
452   }
453
454   @Override
455   public StructureCommandI getResidueAttributes(String attName)
456   {
457     // this alternative command
458     // list residues spec ':*/attName' attr attName
459     // doesn't report 'None' values (which is good), but
460     // fails for 'average.bfactor' (which is bad):
461     return new StructureCommand("list residues attr '" + attName + "'");
462   }
463
464 }