Example #1
0
    def choose_action(self, pdb_string):
        with self.logger("choose_action") as logger:
            with tempfile.TemporaryDirectory() as dirname:
                with open("{}/test.pdb".format(dirname), 'w') as f:
                    f.write(pdb_string)
                pdb = oechem.OEMol()
                prot = oechem.OEMol()
                lig = oechem.OEMol()
                wat = oechem.OEGraphMol()
                other = oechem.OEGraphMol()
                ifs = oechem.oemolistream()
                ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_Default
                              | oechem.OEIFlavor_PDB_DATA
                              | oechem.OEIFlavor_PDB_ALTLOC)  # noqa
                if not ifs.open("{}/test.pdb".format(dirname)):
                    logger.log("crap")
                oechem.OEReadMolecule(ifs, pdb)
                ifs.close()
                if not oechem.OESplitMolComplex(lig, prot, wat, other, pdb):
                    logger.failure("could not split complex. exiting",
                                   exit_all=True)
                else:
                    logger.log("atom sizes for incoming step",
                               len(list(lig.GetAtoms())),
                               len(list(prot.GetAtoms())),
                               len(list(wat.GetAtoms())),
                               len(list(other.GetAtoms())))
                original_smiles, oeclean_smiles = self.env.action.get_new_action_set(
                    aligner=lig)
                data = self.getscores(
                    original_smiles,
                    oeclean_smiles,
                    prot,
                    lig,
                    num_returns=self.num_returns,
                    return_docked_pose=self.return_docked_pose)
                not_worked = True
                idxs = list(range(len(data)))
                idx = idxs.pop(0)
                while not_worked:
                    try:
                        new_mol, new_mol2, gs, action = data[idx]

                        self.env.systemloader.reload_system(
                            gs, new_mol, "{}/test.pdb".format(dirname))
                        self.env.openmm_simulation = self.env.config.openmmWrapper.get_obj(
                            self.env.systemloader, self.env.openmm_simulation)
                        not_worked = False
                    except Exception as e:
                        logger.error("Could not buid system for smiles", gs,
                                     "with exception", e)
                        traceback.print_tb(e.__traceback__)

                        if len(idxs) == 0:
                            logger.failure("No system could build",
                                           exit_all=True)
                        idx = idxs.pop(0)
                self.env.action.apply_action(new_mol2, action)

        return new_mol2, action
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
Example #3
0
def file_to_oemols(filename):
    """Create OEMol from file. If more than one mol in file, return list of OEMols.

    Parameters
    ----------
    filename: str
        absolute path to oeb file

    Returns
    -------
    mollist: list
        list of OEMol for multiple molecules. OEMol if file only has one molecule.
    """
    from openeye import oechem

    if not os.path.exists(filename):
        raise Exception("File {} not found".format(filename))

    ifs = oechem.oemolistream(filename)
    mollist = []

    molecule = oechem.OEMol()
    while oechem.OEReadMolecule(ifs, molecule):
        molecule_copy = oechem.OEMol(molecule)
        oechem.OEPerceiveChiral(molecule_copy)
        oechem.OE3DToAtomStereo(molecule_copy)
        oechem.OE3DToBondStereo(molecule_copy)
        mollist.append(molecule_copy)
    ifs.close()

    if len(mollist) is 1:
        mollist = mollist[0]
    return mollist
