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