Esempio n. 1
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 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
Esempio n. 3
0
    def begin(self):
        receptor = oechem.OEGraphMol()
        self.args.receptor = utils.download_dataset_to_file(self.args.receptor)
        if not oedocking.OEReadReceptorFile(receptor, str(self.args.receptor)):
            raise Exception("Unable to read receptor from {0}".format(self.args.receptor))

        # Initialize Docking
        dock_method = oedocking.OEDockMethod_Hybrid
        if not oedocking.OEReceptorHasBoundLigand(receptor):
            oechem.OEThrow.Warning("No bound ligand, switching OEDockMethod to ChemGauss4.")
            dock_method = oedocking.OEDockMethod_Chemgauss4
        dock_resolution = oedocking.OESearchResolution_Default
        self.sdtag = oedocking.OEDockMethodGetName(dock_method)
        self.dock = oedocking.OEDock(dock_method, dock_resolution)
        if not self.dock.Initialize(receptor):
            raise Exception("Unable to initialize Docking with {0}".format(self.args.receptor))
Esempio n. 4
0
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData)
    # @ <SNIPPET-DOCK-MOLECULES-CONFIGURE>
    oedocking.OEDockMethodConfigure(itf, "-method")
    oedocking.OESearchResolutionConfigure(itf, "-resolution")
    # @ </SNIPPET-DOCK-MOLECULES-CONFIGURE>
    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    imstr = oechem.oemolistream(itf.GetString("-in"))
    omstr = oechem.oemolostream(itf.GetString("-out"))

    receptor = oechem.OEGraphMol()
    if not oedocking.OEReadReceptorFile(receptor, itf.GetString("-receptor")):
        oechem.OEThrow.Fatal("Unable to read receptor")

    # @ <SNIPPET-DOCK-MOLECULES-GET-VALUE>
    dockMethod = oedocking.OEDockMethodGetValue(itf, "-method")
    dockResolution = oedocking.OESearchResolutionGetValue(itf, "-resolution")
    # @ </SNIPPET-DOCK-MOLECULES-GET-VALUE>
    # @ <SNIPPET-DOCK-MOLECULES-SETUP>
    dock = oedocking.OEDock(dockMethod, dockResolution)
    # @ </SNIPPET-DOCK-MOLECULES-SETUP>
    # @ <SNIPPET-DOCK-MOLECULES-INITIALIZE>
    dock.Initialize(receptor)
    # @ </SNIPPET-DOCK-MOLECULES-INITIALIZE>

    for mcmol in imstr.GetOEMols():
        print("docking", mcmol.GetTitle())
        dockedMol = oechem.OEGraphMol()
        # @ <SNIPPET-DOCK-MOLECULES-DOCK>
        retCode = dock.DockMultiConformerMolecule(dockedMol, mcmol)
        if (retCode != oedocking.OEDockingReturnCode_Success):
            oechem.OEThrow.Fatal("Docking Failed with error code " + oedocking.OEDockingReturnCodeGetName(retCode))

        # @ </SNIPPET-DOCK-MOLECULES-DOCK>
        sdtag = oedocking.OEDockMethodGetName(dockMethod)
        # @ <SNIPPET-DOCK-MOLECULES-ASSIGN-SCORE>
        oedocking.OESetSDScore(dockedMol, dock, sdtag)
        # @ </SNIPPET-DOCK-MOLECULES-ASSIGN-SCORE>
        # @ <SNIPPET-DOCK-MOLECULES-ANNOTATE>
        dock.AnnotatePose(dockedMol)
        # @ </SNIPPET-DOCK-MOLECULES-ANNOTATE>
        oechem.OEWriteMolecule(omstr, dockedMol)

    return 0
