예제 #1
0
def get_glowing_image(smiles):
    if '_' in smiles:
        mol_smi = smiles.split('_')[0]
        mol_subs = smiles.split('_')[1]
        try:
            mol = Chem.MolFromSmiles(mol_smi)
            patt = Chem.MolFromSmiles(mol_subs)
            matching = mol.GetSubstructMatch(patt)
            d2d = rdMolDraw2D.MolDraw2DSVG(350, 300)
            d2d.DrawMolecule(mol, highlightAtoms=matching)
            d2d.FinishDrawing()
            return Response(d2d.GetDrawingText(), mimetype='image/svg+xml')
        except:
            return send_file('./images/no_image_available.png',
                             mimetype='image/png')
    else:
        try:
            mol = Chem.MolFromSmiles(smiles)
            d2d = rdMolDraw2D.MolDraw2DSVG(350, 300)
            d2d.DrawMolecule(mol)
            d2d.FinishDrawing()
            return Response(d2d.GetDrawingText(), mimetype='image/svg+xml')
        except:
            return send_file('./images/no_image_available.png',
                             mimetype='image/png')
예제 #2
0
파일: visualizer.py 프로젝트: wibrow/kGCN
    def _draw_mol_structure(self, mol, figsize=(600, 300)):
        from IPython.display import SVG
        from rdkit import Chem
        from rdkit.Chem import rdDepictor
        from rdkit.Chem.Draw import rdMolDraw2D

        self.logger.info(Chem.MolToSmiles(mol))

        rdDepictor.Compute2DCoords(mol)
        drawer = rdMolDraw2D.MolDraw2DSVG(*figsize)

        highlight_atoms, color_atoms = self._get_atoms_color()
        highlight_bonds = []
        color_bonds = {}
        drawer.DrawMolecule(mol,
                            highlightAtoms=highlight_atoms,
                            highlightAtomColors=color_atoms,
                            highlightBonds=highlight_bonds,
                            highlightBondColors=color_bonds)

        drawer.FinishDrawing()
        svg = drawer.GetDrawingText().replace('svg:', '')
        SVG(svg)
        saved_filename = "{}_mol.svg".format(str(self.out_filename))
        with open(saved_filename, "w") as f:
            f.write(svg)
예제 #3
0
        def do_a_picture(smi, smarts, label):

            rdDepictor.SetPreferCoordGen(False)
            mol = Chem.MolFromSmiles(smi)
            mol = Draw.PrepareMolForDrawing(mol)

            acols = {}
            bcols = {}
            h_rads = {}
            h_lw_mult = {}

            for i, smt in enumerate(smarts):
                alist, blist = get_hit_atoms_and_bonds(mol, smt)
                h_rads[alist[0]] = 0.4
                h_lw_mult[blist[0]] = 2
                col = i % 4
                add_colours_to_map(alist, acols, col)
                add_colours_to_map(blist, bcols, col)

            d = rdMolDraw2D.MolDraw2DSVG(500, 500)
            d.drawOptions().fillHighlights = False
            d.DrawMoleculeWithHighlights(mol, label, acols, bcols, h_rads,
                                         h_lw_mult, -1)

            d.FinishDrawing()
            return d.GetDrawingText()
예제 #4
0
def DrawMorganEnvs(envs,
                   molsPerRow=3,
                   subImgSize=(150, 150),
                   baseRad=0.3,
                   useSVG=True,
                   aromaticColor=(0.9, 0.9, 0.2),
                   ringColor=(0.8, 0.8, 0.8),
                   centerColor=(0.6, 0.6, 0.9),
                   extraColor=(0.9, 0.9, 0.9),
                   legends=None,
                   drawOptions=None,
                   **kwargs):
    submols = []
    highlightAtoms = []
    atomColors = []
    highlightBonds = []
    bondColors = []
    highlightRadii = []
    for mol, atomId, radius in envs:
        menv = _getMorganEnv(mol, atomId, radius, baseRad, aromaticColor,
                             ringColor, centerColor, extraColor, **kwargs)
        submols.append(menv.submol)
        highlightAtoms.append(menv.highlightAtoms)
        atomColors.append(menv.atomColors)
        highlightBonds.append(menv.highlightBonds)
        bondColors.append(menv.bondColors)
        highlightRadii.append(menv.highlightRadii)

    if legends is None:
        legends = [''] * len(envs)

    nRows = len(envs) // molsPerRow
    if len(envs) % molsPerRow:
        nRows += 1

    fullSize = (molsPerRow * subImgSize[0], nRows * subImgSize[1])
    # Drawing
    if useSVG:
        drawer = rdMolDraw2D.MolDraw2DSVG(fullSize[0], fullSize[1],
                                          subImgSize[0], subImgSize[1])
    else:
        drawer = rdMolDraw2D.MolDraw2DCairo(fullSize[0], fullSize[1],
                                            subImgSize[0], subImgSize[1])

    if drawOptions is None:
        drawopt = drawer.drawOptions()
        drawopt.continuousHighlight = False
    else:
        drawOptions.continuousHighlight = False
        drawer.SetDrawOptions(drawOptions)
    drawer.DrawMolecules(submols,
                         legends=legends,
                         highlightAtoms=highlightAtoms,
                         highlightAtomColors=atomColors,
                         highlightBonds=highlightBonds,
                         highlightBondColors=bondColors,
                         highlightAtomRadii=highlightRadii,
                         **kwargs)
    drawer.FinishDrawing()
    return drawer.GetDrawingText()
