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