r"""
QFD: which specifications should be developed?
==============================================

Abonyi and Czvetkó (2022) compared three readings of a house of quality:
mixed-integer linear programming that maximizes the satisfaction of the
requirements under a budget, a minimum-cost assignment (network flow) model
that meets every requirement at the lowest cost, and the hypergraph view that
ranks the specifications by centrality. The three are applied to the
electric car house of quality with illustrative development costs.
"""

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

import hatvis as hv
from hatvis.plotting import plot_house_of_quality

q = hv.datasets.load_electric_car_qfd()
R = q.relationship
costs = pd.Series([4, 3, 3, 2, 3, 4, 1, 1, 2, 1, 1], index=R.columns, name="cost")
# [snippet:qfd]
lp = hv.qfd.qfd_select(R, costs=costs, budget=12, max_actions=6)
flow = hv.qfd.qfd_min_cost_assignment(R, costs=costs)
_, edge_c = hv.node_edge_eigenvector(q.hypergraph, "linear")
n_lp = int(lp["selected"].sum())                     # as many as the LP selected
hyper = edge_c.sort_values(ascending=False).index[:n_lp]
# [/snippet:qfd]
def satisfaction(chosen):
    return float(R[list(chosen)].to_numpy().sum())


summary = pd.DataFrame({
    "LP (budget 12)": [sorted(lp.index[lp["selected"]]), lp.attrs["cost"], satisfaction(lp.index[lp["selected"]])],
    "min-cost assignment": [sorted(set(flow["parameter"])), costs[list(set(flow["parameter"]))].sum(),
                            satisfaction(set(flow["parameter"]))],
    "hypergraph centrality": [sorted(hyper), costs[list(hyper)].sum(), satisfaction(hyper)],
}, index=["selected", "cost", "satisfaction"]).T
print(summary.to_string())
print("technical importance:", hv.qfd.technical_importance(R, q.importance).sort_values(ascending=False).head(4).to_dict())

# %%
fig, ax = plt.subplots(figsize=(10, 7.5))
corr = pd.DataFrame(0.0, index=R.columns, columns=R.columns)
for a, b, v in [("ES1", "ES5", 0.5), ("ES5", "ES6", 0.5), ("ES3", "ES4", 0.5), ("ES10", "ES11", 0.5),
                ("ES1", "ES6", 0.3), ("ES7", "ES8", 0.3), ("ES2", "ES4", -0.3)]:
    corr.loc[a, b] = corr.loc[b, a] = v
plot_house_of_quality(R, q.importance, corr, ax=ax, title="house of quality (illustrative roof)")
plt.tight_layout()
