def main(argv=[__name__]):
    if len(argv) != 4:
        oechem.OEThrow.Usage("%s <database> <prefix> <n_servers>" % argv[0])

    # input - preserve rotor-offset-compression
    ifs = oechem.oemolistream()
    oechem.OEPreserveRotCompress(ifs)

    ifname = argv[1]
    if not ifs.open(ifname):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])

    # output
    prefix = argv[2]
    ext = oechem.OEGetFileExtension(prefix)
    extstrt = len(prefix)
    if ext:
        extstrt = -(len(ext) + 1)
    else:
        ext = oechem.OEGetFileExtension(ifname)
    base = prefix[:extstrt]
    fmt = base + "_%i." + ext

    nservers = int(argv[3])
    outstrms = []
    for i in range(1, nservers + 1):
        ofs = oechem.oemolostream()
        if not ofs.open(fmt % i):
            oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])

        outstrms.append(ofs)

    dots = oechem.OEDots(10000, 200, "molecules")
    for mol in ifs.GetOEMols():
        oefastrocs.OEPrepareFastROCSMol(mol)

        nhvyatoms = oechem.OECount(mol, oechem.OEIsHeavy())

        ofs = outstrms[nhvyatoms % nservers]
        oechem.OEWriteMolecule(ofs, mol)

        dots.Update()

    dots.Total()

    for strm in outstrms:
        fname = strm.GetFileName()
        strm.close()
        oechem.OEThrow.Info("Indexing %s" % fname)
        if not oechem.OECreateMolDatabaseIdx(fname):
            oechem.OEThrow.Fatal("Failed to index %s" % fname)

    return 0
Ejemplo n.º 2
0
def main(argv=[__name__]):
    if len(argv) != 5:
        oechem.OEThrow.Usage("%s <queryfile> <fitfile> <outfile> <nhits>" %
                             argv[0])

    if oechem.OEGetFileExtension(sys.argv[1]) != "sq":
        oechem.OEThrow.Fatal("Requires a shape query .sq input file format")

    fitfs = oechem.oemolistream(sys.argv[2])
    outfs = oechem.oemolostream(sys.argv[3])
    nhits = int(sys.argv[4])

    query = oeshape.OEShapeQuery()
    oeshape.OEReadShapeQuery(sys.argv[1], query)

    # Setup OEROCS with specified number of best hits
    options = oeshape.OEROCSOptions()
    options.SetNumBestHits(nhits)
    rocs = oeshape.OEROCS(options)

    rocs.SetDatabase(fitfs)
    for res in rocs.Overlay(query):
        outmol = res.GetOverlayConf()
        oechem.OEWriteMolecule(outfs, outmol)
        print("title: %s  tanimoto combo = %.2f" %
              (outmol.GetTitle(), res.GetTanimotoCombo()))
Ejemplo n.º 3
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureReportOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-in")
    ifs = oechem.oemolistream()
    ifs.SetConfTest(oechem.OEAbsoluteConfTest())  # VTL
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    oname = itf.GetString("-out")
    ext = oechem.OEGetFileExtension(oname)
    if ext != "pdf":
        oechem.OEThrow.Fatal("Output must be PDF format.")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    if itf.HasString("-ringdict"):
        rdfname = itf.GetString("-ringdict")
        if not oechem.OEInit2DRingDictionary(rdfname):
            oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetFooterHeight(25.0)
    report = oedepict.OEReport(ropts)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetDimensions(report.GetCellWidth(), report.GetCellHeight(),
                        oedepict.OEScale_AutoScale)

    for mol in ifs.GetOEMols():  # VTL ignore confs; dont use GetOEGraphMols
        print(mol.GetTitle())  # VTL
        cell = report.NewCell()
        oedepict.OEPrepareDepiction(mol, popts)
        disp = oedepict.OE2DMolDisplay(mol, dopts)
        oedepict.OERenderMolecule(cell, disp)

    font = oedepict.OEFont(oedepict.OEFontFamily_Default,
                           oedepict.OEFontStyle_Bold, 12,
                           oedepict.OEAlignment_Center, oechem.OEBlack)
    for pagenum, footer in enumerate(report.GetFooters()):
        text = "Page %d of %d" % (pagenum + 1, report.NumPages())
        oedepict.OEDrawTextToCenter(footer, text, font)

    oedepict.OEWriteReport(ofs, ext, report)

    return 0
Ejemplo n.º 4
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <molfile> <queryfile>" % sys.argv[0])

    molfs = oechem.oemolistream(sys.argv[1])
    mol = oechem.OEGraphMol()
    oechem.OEReadMolecule(molfs, mol)

    if oechem.OEGetFileExtension(sys.argv[2]) != "sq":
        oechem.OEThrow.Fatal(
            "Only can write shape query to .sq output file format")

    # Use OEOverlapPrep to remove hydrogens and add
    # color atoms to the molecule
    prep = oeshape.OEOverlapPrep()
    prep.Prep(mol)

    # Get the color atoms, create gaussians and add them
    # to the shape query
    query = oeshape.OEShapeQuery()
    for atom in oeshape.OEGetColorAtoms(mol):
        coords = oechem.OEFloatArray(3)
        mol.GetCoords(atom, coords)
        gauss = oegrid.OEGaussian(1.0, 1.0, coords,
                                  oeshape.OEGetColorType(atom))
        query.AddColorGaussian(gauss)

    # Remove color atoms from the molecule and add to the query
    oeshape.OERemoveColorAtoms(mol)
    query.SetMolecule(mol)

    oeshape.OEWriteShapeQuery(sys.argv[2], query)
    print("shape query created")
Ejemplo n.º 5
0
def SetupInterface(argv, itf):
    oechem.OEConfigure(itf, InterfaceData)
    if oechem.OECheckHelp(itf, argv):
        return False
    if not oechem.OEParseCommandLine(itf, argv):
        return False
    infile = itf.GetString("-in")
    if not oechem.OEIsReadable(
            oechem.OEGetFileType(oechem.OEGetFileExtension(infile))):
        oechem.OEThrow.Warning("%s is not a readable input file" % infile)
        return False
    outfile = itf.GetString("-out")
    if not oegrid.OEIsWriteableGrid(
            oegrid.OEGetGridFileType(oechem.OEGetFileExtension(outfile))):
        oechem.OEThrow.Warning("%s is not a writable grid file" % outfile)
        return False
    return True
