windscada_monthly_build.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """月度派生件构建器 —— 补上 v0.2.0 里"有消费者、却没生成端"的那批产物 (2026-09-12)。
  4. ## 为什么有这个脚本
  5. 从零重算 (`rebuild_from_raw.py`) 只覆盖 16 件; 随包里另有 15 件 parquet **没有任何生成端**
  6. (全库搜遍: 只有读取方、0 处写入方), 于是工作台主数据 `/api/fleet` 一缺 `temp_monthly.parquet`
  7. 就整个回 `err=no_products` —— 页面看着像"没数据", 其实是"缺产物"。
  8. 本脚本把这批件**从 data/raw 重新算出来**, 并且**逐值对齐随包件**: 随包件在这里当"标准答案"
  9. (存在 `_products_off/.../windscada/`), `--verify` 会报每件的命中率; 规则是从"标准答案"反推并
  10. 用全量比对确认的, 不是猜的。
  11. ## 已确认的口径 (2026-09-12, 用随包件反推 + 逐值验证)
  12. temp_monthly 每台 × 每月 × 每个温度通道, 在 **发电态功率门 p ≥ 500kW** 行上的**中位数**
  13. 形状 38×19×27 = 19494 行; 实测 WTG01 的 513 格 **逐值 100% 相同**
  14. (对照: 全行中位数只有 5.8% 命中 —— 因为停机时绕组是冷的, 会把中位拉低)
  15. 口径出处: `src/windscada/subsys/temp_nbm.py` 的"发电态×功率档(500kW)", PBINS 步长 500
  16. ## 用法
  17. python scripts/windscada_monthly_build.py --verify # 只比对(不写盘), 报每件命中率
  18. python scripts/windscada_monthly_build.py # 算并写盘
  19. python scripts/windscada_monthly_build.py --turbines WTG01,WTG02 # 只算几台(调试用)
  20. """
  21. from __future__ import annotations
  22. import argparse
  23. import pathlib
  24. import sys
  25. ROOT = pathlib.Path(__file__).resolve().parents[1]
  26. sys.path.insert(0, str(ROOT))
  27. import pandas as pd # noqa: E402
  28. from src import paths as P # noqa: E402
  29. from src.windscada.config import farm # noqa: E402
  30. from src.windscada.data import load_10min, contracted_cols # noqa: E402
  31. POWER_GATE = 500.0 # 发电态功率门 (kW); 出处见 temp_nbm 的"发电态×功率档(500kW)"
  32. GROUPS = ['A.功率', 'B.温度NBM']
  33. def baseline_dir():
  34. """"标准答案"目录: 随包件在哪 (整目录视角; 单件比对用 baseline_for)。"""
  35. inplace = P.store() / '_pre_rebuild_20260911'
  36. if inplace.is_dir():
  37. return inplace
  38. for p in sorted((ROOT / '_products_off').rglob('windscada')):
  39. if p.is_dir():
  40. return p
  41. return None
  42. def baseline_for(name: str):
  43. """这一件产物的"标准答案"在哪。
  44. 注意两个暂存处**内容不同**, 必须逐件找:
  45. · `outputs/<场>/windscada/_pre_rebuild_20260911/` = **台账验收基线**(3 件: alarms/workorders/oil_samples);
  46. · `_products_off*/**/windscada/` = 随包整份产物(31 件 parquet, 含月度派生件)。
  47. 原先只认第一个目录, 于是 temp_monthly 会被报成"没有随包基线可比", 而结论却打印"全部逐值一致"
  48. —— 2026-09-12 实测逮到(假结论比没结论更糟)。
  49. """
  50. cands = []
  51. bd = baseline_dir()
  52. if bd:
  53. cands.append(bd / name)
  54. for p in sorted((ROOT).glob('_products_off*/**/windscada')):
  55. cands.append(p / name)
  56. for c in cands:
  57. if c.is_file():
  58. return c
  59. return None
  60. BASELINE = baseline_dir()
  61. def temp_channels(cfg) -> list:
  62. """契约里 B.温度NBM 组的活通道 (以 _mean 结尾) —— temp_monthly/watch_channels 的列集。"""
  63. return [c for c in contracted_cols(cfg, groups=['B.温度NBM']) if c.endswith('_mean')]
  64. def month_of(s: pd.Series) -> pd.Series:
  65. return s.dt.to_period('M').astype(str)
  66. def build_temp_monthly(cfg, turbines=None, progress=True):
  67. """→ (长表 DataFrame[turbine, channel, month, med], 明细 dict)
  68. 规则: 每台 × 每月 × 每个温度通道, 在 p ≥ 500kW 行上的中位数。
  69. """
  70. chans = temp_channels(cfg)
  71. rows, info = [], {}
  72. for t in (turbines or cfg['turbines']):
  73. d = load_10min(t, cfg, groups=GROUPS)
  74. d['month'] = month_of(d['ts'])
  75. n_all = len(d)
  76. d = d[d['grd_wtc_ActPower_mean'] >= POWER_GATE]
  77. if not len(d):
  78. info[t] = dict(rows_all=n_all, rows_gate=0, months=0)
  79. continue
  80. med = d.groupby('month')[chans].median()
  81. long = med.stack().rename('med').reset_index()
  82. long.columns = ['month', 'channel', 'med']
  83. long.insert(0, 'turbine', t)
  84. rows.append(long)
  85. info[t] = dict(rows_all=n_all, rows_gate=len(d), months=len(med))
  86. if progress:
  87. print(f' {t}: 全 {n_all} 行 → 发电态 {len(d)} 行, {len(med)} 个月', flush=True)
  88. return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame(columns=['turbine', 'channel', 'month', 'med'])), info
  89. PRODUCTS = {
  90. 'temp_monthly.parquet': build_temp_monthly,
  91. }
  92. def verify(cfg) -> int:
  93. """逐件与随包件比对: 行数、键集合、逐值相等比例。
  94. 三种结果分开报, 不许混:
  95. ✅ 逐值一致 ❌ 有差异(规则需修正) ?? 找不到标准答案(**不能**当成一致)
  96. """
  97. ok_all, compared, no_base = True, 0, []
  98. for name in PRODUCTS:
  99. mine_p = P.store() / name
  100. if not mine_p.exists():
  101. print(f' [ -- ] {name:34s} 本仓还没算 (跳过)')
  102. continue
  103. base_p = baseline_for(name)
  104. if base_p is None:
  105. no_base.append(name)
  106. print(f' [ ?? ] {name:34s} 找不到随包件可对比 (台账基线只有 3 件; 随包整份产物在 _products_off*/ 下)')
  107. continue
  108. compared += 1
  109. a, b = pd.read_parquet(base_p), pd.read_parquet(mine_p)
  110. keys = [c for c in a.columns if c != 'med']
  111. m = a.merge(b, on=keys, how='outer', suffixes=('_base', '_mine'), indicator=True)
  112. val = [c for c in a.columns if c not in keys][0]
  113. both = m[m._merge == 'both']
  114. n = len(both)
  115. eq = int((both[f'{val}_base'].sub(both[f'{val}_mine']).abs() < 1e-9).sum())
  116. only_b = int((m._merge == 'left_only').sum())
  117. only_m = int((m._merge == 'right_only').sum())
  118. good = (n > 0 and eq == n and only_b == 0 and only_m == 0)
  119. ok_all &= good
  120. mark = '✅' if good else '❌'
  121. print(f' [{mark}] {name:34s} 基线 {len(a)} 行 / 本仓 {len(b)} 行; 逐值相等 {eq}/{n};'
  122. f' 仅基线 {only_b}; 仅本仓 {only_m} [标准答案: {P.rel(base_p)}]')
  123. if not good and n:
  124. d = both.assign(_d=(both[f'{val}_base'] - both[f'{val}_mine']).abs())
  125. print(' 差异最大的 3 格:')
  126. print(d.nlargest(3, '_d')[keys + [f'{val}_base', f'{val}_mine']].to_string(index=False))
  127. if not compared:
  128. print(f'\n结论: **无法比对**(没有一件找到随包件) —— 这不是"通过"。缺标准答案: {no_base}')
  129. return 5
  130. if no_base:
  131. print(f'\n注意: 另有 {len(no_base)} 件找不到标准答案, 未比对: {no_base}')
  132. print('\n结论:', '已比对的部分全部逐值一致' if ok_all else '有差异 —— 规则还需修正, 别急着写盘')
  133. return 0 if ok_all else 4
  134. def main() -> int:
  135. ap = argparse.ArgumentParser()
  136. ap.add_argument('--verify', action='store_true', help='只与随包基线比对, 不写盘')
  137. ap.add_argument('--turbines', default=None, help='只算这几台 (逗号分隔)')
  138. a = ap.parse_args()
  139. cfg = farm()
  140. ts = a.turbines.split(',') if a.turbines else None
  141. print(f'场站 {cfg["name"] if "name" in cfg else cfg["raw_station"]} · 温度通道 {len(temp_channels(cfg))} 个 · 发电态功率门 {POWER_GATE:.0f} kW\n')
  142. if not a.verify:
  143. for name, fn in PRODUCTS.items():
  144. print(f'== 算 {name}')
  145. df, info = fn(cfg, turbines=ts)
  146. out = P.store() / name
  147. out.parent.mkdir(parents=True, exist_ok=True)
  148. df.to_parquet(out, index=False)
  149. print(f' → {P.rel(out)} {df.shape[0]} 行 × {df.shape[1]} 列\n')
  150. print('== 与随包基线逐值比对 ==')
  151. return verify(cfg)
  152. if __name__ == '__main__':
  153. # 控制台可能是 GBK(中文 Windows 936): print 里的 ✅ ❌ 编不出来会抛 UnicodeEncodeError,
  154. # 明明算完了却以退出码 1 结束。降级为 '?' 而不是崩(同类坑见 src/console.py)。
  155. import sys as _sys
  156. for _s in (_sys.stdout, _sys.stderr):
  157. try: _s.reconfigure(errors='replace')
  158. except Exception: pass
  159. sys.exit(main())