Esempio n. 1
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
Esempio n. 2
0
    def write(self, record, port):

        if not record.has_value(Fields.cycle_id):
            raise ValueError("Missing the current cycle ID")

        cycle_id = record.get_value(Fields.cycle_id)

        if not record.has_value(Fields.prefix_name_field):
            raise ValueError("System prefix name is missing")

        prefix_name = record.get_value(Fields.prefix_name_field)

        name_dataset = prefix_name + '_' + "Recovery_Dataset_" + str(cycle_id -
                                                                     1)

        if in_orion():  # Output to database
            stream = Dataset.create(APISession, name_dataset)
            job_id = environ.get('ORION_JOB_ID')
            APISession.tag_resource(stream, "Job " + str(job_id))
            APISession.tag_resource(stream, "Gmx_Dataset")
            stream.write(record)
            stream.finalize()
        else:
            name_dataset += '.oedb'
            stream = oechem.oeofstream(name_dataset)
            OEWriteRecord(stream, record, fmt="binary")
            stream.close()
Esempio n. 3
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
Esempio n. 4
0
def create_logger(outputs: OutputPaths) -> oechem.oeofstream:
    fname = outputs.protein_pdb.parent.joinpath(
        f"{outputs.protein_pdb.stem}.log")
    errfs = oechem.oeofstream(
        str(fname))  # create a stream that writes internally to a stream
    oechem.OEThrow.SetOutputStream(errfs)
    oechem.OEThrow.Clear()
    oechem.OEThrow.SetLevel(
        oechem.OEErrorLevel_Verbose)  # capture verbose error output
    return errfs
Esempio n. 5
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
Esempio n. 6
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <infile> <csvfile>" % argv[0])

    ifs = oechem.oemolistream()
    if not ifs.open(argv[1]):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
    if ifs.GetFormat() not in [oechem.OEFormat_SDF, oechem.OEFormat_OEB]:
        oechem.OEThrow.Fatal("Only works for sdf or oeb input files")

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

    SDF2CSV(ifs, csv)
Esempio n. 7
0
def main(argv=[__name__]):
    if not (2 <= len(argv) <= 3):
        oechem.OEThrow.Usage("%s <infile> [<outfile>]" % argv[0])

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

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

    GenerateList(ifs, ofs)
Esempio n. 8
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
Esempio n. 9
0
def align2d(file1, file2):

    atomexpr = oechem.OEExprOpts_AtomicNumber | oechem.OEExprOpts_RingMember
    bondexpr = oechem.OEExprOpts_RingMember

    ifs1 = oechem.oemolistream(file1)
    ifs2 = oechem.oemolistream(file2)
    ifs1.SetConfTest(oechem.OEAbsCanonicalConfTest())
    ifs2.SetConfTest(oechem.OEAbsCanonicalConfTest())

    popts, dopts, report = prep_pdf_writer()

    for mol1, mol2 in zip(ifs1.GetOEMols(), ifs2.GetOEMols()):
        oechem.OESuppressHydrogens(mol1)
        oechem.OESuppressHydrogens(mol2)
        oechem.OEGenerate2DCoordinates(mol2)
        ss = oechem.OESubSearch(mol2, atomexpr, bondexpr)

        oechem.OEPrepareSearch(mol1, ss)
        alignres = oedepict.OEPrepareAlignedDepiction(mol1, ss)

        if not alignres.IsValid():
            oechem.OEThrow.Error(
                "Substructure is not found in input molecule!")

        cell1 = report.NewCell()
        cell2 = report.NewCell()
        oedepict.OEPrepareDepiction(mol1, popts)
        oedepict.OEPrepareDepiction(mol2, popts)
        disp1 = oedepict.OE2DMolDisplay(mol1, dopts)
        disp2 = oedepict.OE2DMolDisplay(mol2, dopts)
        oedepict.OERenderMolecule(cell1, disp1)
        oedepict.OERenderMolecule(cell2, disp2)

    ofs = oechem.oeofstream()
    if not ofs.open('output.pdf'):
        oechem.OEThrow.Fatal("Cannot open output file!")
    oedepict.OEWriteReport(ofs, "pdf", report)
Esempio n. 10
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
Esempio n. 11
0
#!/usr/bin/env python
# (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

