Example #1
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)
Example #2
0
def png_wiberg_labels(mol, fname, width=600, height=400):
    """
    Generate png figure of molecule. Bonds are labeled with Wiberg bond order

    Parameters
    ----------
    mol: OpenEye OEMol
    fname: str
        filename for png
    width: int
    height: int

    Returns
    -------
    bool:
    """

    oedepict.OEPrepareDepiction(mol)

    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    # opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())
    # opts.SetAtomPropLabelFont(oedepict.OEFont(oechem.OEDarkGreen))

    bondlabel = LabelBondOrder()
    opts.SetBondPropertyFunctor(bondlabel)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    return oedepict.OERenderMolecule(fname, disp)
Example #3
0
def png_atoms_labeled(smiles, fname):
    """Write out png file of molecule with atoms labeled with their index.

    Parameters
    ----------
    smiles: str
        SMILES
    fname: str
        absolute path and filename for png

    """

    mol = oechem.OEGraphMol()
    oechem.OESmilesToMol(mol, smiles)
    oedepict.OEPrepareDepiction(mol)

    width, height = 300, 200

    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())
    opts.SetAtomPropLabelFont(oedepict.OEFont(oechem.OEDarkGreen))

    disp = oedepict.OE2DMolDisplay(mol, opts)
    return oedepict.OERenderMolecule(fname, disp)
Example #4
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
Example #5
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)
Example #6
0
def Draw2DSurfacePartialCharge(image, mol):

    oedepict.OEPrepareDepiction(mol)

    oechem.OEMMFFAtomTypes(mol)
    oechem.OEMMFF94PartialCharges(mol)

    opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(),
                                          oedepict.OEScale_AutoScale)
    opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
    opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts))

    coloranion = oechem.OEColorStop(-1.0, oechem.OEColor(oechem.OEDarkRed))
    colorcation = oechem.OEColorStop(+1.0, oechem.OEColor(oechem.OEDarkBlue))
    colorg = oechem.OELinearColorGradient(coloranion, colorcation)
    colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEColor(oechem.OEWhite)))

    arcfxn = AtomPartialChargeArcFxn(colorg)

    for atom in mol.GetAtoms():
        oegrapheme.OESetSurfaceArcFxn(mol, atom, arcfxn)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    oegrapheme.OEDraw2DSurface(disp)
    oedepict.OERenderMolecule(image, disp)
Example #7
0
def smiles_to_png(smiles, file_path, image_size=200):
    """Creates a png image of the 2D representation of
    a given smiles pattern.

    Parameters
    ----------
    smiles: str
        The smiles pattern to generate the png of.
    file_path: str
        The path of the output png file.
    image_size: int
        The size in pixels of the square image.
    """

    from openeye import oedepict
    from openforcefield.topology import Molecule

    if os.path.isfile(file_path):
        return

    off_molecule = Molecule.from_smiles(smiles)
    oe_molecule = off_molecule.to_openeye()
    # oe_molecule.SetTitle(off_molecule.to_smiles())

    oedepict.OEPrepareDepiction(oe_molecule)

    options = oedepict.OE2DMolDisplayOptions(image_size, image_size, oedepict.OEScale_AutoScale)

    display = oedepict.OE2DMolDisplay(oe_molecule, options)
    oedepict.OERenderMolecule(file_path, display)
Example #8
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 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)
Example #10
0
def generate_ligands_figure(molecules, figsize=None, filename='ligands.png'):
    """ Plot an image with all of the ligands passed in

    Parameters
    ----------
    molecules : list
        list of openeye.oemol objects
    figsize : list or tuple
        list or tuple of len() == 2 of the horizontal and vertical lengths of image
    filename : string
        name of file to save the image

    Returns
    -------

    """
    from openeye import oechem, oedepict

    to_draw = []
    for lig in molecules:
        oedepict.OEPrepareDepiction(lig)
        to_draw.append(oechem.OEGraphMol(lig))

    dim = int(np.ceil(len(to_draw)**0.5))

    if figsize is None:
        x_len = 1000 * dim
        y_len = 500 * dim
        image = oedepict.OEImage(x_len, y_len)
    else:
        assert (len(figsize) == 2
                ), "figsize arguement should be a tuple or list of length 2"
        image = oedepict.OEImage(figsize[0], figsize[1])

    rows, cols = dim, dim
    grid = oedepict.OEImageGrid(image, rows, cols)

    opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(),
                                          grid.GetCellHeight(),
                                          oedepict.OEScale_AutoScale)

    minscale = float("inf")
    for mol in to_draw:
        minscale = min(minscale, oedepict.OEGetMoleculeScale(mol, opts))
    #     print(mol.GetTitle())

    opts.SetScale(minscale)
    for idx, cell in enumerate(grid.GetCells()):
        mol = to_draw[idx]
        disp = oedepict.OE2DMolDisplay(mol, opts)
        oedepict.OERenderMolecule(cell, disp)

    oedepict.OEWriteImage(filename, image)

    return
