JAL-3551 - wrap pair_fit with undo_disable and undo_enable
[jalview.git] / src / jalview / ext / pymol / PymolCommands.java
1 package jalview.ext.pymol;
2
3 import java.awt.Color;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.List;
7 import java.util.Map;
8
9 import jalview.structure.AtomSpecModel;
10 import jalview.structure.StructureCommand;
11 import jalview.structure.StructureCommandI;
12 import jalview.structure.StructureCommandsBase;
13
14 /**
15  * A class that generates commands to send to PyMol over its XML-RPC interface.
16  * <p>
17  * Note that because the xml-rpc interface can only accept one command at a
18  * time, we can't concatenate commands, and must instead form and send them
19  * individually.
20  * 
21  * @see https://pymolwiki.org/index.php/Category:Commands
22  * @see https://pymolwiki.org/index.php/RPC
23  */
24 public class PymolCommands extends StructureCommandsBase
25 {
26   // https://pymol.org/dokuwiki/doku.php?id=command:zoom
27   // not currently documented on
28   // https://pymolwiki.org/index.php/Category:Commands
29   private static final StructureCommand FOCUS_VIEW = new StructureCommand(
30           "zoom");
31
32   // https://pymolwiki.org/index.php/Quit
33   private static final StructureCommand CLOSE_PYMOL = new StructureCommand(
34           "quit");
35
36   // not currently documented on
37   // https://pymolwiki.org/index.php/Category:Commands
38   private static final StructureCommand COLOUR_BY_CHAIN = new StructureCommand(
39           "spectrum", "chain");
40
41   private static final List<StructureCommandI> COLOR_BY_CHARGE = Arrays
42           .asList(new StructureCommand("color", "white", "*"),
43                   new StructureCommand("color", "red", "resn ASP resn GLU"),
44                   new StructureCommand("color", "blue",
45                           "resn LYS resn ARG"),
46                   new StructureCommand("color", "yellow", "resn CYS"));
47
48   private static final List<StructureCommandI> SHOW_BACKBONE = Arrays
49           .asList(new StructureCommand("hide", "everything"),
50                   new StructureCommand("show", "ribbon"));
51
52   @Override
53   public StructureCommandI colourByChain()
54   {
55     return COLOUR_BY_CHAIN;
56   }
57
58   @Override
59   public List<StructureCommandI> colourByCharge()
60   {
61     return COLOR_BY_CHARGE;
62   }
63
64   @Override
65   public StructureCommandI setBackgroundColour(Color col)
66   {
67     // https://pymolwiki.org/index.php/Bg_Color
68     return new StructureCommand("bg_color", getColourString(col));
69   }
70
71   /**
72    * Returns a colour formatted suitable for use in viewer command syntax. For
73    * example, red is {@code "0xff0000"}.
74    * 
75    * @param c
76    * @return
77    */
78   protected String getColourString(Color c)
79   {
80     return String.format("0x%02x%02x%02x", c.getRed(), c.getGreen(),
81             c.getBlue());
82   }
83
84   @Override
85   public StructureCommandI focusView()
86   {
87     return FOCUS_VIEW;
88   }
89
90   @Override
91   public List<StructureCommandI> showChains(List<String> toShow)
92   {
93     // https://pymolwiki.org/index.php/Show
94     List<StructureCommandI> commands = new ArrayList<>();
95     commands.add(new StructureCommand("hide", "everything"));
96     commands.add(new StructureCommand("show", "lines"));
97     StringBuilder chains = new StringBuilder();
98     for (String chain : toShow)
99     {
100       chains.append(" chain ").append(chain);
101     }
102     commands.add(
103             new StructureCommand("show", "cartoon", chains.toString()));
104     return commands;
105   }
106
107   @Override
108   public List<StructureCommandI> superposeStructures(AtomSpecModel refAtoms,
109           AtomSpecModel atomSpec, AtomSpecType specType)
110   {
111              
112     // https://pymolwiki.org/index.php/Super
113     List<StructureCommandI> commands = new ArrayList<>();
114     String refAtomsAlphaOnly = "("+getAtomSpec(refAtoms, specType)+" and (altloc '' or altloc 'a'))";
115     String atomSpec2AlphaOnly = "("+getAtomSpec(atomSpec, specType)+" and (altloc '' or altloc 'a'))";
116     // pair_fit mobile -> reference
117     // crashes when undo is enabled on 2.5.2 (incentive)
118     commands.add(new StructureCommand("undo_disable"));
119     commands.add(new StructureCommand("pair_fit", 
120             atomSpec2AlphaOnly, refAtomsAlphaOnly));
121     commands.add(new StructureCommand("undo_enable"));
122     
123     /*
124      * and show superposed residues as cartoon
125      */
126     String refAtomsAll = getAtomSpec(refAtoms, AtomSpecType.RESIDUE_ONLY);
127     String atomSpec2All = getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY);
128     commands.add(new StructureCommand("show", "cartoon",
129             refAtomsAll + " " + atomSpec2All));
130
131     return commands;
132   }
133
134   @Override
135   public StructureCommandI openCommandFile(String path)
136   {
137     // https://pymolwiki.org/index.php/Run
138     return new StructureCommand("run", path); // should be .pml
139   }
140
141   @Override
142   public StructureCommandI saveSession(String filepath)
143   {
144     // https://pymolwiki.org/index.php/Save#EXAMPLES
145     return new StructureCommand("save", filepath); // should be .pse
146   }
147
148   /**
149    * Returns a selection string in PyMOL 'selection macro' format:
150    * 
151    * <pre>
152    * modelId// chain/residues/
153    * </pre>
154    * 
155    * If more than one chain, makes a selection expression for each, and they are
156    * separated by spaces.
157    * 
158    * @see https://pymolwiki.org/index.php/Selection_Macros
159    */
160   @Override
161   public String getAtomSpec(AtomSpecModel model, AtomSpecType specType)
162   {
163     StringBuilder sb = new StringBuilder(64);
164     boolean first = true;
165     for (String modelId : model.getModels())
166     {
167       for (String chain : model.getChains(modelId))
168       {
169         if (!first)
170         {
171           sb.append(" ");
172         }
173         first = false;
174         List<int[]> rangeList = model.getRanges(modelId, chain);
175         chain = chain.trim();
176         sb.append(modelId).append("//").append(chain).append("/");
177         boolean firstRange = true;
178         for (int[] range : rangeList)
179         {
180           if (!firstRange)
181           {
182             sb.append("+");
183           }
184           firstRange = false;
185           sb.append(String.valueOf(range[0]));
186           if (range[0] != range[1])
187           {
188             sb.append("-").append(String.valueOf(range[1]));
189           }
190         }
191         sb.append("/");
192         if (specType == AtomSpecType.ALPHA)
193         {
194           sb.append("CA");
195         }
196         if (specType == AtomSpecType.PHOSPHATE)
197         {
198           sb.append("P");
199         }
200       }
201     }
202     return sb.toString();
203   }
204
205   @Override
206   public List<StructureCommandI> showBackbone()
207   {
208     return SHOW_BACKBONE;
209   }
210
211   @Override
212   protected StructureCommandI colourResidues(String atomSpec, Color colour)
213   {
214     // https://pymolwiki.org/index.php/Color
215     return new StructureCommand("color", getColourString(colour), atomSpec);
216   }
217
218   @Override
219   protected String getResidueSpec(String residue)
220   {
221     // https://pymolwiki.org/index.php/Selection_Algebra
222     return "resn " + residue;
223   }
224
225   @Override
226   public StructureCommandI loadFile(String file)
227   {
228     return new StructureCommand("load", file);
229   }
230
231   /**
232    * Overrides the default implementation (which generates concatenated
233    * commands) to generate one per colour (because the XML-RPC interface to
234    * PyMOL only accepts one command at a time)
235    * 
236    * @param colourMap
237    * @return
238    */
239   @Override
240   public List<StructureCommandI> colourBySequence(
241           Map<Object, AtomSpecModel> colourMap)
242   {
243     List<StructureCommandI> commands = new ArrayList<>();
244     for (Object key : colourMap.keySet())
245     {
246       Color colour = (Color) key;
247       final AtomSpecModel colourData = colourMap.get(colour);
248       commands.add(getColourCommand(colourData, colour));
249     }
250
251     return commands;
252   }
253
254   /**
255    * Returns a viewer command to set the given atom property value on atoms
256    * specified by the AtomSpecModel, for example
257    * 
258    * <pre>
259    * iterate 4zho//B/12-34,48-55/CA,jv_chain='primary'
260    * </pre>
261    * 
262    * @param attributeName
263    * @param attributeValue
264    * @param atomSpecModel
265    * @return
266    */
267   protected StructureCommandI setAttribute(String attributeName,
268           String attributeValue, AtomSpecModel atomSpecModel)
269   {
270     StringBuilder sb = new StringBuilder(128);
271     sb.append("p.").append(attributeName).append("='")
272             .append(attributeValue).append("'");
273     String atomSpec = getAtomSpec(atomSpecModel, AtomSpecType.RESIDUE_ONLY);
274     return new StructureCommand("iterate", atomSpec, sb.toString());
275   }
276
277   /**
278    * Traverse the map of features/values/models/chains/positions to construct a
279    * list of 'set property' commands (one per distinct feature type and value).
280    * The values are stored in the 'p' dictionary of user-defined properties of
281    * each atom.
282    * <p>
283    * The format of each command is
284    * 
285    * <pre>
286    * <blockquote> iterate atomspec, p.featureName='value' 
287    * e.g. iterate 4zho//A/23,28-29/CA, p.jv_Metal='Fe'
288    * </blockquote>
289    * </pre>
290    * 
291    * @param featureMap
292    * @return
293    */
294   @Override
295   public List<StructureCommandI> setAttributes(
296           Map<String, Map<Object, AtomSpecModel>> featureMap)
297   {
298     List<StructureCommandI> commands = new ArrayList<>();
299     for (String featureType : featureMap.keySet())
300     {
301       String attributeName = makeAttributeName(featureType);
302
303       /*
304        * todo: clear down existing attributes for this feature?
305        */
306       // commands.add(new StructureCommand("iterate", "all",
307       // "p."+attributeName+"='None'"); //?
308
309       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
310       for (Object value : values.keySet())
311       {
312         /*
313          * for each distinct value recorded for this feature type,
314          * add a command to set the attribute on the mapped residues
315          * Put values in single quotes, encoding any embedded single quotes
316          */
317         AtomSpecModel atomSpecModel = values.get(value);
318         String featureValue = value.toString();
319         featureValue = featureValue.replaceAll("\\'", "&#39;");
320         StructureCommandI cmd = setAttribute(attributeName, featureValue,
321                 atomSpecModel);
322         commands.add(cmd);
323       }
324     }
325
326     return commands;
327   }
328
329   @Override
330   public StructureCommandI openSession(String filepath)
331   {
332     // https://pymolwiki.org/index.php/Load
333     // this version of the command has no dependency on file extension
334     return new StructureCommand("load", filepath, "", "0", "pse");
335   }
336
337   @Override
338   public StructureCommandI closeViewer()
339   {
340     // https://pymolwiki.org/index.php/Quit
341     return CLOSE_PYMOL;
342   }
343
344 }