Ejemplo n.º 1
0
def positions_from_oemol(mol):
    """
    Extract OpenMM positions from OEMol.

    Parameters
    ----------
    mol : oechem.openeye.OEMol
        OpenEye molecule from which to extract coordinates.

    Returns
    -------
    positions : simtk.unit.Quantity of dimension (nparticles,3)

    """
    from openeye import oechem, oeomega
    if mol.GetDimension() != 3:
        # Assign coordinates
        omega = oeomega.OEOmega()
        omega.SetMaxConfs(1)
        omega.SetIncludeInput(False)
        omega.SetCanonOrder(False)
        omega.SetSampleHydrogens(True)  # Word to the wise: skipping this step can lead to significantly different charges!
        omega(mol)  # generate conformation

    coordinates = mol.GetCoords()
    natoms = len(coordinates)
    positions = np.zeros([natoms,3], np.float32)
    for index in range(natoms):
        (x,y,z) = coordinates[index]
        positions[index,0] = x
        positions[index,1] = y
        positions[index,2] = z
    positions = unit.Quantity(positions, unit.angstroms)
    return positions
Ejemplo n.º 2
0
    def begin(self):

        omegaOpts = oeomega.OEOmegaOptions()
        omega = oeomega.OEOmega(omegaOpts)

        omega = oeomega.OEOmega()
        omega.SetIncludeInput(False)
        omega.SetCanonOrder(False)
        omega.SetSampleHydrogens(True)
        omega.SetStrictStereo(False)  # JDC
        omega.SetMaxSearchTime(
            self.args.max_search_time)  # maximum omega search time
        omega.SetEnergyWindow(self.args.energy_window)
        omega.SetMaxConfs(self.args.max_confs)
        omega.SetRMSThreshold(1.0)
        self.omega = omega
Ejemplo n.º 3
0
def create_molecule(iupac_name):
    """
    Create an OEMol molecule from an IUPAC name.

    Parameters
    ----------
    iupac_name : str
        The IUPAC name of the molecule to be created.

    Returns
    -------
    molecule : openeye.oechem.OEMol
        A molecule with AM1-BCC charges.

    """

    molecule = gaff2xml.openeye.iupac_to_oemol(iupac_name)

    # Assign AM1-BCC charges using canonical scheme.
    # TODO: Replace wit updated gaff2xml scheme.
    molecule = assign_am1bcc_charges(molecule)

    # Assign conformations.
    from openeye import oeomega
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega(molecule)

    return molecule
Ejemplo n.º 4
0
def test_oemol_nhfcl():
    """Test coordinates for NHFCl read in as OEMol."""

    import openeye.oechem as oechem
    import openeye.oeomega as oeomega
    # coordinates for N, F, H, Cl respectively
    # generated after minimization with improper phase of 150 degrees
    coordlist = [
        0.155, -0.088, -0.496, -1.054, -0.776, -0.340, -0.025, 0.906, -0.516,
        1.689, -0.635, -1.263
    ]
    # create OEMol
    mol = oechem.OEMol()
    oechem.OESmilesToMol(mol, 'FNCl')
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega.SetIncludeInput(False)
    omega.SetStrictStereo(False)
    status = omega(mol)
    oechem.OETriposAtomTypes(mol)
    oechem.OETriposAtomNames(mol)
    oechem.OEAddExplicitHydrogens(mol)
    # set provided coordinates
    mol.SetCoords(oechem.OEFloatArray(coordlist))
    # calculate and check improper angle
    crds, names = find_improper_angles(mol)
    ang = calc_improper_angle(crds[0][0], crds[0][1], crds[0][2], crds[0][3])
    if abs(ang - 15.0) > 0.1 and abs(ang - 165.0) > 0.1:
        raise Exception(
            "Error calculating improper of test OEMol. Calculated {} degrees, but should be 15 or 165 degrees."
            .format(ang))
Ejemplo n.º 5
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
Ejemplo n.º 6
0
def createOEMolFromSMILES(smiles='CC', title='MOL'):
    """
    Generate an oemol with a geometry
    """
    from openeye import oechem, oeiupac, oeomega

    # Create molecule
    mol = oechem.OEMol()
    oechem.OESmilesToMol(mol, smiles)

    # Set title.
    mol.SetTitle(title)

    # Assign aromaticity and hydrogens.
    oechem.OEAssignAromaticFlags(mol, oechem.OEAroModelOpenEye)
    oechem.OEAddExplicitHydrogens(mol)

    # Create atom names.
    oechem.OETriposAtomNames(mol)

    # Assign geometry
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega.SetIncludeInput(False)
    omega.SetStrictStereo(True)
    omega(mol)

    return mol
