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