products_reverse_audit.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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_slim10min', glob='windscada/slim10min/*', kind='raw-derived',
  59. func='按窗重算底座 · SCADA 10min 窄仓',
  60. algo='scripts/scada_slim_build.py(逐台 load_10min 的公共列子集约 46 列:功率/限电命令/风况/转速/'
  61. '桨距/温度 _mean 27/偏航/液压;不裁剪行。用户令 2026-09-21「判级/曲线随所选时间窗重算」的底座:'
  62. '一次全量扫 ≈2 分钟,之后任何窗的判级与七镜头重算都只是窄仓上的过滤+分组)',
  63. gen='scripts/scada_slim_build.py', input='scada_10min', pred=('rows', 'turbines'),
  64. time_col='ts'),
  65. dict(id='scada_alarms', glob='windscada/alarms.parquet', kind='raw-derived',
  66. func='三门台账 · 报警', algo='scripts/windscada_alarms_ingest.py(SpreadsheetML *.xls → 事件表)',
  67. gen='scripts/windscada_alarms_ingest.py', input='故障报警', pred=('span', 'rows'), time_col='t_on'),
  68. dict(id='scada_workorders', glob='windscada/workorders.parquet', kind='raw-derived',
  69. func='三门台账 · 工单', algo='scripts/windscada_workorder_ingest.py(检修台账 → 工单表)',
  70. gen='scripts/windscada_workorder_ingest.py', input='风机故障记录', pred=('span', 'rows'),
  71. time_col='t_report'),
  72. dict(id='scada_oil', glob='windscada/oil_samples_index.parquet', kind='raw-derived',
  73. func='三门台账 · 油样', algo='scripts/windscada_watch_channels_build.py(油样 PDF → 索引)',
  74. gen='scripts/windscada_watch_channels_build.py', input='油样报告', pred=('span', 'rows'),
  75. time_col='date'),
  76. dict(id='scada_monthly', glob='windscada/temp_monthly.parquet', kind='raw-derived',
  77. func='月度派生件', algo='scripts/windscada_monthly_build.py(逐值对齐随包件 19,494/19,494)',
  78. gen='scripts/windscada_monthly_build.py', input='scada_10min', pred=('span', 'rows'), time_col='month'),
  79. dict(id='scada_derived', glob='windscada/*.parquet', kind='raw-derived',
  80. func='SCADA 派生分析(功率曲线/损失/曲线/控制/停机/温度/偏航/液压/热链/系统辅助)',
  81. algo='src/windscada/perf/{powercurve,availability,curves,control,faults} + subsys/{temp_nbm,yaw,'
  82. 'hydraulic,thermal_chain} + taxonomy.py',
  83. gen='src/windscada/perf/powercurve.py', input='scada_10min', pred=('rows',)),
  84. dict(id='ontology_core', glob='ontology/{objects.json,retrieval_index.json,turbine_params.parquet}',
  85. kind='raw-derived',
  86. func='本体层 · 码表/对象库/检索索引/实机参数',
  87. algo='python -m src.ontology.kb_ingest → populate → chain_ingest → trend_ingest;'
  88. 'src.ontology.retrieval.build;src.ontology.maintenance.refresh_params',
  89. gen='src/ontology/kb_ingest.py', input='西门子4.0技术资料', pred=('rows',)),
  90. dict(id='ontology_aux_build', glob=['ontology/_id_alias.json', 'ontology/retrieval_vec.npy'],
  91. kind='raw-derived',
  92. func='本体层 · 别名表与向量索引缓存', algo='src.ontology.kb_ingest(别名)/ '
  93. 'src.ontology.retrieval.build(use_vec=True)(向量)',
  94. gen='src/ontology/kb_ingest.py', input='西门子4.0技术资料', pred=('rows',)),
  95. dict(id='ontology_domain', glob=['ontology/oil_2026H2_huabiao.json', 'ontology/parts_cost_public.json',
  96. 'ontology/scenario_29_repair.json'],
  97. kind='shipped',
  98. func='本体层 · 领域数据件(油样台账/备件价格/场景修复)', algo='(无生成端, 领域正本出件)',
  99. gen=None, input=None, pred=(), why='领域正本随包发来, 不由 data/raw 推导'),
  100. # ── 以下族: 全库 0 处写入方 ⇒ 反向呼应**在原理上不成立**(如实记账, 不假装成立)────
  101. # ★2026-09-18 用户令补充: 这些件**运行期一律不从交付包补**(用户令 2026-09-17 #1 的延伸),
  102. # 页面如实为空/降级; 要出件只有两条路 —— ① 研发补生成端; ② 现场正本随原始件进 data/raw。
  103. # 故本表的 why 里不再写"从交付包补齐"那种话(那是**离线人工补救**, 见 products_restore_missing.py)。
  104. dict(id='vib_model_run_l6', glob=['m5_cms_tcm/model_run_l6.parquet', 'm5_cms_tcm/model_run_summary.json'],
  105. kind='raw-derived',
  106. func='六层链 model_run 步 · L6 过闸谱线表 + 层小结',
  107. algo='scripts/rudong_model_run.py(候选线=oem_scan_plan 的 11 部件×{BPFI,BPFO,BSF}; 过闸='
  108. 'src/sop/discriminators.py::spectral_line_gates G1–G8; 定级=vib_verdict_and_writeback)',
  109. gen='scripts/rudong_model_run.py', input='m5_cms_tcm', pred=('rows',),
  110. why='★2026-09-19 按口径重建(**无标准答案**: 这两件从未随包, 无法逐值对拍); 峰值拾取仍是本器自定'
  111. '(目标频率 ±2 bin 取最大), 不得当"复现"用 —— 见 docs/振动六层链_接口规格与缺口_v0.1.md §3'),
  112. dict(id='vib_fusion_38', glob='m5_cms_tcm/fusion_38.csv', kind='raw-derived',
  113. func='六层链 fusion 步 · 逐台融合表(报告"融合级"列的来源)',
  114. algo='scripts/rudong_fusion_run.py::fusion_table(模型侧=model_run_l6 过闸线; CMS 侧=窗索引 '
  115. 'RedMask/YellowMask; 裁决=src/sop/fusion_diag.py::fuse)',
  116. gen='scripts/rudong_fusion_run.py', input='m5_cms_tcm', pred=('rows',),
  117. why='★按口径重建(无标准答案): 台号用 WTGnn 形态(消费端 registry 的键), 与 l6 的 f"{n}#" 不同'),
  118. # ★2026-09-19 源代码化(第三批):三族由观澜自算顶上。★族表是**首个命中生效**,故这几族必须
  119. # 排在通配族(`vib_handoff_and_scans` = `m5_cms_tcm/*.{json,parquet,csv,md,txt}`、`tcm_replay`、
  120. # 旧的 `ontology_releases`)**之前**,否则新件会被旧族认领成"无生成端"。
  121. dict(id='vib_line_energy_share', glob='m5_cms_tcm/line_energy_share.parquet', kind='raw-derived',
  122. func='六层链 energy_share 步 · 线能量占比',
  123. algo='scripts/rudong_line_energy_share.py(±2bin 带内能量 ÷ 全谱能量 ×100; 候选线与分母同 oem_scan_plan)',
  124. gen='scripts/rudong_line_energy_share.py', input='m5_cms_tcm', pred=('rows',),
  125. why='2026-09-19 补上: 该步脚本此前未随包(chain_gap_check 报"1 个步骤脚本未随包"); 只报占比不定级'),
  126. dict(id='vib_mask_thresholds', glob=['tcm_compatible_replay/model/mask_thresholds.tsv',
  127. 'tcm_compatible_replay/model/mask_thresholds.说明.json'],
  128. kind='raw-derived', func='TCM 掩码阈值件 (逐台逐测点逐工况的黄/红线)',
  129. algo='scripts/tcm_mask_thresholds_build.py(中位 + 3/6×MAD 自适应基线, 基线先净化, 样本门 n≥30; '
  130. '调 src/sop/discriminators.py::adaptive_baseline_threshold 单一实现)',
  131. gen='scripts/tcm_mask_thresholds_build.py', input='m5_cms_tcm', pred=('rows',),
  132. why='★**观澜自算**阈值, 不是厂商阈值: 现场导出件里没有掩码定义(25,679 个 decode 只有 NumberOfMasks: 175) '
  133. '⇒ 厂商阈值无法复原; 口径写在同目录 mask_thresholds.说明.json, 页面据此标注(workbench.py 分支)'),
  134. dict(id='ontology_releases', glob='ontology/release_*/*', kind='raw-derived',
  135. func='本体发布层 r1/r2(网关 /release/ 只读暴露)',
  136. algo='scripts/ontology_release_build.py(对象库投影: r1 契约层 = objects.json 快照 + manifest; '
  137. 'r2 = 同快照 + layering.json 分层覆盖声明, 不合并主库)',
  138. gen='scripts/ontology_release_build.py', input='西门子4.0技术资料', pred=('rows',),
  139. why='2026-09-19 由观澜自算顶上: 原为随包件(0 处写入方) ⇒ 新机器 /release/ 两件必 503; '
  140. 'manifest 里写 source.sha16, 谁都能核出两层是同一份对象库的投影'),
  141. dict(id='vib_fleet_scalar_z', glob='m5_cms_tcm/fleet_scalar_z.parquet', kind='raw-derived',
  142. func='振动线 · 全场标量 z 值 (fusion 步出件)',
  143. algo='scripts/rudong_fusion_run.py(逆向工程实现: 窗索引 scalar_value → 同 (传感器,测量,工况) 族中位 '
  144. '→ 稳健 z=(val−med)/(1.4826·MAD); 与随包样件 8,887 行逐值对拍 val 列 100% 一致)',
  145. # input 写**原始件目录名**(族表口径: data/raw/<场>/<input>); 真实取数经窗索引一跳,
  146. # 而窗索引本身是 raw-derived(vib_window_index 族) —— 写 windows/_*.parquet 会让审计判"输入不在位"。
  147. gen='scripts/rudong_fusion_run.py', input='m5_cms_tcm', pred=('rows',),
  148. why='2026-09-18 上链: 由 vib_raw_build.py 的 --with-report 分支按当次窗名调用, '
  149. '使 /api/fleet 的振动标量 z 面不再空白'),
  150. dict(id='vib_fusion_handoff', glob='m5_cms_tcm/handoff_vibration_v2.json', kind='raw-derived',
  151. func='融合面 handoff (观澜自算, 同结构于振动线手交件)',
  152. algo='scripts/rudong_fusion_handoff.py(报告状态等级 + fusion_38 融合裁决 + L6 过闸线 → 同结构, '
  153. 'meta.from 标明"观澜自算")',
  154. gen='scripts/rudong_fusion_handoff.py', input='m5_cms_tcm', pred=('rows',),
  155. why='★2026-09-19 用户令「所有的计算均要形成观澜的源代码」: 这件此前全库 0 处写入方(振动线人写), '
  156. '新机器装完 `/detail/v2` 的「需要关注/全场状态」必然空白。现由观澜自算出同结构件; '
  157. '盘上若有**振动线正本**, 生成端不覆盖(正本含人工裁决, 优先)'),
  158. # ★2026-09-19 用户令「所有的计算均要形成观澜的源代码」: 这两件此前 kind=shipped(振动线人交手交件),
  159. # 新机器上 ⑦ 的 `src.ontology.trend_ingest` 报"源缺失"、CMS 报告的三层基线卡为空。
  160. # 现由两个生成端从**窗索引**算: component_history(逐窗标量 x_self → 在升/换件闭环; 窗不足时如实为空
  161. # 并把数据边界逐条写进 meta) / baseline_38(健康期分段中位 → 自基线 + fleet 基线 + ISO 绝对限)。
  162. # ★必须排在通配族 `vib_handoff_and_scans` **之前** (族表首个命中生效), 否则又被认领成"无生成端"。
  163. dict(id='vib_history_baseline',
  164. glob=['m5_cms_tcm/component_history.json', 'm5_cms_tcm/baseline_38.json'],
  165. kind='raw-derived',
  166. func='振动在升/换件闭环历史 + 三层基线(自 / 机群 / 绝对)',
  167. algo='scripts/component_history_build.py(逐窗标量 x_self → 末三窗/早三窗在升 + 换件前后闭环; '
  168. '窗不足时判据不可算则如实空表)+ scripts/baseline_38_build.py(健康期分段中位 + 正常带 + '
  169. 'relMAD → 自基线, 机群同段中位 → fleet 基线, ISO 20816-3 → 绝对限)',
  170. gen='scripts/component_history_build.py', input='windcms', pred=('rows',),
  171. why='输入是 CMS 原始导出的**重算产物**(窗索引), 其 raw 祖先是 data/raw/<场>/windcms; '
  172. '旧随包件是振动线手交件(全库 0 处写入方); 两件都在重算链 ④d/④e, 口径与数据边界写进件内 meta'),
  173. dict(id='vib_handoff_and_scans', glob='m5_cms_tcm/*.{json,parquet,csv,md,txt}',
  174. kind='shipped',
  175. func='振动线出件与专项扫描(handoff / 历史 / 基线 / 各类 freq scan / 判级台账)', algo='(无生成端)',
  176. gen=None, input=None, pred=(), why='振动六层链四步脚本未随包(oem_frequency_scan 等)⇒ '
  177. '运行期不从交付包补(用户令 2026-09-17); 要出件须研发补生成端, '
  178. '或由现场正本随原始件进 data/raw 后重算'),
  179. # (2026-09-19: `line_energy_share` / `mask_thresholds` / `ontology_releases` 三族已移到前面按
  180. # raw-derived 记账 —— 族表是**首个命中生效**, 必须排在通配族 `vib_handoff_and_scans` / `tcm_replay`
  181. # / `ontology_releases(旧)` 之前, 否则新件会被旧族认领成"无生成端")
  182. dict(id='vib_figs', glob='m5_cms_tcm/figs/*', kind='shipped',
  183. func='振动线出图(谱图/趋势图)', algo='(无生成端)', gen=None, input=None, pred=(),
  184. why='随包快照(振动线出件)'),
  185. # ★2026-09-19 拆族 (用户令「所有的计算均要形成观澜的源代码」): `windscada/index.html` 是
  186. # `/detail/v2` 的「全场状态总览」iframe 目标, 此前整族记为"无生成端" ⇒ 新机器上那块必然显示
  187. # "产物不在位"。现在它由 `scripts/windscada_overview_build.py` 用**组件同一个快照烘焙器**
  188. # (src/windscada/ui/snapshot.py::bake, /v2/snapshot 用的就是它)从重算产物生成 ⇒ 单列一族。
  189. dict(id='windscada_overview', glob='windscada/index.html', kind='raw-derived',
  190. func='总览「全场状态」页 (单文件: 接口响应烤进页面, 离线可开)',
  191. algo='scripts/windscada_overview_build.py(ctx 取数函数与在线 /api/* 同一实现; 经 '
  192. 'src/windscada/ui/snapshot.py::bake 烘焙)',
  193. gen='scripts/windscada_overview_build.py', input='scada_10min', pred=('rows',),
  194. why='2026-09-19 用户令后上链: 该页此前是随包件(全库 0 处写入方), 清过产物的机器上 iframe 只能'
  195. '显示"产物不在位"; 现在由观澜自算, 每次重算随数据更新'),
  196. dict(id='windscada_pages', glob='windscada/{turbines/*,review/*}', kind='shipped',
  197. func='逐台静态页 + 评审记录(当前由组件按请求动态出页, 静态件仍属随包快照)', algo='(无生成端)',
  198. gen=None, input=None, pred=(), why='逐台页在运行期由 /turbine/<台> 动态生成, 静态副本无写入方; '
  199. '运行期不从交付包补(用户令 2026-09-17)'),
  200. # ★2026-09-18 补: `windcms/cache/*` 是**读侧缓存**(标量按内容哈希落盘), 它不是随包快照 ——
  201. # 原先 `windcms_pages`(shipped) 先认领了它, 于是重算后新写的缓存被记成"包内无生成端"。
  202. # 写方在 src/windcms/data.py::load_scalars (窗索引 → 标量), 故单列一族并放在 windcms_pages 之前。
  203. dict(id='windcms_cache', glob='windcms/cache/*', kind='raw-derived',
  204. func='CMS 报告侧 · 标量缓存', algo='src/windcms/data.py::load_scalars(窗索引 → 标量数组, '
  205. '按内容哈希命名落 cache/)', gen='src/windcms/data.py', input='windcms', pred=('rows',)),
  206. # ★2026-09-18 补 (用户令"页面只能基于输入数据重算"之后): `windcms/**` 整族原先一律按
  207. # "无生成端"记账 —— 但**报告两步的生成端就在包内**(scripts/windcms.py report → src/windcms/
  208. # report.py + report_std.py), 只要 data/raw/<场>/windcms 里有 decode 导出就出得来。
  209. # 实测(2026-09-18): 从重算出的窗 w0316 一键跑出标准模版报告 + 38 台逐台页 + 总览, 判级 38 台
  210. # (报警 3 / 优秀 35), 缺的只有 model_run/fusion 两步的融合级列(如实写 —)。故拆成两族按 raw-derived 记。
  211. dict(id='windcms_report_std', glob=['windcms/报告_CMS振动状态评估报告_*.md',
  212. 'windcms/报告_CMS振动状态评估报告_*.docx',
  213. 'windcms/登记_三轴_38台.csv'], kind='raw-derived',
  214. func='CMS 标准模版评估报告 (三轴: 状态等级 × 证据状态 × 行动等级建议)',
  215. algo='src/windcms/report_std.py::build(结构化判级 → 报告 md + docx + 登记 csv; '
  216. '由 scripts/windcms.py report 调用)',
  217. gen='src/windcms/report_std.py', input='windcms', pred=('rows',),
  218. why='★同名件有两种来源: 观澜自算(本族: 从 data/raw/<场>/windcms 的 *_decode.json 算) 与 '
  219. '厂家报告转录(scripts/vib_reports_build.py, 输入是现场振动分析报告 PDF)。按名字认领不了'
  220. '这层区别 ⇒ 以"是否由本步生成"为准, 判据看 m5_cms_tcm/vib_raw_manifest.json 的 steps'),
  221. dict(id='windcms_report_overview', glob=['windcms/report.md', 'windcms/index.html',
  222. 'windcms/index_eng.html', 'windcms/overview.html',
  223. 'windcms/turbines/*'], kind='raw-derived',
  224. func='CMS 诊断总览页 + 逐台页 + 结构化层报告',
  225. algo='src/windcms/report.py::build(逐台 turbines/<台>.html + 总览 overview/index.html + '
  226. 'report.md; 融合级列要 model_run/fusion 出件, 缺则如实写"—")',
  227. gen='src/windcms/report.py', input='windcms', pred=('rows',)),
  228. dict(id='windcms_kb', glob='windcms/kb.json', kind='raw-derived',
  229. func='CMS 知识库索引 (问答检索用)',
  230. algo='src/windcms/knowledge.py::build(由 scripts/windcms.py kb 调用; 离线无模型时 0 chunks 也算跑成)',
  231. gen='src/windcms/knowledge.py', input='windcms', pred=('rows',)),
  232. dict(id='windcms_pages', glob='windcms/**', kind='shipped',
  233. func='windcms 里其余件 (厂家报告转录 / 知识库出件等)',
  234. algo='(无随包生成端)', gen=None, input=None, pred=(),
  235. why='上述两族与 cache 之外剩下的 windcms 件: 运行期不从交付包补(用户令 2026-09-17), '
  236. '要出件须研发补生成端'),
  237. # ★2026-09-19 用户令「要让观澜从重算台账生成 claim」: findings 与三份底稿改由**观澜自算**
  238. # (scripts/sop_findings_from_ledger.py 从 alarms/workorders/oil/temp_bins/powercurve_dev/loss_monthly/L6
  239. # 算 claim, 按契约构建器要的字段结构写) ⇒ 单列一族; 契约四件随之由 scripts/guanlan_facts_contract.py 生成。
  240. dict(id='ledger_claims', glob=['sop/findings.json', 'paradigm_r1/experiments/*/底稿*.json'],
  241. kind='raw-derived',
  242. func='事实契约的 claim 本体与底稿 (观澜自算, 替代人裁底稿)',
  243. algo='scripts/sop_findings_from_ledger.py(六族 claim: 报警集中/重复检修/停机损失/温度离群/功率曲线偏离/振动过闸线; '
  244. '每条带 coverage·缺证据·证伪判据, 相对判据封顶「候选」)',
  245. gen='scripts/sop_findings_from_ledger.py', input='scada_10min', pred=('rows',),
  246. why='输入是**重算产物**(windscada/*.parquet + m5_cms_tcm/*): 其 raw 祖先是 故障报警/风机故障记录/scada_10min; '
  247. '本族单列以区别于旧的人裁底稿(同路径旧件无生成端)'),
  248. dict(id='sop_workspace', glob='sop/**', kind='shipped',
  249. func='SOP 中间件/评审/事实契约底稿', algo='(无生成端)', gen=None, input=None, pred=(),
  250. why='评审过程件, 属人工作业留痕'),
  251. dict(id='tcm_replay', glob='tcm_compatible_replay/**', kind='shipped',
  252. func='TCM 兼容链回放资产(模型表/掩码阈值/裁决记录)', algo='(无生成端)', gen=None, input=None,
  253. pred=(), why='随包快照'),
  254. dict(id='paradigm_r1', glob='paradigm_r1/**', kind='shipped',
  255. func='范式实验件(E3/E5/E8 底稿)', algo='(无生成端)', gen=None, input=None, pred=(),
  256. why='实验底稿, 事实契约的输入'),
  257. # ★2026-09-19 用户令「所有的计算均要形成观澜的源代码」: 变桨面两件原来 kind=shipped(无生成端)
  258. # ⇒ 换台机器重算后必然缺件、变桨面恒"不可判"。现由 scripts/pitch_face_build.py 从 data/raw 的
  259. # scada_10min(液压/润滑/柱塞/运行状态) + scada_1min(三叶桨距角/压力/有功) 算出, 并进重算链 ④c。
  260. dict(id='pitch_face', glob='pitch/**', kind='raw-derived',
  261. func='变桨侧派生件(日粒度液压/润滑/柱塞 + 零位三口径月表)',
  262. algo='scripts/pitch_face_build.py(10min 开关量 timeon/压力锯齿 + 1min 停机顺桨段/满发段/运行段分档 '
  263. '三叶桨距角中位 → 相对同月全场中位的零位偏差;口径/阈值/证据见同目录 pitch_face_manifest.json)',
  264. gen='scripts/pitch_face_build.py', input='scada_10min', pred=('rows',),
  265. why='输入是 10min 与 1min 两路 SCADA 原始导出件(scada_source: CSV 优先/MDB 回落);'
  266. '零位按用户令两口径分列(停机顺桨段/满发段),并据实测反推补上**运行段同工况分档**这一判据轴'
  267. '(它才能把现场确诊的 19# 单独拎出来)'),
  268. # (2026-09-19: `ontology_releases` 已移到前面按 raw-derived 记账 —— 现在由
  269. # scripts/ontology_release_build.py 从对象库投影生成, 不再是"由研发出件"的随包层)
  270. # ★2026-09-19 用户令「所有的计算均要形成观澜的源代码」+「从重算台账生成 claim」:
  271. # 这一族从"无生成端"改成 raw-derived —— 生成端 guanlan_facts_contract.py 本来就在包内,
  272. # 原来缺的是**它的输入**(人裁底稿); 现在输入由上游族 ledger_claims 自算
  273. # (scripts/sop_findings_from_ledger.py) ⇒ 新机器上重算即得, /api/facts 不再 503。
  274. dict(id='guanlan_contract', glob='guanlan/**', kind='raw-derived',
  275. func='事实契约与对外派生(门户结论段/取数)',
  276. algo='scripts/guanlan_facts_contract.py(build→render: 契约 + portal_claims/detail_cards/qa_refs/'
  277. 'report_summary; 输入=上游族 ledger_claims 自算的 sop/findings.json + 三份底稿)',
  278. gen='scripts/guanlan_facts_contract.py', input='scada_10min', pred=('rows',),
  279. why='输入与 data/raw 隔着两跳(重算台账 → claims → 契约), 但**两跳的生成端都在包内**; '
  280. 'claim 的判据/缺证据/证伪逐条写在件里, 相对判据封顶「候选」'),
  281. dict(id='windscada_release_manifest', glob='windscada/release-manifest.json', kind='source-derived',
  282. func='发布清单快照(`/healthz` 与版本信息读它)',
  283. algo='scripts/guanlan_baseline_manifest.py(从 src/windscada/ui 源重建 zh 页 → 摘要 '
  284. '{css_tokens, nav, dom, sha256, source blobs})',
  285. gen='scripts/guanlan_baseline_manifest.py', input=None, pred=(),
  286. why='★ 2026-09-17 修正: 它一度被我按"交证件"错分成非产物; 实际**包内有生成端**'
  287. '(guanlan_baseline_manifest.py 就写这个路径), 且 guanlan_gateway.py 运行期读它 ⇒ 是产物'),
  288. dict(id='human_deliverables',
  289. glob=['windscada/mblub_alarm_cross.json', 'windscada/review_presented.json',
  290. 'windscada/给振动线_温度轴回复_20260826.json', 'windscada/给振动线_温度轴回复_20260826.md',
  291. 'windscada/送审_系统结论与判定_20260828.md'],
  292. kind='human',
  293. func='**人工正本/交证件**:与振动线的跨线通知、送审结论、发布评审快照',
  294. algo='(人写的, 不是算出来的)', gen=None, input=None, pred=(),
  295. why='这几件是"人对人的交证件/回执", 内容由分析结论抄写与人判断坐实而成; '
  296. 'mblub_alarm_cross.json 还被 src/ontology/populate.py 当作**证据来源**引用 ⇒ '
  297. '必须随包留在原位, 但**不参与呼应校验**(它本来就没有生成端, 也不该有)'),
  298. dict(id='scratch_in_products', glob=['**/_*.js', '**/_*audit*.md', '**/*.out', '**/*.err',
  299. '**/*_test_*.parquet', '**/*_test_*.json'],
  300. kind='not-product',
  301. func='**非产物**:自审脚本/记录与模型测试输出(躺在产物仓里)', algo='(工具脚本与运行痕迹, 不是产物)',
  302. gen=None, input=None, pred=(),
  303. why='2026-09-17: 17 件已移出到 reference/非产物留痕_20260917/ 并留了 _来源说明.json ⇒ '
  304. '本族现在应为空; 一旦再出现(新脚本往产物仓里写 .out/_audit.js 之类), 本器当场报出来'),
  305. ]
  306. def _files_of(glob) -> list[str]:
  307. """族 glob(str 或 list)→ 台账里的相对键(支持 `{a,b}` 花括号与 `*`)。
  308. ★ 深度必须**显式对齐**(2026-09-17 第一版踩过): `fnmatch` 的 `*` 是**跨 `/`** 的, 于是
  309. `windscada/*.parquet` 会把 `windscada/turbines/xx.parquet`、`windscada/_pre_rebuild_*/xx.parquet`
  310. 一起吞进来 —— 反向审计最怕"族把不该管的件认领了", 那样账就假了。
  311. 规则: 模式里没有 `**` 时, 要求的 `/` 个数必须与键的 `/` 个数**相等**(逐条展开后各自判)。
  312. """
  313. pats = []
  314. for g in ([glob] if isinstance(glob, str) else list(glob)):
  315. if '{' in g:
  316. head, tail = g.split('{', 1)
  317. opts, rest = tail.split('}', 1)
  318. pats += [head + o + rest for o in opts.split(',')]
  319. else:
  320. pats.append(g)
  321. out = []
  322. for rel in LEDGER:
  323. for pt in pats:
  324. if '**' not in pt and rel.count('/') != pt.count('/'):
  325. continue
  326. if fnmatch.fnmatch(rel, pt) or rel == pt:
  327. out.append(rel)
  328. break
  329. return sorted(out)
  330. LEDGER: dict[str, dict] = {}
  331. def load_ledger(farm: str) -> dict[str, dict]:
  332. """台账 = `_provenance.json`(逐件来源) + `_derived_manifest.json`(生成端自登记)。"""
  333. out: dict[str, dict] = {}
  334. root = P.out_root(farm)
  335. for fn in ('_provenance.json', '_derived_manifest.json', '_raw_scan.json'):
  336. f = root / fn
  337. if not f.is_file():
  338. continue
  339. try:
  340. d = json.loads(f.read_text(encoding='utf-8'))
  341. except Exception:
  342. continue
  343. for rel, v in (d.get('files') or {}).items():
  344. if isinstance(v, dict):
  345. out.setdefault(rel, dict(source=v.get('source') or 'raw-derived',
  346. builder=v.get('builder') or v.get('by') or '',
  347. why=v.get('why') or '',))
  348. return out
  349. def _input_home(station: pathlib.Path, sub: str) -> pathlib.Path | None:
  350. """输入类目录在哪 —— 优先场站目录下, 其次 raw 根下。
  351. ★ 机理层资料按 A2 约定**不在场站目录下**(`data/raw/西门子4.0技术资料/`, 见 src/windscada/config.py)。
  352. 只查场站目录会把本体层判成"输入不在位"(2026-09-17 第一版就这么误报过 3 件)。
  353. """
  354. for base in (station, station.parent):
  355. d = base / sub
  356. if d.is_dir():
  357. return base
  358. return None
  359. def _parquet_span(p: pathlib.Path, col: str | None):
  360. import pandas as pd
  361. try:
  362. d = pd.read_parquet(p)
  363. except Exception:
  364. return None, None, 0
  365. n = len(d)
  366. if col and col in d.columns:
  367. s = pd.to_datetime(d[col], errors='coerce')
  368. if s.notna().any():
  369. return str(s.min())[:10], str(s.max())[:10], n
  370. return None, None, n
  371. def _npz_ok(p: pathlib.Path) -> bool:
  372. """振动谱件: npz 能读出来且非空(列数不是"行", 不能拿 parquet 的行数判它)。"""
  373. try:
  374. import numpy as np
  375. with np.load(p, allow_pickle=False) as z:
  376. return any(z[k].size > 0 for k in z.files)
  377. except Exception:
  378. return False
  379. # 已知"含人工裁决/校准"的随包快照(按用户令 2026-09-17 #3 显式登记为人工件)。依据是文档里已经写明的性质:
  380. # docs §7「handoff_vibration_v2.json / component_history.json 是随包快照, 该件含人工裁决/校准更新,
  381. # 不是测量数据的函数」; baseline_38.json 的三层基线 self/absolute 两层由人工坐实; findings.json 是判级发现台账。
  382. HUMAN_SNAPSHOTS = {
  383. 'm5_cms_tcm/component_history.json',
  384. 'm5_cms_tcm/baseline_38.json',
  385. 'm5_cms_tcm/handoff_vibration_v1.json',
  386. 'm5_cms_tcm/findings.json',
  387. }
  388. # ── 逆向工程可行性 (用户令 2026-09-17 #2) ────────────────────────────────────────────
  389. # 问的是: "这批没有生成端的产物, 能不能从原始件/在包生成端**推**出来?"
  390. # 判定不靠印象, 靠两条机器证据:
  391. # ① 生成端在不在包内(在 → 只是没接上, 跑一次就有);
  392. # ② 产物正文里有没有**人工判断**的痕迹("裁决/审核/校准/评审/经验"这类字段)——
  393. # 含人工判断的件不是任何输入的纯函数, 逆向工程推不出来, 只能把那一步人工工作重做。
  394. import re as _re # noqa: E402
  395. JUDGE_PAT = _re.compile(r'人工|裁决|审核|复核|校准|评审|经验值|专家|judg|review|manual|calibrat|verdict|sign[_ ]?off',
  396. _re.I)
  397. # ★ 只认"**字段**叫这个名字"(`"裁决": …` / `裁决,`),不认正文里顺嘴提一句 ——
  398. # 2026-09-17 第一版拿整篇子串匹配, 结果把**页面**里的展示标签(`index.html` 里的"评审/人工")当成
  399. # 人工判断, 于是把"页面"整族误判成不可逆。这属于"判据太糙 → 结论假"。
  400. JUDGE_KEY_PAT = _re.compile(r'["\']?[^"\',:]{0,24}(人工|裁决|审核|复核|校准|评审|经验值|专家|'
  401. r'judg|review|manual|calibrat|verdict|sign[_ ]?off)[^"\',:]{0,24}["\']?\s*[:=]',
  402. _re.I)
  403. def judgement_evidence(farm: str, rels: list[str], cap: int = 8) -> tuple[int, list[str], int]:
  404. """→ (含人工判断字段的抽样比例%, 样例, 被检查件数)。
  405. 只查**数据/文本件**(.json/.csv/.md/.txt); **页面(.html/.js)不算** —— 页面是产物的渲染,
  406. 里面出现"评审/人工"是展示标签, 不代表这份件内含判断。
  407. """
  408. hit, samples, checked, pages = 0, [], 0, 0
  409. for rel in rels[:cap]:
  410. p = P.out_root(farm) / rel
  411. suf = p.suffix.lower()
  412. if suf in ('.html', '.js', '.css', '.htm'):
  413. pages += 1
  414. continue
  415. try:
  416. if suf == '.json':
  417. txt = p.read_text(encoding='utf-8', errors='replace')[:200000]
  418. pat = JUDGE_KEY_PAT
  419. elif suf in ('.csv', '.txt'):
  420. txt = p.read_text(encoding='utf-8', errors='replace')[:50000]
  421. pat = JUDGE_KEY_PAT
  422. elif suf == '.md':
  423. txt = p.read_text(encoding='utf-8', errors='replace')[:50000]
  424. pat = JUDGE_PAT
  425. else:
  426. continue
  427. except Exception:
  428. continue
  429. checked += 1
  430. if pat.search(txt):
  431. hit += 1
  432. samples.append(rel)
  433. return (100 * hit // checked if checked else 0), samples, pages
  434. def feasibility(fam: dict, rels: list[str], gen_ok: bool, in_ok: bool,
  435. judge_pct: int, judge_samples: list[str], pages: int = 0) -> tuple[str, str]:
  436. """→ (可逆性判定, 依据)。四类: 可逆(直接) / 可逆(需反推口径) / 不可逆(人工判断) / 应移出产物仓。"""
  437. if fam['kind'] == 'not-product':
  438. return '应移出产物仓', '它本就不是产物(工具脚本/交证件/测试输出) ⇒ 该从产物仓移走, 而不是"补生成端"'
  439. if gen_ok and in_ok:
  440. return '可逆(直接)', f"生成端在包内({fam['gen']})且输入在位 ⇒ 接上/重跑即可"
  441. if pages and pages >= max(3, len(rels[:8]) // 2):
  442. return '可逆(页面可再生)', ('这一族主要是**页面**(.html): 页面是产物的渲染, 不是独立数据 ⇒ '
  443. '接上在包的页面生成端重出即可(未必逐字节同, 能力与数据一致)')
  444. m_n = sum(1 for r in rels if r.endswith(('.parquet', '.csv', '.npz')))
  445. t_n = len(rels) - m_n
  446. split = f'({m_n} 件测量形态 / {t_n} 件文本·判断件)' if (m_n and t_n) else ''
  447. # 两类都占相当比重时, 结论必须是"混合"而不是挑一类代表全族 —— 否则一句判定就把另一半骗过去了
  448. if m_n and t_n and min(m_n, t_n) * 4 >= len(rels):
  449. return '混合(测量件可反推 / 文本件需人定)', split + \
  450. '测量形态的件可由 data/raw 反推口径 + 逐值对拍; 文本/判断件(评审、裁决、回复)推不出来'
  451. if judge_pct >= 50 and judge_samples:
  452. return '不可逆(人工判断)', (f"抽样 {len(judge_samples)} 件里都写着人工判断字段(如 {judge_samples[0]}) "
  453. f"⇒ 不是输入的纯函数, 逆向工程推不出来")
  454. if m_n and m_n * 2 >= len(rels):
  455. return '可逆(需反推口径)', split + '测量形态的件是测量数据的函数 ⇒ 可从 data/raw 反推口径 + 逐值对拍' \
  456. '(做法同 temp_monthly: 反推 → 逐值一致才敢用)'
  457. if gen_ok:
  458. return '半可逆(生成端在包, 输入不足)', '生成端在包内, 缺的是上游输入 ⇒ 上游补齐后即可重出'
  459. if judge_pct > 0:
  460. return '半可逆(需人工裁定)', f'抽样里 {judge_pct}% 的件含人工判断字段 ⇒ 机器部分可推、判断部分要人定'
  461. return '需人工裁定', '既无生成端、形态也不是测量函数 ⇒ 需研发给口径或领域正本'
  462. def _turbines_of(p: pathlib.Path, col: str = 'turbine', cap: int = 200000):
  463. import pandas as pd
  464. try:
  465. d = pd.read_parquet(p, columns=[col]) if col else pd.read_parquet(p)
  466. except Exception:
  467. return None
  468. try:
  469. return {str(x).upper() for x in d[col].dropna().unique()} if col in d.columns else None
  470. except Exception:
  471. return None
  472. def _input_turbines(station: pathlib.Path, sub: str):
  473. """输入侧机组集合: 逐台 CSV 文件名 / 目录名里的 WTG 号。"""
  474. d = station / sub
  475. if not d.is_dir():
  476. return None
  477. out = set()
  478. for p in d.rglob('*'):
  479. if p.is_file():
  480. for m in __import__('re').finditer(r'(WTG\s?\d{1,2})', p.name.upper()):
  481. out.add(m.group(1).replace(' ', ''))
  482. return out or None
  483. def classify_human(farm: str, rels: list[str], cap: int = 600) -> set[str]:
  484. """逐件判"是不是人工件"(用户令 2026-09-17 #3:人工件不再按自动产物参与呼应校验)。
  485. 判据:**非测量形态**的件(.md/.json/.csv/.txt)里出现人工判断字段(按字段名匹配)。
  486. 测量形态件(.parquet/.csv 数值、.npz)一律不算人工件 —— 它们是数据的函数,属"可反推"那一路。
  487. """
  488. human: set[str] = set()
  489. for rel in rels[:cap]:
  490. if rel in HUMAN_SNAPSHOTS: # ① 文档里已写明含人工裁决/校准的随包快照
  491. human.add(rel)
  492. continue
  493. suf = pathlib.Path(rel).suffix.lower()
  494. if suf == '.md': # ② 产物仓里的 .md 一律是报告/交证/评审记录(人写的)
  495. human.add(rel)
  496. continue
  497. if suf == '.txt':
  498. pat = JUDGE_PAT
  499. elif suf in ('.json', '.csv'):
  500. pat = JUDGE_KEY_PAT
  501. else:
  502. continue
  503. p = P.out_root(farm) / rel
  504. try:
  505. txt = p.read_text(encoding='utf-8', errors='replace')[:120000]
  506. except Exception:
  507. continue
  508. if pat.search(txt): # ③ 正文里有"人工判断字段"
  509. human.add(rel)
  510. return human
  511. def write_human_manifest(farm: str | None = None) -> int:
  512. """把人工件逐件落成 `outputs/<场>/_human_artifacts.json`(机器台账,供自检与审计引用)。"""
  513. farm = farm or P.farm()
  514. global LEDGER
  515. LEDGER = load_ledger(farm)
  516. entries: dict[str, dict] = {}
  517. for fam in FAMILIES:
  518. if fam['kind'] not in ('shipped', 'human', 'not-product'):
  519. continue
  520. rels = [r for r in _files_of(fam['glob']) if r not in entries]
  521. if not rels:
  522. continue
  523. if fam['kind'] == 'human':
  524. for r in rels:
  525. entries[r] = dict(kind='human', family=fam['id'], evidence='族内显式登记为人工正本/交证件')
  526. continue
  527. for r in classify_human(farm, rels):
  528. if r not in entries:
  529. entries[r] = dict(kind='human', family=fam['id'],
  530. evidence='件内含人工判断字段(按字段名匹配),不是输入的纯函数')
  531. out = P.out_root(farm) / '_human_artifacts.json'
  532. out.write_text(json.dumps(dict(
  533. at=__import__('time').strftime('%Y-%m-%d %H:%M:%S'),
  534. note='人工件台账(用户令 2026-09-17 #3):这些件由人写成/坐实,不是任何输入的纯函数 ⇒ '
  535. '不参与"输出↔输入呼应"校验;随包留在原位,重算不会也不该重写它们。'
  536. '本文件由 scripts/products_reverse_audit.py --write-human-manifest 生成。',
  537. count=len(entries), files=entries), ensure_ascii=False, indent=1), encoding='utf-8')
  538. by_fam: dict[str, int] = {}
  539. for v in entries.values():
  540. by_fam[v['family']] = by_fam.get(v['family'], 0) + 1
  541. print(f'人工件台账: {len(entries)} 件 → {P.rel(out)}')
  542. for k, v in sorted(by_fam.items(), key=lambda kv: -kv[1]):
  543. print(f' {k:24s} {v:4d} 件')
  544. return 0
  545. def audit(farm: str | None = None, verbose: bool = True):
  546. farm = farm or P.farm()
  547. global LEDGER
  548. LEDGER = load_ledger(farm)
  549. # ★ 场站原始件目录用唯一取用口 (场站名可与 farm 键不同: 键 = rudong, 目录 = data/raw/如东)
  550. from src.windscada.config import raw_station_dir
  551. station = pathlib.Path(raw_station_dir(farm))
  552. verdict: dict[str, dict] = {}
  553. fam_rows = []
  554. fails: list[str] = []
  555. for fam in FAMILIES:
  556. # ★ 族按**声明顺序**认领, 先声明的先拿 (否则 `m5_cms_tcm/*` 这种宽通配会把 windows/ 下
  557. # 1704 件也吞进来 —— fnmatch 的 `*` 是跨 `/` 的, 2026-09-17 第一版就这么误判过)
  558. rels = [r for r in _files_of(fam['glob']) if r not in verdict]
  559. rels = [r for r in rels if not r.lower().endswith(('.log', '.jsonl'))]
  560. if not rels:
  561. continue
  562. row = dict(id=fam['id'], n=len(rels), func=fam['func'], algo=fam['algo'], input=fam['input'],
  563. pred='+'.join(fam['pred']) or '—', verdict='', note='')
  564. if fam['kind'] == 'not-product':
  565. # ★ 不是产物, 却躺在产物仓里: 反向审计对它的结论是"它压根不该按产物管" ——
  566. # 既不需要生成端, 也谈不上与输入呼应(这一类最该被人看见, 故单独一类, 不当失败计)。
  567. jp, js, pg = judgement_evidence(farm, rels)
  568. fv, fw = feasibility(fam, rels, False, False, jp, js, pg)
  569. row['verdict'] = '✗ 非产物'
  570. row['note'] = fam.get('why', '')
  571. row['rev'], row['rev_why'] = fv, fw
  572. for r in rels:
  573. verdict[r] = dict(fam=fam['id'], verdict='✗',
  574. why='非产物(过程留痕/工具脚本躺在产物仓里): ' + fam.get('why', ''))
  575. elif fam['kind'] == 'human':
  576. # ★ 人工正本/交证件 (用户令 2026-09-17 #3): 由人写、被运行期当证据引用,
  577. # **不参与呼应校验**——它本来就没有、也不该有生成端; 单独计数, 不混进"无生成端"的失败堆里。
  578. row['verdict'] = '◆ 人工件'
  579. row['note'] = fam.get('why', '')
  580. row['rev'], row['rev_why'] = '人工件(正本/交证)', '人写的, 不参与呼应校验; 随包留在原位'
  581. for r in rels:
  582. verdict[r] = dict(fam=fam['id'], verdict='◆',
  583. why='人工件(人工正本/交证件): ' + fam.get('why', ''))
  584. elif fam['kind'] == 'shipped':
  585. jp, js, pg = judgement_evidence(farm, rels)
  586. gen_file = ROOT / fam['gen'] if fam.get('gen') else None
  587. gen_ok0 = bool(gen_file and gen_file.is_file())
  588. # ★ 逐件分人工件 (用户令 2026-09-17 #3): 含人工判断字段的件**不按自动产物参与呼应校验**,
  589. # 单独计 ◆; 余下才是真正的"无生成端"。
  590. human = classify_human(farm, rels)
  591. rest = [r for r in rels if r not in human]
  592. fv, fw = feasibility(fam, rest or rels, gen_ok0, False, jp, js, pg)
  593. row['verdict'] = '✗ 无生成端' if not human else f'✗ 无生成端 + ◆ 人工件 {len(human)}'
  594. row['n'] = len(rest)
  595. row['note'] = fam.get('why', '')
  596. row['rev'], row['rev_why'] = fv, fw
  597. if jp:
  598. row['rev_why'] += f';人工判断字段抽样命中 {jp}%' + (f'(如 {js[0]})' if js else '')
  599. for r in rest:
  600. verdict[r] = dict(fam=fam['id'], verdict='✗', why='无生成端(全库 0 处写入方): ' + fam['why'])
  601. for r in human:
  602. verdict[r] = dict(fam=fam['id'], verdict='◆',
  603. why='人工件(含人工判断字段): 不参与呼应校验, 随包留在原位')
  604. else:
  605. # ① 生成端在位
  606. gen = ROOT / fam['gen'] if fam.get('gen') else None
  607. gen_ok = bool(gen and gen.is_file())
  608. # ② 输入在位(场站目录优先, 机理层资料在 raw 根下 —— 见 _input_home)
  609. spec = INV.INPUTS.get(fam['input'] or '')
  610. i_s = i_e = None
  611. i_n = 0
  612. i_gran = '年'
  613. home = _input_home(station, fam['input']) if fam['input'] else None
  614. if home and spec:
  615. i_s, i_e, i_n, _note, i_gran = INV.input_span(home, fam['input'], spec)
  616. elif home:
  617. # 机理层资料这类"没有跨度判据"的输入: 按件数清点即算在位(INV.INPUTS 里没有它们的
  618. # 跨度口径 —— 技术资料是文档而不是时序数据, 拿跨度比毫无意义)
  619. i_n = sum(1 for p in (home / fam['input']).rglob('*') if p.is_file())
  620. i_gran = '年'
  621. elif fam['kind'] == 'source-derived':
  622. # ★ 输入是**包内源码**而不是 data/raw(如发布清单快照: 从 src/windscada/ui 重建页再摘要)。
  623. # 生成端在位 = 输入在位, 这类产物的"呼应"是对源码的, 不是对原始件的。
  624. i_n = 1
  625. i_s = i_e = '包内源码'
  626. in_ok = i_n > 0
  627. passed, notes = [], []
  628. if fam['pred'] and in_ok:
  629. if 'span' in fam['pred']:
  630. p_s, p_e, n = _parquet_span(P.out_root(farm) / rels[0], fam.get('time_col'))
  631. if p_s and i_s and (p_s[:7] < i_s[:7]):
  632. # ★ 年粒度输入(按文件名年份推的)不判失败: 与正向检查同一条教训 ——
  633. # 台账 xls 里可能含比文件名年份更早的历史记录, 拿年粒度当"输入起点"会造假缺口
  634. # (2026-09-17 实测: 工单产物起点 2020-01 而输入文件名最早 2021 ⇒ 不是数据串了)。
  635. msg = f'产物起点 {p_s} 早于输入起点 {i_s}'
  636. if i_gran in ('日', '月'):
  637. fails.append(f"{fam['id']}: {msg}(跨窗混入 / 键错)")
  638. notes.append('⚠ ' + msg)
  639. else:
  640. notes.append(f'{msg}(输入为年粒度, 只作参考: 台账可能含更早的历史行)')
  641. passed.append(f'跨度 {p_s}~{p_e} ⊆ 输入 {i_s}~{i_e}')
  642. if 'turbines' in fam['pred']:
  643. pt = _turbines_of(P.out_root(farm) / rels[0])
  644. it = _input_turbines(home, fam['input']) if home else None
  645. if pt and it:
  646. extra = pt - it
  647. if extra:
  648. fails.append(f"{fam['id']}: 产物含输入里没有的机组 {sorted(extra)[:5]}")
  649. passed.append(f'机组 {len(pt)} 台 ⊆ 输入 {len(it)} 台')
  650. if 'rows' in fam['pred']:
  651. tot = 0
  652. for r in rels[:400]:
  653. _s, _e, n = _parquet_span(P.out_root(farm) / r, None) if r.endswith('.parquet') \
  654. else (None, None, 1)
  655. tot += n
  656. if tot <= 0:
  657. fails.append(f"{fam['id']}: 产物行数合计为 0")
  658. passed.append(f'件内数据行合计 {tot:,}' + ('(抽样 400 件)' if len(rels) > 400 else ''))
  659. if 'npz' in fam['pred']:
  660. sample = rels[:5]
  661. bad = [r for r in sample if not _npz_ok(P.out_root(farm) / r)]
  662. if bad:
  663. fails.append(f"{fam['id']}: 抽样 {len(bad)}/{len(sample)} 件 npz 读不出或为空")
  664. passed.append(f'{len(rels)} 件谱(抽样 {len(sample)} 件 npz 均可读非空)· 输入源 {i_n} 件')
  665. if 'manifest' in fam['pred']:
  666. try:
  667. mf = json.loads((P.out_root(farm) / rels[0]).read_text(encoding='utf-8'))
  668. passed.append('清单自记: ' + ', '.join(f'{k}={v}' for k, v in list(mf.items())[:3]))
  669. except Exception as e:
  670. fails.append(f"{fam['id']}: 清单读不出来 ({type(e).__name__})")
  671. if not gen_ok:
  672. row['verdict'] = '✗ 生成端不在位'
  673. row['note'] = f"缺 {fam['gen']}"
  674. fails.append(f"{fam['id']}: 生成端不在位 {fam['gen']}")
  675. elif not in_ok:
  676. row['verdict'] = '~ 输入不在位'
  677. row['note'] = (f"缺 {(home / fam['input']) if home else station / str(fam['input'])}"
  678. ' ⇒ 现在无法验证(放数据后复跑本器)')
  679. else:
  680. row['verdict'] = '✓ 呼应成立'
  681. row['note'] = ';'.join(notes + passed)
  682. row['rev'], row['rev_why'] = '已在重算链上', '生成端在位、输入在位、判据通过 —— 无需逆向工程'
  683. for r in rels:
  684. verdict[r] = dict(fam=fam['id'], verdict=row['verdict'][0],
  685. why=row['note'] if row['verdict'][0] != '✓' else row['note'][:120])
  686. fam_rows.append(row)
  687. # 未归类件 (台账里有, 但没有任何族接住)
  688. unclassified = []
  689. for rel, v in LEDGER.items():
  690. if rel.lower().endswith(('.log', '.jsonl')):
  691. continue
  692. if rel in verdict:
  693. continue
  694. # 产物走通配没接住的, 也按台账来源判定
  695. unclassified.append(rel)
  696. verdict[rel] = dict(fam='(未归类)', verdict='?', why='既不在族表、也无法从台账判定来路')
  697. counts = {}
  698. for v in verdict.values():
  699. counts[v['verdict']] = counts.get(v['verdict'], 0) + 1
  700. if verbose:
  701. print(f'== 反向呼应审计 · 场站 {farm} · 台账 {len(LEDGER)} 件 · 判定 {len(verdict)} 件 ==')
  702. print(f' 输入根: {P.rel(station)}')
  703. print()
  704. print(f'{"族":26s} {"件数":>6s} {"判定":14s} {"输入类":12s} {"功能 / 算法 / 依据"}')
  705. for r in fam_rows:
  706. print(f' {r["id"]:24s} {r["n"]:6d} {r["verdict"]:14s} {str(r["input"] or "—"):12s} '
  707. f'{r["func"][:34]}')
  708. if r['note']:
  709. print(f' └─ {r["note"][:150]}')
  710. if unclassified:
  711. print(f'\n 【未归类 {len(unclassified)} 件】')
  712. for r in unclassified[:20]:
  713. print(f' ? {r}')
  714. print('\n 判定汇总: ' + ' · '.join(f'{k}={v}' for k, v in sorted(counts.items())))
  715. print(f' 判据失败 {len(fails)} 条' + (':' + ';'.join(fails[:3]) if fails else ''))
  716. ok = counts.get('✓', 0)
  717. print(f' 结论: 输出↔输入呼应**成立** {ok} 件 / **不成立(无生成端)** {counts.get("✗", 0)} 件 / '
  718. f'**人工件** {counts.get("◆", 0)} 件 / 无法验证 {counts.get("~", 0)} 件 / 未归类 {counts.get("?", 0)} 件')
  719. # ── 逆向工程可行性 (用户令 #2): 没有呼应关系的那些, 能不能推出来 ──
  720. import collections as _c
  721. by_rev = _c.Counter()
  722. for r in fam_rows:
  723. by_rev[r.get('rev', '?')] += r['n']
  724. print()
  725. print('== 反向「可逆性」矩阵(用户令 2026-09-17 #2: 无生成端的件能否从原件推出来)==')
  726. print(f'{"族":26s} {"件数":>6s} {"可逆性":22s} 依据')
  727. for r in fam_rows:
  728. if r['verdict'][0] == '✓':
  729. continue
  730. print(f' {r["id"]:24s} {r["n"]:6d} {r.get("rev", "?"):22s} {r.get("rev_why", "")[:96]}')
  731. print(' 按件数汇总: ' + ' · '.join(f'{k}={v}' for k, v in by_rev.most_common()))
  732. rc = 5 if (fails or unclassified) else 0
  733. return fam_rows, verdict, counts, fails, unclassified, rc
  734. def doc_block(farm: str) -> str:
  735. fam_rows, verdict, counts, fails, unclassified, _rc = audit(farm, verbose=False)
  736. L = [DOC_BEGIN, '### 13.6 反向呼应审计:自输出 → 功能与算法 → 输入(自动生成,勿手改)', '',
  737. f'台账 {len(verdict)} 件产物逐件回溯:**呼应成立 {counts.get("✓", 0)} 件** · '
  738. f'**不成立(无生成端){counts.get("✗", 0)} 件** · 无法验证 {counts.get("~", 0)} 件 · '
  739. f'未归类 {counts.get("?", 0)} 件。'
  740. '判据:① 生成端在位 ② 输入在位 ③ 跨度 ⊆ 输入 / 机组集 ⊆ 输入 / 行数 > 0 / 计数与清单一致。', '',
  741. '| 输出族(产物 glob) | 件数 | 反向判定 | 功能 | 算法 / 生成端 | 输入(data/raw/<场>/) | 判据 | 说明 |',
  742. '|---|---:|---|---|---|---|---|---|']
  743. for r in fam_rows:
  744. fam = next(f for f in FAMILIES if f['id'] == r['id'])
  745. L.append(f'| `{fam["glob"]}` | {r["n"]} | {r["verdict"]} | {r["func"]} | {r["algo"]} | '
  746. f'{r["input"] or "—(无生成端)"} | {r["pred"]} | {r["note"][:160]} |')
  747. if unclassified:
  748. L += ['', f'**未归类 {len(unclassified)} 件**(需人工认领):' + '、'.join(f'`{x}`' for x in unclassified[:12])]
  749. L += ['', '#### 反向「可逆性」:没有呼应关系的那批,能否从原始件推出来(用户令 2026-09-17 #2)', '',
  750. '判据两条机器证据:① 生成端在不在包内 ② 产物正文里有没有**人工判断**字段'
  751. '(`人工/裁决/审核/校准/评审/经验/judge/review/calibrat/verdict`,抽样读件统计命中率)。'
  752. '含人工判断的件不是任何输入的纯函数 ⇒ 逆向工程推不出来,只能把那一步人工工作重做。', '',
  753. '| 输出族 | 件数 | 可逆性 | 依据 |', '|---|---:|---|---|']
  754. for r in fam_rows:
  755. if r['verdict'][0] == '✓':
  756. continue
  757. L.append(f'| `{r["id"]}` | {r["n"]} | {r.get("rev", "?")} | {r.get("rev_why", "")} |')
  758. import collections as _c
  759. by_rev = _c.Counter()
  760. for r in fam_rows:
  761. by_rev[r.get('rev', '?')] += r['n']
  762. L += ['', '**按件数汇总**:' + ' · '.join(f'{k} = {v} 件' for k, v in by_rev.most_common()), '',
  763. '**人工件**:含人工判断字段的件已逐件登记在 outputs/&lt;场&gt;/_human_artifacts.json(用户令 2026-09-17 #3),'
  764. '它们**不参与**呼应校验(人写成/坐实的东西不是任何输入的纯函数);生成方式:'
  765. 'python scripts/products_reverse_audit.py --write-human-manifest。', '',
  766. '> 结论口径:`可逆(直接)` = 包内已有生成端,接上即可;`可逆(需反推口径)` = 内容是测量数据的函数,'
  767. '照 `temp_monthly` 的办法反推 + 逐值对拍;`不可逆(人工判断)` = 逆向工程推不出来,'
  768. '要么由研发补生成端、要么承认它是人工件(不该按产物管)。', DOC_END]
  769. return '\n'.join(L)
  770. def write_doc(farm: str) -> int:
  771. doc = ROOT / 'docs' / '系统设计说明.md'
  772. txt = doc.read_text(encoding='utf-8')
  773. blk = doc_block(farm)
  774. i, j = txt.find(DOC_BEGIN), txt.find(DOC_END)
  775. if i >= 0 and j > i:
  776. txt = txt[:i] + blk + txt[j + len(DOC_END):]
  777. else: # 首次: 追加到文末
  778. txt = txt.rstrip('\n') + '\n\n' + blk + '\n'
  779. doc.write_text(txt, encoding='utf-8', newline='\n')
  780. print(f'已写入 {P.rel(doc)} (§13.6 反向呼应审计块)')
  781. return 0
  782. def main() -> int:
  783. ap = argparse.ArgumentParser(description='反向呼应审计: 输出 → 功能与算法 → 输入')
  784. ap.add_argument('--farm', default=None)
  785. ap.add_argument('--check', action='store_true', help='只出结论 (有未归类/判据失败 → rc=5)')
  786. ap.add_argument('--write-doc', action='store_true', help='把族表写进 docs/系统设计说明.md §13.6')
  787. ap.add_argument('--write-human-manifest', action='store_true',
  788. help='生成人工件台账 outputs/<场>/_human_artifacts.json (用户令 2026-09-17 #3)')
  789. a = ap.parse_args()
  790. if a.write_human_manifest:
  791. return write_human_manifest(a.farm)
  792. if a.write_doc:
  793. return write_doc(a.farm or P.farm())
  794. _rows, _v, counts, fails, uncl, rc = audit(a.farm, verbose=True)
  795. if a.check:
  796. print(f'[{"OK" if rc == 0 else "X"}] 反向呼应审计 rc={rc}'
  797. + (f'(未归类 {len(uncl)} 件 / 判据失败 {len(fails)} 条)' if rc else '(未归类 0 件、判据无失败)'))
  798. return rc
  799. if __name__ == '__main__':
  800. for _s in (sys.stdout, sys.stderr):
  801. try:
  802. _s.reconfigure(errors='replace')
  803. except Exception:
  804. pass
  805. sys.exit(main())