windscada_monthly_build.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. """"标准答案"目录: 随包件在哪。
  35. 优先 `outputs/<场>/windscada/_pre_rebuild_20260911/`(rebuild_from_raw --verify 用的那份);
  36. 没有就回落到 `_products_off/**/windscada/`(products_state --off 挪走后的暂存区, 内容就是随包件)。
  37. 两处都没有 → None(只报"没法比", 不当成错)。
  38. """
  39. inplace = P.store() / '_pre_rebuild_20260911'
  40. if inplace.is_dir():
  41. return inplace
  42. for p in sorted((ROOT / '_products_off').rglob('windscada')):
  43. if p.is_dir():
  44. return p
  45. return None
  46. BASELINE = baseline_dir()
  47. def temp_channels(cfg) -> list:
  48. """契约里 B.温度NBM 组的活通道 (以 _mean 结尾) —— temp_monthly/watch_channels 的列集。"""
  49. return [c for c in contracted_cols(cfg, groups=['B.温度NBM']) if c.endswith('_mean')]
  50. def month_of(s: pd.Series) -> pd.Series:
  51. return s.dt.to_period('M').astype(str)
  52. def build_temp_monthly(cfg, turbines=None, progress=True):
  53. """→ (长表 DataFrame[turbine, channel, month, med], 明细 dict)
  54. 规则: 每台 × 每月 × 每个温度通道, 在 p ≥ 500kW 行上的中位数。
  55. """
  56. chans = temp_channels(cfg)
  57. rows, info = [], {}
  58. for t in (turbines or cfg['turbines']):
  59. d = load_10min(t, cfg, groups=GROUPS)
  60. d['month'] = month_of(d['ts'])
  61. n_all = len(d)
  62. d = d[d['grd_wtc_ActPower_mean'] >= POWER_GATE]
  63. if not len(d):
  64. info[t] = dict(rows_all=n_all, rows_gate=0, months=0)
  65. continue
  66. med = d.groupby('month')[chans].median()
  67. long = med.stack().rename('med').reset_index()
  68. long.columns = ['month', 'channel', 'med']
  69. long.insert(0, 'turbine', t)
  70. rows.append(long)
  71. info[t] = dict(rows_all=n_all, rows_gate=len(d), months=len(med))
  72. if progress:
  73. print(f' {t}: 全 {n_all} 行 → 发电态 {len(d)} 行, {len(med)} 个月', flush=True)
  74. return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame(columns=['turbine', 'channel', 'month', 'med'])), info
  75. PRODUCTS = {
  76. 'temp_monthly.parquet': build_temp_monthly,
  77. }
  78. def verify(cfg) -> int:
  79. """逐件与随包件比对: 行数、键集合、逐值相等比例。"""
  80. ok_all = True
  81. for name in PRODUCTS:
  82. mine_p, base_p = P.store() / name, BASELINE / name
  83. if not mine_p.exists():
  84. print(f' [ -- ] {name:34s} 本仓还没算 (跳过)')
  85. continue
  86. if not base_p.exists():
  87. print(f' [ ?? ] {name:34s} 没有随包基线可比 (基线目录 {P.rel(BASELINE)})')
  88. continue
  89. a, b = pd.read_parquet(base_p), pd.read_parquet(mine_p)
  90. keys = [c for c in a.columns if c != 'med']
  91. m = a.merge(b, on=keys, how='outer', suffixes=('_base', '_mine'), indicator=True)
  92. val = [c for c in a.columns if c not in keys][0]
  93. both = m[m._merge == 'both']
  94. n = len(both)
  95. eq = int((both[f'{val}_base'].sub(both[f'{val}_mine']).abs() < 1e-9).sum())
  96. only_b = int((m._merge == 'left_only').sum())
  97. only_m = int((m._merge == 'right_only').sum())
  98. good = (n > 0 and eq == n and only_b == 0 and only_m == 0)
  99. ok_all &= good
  100. mark = '✅' if good else '❌'
  101. print(f' [{mark}] {name:34s} 基线 {len(a)} 行 / 本仓 {len(b)} 行; 逐值相等 {eq}/{n};'
  102. f' 仅基线 {only_b}; 仅本仓 {only_m}')
  103. if not good and n:
  104. d = both.assign(_d=(both[f'{val}_base'] - both[f'{val}_mine']).abs())
  105. print(' 差异最大的 3 格:')
  106. print(d.nlargest(3, '_d')[keys + [f'{val}_base', f'{val}_mine']].to_string(index=False))
  107. print('\n结论:', '全部逐值一致' if ok_all else '有差异 —— 规则还需修正, 别急着写盘')
  108. return 0 if ok_all else 4
  109. def main() -> int:
  110. ap = argparse.ArgumentParser()
  111. ap.add_argument('--verify', action='store_true', help='只与随包基线比对, 不写盘')
  112. ap.add_argument('--turbines', default=None, help='只算这几台 (逗号分隔)')
  113. a = ap.parse_args()
  114. cfg = farm()
  115. ts = a.turbines.split(',') if a.turbines else None
  116. print(f'场站 {cfg["name"] if "name" in cfg else cfg["raw_station"]} · 温度通道 {len(temp_channels(cfg))} 个 · 发电态功率门 {POWER_GATE:.0f} kW\n')
  117. if not a.verify:
  118. for name, fn in PRODUCTS.items():
  119. print(f'== 算 {name}')
  120. df, info = fn(cfg, turbines=ts)
  121. out = P.store() / name
  122. out.parent.mkdir(parents=True, exist_ok=True)
  123. df.to_parquet(out, index=False)
  124. print(f' → {P.rel(out)} {df.shape[0]} 行 × {df.shape[1]} 列\n')
  125. print('== 与随包基线逐值比对 ==')
  126. return verify(cfg)
  127. if __name__ == '__main__':
  128. # 控制台可能是 GBK(中文 Windows 936): print 里的 ✅ ❌ 编不出来会抛 UnicodeEncodeError,
  129. # 明明算完了却以退出码 1 结束。降级为 '?' 而不是崩(同类坑见 src/console.py)。
  130. import sys as _sys
  131. for _s in (_sys.stdout, _sys.stderr):
  132. try: _s.reconfigure(errors='replace')
  133. except Exception: pass
  134. sys.exit(main())