示例#1
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureReportOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-in")
    ifs = oechem.oemolistream()
    ifs.SetConfTest(oechem.OEAbsoluteConfTest())  # VTL
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    oname = itf.GetString("-out")
    ext = oechem.OEGetFileExtension(oname)
    if ext != "pdf":
        oechem.OEThrow.Fatal("Output must be PDF format.")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    if itf.HasString("-ringdict"):
        rdfname = itf.GetString("-ringdict")
        if not oechem.OEInit2DRingDictionary(rdfname):
            oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetFooterHeight(25.0)
    report = oedepict.OEReport(ropts)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetDimensions(report.GetCellWidth(), report.GetCellHeight(),
                        oedepict.OEScale_AutoScale)

    for mol in ifs.GetOEMols():  # VTL ignore confs; dont use GetOEGraphMols
        print(mol.GetTitle())  # VTL
        cell = report.NewCell()
        oedepict.OEPrepareDepiction(mol, popts)
        disp = oedepict.OE2DMolDisplay(mol, dopts)
        oedepict.OERenderMolecule(cell, disp)

    font = oedepict.OEFont(oedepict.OEFontFamily_Default,
                           oedepict.OEFontStyle_Bold, 12,
                           oedepict.OEAlignment_Center, oechem.OEBlack)
    for pagenum, footer in enumerate(report.GetFooters()):
        text = "Page %d of %d" % (pagenum + 1, report.NumPages())
        oedepict.OEDrawTextToCenter(footer, text, font)

    oedepict.OEWriteReport(ofs, ext, report)

    return 0
示例#2
0
def main(argv=[__name__]):
    # import configuration file
    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    # add configuration for image size and display options
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    ifname = itf.GetString("-in")
    ofname = itf.GetString("-out")

    ifs = oechem.oemolistream(ifname)
    mol = oechem.OEGraphMol()
    oechem.OEReadMolecule(ifs, mol)
    oedepict.OEPrepareDepiction(mol)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    # set up display options from command line parameters
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    oedepict.OERenderMolecule(ofname, disp)
示例#3
0
def ToPdf(mol, oname, frags):#, fragcombs):
    """
    Parameters
    ----------
    mol: charged OEMolGraph
    oname: str
        Output file name
    Returns
    -------

    """
    itf = oechem.OEInterface()
    oedepict.OEPrepareDepiction(mol)

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetFooterHeight(25.0)
    ropts.SetHeaderHeight(ropts.GetPageHeight() / 4.0)
    report = oedepict.OEReport(ropts)

    # setup decpiction options
    opts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
    opts.SetDimensions(cellwidth, cellheight, oedepict.OEScale_AutoScale)
    opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)
    opts.SetAtomLabelFontScale(1.2)

    DepictMoleculeWithFragmentCombinations(report, mol, frags, opts)

    return oedepict.OEWriteReport(oname, report)
示例#4
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 400.0)
    oedepict.OEConfigureImageHeight(itf, 400.0)
    oedepict.OEConfigureImageGridParams(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    rows = oedepict.OEGetImageGridNumRows(itf)
    cols = oedepict.OEGetImageGridNumColumns(itf)
    grid = oedepict.OEImageGrid(image, rows, cols)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetDimensions(grid.GetCellWidth(), grid.GetCellHeight(),
                        oedepict.OEScale_AutoScale)

    celliter = grid.GetCells()
    for iname in itf.GetStringList("-in"):
        ifs = oechem.oemolistream()
        if not ifs.open(iname):
            oechem.OEThrow.Warning("Cannot open %s input file!" % iname)
            continue

        for mol in ifs.GetOEGraphMols():
            if not celliter.IsValid():
                break

            oedepict.OEPrepareDepiction(mol, popts)
            disp = oedepict.OE2DMolDisplay(mol, dopts)
            oedepict.OERenderMolecule(celliter.Target(), disp)
            celliter.Next()

    oedepict.OEWriteImage(ofs, ext, image)

    return 0
def draw_frag_pdf(frag_dict, scaffold=None, pdf_filename='fragments.pdf'):
    from openeye import oechem, oedepict
    import re
    itf = oechem.OEInterface()
    PageByPage = True
    suppress_h = True
    rows = 7
    cols = 5
    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)
    if scaffold:
        oemol = oechem.OEGraphMol()
        scaffold_smi = re.sub(r"\(\[R([1-9])+]\)", r"([*])", scaffold.smiles)
        oechem.OESmilesToMol(oemol, scaffold_smi)
        cell = report.NewCell()
        mol = oechem.OEMol(oemol)
        mol.SetTitle(f'{scaffold.smiles}')
        oedepict.OEPrepareDepiction(mol, False, suppress_h)
        disp = oedepict.OE2DMolDisplay(mol, opts)
        oedepict.OERenderMolecule(cell, disp)
        headerpen = oedepict.OEPen(oechem.OEWhite, oechem.OELightGrey,
                                   oedepict.OEFill_Off, 1.0)
        oedepict.OEDrawBorder(cell, headerpen)

    for rx, smis in frag_dict.items():
        for idx, smi in enumerate(smis):
            if smi != None:

                # Create oemol
                oemol = oechem.OEGraphMol()
                oechem.OESmilesToMol(oemol, smi)

                # Render molecule
                cell = report.NewCell()
                mol = oechem.OEMol(oemol)
                mol.SetTitle(f'R{rx} #{idx+1}')
                oedepict.OEPrepareDepiction(mol, False, suppress_h)
                disp = oedepict.OE2DMolDisplay(mol, opts)

                oedepict.OERenderMolecule(cell, disp)

    oedepict.OEWriteReport(pdf_filename, report)
