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.util.Format;
32 import jalview.util.MessageManager;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Vector;
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;
48 import com.stevesoft.pat.Regex;
51 import mc_view.PDBChain;
52 import mc_view.Residue;
55 * Import and process files with Jmol for file like PDB, mmCIF
60 public class JmolParser extends StructureFile implements JmolStatusListener
64 private boolean alphaFoldModel;
66 public JmolParser(boolean immediate, Object inFile,
67 DataSourceType sourceType) throws IOException
69 // BH 2018 File or String for filename
70 super(immediate, inFile, sourceType);
73 public JmolParser(Object inFile, DataSourceType sourceType)
76 super(inFile, sourceType);
79 public JmolParser(FileParse fp) throws IOException
89 * Calls the Jmol library to parse the PDB/mmCIF file, and then inspects the
90 * resulting object model to generate Jalview-style sequences, with secondary
91 * structure annotation added where available (i.e. where it has been computed
92 * by Jmol using DSSP).
94 * @see jalview.io.AlignFile#parse()
97 public void parse() throws IOException
99 setChains(new Vector<PDBChain>());
100 Viewer jmolModel = getJmolData();
101 jmolModel.openReader(getDataName(), getDataName(), getReader());
102 waitForScript(jmolModel);
105 * Convert one or more Jmol Model objects to Jalview sequences
107 if (jmolModel.ms.mc > 0)
109 // ideally we do this
112 // setStructureFileType(jmolModel.evalString("show _fileType"));
113 // } catch (Exception q)
117 // instead, we distinguish .cif from non-.cif by filename
118 setStructureFileType(getDataName().toLowerCase().endsWith(".cif")
119 ? PDBEntry.Type.MMCIF.toString()
122 transformJmolModelToJalview(jmolModel.ms);
127 * create a headless jmol instance for dataprocessing
131 private Viewer getJmolData()
138 * params -o (output to sysout) -n (nodisplay) -x (exit when finished)
139 * see http://wiki.jmol.org/index.php/Jmol_Application
142 viewer = JalviewJmolBinding.getJmolData(this);
143 // ensure the 'new' (DSSP) not 'old' (Ramachandran) SS method is used
144 viewer.setBooleanProperty("defaultStructureDSSP", true);
145 } catch (ClassCastException x)
147 throw new Error(MessageManager.formatMessage(
148 "error.jmol_version_not_compatible_with_jalview_version",
150 { JmolViewer.getJmolVersion() }), x);
156 public static Regex getNewAlphafoldValidator()
158 Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
159 validator.setIgnoreCase(true);
163 PDBEntry.Type jmolFiletype=null;
165 * resolve a jmol filetype string and update the jmolFiletype field accordingly
166 * @param jmolIdentifiedFileType
167 * @return true if filetype was identified as MMCIF, PDB
169 public boolean updateFileType(String jmolIdentifiedFileType)
171 if (jmolIdentifiedFileType == null
172 || jmolIdentifiedFileType.trim().equals(""))
176 if ("mmcif".equalsIgnoreCase(jmolIdentifiedFileType)) {
177 jmolFiletype = PDBEntry.Type.MMCIF;
180 if ("pdb".equalsIgnoreCase(jmolIdentifiedFileType))
182 jmolFiletype = PDBEntry.Type.PDB;
188 public void transformJmolModelToJalview(ModelSet ms) throws IOException
192 Regex alphaFold = getNewAlphafoldValidator();
194 List<SequenceI> rna = new ArrayList<SequenceI>();
195 List<SequenceI> prot = new ArrayList<SequenceI>();
197 String pdbId = (String) ms.getInfo(0, "title");
198 boolean isMMCIF = false;
199 String jmolFileType_String = (String) ms.getInfo(0, "fileType");
200 if (updateFileType(jmolFileType_String))
202 setStructureFileType(jmolFiletype.toString());
205 isMMCIF = PDBEntry.Type.MMCIF.equals(jmolFiletype);
209 setId(safeName(getDataName()));
210 setPDBIdAvailable(false);
215 setPDBIdAvailable(true);
216 alphaFoldModel = alphaFold.search(pdbId) && isMMCIF;
219 List<Atom> significantAtoms = convertSignificantAtoms(ms);
220 for (Atom tmpatom : significantAtoms)
222 if (tmpatom.resNumIns.trim().equals(lastID))
224 // phosphorylated protein - seen both CA and P..
227 tmpchain = findChain(tmpatom.chain);
228 if (tmpchain != null)
230 tmpchain.atoms.addElement(tmpatom);
233 String tempFString=null;
234 if (isAlphafoldModel())
236 tempFString = "Alphafold Reliability";
239 tmpchain = new PDBChain(getId(), tmpatom.chain,tempFString);
240 getChains().add(tmpchain);
241 tmpchain.atoms.addElement(tmpatom);
243 lastID = tmpatom.resNumIns.trim();
245 if (isParseImmediately())
247 // configure parsing settings from the static singleton
254 for (PDBChain chain : getChains())
256 SequenceI chainseq = postProcessChain(chain);
266 // look at local setting for adding secondary tructure
267 if (predictSecondaryStructure)
269 createAnnotation(chainseq, chain, ms.at);
272 } catch (OutOfMemoryError er)
275 "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
276 throw new IOException(MessageManager
277 .getString("exception.outofmemory_loading_mmcif_file"));
281 private boolean isAlphafoldModel()
283 return alphaFoldModel;
286 private List<Atom> convertSignificantAtoms(ModelSet ms)
288 List<Atom> significantAtoms = new ArrayList<Atom>();
289 HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
290 org.jmol.modelset.Atom prevAtom = null;
291 for (org.jmol.modelset.Atom atom : ms.at)
293 if (atom.getAtomName().equalsIgnoreCase("CA")
294 || atom.getAtomName().equalsIgnoreCase("P"))
296 if (!atomValidated(atom, prevAtom, chainTerMap))
300 Atom curAtom = new Atom(atom.x, atom.y, atom.z);
301 curAtom.atomIndex = atom.getIndex();
302 curAtom.chain = atom.getChainIDStr();
303 curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
304 : atom.group.getInsertionCode();
305 curAtom.name = atom.getAtomName();
306 curAtom.number = atom.getAtomNumber();
307 curAtom.resName = atom.getGroup3(true);
308 curAtom.resNumber = atom.getResno();
309 curAtom.occupancy = ms.occupancies != null
310 ? ms.occupancies[atom.getIndex()]
311 : Float.valueOf(atom.getOccupancy100());
312 String fmt = new Format("%4i").form(curAtom.resNumber);
313 curAtom.resNumIns = (fmt + curAtom.insCode);
314 curAtom.tfactor = atom.getBfactor100() / 100f;
316 // significantAtoms.add(curAtom);
317 // ignore atoms from subsequent models
318 if (!significantAtoms.contains(curAtom))
320 significantAtoms.add(curAtom);
325 return significantAtoms;
328 private boolean atomValidated(org.jmol.modelset.Atom curAtom,
329 org.jmol.modelset.Atom prevAtom,
330 HashMap<String, org.jmol.modelset.Atom> chainTerMap)
332 // System.out.println("Atom: " + curAtom.getAtomNumber()
333 // + " Last atom index " + curAtom.group.lastAtomIndex);
334 if (chainTerMap == null || prevAtom == null)
338 String curAtomChId = curAtom.getChainIDStr();
339 String prevAtomChId = prevAtom.getChainIDStr();
340 // new chain encoutered
341 if (!prevAtomChId.equals(curAtomChId))
343 // On chain switch add previous chain termination to xTerMap if not exists
344 if (!chainTerMap.containsKey(prevAtomChId))
346 chainTerMap.put(prevAtomChId, prevAtom);
348 // if current atom belongs to an already terminated chain and the resNum
349 // diff < 5 then mark as valid and update termination Atom
350 if (chainTerMap.containsKey(curAtomChId))
352 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
356 if ((curAtom.getResno()
357 - chainTerMap.get(curAtomChId).getResno()) < 5)
359 chainTerMap.put(curAtomChId, curAtom);
365 // atom with previously terminated chain encountered
366 else if (chainTerMap.containsKey(curAtomChId))
368 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
372 if ((curAtom.getResno()
373 - chainTerMap.get(curAtomChId).getResno()) < 5)
375 chainTerMap.put(curAtomChId, curAtom);
380 // HETATM with resNum jump > 2
381 return !(curAtom.isHetero()
382 && ((curAtom.getResno() - prevAtom.getResno()) > 2));
385 private void createAnnotation(SequenceI sequence, PDBChain chain,
386 org.jmol.modelset.Atom[] jmolAtoms)
388 char[] secstr = new char[sequence.getLength()];
389 char[] secstrcode = new char[sequence.getLength()];
391 // Ensure Residue size equals Seq size
392 if (chain.residues.size() != sequence.getLength())
397 for (Residue residue : chain.residues)
399 Atom repAtom = residue.getAtoms().get(0);
400 STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
401 .getProteinStructureSubType();
402 setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
406 addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
407 secstrcode, chain.id, sequence.getStart());
411 * Helper method that adds an AlignmentAnnotation for secondary structure to
412 * the sequence, provided at least one secondary structure assignment has been
423 protected void addSecondaryStructureAnnotation(String modelTitle,
424 SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
427 int length = sq.getLength();
428 boolean ssFound = false;
429 Annotation asecstr[] = new Annotation[length + firstResNum - 1];
430 for (int p = 0; p < length; p++)
432 if (secstr[p] >= 'A' && secstr[p] <= 'z')
436 asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
437 secstrcode[p], Float.NaN);
439 } catch (Exception e)
441 // e.printStackTrace();
448 String mt = modelTitle == null ? getDataName() : modelTitle;
450 AlignmentAnnotation ann = new AlignmentAnnotation(
451 "Secondary Structure", "Secondary Structure for " + mt,
453 ann.belowAlignment = true;
455 ann.autoCalculated = false;
456 ann.setCalcId(getClass().getName());
457 ann.adjustForAlignment();
458 ann.validateRangeAndDisplay();
459 annotations.add(ann);
460 sq.addAlignmentAnnotation(ann);
464 private void waitForScript(Viewer jmd)
466 while (jmd.isScriptExecuting())
472 } catch (InterruptedException x)
479 * Convert Jmol's secondary structure code to Jalview's, and stored it in the
480 * secondary structure arrays at the given sequence position
482 * @param proteinStructureSubType
487 protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
488 char[] secstr, char[] secstrcode)
490 switch (proteinStructureSubType)
509 switch (proteinStructureSubType)
515 secstrcode[pos] = 'H';
518 secstrcode[pos] = 'E';
526 * Convert any non-standard peptide codes to their standard code table
527 * equivalent. (Initial version only does Selenomethionine MSE->MET.)
529 * @param threeLetterCode
533 protected void replaceNonCanonicalResidue(String threeLetterCode,
536 String canonical = ResidueProperties
537 .getCanonicalAminoAcid(threeLetterCode);
538 if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
540 seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
545 * Not implemented - returns null
548 public String print(SequenceI[] seqs, boolean jvSuffix)
557 public void setCallbackFunction(String callbackType,
558 String callbackFunction)
563 public void notifyCallback(CBK cbType, Object[] data)
565 String strInfo = (data == null || data[1] == null ? null
566 : data[1].toString());
570 sendConsoleEcho(strInfo);
573 notifyScriptTermination((String) data[2],
574 ((Integer) data[3]).intValue());
577 String mystatus = (String) data[3];
578 if (mystatus.indexOf("Picked") >= 0
579 || mystatus.indexOf("Sequence") >= 0)
582 sendConsoleMessage(strInfo);
584 else if (mystatus.indexOf("Completed") >= 0)
586 sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
587 strInfo.length() - 1));
591 sendConsoleMessage(data == null ? null : strInfo);
594 sendConsoleMessage(strInfo);
601 String lastConsoleEcho = "";
603 private void sendConsoleEcho(String string)
605 lastConsoleEcho += string;
606 lastConsoleEcho += "\n";
609 String lastConsoleMessage = "";
611 private void sendConsoleMessage(String string)
613 lastConsoleMessage += string;
614 lastConsoleMessage += "\n";
617 int lastScriptTermination = -1;
619 String lastScriptMessage = "";
621 private void notifyScriptTermination(String string, int intValue)
623 lastScriptMessage += string;
624 lastScriptMessage += "\n";
625 lastScriptTermination = intValue;
629 public boolean notifyEnabled(CBK callbackPick)
631 switch (callbackPick)
645 * Not implemented - returns null
648 public String eval(String strEval)
654 * Not implemented - returns null
657 public float[][] functionXY(String functionName, int x, int y)
663 * Not implemented - returns null
666 public float[][][] functionXYZ(String functionName, int nx, int ny,
673 * Not implemented - returns null
676 public String createImage(String fileName, String imageType,
677 Object text_or_bytes, int quality)
683 * Not implemented - returns null
686 public Map<String, Object> getRegistryInfo()
695 public void showUrl(String url)
700 * Not implemented - returns null
703 public int[] resizeInnerPanel(String data)
709 public Map<String, Object> getJSpecViewProperty(String arg0)
714 public boolean isPredictSecondaryStructure()
716 return predictSecondaryStructure;
719 public void setPredictSecondaryStructure(
720 boolean predictSecondaryStructure)
722 this.predictSecondaryStructure = predictSecondaryStructure;
725 public boolean isVisibleChainAnnotation()
727 return visibleChainAnnotation;
730 public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
732 this.visibleChainAnnotation = visibleChainAnnotation;