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