Ejemplo n.º 6
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 400.0)
    oedepict.OEConfigureImageHeight(itf, 400.0)
    oedepict.OEConfigureImageGridParams(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    rows = oedepict.OEGetImageGridNumRows(itf)
    cols = oedepict.OEGetImageGridNumColumns(itf)
    grid = oedepict.OEImageGrid(image, rows, cols)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetDimensions(grid.GetCellWidth(), grid.GetCellHeight(),
                        oedepict.OEScale_AutoScale)

    celliter = grid.GetCells()
    for iname in itf.GetStringList("-in"):
        ifs = oechem.oemolistream()
        if not ifs.open(iname):
            oechem.OEThrow.Warning("Cannot open %s input file!" % iname)
            continue

        for mol in ifs.GetOEGraphMols():
            if not celliter.IsValid():
                break

            oedepict.OEPrepareDepiction(mol, popts)
            disp = oedepict.OE2DMolDisplay(mol, dopts)
            oedepict.OERenderMolecule(celliter.Target(), disp)
            celliter.Next()

    oedepict.OEWriteImage(ofs, ext, image)

    return 0
Ejemplo n.º 7
0
    def repo_new(self, oid, filename, hitsize, remote_addr):
        ext = oechem.OEGetFileExtension(filename)
        basename = filename[:-len(ext) - 1]
        reportable = 0 if ext == 'sq' else 1
        timestamp1 = time.time()

        self('INSERT into repo (oid, basename, ext, hitsize, reportable, timestamp1, ip) '
             'VALUES (?,?,?,?,?,?,?)', \
             (oid, basename, ext, hitsize, reportable, timestamp1, remote_addr),
             commit=True)
Ejemplo n.º 8
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    if itf.HasString("-ringdict"):
        rdfname = itf.GetString("-ringdict")
        if not oechem.OEInit2DRingDictionary(rdfname):
            oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)

    oedepict.OEPrepareDepiction(mol, popts)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    dopts = oedepict.OE2DMolDisplayOptions(width, height,
                                           oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)

    disp = oedepict.OE2DMolDisplay(mol, dopts)
    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
Ejemplo n.º 9
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oegraphsim.OEConfigureFingerPrint(
        itf, oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree))

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    ifname = itf.GetString("-in")
    ffname = itf.GetString("-fpdb")

    if oechem.OEGetFileExtension(ffname) != "fpbin":
        oechem.OEThrow.Fatal(
            "Fingerprint database file should have '.fpbin' file extension!")

    idxfname = oechem.OEGetMolDatabaseIdxFileName(ifname)

    if not os.path.exists(idxfname):
        if not oechem.OECreateMolDatabaseIdx(ifname):
            oechem.OEThrow.Warning("Unable to create %s molecule index file" %
                                   idxfname)

    oechem.OEThrow.Info("Using %s index molecule file" % idxfname)

    moldb = oechem.OEMolDatabase()
    if not moldb.Open(ifname):
        oechem.OEThrow.Fatal("Cannot open molecule database file!")

    nrmols = moldb.GetMaxMolIdx()

    fptype = oegraphsim.OESetupFingerPrint(itf)
    oechem.OEThrow.Info("Using fingerprint type %s" % fptype.GetFPTypeString())

    opts = oegraphsim.OECreateFastFPDatabaseOptions(fptype)
    opts.SetTracer(oechem.OEDots(100000, 1000, "fingerprints"))
    oechem.OEThrow.Info("Generating fingerprints with %d threads" %
                        opts.GetNumProcessors())

    timer = oechem.OEWallTimer()
    if not oegraphsim.OECreateFastFPDatabaseFile(ffname, ifname, opts):
        oechem.OEThrow.Fatal("Cannot create fingerprint database file!")

    oechem.OEThrow.Info("%5.2f secs to generate %d fingerprints" %
                        (timer.Elapsed(), nrmols))

    return 0
Ejemplo n.º 10
0
    def upload(self, file, hitsize, remote_addr):
        oid = uuid.uuid4().hex
        filename = secure_filename(file.filename)
        ext = oechem.OEGetFileExtension(filename)
        os.makedirs(f'instance/{oid}', exist_ok=True)
        opath = f'instance/{oid}/query.{ext}'

        file.save(opath)

        if ext != 'sq' and not misc.check_mol(opath):
            os.unlink(opath)
            return

        st = state.State()
        print('hitsize:', hitsize) #@@
        st.repo_new(oid, filename, hitsize, remote_addr)
Ejemplo n.º 11
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <input> <output>" % argv[0])

    # input - preserve rotor-offset-compression
    ifs = oechem.oemolistream()
    ihand = ifs.GetBinaryIOHandler()
    ihand.Clear()
    oechem.OEInitHandler(ihand, oechem.OEBRotCompressOpts(),
                         oechem.OEBRotCompressOpts())

    ifname = argv[1]
    if not ifs.open(ifname):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])

    # output
    ofname = argv[2]
    oformt = oechem.OEGetFileType(oechem.OEGetFileExtension(ofname))
    if oformt != oechem.OEFormat_OEB:
        oechem.OEThrow.Fatal("Output file format much be OEB")

    ofs = oechem.oemolostream()
    if not ofs.open(ofname):
        oechem.OEThrow.Fatal("Unable to open %s for writing" % ofname)

    iss = oechem.oeisstream(COLOR_FORCE_FIELD)
    cff = oeshape.OEColorForceField()
    if not cff.Init(iss):
        oechem.OEThrow.Fatal("Unable to initialize OEColorForceField")

    dots = oechem.OEDots(10000, 200, "molecules")
    for mol in ifs.GetOEMols():
        oefastrocs.OEPrepareFastROCSMol(mol, cff)

        oechem.OEWriteMolecule(ofs, mol)

        dots.Update()

    dots.Total()
    ofs.close()

    print("Indexing %s" % ofname)
    if not oechem.OECreateMolDatabaseIdx(ofname):
        oechem.OEThrow.Fatal("Failed to index %s" % argv[2])

    return 0
