#!/opt/anaconda1anaconda2anaconda3/bin/python
# (C) 2022 Cadence Design Systems, Inc. (Cadence) 
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence 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 Cadence 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 Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.

import sys
from openeye import oechem
from openeye import oeff

# //////////////////////////////////////////////////////////////////////////
# The following example demonstrates how to perform ligand optimization   //
# in the context of a protein using a complex force field.                //
# //////////////////////////////////////////////////////////////////////////


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

        ffType = oechem.OEStringParameter("-ff", "ff14sb_parsley")
        ffType.AddLegalValue("ff14sb_parsley")
        ffType.AddLegalValue("mmff_amber")
        ffType.AddLegalValue("mmff")
        ffType.SetBrief("Force field type")
        self._fftype = self.AddParameter(ffType)
        pass

    def CreateCopy(self):
        return self

    def GetFF(self):
        ff = self._fftype.GetStringValue()
        if ff == "":
            ff = self._fftype.GetStringDefault()

        if ff == "mmff":
            return oeff.OEMMFFComplex()
        elif ff == "mmff_amber":
            return oeff.OEMMFFAmberComplex()
        else:
            return oeff.OEFF14SBParsleyComplex()


def main(argv=[__name__]):
    ffOpts = FFOptions()
    opts = oechem.OERefInputAppOptions(ffOpts, "FFComplexOpt", oechem.OEFileStringType_Mol3D,
                                       oechem.OEFileStringType_Mol3D, oechem.OEFileStringType_DU, "-protein")
    if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
        return 0
    ffOpts.UpdateValues(opts)

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

    rfs = oechem.oeifstream()
    if not rfs.open(opts.GetRefFile()):
        oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetRefFile())

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

    du = oechem.OEDesignUnit()
    if not oechem.OEReadDesignUnit(rfs, du):
        oechem.OEThrow.Fatal("Failed to read design unit")
    protein = oechem.OEGraphMol()
    du.GetProtein(protein)

    ff = ffOpts.GetFF()
    if not ff.SetupHost(protein):
        oechem.OEThrow.Fatal("Failed to setup protein: %s" % protein.GetTitle())

    for mol in ifs.GetOEMols():
        print("Optimizing", mol.GetTitle())
        if (not ff.Setup(mol)):
            oechem.OEThrow.Warning("Unable to process molecule: title = '%s'" % mol.GetTitle())
            oechem.OEWriteMolecule(ofs, mol)
            continue

        vecCoords = oechem.OEDoubleArray(3*mol.GetMaxAtomIdx())
        for conf in mol.GetConfs():
            oechem.OEThrow.Info("Molecule: %s Conformer: %d" % (mol.GetTitle(), conf.GetIdx()+1))
            conf.GetCoords(vecCoords)

            # Calculate energy
            energy = ff(vecCoords)
            oechem.OEThrow.Info("Initial energy: %0.2f kcal/mol" % energy)

            # Optimize the ligand
            optimizer = oeff.OEBFGSOpt()
            energy = optimizer(ff, vecCoords, vecCoords)
            oechem.OEThrow.Info("Optimized energy: %0.2f kcal/mol" % energy)
            conf.SetCoords(vecCoords)

        oechem.OEWriteMolecule(ofs, mol)

    return 0


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