def CreateScaleReportLayout(opts, scale):

    opts = ScaleReportOptions(opts, scale)
    report = oedepict.OEReport(opts)

    borderpen = oedepict.OEPen(oechem.OEGrey, oechem.OEGrey,
                               oedepict.OEFill_Off, 1.0)

    first = report.NewBody()
    oedepict.OEDrawBorder(first, borderpen)

    nrgridpages = 1
    for p in range(0, nrgridpages):
        for c in range(0, report.NumRowsPerPage() * report.NumColsPerPage()):
            cell = report.NewCell()
            oedepict.OEDrawBorder(cell, borderpen)

    for page in report.GetPages():
        oedepict.OEDrawBorder(page, oedepict.OEBlackPen)

    if opts.GetHeaderHeight() > 0.0:
        for header in report.GetHeaders():
            oedepict.OEDrawBorder(header, borderpen)
    if opts.GetFooterHeight() > 0.0:
        for footer in report.GetFooters():
            oedepict.OEDrawBorder(footer, borderpen)

    return report
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def CreateReportLayout():

    rows, cols = 3, 2
    reportopts = oedepict.OEReportOptions(rows, cols)
    reportopts.SetPageWidth(100.0)
    reportopts.SetPageHeight(150.0)
    reportopts.SetPageMargins(5.0)
    reportopts.SetCellGap(5.0)
    reportopts.SetHeaderHeight(15.0)
    reportopts.SetFooterHeight(15.0)
    report = oedepict.OEReport(reportopts)

    borderpen = oedepict.OEPen(oechem.OELightGrey, oechem.OELightGrey,
                               oedepict.OEFill_Off, 1.0)

    first = report.NewBody()
    oedepict.OEDrawBorder(first, borderpen)

    nrgridpages = 3
    for p in range(0, nrgridpages):
        for c in range(0, report.NumRowsPerPage() * report.NumColsPerPage()):
            cell = report.NewCell()
            oedepict.OEDrawBorder(cell, borderpen)

    last = report.NewBody()
    oedepict.OEDrawBorder(last, borderpen)

    for page in report.GetPages():
        oedepict.OEDrawBorder(page, oedepict.OEBlackPen)
    for header in report.GetHeaders():
        oedepict.OEDrawBorder(header, borderpen)
    for footer in report.GetFooters():
        oedepict.OEDrawBorder(footer, borderpen)

    return report
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def write_pdf_report(mollist, pdf_filename, iname):
    """
    Write molecules with SD Data to PDF

    Parameters
    ----------
    mollist : list of openeye.oechem.OEMol
        The list of molecules with SD data tags
    pdf_filename : str
        The PDF filename to write
    iname : str
        Dataset name

    """
    from openeye import oedepict

    # collect data tags
    tags = CollectDataTags(mollist)

    # initialize multi-page report
    rows, cols = 4, 2
    ropts = oedepict.OEReportOptions(rows, cols)
    ropts.SetHeaderHeight(25)
    ropts.SetFooterHeight(25)
    ropts.SetCellGap(2)
    ropts.SetPageMargins(10)
    report = oedepict.OEReport(ropts)

    # setup depiction options
    cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
    opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight,
                                          oedepict.OEScale_AutoScale)

    # generate report
    DepictMoleculesWithData(report, mollist, iname, tags, opts)
    oedepict.OEWriteReport(pdf_filename, report)
Ejemplo n.º 9
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))
Ejemplo n.º 10
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)
# Generate a PDF of all molecules in the set
pdf_filename = 'selected_torsions.pdf'

from openeye import oedepict
itf = oechem.OEInterface()
PageByPage = True
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
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
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)
Ejemplo n.º 15
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)
Ejemplo n.º 16
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
#!/usr/bin/env python
# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.
#
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of OpenEye products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. OpenEye claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable OpenEye offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# 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.

from openeye import oechem
from openeye import oedepict

# @ <SNIPPET-WRITE-REPORT-TO-STRING>
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
oedepict.OEPrepareDepiction(mol)

report = oedepict.OEReport(3, 1)
oedepict.OERenderMolecule(report.NewCell(), mol)
data = oedepict.OEWriteReportToString("pdf", report)
# @ </SNIPPET-WRITE-REPORT-TO-STRING>