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