Example #1
0
    def testSetPalette(self):
        m = Chem.MolFromSmiles('CCOCNCCl')
        dm = Draw.PrepareMolForDrawing(m)
        d = Draw.MolDraw2DSVG(300, 300)
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertTrue(txt.find("stroke:#000000") >= 0)
        self.assertTrue(txt.find("stroke:#00CC00") >= 0)

        d = Draw.MolDraw2DSVG(300, 300)
        d.drawOptions().setAtomPalette({-1: (1, 1, 0)})
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertTrue(txt.find("stroke:#000000") == -1)
        self.assertTrue(txt.find("stroke:#00CC00") == -1)
        self.assertTrue(txt.find("stroke:#FFFF00") >= 0)

        # try a palette that doesn't have a default:
        d = Draw.MolDraw2DSVG(300, 300)
        d.drawOptions().setAtomPalette({0: (1, 1, 0)})
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertTrue(txt.find("stroke:#000000") >= 0)
        self.assertTrue(txt.find("stroke:#00CC00") == -1)
        self.assertTrue(txt.find("stroke:#FFFF00") == -1)
Example #2
0
  def testNewDrawingModes(self):
    m = Chem.MolFromSmiles("CS(=O)(=O)COC(=N)c1cc(Cl)cnc1[NH3+] |SgD:7:note:some extra text:=:::|")

    d2d = Draw.MolDraw2DSVG(300, 300)
    rdMolDraw2D.SetDarkMode(d2d)
    d2d.DrawMolecule(m)
    d2d.FinishDrawing()
    text = d2d.GetDrawingText()
    self.assertIn("<rect style='opacity:1.0;fill:#000000;stroke:none'",text)

    d2d = Draw.MolDraw2DSVG(300, 300)
    rdMolDraw2D.SetMonochromeMode(d2d,(1,1,1),(.5,.5,.5))
    d2d.DrawMolecule(m)
    d2d.FinishDrawing()
    text = d2d.GetDrawingText()
    self.assertIn("<rect style='opacity:1.0;fill:#7F7F7F;stroke:none'",text)
    self.assertIn("stroke:#FFFFFF;stroke-width:2",text)

    d2d = Draw.MolDraw2DSVG(300, 300)
    d2d.drawOptions().useAvalonAtomPalette()
    d2d.DrawMolecule(m)
    d2d.FinishDrawing()
    text = d2d.GetDrawingText()
    self.assertIn("<rect style='opacity:1.0;fill:#FFFFFF;stroke:none'",text)
    self.assertIn("stroke:#007E00;stroke-width:2",text)

    d2d = Draw.MolDraw2DSVG(300, 300)
    d2d.drawOptions().useCDKAtomPalette()
    d2d.DrawMolecule(m)
    d2d.FinishDrawing()
    text = d2d.GetDrawingText()
    self.assertIn("<rect style='opacity:1.0;fill:#FFFFFF;stroke:none'",text)
    self.assertIn("stroke:#2F50F7;stroke-width:2",text)
Example #3
0
    def testUpdateParamsFromJSON(self):
        m = Chem.MolFromSmiles('c1ccccc1NC(=O)C1COC1')
        d2d = Draw.MolDraw2DSVG(250, 200, -1, -1, True)
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        txt = d2d.GetDrawingText()
        self.assertFalse('>8</text>' in txt)

        d2d = Draw.MolDraw2DSVG(250, 200, -1, -1, True)
        Draw.UpdateDrawerParamsFromJSON(d2d, '{"addAtomIndices": 1}')
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        txt = d2d.GetDrawingText()
        self.assertTrue('>8</text>' in txt)
