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