JAL-674 futzing with bugs
[jalview.git] / src / jalview / ext / jmol / PDBFileWithJmol.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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 java.io.IOException;
24 import java.util.Hashtable;
25 import java.util.Map;
26
27 import org.jmol.api.JmolStatusListener;
28 import org.jmol.api.JmolViewer;
29 import org.jmol.constant.EnumCallback;
30 import org.jmol.modelset.Group;
31 import org.jmol.modelset.Model;
32 import org.jmol.modelset.ModelSet;
33 import org.jmol.modelset.Polymer;
34 import org.jmol.modelsetbio.BioPolymer;
35 import org.jmol.viewer.Viewer;
36 import org.openscience.jmol.app.JmolApp;
37
38 import jalview.datamodel.AlignmentAnnotation;
39 import jalview.datamodel.Annotation;
40 import jalview.datamodel.PDBEntry;
41 import jalview.datamodel.Sequence;
42 import jalview.datamodel.SequenceI;
43 import jalview.io.AlignFile;
44 import jalview.io.FileParse;
45
46 /**
47  * Import and process PDB files with Jmol
48  * 
49  * @author jprocter
50  * 
51  */
52 public class PDBFileWithJmol extends AlignFile implements
53         JmolStatusListener
54 {
55
56   JmolApp jmolApp = null;
57
58   Viewer viewer = null;
59
60   public PDBFileWithJmol(String inFile, String type) throws IOException
61   {
62     super(inFile, type);
63   }
64
65   public PDBFileWithJmol(FileParse fp) throws IOException
66   {
67     super(fp);
68   }
69
70   public PDBFileWithJmol()
71   {
72     // TODO Auto-generated constructor stub
73   }
74
75   /**
76    * create a headless jmol instance for dataprocessing
77    * 
78    * @return
79    */
80   private Viewer getJmolData()
81   {
82     if (viewer == null)
83     { // note that -o -n -x are all implied
84       jmolApp = new JmolApp();
85       jmolApp.isDataOnly = true;
86       jmolApp.haveConsole = false;
87       jmolApp.haveDisplay = false;
88       jmolApp.exitUponCompletion = true;
89       try
90       {
91         viewer = (Viewer) JmolViewer.allocateViewer(null, null, null, null,
92                 null, jmolApp.commandOptions, this);
93         viewer.setScreenDimension(jmolApp.startupWidth,
94                 jmolApp.startupHeight);
95         jmolApp.startViewer(viewer, null);
96       } catch (ClassCastException x)
97       {
98         throw new Error(
99                 "Jmol version "
100                         + JmolViewer.getJmolVersion()
101                         + " is not compatible with this version of Jalview. Report this problem at issues.jalview.org",
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     if (jmd.getModelCount() > 0)
134     {
135       ModelSet ms = jmd.getModelSet();
136       String structs = ms.calculateStructures(null, true, false, true);
137       // System.out.println("Structs\n"+structs);
138       for (Model model : ms.getModels())
139       {
140         for (int _bp = 0, _bpc = model.getBioPolymerCount(); _bp < _bpc; _bp++)
141         {
142           Polymer bp = model.getBioPolymer(_bp);
143           if (bp instanceof BioPolymer)
144           {
145             BioPolymer biopoly = (BioPolymer) bp;
146             char _lastChainId = 0;
147             int[] groups = biopoly.getLeadAtomIndices();
148             Group[] bpgrp = biopoly.getGroups();
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             do
152             {
153               if (groupc >= groups.length
154                       || ms.atoms[groups[groupc]].getChainID() != _lastChainId)
155               {
156                 if (len > 0)
157                 {
158                   char newseq[] = new char[len];
159                   System.arraycopy(seq, 0, newseq, 0, len);
160                   Annotation asecstr[] = new Annotation[len+firstrnum-1];
161                   for (int p = 0; p < len; p++)
162                   {
163                     if (secstr[p] >= 'A' && secstr[p] <= 'z')
164                     {
165                       asecstr[p] = new Annotation("" + secstr[p], null,
166                               secstrcode[p], Float.NaN);
167                     }
168                   }
169                   SequenceI sq = new Sequence("" + getDataName() + "|"
170                           + model.getModelTitle() + "|" + _lastChainId,
171                           newseq, firstrnum, lastrnum);
172                   PDBEntry pdbe = new PDBEntry();
173                   pdbe.setFile(getDataName());
174                   pdbe.setId(getDataName());
175                   sq.addPDBId(pdbe);
176                   pdbe.setProperty(new Hashtable());
177                   pdbe.getProperty().put("CHAIN", "" + _lastChainId);
178                   seqs.add(sq);
179                   if (!(biopoly.isDna() || biopoly.isRna()))
180                   {
181                     AlignmentAnnotation ann = new AlignmentAnnotation(
182                             "Secondary Structure",
183                             "Secondary Structure from PDB File", asecstr);
184                     ann.belowAlignment=true;
185                     ann.visible=true;
186                     ann.autoCalculated=false;
187                     ann.setCalcId(getClass().getName());
188                     sq.addAlignmentAnnotation(ann);
189                     ann.adjustForAlignment();
190                     ann.validateRangeAndDisplay();
191                     annotations.add(ann);
192                   }
193                 }
194                 len = 0;
195                 firstrnum = 1;
196                 lastrnum = 0;
197               }
198               if (groupc < groups.length)
199               {
200                 if (len == 0)
201                 {
202                   firstrnum = bpgrp[groupc].getResno();
203                   _lastChainId = bpgrp[groupc].getChainID();
204                 }
205                 else
206                 {
207                   lastrnum = bpgrp[groupc].getResno();
208                 }
209                 seq[len] = bpgrp[groupc].getGroup1();
210                 switch (bpgrp[groupc].getProteinStructureSubType())
211                 {
212                 case HELIX_310:
213                   if (secstr[len] == 0)
214                   {
215                     secstr[len] = '3';
216                   }
217                 case HELIX_ALPHA:
218                   if (secstr[len] == 0)
219                   {
220                     secstr[len] = 'H';
221                   }
222                 case HELIX_PI:
223                   if (secstr[len] == 0)
224                   {
225                     secstr[len] = 'P';
226                   }
227                 case HELIX:
228                   if (secstr[len] == 0)
229                   {
230                     secstr[len] = 'H';
231                   }
232                   secstrcode[len] = 'H';
233                   break;
234                 case SHEET:
235                   secstr[len] = 'E';
236                   secstrcode[len] = 'E';
237                   break;
238                 default:
239                   secstr[len] = 0;
240                   secstrcode[len] = 0;
241                 }
242                 len++;
243               }
244             } while (groupc++ < groups.length);
245
246           }
247         }
248       }
249
250       /*
251        * lastScriptTermination = -9465; String dsspOut =
252        * jmd.evalString("calculate STRUCTURE"); if (dsspOut.equals("pending")) {
253        * while (lastScriptTermination == -9465) { try { Thread.sleep(50); }
254        * catch (Exception x) { } ; } } System.out.println(lastConsoleEcho);
255        */
256     }
257   }
258
259   /*
260    * (non-Javadoc)
261    * 
262    * @see jalview.io.AlignFile#print()
263    */
264   @Override
265   public String print()
266   {
267     // TODO Auto-generated method stub
268     return null;
269   }
270
271   @Override
272   public void setCallbackFunction(String callbackType,
273           String callbackFunction)
274   {
275     // TODO Auto-generated method stub
276
277   }
278
279   /*
280    * @Override public void notifyCallback(EnumCallback type, Object[] data) {
281    * try { switch (type) { case ERROR: case SCRIPT:
282    * notifyScriptTermination((String) data[2], ((Integer) data[3]).intValue());
283    * break; case MESSAGE: sendConsoleMessage((data == null) ? ((String) null) :
284    * (String) data[1]); break; case LOADSTRUCT: notifyFileLoaded((String)
285    * data[1], (String) data[2], (String) data[3], (String) data[4], ((Integer)
286    * data[5]).intValue());
287    * 
288    * break; default: // System.err.println("Unhandled callback " + type + " " //
289    * + data[1].toString()); break; } } catch (Exception e) {
290    * System.err.println("Squashed Jmol callback handler error:");
291    * e.printStackTrace(); } }
292    */
293   public void notifyCallback(EnumCallback type, Object[] data)
294   {
295     String strInfo = (data == null || data[1] == null ? null : data[1]
296             .toString());
297     switch (type)
298     {
299     case ECHO:
300       sendConsoleEcho(strInfo);
301       break;
302     case SCRIPT:
303       notifyScriptTermination((String) data[2],
304               ((Integer) data[3]).intValue());
305       break;
306     case MEASURE:
307       String mystatus = (String) data[3];
308       if (mystatus.indexOf("Picked") >= 0
309               || mystatus.indexOf("Sequence") >= 0) // picking mode
310         sendConsoleMessage(strInfo);
311       else if (mystatus.indexOf("Completed") >= 0)
312         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
313                 strInfo.length() - 1));
314       break;
315     case MESSAGE:
316       sendConsoleMessage(data == null ? null : strInfo);
317       break;
318     case PICK:
319       sendConsoleMessage(strInfo);
320       break;
321     default:
322       break;
323     }
324   }
325
326   private void notifyFileLoaded(String string, String string2,
327           String string3, String string4, int intValue)
328   {
329     // TODO Auto-generated method stub
330
331   }
332
333   String lastConsoleEcho = "";
334
335   private void sendConsoleEcho(String string)
336   {
337     lastConsoleEcho += string;
338     lastConsoleEcho += "\n";
339   }
340
341   String lastConsoleMessage = "";
342
343   private void sendConsoleMessage(String string)
344   {
345     lastConsoleMessage += string;
346     lastConsoleMessage += "\n";
347   }
348
349   int lastScriptTermination = -1;
350
351   String lastScriptMessage = "";
352
353   private void notifyScriptTermination(String string, int intValue)
354   {
355     lastScriptMessage += string;
356     lastScriptMessage += "\n";
357     lastScriptTermination = intValue;
358   }
359
360   @Override
361   public boolean notifyEnabled(EnumCallback callbackPick)
362   {
363     switch (callbackPick)
364     {
365     case MESSAGE:
366     case SCRIPT:
367     case ECHO:
368     case LOADSTRUCT:
369     case ERROR:
370       return true;
371     case MEASURE:
372     case PICK:
373     case HOVER:
374     case RESIZE:
375     case SYNC:
376     case CLICK:
377     case ANIMFRAME:
378     case MINIMIZATION:
379     }
380     return false;
381   }
382
383   @Override
384   public String eval(String strEval)
385   {
386     // TODO Auto-generated method stub
387     return null;
388   }
389
390   @Override
391   public float[][] functionXY(String functionName, int x, int y)
392   {
393     // TODO Auto-generated method stub
394     return null;
395   }
396
397   @Override
398   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
399   {
400     // TODO Auto-generated method stub
401     return null;
402   }
403
404   @Override
405   public String createImage(String fileName, String type,
406           Object text_or_bytes, int quality)
407   {
408     // TODO Auto-generated method stub
409     return null;
410   }
411
412   @Override
413   public Map<String, Object> getRegistryInfo()
414   {
415     // TODO Auto-generated method stub
416     return null;
417   }
418
419   @Override
420   public void showUrl(String url)
421   {
422     // TODO Auto-generated method stub
423
424   }
425
426   @Override
427   public void resizeInnerPanel(String data)
428   {
429     // TODO Auto-generated method stub
430
431   }
432
433 }