Esempio n. 1
0
def write_guest_molecules(old_molecule: oechem.OEMol, new_molecule: oechem.OEMol, filepath: str):
    """
    Write out a file containing the guest molecules with the "old molecule" first.

    Parameters
    ----------
    old_molecule : oechem.OEMol
        The molecule to be written first. It should have coordinates placing it within the guest
    new_molecule : oechem.OEMol
        The molecule to be written next. It does not need to have coordinates, as these will be generated
    filepath : str
        The path to the file that is being written
    """
    ostream = oechem.oemolostream()
    ostream.open(filepath)

    # set molecule names to avoid template name collision:
    old_molecule.SetTitle("oldmol")
    new_molecule.SetTitle("newmol")

    # set tripos atom names
    oechem.OETriposAtomNames(old_molecule)
    oechem.OETriposAtomNames(new_molecule)

    # write the molecules in order:
    oechem.OEWriteMolecule(ostream, old_molecule)
    oechem.OEWriteMolecule(ostream, new_molecule)

    ostream.close()
Esempio n. 2
0
def main(argv=[__name__]):
    ifs = oechem.oemolistream()
    ofs = oechem.oemolostream()
    path = "Docking_Results/*.oeb"  #Convert ligand poses from oeb to pdb format
    files = glob.glob(path)
    for i in files:
        centroid_number = i[-5:-4]
        if ifs.open(i):
            if ofs.open("ligand_poses_pdbs/" + "pose" + str(centroid_number) +
                        ".pdb"):
                for mol in ifs.GetOEGraphMols():
                    oechem.OEWriteMolecule(ofs, mol)
            else:
                oechem.OEThrow.Fatal("Unable to create output")
        else:
            oechem.OEThrow.Fatal("Unable to open input")
    path2 = "receptor_oebs/*.oeb"  #Convert receptors from oeb to pdb format
    files = glob.glob(path2)
    for j in files:
        centroid_number = j[-5:-4]
        if ifs.open(j):
            if ofs.open("receptor_pdbs_converted_from_oebs/" + "receptor" +
                        str(centroid_number) + ".pdb"):
                for mol in ifs.GetOEGraphMols():
                    oechem.OEWriteMolecule(ofs, mol)
            else:
                oechem.OEThrow.Fatal("Unable to create output")
        else:
            oechem.OEThrow.Fatal("Unable to open input")
    return 0
def write_split_molecules_in_folder(mol_list, folder_name):
    ofs = oechem.oemolostream()
    if not os.path.isdir(folder_name):
        os.mkdir(folder_name)
    xyz_folder = os.path.join(folder_name, 'xyz')
    if not os.path.isdir(xyz_folder):
        os.mkdir(xyz_folder)
    mol2_folder = os.path.join(folder_name, 'mol2')
    if not os.path.isdir(mol2_folder):
        os.mkdir(mol2_folder)
    for idx, mol in enumerate(mol_list, 1):
        formula = oechem.OEMolecularFormula(mol)
        #filename = f'{idx:03d}_{formula}.mol2'
        filename = os.path.join(folder_name, f'{idx:03d}_{formula}.sdf')
        print(f'Writing {filename}')
        ofs.open(filename)
        oechem.OEWriteMolecule(ofs, mol)
        ofs.close()
        # write xyz files
        xyzfile = os.path.join(xyz_folder, f'{idx:03d}_{formula}.xyz')
        ofs.open(xyzfile)
        oechem.OEWriteMolecule(ofs, mol)
        ofs.close()
        # write mol2 files
        mol2file = os.path.join(mol2_folder, f'{idx:03d}_{formula}.mol2')
        ofs.open(mol2file)
        oechem.OEWriteMolecule(ofs, mol)
        ofs.close()
Esempio n. 4
0
def GenerateSzmapProbes(oms, cumulativeProb, lig, prot):
    """
    generate multiconf probes and data-rich points at ligand coords
    @rtype : None
    @param oms: output mol stream for points and probes
    @param cumulativeProb: cumulative probability for cutoff of point set
    @param lig: mol defining coordinates for szmap calcs
    @param prot: context mol for szmap calcs (must have charges and radii)
    """

    coord = oechem.OEFloatArray(3)

    sz = oeszmap.OESzmapEngine(prot)
    rslt = oeszmap.OESzmapResults()

    points = oechem.OEGraphMol()
    points.SetTitle("points %s" % lig.GetTitle())

    probes = oechem.OEMol()

    for i, atom in enumerate(lig.GetAtoms()):
        lig.GetCoords(atom, coord)

        if not oeszmap.OEIsClashing(sz, coord):
            oeszmap.OECalcSzmapResults(rslt, sz, coord)

            rslt.PlaceNewAtom(points)

            clear = False
            rslt.PlaceProbeSet(probes, cumulativeProb, clear)

    oechem.OEWriteMolecule(oms, points)
    oechem.OEWriteMolecule(oms, probes)
