# 出典: mo-notebooks/04/power-network.ipynb

# %%
# install dependencies and select solver

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 time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx

# %%
# Download the data
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/dev/notebooks/04/"
nodes_df = pd.read_csv(base_url + "nodes.csv").set_index(["node_id", "instance"])
edges_df = pd.read_csv(base_url + "edges.csv").set_index(["node_id1", "node_id2"])

# Replace 'na' by an empty string
nodes_df.fillna("", inplace=True)

# Split the initial nodes data frame by instance
nodes_by_instance = [
    y.reset_index(level=1).drop("instance", axis=1)
    for x, y in nodes_df.groupby("instance")
]
I = [{"nodes": n, "edges": edges_df} for n in nodes_by_instance]

# Initialize a network for demonstration purposes
network = I[0]

# %%
def visualize_network(network, edge_flows=None, ax=None):
    """Visualize a network instance, highlighting the generators in orange and the load buses in green."""
    plt.figure(figsize=[12, 10])
    g = nx.DiGraph(list(network["edges"].index))
    pos = nx.layout.kamada_kawai_layout(g, weight=None)

    color_mapping = {
        "solar": "#ffcb36",
        "wind": "white",
        "hydro": "#a5efff",
        "coal": "#686868",
        "gas": "#00ab4e",
        "": "#b6b6b6",
    }

    vertex2color = {
        k: color_mapping[v] for k, v in network["nodes"]["energy_type"].items()
    }
    v2c_list = [vertex2color[i] for i in g.nodes]  # Order based on networkx

    nodes = nx.draw_networkx_nodes(
        g,
        pos,
        node_size=250,
        node_color=v2c_list,
        linewidths=2,
    )
    edges = nx.draw_networkx_edges(
        g,
        pos,
        width=2,
        edge_color="#595959",
    )

    # Gives node colors
    ax = plt.gca()
    ax.collections[0].set_edgecolor("#595959")
    ax.set_axis_off()

# %%
visualize_network(network)

# %%
example_nodes = network["nodes"]
example_nodes[example_nodes.is_generator]

# %%
example_nodes[~example_nodes.is_generator]

# %%
edges_df

# %%
def OPF1(network):
    """
    Input:
    - network: a dictionary containing:
      - a dictionary of nodes with a dictionary of attributes
      - a dictionary of edges with a dictionary of attributes

    Output:
    - total energy dispatching cost
    """

    nodes = network["nodes"]
    edges = network["edges"]

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

    m.set_data(nodes, "NODES")
    m.set_data(edges, "EDGES")

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

    return m.obj["energy_cost"].value()

# %%
OPF1_results = [OPF1(instance) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF1_results):.2f}")

# %%
def OPF2(network, max_gas_plants, max_coal_plants):
    """
    Input:
    - network: a dictionary containing:
      - a dictionary of nodes with a dictionary of attributes
      - a dictionary of edges with a dictionary of attributes

    Output:
    - total energy dispatching cost
    """

    nodes = network["nodes"]
    edges = network["edges"]

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

    m.set_data(nodes, "NODES")
    m.set_data(edges, "EDGES")

    m.param["max_gas_plants"] = max_gas_plants
    m.param["max_coal_plants"] = max_coal_plants

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

    return m.obj["energy_cost"].value()

# %%
max_gas_plants = 2
max_coal_plants = 1
OPF2_results = [OPF2(instance, max_gas_plants, max_coal_plants) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF2_results):.2f}")

# %%
def OPF3(network, max_gas_plants, max_coal_plants):
    """
    Input:
    - network: a dictionary containing:
      - a dictionary of nodes with a dictionary of attributes
      - a dictionary of edges with a dictionary of attributes

    Output:
    - total energy dispatching cost
    """

    nodes = network["nodes"]
    edges = network["edges"]

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

    m.set_data(nodes, "NODES")
    m.set_data(edges, "EDGES")

    m.param["max_gas_plants"] = max_gas_plants
    m.param["max_coal_plants"] = max_coal_plants

    m.param["M0"] = 4
    m.param["M1"] = 3
    m.param["M2"] = nodes["p_max"].sum()

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

    return m.obj["energy_cost"].value()

# %%
OPF3_results = [OPF3(instance, max_gas_plants, max_coal_plants) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF3_results):.2f}")

# %%
objs = [OPF1_results, OPF2_results, OPF3_results]

# %%
plt.plot(objs[0], color="blue", label="OPF1")
plt.plot(objs[1], color="green", label="OPF2")
plt.plot(objs[2], color="orange", label="OPF3")
plt.title("Optimal objective values over all instances and models")
plt.xlabel("Instance number")
plt.ylabel("Optimal objective value")
plt.legend()
plt.show()