Ejemplo n.º 12
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    if ifs.GetFormat() != oechem.OEFormat_MDL:
        oechem.OEThrow.Fatal("Input file is not an MDL query file")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMDLQueryFile(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read mdl query input file!")

    clearcoords, suppressH = False, False
    oedepict.OEPrepareDepiction(mol, clearcoords, suppressH)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    opts = oedepict.OE2DMolDisplayOptions(width, height,
                                          oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    disp = oedepict.OE2DMolDisplay(mol, opts)
    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
Ejemplo n.º 13
0
    def __init__(self, ipf, keepAlts=F, verbose=T):
        self.ipf = ipf
        self.keepAlts = keepAlts
        self.verbose = verbose

        flavor = oechem.OEIFlavor_PDB_Default
        ims = oechem.oemolistream()
        ims.SetFlavor(oechem.OEFormat_PDB, flavor)

        if not ims.open(self.ipf):
            oechem.OEThrow.Fatal("Unable to open %s for reading." % self.ipf)

        if not oechem.OEIs3DFormat(ims.GetFormat()):
            oechem.OEThrow.Fatal("%s is not in a 3D format." % self.ipf)

        iftp = oechem.OEGetFileType(oechem.OEGetFileExtension(self.ipf))
        if (iftp == oechem.OEFormat_PDB) and not self.keepAlts:
            oechem.OEThrow.Verbose(
                "Default processing of alt locations (keep just 'A' and ' ').")

        inmol = oechem.OEGraphMol()
        if not oechem.OEReadMolecule(ims, inmol):
            oechem.OEThrow.Fatal("Unable to read %s." % self.ipf)

        ims.close()

        if (inmol.NumAtoms() == 0):
            oechem.OEThrow.Fatal("Input molecule %s contains no atoms." %
                                 self.ipf)

        if inmol.GetTitle() == "":
            inmol.SetTitle(ipf[:-4])

        oechem.OEThrow.Verbose("Processing %s." % inmol.GetTitle())
        if not oechem.OEHasResidues(inmol):
            oechem.OEPerceiveResidues(inmol, oechem.OEPreserveResInfo_All)

        self.inmol = inmol
        self.mol = inmol.CreateCopy()
Ejemplo n.º 14
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 900.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(
        itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(
        itf, oechem.OESplitMolComplexSetup_LigName)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-complex")
    oname = itf.GetString("-out")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    complexmol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, complexmol):
        oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)

    if not oechem.OEHasResidues(complexmol):
        oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)

    # Separate ligand and protein

    sopts = oechem.OESplitMolComplexOptions()
    oechem.OESetupSplitMolComplexOptions(sopts, itf)

    ligand = oechem.OEGraphMol()
    protein = oechem.OEGraphMol()
    water = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    pfilter = sopts.GetProteinFilter()
    wfilter = sopts.GetWaterFilter()
    sopts.SetProteinFilter(oechem.OEOrRoleSet(pfilter, wfilter))
    sopts.SetWaterFilter(
        oechem.OEMolComplexFilterFactory(
            oechem.OEMolComplexFilterCategory_Nothing))

    oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)

    if ligand.NumAtoms() == 0:
        oechem.OEThrow.Fatal("Cannot separate complex!")

    # Perceive interactions

    asite = oechem.OEInteractionHintContainer(protein, ligand)
    if not asite.IsValid():
        oechem.OEThrow.Fatal("Cannot initialize active site!")
    asite.SetTitle(ligand.GetTitle())

    oechem.OEPerceiveInteractionHints(asite)

    oegrapheme.OEPrepareActiveSiteDepiction(asite)

    # Depict active site with interactions

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    cframe = oedepict.OEImageFrame(image, width * 0.80, height,
                                   oedepict.OE2DPoint(0.0, 0.0))
    lframe = oedepict.OEImageFrame(image, width * 0.20, height,
                                   oedepict.OE2DPoint(width * 0.80, 0.0))

    opts = oegrapheme.OE2DActiveSiteDisplayOptions(cframe.GetWidth(),
                                                   cframe.GetHeight())
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
    oegrapheme.OERenderActiveSite(cframe, adisp)

    lopts = oegrapheme.OE2DActiveSiteLegendDisplayOptions(10, 1)
    oegrapheme.OEDrawActiveSiteLegend(lframe, adisp, lopts)

    oedepict.OEWriteImage(oname, image)

    return 0
