309e196d15e9840d52dc7e6f6dabaeb169ee3597
[jalview.git] / src / jalview / ext / jmol / JmolParser.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.DBRefSource;
26 import jalview.datamodel.SequenceI;
27 import jalview.io.FileParse;
28 import jalview.io.StructureFile;
29 import jalview.schemes.ResidueProperties;
30 import jalview.structure.StructureViewSettings;
31 import jalview.util.MessageManager;
32
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Vector;
38
39 import javajs.awt.Dimension;
40
41 import org.jmol.api.JmolStatusListener;
42 import org.jmol.api.JmolViewer;
43 import org.jmol.c.CBK;
44 import org.jmol.c.STR;
45 import org.jmol.modelset.ModelSet;
46 import org.jmol.viewer.Viewer;
47
48 import MCview.Atom;
49 import MCview.PDBChain;
50 import MCview.Residue;
51
52 /**
53  * Import and process files with Jmol for file like PDB, mmCIF
54  * 
55  * @author jprocter
56  * 
57  */
58 public class JmolParser extends StructureFile implements JmolStatusListener
59 {
60   Viewer viewer = null;
61
62   public JmolParser(boolean addAlignmentAnnotations, boolean predictSecStr,
63           boolean externalSecStr, String inFile, String type)
64           throws IOException
65   {
66     super(inFile, type);
67   }
68
69   public JmolParser(boolean addAlignmentAnnotations, boolean predictSecStr,
70           boolean externalSecStr, FileParse fp) throws IOException
71   {
72     super(fp);
73   }
74
75   public JmolParser()
76   {
77   }
78
79   /**
80    * Calls the Jmol library to parse the PDB/mmCIF file, and then inspects the
81    * resulting object model to generate Jalview-style sequences, with secondary
82    * structure annotation added where available (i.e. where it has been computed
83    * by Jmol using DSSP).
84    * 
85    * @see jalview.io.AlignFile#parse()
86    */
87   @Override
88   public void parse() throws IOException
89   {
90     String dataName = getDataName();
91     if (dataName.endsWith(".cif"))
92     {
93       setDbRefType(DBRefSource.MMCIF);
94     }
95     else
96     {
97       setDbRefType(DBRefSource.PDB);
98     }
99     setChains(new Vector<PDBChain>());
100     Viewer jmolModel = getJmolData();
101     jmolModel.openReader(getDataName(), getDataName(), getReader());
102     waitForScript(jmolModel);
103
104     /*
105      * Convert one or more Jmol Model objects to Jalview sequences
106      */
107     if (jmolModel.ms.mc > 0)
108     {
109       transformJmolModelToJalview(jmolModel.ms);
110     }
111   }
112
113   /**
114    * create a headless jmol instance for dataprocessing
115    * 
116    * @return
117    */
118   private Viewer getJmolData()
119   {
120     if (viewer == null)
121     {
122       try
123       {
124         viewer = (Viewer) JmolViewer.allocateViewer(null, null, null, null,
125                 null, "-x -o -n", this);
126         // ensure the 'new' (DSSP) not 'old' (Ramachandran) SS method is used
127         viewer.setBooleanProperty("defaultStructureDSSP", true);
128       } catch (ClassCastException x)
129       {
130         throw new Error(MessageManager.formatMessage(
131                 "error.jmol_version_not_compatible_with_jalview_version",
132                 new String[] { JmolViewer.getJmolVersion() }), x);
133       }
134     }
135     return viewer;
136   }
137
138   public void transformJmolModelToJalview(ModelSet ms) throws IOException
139   {
140     try
141     {
142       String lastID = "";
143       List<SequenceI> rna = new ArrayList<SequenceI>();
144       List<SequenceI> prot = new ArrayList<SequenceI>();
145       PDBChain tmpchain;
146       String pdbId = (String) ms.getInfo(0, "title");
147       setId(pdbId);
148       List<Atom> significantAtoms = convertSignificantAtoms(ms);
149       for (Atom tmpatom : significantAtoms)
150       {
151         try
152         {
153           tmpchain = findChain(tmpatom.chain);
154           if (tmpatom.resNumIns.trim().equals(lastID))
155           {
156             // phosphorylated protein - seen both CA and P..
157             continue;
158           }
159           tmpchain.atoms.addElement(tmpatom);
160         } catch (Exception e)
161         {
162           tmpchain = new PDBChain(pdbId, tmpatom.chain);
163           getChains().add(tmpchain);
164           tmpchain.atoms.addElement(tmpatom);
165         }
166         lastID = tmpatom.resNumIns.trim();
167       }
168       xferSettings();
169
170       makeResidueList();
171       makeCaBondList();
172
173       if (getId() == null)
174       {
175         setId(inFile.getName());
176       }
177       for (PDBChain chain : getChains())
178       {
179         SequenceI chainseq = postProcessChain(chain);
180         if (isRNA(chainseq))
181         {
182           rna.add(chainseq);
183         }
184         else
185         {
186           prot.add(chainseq);
187         }
188
189         if (StructureViewSettings.isPredictSecondaryStructure())
190         {
191           createAnnotation(chainseq, chain, ms.at);
192         }
193       }
194     } catch (OutOfMemoryError er)
195     {
196       System.out
197               .println("OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
198       throw new IOException(
199               MessageManager
200                       .getString("exception.outofmemory_loading_mmcif_file"));
201     }
202   }
203
204   private List<Atom> convertSignificantAtoms(ModelSet ms)
205   {
206     List<Atom> significantAtoms = new ArrayList<Atom>();
207     for (org.jmol.modelset.Atom atom : ms.at)
208     {
209       // System.out.println("Seq Id : " + atom.getSeqID());
210       // System.out.println("To String : " + atom.toString());
211       if (atom.isHetero())
212       {
213         continue;
214       }
215       if (atom.getAtomName().equalsIgnoreCase("CA")
216               || atom.getAtomName().equalsIgnoreCase("P"))
217       {
218         Atom curAtom = new Atom(atom.x, atom.y, atom.z);
219         curAtom.atomIndex = atom.getIndex();
220         curAtom.chain = atom.getChainIDStr();
221         curAtom.insCode = atom.group.getInsertionCode();
222         curAtom.name = atom.getAtomName();
223         curAtom.number = atom.getAtomNumber();
224         curAtom.resName = atom.getGroup3(true);
225         curAtom.resNumber = atom.getResno();
226         curAtom.occupancy = ms.occupancies != null ? ms.occupancies[atom
227                 .getIndex()] : Float.valueOf(atom.getOccupancy100());
228         curAtom.resNumIns = "" + curAtom.resNumber + curAtom.insCode;
229         curAtom.tfactor = atom.getBfactor100() / 100f;
230         curAtom.type = 0;
231         significantAtoms.add(curAtom);
232       }
233     }
234     return significantAtoms;
235   }
236
237   private void createAnnotation(SequenceI sequence, PDBChain chain,
238           org.jmol.modelset.Atom[] jmolAtoms)
239   {
240     char[] secstr = new char[sequence.getLength()];
241     char[] secstrcode = new char[sequence.getLength()];
242
243     // Ensure Residue size equals Seq size
244     if (chain.residues.size() != sequence.getLength())
245     {
246       return;
247     }
248     int annotIndex = 0;
249     for (Residue residue : chain.residues)
250     {
251       Atom repAtom = residue.getAtoms().get(0);
252       STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
253               .getProteinStructureSubType();
254       setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
255               secstrcode);
256       ++annotIndex;
257     }
258     addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
259             secstrcode, chain.id, sequence.getStart());
260   }
261
262   /**
263    * Helper method that adds an AlignmentAnnotation for secondary structure to
264    * the sequence, provided at least one secondary structure prediction has been
265    * made
266    * 
267    * @param modelTitle
268    * @param seq
269    * @param secstr
270    * @param secstrcode
271    * @param chainId
272    * @param firstResNum
273    * @return
274    */
275   protected void addSecondaryStructureAnnotation(String modelTitle,
276           SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
277           int firstResNum)
278   {
279     char[] seq = sq.getSequence();
280     boolean ssFound = false;
281     Annotation asecstr[] = new Annotation[seq.length + firstResNum - 1];
282     for (int p = 0; p < seq.length; p++)
283     {
284       if (secstr[p] >= 'A' && secstr[p] <= 'z')
285       {
286         try
287         {
288         asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
289                 secstrcode[p], Float.NaN);
290         ssFound = true;
291         } catch (Exception e)
292         {
293           // e.printStackTrace();
294         }
295       }
296     }
297
298     if (ssFound)
299     {
300       String mt = modelTitle == null ? getDataName() : modelTitle;
301       mt += chainId;
302       AlignmentAnnotation ann = new AlignmentAnnotation(
303               "Secondary Structure", "Secondary Structure for " + mt,
304               asecstr);
305       ann.belowAlignment = true;
306       ann.visible = true;
307       ann.autoCalculated = false;
308       ann.setCalcId(getClass().getName());
309       ann.adjustForAlignment();
310       ann.validateRangeAndDisplay();
311       annotations.add(ann);
312       sq.addAlignmentAnnotation(ann);
313     }
314   }
315
316   private void waitForScript(Viewer jmd)
317   {
318     while (jmd.isScriptExecuting())
319     {
320       try
321       {
322         Thread.sleep(50);
323
324       } catch (InterruptedException x)
325       {
326       }
327     }
328   }
329
330   /**
331    * Convert Jmol's secondary structure code to Jalview's, and stored it in the
332    * secondary structure arrays at the given sequence position
333    * 
334    * @param proteinStructureSubType
335    * @param pos
336    * @param secstr
337    * @param secstrcode
338    */
339   protected void setSecondaryStructure(STR proteinStructureSubType,
340           int pos, char[] secstr, char[] secstrcode)
341   {
342     switch (proteinStructureSubType)
343     {
344     case HELIX310:
345       secstr[pos] = '3';
346       break;
347     case HELIX:
348     case HELIXALPHA:
349       secstr[pos] = 'H';
350       break;
351     case HELIXPI:
352       secstr[pos] = 'P';
353       break;
354     case SHEET:
355       secstr[pos] = 'E';
356       break;
357     default:
358       secstr[pos] = 0;
359     }
360
361     switch (proteinStructureSubType)
362     {
363     case HELIX310:
364     case HELIXALPHA:
365     case HELIXPI:
366     case HELIX:
367       secstrcode[pos] = 'H';
368       break;
369     case SHEET:
370       secstrcode[pos] = 'E';
371       break;
372     default:
373       secstrcode[pos] = 0;
374     }
375   }
376
377   /**
378    * Convert any non-standard peptide codes to their standard code table
379    * equivalent. (Initial version only does Selenomethionine MSE->MET.)
380    * 
381    * @param threeLetterCode
382    * @param seq
383    * @param pos
384    */
385   protected void replaceNonCanonicalResidue(String threeLetterCode,
386           char[] seq, int pos)
387   {
388     String canonical = ResidueProperties
389             .getCanonicalAminoAcid(threeLetterCode);
390     if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
391     {
392       seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
393     }
394   }
395
396   /**
397    * Not implemented - returns null
398    */
399   @Override
400   public String print()
401   {
402     return null;
403   }
404
405   /**
406    * Not implemented
407    */
408   @Override
409   public void setCallbackFunction(String callbackType,
410           String callbackFunction)
411   {
412   }
413
414   @Override
415   public void notifyCallback(CBK cbType, Object[] data)
416   {
417     String strInfo = (data == null || data[1] == null ? null : data[1]
418             .toString());
419     switch (cbType)
420     {
421     case ECHO:
422       sendConsoleEcho(strInfo);
423       break;
424     case SCRIPT:
425       notifyScriptTermination((String) data[2],
426               ((Integer) data[3]).intValue());
427       break;
428     case MEASURE:
429       String mystatus = (String) data[3];
430       if (mystatus.indexOf("Picked") >= 0
431               || mystatus.indexOf("Sequence") >= 0)
432       {
433         // Picking mode
434         sendConsoleMessage(strInfo);
435       }
436       else if (mystatus.indexOf("Completed") >= 0)
437       {
438         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
439                 strInfo.length() - 1));
440       }
441       break;
442     case MESSAGE:
443       sendConsoleMessage(data == null ? null : strInfo);
444       break;
445     case PICK:
446       sendConsoleMessage(strInfo);
447       break;
448     default:
449       break;
450     }
451   }
452
453   String lastConsoleEcho = "";
454
455   private void sendConsoleEcho(String string)
456   {
457     lastConsoleEcho += string;
458     lastConsoleEcho += "\n";
459   }
460
461   String lastConsoleMessage = "";
462
463   private void sendConsoleMessage(String string)
464   {
465     lastConsoleMessage += string;
466     lastConsoleMessage += "\n";
467   }
468
469   int lastScriptTermination = -1;
470
471   String lastScriptMessage = "";
472
473   private void notifyScriptTermination(String string, int intValue)
474   {
475     lastScriptMessage += string;
476     lastScriptMessage += "\n";
477     lastScriptTermination = intValue;
478   }
479
480   @Override
481   public boolean notifyEnabled(CBK callbackPick)
482   {
483     switch (callbackPick)
484     {
485     case MESSAGE:
486     case SCRIPT:
487     case ECHO:
488     case LOADSTRUCT:
489     case ERROR:
490       return true;
491     default:
492       return false;
493     }
494   }
495
496   /**
497    * Not implemented - returns null
498    */
499   @Override
500   public String eval(String strEval)
501   {
502     return null;
503   }
504
505   /**
506    * Not implemented - returns null
507    */
508   @Override
509   public float[][] functionXY(String functionName, int x, int y)
510   {
511     return null;
512   }
513
514   /**
515    * Not implemented - returns null
516    */
517   @Override
518   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
519   {
520     return null;
521   }
522
523   /**
524    * Not implemented - returns null
525    */
526   @Override
527   public String createImage(String fileName, String imageType,
528           Object text_or_bytes, int quality)
529   {
530     return null;
531   }
532
533   /**
534    * Not implemented - returns null
535    */
536   @Override
537   public Map<String, Object> getRegistryInfo()
538   {
539     return null;
540   }
541
542   /**
543    * Not implemented
544    */
545   @Override
546   public void showUrl(String url)
547   {
548   }
549
550   /**
551    * Not implemented - returns null
552    */
553   @Override
554   public Dimension resizeInnerPanel(String data)
555   {
556     return null;
557   }
558
559   @Override
560   public Map<String, Object> getJSpecViewProperty(String arg0)
561   {
562     return null;
563   }
564
565   public boolean isPredictSecondaryStructure()
566   {
567     return predictSecondaryStructure;
568   }
569
570   public void setPredictSecondaryStructure(boolean predictSecondaryStructure)
571   {
572     this.predictSecondaryStructure = predictSecondaryStructure;
573   }
574
575   public boolean isVisibleChainAnnotation()
576   {
577     return visibleChainAnnotation;
578   }
579
580   public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
581   {
582     this.visibleChainAnnotation = visibleChainAnnotation;
583   }
584
585 }