# Copyright (C) 2021 EDF
# All Rights Reserved
# This code is published under the GNU Lesser General Public License (GNU LGPL)
import numpy as np
import StOptGeners
import StOptGlobal
import imp


# Simulate the optimal strategy with switching
# p_grids                  grid used for  int deterministic state for each regime
# p_optimize               optimizer defining the optimization between two time steps
# p_funcFinalValue         function defining the final value
# p_pointStock             initial point stock
# p_initialRegime          regime at initial date
# p_fileToDump             name of the file used to dump continuation values in optimization
def SimulateSwitchingRegression(p_grids, p_optimize,  p_pointState, p_initialRegime, p_fileToDump) :
    
    simulator = p_optimize.getSimulator()
    nbStep = simulator.getNbStep()
    states = []
    particle0 =  simulator.getParticles()[:,0]
       
    for i in range(simulator.getNbSimul()) :
        states.append(StOptGlobal.StateWithIntState(p_initialRegime, p_pointState, particle0))
            
            
    ar = StOptGeners.BinaryFileArchive(p_fileToDump, "r")
    # name for continuation object in archive
    nameAr = "ContinuationSwitching"
    # cost function
    costFunction = np.zeros((p_optimize.getSimuFuncSize(), simulator.getNbSimul()))

    # iterate on time steps
    for istep in range(nbStep) :
        NewState = StOptGlobal.SimulateStepSwitch(ar, istep, nameAr, p_grids, p_optimize).oneStep(states, costFunction)
        # different from C++
        states = NewState[0]
        costFunction = NewState[1]
        # new stochastic state
        particules = simulator.stepForwardAndGetParticles()
        # update stochastic state
        for i in range(simulator.getNbSimul()) :
            states[i].setStochasticRealization(particules[:,i])


    # average gain/cost
    return costFunction.mean()