Esempio n. 5
0
def prepare_receptor(complex_pdb_filename, prefix):
    # Read the receptor and identify design units
    from openeye import oespruce, oechem
    complex = read_pdb_file(complex_pdb_filename)
    print('Identifying design units...')
    design_units = list(oespruce.OEMakeDesignUnits(complex))
    for i, design_unit in enumerate(design_units):
        filename = f'DU_{i}.oedu'
        print(f'Writing design unit {i} to {filename}')
        oechem.OEWriteDesignUnit(filename, design_unit)
    if len(design_units) > 1:
        print('More than one design unit found---using first one')
        design_unit = design_units[0]

    # Prepare the receptor
    print('Preparing receptor...')
    from openeye import oedocking
    protein = oechem.OEGraphMol()
    design_unit.GetProtein(protein)
    ligand = oechem.OEGraphMol()
    design_unit.GetLigand(ligand)
    receptor = oechem.OEGraphMol()
    oedocking.OEMakeReceptor(receptor, protein, ligand)
    oedocking.OEWriteReceptorFile(receptor, f'{prefix}-receptor.oeb.gz')

    with oechem.oemolostream(f'{prefix}-protein.pdb') as ofs:
        oechem.OEWriteMolecule(ofs, protein)
    with oechem.oemolostream(f'{prefix}-ligand.mol2') as ofs:
        oechem.OEWriteMolecule(ofs, ligand)
    with oechem.oemolostream(f'{prefix}-ligand.pdb') as ofs:
        oechem.OEWriteMolecule(ofs, ligand)
    with oechem.oemolostream(f'{prefix}-ligand.sdf') as ofs:
        oechem.OEWriteMolecule(ofs, ligand)
Esempio n. 6
0
def main(args):
    if len(args) != 3:
        oechem.OEThrow.Usage("%s <input> <output>" % args[0])

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

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

    mmff = oeff.OEMMFF()

    # Setup adaptor. The first (false) means not to pass ownership of mmff,
    # and the second (false) means not to exclude interactions related
    # to the subset which would be fixed for calculations.
    adaptor = oeff.OETorAdaptor(mmff, False, False)

    # Use a simple predicate for the subset of torsions to optimize
    adaptor.Set(oechem.OEIsRotor())

    mol = oechem.OEMol()
    while oechem.OEReadMolecule(ifs, mol):
        oechem.OEAddExplicitHydrogens(mol)

        # Use a simple atoms predicate for the subset, followed by setup
        if (not mmff.PrepMol(mol)) or (not adaptor.Setup(mol)):
            oechem.OEThrow.Warning("Unable to process molecule: title = '%s'" % mol.GetTitle())
            oechem.OEWriteMolecule(ofs, mol)
            continue

        vecCoords = oechem.OEDoubleArray(3*mol.GetMaxAtomIdx())
        for conf in mol.GetConfs():
            oechem.OEThrow.Info("Molecule: %s Conformer: %d" % (mol.GetTitle(), conf.GetIdx()+1))
            conf.GetCoords(vecCoords)

            # Get adaptor variables set corresponding to the coordinates
            vecX = oechem.OEDoubleArray(adaptor.NumVar())
            adaptor.GetVar(vecX, vecCoords)

            # Calculate energy using adaptor
            energy = adaptor(vecX)
            oechem.OEThrow.Info("Initial energy: %d kcal/mol" % energy)

            # Optimize the adaptor
            optimizer = oeff.OEBFGSOpt()
            energy = optimizer(adaptor, vecX, vecX)
            oechem.OEThrow.Info("Optimized energy: %d kcal/mol" % energy)

            # Get optimized coordinates corresponding to the adaptor optimized variables
            adaptor.AdaptVar(vecCoords, vecX)
            conf.SetCoords(vecCoords)

        oechem.OEWriteMolecule(ofs, mol)

    return 0
