# 出典: mo-notebooks/03/job-shop-scheduling.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

# %%
TASKS = {
    ("Paper_1", "Blue"): {"dur": 45, "prec": None},
    ("Paper_1", "Yellow"): {"dur": 10, "prec": ("Paper_1", "Blue")},
    ("Paper_2", "Blue"): {"dur": 20, "prec": ("Paper_2", "Green")},
    ("Paper_2", "Green"): {"dur": 10, "prec": None},
    ("Paper_2", "Yellow"): {"dur": 34, "prec": ("Paper_2", "Blue")},
    ("Paper_3", "Blue"): {"dur": 12, "prec": ("Paper_3", "Yellow")},
    ("Paper_3", "Green"): {"dur": 17, "prec": ("Paper_3", "Blue")},
    ("Paper_3", "Yellow"): {"dur": 28, "prec": None},
}

# %%
def jobshop_model(TASKS):
    m = AMPL()
    m.read("jobshop_model.mod")

    jobs = list(set([j for (j, m) in TASKS]))
    machines = list(set([m for (j, m) in TASKS]))
    tasks = list(TASKS.keys())
    taskorder = [
        (j, m, k, n)
        for (j, m) in tasks
        for (k, n) in tasks
        if (k, n) == TASKS[(j, m)]["prec"]
    ]
    disjunctions = [
        (j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
    ]
    dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
    ub = sum(dur[i] for i in dur)

    m.set["JOBS"] = jobs
    m.set["MACHINES"] = machines
    m.set["TASKS"] = tasks
    m.set["TASKORDER"] = taskorder
    m.set["DISJUNCTIONS"] = disjunctions

    m.param["dur"] = dur
    m.param["ub"] = ub

    return m


jobshop_model(TASKS)

# %%
def jobshop_solve(model):
    model.solve(solver=SOLVER)
    assert model.solve_result == "solved", model.solve_result

    start = model.var["start"].to_dict()
    dur = model.param["dur"].to_dict()
    tasks = model.set["TASKS"].to_dict()

    results = [
        {
            "Job": j,
            "Machine": m,
            "Start": start[j, m],
            "Duration": dur[j, m],
            "Finish": start[j, m] + dur[j, m],
        }
        for j, m in tasks
    ]
    return results


def jobshop(TASKS):
    return jobshop_solve(jobshop_model(TASKS))


results = jobshop(TASKS)
results

# %%
import pandas as pd

schedule = pd.DataFrame(results)

print("\nSchedule by Job")
print(schedule.sort_values(by=["Job", "Start"]).set_index(["Job", "Machine"]))

print("\nSchedule by Machine")
print(schedule.sort_values(by=["Machine", "Start"]).set_index(["Machine", "Job"]))

# %%
import matplotlib.pyplot as plt
import matplotlib as mpl


def visualize(results):
    schedule = pd.DataFrame(results)
    JOBS = sorted(list(schedule["Job"].unique()))
    MACHINES = sorted(list(schedule["Machine"].unique()))
    makespan = schedule["Finish"].max()

    bar_style = {"alpha": 1.0, "lw": 25, "solid_capstyle": "butt"}
    text_style = {"color": "white", "weight": "bold", "ha": "center", "va": "center"}
    colors = mpl.cm.Dark2.colors

    schedule.sort_values(by=["Job", "Start"])
    schedule.set_index(["Job", "Machine"], inplace=True)

    fig, ax = plt.subplots(2, 1, figsize=(12, 5 + (len(JOBS) + len(MACHINES)) / 4))

    for jdx, j in enumerate(JOBS, 1):
        for mdx, m in enumerate(MACHINES, 1):
            if (j, m) in schedule.index:
                xs = schedule.loc[(j, m), "Start"]
                xf = schedule.loc[(j, m), "Finish"]
                ax[0].plot([xs, xf], [jdx] * 2, c=colors[mdx % 7], **bar_style)
                ax[0].text((xs + xf) / 2, jdx, m, **text_style)
                ax[1].plot([xs, xf], [mdx] * 2, c=colors[jdx % 7], **bar_style)
                ax[1].text((xs + xf) / 2, mdx, j, **text_style)

    ax[0].set_title("Job Schedule")
    ax[0].set_ylabel("Job")
    ax[1].set_title("Machine Schedule")
    ax[1].set_ylabel("Machine")

    for idx, s in enumerate([JOBS, MACHINES]):
        ax[idx].set_ylim(0.5, len(s) + 0.5)
        ax[idx].set_yticks(range(1, 1 + len(s)))
        ax[idx].set_yticklabels(s)
        ax[idx].text(
            makespan,
            ax[idx].get_ylim()[0] - 0.2,
            "{0:0.1f}".format(makespan),
            ha="center",
            va="top",
        )
        ax[idx].plot([makespan] * 2, ax[idx].get_ylim(), "r--")
        ax[idx].set_xlabel("Time")
        ax[idx].grid(True)

    fig.tight_layout()


visualize(results)

# %%
def recipe_to_tasks(jobs, machines, durations):
    TASKS = {}
    for j in jobs:
        prec = (None, None)
        for m, d in zip(machines, durations):
            task = (j, m)
            if prec == (None, None):
                TASKS.update({(j, m): {"dur": d, "prec": None}})
            else:
                TASKS.update({(j, m): {"dur": d, "prec": prec}})
            prec = task
    return TASKS


recipeA = recipe_to_tasks(
    "A", ["Mixer", "Reactor", "Separator", "Packaging"], [1, 5, 4, 1.5]
)
visualize(jobshop(recipeA))

# %%
recipeB = recipe_to_tasks("B", ["Separator", "Packaging"], [4.5, 1])
visualize(jobshop(recipeB))

# %%
recipeC = recipe_to_tasks("C", ["Separator", "Reactor", "Packaging"], [5, 3, 1.5])
visualize(jobshop(recipeC))

# %%
TASKS = recipe_to_tasks(
    ["A1", "A2", "A3", "A4"],
    ["Mixer", "Reactor", "Separator", "Packaging"],
    [1, 5, 4, 1.5],
)
results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))