def main(argv=[__name__]):
    itf = oechem.OEInterface()
    oedocking.OEDockMethodConfigure(itf, "-method")
    oedocking.OESearchResolutionConfigure(itf, "-resolution")
    receptors = []
    path = "receptor_oebs/*.oeb"  #input: receptor oebs
    files = glob.glob(path)
    for i in files:
        receptor = oechem.OEGraphMol()
        if not oedocking.OEReadReceptorFile(receptor, i):
            oechem.OEThrow.Fatal("Unable to read receptor from %s" % i)
        receptors.append(receptor)
    dockMethod = 5  #Set scoring function (5=Chemscore)
    dockResolution = 2  #set search resolution (2=Standard)
    dock = oedocking.OEDock(
        dockMethod,
        dockResolution)  #Selecting exhaustive search and scoring functions
    for receptor_idx, receptor in enumerate(receptors):
        Centroid_number = files[receptor_idx][-5:-4]
        omstr = oechem.oemolostream("Docking_Results/Receptor_%s.oeb" %
                                    (Centroid_number))
        dock.Initialize(receptor)  #initialize with receptor object
        imstr = oechem.oemolistream("lig.oeb.gz")
        for mcmol in imstr.GetOEMols():
            print("docking", mcmol.GetTitle())
            dockedMol = oechem.OEMol()
            dock.DockMultiConformerMolecule(dockedMol, mcmol)  #Docking
            sdtag = oedocking.OEDockMethodGetName(dockMethod)
            oedocking.OESetSDScore(dockedMol, dock, sdtag)
            dock.AnnotatePose(dockedMol)
            oechem.OEWriteMolecule(omstr, dockedMol)
            g = open("Docking_Results/score.txt", "a+")  #write scores to file
            g.write(
                str(files[receptor_idx]) + " " + str(mcmol.GetTitle()) + " " +
                str(oechem.OEMCMolBase.GetEnergy(dockedMol)) + "\r\n")
            g.close()
    return 0
Esempio n. 6
0
    def _execute(self, directory, available_resources):

        import mdtraj
        from openeye import oechem, oedocking
        from simtk import unit as simtk_unit

        if (len(self.ligand_substance.components) != 1
                or self.ligand_substance.components[0].role !=
                Component.Role.Ligand):

            raise ValueError(
                "The ligand substance must contain a single ligand component.")

        logger.info("Initializing the receptor molecule.")
        receptor_molecule = self._create_receptor()

        logger.info("Initializing the ligand molecule.")
        ligand_molecule = self._create_ligand()

        logger.info("Initializing the docking object.")

        # Dock the ligand to the receptor.
        dock = oedocking.OEDock()
        dock.Initialize(receptor_molecule)

        docked_ligand = oechem.OEGraphMol()

        logger.info("Performing the docking.")

        status = dock.DockMultiConformerMolecule(docked_ligand,
                                                 ligand_molecule)

        if status != oedocking.OEDockingReturnCode_Success:
            raise RuntimeError("The ligand could not be successfully docked", )

        docking_method = oedocking.OEDockMethodGetName(
            oedocking.OEDockMethod_Default)
        oedocking.OESetSDScore(docked_ligand, dock, docking_method)

        dock.AnnotatePose(docked_ligand)

        self.docked_ligand_coordinate_path = path.join(directory, "ligand.pdb")

        output_stream = oechem.oemolostream(self.docked_ligand_coordinate_path)
        oechem.OEWriteMolecule(output_stream, docked_ligand)
        output_stream.close()

        receptor_pdb_path = path.join(directory, "receptor.pdb")

        output_stream = oechem.oemolostream(receptor_pdb_path)
        oechem.OEWriteMolecule(output_stream, receptor_molecule)
        output_stream.close()

        ligand_trajectory = mdtraj.load(self.docked_ligand_coordinate_path)

        ligand_residue = ligand_trajectory.topology.residue(0)
        ligand_residue.name = self.ligand_residue_name

        # Save the ligand file with the correct residue name.
        ligand_trajectory.save(self.docked_ligand_coordinate_path)

        receptor_trajectory = mdtraj.load(receptor_pdb_path)

        receptor_residue = receptor_trajectory.topology.residue(0)
        receptor_residue.name = self.receptor_residue_name

        # Create a merged ligand-receptor topology.
        complex_topology = ligand_trajectory.topology.copy()

        atom_mapping = {}

        new_residue = complex_topology.add_residue(receptor_residue.name,
                                                   complex_topology.chain(0))

        for receptor_atom in receptor_residue.atoms:

            new_atom = complex_topology.add_atom(
                receptor_atom.name,
                receptor_atom.element,
                new_residue,
                serial=receptor_atom.serial,
            )

            atom_mapping[receptor_atom] = new_atom

        for bond in receptor_trajectory.topology.bonds:

            complex_topology.add_bond(
                atom_mapping[bond[0]],
                atom_mapping[bond[1]],
                type=bond.type,
                order=bond.order,
            )

        complex_positions = []

        complex_positions.extend(
            ligand_trajectory.openmm_positions(0).value_in_unit(
                simtk_unit.angstrom))
        complex_positions.extend(
            receptor_trajectory.openmm_positions(0).value_in_unit(
                simtk_unit.angstrom))

        complex_positions *= simtk_unit.angstrom

        self.docked_complex_coordinate_path = path.join(
            directory, "complex.pdb")

        with open(self.docked_complex_coordinate_path, "w+") as file:
            app.PDBFile.writeFile(complex_topology.to_openmm(),
                                  complex_positions, file)
