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 CombineAndConnectAtomBondSets(fraglist): """ This function was taken from OpeneEye Cookbook https://docs.eyesopen.com/toolkits/cookbook/python/cheminfo/enumfrags.html """ # combine atom and bond sets combined = oechem.OEAtomBondSet() for frag in fraglist: for atom in frag.GetAtoms(): combined.AddAtom(atom) for bond in frag.GetBonds(): combined.AddBond(bond) # add connecting bonds for atomA in combined.GetAtoms(): for atomB in combined.GetAtoms(): if atomA.GetIdx() < atomB.GetIdx(): continue bond = atomA.GetBond(atomB) if bond is None: continue if combined.HasBond(bond): continue combined.AddBond(bond) return combined
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 CombineAndConnectAtomBondSets(fraglist): # combine atom and bond sets combined = oechem.OEAtomBondSet() for frag in fraglist: for atom in frag.GetAtoms(): combined.AddAtom(atom) for bond in frag.GetBonds(): combined.AddBond(bond) # add connecting bonds for atomA in combined.GetAtoms(): for atomB in combined.GetAtoms(): if atomA.GetIdx() < atomB.GetIdx(): continue bond = atomA.GetBond(atomB) if bond is None: continue if combined.HasBond(bond): continue combined.AddBond(bond) return combined
def OEAddHighlighting_OEAtomBondSet(adisp): ligand = adisp.GetDisplayedLigand() highlight = oedepict.OEHighlightByCogwheel(oechem.OEPinkTint) highlight.SetInnerContour(False) abset = oechem.OEAtomBondSet(ligand.GetAtoms(Pred6MemAromAtom()), ligand.GetBonds(Pred6MemAromBond())) oegrapheme.OEAddLigandHighlighting(adisp, highlight, abset)
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 get_dihedral(mol, dihedralAtomIndices): """Get the dihedral corresponding to the indices in dihedralAtomIndices. Note that the indices are zero-indexed. The torsion of interest is the bond between atoms with indices 1 and 2. """ # dihedralAtomIndices = [int(x) for x in get_sd_data(mol, 'TORSION_ATOMS_FRAGMENT').split()] dih = oechem.OEAtomBondSet() tor = oechem.OEAtomBondSet() for i in range(3): srcIdx = dihedralAtomIndices[i] destIdx = dihedralAtomIndices[i + 1] src = mol.GetAtom(oechem.OEHasAtomIdx(srcIdx)) dest = mol.GetAtom(oechem.OEHasAtomIdx(destIdx)) dih.AddAtom(src) bond = mol.GetBond(src, dest) dih.AddBond(bond) if i == 1: tor.AddBond(bond) dih.AddAtom(dest) return dih, tor
def to_atom_bond_set(oemol, atoms, bonds): from openeye import oechem atom_bond_set = oechem.OEAtomBondSet() for a_idx in atoms: atom = oemol.GetAtom(oechem.OEHasAtomIdx(a_idx)) atom_bond_set.AddAtom(atom) for b_tuple in bonds: a1 = oemol.GetAtom(oechem.OEHasAtomIdx(b_tuple[0])) a2 = oemol.GetAtom(oechem.OEHasAtomIdx(b_tuple[-1])) bond = oemol.GetBond(a1, a2) if not bond: raise ValueError("{} is a disconnected bond".format(b_tuple)) atom_bond_set.AddBond(bond) return atom_bond_set
def GetFuncGroups(mol): ''' :param mol: :return: ''' funcGrps = [] for funcGrp in oemedchem.OEGetFuncGroupFragments(mol): if oechem.OECount(funcGrp, oechem.OEIsHeavy()) > 5: continue if oechem.OECount(funcGrp, oechem.OEIsHetero()) == 0: continue if oechem.OECount(funcGrp, oechem.OEAtomIsInRing()) > 0: continue funcGrps.append(oechem.OEAtomBondSet(funcGrp)) return funcGrps
def _to_AtomBondSet(mol, atoms, bonds): """ Builds OpeneyeAtomBondet from atoms and bonds set of indices Parameters ---------- mol: Openeye OEMolGraph atoms: Set of atom indices bonds: Set of bond indices Returns ------- AtomBondSet: Openeye AtomBondSet of fragment """ AtomBondSet = oechem.OEAtomBondSet() for a_idx in atoms: AtomBondSet.AddAtom(mol.GetAtom(oechem.OEHasAtomIdx(a_idx))) for b_idx in bonds: AtomBondSet.AddBond(mol.GetBond(oechem.OEHasBondIdx(b_idx))) return AtomBondSet
def subgraphToAtomBondSet(graph, subgraph, oemol): """ Build Openeye AtomBondSet from subrgaphs for enumerating fragments recipe Parameters ---------- graph: NetworkX graph subgraph: NetworkX subgraph oemol: Openeye OEMolGraph Returns ------ atomBondSet: Openeye oechem atomBondSet """ # Build openeye atombondset from subgraphs atomBondSet = oechem.OEAtomBondSet() for node in subgraph.node: atomBondSet.AddAtom(oemol.GetAtom(oechem.OEHasAtomIdx(node))) for node1, node2 in subgraph.edges(): index = graph.edge[node1][node2]['index'] atomBondSet.AddBond(oemol.GetBond(oechem.OEHasBondIdx(index))) return atomBondSet
def depict_dihedrals(image, dimage, mol1, mol2, refmol, opts, itag, nrbins, colorg): """ Highlights the dihedral atoms of a torsion and the depicts the corresponding dihedral angle histogram when hovering over the center of the torsion on the molecule display. :type image: oedepict.OEImageBase :type dimage: oedepict.OEImageBase :type mol: oechem.OEMol :type refmol: oechem.OEMol :type opts: oedepict.OE2DMolDisplayOptions :type itag: int :type nrbins: int :type oechem.OEColorGradientBase """ nrconfs = mol1.NumConfs() center = oedepict.OEGetCenter(dimage) radius = min(dimage.GetWidth(), dimage.GetHeight()) * 0.40 draw_dihedral_circle(dimage, center, radius, nrbins, nrconfs) suppressH = True oegrapheme.OEPrepareDepictionFrom3D(mol1, suppressH) if refmol is not None: oegrapheme.OEPrepareDepictionFrom3D(refmol, suppressH) disp = oedepict.OE2DMolDisplay(mol1, opts) dihedrals = [] ref_dihedrals = [] centers = [] agroups = [] dgroups = [] dihedrals_ref_dist = [] for group in mol2.GetGroups(oechem.OEHasGroupType(itag)): dihedrals_ref_dist.append(group) nrdihedrals = 0 for group in mol1.GetGroups(oechem.OEHasGroupType(itag)): uniqueid = uuid.uuid4().hex agroup = image.NewSVGGroup("torsion_area_" + uniqueid) dgroup = image.NewSVGGroup("torsion_data_" + uniqueid) oedepict.OEAddSVGHover(agroup, dgroup) dihedrals.append(group) if refmol is not None: ref_dihedrals.append(get_reference_dihedral(group, refmol, itag)) centers.append(get_center(disp, group)) agroups.append(agroup) dgroups.append(dgroup) nrdihedrals += 1 for didx in range(0, nrdihedrals): image.PushGroup(dgroups[didx]) dihedral = dihedrals[didx] abset = oechem.OEAtomBondSet(dihedral.GetAtoms(), dihedral.GetBonds()) draw_highlight(image, disp, abset) dihedral_histogram = dihedral.GetData(itag) dihedral_histogram_ref = dihedrals_ref_dist[didx].GetData(itag) print(dihedral_histogram) print(dihedral_histogram_ref) draw_dihedral_histogram(dimage, dihedral_histogram, dihedral_histogram_ref, center, radius, nrbins, nrconfs) image.PopGroup(dgroups[didx]) clearbackground = True oedepict.OERenderMolecule(image, disp, not clearbackground) markpen = oedepict.OEPen(oechem.OEBlack, oechem.OEWhite, oedepict.OEFill_On, 1.0) farpen = oedepict.OEPen(oechem.OEBlack, oechem.OERed, oedepict.OEFill_Off, 2.0) angleinc = 360.0 / float(nrbins) for didx in range(0, nrdihedrals): image.PushGroup(agroups[didx]) dihedral = dihedrals[didx] dihedral_histogram = dihedral.GetData(itag) flexibility = determine_flexibility(dihedral_histogram) color = colorg.GetColorAt(flexibility) markpen.SetBackColor(color) markradius = disp.GetScale() / 8.0 image.DrawCircle(centers[didx], markradius, markpen) if refmol is not None and ref_dihedrals[didx] is not None: ref_dihedral = ref_dihedrals[didx] if get_closest_dihedral_angle(mol1, dihedral, ref_dihedral, itag) > angleinc: image.DrawCircle(centers[didx], markradius, farpen) radius = disp.GetScale() / 4.0 image.DrawCircle(centers[didx], radius, oedepict.OESVGAreaPen) image.PopGroup(agroups[didx])
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 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 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 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)
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 OEAddHighlighting_OEAtomBondSet(disp): abset = oechem.OEAtomBondSet(mol.GetAtoms(Pred6MemAromAtom()), mol.GetBonds(Pred6MemAromBond())) oedepict.OEAddHighlighting(disp, oechem.OEDarkGreen, oedepict.OEHighlightStyle_Color, abset)
grid = oedepict.OEImageGrid(image, rows, cols) opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), 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)
def applyffExcipients(excipients, opt): """ This function applies the selected force field to the excipients Parameters: ----------- excipients: OEMol molecule The excipients molecules to parametrize opt: python dictionary The options used to parametrize the excipients Return: ------- excipient_structure: Parmed structure instance The parametrized excipient parmed structure """ # OpenMM topology and positions from OEMol topology, positions = oeommutils.oemol_to_openmmTop(excipients) # Try to apply the selected FF on the excipients forcefield = app.ForceField(opt['protein_forcefield']) # List of the unrecognized excipients unmatched_res_list = forcefield.getUnmatchedResidues(topology) # Unique unrecognized excipient names templates = set() for res in unmatched_res_list: templates.add(res.name) if templates: # Some excipients are not recognized oechem.OEThrow.Info("The following excipients are not recognized " "by the protein FF: {}" "\nThey will be parametrized by using the FF: {}".format(templates, opt['other_forcefield'])) # Create a bit vector mask used to split recognized from un-recognize excipients bv = oechem.OEBitVector(excipients.GetMaxAtomIdx()) bv.NegateBits() # Dictionary containing the name and the parmed structures of the unrecognized excipients unrc_excipient_structures = {} # Dictionary used to skip already selected unrecognized excipients and count them unmatched_excp = {} # Ordered list of the unrecognized excipients unmatched_res_order = [] for r_name in templates: unmatched_excp[r_name] = 0 hv = oechem.OEHierView(excipients) for chain in hv.GetChains(): for frag in chain.GetFragments(): for hres in frag.GetResidues(): r_name = hres.GetOEResidue().GetName() if r_name not in unmatched_excp: continue else: unmatched_res_order.append(r_name) if unmatched_excp[r_name]: # Test if we have selected the unknown excipient # Set Bit mask atms = hres.GetAtoms() for at in atms: bv.SetBitOff(at.GetIdx()) unmatched_excp[r_name] += 1 else: unmatched_excp[r_name] = 1 # Create AtomBondSet to extract from the whole excipient system # the current selected FF unknown excipient atms = hres.GetAtoms() bond_set = set() for at in atms: bv.SetBitOff(at.GetIdx()) bonds = at.GetBonds() for bond in bonds: bond_set.add(bond) atom_bond_set = oechem.OEAtomBondSet(atms) for bond in bond_set: atom_bond_set.AddBond(bond) # Create the unrecognized excipient OEMol unrc_excp = oechem.OEMol() if not oechem.OESubsetMol(unrc_excp, excipients, atom_bond_set): oechem.OEThrow.Fatal("Is was not possible extract the residue: {}".format(r_name)) # Charge the unrecognized excipient if not oequacpac.OEAssignCharges(unrc_excp, oequacpac.OEAM1BCCCharges(symmetrize=True)): oechem.OEThrow.Fatal("Is was not possible to " "charge the extract residue: {}".format(r_name)) # If GAFF or GAFF2 is selected as FF check for tleap command if opt['other_forcefield'] in ['GAFF', 'GAFF2']: ff_utils.ParamLigStructure(oechem.OEMol(), opt['other_forcefield']).checkTleap if opt['other_forcefield'] == 'SMIRNOFF': unrc_excp = oeommutils.sanitizeOEMolecule(unrc_excp) # Parametrize the unrecognized excipient by using the selected FF pmd = ff_utils.ParamLigStructure(unrc_excp, opt['other_forcefield'], prefix_name=opt['prefix_name']+'_'+r_name) unrc_excp_struc = pmd.parameterize() unrc_excp_struc.residues[0].name = r_name unrc_excipient_structures[r_name] = unrc_excp_struc # Recognized FF excipients pred_rec = oechem.OEAtomIdxSelected(bv) rec_excp = oechem.OEMol() oechem.OESubsetMol(rec_excp, excipients, pred_rec) if rec_excp.NumAtoms() > 0: top_known, pos_known = oeommutils.oemol_to_openmmTop(rec_excp) ff_rec = app.ForceField(opt['protein_forcefield']) try: omm_system = ff_rec.createSystem(top_known, rigidWater=False) rec_struc = parmed.openmm.load_topology(top_known, omm_system, xyz=pos_known) except: oechem.OEThrow.Fatal("Error in the recognised excipient parametrization") # Unrecognized FF excipients bv.NegateBits() pred_unrc = oechem.OEAtomIdxSelected(bv) unrc_excp = oechem.OEMol() oechem.OESubsetMol(unrc_excp, excipients, pred_unrc) # Unrecognized FF excipients coordinates oe_coord_dic = unrc_excp.GetCoords() unrc_coords = np.ndarray(shape=(unrc_excp.NumAtoms(), 3)) for at_idx in oe_coord_dic: unrc_coords[at_idx] = oe_coord_dic[at_idx] # It is important the order used to assemble the structures. In order to # avoid mismatch between the coordinates and the structures, it is convenient # to use the unrecognized residue order unmatched_res_order_count = [] i = 0 while i < len(unmatched_res_order): res_name = unmatched_res_order[i] for j in range(i+1, len(unmatched_res_order)): if unmatched_res_order[j] == res_name: continue else: break if i == (len(unmatched_res_order) - 1): num = 1 unmatched_res_order_count.append((res_name, num)) break else: num = j - i unmatched_res_order_count.append((res_name, num)) i = j # Merge all the unrecognized Parmed structure unrc_struc = parmed.Structure() for pair in unmatched_res_order_count: res_name = pair[0] nums = pair[1] unrc_struc = unrc_struc + nums*unrc_excipient_structures[res_name] # Set the unrecognized coordinates unrc_struc.coordinates = unrc_coords # Set the parmed excipient structure merging # the unrecognized and recognized parmed # structures together if rec_excp.NumAtoms() > 0: excipients_structure = unrc_struc + rec_struc else: excipients_structure = unrc_struc return excipients_structure else: # All the excipients are recognized by the selected FF omm_system = forcefield.createSystem(topology, rigidWater=False) excipients_structure = parmed.openmm.load_topology(topology, omm_system, xyz=positions) return excipients_structure
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)
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()
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 _extract_oe_fragment( molecule: Molecule, atom_indices: Set[int], bond_indices: Set[Tuple[int, int]] ) -> Molecule: from openeye import oechem oe_molecule = molecule.to_openeye() # Restore the map indices as to_openeye does not automatically add them. for atom_index, map_index in molecule.properties["atom_map"].items(): oe_atom = oe_molecule.GetAtom(oechem.OEHasAtomIdx(atom_index)) oe_atom.SetMapIdx(map_index) # Include any Hs bonded to the included atom set so we can retain their map # indices. for map_index in {*atom_indices}: oe_atom = oe_molecule.GetAtom(oechem.OEHasMapIdx(map_index)) for neighbour in oe_atom.GetAtoms(): if ( neighbour.GetAtomicNum() != 1 or neighbour.GetMapIdx() < 1 or neighbour.GetMapIdx() in atom_indices ): continue atom_indices.add(neighbour.GetMapIdx()) bond_indices.add((map_index, neighbour.GetMapIdx())) atom_bond_set = oechem.OEAtomBondSet() for map_index in atom_indices: atom = oe_molecule.GetAtom(oechem.OEHasMapIdx(map_index)) atom_bond_set.AddAtom(atom) for map_index_1, map_index_2 in bond_indices: atom_1 = oe_molecule.GetAtom(oechem.OEHasMapIdx(map_index_1)) atom_2 = oe_molecule.GetAtom(oechem.OEHasMapIdx(map_index_2)) bond = oe_molecule.GetBond(atom_1, atom_2) if not bond: raise ValueError(f"{(map_index_1, map_index_2)} is a disconnected bond") atom_bond_set.AddBond(bond) atom_predicate = oechem.OEIsAtomMember(atom_bond_set.GetAtoms()) bond_predicate = oechem.OEIsBondMember(atom_bond_set.GetBonds()) fragment = oechem.OEMol() oechem.OESubsetMol(fragment, oe_molecule, atom_predicate, bond_predicate, True) oechem.OEAddExplicitHydrogens(fragment) oechem.OEPerceiveChiral(fragment) # Always restore map? # if restore_maps: # In some cases (symmetric molecules) this changes the atom map so skip it # restore_atom_map(fragment) # atom map should be restored for combinatorial fragmentation # Perceive stereo and check that defined stereo did not change oechem.OEPerceiveChiral(fragment) oechem.OE3DToAtomStereo(fragment) oechem.OE3DToBondStereo(fragment) return Molecule.from_openeye(fragment, allow_undefined_stereo=True)
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be # liable for any damages or liability in connection with the Sample Code # or its use. # @ <SNIPPET> from __future__ import print_function from openeye import oechem # @ <SNIPPET-CREATE-ROLE-OBJECT> role = oechem.OERole("my:analysis:active-site") print(role.GetName()) # @ </SNIPPET-CREATE-ROLE-OBJECT> # @ <SNIPPET-ADD-ROLE-OBJECT> frag = oechem.OEAtomBondSet() # isa OERoleSet frag.AddRole(role) # @ </SNIPPET-ADD-ROLE-OBJECT> # @ <SNIPPET-ADD-ROLE-STRING> frag.AddRole("my:analysis:low-energy") # @ </SNIPPET-ADD-ROLE-STRING> # @ <SNIPPET-HAS-ROLE-OBJECT> role2 = oechem.OERole("my:analysis:low-energy") print(frag.HasRole(role2)) # @ </SNIPPET-HAS-ROLE-OBJECT> # @ <SNIPPET-HAS-ROLE-STRING> print(frag.HasRole("my:analysis:small")) # @ </SNIPPET-HAS-ROLE-STRING>
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 _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 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(): 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)