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