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