예제 #5
0
def DrawRDKitEnv(mol,
                 bondPath,
                 molSize=(150, 150),
                 baseRad=0.3,
                 useSVG=True,
                 aromaticColor=(0.9, 0.9, 0.2),
                 extraColor=(0.9, 0.9, 0.9),
                 nonAromaticColor=None,
                 drawOptions=None,
                 **kwargs):
    menv = _getRDKitEnv(mol, bondPath, baseRad, aromaticColor, extraColor,
                        nonAromaticColor, **kwargs)

    # Drawing
    if useSVG:
        drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    else:
        drawer = rdMolDraw2D.MolDraw2DCairo(molSize[0], molSize[1])

    if drawOptions is None:
        drawopt = drawer.drawOptions()
        drawopt.continuousHighlight = False
    else:
        drawOptions.continuousHighlight = False
        drawer.SetDrawOptions(drawOptions)

    drawer.DrawMolecule(menv.submol,
                        highlightAtoms=menv.highlightAtoms,
                        highlightAtomColors=menv.atomColors,
                        highlightBonds=menv.highlightBonds,
                        highlightBondColors=menv.bondColors,
                        highlightAtomRadii=menv.highlightRadii,
                        **kwargs)
    drawer.FinishDrawing()
    return drawer.GetDrawingText()
예제 #6
0
def img_for_mol(mol, atom_weights=[]):
    # print(atom_weights)
    highlight_kwargs = {}
    if len(atom_weights) > 0:
        norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)
        cmap = cm.get_cmap('bwr')
        plt_colors = cm.ScalarMappable(norm=norm, cmap=cmap)
        atom_colors = {
            i: plt_colors.to_rgba(atom_weights[i])
            for i in range(len(atom_weights))
        }
        highlight_kwargs = {
            'highlightAtoms': list(range(len(atom_weights))),
            'highlightBonds': [],
            'highlightAtomColors': atom_colors
        }
        # print(highlight_kwargs)

    rdDepictor.Compute2DCoords(mol)
    drawer = rdMolDraw2D.MolDraw2DSVG(280, 280)
    drawer.SetFontSize(1)

    mol = rdMolDraw2D.PrepareMolForDrawing(mol)
    drawer.DrawMolecule(mol, **highlight_kwargs)
    # highlightAtoms=list(range(len(atom_weights))),
    # highlightBonds=[],
    # highlightAtomColors=atom_colors)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    svg = svg.replace('svg:', '')
    svg2png(bytestring=svg, write_to='tmp.png', dpi=100)
    img = imread('tmp.png')
    os.remove('tmp.png')
    return img
def smile_to_smile_to_image(mol,
                            molSize=(128, 128),
                            kekulize=True,
                            mol_name=''):
    mol = Chem.MolFromSmiles(mol)
    mc = Chem.Mol(mol.ToBinary())
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            mc = Chem.Mol(mol.ToBinary())
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    image = Image.open(
        io.BytesIO(
            cairosvg.svg2png(bytestring=svg,
                             parent_width=100,
                             parent_height=100,
                             scale=1)))
    image.convert('RGB')
    return ToTensor()(Invert()(image)).numpy()