def main(argv=[__name__]):
    if len(argv) < 3:
        oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
        return 0

    # check system
    if not oefastrocs.OEFastROCSIsGPUReady():
        oechem.OEThrow.Info("No supported GPU available!")
        return 0

    # read in database
    dbname = argv[1]
    print("Opening database file %s ..." % dbname)
    dbase = oefastrocs.OEShapeDatabase()
    moldb = oechem.OEMolDatabase()

    if not moldb.Open(dbname):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    dots = oechem.OEThreadedDots(10000, 200, "conformers")
    if not dbase.Open(moldb, dots):
        oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" %
                             dbname)

    # customize search options
    opts = oefastrocs.OEShapeDatabaseOptions()
    opts.SetInitialOrientation(
        oefastrocs.OEFastROCSOrientation_UserInertialStarts)

    opts.SetLimit(5)

    for qfname in argv[2:]:
        # read in query
        qfs = oechem.oemolistream()
        if not qfs.open(qfname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)

        query = oechem.OEGraphMol()
        if not oechem.OEReadMolecule(qfs, query):
            oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)

        ext = oechem.OEGetFileExtension(qfname)
        base = qfname[:-(len(ext) + 1)]

        # write out everthing to a similary named file
        ofs = oechem.oemolostream()
        ofname = base + "_user_results." + ext
        if not ofs.open(ofname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
        oechem.OEWriteMolecule(ofs, query)

        startsCoords = oechem.OEFloatVector()
        atomIdx = 1
        xyz = query.GetCoords()[atomIdx]
        for x in xyz:
            startsCoords.append(x)
        if not len(startsCoords) % 3 == 0:
            oechem.OEThrow.Fatal(
                "Something went wrong whilst reading in user-starts coordinates"
            )

        opts.SetUserStarts(oechem.OEFloatVector(startsCoords),
                           int(len(startsCoords) / 3))

        opts.SetMaxOverlays(opts.GetNumInertialStarts() *
                            opts.GetNumUserStarts())

        if opts.GetInitialOrientation(
        ) == oefastrocs.OEFastROCSOrientation_UserInertialStarts:
            numStarts = opts.GetNumUserStarts()
            print("This example will use %u starts" % numStarts)

        print("Searching for %s" % qfname)
        for score in dbase.GetSortedScores(query, opts):
            print("Score for mol %u(conf %u) %f shape %f color" %
                  (score.GetMolIdx(), score.GetConfIdx(),
                   score.GetShapeTanimoto(), score.GetColorTanimoto()))
            dbmol = oechem.OEMol()
            molidx = score.GetMolIdx()
            if not moldb.GetMolecule(dbmol, molidx):
                print("Unable to retrieve molecule '%u' from the database" %
                      molidx)
                continue

            mol = oechem.OEGraphMol(
                dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
            oechem.OESetSDData(mol, "ShapeTanimoto",
                               "%.4f" % score.GetShapeTanimoto())
            oechem.OESetSDData(mol, "ColorTanimoto",
                               "%.4f" % score.GetColorTanimoto())
            oechem.OESetSDData(mol, "TanimotoCombo",
                               "%.4f" % score.GetTanimotoCombo())
            score.Transform(mol)

            oechem.OEWriteMolecule(ofs, mol)
        print("Wrote results to %s" % ofname)

    return 0
Ejemplo n.º 16
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageOptions(itf)
    oedepict.OEConfigurePrepareDepictionOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)
    oedepict.OEConfigureHighlightParams(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    smarts = itf.GetString("-smarts")

    ss = oechem.OESubSearch()
    if not ss.Init(smarts):
        oechem.OEThrow.Fatal("Cannot parse smarts: %s" % smarts)

    popts = oedepict.OEPrepareDepictionOptions()
    oedepict.OESetupPrepareDepictionOptions(popts, itf)
    oedepict.OEPrepareDepiction(mol, popts)

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    dopts = oedepict.OE2DMolDisplayOptions(width, height,
                                           oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    dopts.SetMargins(10.0)

    disp = oedepict.OE2DMolDisplay(mol, dopts)

    hstyle = oedepict.OEGetHighlightStyle(itf)
    hcolor = oedepict.OEGetHighlightColor(itf)

    oechem.OEPrepareSearch(mol, ss)

    unique = True
    for match in ss.Match(mol, unique):
        oedepict.OEAddHighlighting(disp, hcolor, hstyle, match)

    oedepict.OERenderMolecule(ofs, ext, disp)

    return 0
Ejemplo n.º 17
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 900.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(
        itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(
        itf, oechem.OESplitMolComplexSetup_LigName
        | oechem.OESplitMolComplexSetup_CovLig)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    if itf.HasString("-complex") and (itf.HasString("-protein")
                                      or itf.HasString("-ligand")):
        oechem.OEThrow.Warning("Only complex in %s file fill be used!" %
                               itf.GetString("-complex"))

    if not (itf.HasString("-complex")) ^ (itf.HasString("-protein")
                                          and itf.HasString("-ligand")):
        oechem.OEThrow.Fatal(
            "Please specify either complex or ligand and protein input files!")

    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    # initialize protein and ligand

    protein = oechem.OEGraphMol()
    ligand = oechem.OEGraphMol()
    if not get_protein_and_ligands(protein, ligand, itf):
        oechem.OEThrow.Fatal("Cannot initialize protein and/or ligand!")

    # depict active site with interactions

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(
        itf)
    image = oedepict.OEImage(width, height)

    interactive_legend = False
    magnify_residue = 1.0

    if ext == 'svg':
        interactive_legend = itf.GetBool("-interactive-legend")
        magnify_residue = itf.GetFloat("-magnify-residue")

    cwidth, cheight = width, height
    if not interactive_legend:
        cwidth = cwidth * 0.8

    opts = oegrapheme.OE2DActiveSiteDisplayOptions(cwidth, cheight)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)

    opts.SetRenderInteractiveLegend(interactive_legend)
    opts.SetSVGMagnifyResidueInHover(magnify_residue)

    if interactive_legend:
        depict_complex(image, protein, ligand, opts)
    else:
        main_frame = oedepict.OEImageFrame(
            image, width * 0.80, height, oedepict.OE2DPoint(width * 0.2, 0.0))
        legend_frame = oedepict.OEImageFrame(
            image, width * 0.20, height, oedepict.OE2DPoint(width * 0.0, 0.0))
        depict_complex(main_frame, protein, ligand, opts, legend_frame)

    if ext == 'svg' and (interactive_legend or magnify_residue > 1.0):
        iconscale = 0.5
        oedepict.OEAddInteractiveIcon(image, oedepict.OEIconLocation_TopRight,
                                      iconscale)
    oedepict.OEDrawCurvedBorder(image, oedepict.OELightGreyPen, 10.0)

    oedepict.OEWriteImage(oname, image)

    return 0
Ejemplo n.º 18
0
# liable for any damages or liability in connection with the Sample Code
# or its use.

# @ <SNIPPET>
from openeye import oechem
import sys

if len(sys.argv) != 4:
    oechem.OEThrow.Usage("%s <input> <output> <title>" % sys.argv[0])

moldb = oechem.OEMolDatabase()
if not moldb.Open(sys.argv[1]):
    oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])

if moldb.GetFormat() != oechem.OEGetFileType(
        oechem.OEGetFileExtension(sys.argv[2])):
    oechem.OEThrow.Fatal(
        "Output format does not match input format: %s != %s" %
        (oechem.OEGetFileExtension(
            sys.argv[1]), oechem.OEGetFileExtension(sys.argv[2])))

ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
    oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])

title = sys.argv[3]

for idx in range(moldb.GetMaxMolIdx()):
    if moldb.GetTitle(idx) == title:
        moldb.WriteMolecule(ofs, idx)
# @ </SNIPPET>
Ejemplo n.º 19
0
def is_allowed_file(name):
    d = read_config()
    return oechem.OEGetFileExtension(name) in d['ALLOWED_EXTENSIONS']