Example #4
0
    def testIsotopeLabels(self):
        m = Chem.MolFromSmiles("[1*]c1cc([2*])c([3*])c[14c]1")
        regex = re.compile(r"<text\s+.*>\d</text>")
        self.assertIsNotNone(m)

        d2d = Draw.MolDraw2DSVG(300, 300, -1, -1, True)
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        textIsoDummyIso = d2d.GetDrawingText()
        nIsoDummyIso = len(regex.findall(textIsoDummyIso))
        self.assertEqual(nIsoDummyIso, 5)

        d2d = Draw.MolDraw2DSVG(300, 300, -1, -1, True)
        d2d.drawOptions().isotopeLabels = False
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        textNoIsoDummyIso = d2d.GetDrawingText()
        nNoIsoDummyIso = len(regex.findall(textNoIsoDummyIso))
        self.assertEqual(nNoIsoDummyIso, 3)

        d2d = Draw.MolDraw2DSVG(300, 300, -1, -1, True)
        d2d.drawOptions().dummyIsotopeLabels = False
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        textIsoNoDummyIso = d2d.GetDrawingText()
        nIsoNoDummyIso = len(regex.findall(textIsoNoDummyIso))
        self.assertEqual(nIsoNoDummyIso, 2)

        d2d = Draw.MolDraw2DSVG(300, 300, -1, -1, True)
        d2d.drawOptions().isotopeLabels = False
        d2d.drawOptions().dummyIsotopeLabels = False
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        textNoIsoNoDummyIso = d2d.GetDrawingText()
        nNoIsoNoDummyIso = len(regex.findall(textNoIsoNoDummyIso))
        self.assertEqual(nNoIsoNoDummyIso, 0)

        m = Chem.MolFromSmiles("C([1H])([2H])([3H])[H]")
        deuteriumTritiumRegex = re.compile(r"<text\s+.*>[DT]</text>")
        d2d = Draw.MolDraw2DSVG(300, 300, -1, -1, True)
        d2d.drawOptions().isotopeLabels = False
        d2d.drawOptions().dummyIsotopeLabels = False
        d2d.drawOptions().atomLabelDeuteriumTritium = True
        d2d.DrawMolecule(m)
        d2d.FinishDrawing()
        textDeuteriumTritium = d2d.GetDrawingText()
        nDeuteriumTritium = len(
            deuteriumTritiumRegex.findall(textDeuteriumTritium))
        self.assertEqual(nDeuteriumTritium, 2)
    def testSimilarityMapsMolDraw2D(self):
        # nothing really sensible to test here, just make sure things run
        mol = Chem.MolFromSmiles(
            'COc1cccc2cc(C(=O)NCCCCN3CCN(c4cccc5nccnc54)CC3)oc21')
        refmol = Chem.MolFromSmiles(
            'CCCN(CCCCN1CCN(c2ccccc2OC)CC1)Cc1ccc2ccccc2c1')
        d = Draw.MolDraw2DSVG(400, 400)
        d.ClearDrawing()
        _, maxWeight = sm.GetSimilarityMapForFingerprint(
            refmol,
            mol,
            lambda m, i: sm.GetMorganFingerprint(m, i, radius=2, fpType='bv'),
            draw2d=d)
        d.FinishDrawing()
        with open('similarityMap1_out.svg', 'w+') as outf:
            outf.write(d.GetDrawingText())

        # Github #2904: make sure we can provide our own colormap as a list:
        colors = [(0, 1, 0, 0.5), (1, 1, 1), (0, 0, 1, 0.5)]
        d = Draw.MolDraw2DSVG(400, 400)
        d.ClearDrawing()
        _, maxWeight = sm.GetSimilarityMapForFingerprint(
            refmol,
            mol,
            lambda m, i: sm.GetMorganFingerprint(m, i, radius=2, fpType='bv'),
            draw2d=d,
            colorMap=colors)
        d.FinishDrawing()
        with open('similarityMap1_out2.svg', 'w+') as outf:
            outf.write(d.GetDrawingText())

        # Github #2904: make sure we can provide our own colormap as a matplotlib colormap:
        try:
            from matplotlib import cm
            d = Draw.MolDraw2DSVG(400, 400)
            d.ClearDrawing()
            _, maxWeight = sm.GetSimilarityMapForFingerprint(
                refmol,
                mol,
                lambda m, i: sm.GetMorganFingerprint(
                    m, i, radius=2, fpType='bv'),
                draw2d=d,
                colorMap=cm.PiYG)
            d.FinishDrawing()
            with open('similarityMap1_out3.svg', 'w+') as outf:
                outf.write(d.GetDrawingText())
        except ImportError:
            pass