예제 #8
0
def highlight_diff(prb_mol, ref_mol, width, height):
    """
    Draw a molecule (prb_mol) with the differences from a reference model highlighted
    :param prb_mol: smiles of the probe molecule
    :param ref_mol: smiles of the reference molecule
    :param width: output image width
    :param height: output image height
    :return: svg string of the image
    """
    if not width:
        width = 200
    if not height:
        height = 200

    mols = [Chem.MolFromSmiles(prb_mol), Chem.MolFromSmiles(ref_mol)]
    [Chem.Kekulize(m) for m in mols]
    match = Chem.rdFMCS.FindMCS(mols,
                                ringMatchesRingOnly=True,
                                completeRingsOnly=True)
    match_mol = Chem.MolFromSmarts(match.smartsString)
    rdDepictor.Compute2DCoords(mols[0])
    unconserved = [
        i for i in range(mols[0].GetNumAtoms())
        if i not in mols[0].GetSubstructMatch(match_mol)
    ]

    drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
    drawer.DrawMolecule(mols[0], highlightAtoms=unconserved)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()

    return svg
예제 #9
0
def draw_fragment(fragment_name, color):

    mol = Chem.MolFromSmarts(re.sub(' \|.*$', '', fragment_name))
    mc = Chem.Mol(mol.ToBinary())
    rdDepictor.Compute2DCoords(mc)

    drawer = rdMolDraw2D.MolDraw2DSVG(80, 80)

    center = int(
        pd.Series({
            atom.GetIdx(): len(atom.GetNeighbors())
            for atom in mol.GetAtoms()
        }).idxmax())

    to_highlight = [center]
    radius_dict = {center: 0.5}
    color_dict = {center: color}

    drawer.DrawMolecule(mc,
                        highlightAtoms=to_highlight,
                        highlightAtomColors=color_dict,
                        highlightAtomRadii=radius_dict,
                        highlightBonds=False)

    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()

    return svg.replace('svg:', '').replace(':svg', '')
예제 #10
0
def _MolsToGridSVG(mols, molsPerRow=3, subImgSize=(200, 200), legends=None, highlightAtomLists=None,
                   highlightBondLists=None, drawOptions=None, **kwargs):
  """ returns an SVG of the grid
  """
  if legends is None:
    legends = [''] * len(mols)

  nRows = len(mols) // molsPerRow
  if len(mols) % molsPerRow:
    nRows += 1

  blocks = [''] * (nRows * molsPerRow)

  fullSize = (molsPerRow * subImgSize[0], nRows * subImgSize[1])

  d2d = rdMolDraw2D.MolDraw2DSVG(fullSize[0], fullSize[1], subImgSize[0], subImgSize[1])
  if drawOptions is not None:
    d2d.SetDrawOptions(drawOptions)
  else:
    dops = d2d.drawOptions()
    for k, v in list(kwargs.items()):
      if hasattr(dops, k):
        setattr(dops, k, v)
        del kwargs[k]
  d2d.DrawMolecules(list(mols), legends=legends, highlightAtoms=highlightAtomLists,
                    highlightBonds=highlightBondLists, **kwargs)
  d2d.FinishDrawing()
  res = d2d.GetDrawingText()
  return res
예제 #11
0
def moltosvg(mol, molSize=(500, 500), kekulize=True):
    mc = mol
    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    return svg.replace('svg:', '')
예제 #12
0
def createImageHighlight(smiles, smarts):
    from rdkit import Chem
    from rdkit.Chem import AllChem
    from rdkit.Chem import rdDepictor
    from rdkit.Chem.Draw import rdMolDraw2D
    from rdkit.Chem.Draw.MolDrawing import DrawingOptions

    mol = Chem.MolFromSmiles(smiles)
    patt = Chem.MolFromSmarts(smarts)
    hitatoms = mol.GetSubstructMatches(patt)  #反応部位のアトムインデックス
    hitatomslist = []
    for x in hitatoms:
        hitatomslist += x
    hitatomsSum = tuple(hitatomslist)
    tm = rdMolDraw2D.PrepareMolForDrawing(mol)
    rdDepictor.Compute2DCoords(mol)  # for generating conformer ID
    # create a drawer container
    drawer = rdMolDraw2D.MolDraw2DSVG(300, 300)
    # define drawer options
    drawer.drawOptions().updateAtomPalette(
        {k: (0, 0, 0)
         for k in DrawingOptions.elemDict.keys()})
    drawer.SetLineWidth(2)
    drawer.SetFontSize(1.0)
    drawer.drawOptions().setHighlightColour((0.95, 0.7, 0.95))  #ハイライトの色指定
    drawer.DrawMolecule(tm, highlightAtoms=hitatomsSum)
    drawer.FinishDrawing()
    # generate and write the svg strings
    svg = drawer.GetDrawingText().replace('svg:', '')
    # "*"記号はファイル名として使えないため、"^"に置換する
    rSmarts = smarts.translate(str.maketrans({"*": "^"}))

    with open("static/images/svgs/" + smiles + "_" + rSmarts + ".svg",
              "w") as f:
        f.write(svg)
