2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ext.jmol;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.io.DataSourceType;
28 import jalview.io.FileParse;
29 import jalview.io.StructureFile;
30 import jalview.schemes.ResidueProperties;
31 import jalview.structure.StructureImportSettings;
32 import jalview.util.Format;
33 import jalview.util.MessageManager;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.Vector;
42 import org.jmol.api.JmolStatusListener;
43 import org.jmol.api.JmolViewer;
44 import org.jmol.c.CBK;
45 import org.jmol.c.STR;
46 import org.jmol.modelset.ModelSet;
47 import org.jmol.viewer.Viewer;
50 import MCview.PDBChain;
51 import MCview.Residue;
54 * Import and process files with Jmol for file like PDB, mmCIF
59 public class JmolParser extends StructureFile implements JmolStatusListener
63 public JmolParser(String inFile, DataSourceType sourceType)
66 super(inFile, sourceType);
69 public JmolParser(FileParse fp) throws IOException
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).
84 * @see jalview.io.AlignFile#parse()
87 public void parse() throws IOException
89 setChains(new Vector<PDBChain>());
90 Viewer jmolModel = getJmolData();
91 jmolModel.openReader(getDataName(), getDataName(), getReader());
92 waitForScript(jmolModel);
95 * Convert one or more Jmol Model objects to Jalview sequences
97 if (jmolModel.ms.mc > 0)
102 // setStructureFileType(jmolModel.evalString("show _fileType"));
103 // } catch (Exception q)
107 // instead, we distinguish .cif from non-.cif by filename
108 setStructureFileType(getDataName().toLowerCase().endsWith(".cif")
109 ? PDBEntry.Type.MMCIF.toString()
112 transformJmolModelToJalview(jmolModel.ms);
117 * create a headless jmol instance for dataprocessing
121 private Viewer getJmolData()
128 * params -o (output to sysout) -n (nodisplay) -x (exit when finished)
129 * see http://wiki.jmol.org/index.php/Jmol_Application
131 viewer = (Viewer) JmolViewer.allocateViewer(null, null, null, null,
132 null, "-x -o -n", this);
133 // ensure the 'new' (DSSP) not 'old' (Ramachandran) SS method is used
134 viewer.setBooleanProperty("defaultStructureDSSP", true);
135 } catch (ClassCastException x)
137 throw new Error(MessageManager.formatMessage(
138 "error.jmol_version_not_compatible_with_jalview_version",
140 { JmolViewer.getJmolVersion() }), x);
146 public void transformJmolModelToJalview(ModelSet ms) throws IOException
151 List<SequenceI> rna = new ArrayList<SequenceI>();
152 List<SequenceI> prot = new ArrayList<SequenceI>();
154 String pdbId = (String) ms.getInfo(0, "title");
158 setId(safeName(getDataName()));
159 setPDBIdAvailable(false);
164 setPDBIdAvailable(true);
166 List<Atom> significantAtoms = convertSignificantAtoms(ms);
167 for (Atom tmpatom : significantAtoms)
171 tmpchain = findChain(tmpatom.chain);
172 if (tmpatom.resNumIns.trim().equals(lastID))
174 // phosphorylated protein - seen both CA and P..
177 tmpchain.atoms.addElement(tmpatom);
178 } catch (Exception e)
180 tmpchain = new PDBChain(getId(), tmpatom.chain);
181 getChains().add(tmpchain);
182 tmpchain.atoms.addElement(tmpatom);
184 lastID = tmpatom.resNumIns.trim();
191 for (PDBChain chain : getChains())
193 SequenceI chainseq = postProcessChain(chain);
203 if (StructureImportSettings.isProcessSecondaryStructure())
205 createAnnotation(chainseq, chain, ms.at);
208 } catch (OutOfMemoryError er)
211 "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
212 throw new IOException(MessageManager
213 .getString("exception.outofmemory_loading_mmcif_file"));
217 private List<Atom> convertSignificantAtoms(ModelSet ms)
219 List<Atom> significantAtoms = new ArrayList<Atom>();
220 HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
221 org.jmol.modelset.Atom prevAtom = null;
222 for (org.jmol.modelset.Atom atom : ms.at)
224 if (atom.getAtomName().equalsIgnoreCase("CA")
225 || atom.getAtomName().equalsIgnoreCase("P"))
227 if (!atomValidated(atom, prevAtom, chainTerMap))
231 Atom curAtom = new Atom(atom.x, atom.y, atom.z);
232 curAtom.atomIndex = atom.getIndex();
233 curAtom.chain = atom.getChainIDStr();
234 curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
235 : atom.group.getInsertionCode();
236 curAtom.name = atom.getAtomName();
237 curAtom.number = atom.getAtomNumber();
238 curAtom.resName = atom.getGroup3(true);
239 curAtom.resNumber = atom.getResno();
240 curAtom.occupancy = ms.occupancies != null
241 ? ms.occupancies[atom.getIndex()]
242 : Float.valueOf(atom.getOccupancy100());
243 String fmt = new Format("%4i").form(curAtom.resNumber);
244 curAtom.resNumIns = (fmt + curAtom.insCode);
245 curAtom.tfactor = atom.getBfactor100() / 100f;
247 // significantAtoms.add(curAtom);
248 // ignore atoms from subsequent models
249 if (!significantAtoms.contains(curAtom))
251 significantAtoms.add(curAtom);
256 return significantAtoms;
259 private boolean atomValidated(org.jmol.modelset.Atom curAtom,
260 org.jmol.modelset.Atom prevAtom,
261 HashMap<String, org.jmol.modelset.Atom> chainTerMap)
263 // System.out.println("Atom: " + curAtom.getAtomNumber()
264 // + " Last atom index " + curAtom.group.lastAtomIndex);
265 if (chainTerMap == null || prevAtom == null)
269 String curAtomChId = curAtom.getChainIDStr();
270 String prevAtomChId = prevAtom.getChainIDStr();
271 // new chain encoutered
272 if (!prevAtomChId.equals(curAtomChId))
274 // On chain switch add previous chain termination to xTerMap if not exists
275 if (!chainTerMap.containsKey(prevAtomChId))
277 chainTerMap.put(prevAtomChId, prevAtom);
279 // if current atom belongs to an already terminated chain and the resNum
280 // diff < 5 then mark as valid and update termination Atom
281 if (chainTerMap.containsKey(curAtomChId))
283 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
287 if ((curAtom.getResno()
288 - chainTerMap.get(curAtomChId).getResno()) < 5)
290 chainTerMap.put(curAtomChId, curAtom);
296 // atom with previously terminated chain encountered
297 else if (chainTerMap.containsKey(curAtomChId))
299 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
303 if ((curAtom.getResno()
304 - chainTerMap.get(curAtomChId).getResno()) < 5)
306 chainTerMap.put(curAtomChId, curAtom);
311 // HETATM with resNum jump > 2
312 return !(curAtom.isHetero()
313 && ((curAtom.getResno() - prevAtom.getResno()) > 2));
316 private void createAnnotation(SequenceI sequence, PDBChain chain,
317 org.jmol.modelset.Atom[] jmolAtoms)
319 char[] secstr = new char[sequence.getLength()];
320 char[] secstrcode = new char[sequence.getLength()];
322 // Ensure Residue size equals Seq size
323 if (chain.residues.size() != sequence.getLength())
328 for (Residue residue : chain.residues)
330 Atom repAtom = residue.getAtoms().get(0);
331 STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
332 .getProteinStructureSubType();
333 setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
337 addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
338 secstrcode, chain.id, sequence.getStart());
342 * Helper method that adds an AlignmentAnnotation for secondary structure to
343 * the sequence, provided at least one secondary structure prediction has been
354 protected void addSecondaryStructureAnnotation(String modelTitle,
355 SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
358 int length = sq.getLength();
359 boolean ssFound = false;
360 Annotation asecstr[] = new Annotation[length + firstResNum - 1];
361 for (int p = 0; p < length; p++)
363 if (secstr[p] >= 'A' && secstr[p] <= 'z')
367 asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
368 secstrcode[p], Float.NaN);
370 } catch (Exception e)
372 // e.printStackTrace();
379 String mt = modelTitle == null ? getDataName() : modelTitle;
381 AlignmentAnnotation ann = new AlignmentAnnotation(
382 "Secondary Structure", "Secondary Structure for " + mt,
384 ann.belowAlignment = true;
386 ann.autoCalculated = false;
387 ann.setCalcId(getClass().getName());
388 ann.adjustForAlignment();
389 ann.validateRangeAndDisplay();
390 annotations.add(ann);
391 sq.addAlignmentAnnotation(ann);
395 private void waitForScript(Viewer jmd)
397 while (jmd.isScriptExecuting())
403 } catch (InterruptedException x)
410 * Convert Jmol's secondary structure code to Jalview's, and stored it in the
411 * secondary structure arrays at the given sequence position
413 * @param proteinStructureSubType
418 protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
419 char[] secstr, char[] secstrcode)
421 switch (proteinStructureSubType)
440 switch (proteinStructureSubType)
446 secstrcode[pos] = 'H';
449 secstrcode[pos] = 'E';
457 * Convert any non-standard peptide codes to their standard code table
458 * equivalent. (Initial version only does Selenomethionine MSE->MET.)
460 * @param threeLetterCode
464 protected void replaceNonCanonicalResidue(String threeLetterCode,
467 String canonical = ResidueProperties
468 .getCanonicalAminoAcid(threeLetterCode);
469 if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
471 seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
476 * Not implemented - returns null
479 public String print(SequenceI[] seqs, boolean jvSuffix)
488 public void setCallbackFunction(String callbackType,
489 String callbackFunction)
494 public void notifyCallback(CBK cbType, Object[] data)
496 String strInfo = (data == null || data[1] == null ? null
497 : data[1].toString());
501 sendConsoleEcho(strInfo);
504 notifyScriptTermination((String) data[2],
505 ((Integer) data[3]).intValue());
508 String mystatus = (String) data[3];
509 if (mystatus.indexOf("Picked") >= 0
510 || mystatus.indexOf("Sequence") >= 0)
513 sendConsoleMessage(strInfo);
515 else if (mystatus.indexOf("Completed") >= 0)
517 sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
518 strInfo.length() - 1));
522 sendConsoleMessage(data == null ? null : strInfo);
525 sendConsoleMessage(strInfo);
532 String lastConsoleEcho = "";
534 private void sendConsoleEcho(String string)
536 lastConsoleEcho += string;
537 lastConsoleEcho += "\n";
540 String lastConsoleMessage = "";
542 private void sendConsoleMessage(String string)
544 lastConsoleMessage += string;
545 lastConsoleMessage += "\n";
548 int lastScriptTermination = -1;
550 String lastScriptMessage = "";
552 private void notifyScriptTermination(String string, int intValue)
554 lastScriptMessage += string;
555 lastScriptMessage += "\n";
556 lastScriptTermination = intValue;
560 public boolean notifyEnabled(CBK callbackPick)
562 switch (callbackPick)
576 * Not implemented - returns null
579 public String eval(String strEval)
585 * Not implemented - returns null
588 public float[][] functionXY(String functionName, int x, int y)
594 * Not implemented - returns null
597 public float[][][] functionXYZ(String functionName, int nx, int ny,
604 * Not implemented - returns null
607 public String createImage(String fileName, String imageType,
608 Object text_or_bytes, int quality)
614 * Not implemented - returns null
617 public Map<String, Object> getRegistryInfo()
626 public void showUrl(String url)
631 * Not implemented - returns null
634 public int[] resizeInnerPanel(String data)
640 public Map<String, Object> getJSpecViewProperty(String arg0)
645 public boolean isPredictSecondaryStructure()
647 return predictSecondaryStructure;
650 public void setPredictSecondaryStructure(
651 boolean predictSecondaryStructure)
653 this.predictSecondaryStructure = predictSecondaryStructure;
656 public boolean isVisibleChainAnnotation()
658 return visibleChainAnnotation;
661 public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
663 this.visibleChainAnnotation = visibleChainAnnotation;