r"""
Directed hypergraphs: assembly feasibility and cost
===================================================

An assembly step needs *all* its input parts — an AND dependency that
ordinary graphs cannot express. Modelled as a directed hypergraph (tail =
inputs, head = outputs), B-reachability tells which products can be made
from the available parts, and minimum B-hyperpaths give the total effort
(sum over all sub-assemblies) or the makespan with parallel preparation (max).
"""

# %%
import matplotlib.pyplot as plt
import pandas as pd

import hatvis as hv
from hatvis import problems

# [snippet:assembly]
D = hv.DirectedHypergraph({
    "cut wires":      (["wire"], ["cut wire"]),
    "crimp":          (["cut wire", "terminal"], ["crimped wire"]),
    "mount housing":  (["housing", "seal"], ["connector"]),
    "insert":         (["crimped wire", "connector"], ["sub-harness"]),
    "tape":           (["sub-harness", "tape"], ["taped sub-harness"]),
    "route":          (["taped sub-harness", "jig"], ["harness"]),
    "buy harness":    (["supplier"], ["harness"]),
    "test":           (["harness", "tester"], ["tested harness"]),
}, weights=[2, 3, 3, 4, 2, 5, 30, 3])
available = ["wire", "terminal", "housing", "seal", "tape", "jig", "tester"]
print("producible:", sorted(problems.b_reachable(D, available) - set(available)))
cost = pd.DataFrame({"sum": problems.shortest_hyperpaths(D, available, "sum"),
                     "max": problems.shortest_hyperpaths(D, available, "max")})
# [/snippet:assembly]
print(cost.loc[["crimped wire", "connector", "sub-harness", "harness", "tested harness", "supplier"]])

# %%
fig, ax = plt.subplots(figsize=(7, 3.6))
c = cost.drop(index=available + ["supplier"])
c.sort_values("sum").plot.barh(ax=ax, color=hv.plotting.PALETTE[:2])
ax.set_xlabel("minimum hyperpath cost")
plt.tight_layout()
