b2ba256e6851d4fbeb6f269606e4f86cf8808ecb
[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       for (PDBChain chain : getChains())
190       {
191         SequenceI chainseq = postProcessChain(chain);
192         if (isRNA(chainseq))
193         {
194           rna.add(chainseq);
195         }
196         else
197         {
198           prot.add(chainseq);
199         }
200
201         if (StructureImportSettings.isProcessSecondaryStructure())
202         {
203           createAnnotation(chainseq, chain, ms.at);
204         }
205       }
206     } catch (OutOfMemoryError er)
207     {
208       System.out
209               .println("OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
210       throw new IOException(
211               MessageManager
212                       .getString("exception.outofmemory_loading_mmcif_file"));
213     }
214   }
215
216   private List<Atom> convertSignificantAtoms(ModelSet ms)
217   {
218     List<Atom> significantAtoms = new ArrayList<Atom>();
219     HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
220     org.jmol.modelset.Atom prevAtom = null;
221     for (org.jmol.modelset.Atom atom : ms.at)
222     {
223       if (atom.getAtomName().equalsIgnoreCase("CA")
224               || atom.getAtomName().equalsIgnoreCase("P"))
225       {
226         if (!atomValidated(atom, prevAtom, chainTerMap))
227         {
228           continue;
229         }
230         Atom curAtom = new Atom(atom.x, atom.y, atom.z);
231         curAtom.atomIndex = atom.getIndex();
232         curAtom.chain = atom.getChainIDStr();
233         curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
234                 : atom.group.getInsertionCode();
235         curAtom.name = atom.getAtomName();
236         curAtom.number = atom.getAtomNumber();
237         curAtom.resName = atom.getGroup3(true);
238         curAtom.resNumber = atom.getResno();
239         curAtom.occupancy = ms.occupancies != null ? ms.occupancies[atom
240                 .getIndex()] : Float.valueOf(atom.getOccupancy100());
241         String fmt = new Format("%4i").form(curAtom.resNumber);
242         curAtom.resNumIns = (fmt + curAtom.insCode);
243         curAtom.tfactor = atom.getBfactor100() / 100f;
244         curAtom.type = 0;
245         // significantAtoms.add(curAtom);
246         // ignore atoms from subsequent models
247         if (!significantAtoms.contains(curAtom))
248         {
249           significantAtoms.add(curAtom);
250         }
251         prevAtom = atom;
252       }
253     }
254     return significantAtoms;
255   }
256
257   private boolean atomValidated(org.jmol.modelset.Atom curAtom,
258           org.jmol.modelset.Atom prevAtom,
259           HashMap<String, org.jmol.modelset.Atom> chainTerMap)
260   {
261     // System.out.println("Atom: " + curAtom.getAtomNumber()
262     // + "   Last atom index " + curAtom.group.lastAtomIndex);
263     if (chainTerMap == null || prevAtom == null)
264     {
265       return true;
266     }
267     String curAtomChId = curAtom.getChainIDStr();
268     String prevAtomChId = prevAtom.getChainIDStr();
269     // new chain encoutered
270     if (!prevAtomChId.equals(curAtomChId))
271     {
272       // On chain switch add previous chain termination to xTerMap if not exists
273       if (!chainTerMap.containsKey(prevAtomChId))
274       {
275         chainTerMap.put(prevAtomChId, prevAtom);
276       }
277       // if current atom belongs to an already terminated chain and the resNum
278       // diff < 5 then mark as valid and update termination Atom
279       if (chainTerMap.containsKey(curAtomChId))
280       {
281         if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
282         {
283           return false;
284         }
285         if ((curAtom.getResno() - chainTerMap.get(curAtomChId).getResno()) < 5)
286         {
287           chainTerMap.put(curAtomChId, curAtom);
288           return true;
289         }
290         return false;
291       }
292     }
293     // atom with previously terminated chain encountered
294     else if (chainTerMap.containsKey(curAtomChId))
295     {
296       if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
297       {
298         return false;
299       }
300       if ((curAtom.getResno() - chainTerMap.get(curAtomChId).getResno()) < 5)
301       {
302         chainTerMap.put(curAtomChId, curAtom);
303         return true;
304       }
305       return false;
306     }
307     // HETATM with resNum jump > 2
308     return !(curAtom.isHetero() && ((curAtom.getResno() - prevAtom
309             .getResno()) > 2));
310   }
311
312   private void createAnnotation(SequenceI sequence, PDBChain chain,
313           org.jmol.modelset.Atom[] jmolAtoms)
314   {
315     char[] secstr = new char[sequence.getLength()];
316     char[] secstrcode = new char[sequence.getLength()];
317
318     // Ensure Residue size equals Seq size
319     if (chain.residues.size() != sequence.getLength())
320     {
321       return;
322     }
323     int annotIndex = 0;
324     for (Residue residue : chain.residues)
325     {
326       Atom repAtom = residue.getAtoms().get(0);
327       STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
328               .getProteinStructureSubType();
329       setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
330               secstrcode);
331       ++annotIndex;
332     }
333     addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
334             secstrcode, chain.id, sequence.getStart());
335   }
336
337   /**
338    * Helper method that adds an AlignmentAnnotation for secondary structure to
339    * the sequence, provided at least one secondary structure prediction has been
340    * made
341    * 
342    * @param modelTitle
343    * @param seq
344    * @param secstr
345    * @param secstrcode
346    * @param chainId
347    * @param firstResNum
348    * @return
349    */
350   protected void addSecondaryStructureAnnotation(String modelTitle,
351           SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
352           int firstResNum)
353   {
354     char[] seq = sq.getSequence();
355     boolean ssFound = false;
356     Annotation asecstr[] = new Annotation[seq.length + firstResNum - 1];
357     for (int p = 0; p < seq.length; p++)
358     {
359       if (secstr[p] >= 'A' && secstr[p] <= 'z')
360       {
361         try
362         {
363           asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
364                   secstrcode[p], Float.NaN);
365           ssFound = true;
366         } catch (Exception e)
367         {
368           // e.printStackTrace();
369         }
370       }
371     }
372
373     if (ssFound)
374     {
375       String mt = modelTitle == null ? getDataName() : modelTitle;
376       mt += chainId;
377       AlignmentAnnotation ann = new AlignmentAnnotation(
378               "Secondary Structure", "Secondary Structure for " + mt,
379               asecstr);
380       ann.belowAlignment = true;
381       ann.visible = true;
382       ann.autoCalculated = false;
383       ann.setCalcId(getClass().getName());
384       ann.adjustForAlignment();
385       ann.validateRangeAndDisplay();
386       annotations.add(ann);
387       sq.addAlignmentAnnotation(ann);
388     }
389   }
390
391   private void waitForScript(Viewer jmd)
392   {
393     while (jmd.isScriptExecuting())
394     {
395       try
396       {
397         Thread.sleep(50);
398
399       } catch (InterruptedException x)
400       {
401       }
402     }
403   }
404
405   /**
406    * Convert Jmol's secondary structure code to Jalview's, and stored it in the
407    * secondary structure arrays at the given sequence position
408    * 
409    * @param proteinStructureSubType
410    * @param pos
411    * @param secstr
412    * @param secstrcode
413    */
414   protected void setSecondaryStructure(STR proteinStructureSubType,
415           int pos, char[] secstr, char[] secstrcode)
416   {
417     switch (proteinStructureSubType)
418     {
419     case HELIX310:
420       secstr[pos] = '3';
421       break;
422     case HELIX:
423     case HELIXALPHA:
424       secstr[pos] = 'H';
425       break;
426     case HELIXPI:
427       secstr[pos] = 'P';
428       break;
429     case SHEET:
430       secstr[pos] = 'E';
431       break;
432     default:
433       secstr[pos] = 0;
434     }
435
436     switch (proteinStructureSubType)
437     {
438     case HELIX310:
439     case HELIXALPHA:
440     case HELIXPI:
441     case HELIX:
442       secstrcode[pos] = 'H';
443       break;
444     case SHEET:
445       secstrcode[pos] = 'E';
446       break;
447     default:
448       secstrcode[pos] = 0;
449     }
450   }
451
452   /**
453    * Convert any non-standard peptide codes to their standard code table
454    * equivalent. (Initial version only does Selenomethionine MSE->MET.)
455    * 
456    * @param threeLetterCode
457    * @param seq
458    * @param pos
459    */
460   protected void replaceNonCanonicalResidue(String threeLetterCode,
461           char[] seq, int pos)
462   {
463     String canonical = ResidueProperties
464             .getCanonicalAminoAcid(threeLetterCode);
465     if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
466     {
467       seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
468     }
469   }
470
471   /**
472    * Not implemented - returns null
473    */
474   @Override
475   public String print()
476   {
477     return null;
478   }
479
480   /**
481    * Not implemented
482    */
483   @Override
484   public void setCallbackFunction(String callbackType,
485           String callbackFunction)
486   {
487   }
488
489   @Override
490   public void notifyCallback(CBK cbType, Object[] data)
491   {
492     String strInfo = (data == null || data[1] == null ? null : data[1]
493             .toString());
494     switch (cbType)
495     {
496     case ECHO:
497       sendConsoleEcho(strInfo);
498       break;
499     case SCRIPT:
500       notifyScriptTermination((String) data[2],
501               ((Integer) data[3]).intValue());
502       break;
503     case MEASURE:
504       String mystatus = (String) data[3];
505       if (mystatus.indexOf("Picked") >= 0
506               || mystatus.indexOf("Sequence") >= 0)
507       {
508         // Picking mode
509         sendConsoleMessage(strInfo);
510       }
511       else if (mystatus.indexOf("Completed") >= 0)
512       {
513         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
514                 strInfo.length() - 1));
515       }
516       break;
517     case MESSAGE:
518       sendConsoleMessage(data == null ? null : strInfo);
519       break;
520     case PICK:
521       sendConsoleMessage(strInfo);
522       break;
523     default:
524       break;
525     }
526   }
527
528   String lastConsoleEcho = "";
529
530   private void sendConsoleEcho(String string)
531   {
532     lastConsoleEcho += string;
533     lastConsoleEcho += "\n";
534   }
535
536   String lastConsoleMessage = "";
537
538   private void sendConsoleMessage(String string)
539   {
540     lastConsoleMessage += string;
541     lastConsoleMessage += "\n";
542   }
543
544   int lastScriptTermination = -1;
545
546   String lastScriptMessage = "";
547
548   private void notifyScriptTermination(String string, int intValue)
549   {
550     lastScriptMessage += string;
551     lastScriptMessage += "\n";
552     lastScriptTermination = intValue;
553   }
554
555   @Override
556   public boolean notifyEnabled(CBK callbackPick)
557   {
558     switch (callbackPick)
559     {
560     case MESSAGE:
561     case SCRIPT:
562     case ECHO:
563     case LOADSTRUCT:
564     case ERROR:
565       return true;
566     default:
567       return false;
568     }
569   }
570
571   /**
572    * Not implemented - returns null
573    */
574   @Override
575   public String eval(String strEval)
576   {
577     return null;
578   }
579
580   /**
581    * Not implemented - returns null
582    */
583   @Override
584   public float[][] functionXY(String functionName, int x, int y)
585   {
586     return null;
587   }
588
589   /**
590    * Not implemented - returns null
591    */
592   @Override
593   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
594   {
595     return null;
596   }
597
598   /**
599    * Not implemented - returns null
600    */
601   @Override
602   public String createImage(String fileName, String imageType,
603           Object text_or_bytes, int quality)
604   {
605     return null;
606   }
607
608   /**
609    * Not implemented - returns null
610    */
611   @Override
612   public Map<String, Object> getRegistryInfo()
613   {
614     return null;
615   }
616
617   /**
618    * Not implemented
619    */
620   @Override
621   public void showUrl(String url)
622   {
623   }
624
625   /**
626    * Not implemented - returns null
627    */
628   @Override
629   public Dimension resizeInnerPanel(String data)
630   {
631     return null;
632   }
633
634   @Override
635   public Map<String, Object> getJSpecViewProperty(String arg0)
636   {
637     return null;
638   }
639
640   public boolean isPredictSecondaryStructure()
641   {
642     return predictSecondaryStructure;
643   }
644
645   public void setPredictSecondaryStructure(boolean predictSecondaryStructure)
646   {
647     this.predictSecondaryStructure = predictSecondaryStructure;
648   }
649
650   public boolean isVisibleChainAnnotation()
651   {
652     return visibleChainAnnotation;
653   }
654
655   public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
656   {
657     this.visibleChainAnnotation = visibleChainAnnotation;
658   }
659
660 }