#!/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 is an example to show how to evaluate energy              //
# and optimize a set of torsions in a small molecule                      //
# //////////////////////////////////////////////////////////////////////////


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, "FFTorAdaptor", 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()

    # Setup adaptor. The first (false) means not to pass ownership of mmff,
    # and the second (false) means not to exclude interactions related
    # to the subset which would be fixed for calculations.
    adaptor = oeff.OETorAdaptor(ff, False, False)

    # Use a simple predicate for the subset of torsions to optimize
    adaptor.Set(oechem.OEIsRotor())

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

            # Get adaptor variables set corresponding to the coordinates
            vecX = oechem.OEDoubleArray(adaptor.NumVar())
            adaptor.GetVar(vecX, vecCoords)

            # Calculate energy using adaptor
            energy = adaptor(vecX)
            oechem.OEThrow.Info("Initial energy: %0.2f kcal/mol" % energy)

            # Optimize the adaptor
            optimizer = oeff.OEBFGSOpt()
            energy = optimizer(adaptor, vecX, vecX)
            oechem.OEThrow.Info("Optimized energy: %0.2f kcal/mol" % energy)

            # Get optimized coordinates corresponding to the adaptor optimized variables
            adaptor.AdaptVar(vecCoords, vecX)
            conf.SetCoords(vecCoords)

        oechem.OEWriteMolecule(ofs, mol)

    return 0


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