# %%
# update is used to append dictionaries
TASKS = recipeA
TASKS.update(recipeB)
TASKS.update(recipeC)

for k, v in TASKS.items():
    print(k, v)

results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))

# %%
TASKS = recipe_to_tasks(
    ["A1", "A2"], ["Mixer", "Reactor", "Separator", "Packaging"], [1, 5, 4, 1.5]
)
TASKS.update(recipe_to_tasks(["B1", "B2"], ["Separator", "Packaging"], [4.5, 1]))
TASKS.update(
    recipe_to_tasks(["C1", "C2"], ["Separator", "Reactor", "Packaging"], [5, 3, 1.5])
)

results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))

# %%
def jobshop_model_clean(TASKS, tclean=0):
    m = AMPL()
    m.read("jobshop_model.mod")

    jobs = list(set([j for (j, m) in TASKS]))
    machines = list(set([m for (j, m) in TASKS]))
    tasks = list(TASKS.keys())
    taskorder = [
        (j, m, k, n)
        for (j, m) in tasks
        for (k, n) in tasks
        if (k, n) == TASKS[(j, m)]["prec"]
    ]
    disjunctions = [
        (j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
    ]
    dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
    ub = sum(dur[i] for i in dur)

    m.set["JOBS"] = jobs
    m.set["MACHINES"] = machines
    m.set["TASKS"] = tasks
    m.set["TASKORDER"] = taskorder
    m.set["DISJUNCTIONS"] = disjunctions

    m.param["dur"] = dur
    m.param["ub"] = ub

    return m


model = jobshop_model_clean(TASKS, tclean=0.5)
results = jobshop_solve(model)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))

# %%
def jobshop_model_clean_zw(TASKS, tclean=0, ZW=False):
    m = AMPL()
    m.read("jobshop_model_clean_zw.mod")

    jobs = list(set([j for (j, m) in TASKS]))
    machines = list(set([m for (j, m) in TASKS]))
    tasks = list(TASKS.keys())
    taskorder = [
        (j, m, k, n)
        for (j, m) in tasks
        for (k, n) in tasks
        if (k, n) == TASKS[(j, m)]["prec"]
    ]
    disjunctions = [
        (j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
    ]
    dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
    ub = sum(dur[i] for i in dur)

    m.set["JOBS"] = jobs
    m.set["MACHINES"] = machines
    m.set["TASKS"] = tasks
    m.set["TASKORDER"] = taskorder
    m.set["DISJUNCTIONS"] = disjunctions

    m.param["dur"] = dur
    m.param["ub"] = ub
    m.param["tclean"] = tclean
    m.param["ZW"] = 1 if ZW else 0

    m.option["solver"] = SOLVER

    return m


model = jobshop_model_clean_zw(TASKS, tclean=0.5, ZW=True)
results = jobshop_solve(model)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