示例#6
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    if itf.HasString("-ringdict"):
        rdfname = itf.GetString("-ringdict")
        if not oechem.OEInit2DRingDictionary(rdfname):
            oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    oedepict.OEPrepareDepiction(mol, popts)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    dopts = oedepict.OE2DMolDisplayOptions(width, height,
                                           oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)

    disp = oedepict.OE2DMolDisplay(mol, dopts)
    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
示例#7
0
def prep_pdf_writer():

    itf = oechem.OEInterface()
    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetFooterHeight(25.0)
    report = oedepict.OEReport(ropts)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetDimensions(report.GetCellWidth(), report.GetCellHeight(), oedepict.OEScale_AutoScale)

    return popts, dopts, report
示例#8
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    if ifs.GetFormat() != oechem.OEFormat_MDL:
        oechem.OEThrow.Fatal("Input file is not an MDL query file")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMDLQueryFile(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read mdl query input file!")

    clearcoords, suppressH = False, False
    oedepict.OEPrepareDepiction(mol, clearcoords, suppressH)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
示例#9
0
def to_pdf(molecules, oname, rows=5, cols=3):
    itf = oechem.OEInterface()
    PageByPage = True

    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)

    for mol in molecules:
        cell = report.NewCell()
        oedepict.OEPrepareDepiction(mol)
        disp = oedepict.OE2DMolDisplay(mol, opts)
        oedepict.OERenderMolecule(cell, disp)
        oedepict.OEDrawCurvedBorder(cell, oedepict.OELightGreyPen, 10.0)

    oedepict.OEWriteReport(oname, report)
示例#10
0
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))
示例#11
0
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)
示例#12
0
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()
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 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)
    oedepict.OEPrepareDepiction(mol, False, suppress_h)
    disp = oedepict.OE2DMolDisplay(mol, opts)

    # Highlight element of interest
    class NoAtom(oechem.OEUnaryAtomPred):