Ejemplo n.º 20
0
def render_atom_mapping(filename, molecule1, molecule2, new_to_old_atom_map, width=1200, height=600):
    """
    Render the atom mapping to a PDF file.

    Parameters
    ----------
    filename : str
        The PDF filename to write to.
    molecule1 : openeye.oechem.OEMol
        Initial molecule
    molecule2 : openeye.oechem.OEMol
        Final molecule
    new_to_old_atom_map : dict of int
        new_to_old_atom_map[molecule2_atom_index] is the corresponding molecule1 atom index
    width : int, optional, default=1200
        Width in pixels
    height : int, optional, default=1200
        Height in pixels

    """
    from openeye import oechem, oedepict

    # Make copies of the input molecules
    molecule1, molecule2 = oechem.OEGraphMol(molecule1), oechem.OEGraphMol(molecule2)

    oechem.OEGenerate2DCoordinates(molecule1)
    oechem.OEGenerate2DCoordinates(molecule2)

    # Add both to an OEGraphMol reaction
    rmol = oechem.OEGraphMol()
    rmol.SetRxn(True)
    def add_molecule(mol):
        # Add atoms
        new_atoms = list()
        old_to_new_atoms = dict()
        for old_atom in mol.GetAtoms():
            new_atom = rmol.NewAtom(old_atom.GetAtomicNum())
            new_atoms.append(new_atom)
            old_to_new_atoms[old_atom] = new_atom
        # Add bonds
        for old_bond in mol.GetBonds():
            rmol.NewBond(old_to_new_atoms[old_bond.GetBgn()], old_to_new_atoms[old_bond.GetEnd()], old_bond.GetOrder())
        return new_atoms, old_to_new_atoms

    [new_atoms_1, old_to_new_atoms_1] = add_molecule(molecule1)
    [new_atoms_2, old_to_new_atoms_2] = add_molecule(molecule2)

    # Label reactant and product
    for atom in new_atoms_1:
        atom.SetRxnRole(oechem.OERxnRole_Reactant)
    for atom in new_atoms_2:
        atom.SetRxnRole(oechem.OERxnRole_Product)
    
    core1 = oechem.OEAtomBondSet()
    core2 = oechem.OEAtomBondSet()
    # add all atoms to the set
    core1.AddAtoms(new_atoms_1)
    core2.AddAtoms(new_atoms_2)
    # Label mapped atoms
    core_change = oechem.OEAtomBondSet()
    index =1
    for (index2, index1) in new_to_old_atom_map.items():
        new_atoms_1[index1].SetMapIdx(index)
        new_atoms_2[index2].SetMapIdx(index)
        # now remove the atoms that are core, so only uniques are highlighted
        core1.RemoveAtom(new_atoms_1[index1])
        core2.RemoveAtom(new_atoms_2[index2])
        if new_atoms_1[index1].GetAtomicNum() != new_atoms_2[index2].GetAtomicNum():
            # this means the element type is changing   
            core_change.AddAtom(new_atoms_1[index1])
            core_change.AddAtom(new_atoms_2[index2])            
        index += 1
    # Set up image options
    itf = oechem.OEInterface()
    oedepict.OEConfigureImageOptions(itf)
    ext = oechem.OEGetFileExtension(filename)
    if not oedepict.OEIsRegisteredImageFile(ext):
        raise Exception('Unknown image type for filename %s' % filename)
    ofs = oechem.oeofstream()
    if not ofs.open(filename):
        raise Exception('Cannot open output file %s' % filename)

    # Setup depiction options
    oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    opts.SetBondWidthScaling(True)
    opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx())
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)

    # Depict reaction with component highlights
    oechem.OEGenerate2DCoordinates(rmol)
    rdisp = oedepict.OE2DMolDisplay(rmol, opts)
    
    oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEPink),oedepict.OEHighlightStyle_Stick, core1)
    oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEPurple),oedepict.OEHighlightStyle_Stick, core2)
    oedepict.OEAddHighlighting(rdisp, oechem.OEColor(oechem.OEGreen),oedepict.OEHighlightStyle_Stick, core_change)
    oedepict.OERenderMolecule(ofs, ext, rdisp)
    ofs.close()
Ejemplo n.º 21
0
def main(argv=[__name__]):
    """
    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    oname = itf.GetString("-out")
    iname = itf.GetString("-in")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

  
    ## INPUT PARAMETERS
    #########################################################
    #########################################################
    
    mm = 'tyk2/og_pdbs'
    qml = 'tyk2/forward_snapshots'
    phase = 'solvent'
    which_ligand = 'old'
    dir_name = iname
    ligand_pdbs_mm = glob.glob(f"{mm}/{dir_name}/{which_ligand}*{phase}.pdb")
    print(len(ligand_pdbs_mm))
    ligand_pdbs_qml = glob.glob(f"{qml}/{dir_name}/{which_ligand}*{phase}.pdb")
    print(len(ligand_pdbs_qml))

    #d = np.load('full_data_dict.npy', allow_pickle=True)
    from_ligand, to_ligand = iname.replace('from', '').replace('to', '').replace('lig', '')
    print(from_ligand)
    print(to_ligand)
    #key1 = (1, 8)
    #key2 = ('solvent', which_ligand)
    #########################################################
    #########################################################

    #d = d.flatten()[0]
    #work = d[key1][key2]
    #print(work)

    
    for i, (mm_pdb_path, ani_pdb_path) in enumerate(zip(ligand_pdbs_mm, ligand_pdbs_qml)):
        print(mm_pdb_path, ani_pdb_path)
        if i == 0:
            MM_mol = createOEMolFromSDF(mm_pdb_path, 0)
            ANI_mol = createOEMolFromSDF(ani_pdb_path, 0)
        else:
            # there absolutely must be a better/faster way of doing this because this is ugly and slow
            MM_mol.NewConf(createOEMolFromSDF(mm_pdb_path, 0))
            ANI_mol.NewConf(createOEMolFromSDF(ani_pdb_path, 0))
"""
    ofs = oechem.oeofstream()
    oname = f"tor_out"
    ext = oechem.OEGetFileExtension(oname)

    mm_pdb_path = f"og_lig0_solvent.pdb"
    ani_pdb_path = f"forward_lig0.solvent.pdb"
    MM_mol = createOEMolFromSDF(mm_pdb_path, 0)
    ANI_mol = createOEMolFromSDF(ani_pdb_path, 0)

    mol = MM_mol
    mol2 = ANI_mol

    for m in [mol, mol2]:
        oechem.OESuppressHydrogens(m)
        oechem.OECanonicalOrderAtoms(m)
        oechem.OECanonicalOrderBonds(m)
        m.Sweep()

    refmol = None

    stag = "dihedral_histogram"
    itag = oechem.OEGetTag(stag)

    nrbins = 20

    print(mol.NumConfs())
    print(mol2.NumConfs())

    get_dihedrals(mol, itag)
    set_dihedral_histograms(mol, itag, nrbins)

    get_dihedrals(mol2, itag)
    #set_weighted_dihedral_histograms(mol2, itag, work, nrbins)
    set_dihedral_histograms(mol2, itag, nrbins)

    width, height = 800, 400
    image = oedepict.OEImage(width, height)

    moffset = oedepict.OE2DPoint(0, 0)
    mframe = oedepict.OEImageFrame(image, width * 0.70, height, moffset)
    doffset = oedepict.OE2DPoint(mframe.GetWidth(), height * 0.30)
    dframe = oedepict.OEImageFrame(image, width * 0.30, height * 0.5, doffset)

    flexibility = True
    colorg = get_color_gradient(nrbins, flexibility)

    opts = oedepict.OE2DMolDisplayOptions(mframe.GetWidth(),
                                          mframe.GetHeight(),
                                          oedepict.OEScale_AutoScale)

    depict_dihedrals(mframe, dframe, mol, mol2, refmol, opts, itag, nrbins,
                     colorg)

    if flexibility:
        lopts = oedepict.OELegendLayoutOptions(
            oedepict.OELegendLayoutStyle_HorizontalTopLeft,
            oedepict.OELegendColorStyle_LightBlue,
            oedepict.OELegendInteractiveStyle_Hover)
        lopts.SetButtonWidthScale(1.2)
        lopts.SetButtonHeightScale(1.2)
        lopts.SetMargin(oedepict.OEMargin_Right, 40.0)
        lopts.SetMargin(oedepict.OEMargin_Bottom, 80.0)

        legend = oedepict.OELegendLayout(image, "Legend", lopts)

        legend_area = legend.GetLegendArea()
        draw_color_gradient(legend_area, colorg)

        oedepict.OEDrawLegendLayout(legend)

    iconscale = 0.5
    oedepict.OEAddInteractiveIcon(image, oedepict.OEIconLocation_TopRight,
                                  iconscale)
    oedepict.OEDrawCurvedBorder(image, oedepict.OELightGreyPen, 10.0)

    oedepict.OEWriteImage(ofs, ext, image)

    return 0
