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