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()
def load_tests(loader, tests, ignore): # pylint: disable=unused-argument """ Add the Doctests from the module """ tests.addTests( doctest.DocTestSuite(EnumerateStereoisomers, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(EnumerateHeterocycles, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(MCS, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(FragmentMatcher, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(MACCSkeys, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(Descriptors, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Recap, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(BRICS, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(AllChem, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(PropertyMol, optionflags=doctest.ELLIPSIS)) tests.addTests( doctest.DocTestSuite(SaltRemover, optionflags=doctest.ELLIPSIS)) tests.addTests(doctest.DocTestSuite(Chem, optionflags=doctest.ELLIPSIS)) # Tests which have a dependency on using the RDKit coordinate generator rdDepictor.SetPreferCoordGen(False) tests.addTests( doctest.DocTestSuite(TemplateAlign, optionflags=doctest.ELLIPSIS)) return tests
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())
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)
"""This module contains two molecular drawing functions to render SVGs or PNGs given an RDKit molecule object: mol_to_svg and mol_to_png.""" import io import base64 import numpy as np from PIL import Image, ImageOps try: from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem import rdDepictor from rdkit import __version__ as RDKIT_VERSION rdDepictor.SetPreferCoordGen(True) except ImportError: Chem = None RDKIT_VERSION = None # pylint: disable=unsubscriptable-object def trim_image_whitespace(img, padding=0): """This function takes a PIL image, img, and crops it to the minimum rectangle based on its whiteness/transparency. 5 pixel padding used automatically.""" # Convert to array as_array = np.array(img) # N x N x (r,g,b,a) # Set previously-transparent pixels to white if as_array.shape[2] == 4:
def _test(): import doctest, sys from rdkit.Chem import rdDepictor rdDepictor.SetPreferCoordGen(False) return doctest.testmod(sys.modules["__main__"])
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) def testConstrainedCoords(self): templ = Chem.MolFromSmiles('c1nccc2n1ccc2') rdDepictor.Compute2DCoords(templ) m1 = Chem.MolFromSmiles('c1cccc2ncn3cccc3c21') rdDepictor.GenerateDepictionMatching2DStructure(m1, templ) m2 = Chem.MolFromSmiles('c1cc(Cl)cc2ncn3cccc3c21') rdDepictor.Compute2DCoords(m2) refPatt1 = Chem.MolFromSmarts('*1****2*1***2') rdDepictor.GenerateDepictionMatching2DStructure(m2, templ, -1, refPatt1) fileN = os.path.join(RDConfig.RDBaseDir, 'Code', 'GraphMol', 'Depictor', 'test_data', '1XP0_ligand.sdf') xp0_lig = Chem.MolFromMolFile(fileN) xp0_lig_2d = Chem.Mol(xp0_lig) rdDepictor.GenerateDepictionMatching3DStructure(xp0_lig_2d, xp0_lig) xp0_ref = Chem.MolFromSmarts('[#6]1~[#7][#6]~[#6]2[#6](=[#8])[#7]~[#6](c3ccccc3)[#7][#7]12') rdDepictor.GenerateDepictionMatching3DStructure(xp0_lig_2d, xp0_lig, -1, xp0_ref) if __name__ == '__main__': rdDepictor.SetPreferCoordGen(False) unittest.main()
def _drawHelper(mol, drawer, **kwargs): tgt = request.get_json() if tgt is None: tgt = request.values sanit = _stringtobool(tgt.get('sanitize', True)) kekulize = _stringtobool(tgt.get('kekulize', True)) for arg in ('highlightAtomColors', 'highlightBondColors'): if arg not in kwargs: tmp = _loadJSONParam(tgt.get(arg, None)) if tmp: for k in list(tmp): tmp[int(k)] = tuple(tmp[k]) del tmp[k] kwargs[arg] = tmp for arg in ('highlightAtoms', 'highlightBonds'): if arg not in kwargs: tmp = _loadJSONParam(tgt.get(arg, None)) if tmp: kwargs[arg] = tmp if 'legend' not in kwargs: kwargs['legend'] = tgt.get('legend', '') # if 'lw' not in kwargs and 'lw' in request.values: # kwargs['lw'] = int(request.values['lw']) if 'highlightSubstruct' not in kwargs: if 'highlightColor' not in kwargs: hcolor = _loadJSONParam(tgt.get('highlightColor', None)) if hcolor: highlightColor = tuple(hcolor) else: highlightColor = None else: highlightColor = kwargs['highlightColor'] del kwargs['higlightColor'] if _stringtobool(tgt.get('highlightSubstruct', False)) or \ 'smiles_highlight' in tgt or \ 'smarts_highlight' in tgt or \ 'mol_highlight' in tgt: qmol = _queryfromrequest(suffix='_highlight') if qmol is not None: qMatches = mol.GetSubstructMatches(qmol) highlights = kwargs.get('highlightAtoms', []) if highlightColor is not None: highlightBonds = kwargs.get('highlightBonds', []) else: highlightBonds = None for entry in qMatches: if highlightColor is not None: had = kwargs.get('highlightAtomColors', {}) for v in entry: had[v] = highlightColor kwargs['highlightAtomColors'] = had hbd = kwargs.get('highlightBondColors', {}) emap = dict(enumerate(entry)) for bond in qmol.GetBonds(): mbond = mol.GetBondBetweenAtoms( emap[bond.GetBeginAtomIdx()], emap[bond.GetEndAtomIdx()]) highlightBonds.append(mbond.GetIdx()) hbd[mbond.GetIdx()] = highlightColor kwargs['highlightBondColors'] = hbd highlights.extend(list(entry)) if highlights: kwargs['highlightAtoms'] = highlights if highlightBonds is not None: kwargs['highlightBonds'] = highlightBonds from rdkit.Chem.Draw import rdDepictor rdDepictor.SetPreferCoordGen(True) # print(Chem.MolToMolBlock(mc)) drawo = drawer.drawOptions() for opt, default in (('dummiesAreAttachments', False), ('comicMode', False), ('addAtomIndices', False), ('addBondIndices', False), ('isotopeLabels', True), ('addStereoAnnotation', False), ('explicitMethyl', False), ('includeChiralFlagLabel', False), ('simplifiedStereoGroupLabel', False)): setattr(drawo, opt, _stringtobool(tgt.get(opt, default))) if drawo.comicMode: drawo.fontFile = os.path.join(RDConfig.RDDataDir, "Fonts", "ComicNeue-Regular.ttf") if drawo.addStereoAnnotation: Chem.FindMolChiralCenters(mol, force=True, useLegacyImplementation=False) if 'backgroundColor' in tgt: tmp = _loadJSONParam(tgt.get('backgroundColor', None)) drawo.SetBackgroundColor(tuple) if _stringtobool(tgt.get('atomIndices', False)): drawo.addAtomIndices = True if _stringtobool(tgt.get('bondIndices', False)): drawo.addBondIndices = True if _stringtobool(tgt.get('useBW', False)): drawo.useBWAtomPalette() if _stringtobool(tgt.get('useGrid', '0')): frags = [] for frag in Chem.GetMolFrags(mol, asMols=True): frags.append( rdMolDraw2D.PrepareMolForDrawing(frag, kekulize=kekulize & sanit, addChiralHs=sanit)) drawer.DrawMolecules(frags) elif _stringtobool(tgt.get('asRxn', False)): drawer.DrawReaction(mol) else: mc = rdMolDraw2D.PrepareMolForDrawing(mol, kekulize=kekulize & sanit, addChiralHs=sanit) mc.SetProp("_Name", "temp") if _stringtobool(tgt.get('collapseAbbreviations',False)) and \ len(Chem.GetMolSubstanceGroups(mc)): mc = rdAbbreviations.CondenseAbbreviationSubstanceGroups(mc) elif _stringtobool(tgt.get('findAbbreviations', False)): mc = rdAbbreviations.CondenseMolAbbreviations( mc, rdAbbreviations.GetDefaultAbbreviations(), maxCoverage=float(tgt.get('maxAbbreviationCoverage', 0.4))) drawer.DrawMolecule(mc, **kwargs) drawer.FinishDrawing()