Esempio n. 7
0
def create_conformers(infile=None, outfile=None, resname=None, folder= None, name = None):

    """
    This function takes a mol1 file and runs Openeye's omega to create conformers for the molecules
    The conformers are stored in separated files, adding the number of the conformer at the end of the filename

    :param infile: Path to input file
    :param outfile: Path to output file return
    :param folder: Name of the folder for the target. If not specified. {name}-liquid is used.
    :param resname: Abbreviation of the Residue. Specified in the mol2
    :return: Number of conformers for this molecule
    """
    if folder is None and name is None:
        log.error('Please specify keyword argument folder or name')
        sys.exit(1)
    elif folder is None:
        folder = name +'-liquid'
    infilepath = os.path.join(folder, infile)
    outfilepath = os.path.join(folder, outfile)
    ifs = oechem.oemolistream()
    if not ifs.open(infilepath):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % infilepath)

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

    if not oechem.OEIs2DFormat(ofs.GetFormat()):
        oechem.OEThrow.Fatal("Invalid output file format for 2D coordinates!")

    omegaOpts = oeomega.OEOmegaOptions()
    omega = oeomega.OEOmega(omegaOpts)
    omega.SetCommentEnergy(True)
    omega.SetEnumNitrogen(True)
    omega.SetSampleHydrogens(True)
    omega.SetEnergyWindow(9.0)
    omega.SetMaxConfs(5)
    omega.SetRangeIncrement(2)
    omega.SetRMSRange([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5])
    filename = '{}-conformers'.format(resname)
    for mol in ifs.GetOEMols():
        ret_code = omega.Build(mol)
        if ret_code == oeomega.OEOmegaReturnCode_Success:
            oechem.OEWriteMolecule(ofs, mol)
            for k, conf in enumerate(mol.GetConfs()):
                ofs1 = oechem.oemolostream()
                if not ofs1.open(os.path.join(folder, filename + '_' + str(k + 1) + '.mol2')):
                    oechem.OEThrow.Fatal("Unable to open %s for writing" % os.path.join(folder, filename + '_' + str(k + 1) + '.mol2'))
                oechem.OEWriteMolecule(ofs1, conf)
                nconf = k + 1
            log.info('Created conformations for {} and saved them to {}'.format(infilepath, outfilepath))

        else:
            oechem.OEThrow.Warning("%s: %s" % (mol.GetTitle(), oeomega.OEGetOmegaError(ret_code)))

    return nconf
Esempio n. 8
0
def main(argv=[__name__]):
    if len(argv) != 5:
        oechem.OEThrow.Usage("%s <reffile> <fitfile> <out.sdf> <keepsize>" %
                             argv[0])

    reffs = oechem.oemolistream(argv[1])
    fitfs = oechem.oemolistream(argv[2])
    outfs = oechem.oemolostream(argv[3])
    keepsize = int(argv[4])

    refmol = oechem.OEMol()
    oechem.OEReadMolecule(reffs, refmol)
    print("Ref. Title:", refmol.GetTitle(), "Num Confs:", refmol.NumConfs())

    # Prepare reference molecule for calculation
    # With default options this will remove any explicit
    # hydrogens present and add color atoms
    prep = oeshape.OEOverlapPrep()
    prep.Prep(refmol)

    overlay = oeshape.OEMultiRefOverlay()
    overlay.SetupRef(refmol)

    for fitmol in fitfs.GetOEMols():
        print("Fit Title:", fitmol.GetTitle(), "Num Confs:", fitmol.NumConfs())

        prep.Prep(fitmol)
        resCount = 0

        # Sort all scores according to highest tanimoto
        scoreiter = oeshape.OEBestOverlayScoreIter()
        oeshape.OESortOverlayScores(scoreiter, overlay.Overlay(fitmol),
                                    oeshape.OEHighestTanimoto())

        for score in scoreiter:
            outmol = oechem.OEGraphMol(
                fitmol.GetConf(oechem.OEHasConfIdx(score.GetFitConfIdx())))
            score.Transform(outmol)

            oechem.OESetSDData(outmol, "RefConfIdx",
                               "%-d" % score.GetRefConfIdx())
            oechem.OESetSDData(outmol, "tanimoto combo",
                               "%-.3f" % score.GetTanimotoCombo())

            oechem.OEWriteMolecule(
                outfs,
                refmol.GetConf(oechem.OEHasConfIdx(score.GetRefConfIdx())))
            oechem.OEWriteMolecule(outfs, outmol)

            resCount += 1

            # Break at the user specified size
            if resCount == keepsize:
                break

        print(resCount, "results returned")
def write_mol2_preserving_atomnames(filename, molecules, residue_name):
    ofs = oechem.oemolostream()
    ofs.open(filename)
    ofs.SetFlavor(oechem.OEFormat_MOL2, oechem.OEOFlavor_MOL2_GeneralFFFormat)
    try:
        for molecule in molecules:
            oechem.OEWriteMolecule(ofs, molecule)
    except:
        oechem.OEWriteMolecule(ofs, molecules)
    ofs.close()
    fix_mol2_resname(filename, residue_name)
Esempio n. 10
0
def WriteResultMols(oms, lig, prot, wat, other):
    if not lig.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, lig)

    if not prot.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, prot)

    if not wat.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, wat)

    if not other.NumAtoms() == 0:
        oechem.OEWriteMolecule(oms, other)
