ed64c006002f22a161bf2582ea46e6ae8af8dabf
[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     commands.add(new StructureCommand("pair_fit", 
118             atomSpec2AlphaOnly, refAtomsAlphaOnly));
119
120     /*
121      * and show superposed residues as cartoon
122      */
123     String refAtomsAll = getAtomSpec(refAtoms, AtomSpecType.RESIDUE_ONLY);
124     String atomSpec2All = getAtomSpec(atomSpec, AtomSpecType.RESIDUE_ONLY);
125     commands.add(new StructureCommand("show", "cartoon",
126             refAtomsAll + " " + atomSpec2All));
127
128     return commands;
129   }
130
131   @Override
132   public StructureCommandI openCommandFile(String path)
133   {
134     // https://pymolwiki.org/index.php/Run
135     return new StructureCommand("run", path); // should be .pml
136   }
137
138   @Override
139   public StructureCommandI saveSession(String filepath)
140   {
141     // https://pymolwiki.org/index.php/Save#EXAMPLES
142     return new StructureCommand("save", filepath); // should be .pse
143   }
144
145   /**
146    * Returns a selection string in PyMOL 'selection macro' format:
147    * 
148    * <pre>
149    * modelId// chain/residues/
150    * </pre>
151    * 
152    * If more than one chain, makes a selection expression for each, and they are
153    * separated by spaces.
154    * 
155    * @see https://pymolwiki.org/index.php/Selection_Macros
156    */
157   @Override
158   public String getAtomSpec(AtomSpecModel model, AtomSpecType specType)
159   {
160     StringBuilder sb = new StringBuilder(64);
161     boolean first = true;
162     for (String modelId : model.getModels())
163     {
164       for (String chain : model.getChains(modelId))
165       {
166         if (!first)
167         {
168           sb.append(" ");
169         }
170         first = false;
171         List<int[]> rangeList = model.getRanges(modelId, chain);
172         chain = chain.trim();
173         sb.append(modelId).append("//").append(chain).append("/");
174         boolean firstRange = true;
175         for (int[] range : rangeList)
176         {
177           if (!firstRange)
178           {
179             sb.append("+");
180           }
181           firstRange = false;
182           sb.append(String.valueOf(range[0]));
183           if (range[0] != range[1])
184           {
185             sb.append("-").append(String.valueOf(range[1]));
186           }
187         }
188         sb.append("/");
189         if (specType == AtomSpecType.ALPHA)
190         {
191           sb.append("CA");
192         }
193         if (specType == AtomSpecType.PHOSPHATE)
194         {
195           sb.append("P");
196         }
197       }
198     }
199     return sb.toString();
200   }
201
202   @Override
203   public List<StructureCommandI> showBackbone()
204   {
205     return SHOW_BACKBONE;
206   }
207
208   @Override
209   protected StructureCommandI colourResidues(String atomSpec, Color colour)
210   {
211     // https://pymolwiki.org/index.php/Color
212     return new StructureCommand("color", getColourString(colour), atomSpec);
213   }
214
215   @Override
216   protected String getResidueSpec(String residue)
217   {
218     // https://pymolwiki.org/index.php/Selection_Algebra
219     return "resn " + residue;
220   }
221
222   @Override
223   public StructureCommandI loadFile(String file)
224   {
225     return new StructureCommand("load", file);
226   }
227
228   /**
229    * Overrides the default implementation (which generates concatenated
230    * commands) to generate one per colour (because the XML-RPC interface to
231    * PyMOL only accepts one command at a time)
232    * 
233    * @param colourMap
234    * @return
235    */
236   @Override
237   public List<StructureCommandI> colourBySequence(
238           Map<Object, AtomSpecModel> colourMap)
239   {
240     List<StructureCommandI> commands = new ArrayList<>();
241     for (Object key : colourMap.keySet())
242     {
243       Color colour = (Color) key;
244       final AtomSpecModel colourData = colourMap.get(colour);
245       commands.add(getColourCommand(colourData, colour));
246     }
247
248     return commands;
249   }
250
251   /**
252    * Returns a viewer command to set the given atom property value on atoms
253    * specified by the AtomSpecModel, for example
254    * 
255    * <pre>
256    * iterate 4zho//B/12-34,48-55/CA,jv_chain='primary'
257    * </pre>
258    * 
259    * @param attributeName
260    * @param attributeValue
261    * @param atomSpecModel
262    * @return
263    */
264   protected StructureCommandI setAttribute(String attributeName,
265           String attributeValue, AtomSpecModel atomSpecModel)
266   {
267     StringBuilder sb = new StringBuilder(128);
268     sb.append("p.").append(attributeName).append("='")
269             .append(attributeValue).append("'");
270     String atomSpec = getAtomSpec(atomSpecModel, AtomSpecType.RESIDUE_ONLY);
271     return new StructureCommand("iterate", atomSpec, sb.toString());
272   }
273
274   /**
275    * Traverse the map of features/values/models/chains/positions to construct a
276    * list of 'set property' commands (one per distinct feature type and value).
277    * The values are stored in the 'p' dictionary of user-defined properties of
278    * each atom.
279    * <p>
280    * The format of each command is
281    * 
282    * <pre>
283    * <blockquote> iterate atomspec, p.featureName='value' 
284    * e.g. iterate 4zho//A/23,28-29/CA, p.jv_Metal='Fe'
285    * </blockquote>
286    * </pre>
287    * 
288    * @param featureMap
289    * @return
290    */
291   @Override
292   public List<StructureCommandI> setAttributes(
293           Map<String, Map<Object, AtomSpecModel>> featureMap)
294   {
295     List<StructureCommandI> commands = new ArrayList<>();
296     for (String featureType : featureMap.keySet())
297     {
298       String attributeName = makeAttributeName(featureType);
299
300       /*
301        * todo: clear down existing attributes for this feature?
302        */
303       // commands.add(new StructureCommand("iterate", "all",
304       // "p."+attributeName+"='None'"); //?
305
306       Map<Object, AtomSpecModel> values = featureMap.get(featureType);
307       for (Object value : values.keySet())
308       {
309         /*
310          * for each distinct value recorded for this feature type,
311          * add a command to set the attribute on the mapped residues
312          * Put values in single quotes, encoding any embedded single quotes
313          */
314         AtomSpecModel atomSpecModel = values.get(value);
315         String featureValue = value.toString();
316         featureValue = featureValue.replaceAll("\\'", "&#39;");
317         StructureCommandI cmd = setAttribute(attributeName, featureValue,
318                 atomSpecModel);
319         commands.add(cmd);
320       }
321     }
322
323     return commands;
324   }
325
326   @Override
327   public StructureCommandI openSession(String filepath)
328   {
329     // https://pymolwiki.org/index.php/Load
330     // this version of the command has no dependency on file extension
331     return new StructureCommand("load", filepath, "", "0", "pse");
332   }
333
334   @Override
335   public StructureCommandI closeViewer()
336   {
337     // https://pymolwiki.org/index.php/Quit
338     return CLOSE_PYMOL;
339   }
340
341 }