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);
164 public void transformJmolModelToJalview(ModelSet ms) throws IOException
168 Regex alphaFold = getNewAlphafoldValidator();
170 List<SequenceI> rna = new ArrayList<SequenceI>();
171 List<SequenceI> prot = new ArrayList<SequenceI>();
173 String pdbId = (String) ms.getInfo(0, "title");
174 String isMMCIF = (String) ms.getInfo(0, "fileType");
178 setId(safeName(getDataName()));
179 setPDBIdAvailable(false);
184 setPDBIdAvailable(true);
185 alphaFoldModel = alphaFold.search(pdbId) && isMMCIF!=null && isMMCIF.equalsIgnoreCase("mmcif");
188 List<Atom> significantAtoms = convertSignificantAtoms(ms);
189 for (Atom tmpatom : significantAtoms)
191 if (tmpatom.resNumIns.trim().equals(lastID))
193 // phosphorylated protein - seen both CA and P..
196 tmpchain = findChain(tmpatom.chain);
197 if (tmpchain != null)
199 tmpchain.atoms.addElement(tmpatom);
202 tmpchain = new PDBChain(getId(), tmpatom.chain,isAlphafoldModel());
203 getChains().add(tmpchain);
204 tmpchain.atoms.addElement(tmpatom);
206 lastID = tmpatom.resNumIns.trim();
208 if (isParseImmediately())
210 // configure parsing settings from the static singleton
217 for (PDBChain chain : getChains())
219 SequenceI chainseq = postProcessChain(chain);
229 // look at local setting for adding secondary tructure
230 if (predictSecondaryStructure)
232 createAnnotation(chainseq, chain, ms.at);
235 } catch (OutOfMemoryError er)
238 "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
239 throw new IOException(MessageManager
240 .getString("exception.outofmemory_loading_mmcif_file"));
244 private boolean isAlphafoldModel()
246 return alphaFoldModel;
249 private List<Atom> convertSignificantAtoms(ModelSet ms)
251 List<Atom> significantAtoms = new ArrayList<Atom>();
252 HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
253 org.jmol.modelset.Atom prevAtom = null;
254 for (org.jmol.modelset.Atom atom : ms.at)
256 if (atom.getAtomName().equalsIgnoreCase("CA")
257 || atom.getAtomName().equalsIgnoreCase("P"))
259 if (!atomValidated(atom, prevAtom, chainTerMap))
263 Atom curAtom = new Atom(atom.x, atom.y, atom.z);
264 curAtom.atomIndex = atom.getIndex();
265 curAtom.chain = atom.getChainIDStr();
266 curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
267 : atom.group.getInsertionCode();
268 curAtom.name = atom.getAtomName();
269 curAtom.number = atom.getAtomNumber();
270 curAtom.resName = atom.getGroup3(true);
271 curAtom.resNumber = atom.getResno();
272 curAtom.occupancy = ms.occupancies != null
273 ? ms.occupancies[atom.getIndex()]
274 : Float.valueOf(atom.getOccupancy100());
275 String fmt = new Format("%4i").form(curAtom.resNumber);
276 curAtom.resNumIns = (fmt + curAtom.insCode);
277 curAtom.tfactor = atom.getBfactor100() / 100f;
279 // significantAtoms.add(curAtom);
280 // ignore atoms from subsequent models
281 if (!significantAtoms.contains(curAtom))
283 significantAtoms.add(curAtom);
288 return significantAtoms;
291 private boolean atomValidated(org.jmol.modelset.Atom curAtom,
292 org.jmol.modelset.Atom prevAtom,
293 HashMap<String, org.jmol.modelset.Atom> chainTerMap)
295 // System.out.println("Atom: " + curAtom.getAtomNumber()
296 // + " Last atom index " + curAtom.group.lastAtomIndex);
297 if (chainTerMap == null || prevAtom == null)
301 String curAtomChId = curAtom.getChainIDStr();
302 String prevAtomChId = prevAtom.getChainIDStr();
303 // new chain encoutered
304 if (!prevAtomChId.equals(curAtomChId))
306 // On chain switch add previous chain termination to xTerMap if not exists
307 if (!chainTerMap.containsKey(prevAtomChId))
309 chainTerMap.put(prevAtomChId, prevAtom);
311 // if current atom belongs to an already terminated chain and the resNum
312 // diff < 5 then mark as valid and update termination Atom
313 if (chainTerMap.containsKey(curAtomChId))
315 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
319 if ((curAtom.getResno()
320 - chainTerMap.get(curAtomChId).getResno()) < 5)
322 chainTerMap.put(curAtomChId, curAtom);
328 // atom with previously terminated chain encountered
329 else if (chainTerMap.containsKey(curAtomChId))
331 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
335 if ((curAtom.getResno()
336 - chainTerMap.get(curAtomChId).getResno()) < 5)
338 chainTerMap.put(curAtomChId, curAtom);
343 // HETATM with resNum jump > 2
344 return !(curAtom.isHetero()
345 && ((curAtom.getResno() - prevAtom.getResno()) > 2));
348 private void createAnnotation(SequenceI sequence, PDBChain chain,
349 org.jmol.modelset.Atom[] jmolAtoms)
351 char[] secstr = new char[sequence.getLength()];
352 char[] secstrcode = new char[sequence.getLength()];
354 // Ensure Residue size equals Seq size
355 if (chain.residues.size() != sequence.getLength())
360 for (Residue residue : chain.residues)
362 Atom repAtom = residue.getAtoms().get(0);
363 STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
364 .getProteinStructureSubType();
365 setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
369 addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
370 secstrcode, chain.id, sequence.getStart());
374 * Helper method that adds an AlignmentAnnotation for secondary structure to
375 * the sequence, provided at least one secondary structure assignment has been
386 protected void addSecondaryStructureAnnotation(String modelTitle,
387 SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
390 int length = sq.getLength();
391 boolean ssFound = false;
392 Annotation asecstr[] = new Annotation[length + firstResNum - 1];
393 for (int p = 0; p < length; p++)
395 if (secstr[p] >= 'A' && secstr[p] <= 'z')
399 asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
400 secstrcode[p], Float.NaN);
402 } catch (Exception e)
404 // e.printStackTrace();
411 String mt = modelTitle == null ? getDataName() : modelTitle;
413 AlignmentAnnotation ann = new AlignmentAnnotation(
414 "Secondary Structure", "Secondary Structure for " + mt,
416 ann.belowAlignment = true;
418 ann.autoCalculated = false;
419 ann.setCalcId(getClass().getName());
420 ann.adjustForAlignment();
421 ann.validateRangeAndDisplay();
422 annotations.add(ann);
423 sq.addAlignmentAnnotation(ann);
427 private void waitForScript(Viewer jmd)
429 while (jmd.isScriptExecuting())
435 } catch (InterruptedException x)
442 * Convert Jmol's secondary structure code to Jalview's, and stored it in the
443 * secondary structure arrays at the given sequence position
445 * @param proteinStructureSubType
450 protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
451 char[] secstr, char[] secstrcode)
453 switch (proteinStructureSubType)
472 switch (proteinStructureSubType)
478 secstrcode[pos] = 'H';
481 secstrcode[pos] = 'E';
489 * Convert any non-standard peptide codes to their standard code table
490 * equivalent. (Initial version only does Selenomethionine MSE->MET.)
492 * @param threeLetterCode
496 protected void replaceNonCanonicalResidue(String threeLetterCode,
499 String canonical = ResidueProperties
500 .getCanonicalAminoAcid(threeLetterCode);
501 if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
503 seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
508 * Not implemented - returns null
511 public String print(SequenceI[] seqs, boolean jvSuffix)
520 public void setCallbackFunction(String callbackType,
521 String callbackFunction)
526 public void notifyCallback(CBK cbType, Object[] data)
528 String strInfo = (data == null || data[1] == null ? null
529 : data[1].toString());
533 sendConsoleEcho(strInfo);
536 notifyScriptTermination((String) data[2],
537 ((Integer) data[3]).intValue());
540 String mystatus = (String) data[3];
541 if (mystatus.indexOf("Picked") >= 0
542 || mystatus.indexOf("Sequence") >= 0)
545 sendConsoleMessage(strInfo);
547 else if (mystatus.indexOf("Completed") >= 0)
549 sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
550 strInfo.length() - 1));
554 sendConsoleMessage(data == null ? null : strInfo);
557 sendConsoleMessage(strInfo);
564 String lastConsoleEcho = "";
566 private void sendConsoleEcho(String string)
568 lastConsoleEcho += string;
569 lastConsoleEcho += "\n";
572 String lastConsoleMessage = "";
574 private void sendConsoleMessage(String string)
576 lastConsoleMessage += string;
577 lastConsoleMessage += "\n";
580 int lastScriptTermination = -1;
582 String lastScriptMessage = "";
584 private void notifyScriptTermination(String string, int intValue)
586 lastScriptMessage += string;
587 lastScriptMessage += "\n";
588 lastScriptTermination = intValue;
592 public boolean notifyEnabled(CBK callbackPick)
594 switch (callbackPick)
608 * Not implemented - returns null
611 public String eval(String strEval)
617 * Not implemented - returns null
620 public float[][] functionXY(String functionName, int x, int y)
626 * Not implemented - returns null
629 public float[][][] functionXYZ(String functionName, int nx, int ny,
636 * Not implemented - returns null
639 public String createImage(String fileName, String imageType,
640 Object text_or_bytes, int quality)
646 * Not implemented - returns null
649 public Map<String, Object> getRegistryInfo()
658 public void showUrl(String url)
663 * Not implemented - returns null
666 public int[] resizeInnerPanel(String data)
672 public Map<String, Object> getJSpecViewProperty(String arg0)
677 public boolean isPredictSecondaryStructure()
679 return predictSecondaryStructure;
682 public void setPredictSecondaryStructure(
683 boolean predictSecondaryStructure)
685 this.predictSecondaryStructure = predictSecondaryStructure;
688 public boolean isVisibleChainAnnotation()
690 return visibleChainAnnotation;
693 public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
695 this.visibleChainAnnotation = visibleChainAnnotation;