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