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