Example #11
0
 def __setupImage(self):
     if self._params["pageOrientation"] == "landscape":
         self.__multi = oedepict.OEMultiPageImageFile(
             oedepict.OEPageOrientation_Landscape,
             oedepict.OEPageSize_US_Letter)
     else:
         self.__multi = oedepict.OEMultiPageImageFile(
             oedepict.OEPageOrientation_Portrait,
             oedepict.OEPageSize_US_Letter)
     self.__image = self.__multi.NewPage()
     self._opts = oedepict.OE2DMolDisplayOptions()
Example #12
0
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 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)
Example #14
0
def plot_indices(mol2, width=200, height=200):
    mol = mol2.CreateCopy()

    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())
    oedepict.OEPrepareDepiction(mol)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    img = oedepict.OEImage(width, height)

    oedepict.OERenderMolecule(img, disp)
    return img
Example #15
0
def DrawMolecule(image, mol, width, height, offset):

    frame = oedepict.OEImageFrame(image, width, height, offset)

    oedepict.OEDrawBorder(frame, oedepict.OELightGreyPen)

    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(mol, opts)

    clearbackground = True
    oedepict.OERenderMolecule(frame, disp, not clearbackground)
def depict(mol, width=500, height=200):
    from IPython.display import Image
    dopt = oedepict.OEPrepareDepictionOptions()
    dopt.SetDepictOrientation(oedepict.OEDepictOrientation_Horizontal)
    oedepict.OEPrepareDepiction(mol, dopt)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(mol, opts)
    ofs = oechem.oeosstream()
    oedepict.OERenderMolecule(ofs, 'png', disp)
    ofs.flush()
    return Image(data="".join(ofs.str()))
Example #17
0
 def mol2svg(self, mol, svg_file):
     oechem.OEAssignImplicitHydrogens(mol)
     oechem.OEAddExplicitHydrogens(mol)
     oedepict.OEPrepareDepiction(mol)
     width = 1000
     height = 1000
     opts = oedepict.OE2DMolDisplayOptions(width, height,
                                           oedepict.OEScale_AutoScale)
     pens = opts.GetDefaultBondPen()
     pens.SetLineWidth(10)
     disp = oedepict.OE2DMolDisplay(mol, opts)
     oedepict.OERenderMolecule(svg_file, disp)
Example #18
0
def render_molecule(
    smiles: str,
    path: str,
    width: int = 320,
    height: int = 240,
    file_format: str = "svg",
    clearbackground: bool = False,
    force_regenerate: bool = False,
) -> None:
    """
    Render the molecule (from SMILES) to an image
    Parameters
    ----------
    smiles : str
        The SMILES string
    filename : str
        Output filename, with image format (pdf, png, jpg) detected from filename
    width : int, optional, default=320
        Default image width
    height : int, optional, default=240
        Default image height
    clearbackground : bool, optional, default=False
        For PNG, whether background should be clear
    """
    # Import the openeye toolkit
    from openeye import oechem, oedepict

    output_name = get_image_filename(smiles)
    output_path = os.path.join(path, os.extsep.join([output_name,
                                                     file_format]))

    if not force_regenerate and os.path.exists(output_path):
        logging.info("Skipping already-rendered molecule: %s", smiles)
        return

    # Generate OpenEye OEMol object from SMILES
    # see https://docs.eyesopen.com/toolkits/python/oechemtk/molctordtor.html?highlight=smiles#construction-from-smiles
    mol = oechem.OEGraphMol()

    if not oechem.OESmilesToMol(mol, smiles):
        raise ValueError(
            f"Failed to convert SMILES string to molecule: {smiles}")

    # Configure options (lots more are available)
    # see https://docs.eyesopen.com/toolkits/python/depicttk/OEDepictClasses/OE2DMolDisplayOptions.html
    opts = oedepict.OE2DMolDisplayOptions()
    opts.SetWidth(width)
    opts.SetHeight(height)

    # Render image
    oedepict.OEPrepareDepiction(mol)
    disp = oedepict.OE2DMolDisplay(mol, opts)
    oedepict.OERenderMolecule(output_path, disp, clearbackground)
