JAL-3438 spotless for 2.11.2.0
[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.util.Locale;
24
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileParse;
31 import jalview.io.StructureFile;
32 import jalview.schemes.ResidueProperties;
33 import jalview.util.Format;
34 import jalview.util.MessageManager;
35
36 import java.io.IOException;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Vector;
42
43 import org.jmol.api.JmolStatusListener;
44 import org.jmol.api.JmolViewer;
45 import org.jmol.c.CBK;
46 import org.jmol.c.STR;
47 import org.jmol.modelset.ModelSet;
48 import org.jmol.viewer.Viewer;
49
50 import com.stevesoft.pat.Regex;
51
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           String tempFString = null;
242           if (isAlphafoldModel())
243           {
244             tempFString = "Alphafold Reliability";
245           }
246
247           tmpchain = new PDBChain(getId(), tmpatom.chain, tempFString);
248           getChains().add(tmpchain);
249           tmpchain.atoms.addElement(tmpatom);
250         }
251         lastID = tmpatom.resNumIns.trim();
252       }
253       if (isParseImmediately())
254       {
255         // configure parsing settings from the static singleton
256         xferSettings();
257       }
258
259       makeResidueList();
260       makeCaBondList();
261
262       for (PDBChain chain : getChains())
263       {
264         SequenceI chainseq = postProcessChain(chain);
265         if (isRNA(chainseq))
266         {
267           rna.add(chainseq);
268         }
269         else
270         {
271           prot.add(chainseq);
272         }
273
274         // look at local setting for adding secondary tructure
275         if (predictSecondaryStructure)
276         {
277           createAnnotation(chainseq, chain, ms.at);
278         }
279       }
280     } catch (OutOfMemoryError er)
281     {
282       System.out.println(
283               "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
284       throw new IOException(MessageManager
285               .getString("exception.outofmemory_loading_mmcif_file"));
286     }
287   }
288
289   private boolean isAlphafoldModel()
290   {
291     return alphaFoldModel;
292   }
293
294   private List<Atom> convertSignificantAtoms(ModelSet ms)
295   {
296     List<Atom> significantAtoms = new ArrayList<Atom>();
297     HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
298     org.jmol.modelset.Atom prevAtom = null;
299     for (org.jmol.modelset.Atom atom : ms.at)
300     {
301       if (atom.getAtomName().equalsIgnoreCase("CA")
302               || atom.getAtomName().equalsIgnoreCase("P"))
303       {
304         if (!atomValidated(atom, prevAtom, chainTerMap))
305         {
306           continue;
307         }
308         Atom curAtom = new Atom(atom.x, atom.y, atom.z);
309         curAtom.atomIndex = atom.getIndex();
310         curAtom.chain = atom.getChainIDStr();
311         curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
312                 : atom.group.getInsertionCode();
313         curAtom.name = atom.getAtomName();
314         curAtom.number = atom.getAtomNumber();
315         curAtom.resName = atom.getGroup3(true);
316         curAtom.resNumber = atom.getResno();
317         curAtom.occupancy = ms.occupancies != null
318                 ? ms.occupancies[atom.getIndex()]
319                 : Float.valueOf(atom.getOccupancy100());
320         String fmt = new Format("%4i").form(curAtom.resNumber);
321         curAtom.resNumIns = (fmt + curAtom.insCode);
322         curAtom.tfactor = atom.getBfactor100() / 100f;
323         curAtom.type = 0;
324         // significantAtoms.add(curAtom);
325         // ignore atoms from subsequent models
326         if (!significantAtoms.contains(curAtom))
327         {
328           significantAtoms.add(curAtom);
329         }
330         prevAtom = atom;
331       }
332     }
333     return significantAtoms;
334   }
335
336   private boolean atomValidated(org.jmol.modelset.Atom curAtom,
337           org.jmol.modelset.Atom prevAtom,
338           HashMap<String, org.jmol.modelset.Atom> chainTerMap)
339   {
340     // System.out.println("Atom: " + curAtom.getAtomNumber()
341     // + " Last atom index " + curAtom.group.lastAtomIndex);
342     if (chainTerMap == null || prevAtom == null)
343     {
344       return true;
345     }
346     String curAtomChId = curAtom.getChainIDStr();
347     String prevAtomChId = prevAtom.getChainIDStr();
348     // new chain encoutered
349     if (!prevAtomChId.equals(curAtomChId))
350     {
351       // On chain switch add previous chain termination to xTerMap if not exists
352       if (!chainTerMap.containsKey(prevAtomChId))
353       {
354         chainTerMap.put(prevAtomChId, prevAtom);
355       }
356       // if current atom belongs to an already terminated chain and the resNum
357       // diff < 5 then mark as valid and update termination Atom
358       if (chainTerMap.containsKey(curAtomChId))
359       {
360         if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
361         {
362           return false;
363         }
364         if ((curAtom.getResno()
365                 - chainTerMap.get(curAtomChId).getResno()) < 5)
366         {
367           chainTerMap.put(curAtomChId, curAtom);
368           return true;
369         }
370         return false;
371       }
372     }
373     // atom with previously terminated chain encountered
374     else if (chainTerMap.containsKey(curAtomChId))
375     {
376       if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
377       {
378         return false;
379       }
380       if ((curAtom.getResno()
381               - chainTerMap.get(curAtomChId).getResno()) < 5)
382       {
383         chainTerMap.put(curAtomChId, curAtom);
384         return true;
385       }
386       return false;
387     }
388     // HETATM with resNum jump > 2
389     return !(curAtom.isHetero()
390             && ((curAtom.getResno() - prevAtom.getResno()) > 2));
391   }
392
393   private void createAnnotation(SequenceI sequence, PDBChain chain,
394           org.jmol.modelset.Atom[] jmolAtoms)
395   {
396     char[] secstr = new char[sequence.getLength()];
397     char[] secstrcode = new char[sequence.getLength()];
398
399     // Ensure Residue size equals Seq size
400     if (chain.residues.size() != sequence.getLength())
401     {
402       return;
403     }
404     int annotIndex = 0;
405     for (Residue residue : chain.residues)
406     {
407       Atom repAtom = residue.getAtoms().get(0);
408       STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
409               .getProteinStructureSubType();
410       setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
411               secstrcode);
412       ++annotIndex;
413     }
414     addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
415             secstrcode, chain.id, sequence.getStart());
416   }
417
418   /**
419    * Helper method that adds an AlignmentAnnotation for secondary structure to
420    * the sequence, provided at least one secondary structure assignment has been
421    * made
422    * 
423    * @param modelTitle
424    * @param seq
425    * @param secstr
426    * @param secstrcode
427    * @param chainId
428    * @param firstResNum
429    * @return
430    */
431   protected void addSecondaryStructureAnnotation(String modelTitle,
432           SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
433           int firstResNum)
434   {
435     int length = sq.getLength();
436     boolean ssFound = false;
437     Annotation asecstr[] = new Annotation[length + firstResNum - 1];
438     for (int p = 0; p < length; p++)
439     {
440       if (secstr[p] >= 'A' && secstr[p] <= 'z')
441       {
442         try
443         {
444           asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
445                   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 }