#!/usr/bin/env python
# (C) 2017 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.

import sys
from openeye import oechem
from openeye import oeff

# //////////////////////////////////////////////////////////////////////////
# The following example demonstrates how to perform ligand optimization   //
# //////////////////////////////////////////////////////////////////////////


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

        ffType = oechem.OEStringParameter("-ff", "parsley")
        ffType.AddLegalValue("parsley")
        ffType.AddLegalValue("mmff94")
        ffType.AddLegalValue("mmff94s")
        ffType.SetBrief("Fore 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 == "mmff94":
            return oeff.OEMMFF()
        elif ff == "mmff94s":
            return oeff.OEMMFF(oeff.OEMMFF94sParams())
        else:
            return oeff.OEParsley()


def main(argv=[__name__]):
    ffOpts = FFOptions()
    opts = oechem.OESimpleAppOptions(ffOpts, "FFOptimize", oechem.OEFileStringType_Mol3D,
                                     oechem.OEFileStringType_Mol3D)
    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())

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

    ff = ffOpts.GetFF()
    for mol in ifs.GetOEMols():
        print("Optimizing", mol.GetTitle())
        if not ff.PrepMol(mol) or 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))
