Beispiel #1
0
def tanimotocombo(ref_mol, query_mol):
    """
    This is the TanimotoCombo function. It takes in two OEMols. 
    It does not matter (for our purposes) which mol is the reference mol and 
    which one is the query mol. The TanimotoCombo distance between the two
    mols is the same no matter which is the reference and which is the query.
    The GetTanimotoCombo() function comes from openeye.
     
    Args:
        ref_mol (oemol) An oemol that has already been read in. 
        query_mol (oemol) Another oemol that has already been read in. 
 
    Returns: 
        res.GetTanimotoCombo() (float) The TanimotoCombo value.
    """
    # Prepare reference molecule for calculation
    # With default options this will remove any explicit
    # hydrogens present and add color atoms
    prep = oeshape.OEOverlapPrep()
    prep.Prep(ref_mol)
    # Get appropriate function to calculate both shape and color
    # By default the OEOverlapFunc contains OEGridShapeFunc for shape
    # and OEExactColorFunc for color
    func = oeshape.OEOverlapFunc()
    func.SetupRef(ref_mol)
    res = oeshape.OEOverlapResults()
    prep.Prep(query_mol)
    func.Overlap(query_mol, res)
    return (res.GetTanimotoCombo())
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <fitfile>" % argv[0])

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

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

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

    # Get appropriate function to calculate both shape and color
    # By default the OEOverlapFunc contains OEGridShapeFunc for shape
    # and OEExactColorFunc for color
    func = oeshape.OEOverlapFunc()
    func.SetupRef(refmol)

    res = oeshape.OEOverlapResults()
    for fitmol in fitfs.GetOEGraphMols():
        prep.Prep(fitmol)
        func.Overlap(fitmol, res)
        print("title: %s  tanimoto combo = %.2f shape tanimoto = %.2f color tanimoto = %.2f" %
              (fitmol.GetTitle(), res.GetTanimotoCombo(),
               res.GetTanimoto(), res.GetColorTanimoto()))
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <fitfile>" % argv[0])

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

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

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

    # Get appropriate function to calculate exact color
    colorFunc = oeshape.OEExactColorFunc()
    colorFunc.SetupRef(refmol)

    res = oeshape.OEOverlapResults()
    fitmol = oechem.OEGraphMol()
    while oechem.OEReadMolecule(fitfs, fitmol):
        prep.Prep(fitmol)
        colorFunc.Overlap(fitmol, res)
        print("title: %s  color score = %.2f" %
              (fitmol.GetTitle(), res.GetColorScore()))
Beispiel #4
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()))
Beispiel #5
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <fitfile>" % argv[0])

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

    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():
        prep.Prep(fitmol)
        score = oeshape.OEBestOverlayScore()
        overlay.BestOverlay(score, fitmol, oeshape.OEHighestTanimoto())
        print(
            "Fit Title: %-4s FitConfIdx: %-4d RefConfIdx: %-4d tanimoto combo: %.2f"
            % (fitmol.GetTitle(), score.GetFitConfIdx(), score.GetRefConfIdx(),
               score.GetTanimotoCombo()))
Beispiel #6
0
 def __init__(self, refmol, ifs):
     Thread.__init__(self)
     self._prep = oeshape.OEOverlapPrep()
     self._prep.Prep(refmol)
     self._overlay = oeshape.OEMultiRefOverlay()
     self._overlay.SetupRef(refmol)
     self._ifs = ifs