示例#14
0
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)
示例#15
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 900.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(
        itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(
        itf, oechem.OESplitMolComplexSetup_LigName
        | oechem.OESplitMolComplexSetup_CovLig)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    if itf.HasString("-complex") and (itf.HasString("-protein")
                                      or itf.HasString("-ligand")):
        oechem.OEThrow.Warning("Only complex in %s file fill be used!" %
                               itf.GetString("-complex"))

    if not (itf.HasString("-complex")) ^ (itf.HasString("-protein")
                                          and itf.HasString("-ligand")):
        oechem.OEThrow.Fatal(
            "Please specify either complex or ligand and protein input files!")

    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    # initialize protein and ligand

    protein = oechem.OEGraphMol()
    ligand = oechem.OEGraphMol()
    if not get_protein_and_ligands(protein, ligand, itf):
        oechem.OEThrow.Fatal("Cannot initialize protein and/or ligand!")

    # depict active site with interactions

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    interactive_legend = False
    magnify_residue = 1.0

    if ext == 'svg':
        interactive_legend = itf.GetBool("-interactive-legend")
        magnify_residue = itf.GetFloat("-magnify-residue")

    cwidth, cheight = width, height
    if not interactive_legend:
        cwidth = cwidth * 0.8

    opts = oegrapheme.OE2DActiveSiteDisplayOptions(cwidth, cheight)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    opts.SetRenderInteractiveLegend(interactive_legend)
    opts.SetSVGMagnifyResidueInHover(magnify_residue)

    if interactive_legend:
        depict_complex(image, protein, ligand, opts)
    else:
        main_frame = oedepict.OEImageFrame(
            image, width * 0.80, height, oedepict.OE2DPoint(width * 0.2, 0.0))
        legend_frame = oedepict.OEImageFrame(
            image, width * 0.20, height, oedepict.OE2DPoint(width * 0.0, 0.0))
        depict_complex(main_frame, protein, ligand, opts, legend_frame)

    if ext == 'svg' and (interactive_legend or magnify_residue > 1.0):
        iconscale = 0.5
        oedepict.OEAddInteractiveIcon(image, oedepict.OEIconLocation_TopRight,
                                      iconscale)
    oedepict.OEDrawCurvedBorder(image, oedepict.OELightGreyPen, 10.0)

    oedepict.OEWriteImage(oname, image)

    return 0
示例#16
0
def smiles_to_pdf(smiles, file_path, rows=10, columns=6):
    """Creates a PDF file containing images of a list of molecules
    described by their SMILES patterns.

    Parameters
    ----------
    smiles: list of str or tuple of str
        The SMILES patterns of the molecules. The list can either contain
        a list of single SMILES strings, or a tuple of SMILES strings. If
        tuples of SMILES are provided, these smiles will be grouped together
        in the output. All tuples in the list must have the same length.
    file_path: str
        The file path to save the pdf to.
    rows: int
        The maximum number of rows of molecules to include per page.
    columns: int
        The maximum number of molecules to include per row.
    """

    assert len(smiles) > 0

    # Validate the input type.
    assert all(isinstance(x, str)
               for x in smiles) or all(isinstance(x, tuple) for x in smiles)

    # Make sure the smiles tuples are the same length.
    molecules_per_group = 1

    if isinstance(smiles[0], tuple):

        assert (len(x) == len(smiles[0]) for x in smiles)
        molecules_per_group = len(smiles[0])

    # Convert the list of tuple to list of strings.
    if isinstance(smiles[0], tuple):
        smiles = [".".join(sorted(x)) for x in smiles]

    # Create OEMol objects for each unique smiles pattern provided.
    oe_molecules = {}

    unique_smiles = set(smiles)

    for smiles_pattern in unique_smiles:

        molecule = oechem.OEMol()
        oechem.OEParseSmiles(molecule, smiles_pattern)

        oe_molecules[smiles_pattern] = molecule

    # Take into account that each group may have more than one molecule
    columns = int(math.floor(columns / molecules_per_group))

    report_options = oedepict.OEReportOptions(rows, columns)
    report_options.SetHeaderHeight(25)
    report_options.SetFooterHeight(25)
    report_options.SetCellGap(4)
    report_options.SetPageMargins(10)

    report = oedepict.OEReport(report_options)

    cell_width, cell_height = report.GetCellWidth(), report.GetCellHeight()

    display_options = oedepict.OE2DMolDisplayOptions(
        cell_width, cell_height, oedepict.OEScale_Default * 0.5)
    display_options.SetAromaticStyle(oedepict.OEAromaticStyle_Circle)

    pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On,
                         1.0)
    display_options.SetDefaultBondPen(pen)

    interface = oechem.OEInterface()
    oedepict.OESetup2DMolDisplayOptions(display_options, interface)

    for i, smiles_pattern in enumerate(smiles):

        cell = report.NewCell()

        oe_molecule = oechem.OEMol(oe_molecules[smiles_pattern])
        oedepict.OEPrepareDepiction(oe_molecule, False, True)

        display = oedepict.OE2DMolDisplay(oe_molecule, display_options)
        oedepict.OERenderMolecule(cell, display)

    oedepict.OEWriteReport(file_path, report)
