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