JAL-1803 JAL-1919 set type when structure file is parsed
[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()) < 5)
274         {
275           chainTerMap.put(curAtomChId, curAtom);
276           return true;
277         }
278         return false;
279       }
280     }
281     // atom with previously terminated chain encountered
282     else if (chainTerMap.containsKey(curAtomChId))
283     {
284       if ((curAtom.getResno() - chainTerMap.get(curAtomChId).getResno()) < 5)
285       {
286         chainTerMap.put(curAtomChId, curAtom);
287         return true;
288       }
289       return false;
290     }
291     // HETATM with resNum jump > 2
292     return !(curAtom.isHetero() && ((curAtom.getResno() - prevAtom
293             .getResno()) > 2));
294   }
295
296   private void createAnnotation(SequenceI sequence, PDBChain chain,
297           org.jmol.modelset.Atom[] jmolAtoms)
298   {
299     char[] secstr = new char[sequence.getLength()];
300     char[] secstrcode = new char[sequence.getLength()];
301
302     // Ensure Residue size equals Seq size
303     if (chain.residues.size() != sequence.getLength())
304     {
305       return;
306     }
307     int annotIndex = 0;
308     for (Residue residue : chain.residues)
309     {
310       Atom repAtom = residue.getAtoms().get(0);
311       STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
312               .getProteinStructureSubType();
313       setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
314               secstrcode);
315       ++annotIndex;
316     }
317     addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
318             secstrcode, chain.id, sequence.getStart());
319   }
320
321   /**
322    * Helper method that adds an AlignmentAnnotation for secondary structure to
323    * the sequence, provided at least one secondary structure prediction has been
324    * made
325    * 
326    * @param modelTitle
327    * @param seq
328    * @param secstr
329    * @param secstrcode
330    * @param chainId
331    * @param firstResNum
332    * @return
333    */
334   protected void addSecondaryStructureAnnotation(String modelTitle,
335           SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
336           int firstResNum)
337   {
338     char[] seq = sq.getSequence();
339     boolean ssFound = false;
340     Annotation asecstr[] = new Annotation[seq.length + firstResNum - 1];
341     for (int p = 0; p < seq.length; p++)
342     {
343       if (secstr[p] >= 'A' && secstr[p] <= 'z')
344       {
345         try
346         {
347         asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
348                 secstrcode[p], Float.NaN);
349         ssFound = true;
350         } catch (Exception e)
351         {
352           // e.printStackTrace();
353         }
354       }
355     }
356
357     if (ssFound)
358     {
359       String mt = modelTitle == null ? getDataName() : modelTitle;
360       mt += chainId;
361       AlignmentAnnotation ann = new AlignmentAnnotation(
362               "Secondary Structure", "Secondary Structure for " + mt,
363               asecstr);
364       ann.belowAlignment = true;
365       ann.visible = true;
366       ann.autoCalculated = false;
367       ann.setCalcId(getClass().getName());
368       ann.adjustForAlignment();
369       ann.validateRangeAndDisplay();
370       annotations.add(ann);
371       sq.addAlignmentAnnotation(ann);
372     }
373   }
374
375   private void waitForScript(Viewer jmd)
376   {
377     while (jmd.isScriptExecuting())
378     {
379       try
380       {
381         Thread.sleep(50);
382
383       } catch (InterruptedException x)
384       {
385       }
386     }
387   }
388
389   /**
390    * Convert Jmol's secondary structure code to Jalview's, and stored it in the
391    * secondary structure arrays at the given sequence position
392    * 
393    * @param proteinStructureSubType
394    * @param pos
395    * @param secstr
396    * @param secstrcode
397    */
398   protected void setSecondaryStructure(STR proteinStructureSubType,
399           int pos, char[] secstr, char[] secstrcode)
400   {
401     switch (proteinStructureSubType)
402     {
403     case HELIX310:
404       secstr[pos] = '3';
405       break;
406     case HELIX:
407     case HELIXALPHA:
408       secstr[pos] = 'H';
409       break;
410     case HELIXPI:
411       secstr[pos] = 'P';
412       break;
413     case SHEET:
414       secstr[pos] = 'E';
415       break;
416     default:
417       secstr[pos] = 0;
418     }
419
420     switch (proteinStructureSubType)
421     {
422     case HELIX310:
423     case HELIXALPHA:
424     case HELIXPI:
425     case HELIX:
426       secstrcode[pos] = 'H';
427       break;
428     case SHEET:
429       secstrcode[pos] = 'E';
430       break;
431     default:
432       secstrcode[pos] = 0;
433     }
434   }
435
436   /**
437    * Convert any non-standard peptide codes to their standard code table
438    * equivalent. (Initial version only does Selenomethionine MSE->MET.)
439    * 
440    * @param threeLetterCode
441    * @param seq
442    * @param pos
443    */
444   protected void replaceNonCanonicalResidue(String threeLetterCode,
445           char[] seq, int pos)
446   {
447     String canonical = ResidueProperties
448             .getCanonicalAminoAcid(threeLetterCode);
449     if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
450     {
451       seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
452     }
453   }
454
455   /**
456    * Not implemented - returns null
457    */
458   @Override
459   public String print()
460   {
461     return null;
462   }
463
464   /**
465    * Not implemented
466    */
467   @Override
468   public void setCallbackFunction(String callbackType,
469           String callbackFunction)
470   {
471   }
472
473   @Override
474   public void notifyCallback(CBK cbType, Object[] data)
475   {
476     String strInfo = (data == null || data[1] == null ? null : data[1]
477             .toString());
478     switch (cbType)
479     {
480     case ECHO:
481       sendConsoleEcho(strInfo);
482       break;
483     case SCRIPT:
484       notifyScriptTermination((String) data[2],
485               ((Integer) data[3]).intValue());
486       break;
487     case MEASURE:
488       String mystatus = (String) data[3];
489       if (mystatus.indexOf("Picked") >= 0
490               || mystatus.indexOf("Sequence") >= 0)
491       {
492         // Picking mode
493         sendConsoleMessage(strInfo);
494       }
495       else if (mystatus.indexOf("Completed") >= 0)
496       {
497         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
498                 strInfo.length() - 1));
499       }
500       break;
501     case MESSAGE:
502       sendConsoleMessage(data == null ? null : strInfo);
503       break;
504     case PICK:
505       sendConsoleMessage(strInfo);
506       break;
507     default:
508       break;
509     }
510   }
511
512   String lastConsoleEcho = "";
513
514   private void sendConsoleEcho(String string)
515   {
516     lastConsoleEcho += string;
517     lastConsoleEcho += "\n";
518   }
519
520   String lastConsoleMessage = "";
521
522   private void sendConsoleMessage(String string)
523   {
524     lastConsoleMessage += string;
525     lastConsoleMessage += "\n";
526   }
527
528   int lastScriptTermination = -1;
529
530   String lastScriptMessage = "";
531
532   private void notifyScriptTermination(String string, int intValue)
533   {
534     lastScriptMessage += string;
535     lastScriptMessage += "\n";
536     lastScriptTermination = intValue;
537   }
538
539   @Override
540   public boolean notifyEnabled(CBK callbackPick)
541   {
542     switch (callbackPick)
543     {
544     case MESSAGE:
545     case SCRIPT:
546     case ECHO:
547     case LOADSTRUCT:
548     case ERROR:
549       return true;
550     default:
551       return false;
552     }
553   }
554
555   /**
556    * Not implemented - returns null
557    */
558   @Override
559   public String eval(String strEval)
560   {
561     return null;
562   }
563
564   /**
565    * Not implemented - returns null
566    */
567   @Override
568   public float[][] functionXY(String functionName, int x, int y)
569   {
570     return null;
571   }
572
573   /**
574    * Not implemented - returns null
575    */
576   @Override
577   public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
578   {
579     return null;
580   }
581
582   /**
583    * Not implemented - returns null
584    */
585   @Override
586   public String createImage(String fileName, String imageType,
587           Object text_or_bytes, int quality)
588   {
589     return null;
590   }
591
592   /**
593    * Not implemented - returns null
594    */
595   @Override
596   public Map<String, Object> getRegistryInfo()
597   {
598     return null;
599   }
600
601   /**
602    * Not implemented
603    */
604   @Override
605   public void showUrl(String url)
606   {
607   }
608
609   /**
610    * Not implemented - returns null
611    */
612   @Override
613   public Dimension resizeInnerPanel(String data)
614   {
615     return null;
616   }
617
618   @Override
619   public Map<String, Object> getJSpecViewProperty(String arg0)
620   {
621     return null;
622   }
623
624   public boolean isPredictSecondaryStructure()
625   {
626     return predictSecondaryStructure;
627   }
628
629   public void setPredictSecondaryStructure(boolean predictSecondaryStructure)
630   {
631     this.predictSecondaryStructure = predictSecondaryStructure;
632   }
633
634   public boolean isVisibleChainAnnotation()
635   {
636     return visibleChainAnnotation;
637   }
638
639   public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
640   {
641     this.visibleChainAnnotation = visibleChainAnnotation;
642   }
643
644 }