Ejemplo n.º 22
0
def main(argv=[__name__]):

    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 600.0)
    oedepict.OEConfigureImageHeight(itf, 600.0)
    oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
    oechem.OEConfigureSplitMolComplexOptions(itf, oechem.OESplitMolComplexSetup_LigName)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-complex")
    oname = itf.GetString("-out")

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    complexmol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, complexmol):
        oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)

    if not oechem.OEHasResidues(complexmol):
        oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)

    # Separate ligand and protein

    sopts = oechem.OESplitMolComplexOptions()
    oechem.OESetupSplitMolComplexOptions(sopts, itf)

    ligand = oechem.OEGraphMol()
    protein = oechem.OEGraphMol()
    water = oechem.OEGraphMol()
    other = oechem.OEGraphMol()

    oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)

    if ligand.NumAtoms() == 0:
        oechem.OEThrow.Fatal("Cannot separate complex!")

    # Calculate average BFactor of the whole complex

    avgbfactor = GetAverageBFactor(complexmol)

    # Calculate minimum and maximum BFactor of the ligand and its environment

    minbfactor, maxbfactor = GetMinAndMaxBFactor(ligand, protein)

    # Attach to each ligand atom the average BFactor of the nearby protein atoms

    stag = "avg residue BFfactor"
    itag = oechem.OEGetTag(stag)
    SetAverageBFactorOfNearbyProteinAtoms(ligand, protein, itag)

    oechem.OEThrow.Info("Average BFactor of the complex = %+.3f" % avgbfactor)
    oechem.OEThrow.Info("Minimum BFactor of the ligand and its environment = %+.3f" % minbfactor)
    oechem.OEThrow.Info("Maximum BFactor of the ligand and its environment = %+.3f" % maxbfactor)

    # Create image

    imagewidth, imageheight = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
    image = oedepict.OEImage(imagewidth, imageheight)

    mframe = oedepict.OEImageFrame(image, imagewidth,
                                   imageheight * 0.90, oedepict.OE2DPoint(0.0, 0.0))
    lframe = oedepict.OEImageFrame(image, imagewidth, imageheight * 0.10,
                                   oedepict.OE2DPoint(0.0, imageheight * 0.90))

    opts = oedepict.OE2DMolDisplayOptions(mframe.GetWidth(), mframe.GetHeight(),
                                          oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)

    # Create BFactor color gradient

    colorg = oechem.OELinearColorGradient()
    colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEDarkBlue))
    colorg.AddStop(oechem.OEColorStop(10.0, oechem.OELightBlue))
    colorg.AddStop(oechem.OEColorStop(25.0, oechem.OEYellowTint))
    colorg.AddStop(oechem.OEColorStop(50.0, oechem.OERed))
    colorg.AddStop(oechem.OEColorStop(100.0, oechem.OEDarkRose))

    # Prepare ligand for depiction

    oegrapheme.OEPrepareDepictionFrom3D(ligand)
    arcfxn = BFactorArcFxn(colorg, itag)
    for atom in ligand.GetAtoms():
        oegrapheme.OESetSurfaceArcFxn(ligand, atom, arcfxn)
    opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(ligand, opts))

    # Render ligand and visualize BFactor

    disp = oedepict.OE2DMolDisplay(ligand, opts)
    colorbfactor = ColorLigandAtomByBFactor(colorg)
    oegrapheme.OEAddGlyph(disp, colorbfactor, oechem.OEIsTrueAtom())
    oegrapheme.OEDraw2DSurface(disp)
    oedepict.OERenderMolecule(mframe, disp)

    # Draw color gradient

    opts = oegrapheme.OEColorGradientDisplayOptions()
    opts.SetColorStopPrecision(1)
    opts.AddMarkedValue(avgbfactor)
    opts.SetBoxRange(minbfactor, maxbfactor)

    oegrapheme.OEDrawColorGradient(lframe, colorg, opts)

    oedepict.OEWriteImage(oname, image)

    return 0
