# --------------------------------------------------------------------------
# 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 solve_br(AAverage,BAverage,SigmaXk,SigmaU,xk=np.array([4.84,.002,.0001,.001,0,0,0,.01,-.01,100,1001])):
    """ 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)
    """
    simulator=sim.Simulation()
    t=simulator.t
    r=np.array([30,5,.5,10,5,1,5,10,30,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=np.hstack((SigmaU,SigmaU))
    SigmaU=np.delete(SigmaU,9,0)

    coef1=np.hstack((np.dot(C, (np.dot(AAverage,BAverage)*t*t  + BAverage*t)), (np.dot(C ,BAverage))*t))
    b1=xref-np.dot(C,np.dot((np.dot(AAverage,AAverage)*t*t+2*AAverage*t+np.identity(11)),xk))
    #b2=r-xref+np.dot(C,np.dot((np.dot(AAverage,AAverage)*t*t+2*AAverage*t+np.identity(11)),xk))

    mdl = Model(name='BoundedRat')

    stateSize=10
    actionSize=4
    numSamples=3
    numProbs=6

    set_Samp = range(0, numSamples )
    set_U = range(0, actionSize * 2)
    set_State= range(0, stateSize)
    set_P = range(0, numProbs)

    MVecX=np.array([100,100,100,100,100,100,100,100,100,1000])
    uUpper=np.array([35,8000000,35,35,35,8000000,35,55])
    uLower=np.array([-35,100,-35,-35,-35,100,-35,-35])

    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-1], ub=uUpper[i-1],name="u_{0}".format(i))
     for i in set_U}

    y_vars ={(i, j): mdl.binary_var(name="v_{0}_{1}".format(i, j))
     for i in set_U for j in set_Samp}
    z_vars ={(i, j): mdl.continuous_var(name="z_{0}_{1}".format(i, j))
     for i in set_U for j in set_Samp}

    w_vars = {(i, j): mdl.binary_var(name="w_{0}_{1}".format(i, j))
              for i in set_State for j in range(0,2)}
    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(-1*w_vars[s, 0]*MVecX[s]-p_vars[p]*MVecX[s]+ (coef1[s,u] + Probs[p] * SigmaU[s,u])*u_vars[u]  for u in set_U)<= (r+(b1[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(-1*w_vars[s, 0]*MVecX[s]-p_vars[p]*MVecX[s]+ (-1*coef1[s,u] - Probs[p] * SigmaU[s,u])*u_vars[u]  for u in set_U) <= (r-(b1[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(-1*w_vars[s, 1]*MVecX[s]-p_vars[p]*MVecX[s]+ (coef1[s,u] - Probs[p] * SigmaU[s,u])*u_vars[u]   for u in set_U)<= (r+b1[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(-1*w_vars[s, 1]*MVecX[s]-p_vars[p]*MVecX[s]+ (-1*coef1[s,u] + Probs[p] * SigmaU[s,u])*u_vars[u]  for u in set_U) <= (r-(b1[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}")}

    constraintsEQ_W= {
    mdl.add_constraint(
            ct=w_vars[s,0]+w_vars[s,1] ==1 ,
            ctname="WEq_{0}".format(s))
        for s in set_State}

    print('constraint')
    print(constraintsCC_PP_UP)

    # --- objective ---
    objective = mdl.sum(p_vars[p]*Probs[p] for p in set_P)
    print("OBJ")
    print(objective)
    mdl.minimize(objective)
    sol=mdl.solve()
    mdl.print_solution()
    print("SOLVED")
    print(mdl.get_solve_status())
    print(sol[p_vars[0]])
    print(sol[p_vars[1]])


    return mdl


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))


def build_default_production_problem(**kwargs):
    return solve_br(PRODUCTS, RESOURCES, CONSUMPTIONS, **kwargs)

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


if __name__ == '__main__':
    # Build the model
    model = solve_br(PRODUCTS, RESOURCES, CONSUMPTIONS)
    model.print_information()
    # Solve the model.
    if model.solve():
        print_production_solution(model, PRODUCTS)
        # Save the CPLEX solution as "solution.json" program output
        with get_environment().get_output_stream("solution.json") as fp:
            model.solution.export(fp, "json")
    else:
        print("Problem has no solution")