def __alignListWorker(self):
        """Working method comparing a reference molecule with a list of fit molecules.

        pairMolList = (refId,refMol,refTitle,fitId,fitMol,fitTitle)

        Map of corresponding atoms is returned.

        Output image is a single-page with grid layout.
        """
        #
        atomMap = []
        firstOne = True

        for (refId, refMol, _refTitle, refImagePath, fitId, fitMol, _fitTitle,
             fitImagePath) in self._pairMolList:
            #
            self.__setupImage()
            #
            OEPrepareDepiction(refMol)
            self._setupMCSS(refMol)

            OEPrepareDepiction(fitMol)
            #
            nAtomsRef = refMol.NumAtoms()
            nAtomsFit = fitMol.NumAtoms()
            minAtoms = min(nAtomsRef, nAtomsFit)
            self._mcss.SetMinAtoms(int(minAtoms * self._minAtomMatchFraction))

            # scaling
            refscale = OEGetMoleculeScale(refMol, self._opts)
            fitscale = OEGetMoleculeScale(refMol, self._opts)
            self._opts.SetScale(min(refscale, fitscale))

            unique = True
            self._miter = self._mcss.Match(fitMol, unique)
            if self._miter.IsValid():
                match = self._miter.Target()
                OEPrepareAlignedDepiction(fitMol, self._mcss.GetPattern(),
                                          match)

                # Depict reference molecule with MCS highlighting
                if firstOne:
                    firstOne = False
                    refdisp = self._setHighlightStyleRef(
                        matchObj=match, refMol=self._mcss.GetPattern())
                    OERenderMolecule(self.__imageRef, refdisp)
                    OEWriteImage(refImagePath, self.__imageRef)

                # Depict fit molecule with MCS highlighting
                fitdisp = self._setHighlightStyleFit(matchObj=match,
                                                     fitMol=fitMol)
                OERenderMolecule(self.__imageFit, fitdisp)
                OEWriteImage(fitImagePath, self.__imageFit)

                for mAt in match.GetAtoms():
                    atomMap.append((refId, mAt.pattern.GetName(), fitId,
                                    mAt.target.GetName()))

        return atomMap
def depict_smiles(smiles):
    """ OEChem and OEDepict image generation """
    # Image to draw on
    image = OEImage(400, 400)

    # Process SMILES
    mol = OEGraphMol()
    parsed = OESmilesToMol(mol, str(unquote(smiles)))
    
    if parsed:
        # Create image of molecule
        newtitle = []
        for c in mol.GetTitle():
            newtitle.append(choice(ALL_EMOJI))
        mol.SetTitle(("".join(newtitle)).encode("UTF-8"))
        
        OEPrepareDepiction(mol)

        disp = OE2DMolDisplay(mol)
        for adisp in disp.GetAtomDisplays():
            adisp.SetLabel(choice(ALL_EMOJI).encode("UTF-8"))
        
        OERenderMolecule(image, disp)
    else:
        # Create error image
        font = OEFont(OEFontFamily_Helvetica, OEFontStyle_Default, 20,
                      OEAlignment_Center, OERed)
        image.DrawText(OE2DPoint(image.GetWidth()/2.0, image.GetHeight()/2.0),
                       'Your SMILES is not valid', font)

    img_content = OEWriteImageToString('svg', image)

    return Response(img_content, mimetype='image/svg+xml')
Exemplo n.º 3
0
    def setRefId(self,
                 ccId,
                 title=None,
                 suppressHydrogens=False,
                 cachePath="/data/components/ligand-dict-v3"):
        """Set the query molecule for MCSS comparison using the input chemical component ID.
        It is assumed that the definition for this ID can be obtained from the chemical component
        repository.

        Once the reference molecule is built, the MCSS calculation is initialized.

        A title is optionally provided otherwise the component Id will be used.

        The hydrogen flag can be used to perform the MCSS using only heavy atoms.
        """
        self.__refId = ccId
        ccIdU = ccId.upper()
        self.__refPath = os.path.join(cachePath, ccIdU[0], ccIdU,
                                      ccIdU + ".cif")

        _id, self.__refmol, self.__refFD = self.__getCCDefFile(
            self.__refPath, suppressHydrogens=suppressHydrogens)
        #
        # Insert title here -
        if title is not None:
            self.__refmol.SetTitle(title)
            self.__refTitle = title
        else:
            self.__refmol.SetTitle(self.__refId)
            self.__refTitle = None
        #
        #
        OEPrepareDepiction(self.__refmol)
        self.__setupMCSS(self.__refmol)