Example #4
0
def enumerate_from_smiles(smiles, oe_options=None):
    oe_options = oe_options or OEOptions()

    omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Pose)
    omegaOpts.SetMaxSearchTime(60)
    omega = oeomega.OEOmega(omegaOpts)

    if oe_options.use_tautomer:
        tautomer_options = oequacpac.OETautomerOptions()
        pKa_norm = True
        taut_iter = lambda x: oequacpac.OEGetReasonableTautomers(x, tautomer_options, pKa_norm)
    else:
        taut_iter = lambda x: [x]

    if oe_options.use_flipper:
        flipper = lambda x: oeomega.OEFlipper(x.GetActive(), oe_options.num_sterocenters, oe_options.force_flipper)
    else:
        flipper = lambda x: [x]

    # get molecule
    try:
        molecule = mol_from_smiles(smiles)
    except ValueError:
        return [None]

    results = []
    for enantiomer in flipper(molecule):
        for tautomer in taut_iter(enantiomer):
            tautomer = oechem.OEMol(tautomer)
            omega.Build(tautomer)
            tautomer2 = oechem.OEMol(tautomer)
            results.append(tautomer2)
    return results
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
def genConfs(c_mol, ofsff, ofsTri, index):
    # set omega settings
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega.SetIncludeInput(False)
    omega.SetEnergyWindow(15.0)
    strict_stereo = True
    omega.SetStrictStereo(strict_stereo)
    omega.SetSampleHydrogens(True)
    omega.SetStrictAtomTypes(True)

    mol = oechem.OEMol(c_mol)
    status = omega(mol)

    if status:
        # change title
        mol.SetTitle(f'DrugBank_{index}')
        # save force field type
        mol1 = oechem.OEMol(mol)
        oechem.OETriposAtomNames(mol1)
        oechem.OEWriteConstMolecule(ofsff, mol1)

        # save Tripos atom types
        mol2 = oechem.OEMol(mol)
        oechem.OETriposAtomTypeNames(mol2)
        oechem.OEWriteConstMolecule(ofsTri, mol2)

    return status
Example #7
0
    def test_success(self):
        print('Testing cube:', self.cube.name)
        # File name
        fn_protein = ommutils.get_data_filename('examples',
                                                'data/Bace_solvated.oeb.gz')
        fn_ligand = ommutils.get_data_filename('examples',
                                               'data/lig_CAT13a_chg.oeb.gz')

        # Read Protein molecule
        protein = oechem.OEMol()

        with oechem.oemolistream(fn_protein) as ifs:
            oechem.OEReadMolecule(ifs, protein)

        # Read Ligand molecule
        ligand = oechem.OEMol()

        with oechem.oemolistream(fn_ligand) as ifs:
            oechem.OEReadMolecule(ifs, ligand)

        # Process the molecules
        self.cube.process(protein, self.cube.intake.name)
        # Why do I have to manually set these on?
        self.cube.check_system = True
        self.cube.system = protein
        self.cube.process(ligand, self.cube.system_port)

        # Assert that one molecule was emitted on the success port
        self.assertEqual(self.runner.outputs['success'].qsize(), 1)
        # Assert that zero molecules were emitted on the failure port
        self.assertEqual(self.runner.outputs['failure'].qsize(), 0)

        complex = self.runner.outputs["success"].get()

        self.assertEquals(complex.GetMaxAtomIdx(), 52312)
Example #8
0
def delete_shell(core_mol, del_mol, cut_off, in_out='in'):
    """
    This function deletes molecules present in the passed argument
    del_mol that are far (in_out=out) or close (in_out=in) than the
    selected cutoff distance (in A) from the passed molecules core_mol

    Parameters:
    -----------
    core_mol: OEMol molecule
        The core molecules
    del_mol: OEMol molecule
        The molecules to be deleted if their distances from the core_mol
        molecules are greater or closer that the selected cutoff distance
    cut_off: python float number
        The threshold distance in A used to mark atom for deletion
    in_out: python string
        A flag used to select if delete molecules far or close than
        the cutoff distance from the core_mol

    Return:
    -------
    reset_del: copy of del_mol where atoms have been deleted with
        reset atom indexes
    """

    if in_out not in ['in', 'out']:
        raise ValueError(
            "The passed in_out parameter is not recognized: {}".format(in_out))

    # Copy the passed molecule to delete in
    to_del = oechem.OEMol(del_mol)

    # Create a OE bit vector mask for each atoms of the
    # molecule to delete
    bv = oechem.OEBitVector(to_del.GetMaxAtomIdx())
    bv.NegateBits()

    # Create the Nearest neighbours
    nn = oechem.OENearestNbrs(to_del, cut_off)
    for nbrs in nn.GetNbrs(core_mol):
        # bv.SetBitOff(nbrs.GetBgn().GetIdx())
        for atom in oechem.OEGetResidueAtoms(nbrs.GetBgn()):
            bv.SetBitOff(atom.GetIdx())

    # Invert selection mask
    if in_out == 'in':
        bv.NegateBits()

    pred = oechem.OEAtomIdxSelected(bv)
    for atom in to_del.GetAtoms(pred):
        to_del.DeleteAtom(atom)

    # It is necessary to reset the atom indexes of the molecule with
    # delete atoms to avoid possible mismatching
    reset_del = oechem.OEMol(to_del)

    return reset_del
