# 出典: mo-notebooks/07/fleet-assignment.ipynb

# %%
# install dependencies and select solver

SOLVER = "highs"  # highs, scip, cbc, mosek, gurobi, cplex, xpress, 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 pandas as pd
import matplotlib.pyplot as plt
from numpy.random import RandomState


# python generator creates departure and arrival times for a single airport
def generate_flights(
    N_flights=30, min_duration=1, max_duration=4, max_departure=24, seed=0
):
    rs = RandomState(seed)
    for flight in range(N_flights):
        end_flight = max_departure + 1
        while end_flight > max_departure:
            start_flight = np.floor(max_departure * rs.rand())
            end_flight = start_flight + 3 * np.ceil(
                (max_duration + 1 - min_duration) * rs.rand()
            )
        yield flight + 1, int(start_flight), int(end_flight)


# generate flight data
FlightData = pd.DataFrame(
    [[flight, departure, arrival] for flight, departure, arrival in generate_flights()]
)
FlightData.columns = ["Flight", "Departure", "Arrival"]
FlightData.set_index("Flight", inplace=True)
FlightData.head()

# %%
# visualize flight data
def draw_flights(FlightData):
    bar_style = {"alpha": 1.0, "lw": 10, "solid_capstyle": "butt"}
    text_style = {
        "fontsize": 7,
        "color": "white",
        "weight": "bold",
        "ha": "center",
        "va": "center",
    }
    fig = plt.figure(figsize=(12, 7))
    ax = fig.add_subplot(111, xlabel="Departure/Arrival Time", title="Flight schedule")
    ax.get_yaxis().set_visible(False)
    for flight, row in FlightData.iterrows():
        departure, arrival = row
        ax.plot([departure, arrival], [flight] * 2, "gray", **bar_style)
        ax.text((departure + arrival) / 2, flight, f"Flight {flight}", **text_style)
    for hr in range(25):
        ax.axvline(hr, alpha=0.1)
    ax.set_xlim(-1, 25)
    ax.set_xticks([4 * i for i in range(7)])
    return ax


ax = draw_flights(FlightData)

# %%
min_time = 1


def feasible_flight_pairs(FlightData, min_time=1):
    # return a dictionary of turnaound times index by flight pairs
    turnaround = (
        lambda pair: FlightData.loc[pair[1], "Departure"]
        - FlightData.loc[pair[0], "Arrival"]
    )
    pairs = filter(
        lambda pair: turnaround(pair) >= min_time,
        [(i, j) for i in FlightData.index for j in FlightData.index if i != j],
    )
    return {pair: turnaround(pair) for pair in pairs}


flight_pairs = feasible_flight_pairs(FlightData).keys()

# %%
import networkx as nx

dg = nx.DiGraph()

for flight in FlightData.index:
    dg.add_node(flight)

for pair, dur in feasible_flight_pairs(FlightData).items():
    dg.add_edge(pair[0], pair[1], color="r" if dur <= min_time else "g")

size = int(1.5 * np.sqrt(len(FlightData)))
fig = plt.figure(figsize=(size, size))
pos = nx.circular_layout(dg)
nx.draw_networkx_nodes(dg, pos=pos, node_size=500, alpha=0.8)
nx.draw_networkx_labels(dg, pos=pos, font_color="w")
nx.draw_networkx_edges(
    dg, pos=pos, width=0.5, edge_color=[dg.edges[u, v]["color"] for u, v in dg.edges]
)

# %%
in_nodes = {flight: set() for flight in FlightData.index}
out_nodes = {flight: set() for flight in FlightData.index}

for flight1, flight2 in flight_pairs:
    in_nodes[flight2].add(flight1)
    out_nodes[flight1].add(flight2)

# %%
ampl = AMPL()
ampl.read("fleet_assign.mod")

ampl.set["FLIGHTS"] = list(FlightData.index)
ampl.set["PAIRS"] = list(flight_pairs)

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

print(f"Minimum airplanes required = {ampl.get_value('Airplanes')}")

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

# %%
import networkx as nx

dg_soln = nx.DiGraph()

for flight in FlightData.index:
    dg_soln.add_node(flight)

for pair, dur in feasible_flight_pairs(FlightData).items():
    if x[pair[0], pair[1]] > 0.5:
        dg_soln.add_edge(pair[0], pair[1], color="r" if dur <= min_time else "g")