Beispiel #7
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <molfile> <queryfile>" % sys.argv[0])

    molfs = oechem.oemolistream(sys.argv[1])
    mol = oechem.OEGraphMol()
    oechem.OEReadMolecule(molfs, mol)

    if oechem.OEGetFileExtension(sys.argv[2]) != "sq":
        oechem.OEThrow.Fatal(
            "Only can write shape query to .sq output file format")

    # Use OEOverlapPrep to remove hydrogens and add
    # color atoms to the molecule
    prep = oeshape.OEOverlapPrep()
    prep.Prep(mol)

    # Get the color atoms, create gaussians and add them
    # to the shape query
    query = oeshape.OEShapeQuery()
    for atom in oeshape.OEGetColorAtoms(mol):
        coords = oechem.OEFloatArray(3)
        mol.GetCoords(atom, coords)
        gauss = oegrid.OEGaussian(1.0, 1.0, coords,
                                  oeshape.OEGetColorType(atom))
        query.AddColorGaussian(gauss)

    # Remove color atoms from the molecule and add to the query
    oeshape.OERemoveColorAtoms(mol)
    query.SetMolecule(mol)

    oeshape.OEWriteShapeQuery(sys.argv[2], query)
    print("shape query created")
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <fitfile>" % argv[0])

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

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

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

    # Get appropriate function to calculate exact shape
    shapeFunc = oeshape.OEExactShapeFunc()
    shapeFunc.SetupRef(refmol)

    res = oeshape.OEOverlapResults()
    for fitmol in fitfs.GetOEGraphMols():
        prep.Prep(fitmol)
        shapeFunc.Overlap(fitmol, res)
        print("title: %s  exact tanimoto = %.2f" %
              (fitmol.GetTitle(), res.GetTanimoto()))
Beispiel #9
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")
Beispiel #10
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <infile> <csvfile>" % argv[0])

    csvfile = open(argv[2], "w")
    genHeader(sys.argv[1], csvfile)

    prep = oeshape.OEOverlapPrep()
    prep.SetAssignColor(False)
    afs = oechem.oemolistream(argv[1])
    for molA in afs.GetOEMols():
        prep.Prep(molA)
        print(molA.GetTitle())
        for conf in molA.GetConfs():
            oneConf(conf, prep, sys.argv[1], csvfile)
Beispiel #11
0
def overlay_molecules(
    reference_molecule: oechem.OEGraphMol,
    fit_molecule: oechem.OEMol,
    return_overlay: bool = True,
) -> (int, List[oechem.OEGraphMol]):
    """
    Overlay two molecules and calculate TanimotoCombo score.
    Parameters
    ----------
    reference_molecule: oechem.OEGraphMol
        An OpenEye molecule holding the reference molecule for overlay.
    fit_molecule: oechem.OEMol
        An OpenEye multi-conformer molecule holding the fit molecule for overlay.
    return_overlay: bool
        If the best scored overlay of molecules should be returned.
    Returns
    -------
        : int or int and list of oechem.OEGraphMol
        The TanimotoCombo score of the best overlay and the overlay if score_only is set False.
    """
    from openeye import oechem, oeshape

    prep = oeshape.OEOverlapPrep()
    prep.Prep(reference_molecule)

    overlay = oeshape.OEOverlay()
    overlay.SetupRef(reference_molecule)

    prep.Prep(fit_molecule)
    score = oeshape.OEBestOverlayScore()
    overlay.BestOverlay(score, fit_molecule, oeshape.OEHighestTanimoto())
    if not return_overlay:
        return score.GetTanimotoCombo()
    else:
        overlay = [reference_molecule]
        fit_molecule = oechem.OEGraphMol(
            fit_molecule.GetConf(oechem.OEHasConfIdx(score.GetFitConfIdx())))
        score.Transform(fit_molecule)
        overlay.append(fit_molecule)
        return score.GetTanimotoCombo(), overlay
