# 出典: mo-notebooks/08/bim-robust-optimization.ipynb

# %%
# install dependencies and select solver

SOLVER_MILP = "highs"  # highs, scip, cbc, mosek, gurobi
SOLVER_NLO = "ipopt"
SOLVER_MINLO = "bonmin"  # mosek, scip, gurobi, knitro

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["coin", "highs"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register notebook magics

# %%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

# %%
ampl.eval(r"""
set CHIPS;

param profits{CHIPS};
param copper{CHIPS};

var x{CHIPS} >= 0;

maximize Profit: sum {c in CHIPS} profits[c] * x[c];

s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
s.t. Copper: sum {c in CHIPS} copper[c] * x[c] <= 4800;
""")

# %%
chips = ["logic", "memory"]
profits = {"logic": 12, "memory": 9}
copper = {"logic": 4, "memory": 2}

ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper

ampl.option["solver"] = SOLVER_MILP
ampl.solve()

x = ampl.get_variable("x").to_dict()

print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
def ShowDuals(ampl):
    import fractions

    # display all duals
    print("The dual variable corresponding to:\n")
    for name, con in ampl.get_constraints():
        print(
            "- the constraint on",
            name,
            "is equal to ",
            str(fractions.Fraction(con.dual())),
        )


ShowDuals(ampl)

# %%
plt.rcParams.update({"font.size": 12})

seed = 0
rng = np.random.default_rng(seed)
n = 2000

f = rng.lognormal(np.log(4.0), 0.005, n)
g = rng.lognormal(np.log(2.0), 0.005, n)

plt.figure()
plt.plot(f, g, ".")
plt.xlabel("Copper gr needed for logic chips")
plt.ylabel("Copper gr needed for memory chips")
plt.show()

# %%
plt.figure()
plt.plot(f, g, ".")
currentAxis = plt.gca()
currentAxis.add_patch(
    patches.Rectangle(
        (min(f), min(g)),
        max(f) - min(f),
        max(g) - min(g),
        fill=False,
        color="r",
    )
)
plt.xlabel("Copper gr needed for logic chips")
plt.ylabel("Copper gr needed for memory chips")
plt.show()

# calculate the upper and lower bounds for each uncertain parameter
lower = {"logic": min(f), "memory": min(g)}
upper = {"logic": max(f), "memory": max(g)}
print("Lower bounds", lower)
print("Upper bounds", upper)

# %%
def BIMWithBoxUncertainty(lower, upper, int_x=False):
    ampl = AMPL()
    ampl.read("BIM_robust_box.mod")

    ampl.set["CHIPS"] = chips
    ampl.param["profits"] = profits
    ampl.param["copper"] = copper

    ampl.param["lower"] = lower
    ampl.param["upper"] = upper

    if not int_x:
        ampl.eval("let {i in CHIPS} x[i].relax := 1;")

    ampl.solve(solver=SOLVER_MILP)
    assert ampl.solve_result == "solved", ampl.solve_result

    return ampl


ampl = BIMWithBoxUncertainty(lower, upper)

x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
# The parameter delta allows you to tune the amount of uncertainty.
# In particular, if you take delta=0, you obtain the same result as the nominal model.
delta = 0.05


def BIMWithSymmetricalBoxUncertainty(delta, int_x=False):
    lower = {chip: copper[chip] - delta for chip in chips}
    upper = {chip: copper[chip] + delta for chip in chips}
    return BIMWithBoxUncertainty(lower, upper, int_x)


ampl = BIMWithSymmetricalBoxUncertainty(delta)

x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
ampl = BIMWithBoxUncertainty(lower, upper, True)

x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
import pandas as pd

df = pd.DataFrame()
for delta in np.linspace(0, 0.5, 21):
    ampl = BIMWithSymmetricalBoxUncertainty(delta, True)
    x = ampl.get_variable("x").to_dict()
    results = [ampl.get_value("Profit")] + [x[str(i)] for i in chips]
    df.at[delta, "profit"] = results[0]
    df.at[delta, chips[0]] = results[1]
    df.at[delta, chips[1]] = results[2]
df

# %%
df[["profit"]].plot()
plt.ylim([16001, 17999])
plt.xlabel("Margin $\delta$ of the uncertainty box")
plt.ylabel("Profit")
plt.show()
df[["logic", "memory"]].plot()
plt.xlabel("Margin $\delta$ of the uncertainty box")
plt.ylabel("Optimal number of produced chips")
plt.show()

# %%
def BIMWithBudgetUncertainty(delta, gamma):
    ampl = AMPL()
    ampl.read("BIM_robust_cardinality.mod")

    ampl.set["CHIPS"] = chips
    ampl.param["profits"] = profits
    ampl.param["copper"] = copper

    ampl.param["delta"] = delta
    ampl.param["Gamma"] = gamma

    ampl.option["solver"] = SOLVER_MILP
    ampl.solve()

    return ampl


ampl = BIMWithBudgetUncertainty(0.01, 2)

x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
def BIMWithSetOfScenarios(Z=[{"logic": 0, "memory": 0}]):
    ampl = AMPL()
    ampl.read("BIM_robust_cardinality_adversarial.mod")

    ampl.set["CHIPS"] = chips
    ampl.param["profits"] = profits
    ampl.param["copper"] = copper

    dfZ = pd.DataFrame(Z)
    ampl.set["CUTS"] = list(dfZ.index)
    ampl.param["Z"] = dfZ.T.unstack(1)

    ampl.option["solver"] = SOLVER_MILP
    ampl.solve()

    return ampl

# %%
def BIMPessimization(x, delta, gamma):
    ampl = AMPL()
    ampl.read("BIM_robust_cardinality_pessimizer.mod")

    ampl.set["CHIPS"] = chips
    ampl.param["copper"] = copper

    ampl.param["x"] = x
    ampl.param["Gamma"] = gamma
    ampl.param["delta"] = delta

    ampl.option["solver"] = SOLVER_MILP
    ampl.solve()

    worst_z = ampl.get_variable("z").to_dict()

    return worst_z, ampl.get_value("Violation")

# %%
# Parameters
adversarial_converged = False
stopping_precision = 0.1
max_iterations = 5
adversarial_iterations = 0
delta = 0.2
gamma = 1.5
chips = ["logic", "memory"]

# Initialize the null scenario - no perturbation
Z = [{"logic": 0, "memory": 0}]

while (not adversarial_converged) and (adversarial_iterations < max_iterations):
    # Building and solving the master problem
    ampl = BIMWithSetOfScenarios(Z)

    # Saving the current solution
    x = ampl.get_variable("x").to_dict()

    print(f"\nIteration #{adversarial_iterations}")
    print(f"Current solution: ")
    for c in chips:
        print(f"x['{c}']= {x[c]:.2f}")

    # Pessimization
    worst_z, constraint_violation = BIMPessimization(x, delta, gamma)

    # If pessimization yields no violation, stop the procedure, otherwise add a scenario and repeat
    if constraint_violation < stopping_precision:
        print("No violation found. Stopping the procedure.")
        adversarial_converged = True
    else:
        print(
            f"Violation found: z['logic'] = {worst_z['logic']},  z['memory'] = {worst_z['memory']}, "
            f"constraint violation: {constraint_violation:6.2f}"
        )
        Z.append(worst_z)

    adversarial_iterations += 1

# %%
def BIMWithBallUncertainty(radius, SOLVER, int_x=False):
    ampl = AMPL()
    ampl.read("BIM_robust_ball.mod")
    if int_x:
        ampl.eval("redeclare var x{CHIPS} >= 0, integer;")

    ampl.set["CHIPS"] = chips
    ampl.param["profits"] = profits
    ampl.param["copper"] = copper

    ampl.param["radius"] = radius

    ampl.option["solver"] = SOLVER
    ampl.solve()

    return ampl

# %%
radius = 0.05
ampl = BIMWithBallUncertainty(radius, SOLVER_NLO)

x = ampl.get_variable("x").to_dict()
print(f"Solver: {SOLVER_NLO}, solver status:", ampl.solve_result)
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')

# %%
ampl = BIMWithBallUncertainty(radius, SOLVER_MINLO, True)

x = ampl.get_variable("x").to_dict()
print(f"Solver: {SOLVER_MINLO}, solver status:", ampl.solve_result)
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