Esempio n. 11
0
def main(args):
    if len(args) != 4:
        oechem.OEThrow.Usage("%s <protein> <ligand> <output>" % args[0])

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

    ils = oechem.oemolistream()
    if not ils.open(args[2]):
        oechem.OEThrow.Fatal("Unable to open %s for reading ligand" % args[2])

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

    # Load the protein molecule and Prepare with MMFF
    protein = oechem.OEGraphMol()
    oechem.OEReadMolecule(ips, protein)
    oechem.OEAddExplicitHydrogens(protein)
    mmff = oeff.OEMMFFAmber(protein)
    mmff.PrepMol(protein)

    mol = oechem.OEMol()
    while oechem.OEReadMolecule(ils, mol):
        oechem.OEAddExplicitHydrogens(mol)
        if (not mmff.PrepMol(mol)) or (not mmff.Setup(mol)):
            oechem.OEThrow.Warning("Unable to process molecule: title = '%s'" %
                                   mol.GetTitle())
            oechem.OEWriteMolecule(ofs, mol)
            continue

        vecCoords = oechem.OEDoubleArray(3 * mol.GetMaxAtomIdx())
        for conf in mol.GetConfs():
            oechem.OEThrow.Info("Molecule: %s Conformer: %d" %
                                (mol.GetTitle(), conf.GetIdx() + 1))
            conf.GetCoords(vecCoords)

            # Calculate energy
            energy = mmff(vecCoords)
            oechem.OEThrow.Info("Initial energy: %d kcal/mol" % energy)

            # Optimize the ligand
            optimizer = oeff.OEBFGSOpt()
            energy = optimizer(mmff, vecCoords, vecCoords)
            oechem.OEThrow.Info("Optimized energy: %d kcal/mol" % energy)
            conf.SetCoords(vecCoords)

        oechem.OEWriteMolecule(ofs, mol)
    return 0
Esempio n. 12
0
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData, argv)

    ifs = oechem.oemolistream()
    if not ifs.open(itf.GetString("-i")):
        oechem.OEThrow.Fatal("Unable to open %s for reading" %
                             itf.GetString("-i"))

    ofs = oechem.oemolostream(".ism")
    if itf.HasString("-o"):
        if not ofs.open(itf.GetString("-o")):
            oechem.OEThrow.Fatal("Unable to open %s for writing" %
                                 itf.GetString("-o"))

    minhac = float("-inf")
    if itf.HasInt("-minhac"):
        minhac = itf.GetInt("-minhac")
    maxhac = float("inf")
    if itf.HasInt("-maxhac"):
        maxhac = itf.GetInt("-maxhac")
    minwt = float("-inf")
    if itf.HasDouble("-minwt"):
        minwt = itf.GetDouble("-minwt")
    maxwt = float("inf")
    if itf.HasDouble("-maxwt"):
        maxwt = itf.GetDouble("-maxwt")

    for mol in ifs.GetOEMols():
        if not IsMoleculeInHeavyAtomCountRange(minhac, maxhac, mol):
            continue
        if not IsMoleculeInMolWtRange(minwt, maxwt, mol):
            continue

        oechem.OEWriteMolecule(ofs, mol)
Esempio n. 13
0
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData)

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

    ifs = oechem.oemolistream()

    inputFile = itf.GetString("-in")
    if not ifs.open(inputFile):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % inputFile)

    ofs = oechem.oemolostream()

    outFile = itf.GetString("-out")
    if not ofs.open(outFile):
        oechem.OEThrow.Fatal("Unable to open %s for writing" % outFile)

    chargeName = itf.GetString("-method")

    mol = oechem.OEMol()
    while oechem.OEReadMolecule(ifs, mol):
        if not AssignChargesByName(mol, chargeName):
            oechem.OEThrow.Warning("Unable to assign %s charges to mol %s" %
                                   (chargeName, mol.GetTitle()))
        oechem.OEWriteMolecule(ofs, mol)

    ifs.close()
    ofs.close()
Esempio n. 14
0
def run_select_final(args):
    """Generates an SMI file with final selected molecules from SELECT mode."""
    logging.info("STARTING SELECT-FINAL")

    directory = args["select_final_dir"]
    output_file = args["select_final_output_file"]
    ofs = oechem.oemolostream(output_file)
    n = args["select_final_n"]

    logging.info(
        f"Reading molecules in {directory}, selecting and writing to {output_file}"
    )

    for f in glob.iglob(f"{directory}/*.smi"):
        ifs = oechem.oemolistream(f)
        mols = []
        mol = oechem.OEMol()
        while oechem.OEReadMolecule(ifs, mol):
            mols.append(oechem.OEMol(mol))
        ifs.close()
        logging.debug(f"Found {len(mols)} mols in {f}")
        mols.sort(key=lambda m: m.NumAtoms())
        for m in mols[:n]:
            oechem.OEWriteMolecule(ofs, m)
    ofs.close()

    logging.info("FINISHED SELECT-FINAL")