Beispiel #12
0
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <overlayfile>" % argv[0])

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

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

    # Modify ImplicitMillsDean color force field by
    # adding user defined color interactions
    cff = oeshape.OEColorForceField()
    cff.Init(oeshape.OEColorFFType_ImplicitMillsDean)
    cff.ClearInteractions()
    donorType = cff.GetType("donor")
    accepType = cff.GetType("acceptor")
    cff.AddInteraction(donorType, donorType, "gaussian", -1.0, 1.0)
    cff.AddInteraction(accepType, accepType, "gaussian", -1.0, 1.0)

    # Prepare reference molecule for calculation
    # With default options this will add required color atoms
    # Set the modified color force field for addignment
    prep = oeshape.OEOverlapPrep()
    prep.SetColorForceField(cff)
    prep.Prep(refmol)

    # Get appropriate function to calculate exact color
    # Set appropriate options to use the user defined color
    options = oeshape.OEColorOptions()
    options.SetColorForceField(cff)
    colorFunc = oeshape.OEExactColorFunc(options)
    colorFunc.SetupRef(refmol)

    res = oeshape.OEOverlapResults()
    for fitmol in fitfs.GetOEGraphMols():
        prep.Prep(fitmol)
        colorFunc.Overlap(fitmol, res)
        print("Fit Title: %s  Color Tanimoto: %.2f" %
              (fitmol.GetTitle(), res.GetColorTanimoto()))
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <reffile> <fitfile>" % argv[0])

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

    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

        # double loop over results and scores to obtain all scores
        for res in overlay.Overlay(fitmol):
            for score in res.GetScores():
                print(
                    "FitConfIdx: %-4d RefConfIdx: %-4d tanimoto combo: %.2f" %
                    (score.GetFitConfIdx(), score.GetRefConfIdx(),
                     score.GetTanimotoCombo()))
                resCount += 1

        print(resCount, "results returned")
