products_reverse_audit.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""**反向**呼应审计:自输出 → 功能与算法 → 输入(用户令 2026-09-17)。
  4. ## 与 `inventory_products.py` 的区别(两个方向,各管一件事)
  5. · `inventory_products.py` 是**正向**:从 `data/raw/<场>/` 的每一类输入出发,找它喂出来的产物,
  6. 比跨度/条数("输入到了 2026-07,产物只到 2026-04 → 未重算")。它只覆盖 5 类输入、十几件产物。
  7. · 本器是**反向**:从 `outputs/<场>/` 的**每一件产物**出发,问三个问题:
  8. ① 它是谁算出来的?(功能与算法 = 生成端)
  9. ② 它从哪份输入算出来的?(`data/raw/<场>/` 的哪一类)
  10. ③ 这条"输出 ↔ 输入"的呼应关系**成立吗**?(生成端在位 ∧ 输入在位 ∧ 可机检的对应判据通过)
  11. 逐件判定,最后给出"成立 / 不成立(无生成端)/ 无法验证"三类账。
  12. ## 为什么必须做反向
  13. 正向只查"我关心的输入有没有被算成产物",查不出**"盘上这件产物到底有没有来路"**。
  14. 2026-09-17 现场就是栽在这里:清了产物之后,页面缺的 `windscada/index.html`、
  15. `m5_cms_tcm/handoff_vibration_v2.json` 这类件**根本没有生成端**(全库 0 处写入方),
  16. 正向那几条跨度判据一条都不会报 —— 它们压根不在 `INPUTS` 的 `feeds` 里。
  17. 反向一对账就清楚了:**有来路的件**(生成端 + 输入 + 判据都过)与**没来路的件**(只能从交付包补)。
  18. ## 判定口径(每条都写进结果里,不含糊)
  19. ✓ 呼应成立 生成端在位 ∧ 输入在位 ∧ 判据通过(跨度 ⊆ 输入 / 键集 ⊆ 输入 / 计数一致 / 行数 > 0)
  20. ~ 输入不在位 生成端知道,但 `data/raw/<场>/<类>` 不在 ⇒ **现在无法验证**(放数据后复跑本器)
  21. ✗ 无生成端 全库 0 处写入方 ⇒ **输出↔输入的呼应在原理上不成立**:这件产物无法由输入推导出来,
  22. **无法由重算生出来**;按用户令 2026-09-17 #1 运行期也不从交付包补齐 ⇒ 只能由研发补生成端(本器 --feasibility 给出逐族可逆性)
  23. ? 未归类 既不在族表里、台账里也没有 —— 需要人工认领(本器把它当缺口报出来)
  24. ## 用法
  25. python scripts/products_reverse_audit.py # 全量反向审计(人看)
  26. python scripts/products_reverse_audit.py --check # 只出结论(有 ✗/? 时退出码 5)
  27. python scripts/products_reverse_audit.py --write-doc # 把族表写进 docs/系统设计说明.md §13.6
  28. 退出码: 0 全部成立(允许 ✗,只要它们都在台账里如实标了 shipped)· 5 有未归类件或判据失败
  29. """
  30. from __future__ import annotations
  31. import argparse
  32. import fnmatch
  33. import json
  34. import pathlib
  35. import sys
  36. ROOT = pathlib.Path(__file__).resolve().parents[1]
  37. sys.path.insert(0, str(ROOT))
  38. sys.path.insert(0, str(ROOT / 'scripts'))
  39. from src import paths as P # noqa: E402
  40. import inventory_products as INV # noqa: E402
  41. DOC_BEGIN, DOC_END = '<!-- REVERSE-AUDIT:BEGIN -->', '<!-- REVERSE-AUDIT:END -->'
  42. # ── 族表: 输出(glob) → 功能 / 算法(生成端) / 输入类 / 判据 ────────────────────────────
  43. # pred: span=产物时间跨度必须落在输入跨度内; turbines=产物机组集 ⊆ 输入机组集;
  44. # rows=行数>0; count=件数/计数与说明一致; manifest=与清单自记一致
  45. FAMILIES: list[dict] = [
  46. dict(id='vib_window_index', glob='m5_cms_tcm/windows/*/index.parquet', kind='raw-derived',
  47. func='振动摄入 · 窗索引', algo='scripts/rudong_tcm_index.py(逐 decode JSON 解析 54 列:turbine/'
  48. 'sensor_name/meas_name/trigger_time/rpm/condition_key/alarm_type)',
  49. gen='scripts/rudong_tcm_index.py', input='windcms', pred=('span', 'turbines', 'rows'),
  50. time_col='trigger_time'),
  51. dict(id='vib_spectra', glob=['m5_cms_tcm/windows/*/spectra/**', 'm5_cms_tcm/windows/*/spectra_meta.parquet'],
  52. kind='raw-derived',
  53. func='振动摄入 · 谱库', algo='scripts/rudong_tcm_spectra.py(FFT_ 测量 → npz 幅值数组, 分片存 `spectra/p<NN>/`)',
  54. gen='scripts/rudong_tcm_spectra.py', input='windcms', pred=('npz',)),
  55. dict(id='vib_raw_manifest', glob='m5_cms_tcm/vib_raw_manifest.json', kind='raw-derived',
  56. func='振动摄入 · 清单', algo='scripts/vib_raw_build.py(汇总窗/谱件数、时间跨度、missing_chain 缺口)',
  57. gen='scripts/vib_raw_build.py', input='windcms', pred=('manifest',)),
  58. dict(id='scada_alarms', glob='windscada/alarms.parquet', kind='raw-derived',
  59. func='三门台账 · 报警', algo='scripts/windscada_alarms_ingest.py(SpreadsheetML *.xls → 事件表)',
  60. gen='scripts/windscada_alarms_ingest.py', input='故障报警', pred=('span', 'rows'), time_col='t_on'),
  61. dict(id='scada_workorders', glob='windscada/workorders.parquet', kind='raw-derived',
  62. func='三门台账 · 工单', algo='scripts/windscada_workorder_ingest.py(检修台账 → 工单表)',
  63. gen='scripts/windscada_workorder_ingest.py', input='风机故障记录', pred=('span', 'rows'),
  64. time_col='t_report'),
  65. dict(id='scada_oil', glob='windscada/oil_samples_index.parquet', kind='raw-derived',
  66. func='三门台账 · 油样', algo='scripts/windscada_watch_channels_build.py(油样 PDF → 索引)',
  67. gen='scripts/windscada_watch_channels_build.py', input='油样报告', pred=('span', 'rows'),
  68. time_col='date'),
  69. dict(id='scada_monthly', glob='windscada/temp_monthly.parquet', kind='raw-derived',
  70. func='月度派生件', algo='scripts/windscada_monthly_build.py(逐值对齐随包件 19,494/19,494)',
  71. gen='scripts/windscada_monthly_build.py', input='scada_10min', pred=('span', 'rows'), time_col='month'),
  72. dict(id='scada_derived', glob='windscada/*.parquet', kind='raw-derived',
  73. func='SCADA 派生分析(功率曲线/损失/曲线/控制/停机/温度/偏航/液压/热链/系统辅助)',
  74. algo='src/windscada/perf/{powercurve,availability,curves,control,faults} + subsys/{temp_nbm,yaw,'
  75. 'hydraulic,thermal_chain} + taxonomy.py',
  76. gen='src/windscada/perf/powercurve.py', input='scada_10min', pred=('rows',)),
  77. dict(id='ontology_core', glob='ontology/{objects.json,retrieval_index.json,turbine_params.parquet}',
  78. kind='raw-derived',
  79. func='本体层 · 码表/对象库/检索索引/实机参数',
  80. algo='python -m src.ontology.kb_ingest → populate → chain_ingest → trend_ingest;'
  81. 'src.ontology.retrieval.build;src.ontology.maintenance.refresh_params',
  82. gen='src/ontology/kb_ingest.py', input='西门子4.0技术资料', pred=('rows',)),
  83. dict(id='ontology_aux_build', glob=['ontology/_id_alias.json', 'ontology/retrieval_vec.npy'],
  84. kind='raw-derived',
  85. func='本体层 · 别名表与向量索引缓存', algo='src.ontology.kb_ingest(别名)/ '
  86. 'src.ontology.retrieval.build(use_vec=True)(向量)',
  87. gen='src/ontology/kb_ingest.py', input='西门子4.0技术资料', pred=('rows',)),
  88. dict(id='ontology_domain', glob=['ontology/oil_2026H2_huabiao.json', 'ontology/parts_cost_public.json',
  89. 'ontology/scenario_29_repair.json'],
  90. kind='shipped',
  91. func='本体层 · 领域数据件(油样台账/备件价格/场景修复)', algo='(无生成端, 领域正本出件)',
  92. gen=None, input=None, pred=(), why='领域正本随包发来, 不由 data/raw 推导'),
  93. # ── 以下族: 全库 0 处写入方 ⇒ 反向呼应**在原理上不成立**(如实记账, 不假装成立)────
  94. dict(id='vib_handoff_and_scans', glob='m5_cms_tcm/*.{json,parquet,csv,md,txt}',
  95. kind='shipped',
  96. func='振动线出件与专项扫描(handoff / 历史 / 基线 / 各类 freq scan / 判级台账)', algo='(无生成端)',
  97. gen=None, input=None, pred=(), why='振动六层链四步脚本未随包(oem_frequency_scan 等),'
  98. '现场正本才可重出;现只能从交付包补齐'),
  99. dict(id='vib_figs', glob='m5_cms_tcm/figs/*', kind='shipped',
  100. func='振动线出图(谱图/趋势图)', algo='(无生成端)', gen=None, input=None, pred=(),
  101. why='随包快照(振动线出件)'),
  102. dict(id='windscada_pages', glob='windscada/{index.html,turbines/*,review/*}', kind='shipped',
  103. func='总览「全场状态」静态页 + 逐台页 + 评审记录', algo='(无生成端)',
  104. gen=None, input=None, pred=(), why='页面件由振动线/历史分析出件,本包无写入方'),
  105. dict(id='windcms_pages', glob='windcms/**', kind='shipped',
  106. func='CMS 振动评估报告页/逐台页/缓存', algo='scripts/windcms.py report(本包缺 model_run/fusion '
  107. '产物, 重生成会掉内容 −97%, 故**按设计跳过**)', gen=None, input=None, pred=(),
  108. why='生成端在包内但输入不足 ⇒ 现状按随包件冻结'),
  109. dict(id='sop_workspace', glob='sop/**', kind='shipped',
  110. func='SOP 中间件/评审/事实契约底稿', algo='(无生成端)', gen=None, input=None, pred=(),
  111. why='评审过程件, 属人工作业留痕'),
  112. dict(id='tcm_replay', glob='tcm_compatible_replay/**', kind='shipped',
  113. func='TCM 兼容链回放资产(模型表/掩码阈值/裁决记录)', algo='(无生成端)', gen=None, input=None,
  114. pred=(), why='随包快照'),
  115. dict(id='paradigm_r1', glob='paradigm_r1/**', kind='shipped',
  116. func='范式实验件(E3/E5/E8 底稿)', algo='(无生成端)', gen=None, input=None, pred=(),
  117. why='实验底稿, 事实契约的输入'),
  118. dict(id='pitch_shipped', glob='pitch/**', kind='shipped',
  119. func='变桨侧派生件(零位/日粒度)', algo='(无生成端;rebuild_from_raw --scada 只覆盖其中一部分)',
  120. gen=None, input=None, pred=(), why='随包快照'),
  121. dict(id='ontology_releases', glob='ontology/release_*/*', kind='shipped',
  122. func='本体发布层 r1/r2(只读暴露给网关 /release/)', algo='(无生成端)', gen=None, input=None,
  123. pred=(), why='发布层清单, 由研发出件'),
  124. dict(id='guanlan_contract', glob='guanlan/**', kind='shipped',
  125. func='事实契约与对外派生(门户结论段/取数)', algo='scripts/guanlan_facts_contract.py(读者在包内, '
  126. '输入是 ontology+m5+sop 三处**产物**)', gen=None, input=None, pred=(),
  127. why='派生链的中间层:它的"输入"本身是产物而非 data/raw ⇒ 与 raw 之间隔着不止一跳'),
  128. dict(id='windscada_release_manifest', glob='windscada/release-manifest.json', kind='source-derived',
  129. func='发布清单快照(`/healthz` 与版本信息读它)',
  130. algo='scripts/guanlan_baseline_manifest.py(从 src/windscada/ui 源重建 zh 页 → 摘要 '
  131. '{css_tokens, nav, dom, sha256, source blobs})',
  132. gen='scripts/guanlan_baseline_manifest.py', input=None, pred=(),
  133. why='★ 2026-09-17 修正: 它一度被我按"交证件"错分成非产物; 实际**包内有生成端**'
  134. '(guanlan_baseline_manifest.py 就写这个路径), 且 guanlan_gateway.py 运行期读它 ⇒ 是产物'),
  135. dict(id='human_deliverables',
  136. glob=['windscada/mblub_alarm_cross.json', 'windscada/review_presented.json',
  137. 'windscada/给振动线_温度轴回复_20260826.json', 'windscada/给振动线_温度轴回复_20260826.md',
  138. 'windscada/送审_系统结论与判定_20260828.md'],
  139. kind='human',
  140. func='**人工正本/交证件**:与振动线的跨线通知、送审结论、发布评审快照',
  141. algo='(人写的, 不是算出来的)', gen=None, input=None, pred=(),
  142. why='这几件是"人对人的交证件/回执", 内容由分析结论抄写与人判断坐实而成; '
  143. 'mblub_alarm_cross.json 还被 src/ontology/populate.py 当作**证据来源**引用 ⇒ '
  144. '必须随包留在原位, 但**不参与呼应校验**(它本来就没有生成端, 也不该有)'),
  145. dict(id='scratch_in_products', glob=['**/_*.js', '**/_*audit*.md', '**/*.out', '**/*.err',
  146. '**/*_test_*.parquet', '**/*_test_*.json'],
  147. kind='not-product',
  148. func='**非产物**:自审脚本/记录与模型测试输出(躺在产物仓里)', algo='(工具脚本与运行痕迹, 不是产物)',
  149. gen=None, input=None, pred=(),
  150. why='2026-09-17: 17 件已移出到 reference/非产物留痕_20260917/ 并留了 _来源说明.json ⇒ '
  151. '本族现在应为空; 一旦再出现(新脚本往产物仓里写 .out/_audit.js 之类), 本器当场报出来'),
  152. ]
  153. def _files_of(glob) -> list[str]:
  154. """族 glob(str 或 list)→ 台账里的相对键(支持 `{a,b}` 花括号与 `*`)。
  155. ★ 深度必须**显式对齐**(2026-09-17 第一版踩过): `fnmatch` 的 `*` 是**跨 `/`** 的, 于是
  156. `windscada/*.parquet` 会把 `windscada/turbines/xx.parquet`、`windscada/_pre_rebuild_*/xx.parquet`
  157. 一起吞进来 —— 反向审计最怕"族把不该管的件认领了", 那样账就假了。
  158. 规则: 模式里没有 `**` 时, 要求的 `/` 个数必须与键的 `/` 个数**相等**(逐条展开后各自判)。
  159. """
  160. pats = []
  161. for g in ([glob] if isinstance(glob, str) else list(glob)):
  162. if '{' in g:
  163. head, tail = g.split('{', 1)
  164. opts, rest = tail.split('}', 1)
  165. pats += [head + o + rest for o in opts.split(',')]
  166. else:
  167. pats.append(g)
  168. out = []
  169. for rel in LEDGER:
  170. for pt in pats:
  171. if '**' not in pt and rel.count('/') != pt.count('/'):
  172. continue
  173. if fnmatch.fnmatch(rel, pt) or rel == pt:
  174. out.append(rel)
  175. break
  176. return sorted(out)
  177. LEDGER: dict[str, dict] = {}
  178. def load_ledger(farm: str) -> dict[str, dict]:
  179. """台账 = `_provenance.json`(逐件来源) + `_derived_manifest.json`(生成端自登记)。"""
  180. out: dict[str, dict] = {}
  181. root = P.out_root(farm)
  182. for fn in ('_provenance.json', '_derived_manifest.json'):
  183. f = root / fn
  184. if not f.is_file():
  185. continue
  186. try:
  187. d = json.loads(f.read_text(encoding='utf-8'))
  188. except Exception:
  189. continue
  190. for rel, v in (d.get('files') or {}).items():
  191. if isinstance(v, dict):
  192. out.setdefault(rel, dict(source=v.get('source') or 'raw-derived',
  193. builder=v.get('builder') or v.get('by') or '',
  194. why=v.get('why') or '',))
  195. return out
  196. def _input_home(station: pathlib.Path, sub: str) -> pathlib.Path | None:
  197. """输入类目录在哪 —— 优先场站目录下, 其次 raw 根下。
  198. ★ 机理层资料按 A2 约定**不在场站目录下**(`data/raw/西门子4.0技术资料/`, 见 src/windscada/config.py)。
  199. 只查场站目录会把本体层判成"输入不在位"(2026-09-17 第一版就这么误报过 3 件)。
  200. """
  201. for base in (station, station.parent):
  202. d = base / sub
  203. if d.is_dir():
  204. return base
  205. return None
  206. def _parquet_span(p: pathlib.Path, col: str | None):
  207. import pandas as pd
  208. try:
  209. d = pd.read_parquet(p)
  210. except Exception:
  211. return None, None, 0
  212. n = len(d)
  213. if col and col in d.columns:
  214. s = pd.to_datetime(d[col], errors='coerce')
  215. if s.notna().any():
  216. return str(s.min())[:10], str(s.max())[:10], n
  217. return None, None, n
  218. def _npz_ok(p: pathlib.Path) -> bool:
  219. """振动谱件: npz 能读出来且非空(列数不是"行", 不能拿 parquet 的行数判它)。"""
  220. try:
  221. import numpy as np
  222. with np.load(p, allow_pickle=False) as z:
  223. return any(z[k].size > 0 for k in z.files)
  224. except Exception:
  225. return False
  226. # ── 逆向工程可行性 (用户令 2026-09-17 #2) ────────────────────────────────────────────
  227. # 问的是: "这批没有生成端的产物, 能不能从原始件/在包生成端**推**出来?"
  228. # 判定不靠印象, 靠两条机器证据:
  229. # ① 生成端在不在包内(在 → 只是没接上, 跑一次就有);
  230. # ② 产物正文里有没有**人工判断**的痕迹("裁决/审核/校准/评审/经验"这类字段)——
  231. # 含人工判断的件不是任何输入的纯函数, 逆向工程推不出来, 只能把那一步人工工作重做。
  232. import re as _re # noqa: E402
  233. JUDGE_PAT = _re.compile(r'人工|裁决|审核|复核|校准|评审|经验值|专家|judg|review|manual|calibrat|verdict|sign[_ ]?off',
  234. _re.I)
  235. # ★ 只认"**字段**叫这个名字"(`"裁决": …` / `裁决,`),不认正文里顺嘴提一句 ——
  236. # 2026-09-17 第一版拿整篇子串匹配, 结果把**页面**里的展示标签(`index.html` 里的"评审/人工")当成
  237. # 人工判断, 于是把"页面"整族误判成不可逆。这属于"判据太糙 → 结论假"。
  238. JUDGE_KEY_PAT = _re.compile(r'["\']?[^"\',:]{0,24}(人工|裁决|审核|复核|校准|评审|经验值|专家|'
  239. r'judg|review|manual|calibrat|verdict|sign[_ ]?off)[^"\',:]{0,24}["\']?\s*[:=]',
  240. _re.I)
  241. def judgement_evidence(farm: str, rels: list[str], cap: int = 8) -> tuple[int, list[str], int]:
  242. """→ (含人工判断字段的抽样比例%, 样例, 被检查件数)。
  243. 只查**数据/文本件**(.json/.csv/.md/.txt); **页面(.html/.js)不算** —— 页面是产物的渲染,
  244. 里面出现"评审/人工"是展示标签, 不代表这份件内含判断。
  245. """
  246. hit, samples, checked, pages = 0, [], 0, 0
  247. for rel in rels[:cap]:
  248. p = P.out_root(farm) / rel
  249. suf = p.suffix.lower()
  250. if suf in ('.html', '.js', '.css', '.htm'):
  251. pages += 1
  252. continue
  253. try:
  254. if suf == '.json':
  255. txt = p.read_text(encoding='utf-8', errors='replace')[:200000]
  256. pat = JUDGE_KEY_PAT
  257. elif suf in ('.csv', '.txt'):
  258. txt = p.read_text(encoding='utf-8', errors='replace')[:50000]
  259. pat = JUDGE_KEY_PAT
  260. elif suf == '.md':
  261. txt = p.read_text(encoding='utf-8', errors='replace')[:50000]
  262. pat = JUDGE_PAT
  263. else:
  264. continue
  265. except Exception:
  266. continue
  267. checked += 1
  268. if pat.search(txt):
  269. hit += 1
  270. samples.append(rel)
  271. return (100 * hit // checked if checked else 0), samples, pages
  272. def feasibility(fam: dict, rels: list[str], gen_ok: bool, in_ok: bool,
  273. judge_pct: int, judge_samples: list[str], pages: int = 0) -> tuple[str, str]:
  274. """→ (可逆性判定, 依据)。四类: 可逆(直接) / 可逆(需反推口径) / 不可逆(人工判断) / 应移出产物仓。"""
  275. if fam['kind'] == 'not-product':
  276. return '应移出产物仓', '它本就不是产物(工具脚本/交证件/测试输出) ⇒ 该从产物仓移走, 而不是"补生成端"'
  277. if gen_ok and in_ok:
  278. return '可逆(直接)', f"生成端在包内({fam['gen']})且输入在位 ⇒ 接上/重跑即可"
  279. if pages and pages >= max(3, len(rels[:8]) // 2):
  280. return '可逆(页面可再生)', ('这一族主要是**页面**(.html): 页面是产物的渲染, 不是独立数据 ⇒ '
  281. '接上在包的页面生成端重出即可(未必逐字节同, 能力与数据一致)')
  282. m_n = sum(1 for r in rels if r.endswith(('.parquet', '.csv', '.npz')))
  283. t_n = len(rels) - m_n
  284. split = f'({m_n} 件测量形态 / {t_n} 件文本·判断件)' if (m_n and t_n) else ''
  285. # 两类都占相当比重时, 结论必须是"混合"而不是挑一类代表全族 —— 否则一句判定就把另一半骗过去了
  286. if m_n and t_n and min(m_n, t_n) * 4 >= len(rels):
  287. return '混合(测量件可反推 / 文本件需人定)', split + \
  288. '测量形态的件可由 data/raw 反推口径 + 逐值对拍; 文本/判断件(评审、裁决、回复)推不出来'
  289. if judge_pct >= 50 and judge_samples:
  290. return '不可逆(人工判断)', (f"抽样 {len(judge_samples)} 件里都写着人工判断字段(如 {judge_samples[0]}) "
  291. f"⇒ 不是输入的纯函数, 逆向工程推不出来")
  292. if m_n and m_n * 2 >= len(rels):
  293. return '可逆(需反推口径)', split + '测量形态的件是测量数据的函数 ⇒ 可从 data/raw 反推口径 + 逐值对拍' \
  294. '(做法同 temp_monthly: 反推 → 逐值一致才敢用)'
  295. if gen_ok:
  296. return '半可逆(生成端在包, 输入不足)', '生成端在包内, 缺的是上游输入 ⇒ 上游补齐后即可重出'
  297. if judge_pct > 0:
  298. return '半可逆(需人工裁定)', f'抽样里 {judge_pct}% 的件含人工判断字段 ⇒ 机器部分可推、判断部分要人定'
  299. return '需人工裁定', '既无生成端、形态也不是测量函数 ⇒ 需研发给口径或领域正本'
  300. def _turbines_of(p: pathlib.Path, col: str = 'turbine', cap: int = 200000):
  301. import pandas as pd
  302. try:
  303. d = pd.read_parquet(p, columns=[col]) if col else pd.read_parquet(p)
  304. except Exception:
  305. return None
  306. try:
  307. return {str(x).upper() for x in d[col].dropna().unique()} if col in d.columns else None
  308. except Exception:
  309. return None
  310. def _input_turbines(station: pathlib.Path, sub: str):
  311. """输入侧机组集合: 逐台 CSV 文件名 / 目录名里的 WTG 号。"""
  312. d = station / sub
  313. if not d.is_dir():
  314. return None
  315. out = set()
  316. for p in d.rglob('*'):
  317. if p.is_file():
  318. for m in __import__('re').finditer(r'(WTG\s?\d{1,2})', p.name.upper()):
  319. out.add(m.group(1).replace(' ', ''))
  320. return out or None
  321. def classify_human(farm: str, rels: list[str], cap: int = 600) -> set[str]:
  322. """逐件判"是不是人工件"(用户令 2026-09-17 #3:人工件不再按自动产物参与呼应校验)。
  323. 判据:**非测量形态**的件(.md/.json/.csv/.txt)里出现人工判断字段(按字段名匹配)。
  324. 测量形态件(.parquet/.csv 数值、.npz)一律不算人工件 —— 它们是数据的函数,属"可反推"那一路。
  325. """
  326. human: set[str] = set()
  327. for rel in rels[:cap]:
  328. suf = pathlib.Path(rel).suffix.lower()
  329. if suf in ('.md', '.txt'):
  330. pat = JUDGE_PAT
  331. elif suf in ('.json', '.csv'):
  332. pat = JUDGE_KEY_PAT
  333. else:
  334. continue
  335. p = P.out_root(farm) / rel
  336. try:
  337. txt = p.read_text(encoding='utf-8', errors='replace')[:120000]
  338. except Exception:
  339. continue
  340. if pat.search(txt):
  341. human.add(rel)
  342. return human
  343. def write_human_manifest(farm: str | None = None) -> int:
  344. """把人工件逐件落成 `outputs/<场>/_human_artifacts.json`(机器台账,供自检与审计引用)。"""
  345. farm = farm or P.farm()
  346. global LEDGER
  347. LEDGER = load_ledger(farm)
  348. entries: dict[str, dict] = {}
  349. for fam in FAMILIES:
  350. if fam['kind'] not in ('shipped', 'human', 'not-product'):
  351. continue
  352. rels = [r for r in _files_of(fam['glob']) if r not in entries]
  353. if not rels:
  354. continue
  355. if fam['kind'] == 'human':
  356. for r in rels:
  357. entries[r] = dict(kind='human', family=fam['id'], evidence='族内显式登记为人工正本/交证件')
  358. continue
  359. for r in classify_human(farm, rels):
  360. if r not in entries:
  361. entries[r] = dict(kind='human', family=fam['id'],
  362. evidence='件内含人工判断字段(按字段名匹配),不是输入的纯函数')
  363. out = P.out_root(farm) / '_human_artifacts.json'
  364. out.write_text(json.dumps(dict(
  365. at=__import__('time').strftime('%Y-%m-%d %H:%M:%S'),
  366. note='人工件台账(用户令 2026-09-17 #3):这些件由人写成/坐实,不是任何输入的纯函数 ⇒ '
  367. '不参与"输出↔输入呼应"校验;随包留在原位,重算不会也不该重写它们。'
  368. '本文件由 scripts/products_reverse_audit.py --write-human-manifest 生成。',
  369. count=len(entries), files=entries), ensure_ascii=False, indent=1), encoding='utf-8')
  370. by_fam: dict[str, int] = {}
  371. for v in entries.values():
  372. by_fam[v['family']] = by_fam.get(v['family'], 0) + 1
  373. print(f'人工件台账: {len(entries)} 件 → {P.rel(out)}')
  374. for k, v in sorted(by_fam.items(), key=lambda kv: -kv[1]):
  375. print(f' {k:24s} {v:4d} 件')
  376. return 0
  377. def audit(farm: str | None = None, verbose: bool = True):
  378. farm = farm or P.farm()
  379. global LEDGER
  380. LEDGER = load_ledger(farm)
  381. # ★ 场站原始件目录用唯一取用口 (场站名可与 farm 键不同: 键 = rudong, 目录 = data/raw/如东)
  382. from src.windscada.config import raw_station_dir
  383. station = pathlib.Path(raw_station_dir(farm))
  384. verdict: dict[str, dict] = {}
  385. fam_rows = []
  386. fails: list[str] = []
  387. for fam in FAMILIES:
  388. # ★ 族按**声明顺序**认领, 先声明的先拿 (否则 `m5_cms_tcm/*` 这种宽通配会把 windows/ 下
  389. # 1704 件也吞进来 —— fnmatch 的 `*` 是跨 `/` 的, 2026-09-17 第一版就这么误判过)
  390. rels = [r for r in _files_of(fam['glob']) if r not in verdict]
  391. rels = [r for r in rels if not r.lower().endswith(('.log', '.jsonl'))]
  392. if not rels:
  393. continue
  394. row = dict(id=fam['id'], n=len(rels), func=fam['func'], algo=fam['algo'], input=fam['input'],
  395. pred='+'.join(fam['pred']) or '—', verdict='', note='')
  396. if fam['kind'] == 'not-product':
  397. # ★ 不是产物, 却躺在产物仓里: 反向审计对它的结论是"它压根不该按产物管" ——
  398. # 既不需要生成端, 也谈不上与输入呼应(这一类最该被人看见, 故单独一类, 不当失败计)。
  399. jp, js, pg = judgement_evidence(farm, rels)
  400. fv, fw = feasibility(fam, rels, False, False, jp, js, pg)
  401. row['verdict'] = '✗ 非产物'
  402. row['note'] = fam.get('why', '')
  403. row['rev'], row['rev_why'] = fv, fw
  404. for r in rels:
  405. verdict[r] = dict(fam=fam['id'], verdict='✗',
  406. why='非产物(过程留痕/工具脚本躺在产物仓里): ' + fam.get('why', ''))
  407. elif fam['kind'] == 'human':
  408. # ★ 人工正本/交证件 (用户令 2026-09-17 #3): 由人写、被运行期当证据引用,
  409. # **不参与呼应校验**——它本来就没有、也不该有生成端; 单独计数, 不混进"无生成端"的失败堆里。
  410. row['verdict'] = '◆ 人工件'
  411. row['note'] = fam.get('why', '')
  412. row['rev'], row['rev_why'] = '人工件(正本/交证)', '人写的, 不参与呼应校验; 随包留在原位'
  413. for r in rels:
  414. verdict[r] = dict(fam=fam['id'], verdict='◆',
  415. why='人工件(人工正本/交证件): ' + fam.get('why', ''))
  416. elif fam['kind'] == 'shipped':
  417. jp, js, pg = judgement_evidence(farm, rels)
  418. gen_file = ROOT / fam['gen'] if fam.get('gen') else None
  419. gen_ok0 = bool(gen_file and gen_file.is_file())
  420. # ★ 逐件分人工件 (用户令 2026-09-17 #3): 含人工判断字段的件**不按自动产物参与呼应校验**,
  421. # 单独计 ◆; 余下才是真正的"无生成端"。
  422. human = classify_human(farm, rels)
  423. rest = [r for r in rels if r not in human]
  424. fv, fw = feasibility(fam, rest or rels, gen_ok0, False, jp, js, pg)
  425. row['verdict'] = '✗ 无生成端' if not human else f'✗ 无生成端 + ◆ 人工件 {len(human)}'
  426. row['n'] = len(rest)
  427. row['note'] = fam.get('why', '')
  428. row['rev'], row['rev_why'] = fv, fw
  429. if jp:
  430. row['rev_why'] += f';人工判断字段抽样命中 {jp}%' + (f'(如 {js[0]})' if js else '')
  431. for r in rest:
  432. verdict[r] = dict(fam=fam['id'], verdict='✗', why='无生成端(全库 0 处写入方): ' + fam['why'])
  433. for r in human:
  434. verdict[r] = dict(fam=fam['id'], verdict='◆',
  435. why='人工件(含人工判断字段): 不参与呼应校验, 随包留在原位')
  436. else:
  437. # ① 生成端在位
  438. gen = ROOT / fam['gen'] if fam.get('gen') else None
  439. gen_ok = bool(gen and gen.is_file())
  440. # ② 输入在位(场站目录优先, 机理层资料在 raw 根下 —— 见 _input_home)
  441. spec = INV.INPUTS.get(fam['input'] or '')
  442. i_s = i_e = None
  443. i_n = 0
  444. i_gran = '年'
  445. home = _input_home(station, fam['input']) if fam['input'] else None
  446. if home and spec:
  447. i_s, i_e, i_n, _note, i_gran = INV.input_span(home, fam['input'], spec)
  448. elif home:
  449. # 机理层资料这类"没有跨度判据"的输入: 按件数清点即算在位(INV.INPUTS 里没有它们的
  450. # 跨度口径 —— 技术资料是文档而不是时序数据, 拿跨度比毫无意义)
  451. i_n = sum(1 for p in (home / fam['input']).rglob('*') if p.is_file())
  452. i_gran = '年'
  453. elif fam['kind'] == 'source-derived':
  454. # ★ 输入是**包内源码**而不是 data/raw(如发布清单快照: 从 src/windscada/ui 重建页再摘要)。
  455. # 生成端在位 = 输入在位, 这类产物的"呼应"是对源码的, 不是对原始件的。
  456. i_n = 1
  457. i_s = i_e = '包内源码'
  458. in_ok = i_n > 0
  459. passed, notes = [], []
  460. if fam['pred'] and in_ok:
  461. if 'span' in fam['pred']:
  462. p_s, p_e, n = _parquet_span(P.out_root(farm) / rels[0], fam.get('time_col'))
  463. if p_s and i_s and (p_s[:7] < i_s[:7]):
  464. # ★ 年粒度输入(按文件名年份推的)不判失败: 与正向检查同一条教训 ——
  465. # 台账 xls 里可能含比文件名年份更早的历史记录, 拿年粒度当"输入起点"会造假缺口
  466. # (2026-09-17 实测: 工单产物起点 2020-01 而输入文件名最早 2021 ⇒ 不是数据串了)。
  467. msg = f'产物起点 {p_s} 早于输入起点 {i_s}'
  468. if i_gran in ('日', '月'):
  469. fails.append(f"{fam['id']}: {msg}(跨窗混入 / 键错)")
  470. notes.append('⚠ ' + msg)
  471. else:
  472. notes.append(f'{msg}(输入为年粒度, 只作参考: 台账可能含更早的历史行)')
  473. passed.append(f'跨度 {p_s}~{p_e} ⊆ 输入 {i_s}~{i_e}')
  474. if 'turbines' in fam['pred']:
  475. pt = _turbines_of(P.out_root(farm) / rels[0])
  476. it = _input_turbines(home, fam['input']) if home else None
  477. if pt and it:
  478. extra = pt - it
  479. if extra:
  480. fails.append(f"{fam['id']}: 产物含输入里没有的机组 {sorted(extra)[:5]}")
  481. passed.append(f'机组 {len(pt)} 台 ⊆ 输入 {len(it)} 台')
  482. if 'rows' in fam['pred']:
  483. tot = 0
  484. for r in rels[:400]:
  485. _s, _e, n = _parquet_span(P.out_root(farm) / r, None) if r.endswith('.parquet') \
  486. else (None, None, 1)
  487. tot += n
  488. if tot <= 0:
  489. fails.append(f"{fam['id']}: 产物行数合计为 0")
  490. passed.append(f'件内数据行合计 {tot:,}' + ('(抽样 400 件)' if len(rels) > 400 else ''))
  491. if 'npz' in fam['pred']:
  492. sample = rels[:5]
  493. bad = [r for r in sample if not _npz_ok(P.out_root(farm) / r)]
  494. if bad:
  495. fails.append(f"{fam['id']}: 抽样 {len(bad)}/{len(sample)} 件 npz 读不出或为空")
  496. passed.append(f'{len(rels)} 件谱(抽样 {len(sample)} 件 npz 均可读非空)· 输入源 {i_n} 件')
  497. if 'manifest' in fam['pred']:
  498. try:
  499. mf = json.loads((P.out_root(farm) / rels[0]).read_text(encoding='utf-8'))
  500. passed.append('清单自记: ' + ', '.join(f'{k}={v}' for k, v in list(mf.items())[:3]))
  501. except Exception as e:
  502. fails.append(f"{fam['id']}: 清单读不出来 ({type(e).__name__})")
  503. if not gen_ok:
  504. row['verdict'] = '✗ 生成端不在位'
  505. row['note'] = f"缺 {fam['gen']}"
  506. fails.append(f"{fam['id']}: 生成端不在位 {fam['gen']}")
  507. elif not in_ok:
  508. row['verdict'] = '~ 输入不在位'
  509. row['note'] = (f"缺 {(home / fam['input']) if home else station / str(fam['input'])}"
  510. ' ⇒ 现在无法验证(放数据后复跑本器)')
  511. else:
  512. row['verdict'] = '✓ 呼应成立'
  513. row['note'] = ';'.join(notes + passed)
  514. row['rev'], row['rev_why'] = '已在重算链上', '生成端在位、输入在位、判据通过 —— 无需逆向工程'
  515. for r in rels:
  516. verdict[r] = dict(fam=fam['id'], verdict=row['verdict'][0],
  517. why=row['note'] if row['verdict'][0] != '✓' else row['note'][:120])
  518. fam_rows.append(row)
  519. # 未归类件 (台账里有, 但没有任何族接住)
  520. unclassified = []
  521. for rel, v in LEDGER.items():
  522. if rel.lower().endswith(('.log', '.jsonl')):
  523. continue
  524. if rel in verdict:
  525. continue
  526. # 产物走通配没接住的, 也按台账来源判定
  527. unclassified.append(rel)
  528. verdict[rel] = dict(fam='(未归类)', verdict='?', why='既不在族表、也无法从台账判定来路')
  529. counts = {}
  530. for v in verdict.values():
  531. counts[v['verdict']] = counts.get(v['verdict'], 0) + 1
  532. if verbose:
  533. print(f'== 反向呼应审计 · 场站 {farm} · 台账 {len(LEDGER)} 件 · 判定 {len(verdict)} 件 ==')
  534. print(f' 输入根: {P.rel(station)}')
  535. print()
  536. print(f'{"族":26s} {"件数":>6s} {"判定":14s} {"输入类":12s} {"功能 / 算法 / 依据"}')
  537. for r in fam_rows:
  538. print(f' {r["id"]:24s} {r["n"]:6d} {r["verdict"]:14s} {str(r["input"] or "—"):12s} '
  539. f'{r["func"][:34]}')
  540. if r['note']:
  541. print(f' └─ {r["note"][:150]}')
  542. if unclassified:
  543. print(f'\n 【未归类 {len(unclassified)} 件】')
  544. for r in unclassified[:20]:
  545. print(f' ? {r}')
  546. print('\n 判定汇总: ' + ' · '.join(f'{k}={v}' for k, v in sorted(counts.items())))
  547. print(f' 判据失败 {len(fails)} 条' + (':' + ';'.join(fails[:3]) if fails else ''))
  548. ok = counts.get('✓', 0)
  549. print(f' 结论: 输出↔输入呼应**成立** {ok} 件 / **不成立(无生成端)** {counts.get("✗", 0)} 件 / '
  550. f'**人工件** {counts.get("◆", 0)} 件 / 无法验证 {counts.get("~", 0)} 件 / 未归类 {counts.get("?", 0)} 件')
  551. # ── 逆向工程可行性 (用户令 #2): 没有呼应关系的那些, 能不能推出来 ──
  552. import collections as _c
  553. by_rev = _c.Counter()
  554. for r in fam_rows:
  555. by_rev[r.get('rev', '?')] += r['n']
  556. print()
  557. print('== 反向「可逆性」矩阵(用户令 2026-09-17 #2: 无生成端的件能否从原件推出来)==')
  558. print(f'{"族":26s} {"件数":>6s} {"可逆性":22s} 依据')
  559. for r in fam_rows:
  560. if r['verdict'][0] == '✓':
  561. continue
  562. print(f' {r["id"]:24s} {r["n"]:6d} {r.get("rev", "?"):22s} {r.get("rev_why", "")[:96]}')
  563. print(' 按件数汇总: ' + ' · '.join(f'{k}={v}' for k, v in by_rev.most_common()))
  564. rc = 5 if (fails or unclassified) else 0
  565. return fam_rows, verdict, counts, fails, unclassified, rc
  566. def doc_block(farm: str) -> str:
  567. fam_rows, verdict, counts, fails, unclassified, _rc = audit(farm, verbose=False)
  568. L = [DOC_BEGIN, '### 13.6 反向呼应审计:自输出 → 功能与算法 → 输入(自动生成,勿手改)', '',
  569. f'台账 {len(verdict)} 件产物逐件回溯:**呼应成立 {counts.get("✓", 0)} 件** · '
  570. f'**不成立(无生成端){counts.get("✗", 0)} 件** · 无法验证 {counts.get("~", 0)} 件 · '
  571. f'未归类 {counts.get("?", 0)} 件。'
  572. '判据:① 生成端在位 ② 输入在位 ③ 跨度 ⊆ 输入 / 机组集 ⊆ 输入 / 行数 > 0 / 计数与清单一致。', '',
  573. '| 输出族(产物 glob) | 件数 | 反向判定 | 功能 | 算法 / 生成端 | 输入(data/raw/<场>/) | 判据 | 说明 |',
  574. '|---|---:|---|---|---|---|---|---|']
  575. for r in fam_rows:
  576. fam = next(f for f in FAMILIES if f['id'] == r['id'])
  577. L.append(f'| `{fam["glob"]}` | {r["n"]} | {r["verdict"]} | {r["func"]} | {r["algo"]} | '
  578. f'{r["input"] or "—(无生成端)"} | {r["pred"]} | {r["note"][:160]} |')
  579. if unclassified:
  580. L += ['', f'**未归类 {len(unclassified)} 件**(需人工认领):' + '、'.join(f'`{x}`' for x in unclassified[:12])]
  581. L += ['', '#### 反向「可逆性」:没有呼应关系的那批,能否从原始件推出来(用户令 2026-09-17 #2)', '',
  582. '判据两条机器证据:① 生成端在不在包内 ② 产物正文里有没有**人工判断**字段'
  583. '(`人工/裁决/审核/校准/评审/经验/judge/review/calibrat/verdict`,抽样读件统计命中率)。'
  584. '含人工判断的件不是任何输入的纯函数 ⇒ 逆向工程推不出来,只能把那一步人工工作重做。', '',
  585. '| 输出族 | 件数 | 可逆性 | 依据 |', '|---|---:|---|---|']
  586. for r in fam_rows:
  587. if r['verdict'][0] == '✓':
  588. continue
  589. L.append(f'| `{r["id"]}` | {r["n"]} | {r.get("rev", "?")} | {r.get("rev_why", "")} |')
  590. import collections as _c
  591. by_rev = _c.Counter()
  592. for r in fam_rows:
  593. by_rev[r.get('rev', '?')] += r['n']
  594. L += ['', '**按件数汇总**:' + ' · '.join(f'{k} = {v} 件' for k, v in by_rev.most_common()), '',
  595. '**人工件**:含人工判断字段的件已逐件登记在 outputs/&lt;场&gt;/_human_artifacts.json(用户令 2026-09-17 #3),'
  596. '它们**不参与**呼应校验(人写成/坐实的东西不是任何输入的纯函数);生成方式:'
  597. 'python scripts/products_reverse_audit.py --write-human-manifest。', '',
  598. '> 结论口径:`可逆(直接)` = 包内已有生成端,接上即可;`可逆(需反推口径)` = 内容是测量数据的函数,'
  599. '照 `temp_monthly` 的办法反推 + 逐值对拍;`不可逆(人工判断)` = 逆向工程推不出来,'
  600. '要么由研发补生成端、要么承认它是人工件(不该按产物管)。', DOC_END]
  601. return '\n'.join(L)
  602. def write_doc(farm: str) -> int:
  603. doc = ROOT / 'docs' / '系统设计说明.md'
  604. txt = doc.read_text(encoding='utf-8')
  605. blk = doc_block(farm)
  606. i, j = txt.find(DOC_BEGIN), txt.find(DOC_END)
  607. if i >= 0 and j > i:
  608. txt = txt[:i] + blk + txt[j + len(DOC_END):]
  609. else: # 首次: 追加到文末
  610. txt = txt.rstrip('\n') + '\n\n' + blk + '\n'
  611. doc.write_text(txt, encoding='utf-8', newline='\n')
  612. print(f'已写入 {P.rel(doc)} (§13.6 反向呼应审计块)')
  613. return 0
  614. def main() -> int:
  615. ap = argparse.ArgumentParser(description='反向呼应审计: 输出 → 功能与算法 → 输入')
  616. ap.add_argument('--farm', default=None)
  617. ap.add_argument('--check', action='store_true', help='只出结论 (有未归类/判据失败 → rc=5)')
  618. ap.add_argument('--write-doc', action='store_true', help='把族表写进 docs/系统设计说明.md §13.6')
  619. ap.add_argument('--write-human-manifest', action='store_true',
  620. help='生成人工件台账 outputs/<场>/_human_artifacts.json (用户令 2026-09-17 #3)')
  621. a = ap.parse_args()
  622. if a.write_human_manifest:
  623. return write_human_manifest(a.farm)
  624. if a.write_doc:
  625. return write_doc(a.farm or P.farm())
  626. _rows, _v, counts, fails, uncl, rc = audit(a.farm, verbose=True)
  627. if a.check:
  628. print(f'[{"OK" if rc == 0 else "X"}] 反向呼应审计 rc={rc}'
  629. + (f'(未归类 {len(uncl)} 件 / 判据失败 {len(fails)} 条)' if rc else '(未归类 0 件、判据无失败)'))
  630. return rc
  631. if __name__ == '__main__':
  632. for _s in (sys.stdout, sys.stderr):
  633. try:
  634. _s.reconfigure(errors='replace')
  635. except Exception:
  636. pass
  637. sys.exit(main())