Example #6
0
    def export_2d_annotation(self,
                             file_name: str,
                             wedge_bonds: bool = True) -> None:
        """Generates 2D depiction in JSON format with annotation of
        bonds and atoms to be redrawn in the interactions component.

        Args:
            file_name (str): Path to the file
        """
        w, h = drawing.get_drawing_scale(self.mol2D)
        drawer = Draw.MolDraw2DSVG(w, h)
        drawer.drawOptions().includeAtomTags = True
        try:
            tmp = rdkit.Chem.Draw.PrepareMolForDrawing(self.mol2D,
                                                       wedgeBonds=wedge_bonds,
                                                       kekulize=True,
                                                       addChiralHs=False)
        except (RuntimeError, ValueError):
            tmp = rdkit.Chem.Draw.PrepareMolForDrawing(self.mol2D,
                                                       wedgeBonds=False,
                                                       kekulize=True,
                                                       addChiralHs=False)
        drawer.DrawMolecule(tmp)
        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        json_repr = drawing.convert_svg(svg, self.id, self.mol2D)

        with open(file_name, 'w') as fp:
            json.dump(json_repr, fp, indent=4, sort_keys=True)
Example #7
0
    def draw_mol(self, mol, size=(160, 120), **kwargs):
        """Draw a molecule

        Parameters
        ----------
        mol : rdkit.Chem.rdchem.Mol
            The molecule to draw
        size : tuple
            The size of the drawing canvas
        **kwargs : object
            Attributes of the rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions class
            like `fixedBondLength=35, bondLineWidth=2`
        
        Notes
        -----
        The list of supported MolDrawOptions attributes are available in
        https://www.rdkit.org/docs/source/rdkit.Chem.Draw.rdMolDraw2D.html#rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions
        """
        if self.useSVG:
            d2d = Draw.MolDraw2DSVG(*size)
        else:
            d2d = Draw.MolDraw2DCairo(*size)
        opts = Draw.MolDrawOptions()
        for key, value in kwargs.items():
            setattr(opts, key, value)
        d2d.SetDrawOptions(opts)
        d2d.DrawMolecule(mol)
        d2d.FinishDrawing()
        return d2d.GetDrawingText()
Example #8
0
 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)
Example #9
0
    def replace_label_with_smiles(self,svg_file='', smiles='C=C', search_index='~0'):
        """
        draws a small organic rest, looks for the ~index comment in the complete svg, finds the glyphs and replaces them with the organic subsituent. 
        Note that this is hacky and the position of the organic subsituent likely needs to be fixed in a vector software such as Inkscape. 

        Parameters
        ----------
        svg_file : str
           the text of the svg file which contains the comments that are replaced
        search_index: str
            the name of the comment which is indicated by a prepended tilde by the user
        smiles: str
            the smiles string used for the replacement
        """
        m = Chem.MolFromSmiles(smiles)
        dm = Draw.PrepareMolForDrawing(m)
        d2d = Draw.MolDraw2DSVG(100,100)
        d2d.drawOptions().padding=0
        d2d.drawOptions().clearBackground=False
        d2d.drawOptions().useBWAtomPalette()
        d2d.DrawMolecule(dm)
        d2d.FinishDrawing()
        # scale smiles molecule and remove clutter
        group1 = d2d.GetDrawingText()
        replace_str=group1[group1.find('<!-- END OF HEADER -->')+len("<!-- END OF HEADER -->")+1:-8]
        replace_str='<g transform="translate(-300,-300)scale(6)">'+replace_str+"</g>"
        # find the index in the pie chart that needs to be replaced, we will geplace the two glyphs with the svg text from rdkit
        index_of_comment=svg_file.find(str(search_index))
        index_of_defsend=svg_file[index_of_comment:].find('</defs>')
        start=svg_file[index_of_comment+index_of_defsend:].find('<use')
        end=svg_file[index_of_comment+index_of_defsend:].find('</g>')
        item_to_replace=svg_file[index_of_comment+index_of_defsend+start:index_of_comment+index_of_defsend+end]
        return svg_file.replace(item_to_replace, replace_str)
