akg-factor-bridge/test_plan_quality_rank.py

168 lines
8.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""质地调整分(2026-09-14 工作包四,台账 058):把公司质地并进计划的组内名次。
装配阶段已经读到公司深度评析的质地档,本改动在主榜与观察档这两个分数序列上按质地重排一次:
质地好的票同档内前移、差的后移。只改组内名次,不跨档,不改分值——档位标签仍按原始分解码。
离线,不连库不起服务。跑法:python3 test_plan_quality_rank.py,预期最后一行是 ALL OK。
本机没有真实快照时会跳过最后一轮(在部署机上跑才有那份)。
四条不变式对应本文件:
一 从不跨档 test_no_tier_cross(正常组内分下重排后原始档位序列不升;标签按原始分解码)
二 加分为 0 逐字相同 test_zero_bonus_identical(关掉后序列与分值都原样)
三 重编后名次连续 test_rank_continuous(重排后 enumerate 出的名次是连续的 1..n)
四 快照带 score_adj test_wiring(collect 两个序列都重排、_row 落 score_adj,快照因此带上它)
"""
import os
import sys
import types
# 离线不连库:装不上的驱动打个空壳,pandas 本机装得上就用真的(重排要在真 Series 上验)。
for _n in ("pandas", "pymysql", "psycopg"):
if _n not in sys.modules:
try:
__import__(_n)
except Exception: # noqa: BLE001
_m = types.ModuleType(_n)
if _n == "pandas":
_m.DataFrame = type("DataFrame", (), {})
sys.modules[_n] = _m
import pandas as pd # noqa: E402 —— 本包重排就在 pd.Series 上做,直接用真的 pandas
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import plan # noqa: E402
FAILED = []
def t(name, cond, extra=""):
print((" ok " if cond else " FAIL ") + name + ((" " + str(extra)) if not cond else ""))
if not cond:
FAILED.append(name)
def _cards(spec: dict) -> dict:
"""spec 是 {代码: 质地档},装成 collect 里 cards 的形状(只放本改动要读的那一路)。"""
return {k: {"company_review": ({"overall": q} if q else None)} for k, q in spec.items()}
def test_quality_bonus():
print("[质地加成的取值]")
t("好加满分", plan._quality_bonus({"overall": "好"}, 8) == 8.0)
t("差减满分", plan._quality_bonus({"overall": "差"}, 8) == -8.0)
t("中不动", plan._quality_bonus({"overall": "中"}, 8) == 0.0)
t("证据不足/无评析不动", plan._quality_bonus({"overall": "证据不足"}, 8) == 0.0)
t("没有评析字典不动", plan._quality_bonus(None, 8) == 0.0)
t("加成为 0 时任何质地都回 0", plan._quality_bonus({"overall": "好"}, 0) == 0.0)
def test_zero_bonus_identical():
print("[不变式二:加分为 0,序列与分值逐字回旧]")
ranked = pd.Series({"A": 242.0, "B": 238.0, "C": 222.0, "D": 218.0})
cards = _cards({"A": "差", "B": "好", "C": "好", "D": "差"})
out = plan._rerank_by_quality(ranked, cards, 0)
t("名次顺序原样", list(out.index) == list(ranked.index), list(out.index))
t("分值原样", list(out.values) == list(ranked.values))
def test_no_tier_cross():
print("[不变式一:正常组内分下重排不跨档,标签按原始分解码]")
# 强传导基准 240、弱传导基准 220,组内分只给 ±2(正常量级)。加减 8 后仍不跨档:
# 最低的强(差 240-2-8=230) 仍高于 最高的弱(好 220+2+8=230) 的严格判定见下。
ranked = pd.Series({"S_top": 242.0, "S_bot": 238.0, "W_top": 222.0, "W_bot": 218.0})
cards = _cards({"S_top": "差", "S_bot": "好", "W_top": "好", "W_bot": "差"})
out = plan._rerank_by_quality(ranked, cards, 8)
order = list(out.index)
# 强的两只都排在弱的两只前面——没有弱窜到强前,没有强掉到弱后
t("重排后档位序列不升(强在前、弱在后)",
order == ["S_bot", "S_top", "W_top", "W_bot"], order)
# 同档内质地好的前移:强档里 S_bot(好) 排到 S_top(差) 前
t("同档内好票前移", order.index("S_bot") < order.index("S_top"))
t("同档内好票前移(弱档)", order.index("W_top") < order.index("W_bot"))
# 标签按原始分解码,不受加成影响:重排后每只的档位仍是它本来的档
tiers = [plan._tier_label(out[k]) for k in order]
t("档位标签仍按原始分解码", tiers == ["强传导", "强传导", "弱传导", "弱传导"], tiers)
# 分值不被加成污染(供 _tier_label 解码的是原始分)
t("分值不被改动", out["S_bot"] == 238.0 and out["W_top"] == 222.0)
def test_rank_continuous():
print("[不变式三:重排后按序 enumerate 出的名次连续]")
ranked = pd.Series({"A": 240.0, "B": 240.0, "C": 220.0, "D": 220.0, "E": 200.0})
cards = _cards({"A": "差", "B": "好", "C": "好", "D": "中", "E": "好"})
out = plan._rerank_by_quality(ranked, cards, 8)
ranks = [i for i, _ in enumerate(out.items(), 1)]
t("名次是连续的 1..n", ranks == list(range(1, len(out) + 1)), ranks)
# 同分并列用稳定排序:加成相同的 A、B 若加成后仍并列,保持原始顺序
stable = pd.Series({"X": 240.0, "Y": 240.0})
outs = plan._rerank_by_quality(stable, _cards({"X": "好", "Y": "好"}), 8)
t("加成后并列时保持原始先后(稳定排序)", list(outs.index) == ["X", "Y"], list(outs.index))
def test_wiring():
print("[不变式四的接线:collect 两序列都重排、_row 落 score_adj]")
src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "plan.py"),
encoding="utf-8").read()
# 2026-09-17:调用点改成先算旧序拿 rank_old(main_old/obs_old),再按轴分派算新序,匹配串随之更新。
i_main = src.find("main_old = _rerank_by_quality(main, cards,")
i_obs = src.find("obs_old = _rerank_by_quality(obs, cards,")
t("主榜序列被重排", i_main > 0)
t("观察档序列被重排", i_obs > 0)
# 重排必须在 _pick 与 _full_rows 定义之前——四个出口才同序
i_pick = src.find("def _pick(")
i_full = src.find("def _full_rows(")
t("重排排在 _pick 之前", 0 < i_main < i_pick and 0 < i_obs < i_pick)
t("重排排在 _full_rows 之前", 0 < i_main < i_full)
# _row 里落 score_adj,快照走 _full_rows→_row,因此快照带 score_adj
i_row = src.find("def _row(")
i_full_rows_def = src.find("def _full_rows(")
body = src[i_row:i_full_rows_def]
t("_row 落 score_adj 字段", '"score_adj"' in body)
t("_row 的 score_adj 用原始分加质地加成算", "_quality_bonus(c.get(\"company_review\")" in body)
# _tier_label 喂的是原始分 s(序列值未被加成改动),不是 score_adj
t("档位标签仍按原始分 s 解码", 'r["tier"] = _tier_label(s)' in body)
def test_against_real_snapshot():
print("[拿真实快照看名次连续 —— 本机没有就跳过]")
import glob
import json
import config
fs = sorted(glob.glob(os.path.join(config.PLAN_SNAPSHOT_DIR, "plan_*.json")))
if not fs:
print(" -- 本机没有快照文件,跳过这一轮(在部署机上跑才有;接口层判收见 §5.4 的 curl)")
return
snap = json.load(open(fs[-1], encoding="utf-8"))
shown = snap.get("main_shown") or []
if shown:
t("下发主榜名次连续", [r.get("rank") for r in shown] == list(range(1, len(shown) + 1)))
full = snap.get("main") or []
if full and all("score_adj" in r for r in full):
# 这份是本改动上线之后出的快照:每行都该带 score_adj,档位仍按原始分解码
t("全量主榜每行都带 score_adj", True)
bad = [r["code"] for r in full
if r.get("tier") and r["tier"] != plan._tier_label(r["score"])]
t("档位标签与原始分一致(未被 score_adj 污染)", not bad, bad[:5])
else:
print(" -- 最新快照还没有 score_adj(本改动未在该快照生成时上线),只验了名次连续")
def main():
test_quality_bonus()
test_zero_bonus_identical()
test_no_tier_cross()
test_rank_continuous()
test_wiring()
test_against_real_snapshot()
print("-" * 70)
if FAILED:
print("FAILED %d: %s" % (len(FAILED), "; ".join(FAILED)))
return 1
print("ALL OK — 质地调整分:加成取值 / 关掉逐字回旧 / 不跨档 / 名次连续 / 接线")
return 0
if __name__ == "__main__":
sys.exit(main())