Exemplo n.º 4
0
    def prepare(self):
        self.__setupImage()
        # We convert to list as may come in as a python 3 zipobject with is not indexable
        mollist = list(self._molTitleList)
        for idx, cell in enumerate(self.__grid.GetCells()):
            _ccId, oeMol, title = mollist[idx]
            #
            if self._params["suppressHydrogens"]:
                mol = oeMol.getGraphMolSuppressH()
            else:
                mol = oeMol.getMol()
            if self.__useTitle:
                mol.SetTitle(title)
                self._opts.SetTitleHeight(5.0)
            else:
                mol.SetTitle("")
            #
            #
            OEPrepareDepiction(mol)
            self._opts.SetDimensions(cell.GetWidth(), cell.GetHeight(),
                                     OEScale_AutoScale)

            self._assignDisplayOptions()

            disp = OE2DMolDisplay(mol, self._opts)
            OERenderMolecule(cell, disp)
            if self._params["cellBorders"]:
                OEDrawBorder(cell, OEPen(OEBlackPen))
Exemplo n.º 5
0
    def setRefPath(self,
                   ccPath,
                   title=None,
                   suppressHydrogens=False,
                   type="CC",
                   importType="2D"):  # pylint: disable=redefined-builtin
        """Set the query molecule for MCSS comparison using the input file path.

        The file type is either ['CC'] for a chemical component definition or another file type
        supported by OE toolkit assumed to have a conventional file extension for this type.

        Once the reference molecule is built, the MCSS calculation is initialized.

        A title is optionally provided otherwise the component Id will be used.

        The hydrogen flag can be used to perform the MCSS using only heavy atoms.
        """
        self.__refPath = ccPath
        if type in ["CC"]:
            (self.__refId, self.__refmol, self.__refFD) = self.__getCCDefFile(
                ccPath, suppressHydrogens=suppressHydrogens)
        else:
            (self.__refId, self.__refmol, self.__refFD) = self.__getMiscFile(
                ccPath,
                suppressHydrogens=suppressHydrogens,
                importType=importType)

        if self.__verbose:
            self.__lfh.write("Derived ref ID     = %s\n" % self.__refId)
            self.__lfh.write("SMILES (stereo)  = %s\n" %
                             self.__refFD["SMILES_STEREO"])
        #
        # Insert title here -
        if title is not None:
            self.__refmol.SetTitle(title)
            self.__refTitle = title
        else:
            self.__refmol.SetTitle(self.__refId)
            self.__refTitle = None

        OEPrepareDepiction(self.__refmol)
        self.__setupMCSS(self.__refmol)
Exemplo n.º 6
0
    def prepare(self):
        self.__setupImage()
        rows = self._params["gridRows"]
        cols = self._params["gridCols"]
        grid = OEImageGrid(self.__image, rows, cols)

        citer = grid.GetCells()

        for _ccId, oeMol, title in self._molTitleList:
            if not citer.IsValid():
                # go to next page
                self.__image = self.__multi.NewPage()
                grid = OEImageGrid(self.__image, rows, cols)
                grid.SetCellGap(self._params["cellGap"])
                grid.SetMargins(self._params["cellMargin"])
                citer = grid.GetCells()

            cell = citer.Target()
            #
            if self._params["suppressHydrogens"]:
                mol = oeMol.getGraphMolSuppressH()
            else:
                mol = oeMol.getMol()

            if self.__useTitle:
                mol.SetTitle(title)
                self._opts.SetTitleHeight(5.0)
            else:
                mol.SetTitle("")
            #
            #
            OEPrepareDepiction(mol)
            self._opts.SetDimensions(cell.GetWidth(), cell.GetHeight(),
                                     OEScale_AutoScale)
            self._assignDisplayOptions()

            disp = OE2DMolDisplay(mol, self._opts)
            OERenderMolecule(cell, disp)
            OEDrawBorder(cell, OEPen(OEBlackPen))

            citer.Next()