Example #19
0
def genHBIndexGuide(inpmol):
    """
    For each mol, generate depiction of molecule with labeled
      indices as read in by oechem. Saved as   _____
    """
    mol = oechem.OEGraphMol(inpmol)
    dopt = oedepict.OEPrepareDepictionOptions()
    dopt.SetDepictOrientation(oedepict.OEDepictOrientation_Horizontal)
    oedepict.OEPrepareDepiction(mol, dopt)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())
    oedepict.OERenderMolecule(outfn, mol)
Example #20
0
def oedepict_pdf(all_probe_mols, subdir):
    """
    Generate a PDF report of all molecules together, color-coded
    by parameter ID and labeled with parameter ID and SMILES tag.

    Parameters
    ----------
    all_probe_mols:
        key is string of a parameter id to be probed;
        value is a list of oegraphmols with this parameter id
    subdir : string
        Name of subdirectory in which to save results.pdf file
    """
    multi = oedepict.OEMultiPageImageFile(oedepict.OEPageOrientation_Landscape,
                                          oedepict.OEPageSize_US_Letter)
    image = multi.NewPage()

    opts = oedepict.OE2DMolDisplayOptions()

    rows, cols = 4, 4
    grid = oedepict.OEImageGrid(image, rows, cols)
    grid.SetCellGap(20)
    grid.SetMargins(20)
    citer = grid.GetCells()

    colors = list(oechem.OEGetContrastColors())

    for i, (param, mol_list) in enumerate(all_probe_mols.items()):

        pen = oedepict.OEPen(oechem.OEWhite, colors[i], oedepict.OEFill_Off, 4.0)

        for mol in mol_list:

            # go to next page
            if not citer.IsValid():
                image = multi.NewPage()
                grid = oedepict.OEImageGrid(image, rows, cols)
                grid.SetCellGap(20)
                grid.SetMargins(20)
                citer = grid.GetCells()

            cell = citer.Target()
            mol.SetTitle(f"{param}   {oechem.OEGetSDData(mol, 'SMILES QCArchive')}")
            oedepict.OEPrepareDepiction(mol)
            opts.SetDimensions(cell.GetWidth(), cell.GetHeight(), oedepict.OEScale_AutoScale)
            disp = oedepict.OE2DMolDisplay(mol, opts)
            oedepict.OERenderMolecule(cell, disp)
            oedepict.OEDrawBorder(cell, pen)
            citer.Next()

    oedepict.OEWriteMultiPageImage(f"{subdir}/results.pdf", multi)
Example #21
0
def highlight_atoms_in_mol(mol2, dihedralAtomIndices, width=200, height=200):
    mol = mol2.CreateCopy()
    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    oedepict.OEPrepareDepiction(mol)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    img = oedepict.OEImage(width, height)

    hstyle = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint)
    for atom_idx in dihedralAtomIndices:
        oedepict.OEAddHighlighting(disp, hstyle, oechem.OEHasAtomIdx(atom_idx))

    oedepict.OERenderMolecule(img, disp)
    return img
Example #22
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
Example #23
0
def depictMatch(mol, match, width=500, height=200):
    from IPython.display import Image
    dopt = oedepict.OEPrepareDepictionOptions()
    dopt.SetDepictOrientation(oedepict.OEDepictOrientation_Horizontal)
    dopt.SetSuppressHydrogens(True)
    oedepict.OEPrepareDepiction(mol, dopt)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(mol, opts)
    hstyle = oedepict.OEHighlightStyle_Color
    hcolor = oechem.OEColor(oechem.OELightBlue)
    oedepict.OEAddHighlighting(disp, hcolor, hstyle, match)
    ofs = oechem.oeosstream()
    oedepict.OERenderMolecule(ofs, 'png', disp)
    ofs.flush()
    return Image(data="".join(ofs.str()))