Ejemplo n.º 7
0
def prep_structure(rdmol):
    mb = Chem.MolToMolBlock(rdmol)
    ims = oechem.oemolistream()
    ims.SetFormat(oechem.OEFormat_SDF)
    ims.openstring(mb)

    for buf_mol in ims.GetOEMols():
        oemol = oechem.OEMol(buf_mol)

    omega = oeomega.OEOmega()
    # omega.SetIncludeInput(True)
    omega.SetMaxSearchTime(30)
    omega.SetCanonOrder(False)
    omega.SetSampleHydrogens(True)
    eWindow = 15.0
    omega.SetEnergyWindow(eWindow)
    # omega.SetMaxConfs(800)
    omega.SetMaxConfs(400)
    omega.SetRMSThreshold(1.0)

    if omega(oemol):
        result = oequacpac.OEAssignCharges(oemol,
                                           oequacpac.OEAM1BCCELF10Charges())
        if result is False:
            return None
        else:
            charges = []
            for index, atom in enumerate(oemol.GetAtoms()):
                q = atom.GetPartialCharge() * np.sqrt(ONE_4PI_EPS0)
                charges.append(q)
            return charges
    else:
        return None
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def __init__(self, prefix: str, ref_file: str, **kwargs):
        """
        Shape alignment on generated molecules to a reference molecule
        :param prefix: Name (to help keep track metrics, if using a scoring function class more than once)
        :param ref_file: Path to reference file to overlay query to (.pdb)
        :param return_best_overlay: Whether to also return best overlay (for use with docking)
        :param kwargs: Ignored
        """

        self.prefix = prefix.replace(" ", "_")
        self.rocs_metrics = [
            'GetColorScore', 'GetColorTanimoto', 'GetColorTversky',
            'GetComboScore', 'GetFitColorTversky', 'GetFitSelfColor',
            'GetFitSelfOverlap', 'GetFitTversky', 'GetFitTverskyCombo',
            'GetOverlap', 'GetRefColorTversky', 'GetRefSelfColor',
            'GetRefSelfOverlap', 'GetRefTversky', 'GetRefTverskyCombo',
            'GetShapeTanimoto', 'GetTanimoto', 'GetTanimotoCombo',
            'GetTversky', 'GetTverskyCombo'
        ]
        self.ref_file = ref_file
        self.refmol = oechem.OEMol()
        ifs = oechem.oemolistream(self.ref_file)  # Set up input file stream
        oechem.OEReadMolecule(ifs, self.refmol)  # Read ifs to empty mol object
        self.fitmol = None
        self.rocs_results = None
        self.best_overlay = None

        omegaOpts = oeomega.OEOmegaOptions()
        omegaOpts.SetStrictStereo(False)
        omegaOpts.SetMaxSearchTime(1.0)
        self.omega = oeomega.OEOmega(omegaOpts)
Ejemplo n.º 10
0
def prep_structure(rdmol):
    oemol = convert_to_oe(rdmol)
    omega = oeomega.OEOmega()
    # omega.SetIncludeInput(True)
    omega.SetMaxSearchTime(30)
    omega.SetCanonOrder(False)
    omega.SetSampleHydrogens(True)
    eWindow = 15.0
    omega.SetEnergyWindow(eWindow)
    # omega.SetMaxConfs(800)
    omega.SetMaxConfs(400)
    omega.SetRMSThreshold(1.0)

    if omega(oemol):
        result = oequacpac.OEAssignCharges(oemol,
                                           oequacpac.OEAM1BCCELF10Charges())
        if result is False:
            return None
        else:
            charges = []
            for index, atom in enumerate(oemol.GetAtoms()):
                q = atom.GetPartialCharge() * np.sqrt(ONE_4PI_EPS0)
                charges.append(q)
            return charges
    else:
        return None