size = int(1.5 * np.sqrt(len(FlightData)))
fig = plt.figure(figsize=(size, size))

nx.draw_networkx_nodes(dg_soln, pos=pos, node_size=500, alpha=0.8)
nx.draw_networkx_labels(dg_soln, pos=pos, font_color="w")
nx.draw_networkx_edges(
    dg_soln,
    pos=pos,
    width=3,
    edge_color=[dg_soln.edges[u, v]["color"] for u, v in dg_soln.edges],
)
nx.draw_networkx_edges(
    dg, pos=pos, width=0.5, edge_color=[dg.edges[u, v]["color"] for u, v in dg.edges]
)
nx.draw_networkx_edges(
    dg_soln,
    pos=pos,
    width=3,
    edge_color=[dg_soln.edges[u, v]["color"] for u, v in dg_soln.edges],
)

# %%
ax = draw_flights(FlightData)
for flight1, flight2 in flight_pairs:
    if x[flight1, flight2] > 0.5:
        arr = FlightData.loc[flight1, "Arrival"]
        dep = FlightData.loc[flight2, "Departure"]
        c = "r" if dep - arr <= min_time else "g"
        ax.plot([arr, dep], [flight1, flight2], color=c, lw=4, alpha=0.4)

for flight in FlightData.index:
    if p[flight] > 0.5:
        dep = FlightData.loc[flight, "Departure"]
        ax.plot([-1, dep], [flight] * 2, "g", lw=4, alpha=0.4)
    if q[flight] > 0.5:
        arr = FlightData.loc[flight, "Arrival"]
        ax.plot([arr, 25], [flight] * 2, "g", lw=4, alpha=0.4)

# %%
FlightSchedule = FlightData.copy()

# create a generator of aircraft ids
aircraft = (f"A{n+1:02d}" for n in range(len(FlightData.index)))

# traverse each path through the graph
for f in FlightData.index:
    if p[f] > 0.5:
        id = next(aircraft)
        FlightSchedule.loc[f, "Aircraft"] = id
        while q[f] < 0.5:
            f = next(filter(lambda _: x[f, _] > 0.5, out_nodes[f]))
            FlightSchedule.loc[f, "Aircraft"] = id

FlightSchedule = FlightSchedule[["Aircraft", "Departure", "Arrival"]]
display(FlightSchedule)

# %%
AircraftSchedule = FlightSchedule.copy()
AircraftSchedule["Flight"] = AircraftSchedule.index
AircraftSchedule = AircraftSchedule.sort_values(["Aircraft", "Departure"])
AircraftSchedule.index = pd.MultiIndex.from_frame(
    AircraftSchedule[["Aircraft", "Flight"]]
)
AircraftSchedule = AircraftSchedule[["Departure", "Arrival"]]
display(AircraftSchedule)

# %%
def schedule(FlightData, N_planes, min_time=1):
    pairs = feasible_flight_pairs(FlightData, min_time)

    weights = {pair: int(pairs[pair] <= min_time) for pair in pairs}

    ampl = AMPL()
    ampl.read("fleet_assign_minrisk.mod")

    ampl.set["FLIGHTS"] = list(FlightData.index)
    ampl.set["PAIRS"] = list(pairs.keys())
    ampl.param["N_planes"] = N_planes
    ampl.param["weight"] = weights

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

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

    ax = draw_flights(FlightData)
    for flight1, flight2 in pairs.keys():
        if x[flight1, flight2] > 0.5:
            arr = FlightData.loc[flight1, "Arrival"]
            dep = FlightData.loc[flight2, "Departure"]
            c = "r" if dep - arr <= min_time else "g"
            ax.plot([arr, dep], [flight1, flight2], color=c, lw=4, alpha=0.4)

    for flight in FlightData.index:
        if p[flight] > 0.5:
            dep = FlightData.loc[flight, "Departure"]
            ax.plot([-1, dep], [flight] * 2, "g", lw=4, alpha=0.4)
        if q[flight] > 0.5:
            arr = FlightData.loc[flight, "Arrival"]
            ax.plot([arr, 25], [flight] * 2, "g", lw=4, alpha=0.4)

    return ampl

# %%
m = schedule(FlightData, N_planes=14, min_time=1)

# %%
m = schedule(FlightData, N_planes=15, min_time=1)

# %%
m = schedule(FlightData, N_planes=15, min_time=2)