Example #9
0
def strip_water_ions(in_system):
    """
    This function remove waters and ions molecules
    from the input system

    Parameters:
    ----------
    in_system : oechem.OEMol
        The bio-molecular system to clean
    opt: python dictionary
        The system option

    Output:
    -------
    clean_system : oechem.OEMol
        The cleaned system

    """
    # Copy the input system
    system = oechem.OEMol(in_system)

    # Create a bit vector mask
    bv = oechem.OEBitVector(system.GetMaxAtomIdx())
    bv.NegateBits()

    # Create a Hierarchical View of the protein system
    hv = oechem.OEHierView(
        system,
        oechem.OEAssumption_BondedResidue + oechem.OEAssumption_ResPerceived)

    # Looping over the system residues
    for chain in hv.GetChains():
        for frag in chain.GetFragments():
            for hres in frag.GetResidues():
                res = hres.GetOEResidue()

                # Check if a residue is a mono atomic ion
                natoms = 0
                for at in hres.GetAtoms():
                    natoms += 1

                # Set the atom bit mask off
                if oechem.OEGetResidueIndex(
                        res) == oechem.OEResidueIndex_HOH or natoms == 1:
                    # Set Bit mask
                    atms = hres.GetAtoms()
                    for at in atms:
                        bv.SetBitOff(at.GetIdx())

    # Extract the system without waters or ions
    pred = oechem.OEAtomIdxSelected(bv)
    clean_system = oechem.OEMol()
    oechem.OESubsetMol(clean_system, system, pred)

    return clean_system
def dock_molecule(molecule, default_receptor='x0387'):
    """
    Dock the specified molecules, writing out to specified file

    Parameters
    ----------
    molecule : OEMol
        The molecule to dock
    default_receptor : str, optional, default='0387'
        The default receptor to dock to

    Returns
    -------
    all_docked_molecules : list of OEMol
        All docked molecules
    """
    import os
    import oechem

    # Make a copy of the molecule
    molecule = oechem.OEMol(molecule)

    # Extract list of corresponding receptor(s)
    fragments = list()
    fragments = oechem.OEGetSDData(molecule, "fragments").split(',')
    fragments = [
        fragment for fragment in fragments
        if os.path.exists(f'../receptors/Mpro-{fragment}-receptor.oeb.gz')
    ]

    if len(fragments) == 0:
        fragments = [default_receptor]

    # Dock them
    all_docked_molecules = list()
    for fragment in fragments:
        molecule_to_dock = oechem.OEMol(molecule)

        import os
        receptor_filename = os.path.join(
            f'../receptors/Mpro-{fragment}-receptor.oeb.gz')
        oechem.OESetSDData(molecule_to_dock, "fragments", fragment)

        # Enumerate reasonable protomers/tautomers
        from openeye import oequacpac
        protomer = oechem.OEMol()
        protomers = [
            oechem.OEMol(protomer) for protomer in
            oequacpac.OEGetReasonableProtomers(molecule_to_dock)
        ]
        docked_molecules = dock_molecules_to_receptor(receptor_filename,
                                                      protomers)
        all_docked_molecules += docked_molecules

    return all_docked_molecules