def dock_molecule_to_receptor(molecule, receptor_filename, covalent=False):
    """
    Dock the specified molecules, writing out to specified file

    Parameters
    ----------
    molecule : oechem.OEMol
        The molecule to dock
    receptor_filename : str
        Receptor to dock to
    covalent : bool, optional, default=False
        If True, try to place covalent warheads in proximity to CYS145

    Returns
    -------
    docked_molecule : openeye.oechem.OEMol
        Returns the best tautomer/protomer in docked geometry, annotated with docking score
        None is returned if no viable docked pose found
    """
    import os

    # Extract the fragment name for the receptor
    fragment = extract_fragment_from_filename(receptor_filename)

    # 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")
    #print(f'Receptor has {receptor.NumAtoms()} atoms')

    if not oedocking.OEReceptorHasBoundLigand(receptor):
        raise Exception("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)

    # Add covalent restraint if specified
    warheads_found = find_warheads(molecule)
    if covalent and len(warheads_found) > 0:
        warheads_found = set(warheads_found.keys())

        # Initialize covalent constraints
        customConstraints = oedocking.OEReceptorGetCustomConstraints(receptor)

        # Find CYS145 SG atom
        hv = oechem.OEHierView(receptor)
        hres = hv.GetResidue("A", "CYS", 145)
        proteinHeavyAtom = None
        for atom in hres.GetAtoms():
            if atom.GetName().strip() == 'SG':
                proteinHeavyAtom = atom
                break
        if proteinHeavyAtom is None:
            raise Exception('Could not find CYS145 SG')

        # Add the constraint
        feature = customConstraints.AddFeature()
        feature.SetFeatureName("CYS145 proximity")
        for warhead_type in warheads_found:
            smarts = covalent_warhead_smarts[warhead_type]
            print(f'Adding constraint for SMARTS pattern {smarts}')
            feature.AddSmarts(smarts)
        sphereRadius = 4.0 # Angstroms
        sphereCenter = oechem.OEFloatArray(3)
        receptor.GetCoords(proteinHeavyAtom, sphereCenter)
        sphere = feature.AddSphere()
        sphere.SetRad(sphereRadius)
        sphere.SetCenter(sphereCenter[0], sphereCenter[1], sphereCenter[2])
        oedocking.OEReceptorSetCustomConstraints(receptor, customConstraints)

    # Enumerate tautomers
    from openeye import oequacpac
    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
    tautomers = [ oechem.OEMol(tautomer) for tautomer in oequacpac.OEGetReasonableTautomers(molecule, tautomer_options, pKa_norm) ]

    # Set up Omega
    #print('Expanding conformers...')
    from openeye import oeomega
    #omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)
    omegaOpts = oeomega.OEOmegaOptions()
    #omegaOpts.SetMaxConfs(5000)
    omegaOpts.SetMaxSearchTime(60.0) # time out
    omega = oeomega.OEOmega(omegaOpts)
    omega.SetStrictStereo(False) # enumerate sterochemistry if uncertain

    # Dock tautomers
    docked_molecules = list()
    from tqdm import tqdm
    for mol in tautomers:
        dockedMol = oechem.OEGraphMol()

        # Expand conformers
        omega.Build(mol)

        # Dock molecule
        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)
        oechem.OESetSDData(dockedMol, "docked_fragment", fragment)
        dock.AnnotatePose(dockedMol)

        docked_molecules.append( dockedMol.CreateCopy() )

    if len(docked_molecules) == 0:
        return None

    # Select the best-ranked molecule and pose
    # Note that this ignores protonation state and tautomer penalties
    docked_molecules.sort(key=score)
    best_molecule = docked_molecules[0]

    return best_molecule
