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.util.Locale;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileParse;
31 import jalview.io.StructureFile;
32 import jalview.schemes.ResidueProperties;
33 import jalview.util.Format;
34 import jalview.util.MessageManager;
36 import java.io.IOException;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
41 import java.util.Vector;
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;
50 import com.stevesoft.pat.Regex;
53 import mc_view.PDBChain;
54 import mc_view.Residue;
57 * Import and process files with Jmol for file like PDB, mmCIF
62 public class JmolParser extends StructureFile implements JmolStatusListener
66 private boolean alphaFoldModel;
68 public JmolParser(boolean immediate, Object inFile,
69 DataSourceType sourceType) throws IOException
71 // BH 2018 File or String for filename
72 super(immediate, inFile, sourceType);
75 public JmolParser(Object inFile, DataSourceType sourceType)
78 super(inFile, sourceType);
81 public JmolParser(FileParse fp) throws IOException
91 * Calls the Jmol library to parse the PDB/mmCIF file, and then inspects the
92 * resulting object model to generate Jalview-style sequences, with secondary
93 * structure annotation added where available (i.e. where it has been computed
94 * by Jmol using DSSP).
96 * @see jalview.io.AlignFile#parse()
99 public void parse() throws IOException
101 setChains(new Vector<PDBChain>());
102 Viewer jmolModel = getJmolData();
103 jmolModel.openReader(getDataName(), getDataName(), getReader());
104 waitForScript(jmolModel);
107 * Convert one or more Jmol Model objects to Jalview sequences
109 if (jmolModel.ms.mc > 0)
111 // ideally we do this
114 // setStructureFileType(jmolModel.evalString("show _fileType"));
115 // } catch (Exception q)
119 // instead, we distinguish .cif from non-.cif by filename
120 setStructureFileType(getDataName().toLowerCase(Locale.ROOT).endsWith(".cif")
121 ? PDBEntry.Type.MMCIF.toString()
124 transformJmolModelToJalview(jmolModel.ms);
129 * create a headless jmol instance for dataprocessing
133 private Viewer getJmolData()
140 * params -o (output to sysout) -n (nodisplay) -x (exit when finished)
141 * see http://wiki.jmol.org/index.php/Jmol_Application
144 viewer = JalviewJmolBinding.getJmolData(this);
145 // ensure the 'new' (DSSP) not 'old' (Ramachandran) SS method is used
146 viewer.setBooleanProperty("defaultStructureDSSP", true);
147 } catch (ClassCastException x)
149 throw new Error(MessageManager.formatMessage(
150 "error.jmol_version_not_compatible_with_jalview_version",
152 { JmolViewer.getJmolVersion() }), x);
158 public static Regex getNewAlphafoldValidator()
160 Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
161 validator.setIgnoreCase(true);
165 PDBEntry.Type jmolFiletype=null;
167 * resolve a jmol filetype string and update the jmolFiletype field accordingly
168 * @param jmolIdentifiedFileType
169 * @return true if filetype was identified as MMCIF, PDB
171 public boolean updateFileType(String jmolIdentifiedFileType)
173 if (jmolIdentifiedFileType == null
174 || jmolIdentifiedFileType.trim().equals(""))
178 if ("mmcif".equalsIgnoreCase(jmolIdentifiedFileType)) {
179 jmolFiletype = PDBEntry.Type.MMCIF;
182 if ("pdb".equalsIgnoreCase(jmolIdentifiedFileType))
184 jmolFiletype = PDBEntry.Type.PDB;
190 public void transformJmolModelToJalview(ModelSet ms) throws IOException
194 Regex alphaFold = getNewAlphafoldValidator();
196 List<SequenceI> rna = new ArrayList<SequenceI>();
197 List<SequenceI> prot = new ArrayList<SequenceI>();
199 String pdbId = (String) ms.getInfo(0, "title");
200 boolean isMMCIF = false;
201 String jmolFileType_String = (String) ms.getInfo(0, "fileType");
202 if (updateFileType(jmolFileType_String))
204 setStructureFileType(jmolFiletype.toString());
207 isMMCIF = PDBEntry.Type.MMCIF.equals(jmolFiletype);
211 setId(safeName(getDataName()));
212 setPDBIdAvailable(false);
217 setPDBIdAvailable(true);
218 alphaFoldModel = alphaFold.search(pdbId) && isMMCIF;
221 List<Atom> significantAtoms = convertSignificantAtoms(ms);
222 for (Atom tmpatom : significantAtoms)
224 if (tmpatom.resNumIns.trim().equals(lastID))
226 // phosphorylated protein - seen both CA and P..
229 tmpchain = findChain(tmpatom.chain);
230 if (tmpchain != null)
232 tmpchain.atoms.addElement(tmpatom);
235 String tempFString=null;
236 if (isAlphafoldModel())
238 tempFString = "Alphafold Reliability";
241 tmpchain = new PDBChain(getId(), tmpatom.chain,tempFString);
242 getChains().add(tmpchain);
243 tmpchain.atoms.addElement(tmpatom);
245 lastID = tmpatom.resNumIns.trim();
247 if (isParseImmediately())
249 // configure parsing settings from the static singleton
256 for (PDBChain chain : getChains())
258 SequenceI chainseq = postProcessChain(chain);
268 // look at local setting for adding secondary tructure
269 if (predictSecondaryStructure)
271 createAnnotation(chainseq, chain, ms.at);
274 } catch (OutOfMemoryError er)
277 "OUT OF MEMORY LOADING TRANSFORMING JMOL MODEL TO JALVIEW MODEL");
278 throw new IOException(MessageManager
279 .getString("exception.outofmemory_loading_mmcif_file"));
283 private boolean isAlphafoldModel()
285 return alphaFoldModel;
288 private List<Atom> convertSignificantAtoms(ModelSet ms)
290 List<Atom> significantAtoms = new ArrayList<Atom>();
291 HashMap<String, org.jmol.modelset.Atom> chainTerMap = new HashMap<String, org.jmol.modelset.Atom>();
292 org.jmol.modelset.Atom prevAtom = null;
293 for (org.jmol.modelset.Atom atom : ms.at)
295 if (atom.getAtomName().equalsIgnoreCase("CA")
296 || atom.getAtomName().equalsIgnoreCase("P"))
298 if (!atomValidated(atom, prevAtom, chainTerMap))
302 Atom curAtom = new Atom(atom.x, atom.y, atom.z);
303 curAtom.atomIndex = atom.getIndex();
304 curAtom.chain = atom.getChainIDStr();
305 curAtom.insCode = atom.group.getInsertionCode() == '\000' ? ' '
306 : atom.group.getInsertionCode();
307 curAtom.name = atom.getAtomName();
308 curAtom.number = atom.getAtomNumber();
309 curAtom.resName = atom.getGroup3(true);
310 curAtom.resNumber = atom.getResno();
311 curAtom.occupancy = ms.occupancies != null
312 ? ms.occupancies[atom.getIndex()]
313 : Float.valueOf(atom.getOccupancy100());
314 String fmt = new Format("%4i").form(curAtom.resNumber);
315 curAtom.resNumIns = (fmt + curAtom.insCode);
316 curAtom.tfactor = atom.getBfactor100() / 100f;
318 // significantAtoms.add(curAtom);
319 // ignore atoms from subsequent models
320 if (!significantAtoms.contains(curAtom))
322 significantAtoms.add(curAtom);
327 return significantAtoms;
330 private boolean atomValidated(org.jmol.modelset.Atom curAtom,
331 org.jmol.modelset.Atom prevAtom,
332 HashMap<String, org.jmol.modelset.Atom> chainTerMap)
334 // System.out.println("Atom: " + curAtom.getAtomNumber()
335 // + " Last atom index " + curAtom.group.lastAtomIndex);
336 if (chainTerMap == null || prevAtom == null)
340 String curAtomChId = curAtom.getChainIDStr();
341 String prevAtomChId = prevAtom.getChainIDStr();
342 // new chain encoutered
343 if (!prevAtomChId.equals(curAtomChId))
345 // On chain switch add previous chain termination to xTerMap if not exists
346 if (!chainTerMap.containsKey(prevAtomChId))
348 chainTerMap.put(prevAtomChId, prevAtom);
350 // if current atom belongs to an already terminated chain and the resNum
351 // diff < 5 then mark as valid and update termination Atom
352 if (chainTerMap.containsKey(curAtomChId))
354 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
358 if ((curAtom.getResno()
359 - chainTerMap.get(curAtomChId).getResno()) < 5)
361 chainTerMap.put(curAtomChId, curAtom);
367 // atom with previously terminated chain encountered
368 else if (chainTerMap.containsKey(curAtomChId))
370 if (curAtom.getResno() < chainTerMap.get(curAtomChId).getResno())
374 if ((curAtom.getResno()
375 - chainTerMap.get(curAtomChId).getResno()) < 5)
377 chainTerMap.put(curAtomChId, curAtom);
382 // HETATM with resNum jump > 2
383 return !(curAtom.isHetero()
384 && ((curAtom.getResno() - prevAtom.getResno()) > 2));
387 private void createAnnotation(SequenceI sequence, PDBChain chain,
388 org.jmol.modelset.Atom[] jmolAtoms)
390 char[] secstr = new char[sequence.getLength()];
391 char[] secstrcode = new char[sequence.getLength()];
393 // Ensure Residue size equals Seq size
394 if (chain.residues.size() != sequence.getLength())
399 for (Residue residue : chain.residues)
401 Atom repAtom = residue.getAtoms().get(0);
402 STR proteinStructureSubType = jmolAtoms[repAtom.atomIndex].group
403 .getProteinStructureSubType();
404 setSecondaryStructure(proteinStructureSubType, annotIndex, secstr,
408 addSecondaryStructureAnnotation(chain.pdbid, sequence, secstr,
409 secstrcode, chain.id, sequence.getStart());
413 * Helper method that adds an AlignmentAnnotation for secondary structure to
414 * the sequence, provided at least one secondary structure assignment has been
425 protected void addSecondaryStructureAnnotation(String modelTitle,
426 SequenceI sq, char[] secstr, char[] secstrcode, String chainId,
429 int length = sq.getLength();
430 boolean ssFound = false;
431 Annotation asecstr[] = new Annotation[length + firstResNum - 1];
432 for (int p = 0; p < length; p++)
434 if (secstr[p] >= 'A' && secstr[p] <= 'z')
438 asecstr[p] = new Annotation(String.valueOf(secstr[p]), null,
439 secstrcode[p], Float.NaN);
441 } catch (Exception e)
443 // e.printStackTrace();
450 String mt = modelTitle == null ? getDataName() : modelTitle;
452 AlignmentAnnotation ann = new AlignmentAnnotation(
453 "Secondary Structure", "Secondary Structure for " + mt,
455 ann.belowAlignment = true;
457 ann.autoCalculated = false;
458 ann.setCalcId(getClass().getName());
459 ann.adjustForAlignment();
460 ann.validateRangeAndDisplay();
461 annotations.add(ann);
462 sq.addAlignmentAnnotation(ann);
466 private void waitForScript(Viewer jmd)
468 while (jmd.isScriptExecuting())
474 } catch (InterruptedException x)
481 * Convert Jmol's secondary structure code to Jalview's, and stored it in the
482 * secondary structure arrays at the given sequence position
484 * @param proteinStructureSubType
489 protected void setSecondaryStructure(STR proteinStructureSubType, int pos,
490 char[] secstr, char[] secstrcode)
492 switch (proteinStructureSubType)
511 switch (proteinStructureSubType)
517 secstrcode[pos] = 'H';
520 secstrcode[pos] = 'E';
528 * Convert any non-standard peptide codes to their standard code table
529 * equivalent. (Initial version only does Selenomethionine MSE->MET.)
531 * @param threeLetterCode
535 protected void replaceNonCanonicalResidue(String threeLetterCode,
538 String canonical = ResidueProperties
539 .getCanonicalAminoAcid(threeLetterCode);
540 if (canonical != null && !canonical.equalsIgnoreCase(threeLetterCode))
542 seq[pos] = ResidueProperties.getSingleCharacterCode(canonical);
547 * Not implemented - returns null
550 public String print(SequenceI[] seqs, boolean jvSuffix)
559 public void setCallbackFunction(String callbackType,
560 String callbackFunction)
565 public void notifyCallback(CBK cbType, Object[] data)
567 String strInfo = (data == null || data[1] == null ? null
568 : data[1].toString());
572 sendConsoleEcho(strInfo);
575 notifyScriptTermination((String) data[2],
576 ((Integer) data[3]).intValue());
579 String mystatus = (String) data[3];
580 if (mystatus.indexOf("Picked") >= 0
581 || mystatus.indexOf("Sequence") >= 0)
584 sendConsoleMessage(strInfo);
586 else if (mystatus.indexOf("Completed") >= 0)
588 sendConsoleEcho(strInfo.substring(strInfo.lastIndexOf(",") + 2,
589 strInfo.length() - 1));
593 sendConsoleMessage(data == null ? null : strInfo);
596 sendConsoleMessage(strInfo);
603 String lastConsoleEcho = "";
605 private void sendConsoleEcho(String string)
607 lastConsoleEcho += string;
608 lastConsoleEcho += "\n";
611 String lastConsoleMessage = "";
613 private void sendConsoleMessage(String string)
615 lastConsoleMessage += string;
616 lastConsoleMessage += "\n";
619 int lastScriptTermination = -1;
621 String lastScriptMessage = "";
623 private void notifyScriptTermination(String string, int intValue)
625 lastScriptMessage += string;
626 lastScriptMessage += "\n";
627 lastScriptTermination = intValue;
631 public boolean notifyEnabled(CBK callbackPick)
633 switch (callbackPick)
647 * Not implemented - returns null
650 public String eval(String strEval)
656 * Not implemented - returns null
659 public float[][] functionXY(String functionName, int x, int y)
665 * Not implemented - returns null
668 public float[][][] functionXYZ(String functionName, int nx, int ny,
675 * Not implemented - returns null
678 public String createImage(String fileName, String imageType,
679 Object text_or_bytes, int quality)
685 * Not implemented - returns null
688 public Map<String, Object> getRegistryInfo()
697 public void showUrl(String url)
702 * Not implemented - returns null
705 public int[] resizeInnerPanel(String data)
711 public Map<String, Object> getJSpecViewProperty(String arg0)
716 public boolean isPredictSecondaryStructure()
718 return predictSecondaryStructure;
721 public void setPredictSecondaryStructure(
722 boolean predictSecondaryStructure)
724 this.predictSecondaryStructure = predictSecondaryStructure;
727 public boolean isVisibleChainAnnotation()
729 return visibleChainAnnotation;
732 public void setVisibleChainAnnotation(boolean visibleChainAnnotation)
734 this.visibleChainAnnotation = visibleChainAnnotation;