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