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