# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2018
# --------------------------------------------------------------------------

"""The model aims at minimizing the production cost for a number of products
while satisfying customer demand. Each product can be produced either inside
the company or outside, at a higher cost.
The inside production is constrained by the company's resources, while outside
production is considered unlimited.
The model first declares the products and the resources.
The data consists of the description of the products (the demand, the inside
and outside costs, and the resource consumption) and the capacity of the
various resources.
The variables for this problem are the inside and outside production for each
product.
"""

from docplex.mp.model import Model
from docplex.util.environment import get_environment
import numpy as np
import Simulation as sim


# ----------------------------------------------------------------------------
# Initialize the problem data
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# Build the model
# ----------------------------------------------------------------------------

def propogateStates(A,B,t,numProp=2):
    prev_uk_coeff = []
    prev_uk_coeff.append((np.zeros((11, 4))))
    uk_coeff = []
    prev_Xk_coeff = np.identity(11)


    for i in range(numProp):
        xk_coeff = np.dot(A, prev_Xk_coeff) * t + prev_Xk_coeff
        prev_Xk_coeff = xk_coeff

        for j in range(len(prev_uk_coeff)):
            uk_coeff.append(np.dot(A, prev_uk_coeff[j]) * t + B * t)

        uk_coeff.append((np.zeros((11, 4))))

        prev_uk_coeff = uk_coeff
        uk_coeff = []
    return prev_Xk_coeff,prev_uk_coeff