def main(argv=[__name__]):
    if len(argv) < 3:
        oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])

    dbname = argv[1]
    # read in database
    ifs = oechem.oemolistream()
    if not ifs.open(dbname):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    print("Opening database file %s ..." % dbname)
    timer = oechem.OEWallTimer()
    dbase = oefastrocs.OEShapeDatabase()
    moldb = oechem.OEMolDatabase()
    if not moldb.Open(ifs):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    dots = oechem.OEThreadedDots(10000, 200, "conformers")
    if not dbase.Open(moldb, dots):
        oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" %
                             dbname)

    dots.Total()
    print("%s seconds to load database" % timer.Elapsed())

    opts = oefastrocs.OEShapeDatabaseOptions()
    opts.SetSimFunc(oefastrocs.OEShapeSimFuncType_Tversky)
    numHits = moldb.NumMols()
    opts.SetLimit(numHits)

    for qfname in argv[2:]:
        # read in query
        qfs = oechem.oemolistream()
        if not qfs.open(qfname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % argv[1])

        query = oechem.OEGraphMol()
        if not oechem.OEReadMolecule(qfs, query):
            oechem.OEThrow.Fatal("Unable to read query from '%s'" % argv[1])

        ext = oechem.OEGetFileExtension(qfname)
        base = qfname[:-(len(ext) + 1)]

        # write out everthing to a similary named file
        ofs = oechem.oemolostream()
        ofname = base + "_results." + ext
        if not ofs.open(ofname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])

        print("Searching for %s" % qfname)
        for score in dbase.GetSortedScores(query, opts):
            dbmol = oechem.OEMol()
            molidx = score.GetMolIdx()
            if not moldb.GetMolecule(dbmol, molidx):
                print("Unable to retrieve molecule '%u' from the database" %
                      molidx)
                continue
            mol = oechem.OEGraphMol(
                dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))

            oechem.OESetSDData(mol, "ShapeTversky",
                               "%.4f" % score.GetShapeTversky())
            oechem.OESetSDData(mol, "ColorTversky",
                               "%.4f" % score.GetColorTversky())
            oechem.OESetSDData(mol, "TverskyCombo",
                               "%.4f" % score.GetTverskyCombo())
            score.Transform(mol)

            oechem.OEWriteMolecule(ofs, mol)
        print("Wrote results to %s" % ofname)
    return 0
