# 出典: mo-notebooks/09/economicdispatch.ipynb

# %%
# install AMPL and solvers

SOLVER = "highs"

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["highs"],  # 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
import seaborn as sns

# %%
def read_economic_dispatch_data():
    # Read local nodes.csv if exists
    base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/notebooks/09/"
    nodes_df = pd.read_csv(base_url + "nodes.csv", index_col=0)[
        ["node_id", "d", "p_min", "p_max", "c_var"]
    ]
    wind_production_samples_df = pd.read_csv(base_url + "discrete_wind.csv").T

    # Read data
    nodes = nodes_df.set_index("node_id").T.to_dict()
    wind_production_samples = list(wind_production_samples_df.to_dict().values())
    wind_production_samples = [sum(d.values()) for d in wind_production_samples]

    return nodes, wind_production_samples


nodes, wind_production_samples = read_economic_dispatch_data()

# %%
wind_production_samples[4]  # fifth outcome

# %%
sns.set_style("darkgrid")
sns.histplot(
    wind_production_samples, kde=True, stat="density", kde_kws=dict(cut=1)
).set_title("wind production")
plt.show()

# %%
nodes[0]  # first node properties

# %%
df_nodes = pd.DataFrame.from_dict(nodes, orient="index")
df_nodes["type"] = "consumer"
df_nodes.loc[df_nodes.p_max > 0, "type"] = "producer"
np.random.seed(2023)
df_nodes["x"] = np.random.randint(0, 100, len(nodes))
df_nodes["y"] = np.random.randint(0, 100, len(nodes))
df_nodes["size"] = df_nodes[["d", "p_max"]].max(axis=1)


def ShowInstance(df_nodes):
    # Define the size of the figure
    fig, ax = plt.subplots(figsize=(8, 6))

    # Set the scales of the x and y axes
    ax.set_xlim([min(df_nodes["x"]) - 10, max(df_nodes["x"]) + 10])
    ax.set_ylim([min(df_nodes["y"]) - 10, max(df_nodes["y"]) + 10])

    # Create a scatter plot with bubbles proportional to size
    # ax.scatter(df_nodes['x'], df_nodes['y'], s=df_nodes['size']*1)
    for (category, group), z, color in zip(
        df_nodes.groupby("type"), [2, 1], ["red", "green"]
    ):
        ax.scatter(
            group.x,
            group.y,
            s=group["size"] * 1,
            label=category,
            alpha=0.2,
            zorder=z,
            color=color,
        )
        if "sol" in group:
            ax.scatter(
                group.x,
                group.y,
                s=group["sol"] * 1,
                label=None,
                alpha=1,
                zorder=z,
                color=color,
            )

    plt.legend()
    # Show the chart
    plt.show()


ShowInstance(df_nodes)

# %%
def economic_dispatch(nodes_df, samples, eps, Delta):
    # Create AMPL instance and load the model
    ampl = AMPL()
    ampl.read("economic_dispatch.mod")

    # Load the data
    ampl.set["V"] = nodes_df["node_id"]
    ampl.param["c"] = nodes_df["c_var"]
    ampl.param["p_min"] = nodes_df["p_min"]
    ampl.param["p_max"] = nodes_df["p_max"]
    ampl.param["d"] = nodes_df["d"]

    ampl.param["N"] = len(samples)
    ampl.param["samples"] = samples

    ampl.param["eps"] = eps
    ampl.param["Delta"] = Delta

    # Set solver
    ampl.option["solver"] = SOLVER

    return ampl

# %%
# Data
eps = 0.20
Delta = 1000
N = 500

base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/notebooks/09/"
# Dataframe with node information
nodes_df = pd.read_csv(base_url + "nodes.csv", index_col=0)[
    ["node_id", "d", "p_min", "p_max", "c_var"]
]

# Solve model and report the solution
model = economic_dispatch(nodes_df, wind_production_samples, eps, Delta)
model.solve()

sum_production = model.get_value("sum{i in V} p[i]")
sum_demand = sum(nodes_df["d"])
print(f"Total energy demand: {sum_demand:.3f}")
print(f"Total optimal energy production: {sum_production:.3f}")
print(f"Total energy production cost: {model.obj['my_objective'].value():.3f}")

# %%
df_nodes["sol"] = model.var["p"].to_pandas()
ShowInstance(df_nodes)

# %%
fixed_Delta = 1000

feas_eps = []
feas_objs = []

eps = 0
model = economic_dispatch(nodes_df, wind_production_samples, eps, fixed_Delta)

for eps in np.linspace(0, 1, num=20):
    model.param["eps"] = eps
    model.solve()
    assert model.solve_result == "solved", model.solve_result

    if model.solve_result == "solved":
        feas_eps.append(eps)
        feas_objs.append(model.obj["my_objective"].value())

plt.plot(feas_eps, feas_objs, marker="o", linestyle="--")
plt.xlabel("$\epsilon$")
plt.ylabel("objective value")
plt.show()

# %%
fixed_eps = 0.02

feas_Deltas = []
feas_objs = []

Delta = 0
model = economic_dispatch(nodes_df, wind_production_samples, fixed_eps, Delta)

for Delta in np.linspace(0, 2000, num=20):
    model.param["Delta"] = Delta
    model.solve()
    assert model.solve_result in ["solved", "infeasible"], model.solve_result

    if model.solve_result == "solved":
        feas_Deltas.append(Delta)
        feas_objs.append(model.obj["my_objective"].value())

plt.plot(feas_Deltas, feas_objs, marker="o", linestyle="--")
plt.xlabel("$\Delta$")
plt.ylabel("objective value")
plt.show()
