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