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