def generate_restricted_conformers(receptor, refmol, mol, core_smarts=None):
    """
    Generate and select a conformer of the specified molecule using the reference molecule

    Parameters
    ----------
    receptor : openeye.oechem.OEGraphMol
        Receptor (already prepped for docking) for identifying optimal pose
    refmol : openeye.oechem.OEGraphMol
        Reference molecule which shares some part in common with the proposed molecule
    mol : openeye.oechem.OEGraphMol
        Molecule whose conformers are to be enumerated
    core_smarts : str, optional, default=None
        If core_smarts is specified, substructure will be extracted using SMARTS.
    """
    from openeye import oechem, oeomega

    # DEBUG: For benzotriazoles, truncate refmol
    core_smarts = 'c1ccc(NC(=O)[C,N]n2nnc3ccccc32)cc1' # prospective
    core_smarts = 'NC(=O)[C,N]n2nnc3ccccc32' # retrospective

    # Get core fragment
    if core_smarts:
        # Truncate refmol to SMARTS if specified
        #print(f'Trunctating using SMARTS {refmol_smarts}')
        ss = oechem.OESubSearch(core_smarts)
        oechem.OEPrepareSearch(refmol, ss)
        for match in ss.Match(refmol):
            core_fragment = oechem.OEGraphMol()
            oechem.OESubsetMol(core_fragment, match)
            break
        #print(f'refmol has {refmol.NumAtoms()} atoms')
    else:
        core_fragment = GetCoreFragment(refmol, [mol])
        oechem.OESuppressHydrogens(core_fragment)
        #print(f'  Core fragment has {core_fragment.NumAtoms()} heavy atoms')
        MIN_CORE_ATOMS = 6
        if core_fragment.NumAtoms() < MIN_CORE_ATOMS:
            return None

    # Create an Omega instance
    #omegaOpts = oeomega.OEOmegaOptions()
    omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)

    # Set the fixed reference molecule
    omegaFixOpts = oeomega.OEConfFixOptions()
    omegaFixOpts.SetFixMaxMatch(10) # allow multiple MCSS matches
    omegaFixOpts.SetFixDeleteH(True) # only use heavy atoms
    omegaFixOpts.SetFixMol(core_fragment)
    #omegaFixOpts.SetFixSmarts(smarts)
    omegaFixOpts.SetFixRMS(0.5)

    atomexpr = oechem.OEExprOpts_Aromaticity | oechem.OEExprOpts_Hybridization
    bondexpr = oechem.OEExprOpts_BondOrder | oechem.OEExprOpts_Aromaticity
    omegaFixOpts.SetAtomExpr(atomexpr)
    omegaFixOpts.SetBondExpr(bondexpr)
    omegaOpts.SetConfFixOptions(omegaFixOpts)

    molBuilderOpts = oeomega.OEMolBuilderOptions()
    molBuilderOpts.SetStrictAtomTypes(False) # don't give up if MMFF types are not found
    omegaOpts.SetMolBuilderOptions(molBuilderOpts)

    omegaOpts.SetWarts(False) # expand molecule title
    omegaOpts.SetStrictStereo(False) # set strict stereochemistry
    omegaOpts.SetIncludeInput(False) # don't include input
    omegaOpts.SetMaxConfs(1000) # generate lots of conformers
    #omegaOpts.SetEnergyWindow(10.0) # allow high energies
    omega = oeomega.OEOmega(omegaOpts)

    from openeye import oequacpac
    if not oequacpac.OEGetReasonableProtomer(mol):
        print('No reasonable protomer found')
        return None

    mol = oechem.OEMol(mol) # multi-conformer molecule

    ret_code = omega.Build(mol)
    if (mol.GetDimension() != 3) or (ret_code != oeomega.OEOmegaReturnCode_Success):
        print(f'Omega failure: {mol.GetDimension()} and {oeomega.OEGetOmegaError(ret_code)}')
        return None

    # Extract poses
    class Pose(object):
        def __init__(self, conformer):
            self.conformer = conformer
            self.clash_score = None
            self.docking_score = None
            self.overlap_score = None

    poses = [ Pose(conf) for conf in mol.GetConfs() ]

    # Score clashes
    bump_check = BumpCheck(receptor)
    for pose in poses:
        pose.clash_score = bump_check.count(pose.conformer)

    # Score docking poses
    from openeye import oedocking
    score = oedocking.OEScore(oedocking.OEScoreType_Chemgauss4)
    score.Initialize(receptor)
    for pose in poses:
        pose.docking_score = score.ScoreLigand(pose.conformer)

    # Compute overlap scores
    from openeye import oeshape
    overlap_prep = oeshape.OEOverlapPrep()
    overlap_prep.Prep(refmol)
    shapeFunc = oeshape.OEExactShapeFunc()
    shapeFunc.SetupRef(refmol)
    oeshape_result = oeshape.OEOverlapResults()
    for pose in poses:
        tmpmol = oechem.OEGraphMol(pose.conformer)
        overlap_prep.Prep(tmpmol)
        shapeFunc.Overlap(tmpmol, oeshape_result)
        pose.overlap_score = oeshape_result.GetRefTversky()

    # Filter poses based on top 10% of overlap
    poses = sorted(poses, key= lambda pose : pose.overlap_score)
    poses = poses[int(0.9*len(poses)):]

    # Select the best docking score
    import numpy as np
    poses = sorted(poses, key=lambda pose : pose.docking_score)
    pose = poses[0]
    mol.SetActive(pose.conformer)
    oechem.OESetSDData(mol, 'clash_score', str(pose.clash_score))
    oechem.OESetSDData(mol, 'docking_score', str(pose.docking_score))
    oechem.OESetSDData(mol, 'overlap_score', str(pose.overlap_score))

    # Convert to single-conformer molecule
    mol = oechem.OEGraphMol(mol)

    return mol
    for filename in tqdm(filenames):
        with oechem.oemolistream(filename) as ifs:
            fragment = oechem.OEGraphMol()
            while oechem.OEReadMolecule(ifs, fragment):
                oechem.OESuppressHydrogens(fragment)
                match = re.search('Mpro-(?P<fragment_name>x\d\d\d\d)-ligand.mol2', filename)
                fragment_name = match.group('fragment_name')
                # Set fragment name as title
                fragment.SetTitle(fragment_name)

                # Store it
                fragments[fragment_name] = fragment.CreateCopy()
    print(f'{len(fragments)} fragments loaded.')

    # Get appropriate function to calculate analytic shape
    prep = oeshape.OEOverlapPrep()
    result = oeshape.OEOverlapResults()
    fragment_func = oeshape.OEExactColorFunc()
    print('Computing overlap scores...')
    for molecule in tqdm(docked_molecules):
        # Compute overlap with merged query
        refmol = molecule.CreateCopy()
        prep.Prep(refmol)
        fragment_func.SetupRef(refmol)
        volume = oeshape.OECalcVolume(molecule)

        # Compute overlaps
        overlapping_fragments = list()
        fragment_overlap_scores = dict()
        score = 0.0
        inspiration_fragment_names = oechem.OEGetSDData(molecule, 'fragments').split(',')