Example #10
0
    def draw_nicely(self, mol, show=True, **kwargs) -> Draw.MolDraw2DSVG:
        """
        Draw with atom indices for Jupyter notebooks.


        :param mol:
        :param kwargs: Key value pairs get fed into ``PrepareAndDrawMolecule``.
        :return:
        """
        if mol.HasProp('_Name'):
            print(mol.GetProp('_Name'))
        d = Draw.MolDraw2DSVG(400, 400)
        d.drawOptions().addAtomIndices = True
        d.drawOptions().addStereoAnnotation = True
        d.drawOptions().prepareMolsBeforeDrawing = False
        d.drawOptions().dummiesAreAttachments = True
        x = Chem.Mol(mol)
        AllChem.Compute2DCoords(x)
        Chem.SanitizeMol(x, catchErrors=True)
        try:
            # x = Chem.MolFromSmiles(Chem.MolToSmiles(x, kekuleSmiles=False), sanitize=False)
            Draw.PrepareAndDrawMolecule(d, x, **kwargs)
            d.FinishDrawing()
            if show:
                display(SVG(d.GetDrawingText()))
            return d
        except Exception as err:
            warn(f'*{err.__class__.__name__}* : {err}')
            display(x)
Example #11
0
    def testGridContours(self):
        grid = np.zeros((50, 100), np.double)
        ycoords = list(np.arange(0, 5, 0.1))
        xcoords = list(np.arange(0, 10, 0.1))
        for i in range(grid.shape[1]):
            gxp = xcoords[i]
            for j in range(grid.shape[0]):
                gyp = ycoords[j]
                for v in range(1, 4):
                    dvx = 2 * v - gxp
                    dvy = v - gyp
                    d2 = dvx * dvx + dvy * dvy
                    if d2 > 0:
                        grid[j, i] += 1 / np.sqrt(d2)

        # sg = 255 * grid / np.max(grid)
        # from PIL import Image
        # img = Image.fromarray(sg.astype(np.uint8))
        # img.save('img.png')

        d = Draw.MolDraw2DSVG(300, 300)
        d.ClearDrawing()
        Draw.ContourAndDrawGrid(d, np.transpose(grid), xcoords, ycoords)
        d.drawOptions().clearBackground = False
        d.FinishDrawing()
        txt = d.GetDrawingText()
        with open("contour_from_py_3.svg", 'w+') as outf:
            print(txt, file=outf)
Example #12
0
 def testReaction4(self):
     rxn = AllChem.ReactionFromSmarts(
         '[CH3:1][C:2](=[O:3])[OH:4].[CH3:5][NH2:6]>CC(O)C.[Pt]>[CH3:1][C:2](=[O:3])[NH:6][CH3:5].[OH2:4]',
         useSmiles=True)
     colors = [(100, 155, 245), (0, 45, 155)]
     d = Draw.MolDraw2DSVG(900, 300)
     self.assertRaises(ValueError, d.DrawReaction, rxn, True, colors)
Example #13
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
Example #14
0
    def testBWDrawing(self):
        m = Chem.MolFromSmiles('CCOCNCCl')
        dm = Draw.PrepareMolForDrawing(m)
        d = Draw.MolDraw2DSVG(300, 300)
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertTrue(txt.find("stroke:#000000") >= 0)
        self.assertTrue(txt.find("stroke:#00CC00") >= 0)

        d = Draw.MolDraw2DSVG(300, 300)
        d.drawOptions().useBWAtomPalette()
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        self.assertTrue(txt.find("stroke:#000000") >= 0)
        self.assertTrue(txt.find("stroke:#00CC00") == -1)
Example #15
0
 def testSetLineWidth(self):
     " this was github #2149 "
     m = Chem.MolFromSmiles('CC')
     dm = Draw.PrepareMolForDrawing(m)
     d = Draw.MolDraw2DSVG(300, 300)
     d.DrawMolecule(dm)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     self.assertTrue(txt.find("stroke-width:2.0px") >= 0)
     self.assertTrue(txt.find("stroke-width:4.0px") == -1)
     d = Draw.MolDraw2DSVG(300, 300)
     d.SetLineWidth(4)
     d.DrawMolecule(dm)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     self.assertTrue(txt.find("stroke-width:2.0px") == -1)
     self.assertTrue(txt.find("stroke-width:4.0px") >= 0)
 def testReaction2(self):
   rxn = AllChem.ReactionFromSmarts('[CH3:1][C:2](=[O:3])[OH:4].[CH3:5][NH2:6]>CC(O)C.[Pt]>[CH3:1][C:2](=[O:3])[NH:6][CH3:5].[OH2:4]',useSmiles=True)
   d = Draw.MolDraw2DSVG(900, 300)
   d.DrawReaction(rxn,highlightByReactant=True)
   d.FinishDrawing()
   txt = d.GetDrawingText()
   self.assertTrue(txt.find("<svg") != -1)
   self.assertTrue(txt.find("</svg>") != -1)