Esempio n. 15
0
    def add_dataset(self):
        url = self.args.url + "/datasets/"
        act_mol_idx = {}
        dataset = None
        parameters = {}

        self.dataset = tempfile.NamedTemporaryFile(suffix='.oeb',
                                                   mode='wb',
                                                   delete=False)
        with oechem.oemolostream(self.dataset.name) as ofs:
            for idx, mol in enumerate(self.act_list):
                act_mol_idx[mol.GetTitle()] = idx
                oechem.OEWriteMolecule(ofs, mol)
        self.dataset.flush()

        dataset = open(self.dataset.name, 'rb')
        parameters["dataset"] = (self.dataset.name, dataset,
                                 'application/octet-stream')
        parameters["name"] = 'dataset of active molecules'

        multipart_data = MultipartEncoder(fields=parameters)

        response = requests.post(
            url,
            data=multipart_data,
            headers={"content-type": multipart_data.content_type})

        if dataset is not None:
            dataset.close()
        os.remove(self.dataset.name)

        data = response.json()
        dataset_infos = (data["id"], act_mol_idx)
        return dataset_infos
Esempio n. 16
0
def FromMol(mol, isomer=True, num_enantiomers=-1):
    """
    Generates a set of conformers as an OEMol object
    Inputs:
        mol is an OEMol
        isomers is a boolean controling whether or not the various diasteriomers of a molecule are created
        num_enantiomers is the allowable number of enantiomers. For all, set to -1
    """
    omegaOpts = oeomega.OEOmegaOptions()
    omegaOpts.SetMaxConfs(199)
    omega = oeomega.OEOmega(omegaOpts)
    out_conf = []
    ofs = oechem.oemolostream("test.sdf")
    if not isomer:
        ret_code = omega.Build(mol)
        if ret_code == oeomega.OEOmegaReturnCode_Success:
            out_conf.append(mol)
        else:
            oechem.OEThrow.Warning("%s: %s" % (mol.GetTitle(), oeomega.OEGetOmegaError(ret_code)))

    elif isomer:
        for enantiomer in oeomega.OEFlipper(mol.GetActive(), 12, True):
            enantiomer = oechem.OEMol(enantiomer)
            ret_code = omega.Build(enantiomer)
            if ret_code == oeomega.OEOmegaReturnCode_Success:
                out_conf.append(enantiomer)
                num_enantiomers -= 1
                oechem.OEWriteMolecule(ofs, mol)
                if num_enantiomers == 0:
                    break
            else:
                oechem.OEThrow.Warning("%s: %s" % (mol.GetTitle(), oeomega.OEGetOmegaError(ret_code)))

    return out_conf
Esempio n. 17
0
def dock_molecules(receptor_filename, molecules, filename):
    """
    Dock the specified molecules, writing out to specified file

    Parameters
    ----------
    receptor_filename : str
        Receptor .oeb.gz filename
    molecules : list of openeye.oechem.OEMol
        The read molecules to dock
    filename : str
        The filename to stream docked molecules to

    """
    # Read the receptor
    print('Loading receptor...')
    from openeye import oechem, oedocking
    receptor = oechem.OEGraphMol()
    if not oedocking.OEReadReceptorFile(receptor, 'receptor.oeb.gz'):
        oechem.OEThrow.Fatal("Unable to read receptor")

    if oedocking.OEReceptorHasBoundLigand(receptor):
        print("Receptor has a bound ligand")
    else:
        print("Receptor does not have bound ligand")

    print('Initializing receptor...')
    dockMethod = oedocking.OEDockMethod_Hybrid2
    dockResolution = oedocking.OESearchResolution_High
    dock = oedocking.OEDock(dockMethod, dockResolution)
    success = dock.Initialize(receptor)

    # Set up Omega
    from openeye import oeomega
    omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)
    #omegaOpts = oeomega.OEOmegaOptions()
    omega = oeomega.OEOmega(omegaOpts)
    omega.SetStrictStereo(False)

    # Dock molecules
    with oechem.oemolostream(filename) as ofs:
        from tqdm import tqdm
        for mol in tqdm(molecules):
            dockedMol = oechem.OEGraphMol()

            # Expand conformers
            omega.Build(mol)

            # Dock molecule
            retCode = dock.DockMultiConformerMolecule(dockedMol, mol)
            if (retCode != oedocking.OEDockingReturnCode_Success):
                oechem.OEThrow.Fatal("Docking Failed with error code " + oedocking.OEDockingReturnCodeGetName(retCode))

            # Store docking data
            sdtag = oedocking.OEDockMethodGetName(dockMethod)
            oedocking.OESetSDScore(dockedMol, dock, sdtag)
            dock.AnnotatePose(dockedMol)

            # Write molecule
            oechem.OEWriteMolecule(ofs, dockedMol)
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData, argv)

    cutoff = itf.GetFloat("-cutoff")

    ofs = oechem.oemolostream()
    if not ofs.open(itf.GetString("-clusters")):
        oechem.OEThrow.Fatal("Unable to open '%s'" % itf.GetString("-clusters"))

    if ofs.GetFormat() != oechem.OEFormat_OEB:
        oechem.OEThrow.Fatal("Output file must be OEB")

    sdtag = "TanimotoComboFromHead"
    if itf.GetBool("-shapeOnly"):
        sdtag = "ShapeTanimotoFromHead"
    getter = GetScoreGetter(itf.GetBool("-shapeOnly"))

    cluster = ShapeCluster(itf.GetString("-dbase"), cutoff, itf.GetBool("-shapeOnly"))

    # do the clustering
    while cluster.HasRemainingMolecules():
        clusterHead = cluster.GetNextClusterHead()
        print("Searching for neighbors of %s" % clusterHead.GetTitle())

        for nbrMol, score in cluster.GetCluster(clusterHead):
            oechem.OESetSDData(nbrMol, sdtag, "%.4f" % getter(score))

            score.Transform(nbrMol)

            clusterHead.AddData(nbrMol.GetTitle(), nbrMol)

        oechem.OEWriteMolecule(ofs, clusterHead)

    return 0
