JAL-3390 StructureCommands atomspec helper, corrected Jmol atomspec/test
[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.ext.rbvi.chimera.AtomSpecModel;
31 import jalview.ext.rbvi.chimera.StructureCommands;
32 import jalview.renderer.seqfeatures.FeatureColourFinder;
33 import jalview.structure.StructureMapping;
34 import jalview.structure.StructureMappingcommandSet;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.structures.models.AAStructureBindingModel;
37
38 import java.awt.Color;
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.Map;
42
43 /**
44  * Routines for generating Jmol commands for Jalview/Jmol binding
45  * 
46  * @author JimP
47  * 
48  */
49 public class JmolCommands extends StructureCommands
50 {
51   private static final String COMMA = ",";
52
53   /**
54    * Jmol utility which constructs the commands to colour chains by the given
55    * alignment
56    * 
57    * @returns Object[] { Object[] { <model being coloured>,
58    * 
59    */
60   public static StructureMappingcommandSet[] getColourBySequenceCommand(
61           StructureSelectionManager ssm, String[] files,
62           AAStructureBindingModel binding, AlignmentViewPanel viewPanel)
63   {
64     SequenceRenderer sr = binding.getSequenceRenderer(viewPanel);
65     SequenceI[][] sequence = binding.getSequence();
66     return getColourBySequenceCommand(ssm, files, sequence, sr, viewPanel);
67   }
68
69   public static StructureMappingcommandSet[] getColourBySequenceCommand(
70           StructureSelectionManager ssm, String[] files,
71           SequenceI[][] sequence, SequenceRenderer sr,
72           AlignmentViewPanel viewPanel)
73   {
74     FeatureRenderer fr = viewPanel.getFeatureRenderer();
75     FeatureColourFinder finder = new FeatureColourFinder(fr);
76     AlignViewportI viewport = viewPanel.getAlignViewport();
77     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
78     AlignmentI al = viewport.getAlignment();
79     List<StructureMappingcommandSet> cset = new ArrayList<>();
80
81     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
82     {
83       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
84       StringBuffer command = new StringBuffer();
85       StructureMappingcommandSet smc;
86       ArrayList<String> str = new ArrayList<>();
87
88       if (mapping == null || mapping.length < 1)
89       {
90         continue;
91       }
92
93       for (int s = 0; s < sequence[pdbfnum].length; s++)
94       {
95         for (int sp, m = 0; m < mapping.length; m++)
96         {
97           if (mapping[m].getSequence() == sequence[pdbfnum][s]
98                   && (sp = al.findIndex(sequence[pdbfnum][s])) > -1)
99           {
100             int lastPos = StructureMapping.UNASSIGNED_VALUE;
101             SequenceI asp = al.getSequenceAt(sp);
102             for (int r = 0; r < asp.getLength(); r++)
103             {
104               // no mapping to gaps in sequence
105               if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
106               {
107                 continue;
108               }
109               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
110
111               if (pos == lastPos)
112               {
113                 continue;
114               }
115               if (pos == StructureMapping.UNASSIGNED_VALUE)
116               {
117                 // terminate current colour op
118                 if (command.length() > 0
119                         && command.charAt(command.length() - 1) != ';')
120                 {
121                   command.append(";");
122                 }
123                 // reset lastPos
124                 lastPos = StructureMapping.UNASSIGNED_VALUE;
125                 continue;
126               }
127
128               lastPos = pos;
129
130               Color col = sr.getResidueColour(sequence[pdbfnum][s], r,
131                       finder);
132
133               /*
134                * shade hidden regions darker
135                */
136               if (!cs.isVisible(r))
137               {
138                 col = Color.GRAY;
139               }
140
141               String newSelcom = (mapping[m].getChain() != " "
142                       ? ":" + mapping[m].getChain()
143                       : "") + "/" + (pdbfnum + 1) + ".1" + ";color["
144                       + col.getRed() + COMMA + col.getGreen() + COMMA
145                       + col.getBlue() + "]";
146               if (command.length() > newSelcom.length() && command
147                       .substring(command.length() - newSelcom.length())
148                       .equals(newSelcom))
149               {
150                 command = JmolCommands.condenseCommand(command, pos);
151                 continue;
152               }
153               // TODO: deal with case when buffer is too large for Jmol to parse
154               // - execute command and flush
155
156               if (command.length() > 0
157                       && command.charAt(command.length() - 1) != ';')
158               {
159                 command.append(";");
160               }
161
162               if (command.length() > 51200)
163               {
164                 // add another chunk
165                 str.add(command.toString());
166                 command.setLength(0);
167               }
168               command.append("select " + pos);
169               command.append(newSelcom);
170             }
171             // break;
172           }
173         }
174       }
175       {
176         // add final chunk
177         str.add(command.toString());
178         command.setLength(0);
179       }
180       // Finally, add the command set ready to be returned.
181       cset.add(new StructureMappingcommandSet(JmolCommands.class,
182               files[pdbfnum], str.toArray(new String[str.size()])));
183
184     }
185     return cset.toArray(new StructureMappingcommandSet[cset.size()]);
186   }
187
188   public static StringBuffer condenseCommand(StringBuffer command, int pos)
189   {
190
191     // work back to last 'select'
192     int p = command.length(), q = p;
193     do
194     {
195       p -= 6;
196       if (p < 1)
197       {
198         p = 0;
199       }
200       ;
201     } while ((q = command.indexOf("select", p)) == -1 && p > 0);
202
203     StringBuffer sb = new StringBuffer(command.substring(0, q + 7));
204
205     command = command.delete(0, q + 7);
206
207     String start;
208
209     if (command.indexOf("-") > -1)
210     {
211       start = command.substring(0, command.indexOf("-"));
212     }
213     else
214     {
215       start = command.substring(0, command.indexOf(":"));
216     }
217
218     sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
219
220     return sb;
221   }
222
223   /**
224    * Answers a Jmol 'color' command to colour residues as described by the given
225    * map of {@code <Color, AtomSpecModel>}
226    * 
227    * @param map
228    * @return
229    */
230   public static String[] getColourBySequenceCommand(
231           Map<Object, AtomSpecModel> map)
232   {
233     String[] cmds = new String[map.keySet().size()];
234
235     int i = 0;
236     for (Object o : map.keySet())
237     {
238       StringBuilder cmd = new StringBuilder(128);
239       Color c = (Color) o;
240       String atomSpec = getAtomSpec(map.get(o));
241       cmd.append("select ").append(atomSpec).append(";color[")
242               .append(c.getRed()).append(COMMA).append(c.getGreen())
243               .append(COMMA).append(c.getBlue()).append("];");
244       cmds[i] = cmd.toString();
245       i++;
246     }
247
248     return cmds;
249   }
250
251   /**
252    * Builds a Jmol syntax selection expression from the given model, for example
253    * 
254    * <pre>
255    * 61-64,70:A/1.1,12-25,41-44:B/1.1,12:A/2.1
256    * for model 1, chain A, residues 61-64 and 70, chain B residues 12-25 and 41-44, model 2 chain A residue 12
257    * </pre>
258    * 
259    * @param atomSpecModel
260    * @return
261    */
262   public static String getAtomSpec(AtomSpecModel atomSpecModel)
263   {
264     StringBuilder sb = new StringBuilder(64);
265     for (int model : atomSpecModel.getModels())
266     {
267       for (String chain : atomSpecModel.getChains(model))
268       {
269         if (sb.length() > 0)
270         {
271           sb.append(COMMA);
272         }
273         boolean firstRange = true;
274
275         List<int[]> rangeList = atomSpecModel.getRanges(model, chain);
276
277         if (rangeList.size() > 1)
278         {
279           sb.append("(");
280         }
281         appendResidueRange(sb, rangeList, null, firstRange);
282         if (rangeList.size() > 1)
283         {
284           sb.append(")&");
285         }
286         sb.append(":").append(chain.trim()).append("/")
287                 .append(String.valueOf(model + 1))
288                 .append(".1");
289       }
290     }
291
292     return sb.toString();
293   }
294
295 }