Ejemplo n.º 24
0
def main(argv=[__name__]):
    if len(argv) < 3:
        oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
        return 0

    # check system
    if not oefastrocs.OEFastROCSIsGPUReady():
        oechem.OEThrow.Info("No supported GPU available!")
        return 0

    # read in database
    dbname = argv[1]
    print("Opening database file %s ..." % dbname)
    dbase = oefastrocs.OEShapeDatabase()
    moldb = oechem.OEMolDatabase()

    if not moldb.Open(dbname):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    dots = oechem.OEThreadedDots(10000, 200, "conformers")
    if not dbase.Open(moldb, dots):
        oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" %
                             dbname)

    # customize search options
    opts = oefastrocs.OEShapeDatabaseOptions()

    opts.SetLimit(5)

    for qfname in argv[2:]:
        # read in query
        qfs = oechem.oemolistream()
        if not qfs.open(qfname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)

        query = oechem.OEGraphMol()
        if not oechem.OEReadMolecule(qfs, query):
            oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)

        ext = oechem.OEGetFileExtension(qfname)
        base = qfname[:-(len(ext) + 1)]

        # write out everthing to a similary named file
        ofs = oechem.oemolostream()
        ofname = base + "_results." + ext
        if not ofs.open(ofname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
        oechem.OEWriteMolecule(ofs, query)

        print("Searching for %s" % qfname)
        for score in dbase.GetSortedScores(query, opts):
            print("Score for mol %u(conf %u) %f shape %f color" %
                  (score.GetMolIdx(), score.GetConfIdx(),
                   score.GetShapeTanimoto(), score.GetColorTanimoto()))
            dbmol = oechem.OEMol()
            molidx = score.GetMolIdx()
            if not moldb.GetMolecule(dbmol, molidx):
                print("Unable to retrieve molecule '%u' from the database" %
                      molidx)
                continue

            mol = oechem.OEGraphMol(
                dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
            oechem.OESetSDData(mol, "ShapeTanimoto",
                               "%.4f" % score.GetShapeTanimoto())
            oechem.OESetSDData(mol, "ColorTanimoto",
                               "%.4f" % score.GetColorTanimoto())
            oechem.OESetSDData(mol, "TanimotoCombo",
                               "%.4f" % score.GetTanimotoCombo())
            score.Transform(mol)

            oechem.OEWriteMolecule(ofs, mol)
        print("Wrote results to %s" % ofname)

    return 0
Ejemplo n.º 25
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureReportOptions(itf)
    oedepict.OEConfigure2DMolDisplayOptions(itf)
    oedepict.OEConfigureHighlightParams(itf)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    qname = itf.GetString("-query")
    tname = itf.GetString("-target")
    oname = itf.GetString("-out")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredMultiPageImageFile(ext):
        oechem.OEThrow.Fatal("Unknown multipage image type!")

    qfile = oechem.oemolistream()
    if not qfile.open(qname):
        oechem.OEThrow.Fatal("Cannot open mdl query file!")
    if qfile.GetFormat() != oechem.OEFormat_MDL and qfile.GetFormat(
    ) != oechem.OEFormat_SDF:
        oechem.OEThrow.Fatal("Query file has to be an MDL file!")

    ifs = oechem.oemolistream()
    if not ifs.open(tname):
        oechem.OEThrow.Fatal("Cannot open target input file!")

    depictquery = oechem.OEGraphMol()
    if not oechem.OEReadMDLQueryFile(qfile, depictquery):
        oechem.OEThrow.Fatal("Cannot read query molecule!")
    oedepict.OEPrepareDepiction(depictquery)
    queryopts = oechem.OEMDLQueryOpts_Default | oechem.OEMDLQueryOpts_SuppressExplicitH
    qmol = oechem.OEQMol()
    oechem.OEBuildMDLQueryExpressions(qmol, depictquery, queryopts)

    ss = oechem.OESubSearch()
    if not ss.Init(qmol):
        oechem.OEThrow.Fatal("Cannot initialize substructure search!")

    hstyle = oedepict.OEGetHighlightStyle(itf)
    hcolor = oedepict.OEGetHighlightColor(itf)
    align = itf.GetBool("-align")

    ropts = oedepict.OEReportOptions()
    oedepict.OESetupReportOptions(ropts, itf)
    ropts.SetHeaderHeight(140.0)
    report = oedepict.OEReport(ropts)

    dopts = oedepict.OE2DMolDisplayOptions()
    oedepict.OESetup2DMolDisplayOptions(dopts, itf)
    cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
    dopts.SetDimensions(cellwidth, cellheight, oedepict.OEScale_AutoScale)

    unique = True
    for mol in ifs.GetOEGraphMols():

        oechem.OEPrepareSearch(mol, ss)

        miter = ss.Match(mol, unique)
        if not miter.IsValid():
            continue  # no match

        alignres = oedepict.OEAlignmentResult(miter.Target())
        if align:
            alignres = oedepict.OEPrepareAlignedDepiction(mol, ss)
        else:
            oedepict.OEPrepareDepiction(mol)

        cell = report.NewCell()
        disp = oedepict.OE2DMolDisplay(mol, dopts)
        if alignres.IsValid():
            oedepict.OEAddHighlighting(disp, hcolor, hstyle, alignres)
        oedepict.OERenderMolecule(cell, disp)
        oedepict.OEDrawBorder(cell, oedepict.OELightGreyPen)

    # render query structure in each header
    headwidth, headheight = report.GetHeaderWidth(), report.GetHeaderHeight()
    dopts.SetDimensions(headwidth, headheight, oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(depictquery, dopts)
    for header in report.GetHeaders():
        oedepict.OERenderMolecule(header, disp)
        oedepict.OEDrawBorder(header, oedepict.OELightGreyPen)

    oedepict.OEWriteReport(oname, report)

    return 0
Ejemplo n.º 26
0
def main(argv=[__name__]):

    parser = argparse.ArgumentParser()

    # positional arguments retaining backward compatibility
    parser.add_argument(
        'database',
        help='File containing the database molecules to be search \
                              (format not restricted to *.oeb).')
    parser.add_argument(
        'query',
        default=[],
        nargs='+',
        help='File containing the query molecule(s) to be search \
                              (format not restricted to *.oeb).')
    parser.add_argument(
        '--nHits',
        dest='nHits',
        type=int,
        default=100,
        help='Number of hits to return (default = number of database mols).')
    parser.add_argument('--cutoff',
                        dest='cutoff',
                        type=float,
                        default=argparse.SUPPRESS,
                        help='Specify a cutoff criteria for scores.')
    parser.add_argument(
        '--tversky',
        dest='tversky',
        action='store_true',
        default=argparse.SUPPRESS,
        help='Switch to Tversky similarity scoring (default = Tanimoto).')

    args = parser.parse_args()

    dbname = args.database

    if not oefastrocs.OEFastROCSIsGPUReady():
        oechem.OEThrow.Info("No supported GPU available!")
        return 0

    # set options
    opts = oefastrocs.OEShapeDatabaseOptions()
    opts.SetLimit(args.nHits)
    print("Number of hits set to %u" % opts.GetLimit())
    if hasattr(args, 'cutoff') is not False:
        opts.SetCutoff(args.cutoff)
        print("Cutoff set to %f" % args.cutoff)
    if hasattr(args, 'tversky') is not False:
        opts.SetSimFunc(args.tversky)
        print("Tversky similarity scoring set.")

    # read in database
    ifs = oechem.oemolistream()
    if not ifs.open(dbname):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    print("\nOpening database file %s ..." % dbname)
    timer = oechem.OEWallTimer()
    dbase = oefastrocs.OEShapeDatabase()
    moldb = oechem.OEMolDatabase()
    if not moldb.Open(ifs):
        oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)

    dots = oechem.OEThreadedDots(10000, 200, "conformers")
    if not dbase.Open(moldb, dots):
        oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" %
                             dbname)

    dots.Total()
    print("%f seconds to load database\n" % timer.Elapsed())

    for qfname in args.query:

        # read in query
        qfs = oechem.oemolistream()
        if not qfs.open(qfname):
            oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)

        mcmol = oechem.OEMol()
        if not oechem.OEReadMolecule(qfs, mcmol):
            oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
        qfs.rewind()

        ext = oechem.OEGetFileExtension(qfname)

        qmolidx = 0
        while oechem.OEReadMolecule(qfs, mcmol):

            # write out to file name based on molecule title
            ofs = oechem.oemolostream()
            moltitle = mcmol.GetTitle()
            if len(moltitle) == 0:
                moltitle = str(qmolidx)
            ofname = moltitle + "_results." + ext
            if not ofs.open(ofname):
                oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])

            print("Searching for %s of %s (%s conformers)" %
                  (moltitle, qfname, mcmol.NumConfs()))

            qconfidx = 0
            for conf in mcmol.GetConfs():

                for score in dbase.GetSortedScores(conf, opts):

                    dbmol = oechem.OEMol()
                    dbmolidx = score.GetMolIdx()
                    if not moldb.GetMolecule(dbmol, dbmolidx):
                        print(
                            "Unable to retrieve molecule '%u' from the database"
                            % dbmolidx)
                        continue

                    mol = oechem.OEGraphMol(
                        dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))

                    oechem.OESetSDData(mol, "QueryConfidx", "%s" % qconfidx)
                    oechem.OESetSDData(mol, "ShapeTanimoto",
                                       "%.4f" % score.GetShapeTanimoto())
                    oechem.OESetSDData(mol, "ColorTanimoto",
                                       "%.4f" % score.GetColorTanimoto())
                    oechem.OESetSDData(mol, "TanimotoCombo",
                                       "%.4f" % score.GetTanimotoCombo())
                    score.Transform(mol)

                    oechem.OEWriteMolecule(ofs, mol)

                qconfidx += 1

            print("%s conformers processed" % qconfidx)
            print("Wrote results to %s\n" % ofname)

        qmolidx += 1
    return 0
Ejemplo n.º 27
0
# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.
#
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of OpenEye products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. OpenEye claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable OpenEye offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be
# liable for any damages or liability in connection with the Sample Code
# or its use.

from openeye import oechem
from openeye import oedepict
import sys

if len(sys.argv) != 2:
    oechem.OEThrow.Usage("%s <imagefile>" % sys.argv[0])

# @ <SNIPPET-OEIsRegisteredImageFile>
filename = sys.argv[1]
ext = oechem.OEGetFileExtension(filename)
if not oedepict.OEIsRegisteredImageFile(ext):
    oechem.OEThrow.Fatal("Unknown image type!")
# @ </SNIPPET-OEIsRegisteredImageFile>