Example #11
0
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData, argv)

    # Set up best overlay to the query molecule
    qfs = oechem.oemolistream()
    if not qfs.open(itf.GetString("-q")):
        oechem.OEThrow.Fatal("Unable to open %s" % itf.GetString("-q"))

    qmol = oechem.OEMol()
    oechem.OEReadMolecule(qfs, qmol)

    # Set up overlap to protein exclusion volume
    efs = oechem.oemolistream()
    if not efs.open(itf.GetString("-e")):
        oechem.OEThrow.Fatal("Unable to open %s" % itf.GetString("-e"))

    emol = oechem.OEMol()
    oechem.OEReadMolecule(efs, emol)

    evol = oeshape.OEExactShapeFunc()
    evol.SetupRef(emol)

    # open database and output streams
    ifs = oechem.oemolistream()
    if not ifs.open(itf.GetString("-d")):
        oechem.OEThrow.Fatal("Unable to open %s" % itf.GetString("-d"))

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

    print("Title                Combo  Rescore")
    for mol in ifs.GetOEMols():
        res = oeshape.OEROCSResult()
        oeshape.OEROCSOverlay(res, qmol, mol)
        outmol = res.GetOverlayConf()

        # calculate overlap with protein
        eres = oeshape.OEOverlapResults()
        evol.Overlap(outmol, eres)

        frac = eres.GetOverlap() / eres.GetFitSelfOverlap()
        rescore = res.GetTanimotoCombo() - frac

        # attach data to molecule and write it
        oechem.OESetSDData(outmol, "TanimotoCombo", "%-.3f" % res.GetTanimotoCombo())
        oechem.OESetSDData(outmol, "Exclusion Volume", "%-.3f" % eres.overlap)
        oechem.OESetSDData(outmol, "Fraction Overlap", "%-.3f" % frac)
        oechem.OESetSDData(outmol, "Rescore", "%-.3f" % rescore)

        oechem.OEWriteMolecule(ofs, outmol)

        print("%-20s %.3f  %.3f" %
              (outmol.GetTitle(), res.GetTanimotoCombo(), rescore))
def draw_frag_pdf(frag_dict, scaffold=None, pdf_filename='fragments.pdf'):
    from openeye import oechem, oedepict
    import re
    itf = oechem.OEInterface()
    PageByPage = True
    suppress_h = True
    rows = 7
    cols = 5
    ropts = oedepict.OEReportOptions(rows, cols)
    ropts.SetHeaderHeight(25)
    ropts.SetFooterHeight(25)
    ropts.SetCellGap(2)
    ropts.SetPageMargins(10)
    report = oedepict.OEReport(ropts)
    cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
    opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight,
                                          oedepict.OEScale_Default * 0.5)
    opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle)
    pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On,
                         1.0)
    opts.SetDefaultBondPen(pen)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    if scaffold:
        oemol = oechem.OEGraphMol()
        scaffold_smi = re.sub(r"\(\[R([1-9])+]\)", r"([*])", scaffold.smiles)
        oechem.OESmilesToMol(oemol, scaffold_smi)
        cell = report.NewCell()
        mol = oechem.OEMol(oemol)
        mol.SetTitle(f'{scaffold.smiles}')
        oedepict.OEPrepareDepiction(mol, False, suppress_h)
        disp = oedepict.OE2DMolDisplay(mol, opts)
        oedepict.OERenderMolecule(cell, disp)
        headerpen = oedepict.OEPen(oechem.OEWhite, oechem.OELightGrey,
                                   oedepict.OEFill_Off, 1.0)
        oedepict.OEDrawBorder(cell, headerpen)

    for rx, smis in frag_dict.items():
        for idx, smi in enumerate(smis):
            if smi != None:

                # Create oemol
                oemol = oechem.OEGraphMol()
                oechem.OESmilesToMol(oemol, smi)

                # Render molecule
                cell = report.NewCell()
                mol = oechem.OEMol(oemol)
                mol.SetTitle(f'R{rx} #{idx+1}')
                oedepict.OEPrepareDepiction(mol, False, suppress_h)
                disp = oedepict.OE2DMolDisplay(mol, opts)

                oedepict.OERenderMolecule(cell, disp)

    oedepict.OEWriteReport(pdf_filename, report)
Example #13
0
 def call_static(data):
     original_smiles, oe_smiles, refmol = data
     fitfs = oechem.oemolistream()
     fitfs.SetFormat(oechem.OEFormat_SMI)
     fitfs.openstring(oe_smiles)
     mol = oechem.OEMol()
     oechem.OEReadMolecule(fitfs, mol)
     new_mol = RocsMolAligner.from_oemol_static(mol, refmol)
     if new_mol is None:
         return None
     return new_mol, oechem.OEMol(new_mol), oe_smiles, original_smiles