Example #24
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
Example #25
0
 def __setupImage(self):
     """Internal method to configure a single page image."""
     #
     self.__image = oedepict.OEImage(self._params["imageSizeX"],
                                     self._params["imageSizeY"])
     self.__grid = oedepict.OEImageGrid(self.__image,
                                        self._params["gridRows"],
                                        self._params["gridCols"])
     self.__grid.SetCellGap(self._params["cellGap"])
     self.__grid.SetMargins(self._params["cellMargin"])
     self._opts = oedepict.OE2DMolDisplayOptions(
         self.__grid.GetCellWidth(), self.__grid.GetCellHeight(),
         oedepict.OEScale_AutoScale)
     #
     logger.debug("Num columns %d", self.__grid.NumCols())
     logger.debug("Num rows    %d", self.__grid.NumRows())
def Draw2DSurface(image, mol):

    oedepict.OEPrepareDepiction(mol)

    opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(),
                                          oedepict.OEScale_AutoScale)
    opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
    opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts))

    arcfxn = AtomColorArcFxn()
    for atom in mol.GetAtoms():
        oegrapheme.OESetSurfaceArcFxn(mol, atom, arcfxn)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    oegrapheme.OEDraw2DSurface(disp)
    oedepict.OERenderMolecule(image, disp)
Example #27
0
def DepictMoleculesWithHighlight(smiles, ss, highlight, basefilename):

    mol = oechem.OEGraphMol()
    oechem.OESmilesToMol(mol, smiles)
    oedepict.OEPrepareDepiction(mol)
    opts = oedepict.OE2DMolDisplayOptions(220, 160, oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(mol, opts)

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

    image = oedepict.OEImage(disp.GetWidth(), disp.GetHeight())
    oedepict.OERenderMolecule(image, disp)

    oedepict.OEWriteImage(basefilename + ".png", image)
    oedepict.OEWriteImage(basefilename + ".pdf", image)
Example #28
0
def DepictMoleculesWithHighlight(smiles, ss, highlight, basefilename):

    mol = oechem.OEGraphMol()
    oechem.OESmilesToMol(mol, smiles)
    oedepict.OEPrepareDepiction(mol)

    opts = oedepict.OE2DMolDisplayOptions(250, 160, oedepict.OEScale_AutoScale)
    opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
    disp = oedepict.OE2DMolDisplay(mol, opts)

    unique = True
    oedepict.OEAddHighlightOverlay(disp, highlight, ss.Match(mol, unique))

    image = oedepict.OEImage(disp.GetWidth(), disp.GetHeight())
    oedepict.OERenderMolecule(image, disp)

    oedepict.OEWriteImage(basefilename + ".png", image)
    oedepict.OEWriteImage(basefilename + ".pdf", image)
Example #29
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
Example #30
0
def png_atoms_labeled(smiles,
                      fname,
                      map_idx=True,
                      width=600,
                      height=400,
                      label_scale=2.0,
                      scale_bondwidth=True):
    """Write out png file of molecule with atoms labeled with their map index.

    Parameters
    ----------
    smiles: str
        SMILES
    fname: str
        absolute path and filename for png
    map_idx: bool
        If True, lable atoms with map index instead of atom index. If set to True, input SMILES must have map indices.

    """

    mol = oechem.OEGraphMol()
    oechem.OESmilesToMol(mol, smiles)
    oedepict.OEPrepareDepiction(mol)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)

    if map_idx:
        # check if molecule has map
        if not cmiles.utils.has_atom_map(mol):
            raise ValueError(
                "Input SMILES must have atom maps to display map indices in image"
            )
        opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx())
        opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx())
    if not map_idx:
        opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())

    opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx())
    opts.SetAtomPropLabelFont(oedepict.OEFont(oechem.OEDarkGreen))
    opts.SetAtomPropLabelFontScale(label_scale)
    opts.SetBondWidthScaling(scale_bondwidth)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    return oedepict.OERenderMolecule(fname, disp)