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
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)
def _moltoSVG(mol, sz, highlights, legend, kekulize, drawOptions=None, **kwargs): try: with rdBase.BlockLogs(): mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) kekulize = _okToKekulizeMol(mol, kekulize) try: with rdBase.BlockLogs(): 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) # we already prepared the molecule: d2d.drawOptions().prepareMolsBeforeDrawing = False bondHighlights = kwargs.get('highlightBonds', None) if bondHighlights is not None: d2d.DrawMolecule(mc, legend=legend or "", highlightAtoms=highlights or [], highlightBonds=bondHighlights) else: d2d.DrawMolecule(mc, legend=legend or "", highlightAtoms=highlights or []) d2d.FinishDrawing() svg = d2d.GetDrawingText() return svg
def sanitizeMol(self, kekulize=False): self.computeNewCoords() self._drawmol = Chem.Mol(self._mol.ToBinary()) #Is this necessary? try: Chem.SanitizeMol(self._drawmol) self.sanitizeSignal.emit("Sanitizable") except: self.sanitizeSignal.emit("UNSANITIZABLE") self.logger.warning("Unsanitizable") try: self._drawmol.UpdatePropertyCache(strict=False) except: self.sanitizeSignal.emit("UpdatePropertyCache FAIL") self.logger.error("Update Property Cache failed") #Kekulize if kekulize: try: Chem.Kekulize(self._drawmol) except: self.logger.warning("Unkekulizable") try: self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=kekulize) except ValueError: # <- can happen on a kekulization failure self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=False)
def _moltoimg(mol, sz, highlights, legend, returnPNG=False, **kwargs): try: mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) kekulize = _okToKekulizeMol(mol, kwargs.get('kekulize', True)) try: mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize) except ValueError: # <- can happen on a kekulization failure mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False) if not hasattr(rdMolDraw2D, 'MolDraw2DCairo'): img = MolToImage(mc, sz, legend=legend, highlightAtoms=highlights, **kwargs) if returnPNG: bio = BytesIO() img.save(bio, format='PNG') img = bio.getvalue() else: d2d = rdMolDraw2D.MolDraw2DCairo(sz[0], sz[1]) d2d.DrawMolecule(mc, legend=legend, highlightAtoms=highlights) d2d.FinishDrawing() if returnPNG: img = d2d.GetDrawingText() else: img = _drawerToImage(d2d) return img
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:', '')
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
def _moltoimg(mol, sz, highlights, legend, returnPNG=False, drawOptions=None, **kwargs): try: blocker = rdBase.BlockLogs() mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) kekulize = _okToKekulizeMol(mol, kwargs.get('kekulize', True)) wedge = kwargs.get('wedgeBonds', True) try: blocker = rdBase.BlockLogs() mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize, wedgeBonds=wedge) except ValueError: # <- can happen on a kekulization failure mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False, wedgeBonds=wedge) if not hasattr(rdMolDraw2D, 'MolDraw2DCairo'): img = MolToImage(mc, sz, legend=legend, highlightAtoms=highlights, **kwargs) if returnPNG: bio = BytesIO() img.save(bio, format='PNG') img = bio.getvalue() else: d2d = rdMolDraw2D.MolDraw2DCairo(sz[0], sz[1]) if drawOptions is not None: d2d.SetDrawOptions(drawOptions) if 'highlightColor' in kwargs: d2d.drawOptions().setHighlightColor(kwargs['highlightColor']) # we already prepared the molecule: d2d.drawOptions().prepareMolsBeforeDrawing = False bondHighlights = kwargs.get('highlightBonds', None) if bondHighlights is not None: d2d.DrawMolecule(mc, legend=legend or "", highlightAtoms=highlights or [], highlightBonds=bondHighlights) else: d2d.DrawMolecule(mc, legend=legend or "", highlightAtoms=highlights or []) d2d.FinishDrawing() if returnPNG: img = d2d.GetDrawingText() else: img = _drawerToImage(d2d) return img
def testPrepareForDrawing(self): m = Chem.MolFromSmiles('c1ccccc1[C@H](F)Cl') nm = rdMolDraw2D.PrepareMolForDrawing(m) self.assertEqual(nm.GetNumAtoms(), 9) self.assertEqual(nm.GetNumConformers(), 1) m = Chem.MolFromSmiles('C1CC[C@H]2NCCCC2C1') nm = rdMolDraw2D.PrepareMolForDrawing(m) self.assertEqual(nm.GetNumAtoms(), 11) self.assertEqual(nm.GetNumConformers(), 1) nm = rdMolDraw2D.PrepareMolForDrawing(m, addChiralHs=False) self.assertEqual(nm.GetNumAtoms(), 10) self.assertEqual(nm.GetNumConformers(), 1)
def _draw_mol(self, mol, kekulize=True, add_chiral_hs=True): if mol is None: raise ValueError( 'Expected a rdkit molecule instance but got \'None\'') mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize, addChiralHs=add_chiral_hs) mol = SlideGenerator._scale_bond_length(mol) drawer = rdMolDraw2D.MolDraw2DCairo(self.image_width, self.molecule_image_height) drawer.SetFontSize(self.font_size) opts = drawer.drawOptions() opts.clearBackground = False opts.bondLineWidth = self.bond_width opts.fixedBondLength = self.bond_length opts.minFontSize = self.font_size opts.maxFontSize = self.font_size opts.fontFile = self.font_path drawer.DrawMolecule(mol) drawer.FinishDrawing() png = drawer.GetDrawingText() mol_image = Image.open(BytesIO(png)) mol_image.load() return mol_image
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)
async def popochem(self, ctx, *, name: str): outstr = "" properties = [ "IUPACName", "MolecularFormula", "MolecularWeight", "CanonicalSMILES" ] translator = Translator() name = translator.translate(text=name, dest="en").text rslt = pcp.get_properties(properties, name, "name") if rslt == []: outstr += "検索した分子は見つかりませんでした.\nタイプミス等の可能性があります." await ctx.send(outstr) else: smiles = rslt[0].get("CanonicalSMILES") if rslt[0].get("IUPACName") is not None: iupac_name = "IUPAC名: " + rslt[0].get("IUPACName") + "\n" else: iupac_name = "" mol_info = "分子式 (分子量): " + rslt[0].get("MolecularFormula") + \ " (" + rslt[0].get("MolecularWeight") + ")" outstr += iupac_name + mol_info view = rdMolDraw2D.MolDraw2DCairo(330, 300) options = view.drawOptions() options.legendFontSize = 24 options.multipleBondOffset = 0.1 options.useBWAtomPalette() struct = rdMolDraw2D.PrepareMolForDrawing( Chem.MolFromSmiles(smiles)) view.DrawMolecule(struct) view.FinishDrawing() view.WriteDrawingText("structure.png") img_path = discord.File("structure.png") await ctx.send(outstr, file=img_path) os.remove("structure.png")
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)
def render(self, params, d): molfile = params['molfile'][0] svg_width = int(params['width'][0]) svg_height = int(params['height'][0]) print "Render (" + str(svg_width) + ", " + str( svg_height) + ") image of '" + molfile[0:30].replace('\n', ' ') + "...'" mol = Chem.MolFromMolBlock(molfile, sanitize=False) if mol == None: raise Exception("Unable to read molfile.") # Update valences etc. so drawing code doesn't choke on the non-sanitized input. mol.UpdatePropertyCache(strict=False) # And ring info also needs to be there. Chem.rdmolops.GetSSSR(mol) rdMolDraw2D.PrepareMolForDrawing(mol) drawer = rdMolDraw2D.MolDraw2DSVG(svg_width, svg_height) drawer.DrawMolecule(mol) drawer.FinishDrawing() svg = drawer.GetDrawingText() d['svg'] = svg return d
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)
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 _toPNG(mol): if hasattr(mol, '__sssAtoms'): highlightAtoms = mol.__sssAtoms else: highlightAtoms = [] try: mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) if not hasattr(rdMolDraw2D, 'MolDraw2DCairo'): mc = copy.deepcopy(mol) try: img = Draw.MolToImage(mc, size=molSize, kekulize=kekulizeStructures, highlightAtoms=highlightAtoms) except ValueError: # <- can happen on a kekulization failure mc = copy.deepcopy(mol) img = Draw.MolToImage(mc, size=molSize, kekulize=False, highlightAtoms=highlightAtoms) bio = BytesIO() img.save(bio, format='PNG') return bio.getvalue() else: nmol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulizeStructures) d2d = rdMolDraw2D.MolDraw2DCairo(molSize[0], molSize[1]) d2d.DrawMolecule(nmol, highlightAtoms=highlightAtoms) d2d.FinishDrawing() return d2d.GetDrawingText()
def draw_cpd_with_labels(self, image_file="mol.svg", height=300, width=500, highlightAtoms=[], highlightAtomColors={}, highlightAtomRadii={}, start=0, custom_label=None): """ depicts the compound with node labels and saves it as image_file in the working directory. If the 2D coordinates are not calculated yet, this method calls self._compute_2d_coords(). """ if not self.fit2d: self._compute_2d_coords() if custom_label is None: node_label = self._get_node_labels(start) else: node_label = custom_label view = rdMolDraw2D.MolDraw2DSVG(height,width) tm = rdMolDraw2D.PrepareMolForDrawing(self.mol) view.SetFontSize(0.9*view.FontSize()) option = view.drawOptions() for k, v in sorted(node_label.items()): option.atomLabels[k] = v #option.atomLabels[6] = 'N1' #option.atomLabels[8] = 'N2' #option.multipleBondOffset=0.07 #option.padding=0.11 #option.legendFontSize=20 view.DrawMolecule(tm, highlightAtoms=highlightAtoms, highlightAtomColors=highlightAtomColors, highlightAtomRadii=highlightAtomRadii) view.FinishDrawing() svg = view.GetDrawingText() with open(image_file, 'w') as f: f.write(svg) return SVG(svg.replace('svg:', ''))
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:', '')
def moltosvg(mol, molSize=(450, 200), kekulize=True, drawer=None, **kwargs): mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize) if drawer is None: drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1]) drawer.DrawMolecule(mc, **kwargs) drawer.FinishDrawing() svg = drawer.GetDrawingText() return SVG(svg.replace('svg:', ''))
def graphSVG(self, filedir, mol): tm = rdMolDraw2D.PrepareMolForDrawing(mol) view = rdMolDraw2D.MolDraw2DSVG(500, 500) view.DrawMolecule(tm) view.FinishDrawing() svg = view.GetDrawingText() with open(filedir, "w") as f: f.writelines(svg)
def _MolsToGridSVG(mols, molsPerRow=3, subImgSize=(200, 200), legends=None, highlightAtomLists=None, stripSVGNamespace=True, **kwargs): """ returns an SVG of the grid """ matcher = re.compile( r'^(<.*>\n)(<svg:rect .*</svg\:rect>\n)(.*)</svg\:svg>', re.DOTALL) if legends is None: legends = [''] * len(mols) hdr = '' ftr = '</svg:svg>' rect = '' nRows = len(mols) // molsPerRow if len(mols) % molsPerRow: nRows += 1 blocks = [''] * (nRows * molsPerRow) fullSize = (molsPerRow * subImgSize[0], nRows * subImgSize[1]) for i, mol in enumerate(mols): highlights = None if highlightAtomLists and highlightAtomLists[i]: highlights = highlightAtomLists[i] if mol is not None: nmol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kwargs.get( 'kekulize', True)) d2d = rdMolDraw2D.MolDraw2DSVG(subImgSize[0], subImgSize[1]) d2d.DrawMolecule(nmol, legend=legends[i], highlightAtoms=highlights) d2d.FinishDrawing() txt = d2d.GetDrawingText() h, r, b = matcher.match(txt).groups() if not hdr: hdr = h.replace("width='%dpx' height='%dpx' >" % subImgSize, "width='%dpx' height='%dpx' >" % fullSize) if not rect: rect = r blocks[i] = b for i, elem in enumerate(blocks): row = i // molsPerRow col = i % molsPerRow elem = rect + elem blocks[i] = '<g transform="translate(%d,%d)" >%s</g>' % ( col * subImgSize[0], row * subImgSize[1], elem) res = hdr + '\n'.join(blocks) + ftr if stripSVGNamespace: res = res.replace('svg:', '') return res
def draw_pretty_2D_pics(mol): """ Given an RDKit mol object, return an SVG picture """ rdDepictor.Compute2DCoords(mol) mc_mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=True) drawer = rdMolDraw2D.MolDraw2DSVG(400, 200) drawer.DrawMolecule(mc_mol) drawer.FinishDrawing() svg = drawer.GetDrawingText().replace("svg:", "") return SVG(svg)
def testPrepareForDrawing(self): m = Chem.MolFromSmiles('c1ccccc1[C@H](F)Cl') nm = rdMolDraw2D.PrepareMolForDrawing(m) self.assertEqual(nm.GetNumAtoms(), 9) self.assertEqual(nm.GetNumConformers(), 1) m = Chem.MolFromSmiles('C1CC[C@H]2NCCCC2C1') nm = rdMolDraw2D.PrepareMolForDrawing(m) self.assertEqual(nm.GetNumAtoms(), 11) self.assertEqual(nm.GetNumConformers(), 1) nm = rdMolDraw2D.PrepareMolForDrawing(m, addChiralHs=False) self.assertEqual(nm.GetNumAtoms(), 10) self.assertEqual(nm.GetNumConformers(), 1) m = Chem.MolFromSmiles('CC=CC') m.GetBondWithIdx(1).SetStereo(Chem.BondStereo.STEREOANY) nm = rdMolDraw2D.PrepareMolForDrawing(m) self.assertEqual(nm.GetBondWithIdx(1).GetStereo(), Chem.BondStereo.STEREOANY) self.assertEqual(nm.GetBondWithIdx(0).GetBondDir(), Chem.BondDir.NONE) nm = rdMolDraw2D.PrepareMolForDrawing(m, wavyBonds=True) self.assertEqual(nm.GetBondWithIdx(1).GetStereo(), Chem.BondStereo.STEREONONE) self.assertEqual(nm.GetBondWithIdx(0).GetBondDir(), Chem.BondDir.UNKNOWN)
def _toSVG(mol): if not ipython_useSVG: return None if hasattr(mol, '__sssAtoms'): highlightAtoms = mol.__sssAtoms else: highlightAtoms = [] try: mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) try: mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulizeStructures) except ValueError: # <- can happen on a kekulization failure mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False) d2d = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1]) d2d.DrawMolecule(mc, highlightAtoms=highlightAtoms) d2d.FinishDrawing() svg = d2d.GetDrawingText() return svg.replace("svg:", "")
def DrawMol(mol, out_path, size=(500, 500)): drawer = rdMolDraw2D.MolDraw2DCairo(size[0], size[1]) tm = rdMolDraw2D.PrepareMolForDrawing(mol) option = drawer.drawOptions() option.addAtomIndices = True drawer.DrawMolecule(tm) drawer.FinishDrawing() img = drawer.GetDrawingText() with open(out_path, mode="wb") as f: f.write(img)
def GenClustTable( Mol_List, output_name, column=5 ): Img_Data = [] for idx, Mols in enumerate(Mol_List): Img = [] for mol in Mols: # Get molecule info try: m1 = mol.GetProp('Name') except KeyError: name = mol.GetProp('_Name') if re.search(r'::', name): m1 = name.split('::')[0] else: m1 = name try: m2 = mol.GetProp('Rank') except KeyError: m2 = '' try: m3 = mol.GetProp('Score') except KeyError: m3 = '' try: m4 = mol.GetProp('Type') except KeyError: m4 = '' # Create tag and write out to sdf file mol.SetProp('Cluster', str(idx+1)) mol.SetProp('SMILES' , Chem.MolToSmiles(mol)) AssignStereochemistryFrom3D(mol) svg_name = '_TEMP.'+m1+'.svg' mol = Chem.MolFromSmiles(Chem.MolToSmiles(mol)) rdMolDraw2D.PrepareMolForDrawing(mol) mol = Chem.RemoveHs(mol) AllChem.Compute2DCoords(mol) DrawingOptions.atomLabelFontSize=18 Draw.MolToFile(mol, svg_name, size=(225,225)) # cairosvg.svg2png( url=svg_name, write_to=png_name, dpi=240 ) img_link = '<img src="'+svg_name+'">' # Img = (image_link, Name, Rank, Score, Type) Img.append([img_link, m1, m2, m3, m4]) Img_Data.append(Img) ## Print out a HTML page, in which every row has a maximum of 5 compound png. ## Every major cluster of compounds is grouped together. ## List the Name of the compound, then the Rank and Score. grid_print(output_name, Img_Data, 'formatted', column=5) os.system('rm ./_TEMP.*.svg ./{0}.html'.format(output_name))
def sanitizeMol(self, kekulize=False): self._drawmol = Chem.Mol(self._mol.ToBinary()) #Is this necessary? try: Chem.SanitizeMol(self._drawmol) self.sanitizeSignal.emit("Sanitizable") except: self.sanitizeSignal.emit("UNSANITIZABLE") self.logger.warning("Unsanitizable") try: self._drawmol.UpdatePropertyCache(strict=False) except: self.sanitizeSignal.emit("UpdatePropertyCache FAIL") self.logger.error("Update Property Cache failed") #Kekulize if kekulize: try: Chem.Kekulize(self._drawmol) except: self.logger.warning("Unkekulizable") try: self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=kekulize) except ValueError: # <- can happen on a kekulization failure self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=False) #Generate 2D coords if none present if not self._drawmol.GetNumConformers(): rdDepictor.Compute2DCoords(self._drawmol) self.logger.debug("No Conformers found, computing 2D coords") else: #TODO match to already drawed self.logger.debug("%i Conformers in molecule" % self._drawmol.GetNumConformers()) # try: # rdDepictor.GenerateDepictionMatching2DStructure(self._drawmol, self._prevmol)#, acceptFailure=True) # except: rdDepictor.Compute2DCoords(self._drawmol)
def draw_mol_smi(smi, size=(300, 300), highlights=None, legend=None, kekulize=True, use_default_setting=True, **kwargs): mol = Chem.MolFromSmiles(smi) if mol is None: raise ValueError('SMILES Parse Error') try: mol.GetAtomWithIdx(0).GetExplicitValence() except RuntimeError: mol.UpdatePropertyCache(False) kekulize = _okToKekulizeMol(mol, kekulize) d2d = rdMolDraw2D.MolDraw2DSVG(size[0], size[1]) if use_default_setting: d2d.SetFontSize(1.3 * d2d.FontSize()) option = d2d.drawOptions() # option.circleAtoms = False # option.continuousHighlight = False # option.legendFontSize = 20 option.multipleBondOffset = 0.07 if legend is not None: option.padding = 0.11 try: mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize) except ValueError: # <- can happen on a kekulization failure mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=False) # d2d.DrawMolecule(mc, legend=legend, highlightAtoms=highlights) d2d.DrawMolecule(mc, highlightAtoms=highlights) d2d.FinishDrawing() svg = d2d.GetDrawingText() return svg
def check_task(request): task_id = request.GET["task_id"] result_key = "task_result_{}".format(task_id) result = redis_client.get(result_key) if result: result = ast.literal_eval(result) #draw molecules drawer = rdMolDraw2D.MolDraw2DSVG(1000, 600) drawer.SetFontSize(.6) opts = drawer.drawOptions() weightedShift = { int(item.split(',')[0]): item.split(',')[1] for item in filter(None, result['weightedShiftTxt'].split(';')) } for k, v in weightedShift.items(): opts.atomLabels[k - 1] = v opts.clearBackground = False opts.bondLineWidth = 0.5 opts.padding = 0.1 opts.additionalAtomLabelPadding = 0.3 smiles = result['smiles'] mol = Chem.MolFromSmiles(smiles) AllChem.Compute2DCoords(mol) mol = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=True) drawer.DrawMolecule(mol) drawer.FinishDrawing() svg = drawer.GetDrawingText().replace('svg:', '').replace(':svg', '') result_html = render( request, "cascade/results.html", { 'jsmol_command': result['jsmol_command'], 'svg': svg, 'smiles': smiles, 'weightedShift': result['weightedShiftTxt'], 'confShift': result['confShiftTxt'], 'relative_E': result['relative_E'], 'taskId': task_id, }) return result_html else: return HttpResponse('running')