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