Ejemplo n.º 11
0
def configure_omega(library,
                    rotor_predicate,
                    rms_cutoff,
                    energy_window,
                    num_conformers=MAX_CONFS):
    opts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)
    opts.SetEnumRing(False)
    opts.SetEnumNitrogen(oeomega.OENitrogenEnumeration_Off)
    opts.SetSampleHydrogens(True)
    opts.SetRotorPredicate(rotor_predicate)
    opts.SetIncludeInput(False)

    opts.SetEnergyWindow(energy_window)
    opts.SetMaxConfs(num_conformers)
    opts.SetRMSThreshold(rms_cutoff)

    conf_sampler = oeomega.OEOmega(opts)
    conf_sampler.SetCanonOrder(False)
    torlib = conf_sampler.GetTorLib()

    # torlib.ClearTorsionLibrary()
    for rule in library:
        if not torlib.AddTorsionRule(rule):
            oechem.OEThrow.Fatal('Failed to add torsion rule: {}'.format(rule))
    conf_sampler.SetTorLib(torlib)

    return conf_sampler
Ejemplo n.º 12
0
def create_molecule(name, filename):
    # Open output file.
    ofs = oechem.oemolostream()
    ofs.open(filename)

    # Create molecule.
    mol = oechem.OEMol()

    # Speculatively reorder CAS permuted index names
    str = oeiupac.OEReorderIndexName(name)
    if len(str) == 0:
        str = name

    done = oeiupac.OEParseIUPACName(mol, str)

    # Create conformation.
    omega = oeomega.OEOmega()
    omega.SetIncludeInput(False)  # don't include input
    omega.SetMaxConfs(1)  # set maximum number of conformations to 1
    omega(mol)

    # Set molecule name
    mol.SetTitle(name)

    # Write molecule.
    oechem.OEWriteMolecule(ofs, mol)

    # Close stream.
    ofs.close()

    return
Ejemplo n.º 13
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
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
Ejemplo n.º 15
0
def createOEMolFromIUPAC(iupac_name='bosutinib'):
    from openeye import oechem, oeiupac, oeomega

    # Create molecule.
    mol = oechem.OEMol()
    oeiupac.OEParseIUPACName(mol, iupac_name)
    mol.SetTitle(iupac_name)

    # Assign aromaticity and hydrogens.
    oechem.OEAssignAromaticFlags(mol, oechem.OEAroModelOpenEye)
    oechem.OEAddExplicitHydrogens(mol)

    # Create atom names.
    oechem.OETriposAtomNames(mol)

    # Create bond types
    oechem.OETriposBondTypeNames(mol)

    # Assign geometry
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega.SetIncludeInput(False)
    omega.SetStrictStereo(True)
    omega(mol)

    return mol
