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