# 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 math as maths

# american option by Longstaff-Schwartz
# p_sim        Monte Carlo simulator
# p_payOff     Option pay off
# p_regressor  regressor object
def resolution(p_simulator, p_payOff, p_regressor) :
    
    step = p_simulator.getStep()
    # asset simulated under the neutral risk probability : get the trend of first asset to get interest rate
    expRate = np.exp(-step * p_simulator.getMu()[0])
    # Terminal
    particle = p_simulator.getParticles()
    Cash = p_payOff.operator(particle)
    
    for iStep in range(0, p_simulator.getNbStep()):
        asset = p_simulator.stepBackwardAndGetParticles()
        payOffLoc = p_payOff.operator(asset)
        isLastStep = False        
        if iStep == p_simulator.getNbStep() - 1 :
            isLastStep = True
    
        p_regressor.updateSimulations(isLastStep, asset)
        # conditional expectation
        condEspec = p_regressor.getAllSimulations(Cash).squeeze() * expRate
        # arbitrage
        Cash = np.where(condEspec < payOffLoc, payOffLoc, Cash * expRate) 
       
    return maths.fsum(Cash) / len(Cash)