Ejemplo n.º 16
0
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
Ejemplo n.º 17
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
Ejemplo n.º 18
0
def FromMol(mol, use_flipper=True, num_sterocenters=12, force_flipper=False):
    """
    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.SetMaxConfRange("200,800")
    omegaOpts.SetRangeIncrement(8)
    omegaOpts.SetMaxSearchTime(30)
    omega = oeomega.OEOmega(omegaOpts)

    out_conf = []

    for enantiomer in oeomega.OEFlipper(mol.GetActive(), num_sterocenters,
                                        force_flipper):
        enantiomer = oechem.OEMol(enantiomer)
        ret_code = omega.Build(enantiomer)
        if ret_code == oeomega.OEOmegaReturnCode_Success:
            out_conf.append(enantiomer)

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

    return out_conf
Ejemplo n.º 19
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)
Ejemplo n.º 20
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.OEOmegaOptions()
    omega = oeomega.OEOmega(omegaOpts)

    for mol in ifs.GetOEMols():
        oechem.OEThrow.Info("Title: %s" % mol.GetTitle())

        for enantiomer in oeomega.OEFlipper(mol.GetActive(), 12, True):
            enantiomer = oechem.OEMol(enantiomer)
            ret_code = omega.Build(enantiomer)
            if ret_code == oeomega.OEOmegaReturnCode_Success:
                oechem.OEWriteMolecule(ofs, enantiomer)
            else:
                oechem.OEThrow.Warning(
                    "%s: %s" %
                    (enantiomer.GetTitle(), oeomega.OEGetOmegaError(ret_code)))

    return 0
Ejemplo n.º 21
0
def generate_confs(mol):
    """
    Generate conformers of molecule from its SMILES string.

    Parameters
    ----------
    mol : OEChem molecule

    Returns
    -------
    molWithConfs : OEChem molecule with omega-generated conformers

    """
    molWithConfs = oechem.OEMol(mol)
    omega = oeomega.OEOmega()
    maxConfs = 0
    omega.SetMaxConfs(maxConfs)
    omega.SetStrictStereo(False)
    omega.SetSampleHydrogens(True)
    omega.SetEnumNitrogen(oeomega.OENitrogenEnumeration_All)
    if not omega(molWithConfs):
        print("omega failed on %s" % mol.GetTitle())
        return None
    else:
        return molWithConfs
Ejemplo n.º 22
0
def main(argv=[__name__]):

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

    ofs = oechem.oemolostream()
    if not ofs.open("lig.oeb.gz"):  #output: OEBinary Format
        oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])

    omegaOpts = oeomega.OEOmegaOptions()  #Parameters
    omegaOpts.SetMaxConfs(800)
    omegaOpts.SetCanonOrder(False)
    omegaOpts.SetSampleHydrogens(True)
    omegaOpts.SetEnergyWindow(15.0)
    omegaOpts.SetRMSThreshold(1.0)
    omegaOpts.SetStrictStereo(True)
    omegaOpts.SetRangeIncrement(8)
    omega = oeomega.OEOmega(omegaOpts)

    for mol in ifs.GetOEMols():
        oechem.OEThrow.Info("Title: %s" % mol.GetTitle())
        if omega(mol):
            oechem.OEWriteMolecule(ofs, mol)

    return 0
def dock_molecules_to_receptor(receptor_filename):
    """
    Dock the specified molecules, writing out to specified file

    Parameters
    ----------
    receptor_filename : str
        Receptor .oeb.gz filename
    fragment : str
        The fragment name to dock to

    """
    import os

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

    if not oedocking.OEReceptorHasBoundLigand(receptor):
        raise Exception("Receptor does not have bound ligand")

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

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

    # Dock molecules
    docked_molecules = list()
    for mol in molecules:
        dockedMol = oechem.OEGraphMol()

        # Expand conformers
        omega.Build(mol)

        # Dock molecule
        #print(f'Docking {mol.NumConfs()} conformers...')
        retCode = dock.DockMultiConformerMolecule(dockedMol, mol)
        if (retCode != oedocking.OEDockingReturnCode_Success):
            print("Docking Failed with error code " + oedocking.OEDockingReturnCodeGetName(retCode))
            continue

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

        docked_molecules.append( oechem.OEMol(dockedMol) )

    return docked_molecules
Ejemplo n.º 24
0
def create_molecule_from_smiles(smiles):
    """
    Create an ``OEMol`` molecule from a smiles pattern.

    .. todo:: Replace with the toolkit function when finished.

    Parameters
    ----------
    smiles : str
        Smiles pattern

    Returns
    -------
    molecule : OEMol
        OEMol with 3D coordinates, but no charges
     """

    from openeye import oechem, oeomega

    # Check cache
    if smiles in _cached_molecules:
        return copy.deepcopy(_cached_molecules[smiles])

    # Create molecule from smiles.
    molecule = oechem.OEMol()
    parse_smiles_options = oechem.OEParseSmilesOptions(quiet=True)

    if not oechem.OEParseSmiles(molecule, smiles, parse_smiles_options):

        logging.warning('Could not parse SMILES: ' + smiles)
        return False

    # Normalize molecule
    oechem.OEAssignAromaticFlags(molecule, oechem.OEAroModelOpenEye)
    oechem.OEAddExplicitHydrogens(molecule)
    # oechem.OETriposAtomNames(molecule)

    # Create configuration
    omega = oeomega.OEOmega()

    omega.SetMaxConfs(1)
    omega.SetIncludeInput(False)
    omega.SetCanonOrder(False)
    omega.SetSampleHydrogens(True)
    omega.SetStrictStereo(True)
    omega.SetStrictAtomTypes(False)

    status = omega(molecule)

    if not status:

        logging.warning('Could not generate a conformer for ' + smiles)
        return False

    _cached_molecules[smiles] = molecule

    return molecule
Ejemplo n.º 25
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
Ejemplo n.º 26
0
 def __init__(self, receptor: utils.FilePath):
     self.receptor_file = receptor
     omegaOpts = oeomega.OEOmegaOptions()
     omegaOpts.SetStrictStereo(False)
     self.omega = oeomega.OEOmega(omegaOpts)
     oechem.OEThrow.SetLevel(10000)
     oereceptor = oechem.OEGraphMol()
     oedocking.OEReadReceptorFile(oereceptor, self.receptor_file)
     self.dock = oedocking.OEDock()
     self.dock.Initialize(oereceptor)
Ejemplo n.º 27
0
def smiles_to_oemol(smiles, title='MOL', max_confs=1):
    """
    Generate an oemol from a SMILES string

    Parameters
    ----------
    smiles : str
        SMILES string of molecule
    title : str, default 'MOL'
        title of OEMol molecule
    max_confs : int, default 1
        maximum number of conformers to generate
    Returns
    -------
    molecule : openeye.oechem.OEMol
        OEMol object of the molecule
    """
    from openeye import oeomega

    # Create molecule
    molecule = oechem.OEMol()
    oechem.OESmilesToMol(molecule, smiles)

    # create unique atom names
    if len([atom.GetName() for atom in molecule.GetAtoms()]) > len(
            set([atom.GetName() for atom in molecule.GetAtoms()])):
        # the atom names are not unique
        molecule = generate_unique_atom_names(molecule)
    else:
        pass

    # Set title.
    molecule.SetTitle(title)

    # Assign aromaticity and hydrogens.
    oechem.OEAssignAromaticFlags(molecule, oechem.OEAroModelOpenEye)
    oechem.OEAssignHybridization(molecule)
    oechem.OEAddExplicitHydrogens(molecule)
    oechem.OEPerceiveChiral(molecule)

    # Create atom names.
    oechem.OETriposAtomNames(molecule)
    oechem.OETriposBondTypeNames(molecule)

    # perceive chirality before attempting omega geometry proposal
    assert oechem.OEPerceiveChiral(molecule), f"chirality perception failed"

    # Assign geometry
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(max_confs)
    omega.SetIncludeInput(False)
    omega.SetStrictStereo(True)

    omega(molecule)
    return molecule
Ejemplo n.º 28
0
def fit_smiles_molecule(mol: oechem.OEMol):
    """Modifies the given molecule in-place to give it 3D coordinates"""
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega.SetIncludeInput(True)
    omega.SetCanonOrder(True)
    omega.SetSampleHydrogens(True)
    omega.SetStrictStereo(True)
    omega.SetStrictAtomTypes(True)
    omega.SetIncludeInput(False)
    omega(mol)
Ejemplo n.º 29
0
def generate_initial_molecule(mol_smiles):
    """
    Generate an oemol with a geometry
    """
    mol = oechem.OEMol()
    oechem.OESmilesToMol(mol, mol_smiles)
    oechem.OEAddExplicitHydrogens(mol)
    omega = oeomega.OEOmega()
    omega.SetMaxConfs(1)
    omega(mol)
    return mol
Ejemplo n.º 30
0
def _docking_internal(receptor: oechem.OEGraphMol,
                      bound_ligand: oechem.OEGraphMol, ligand_string):
    """
    Internal method for docking to a receptor given a bound ligand and ligand to dock to

    Parameters
    ----------
    receptor: oechem.OEGraphMol, required
        An oechem receptor to dock to

    bound_ligand: oechem.OEGraphMol, required
        The ligand bound to the current receptor pocket

    docking_ligand: oechem.OEGraphMol, required
        The ligand to dock.

    Returns
    -------
    An oechem molecule with coordinates of its docking

    """
    # Create posit config
    oedocking.OEReceptorSetBoundLigand(receptor, bound_ligand)
    poser = oedocking.OEHybrid(oedocking.OEDockMethod_Hybrid2,
                               oedocking.OESearchResolution_High)
    poser.Initialize(receptor)

    # Create multiple conformations
    omegaOpts = oeomega.OEOmegaOptions()
    omegaOpts.SetMaxConfs(1000)
    omega_driver = oeomega.OEOmega(omegaOpts)
    conformer_docking = oechem.OEMol()  # type: OEMol
    oechem.OESmilesToMol(conformer_docking, ligand_string)
    oechem.OEAddExplicitHydrogens(conformer_docking)
    print(conformer_docking.NumAtoms())

    if not omega_driver(conformer_docking):
        single_sdf = tempfile.NamedTemporaryFile(suffix=".sdf")
        double_sdf = tempfile.NamedTemporaryFile(suffix=".sdf")
        smiles = ligand_string
        subprocess.run(
            "obabel -:'%s' -O %s --gen3d; obabel %s -O %s --confab --conf = 100"
            % (smiles, single_sdf.name, single_sdf.name, double_sdf.name),
            shell=True)
        ins = oechem.oemolistream()
        ins.SetConfTest(oechem.OEOmegaConfTest())
        ins.open(double_sdf.name)
        oechem.OEReadMolecule(ins, conformer_docking)

    # Dock and get top conformer
    posed_ligand = oechem.OEGraphMol()  # type: OEGraphMol
    poser.DockMultiConformerMolecule(posed_ligand, conformer_docking)
    return posed_ligand