Beispiel #1
0
def draw_gt_reaction(data,
                     mapping=False,
                     fontsize=0.98,
                     gt_colors={
                         1: (0.7, 1, 0.7),
                         2: (1, 0.7, 0.7)
                     }):
    r_mol, p_mol = get_react_prouct(data['smarts'], mapping)
    rdDepictor.Compute2DCoords(r_mol)
    rdDepictor.Compute2DCoords(p_mol)
    target_reactants = data['target_main_product'] + data['target_center']
    target_reactants[target_reactants == -1] = 0
    target_product = get_target_product(data) + 1
    r_png = get_molecule_svg(r_mol,
                             target=target_reactants,
                             target_type='GT',
                             gt_colors=gt_colors,
                             dpa=100,
                             fontsize=fontsize)
    p_png = get_molecule_svg(p_mol,
                             target=target_product,
                             target_type='GT',
                             gt_colors=gt_colors,
                             dpa=100,
                             fontsize=fontsize)
    return p_png, r_png
Beispiel #2
0
def createPic(mol : "models.Molecule", format : "models.PictureFormat"):
    content = None
    rd_mol = mol.rdMol
    if format.extension == '.svg':
        rdDepictor.Compute2DCoords(rd_mol)
        mc = Chem.Mol(rd_mol.ToBinary())
        Chem.Kekulize(mc)
        drawer = Draw.MolDraw2DSVG(400,400)
        drawer.DrawMolecule(mc)
        drawer.FinishDrawing()
        content_io = StringIO()
        content_io.write(drawer.GetDrawingText())
    elif format.extension == '.png':
        rdDepictor.Compute2DCoords(rd_mol)
        content = Draw.MolToImage(rd_mol, size=(400, 400))
        content_io = BytesIO()
        content.save(content_io, format='PNG')
    else:
        raise NotImplementedError('Unsupported file format:', format.extension)

    content = ContentFile(content_io.getvalue())
    with transaction.atomic():
        img = models.MoleculePic.objects.create(
                molecule=mol,
                format=format
            )
        img.image.save(f'mol_{mol.id}{format.extension}', content)
        img.save()

    return img
Beispiel #3
0
    def test4SamplingSpread(self):
        mol = Chem.MolFromMolFile(
            os.path.join(RDConfig.RDBaseDir, 'Code/GraphMol/Depictor',
                         'test_data/7UPJ_xtal.mol'))

        # default mode
        rdDepictor.Compute2DCoords(mol, canonOrient=False)
        self.assertTrue(
            compareCoords(
                mol,
                os.path.join(RDConfig.RDBaseDir, 'Code/GraphMol/Depictor',
                             'test_data/7UPJ_default.mol')))

        # spread the structure as much as possible by sampling
        rdDepictor.Compute2DCoords(mol,
                                   canonOrient=False,
                                   nFlipsPerSample=3,
                                   nSample=100,
                                   sampleSeed=100,
                                   permuteDeg4Nodes=1)
        self.assertTrue(
            compareCoords(
                mol,
                os.path.join(RDConfig.RDBaseDir, 'Code/GraphMol/Depictor',
                             'test_data/7UPJ_spread.mol')))
Beispiel #4
0
 def test6ChangeBondLength(self):
     m = Chem.MolFromSmiles('CC')
     rdDepictor.Compute2DCoords(m)
     conf = m.GetConformer()
     self.assertAlmostEqual(conf.GetAtomPosition(0).x, -0.750, 3)
     self.assertAlmostEqual(conf.GetAtomPosition(1).x, 0.750, 3)
     rdDepictor.Compute2DCoords(m, bondLength=1.0)
     conf = m.GetConformer()
     self.assertAlmostEqual(conf.GetAtomPosition(0).x, -0.500, 3)
     self.assertAlmostEqual(conf.GetAtomPosition(1).x, 0.500, 3)
     rdDepictor.Compute2DCoords(m)
     conf = m.GetConformer()
     self.assertAlmostEqual(conf.GetAtomPosition(0).x, -0.750, 3)
     self.assertAlmostEqual(conf.GetAtomPosition(1).x, 0.750, 3)