def generate_restricted_conformers(receptor, refmol, mol, core_smarts=None):
    """
    Generate and select a conformer of the specified molecule using the reference molecule

    Parameters
    ----------
    receptor : openeye.oechem.OEGraphMol
        Receptor (already prepped for docking) for identifying optimal pose
    refmol : openeye.oechem.OEGraphMol
        Reference molecule which shares some part in common with the proposed molecule
    mol : openeye.oechem.OEGraphMol
        Molecule whose conformers are to be enumerated
    core_smarts : str, optional, default=None
        If core_smarts is specified, substructure will be extracted using SMARTS.
    """
    from openeye import oechem, oeomega

    logging.debug(
        f'mol: {oechem.OEMolToSmiles(mol)} | core_smarts: {core_smarts}')

    # Be quiet
    from openeye import oechem
    oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Quiet)
    #oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Error)

    # Get core fragment
    if core_smarts:
        # Truncate refmol to SMARTS if specified
        #print(f'Trunctating using SMARTS {refmol_smarts}')
        ss = oechem.OESubSearch(core_smarts)
        oechem.OEPrepareSearch(refmol, ss)
        for match in ss.Match(refmol):
            core_fragment = oechem.OEGraphMol()
            oechem.OESubsetMol(core_fragment, match)
            logging.debug(
                f'Truncated refmol to generate core_fragment: {oechem.OEMolToSmiles(core_fragment)}'
            )
            break
        #print(f'refmol has {refmol.NumAtoms()} atoms')
    else:
        core_fragment = GetCoreFragment(refmol, [mol])
        oechem.OESuppressHydrogens(core_fragment)
        #print(f'  Core fragment has {core_fragment.NumAtoms()} heavy atoms')
        MIN_CORE_ATOMS = 6
        if core_fragment.NumAtoms() < MIN_CORE_ATOMS:
            return None

    # Create an Omega instance
    #omegaOpts = oeomega.OEOmegaOptions()
    omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)

    # Set the fixed reference molecule
    omegaFixOpts = oeomega.OEConfFixOptions()
    omegaFixOpts.SetFixMaxMatch(10)  # allow multiple MCSS matches
    omegaFixOpts.SetFixDeleteH(True)  # only use heavy atoms
    omegaFixOpts.SetFixMol(core_fragment)
    #omegaFixOpts.SetFixSmarts(core_smarts) # DEBUG
    omegaFixOpts.SetFixRMS(0.5)

    # This causes a warning:
    #Warning: OESubSearch::Match() is unable to match unset hybridization in the target (EN300-221518_3_1) for patterns with set hybridization, call OEPrepareSearch on the target first
    #atomexpr = oechem.OEExprOpts_Aromaticity | oechem.OEExprOpts_Hybridization

    atomexpr = oechem.OEExprOpts_Aromaticity | oechem.OEExprOpts_AtomicNumber
    bondexpr = oechem.OEExprOpts_BondOrder | oechem.OEExprOpts_Aromaticity
    omegaFixOpts.SetAtomExpr(atomexpr)
    omegaFixOpts.SetBondExpr(bondexpr)
    omegaOpts.SetConfFixOptions(omegaFixOpts)

    molBuilderOpts = oeomega.OEMolBuilderOptions()
    molBuilderOpts.SetStrictAtomTypes(
        False)  # don't give up if MMFF types are not found
    omegaOpts.SetMolBuilderOptions(molBuilderOpts)

    omegaOpts.SetWarts(False)  # expand molecule title
    omegaOpts.SetStrictStereo(True)  # set strict stereochemistry
    omegaOpts.SetIncludeInput(False)  # don't include input
    omegaOpts.SetMaxConfs(1000)  # generate lots of conformers
    omegaOpts.SetEnergyWindow(20.0)  # allow high energies
    omega = oeomega.OEOmega(omegaOpts)

    # TODO: Expand protonation states and tautomers
    from openeye import oequacpac
    if not oequacpac.OEGetReasonableProtomer(mol):
        logging.warning('No reasonable protomer found')
        return None

    mol = oechem.OEMol(mol)  # multi-conformer molecule

    ret_code = omega.Build(mol)
    if (mol.GetDimension() != 3) or (ret_code !=
                                     oeomega.OEOmegaReturnCode_Success):
        msg = f'\nOmega failure for {mol.GetTitle()} : SMILES {oechem.OEMolToSmiles(mol)} : core_smarts {core_smarts} : {oeomega.OEGetOmegaError(ret_code)}\n'
        logging.warning(msg)
        return None
        # Return the molecule with an error code
        #oechem.OESetSDData(mol, 'error', '{oeomega.OEGetOmegaError(ret_code)}')
        #return mol

    # Extract poses
    class Pose(object):
        def __init__(self, conformer):
            self.conformer = conformer
            self.clash_score = None
            self.docking_score = None
            self.overlap_score = None

    poses = [Pose(conf) for conf in mol.GetConfs()]

    # Score clashes
    bump_check = BumpCheck(receptor)
    for pose in poses:
        pose.clash_score = bump_check.count(pose.conformer)

    # Score docking poses
    from openeye import oedocking
    score = oedocking.OEScore(oedocking.OEScoreType_Chemgauss4)
    score.Initialize(receptor)
    for pose in poses:
        pose.docking_score = score.ScoreLigand(pose.conformer)

    # Compute overlap scores
    from openeye import oeshape
    overlap_prep = oeshape.OEOverlapPrep()
    overlap_prep.Prep(refmol)
    shapeFunc = oeshape.OEExactShapeFunc()
    shapeFunc.SetupRef(refmol)
    oeshape_result = oeshape.OEOverlapResults()
    for pose in poses:
        tmpmol = oechem.OEGraphMol(pose.conformer)
        overlap_prep.Prep(tmpmol)
        shapeFunc.Overlap(tmpmol, oeshape_result)
        pose.overlap_score = oeshape_result.GetRefTversky()

    # Filter poses based on top 10% of overlap
    poses = sorted(poses, key=lambda pose: pose.overlap_score)
    poses = poses[int(0.9 * len(poses)):]

    # Select the best docking score
    import numpy as np
    poses = sorted(poses, key=lambda pose: pose.docking_score)
    pose = poses[0]
    mol.SetActive(pose.conformer)
    oechem.OESetSDData(mol, 'clash_score', str(pose.clash_score))
    oechem.OESetSDData(mol, 'docking_score', str(pose.docking_score))
    oechem.OESetSDData(mol, 'overlap_score', str(pose.overlap_score))

    # Convert to single-conformer molecule
    mol = oechem.OEGraphMol(mol)

    # Compute MMFF energy
    energy = mmff_energy(mol)
    oechem.OESetSDData(mol, 'MMFF_internal_energy', str(energy))

    # Store SMILES
    docked_smiles = oechem.OEMolToSmiles(mol)
    oechem.OESetSDData(mol, 'docked_smiles', docked_smiles)

    return mol
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData, argv)

    NPolyMax_MAX = itf.GetInt("-NPolyMax_MAX")

    ifrefname = itf.GetString("-inputreffile")
    iffitname = itf.GetString("-inputfitfile")
    ofname = itf.GetString("-outputfile")

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

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

    refmol = oechem.OEMol()

    if not oechem.OEReadMolecule(ifsref, refmol):
        oechem.OEThrow.Fatal("Unable to read molecule in %s" % ifrefname)

    prep = oeshape.OEOverlapPrep()
    prep.SetAssignColor(False)
    prep.Prep(refmol)
    reftransfm = oechem.OETrans()
    oeshape.OEOrientByMomentsOfInertia(refmol, reftransfm)

    hermiteoptionsref = oeshape.OEHermiteOptions()
    hermiteoptionsref.SetNPolyMax(NPolyMax_MAX)
    hermiteoptionsref.SetUseOptimalLambdas(True)

    hermiteoptionsfit = oeshape.OEHermiteOptions()
    hermiteoptionsfit.SetNPolyMax(NPolyMax_MAX)
    hermiteoptionsfit.SetUseOptimalLambdas(True)

    hermitefunc = oeshape.OEHermiteShapeFunc(hermiteoptionsref,
                                             hermiteoptionsfit)

    options = oeshape.OEOverlayOptions()
    options.SetOverlapFunc(hermitefunc)
    overlay = oeshape.OEOverlay(options)
    overlay.SetupRef(refmol)

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

    transfm = oechem.OETrans()
    fitmol = oechem.OEMol()
    while oechem.OEReadMolecule(ifsfit, fitmol):
        prep.Prep(fitmol)
        oeshape.OEOrientByMomentsOfInertia(fitmol, transfm)

        score = oeshape.OEBestOverlayScore()
        overlay.BestOverlay(score, fitmol)
        print("Hermite Tanimoto = ", score.GetTanimoto())

        oechem.OESetSDData(fitmol, "HermiteTanimoto_" + str(NPolyMax_MAX),
                           str(score.GetTanimoto()))
        score.Transform(fitmol)

        # Transform from the inertial frame to the original reference mol frame
        reftransfm.Transform(fitmol)

        oechem.OEWriteMolecule(ofs, fitmol)