Example #14
0
    def from_oemol(self, from_oemol):
        with self.logger("from_oemol") as logger:
            tautomer_options = oequacpac.OETautomerOptions()
            tautomer_options.SetMaxTautomersGenerated(4096)
            tautomer_options.SetMaxTautomersToReturn(16)
            tautomer_options.SetCarbonHybridization(True)
            tautomer_options.SetMaxZoneSize(50)
            tautomer_options.SetApplyWarts(True)

            pKa_norm = True

            omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Pose)
            omegaOpts.SetStrictAtomTypes(False)
            omegaOpts.SetSampleHydrogens(True)
            omegaOpts.SetMaxSearchTime(30)
            omegaOpts.SetFixDeleteH(True)
            omega = oeomega.OEOmega(omegaOpts)

            options = oeshape.OEROCSOptions()
            overlayoptions = oeshape.OEOverlayOptions()
            overlayoptions.SetOverlapFunc(
                oeshape.OEOverlapFunc(oeshape.OEAnalyticShapeFunc()))
            options.SetOverlayOptions(overlayoptions)
            # options.SetNumBestHits(10)
            options.SetConfsPerHit(200)
            # options.SetMaxHits(10000)
            rocs = oeshape.OEROCS(options)
            for tautomer in oequacpac.OEGetReasonableTautomers(
                    from_oemol, tautomer_options, pKa_norm):
                logger.log("got enantiomer")
                for enantiomer in oeomega.OEFlipper(tautomer, 4, False):
                    logger.log("got tautomer ")
                    enantiomer_ = oechem.OEMol(enantiomer)
                    ret_code = omega.Build(enantiomer_)
                    if ret_code != oeomega.OEOmegaReturnCode_Success:
                        logger.error("got oemeg_failed",
                                     oeomega.OEGetOmegaError(ret_code))
                    else:
                        rocs.AddMolecule(oechem.OEMol(enantiomer_))

            for res in rocs.Overlay(self.refmol):
                outmol = oechem.OEMol(res.GetOverlayConfs())
                good_mol = oechem.OEMol(outmol)
                oechem.OEAddExplicitHydrogens(good_mol)
                oechem.OEClearSDData(good_mol)
                oeshape.OEDeleteCompressedColorAtoms(good_mol)
                oeshape.OEClearCachedSelfColor(good_mol)
                oeshape.OEClearCachedSelfShape(good_mol)
                oeshape.OERemoveColorAtoms(good_mol)
                return good_mol
            logger.error("Returning None.")

        return None
Example #15
0
def are_equal_microstates(mol1: oechem.OEMol, mol2: oechem.OEMol):
    """ Check if two supplied OE(Graph)Mol objects have the same molecular microstate present.
    
    If all atoms and bonds are matched in MCSS returns True. Ignores charges and bond order
    to deal with chirality and geometry differences as well as resonance structures
    (which we won't consider as different).
    
    Returns
    -------
    bool    
    """
    # Copy input
    pattern = oechem.OEMol(mol1)
    target = oechem.OEMol(mol2)

    # Atoms are equal if they have same atomic number (so explicit Hydrogens are needed as well for a match)
    atomexpr = oechem.OEExprOpts_AtomicNumber
    # single or double bonds are considered identical (resonance,chirality fix)
    bondexpr = oechem.OEExprOpts_EqSingleDouble
    # create maximum common substructure object
    mcss = oechem.OEMCSSearch(pattern, atomexpr, bondexpr,
                              oechem.OEMCSType_Exhaustive)

    # set scoring function
    mcss.SetMCSFunc(oechem.OEMCSMaxAtomsCompleteCycles())
    # ignore matches smaller than 6 atoms
    mcss.SetMinAtoms(6)
    unique = True

    # loop over matches
    count = 0
    match = oechem.OEMol()
    for i, match in enumerate(mcss.Match(target, unique)):
        count = i + 1
        logger.debug("Match %d:" % (count))

        logger.debug("Num atoms in match %d" % match.NumAtoms())
        logger.debug("Num atoms in mol1 %d" % pattern.NumAtoms())
        logger.debug("Num atoms in mol2 %d" % target.NumAtoms())

    # check if there is only single match
    if (count > 1):
        logger.warning("Warning! There are multiple matches.")
    elif count == 0:
        logger.debug("No match")

    m_num = match.NumAtoms()
    p_num = pattern.NumAtoms()
    t_num = target.NumAtoms()

    return m_num == p_num == t_num