Beispiel #5
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)
Beispiel #6
0
 def set2DStructure(self):
     if self.smiles:
         try:
             mol = Chem.MolFromSmiles(self.smiles)
             self.molwt = rdMolDescriptors.CalcExactMolWt(mol)
             self.molformula = rdMolDescriptors.CalcMolFormula(mol)
             rdDepictor.Compute2DCoords(mol)
             self.structure_image = Draw.MolToImage(mol, size=(400,200), kekulize=True, wedgeBonds=False)
             pixdata = self.structure_image.load()
             for y in range(self.structure_image.size[1]):
                 for x in range(self.structure_image.size[0]):
                     if pixdata[x, y] == (255, 255, 255, 255):
                         pixdata[x, y] = (255, 255, 255, 0)
             self.structure_qt = ImageQt.ImageQt(self.structure_image)
         except Exception as e:
             print(e)
             self.molwt = False
             self.molformula = False
             self.structure_image = False
             self.structure_data = False
     else:
         self.molwt = False
         self.molformula = False
         self.structure_image = False
         self.structure_data = False
Beispiel #7
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()
Beispiel #9
0
def stereoCompare(smilesFile):
    smiSup = Chem.SmilesMolSupplier(smilesFile, ",", 0, -1)
    for mol in smiSup:
        rdDepictor.Compute2DCoords(mol, canonOrient=False)
        mb = Chem.MolToMolBlock(mol)
        nmol = Chem.MolFromMolBlock(mb)
        matches = nmol.GetSubstructMatches(mol, False)
        dbnds = [
            x for x in mol.GetBonds()
            if (x.GetBondType() == Chem.BondType.DOUBLE
                and x.GetStereo() > Chem.BondStereo.STEREOANY)
        ]
        ok = True
        for match in matches:
            for bnd in dbnds:
                obnd = nmol.GetBondBetweenAtoms(match[bnd.GetBeginAtomIdx()],
                                                match[bnd.GetEndAtomIdx()])
                assert (obnd.GetBondType() == Chem.BondType.DOUBLE)
            if ok:
                break
        if not ok:
            print(Chem.MolToMolBlock(mol), file=sys.stderr)
            print("$$$$", file=sys.stderr)
            return 0
    return 1
Beispiel #10
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:', '')
Beispiel #11
0
def draw_molecule(m, node2color, dpa, fontsize):
    mol = Chem.Mol(m.ToBinary())
    rdDepictor.Compute2DCoords(mol, bondLength=-1.0)
    coords = mol.GetConformer(-1).GetPositions()
    min_p = Geometry.Point2D(*coords.min(0)[:2] - 1)
    max_p = Geometry.Point2D(*coords.max(0)[:2] + 1)
    w = int(dpa * (max_p.x - min_p.x)) + 1
    h = int(dpa * (max_p.y - min_p.y)) + 1
    Chem.Kekulize(mol)

    mcs_bonds = []
    b_col = []
    for i in range(0, len(mol.GetBonds())):
        bond = mol.GetBondWithIdx(i)
        beg_h, end_h = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()

        if beg_h in node2color and end_h in node2color:
            mcs_bonds.append(i)
            b_col.append(max(node2color[beg_h], node2color[end_h]))

    b_col = dict(zip(mcs_bonds, b_col))

    drawer = rdMolDraw2D.MolDraw2DSVG(w, h)
    drawer.SetScale(w, h, min_p, max_p)
    drawer.SetFontSize(fontsize)
    drawer.DrawMolecule(
        mol,
        highlightAtoms=list(node2color.keys()),
        highlightAtomColors=node2color,
        highlightBonds=mcs_bonds,
        highlightBondColors=b_col,
    )
    drawer.FinishDrawing()
    png = drawer.GetDrawingText()
    return png