Exemplo n.º 7
0
    OEAddHighlighting,
    OEGetMoleculeScale,
    OEHighlightStyle_BallAndStick,
    OEImage,
    OEImageGrid,
    OEPrepareAlignedDepiction,
    OEPrepareDepiction,
    OERenderMolecule,
    OEScale_AutoScale,
    OETitleLocation_Hidden,
    OEWriteImage,
)

refmol = OEGraphMol()
OEParseSmiles(refmol, "c1cc(c2cc(cnc2c1)CCCO)C(=O)CCO")
OEPrepareDepiction(refmol)

fitmol = OEGraphMol()
OEParseSmiles(fitmol, "c1cc2ccc(cc2c(c1)C(=O)O)CCO")
OEPrepareDepiction(fitmol)

mcss = OEMCSSearch(OEMCSType_Approximate)
atomexpr = OEExprOpts_DefaultAtoms
bondexpr = OEExprOpts_DefaultBonds
mcss.Init(refmol, atomexpr, bondexpr)
mcss.SetMCSFunc(OEMCSMaxBondsCompleteCycles())

image = OEImage(400, 200)

rows = 1
cols = 2
Exemplo n.º 8
0
    def alignPairList(
        self,
        imagePath="multi.pdf",
        suppressHydrogens=False,
        gridRows=2,
        gridCols=2,
        optInverseFit=True,
        highLightStyle="stick",
        highLightMatchColor="green",
        highLightNotMatchColor="pink",
    ):
        """Compare molecule pairs in the current __pairTupleList.

        pairTupleList = (refId,refPath,refTitle,fitId,fitPath,fitTitle)

        Map of corresponding atoms is returned.

        Image Output is in multipage layout.
        """
        #
        self.__setupImageMulti(gridRows=gridRows, gridCols=gridCols)
        #
        atomMap = []
        #
        numRows = self.__grid.NumRows()
        rowIdx = 0
        for (refId, refPath, refTitle, fitId, fitPath,
             fitTitle) in self.__pairTupleList:
            self.setRefPath(refPath,
                            title=refTitle,
                            suppressHydrogens=suppressHydrogens)
            OEPrepareDepiction(self.__refmol)

            #
            _tId, fitmol, _fitFD = self.__getCCDefFile(
                fitPath, suppressHydrogens=suppressHydrogens)
            fitmol.SetTitle(fitTitle)
            #
            # self.__minAtomMatchFraction %  of the smaller molecule --
            #
            nAtomsRef = self.__refmol.NumAtoms()
            nAtomsFit = fitmol.NumAtoms()
            minAtoms = min(nAtomsRef, nAtomsFit)
            mcssMinAtoms = int(minAtoms * self.__minAtomMatchFraction)
            self.__mcss.SetMinAtoms(mcssMinAtoms)

            OEPrepareDepiction(fitmol)
            rowIdx += 1
            if rowIdx > numRows:
                self.__newPage()
                rowIdx = 1
            refcell = self.__grid.GetCell(rowIdx, 1)
            fitcell = self.__grid.GetCell(rowIdx, 2)

            self.__opts.SetAtomStereoStyle(OEAtomStereoStyle_Display_All)
            # opts.SetTitleLocation(OETitleLocation_Hidden)

            refscale = OEGetMoleculeScale(self.__refmol, self.__opts)
            fitscale = OEGetMoleculeScale(self.__refmol, self.__opts)
            self.__opts.SetScale(min(refscale, fitscale))

            if highLightStyle == "ballAndStick":
                hstyle = OEHighlightStyle_BallAndStick
            elif highLightStyle == "stick":
                hstyle = OEHighlightStyle_Stick
            else:
                hstyle = OEHighlightStyle_BallAndStick

            if highLightMatchColor == "blue":
                myHighLightMatchColor = OEBlueTint
            elif highLightMatchColor == "green":
                myHighLightMatchColor = OEGreenTint
            elif highLightMatchColor == "pink":
                myHighLightMatchColor = OEPinkTint
            else:
                myHighLightMatchColor = OEBlueTint

            if highLightNotMatchColor == "blue":
                myHighLightNotMatchColor = OEBlueTint
            elif highLightNotMatchColor == "green":
                myHighLightNotMatchColor = OEGreenTint
            elif highLightNotMatchColor == "pink":
                myHighLightNotMatchColor = OEPinkTint
            else:
                myHighLightNotMatchColor = OEBlueTint

            optInverseFit = True

            self.__lfh.write(
                "+OeAlignDepict.alignPairList refId %s fitId %s nAtomsRef %d nAtomsFit %s mcssMinAtoms %d\n"
                % (refId, fitId, nAtomsRef, nAtomsFit, mcssMinAtoms))
            unique = True

            miter = self.__mcss.Match(fitmol, unique)
            if miter.IsValid():
                match = miter.Target()
                OEPrepareAlignedDepiction(fitmol, self.__mcss.GetPattern(),
                                          match)

                # Depict reference molecule with MCS highlighting

                refdisp = OE2DMolDisplay(self.__mcss.GetPattern(), self.__opts)
                patoms = OEIsAtomMember(match.GetPatternAtoms())
                OEAddHighlighting(refdisp, myHighLightMatchColor, hstyle,
                                  patoms)
                pbonds = OEIsBondMember(match.GetPatternBonds())
                OEAddHighlighting(refdisp, myHighLightMatchColor, hstyle,
                                  pbonds)
                OERenderMolecule(refcell, refdisp)

                # Depict fit molecule with MCS highlighting
                if optInverseFit:
                    fitdisp = OE2DMolDisplay(fitmol, self.__opts)
                    tatoms = OEIsAtomMember(match.GetTargetAtoms())
                    OEAddHighlighting(fitdisp, myHighLightNotMatchColor,
                                      hstyle, OENotAtom(tatoms))
                    tbonds = OEIsBondMember(match.GetTargetBonds())
                    OEAddHighlighting(fitdisp, myHighLightNotMatchColor,
                                      hstyle, OENotBond(tbonds))
                    OERenderMolecule(fitcell, fitdisp)
                else:
                    fitdisp = OE2DMolDisplay(fitmol, self.__opts)
                    tatoms = OEIsAtomMember(match.GetTargetAtoms())
                    OEAddHighlighting(fitdisp, myHighLightNotMatchColor,
                                      hstyle, tatoms)
                    tbonds = OEIsBondMember(match.GetTargetBonds())
                    OEAddHighlighting(fitdisp, myHighLightNotMatchColor,
                                      hstyle, tbonds)
                    OERenderMolecule(fitcell, fitdisp)

                for mAt in match.GetAtoms():
                    atomMap.append((self.__refId, mAt.pattern.GetName(), fitId,
                                    mAt.target.GetName()))

        OEWriteMultiPageImage(imagePath, self.__multi)
        return atomMap