Example #16
0
def split(mol):
    """
    This function splits the passed system in protein, ligand,
    water and excipients

    Parameters:
    ----------
    mol : oechem.OEMol
        The bio-molecular system to split

    Output:
    -------
    protein : oechem.OEMol
        The split protein
    ligand : oechem.OEMol
        The split ligand
    wat : oechem.OEMol
        The spit water
    other : oechem.OEMol
        The excipients
    
    """

    # Set empty molecule containers
    prot = oechem.OEMol()
    lig = oechem.OEMol()
    wat = oechem.OEMol()
    other = oechem.OEMol()

    # Define the Filter options before the splitting
    opt = oechem.OESplitMolComplexOptions()

    # The protein filter is set to avoid that multiple
    # chains are separated during the splitting
    pf = oechem.OEMolComplexFilterFactory(oechem.OEMolComplexFilterCategory_Protein)
    # The ligand filter is set to recognize just the ligand
    lf = oechem.OEMolComplexFilterFactory(oechem.OEMolComplexFilterCategory_Ligand)
    # The water filter is set to recognize just water molecules
    wf = oechem.OEMolComplexFilterFactory(oechem.OEMolComplexFilterCategory_Water)
    opt.SetProteinFilter(pf)
    opt.SetLigandFilter(lf)
    opt.SetWaterFilter(wf)
    
    # Splitting the system
    if not oechem.OESplitMolComplex(lig, prot, wat, other, mol, opt):
        oechem.OEThrow.Fatal('Unable to split the complex')
    
    # At this point prot contains the protein, lig contains the ligand,
    # wat contains the water and excipients contains the excipients

    return prot, lig, wat, other
Example #17
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <receptor> <conformers>" % argv[0])

    receptor = oechem.OEGraphMol()
    oedocking.OEReadReceptorFile(receptor, argv[1])
    dock = oedocking.OEDock()
    dock.Initialize(receptor)

    conformers = oechem.OEMol()
    imstr = oechem.oemolistream(argv[2])
    for conformers in imstr.GetOEMols():
        poses = oechem.OEMol()
        dock.DockMultiConformerMolecule(poses, conformers)
        TagPoses(dock, poses, dock.GetName())
Example #18
0
def gen_conf(mol):
    oemols = []
    omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_FastROCS)
    omega = oeomega.OEOmega(omegaOpts)
    for enantiomer in oeomega.OEFlipper(mol.GetActive(), 6, True):
        enantiomer = oechem.OEMol(enantiomer)
        ret_code = omega.Build(enantiomer)
        if ret_code == oeomega.OEOmegaReturnCode_Success:
            halfMol = oechem.OEMol(mol, oechem.OEMCMolType_HalfFloatCartesian)
            oemols.append(halfMol)
        else:
            oechem.OEThrow.Warning(
                "%s: %s" %
                (enantiomer.GetTitle(), oeomega.OEGetOmegaError(ret_code)))
    return oemols
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
def read_molecules(filename):
    """Read a file into an OpenEye molecule (or list of molecules).

    Parameters
    ----------
    filename : str
        The name of the file to read (e.g. mol2, sdf)

    Returns
    -------
    molecule : openeye.oechem.OEMol
        The OEMol molecule read, or a list of molecules if multiple molecules are read.
        If no molecules are read, None is returned.

    """

    ifs = oechem.oemolistream(filename)
    molecules = list()
    for mol in ifs.GetOEMols():
        mol_copy = oechem.OEMol(mol)
        molecules.append(mol_copy)
    ifs.close()

    if len(molecules) == 0:
        return None
    elif len(molecules) == 1:
        return molecules[0]
    else:
        return molecules
def read_molecule(filename):
    ifs = oechem.oemolistream()
    ifs.open(filename)
    molecule = oechem.OEMol()
    oechem.OEReadMolecule(ifs, molecule)
    ifs.close()
    return molecule
Example #22
0
def test_partial_bondorder(verbose=False):
    """Test setup of a molecule which activates partial bond order code."""
    from openeye import oechem
    mol = oechem.OEMol()
    from openeye import oeiupac
    oeiupac.OEParseIUPACName(mol, 'benzene')
    positions = positions_from_oemol(mol)
    oechem.OETriposAtomNames(mol)
    topology = generateTopologyFromOEMol(mol)
    # Load forcefield from above
    ffxml = StringIO(ffxml_contents_noconstraints)
    ff = ForceField(ffxml)

    # Set up once using AM1BCC charges
    system = ff.createSystem(topology, [mol],
                             chargeMethod='OECharges_AM1BCCSym',
                             verbose=verbose)

    # Check that energy is what it ought to be -- the partial bond order
    # for benzene makes the energy a bit higher than it would be without it
    energy = get_energy(system, positions)
    if energy < 7.50 or energy > 7.60:
        raise Exception(
            "Partial bond order code seems to have issues, as energy for benzene is outside of tolerance in tests."
        )

    # Set up once also without asking for charges
    system = ff.createSystem(topology, [mol], verbose=verbose)
    energy = get_energy(system, positions)
    # Energy is lower with user supplied charges (which in this case are zero)
    if energy < 4.00 or energy > 6.0:
        raise Exception(
            "Partial bond order code seems to have issues when run with user-provided charges, as energy for benzene is out of tolerance in tests."
        )
