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