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