def Draw2DSurfacePartialCharge(image, mol): oedepict.OEPrepareDepiction(mol) oechem.OEMMFFAtomTypes(mol) oechem.OEMMFF94PartialCharges(mol) opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(), oedepict.OEScale_AutoScale) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts)) coloranion = oechem.OEColorStop(-1.0, oechem.OEColor(oechem.OEDarkRed)) colorcation = oechem.OEColorStop(+1.0, oechem.OEColor(oechem.OEDarkBlue)) colorg = oechem.OELinearColorGradient(coloranion, colorcation) colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEColor(oechem.OEWhite))) arcfxn = AtomPartialChargeArcFxn(colorg) for atom in mol.GetAtoms(): oegrapheme.OESetSurfaceArcFxn(mol, atom, arcfxn) disp = oedepict.OE2DMolDisplay(mol, opts) oegrapheme.OEDraw2DSurface(disp) oedepict.OERenderMolecule(image, disp)
def draw_dihedral_circle(image, center, radius, nrbins, nrconfs): """ Draws the base radial histogram. :type image: oedepict.OEImageBase :type center: oedepict.OE2DPoint :type radius: float :type nrbins: int :type nrconfs: int """ grey = oechem.OEColor(210, 210, 210) pen = oedepict.OEPen(grey, grey, oedepict.OEFill_On, 1.0) image.DrawCircle(center, radius, pen) linegrey = oechem.OEColor(220, 220, 220) linepen = oedepict.OEPen(linegrey, linegrey, oedepict.OEFill_On, 1.0) angleinc = 360.0 / float(nrbins) v = oedepict.OE2DPoint(0.0, -1.0) for i in range(0, nrbins): end = oedepict.OELengthenVector( oedepict.OERotateVector(v, i * angleinc), radius) image.DrawLine(center, center + end, linepen) fontsize = int(math.floor(radius * 0.1)) font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Bold, fontsize, oedepict.OEAlignment_Center, oechem.OEBlack) for i in range(0, 4): angle = i * 90.0 end = oedepict.OELengthenVector(oedepict.OERotateVector(v, angle), radius * 1.20) text = '{:.1f}'.format(angle) dim = radius / 2.5 textframe = oedepict.OEImageFrame( image, dim, dim, center + end - oedepict.OE2DPoint(dim / 2.0, dim / 2.0)) oedepict.OEDrawTextToCenter(textframe, text, font) minradius = radius / 3.0 whitepen = oedepict.OEPen(oechem.OEWhite, oechem.OEWhite, oedepict.OEFill_On, 1.0, oedepict.OEStipple_NoLine) image.DrawCircle(center, minradius, whitepen) font.SetSize(int(fontsize * 1.5)) top = oedepict.OE2DPoint(image.GetWidth() / 2.0, -10.0) image.DrawText(top, 'torsion histogram', font) top = oedepict.OE2DPoint(image.GetWidth() / 2.0, -30.0) image.DrawText(top, 'MM: blue; ANI: red', font) bottom = oedepict.OE2DPoint(image.GetWidth() / 2.0, image.GetHeight() + 26.0) image.DrawText(bottom, 'number of conformations: {}'.format(nrconfs), font)
def SetProteinLigandVizStyle(protein, ligand, carbonRGB=(180, 180, 180)): # set the carbon color (and phosphorus to magenta) carbonColor = oechem.OEColor(carbonRGB[0], carbonRGB[1], carbonRGB[2]) acolorer = oechem.OEMolStyleColorer(oechem.OEAtomColorScheme_Element) acolorer.AddColor(15, oechem.OEMagenta) acolorer.AddColor(6, carbonColor) # make the protein style object protein_style = oechem.OE3DMolStyle() protein_style.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Polar) protein_style.SetAtomStyle(oechem.OEAtomStyle_Hidden) protein_style.SetProteinStyle(oechem.OEProteinStyle_Ribbons) protein_style.SetProteinColorer( oechem.OEMolStyleColorer(oechem.OEProteinColorScheme_AtomColor)) protein_style.SetAtomColorer(acolorer) # make the active site style object asite_style = oechem.OE3DMolStyle() asite_style.SetAtomStyle(oechem.OEAtomStyle_Wireframe) # make the ligand style object ligand_style = oechem.OE3DMolStyle() ligand_style.SetAtomStyle(oechem.OEAtomStyle_Stick) ligand_style.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Polar) ligand_style.SetAtomColorer(acolorer) # now color the protein and the ligand oechem.OEClearStyle(protein) oechem.OESetStyle(protein, protein_style) oechem.OEClearStyle(ligand) oechem.OESetStyle(ligand, ligand_style) # display binding site residues asitePred = oechem.OEAtomMatchResidue(protein, ligand, 5) for atom in protein.GetAtoms(asitePred): oechem.OEClearStyle(atom) oechem.OESetStyle(atom, asite_style) return
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 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 HighlightCell(cell, idx): font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 10, oedepict.OEAlignment_Center, oechem.OEBlack) color = oechem.OEColor(oechem.OELightGrey) borderpen = oedepict.OEPen(color, color, oedepict.OEFill_On, 1.0) oedepict.OEDrawBorder(cell, borderpen) p = oedepict.OE2DPoint(cell.GetWidth() / 2.0, cell.GetHeight() / 2.0 + font.GetSize() / 2.0) cell.DrawText(p, "(%d)" % idx, font)
def RenderGlyph(self, disp, atom): adisp = disp.GetAtomDisplay(atom) if adisp is None or not adisp.IsVisible(): return False charge = atom.GetPartialCharge() if charge == 0.0: return True color = self.colorg.GetColorAt(charge) pen = oedepict.OEPen() pen.SetForeColor(oechem.OEColor(color)) color.SetA(100) pen.SetBackColor(oechem.OEColor(color)) pen.SetFill(oedepict.OEFill_On) radius = disp.GetScale() / 2.5 layer = disp.GetLayer(oedepict.OELayerPosition_Below) oegrapheme.OEDrawCircle(layer, oegrapheme.OECircleStyle_Simpson, adisp.GetCoords(), radius, pen) return True
def HighlightStyleMolecule(mol): hiliteColorer = oechem.OEMolStyleColorer(oechem.OEAtomColorScheme_Element) hiliteCarbonColor = oechem.OEColor(245, 210, 150) hiliteColorer.AddColor(6, hiliteCarbonColor) hiliteColorer.AddColor(15, oechem.OEMagenta) # hiliteConfStyle = oechem.OE3DMolStyle() hiliteConfStyle.SetAtomStyle(oechem.OEAtomStyle_Stick) hiliteConfStyle.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Polar) hiliteConfStyle.SetAtomColorer(hiliteColorer) # oechem.OEClearStyle(mol) oechem.OESetStyle(mol, hiliteConfStyle) return
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 generate_molecule_images(fragments_dict, name, colors, parent_mol): for i, b in enumerate(fragments_dict): to_plot = [] wbos = [] sorted_frags = sort_fragments(fragments_dict[b]) for f in sorted_frags: smiles = fragments_dict[b][f]['map_to_parent'] mol = oechem.OEMol() oechem.OESmilesToMol(mol, smiles) mol.SetTitle(str(fragments_dict[b][f]['mmd_exp'])) to_plot.append(mol) wbos.append(fragments_dict[b][f]['elf_estimate']) int_colors = [rbg_to_int(rbg, alpha=150) for rbg in colors[i]] colors_oe = [oechem.OEColor(*j) for j in int_colors] fname = 'validation_set/{}/{}_bond_{}_{}_aligned.pdf'.format( name, name, str(b[0]), str(b[1])) chemi.to_pdf(to_plot, fname, rows=3, cols=3, bond_map_idx=b, bo=wbos, color=colors_oe, align=to_plot[0]) fname = 'validation_set/{}/{}_bond_{}_{}_aligned_to_parent.pdf'.format( name, name, str(b[0]), str(b[1])) chemi.to_pdf(to_plot, fname, rows=3, cols=3, bond_map_idx=b, bo=wbos, color=colors_oe, align=parent_mol) fname = 'validation_set/{}/{}_bond_{}_{}_no_alignemnet.pdf'.format( name, name, str(b[0]), str(b[1])) chemi.to_pdf(to_plot, fname, rows=3, cols=3, bond_map_idx=b, bo=wbos, color=colors_oe)
def _create_openeye_pdf(molecules: List[Molecule], file_name: str, columns: int): """Make the pdf of the molecules using OpenEye.""" from openeye import oechem, oedepict itf = oechem.OEInterface() suppress_h = True rows = 10 cols = columns 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) # now we load the molecules for off_mol in molecules: off_mol = copy.deepcopy(off_mol) off_mol._conformers = [] off_mol.name = None cell = report.NewCell() mol = off_mol.to_openeye() oedepict.OEPrepareDepiction(mol, False, suppress_h) disp = oedepict.OE2DMolDisplay(mol, opts) if "dihedrals" in off_mol.properties: # work out if we have a double or single torsion if len(off_mol.properties["dihedrals"]) == 1: dihedrals = off_mol.properties["dihedrals"][0] center_bonds = dihedrals[1:3] else: # double torsion case dihedrals = [ *off_mol.properties["dihedrals"][0], *off_mol.properties["dihedrals"][1], ] center_bonds = [ *off_mol.properties["dihedrals"][0][1:3], *off_mol.properties["dihedrals"][1][1:3], ] # 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 dihedrals class NoBond(oechem.OEUnaryBondPred): def __call__(self, bond): return False class CentralBondInTorsion(oechem.OEUnaryBondPred): def __call__(self, bond): return (bond.GetBgn().GetIdx() in center_bonds) and (bond.GetEnd().GetIdx() in center_bonds) 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.OEWriteReport(file_name, report)
frag_sizes = [n_heavy_atoms(s)**3 for s in sorted_map_to_parent] front = plot_pareto_frontier(sorted_scores, frag_sizes, maxX=False, maxY=False, indices=indices, parent_idx=7, filename='pareto_front.pdf') # Prepare data for molecules to visualize to_plot = [] wbos = [] smiles_to_plot = [] for i in indices: f = sorted_frags[i] map_to_parent = sorted_map_to_parent[i] smiles_to_plot.append(map_to_parent) wbos.append(wbos_des[(35, 14)][f]['ensamble']) int_colors = [rbg_to_int(rbg, alpha=250) for rbg in highlights[0]] colors_oe = [oechem.OEColor(*int_colors[j]) for j in indices] visualize_mols(smiles_to_plot, 'fragments.pdf', rows=3, cols=2, wbos=wbos, colors=colors_oe, bond_idx=(35, 14), align_to=6)
# @ <SNIPPET-OE2DMOLDISPLAY-OPTIONS-AROMATIC-STYLE> width, height, scale = 300.0, 200.0, oedepict.OEScale_AutoScale opts = oedepict.OE2DMolDisplayOptions(width, height, scale) opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle) # @ </SNIPPET-OE2DMOLDISPLAY-OPTIONS-AROMATIC-STYLE> DepictMolecules(opts, smiles, "OE2DMolDisplayOptions_SetAromaticStyle") ######################################################################## # ATOM ######################################################################## # @ <SNIPPET-OE2DMOLDISPLAY-OPTIONS-ATOM-COLOR> width, height, scale = 300.0, 200.0, oedepict.OEScale_AutoScale opts = oedepict.OE2DMolDisplayOptions(width, height, scale) opts.SetAtomColor(oechem.OEElemNo_O, oechem.OEColor(80, 0, 0)) # very dark red opts.SetAtomColor(oechem.OEElemNo_N, oechem.OEColor(0, 0, 80)) # very dark blue # @ </SNIPPET-OE2DMOLDISPLAY-OPTIONS-ATOM-COLOR> DepictMolecules(opts, smiles, "OE2DMolDisplayOptions_SetAtomColor") # @ <SNIPPET-OE2DMOLDISPLAY-OPTIONS-ATOM-COLOR-STYLE> width, height, scale = 300.0, 200.0, oedepict.OEScale_AutoScale opts = oedepict.OE2DMolDisplayOptions(width, height, scale) opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_BlackMonochrome) # @ </SNIPPET-OE2DMOLDISPLAY-OPTIONS-ATOM-COLOR-STYLE> DepictMolecules(opts, smiles, "OE2DMolDisplayOptions_SetAtomColorStyle") # @ <SNIPPET-OE2DMOLDISPLAY-OPTIONS-ATOM-LABEL-FONT> width, height, scale = 300.0, 200.0, oedepict.OEScale_AutoScale opts = oedepict.OE2DMolDisplayOptions(width, height, scale)
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 highltigh_torsion_by_cluster(mapped_molecule, clustered_dihedrals, fname, width=600, height=400): """ Highlight torsion by cluster. This is used to visualize clustering output. Parameters ---------- mapped_molecule: oemol with map indices clustered_dihedrals fname width height Returns ------- """ mol = oechem.OEMol(mapped_molecule) atom_bond_sets = [] for cluster in clustered_dihedrals: atom_bond_set = oechem.OEAtomBondSet() for dihedral in clustered_dihedrals[cluster]: a = mol.GetAtom(oechem.OEHasMapIdx(dihedral[0] + 1)) atom_bond_set.AddAtom(a) for idx in dihedral[1:]: a2 = mol.GetAtom(oechem.OEHasMapIdx(idx + 1)) atom_bond_set.AddAtom(a2) bond = mol.GetBond(a, a2) atom_bond_set.AddBond(bond) a = a2 atom_bond_sets.append(atom_bond_set) dopt = oedepict.OEPrepareDepictionOptions() dopt.SetSuppressHydrogens(False) oedepict.OEPrepareDepiction(mol, dopt) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) disp = oedepict.OE2DMolDisplay(mol, opts) aroStyle = oedepict.OEHighlightStyle_Color aroColor = oechem.OEColor(oechem.OEBlack) oedepict.OEAddHighlighting(disp, aroColor, aroStyle, oechem.OEIsAromaticAtom(), oechem.OEIsAromaticBond()) hstyle = oedepict.OEHighlightStyle_BallAndStick # if color: # highlight = oechem.OEColor(color) # # combine all atom_bond_sets # atom_bond_set = oechem.OEAtomBondSet() # for ab_set in atom_bond_sets: # for a in ab_set.GetAtoms(): # atom_bond_set.AddAtom(a) # for b in ab_set.GetBonds(): # atom_bond_set.AddBond(b) # oedepict.OEAddHighlighting(disp, highlight, hstyle, atom_bond_set) # else: highlight = oedepict.OEHighlightOverlayByBallAndStick( oechem.OEGetContrastColors()) oedepict.OEAddHighlightOverlay(disp, highlight, atom_bond_sets) #hcolor = oechem.OEColor(oechem.OELightBlue) #oedepict.OEAddHighlighting(disp, hcolor, hstyle, atom_bond_sets) return oedepict.OERenderMolecule(fname, disp)
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)
oedepict.OEAlignment_Center, oechem.OEDarkRed) label = oedepict.OEHighlightLabel('match', font) # @ </SNIPPET-OEHIGHLIGHTLABEL-FONT> DepictMoleculesWithLabel(smiles, ss, highlight, label, "OEHighlightLabel_Font") # @ <SNIPPET-OEHIGHLIGHTLABEL-SETFONT> label = oedepict.OEHighlightLabel('match') font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 12, oedepict.OEAlignment_Center, oechem.OEDarkRed) label.SetFont(font) # @ </SNIPPET-OEHIGHLIGHTLABEL-SETFONT> DepictMoleculesWithLabel(smiles, ss, highlight, label, "OEHighlightLabel_SetFont") # @ <SNIPPET-OEHIGHLIGHTLABEL-SETBOUNDINGBOXPEN> label = oedepict.OEHighlightLabel('match') pen = oedepict.OEPen(oechem.OEColor(255, 220, 220), oechem.OEDarkRed, oedepict.OEFill_On, 16.0, oedepict.OEStipple_ShortDash) label.SetBoundingBoxPen(pen) # @ </SNIPPET-OEHIGHLIGHTLABEL-SETBOUNDINGBOXPEN> DepictMoleculesWithLabel(smiles, ss, highlight, label, "OEHighlightLabel_SetBoundingBoxPen") # @ <SNIPPET-OEHIGHLIGHTLABEL-SETFONTSCALE> label = oedepict.OEHighlightLabel('match') label.SetFontScale(1.2) # @ </SNIPPET-OEHIGHLIGHTLABEL-SETFONTSCALE> DepictMoleculesWithLabel(smiles, ss, highlight, label, "OEHighlightLabel_SetFontScale")
def highlight_bonds(mol_copy, fname, conjugation=True, rotor=False, width=600, height=400, label=None): """ Generate image of molecule with highlighted bonds. The bonds can either be highlighted with a conjugation tag or if it is rotatable. Parameters ---------- mol_copy: OEMol fname: str Name of image file conjugation: Bool, optional, Default is True If True, the bonds with conjugation tag set to True will be highlighted rotor: Bool, optional, Default is False If True, the rotatable bonds will be highlighted. width: int height: int label: string. Optional, Default is None The bond order label. The options are WibergBondOrder, Wiberg_psi4, Mayer_psi4. """ mol = oechem.OEMol(mol_copy) bond_index_list = [] for bond in mol.GetBonds(): if conjugation: try: if bond.GetData('conjugated'): bond_index_list.append(bond.GetIdx()) except ValueError: pass if rotor: if bond.IsRotor(): bond_index_list.append(bond.GetIdx()) atomBondSet = oechem.OEAtomBondSet() for bond in mol.GetBonds(): if bond.GetIdx() in bond_index_list: atomBondSet.AddBond(bond) atomBondSet.AddAtom(bond.GetBgn()) atomBondSet.AddAtom(bond.GetEnd()) dopt = oedepict.OEPrepareDepictionOptions() dopt.SetSuppressHydrogens(True) oedepict.OEPrepareDepiction(mol, dopt) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) if label is not None: bond_label = { 'WibergBondOrder': LabelWibergBondOrder, 'Wiberg_psi4': LabelWibergPsiBondOrder, 'Mayer_psi4': LabelMayerPsiBondOrder } bondlabel = bond_label[label] opts.SetBondPropertyFunctor(bondlabel()) disp = oedepict.OE2DMolDisplay(mol, opts) aroStyle = oedepict.OEHighlightStyle_Color aroColor = oechem.OEColor(oechem.OEBlack) oedepict.OEAddHighlighting(disp, aroColor, aroStyle, oechem.OEIsAromaticAtom(), oechem.OEIsAromaticBond()) hstyle = oedepict.OEHighlightStyle_BallAndStick hcolor = oechem.OEColor(oechem.OELightBlue) oedepict.OEAddHighlighting(disp, hcolor, hstyle, atomBondSet) return oedepict.OERenderMolecule(fname, disp)
suppress_h = True rows = 10 cols = 6 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 _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 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)
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)
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 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 show_oemol_struc(oemol, torsions=False, atom_indices=[]): """ Returns the oedepict image with or without the torsion highlighted Parameters ---------- oemol: openeye oechem mol object torsions: boolean, to highlight dihedrals atom_indices: dihedral atom indices to highlight Returns ------- Image: image in png format """ from IPython.display import Image from openeye import oechem, oedepict width = 400 height = 300 # 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 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)
def highlight_torsion(mapped_molecule, dihedrals, fname, width=600, height=400, combine_central_bond=True, color=None): mol = oechem.OEMol(mapped_molecule) atom_bond_sets = [] if combine_central_bond: central_bonds = [(tor[1], tor[2]) for tor in dihedrals] eq_torsions = { cb: [ tor for tor in dihedrals if cb == (tor[1], tor[2]) or cb == (tor[2], tor[1]) ] for cb in central_bonds } for cb in eq_torsions: atom_bond_set = oechem.OEAtomBondSet() for dihedral in eq_torsions[cb]: a = mol.GetAtom(oechem.OEHasMapIdx(dihedral[0] + 1)) atom_bond_set.AddAtom(a) for idx in dihedral[1:]: a2 = mol.GetAtom(oechem.OEHasMapIdx(idx + 1)) atom_bond_set.AddAtom((a2)) bond = mol.GetBond(a, a2) atom_bond_set.AddBond(bond) a = a2 atom_bond_sets.append(atom_bond_set) if not combine_central_bond: for dihedral in dihedrals: atom_bond_set = oechem.OEAtomBondSet() a = mol.GetAtom(oechem.OEHasMapIdx(dihedral[0] + 1)) atom_bond_set.AddAtom(a) for idx in dihedral[1:]: a2 = mol.GetAtom(oechem.OEHasMapIdx(idx + 1)) atom_bond_set.AddAtom((a2)) bond = mol.GetBond(a, a2) atom_bond_set.AddBond(bond) a = a2 atom_bond_sets.append(atom_bond_set) dopt = oedepict.OEPrepareDepictionOptions() dopt.SetSuppressHydrogens(False) oedepict.OEPrepareDepiction(mol, dopt) opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale) opts.SetTitleLocation(oedepict.OETitleLocation_Hidden) disp = oedepict.OE2DMolDisplay(mol, opts) aroStyle = oedepict.OEHighlightStyle_Color aroColor = oechem.OEColor(oechem.OEBlack) oedepict.OEAddHighlighting(disp, aroColor, aroStyle, oechem.OEIsAromaticAtom(), oechem.OEIsAromaticBond()) hstyle = oedepict.OEHighlightStyle_BallAndStick if color: highlight = oechem.OEColor(color) # combine all atom_bond_sets atom_bond_set = oechem.OEAtomBondSet() for ab_set in atom_bond_sets: for a in ab_set.GetAtoms(): atom_bond_set.AddAtom(a) for b in ab_set.GetBonds(): atom_bond_set.AddBond(b) oedepict.OEAddHighlighting(disp, highlight, hstyle, atom_bond_set) else: highlight = oedepict.OEHighlightOverlayByBallAndStick( oechem.OEGetContrastColors()) oedepict.OEAddHighlightOverlay(disp, highlight, atom_bond_sets) #hcolor = oechem.OEColor(oechem.OELightBlue) #oedepict.OEAddHighlighting(disp, hcolor, hstyle, atom_bond_sets) return oedepict.OERenderMolecule(fname, disp)
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))
'palevioletred', 'lightpink'] colors = mcolors.CSS4_COLORS #color=cm.rainbow_r(np.linspace(0,1,len(fgroups_smarts))) #color = chemi._KELLYS_COLORS def get_rgb_int(rgb, alpha): return (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255), int(rgb[3]*alpha)) fgroups_wbos = {} for i, fgroup in enumerate(fgroups_smarts): print(fgroup) wbo_dict = group_by_fgroup_and_wbo(fgroup, all_mols) fgroups_wbos[fgroup] = wbo_dict mols, bond_maps, wbos = prep_mols_for_vis(wbo_dict, fgroup=fgroup) #c = get_rgb_int(color[i], alpha=180) c_oe = oechem.OEColor(colors[color_keys[i]]) chemi.to_pdf(molecules=mols, bond_map_idx=bond_maps, bo=wbos, align=mols[0], color=c_oe, fname='figures/oe_wbos/{}.pdf'.format(fgroup)) # Save WBOs to_save = [[wbo, mol.GetTitle(), oechem.OEMolToSmiles(mol)] for wbo, mol in zip(wbos, mols)] with open('data/{}_R1_wbos.json'.format(fgroup), 'w') as f: json.dump(to_save, f, indent=2, sort_keys=True) # Generate joy plot fig, axes = plt.subplots(len(fgroups_wbos)) for i, fgroup in enumerate(fgroups_wbos): ax = plt.subplot(len(fgroups_wbos), 1, i+1) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)