Example #17
0
 def testSetLineWidth(self):
     " this was github #2149 "
     m = Chem.MolFromSmiles('CC')
     dm = Draw.PrepareMolForDrawing(m)
     d = Draw.MolDraw2DSVG(300, 300)
     d.DrawMolecule(dm)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     self.assertTrue(txt.find("stroke-width:7px") >= 0)
     self.assertTrue(txt.find("stroke-width:21px") == -1)
     d = Draw.MolDraw2DSVG(300, 300)
     d.SetLineWidth(4)
     d.DrawMolecule(dm)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     # the line width is scaled, so 4 is drawn as 21 pixels wide.
     self.assertTrue(txt.find("stroke-width:7px") == -1)
     self.assertTrue(txt.find("stroke-width:14px") >= 0)
Example #18
0
def smiles_rxn_to_svg(smiles_rxn, rxnSize=(900, 300)):
    rxn = rdChemReactions.ReactionFromSmarts(smiles_rxn, useSmiles=True)
    d = Draw.MolDraw2DSVG(rxnSize[0], rxnSize[1])
    opts = d.drawOptions()
    opts.addStereoAnnotation = True
    d.DrawReaction(rxn)
    d.FinishDrawing()
    svg = d.GetDrawingText()
    return svg
Example #19
0
 def test1(self):
     m = Chem.MolFromSmiles('c1ccc(C)c(C)c1C')
     AllChem.Compute2DCoords(m)
     d = Draw.MolDraw2DSVG(300, 300)
     d.DrawMolecule(m)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     self.assertTrue(txt.find("<svg") != -1)
     self.assertTrue(txt.find("</svg>") != -1)
Example #20
0
 def testGithub4838(self):
     m = Chem.MolFromSmiles("CCCC")
     d2d = Draw.MolDraw2DSVG(300, 300)
     d2d.DrawMolecule(m)
     d2d.DrawString("foo1", Geometry.Point2D(1, 0))
     d2d.DrawString("foo0", Geometry.Point2D(1, 1), 0)
     d2d.DrawString("foo2", Geometry.Point2D(1, 2), 1)
     d2d.DrawString("foo3", Geometry.Point2D(1, 3), 2)
     with self.assertRaises(ValueError):
         d2d.DrawString("fail", Geometry.Point2D(1, 4), 3)
Example #21
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)
Example #22
0
def mol_to_svg(mol, max_size=300, bond_length=25):
    """Returns a string with an <svg> tag containing a rendering of the input
    molecule. Note that the SVG is not cropped."""
    rdDepictor.Compute2DCoords(mol)
    Chem.Kekulize(mol)
    drawer = Draw.MolDraw2DSVG(max_size, max_size)
    drawer.drawOptions().fixedBondLength = bond_length
    drawer.DrawMolecule(mol)
    drawer.FinishDrawing()
    return drawer.GetDrawingText()
Example #23
0
 def test2(self):
     m = Chem.MolFromSmiles('c1ccc(C)c(C)c1C')
     AllChem.Compute2DCoords(m)
     d = Draw.MolDraw2DSVG(300, 300)
     do = d.drawOptions()
     do.atomLabels[3] = 'foolabel'
     d.DrawMolecule(m)
     d.FinishDrawing()
     txt = d.GetDrawingText()
     self.assertTrue(txt.find("foolabel") != -1)
Example #24
0
    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)
