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