예제 #13
0
def DrawMorganEnv(mol, atomId, radius, molSize=(150, 150), baseRad=0.3, useSVG=True,
                  aromaticColor=(0.9, 0.9, 0.2), ringColor=(0.8, 0.8, 0.8),
                  centerColor=(0.6, 0.6, 0.9), extraColor=(0.9, 0.9, 0.9), drawOptions=None,
                  **kwargs):
    """Get SMARTS and SVG image from given ceten and radius
    *internal only*
    """
    menv = _getMorganEnv(mol, atomId, radius, baseRad, aromaticColor, ringColor, centerColor,
                         extraColor, **kwargs)

    submol = menv.submol
    subMol = Chem.MolToSmiles(submol, isomericSmiles=False, allBondsExplicit=True, allHsExplicit=True)
    # Drawing
    if useSVG:
        drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    else:
        drawer = rdMolDraw2D.MolDraw2DCairo(molSize[0], molSize[1])

    if drawOptions is None:
        drawopt = drawer.drawOptions()
        drawopt.continuousHighlight = False
    else:
        drawOptions.continuousHighlight = False
        drawer.SetDrawOptions(drawOptions)

    drawer.DrawMolecule(menv.submol, highlightAtoms=menv.highlightAtoms,
                        highlightAtomColors=menv.atomColors, highlightBonds=menv.highlightBonds,
                        highlightBondColors=menv.bondColors, highlightAtomRadii=menv.highlightRadii,
                        **kwargs)
    drawer.FinishDrawing()
    return subMol, drawer.GetDrawingText().replace('\n', '')
예제 #14
0
def _mols2svg(mols,
              size,
              kekulize=False,
              atomMapNumber=False,
              computeCoords=False,
              highlightAtomLists=None):

    if not mols:
        return ''
    else:
        # process only one molecule
        mols = mols[0:1]

    _call(mols, 'UpdatePropertyCache', strict=False)
    _apply(mols, ct._sssr)

    if computeCoords:
        _apply(mols, _computeCoords, True)
    if atomMapNumber:
        _apply(mols, _atomMapNumber)

    if kekulize:
        _apply(mols, _kekulize)

    if highlightAtomLists:
        highlightAtomLists = highlightAtomLists[0]

    drawer = rdMolDraw2D.MolDraw2DSVG(size, size)
    opts = drawer.drawOptions()
    opts.clearBackground = False
    drawer.DrawMolecule(mols[0], highlightAtoms=highlightAtomLists)
    drawer.FinishDrawing()
    return drawer.GetDrawingText()
예제 #15
0
def VisualizeFragment(mol, highlightAtoms, figsize=[400, 200]):
    from rdkit.Chem.Draw import IPythonConsole, rdMolDraw2D
    from IPython.display import SVG
    from rdkit.Chem import rdDepictor
    """
    This function is used for show which part of fragment matched the SMARTS
    
    Parameters:
    -----------
    mol: rdkit.Chem.rdchem.Mol
        the molecule to be visualized
    atoms: tuple
        the index of atoms to be highlighted
    
    Rrturn:
    -----------
    pic: IPython.core.display.SVG
        a SVG file
    
    Usage:
    ----------- 
    mol = Chem.MolFromSmiles('C1=CC=C2C(=O)CC(=O)C2=C1')    
    pic = VisualizeFragment(mol,(0, 1, 2, 6, 7, 8,10))
    """
    rdDepictor.Compute2DCoords(mol)
    drawer = rdMolDraw2D.MolDraw2DSVG(*figsize)
    drawer.DrawMolecule(mol, highlightAtoms=highlightAtoms)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText().replace('svg:', '')
    fig = SVG(svg)
    return fig