Beispiel #18
0
def main(argv=[__name__]):
    itf = oechem.OEInterface(InterfaceData, argv)

    NPolyMax = itf.GetInt("-NPolyMax")
    gridspacing = itf.GetFloat("-gridspacing")

    ifname = itf.GetString("-inputfile")
    ofname = itf.GetString("-outputgrid")\

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

    if (not ofname.endswith(".grd")):
        oechem.OEThrow.Fatal("Output grid file extension hast to be '.grd' ")

    mol = oechem.OEMol()

    if (not oechem.OEReadMolecule(ifs, mol)):
        oechem.OEThrow.Fatal("Unable to read molecule in %s" % ifname)

    prep = oeshape.OEOverlapPrep()
    prep.SetAssignColor(False)
    prep.Prep(mol)
    transfm = oechem.OETrans()
    oeshape.OEOrientByMomentsOfInertia(mol, transfm)

    hermiteoptions = oeshape.OEHermiteOptions()
    hermiteoptions.SetNPolyMax(NPolyMax)
    hermiteoptions.SetUseOptimalLambdas(True)

    hermite = oeshape.OEHermite(hermiteoptions)

    if (not hermite.Setup(mol)):
        oechem.OEThrow.Fatal(
            "Was not able to Setup the molecule for the OEHermite class.")

    hopts = hermite.GetOptions()
    print("Best lambdas found X=" + str(hopts.GetLambdaX()) + "  Y=" +
          str(hopts.GetLambdaY()) + "  Z=" + str(hopts.GetLambdaZ()))

    print("Hermite self-overlap=", hermite.GetSelfOverlap())

    basis_size = int((NPolyMax + 1) * (NPolyMax + 2) * (NPolyMax + 3) / 6)
    coeffs = oechem.OEDoubleVector(basis_size)
    hermite.GetCoefficients(coeffs)
    NPolyMaxstring = str(NPolyMax)
    print("Hermite coefficients f_{l,m,n} in the following order l = 0..." +
          NPolyMaxstring + ", m = 0..." + NPolyMaxstring + "-l, n = " +
          NPolyMaxstring + "-l-m :")

    for x in coeffs:
        print(str(x) + " "),

    grid = oegrid.OEScalarGrid()

    hermite.CreateGrid(grid, gridspacing)

    if (not oegrid.OEWriteGrid(ofname, grid)):
        oechem.OEThrow.Fatal("Unable to write grid file")

    return 0