Beispiel #12
0
def moltosvg_highlight(mol, atom_list, atom_predictions, \
    molSize=(1000,1000),kekulize=False):

    min_pred = np.amin(atom_predictions)
    max_pred = np.amax(atom_predictions)

    norm = matplotlib.colors.Normalize(vmin=min_pred, vmax=max_pred)
    cmap = cm.get_cmap('plasma')

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

    atom_colors = {}
    for i, atom in enumerate(atom_list):
        color_rgba = plt_colors.to_rgba(atom_predictions[i])
        atom_rgb = color_rgba  #(color_rgba[0],color_rgba[1],color_rgba[2])
        atom_colors[atom] = atom_rgb

    rdDepictor.Compute2DCoords(mol)

    drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1])
    #drawer.DrawMolecule(mc)
    drawer.DrawMolecule(mol,
                        highlightAtoms=atom_list,
                        highlightBonds=[],
                        highlightAtomColors=atom_colors)

    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    # It seems that the svg renderer used doesn't quite hit the spec.
    # Here are some fixes to make it work in the notebook, although I think
    # the underlying issue needs to be resolved at the generation step
    return svg.replace('svg:', '')
Beispiel #13
0
def draw_molecule(molec, molsize):
    rdDepictor.Compute2DCoords(molec)
    drawer = rdMolDraw2D.MolDraw2DSVG(molsize[0], molsize[1])
    drawer.DrawMolecule(molec)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    display(SVG(svg.replace("svg:", "")))
Beispiel #14
0
 def toogleEZ(self, bond):
     self.backupMol()
     #Chem.rdmolops.AssignStereochemistry(self._mol,cleanIt=True,force=False)
     stereotype = bond.GetStereo()
     self.assert_stereo_atoms(bond)
     self.logger.debug("Current stereotype of clicked atom %s" % stereotype)
     #TODO: what if molecule already contain STEREOE or STEREOZ
     stereotypes = [
         Chem.rdchem.BondStereo.STEREONONE,
         Chem.rdchem.BondStereo.STEREOCIS,
         Chem.rdchem.BondStereo.STEREOTRANS,
         #                        Chem.rdchem.BondStereo.STEREOANY, TODO, this should be wiggly, but is not
         Chem.rdchem.BondStereo.STEREONONE,
     ]
     newidx = np.argmax(np.array(stereotypes) == stereotype) + 1
     bond.SetStereo(stereotypes[newidx])
     self.logger.debug("New stereotype set to %s" % bond.GetStereo())
     try:
         self.logger.debug(
             "StereoAtoms are %s and %s" % bond.GetStereoAtoms()[0],
             bond.GetStereoAtoms()[1])
     except:
         self.logger.warning("StereoAtoms not defined")
     self._mol.ClearComputedProps()
     #Chem.rdmolops.AssignStereochemistry(self._mol,cleanIt=True,force=False)
     self._mol.UpdatePropertyCache()
     rdDepictor.Compute2DCoords(self._mol)
     self.molChanged.emit()
Beispiel #15
0
def moltosvg(mol, SMARTSinfo, picSize=(400, 400)):
    '''
	mc = Chem.Mol(mol.ToBinary())
	try:
		Chem.Kekulize(mc)
	except:
		mc = Chem.Mol(mol.ToBinary())

	mc.UpdatePropertyCache(strict=False)
	Chem.SanitizeMol(mc, Chem.SanitizeFlags.SANITIZE_KEKULIZE,catchErrors=True)
	'''
    rdDepictor.Compute2DCoords(mol)

    drawer = rdMolDraw2D.MolDraw2DSVG(picSize[0], picSize[1])
    #drawer.SetFontSize(6)
    #drawer.DrawMolecule(mc)
    drawer.DrawMolecule(mol,
                        highlightAtoms=mol.GetSubstructMatch(
                            Chem.MolFromSmarts(SMARTSinfo)))
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    '''
	smartMol = Chem.MolFromSmarts(SMARTSinfo)
	Chem.Kekulize(smartMol)
	rdDepictor.Compute2DCoords(smartMol)
	drawer2 = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])
	drawer2.DrawMolecule(smartMol)
	drawer2.FinishDrawing()
	svg2 = drawer2.GetDrawingText()
	'''
    #return svg.replace('svg:',''), svg2.replace('svg:','')
    return svg
