# 出典: mo-notebooks/10/ccg.ipynb

# %%
# install dependencies and select solver

SOLVER = "cbc"

from amplpy import AMPL, ampl_notebook

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

# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# %%
# Function to return the vectors and matrices c, q, R, S, t evaluated for a specific realization (z_A, z_B, z_D)
def model_params(z_A=0, z_B=0, z_D=0):
    c = {"x": -10}

    q = {"y1": 0, "y2": 0, "y3": 1}

    R = {
        "profit": {"x": 0},
        "demand": {"x": 0},
        "labor A": {"x": 0},
        "labor B": {"x": 0},
        "raw materials": {"x": -1},
    }

    S = {
        "profit": {
            "y1": -(140 - 50 * z_A - 80 * z_B),
            "y2": -(120 - 50 * z_A - 40 * z_B),
            "y3": 1,
        },
        "demand": {"y1": -1, "y2": 0, "y3": 0},
        "labor A": {"y1": 1, "y2": 1 + z_A, "y3": 0},
        "labor B": {"y1": 2 + 2 * z_B, "y2": 1 + z_B, "y3": 0},
        "raw materials": {"y1": 10, "y2": 9, "y3": 0},
    }

    t = {
        "profit": 0,
        "demand": -20 * (1 + z_D),
        "labor A": 80,
        "labor B": 100,
        "raw materials": 0,
    }

    return c, q, R, S, t


c, q, R, S, t = model_params()

print(f"c = {c}")
print(f"q = {q}")
print(f"R = {R}")
print(f"S = {S}")
print(f"t = {t}")

# %%
# Sample the random variables z_A, z_B, z_D uniformly in the given set
def z_sample(seed):
    rng = np.random.default_rng(seed)
    while True:
        sample = {
            "z_A": 0.15 * rng.uniform(low=-1, high=1),
            "z_B": 0.25 * rng.uniform(low=-1, high=1),
            "z_D": 0.25 * rng.uniform(low=-1, high=1),
        }
        if (
            abs(sample["z_A"]) / 0.15
            + abs(sample["z_B"]) / 0.25
            + abs(sample["z_D"]) / 0.25
            <= 2
        ):
            break
    return sample


# Convert the data of a double nested dictionary into a dictionary with compound keys
# For example {a: {b: c}} will be converted into {(a, b): c}
def flatten_dict(D):
    N = {}
    for k1, v1 in D.items():
        for k2, v2 in v1.items():
            N[(k1, k2)] = v2
    return N


# Aggregate data generated based on a list of sample parameters Z.
# S and t sets are generated for each sample and agregated in a dictionary
# with an aditional key to denote the scenario.
def scenarios_data(Z):
    S = {}
    t = {}
    for i, z in enumerate(Z):
        c0, q0, R0, S0, t0 = model_params(**z)
        for k1, v1 in S0.items():
            for k2, v2 in v1.items():
                S[(i, k1, k2)] = v2
        for k, v in t0.items():
            t[(i, k)] = v
    return S, t


