# 出典: mo-notebooks/03/recharging-electric-vehicle.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 numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# specify number of charging stations
n_charging_stations = 20

# randomly distribute charging stations along a fixed route
np.random.seed(1842)
d = np.round(np.cumsum(np.random.triangular(20, 150, 223, n_charging_stations)), 1)

# randomly assign changing capacities
c = np.random.choice([50, 100, 150, 250], n_charging_stations, p=[0.2, 0.4, 0.3, 0.1])

# assign names to the charging stations
s = [f"S_{i:02d}" for i in range(n_charging_stations)]

stations = pd.DataFrame([s, d, c]).T
stations.columns = ["name", "location", "kw"]
display(stations)

# %%
# current location (km) and charge (kw)
x = 0

# planning horizon
D = 2000

# visualize
fig, ax = plt.subplots(1, 1, figsize=(15, 3))


def plot_stations(stations, x, D, ax=ax):
    for station in stations.index:
        xs = stations.loc[station, "location"]
        ys = stations.loc[station, "kw"]
        ax.plot([xs, xs], [0, ys], "b", lw=10, solid_capstyle="butt")
        ax.text(xs, 0 - 30, stations.loc[station, "name"], ha="center")

    ax.plot([x, x + D], [0, 0], "r", lw=5, solid_capstyle="butt", label="plan horizon")
    ax.plot([x, x + D], [0, 0], "r.", ms=20)

    ax.axhline(0)
    ax.set_ylim(-50, 300)
    ax.set_xlabel("Distance")
    ax.set_ylabel("kw")
    ax.set_title("charging stations")
    ax.legend()


plot_stations(stations, x, D)

# %%
# charge limits (kw)
c_max = 150
c_min = 0.2 * c_max
c = c_max

# velocity km/hr and discharge rate kwh/km
v = 100.0
R = 0.24

# lost time
t_lost = 10 / 60
t_rest = 10 / 60

# rest time
r_max = 3

# %%
def ev_plan(stations, x, D):
    # data preprocessing

    # find stations between x and x + D
    on_route = stations[(stations["location"] >= x) & (stations["location"] <= x + D)]

    # adjust the index to match the model directly
    on_route.index += 1

    n = len(on_route)

    # get the values of the location parameter
    location = on_route["location"].to_dict()
    location[0] = x
    location[n + 1] = x + D

    # get the values for the dist parameter
    dist = {}
    for s in range(1, n + 2):
        dist[s] = location[s] - location[s - 1]

    # define the indexing sets
    # note the +1 at the end because Python ranges are not inclusive at the endpoint
    STATIONS = list(range(1, n + 1))  # 1 to n
    LOCATIONS = list(range(n + 2))  # 0 to n + 1
    SEGMENTS = list(range(1, n + 2))  # 1 to n + 1

    # instantiate AMPL and load model
    m = AMPL()
    m.read("ev_plan.mod")

    m.set["STATIONS"] = STATIONS
    m.set["LOCATIONS"] = LOCATIONS
    m.set["SEGMENTS"] = SEGMENTS

    # load data
    m.param["C"] = on_route["kw"]
    m.param["location"] = location
    m.param["D"] = D
    m.param["n"] = n
    m.param["c_min"] = c_min
    m.param["c_max"] = c_max
    m.param["r_max"] = r_max
    m.param["t_lost"] = t_lost
    m.param["v"] = v
    m.param["R"] = R
    m.param["dist"] = dist

    # initial conditions
    m.var["x"][0].fix(x)
    m.var["t_dep"][0].fix(0.0)
    m.var["r_dep"][0].fix(0.0)
    m.var["c_dep"][0].fix(c)

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

    return m


def get_results(model):
    x = [(int(k), v) for k, v in model.var["x"].to_list()]
    t_arr = [v for k, v in model.var["t_arr"].to_list()]
    t_dep = [v for k, v in model.var["t_dep"].to_list()]
    c_arr = [v for k, v in model.var["c_arr"].to_list()]
    c_dep = [v for k, v in model.var["c_dep"].to_list()]

    results = pd.DataFrame(x, columns=["index", "location"]).set_index("index")
    results["t_arr"] = t_arr
    results["t_dep"] = t_dep
    results["c_arr"] = c_arr
    results["c_dep"] = c_dep
    results["t_stop"] = results["t_dep"] - results["t_arr"]
    results["t_stop"] = results["t_stop"].round(6)

    return results


m = ev_plan(stations, 0, 2000)
results = get_results(m)
display(results)

# %%
# visualize


def visualize(m):
    D = m.param["D"].value()

    results = get_results(m)

    results["t_stop"] = results["t_dep"] - results["t_arr"]

    fig, ax = plt.subplots(2, 1, figsize=(15, 8), sharex=True)

    # plot stations
    for station in stations.index:
        xs = stations.loc[station, "location"]
        ys = stations.loc[station, "kw"]
        ax[0].plot([xs, xs], [0, ys], "b", lw=10, solid_capstyle="butt")
        ax[0].text(xs, 0 - 30, stations.loc[station, "name"], ha="center")

    # plot planning horizon
    ax[0].plot(
        [x, x + D], [0, 0], "r", lw=5, solid_capstyle="butt", label="plan horizon"
    )
    ax[0].plot([x, x + D], [0, 0], "r.", ms=20)

    # annotations
    ax[0].axhline(0)
    ax[0].set_ylim(-50, 300)
    ax[0].set_ylabel("kw")
    ax[0].set_title("charging stations")
    ax[0].legend()

    SEGMENTS = m.set["SEGMENTS"].to_list()

    # plot battery charge
    for i in SEGMENTS:
        xv = [results.loc[i - 1, "location"], results.loc[i, "location"]]
        cv = [results.loc[i - 1, "c_dep"], results.loc[i, "c_arr"]]
        ax[1].plot(xv, cv, "g")

    STATIONS = m.set["STATIONS"].to_list()

    # plot charge at stations
    for i in STATIONS:
        xv = [results.loc[i, "location"]] * 2
        cv = [results.loc[i, "c_arr"], results.loc[i, "c_dep"]]
        ax[1].plot(xv, cv, "g")

    # mark stop locations
    for i in STATIONS:
        if results.loc[i, "t_stop"] > 0:
            ax[1].axvline(results.loc[i, "location"], color="r", ls="--")

    # show constraints on battery charge
    ax[1].axhline(c_max, c="g")
    ax[1].axhline(c_min, c="g")
    ax[1].set_ylim(0, 1.1 * c_max)
    ax[1].set_ylabel("Charge (kw)")


visualize(ev_plan(stations, 0, 2000))