示例#17
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 900.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(
        itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(
        itf, oechem.OESplitMolComplexSetup_LigName)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-complex")
    oname = itf.GetString("-out")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    complexmol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, complexmol):
        oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)

    if not oechem.OEHasResidues(complexmol):
        oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)

    # Separate ligand and protein

    sopts = oechem.OESplitMolComplexOptions()
    oechem.OESetupSplitMolComplexOptions(sopts, itf)

    ligand = oechem.OEGraphMol()
    protein = oechem.OEGraphMol()
    water = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    pfilter = sopts.GetProteinFilter()
    wfilter = sopts.GetWaterFilter()
    sopts.SetProteinFilter(oechem.OEOrRoleSet(pfilter, wfilter))
    sopts.SetWaterFilter(
        oechem.OEMolComplexFilterFactory(
            oechem.OEMolComplexFilterCategory_Nothing))

    oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)

    if ligand.NumAtoms() == 0:
        oechem.OEThrow.Fatal("Cannot separate complex!")

    # Perceive interactions

    asite = oechem.OEInteractionHintContainer(protein, ligand)
    if not asite.IsValid():
        oechem.OEThrow.Fatal("Cannot initialize active site!")
    asite.SetTitle(ligand.GetTitle())

    oechem.OEPerceiveInteractionHints(asite)

    oegrapheme.OEPrepareActiveSiteDepiction(asite)

    # Depict active site with interactions

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    cframe = oedepict.OEImageFrame(image, width * 0.80, height,
                                   oedepict.OE2DPoint(0.0, 0.0))
    lframe = oedepict.OEImageFrame(image, width * 0.20, height,
                                   oedepict.OE2DPoint(width * 0.80, 0.0))

    opts = oegrapheme.OE2DActiveSiteDisplayOptions(cframe.GetWidth(),
                                                   cframe.GetHeight())
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
    oegrapheme.OERenderActiveSite(cframe, adisp)

    lopts = oegrapheme.OE2DActiveSiteLegendDisplayOptions(10, 1)
    oegrapheme.OEDrawActiveSiteLegend(lframe, adisp, lopts)

    oedepict.OEWriteImage(oname, image)

    return 0
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)
示例#19
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)
    oedepict.OEConfigureHighlightParams(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    smarts = itf.GetString("-smarts")

    ss = oechem.OESubSearch()
    if not ss.Init(smarts):
        oechem.OEThrow.Fatal("Cannot parse smarts: %s" % smarts)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)
    oedepict.OEPrepareDepiction(mol, popts)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    dopts = oedepict.OE2DMolDisplayOptions(width, height,
                                           oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetMargins(10.0)

    disp = oedepict.OE2DMolDisplay(mol, dopts)

    hstyle = oedepict.OEGetHighlightStyle(itf)
    hcolor = oedepict.OEGetHighlightColor(itf)

    oechem.OEPrepareSearch(mol, ss)

    unique = True
    for match in ss.Match(mol, unique):
        oedepict.OEAddHighlighting(disp, hcolor, hstyle, match)

    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
示例#20
0
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)
示例#21
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 600.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(itf, oechem.OESplitMolComplexSetup_LigName)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-complex")
    oname = itf.GetString("-out")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    complexmol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, complexmol):
        oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)

    if not oechem.OEHasResidues(complexmol):
        oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)

    # Separate ligand and protein

    sopts = oechem.OESplitMolComplexOptions()
    oechem.OESetupSplitMolComplexOptions(sopts, itf)

    ligand = oechem.OEGraphMol()
    protein = oechem.OEGraphMol()
    water = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)

    if ligand.NumAtoms() == 0:
        oechem.OEThrow.Fatal("Cannot separate complex!")

    # Calculate average BFactor of the whole complex

    avgbfactor = GetAverageBFactor(complexmol)

    # Calculate minimum and maximum BFactor of the ligand and its environment

    minbfactor, maxbfactor = GetMinAndMaxBFactor(ligand, protein)

    # Attach to each ligand atom the average BFactor of the nearby protein atoms

    stag = "avg residue BFfactor"
    itag = oechem.OEGetTag(stag)
    SetAverageBFactorOfNearbyProteinAtoms(ligand, protein, itag)

    oechem.OEThrow.Info("Average BFactor of the complex = %+.3f" % avgbfactor)
    oechem.OEThrow.Info("Minimum BFactor of the ligand and its environment = %+.3f" % minbfactor)
    oechem.OEThrow.Info("Maximum BFactor of the ligand and its environment = %+.3f" % maxbfactor)

    # Create image

    imagewidth, imageheight = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
    image = oedepict.OEImage(imagewidth, imageheight)

    mframe = oedepict.OEImageFrame(image, imagewidth,
                                   imageheight * 0.90, oedepict.OE2DPoint(0.0, 0.0))
    lframe = oedepict.OEImageFrame(image, imagewidth, imageheight * 0.10,
                                   oedepict.OE2DPoint(0.0, imageheight * 0.90))

    opts = oedepict.OE2DMolDisplayOptions(mframe.GetWidth(), mframe.GetHeight(),
                                          oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)

    # Create BFactor color gradient

    colorg = oechem.OELinearColorGradient()
    colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEDarkBlue))
    colorg.AddStop(oechem.OEColorStop(10.0, oechem.OELightBlue))
    colorg.AddStop(oechem.OEColorStop(25.0, oechem.OEYellowTint))
    colorg.AddStop(oechem.OEColorStop(50.0, oechem.OERed))
    colorg.AddStop(oechem.OEColorStop(100.0, oechem.OEDarkRose))

    # Prepare ligand for depiction

    oegrapheme.OEPrepareDepictionFrom3D(ligand)
    arcfxn = BFactorArcFxn(colorg, itag)
    for atom in ligand.GetAtoms():
        oegrapheme.OESetSurfaceArcFxn(ligand, atom, arcfxn)
    opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(ligand, opts))

    # Render ligand and visualize BFactor

    disp = oedepict.OE2DMolDisplay(ligand, opts)
    colorbfactor = ColorLigandAtomByBFactor(colorg)
    oegrapheme.OEAddGlyph(disp, colorbfactor, oechem.OEIsTrueAtom())
    oegrapheme.OEDraw2DSurface(disp)
    oedepict.OERenderMolecule(mframe, disp)

    # Draw color gradient

    opts = oegrapheme.OEColorGradientDisplayOptions()
    opts.SetColorStopPrecision(1)
    opts.AddMarkedValue(avgbfactor)
    opts.SetBoxRange(minbfactor, maxbfactor)

    oegrapheme.OEDrawColorGradient(lframe, colorg, opts)

    oedepict.OEWriteImage(oname, image)

    return 0
