Python rdkit.Chem.Draw.MolToImage() Examples

The following are 9 code examples of rdkit.Chem.Draw.MolToImage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdkit.Chem.Draw , or try the search function .
Example #1
Source File: chem.py    From spektral with MIT License 5 votes vote down vote up
def plot_rdkit(mol, filename=None):
    """
    Plots an RDKit molecule in Matplotlib
    :param mol: an RDKit molecule 
    :param filename: save the image with the given filename 
    :return: the image as np.array
    """
    if rdc is None:
        raise ImportError('`draw_rdkit_mol` requires RDkit.')
    if filename is not None:
        Draw.MolToFile(mol, filename)
    img = Draw.MolToImage(mol)
    return img 
Example #2
Source File: tensorboard.py    From reinvent-randomized with MIT License 5 votes vote down vote up
def add_mol(writer, tag, mol, global_step=None, walltime=None, size=(300, 300)):
    """
    Adds a molecule to the images section of Tensorboard.
    """
    image = rkcd.MolToImage(mol, size=size)
    add_image(writer, tag, image, global_step, walltime) 
Example #3
Source File: draw.py    From ASKCOS with Mozilla Public License 2.0 5 votes vote down vote up
def MolToImage(mol, max_size=(1000, 1000), kekulize=True, options=None,
               canvas=None, **kwargs):
    '''Wrapper for RDKit's MolToImage. If mol == None, an arrow is drawn'''

    if not options:
        options = defaultDrawOptions()
    if mol == '->':
        subImgSize = (100, 100)
        img, canvas = Draw._createCanvas(subImgSize)
        p0 = (10, subImgSize[1]//2)
        p1 = (subImgSize[0]-10, subImgSize[1]//2)
        p3 = (subImgSize[0]-20, subImgSize[1]//2-10)
        p4 = (subImgSize[0]-20, subImgSize[1]//2+10)
        canvas.addCanvasLine(p0, p1, lineWidth=2, color=(0, 0, 0))
        canvas.addCanvasLine(p3, p1, lineWidth=2, color=(0, 0, 0))
        canvas.addCanvasLine(p4, p1, lineWidth=2, color=(0, 0, 0))
        if hasattr(canvas, 'flush'):
            canvas.flush()
        else:
            canvas.save()
        return img        
    elif mol == '<-':  # retro arrow or error
        subImgSize = (100, 100)
        (a, b) = subImgSize
        img, canvas = Draw._createCanvas(subImgSize)
        canvas.addCanvasLine((10, b//2-7), (a-17, b//2-7),
                             lineWidth=2, color=(0, 0, 0))
        canvas.addCanvasLine((10, b//2+7), (a-17, b//2+7),
                             lineWidth=2, color=(0, 0, 0))
        canvas.addCanvasLine((a-24, b//2-14), (a-10, b//2),
                             lineWidth=2, color=(0, 0, 0))
        canvas.addCanvasLine((a-24, b//2+14), (a-10, b//2),
                             lineWidth=2, color=(0, 0, 0))
        if hasattr(canvas, 'flush'):
            canvas.flush()
        else:
            canvas.save()
        return img
    elif mol is not None:
        return Draw.MolToImage(mol, size=max_size, kekulize=kekulize, options=options,
                               canvas=canvas, **kwargs) 
Example #4
Source File: draw.py    From ASKCOS with Mozilla Public License 2.0 5 votes vote down vote up
def ReactionToImage(rxn, dummyAtoms=False, kekulize=True, options=None, **kwargs):
    '''Modification of RDKit's ReactionToImage to allow for each molecule 
    to have a different drawn size. rxn is an RDKit reaction object

    warning: this function adds hydrogens as it sees fit'''
    # Extract mols from reaction
    mols = []
    for i in range(rxn.GetNumReactantTemplates()):
        mol = rxn.GetReactantTemplate(i)
        mol.UpdatePropertyCache(False)
        mols.append(mol)
        if dummyAtoms:
            [CheckAtomForGeneralization(atom) for atom in mol.GetAtoms()]

    if kwargs.pop('retro', True):
        mols.append('<-')  # placeholder for arrow
    else:
        mols.append('->')

    for j in range(rxn.GetNumProductTemplates()):
        mol = rxn.GetProductTemplate(j)
        mol.UpdatePropertyCache(False)
        mols.append(mol)
        if dummyAtoms:
            [CheckAtomForGeneralization(atom) for atom in mol.GetAtoms()]

    # Generate images for all molecules/arrow
    imgs = [TrimImgByWhite(MolToImage(
        mol, kekulize=kekulize, options=options), padding=10) for mol in mols]

    # Combine
    return StitchPILsHorizontally(imgs) 
Example #5
Source File: draw.py    From ASKCOS with Mozilla Public License 2.0 5 votes vote down vote up
def ReactionStringToImage(rxn_string, strip=True, update=True, options=None,
        retro=False, **kwargs):
    '''This function takes a SMILES rxn_string as input, not an 
    RDKit reaction object, and draws it.'''

    reactants, agents, products = [mols_from_smiles_list(x) for x in
                                   [mols.split('.') for mols in rxn_string.split('>')]]
    if None in reactants + products:
        raise ValueError(
            'Could not parse entirety of reaction: {}'.format(rxn_string))

    # Stich together mols (ignore agents)
    if retro:
        mols = reactants + ['<-'] + products
    else:
        mols = reactants + ['->'] + products
    if update:
        [mol.UpdatePropertyCache(False) for mol in mols if mol is not None and type(mol) != str]
    if strip:
        for mol in mols:
            if mol is not None and type(mol) != str:
                [a.ClearProp('molAtomMapNumber') for a in mol.GetAtoms()]

    # Generate images
    imgs = [TrimImgByWhite(MolToImage(
        mol, kekulize=True, options=options), padding=10) for mol in mols]

    # Combine
    return StitchPILsHorizontally(imgs) 
Example #6
Source File: draw.py    From ASKCOS with Mozilla Public License 2.0 5 votes vote down vote up
def MolsSmilesToImage(smiles, options=None, **kwargs):
    '''This function takes a SMILES string of one or more molecules
    and generates a combined image for that molecule set.'''

    # Generate mols
    mols = mols_from_smiles_list(smiles.split('.'))
    # Generate images
    imgs = [TrimImgByWhite(MolToImage(
        mol, kekulize=True, options=options), padding=10) for mol in mols]
    # Combine
    return StitchPILsHorizontally(imgs) 
Example #7
Source File: chemical.py    From thermo with MIT License 5 votes vote down vote up
def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover
        r'''Interface for drawing a 2D image of the molecule.
        Requires an HTML5 browser, and the libraries RDKit and
        IPython. An exception is raised if either of these libraries is
        absent.

        Parameters
        ----------
        width : int
            Number of pixels wide for the view
        height : int
            Number of pixels tall for the view
        Hs : bool
            Whether or not to show hydrogen

        Examples
        --------
        >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS
        <PIL.Image.Image image mode=RGBA size=300x300 at 0x...>
        '''
        try:
            from rdkit.Chem import Draw
            from rdkit.Chem.Draw import IPythonConsole
            if Hs:
                mol = self.rdkitmol_Hs
            else:
                mol = self.rdkitmol
            return Draw.MolToImage(mol, size=(width, height))
        except:
            return 'Rdkit is required for this feature.' 
Example #8
Source File: tensorboard.py    From reinvent-scaffold-decorator with MIT License 5 votes vote down vote up
def add_mol(writer, tag, mol, global_step=None, walltime=None, size=(300, 300)):
    """
    Adds a molecule to the images section of Tensorboard.
    """
    image = rkcd.MolToImage(mol, size=size)
    add_image(writer, tag, image, global_step, walltime) 
Example #9
Source File: molecule.py    From chemml with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visualize(self, filename=None, **kwargs):
        """
        This function visualizes the molecule. If both rdkit and pybel objects are avaialble, the rdkit object
        will be used for visualization.

        Parameters
        ----------
        filename: str, optional (default = None)
            This is the path to the file that you want write the image in it.
            Tkinter and Python Imaging Library are required for writing the image.

        kwargs:
            any extra parameter that you want to pass to the rdkit or pybel draw tool.
            Additional information at:
                - https://www.rdkit.org/docs/source/rdkit.Chem.Draw.html
                - http://openbabel.org/docs/dev/UseTheLibrary/Python_PybelAPI.html#pybel.Molecule.draw

        Returns
        -------
        object
            You will be able to display this object, e.g., inside the Jupyter Notebook.

        """
        engine = self._check_original_molecule()
        if engine == 'rdkit':
            from rdkit.Chem import Draw
            if filename is not None:
                Draw.MolToFile(self.rdkit_molecule, filename, **kwargs)
            else:
                return Draw.MolToImage(self.rdkit_molecule, **kwargs)
        elif engine == 'pybel':
            if filename is not None:
                self.pybel_molecule.draw(show=False, filename=filename, **kwargs)
            else:
                return self.pybel_molecule # it seems that the object alone is displayable