def testPrepareAndDrawMolecule(self): m = Chem.MolFromSmiles("C1N[C@@H]2OCC12") d = Draw.MolDraw2DSVG(300, 300, -1, -1, True) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() self.assertTrue(txt.find(">H</text>") > 0)
def plot_mol_with_color(smi, x_with_w_norm, save_name): mol = Chem.MolFromSmiles(smi) atoms = mol.GetNumAtoms() #for i in range( atoms ): #mol.GetAtomWithIdx(i).SetProp( #'molAtomMapNumber', str(mol.GetAtomWithIdx(i).GetIdx())) d = rdMolDraw2D.MolDraw2DCairo(500, 500) atom_list = list(range(atoms)) atom_cols = {} for index, i in enumerate(list(x_with_w_norm)): atom_cols[index] = (0, 0, i) rdMolDraw2D.PrepareAndDrawMolecule( d, mol, highlightAtoms=atom_list, highlightAtomColors=atom_cols, ) with open(save_name, 'wb') as f: f.write(d.GetDrawingText()) return mol
def func(pathname, pathkey, pathvalue, template): template = Chem.MolFromSmarts(template) pathname = Chem.MolFromSmiles(pathkey) # pathname.GetSubstructMatches(template) # a=pathname.GetSubstructMatches(template) # z = Chem.Draw.MolToImage(pathname, size=(300, 300), kekulize=True, wedgeBonds=True, useSVG=True,highlightAtoms=list(a[0])) # z.save("pathname.png","PNG") # Compute2DCoords(z) drawer = rdMolDraw2D.MolDraw2DSVG(250, 250) hit_bonds = [] hit_ats = list(pathname.GetSubstructMatch(template)) for bond in template.GetBonds(): aid1 = hit_ats[bond.GetBeginAtomIdx()] aid2 = hit_ats[bond.GetEndAtomIdx()] hit_bonds.append(pathname.GetBondBetweenAtoms(aid1, aid2).GetIdx()) rdMolDraw2D.PrepareAndDrawMolecule(drawer, pathname, highlightAtoms=hit_ats, highlightBonds=hit_bonds) drawer.DrawMolecule(pathname) drawer.FinishDrawing() # print(drawer.GetDrawingText()) return drawer.GetDrawingText()
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()
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)
def testSetDrawOptions(self): m = Chem.MolFromSmiles('CCNC(=O)O') d = rdMolDraw2D.MolDraw2DSVG(250, 200, -1, -1, True) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() self.assertNotEqual(txt.find("fill:#0000FF' >N</text>"), -1) self.assertEqual(txt.find("fill:#000000' >N</text>"), -1) d = rdMolDraw2D.MolDraw2DSVG(250, 200, -1, -1, True) do = rdMolDraw2D.MolDrawOptions() do.useBWAtomPalette() d.SetDrawOptions(do) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() self.assertEqual(txt.find("fill:#0000FF' >N</text>"), -1) self.assertNotEqual(txt.find("fill:#000000' >N</text>"), -1)
def testPrepareAndDrawMolecule(self): m = Chem.MolFromSmiles("C1N[C@@H]2OCC12") d = Draw.MolDraw2DSVG(300, 300, -1, -1, True) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() self.assertTrue(txt.find(">H</text>") > 0) m = Chem.MolFromSmiles("c1ccccc1") d = Draw.MolDraw2DSVG(300, 300, -1, -1, True) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() self.assertLess(txt.find("stroke-dasharray"), 0) d = Draw.MolDraw2DSVG(300, 300, -1, -1, True) rdMolDraw2D.PrepareAndDrawMolecule(d, m, kekulize=False) d.FinishDrawing() txt = d.GetDrawingText() self.assertGreater(txt.find("stroke-dasharray"), 0)
def testAtomTagging(self): m = Chem.MolFromSmiles("C1N[C@@H]2OCC12") d = Draw.MolDraw2DSVG(300, 300) dm = Draw.PrepareMolForDrawing(m) rdMolDraw2D.PrepareAndDrawMolecule(d, dm) d.TagAtoms(dm, events={'onclick': 'alert'}) d.FinishDrawing() txt = d.GetDrawingText() self.assertTrue(txt.find("<circle") > 0) self.assertTrue(txt.find("onclick=") > 0)
def testAlternativeFreetypeFont(self): # this one, you have to look at the pictures m = Chem.MolFromSmiles('S(=O)(=O)(O)c1c(Cl)c(Br)c(I)c(F)c(N)1') d = rdMolDraw2D.MolDraw2DSVG(250, 200) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() with open('test_ff.svg', 'w') as f: f.write(txt) d = rdMolDraw2D.MolDraw2DSVG(250, 200) do = rdMolDraw2D.MolDrawOptions() rdbase = environ['RDBASE'] if rdbase: do.fontFile = '{}/Code/GraphMol/MolDraw2D/Amadeus.ttf'.format(rdbase) d.SetDrawOptions(do) rdMolDraw2D.PrepareAndDrawMolecule(d, m) d.FinishDrawing() txt = d.GetDrawingText() with open('test_aff.svg', 'w') as f: f.write(txt) else: pass
def smiles_to_svg(smiles: str, torsion_indices: (int, int), image_width: int = 200, image_height: int = 200) -> str: """Renders a 2D representation of a molecule based on its SMILES representation as an SVG string. Parameters ---------- smiles The SMILES pattern. torsion_indices The torsion indices for the molecule. image_width The width to make the final SVG. image_height The height to make the final SVG. Returns ------- The 2D SVG representation. """ # Parse the SMILES into an RDKit molecule smiles_parser = Chem.rdmolfiles.SmilesParserParams() smiles_parser.removeHs = False oe_conformed = False try: oe_molecule, status = smiles2oemol(smiles) openff_molecule = Molecule.from_openeye(oe_molecule) rdkit_molecule = openff_molecule.to_rdkit() oe_conformed = True except: rdkit_molecule = Chem.MolFromSmiles(smiles, smiles_parser) # Generate a set of 2D coordinates. Chem.rdDepictor.Compute2DCoords(rdkit_molecule) drawer = rdMolDraw2D.MolDraw2DSVG(image_width, image_height) torsion_bonds = [] if oe_conformed: for i in range(len(torsion_indices) - 1): if rdkit_molecule.GetBondBetweenAtoms(torsion_indices[i], torsion_indices[i+1]): torsion_bonds.append(rdkit_molecule.GetBondBetweenAtoms(torsion_indices[i], torsion_indices[i+1]).GetIdx()) rdMolDraw2D.PrepareAndDrawMolecule(drawer, rdkit_molecule, highlightBonds = torsion_bonds) drawer.FinishDrawing() svg_content = drawer.GetDrawingText() return svg_content
def draw_with_bond_note(self, bond_note, filename="mol.png", show_atom_idx=True): """ Draw molecule using rdkit and show bond annotation, e.g. bond energy. Args: bond_note (dict): {bond_index: note}. The note to show for the corresponding bond. filename (str): path to the save the generated image. If `None` the molecule is returned and can be viewed in Jupyter notebook. """ m = self.draw(show_atom_idx=show_atom_idx) # set bond annotation highlight_bonds = [] for bond, note in bond_note.items(): if isinstance(note, (float, np.floating)): note = "{:.3g}".format(note) idx = m.GetBondBetweenAtoms(*bond).GetIdx() m.GetBondWithIdx(idx).SetProp("bondNote", note) highlight_bonds.append(idx) # set highlight color bond_colors = { b: (192 / 255, 192 / 255, 192 / 255) for b in highlight_bonds } d = rdMolDraw2D.MolDraw2DCairo(400, 300) # smaller font size d.SetFontSize(0.8 * d.FontSize()) rdMolDraw2D.PrepareAndDrawMolecule(d, m, highlightBonds=highlight_bonds, highlightBondColors=bond_colors) d.FinishDrawing() create_directory(filename) with open(to_path(filename), "wb") as f: f.write(d.GetDrawingText())
def draw_nicely(self, mol, show=True, **kwargs) -> rdMolDraw2D.MolDraw2DSVG: """ Draw with atom indices for Jupyter notebooks. :param mol: :param kwargs: Key value pairs get fed into ``PrepareAndDrawMolecule``. :return: """ d = rdMolDraw2D.MolDraw2DSVG(400, 400) d.drawOptions().addAtomIndices = True d.drawOptions().addStereoAnnotation = True x = Chem.Mol(mol) AllChem.Compute2DCoords(x) rdMolDraw2D.PrepareAndDrawMolecule(d, x, **kwargs) d.FinishDrawing() if show: display(SVG(d.GetDrawingText())) return d
def mol_svg(smi, filename=None, filepath='./', molSize=(450, 150)): """Will write molecule 2D drawing to SVG file""" # if no filename given, use SMILES if not filename: name = smi + '.svg' else: name = filename + '.svg' mol = Chem.MolFromSmiles(smi) # read the smiles string to RDKit d = rdMolDraw2D.MolDraw2DSVG(molSize[0], molSize[1]) # set size of SVG image rdMolDraw2D.PrepareAndDrawMolecule(d, mol) # draw molecule svg = d.GetDrawingText() # get XML text of the SVG svg = svg + '</svg>' # fix missing line to close svg # edit XML to create transparent background svg = svg.replace("rect style='opacity:1.0;fill:#FFFFFF", "rect style='opacity:1.0;fill:none", 1) # write to file with open(filepath + name, 'w') as f: f.write(svg)
def draw_molecule(self, representation, atom_indexes=list(), radii_dict=dict(), atom_color_dict=dict(), bond_indexes=list(), bond_color_dict=dict()): """ Given a molecular representation, it returns its image as SVG. Parameters ---------- representation : an RDKit.molecule object It is an RDKit molecule with an embeded 2D representation Returns ------- image : an IPython's SVG display object The image of the molecular representation to display """ from rdkit.Chem.Draw import rdMolDraw2D draw = rdMolDraw2D.MolDraw2DSVG(500, 500) draw.SetLineWidth(4) rdMolDraw2D.PrepareAndDrawMolecule(draw, representation, highlightAtoms=atom_indexes, highlightAtomRadii=radii_dict, highlightAtomColors=atom_color_dict, highlightBonds=bond_indexes, highlightBondColors=bond_color_dict) draw.FinishDrawing() from IPython.display import SVG image = SVG(draw.GetDrawingText()) return image
def show_substruct_matches(reactants, sub): # https://www.rdkit.org/docs/GettingStartedInPython.html#drawing-molecules # p = Chem.MolFromSmiles(reactants) # subms = [x for x in ms if x.HasSubstructMatch(p)] close_img_viewer() mol = Chem.MolFromSmiles(reactants) patt = Chem.MolFromSmarts(sub) hit_ats = list(mol.GetSubstructMatch(patt)) hit_bonds = [] for bond in patt.GetBonds(): aid1 = hit_ats[bond.GetBeginAtomIdx()] aid2 = hit_ats[bond.GetEndAtomIdx()] hit_bonds.append(mol.GetBondBetweenAtoms(aid1, aid2).GetIdx()) d = rdMolDraw2D.MolDraw2DCairo(500, 500) # or MolDraw2DCairo to get PNGs rdMolDraw2D.PrepareAndDrawMolecule(d, mol, highlightAtoms=hit_ats, highlightBonds=hit_bonds) # d.drawMolecule d.FinishDrawing() d.WriteDrawingText("atom_annotation_1.png") i = Image.open("atom_annotation_1.png") i.show()
def plot_node_activations( mol, node_activations, fig_fname, plot_cbar = False ): """ Saves a molecule colored by node activations in a directory specified by `fname`. Params ------ mol (rdkit.Chem.rdchem.Mol) RDKit molecule. node_activations (array-like) Per node activation map generated by e.g. `get_CAM_activations()`. fig_fname(str) path to save file + file name plot_cbar(bool, default = False) Whether or not to plot colorbar to get a sense of scale. Notes: Uses viridis by default. Doesn't return an object. """ min_act, max_act = node_activations.min(), node_activations.max() normalizer =mpl.colors.Normalize(vmin=min_act, vmax = max_act) cmap = cm.viridis mapper = cm.ScalarMappable(norm=normalizer, cmap=cmap) d = rdMolDraw2D.MolDraw2DCairo(500, 500) n_atoms = len(list(mol.GetAtoms())) rdMolDraw2D.PrepareAndDrawMolecule( d, mol, highlightAtoms=list(range(n_atoms)), highlightAtomColors={ i: mapper.to_rgba(node_activations[i]) for i in range(n_atoms) }, ) with open(fig_fname,'wb') as file: file.write(d.GetDrawingText()) if plot_cbar: plt.imshow( np.linspace(min_act, max_act, 10).reshape(1, -1), cmap = cmap ) plt.gca().set_visible(False) plt.colorbar(orientation = 'horizontal') plt.savefig( fig_fname.split('.png')[0] + '_cbar.png', dpi = 230, bbox_inches='tight' ) return None
def smiles_to_svg(smiles: str, highlight_smirks: Optional[str]) -> str: """Renders a 2D representation of a molecule based on its SMILES representation as an SVG string. Parameters ---------- smiles The SMILES pattern. highlight_smirks An optional SMIRK pattern to use to highlight a subset of atoms within the molecule. Returns ------- The 2D SVG representation. """ from openforcefield.topology import Molecule from openforcefield.utils import RDKitToolkitWrapper # Parse the SMILES into an RDKit molecule smiles_parser = Chem.rdmolfiles.SmilesParserParams() smiles_parser.removeHs = False rdkit_molecule = Chem.MolFromSmiles(smiles, smiles_parser) # Generate a set of 2D coordinates. if not rdkit_molecule.GetNumConformers(): Chem.rdDepictor.Compute2DCoords(rdkit_molecule) # Find any atoms which should be highlighted. highlight_atoms = set() highlight_bonds = set() if highlight_smirks is not None: openff_molecule = Molecule.from_smiles(smiles, allow_undefined_stereo=True) matches = RDKitToolkitWrapper().find_smarts_matches( openff_molecule, highlight_smirks) for match in matches: matched_bonds = [ rdkit_molecule.GetBondBetweenAtoms(match[i], match[i + 1]) for i in range(len(match) - 1) ] highlight_atoms.update(match) highlight_bonds.update(bond.GetIdx() for bond in matched_bonds if bond is not None) drawer = rdMolDraw2D.MolDraw2DSVG(300, 300) rdMolDraw2D.PrepareAndDrawMolecule( drawer, rdkit_molecule, highlightAtoms=[*highlight_atoms], highlightBonds=[*highlight_bonds], ) drawer.FinishDrawing() svg_content = drawer.GetDrawingText() return svg_content