def solve_br(AAverage,BAverage,SigmaXk,SigmaU,Z=np.zeros((11)),xk=np.array([4.84,0,0,0,0,0,0,0,0,100,1001]),valFunc=np.zeros((19))):
    """ Takes as input:
        - a list of product tuples (name, demand, inside, outside)
        - a list of resource tuples (name, capacity)
        - a list of consumption tuples (product_name, resource_named, consumed)
    """
    #xk=np.array([ 4.58404537e+00, -7.00335542e+00, -2.59237351e+00,  4.07468589e-02,-1.82812316e-04, -1.26851525e+00, 5.04098160e-03, -9.70726285e-02,1.69730427e-04,  1.00959890e+02,  1.00821996e+03])
    simulator=sim.Simulation()
    t=simulator.t
    r=np.array([100,30,100,50,50,100,50,10,10,300]).reshape(10,-1)
    r2 = np.array([100, 30, 100, 50, 50, 100, 50, 10, 10, 300]).reshape(10, -1)
    xref=np.array([5,0,0,0,0,0,0,0,0,1000]).reshape(10,-1)
    xk=xk.reshape(11,-1)
    C=np.identity(11)
    C=np.delete(C,9,0)
    SigmaU_twostep=np.hstack((SigmaU,SigmaU))
    SigmaU_twostep = np.delete(SigmaU_twostep, 9, 0)

    SigmaU_threestep = np.hstack((SigmaU, SigmaU,SigmaU))
    SigmaU_threestep = np.delete(SigmaU_threestep, 9, 0)

    SigmaU_fourstep = np.hstack((SigmaU, SigmaU, SigmaU,SigmaU))
    SigmaU_fourstep = np.delete(SigmaU_fourstep, 9, 0)


    xkC_TwoStep,ukC_TwoStep=propogateStates(AAverage,BAverage,t,2)

    xkC_ThreeStep, ukC_ThreeStep = propogateStates(AAverage, BAverage, t, 3)

    xkC_FourStep, ukC_FourStep = propogateStates(AAverage, BAverage, t, 4)


    #U coefficients
    uk1_TwoStep,uk2_TwoStep,_=ukC_TwoStep
    coef1_TwoStep=np.hstack((np.dot(C, uk1_TwoStep), (np.dot(C ,uk2_TwoStep))))

    uk1_ThreeStep, uk2_ThreeStep,uk3_ThreeStep, _ = ukC_ThreeStep
    coef1_ThreeStep = np.hstack((np.dot(C, uk1_ThreeStep), np.dot(C, uk2_ThreeStep),np.dot(C, uk3_ThreeStep)))

    uk1_FourStep, uk2_FourStep, uk3_FourStep,uk4_FourStep, _ = ukC_FourStep
    coef1_FourStep = np.hstack((np.dot(C, uk1_FourStep), np.dot(C, uk2_FourStep), np.dot(C, uk3_FourStep), np.dot(C, uk4_FourStep)))

    #XK Coefficients
    b1_TwoStep=(r+xref-np.dot(C,np.dot(xkC_TwoStep,xk))).reshape(-1)
    b2_TwoStep=(r-xref+np.dot(C,np.dot(xkC_TwoStep,xk))).reshape(-1)

    b1_ThreeStep = (r2 + xref - np.dot(C, np.dot(xkC_ThreeStep, xk))).reshape(-1)
    b2_ThreeStep = (r2 - xref + np.dot(C, np.dot(xkC_ThreeStep, xk))).reshape(-1)

    b1_FourStep = (r2 + xref - np.dot(C, np.dot(xkC_FourStep, xk))).reshape(-1)
    b2_FourStep = (r2 - xref + np.dot(C, np.dot(xkC_FourStep, xk))).reshape(-1)

    mdl = Model(name='BoundedRat')

    stateSize=10
    actionSize=4
    numProbs=6

    set_U_twoStep = range(0, actionSize * 2)
    set_U_threeStep = range(0, actionSize * 3)
    set_U_fourStep = range(0, actionSize * 4)
    set_State= range(0, stateSize)
    set_P = range(0, numProbs)

    MVecX=np.array([1000,1000,1000,1000,1000,1000,1000,1000,1000,10000])
    uUpper=np.array([45,7300,45,45,45,7300,45,45,45,7300,45,45,45,7300,45,45])
    uLower=np.array([-45,7269,-45,-45,-45,7269,-45,-45,-45,7269,-45,-45,-45,7269,-45,-45])

    Probs=np.array([0.0125,0.253,0.5244,0.8416,1.2815,1.644])


    # --- decision variables ---

    u_vars ={(i): mdl.continuous_var(lb=uLower[i], ub=uUpper[i],name="u_{0}".format(i))
     for i in set_U_fourStep}

    p_vars = {(i): mdl.binary_var(name="p_{0}".format(i))
              for i in set_P}

    # --- constraints ---
    # demand satisfaction

    #Positive absolute value of probability, positive absolute value of U

    constraintsCC_PP_UP = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (coef1_TwoStep[s,u] + Probs[p] * SigmaU_twostep[s,u])*u_vars[u]  for u in set_U_twoStep)<= (b1_TwoStep[s]-Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintCC_PP_UP_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, positive absolute value of U
    constraintsCC_PN_UP = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (-1*coef1_TwoStep[s,u] - Probs[p] * SigmaU_twostep[s,u])*u_vars[u]  for u in set_U_twoStep) <= (b2_TwoStep[s]+Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PN_UP_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}

    #Positive absolute value of probability, negative absolute value of U
    constraintsCC_PP_UN = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (coef1_TwoStep[s,u] - Probs[p] * SigmaU_twostep[s,u])*u_vars[u]   for u in set_U_twoStep)<= (b1_TwoStep[s]-Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PP_UN_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, negative absolute value of U
    constraintsCC_PN_UN= {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (-1*coef1_TwoStep[s,u] + Probs[p] * SigmaU_twostep[s,u])*u_vars[u]  for u in set_U_twoStep) <= (b2_TwoStep[s]+Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PN_UN_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}


    ##########################SET FOR THREE STEP
    constraintsCC_PP_UP = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (coef1_ThreeStep[s,u] + Probs[p] * SigmaU_threestep[s,u])*u_vars[u]  for u in set_U_threeStep)<= (b1_ThreeStep[s]-Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintCC_PP_UP_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, positive absolute value of U
    constraintsCC_PN_UP = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (-1*coef1_ThreeStep[s,u] - Probs[p] * SigmaU_threestep[s,u])*u_vars[u]  for u in set_U_threeStep) <= (b2_ThreeStep[s]+Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PN_UP_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}

    #Positive absolute value of probability, negative absolute value of U
    constraintsCC_PP_UN = {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (coef1_ThreeStep[s,u] - Probs[p] * SigmaU_threestep[s,u])*u_vars[u]   for u in set_U_threeStep)<= (b1_ThreeStep[s]-Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PP_UN_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, negative absolute value of U
    constraintsCC_PN_UN= {(s,p):
    mdl.add_constraint(
            ct=mdl.sum(-p_vars[p]*MVecX[s]+ (-1*coef1_ThreeStep[s,u] + Probs[p] * SigmaU_threestep[s,u])*u_vars[u]  for u in set_U_threeStep) <= (b2_ThreeStep[s]+Probs[p]*np.dot(SigmaXk[s],abs(xk))).item() ,
            ctname="chanceConstraintPlusCC_PN_UN_{0}_{1}".format(s,p))
        for s in set_State for p in set_P}

    #############SET FOR FOUR STEP
    constraintsCC_PP_UP = {(s, p):
        mdl.add_constraint(
            ct=mdl.sum(
                -p_vars[p] * MVecX[s] + (coef1_FourStep[s, u] + Probs[p] * SigmaU_fourstep[s, u]) * u_vars[u] for u in
                set_U_fourStep) <= (b1_FourStep[s] - Probs[p] * np.dot(SigmaXk[s], abs(xk))).item(),
            ctname="chanceConstraintCC_PP_UP_{0}_{1}".format(s, p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, positive absolute value of U
    constraintsCC_PN_UP = {(s, p):
        mdl.add_constraint(
            ct=mdl.sum(
                -p_vars[p] * MVecX[s] + (-1 * coef1_FourStep[s, u] - Probs[p] * SigmaU_fourstep[s, u]) * u_vars[u] for
                u in set_U_fourStep) <= (b2_FourStep[s] + Probs[p] * np.dot(SigmaXk[s], abs(xk))).item(),
            ctname="chanceConstraintPlusCC_PN_UP_{0}_{1}".format(s, p))
        for s in set_State for p in set_P}

    # Positive absolute value of probability, negative absolute value of U
    constraintsCC_PP_UN = {(s, p):
        mdl.add_constraint(
            ct=mdl.sum(
                -p_vars[p] * MVecX[s] + (coef1_FourStep[s, u] - Probs[p] * SigmaU_fourstep[s, u]) * u_vars[u] for u in
                set_U_fourStep) <= (b1_FourStep[s] - Probs[p] * np.dot(SigmaXk[s], abs(xk))).item(),
            ctname="chanceConstraintPlusCC_PP_UN_{0}_{1}".format(s, p))
        for s in set_State for p in set_P}
    # Negative absolute value of probability, negative absolute value of U
    constraintsCC_PN_UN = {(s, p):
        mdl.add_constraint(
            ct=mdl.sum(
                -p_vars[p] * MVecX[s] + (-1 * coef1_FourStep[s, u] + Probs[p] * SigmaU_fourstep[s, u]) * u_vars[u] for
                u in set_U_fourStep) <= (b2_FourStep[s] + Probs[p] * np.dot(SigmaXk[s], abs(xk))).item(),
            ctname="chanceConstraintPlusCC_PN_UN_{0}_{1}".format(s, p))
        for s in set_State for p in set_P}




    constraintsEQ_P = {
    mdl.add_constraint(
        ct=mdl.sum(p_vars[p] for p in set_P) == numProbs-1,
        ctname="ProbDecisionVariables_{0}_{1}")}


    # --- objective ---
    objective = mdl.sum(p_vars[p]*Probs[p] for p in set_P)-mdl.sum(valFunc[u+11]*u_vars[u] for u in set_U_twoStep)
    mdl.minimize(objective)
    sol=mdl.solve()
    mdl.print_solution()
    print(mdl.get_solve_status())

    solution=[sol[u_vars[u]] for u in set_U_twoStep]
    print([sol[u_vars[u]] for u in set_U_threeStep])


    return solution


def print_production_solution(mdl, products):
    obj = mdl.objective_value
    print("* Production model solved with objective: {:g}".format(obj))
    print("* Total inside cost=%g" % mdl.total_inside_cost.solution_value)
    for p in products:
        print("Inside production of {product}: {ins_var}".format
              (product=p[0], ins_var=mdl.inside_vars[p].solution_value))
    print("* Total outside cost=%g" % mdl.total_outside_cost.solution_value)
    for p in products:
        print("Outside production of {product}: {out_var}".format
              (product=p[0], out_var=mdl.outside_vars[p].solution_value))


# ----------------------------------------------------------------------------
# Solve the model and display the result
# ----------------------------------------------------------------------------


if __name__ == '__main__':
    # Build the model
    model = solve_br()
    model.print_information()
