#!/usr/bin/env python
# (C) 2024 OpenEye Scientific Software Inc. All rights reserved.
#
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of OpenEye products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. OpenEye claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable OpenEye offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be
# liable for any damages or liability in connection with the Sample Code
# or its use.


'''
This script performs simple eon charge overlap calculations on input reference and fit molecules
molecules, scores each conformer with a charge tanimoto and outputs results.

Usage:
python eon_overlap.py -query query.sdf -in database_molecules.oeb.gz -out output.oeb.gz

python eon_overlap.py -query query.sdf -in database_molecules.oeb.gz -out output.oeb.gz -charges existing

python eon_overlap.py -query query.sdf -in database_molecules.oeb.gz -out output.oeb.gz -charges mmff94
'''

from openeye import oechem
from openeye import oeet
from openeye import oeshape
from openeye import oequacpac

class EonOverlapOption(oechem.OEOptions):
    def __init__(self):
        oechem.OEOptions.__init__(self, "EonOverlapOptions")

        chargesParam = oechem.OEStringParameter("-charges", "mmff94")
        chargesParam.SetRequired(True)
        chargesParam.SetVisibility(oechem.OEParamVisibility_Simple)
        chargesParam.SetBrief("Choices for this parameter are mmff94 (fix pka and set charges to mmff94), or existing (assume input has charges)")

        self._chargesParam = self.AddParameter(chargesParam)
        pass

    def CreateCopy(self):
        return self

    def GetCharges(self):
        value = self._chargesParam.GetStringValue()
        if value != "":
            return value

        return self._chargesParam.GetStringDefault()


def prep_mol(inmol):
    # remove color atoms if present
    if oeshape.OEHasColorAtoms(inmol):
        oeshape.OERemoveColorAtoms(inmol)

    # add explicit hydrogens and assign radii
    oechem.OEAddExplicitHydrogens(inmol)
    oechem.OEAssignBondiVdWRadii(inmol)

    oequacpac.OESetNeutralpHModel(inmol)
    oequacpac.OEAssignCharges(inmol, oequacpac.OEMMFF94Charges())

    inmol.Sweep()


def main(argv=[__name__]):
    eonOpts = EonOverlapOption()

    opts = oechem.OERefInputAppOptions(
        eonOpts, "EonOverlapOptions",
        oechem.OEFileStringType_Mol3D,
        oechem.OEFileStringType_Mol3D,
        oechem.OEFileStringType_Mol3D, "-query")

    if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
        return 0

    eonOpts.UpdateValues(opts)

    inputFilename       = opts.GetInFile()
    outputFilename      = opts.GetOutFile()
    queryFilename       = opts.GetRefFile()
    charges             = eonOpts.GetCharges()

    qfs = oechem.oemolistream()
    if not qfs.open(queryFilename):
        oechem.OEThrow.Fatal(f'Unable to open {queryFilename} for reading')

    ifs = oechem.oemolistream()
    if not ifs.open(inputFilename):
        oechem.OEThrow.Fatal(f'Unable to open {inputFilename} for reading')

    ofs = oechem.oemolostream()
    if not ofs.open(outputFilename):
        oechem.OEThrow.Fatal(f'Unable to open {outputFilename} for writing')
   
    chargeFunc = oeet.OEExactChargeFunc()
   
    # set up query
    refmol = oechem.OEMol()
    oechem.OEReadMolecule(qfs, refmol)

    if (charges == "mmff94"):
        prep_mol(refmol)

    chargeFunc.SetupRef(refmol)

    # write query to output file
    oechem.OEWriteMolecule(ofs, refmol)

    for mol in ifs.GetOEMols():
        if (charges == "mmff94"):
            prep_mol(mol)
        score = oeet.OEEonOverlapScore()
        for conf in mol.GetConfs():
            chargeFunc.Overlap(conf, score)
            oechem.OESetSDData(conf, '(Static) Charge Tanimoto', f'{score.GetETTanimoto():.4f}')
        oechem.OEWriteMolecule(ofs, mol)

    qfs.close()
    ifs.close()
    ofs.close()

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))