def OEAddLabel_Predicate(disp): ringhighlight = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) oedepict.OEAddHighlighting(disp, ringhighlight, oechem.OEAtomIsInRing(), oechem.OEBondIsInRing()) ringlabel = oedepict.OEHighlightLabel("ring", oechem.OELightGreen) oedepict.OEAddLabel(disp, ringlabel, oechem.OEAtomIsInRing()) chainhighlight = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint) oedepict.OEAddHighlighting(disp, chainhighlight, oechem.OEAtomIsInChain(), oechem.OEBondIsInChain()) chainlabel = oedepict.OEHighlightLabel("chain", oechem.OEBlueTint) oedepict.OEAddLabel(disp, chainlabel, oechem.OEAtomIsInChain())
def OEAddLabel_OEAtomBondSet(disp): mol = disp.GetMolecule() ringset = oechem.OEAtomBondSet(mol.GetAtoms(oechem.OEAtomIsInRing()), mol.GetBonds(oechem.OEBondIsInRing())) ringhighlight = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) oedepict.OEAddHighlighting(disp, ringhighlight, ringset) ringlabel = oedepict.OEHighlightLabel("ring", oechem.OELightGreen) oedepict.OEAddLabel(disp, ringlabel, ringset) chainset = oechem.OEAtomBondSet(mol.GetAtoms(oechem.OEAtomIsInChain()), mol.GetBonds(oechem.OEBondIsInChain())) chainhighlight = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint) oedepict.OEAddHighlighting(disp, chainhighlight, chainset) chainlabel = oedepict.OEHighlightLabel("chain", oechem.OEBlueTint) oedepict.OEAddLabel(disp, chainlabel, chainset)
def OEAddHighlighting_OEAtomBondSet(disp): mol = disp.GetMolecule() abset = oechem.OEAtomBondSet(mol.GetAtoms(Pred6MemAromAtom()), mol.GetBonds(Pred6MemAromBond())) highlightstyle = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) oedepict.OEAddHighlighting(disp, highlightstyle, abset)
def OEAddLabel_OEMatch(disp): subs = oechem.OESubSearch("a1aaaaa1") unique = True highlightstyle = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) for match in subs.Match(disp.GetMolecule(), unique): oedepict.OEAddHighlighting(disp, highlightstyle, match) label = oedepict.OEHighlightLabel("aromatic", oechem.OELightGreen) oedepict.OEAddLabel(disp, label, match)
def smiles_to_image_grid_mod( smiles: set, output_path: str, cols: int = 8, cell_width: int = 200, cell_height: int = 200, ): from openeye import oechem, oedepict itf = oechem.OEInterface() PageByPage = True suppress_h = True rows = math.ceil(len(smiles) / cols) image = oedepict.OEImage(cell_width * cols, cell_height * rows) grid = oedepict.OEImageGrid(image, rows, cols) opts = oedepict.OE2DMolDisplayOptions( grid.GetCellWidth(), grid.GetCellHeight(), oedepict.OEScale_AutoScale ) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) opts.SetTitleLocation(oedepict.OETitleLocation_Bottom) for i, (smi, cell) in enumerate(zip(smiles, grid.GetCells())): mol = oechem.OEGraphMol() oechem.OESmilesToMol(mol, smi) center_bond = [] for atom in mol.GetAtoms(): if atom.GetMapIdx() >0: center_bond.append(atom.GetIdx()) # print(smi, center_bond) assert len(center_bond) == 2 oedepict.OEPrepareDepiction(mol, False, suppress_h) disp = oedepict.OE2DMolDisplay(mol, opts) # Highlight element of interest class NoAtom(oechem.OEUnaryAtomPred): def __call__(self, atom): return False class NoBond(oechem.OEUnaryBondPred): def __call__(self, bond): return False class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in center_bond) and (bond.GetEnd().GetIdx() in center_bond) atoms = mol.GetAtoms(NoAtom()) bonds = mol.GetBonds(CentralBondInTorsion()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEMandarin), oedepict.OEHighlightStyle_BallAndStick, abset) oedepict.OERenderMolecule(cell, disp) oedepict.OEWriteImage(output_path, image)
def plot_dihedral(mol2, width=200, height=200): mol = mol2.CreateCopy() dihedralAtomIndices = [ int(x) - 1 for x in get_sd_data(mol, "TORSION_ATOMS_FRAGMENT").split() ] dih, tor = get_dihedral(mol, dihedralAtomIndices) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) oedepict.OEPrepareDepiction(mol) disp = oedepict.OE2DMolDisplay(mol, opts) img = oedepict.OEImage(width, height) hstyle = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint) oedepict.OEAddHighlighting(disp, hstyle, dih) hstyle = oedepict.OEHighlightByColor(oechem.OERed) oedepict.OEAddHighlighting(disp, hstyle, tor) oedepict.OERenderMolecule(img, disp) return img
def show_oemol_struc(oemol, torsions=False, atom_indices=[], width=500, height=300): from IPython.display import Image from openeye import oechem, oedepict # Highlight element of interest class NoAtom(oechem.OEUnaryAtomPred): def __call__(self, atom): return False class AtomInTorsion(oechem.OEUnaryAtomPred): def __call__(self, atom): return atom.GetIdx() in atom_indices class NoBond(oechem.OEUnaryBondPred): def __call__(self, bond): return False class BondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices) and (bond.GetEnd().GetIdx() in atom_indices) class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices[1:3]) and (bond.GetEnd().GetIdx() in atom_indices[1:3]) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx()) oedepict.OEPrepareDepiction(oemol) img = oedepict.OEImage(width, height) display = oedepict.OE2DMolDisplay(oemol, opts) if torsions: atoms = oemol.GetAtoms(AtomInTorsion()) bonds = oemol.GetBonds(NoBond()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting( display, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, abset, ) oedepict.OERenderMolecule(img, display) png = oedepict.OEWriteImageToString("png", img) return Image(png)
def highlight_atoms_in_mol(mol2, dihedralAtomIndices, width=200, height=200): mol = mol2.CreateCopy() opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) oedepict.OEPrepareDepiction(mol) disp = oedepict.OE2DMolDisplay(mol, opts) img = oedepict.OEImage(width, height) hstyle = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint) for atom_idx in dihedralAtomIndices: oedepict.OEAddHighlighting(disp, hstyle, oechem.OEHasAtomIdx(atom_idx)) oedepict.OERenderMolecule(img, disp) return img
def depictMatch(mol, match, width=500, height=200): from IPython.display import Image dopt = oedepict.OEPrepareDepictionOptions() dopt.SetDepictOrientation(oedepict.OEDepictOrientation_Horizontal) dopt.SetSuppressHydrogens(True) oedepict.OEPrepareDepiction(mol, dopt) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) disp = oedepict.OE2DMolDisplay(mol, opts) hstyle = oedepict.OEHighlightStyle_Color hcolor = oechem.OEColor(oechem.OELightBlue) oedepict.OEAddHighlighting(disp, hcolor, hstyle, match) ofs = oechem.oeosstream() oedepict.OERenderMolecule(ofs, 'png', disp) ofs.flush() return Image(data="".join(ofs.str()))
def DepictMoleculesWithHighlight(smiles, ss, highlight, basefilename): mol = oechem.OEGraphMol() oechem.OESmilesToMol(mol, smiles) oedepict.OEPrepareDepiction(mol) opts = oedepict.OE2DMolDisplayOptions(220, 160, oedepict.OEScale_AutoScale) disp = oedepict.OE2DMolDisplay(mol, opts) unique = True for match in ss.Match(mol, unique): oedepict.OEAddHighlighting(disp, highlight, match) image = oedepict.OEImage(disp.GetWidth(), disp.GetHeight()) oedepict.OERenderMolecule(image, disp) oedepict.OEWriteImage(basefilename + ".png", image) oedepict.OEWriteImage(basefilename + ".pdf", image)
def draw_subsearch_highlights(mol, subsearch, width=400.0, height=400.0): """ Draws the hits for the substructure in a given molecule. Copied from http://notebooks.eyesopen.com/substructure-search-pandas-oenotebook.html """ opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) mol = oechem.OEGraphMol(mol) oedepict.OEPrepareDepiction(mol) img = oedepict.OEImage(width, height) hstyle = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint) disp = oedepict.OE2DMolDisplay(mol, opts) unique = True for match in subsearch.Match(mol, unique): oedepict.OEAddHighlighting(disp, hstyle, match) oedepict.OERenderMolecule(img, disp) # return oenb.draw_oeimage_to_img_tag(img) return img
def gen_pdf( tid_clusters_list: list, output_path: str, cols: int = 8, cell_width: int = 200, cell_height: int = 200, ): from openeye import oechem, oedepict from openforcefield.topology import Molecule itf = oechem.OEInterface() PageByPage = True suppress_h = True n = sum([len(clusters) for tid, clusters in tid_clusters_list.items()]) rows = math.ceil(n / cols) image = oedepict.OEImage(cell_width * cols, cell_height * rows) grid = oedepict.OEImageGrid(image, rows, cols) opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), grid.GetCellHeight(), oedepict.OEScale_AutoScale) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) opts.SetTitleLocation(oedepict.OETitleLocation_Bottom) count = 0 for tid, clusters in tid_clusters_list.items(): for cluster in clusters: torsions = cluster['torsions'] label = cluster['cluster_label'] torsions = cluster['torsions'] for torsion in torsions: cell = grid.GetCell(count // cols + 1, count % cols + 1) smi = torsion['mol_index'] atom_indices = torsion['indices'] # mol = oechem.OEGraphMol() # oechem.OESmilesToMol(mol, smi) off_mol = Molecule.from_smiles(smi, allow_undefined_stereo=True) off_mol = off_mol.canonical_order_atoms() mol = Molecule.to_openeye(off_mol) title = '{} ({})'.format(tid, set(torsion['covered_tids'])) mol.SetTitle(title) oedepict.OEPrepareDepiction(mol, False, suppress_h) disp = oedepict.OE2DMolDisplay(mol, opts) # Highlight element of interest class NoAtom(oechem.OEUnaryAtomPred): def __call__(self, atom): return False class AtomInTorsion(oechem.OEUnaryAtomPred): def __call__(self, atom): return atom.GetIdx() in atom_indices class NoBond(oechem.OEUnaryBondPred): def __call__(self, bond): return False class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices[1:3] ) and (bond.GetEnd().GetIdx() in atom_indices[1:3]) atoms = mol.GetAtoms(AtomInTorsion()) bonds = mol.GetBonds(NoBond()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting( disp, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, abset) atoms = mol.GetAtoms(NoAtom()) bonds = mol.GetBonds(CentralBondInTorsion()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting( disp, oechem.OEColor(oechem.OEMandarin), oedepict.OEHighlightStyle_BallAndStick, abset) oedepict.OERenderMolecule(cell, disp) count += 1 oedepict.OEWriteImage(output_path, image)
def to_pdf(molecules, bond_map_idx, fname, rows=3, cols=2, align=None): """ Generate PDF of list of oemols or SMILES Parameters ---------- molecules : list of OEMols These mols need to have map indices on bond of interest and WBO attached to that bond's data fname : str Name of PDF rows : int How many rows of molecules per page cols : int How many columns of molecule per page bond_map_idx : tuple of bond to highlight align: oemol molecule to align all other molecules in the list """ itf = oechem.OEInterface() ropts = oedepict.OEReportOptions(rows, cols) ropts.SetHeaderHeight(25) ropts.SetFooterHeight(25) ropts.SetCellGap(2) ropts.SetPageMargins(10) report = oedepict.OEReport(ropts) cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight() opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_AutoScale) oedepict.OESetup2DMolDisplayOptions(opts, itf) if align: if isinstance(align, str): ref_mol = oechem.OEGraphMol() oechem.OESmilesToMol(ref_mol, align) elif isinstance(align, (oechem.OEMol, oechem.OEMolBase, oechem.OEGraphMol)): ref_mol = align oedepict.OEPrepareDepiction(ref_mol) for i, mol in enumerate(molecules): cell = report.NewCell() mol_copy = oechem.OEMol(mol) oedepict.OEPrepareDepiction(mol_copy, False, True) atom_bond_set = oechem.OEAtomBondSet() a1 = mol_copy.GetAtom(oechem.OEHasMapIdx(bond_map_idx[0])) a2 = mol_copy.GetAtom(oechem.OEHasMapIdx(bond_map_idx[1])) b = mol_copy.GetBond(a1, a2) opts.SetBondPropertyFunctor(fragmenter.chemi.LabelWibergBondOrder()) atom_bond_set.AddAtom(a1) atom_bond_set.AddAtom(a2) atom_bond_set.AddBond(b) hstyle = oedepict.OEHighlightStyle_BallAndStick hcolor = oechem.OEColor(oechem.OELightBlue) overlaps = oegraphsim.OEGetFPOverlap( ref_mol, mol_copy, oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree)) oedepict.OEPrepareMultiAlignedDepiction(mol_copy, ref_mol, overlaps) disp = oedepict.OE2DMolDisplay(mol_copy, opts) oedepict.OEAddHighlighting(disp, hcolor, hstyle, atom_bond_set) oedepict.OERenderMolecule(cell, disp) oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) oedepict.OEWriteReport(fname, report)
def DepictMoleculeWithFragmentCombinations(report, mol, frags, opts): #fragcombs, opts): """ This function was taken from https://docs.eyesopen.com/toolkits/cookbook/python/depiction/enumfrags.html with some modification """ stag = "fragment idx" itag = oechem.OEGetTag(stag) for fidx, frag in enumerate(frags): for bond in frags[frag].GetBonds(): bond.SetData(itag, fidx) # setup depiction styles nrfrags = len(frags) colors = [c for c in oechem.OEGetLightColors()] if len(colors) < nrfrags: colors = [c for c in oechem.OEGetColors(oechem.OEYellowTint, oechem.OEDarkOrange, nrfrags)] bondglyph = ColorBondByFragmentIndex(colors, itag) lineWidthScale = 0.75 fadehighlight = oedepict.OEHighlightByColor(oechem.OEGrey, lineWidthScale) # depict each fragment combinations for frag in frags: cell = report.NewCell() disp = oedepict.OE2DMolDisplay(mol, opts) fragatoms = oechem.OEIsAtomMember(frags[frag].GetAtoms()) fragbonds = oechem.OEIsBondMember(frags[frag].GetBonds()) notfragatoms = oechem.OENotAtom(fragatoms) notfragbonds = oechem.OENotBond(fragbonds) oedepict.OEAddHighlighting(disp, fadehighlight, notfragatoms, notfragbonds) bond = mol.GetBond(oechem.OEHasBondIdx(frag)) atomBondSet = oechem.OEAtomBondSet() atomBondSet.AddBond(bond) atomBondSet.AddAtom(bond.GetBgn()) atomBondSet.AddAtom(bond.GetEnd()) hstyle = oedepict.OEHighlightStyle_BallAndStick hcolor = oechem.OEColor(oechem.OELightBlue) oedepict.OEAddHighlighting(disp, hcolor, hstyle, atomBondSet) #oegrapheme.OEAddGlyph(disp, bondglyph, fragbonds) oedepict.OERenderMolecule(cell, disp) # depict original fragmentation in each header cellwidth, cellheight = report.GetHeaderWidth(), report.GetHeaderHeight() opts.SetDimensions(cellwidth, cellheight, oedepict.OEScale_AutoScale) opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome) bondlabel = LabelBondOrder() opts.SetBondPropertyFunctor(bondlabel) disp = oedepict.OE2DMolDisplay(mol, opts) #oegrapheme.OEAddGlyph(disp, bondglyph, oechem.IsTrueBond()) headerpen = oedepict.OEPen(oechem.OEWhite, oechem.OELightGrey, oedepict.OEFill_Off, 2.0) for header in report.GetHeaders(): oedepict.OERenderMolecule(header, disp) oedepict.OEDrawBorder(header, headerpen)
ropts = oedepict.OEReportOptions(rows, cols) ropts.SetHeaderHeight(25) ropts.SetFooterHeight(25) ropts.SetCellGap(2) ropts.SetPageMargins(10) report = oedepict.OEReport(ropts) cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight() opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_Default * 0.5) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On, 1.0) opts.SetDefaultBondPen(pen) oedepict.OESetup2DMolDisplayOptions(opts, itf) for i, mol in enumerate(oemols): cell = report.NewCell() mol_copy = oechem.OEMol(mol) oedepict.OEPrepareDepiction(mol_copy, False, suppress_h) disp = oedepict.OE2DMolDisplay(mol_copy, opts) # Highlight element of interest unique = False if subs is not None: for match in subs.Match(mol_copy, unique): oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, match) oedepict.OERenderMolecule(cell, disp) oedepict.OEWriteReport(pdf_filename, report)
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', '--json', default='selected_torsions.json') parser.add_argument('-o', '--outfile', default='selected_torsions.pdf') args = parser.parse_args() json_molecules = read_molecules(args.json) # Generate a PDF of all molecules in the set pdf_filename = args.outfile from openeye import oedepict itf = oechem.OEInterface() PageByPage = True suppress_h = True rows = 7 cols = 3 ropts = oedepict.OEReportOptions(rows, cols) ropts.SetHeaderHeight(25) ropts.SetFooterHeight(25) ropts.SetCellGap(2) ropts.SetPageMargins(10) report = oedepict.OEReport(ropts) cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight() opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_Default * 0.5) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On, 1.0) opts.SetDefaultBondPen(pen) oedepict.OESetup2DMolDisplayOptions(opts, itf) for json_molecule in json_molecules.values(): # Create oemol oemol = cmiles.utils.load_molecule( json_molecule['initial_molecules'][0]) # Get atom indices atom_indices = json_molecule['atom_indices'][0] # Render molecule cell = report.NewCell() mol = oechem.OEMol(oemol) torsion_param = get_torsion_definition(ff_torsion_param_list, json_molecule['tid']) mol.SetTitle(f'{torsion_param.id} ({torsion_param.smirks})') oedepict.OEPrepareDepiction(mol, False, suppress_h) disp = oedepict.OE2DMolDisplay(mol, opts) # Highlight element of interest class NoAtom(oechem.OEUnaryAtomPred): def __call__(self, atom): return False class AtomInTorsion(oechem.OEUnaryAtomPred): def __call__(self, atom): return atom.GetIdx() in atom_indices class NoBond(oechem.OEUnaryBondPred): def __call__(self, bond): return False class BondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices) and (bond.GetEnd().GetIdx() in atom_indices) class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices[1:3]) and (bond.GetEnd().GetIdx() in atom_indices[1:3]) atoms = mol.GetAtoms(AtomInTorsion()) bonds = mol.GetBonds(NoBond()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, abset) atoms = mol.GetAtoms(NoAtom()) bonds = mol.GetBonds(CentralBondInTorsion()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEOrange), oedepict.OEHighlightStyle_BallAndStick, abset) oedepict.OERenderMolecule(cell, disp) #oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) oedepict.OEWriteReport(pdf_filename, report)
from openeye import oechem from openeye import oedepict # @ <SNIPPET-HIGHLIGHT-MULTI> mol = oechem.OEGraphMol() oechem.OESmilesToMol(mol, "c1cncc2c1cc3c(cncc3)c2") oedepict.OEPrepareDepiction(mol) subs = oechem.OESubSearch("c1cc[c,n]cc1") width, height = 350, 250 image = oedepict.OEImage(width, height) rows, cols = 2, 2 grid = oedepict.OEImageGrid(image, rows, cols) opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), grid.GetCellHeight(), oedepict.OEScale_AutoScale) unique = True for match, cell in zip(subs.Match(mol, unique), grid.GetCells()): disp = oedepict.OE2DMolDisplay(mol, opts) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEPink), oedepict.OEHighlightStyle_Color, match) oedepict.OERenderMolecule(cell, disp) oedepict.OEWriteImage("HighlightMulti.png", image) # @ </SNIPPET-HIGHLIGHT-MULTI> oedepict.OEWriteImage("HighlightMulti.pdf", image)
def render_atom_mapping(filename, molecule1, molecule2, new_to_old_atom_map, width=1200, height=600): """ Render the atom mapping to a PDF file. Parameters ---------- filename : str The PDF filename to write to. molecule1 : openeye.oechem.OEMol Initial molecule molecule2 : openeye.oechem.OEMol Final molecule new_to_old_atom_map : dict of int new_to_old_atom_map[molecule2_atom_index] is the corresponding molecule1 atom index width : int, optional, default=1200 Width in pixels height : int, optional, default=1200 Height in pixels """ from openeye import oechem, oedepict # Make copies of the input molecules molecule1, molecule2 = oechem.OEGraphMol(molecule1), oechem.OEGraphMol(molecule2) oechem.OEGenerate2DCoordinates(molecule1) oechem.OEGenerate2DCoordinates(molecule2) # Add both to an OEGraphMol reaction rmol = oechem.OEGraphMol() rmol.SetRxn(True) def add_molecule(mol): # Add atoms new_atoms = list() old_to_new_atoms = dict() for old_atom in mol.GetAtoms(): new_atom = rmol.NewAtom(old_atom.GetAtomicNum()) new_atoms.append(new_atom) old_to_new_atoms[old_atom] = new_atom # Add bonds for old_bond in mol.GetBonds(): rmol.NewBond(old_to_new_atoms[old_bond.GetBgn()], old_to_new_atoms[old_bond.GetEnd()], old_bond.GetOrder()) return new_atoms, old_to_new_atoms [new_atoms_1, old_to_new_atoms_1] = add_molecule(molecule1) [new_atoms_2, old_to_new_atoms_2] = add_molecule(molecule2) # Label reactant and product for atom in new_atoms_1: atom.SetRxnRole(oechem.OERxnRole_Reactant) for atom in new_atoms_2: atom.SetRxnRole(oechem.OERxnRole_Product) core1 = oechem.OEAtomBondSet() core2 = oechem.OEAtomBondSet() # add all atoms to the set core1.AddAtoms(new_atoms_1) core2.AddAtoms(new_atoms_2) # Label mapped atoms core_change = oechem.OEAtomBondSet() index =1 for (index2, index1) in new_to_old_atom_map.items(): new_atoms_1[index1].SetMapIdx(index) new_atoms_2[index2].SetMapIdx(index) # now remove the atoms that are core, so only uniques are highlighted core1.RemoveAtom(new_atoms_1[index1]) core2.RemoveAtom(new_atoms_2[index2]) if new_atoms_1[index1].GetAtomicNum() != new_atoms_2[index2].GetAtomicNum(): # this means the element type is changing core_change.AddAtom(new_atoms_1[index1]) core_change.AddAtom(new_atoms_2[index2]) index += 1 # Set up image options itf = oechem.OEInterface() oedepict.OEConfigureImageOptions(itf) ext = oechem.OEGetFileExtension(filename) if not oedepict.OEIsRegisteredImageFile(ext): raise Exception('Unknown image type for filename %s' % filename) ofs = oechem.oeofstream() if not ofs.open(filename): raise Exception('Cannot open output file %s' % filename) # Setup depiction options oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) oedepict.OESetup2DMolDisplayOptions(opts, itf) opts.SetBondWidthScaling(True) opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx()) opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome) # Depict reaction with component highlights oechem.OEGenerate2DCoordinates(rmol) rdisp = oedepict.OE2DMolDisplay(rmol, opts) oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEPink),oedepict.OEHighlightStyle_Stick, core1) oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEPurple),oedepict.OEHighlightStyle_Stick, core2) oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEGreen),oedepict.OEHighlightStyle_Stick, core_change) oedepict.OERenderMolecule(ofs, ext, rdisp) ofs.close()
def OEAddHighlighting_AtomAndBondPredicate(disp): oedepict.OEAddHighlighting(disp, oechem.OEDarkGreen, oedepict.OEHighlightStyle_Color, Pred6MemAromAtom(), Pred6MemAromBond())
def OEAddHighlighting_OESubSearch(disp): subsearch = oechem.OESubSearch("a1aaaaa1") highlightstyle = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) oedepict.OEAddHighlighting(disp, highlightstyle, subsearch)
def _oe_render_fragment( parent: Molecule, fragment: Molecule, bond_indices: BondTuple, image_width: int = 283, image_height: int = 169, ) -> str: from openeye import oechem, oedepict # Map the OpenFF molecules into OE ones, making sure to explicitly set the atom # map on the OE object as this is not handled by the OpenFF toolkit. oe_parent = parent.to_openeye() for atom in oe_parent.GetAtoms(): atom.SetMapIdx(get_map_index(parent, atom.GetIdx(), False)) oedepict.OEPrepareDepiction(oe_parent) oe_fragment = fragment.to_openeye() for atom in oe_fragment.GetAtoms(): atom.SetMapIdx(get_map_index(fragment, atom.GetIdx(), False)) oe_parent_bond = oe_parent.GetBond( oe_parent.GetAtom(oechem.OEHasMapIdx(bond_indices[0])), oe_parent.GetAtom(oechem.OEHasMapIdx(bond_indices[1])), ) # Set-up common display options. image = oedepict.OEImage(image_width, image_height) display_options = oedepict.OE2DMolDisplayOptions( image_width, image_height, oedepict.OEScale_AutoScale) display_options.SetTitleLocation(oedepict.OETitleLocation_Hidden) display_options.SetAtomColorStyle( oedepict.OEAtomColorStyle_WhiteMonochrome) display_options.SetAtomLabelFontScale(1.2) # display_options.SetBondPropertyFunctor(_oe_wbo_label_display({bond_indices})) display = oedepict.OE2DMolDisplay(oe_parent, display_options) fragment_atom_predicate, fragment_bond_predicate = _oe_fragment_predicates( {atom.GetMapIdx() for atom in oe_fragment.GetAtoms()}) not_fragment_atoms = oechem.OENotAtom(fragment_atom_predicate) not_fragment_bonds = oechem.OENotBond(fragment_bond_predicate) oedepict.OEAddHighlighting( display, oedepict.OEHighlightByColor(oechem.OEGrey, 0.75), not_fragment_atoms, not_fragment_bonds, ) rotatable_bond = oechem.OEAtomBondSet() rotatable_bond.AddBond(oe_parent_bond) rotatable_bond.AddAtom(oe_parent_bond.GetBgn()) rotatable_bond.AddAtom(oe_parent_bond.GetEnd()) oedepict.OEAddHighlighting( display, oechem.OEColor(oechem.OELimeGreen), oedepict.OEHighlightStyle_BallAndStick, rotatable_bond, ) oedepict.OERenderMolecule(image, display) svg_contents = oedepict.OEWriteImageToString("svg", image) return svg_contents.decode()
def OEAddHighlighting_AtomAndBondPredicate(disp): highlightstyle = oedepict.OEHighlightByBallAndStick(oechem.OELightGreen) oedepict.OEAddHighlighting(disp, highlightstyle, Pred6MemAromAtom(), Pred6MemAromBond())
grid.GetCellHeight(), oedepict.OEScale_AutoScale) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) refscale = oedepict.OEGetMoleculeScale(refmol, opts) fitscale = oedepict.OEGetMoleculeScale(fitmol, opts) opts.SetScale(min(refscale, fitscale)) refdisp = oedepict.OE2DMolDisplay(mcss.GetPattern(), opts) fitdisp = oedepict.OE2DMolDisplay(fitmol, opts) if alignres.IsValid(): refabset = oechem.OEAtomBondSet(alignres.GetPatternAtoms(), alignres.GetPatternBonds()) oedepict.OEAddHighlighting(refdisp, oechem.OEBlueTint, oedepict.OEHighlightStyle_BallAndStick, refabset) fitabset = oechem.OEAtomBondSet(alignres.GetTargetAtoms(), alignres.GetTargetBonds()) oedepict.OEAddHighlighting(fitdisp, oechem.OEBlueTint, oedepict.OEHighlightStyle_BallAndStick, fitabset) refcell = grid.GetCell(1, 1) oedepict.OERenderMolecule(refcell, refdisp) fitcell = grid.GetCell(1, 2) oedepict.OERenderMolecule(fitcell, fitdisp) oedepict.OEWriteImage("MCSAlign.png", image)
def OEAddHighlighting_OEMatch(disp): subs = oechem.OESubSearch("a1aaaaa1") unique = True for match in subs.Match(disp.GetMolecule(), unique): oedepict.OEAddHighlighting(disp, oechem.OEDarkGreen, oedepict.OEHighlightStyle_Color, match)
return False class BondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices) and (bond.GetEnd().GetIdx() in atom_indices) class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in atom_indices[1:3]) and (bond.GetEnd().GetIdx() in atom_indices[1:3]) atoms = mol.GetAtoms(AtomInTorsion()) bonds = mol.GetBonds(NoBond()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, abset) atoms = mol.GetAtoms(NoAtom()) bonds = mol.GetBonds(CentralBondInTorsion()) abset = oechem.OEAtomBondSet(atoms, bonds) oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEOrange), oedepict.OEHighlightStyle_BallAndStick, abset) oedepict.OERenderMolecule(cell, disp) #oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) oedepict.OEWriteReport(pdf_filename, report)
def OEAddHighlighting_OEAtomBondSet(disp): abset = oechem.OEAtomBondSet(mol.GetAtoms(Pred6MemAromAtom()), mol.GetBonds(Pred6MemAromBond())) oedepict.OEAddHighlighting(disp, oechem.OEDarkGreen, oedepict.OEHighlightStyle_Color, abset)
def visualize_bond_atom_sensitivity(mols, bonds, scores, fname, rows, cols, atoms=None, min_scale=True): """ Parameters ---------- mols : bonds : scores : fname : wbos : rows : cols : atoms : height : width : Returns ------- """ itf = oechem.OEInterface() ropts = oedepict.OEReportOptions(rows, cols) ropts.SetHeaderHeight(0.01) ropts.SetFooterHeight(0.01) ropts.SetCellGap(0.0001) ropts.SetPageMargins(0.01) report = oedepict.OEReport(ropts) cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight() opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_AutoScale) oedepict.OESetup2DMolDisplayOptions(opts, itf) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome) pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_Off, 0.9) opts.SetDefaultBondPen(pen) oedepict.OESetup2DMolDisplayOptions(opts, itf) if min_scale: minscale = float("inf") for m in mols: oedepict.OEPrepareDepiction(m, False, True) minscale = min(minscale, oedepict.OEGetMoleculeScale(m, opts)) opts.SetScale(minscale) for i, mol in enumerate(mols): cell = report.NewCell() oedepict.OEPrepareDepiction(mol, False, True) atom_bond_sets = [] for j, bond in enumerate(bonds[i]): bo = get_bond(mol, bond) atom_bond_set = oechem.OEAtomBondSet() atom_bond_set.AddBond(bo) atom_bond_sets.append(atom_bond_set) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) disp = oedepict.OE2DMolDisplay(mol, opts) hstyle = oedepict.OEHighlightStyle_Stick hstyle_2 = oedepict.OEHighlightStyle_Color score = scores[i] norm = plt.Normalize(0, max(score)) colors = plt.cm.coolwarm(norm(score)) colors_oe = [rbg_to_int(c, 200) for c in colors] for j, atom_bond_set in enumerate(atom_bond_sets): highlight = oechem.OEColor(*colors_oe[j]) oedepict.OEAddHighlighting(disp, highlight, hstyle, atom_bond_set) oedepict.OEAddHighlighting(disp, highlight, hstyle_2, atom_bond_set) highlight = oedepict.OEHighlightByCogwheel(oechem.OEDarkPurple) highlight.SetBallRadiusScale(5.0) if not atoms is None: for a_b in atoms[i]: if isinstance(a_b[-1], list): for k, c in enumerate(a_b[-1]): print(c) color = oechem.OEColor(*colors_oe[c]) highlight.SetBallRadiusScale(5.0 - 2.5 * k) highlight.SetColor(color) atom_bond_set_a = oechem.OEAtomBondSet() if len(a_b[0]) == 1: a = mol.GetAtom(oechem.OEHasMapIdx(a_b[0][0])) atom_bond_set_a.AddAtom(a) oedepict.OEAddHighlighting(disp, highlight, atom_bond_set_a) else: color = oechem.OEColor(*colors_oe[a_b[-1]]) highlight.SetColor(color) atom_bond_set_a = oechem.OEAtomBondSet() if len(a_b[0]) == 1: a = mol.GetAtom(oechem.OEHasMapIdx(a_b[0][0])) atom_bond_set_a.AddAtom(a) else: for b in itertools.combinations(a_b[0], 2): bo = get_bond(mol, b) if not bo: continue atom_bond_set_a.AddAtom(bo.GetBgn()) atom_bond_set_a.AddAtom(bo.GetEnd()) atom_bond_set_a.AddBond(bo) oedepict.OEAddHighlighting(disp, highlight, atom_bond_set_a) oedepict.OERenderMolecule(cell, disp) # oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) return oedepict.OEWriteReport(fname, report)
def OEAddHighlighting_OESubSearch(disp): subsearch = oechem.OESubSearch("a1aaaaa1") oedepict.OEAddHighlighting(disp, oechem.OEDarkGreen, oedepict.OEHighlightStyle_Color, subsearch)
def visualize_mols(smiles, fname, rows, cols, bond_idx, wbos, colors, align_to=0): """ Visualize molecules with highlighted bond and labeled with WBO Parameters ---------- smiles : list of SMILES to visualize. bond atoms should have map indices fname : str filename rows : int cols : int bond_idx : tuple of atom maps of bond to highlight. wbos : list of floats colors : list of hex values for colors align_to: int, optional, default 0 index for which molecule to align to. If zero, will align to first molecules in SMILES list """ itf = oechem.OEInterface() ropts = oedepict.OEReportOptions(rows, cols) ropts.SetHeaderHeight(25) ropts.SetFooterHeight(25) ropts.SetCellGap(2) ropts.SetPageMargins(10) report = oedepict.OEReport(ropts) cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight() opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_AutoScale) oedepict.OESetup2DMolDisplayOptions(opts, itf) # align to chosen molecule ref_mol = oechem.OEGraphMol() oechem.OESmilesToMol(ref_mol, smiles[align_to]) oedepict.OEPrepareDepiction(ref_mol) mols = [] minscale = float("inf") for s in smiles: mol = oechem.OEMol() oechem.OESmilesToMol(mol, s) mols.append(mol) oedepict.OEPrepareDepiction(mol, False, True) minscale = min(minscale, oedepict.OEGetMoleculeScale(mol, opts)) print(minscale) print(minscale) opts.SetScale(minscale) for i, mol in enumerate(mols): cell = report.NewCell() oedepict.OEPrepareDepiction(mol, False, True) bond = get_bond(mol, bond_idx) atom_bond_set = oechem.OEAtomBondSet() atom_bond_set.AddAtoms([bond.GetBgn(), bond.GetEnd()]) atom_bond_set.AddBond(bond) hstyle = oedepict.OEHighlightStyle_BallAndStick hcolor = oechem.OEColor(*colors[i]) overlaps = oegraphsim.OEGetFPOverlap( ref_mol, mol, oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree)) oedepict.OEPrepareMultiAlignedDepiction(mol, ref_mol, overlaps) #opts.SetBondPropLabelFontScale(4.0) disp = oedepict.OE2DMolDisplay(mol, opts) oedepict.OEAddHighlighting(disp, hcolor, hstyle, atom_bond_set) #font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Bold, 12, # oedepict.OEAlignment_Default, oechem.OEBlack) bond_label = oedepict.OEHighlightLabel("{:.2f}".format((wbos[i])), hcolor) bond_label.SetFontScale(1.4) #bond_label.SetFont(font) oedepict.OEAddLabel(disp, bond_label, atom_bond_set) oedepict.OERenderMolecule(cell, disp) # oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0) return (oedepict.OEWriteReport(fname, report))
def main(argv=[__name__]): itf = oechem.OEInterface(InterfaceData) oedepict.OEConfigureImageOptions(itf) oedepict.OEConfigurePrepareDepictionOptions(itf) oedepict.OEConfigure2DMolDisplayOptions(itf) oedepict.OEConfigureHighlightParams(itf) if not oechem.OEParseCommandLine(itf, argv): oechem.OEThrow.Fatal("Unable to interpret command line!") iname = itf.GetString("-in") oname = itf.GetString("-out") ext = oechem.OEGetFileExtension(oname) if not oedepict.OEIsRegisteredImageFile(ext): oechem.OEThrow.Fatal("Unknown image type!") ifs = oechem.oemolistream() if not ifs.open(iname): oechem.OEThrow.Fatal("Cannot open input file!") ofs = oechem.oeofstream() if not ofs.open(oname): oechem.OEThrow.Fatal("Cannot open output file!") mol = oechem.OEGraphMol() if not oechem.OEReadMolecule(ifs, mol): oechem.OEThrow.Fatal("Cannot read input file!") smarts = itf.GetString("-smarts") ss = oechem.OESubSearch() if not ss.Init(smarts): oechem.OEThrow.Fatal("Cannot parse smarts: %s" % smarts) popts = oedepict.OEPrepareDepictionOptions() oedepict.OESetupPrepareDepictionOptions(popts, itf) oedepict.OEPrepareDepiction(mol, popts) width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight( itf) dopts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) oedepict.OESetup2DMolDisplayOptions(dopts, itf) dopts.SetMargins(10.0) disp = oedepict.OE2DMolDisplay(mol, dopts) hstyle = oedepict.OEGetHighlightStyle(itf) hcolor = oedepict.OEGetHighlightColor(itf) oechem.OEPrepareSearch(mol, ss) unique = True for match in ss.Match(mol, unique): oedepict.OEAddHighlighting(disp, hcolor, hstyle, match) oedepict.OERenderMolecule(ofs, ext, disp) return 0