Esempio n. 8
0
def hybrid_docking(receptor_path,
                   molecules_path,
                   docked_molecules_path,
                   n_poses=10):
    """Automated hybrid docking of small molecules to a receptor.

    Parameters
    ----------
    receptor_path : str
        Path to PDB file containing receptor and reference ligand, or pre-prepared receptor for docking
    molecules_path : str
        Path to file containing one or more molecules (in OpenEye readable format) to be docked.
        (For example, list of SMILES)
    docked_molecules_path : str
        Path to output file to be created to contain docked molecules
        Uses OpenEye recognized file extension, such as .mol2 or .sdf
    n_poses : int, optional, default=1
        Number of docked poses to generate
    receptor_filename : str, optional, default=None
        If not None, the pre-prepared receptor is loaded

    TODO: How can this API be improved?

    """
    from .docking import create_receptor, load_receptor, pose_molecule
    from openeye import oedocking, oechem
    #import openmoltools as moltools # TODO: Bring these methods into this module

    # Try to load pre-prepared receptor from specified file
    receptor = oechem.OEGraphMol()
    print('Attempting to load receptor from {}...'.format(receptor_path))
    if not oedocking.OEReadReceptorFile(receptor, receptor_path):
        # Load complex of receptor and reference ligand
        complex_istream = oechem.oemolistream(receptor_path)
        complex = oechem.OEGraphMol()
        oechem.OEReadMolecule(complex_istream, complex)

        # Attempt to split into components and build receptor based on reference ligand
        print('Attempting to split complex into components...')
        ligand = oechem.OEGraphMol()
        protein = oechem.OEGraphMol()
        water = oechem.OEGraphMol()
        other = oechem.OEGraphMol()
        if oechem.OESplitMolComplex(ligand, protein, water, other, complex):
            # Create receptor using bound ligand reference
            print('Creating receptor using reference ligand...')
            oedocking.OEMakeReceptor(receptor, protein, ligand)
            # TODO: We can store prepared receptor file if desired
            oedocking.OEWriteReceptorFile(
                receptor,
                '/home/guoj1/projects/INSPIRE/kinomodel/kinomodel/data/docking/prepared_receptor.oeb'
            )

        else:
            raise Exception(
                'Could not split specified PDB file {} into receptor and reference ligand'
                .format(receptor_path))

    # Open file for writing docked molecules
    docked_molecules_ostream = oechem.oemolostream(docked_molecules_path)

    # Configure omega
    # From canonical recipe: https://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html
    from openeye import oeomega
    omega = oeomega.OEOmega()
    omega.SetIncludeInput(False)
    omega.SetCanonOrder(False)
    omega.SetSampleHydrogens(True)
    eWindow = 15.0
    omega.SetEnergyWindow(eWindow)
    omega.SetMaxConfs(800)
    omega.SetRMSThreshold(1.0)

    # Dock all molecules requested
    dock_method = oedocking.OEDockMethod_Hybrid2
    dock_resolution = oedocking.OESearchResolution_Standard
    dock = oedocking.OEDock(dock_method, dock_resolution)
    dock.Initialize(receptor)
    molecules_istream = oechem.oemolistream(molecules_path)
    molecule = oechem.OEGraphMol()
    for molecule in molecules_istream.GetOEMols():
        print("docking", molecule.GetTitle())
        #docked_molecules = pose_molecule(receptor, molecule, n_poses=n_poses)
        #molecule = moltools.openeye.get_charges(molecule, keep_confs=10)

        # Generate conformers
        if not omega(molecule):
            continue

        # Apply charges
        from openeye import oequacpac
        oequacpac.OEAssignCharges(molecule, oequacpac.OEAM1BCCELF10Charges())

        # Dock
        docked_molecule = oechem.OEGraphMol()
        dock.DockMultiConformerMolecule(docked_molecule, molecule)
        sdtag = oedocking.OEDockMethodGetName(dock_method)
        oedocking.OESetSDScore(docked_molecule, dock, sdtag)
        dock.AnnotatePose(docked_molecule)
        oechem.OEWriteMolecule(docked_molecules_ostream, docked_molecule)