Beispiel #16
0
def moltosvg(mol, molSize=(400,400), index=False, kekulize=True):
    
    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])
    opts = drawer.drawOptions()
    if index:
        for i in range(mc.GetNumAtoms()):
            opts.atomLabels[i] = str(i)

    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    
    # It seems that the svg renderer used doesn't quite hit the spec.
    # Here are some fixes to make it work in the notebook, although I think
    # the underlying issue needs to be resolved at the generation step
    
    return svg.replace('svg:','')
Beispiel #17
0
def weight_visulize_origin(smiles, atom_weight):
    print(smiles)
    mol = Chem.MolFromSmiles(smiles)
    norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
    cmap = cm.get_cmap('Oranges')
    plt_colors = cm.ScalarMappable(norm=norm, cmap=cmap)
    atom_colors = {}
    atom_raddi = {}
    # weight_norm = np.array(ind_weight).flatten()
    # threshold = weight_norm[np.argsort(weight_norm)[1]]
    # weight_norm = np.where(weight_norm < threshold, 0, weight_norm)
    
    for i in range(mol.GetNumAtoms()):
        if atom_weight[i] <= 0.3:
            atom_colors[i] = plt_colors.to_rgba(float(0.05))
        elif atom_weight[i] <= 0.4:
            atom_colors[i] = plt_colors.to_rgba(float(0.25))
        elif atom_weight[i] <= 0.5:
            atom_colors[i] = plt_colors.to_rgba(float(0.6))
        else:
            atom_colors[i] = plt_colors.to_rgba(float(1.0))
    rdDepictor.Compute2DCoords(mol)
    
    drawer = rdMolDraw2D.MolDraw2DSVG(280, 280)
    drawer.SetFontSize(1)
    op = drawer.drawOptions()
    
    mol = rdMolDraw2D.PrepareMolForDrawing(mol)
    drawer.DrawMolecule(mol, highlightAtoms=range(0, mol.GetNumAtoms()), highlightBonds=[],
                        highlightAtomColors=atom_colors)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText()
    svg2 = svg.replace('svg:', '')
    svg3 = SVG(svg2)
    display(svg3)
Beispiel #18
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}")
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', '')
Beispiel #20
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
Beispiel #21
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
 def make_svg(self):
     drawer = Draw.rdMolDraw2D.MolDraw2DSVG(400, 200)
     rdDepictor.Compute2DCoords(self.mol)
     drawer.DrawMolecule(self.mol)
     drawer.FinishDrawing()
     svg = drawer.GetDrawingText()
     open(f'svgs/{self.name}.svg', 'w').write(svg)
    def make_skeleton(self, Cnlist):
        from rdkit import Chem
        from rdkit.Chem import rdDepictor
        from rdkit.Chem import Draw
        from PIL import Image

        for Cn in Cnlist:
            with open('KNApSAck_mol/%s.mol' % Cn)as fi:
                mol = Chem.MolFromMolBlock(fi.read())
                rdDepictor.Compute2DCoords(mol)
                filename = self.genus + "/" + Cn + ".png"
                im = Draw.MolToImage(mol, size=(500, 500))
                trans = Image.new('RGBA', im.size, (0, 0, 0, 0))
                width = im.size[0]
                height = im.size[1]
                for x in range(width):
                    for y in range(height):
                        pixel = im.getpixel( (x, y) )

                        # 白なら処理しない
                        if pixel[0] == 255 and pixel[1] == 255 and pixel[2] == 255:
                            continue

                        # 白以外なら、用意した画像にピクセルを書き込み
                        trans.putpixel( (x, y), pixel )
                # 透過画像を保存
                trans.save(filename)