Example #25
0
 def draw_smiles(self):
     """
         draws the smiles string for the plotting, needs to return the drawing objects also because the atom indeces are extracted.
     """
     m = Chem.MolFromSmiles(self.settings['SMILESSTRING'])
     dm = Draw.PrepareMolForDrawing(m)
     d2d = Draw.MolDraw2DSVG(350,350)
     if self.settings['use_bw_atom_theme']:
         d2d.drawOptions().useBWAtomPalette()
     d2d.DrawMolecule(dm)
     d2d.FinishDrawing()
     return d2d.GetDrawingText(), d2d, dm
Example #26
0
def rxntosvg(list_rxns, rxnSize=(900, 300)):
    list_svgs = []
    for i, rxn in enumerate(list_rxns):
        rdkit_reaction = rxn.rxn
        d = Draw.MolDraw2DSVG(rxnSize[0], rxnSize[1])
        opts = d.drawOptions()
        opts.addStereoAnnotation = True
        d.DrawReaction(rdkit_reaction)
        d.FinishDrawing()
        svg = d.GetDrawingText()
        list_svgs.append(svg)

    return list_svgs
Example #27
0
    def testMolContours(self):
        m = Chem.MolFromSmiles("C1N[C@@H]2OCC12")
        dm = Draw.PrepareMolForDrawing(m)

        conf = dm.GetConformer()
        gs = []
        ws = []
        hs = []
        for i in range(conf.GetNumAtoms()):
            p = conf.GetAtomPosition(i)
            p2 = Geometry.Point2D(p.x, p.y)
            gs.append(p2)
            hs.append(0.4)
            if not i % 2:
                ws.append(-0.5)
            else:
                ws.append(1)

        d = Draw.MolDraw2DSVG(300, 300)
        d.ClearDrawing()
        Draw.ContourAndDrawGaussians(d, gs, hs, ws, mol=dm)
        d.drawOptions().clearBackground = False
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        with open("contour_from_py_1.svg", 'w+') as outf:
            print(txt, file=outf)

        d = Draw.MolDraw2DSVG(300, 300)
        d.ClearDrawing()
        ps = Draw.ContourParams()
        ps.fillGrid = True
        Draw.ContourAndDrawGaussians(d, gs, hs, ws, params=ps, mol=dm)
        d.drawOptions().clearBackground = False
        d.DrawMolecule(dm)
        d.FinishDrawing()
        txt = d.GetDrawingText()
        with open("contour_from_py_2.svg", 'w+') as outf:
            print(txt, file=outf)
Example #28
0
def draw_with_indeces(settings):
    """
    Drawing function that displays the input smiles string with all atom indeces
    """
    m = Chem.MolFromSmiles(settings['SMILESSTRING'])
    dm = Draw.PrepareMolForDrawing(m)
    d2d = Draw.MolDraw2DSVG(350, 350)
    opts = d2d.drawOptions()
    for i in range(m.GetNumAtoms()):
        opts.atomLabels[i] = m.GetAtomWithIdx(i).GetSymbol() + str(i)
    d2d.DrawMolecule(dm)
    d2d.FinishDrawing()
    return d2d.GetDrawingText()
Example #29
0
 def testGetDrawCoords(self):
     m = Chem.MolFromSmiles('c1ccc(C)c(C)c1C')
     AllChem.Compute2DCoords(m)
     d = Draw.MolDraw2DSVG(300, 300)
     d.DrawMolecule(m)
     conf = m.GetConformer()
     for idx in range(m.GetNumAtoms()):
         pos = conf.GetAtomPosition(idx)
         pos = Geometry.Point2D(pos.x, pos.y)
         dpos1 = d.GetDrawCoords(idx)
         dpos2 = d.GetDrawCoords(pos)
         self.assertAlmostEqual(dpos1.x, dpos2.x, 6)
         self.assertAlmostEqual(dpos1.y, dpos2.y, 6)
Example #30
0
def _get_svg_doc(mol):
    """
    Draws molecule a generates SVG string.
    :param mol:
    :return:
    """
    dm = Draw.PrepareMolForDrawing(mol)
    d2d = Draw.MolDraw2DSVG(300, 300)
    d2d.DrawMolecule(dm)
    d2d.AddMoleculeMetadata(dm)
    d2d.FinishDrawing()
    svg = d2d.GetDrawingText()

    doc = minidom.parseString(svg)
    return doc