#!/usr/bin/python3

# Copyright (C) 2016 EDF
# All Rights Reserved
# This code is published under the GNU Lesser General Public License (GNU LGPL)
import numpy as np
import StOptReg as reg
import StOptGrids
import StOptGlobal
import Simulators as sim
import Optimizers as opt
import Utils
import dp.DynamicProgrammingByRegressionHighLevel as dyn
import dp.SimulateRegressionControlHighLevel as srtc
import unittest
import importlib

accuracyClose = 1.5


# valorization of a given Lake on a  grid
# Gain are proportional to what is withdrawed from the storage
# Only inflows are stochastic
# p_grid             the grid
# p_maxLevelStorage  maximum level
# p_mesh             number of mesh
# p_bCheckClose      Do we check if optimization and simulations are close
def lake(p_grid, p_maxLevelStorage, p_mesh, p_bCheckClose):

     # test MPI
    moduleMpi4Py=importlib.util.find_spec('mpi4py')
    if (moduleMpi4Py is not None):
        from mpi4py import MPI

    # storage
    #########
    withdrawalRateStorage = 1000

    maturity = 1.
    nstep = 10

    # number of simulations
    nbsimulOpt = 8000

    # inflow model
    D0 = 50 # initial inflow
    m = D0 # average inflow
    sig = 5. # volatility
    mr = 5. # mean reverting
    # a backward simulator
    ######################
    bForward = False
    backSimulator = sim.AR1Simulator(D0, m, sig, mr, maturity, nstep, nbsimulOpt, bForward)
    # optimizer
    ##########
    storage = opt.OptimizeLakeAR1(withdrawalRateStorage)

    # regressor
    ###########
    nbMesh = np.array([], dtype = np.int32)

    if p_mesh > 0:
        nbMesh = np.zeros(1, dtype = np.int32) + p_mesh

    regressor = reg.LocalLinearRegression(nbMesh)
    # final value
    vFunction = Utils.ZeroPayOff()

    # initial values
    initialStock = np.zeros(1) + p_maxLevelStorage
    initialRegime = 0 # only one regime

    # Optimize
    fileToDump = "CondExpLakeHL"

    # link the simulations to the optimizer
    storage.setSimulator(backSimulator)
    valueOptim = dyn.DynamicProgrammingByRegressionHighLevel(p_grid, storage, regressor , vFunction, initialStock, initialRegime, fileToDump)

    nbsimulSim = 8000
    bForward = True

    forSimulator2 = sim.AR1Simulator(D0, m, sig, mr, maturity, nstep, nbsimulSim, bForward)

    storage.setSimulator(forSimulator2)
    valSimu2 = srtc.SimulateRegressionControl(p_grid, storage, vFunction, initialStock, initialRegime, fileToDump)

    print("valSimu2", valSimu2, "valueOptim", valueOptim)

class testLakeTest(unittest.TestCase):

    # linear interpolation
    def test_lakeLegendreLinear(self):

        # storage
        #########
        maxLevelStorage = 5000
        # grid
        ######
        nGrid = 10
        lowValues = np.zeros(1)
        step = np.zeros(1) + (maxLevelStorage / nGrid)
        nbStep = np.zeros(1, dtype = np.int32) + nGrid
        poly = np.zeros(1, dtype = np.int32) + 1
        grid = StOptGrids.RegularLegendreGrid(lowValues, step, nbStep, poly)
        nbmesh = 4

        lake(grid, maxLevelStorage, nbmesh, True)

    # quadratic interpolation on the basis functions
    def test_simpleStorageLegendreQuad(self):

        # storage
        #########
        maxLevelStorage = 5000
        # grid
        ######
        nGrid = 5
        lowValues = np.zeros(1)
        step = np.zeros(1) + (maxLevelStorage / nGrid)
        nbStep = np.zeros(1, dtype = np.int32) + nGrid
        poly = np.zeros(1, dtype = np.int32) + 2
        grid = StOptGrids.RegularLegendreGrid(lowValues, step, nbStep, poly)
        nbmesh = 4

        lake(grid, maxLevelStorage, nbmesh, True)

    # forget the AR1 model and suppose that inflows are iid
    def test_simpleStorageAverageInflows(self):

        # storage
        #########
        maxLevelStorage = 5000
        # grid
        ######
        nGrid = 10
        lowValues = np.zeros(1)
        step = np.zeros(1) + (maxLevelStorage / nGrid)
        nbStep = np.zeros(1, dtype = np.int32) + nGrid
        poly = np.zeros(1, dtype = np.int32) + 1
        grid = StOptGrids.RegularLegendreGrid(lowValues, step, nbStep, poly)
        nbmesh = 0

        lake(grid, maxLevelStorage, nbmesh, False)

if __name__ == '__main__':
    unittest.main()