Beispiel #24
0
def mol_to_svg(mol, min_size=50, max_size=300, bond_length=25, padding=10):
    """Creates a (cropped) SVG molecule drawing as a string.

    Args:
        mol: RDKit Mol.
        min_size: Integer minimum image size (in pixels).
        max_size: Integer maximum image size (in pixels).
        bond_length: Integer bond length (in pixels).
        padding: Integer number of padding pixels in each dimension.

    Returns:
        String SVG image.
    """
    Chem.Kekulize(mol)
    rdDepictor.Compute2DCoords(mol)
    drawer = _draw_svg(mol,
                       size_x=max_size,
                       size_y=max_size,
                       bond_length=bond_length)
    # Find the extent of the drawn image so we can crop the canvas.
    min_x, max_x, min_y, max_y = np.inf, -np.inf, np.inf, -np.inf
    for atom in mol.GetAtoms():
        canvas_x, canvas_y = drawer.GetDrawCoords(atom.GetIdx())
        min_x = min(canvas_x, min_x)
        max_x = max(canvas_x, max_x)
        min_y = min(canvas_y, min_y)
        max_y = max(canvas_y, max_y)
    drawer = _draw_svg(mol,
                       size_x=max(min_size, int(max_x - min_x + 2 * padding)),
                       size_y=max(min_size, int(max_y - min_y + 2 * padding)),
                       bond_length=bond_length)
    match = re.search(r'(<svg\s+.*</svg>)',
                      drawer.GetDrawingText(),
                      flags=re.DOTALL)
    return match.group(1)
Beispiel #25
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
Beispiel #26
0
 def computeNewCoords(self, ignoreExisting=False):
     """Computes new coordinates for the molecule taking into account all
     existing positions (feeding these to the rdkit coordinate generation as
     prev_coords).
     """
     # This code is buggy when you are not using the CoordGen coordinate
     # generation system, so we enable it here
     rdDepictor.SetPreferCoordGen(True)
     prev_coords = {}
     if self._mol.GetNumConformers() == 0:
         self.logger.debug("No Conformers found, computing all 2D coords")
     elif ignoreExisting:
         self.logger.debug("Ignoring existing conformers, computing all "
                           "2D coords")
     else:
         assert self._mol.GetNumConformers() == 1
         self.logger.debug("1 Conformer found, computing 2D coords not in "
                           "found conformer")
         conf = self._mol.GetConformer(0)
         for a in self._mol.GetAtoms():
             pos3d = conf.GetAtomPosition(a.GetIdx())
             if (pos3d.x, pos3d.y) == (0, 0):
                 continue
             prev_coords[a.GetIdx()] = Point2D(pos3d.x, pos3d.y)
     rdDepictor.Compute2DCoords(self._mol, coordMap=prev_coords)
Beispiel #27
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
Beispiel #28
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

        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)
Beispiel #29
0
        def __call__(self, arg):
            res = list(arg)
            if self.verbose:
                sys.stderr.write('Render(%d): %s\n' %
                                 (self.smiCol, str(res[0])))
            smi = res[self.smiCol]
            aspect = 1
            width = self.width
            height = aspect * width
            try:
                mol = Chem.MolFromSmiles(smi)
                Chem.Kekulize(mol)
                canv = Canvas((width, height))
                options = DrawingOptions()
                options.atomLabelMinFontSize = 3
                options.bondLineWidth = 0.5
                drawing = MolDrawing(options=options)
                if not mol.GetNumConformers():
                    rdDepictor.Compute2DCoords(mol)
                drawing.AddMol(mol, canvas=canv)
                ok = True
            except Exception:
                if self.verbose:
                    import traceback
                    traceback.print_exc()
                ok = False

            if ok:
                res[self.smiCol] = canv.drawing
            else:
                # FIX: maybe include smiles here in a Paragraph?
                res[self.smiCol] = 'Failed'
            return res
Beispiel #30
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