Example #23
0
def test_improper(verbose=False):
    """Test implement of impropers on benzene."""
    from openeye import oechem
    # Load benzene
    ifs = oechem.oemolistream(get_data_filename('molecules/benzene.mol2'))
    mol = oechem.OEMol()
    flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield
    ifs.SetFlavor(oechem.OEFormat_MOL2, flavor)
    oechem.OEReadMolecule(ifs, mol)
    ifs.close()
    # Load forcefield
    ffxml = get_data_filename('forcefield/benzene_minimal.ffxml')
    ff = ForceField(ffxml)

    # Load AMBER files and compare
    crd = get_data_filename('molecules/benzene.crd')
    top = get_data_filename('molecules/benzene.top')
    g0, g1, e0, e1 = compare_molecule_energies(top,
                                               crd,
                                               ff,
                                               mol,
                                               skip_assert=True)

    # Check that torsional energies the same to 1 in 10^6
    rel_error = np.abs((g0['torsion'] - g1['torsion']) / g0['torsion'])
    if rel_error > 2e-5:  #Note that this will not be tiny because we use six-fold impropers and they use a single improper
        raise Exception(
            "Improper torsion energy for benzene differs too much (relative error %.4g) between AMBER and SMIRNOFF."
            % rel_error)
Example #24
0
    def test_excipient_successGaff2(self):
        print('Testing cube:', self.cube.name)
        # File name
        fn_complex = ommutils.get_data_filename(
            'examples', 'data/pbace_lcat13a_solvated_complex.oeb.gz')

        # Read Protein molecule
        complex = oechem.OEMol()

        with oechem.oemolistream(fn_complex) as ifs:
            oechem.OEReadMolecule(ifs, complex)

        # Selecting ligand and excipient parametrization
        self.cube.args.ligand_forcefield = 'GAFF2'
        self.cube.args.other_forcefield = 'GAFF2'

        # Process the molecules
        self.cube.process(complex, self.cube.intake.name)

        # Assert that one molecule was emitted on the success port
        self.assertEqual(self.runner.outputs['success'].qsize(), 1)
        # Assert that zero molecules were emitted on the failure port
        self.assertEqual(self.runner.outputs['failure'].qsize(), 0)

        complex = self.runner.outputs["success"].get()
Example #25
0
def test_merge_system():
    """Test merging of a system created from AMBER and another created from SMIRNOFF."""

    #Create System from AMBER
    prefix = os.path.join('systems', 'amber', 'cyclohexane_ethanol_0.4_0.6')
    prmtop = get_data_filename(prefix + '.prmtop')
    incrd = get_data_filename(prefix + '.inpcrd')

    from openforcefield.typing.engines.smirnoff import create_system_from_amber
    topology0, system0, positions0 = create_system_from_amber(prmtop, incrd)

    from openeye import oechem
    # Load simple OEMol
    ifs = oechem.oemolistream(
        get_data_filename('molecules/AlkEthOH_c100.mol2'))
    mol = oechem.OEMol()
    flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield
    ifs.SetFlavor(oechem.OEFormat_MOL2, flavor)
    oechem.OEReadMolecule(ifs, mol)
    oechem.OETriposAtomNames(mol)

    # Load forcefield file
    forcefield = ForceField(
        get_data_filename('forcefield/Frosst_AlkEthOH.ffxml'))
    topology1, system1, positions1 = create_system_from_molecule(
        forcefield, mol)

    merge_system(topology0,
                 topology1,
                 system0,
                 system1,
                 positions0,
                 positions1,
                 verbose=True)
