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