Esempio n. 19
0
    def reload_system(self, ln: str, smis: oechem.OEMol, old_pdb: str, is_oe_already: bool = False):
        with self.logger("reload_system") as logger:
            logger.log("Loading {} with new smiles {}".format(old_pdb, ln))
            with tempfile.TemporaryDirectory() as dirpath:
                ofs = oechem.oemolostream("{}/newlig.mol2".format(dirpath))
                oechem.OEWriteMolecule(ofs, smis)
                ofs.close()
                cmd.reinitialize()
                cmd.load(old_pdb)
                cmd.remove("not polymer")
                cmd.load("{}/newlig.mol2".format(dirpath), "UNL")
                cmd.alter("UNL", "resn='UNL'")
                cmd.alter("UNL", "chain='A'")
                self.config.pdb_file_name = self.config.tempdir() + "reloaded.pdb"
                cmd.save(self.config.pdb_file_name)
                cmd.save(self.config.tempdir() + "apo.pdb")

                with open(self.config.pdb_file_name, 'r') as f:
                    self.pdb = app.PDBFile(f)
                self.positions, self.topology = self.pdb.getPositions(), self.pdb.getTopology()

                if self.config.explicit and self.config.method == 'amber':
                    self.system, self.topology, self.positions = self.__setup_system_ex_amber(
                        pdbfile=self.config.pdb_file_name)
                elif self.config.explicit:
                    self.system, self.topology, self.positions = self.__setup_system_ex_mm()
                else:
                    self.system, self.topology, self.positions = self.__setup_system_im( pdbfile=self.config.pdb_file_name)

        return self.system
Esempio n. 20
0
def main():
    args = parse_args()

    start_time = time.time()
    ifs = oechem.oemolistream()
    if ifs.open(args.infile):
        mols = [oechem.OEMol(mol) for mol in ifs.GetOEGraphMols()]
        ifs.close()
    else:
        oechem.OEThrow.Fatal(f"Unable to open {args.infile}")

    out_mols = generate_ml_profiles(mols, args.model_file, args.scaler_file)
    count = len(out_mols)

    ofs = oechem.oemolostream()
    if ofs.open(args.outfile):
        for mol in out_mols:
            oechem.OEWriteMolecule(ofs, mol)
        ofs.close()
    else:
        oechem.OEThrow.Fatal(f"Unable to open {args.outfile}")

    time_elapsed = time.time() - start_time
    logging.warning('Generated profiles for %d molecules in %.1f seconds',
                    count, time_elapsed)
Esempio n. 21
0
def main(argv=[__name__]):
    if 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.oemolostream()
    if not ofs.open(argv[2]):
        oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])

    if not oechem.OEIs3DFormat(ofs.GetFormat()):
        oechem.OEThrow.Fatal("Invalid output file format for 3D coordinates!")

    omegaOpts = oeomega.OEMacrocycleOmegaOptions()
    mcomega = oeomega.OEMacrocycleOmega(omegaOpts)

    for mol in ifs.GetOEMols():
        oechem.OEThrow.Info("Title: %s" % mol.GetTitle())
        ret_code = mcomega.Build(mol)
        if ret_code == oeomega.OEOmegaReturnCode_Success:
            oechem.OEWriteMolecule(ofs, mol)
        else:
            oechem.OEThrow.Warning("%s: %s" % (mol.GetTitle(), oeomega.OEGetOmegaError(ret_code)))

    return 0
