#!/usr/bin/env python3
# (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.

#############################################################################
# Calculates XLogP of a molecule and depict the contribution of
# fragments to the total XLogP
#############################################################################

import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
from openeye import oemolprop
from openeye import oemedchem
from openeye import oequacpac


def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)
    oedepict.OEConfigureImageWidth(itf, 400.0)
    oedepict.OEConfigureImageHeight(itf, 300.0)
    oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)

    if not oechem.OEParseCommandLine(itf, argv):
        return 1

    iname = itf.GetString("-in")
    oname = itf.GetString("-out")

    # check input/output files

    ifs = oechem.oemolistream()
    if not ifs.open(iname):
        oechem.OEThrow.Fatal("Cannot open input file!")

    ext = oechem.OEGetFileExtension(oname)
    if not oedepict.OEIsRegisteredImageFile(ext):
        oechem.OEThrow.Fatal("Unknown image type!")

    ofs = oechem.oeofstream()
    if not ofs.open(oname):
        oechem.OEThrow.Fatal("Cannot open output file!")

    # read a molecule

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ifs, mol):
        oechem.OEThrow.Fatal("Cannot read input file!")

    # initialize fragmentation function

    fragfunc = get_fragmentation_function(itf)

    # create image

    width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
    image = oedepict.OEImage(width, height)

    # setup depiction options

    opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
    oedepict.OESetup2DMolDisplayOptions(opts, itf)
    opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)

    # depict molecule with XLogP atom contributions

    oedepict.OEPrepareDepiction(mol)
    depict_molecule_fragment_xlogp(image, mol, fragfunc, opts)

    oedepict.OEWriteImage(ofs, ext, image)

    return 0


def set_atom_properties(mol, datatag):
    """
    Attaches the XLogP atom contribution to each atom with the given tag.

    :type mol: oechem.OEMolBase
    :type datatag: string
    """

    oequacpac.OERemoveFormalCharge(mol)

    avals = oechem.OEFloatArray(mol.GetMaxAtomIdx())
    logp = oemolprop.OEGetXLogP(mol, avals)

    mol.SetTitle(mol.GetTitle() + " -- OEXLogP = %.2f" % logp)

    for atom in mol.GetAtoms():
        val = avals[atom.GetIdx()]
        atom.SetData(datatag, val)


def fragment_molecule(mol, fragfunc, grouptag):
    """
    Fragments the molecule and stores each fragment as a group on the molecule.

    :type mol: oechem.OEMolBase
    :type fragfunc: function()
    :type grouptag: string
    """

    for frag in fragfunc(mol):

        atoms = oechem.OEAtomVector()
        for atom in frag.GetAtoms():
            atoms.append(atom)
        bonds = oechem.OEBondVector()
        for bond in frag.GetBonds():
            bonds.append(bond)

        mol.NewGroup(grouptag, atoms, bonds)


def set_fragment_properties(mol, datatag, grouptag):
    """
    Calculates the fragment contribution based on attached atom properties
    for pre-generated fragments.

    :type mol: oechem.OEMolBase
    :type datatag: string
    :type grouptag: string
    """

    minvalue = float("inf")
    maxvalue = float("-inf")

    for group in mol.GetGroups(oechem.OEHasGroupType(grouptag)):

        sumprop = 0.0
        for atom in group.GetAtoms():
            sumprop += atom.GetData(datatag)
        group.SetData(datatag, sumprop)

        minvalue = min(minvalue, sumprop)
        maxvalue = max(maxvalue, sumprop)

    return minvalue, maxvalue


def depict_molecule_fragment_xlogp(image, mol, fragfunc, opts):
    """
    Generates an image of a molecule depicting the fragment contribution of XLogP.

    :type image: oedepict.OEImageBase
    :type mol: oechem.OEMolBase
    :type fragfunc: function()
    :type opts: oedepict.OE2DMolDiplayOptions
    """

    # calculate atom contributions of XLogP

    sdatatag = "XLogP"
    idatatag = oechem.OEGetTag(sdatatag)
    set_atom_properties(mol, idatatag)

    # fragment molecule

    sgrouptag = "fragment"
    igrouptag = oechem.OEGetTag(sgrouptag)
    fragment_molecule(mol, fragfunc, igrouptag)

    # calculate fragment contributions

    minvalue, maxvalue = set_fragment_properties(mol, idatatag, igrouptag)

    # initialize color gradient

    lightgrey = oechem.OEColor(240, 240, 240)
    colorg = oechem.OELinearColorGradient(oechem.OEColorStop(0.0, lightgrey))
    colorg.AddStop(oechem.OEColorStop(minvalue, oechem.OEDarkGreen))
    colorg.AddStop(oechem.OEColorStop(maxvalue, oechem.OEDarkPurple))

    # generate image frames

    iwidth, iheight = image.GetWidth(), image.GetHeight()
    mframe = oedepict.OEImageFrame(image, iwidth, iheight * 0.8,
                                   oedepict.OE2DPoint(0.0, 0.0))
    cframe = oedepict.OEImageFrame(image, iwidth, iheight * 0.2,
                                   oedepict.OE2DPoint(0.0, iheight * 0.8))

    # initialize molecule display

    opts.SetDimensions(mframe.GetWidth(), mframe.GetHeight(), oedepict.OEScale_AutoScale)
    disp = oedepict.OE2DMolDisplay(mol, opts)

    # initialize highlighting style

    highlight = oedepict.OEHighlightByLasso(oechem.OEWhite)
    highlight.SetConsiderAtomLabelBoundingBox(True)

    colorgopts = oegrapheme.OEColorGradientDisplayOptions()

    for group in mol.GetGroups(oechem.OEHasGroupType(igrouptag)):
        groupvalue = group.GetData(idatatag)
        colorgopts.AddMarkedValue(groupvalue)

        # depict fragment contribution

        color = colorg.GetColorAt(groupvalue)
        highlight.SetColor(color)

        abset = oechem.OEAtomBondSet(group.GetAtoms(), group.GetBonds())
        oedepict.OEAddHighlighting(disp, highlight, abset)

    # render molecule and color gradient

    oedepict.OERenderMolecule(mframe, disp)
    oegrapheme.OEDrawColorGradient(cframe, colorg, colorgopts)


def get_fragmentation_function(itf):

    fstring = itf.GetString("-fragtype")
    if fstring == "funcgroup":
        return oemedchem.OEGetFuncGroupFragments
    if fstring == "ring-chain":
        return oemedchem.OEGetRingChainFragments
    return oemedchem.OEGetRingLinkerSideChainFragments


#############################################################################
# INTERFACE
#############################################################################

InterfaceData = """
!CATEGORY "input/output options" 1

    !PARAMETER -in
      !ALIAS -i
      !TYPE string
      !REQUIRED true
      !KEYLESS 1
      !VISIBILITY simple
      !BRIEF Input molecule filename
    !END

    !PARAMETER -out
      !ALIAS -o
      !TYPE string
      !REQUIRED true
      !KEYLESS 2
      !VISIBILITY simple
      !BRIEF Output filename of the generated image
    !END

!END

!CATEGORY "fragmentation options" 2
    !PARAMETER -fragtype
      !ALIAS -ftype
      !TYPE string
      !REQUIRED false
      !KEYLESS 3
      !DEFAULT funcgroup
      !LEGAL_VALUE funcgroup
      !LEGAL_VALUE ring-chain
      !LEGAL_VALUE ring-linker-sidechain
      !VISIBILITY simple
      !BRIEF Fragmentation type
    !END
!END
"""

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