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