a7e30bf57259c3db28eee18ea8f73bd9ba338fcc
[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(String.valueOf(secstr[p]), null,
446                   secstrcode[p], Float.NaN);
447           ssFound = true;
448         } catch (Exception e)
449         {
450           // e.printStackTrace();
451         }
452       }
453     }
454
455     if (ssFound)
456     {
457       String mt = modelTitle == null ? getDataName() : modelTitle;
458       mt += chainId;
459       AlignmentAnnotation ann = new AlignmentAnnotation(
460               "Secondary Structure", "Secondary Structure for " + mt,
461               asecstr);
462       ann.belowAlignment = true;
463       ann.visible = true;
464       ann.autoCalculated = false;
465       ann.setCalcId(getClass().getName());
466       ann.adjustForAlignment();
467       ann.validateRangeAndDisplay();
468       annotations.add(ann);
469       sq.addAlignmentAnnotation(ann);
470     }
471   }
472
473   private void waitForScript(Viewer jmd)
474   {
475     while (jmd.isScriptExecuting())
476     {
477       try
478       {
479         Thread.sleep(50);
480
481       } catch (InterruptedException x)
482       {
483       }
484     }
485   }
486
487   /**
488    * Convert Jmol's secondary structure code to Jalview's, and stored it in the
489    * secondary structure arrays at the given sequence position
490    * 
491    * @param proteinStructureSubType
492    * @param pos
493    * @param secstr
494    * @param secstrcode
495    */
496   protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
497           char[] secstr, char[] secstrcode)
498   {
499     switch (proteinStructureSubType)
500     {
501     case HELIX310:
502       secstr[pos] = '3';
503       break;
504     case HELIX:
505     case HELIXALPHA:
506       secstr[pos] = 'H';
507       break;
508     case HELIXPI:
509       secstr[pos] = 'P';
510       break;
511     case SHEET:
512       secstr[pos] = 'E';
513       break;
514     default:
515       secstr[pos] = 0;
516     }
517
518     switch (proteinStructureSubType)
519     {
520     case HELIX310:
521     case HELIXALPHA:
522     case HELIXPI:
523     case HELIX:
524       secstrcode[pos] = 'H';
525       break;
526     case SHEET:
527       secstrcode[pos] = 'E';
528       break;
529     default:
530       secstrcode[pos] = 0;
531     }
532   }
533
534   /**
535    * Convert any non-standard peptide codes to their standard code table
536    * equivalent. (Initial version only does Selenomethionine MSE->MET.)
537    * 
538    * @param threeLetterCode
539    * @param seq
540    * @param pos
541    */
542   protected void replaceNonCanonicalResidue(String threeLetterCode,
543           char[] seq, int pos)
544   {
545     String canonical = ResidueProperties
546             .getCanonicalAminoAcid(threeLetterCode);
547     if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
548     {
549       seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
550     }
551   }
552
553   /**
554    * Not implemented - returns null
555    */
556   @Override
557   public String print(SequenceI[] seqs, boolean jvSuffix)
558   {
559     return null;
560   }
561
562   /**
563    * Not implemented
564    */
565   @Override
566   public void setCallbackFunction(String callbackType,
567           String callbackFunction)
568   {
569   }
570
571   @Override
572   public void notifyCallback(CBK cbType, Object[] data)
573   {
574     String strInfo = (data == null || data[1] == null ? null
575             : data[1].toString());
576     switch (cbType)
577     {
578     case ECHO:
579       sendConsoleEcho(strInfo);
580       break;
581     case SCRIPT:
582       notifyScriptTermination((String) data[2],
583               ((Integer) data[3]).intValue());
584       break;
585     case MEASURE:
586       String mystatus = (String) data[3];
587       if (mystatus.indexOf("Picked") >= 0
588               || mystatus.indexOf("Sequence") >= 0)
589       {
590         // Picking mode
591         sendConsoleMessage(strInfo);
592       }
593       else if (mystatus.indexOf("Completed") >= 0)
594       {
595         sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
596                 strInfo.length() - 1));
597       }
598       break;
599     case MESSAGE:
600       sendConsoleMessage(data == null ? null : strInfo);
601       break;
602     case PICK:
603       sendConsoleMessage(strInfo);
604       break;
605     default:
606       break;
607     }
608   }
609
610   String lastConsoleEcho = "";
611
612   private void sendConsoleEcho(String string)
613   {
614     lastConsoleEcho += string;
615     lastConsoleEcho += "\n";
616   }
617
618   String lastConsoleMessage = "";
619
620   private void sendConsoleMessage(String string)
621   {
622     lastConsoleMessage += string;
623     lastConsoleMessage += "\n";
624   }
625
626   int lastScriptTermination = -1;
627
628   String lastScriptMessage = "";
629
630   private void notifyScriptTermination(String string, int intValue)
631   {
632     lastScriptMessage += string;
633     lastScriptMessage += "\n";
634     lastScriptTermination = intValue;
635   }
636
637   @Override
638   public boolean notifyEnabled(CBK callbackPick)
639   {
640     switch (callbackPick)
641     {
642     case MESSAGE:
643     case SCRIPT:
644     case ECHO:
645     case LOADSTRUCT:
646     case ERROR:
647       return true;
648     default:
649       return false;
650     }
651   }
652
653   /**
654    * Not implemented - returns null
655    */
656   @Override
657   public String eval(String strEval)
658   {
659     return null;
660   }
661
662   /**
663    * Not implemented - returns null
664    */
665   @Override
666   public float[][] functionXY(String functionName, int x, int y)
667   {
668     return null;
669   }
670
671   /**
672    * Not implemented - returns null
673    */
674   @Override
675   public float[][][] functionXYZ(String functionName, int nx, int ny,
676           int nz)
677   {
678     return null;
679   }
680
681   /**
682    * Not implemented - returns null
683    */
684   @Override
685   public String createImage(String fileName, String imageType,
686           Object text_or_bytes, int quality)
687   {
688     return null;
689   }
690
691   /**
692    * Not implemented - returns null
693    */
694   @Override
695   public Map<String, Object> getRegistryInfo()
696   {
697     return null;
698   }
699
700   /**
701    * Not implemented
702    */
703   @Override
704   public void showUrl(String url)
705   {
706   }
707
708   /**
709    * Not implemented - returns null
710    */
711   @Override
712   public int[] resizeInnerPanel(String data)
713   {
714     return null;
715   }
716
717   @Override
718   public Map<String, Object> getJSpecViewProperty(String arg0)
719   {
720     return null;
721   }
722
723   public boolean isPredictSecondaryStructure()
724   {
725     return predictSecondaryStructure;
726   }
727
728   public void setPredictSecondaryStructure(
729           boolean predictSecondaryStructure)
730   {
731     this.predictSecondaryStructure = predictSecondaryStructure;
732   }
733
734   public boolean isVisibleChainAnnotation()
735   {
736     return visibleChainAnnotation;
737   }
738
739   public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
740   {
741     this.visibleChainAnnotation = visibleChainAnnotation;
742   }
743
744 }