JAL-1759 updates for Jmol 14.2.14_25.06.11
[jalview.git] / src / jalview / ext / jmol / PDBFileWithJmol.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.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.AlignFile;
29 import jalview.io.FileParse;
30 import jalview.schemes.ResidueProperties;
31 import jalview.util.MessageManager;
32
33 import java.io.IOException;
34 import java.util.Hashtable;
35 import java.util.Map;
36
37 import javajs.awt.Dimension;
38
39 import org.jmol.api.JmolStatusListener;
40 import org.jmol.api.JmolViewer;
41 import org.jmol.c.CBK;
42 import org.jmol.modelset.Group;
43 import org.jmol.modelset.Model;
44 import org.jmol.modelset.ModelSet;
45 import org.jmol.modelsetbio.BioModel;
46 import org.jmol.modelsetbio.BioPolymer;
47 import org.jmol.viewer.Viewer;
48 import org.openscience.jmol.app.JmolApp;
49
50 /**
51  * Import and process PDB files with Jmol
52  * 
53  * @author jprocter
54  * 
55  */
56 public class PDBFileWithJmol extends AlignFile implements
57         JmolStatusListener
58 {
59
60   JmolApp jmolApp = null;
61
62   Viewer viewer = null;
63
64   public PDBFileWithJmol(String inFile, String type) throws IOException
65   {
66     super(inFile, type);
67   }
68
69   public PDBFileWithJmol(FileParse fp) throws IOException
70   {
71     super(fp);
72   }
73
74   public PDBFileWithJmol()
75   {
76     // TODO Auto-generated constructor stub
77   }
78
79   /**
80    * create a headless jmol instance for dataprocessing
81    * 
82    * @return
83    */
84   private Viewer getJmolData()
85   {
86     if (viewer == null)
87     { // note that -o -n -x are all implied // TODO check for Jmol 14.2
88       jmolApp = new JmolApp();
89       jmolApp.isDataOnly = true;
90       jmolApp.haveConsole = false;
91       jmolApp.haveDisplay = false;
92       try
93       {
94         viewer = (Viewer) JmolViewer.allocateViewer(null, null, null, null,
95                 null, "-x -o -n", this);
96         viewer.setScreenDimension(jmolApp.startupWidth,
97                 jmolApp.startupHeight);
98         jmolApp.startViewer(viewer, null, false);
99       } catch (ClassCastException x)
100       {
101         throw new Error(MessageManager.formatMessage("error.jmol_version_not_compatible_with_jalview_version", new String[]{JmolViewer.getJmolVersion()}),
102                 x);
103       }
104     }
105     return viewer;
106   }
107
108   private void waitForScript(Viewer jmd)
109   {
110     while (jmd.isScriptExecuting())
111     {
112       try
113       {
114         Thread.sleep(50);
115
116       } catch (InterruptedException x)
117       {
118       }
119     }
120   }
121
122   /*
123    * (non-Javadoc)
124    * 
125    * @see jalview.io.AlignFile#parse()
126    */
127   @Override
128   public void parse() throws IOException
129   {
130     Viewer jmd = getJmolData();
131     jmd.openReader(getDataName(), getDataName(), getReader());
132     waitForScript(jmd);
133
134     if (jmd.ms.mc > 0)
135     {
136       ModelSet ms = jmd.ms;
137       // Jmol 14.2 added third argument doReport = false
138       ms.calculateStructures(null, true, false, false, true);
139       // System.out.println("Structs\n"+structs);
140       Group group = null;
141       int modelIndex = -1;
142       for (Model model : ms.am)
143       {
144         modelIndex++;
145         for (BioPolymer bp : ((BioModel) model).bioPolymers)
146         {
147           int _lastChainId = 0;
148           int[] groups = bp.getLeadAtomIndices();
149           char seq[] = new char[groups.length], secstr[] = new char[groups.length], secstrcode[] = new char[groups.length];
150           int groupc = 0, len = 0, firstrnum = 1, lastrnum = 0;
151
152           do
153           {
154             if (groupc >= groups.length
155                     || ms.at[groups[groupc]].group.chain.chainID != _lastChainId)
156             {
157               /*
158                * on change of chain (or at end), construct the sequence and
159                * secondary structure annotation for the last chain
160                */
161               if (len > 0)
162               {
163                 boolean isNa = bp.isNucleic();
164                 // normalise sequence from Jmol to jalview
165                 int[] cinds = isNa ? ResidueProperties.nucleotideIndex
166                         : ResidueProperties.aaIndex;
167                 int nonGap = isNa ? ResidueProperties.maxNucleotideIndex
168                         : ResidueProperties.maxProteinIndex;
169                 char ngc = 'X';
170                 char newseq[] = new char[len];
171                 Annotation asecstr[] = new Annotation[len + firstrnum - 1];
172                 for (int p = 0; p < len; p++)
173                 {
174                   newseq[p] = cinds[seq[p]] == nonGap ? ngc : seq[p];
175                   if (secstr[p] >= 'A' && secstr[p] <= 'z')
176                   {
177                     asecstr[p] = new Annotation("" + secstr[p], null,
178                             secstrcode[p], Float.NaN);
179                   }
180                 }
181                 String modelTitle = (String) ms
182                         .getInfo(modelIndex, "title");
183                 SequenceI sq = new Sequence("" + getDataName() + "|"
184                         + modelTitle + "|" + _lastChainId, newseq,
185                         firstrnum, lastrnum);
186                 PDBEntry pdbe = new PDBEntry();
187                 pdbe.setFile(getDataName());
188                 pdbe.setId(getDataName());
189                 pdbe.setProperty(new Hashtable());
190                 // pdbe.getProperty().put("CHAIN", "" + _lastChainId);
191                 pdbe.setChainCode(String.valueOf(_lastChainId));
192                 sq.addPDBId(pdbe);
193                 // JAL-1533
194                 // Need to put the number of models for this polymer somewhere
195                 // for Chimera/others to grab
196                 // pdbe.getProperty().put("PDBMODELS", biopoly.)
197                 seqs.add(sq);
198                 if (!isNa)
199                 {
200                   String mt = modelTitle == null ? getDataName()
201                           : modelTitle;
202                   if (_lastChainId >= ' ')
203                   {
204                     mt += _lastChainId;
205                   }
206                   AlignmentAnnotation ann = new AlignmentAnnotation(
207                           "Secondary Structure", "Secondary Structure for "
208                                   + mt, asecstr);
209                   ann.belowAlignment = true;
210                   ann.visible = true;
211                   ann.autoCalculated = false;
212                   ann.setCalcId(getClass().getName());
213                   sq.addAlignmentAnnotation(ann);
214                   ann.adjustForAlignment();
215                   ann.validateRangeAndDisplay();
216                   annotations.add(ann);
217                 }
218               }
219               len = 0;
220               firstrnum = 1;
221               lastrnum = 0;
222             }
223             if (groupc < groups.length)
224             {
225               group = ms.at[groups[groupc]].group;
226               if (len == 0)
227               {
228                 firstrnum = group.getResno();
229                 _lastChainId = group.chain.chainID;
230               }
231               else
232               {
233                 lastrnum = group.getResno();
234               }
235               seq[len] = group.getGroup1();
236               switch (group.getProteinStructureSubType())
237               {
238               case HELIX310:
239                 if (secstr[len] == 0)
240                 {
241                   secstr[len] = '3';
242                 }
243               case HELIXALPHA:
244                 if (secstr[len] == 0)
245                 {
246                   secstr[len] = 'H';
247                 }
248               case HELIXPI:
249                 if (secstr[len] == 0)
250                 {
251                   secstr[len] = 'P';
252                 }
253               case HELIX:
254                 if (secstr[len] == 0)
255                 {
256                   secstr[len] = 'H';
257                 }
258                 secstrcode[len] = 'H';
259                 break;
260               case SHEET:
261                 secstr[len] = 'E';
262                 secstrcode[len] = 'E';
263                 break;
264               default:
265                 secstr[len] = 0;
266                 secstrcode[len] = 0;
267               }
268               len++;
269             }
270           } while (groupc++ < groups.length);
271         }
272       }
273
274       /*
275        * lastScriptTermination = -9465; String dsspOut =
276        * jmd.evalString("calculate STRUCTURE"); if (dsspOut.equals("pending")) {
277        * while (lastScriptTermination == -9465) { try { Thread.sleep(50); }
278        * catch (Exception x) { } ; } } System.out.println(lastConsoleEcho);
279        */
280     }
281   }
282
283   /*
284    * (non-Javadoc)
285    * 
286    * @see jalview.io.AlignFile#print()
287    */
288   @Override
289   public String print()
290   {
291     // TODO Auto-generated method stub
292     return null;
293   }
294
295   @Override
296   public void setCallbackFunction(String callbackType,
297           String callbackFunction)
298   {
299     // TODO Auto-generated method stub
300
301   }
302
303   /*
304    * @Override public void notifyCallback(EnumCallback type, Object[] data) {
305    * try { switch (type) { case ERROR: case SCRIPT:
306    * notifyScriptTermination((String) data[2], ((Integer) data[3]).intValue());
307    * break; case MESSAGE: sendConsoleMessage((data == null) ? ((String) null) :
308    * (String) data[1]); break; case LOADSTRUCT: notifyFileLoaded((String)
309    * data[1], (String) data[2], (String) data[3], (String) data[4], ((Integer)
310    * data[5]).intValue());
311    * 
312    * break; default: // System.err.println("Unhandled callback " + type + " " //
313    * + data[1].toString()); break; } } catch (Exception e) {
314    * System.err.println("Squashed Jmol callback handler error:");
315    * e.printStackTrace(); } }
316    */
317   public void notifyCallback(CBK type, Object[] data)
318   {
319     String strInfo = (data == null || data[1] == null ? null : data[1]
320             .toString());
321     switch (type)
322     {
323     case ECHO:
324       sendConsoleEcho(strInfo);
325       break;
326     case SCRIPT:
327       notifyScriptTermination((String) data[2],
328               ((Integer) data[3]).intValue());
329       break;
330     case MEASURE:
331       String mystatus = (String) data[3];
332       if (mystatus.indexOf("Picked") >= 0
333               || mystatus.indexOf("Sequence") >= 0)
334       {
335         // Picking mode
336         sendConsoleMessage(strInfo);
337       }
338       else if (mystatus.indexOf("Completed") >= 0)
339       {
340         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
341                 strInfo.length() - 1));
342       }
343       break;
344     case MESSAGE:
345       sendConsoleMessage(data == null ? null : strInfo);
346       break;
347     case PICK:
348       sendConsoleMessage(strInfo);
349       break;
350     default:
351       break;
352     }
353   }
354
355   String lastConsoleEcho = "";
356
357   private void sendConsoleEcho(String string)
358   {
359     lastConsoleEcho += string;
360     lastConsoleEcho += "\n";
361   }
362
363   String lastConsoleMessage = "";
364
365   private void sendConsoleMessage(String string)
366   {
367     lastConsoleMessage += string;
368     lastConsoleMessage += "\n";
369   }
370
371   int lastScriptTermination = -1;
372
373   String lastScriptMessage = "";
374
375   private void notifyScriptTermination(String string, int intValue)
376   {
377     lastScriptMessage += string;
378     lastScriptMessage += "\n";
379     lastScriptTermination = intValue;
380   }
381
382   @Override
383   public boolean notifyEnabled(CBK callbackPick)
384   {
385     switch (callbackPick)
386     {
387     case MESSAGE:
388     case SCRIPT:
389     case ECHO:
390     case LOADSTRUCT:
391     case ERROR:
392       return true;
393     default:
394       return false;
395     }
396   }
397
398   @Override
399   public String eval(String strEval)
400   {
401     // TODO Auto-generated method stub
402     return null;
403   }
404
405   @Override
406   public float[][] functionXY(String functionName, int x, int y)
407   {
408     // TODO Auto-generated method stub
409     return null;
410   }
411
412   @Override
413   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
414   {
415     // TODO Auto-generated method stub
416     return null;
417   }
418
419   @Override
420   public String createImage(String fileName, String type,
421           Object text_or_bytes, int quality)
422   {
423     // TODO Auto-generated method stub
424     return null;
425   }
426
427   @Override
428   public Map<String, Object> getRegistryInfo()
429   {
430     // TODO Auto-generated method stub
431     return null;
432   }
433
434   @Override
435   public void showUrl(String url)
436   {
437     // TODO Auto-generated method stub
438
439   }
440
441   @Override
442   public Dimension resizeInnerPanel(String data)
443   {
444     return null;
445   }
446
447   @Override
448   public Map<String, Object> getJSpecViewProperty(String arg0)
449   {
450     return null;
451   }
452
453 }