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