Esempio n. 22
0
def AtomPathLength(ifs, ofs, itf, atm1, atm2):
    for mol in ifs.GetOEGraphMols():
        oechem.OETriposAtomNames(mol)

        a1 = None
        a2 = None
        for atm in mol.GetAtoms():
            if atm.GetName() == atm1:
                a1 = atm
            if atm.GetName() == atm2:
                a2 = atm
            if a1 is not None and a2 is not None:
                break

        if a1 is None or a2 is None:
            oechem.OEThrow.Warning(
                "Failed to find atoms %s and %s in molecule" % (atm1, atm2))
            continue

        pathlen = oechem.OEGetPathLength(a1, a2)
        if itf.GetBool("-verbose") or not itf.HasString("-o"):
            print("Path length: %s in %s" %
                  (pathlen, oechem.OEMolToSmiles(mol)))

        spath = oechem.OEShortestPath(a1, a2)
        spathmol = oechem.OEGraphMol()
        adjustHCount = True
        oechem.OESubsetMol(spathmol, mol, oechem.OEIsAtomMember(spath),
                           adjustHCount)
        spathsmiles = oechem.OEMolToSmiles(spathmol)

        if itf.HasString("-o"):
            oechem.OEWriteMolecule(ofs, spathmol)
        elif itf.GetBool("-verbose"):
            print(spathsmiles)
def WriteStructures(receptor, lig, apo_path, lig_path):
    ofs = oechem.oemolostream()
    success = True
    if ofs.open(apo_path):
        oechem.OEWriteMolecule(ofs,receptor)
        ofs.close()
    else:
        success = False
    # TODO: If MAX_POSES != 1, we should select the top pose to save
    conf = list(lig.GetConfs())[0]
    if ofs.open(lig_path):
        oechem.OEWriteMolecule(ofs,conf)
        ofs.close()
    else:
        success = False
    return success
def main(args):
    if len(args) != 3:
        oechem.OEThrow.Usage("%s <input> <output>" % args[0])

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

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

    mol = oechem.OEMol()
    oechem.OEReadMolecule(ifs, mol)

    opts = oeszybki.OEFreeFormConfOptions()
    ffconf = oeszybki.OEFreeFormConf(opts)

    # Estimate free energies to ontain the minimum energy conformers
    omol = oechem.OEMol(mol)
    if not (ffconf.EstimateFreeEnergies(omol)
            == oeszybki.OEFreeFormReturnCode_Success):
        oechem.OEThrow.Error("Failed to estimate conformational free energies")

    # Find similar conformers to the ones we started with, from the
    # pool of minimum energy conformers
    fmol = oechem.OEMol(mol)
    for conf in mol.GetConfs():
        ffconf.FindSimilarConfs(fmol, omol, conf, oechem.OESimilarByRMSD(0.05))

    oechem.OEWriteMolecule(ofs, fmol)

    return 0
Esempio n. 25
0
def main(argv=[__name__]):
    if len(argv) != 4:
        oechem.OEThrow.Usage("%s <reffile> <rocs_hits_file> <output.sdf>" %
                             argv[0])

    reffs = oechem.oemolistream(argv[1])
    fitfs = oechem.oemolistream(argv[2])
    outfs = oechem.oemolostream(argv[3])

    refmol = oechem.OEGraphMol()
    oechem.OEReadMolecule(reffs, refmol)

    # Prepare reference molecule for calculation
    # With default options this will add required color atoms
    prep = oeshape.OEOverlapPrep()
    prep.Prep(refmol)

    # Get appropriate function to calculate analytic color
    colorFunc = oeshape.OEAnalyticColorFunc()
    colorFunc.SetupRef(refmol)

    res = oeshape.OEOverlapResults()
    for fitmol in fitfs.GetOEGraphMols():
        prep.Prep(fitmol)
        colorFunc.Overlap(fitmol, res)
        oechem.OESetSDData(fitmol, "AnalyticColorTanimoto",
                           "%.2f" % res.GetColorTanimoto())
        oechem.OEWriteMolecule(outfs, fitmol)
        print("Fit Title: %s  Color Tanimoto: %.2f" %
              (fitmol.GetTitle(), res.GetColorTanimoto()))
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData, argv)

    ifname = itf.GetString("-in")
    ofname = itf.GetString("-out")

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

    if not oechem.OEIs2DFormat(ifs.GetFormat()):
        oechem.OEThrow.Fatal("Invalid input format: need 2D coordinates")

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

    if not oechem.OEIs2DFormat(ofs.GetFormat()):
        oechem.OEThrow.Fatal(
            "Invalid output format: unable to write 2D coordinates")

    nrrings = 0
    for mol in ifs.GetOEGraphMols():
        for ring in oechem.OEExtractRingTemplates(mol):
            nrrings += 1
            oechem.OEWriteMolecule(ofs, ring)

    oechem.OEThrow.Info("%d number of ring templates extracted" % nrrings)