def expand_stereochemistry(mols):
    """Expand stereochemistry when uncertain

    Parameters
    ----------
    mols : openeye.oechem.OEGraphMol
        Molecules to be expanded

    Returns
    -------
    expanded_mols : openeye.oechem.OEMol
        Expanded molecules
    """
    expanded_mols = list()

    from openeye import oechem, oeomega
    omegaOpts = oeomega.OEOmegaOptions()
    omega = oeomega.OEOmega(omegaOpts)
    maxcenters = 12
    forceFlip = False
    enumNitrogen = True
    warts = True # add suffix for stereoisomers
    for mol in mols:
        for enantiomer in oeomega.OEFlipper(mol, maxcenters, forceFlip, enumNitrogen, warts):
            enantiomer = oechem.OEMol(enantiomer)
            expanded_mols.append(enantiomer)

    return expanded_mols
Example #27
0
    def get_stage_topology(self, stg_name='last'):
        """
        This method returns the MD topology of the selected stage name. If no stage name is passed
        the last stage is selected.

        Parameters
        -----------
        stg_name: String
            The MD stage name

        Returns
        -------
        topology : OEMol
            The topology of the selected MD stage
        """

        stage = self.get_stage_by_name(stg_name)

        stage_name = stage.get_value(Fields.stage_name)

        dir_stage = self.processed[stage_name]

        topology_fn = os.path.join(dir_stage, MDFileNames.topology)

        topology = oechem.OEMol()

        with oechem.oemolistream(topology_fn) as ifs:
            oechem.OEReadMolecule(ifs, topology)

        return topology
Example #28
0
def generate_conformations(molecule: oechem.OEGraphMol,
                           max_conformations: int = 1000,
                           dense: bool = False) -> oechem.OEMol:
    """
    Generate conformations of a given molecule.
    Parameters
    ----------
    molecule: oechem.OEGraphMol
        An OpenEye molecule.
    max_conformations: int
        Maximal number of conformations to generate.
    dense: bool
        If densely sampled conformers should be generated. Will overwrite max_conformations settings.
    Returns
    -------
    conformations: oechem.OEMol
        An OpenEye multi-conformer molecule holding the generated conformations.
    """
    from openeye import oechem, oeomega

    if dense:
        omega_options = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)
    else:
        omega_options = oeomega.OEOmegaOptions()
        omega_options.SetMaxSearchTime(60.0)  # time out
        omega_options.SetMaxConfs(max_conformations)

    omega = oeomega.OEOmega(omega_options)
    omega.SetStrictStereo(False)

    conformations = oechem.OEMol(molecule)
    omega.Build(conformations)

    return conformations
Example #29
0
def iupac_to_oemol(iupac_name: str) -> oechem.OEMol:
    """
    Convert an IUPAC name to an OEMol with openeye

    Parameters
    ----------
    iupac_name : str
        The name of the molecule

    Returns
    -------
    mol : oechem.OEMol
        The OEMol corresponding to the IUPAC name with all hydrogens
    """
    mol = oechem.OEMol()
    oeiupac.OEParseIUPACName(mol, iupac_name)
    oechem.OEAddExplicitHydrogens(mol)

    # generate conformers:
    omega = oeomega.OEOmega()
    omega.SetStrictStereo(False)
    omega.SetMaxConfs(1)
    omega(mol)

    return mol
Example #30
0
def convert_mdtraj_to_oemol(traj: md.Trajectory) -> oechem.OEMol:
    """
    This method converts an mdtraj Trajectory to an OEMol via saving as a PDBfile
    and reading in with OpenEye. Although this seems hacky, it seems less error-prone
    than trying to manually construct the OEMol.

    Parameters
    ----------
    mdtraj: md.Trajectory
        The trajectory to turn into an OEMol

    Returns
    -------
    mol : oechem.OEMol
        The trajectory represented as an OEMol
    """
    # create a temporary file with a PDB suffix and save with MDTraj
    pdb_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdb")
    traj.save(pdb_file.name)
    pdb_file.close()

    # Now use the openeye oemolistream to read in this file as an OEMol:
    ifs = oechem.oemolistream()
    ifs.open(pdb_file.name)
    ifs.SetFormat(oechem.OEFormat_PDB)

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

    # close the stream and delete the temporary pdb file
    ifs.close()
    os.unlink(pdb_file.name)

    return mol