JAL-1761 backbone type parameter for configuring which atoms are used for superpositi...
[jalview.git] / src / jalview / ext / jmol / JmolCommands.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.jmol;
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.api.AlignViewportI;
30 import jalview.api.AlignmentViewPanel;
31 import jalview.api.FeatureRenderer;
32 import jalview.api.SequenceRenderer;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.HiddenColumns;
35 import jalview.datamodel.SequenceI;
36 import jalview.renderer.seqfeatures.FeatureColourFinder;
37 import jalview.structure.AtomSpecModel;
38 import jalview.structure.StructureCommand;
39 import jalview.structure.StructureCommandI;
40 import jalview.structure.StructureCommandsBase;
41 import jalview.structure.StructureMapping;
42 import jalview.structure.StructureSelectionManager;
43 import jalview.structure.StructureCommandsI.AtomSpecType;
44 import jalview.util.Comparison;
45 import jalview.util.Platform;
46
47 /**
48  * Routines for generating Jmol commands for Jalview/Jmol binding
49  * 
50  * @author JimP
51  * 
52  */
53 public class JmolCommands extends StructureCommandsBase
54 {
55   private static final StructureCommand SHOW_BACKBONE = new StructureCommand(
56           "select *; cartoons off; backbone");
57
58   private static final StructureCommand FOCUS_VIEW = new StructureCommand("zoom 0");
59
60   private static final StructureCommand COLOUR_ALL_WHITE = new StructureCommand(
61           "select *;color white;");
62
63   private static final StructureCommandI COLOUR_BY_CHARGE = new StructureCommand(
64           "select *;color white;select ASP,GLU;color red;"
65                   + "select LYS,ARG;color blue;select CYS;color yellow");
66
67   private static final StructureCommandI COLOUR_BY_CHAIN = new StructureCommand(
68           "select *;color chain");
69
70   private static final String PIPE = "|";
71
72   private static final String HYPHEN = "-";
73
74   private static final String COLON = ":";
75
76   private static final String SLASH = "/";
77
78   /**
79    * {@inheritDoc}
80    * 
81    * @return
82    */
83   @Override
84   public int getModelStartNo()
85   {
86     return 1;
87   }
88
89   /**
90    * Returns a string representation of the given colour suitable for inclusion
91    * in Jmol commands
92    * 
93    * @param c
94    * @return
95    */
96   protected String getColourString(Color c)
97   {
98     return c == null ? null
99             : String.format("[%d,%d,%d]", c.getRed(), c.getGreen(),
100                     c.getBlue());
101   }
102
103   @Override
104   public StructureCommandI colourByChain()
105   {
106     return COLOUR_BY_CHAIN;
107   }
108
109   @Override
110   public List<StructureCommandI> colourByCharge()
111   {
112     return Arrays.asList(COLOUR_BY_CHARGE);
113   }
114
115   @Override
116   public List<StructureCommandI> colourByResidues(Map<String, Color> colours)
117   {
118     List<StructureCommandI> cmds = super.colourByResidues(colours);
119     cmds.add(0, COLOUR_ALL_WHITE);
120     return cmds;
121   }
122
123   @Override
124   public StructureCommandI setBackgroundColour(Color col)
125   {
126     return new StructureCommand("background " + getColourString(col));
127   }
128
129   @Override
130   public StructureCommandI focusView()
131   {
132     return FOCUS_VIEW;
133   }
134
135   @Override
136   public List<StructureCommandI> showChains(List<String> toShow)
137   {
138     StringBuilder atomSpec = new StringBuilder(128);
139     boolean first = true;
140     for (String chain : toShow)
141     {
142       String[] tokens = chain.split(":");
143       if (tokens.length == 2)
144       {
145         if (!first)
146         {
147           atomSpec.append(" or ");
148         }
149         first = false;
150         atomSpec.append(":").append(tokens[1]).append(" /").append(tokens[0]);
151       }
152     }
153
154     String spec = atomSpec.toString();
155     String command = "select *;restrict " + spec + ";cartoon;center "
156             + spec;
157     return Arrays.asList(new StructureCommand(command));
158   }
159
160   /**
161    * Returns a command to superpose atoms in {@code atomSpec} to those in
162    * {@code refAtoms}, restricted to alpha carbons only (Phosphorous for rna).
163    * For example
164    * 
165    * <pre>
166    * compare {2.1} {1.1} SUBSET {(*.CA | *.P) and conformation=1} 
167    *         ATOMS {1-87:A}{2-54:A|61-94:A} ROTATE TRANSLATE 1.0;
168    * </pre>
169    * 
170    * where {@code conformation=1} excludes ALTLOC atom locations, and 1.0 is the
171    * time in seconds to animate the action. For this example, atoms in model 2
172    * are moved towards atoms in model 1.
173    * <p>
174    * The two atomspecs should each be for one model only, but may have more than
175    * one chain. The number of atoms specified should be the same for both
176    * models, though if not, Jmol may make a 'best effort' at superposition.
177    * 
178    * @see https://chemapps.stolaf.edu/jmol/docs/#compare
179    */
180   @Override
181   public List<StructureCommandI> superposeStructures(AtomSpecModel refAtoms,
182           AtomSpecModel atomSpec, AtomSpecType backbone)
183   {
184     StringBuilder sb = new StringBuilder(64);
185     String refModel = refAtoms.getModels().iterator().next();
186     String model2 = atomSpec.getModels().iterator().next();
187     sb.append(String.format("compare {%s.1} {%s.1}", model2, refModel));
188     sb.append(" SUBSET {(*.CA | *.P) and conformation=1} ATOMS {");
189
190     /*
191      * command examples don't include modelspec with atoms, getAtomSpec does;
192      * it works, so leave it as it is for simplicity
193      */
194     sb.append(getAtomSpec(atomSpec, backbone)).append("}{");
195     sb.append(getAtomSpec(refAtoms, backbone)).append("}");
196     sb.append(" ROTATE TRANSLATE ");
197     sb.append(getCommandSeparator());
198
199     /*
200      * show residues used for superposition as ribbon
201      */
202     sb.append("select ").append(getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY)).append("|");
203     sb.append(getAtomSpec(refAtoms, AtomSpecType.RESIDUE_ONLY)).append(getCommandSeparator())
204             .append("cartoons");
205
206     return Arrays.asList(new StructureCommand(sb.toString()));
207   }
208
209   @Override
210   public StructureCommandI openCommandFile(String path)
211   {
212     /*
213      * https://chemapps.stolaf.edu/jmol/docs/#script
214      * not currently used in Jalview
215      */
216     return new StructureCommand("script " + path);
217   }
218
219   @Override
220   public StructureCommandI saveSession(String filepath)
221   {
222     /*
223      * https://chemapps.stolaf.edu/jmol/docs/#writemodel
224      */
225     return new StructureCommand("write STATE \"" + filepath + "\"");
226   }
227
228   @Override
229   protected StructureCommandI colourResidues(String atomSpec, Color colour)
230   {
231     StringBuilder sb = new StringBuilder(atomSpec.length()+20);
232     sb.append("select ").append(atomSpec).append(getCommandSeparator())
233             .append("color").append(getColourString(colour));
234     return new StructureCommand(sb.toString());
235   }
236
237   @Override
238   protected String getResidueSpec(String residue)
239   {
240     return residue;
241   }
242
243   /**
244    * Generates a Jmol atomspec string like
245    * 
246    * <pre>
247    * 2-5:A/1.1,8:A/1.1,5-10:B/2.1
248    * </pre>
249    * 
250    * Parameter {@code alphaOnly} is not used here - this restriction is made by
251    * a separate clause in the {@code compare} (superposition) command.
252    */
253   @Override
254   public String getAtomSpec(AtomSpecModel model, AtomSpecType specType)
255   {
256     StringBuilder sb = new StringBuilder(128);
257
258     boolean first = true;
259     for (String modelNo : model.getModels())
260     {
261       for (String chain : model.getChains(modelNo))
262       {
263         for (int[] range : model.getRanges(modelNo, chain))
264         {
265           if (!first)
266           {
267             sb.append(PIPE);
268           }
269           first = false;
270           if (range[0] == range[1])
271           {
272             sb.append(range[0]);
273           }
274           else
275           {
276             sb.append(range[0]).append(HYPHEN).append(range[1]);
277           }
278           sb.append(COLON).append(chain.trim()).append(SLASH);
279           sb.append(String.valueOf(modelNo)).append(".1");
280         }
281       }
282     }
283
284     return sb.toString();
285   }
286
287   @Override
288   public List<StructureCommandI> showBackbone()
289   {
290     return Arrays.asList(SHOW_BACKBONE);
291   }
292
293   @Override
294   public StructureCommandI loadFile(String file)
295   {
296     // https://chemapps.stolaf.edu/jmol/docs/#loadfiles
297     return new StructureCommand("load FILES \"" + 
298             Platform.escapeBackslashes(file) + "\"");
299   }
300
301   /**
302    * Obsolete method, only referenced from
303    * jalview.javascript.MouseOverStructureListener
304    * 
305    * @param ssm
306    * @param files
307    * @param sequence
308    * @param sr
309    * @param viewPanel
310    * @return
311    */
312   @Deprecated
313   public String[] colourBySequence(StructureSelectionManager ssm,
314           String[] files, SequenceI[][] sequence, SequenceRenderer sr,
315           AlignmentViewPanel viewPanel)
316   {
317     // TODO delete method
318
319     FeatureRenderer fr = viewPanel.getFeatureRenderer();
320     FeatureColourFinder finder = new FeatureColourFinder(fr);
321     AlignViewportI viewport = viewPanel.getAlignViewport();
322     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
323     AlignmentI al = viewport.getAlignment();
324     List<String> cset = new ArrayList<>();
325
326     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
327     {
328       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
329       StringBuilder command = new StringBuilder(128);
330       List<String> str = new ArrayList<>();
331
332       if (mapping == null || mapping.length < 1)
333       {
334         continue;
335       }
336
337       for (int s = 0; s < sequence[pdbfnum].length; s++)
338       {
339         for (int sp, m = 0; m < mapping.length; m++)
340         {
341           if (mapping[m].getSequence() == sequence[pdbfnum][s]
342                   && (sp = al.findIndex(sequence[pdbfnum][s])) > -1)
343           {
344             int lastPos = StructureMapping.UNASSIGNED_VALUE;
345             SequenceI asp = al.getSequenceAt(sp);
346             for (int r = 0; r < asp.getLength(); r++)
347             {
348               // no mapping to gaps in sequence
349               if (Comparison.isGap(asp.getCharAt(r)))
350               {
351                 continue;
352               }
353               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
354
355               if (pos == lastPos)
356               {
357                 continue;
358               }
359               if (pos == StructureMapping.UNASSIGNED_VALUE)
360               {
361                 // terminate current colour op
362                 if (command.length() > 0
363                         && command.charAt(command.length() - 1) != ';')
364                 {
365                   command.append(";");
366                 }
367                 // reset lastPos
368                 lastPos = StructureMapping.UNASSIGNED_VALUE;
369                 continue;
370               }
371
372               lastPos = pos;
373
374               Color col = sr.getResidueColour(sequence[pdbfnum][s], r,
375                       finder);
376
377               /*
378                * shade hidden regions darker
379                */
380               if (!cs.isVisible(r))
381               {
382                 col = Color.GRAY;
383               }
384
385               String newSelcom = (mapping[m].getChain() != " "
386                       ? ":" + mapping[m].getChain()
387                       : "") + "/" + (pdbfnum + 1) + ".1" + ";color"
388                       + getColourString(col);
389               if (command.length() > newSelcom.length() && command
390                       .substring(command.length() - newSelcom.length())
391                       .equals(newSelcom))
392               {
393                 command = JmolCommands.condenseCommand(command, pos);
394                 continue;
395               }
396               // TODO: deal with case when buffer is too large for Jmol to parse
397               // - execute command and flush
398
399               if (command.length() > 0
400                       && command.charAt(command.length() - 1) != ';')
401               {
402                 command.append(";");
403               }
404
405               if (command.length() > 51200)
406               {
407                 // add another chunk
408                 str.add(command.toString());
409                 command.setLength(0);
410               }
411               command.append("select " + pos);
412               command.append(newSelcom);
413             }
414             // break;
415           }
416         }
417       }
418       {
419         // add final chunk
420         str.add(command.toString());
421         command.setLength(0);
422       }
423       cset.addAll(str);
424
425     }
426     return cset.toArray(new String[cset.size()]);
427   }
428
429   /**
430    * Helper method
431    * 
432    * @param command
433    * @param pos
434    * @return
435    */
436   @Deprecated
437   private static StringBuilder condenseCommand(
438           StringBuilder command,
439           int pos)
440   {
441
442     // work back to last 'select'
443     int p = command.length(), q = p;
444     do
445     {
446       p -= 6;
447       if (p < 1)
448       {
449         p = 0;
450       }
451       ;
452     } while ((q = command.indexOf("select", p)) == -1 && p > 0);
453
454     StringBuilder sb = new StringBuilder(command.substring(0, q + 7));
455
456     command = command.delete(0, q + 7);
457
458     String start;
459
460     if (command.indexOf("-") > -1)
461     {
462       start = command.substring(0, command.indexOf("-"));
463     }
464     else
465     {
466       start = command.substring(0, command.indexOf(":"));
467     }
468
469     sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
470
471     return sb;
472   }
473
474   @Override
475   public StructureCommandI openSession(String filepath)
476   {
477     return loadFile(filepath);
478   }
479
480   @Override
481   public StructureCommandI closeViewer()
482   {
483     return null; // not an external viewer
484   }
485 }