Esempio n. 27
0
 def write (self , filename, format = "mol2", mode = "w"):
     """                                               
     Writes this structure into a file in the designated format.     
     @type  format: C{str}                  
     @param format: Format must be one of the following case-sensitive strings: "pdb", "mol2", "xyz","sdf" and "smi"                   
     """
     if mode == "a":                                   
         raise ValueError("OeStruc write doesn't support append method")
     elif mode == "w":                                 
         if format == "pdb":                           
             ofs = oechem.oemolostream(filename + '.pdb')
             ofs.SetFormat(oechem.OEFormat_PDB)        
         elif format == "mol2":                        
             ofs = oechem.oemolostream(filename + '.mol2')
             ofs.SetFormat(oechem.OEFormat_MOL2)       
         elif format == "xyz":                         
             ofs = oechem.oemolostream(filename + '.xyz')
             ofs.SetFormat(oechem.OEFormat_XYZ)        
         elif format == "sdf":                         
             ofs = oechem.oemolostream(filename + '.sdf')
             ofs.SetFormat(oechem.OEFormat_SDF)        
         elif format == "smi":                         
             ofs = oechem.oemolostream(filename + '.smi')
             ofs.SetFormat(oechem.OEFormat_SMI)        
     else:                                             
         raise ValueError( "Invalid value for `mode' argument: '%s', should be one of 'a' and 'w'.")
     return oechem.OEWriteMolecule(ofs, self._struc  )
Esempio n. 28
0
def main(args=[__name__]):
    if len(args) != 3:
        oechem.OEThrow.Usage("%s <molfile> <outfile>" % args[0])

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

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

    mol = oechem.OEMol()
    oechem.OEReadMolecule(ifs, mol)

    opts = oeszybki.OESzybkiOptions()
    opts.GetGeneralOptions().SetForceFieldType(oeszybki.OEForceFieldType_SMIRNOFF)
    sz = oeszybki.OESzybki(opts)
    results = oeszybki.OESzybkiResults()
    if not sz(mol, results):
        return 1

    oechem.OEWriteMolecule(ofs, mol)
    results.Print(oechem.oeout)

    return 0
Esempio n. 29
0
def main(args):
    if len(args) != 3:
        oechem.OEThrow.Usage("%s input_molecule output_molecule" % args[0])

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

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

    mol = oechem.OEMol()
    oechem.OEReadMolecule(ifs, mol)

    opts = oeszybki.OESzybkiOptions()
    opts.GetOptOptions().SetOptimizerType(oeszybki.OEOptType_NEWTON)
    opts.GetSolventOptions().SetSolventModel(oeszybki.OESolventModel_Sheffield)

    sz = oeszybki.OESzybki(opts)
    res = oeszybki.OESzybkiResults()
    if (sz(mol, res)):
        oechem.OEWriteMolecule(ofs, mol)
        res.Print(oechem.oeout)

    return 0
Esempio n. 30
0
def main(args):
    if len(args) != 3:
        oechem.OEThrow.Usage("%s <input> <output>" % args[0])

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

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

    mol = oechem.OEMol()
    oechem.OEReadMolecule(ifs, mol)

    opts = oeszybki.OEFreeFormConfOptions()
    ffconf = oeszybki.OEFreeFormConf(opts)

    omol = oechem.OEMol(mol)
    if not (ffconf.EstimateFreeEnergies(omol) == oeszybki.OEFreeFormReturnCode_Success):
        oechem.OEThrow.Error("Failed to estimate conformational free energies")

    res = oeszybki.OEFreeFormConfResults(omol)
    oechem.OEThrow.Info("Number of unique conformations: %d" % res.GetNumUniqueConfs())
    oechem.OEThrow.Info("Conf.  Delta_G   Vibrational_Entropy")
    oechem.OEThrow.Info("      [kcal/mol]     [J/(mol K)]")
    for r in res.GetResultsForConformations():
        oechem.OEThrow.Info("%2d %10.2f %14.2f" % (r.GetConfIdx(), r.GetDeltaG(),
                                                   r.GetVibrationalEntropy()))

    oechem.OEWriteMolecule(ofs, omol)

    return 0