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 java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Locale;
29 import java.util.Vector;
31 import org.jmol.api.JmolStatusListener;
32 import org.jmol.api.JmolViewer;
33 import org.jmol.c.CBK;
34 import org.jmol.c.STR;
35 import org.jmol.modelset.ModelSet;
36 import org.jmol.viewer.Viewer;
38 import com.stevesoft.pat.Regex;
40 import jalview.datamodel.AlignmentAnnotation;
41 import jalview.datamodel.Annotation;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SequenceI;
44 import jalview.io.DataSourceType;
45 import jalview.io.FileParse;
46 import jalview.io.StructureFile;
47 import jalview.schemes.ResidueProperties;
48 import jalview.util.Format;
49 import jalview.util.MessageManager;
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(
119 getDataName().toLowerCase(Locale.ROOT).endsWith(".cif")
120 ? PDBEntry.Type.MMCIF.toString()
123 transformJmolModelToJalview(jmolModel.ms);
128 * create a headless jmol instance for dataprocessing
132 private Viewer getJmolData()
139 * params -o (output to sysout) -n (nodisplay) -x (exit when finished)
140 * see http://wiki.jmol.org/index.php/Jmol_Application
143 viewer = JalviewJmolBinding.getJmolData(this);
144 // ensure the 'new' (DSSP) not 'old' (Ramachandran) SS method is used
145 viewer.setBooleanProperty("defaultStructureDSSP", true);
146 } catch (ClassCastException x)
148 throw new Error(MessageManager.formatMessage(
149 "error.jmol_version_not_compatible_with_jalview_version",
151 { JmolViewer.getJmolVersion() }), x);
157 public static Regex getNewAlphafoldValidator()
159 Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
160 validator.setIgnoreCase(true);
164 PDBEntry.Type jmolFiletype = null;
167 * resolve a jmol filetype string and update the jmolFiletype field
170 * @param jmolIdentifiedFileType
171 * @return true if filetype was identified as MMCIF, PDB
173 public boolean updateFileType(String jmolIdentifiedFileType)
175 if (jmolIdentifiedFileType == null
176 || jmolIdentifiedFileType.trim().equals(""))
180 if ("mmcif".equalsIgnoreCase(jmolIdentifiedFileType))
182 jmolFiletype = PDBEntry.Type.MMCIF;
185 if ("pdb".equalsIgnoreCase(jmolIdentifiedFileType))
187 jmolFiletype = PDBEntry.Type.PDB;
193 public void transformJmolModelToJalview(ModelSet ms) throws IOException
197 Regex alphaFold = getNewAlphafoldValidator();
199 List<SequenceI> rna = new ArrayList<SequenceI>();
200 List<SequenceI> prot = new ArrayList<SequenceI>();
202 String pdbId = (String) ms.getInfo(0, "title");
203 boolean isMMCIF = false;
204 String jmolFileType_String = (String) ms.getInfo(0, "fileType");
205 if (updateFileType(jmolFileType_String))
207 setStructureFileType(jmolFiletype.toString());
210 isMMCIF = PDBEntry.Type.MMCIF.equals(jmolFiletype);
214 setId(safeName(getDataName()));
215 setPDBIdAvailable(false);
220 setPDBIdAvailable(true);
221 alphaFoldModel = alphaFold.search(pdbId) && isMMCIF;
224 List<Atom> significantAtoms = convertSignificantAtoms(ms);
225 for (Atom tmpatom : significantAtoms)
227 if (tmpatom.resNumIns.trim().equals(lastID))
229 // phosphorylated protein - seen both CA and P..
232 tmpchain = findChain(tmpatom.chain);
233 if (tmpchain != null)
235 tmpchain.atoms.addElement(tmpatom);
239 String tempFString = null;
240 if (isAlphafoldModel())
242 tempFString = "Alphafold Reliability";
245 tmpchain = new PDBChain(getId(), tmpatom.chain, tempFString);
246 getChains().add(tmpchain);
247 tmpchain.atoms.addElement(tmpatom);
249 lastID = tmpatom.resNumIns.trim();
251 if (isParseImmediately())
253 // configure parsing settings from the static singleton
260 for (PDBChain chain : getChains())
262 SequenceI chainseq = postProcessChain(chain);
272 // look at local setting for adding secondary tructure
273 if (predictSecondaryStructure)
275 createAnnotation(chainseq, chain, ms.at);
278 } catch (OutOfMemoryError er)
281 "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
282 throw new IOException(MessageManager
283 .getString("exception.outofmemory_loading_mmcif_file"));
287 private boolean isAlphafoldModel()
289 return alphaFoldModel;
292 private List<Atom> convertSignificantAtoms(ModelSet ms)
294 List<Atom> significantAtoms = new ArrayList<Atom>();
295 HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
296 org.jmol.modelset.Atom prevAtom = null;
297 for (org.jmol.modelset.Atom atom : ms.at)
299 if (atom.getAtomName().equalsIgnoreCase("CA")
300 || atom.getAtomName().equalsIgnoreCase("P"))
302 if (!atomValidated(atom, prevAtom, chainTerMap))
306 Atom curAtom = new Atom(atom.x, atom.y, atom.z);
307 curAtom.atomIndex = atom.getIndex();
308 curAtom.chain = atom.getChainIDStr();
309 curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
310 : atom.group.getInsertionCode();
311 curAtom.name = atom.getAtomName();
312 curAtom.number = atom.getAtomNumber();
313 curAtom.resName = atom.getGroup3(true);
314 curAtom.resNumber = atom.getResno();
315 curAtom.occupancy = ms.occupancies != null
316 ? ms.occupancies[atom.getIndex()]
317 : Float.valueOf(atom.getOccupancy100());
318 String fmt = new Format("%4i").form(curAtom.resNumber);
319 curAtom.resNumIns = (fmt + curAtom.insCode);
320 curAtom.tfactor = atom.getBfactor100() / 100f;
322 // significantAtoms.add(curAtom);
323 // ignore atoms from subsequent models
324 if (!significantAtoms.contains(curAtom))
326 significantAtoms.add(curAtom);
331 return significantAtoms;
334 private boolean atomValidated(org.jmol.modelset.Atom curAtom,
335 org.jmol.modelset.Atom prevAtom,
336 HashMap<String, org.jmol.modelset.Atom> chainTerMap)
338 // System.out.println("Atom: " + curAtom.getAtomNumber()
339 // + " Last atom index " + curAtom.group.lastAtomIndex);
340 if (chainTerMap == null || prevAtom == null)
344 String curAtomChId = curAtom.getChainIDStr();
345 String prevAtomChId = prevAtom.getChainIDStr();
346 // new chain encoutered
347 if (!prevAtomChId.equals(curAtomChId))
349 // On chain switch add previous chain termination to xTerMap if not exists
350 if (!chainTerMap.containsKey(prevAtomChId))
352 chainTerMap.put(prevAtomChId, prevAtom);
354 // if current atom belongs to an already terminated chain and the resNum
355 // diff < 5 then mark as valid and update termination Atom
356 if (chainTerMap.containsKey(curAtomChId))
358 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
362 if ((curAtom.getResno()
363 - chainTerMap.get(curAtomChId).getResno()) < 5)
365 chainTerMap.put(curAtomChId, curAtom);
371 // atom with previously terminated chain encountered
372 else if (chainTerMap.containsKey(curAtomChId))
374 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
378 if ((curAtom.getResno()
379 - chainTerMap.get(curAtomChId).getResno()) < 5)
381 chainTerMap.put(curAtomChId, curAtom);
386 // HETATM with resNum jump > 2
387 return !(curAtom.isHetero()
388 && ((curAtom.getResno() - prevAtom.getResno()) > 2));
391 private void createAnnotation(SequenceI sequence, PDBChain chain,
392 org.jmol.modelset.Atom[] jmolAtoms)
394 char[] secstr = new char[sequence.getLength()];
395 char[] secstrcode = new char[sequence.getLength()];
397 // Ensure Residue size equals Seq size
398 if (chain.residues.size() != sequence.getLength())
403 for (Residue residue : chain.residues)
405 Atom repAtom = residue.getAtoms().get(0);
406 STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
407 .getProteinStructureSubType();
408 setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
412 addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
413 secstrcode, chain.id, sequence.getStart());
417 * Helper method that adds an AlignmentAnnotation for secondary structure to
418 * the sequence, provided at least one secondary structure assignment has been
429 protected void addSecondaryStructureAnnotation(String modelTitle,
430 SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
433 int length = sq.getLength();
434 boolean ssFound = false;
435 Annotation asecstr[] = new Annotation[length + firstResNum - 1];
436 for (int p = 0; p < length; p++)
438 if (secstr[p] >= 'A' && secstr[p] <= 'z')
442 asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
443 secstrcode[p], Float.NaN);
445 } catch (Exception e)
447 // e.printStackTrace();
454 String mt = modelTitle == null ? getDataName() : modelTitle;
456 AlignmentAnnotation ann = new AlignmentAnnotation(
457 "Secondary Structure", "Secondary Structure for " + mt,
459 ann.belowAlignment = true;
461 ann.autoCalculated = false;
462 ann.setCalcId(getClass().getName());
463 ann.adjustForAlignment();
464 ann.validateRangeAndDisplay();
465 annotations.add(ann);
466 sq.addAlignmentAnnotation(ann);
470 private void waitForScript(Viewer jmd)
472 while (jmd.isScriptExecuting())
478 } catch (InterruptedException x)
485 * Convert Jmol's secondary structure code to Jalview's, and stored it in the
486 * secondary structure arrays at the given sequence position
488 * @param proteinStructureSubType
493 protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
494 char[] secstr, char[] secstrcode)
496 switch (proteinStructureSubType)
515 switch (proteinStructureSubType)
521 secstrcode[pos] = 'H';
524 secstrcode[pos] = 'E';
532 * Convert any non-standard peptide codes to their standard code table
533 * equivalent. (Initial version only does Selenomethionine MSE->MET.)
535 * @param threeLetterCode
539 protected void replaceNonCanonicalResidue(String threeLetterCode,
542 String canonical = ResidueProperties
543 .getCanonicalAminoAcid(threeLetterCode);
544 if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
546 seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
551 * Not implemented - returns null
554 public String print(SequenceI[] seqs, boolean jvSuffix)
563 public void setCallbackFunction(String callbackType,
564 String callbackFunction)
569 public void notifyCallback(CBK cbType, Object[] data)
571 String strInfo = (data == null || data[1] == null ? null
572 : data[1].toString());
576 sendConsoleEcho(strInfo);
579 notifyScriptTermination((String) data[2],
580 ((Integer) data[3]).intValue());
583 String mystatus = (String) data[3];
584 if (mystatus.indexOf("Picked") >= 0
585 || mystatus.indexOf("Sequence") >= 0)
588 sendConsoleMessage(strInfo);
590 else if (mystatus.indexOf("Completed") >= 0)
592 sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
593 strInfo.length() - 1));
597 sendConsoleMessage(data == null ? null : strInfo);
600 sendConsoleMessage(strInfo);
607 String lastConsoleEcho = "";
609 private void sendConsoleEcho(String string)
611 lastConsoleEcho += string;
612 lastConsoleEcho += "\n";
615 String lastConsoleMessage = "";
617 private void sendConsoleMessage(String string)
619 lastConsoleMessage += string;
620 lastConsoleMessage += "\n";
623 int lastScriptTermination = -1;
625 String lastScriptMessage = "";
627 private void notifyScriptTermination(String string, int intValue)
629 lastScriptMessage += string;
630 lastScriptMessage += "\n";
631 lastScriptTermination = intValue;
635 public boolean notifyEnabled(CBK callbackPick)
637 switch (callbackPick)
651 * Not implemented - returns null
654 public String eval(String strEval)
660 * Not implemented - returns null
663 public double[][] functionXY(String functionName, int x, int y)
669 * Not implemented - returns null
672 public double[][][] functionXYZ(String functionName, int nx, int ny,
679 * Not implemented - returns null
682 public String createImage(String fileName, String imageType,
683 Object text_or_bytes, int quality)
689 * Not implemented - returns null
692 public Map<String, Object> getRegistryInfo()
701 public void showUrl(String url)
706 * Not implemented - returns null
709 public int[] resizeInnerPanel(String data)
715 public Map<String, Object> getJSpecViewProperty(String arg0)
720 public boolean isPredictSecondaryStructure()
722 return predictSecondaryStructure;
725 public void setPredictSecondaryStructure(
726 boolean predictSecondaryStructure)
728 this.predictSecondaryStructure = predictSecondaryStructure;
731 public boolean isVisibleChainAnnotation()
733 return visibleChainAnnotation;
736 public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
738 this.visibleChainAnnotation = visibleChainAnnotation;