# @ <SNIPPET-OEThrowFile>
fname = "log.txt"
errfs = oechem.oeofstream(fname)

if not errfs:
    oechem.OEThrow.Fatal("Unable to create %s" % fname)
oechem.OEThrow.SetOutputStream(errfs)
oechem.OEThrow.Warning("Sending warning to 'log.txt' file")
# @ </SNIPPET-OEThrowFile>
Esempio n. 12
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
    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)

    return mol


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

receptor = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])

asite = oechem.OEInteractionHintContainer(receptor, ligand)
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)

# @ <SNIPPET-OERENDERACTIVESITE-STREAM-ADISP>
# initializing asite oechem.OEInteractionHintContainer(receptor, ligand) object

opts = oegrapheme.OE2DActiveSiteDisplayOptions(800.0, 600.0)
opts.SetRenderInteractiveLegend(True)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)

ofs = oechem.oeofstream("OERenderActiveSite-stream-adisp.svg")
oegrapheme.OERenderActiveSite(ofs, "svg", adisp)
# @ </SNIPPET-OERENDERACTIVESITE-STREAM-ADISP>
ofs = oechem.oeofstream("OERenderActiveSite-stream-adisp.pdf")
oegrapheme.OERenderActiveSite(ofs, "pdf", adisp)
Esempio 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
Esempio n. 15
0
def render_atom_mapping(filename, molecule1, molecule2, new_to_old_atom_map, width=1200, height=1200):
    """
    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

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

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

    old_atoms_1 = [atom for atom in molecule1.GetAtoms()]
    old_atoms_2 = [atom for atom in molecule2.GetAtoms()]

    # 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)

    # Label mapped atoms
    index =1
    for (index2, index1) in new_to_old_atom_map.items():
        new_atoms_1[index1].SetMapIdx(index)
        new_atoms_2[index2].SetMapIdx(index)
        index += 1
    # Set up image options
    from openeye import oedepict
    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)

    colors = [c for c in oechem.OEGetLightColors()]
    highlightstyle = oedepict.OEHighlightStyle_BallAndStick
    #common_atoms_and_bonds = oechem.OEAtomBondSet(common_atoms)
    oedepict.OERenderMolecule(ofs, ext, rdisp)
    ofs.close()
Esempio 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
Esempio n. 17
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
Esempio n. 18
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()
Esempio n. 19
0
def main(argv=[__name__]):
    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, Interface)
    OEAddParameterColors(itf, "-atom_contribution_positive_color")
    OEAddParameterColors(itf, "-atom_contribution_negative_color")
    OEAddParameterColors(itf, "-classification_colors")
    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    # Figure out output file name
    outFile = OEGetFilename(itf, "-molecule_file")
    reportFile = OEGetFilename(itf, "-report_file")
    failTrainFile = OEGetFilename(itf, "-training_fail_file")
    failKrigeFile = OEGetFilename(itf, "-prediction_fail_file")
    settingsFile = OEGetFilename(itf, "-settings_file")

    # Write the settings file and splash to screen
    oechem.OEWriteSettings(itf, oechem.oeout, False)
    ofs = oechem.oeofstream(settingsFile)
    oechem.OEWriteSettings(itf, ofs, True)
    ofs.close()

    # Setup report options
    rOpts = oestats.OEKrigeReportOptions()
    if itf.HasString("-report_title"):
        rOpts.SetTitle(itf.GetString("-report_title"))
    if itf.HasString("-response_name"):
        rOpts.SetResponseName(itf.GetString("-response_name"))
        responseName = itf.GetString("-response_name")
    else:
        rOpts.SetResponseName(itf.GetString("-response_tag"))
        responseName = itf.GetString("-response_tag")
    if itf.HasString("-atom_contribution_negative_color"):
        color = OETextToColor(
            itf.GetString("-atom_contribution_negative_color"))
        rOpts.SetContributionNegativeColor(color)
    if itf.HasString("-atom_contribution_positive_color"):
        color = OETextToColor(
            itf.GetString("-atom_contribution_positive_color"))
        rOpts.SetContributionPositiveColor(color)
    iExtra = 0
    while itf.HasString("-report_tagged_data", iExtra):
        rOpts.PushSDProperty(itf.GetString("-report_tagged_data", iExtra))
        iExtra += 1
    iClass = 0
    while itf.HasDouble("-classification_boundries", iClass):
        boundry = itf.GetDouble("-classification_boundries", iClass)
        if itf.GetBool("-krige_log"):
            boundry = log10(boundry)
        rOpts.PushClassificationBoundry(boundry)
        iClass += 1
    iClass = 0
    while itf.HasString("-classification_colors", iClass):
        color = OETextToColor(itf.GetString("-classification_colors", iClass))
        rOpts.PushClassificationColor(color)
        iClass += 1
    if itf.GetBool("-hide_krige_details"):
        rOpts.SetShowKrigeDetails(False)
    else:
        rOpts.SetShowKrigeDetails(True)
    rOpts.SetUnlog(itf.GetBool("-krige_log"))
    rOpts.SetShowConfidence(itf.GetBool("-show_response_confidence"))
    rOpts.SetResponseSignificantFigures(
        itf.GetUnsignedInt("-report_significant_figures"))
    if itf.HasString("-atom_contribution_positive_label"):
        rOpts.SetContributionPositiveLabel(
            itf.GetString("-atom_contribution_positive_label"))
    if itf.HasString("-atom_contribution_negative_label"):
        rOpts.SetContributionNegativeLabel(
            itf.GetString("-atom_contribution_negative_label"))
    if itf.HasDouble("-atom_contribution_baseline_response"):
        baseline = itf.GetDouble("-atom_contribution_baseline_response")
        if itf.GetBool("-krige_log"):
            baseline = log10(baseline)
            rOpts.SetContributionBaseline(baseline)

    # Figure out the trend properties for universal kriging if we have them
    universalProps = oechem.OEMolPropertyList()
    iProp = 0
    while itf.HasString("-universal_prop", iProp):
        propStr = itf.GetString("-universal_prop", iProp)
        if propStr == "mw":
            universalProps.Add(oestats.OEMolecularWeightPropertyFxn())
            rOpts.PushProperty(oestats.OEMolecularWeightPropertyFxn(),
                               "Molecular Weight")
        else:
            oechem.OEThrow.Error(
                "Unknow property (%s) passed to -universal_prop" % propStr)
        iProp += 1

    # Setup the object for getting the response from the training molecules
    responseFxn = oechem.OEMolTaggedPropertyFxn(itf.GetString("-response_tag"))
    if itf.GetBool("-krige_log"):
        responseFxn = oestats.OEMolLog10PropertyFxn(responseFxn)

    # Construct the krige
    if itf.HasUnsignedInt("-local_krige"):
        opts = oestats.OELocalKrigeOptions()
        opts.SetNumLocal(itf.GetUnsignedInt("-local_krige"))
    else:
        opts = oestats.OEGlobalKrigeOptions()

    # Set if the distance function is stereo aware
    distOpts = oestats.OEDefaultKrigeDistanceOptions()
    distOpts.SetStereoAware(not itf.GetBool("-ignore_stereo"))

    krige = oestats.OEMolKrige(distOpts, universalProps, opts)

    # Add the training molecules to the Krige
    print("Reading in training molecules")
    sw = oechem.OEStopwatch()
    failStr = None
    numTrain = 0
    numTrainFail = 0
    numTrainUnmeasured = 0
    numTrainMeasured = 0
    for trainFile in itf.GetStringList("-train"):
        imstr = oechem.oemolistream(trainFile)
        for mol in imstr.GetOEMols():
            success = False
            # measured = True
            if responseFxn.Has(mol):
                response = responseFxn.Get(mol)
                if OEIsUnmeasured(itf, response):
                    numTrainUnmeasured += 1
                    # measured = False
                    success = krige.AddUnmeasuredTraining(mol, response)
                else:
                    numTrainMeasured += 1
                    success = krige.AddTraining(mol, response)
                numTrain += 1
            if not success:
                numTrainFail += 1
                if failStr is None:
                    failStr = oechem.oemolostream(failTrainFile)
                oechem.OEWriteMolecule(failStr, mol)
            if sw.Elapsed() > 10.0:
                sw.Start()
                if numTrainFail != 0:
                    print("So far added %d training molecules, and of those \
                          %d unmeasured are unmeasured.  "
                          "%d input molecules are missing response data or \
                          universal krige properties." %
                          (numTrain, numTrainUnmeasured, numTrainFail))
                else:
                    print("So far added %d training molecules, and of those \
                          %d unmeasured are unmeasured." %
                          (numTrain, numTrainUnmeasured))
        imstr.close()
    if failStr is not None:
        failStr.close()
        print("Training failed molecules written to %s" % failTrainFile)
    if numTrainFail != 0:
        print(
            "Added %d training molecules, and of those %d unmeasured are unmeasured.  "
            "%d input molecules are missing response data or universal krige properties."
            % (numTrain, numTrainUnmeasured, numTrainFail))
    else:
        print(
            "Added %d training molecules, and of those %d unmeasured are unmeasured."
            % (numTrain, numTrainUnmeasured))

    # Train the Krige on the molecules we added
    print("Training krige model")
    if krige.Train():
        print("Training successful")
    else:
        print("Training failed, aborting")
        return

    # Krige for MW of the test molecules, and compare to actual MW
    krigeTag = "Krige(%s)" % responseName
    upperTag = "Krige(%s) 95%% confidence upper" % responseName
    lowerTag = "Krige(%s) 95%% confidence lower" % responseName

    print("Predicting %s of input molecules" % responseName)
    numKrige = 0
    numKrigeFail = 0
    outstr = oechem.oemolostream(outFile)
    multi = oedepict.OEMultiPageImageFile(oedepict.OEPageOrientation_Landscape,
                                          oedepict.OEPageSize_US_Letter)
    failStr = None
    sw.Start()
    for molFile in itf.GetStringList("-in"):
        imstr = oechem.oemolistream(molFile)
        for mol in imstr.GetOEMols():
            result = krige.GetResult(mol)
            success = True
            if result.Valid():
                response = result.GetResponse()
                conf95 = 1.96 * sqrt(result.GetVariance())
                upper95 = response + conf95
                lower95 = response - conf95
                if itf.GetBool("-krige_log"):
                    response = pow(10.0, response)
                    upper95 = pow(10.0, upper95)
                    lower95 = pow(10.0, lower95)
                oechem.OESetSDData(mol, krigeTag, str(response))
                oechem.OESetSDData(mol, upperTag, str(upper95))
                oechem.OESetSDData(mol, lowerTag, str(lower95))
                if not itf.GetBool("-no_report"):
                    oestats.OEKrigeRenderReport(multi.NewPage(), result, mol,
                                                rOpts)
                oechem.OEWriteMolecule(outstr, mol)
            else:
                success = False
            numKrige += 1
            if not success:
                numKrigeFail += 1
                failStr = oechem.oemolostream(failKrigeFile)
                oechem.OEWriteMolecule(failStr, mol)
            if sw.Elapsed() > 10.0:
                print("Kriging predicted %d molecules (%d failures) so far" %
                      (numKrige, numKrigeFail))
                sw.Start()
        imstr.close()
    outstr.close()
    if failStr is not None:
        failStr.close()
    print("Kriging predicted %d molecules (%d failures)" %
          (numKrige, numKrigeFail))

    if not itf.GetBool("-no_report"):
        print("Writing report to %s" % reportFile)
        oedepict.OEWriteMultiPageImage(reportFile, multi)
    print("Finished")

    return 0
Esempio n. 20
0
def data_trajectory_extraction(ctx, name, only):

    check_only = ['a', 'stages', 'parmed', 'protein_confs']

    for v in only:
        if v not in check_only:
            raise ValueError(
                "The only keyword value is not recognized {}. Option available: {}"
                .format(only, check_only[1:]))

    session = ctx.obj['session']

    ofs = oechem.oeofstream(name)

    for record in tqdm(ctx.obj['records']):

        new_record = OERecord(record)

        if not record.has_field(Fields.collection):
            raise ValueError(
                "No Collection field has been found in the record")

        collection_id = record.get_value(Fields.collection)

        collection = session.get_resource(ShardCollection, collection_id)

        new_stages = []

        if 'a' in only or 'stages' in only:

            mdrecord = MDDataRecord(record)

            stages = mdrecord.get_stages

            system_title = mdrecord.get_title
            sys_id = mdrecord.get_flask_id

            for stage in stages:

                stg_type = stage.get_value(Fields.stage_type)
                new_stage = OERecord(stage)

                with TemporaryDirectory() as output_directory:
                    data_fn = os.path.basename(
                        output_directory) + '_' + system_title + '_' + str(
                            sys_id) + '-' + stg_type + '.tar.gz'
                    shard_id = stage.get_value(
                        OEField("MDData_OPLMD", Types.Int))

                    shard = session.get_resource(Shard(collection=collection),
                                                 shard_id)
                    shard.download_to_file(data_fn)

                    new_stage.delete_field(OEField("MDData_OPLMD", Types.Int))
                    new_stage.set_value(Fields.mddata, data_fn)

                    if stage.has_field(OEField("Trajectory_OPLMD", Types.Int)):

                        trj_field = stage.get_field("Trajectory_OPLMD")

                        trj_meta = trj_field.get_meta()
                        md_engine = trj_meta.get_attribute(
                            Meta.Annotation.Description)

                        trj_id = stage.get_value(trj_field)
                        trj_fn = os.path.basename(
                            output_directory) + '_' + system_title + '_' + str(
                                sys_id) + '-' + stg_type + '_traj' + '.tar.gz'

                        resource = session.get_resource(File, trj_id)
                        resource.download_to_file(trj_fn)

                        trj_meta = OEFieldMeta()
                        trj_meta.set_attribute(Meta.Annotation.Description,
                                               md_engine)
                        new_trj_field = OEField(Fields.trajectory.get_name(),
                                                Fields.trajectory.get_type(),
                                                meta=trj_meta)

                        new_stage.delete_field(
                            OEField("Trajectory_OPLMD", Types.Int))
                        new_stage.set_value(new_trj_field, trj_fn)

                new_stages.append(new_stage)

            new_record.set_value(Fields.md_stages, new_stages)

        if 'a' in only or 'parmed' in only:
            if record.has_field(OEField('Structure_Parmed_OPLMD', Types.Int)):
                pmd_id = record.get_value(
                    OEField('Structure_Parmed_OPLMD', Types.Int))
                shard = session.get_resource(Shard(collection=collection),
                                             pmd_id)

                with TemporaryDirectory() as output_directory:
                    parmed_fn = os.path.join(output_directory, "parmed.pickle")

                    shard.download_to_file(parmed_fn)

                    with open(parmed_fn, 'rb') as f:
                        parm_dic = pickle.load(f)

                    pmd_structure = parmed.structure.Structure()
                    pmd_structure.__setstate__(parm_dic)

                new_record.delete_field(
                    OEField('Structure_Parmed_OPLMD', Types.Int))
                new_record.set_value(Fields.pmd_structure, pmd_structure)

        if 'a' in only or 'protein_confs' in only:
            if record.has_field(OEField('OETraj', Types.Record)):

                oetrajrec = record.get_value(OEField('OETraj', Types.Record))

                prot_conf_id = oetrajrec.get_value(
                    OEField("ProtTraj_OPLMD", Types.Int))

                shard = session.get_resource(Shard(collection=collection),
                                             prot_conf_id)

                with TemporaryDirectory() as output_directory:
                    protein_fn = os.path.join(output_directory,
                                              "prot_traj_confs.oeb")

                    shard.download_to_file(protein_fn)

                    protein_conf = oechem.OEMol()

                    with oechem.oemolistream(protein_fn) as ifs:
                        oechem.OEReadMolecule(ifs, protein_conf)

                oetrajrec.delete_field(OEField('ProtTraj_OPLMD', Types.Int))
                oetrajrec.set_value(Fields.protein_traj_confs, protein_conf)

                new_record.set_value(OEField('OETraj', Types.Record),
                                     oetrajrec)

        new_record.delete_field(Fields.collection)

        OEWriteRecord(ofs, new_record, fmt='binary')

    ofs.close()
#
# 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

mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol,
                     "c1cc(N)cc(S(=O)(=O)O)c1 3-aminobenzenesulfonic acid")
# @ <SNIPPET-OEDEPICTMOLECULE-STREAM-MOL>
oedepict.OEPrepareDepiction(mol)

ofs = oechem.oeofstream("OERenderMolecule-stream-mol.png")
oedepict.OERenderMolecule(ofs, "png", mol)
# @ </SNIPPET-OEDEPICTMOLECULE-STREAM-MOL>
ofs = oechem.oeofstream("OERenderMolecule-stream-mol.pdf")
oedepict.OERenderMolecule(ofs, "pdf", mol)