"""有限候选的帕累托筛选与取舍。运行:python mmf_multiobjective.py。""" import json # NumPy 按成本和等待做向量比较,Matplotlib 展示支配关系及权重取舍。 import matplotlib.pyplot as plt import numpy as np def nondominated(values): # 所有列都越小越好。严格改善至少一列,才算真正支配当前方案。 keep = np.ones(len(values), dtype=bool) for index, point in enumerate(values): # 广播把 point 与所有候选行比较,axis=1 汇总同一方案的两项目标。 no_worse = np.all(values <= point, axis=1) better = np.any(values < point, axis=1) keep[index] = not np.any(no_worse & better) return keep def epsilon_choices(values, thresholds): # 先按成本、再按等待排序。主目标并列时选等待更少的方案。 # lexsort 以最后一个键为主键,因此这里成本优先,成本同分时选等待更少的。 order = np.lexsort((values[:, 1], values[:, 0])) selections = [] # 同一排序可复用于不同等待上限;顺序中第一个合格方案就是所求。 for threshold in thresholds: eligible = order[values[order, 1] <= threshold] if eligible.size == 0: raise ValueError(f"等待上限 {threshold:g} 下没有可行方案") selections.append(int(eligible[0])) return np.array(selections) def main(): # 已经过统一量纲换算的模拟目标,四行对应 A、B、C、D。 values = np.array([[3, 8], [5, 6], [7, 2], [6, 7]]) keep = nondominated(values) weight = np.linspace(0, 1, 101) # 第 j 列是一个权重组合,一次矩阵乘法计算全部方案的加权分。 scores = values @ np.vstack([weight, 1 - weight]) # 每列是一组权重,沿方案行找最小分数,再去重得到扫描中出现过的解。 weighted_ids = np.unique(np.argmin(scores, axis=0)) thresholds = [2, 6, 8] chosen = epsilon_choices(values, thresholds) result = { "pareto_ids": (np.flatnonzero(keep) + 1).tolist(), "weighted_ids": (weighted_ids + 1).tolist(), "epsilon_choices": (chosen + 1).tolist(), } print("LAB_RESULT " + json.dumps(result)) # A–C 虚线只是加权几何参照,线上的中间点并不是可选设计。 fig, (front, scalar) = plt.subplots(1, 2, figsize=(9, 4)) front.scatter(*values[keep].T, label="Nondominated") front.scatter(*values[~keep].T, marker="x", label="Dominated") front.plot(*values[[0, 2]].T, "--", color="0.5", label="A-C reference") front.axhline(thresholds[1], linestyle=":", color="tab:green", label="Wait threshold") for name, point in zip("ABCD", values): front.annotate(name, point, xytext=(5, 5), textcoords="offset points") front.set(xlabel="Cost index", ylabel="Wait index", title="Four candidate designs") front.legend(fontsize=8) # 右图沿权重绘制各方案加权分;黑色虚线取每一权重下的最低分。 for name, score in zip("ABCD", scores): scalar.plot(weight, score, label=name) scalar.plot(weight, scores.min(axis=0), color="0.15", linestyle="--", label="Minimum") scalar.set(xlabel="Weight on cost", ylabel="Weighted objective", title="Why B never wins") scalar.legend(fontsize=8) fig.tight_layout() if plt.get_backend().lower() == "agg": fig.canvas.draw() else: plt.show() if __name__ == "__main__": main()