예제 #16
0
 def testDrawMoleculesArgs(self):
   smis = ['O=C1c2cccc3c(N4CCCCC4)ccc(c23)C(=O)N1c1ccccn1', 'Cc1ccc[n+](C2=Nc3ccccc3[N-]C2=C(C#N)C#N)c1', 'CC(=O)NC1=NN(C(C)=O)C(c2ccccn2)S1', 'COc1cc(Cc2nccc3cc(OC)c(OC)cc23)c(S(=O)(=O)O)cc1OC']
   tms = [Chem.MolFromSmiles(x) for x in smis]
   [rdMolDraw2D.PrepareMolForDrawing(x) for x in tms]
   drawer = rdMolDraw2D.MolDraw2DSVG(600,600,300,300)
   p = Chem.MolFromSmarts('c1ccccn1')
   matches = [x.GetSubstructMatch(p) for x in tms]
   acolors = []
   for mv in matches:
       clrs = {}
       random.seed(0xf00d)
       for idx in mv:
           clrs[idx] = (random.random(),random.random(),random.random())
       acolors.append(clrs)
   # the bonds between the matching atoms too
   bnds = []
   for mol,mv in zip(tms,matches):
       tmp = []
       for bnd in p.GetBonds():
           tmp.append(mol.GetBondBetweenAtoms(mv[bnd.GetBeginAtomIdx()],mv[bnd.GetEndAtomIdx()]).GetIdx())
       bnds.append(tmp)
   drawer.DrawMolecules(tms,highlightAtoms=matches,highlightBonds=bnds,highlightAtomColors=acolors)
   drawer.FinishDrawing()
   svg = drawer.GetDrawingText()
   # 4 molecules, 6 bonds each:
   self.assertEqual(svg.count('fill:none;fill-rule:evenodd;stroke:#FF7F7F'),24)
   # 4 molecules, one atom each:
   self.assertEqual(svg.count('fill:#DB2D2B;fill-rule:evenodd;stroke:#DB2D2B'), 4)