# Function to solve the robust problem using the sampled realizations
def max_min_profit(Z):
    c, q, R, S, t = model_params()
    R = flatten_dict(R)

    # get model parameters for all the scenarios
    Sd, td = scenarios_data(Z)

    m = AMPL()
    m.read("max_min_profit.mod")

    m.set["I"] = c.keys()
    m.set["J"] = q.keys()
    m.set["SCENARIOS"] = list(range(len(Z)))
    m.set["SK"] = S.keys()

    m.param["c"] = c
    m.param["R"] = R
    m.param["S"] = Sd
    m.param["t"] = td

    # solve the problem
    m.solve(solver=SOLVER, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    return m

# %%
# Get a sample of 1000 realizations of the random variables z_A, z_B, z_D
N = 1000
Z = [z_sample(j) for j in range(N)]

# Solve the nominal problem
print("\nSolution to the nominal problem")
m = max_min_profit([{"z_A": 0, "z_B": 0, "z_D": 0}])
print(f"Objective value: {m.obj['worst_case_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")

# Solve the robust problem using the sampled realizations
print("\nSolution to the robust problem using sampling")
m = max_min_profit(Z)
print(f"Objective value: {m.obj['worst_case_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")

# %%
def max_avg_profit(Z):
    c, q, R, S, t = model_params()

    R = flatten_dict(R)
    Sd, td = scenarios_data(Z)

    m = AMPL()
    m.read("max_avg_profit.mod")

    m.set["I"] = c.keys()
    m.set["J"] = q.keys()
    m.set["SCENARIOS"] = list(range(len(Z)))
    m.set["SK"] = S.keys()

    m.param["c"] = c
    m.param["R"] = R
    m.param["S"] = Sd
    m.param["t"] = td

    # solve the problem
    m.solve(solver=SOLVER, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    return m

# %%
m = max_avg_profit(Z)
print(f"Objective value: {m.obj['avg_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")

# Store the per-scenario profit realizations into a numpy array
avg_case_ps = np.zeros(len(Z))

for s in range(len(Z)):
    mystr = "sum{i in I} (c[i] * x[i]) + y[%d, 'y3'];" % (s,)
    avg_case_ps[s] = m.get_value(mystr)

# %%
def max_profit_fixed_x(Z, fixed_x_value, worst_case=True):
    c, q, R, S, t = model_params()

    R = flatten_dict(R)
    Sd, td = scenarios_data(Z)

    m = AMPL()
    m.read("max_profit_fixed_x.mod")

    m.set["I"] = list(c.keys())
    m.set["J"] = list(q.keys())
    m.set["SCENARIOS"] = list(range(len(Z)))
    m.set["SK"] = list(S.keys())

    m.param["R"] = R
    m.param["c"] = c
    m.param["S"] = Sd
    m.param["t"] = td
    m.param["worst_case"] = 1 if worst_case else 0

    for i in list(c.keys()):
        m.var["x"][i].fix(fixed_x_value)

    # solve the problem
    m.solve(solver=SOLVER, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    return m

# %%
xopt_rob = 547.81
print(
    f"\nSolving for the average with optimal-worst-case first-stage decision x = {xopt_rob}"
)
m = max_profit_fixed_x(Z, xopt_rob, worst_case=False)
print(f"Objective value: {m.obj['profit'].value():.2f} (average profit)")

# Extracting the per-scenario realizations of the worst-case optimal solution
worst_case_ps = np.zeros(len(Z))
for s in range(len(Z)):
    mystr = "sum{i in I} (c[i] * x[i]) + y[%d, 'y3'];" % (s,)
    worst_case_ps[s] = m.get_value(mystr)

xopt_avg = 637.08
print(
    f"\nSolving for the worst-case with optimal-average first-stage decision x = {xopt_avg}"
)
m = max_profit_fixed_x(Z, xopt_avg, worst_case=True)
print(f"Objective value: {m.obj['profit'].value():.2f} (worst-case profit)")

# %%
# Collecting the per-scenario optimal values of both the stochastic and robust problems
data = pd.DataFrame({"Robust": worst_case_ps, "Stochastic": avg_case_ps})

# Plotting the results in a histogram
fig, ax = plt.subplots(figsize=(10, 6))
data.plot.hist(bins=20, alpha=0.5, ax=ax)
ax.set_xlabel("Profit")
plt.show()

# %%
def subproblem_params(dec):
    Left = {
        "demand": {"z_A": 0, "z_B": 0, "z_D": 20},
        "profit": {
            "z_A": (50 * dec["y1"] + 50 * dec["y2"]),
            "z_B": (80 * dec["y1"] + 40 * dec["y2"]),
            "z_D": 0,
        },
        "labor A": {"z_A": dec["y1"] + dec["y2"], "z_B": 0, "z_D": 0},
        "labor B": {"z_A": 0, "z_B": 2 * dec["y1"] + dec["y2"], "z_D": 0},
    }

    Right = {
        "demand": dec["y1"] - 20,
        "profit": 140 * dec["y1"] + 120 * dec["y2"] - dec["y3"],
        "labor A": 80 - dec["y1"] - dec["y2"],
        "labor B": 100 - 2 * dec["y1"] - dec["y2"],
    }

    return Left, Right


def subproblem_data(master_solution):
    L = {}
    R = {}

    for s in range(len(master_solution)):
        L0, R0 = subproblem_params(master_solution[s])

        for k1, v1 in L0.items():
            for k2, v2 in v1.items():
                L[(s, k1, k2)] = v2

        for k, v in R0.items():
            R[(s, k)] = v

    return L, R

# %%
def pessimization_problem(
    master_solution,
    z_A_max=0.15,
    z_B_max=0.25,
    z_D_max=0.5,
    Gamma=2,
):
    z_max = {"z_A": z_A_max, "z_B": z_B_max, "z_D": z_D_max}
    big_M = 1000

    L, R = subproblem_params(master_solution[0])
    Ld, Rd = subproblem_data(master_solution)

    m = AMPL()
    m.read("pessimization_problem.mod")

    m.set["Z_INDICES"] = z_max.keys()
    m.set["SCENARIOS"] = range(len(master_solution))
    m.set["LKEYS"] = L.keys()

    m.param["z_max"] = z_max
    m.param["Gamma"] = Gamma
    m.param["L"] = Ld
    m.param["R"] = Rd
    m.param["big_M"] = big_M

    m.solve(solver=SOLVER, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    theta = m.var["theta"].value()
    z = m.var["z"].to_dict()

    return theta, z["z_A"], z["z_B"], z["z_D"]

# %%
ccg_converged = False
stopping_precision = 0.1
max_iterations = 50
ccg_iterations = 0

# Initialize the null scenario - no perturbation
Z = [{"z_A": 0, "z_B": 0, "z_D": 0}]

while (not ccg_converged) and (ccg_iterations < max_iterations):
    # Building and solving the master problem
    m = max_min_profit(Z)

    # Exporting the data from the master problem into a list of dictionaries
    c, q, *_ = model_params()

    master_solution = []

    print(f"\nIteration #{ccg_iterations}")

    for s in range(len(Z)):
        single_solution = {}

        for x_key in c.keys():
            single_solution[x_key] = m.var["x"][x_key].value()

        for y_key in q.keys():
            single_solution[y_key] = m.var["y"][s, y_key].value()

        master_solution.append(single_solution)

    print(f'Current solution: x = {master_solution[0]["x"]:.2f}')

    # Pessimization
    theta_opt, z_A, z_B, z_D = pessimization_problem(
        master_solution, 0.15, 0.25, 0.25, 2
    )

    # If pessimization yields no violation, stop the procedure, otherwise add a scenario and repeat
    if theta_opt < stopping_precision:
        print("No violation found. Stopping the procedure.")
        ccg_converged = True
    else:
        print(
            f"Violation found: z_A = {z_A:4.2f},  z_B = {z_B:4.2f},  z_D = {z_D:4.2f}"
        )
        print(f"Constraint violation: {theta_opt:6.2f}")
        Z.append({"z_A": z_A, "z_B": z_B, "z_D": z_D})

    ccg_iterations += 1