Exemplo n.º 9
0
    def alignPair(self, imagePath="mcs-match.svg", imageX=400, imageY=400):
        """Compare current reference and fit molecules by MCSS.

        Map of corresponding atoms is returned.

        imagePath is the path of the output image.
        """
        atomMap = []
        self.__setupImage(imageX=imageX, imageY=imageY)

        if self.__refTitle is None:
            self.__refTitle = self.__refId + "/" + self.__fitId
        self.__refmol.SetTitle(self.__refTitle)
        OEPrepareDepiction(self.__refmol)

        #
        if self.__fitTitle is None:
            self.__fitTitle = self.__fitId + "/" + self.__refId
        self.__fitmol.SetTitle(self.__fitTitle)
        OEPrepareDepiction(self.__fitmol)

        #
        # opts = OE2DMolDisplayOptions(self.__grid.GetCellWidth(), self.__grid.GetCellHeight(), OEScale_AutoScale)
        #
        refcell = self.__grid.GetCell(1, 1)
        fitcell = self.__grid.GetCell(1, 2)

        self.__opts.SetAtomStereoStyle(OEAtomStereoStyle_Display_All)
        # opts.SetTitleLocation(OETitleLocation_Hidden)

        refscale = OEGetMoleculeScale(self.__refmol, self.__opts)
        fitscale = OEGetMoleculeScale(self.__refmol, self.__opts)
        self.__opts.SetScale(min(refscale, fitscale))

        hstyle = OEHighlightStyle_BallAndStick

        unique = True
        miter = self.__mcss.Match(self.__fitmol, unique)
        if miter.IsValid():
            match = miter.Target()
            OEPrepareAlignedDepiction(self.__fitmol, self.__mcss.GetPattern(),
                                      match)

            # Depict reference molecule with MCS highlighting

            refdisp = OE2DMolDisplay(self.__mcss.GetPattern(), self.__opts)
            patoms = OEIsAtomMember(match.GetPatternAtoms())
            OEAddHighlighting(refdisp, OEBlueTint, hstyle, patoms)
            pbonds = OEIsBondMember(match.GetPatternBonds())
            OEAddHighlighting(refdisp, OEBlueTint, hstyle, pbonds)
            OERenderMolecule(refcell, refdisp)

            # Depict fit molecule with MCS highlighting

            fitdisp = OE2DMolDisplay(self.__fitmol, self.__opts)
            tatoms = OEIsAtomMember(match.GetTargetAtoms())
            OEAddHighlighting(fitdisp, OEBlueTint, hstyle, tatoms)
            tbonds = OEIsBondMember(match.GetTargetBonds())
            OEAddHighlighting(fitdisp, OEBlueTint, hstyle, tbonds)
            OERenderMolecule(fitcell, fitdisp)

            for mAt in match.GetAtoms():
                atomMap.append(
                    (self.__refId, mAt.pattern.GetName(), self.__fitId,
                     mAt.target.GetName()))

        OEWriteImage(imagePath, self.__image)
        return atomMap
    def __alignListWorker(self, imagePath="single.pdf", layout="pairs"):
        """Working method comparing a reference molecule with a list of fit molecules.

        pairMolList = (refId,refMol,refTitle,refImgPath,fitId,fitMol,fitTitle,fitImgPath)

        Map of corresponding atoms is returned.

        Output image is a single-page with grid layout.
        """
        #
        self.__setupImage()
        #
        atomMap = []

        firstOne = True

        for (refId, refMol, _refTitle, _refImagePath, fitId, fitMol, fitTitle,
             _fitImagePath) in self._pairMolList:
            #
            OEPrepareDepiction(refMol)
            self._setupMCSS(refMol)
            #
            fitMol.SetTitle(fitTitle)
            OEPrepareDepiction(fitMol)
            #
            #
            nAtomsRef = refMol.NumAtoms()
            nAtomsFit = fitMol.NumAtoms()
            minAtoms = min(nAtomsRef, nAtomsFit)
            self._mcss.SetMinAtoms(int(minAtoms * self._minAtomMatchFraction))

            # scaling
            refscale = OEGetMoleculeScale(refMol, self._opts)
            fitscale = OEGetMoleculeScale(refMol, self._opts)
            self._opts.SetScale(min(refscale, fitscale))

            unique = True
            self._miter = self._mcss.Match(fitMol, unique)

            if self._miter.IsValid():
                match = self._miter.Target()
                OEPrepareAlignedDepiction(fitMol, self._mcss.GetPattern(),
                                          match)

                # Depict reference molecule with MCS highlighting
                if (firstOne and
                    (layout in ["list"])) or (layout in ["pairs"]):
                    firstOne = False
                    refdisp = self._setHighlightStyleRef(
                        matchObj=match, refMol=self._mcss.GetPattern())
                    if not self.__citer.IsValid():
                        break
                    cell = self.__citer.Target()
                    self.__citer.Next()
                    OERenderMolecule(cell, refdisp)
                    if self._params["cellBorders"]:
                        OEDrawBorder(cell, OEPen(OEBlackPen))

                # Depict fit molecule with MCS highlighting
                fitdisp = self._setHighlightStyleFit(matchObj=match,
                                                     fitMol=fitMol)
                if not self.__citer.IsValid():
                    break
                cell = self.__citer.Target()
                self.__citer.Next()
                OERenderMolecule(cell, fitdisp)

                if self._params["cellBorders"]:
                    OEDrawBorder(cell, OEPen(OEBlackPen))

                for mAt in match.GetAtoms():
                    atomMap.append((refId, mAt.pattern.GetName(), fitId,
                                    mAt.target.GetName()))

        OEWriteImage(imagePath, self.__image)
        return atomMap
    def __alignListMultiWorker(self, imagePath="multi.pdf", layout="pairs"):
        """Working method comparing a reference molecule with a list of fit molecules.

        pairMolList = (refId,refMol,refTitle,fitId,fitMol,fitTitle)

        Map of corresponding atoms is returned.

        Image Output is in multipage layout.
        """
        #
        self.__setupImageMulti()
        #
        atomMap = []
        firstOne = True
        iCount = 0
        for (refId, refMol, _refTitle, _refImagePath, fitId, fitMol, fitTitle,
             _fitImagePath) in self._pairMolList:
            iCount += 1
            self.__lfh.write(
                "+OeDepictMCSAlignMulti.__alignListMultiWorker Starting match pair refId %s fitId %s count %d of %d\n"
                % (refId, fitId, iCount, len(self._pairMolList)))

            #
            OEPrepareDepiction(refMol)
            self._setupMCSS(refMol)
            #
            fitMol.SetTitle(fitTitle)
            OEPrepareDepiction(fitMol)
            #
            nAtomsRef = refMol.NumAtoms()
            nAtomsFit = fitMol.NumAtoms()
            minAtoms = min(nAtomsRef, nAtomsFit)
            mcssMinAtoms = int(minAtoms * self._minAtomMatchFraction)
            self._mcss.SetMinAtoms(mcssMinAtoms)

            # scaling
            refscale = OEGetMoleculeScale(refMol, self._opts)
            fitscale = OEGetMoleculeScale(refMol, self._opts)
            self._opts.SetScale(min(refscale, fitscale))

            unique = True
            self.__lfh.write(
                "+OeDepictMCSAlignMulti.__alignListMultiWorker refId %s fitId %s nAtomsRef %d nAtomsFit %d mcssMinAtoms %d\n"
                % (refId, fitId, nAtomsRef, nAtomsFit, mcssMinAtoms))
            self._miter = self._mcss.Match(fitMol, unique)

            self.__lfh.write(
                "+OeDepictMCSAlignMulti.__alignListMultiWorker mcss match completed for refId %s fitId %s\n"
                % (refId, fitId))
            if self._miter.IsValid():
                match = self._miter.Target()
                OEPrepareAlignedDepiction(fitMol, self._mcss.GetPattern(),
                                          match)

                # Depict reference molecule with MCS highlighting
                if (firstOne and
                    (layout in ["list"])) or (layout in ["pairs"]):
                    firstOne = False
                    refdisp = self._setHighlightStyleRef(
                        matchObj=match, refMol=self._mcss.GetPattern())
                    if not self.__citer.IsValid():
                        self.__newPage()
                    cell = self.__citer.Target()
                    self.__citer.Next()
                    OERenderMolecule(cell, refdisp)
                    if self._params["cellBorders"]:
                        OEDrawBorder(cell, OEPen(OEBlackPen))

                # Depict fit molecule with MCS highlighting
                fitdisp = self._setHighlightStyleFit(matchObj=match,
                                                     fitMol=fitMol)
                if not self.__citer.IsValid():
                    self.__newPage()
                cell = self.__citer.Target()
                self.__citer.Next()
                OERenderMolecule(cell, fitdisp)

                if self._params["cellBorders"]:
                    OEDrawBorder(cell, OEPen(OEBlackPen))

                for mAt in match.GetAtoms():
                    atomMap.append((refId, mAt.pattern.GetName(), fitId,
                                    mAt.target.GetName()))

                self.__lfh.write(
                    "+OeDepictMCSAlignMulti.__alignListMultiWorker mcss match completed for refId %s fitId %s total map length %d \n"
                    % (refId, fitId, len(atomMap)))

        self.__lfh.write(
            "+OeDepictMCSAlignMulti.__alignListMultiWorker writing image %s\n"
            % imagePath)
        OEWriteMultiPageImage(imagePath, self.__multi)
        self.__lfh.write(
            "+OeDepictMCSAlignMulti.__alignListMultiWorker completed with map lenth %d\n"
            % len(atomMap))
        #
        return atomMap