예제 #17
0
def smiles_to_svg(smiles, size=(350, 300), draw_options=None):
    """Create an SVG string from a SMILES string.

    Parameters
    ----------
    smiles : str
        SMILES to create SVG image.
    size : tuple, optional
        Size of image, the default is (350, 300).
    draw_options : rdMolDraw2D.MolDrawOptions
        Options to pass to the drawer.

    Returns
    -------
    svg : str
        SVG text for molecule.

    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return ''
    mol = _maybe_kekulize(mol)
    drawer = rdMolDraw2D.MolDraw2DSVG(*size)
    if draw_options:
        drawer.SetDrawOptions(draw_options)
    rdMolDraw2D.PrepareAndDrawMolecule(drawer, mol)
    drawer.FinishDrawing()
    return drawer.GetDrawingText()
예제 #18
0
def mol_to_svg(mol, size=(400,200)):
    """
    Returns a RDKit MolDraw2DSVG object containing an image of the given molecule's structure.

    Args:
        mol (rdkit.Chem.Mol): Object representing molecule.

        size (tuple): Width and height of bounding box of image.

    Returns:
       RDKit.rdMolDraw2D.MolDraw2DSVG text (str): An SVG object containing an image of the molecule's structure.

    """
    img_wd, img_ht = size
    AllChem.Compute2DCoords(mol)
    try:
        mol.GetAtomWithIdx(0).GetExplicitValence()
    except RuntimeError:
        mol.UpdatePropertyCache(False)
    try:
        mc_mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=True)
    except ValueError:
        # can happen on a kekulization failure
        mc_mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False)
    drawer = rdMolDraw2D.MolDraw2DSVG(img_wd, img_ht)
    drawer.DrawMolecule(mc_mol)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    svg = svg.replace('svg:','')
    svg = svg.replace('xmlns:svg','xmlns')
    return svg
예제 #19
0
def draw_mol(
    smiles,
    height=200,
    width=200,
    img_type=None,
    highlightAtoms=[],
    atomcolors=[],
    highlightBonds=[],
    bondcolors={},
    mol=None,
):
    """
    Draw a molecule from a smiles
    :param smiles: the SMILES to render
    :param height: the height in px
    :param width: the width in px
    :return: an SVG as a string of the inage
    """
    if mol is None:
        mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return "None Mol"
    AllChem.Compute2DCoords(mol)
    Chem.Kekulize(mol)
    if not height:
        height = 200
    if not width:
        width = 200
    if img_type == "png":
        img = Draw.MolToImage(
            mol,
            highlightBonds=highlightBonds,
            highlightBondColors=bondcolors,
        )
        img = img.convert("RGBA")
        datas = img.getdata()
        newData = []
        for item in datas:
            if item[0] == 255 and item[1] == 255 and item[2] == 255:
                newData.append((255, 255, 255, 0))
            else:
                newData.append(item)
        img.putdata(newData)
        response = HttpResponse(content_type="image/png")
        img.save(response, "PNG")
        return response
    else:
        drawer = rdMolDraw2D.MolDraw2DSVG(height, width)
        drawopt = drawer.drawOptions()
        drawopt.clearBackground = False
        drawer.DrawMolecule(
            mol,
            highlightAtoms=highlightAtoms,
            highlightAtomColors=atomcolors,
            highlightBonds=highlightBonds,
            highlightBondColors=bondcolors,
        )
        drawer.DrawMolecule(mol)
        drawer.FinishDrawing()
        return drawer.GetDrawingText().replace("svg:", "")
예제 #20
0
def moltosvg_interaction_known(mol, atom_list, atom_predictions,
                               molecule_prediction, molecule_experiment,
                               max_atom_pred, min_atom_pred, Number):

    note = '(' + str(Number) + ') y-y\' : ' + str(round(
        molecule_experiment, 2)) + '-' + str(round(molecule_prediction, 2))
    norm = matplotlib.colors.Normalize(vmin=min_atom_pred * 0.9,
                                       vmax=max_atom_pred * 1.1)
    cmap = cm.get_cmap('gray_r')

    plt_colors = cm.ScalarMappable(norm=norm, cmap=cmap)

    atom_colors = {}
    for i, atom in enumerate(atom_list):
        atom_colors[atom] = plt_colors.to_rgba(atom_predictions[i])
    rdDepictor.Compute2DCoords(mol)

    drawer = rdMolDraw2D.MolDraw2DSVG(280, 218)
    op = drawer.drawOptions()
    for i in range(mol.GetNumAtoms()):
        op.atomLabels[i] = mol.GetAtomWithIdx(i).GetSymbol() + str(i)

    mol = rdMolDraw2D.PrepareMolForDrawing(mol)
    drawer.DrawMolecule(mol,
                        highlightAtoms=atom_list,
                        highlightBonds=[],
                        highlightAtomColors=atom_colors,
                        legend=note)
    drawer.SetFontSize(68)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    return svg.replace('svg:', '')
예제 #21
0
def moldraw(smi, size=(450, 150), kekulize=True, highlight_atoms=None):

    filename = os.path.join(IMAGEPATH, hashlib.sha1(smi).hexdigest() + '.svg')

    mol = Chem.MolFromSmiles(smi)
    mc = Chem.Mol(mol.ToBinary())
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            mc = Chem.Mol(mol.ToBinary())

    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    if highlight_atoms:
        coord_ = _colorizer(mc, highlight_atoms)
    else:
        coord_ = None

    if coord_ is not None:
        dwr = rdMolDraw2D.MolDraw2DSVG(size[0], size[1])
        dwr.DrawMolecule(mc, highlightAtoms=coord_)
        dwr.FinishDrawing()
        svg = dwr.GetDrawingText().replace('svg:', '')
        svg_noframe = '\n'.join(
            [line for line in svg.split('\n') if line[0:5] != '<rect'])

        f = open(filename, 'w')
        f.write(svg_noframe)
        f.close()

        return filename
예제 #22
0
def draw_mol_outlier(smiles, missing_atoms, missing_bonds, figsize=(300, 300)):

    mol = Chem.MolFromSmiles(smiles)
    missing_bonds_adjusted = []
    for bond_index in missing_bonds:

        if bond_index >= mol.GetNumBonds():

            molH = Chem.AddHs(mol)
            bond = molH.GetBondWithIdx(int(bond_index))

            start_atom = mol.GetAtomWithIdx(bond.GetBeginAtomIdx())
            mol = Chem.AddHs(mol, onlyOnAtoms=[start_atom.GetIdx()])
            bond_index = mol.GetNumBonds() - 1

        missing_bonds_adjusted += [int(bond_index)]

    if not mol.GetNumConformers():
        rdDepictor.Compute2DCoords(mol)

    drawer = rdMolDraw2D.MolDraw2DSVG(*figsize)
    drawer.SetFontSize(.6)
    drawer.DrawMolecule(mol,
                        highlightAtoms=[int(index) for index in missing_atoms],
                        highlightBonds=missing_bonds_adjusted)

    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()

    svg = svg.replace('svg:', '').replace(':svg', '')

    if flask:
        return Markup(svg)
    else:
        return svg
예제 #23
0
def drawTopicWeightsMolecule(mol, molID, topicID, topicModel, molSize=(450,200), kekulize=True,\
                             baseRad=0.1, color=(.9,.9,.9), fontSize=0.9):

    # get the atom weights
    atomWeights, maxWeightTopic = _getAtomWeights(mol, molID, topicID,
                                                  topicModel)
    atRads = {}
    atColors = {}

    # color the atoms and set their highlight radius according to their weight
    if np.sum(atomWeights) > 0:
        for at, score in enumerate(atomWeights):
            atColors[at] = color
            atRads[at] = max(atomWeights[at] / maxWeightTopic, 0.0) * baseRad

            if atRads[at] > 0 and atRads[at] < 0.2:
                atRads[at] = 0.2

    try:
        mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize)
    except ValueError:  # <- can happen on a kekulization failure
        mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False)

    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    drawer.SetFontSize(fontSize)
    drawer.DrawMolecule(mc,
                        highlightAtoms=atColors.keys(),
                        highlightAtomColors=atColors,
                        highlightAtomRadii=atRads,
                        highlightBonds=[])
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    return svg.replace('svg:', '')
예제 #24
0
    def _draw_mol_structure(self, mol, figsize=(600, 300)):
        from IPython.display import SVG
        from rdkit import Chem
        from rdkit.Chem import rdDepictor
        from rdkit.Chem.Draw import rdMolDraw2D
        from rdkit.Chem.Draw.MolDrawing import DrawingOptions

        self.logger.info(Chem.MolToSmiles(mol))

        rdDepictor.Compute2DCoords(mol)
        drawer = rdMolDraw2D.MolDraw2DSVG(*figsize)

        drawer.drawOptions().updateAtomPalette({k: (0, 0, 0) for k in DrawingOptions.elemDict.keys()})
        try:
            drawer.SetLineWidth(3)
        except AttributeError:  # for RDkit bug : https://github.com/rdkit/rdkit/issues/2251
            pass
        drawer.SetFontSize(0.7)

        highlight_atoms, color_atoms = self._get_atoms_color(mol.GetNumAtoms())
        highlight_bonds = []
        color_bonds = {}
        drawer.DrawMolecule(mol,
                            highlightAtoms=highlight_atoms,
                            highlightAtomColors=color_atoms,
                            highlightBonds=highlight_bonds,
                            highlightBondColors=color_bonds)

        drawer.FinishDrawing()
        svg = drawer.GetDrawingText().replace('svg:', '')
        SVG(svg)
        saved_filename = f"{self.out_filename}_mol.svg"
        with open(saved_filename, "w") as f:
            f.write(svg)
        self.logger.info(f"[SAVE] {saved_filename}")
예제 #25
0
def _moltoSVG(mol,
              sz,
              highlights,
              legend,
              kekulize,
              drawOptions=None,
              **kwargs):
    try:
        mol.GetAtomWithIdx(0).GetExplicitValence()
    except RuntimeError:
        mol.UpdatePropertyCache(False)

    kekulize = _okToKekulizeMol(mol, kekulize)

    try:
        mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize)
    except ValueError:  # <- can happen on a kekulization failure
        mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False)
    d2d = rdMolDraw2D.MolDraw2DSVG(sz[0], sz[1])
    if drawOptions is not None:
        d2d.SetDrawOptions(drawOptions)

    d2d.DrawMolecule(mc, legend=legend, highlightAtoms=highlights)
    d2d.FinishDrawing()
    svg = d2d.GetDrawingText()
    return svg
예제 #26
0
def show_predictions(mol, prob, cutoff=0.75, show_prob_label=False):
    """
    Build 2D depiction of rdkit molecule
    Label atoms with index number and SOM prediction probabilities if
    above cutoff.
    """

    prob_dict = dict([(int(a.split('.')[1]), b) for a, b in prob.items()])

    Chem.rdDepictor.Compute2DCoords(mol)
    for atom in mol.GetAtoms():
        idx = atom.GetIdx() + 1
        if show_prob_label:
            atom.SetProp('molAtomMapNumber',
                         '{0}-{1:.2f}'.format(idx, prob_dict.get(idx, 0.0)))
        else:
            atom.SetProp('molAtomMapNumber', '{0}'.format(idx))

    drawer = rdMolDraw2D.MolDraw2DSVG(350, 225)
    drawer.DrawMolecule(
        mol,
        highlightAtoms=[i - 1 for i in prob_dict if prob_dict[i] >= cutoff])
    drawer.FinishDrawing()

    return drawer.GetDrawingText().replace('svg:', '')
예제 #27
0
    def testExplictMethyl(self):
        m = Chem.MolFromSmiles('CC')
        d = rdMolDraw2D.MolDraw2DSVG(250, 200)
        rdMolDraw2D.PrepareAndDrawMolecule(d, m)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertEqual(txt.find("class='atom-"), -1)

        d = rdMolDraw2D.MolDraw2DSVG(250, 200)
        do = rdMolDraw2D.MolDrawOptions()
        do.explicitMethyl = True
        d.SetDrawOptions(do)
        rdMolDraw2D.PrepareAndDrawMolecule(d, m)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertNotEqual(txt.find("class='atom-"), -1)
예제 #28
0
def do_a_picture(smi, smarts, filename, label, fmt='svg'):

    rdDepictor.SetPreferCoordGen(True)
    mol = Chem.MolFromSmiles(smi)
    mol = Draw.PrepareMolForDrawing(mol)

    acols = {}
    bcols = {}
    h_rads = {}
    h_lw_mult = {}

    for i, smt in enumerate(smarts):
        alist, blist = get_hit_atoms_and_bonds(mol, smt)
        col = i % 4
        add_colours_to_map(alist, acols, col)
        add_colours_to_map(blist, bcols, col)

    if fmt == 'svg':
        d = rdMolDraw2D.MolDraw2DSVG(300, 300)
        mode = 'w'
    elif fmt == 'png':
        d = rdMolDraw2D.MolDraw2DCairo(300, 300)
        mode = 'wb'
    else:
        print('unknown format {}'.format(fmt))
        return

    d.drawOptions().fillHighlights = False
    d.DrawMoleculeWithHighlights(mol, label, acols, bcols, h_rads, h_lw_mult,
                                 -1)
    d.FinishDrawing()

    with open(filename, mode) as f:
        f.write(d.GetDrawingText())
예제 #29
0
def mol_to_svg(mol, img_file, size=(400, 200)):
    """
    Draw molecule mol's structure into an SVG file with path 'img_file' and with the
    given size.

    Args:
        mol (rdkit.Chem.Mol): Object representing molecule.

        img_file (str): Path to write SVG file to.

        size (tuple): Width and height of bounding box of image.

    """
    img_wd, img_ht = size
    AllChem.Compute2DCoords(mol)
    try:
        mol.GetAtomWithIdx(0).GetExplicitValence()
    except RuntimeError:
        mol.UpdatePropertyCache(False)
    try:
        mc_mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=True)
    except ValueError:
        # can happen on a kekulization failure
        mc_mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False)
    drawer = rdMolDraw2D.MolDraw2DSVG(img_wd, img_ht)
    drawer.DrawMolecule(mc_mol)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    svg = svg.replace('svg:', '')
    svg = svg.replace('xmlns:svg', 'xmlns')
    with open(img_file, 'w') as img_out:
        img_out.write(svg)
예제 #30
0
def mol2im(mc, molSize=(300, 120), kekulize=False, outfile=None, im_type="png"):
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            pass
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    if im_type == "svg":
        drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    else:
        drawer = rdMolDraw2D.MolDraw2DCairo(molSize[0], molSize[1])

    drawer.SetFontSize(drawer.FontSize() * 0.8)
    opts = drawer.drawOptions()
    for i in range(mc.GetNumAtoms()):
        opts.atomLabels[i] = mc.GetAtomWithIdx(i).GetSymbol() + str(i)
    opts.padding = 0.1
    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()

    im = drawer.GetDrawingText()

    if im_type == "svg":
        im = im.replace('svg:', '')
        if outfile:
            with open(outfile, "w") as OUT:
                OUT.write(im)
    else:
        if outfile:
            drawer.WriteDrawingText(outfile)
    return im