# --------------------------------------------------------------------------
# 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
import torch


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


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


def solve_br( Z=np.zeros((50)),
             fC2=np.zeros((5, 8 + 50)), fC3=np.ones((5)),fB2=np.ones((5)),fB3=np.ones((5)),
              ratF1=[],ratB1=[],ratF2=[],ratB2=[],
              ratF3=[],ratB3=[],includeSafety=True,probDisc=10):
    """ 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)
    """

    # print('xk',xk)



    # --- decision variables ---
    mdl = Model(name='BoundedRat')

    pUpper = np.array([4.0])
    pLower = np.array([0])
    set_params = range(0, 1)



    params= {(i): mdl.continuous_var(lb=pLower[i], ub=pUpper[i], name="u_{0}".format(i))
              for i in set_params}


    ################SAFETY CONSTRAINTS##########################3
    ###################RELU
    M = 100
    eps1=0
    rat_fc1 = ratF1[0].shape[0]
    rat_fc2 = ratF2[0].shape[0]
    rat_fc3 = 1
    # set_U_allStep = range(0, 8)
    rat_Neurons1 = range(0, rat_fc1)
    rat_Neurons2 = range(0, rat_fc2)
    rat_Neurons3 = range(0, rat_fc3)
    # set_Neurons = set([0,1,2,3,4])


    ratNum=len(ratF1)
    Ri_vars = {(i,r): mdl.binary_var(name="Ri_{0}_{1}".format(i,r))
              for i in rat_Neurons1 for r in range(0,ratNum)}
    Ro1 = {(i,r): mdl.continuous_var(lb=-1000000000, ub=100000000, name="Ro1_{0}_{1}".format(i,r), )
          for i in rat_Neurons1 for r in range(0,ratNum)}
    Ro2 = {(i,r): mdl.continuous_var(lb=-10000000000, ub=1000000000, name="Ro2_{0}_{1}".format(i,r))
          for i in rat_Neurons1 for r in range(0,ratNum)}
    Ro3 = {(i,r): mdl.continuous_var(lb=-1000000000, ub=100000000, name="Ro3_{0}_{1}".format(i,r), )
           for i in rat_Neurons2 for r in range(0,ratNum)}

    Ri_vars2 = {(i,r): mdl.binary_var(name="Ri2_{0}_{1}".format(i,r))
               for i in rat_Neurons2 for r in range(0,ratNum)}
    Ro4 = {(i,r): mdl.continuous_var(lb=-1000000000, ub=100000000, name="Ro4_{0}_{1}".format(i,r), )
          for i in rat_Neurons2 for r in range(0,ratNum)}
    Ro5 = {(i,r): mdl.continuous_var(lb=-10000000000, ub=1000000000, name="Ro5_{0}_{1}".format(i,r))
          for i in rat_Neurons3 for r in range(0,ratNum)}

    mean = mdl.continuous_var(lb=-10000000000, ub=1000000000, name="mean")
    stdVarI = {(r): mdl.continuous_var(lb=0, ub=100000000, name="stdVarI_{0}".format(r), )
          for r in range(0,ratNum)}
    allStdVar = mdl.continuous_var(lb=0, ub=1000000000, name="allStdVar")


    RconstraintsO1 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro1[n,rNum] == mdl.sum(ratF1[rNum][n, p] * params[p] +ratB1[rNum][n] for p in set_params),
            ctname="RchanceConstraintO1_{0}_{1}".format(n,rNum))
        for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL1 = {(n,rNum):
                          mdl.add_indicator(Ri_vars[n,rNum],
                                            0<= Ro1[n,rNum],
                                            name="RchanceConstraintRL1_{0}_{1}".format(n,rNum), active_value=1)
                      for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL2 = {(n,rNum):
                          mdl.add_indicator(Ri_vars[n,rNum],
                                            Ro1[n,rNum] <= 0,
                                            name="RchanceConstraintRL2_{0}_{1}".format(n,rNum), active_value=0)
                      for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL3 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro1[n,rNum] - (1 - Ri_vars[n,rNum]) * M -0 <= Ro2[n,rNum],
            ctname="RchanceConstraintRL3_{0}_{1}".format(n,rNum))
        for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL4 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro2[n,rNum] <= Ro1[n,rNum] + (1 - Ri_vars[n,rNum]) * M +0,
            ctname="RchanceConstraintRL4_{0}_{1}".format(n,rNum))
        for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL5 = {(n,rNum):
        mdl.add_constraint(
            -1 * (Ri_vars[n,rNum]) * M - 0 <= Ro2[n,rNum],
            ctname="RchanceConstraintRL5_{0}_{1}".format(n,rNum))
        for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsRL6 = {(n,rNum):
        mdl.add_constraint(
            Ro2[n,rNum] <= (Ri_vars[n,rNum]) * M + 0,
            ctname="RchanceConstraintRL6_{0}_{1}".format(n,rNum))
        for n in rat_Neurons1 for rNum in range(0,ratNum)}

    RconstraintsO1 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro3[n,rNum] == mdl.sum(ratF2[rNum][n,r].item() * Ro2[r,rNum] for r in rat_Neurons1)+ratB2[rNum][0],
            ctname="RchanceConstraintO1_{0}_{1}".format(n,rNum))
        for n in rat_Neurons2 for rNum in range(0,ratNum)}

    RconstraintsRL3 = {(n,rNum):
                          mdl.add_indicator(Ri_vars2[n,rNum],
                                            -eps1 <= Ro3[n,rNum],
                                            name="chanceConstraintRL3_{0}_{1}".format(n,rNum), active_value=1)
                      for n in rat_Neurons2 for rNum in range(0,ratNum)}

    RconstraintsRL4 = {(n):
                          mdl.add_indicator(Ri_vars2[n,rNum],
                                            Ro3[n,rNum] <= eps1,
                                            name="chanceConstraintRL4_{0}_{1}".format(n,rNum), active_value=0)
                      for n in rat_Neurons2 for rNum in range(0,ratNum)}

    RconstraintsRL3 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro3[n,rNum] - (1 - Ri_vars2[n,rNum]) * M - eps1 <= Ro4[n,rNum],
            ctname="chanceConstraintRL3_{0}_{1}".format(n,rNum))
        for n in rat_Neurons2 for rNum in range(0,ratNum)}

    constraintsRL4 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro4[n,rNum] <= Ro3[n,rNum] + (1 - Ri_vars2[n,rNum]) * M + eps1,
            ctname="chanceConstraintRL4_{0}_{1}".format(n,rNum))
        for n in rat_Neurons2 for rNum in range(0,ratNum)}

    RconstraintsRL5 = {(n,rNum):
        mdl.add_constraint(
            -1 * (Ri_vars2[n,rNum]) * M - eps1 <= Ro4[n,rNum],
            ctname="chanceConstraintRL5_{0}_{1}".format(n,rNum))
        for n in rat_Neurons2 for rNum in range(0,ratNum)}

    RconstraintsRL6 = {(n,rNum):
        mdl.add_constraint(
            Ro4[n,rNum] <= (Ri_vars2[n,rNum]) * M + eps1,
            ctname="chanceConstraintRL6_{0}_{1}".format(n,rNum))
        for n in rat_Neurons2 for rNum in range(0,ratNum)}

    constraintsO1 = {(n,rNum):
        mdl.add_constraint(
            ct=Ro5[n,rNum] == mdl.sum(ratF3[rNum][r].item() * Ro4[r,rNum] for r in rat_Neurons2) + ratB3[rNum][n],
            ctname="chanceConstraintO1_{0}_{1}".format(n,rNum))
        for n in rat_Neurons3 for rNum in range(0,ratNum)}

    constraintsMean = {(1):
        mdl.add_constraint(
            ct=mean == mdl.sum(Ro5[0, rNum] for rNum in range(0, ratNum))/ratNum,
            ctname="RchanceConstraintFinal")}

    std= {(rNum):
        mdl.add_constraint(
            ct=stdVarI[rNum] >= mean-Ro5[0, rNum],
            ctname="RchanceConstraintFinal_{0}".format(rNum)) for rNum in range(0, ratNum)}
    std = {(rNum):
        mdl.add_constraint(
            ct=stdVarI[rNum] >= Ro5[0, rNum]-mean,
            ctname="RchanceConstraintFinal_{0}".format(rNum)) for rNum in range(0, ratNum)}

    #Probs = np.array([0.1, .3, .5, .75, 1.0, 1.25, 2.63])
    Probs=np.linspace(0,2.63 , probDisc)
    numProbs = Probs.shape[0]
    set_P = range(0, numProbs)
    p_vars = {(i): mdl.binary_var(name="p1_{0}".format(i))
               for i in set_P}
    MVecX = 10000.0



    allStd = {(1):
        mdl.add_constraint(
            ct=allStdVar == mdl.sum(stdVarI[rNum]for rNum in range(0, ratNum))/ratNum,
            ctname="RchanceConstraintFinal") }

    if includeSafety==True:
        probLevel=.5
        threshold=-.5
        """final = {(1):
            mdl.add_constraint(
                ct= threshold<=  mean -probLevel*allStdVar,
                ctname="RchanceConstraintFinal")}
                """


        constraintsEQ_P2 = {
            mdl.add_constraint(
                ct=mdl.sum(p_vars[p] for p in set_P) == numProbs - 1,
                ctname="ProbDecisionVariables2_{0}_{1}")}
        constraintsCC_PP_UP = {(p):
            mdl.add_constraint(
                ct=threshold <=p_vars[p] * MVecX + mean-
                    (Probs[p] * allStdVar) ,
                ctname="chanceConstraintCC_PP_UP_{0}".format(p))
            for p in set_P}

    ###################RELU
    M = 100000
    neuronNum_fc2 = fC2.shape[0]
    set_Neurons2 = range(0, neuronNum_fc2)

    neuronNum_fc3 = fC3.shape[0]
    set_Neurons3 = range(0, neuronNum_fc3)

    i_vars1 = {(i): mdl.binary_var(name="i1_{0}".format(i))
              for i in set_Neurons2}
    o1 = {(i): mdl.continuous_var(lb=-1000000000, ub=100000000, name="o1_{0}".format(i), )
          for i in set_Neurons2}
    o2 = {(i): mdl.continuous_var(lb=-10000000000, ub=1000000000, name="o2_{0}".format(i))
          for i in set_Neurons2}
    o3 = {(i): mdl.continuous_var(lb=-1000000000, ub=100000000, name="o3_{0}".format(i), )
          for i in set_Neurons3}

    """neuronNum_fc4 = fC4.shape[0]
    # set_U_allStep = range(0, 8)
    set_Neurons4 = range(0, neuronNum_fc4)
    set_outNeurons=range(0,1)

    i_vars2 = {(i): mdl.binary_var(name="i2_{0}".format(i))
              for i in set_Neurons4}
    o4 = {(i): mdl.continuous_var(lb=-1000000000, ub=100000000, name="o4_{0}".format(i), )
          for i in set_Neurons4}
    o5 = {(i): mdl.continuous_var(lb=-10000000000, ub=1000000000, name="o5_{0}".format(i))
          for i in set_Neurons4}
          """



    uMat = fC2[:, -1:]
    ZMat = fC2[:, :-1]
    zVec = np.dot(ZMat, Z)
    ################RELU CONSTRAINTS
    eps1 = .0000001

    constraintsO1 = {(n):
        mdl.add_constraint(
            ct=o1[n] == mdl.sum(uMat[n, u] * params[u] for u in set_params) + zVec[n].item()+fB2[n],
            ctname="chanceConstraintO1_{0}".format(n))
        for n in set_Neurons2}

    constraintsRL1 = {(n):
                          mdl.add_indicator(i_vars1[n],
                                            -eps1 <= o1[n],
                                            name="chanceConstraintRL1_{0}".format(n), active_value=1)
                      for n in set_Neurons2}

    constraintsRL2 = {(n):
                          mdl.add_indicator(i_vars1[n],
                                            o1[n] <= eps1,
                                            name="chanceConstraintRL2_{0}".format(n), active_value=0)
                      for n in set_Neurons2}

    constraintsRL3 = {(n):
        mdl.add_constraint(
            ct=o1[n] - (1 - i_vars1[n]) * M - eps1 <= o2[n],
            ctname="chanceConstraintRL3_{0}".format(n))
        for n in set_Neurons2}

    constraintsRL4 = {(n):
        mdl.add_constraint(
            ct=o2[n] <= o1[n] + (1 - i_vars1[n]) * M + eps1,
            ctname="chanceConstraintRL4_{0}".format(n))
        for n in set_Neurons2}

    constraintsRL5 = {(n):
        mdl.add_constraint(
            -1 * (i_vars1[n]) * M - eps1 <= o2[n],
            ctname="chanceConstraintRL5_{0}".format(n))
        for n in set_Neurons2}

    constraintsRL6 = {(n):
        mdl.add_constraint(
            o2[n] <= (i_vars1[n]) * M + eps1,
            ctname="chanceConstraintRL6_{0}".format(n))
        for n in set_Neurons2}

    constraintsO1 = {(n):
        mdl.add_constraint(
            ct=o3[n] == mdl.sum(fC3[r] * o2[r] for r in set_Neurons2) + fB3[n],
            ctname="chanceConstraintO1_{0}".format(n))
        for n in range(0, 1)}


    """parts two"""
    """
    constraintsRL3 = {(n):
                          mdl.add_indicator(i_vars2[n],
                                            -eps1 <= o3[n],
                                            name="chanceConstraintRL3_{0}".format(n), active_value=1)
                      for n in set_Neurons3}

    constraintsRL4 = {(n):
                          mdl.add_indicator(i_vars2[n],
                                            o3[n] <= eps1,
                                            name="chanceConstraintRL4_{0}".format(n), active_value=0)
                      for n in set_Neurons3}

    constraintsRL3 = {(n):
        mdl.add_constraint(
            ct=o3[n] - (1 - i_vars2[n]) * M - eps1 <= o4[n],
            ctname="chanceConstraintRL3_{0}".format(n))
        for n in set_Neurons3}

    constraintsRL4 = {(n):
        mdl.add_constraint(
            ct=o4[n] <= o3[n] + (1 - i_vars2[n]) * M + eps1,
            ctname="chanceConstraintRL4_{0}".format(n))
        for n in set_Neurons3}

    constraintsRL5 = {(n):
        mdl.add_constraint(
            -1 * (i_vars2[n]) * M - eps1 <= o4[n],
            ctname="chanceConstraintRL5_{0}".format(n))
        for n in set_Neurons3}

    constraintsRL6 = {(n):
        mdl.add_constraint(
            o4[n] <= (i_vars2[n]) * M + eps1,
            ctname="chanceConstraintRL6_{0}".format(n))
        for n in set_Neurons3}

    constraintsO1 = {(n):
        mdl.add_constraint(
            ct=o5[n] == mdl.sum(fC4[r].item() * o4[r] for r in set_Neurons3)+fB4[0],
            ctname="chanceConstraintO1_{0}".format(n))
        for n in set_Neurons4}
        """


    # --- objective ---
    #

    maxInfoGain_Objective = mdl.sum(fC3[r].item() * o2[r] for r in set_Neurons2)+fB3[0]
    maxSafety_Objective=mdl.sum((1 - p_vars[p]) * Probs[p] for p in set_P)

    # -.0000001*maxInfoGain_Objective
    objective = maxInfoGain_Objective+.005*maxSafety_Objective
    mdl.maximize(objective)
    sol = mdl.solve()
    #print(mdl.get_solve_status())

    #mdl.print_solution()
    print("prob", [(1 - sol[p_vars[p2]]) * Probs[p2] for p2 in set_P])
    finalProb=np.sum(np.array( [(1 - sol[p_vars[p2]]) * Probs[p2] for p2 in set_P]))


    solution = sol[params[0]]
    maxVal = sol[o3[0]]
    #print('maxVal',maxVal)

    #print('Best Action for Info Gain',solution)
    return solution,finalProb


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