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