示例#22
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureReportOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)
    oedepict.OEConfigureHighlightParams(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    qname = itf.GetString("-query")
    tname = itf.GetString("-target")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredMultiPageImageFile(ext):
        oechem.OEThrow.Fatal("Unknown multipage image type!")

    qfile = oechem.oemolistream()
    if not qfile.open(qname):
        oechem.OEThrow.Fatal("Cannot open mdl query file!")
    if qfile.GetFormat() != oechem.OEFormat_MDL and qfile.GetFormat(
    ) != oechem.OEFormat_SDF:
        oechem.OEThrow.Fatal("Query file has to be an MDL file!")

    ifs = oechem.oemolistream()
    if not ifs.open(tname):
        oechem.OEThrow.Fatal("Cannot open target input file!")

    depictquery = oechem.OEGraphMol()
    if not oechem.OEReadMDLQueryFile(qfile, depictquery):
        oechem.OEThrow.Fatal("Cannot read query molecule!")
    oedepict.OEPrepareDepiction(depictquery)
    queryopts = oechem.OEMDLQueryOpts_Default | oechem.OEMDLQueryOpts_SuppressExplicitH
    qmol = oechem.OEQMol()
    oechem.OEBuildMDLQueryExpressions(qmol, depictquery, queryopts)

    ss = oechem.OESubSearch()
    if not ss.Init(qmol):
        oechem.OEThrow.Fatal("Cannot initialize substructure search!")

    hstyle = oedepict.OEGetHighlightStyle(itf)
    hcolor = oedepict.OEGetHighlightColor(itf)
    align = itf.GetBool("-align")

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetHeaderHeight(140.0)
    report = oedepict.OEReport(ropts)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
    dopts.SetDimensions(cellwidth, cellheight, oedepict.OEScale_AutoScale)

    unique = True
    for mol in ifs.GetOEGraphMols():

        oechem.OEPrepareSearch(mol, ss)

        miter = ss.Match(mol, unique)
        if not miter.IsValid():
            continue  # no match

        alignres = oedepict.OEAlignmentResult(miter.Target())
        if align:
            alignres = oedepict.OEPrepareAlignedDepiction(mol, ss)
        else:
            oedepict.OEPrepareDepiction(mol)

        cell = report.NewCell()
        disp = oedepict.OE2DMolDisplay(mol, dopts)
        if alignres.IsValid():
            oedepict.OEAddHighlighting(disp, hcolor, hstyle, alignres)
        oedepict.OERenderMolecule(cell, disp)
        oedepict.OEDrawBorder(cell, oedepict.OELightGreyPen)

    # render query structure in each header
    headwidth, headheight = report.GetHeaderWidth(), report.GetHeaderHeight()
    dopts.SetDimensions(headwidth, headheight, oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(depictquery, dopts)
    for header in report.GetHeaders():
        oedepict.OERenderMolecule(header, disp)
        oedepict.OEDrawBorder(header, oedepict.OELightGreyPen)

    oedepict.OEWriteReport(oname, report)

    return 0