fatigue_validation.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # -*- coding: utf-8 -*-
  2. """fatigue_validation.py — 疲劳暴露校核: per机组 **相对 TI(湍流)疲劳暴露排序** (非绝对寿命).
  3. 裁决对象 = fleet 内 **谁暴露在更强湍流 → 谁疲劳载荷循环剂量更高** 的相对排序 —
  4. 上游 (power-curve / 选址复盘) 想知道"哪几台位置的湍流暴露显著高于同场其余台"。
  5. 区别: 这**不是绝对疲劳寿命** (无气弹标定 / 无 S-N 材料曲线) → 只给**排序**不给寿命。
  6. 来源: fushan E映射 (outputs/fushan/sop/mapping_E_del.json, gitignored 真盘) 实证:
  7. fore-aft 塔振 DEL (雨流, 相对) 的 **within-turbine** 回归 R2 load-only 0.286 → +TI 0.40
  8. (dR2_TI 0.114, TI 系数 0.344, ws 系数 0.632); inter-turbine 台间 TI暴露 vs DEL
  9. spearman 0.42 (p=0.064, n=18)。→ 湍流强度 TI 在载荷(风速/推力/转速/功率)之外对
  10. fore-aft 疲劳有 **正边际**, 且台间 TI 暴露差与 DEL 剂量差同向。
  11. ★物理 trace (第一性, no black box):
  12. 湍流强度 TI = σ(ws)/mean(ws) = 阵风波动幅度。塔架/叶根 fore-aft 疲劳 ∝ 载荷循环
  13. 的幅值×次数 (Palmgren-Miner 线性累积 + S-N 曲线)。高 TI → 单位时间内推力波动的
  14. 幅值与过零次数↑ → 雨流计数出的等效循环 DEL↑。故 "TI↑ → 相对疲劳暴露↑" 是**推力
  15. 脉动驱动的载荷循环**这一物理量, 非统计巧合。within-turbine 弹性 (消逐台加速度计
  16. 增益污染: 同台自比) 定标该驱动强度; inter-turbine 排序定位高暴露台。
  17. ★算法 (两层, 皆相对无黑箱):
  18. 1. **暴露排序 (per台, inter-turbine)**: per台 gen 态有效窗 TI 均值 = ti_exposure;
  19. fleet 稳健 z = (ti_i − median)/(1.4826·MAD) (MAD=0 退化 std); **单侧** flag 高暴露
  20. (z ≥ z_gate) — 疲劳风险方向 = 高 TI。rank 按 ti_exposure 降序 (1=最高)。
  21. 2. **弹性物理校验 (fleet, within-turbine, 可选)**: 有 DEL 代理列时, 逐台 z-within 变换
  22. log(DEL) ~ [z-within 载荷控制] (+z-within TI) 池化 OLS → R2_load_within / R2_plusTI /
  23. dR2_TI / TI 系数。**消增益污染** (同台自比, 镜像 mapping_E within_turbine 口径)。
  24. 正 dR2 + 正 TI 系数 = TI→载荷弹性成立 → 排序物理前提坐实; 非正 → 响亮 caveat。
  25. ★诚实界 (task 明列 5 条 + 3原则审, 未调参掩盖):
  26. (a) **相对非绝对疲劳**: 无气弹标定 / 无 S-N 材料曲线 → 给 fleet 内**排序**, 不给寿命/
  27. DEL 绝对值/剩余年限。DEL 是相对雨流量 (逐台加速度计增益未标定)。
  28. (b) **TI 是暴露代理非直接损伤**: TI 高 ≠ 该台一定先坏 (材料/结构裕度/S-N 未入模);
  29. TI 是"输入端载荷环境"代理, 损伤还需材料侧信息才能定寿命。
  30. (c) **单场单月**: fushan Oct2023 1s 单场单月验证; **跨场泛化未测** (n=1 场, 非 systemic);
  31. 迁到别场须重验 TI→DEL 弹性符号与量级 (§0.3 [暂行], SOP n<3 未定谳)。
  32. (d) **需 TI 通道 (ws_std/ws_mean 或直接 ti) 或塔振 DEL**: 两者皆缺 → 排序无输入 →
  33. **INSUFFICIENT 弃权** (非静默全零"干净")。仅 DEL 无 TI → 排序不可出 (排序轴是 TI)。
  34. (e) **fleet-relative → 批次盲**: 全场一致高 TI 暴露 (选址整体差) → 稳健 z 皆≈0 → **无一
  35. flag** = 本臂天然盲 (承 memory relative-criterion-batch-blindness + sensor 批次盲教训)。
  36. 批次嫌疑场须先做场型识别 / 引入绝对 TI 基准 (IEC 类别 / 邻场), 不能只靠场内相对。
  37. (f) **DEL 代理异质 (RV-1 逮, 第五角数据面复发)**: DEL 通道跨台常两 population — fushan del_fa
  38. 13 台 cv≈0.4 (物理) + 5 台 cv≈4 (A04-07/A11, mean 58-148 = 非物理坏通道)。原 pooled 弹性
  39. (dR2 0.114/TI系数 0.344) 是干净子集 (~0.21/0.46) 与死通道噪声的**稀释均值** → per台 DEL
  40. cv>del_cv_max(1.5) 已剔 (elasticity.del_excluded), 但**迁场必核 DEL 通道质量** (同 sensor 派生相/
  41. GC9 换制/pitch 高集距: 通道质量闸=生产必备)。premise_holds in-sample dR2 恒>0 → **约等 sign(TI系数)**,
  42. 非强前提检验 (加 0.01 dR2 下界防 near-vacuous, 仍诚实标非 gold-standard)。
  43. ★可证伪判据 (falsifiable): 若高 TI 暴露台的 within-turbine DEL~TI 弹性 **≤ 0** (TI 不驱动
  44. DEL, 或反向) → "TI 暴露 = 疲劳剂量代理" 的物理前提在该场**假** → 排序不可作疲劳解读
  45. (退化为单纯湍流环境描述)。elasticity 块 ti_coef/dR2 符号即此判据的机器检查点。
  46. ★3 First Principles 自审:
  47. 1. 物理: TI→推力脉动→载荷循环 DEL (Palmgren-Miner + S-N), 见上 trace ✓ (物理量非拟合噱头)。
  48. 2. 统计: n 逐台声明 (min_windows) + fleet n (min_turb); 聚合层显式 (inter=排序/intra=弹性);
  49. falsifiable 判据显式; confounder = 载荷 (ws/rotor/power) 入 within 控制项排掉;
  50. 单场单月 → **不作跨场 systemic claim** (诚实界 c)。
  51. 3. 第一性: OLS + 稳健 z (median/MAD), 无黑箱; 不诉诸 memory label (fushan 数字须 data-first 复现)。
  52. DP 验收 = tests/sop/test_fatigue_ti_dp.py (合成 deterministic + fushan 真盘 skipif sanity)。
  53. 纯核心无 I/O 可测; per-farm 加载在调用方 (skill/report 层)。
  54. """
  55. from __future__ import annotations
  56. import numpy as np
  57. import pandas as pd
  58. Z_GATE = 2.0 # 单侧高暴露 flag 门 (fleet 稳健 z)
  59. MIN_WINDOWS = 200 # per台最少有效窗 (暴露均值稳)
  60. MIN_TURB = 5 # fleet-相对 z 最少台数
  61. MIN_POOL_ROWS = 1000 # within-turbine 弹性池化 OLS 最少行数
  62. TI_LO = 0.01 # TI 有效下界 (去 0/负野值)
  63. TI_HI = 0.6 # TI 有效上界 (去传感器野值)
  64. def _robust_z(vals: np.ndarray) -> np.ndarray:
  65. """稳健 z = (x − median)/(1.4826·MAD); MAD=0 退化 std(ddof=1); 全常量 → 全 0。"""
  66. med = float(np.median(vals))
  67. mad = float(np.median(np.abs(vals - med))) * 1.4826
  68. sd = mad if mad > 0 else float(np.std(vals, ddof=1)) if len(vals) > 1 else 0.0
  69. if not sd or sd <= 0:
  70. return np.zeros_like(vals, dtype=float)
  71. return (vals - med) / sd
  72. def _zwithin(df: pd.DataFrame, col: str, turbine_col: str) -> np.ndarray:
  73. """逐台 z-within 变换 (x − 台均)/台std → 消逐台增益/偏置污染 (同台自比)。
  74. 单元素/常量台 std=NaN/0 → 结果 NaN → fillna(0) (无 within 方差, 不贡献斜率)。"""
  75. g = df.groupby(turbine_col)[col]
  76. z = (df[col] - g.transform("mean")) / g.transform("std")
  77. return z.replace([np.inf, -np.inf], np.nan).fillna(0.0).to_numpy(float)
  78. def _r2(y: np.ndarray, yh: np.ndarray) -> float:
  79. ss_res = float(np.sum((y - yh) ** 2))
  80. ss_tot = float(np.sum((y - y.mean()) ** 2))
  81. return 1.0 - ss_res / ss_tot if ss_tot > 0 else float("nan")
  82. def _within_elasticity(sub: pd.DataFrame, *, del_col: str, ti_col: str,
  83. load_cols: list, turbine_col: str, min_pool_rows: int,
  84. del_log: bool, del_cv_max: float = 1.5) -> dict | None:
  85. """within-turbine 池化 OLS: z-within(logDEL) ~ z-within(载荷) (+z-within TI)。
  86. 镜像 mapping_E_fushan_analyze within_turbine 口径 (zwin + ΔR2_TI)。None = 行数不足。
  87. ★DEL 通道活性闸 (RV-1 逮, 第五角数据面复发): DEL 代理跨台常两 population —
  88. fushan del_fa 13台 cv≈0.4(物理) + 5台 cv≈4(A04-07/A11, mean 58-148=非物理坏通道) →
  89. pool 会稀释 (0.114 是干净13台强信号与死5台噪声的均值)。**per台 DEL cv>del_cv_max 剔除再池化**
  90. (承 sensor 派生相 / GC9 换制 / pitch 高集距: 通道质量闸=生产必备, 别静默 pool 垃圾), 报 del_excluded。"""
  91. need = [turbine_col, del_col, ti_col] + load_cols
  92. d = sub[need].replace([np.inf, -np.inf], np.nan).dropna()
  93. d = d[d[del_col] > 0] # DEL>0 (log 前提)
  94. # per台 DEL cv 活性闸: 剔非物理坏通道 (cv=std/|mean| ≫ 物理), pool 前
  95. cv = d.groupby(turbine_col)[del_col].agg(lambda x: float(x.std() / abs(x.mean())) if x.mean() else np.inf)
  96. kept = cv[cv <= del_cv_max].index.tolist()
  97. excluded = sorted(str(t) for t in cv[cv > del_cv_max].index)
  98. d = d[d[turbine_col].astype(str).isin([str(t) for t in kept])]
  99. if len(d) < min_pool_rows:
  100. return None
  101. y_raw = np.log(d[del_col].to_numpy(float)) if del_log else d[del_col].to_numpy(float)
  102. dd = d.assign(_y=y_raw)
  103. yw = _zwithin(dd, "_y", turbine_col)
  104. ones = np.ones(len(dd))
  105. load_z = [_zwithin(dd, c, turbine_col) for c in load_cols]
  106. ti_z = _zwithin(dd, ti_col, turbine_col)
  107. X_load = np.column_stack([ones] + load_z) if load_z else ones.reshape(-1, 1)
  108. X_ti = np.column_stack([X_load, ti_z])
  109. b_load, *_ = np.linalg.lstsq(X_load, yw, rcond=None)
  110. b_ti, *_ = np.linalg.lstsq(X_ti, yw, rcond=None)
  111. r2_load = _r2(yw, X_load @ b_load)
  112. r2_ti = _r2(yw, X_ti @ b_ti)
  113. ti_coef = float(b_ti[-1])
  114. dr2 = r2_ti - r2_load
  115. return {
  116. "R2_load_within": round(r2_load, 4),
  117. "R2_plusTI_within": round(r2_ti, 4),
  118. "dR2_TI_within": round(dr2, 4),
  119. "TI_coef_within": round(ti_coef, 4),
  120. "n_windows": int(len(dd)),
  121. "n_turbines": int(dd[turbine_col].nunique()),
  122. "load_controls": list(load_cols),
  123. "del_excluded": excluded, # cv>del_cv_max 剔的死通道台 (RV-1)
  124. "del_cv_max": del_cv_max,
  125. # premise: in-sample 加回归元 dR2 恒>0 → 近似 sign(TI_coef) (RV-1 逮); 加 dR2 幅值下界防 vacuous
  126. "premise_holds": bool(ti_coef > 0 and dr2 > 0.01),
  127. "premise_note": "premise=ti_coef>0 ∧ dR2>0.01; in-sample dR2 恒>0 故约等 sign(TI_coef), 0.01 下界防 near-vacuous (RV-1)",
  128. }
  129. def fatigue_ti_exposure_verdict(
  130. df: pd.DataFrame, *, turbine_col: str,
  131. ti_col: str | None = None, ws_std_col: str | None = None, ws_mean_col: str | None = None,
  132. del_col: str | None = None,
  133. ws_col: str | None = None, rotor_col: str | None = None, power_col: str | None = None,
  134. gen_frac_col: str | None = None, gen_frac_min: float = 0.8, gen_power_min: float = 50.0,
  135. z_gate: float = Z_GATE, min_windows: int = MIN_WINDOWS, min_turb: int = MIN_TURB,
  136. min_pool_rows: int = MIN_POOL_ROWS, ti_lo: float = TI_LO, ti_hi: float = TI_HI,
  137. del_log: bool = True,
  138. ) -> dict:
  139. """per-机组 **相对 TI 疲劳暴露排序** 裁决 (相对非绝对; 见模块 docstring 诚实界)。
  140. 返回 {
  141. "verdict": "CANDIDATE_RANKING" | "INSUFFICIENT",
  142. "per_turbine": {tid: {"ti_exposure": TI均值, "z": fleet稳健z, "flag": 高暴露bool,
  143. "rank": 1..N (1=最高TI暴露), "n": 有效窗, "note"?: 弃权/低置信}},
  144. "elasticity": {within-turbine TI→DEL 弹性块} | None,
  145. "honesty": [5 条诚实界字符串],
  146. "note": 总体说明,
  147. }
  148. TI 源: ti_col (直接) 优先; 否则 ws_std_col/ws_mean_col 派生 TI=σ/mean; 皆缺 → INSUFFICIENT。
  149. flag = 单侧高暴露 (z ≥ z_gate)。elasticity 需 del_col (+可选载荷控制 ws/rotor/power)。
  150. df 要求: 逐行 = 一个窗 (10min 或调用方定义); gen 掩码用 gen_frac_col≥gen_frac_min 优先,
  151. 否则 power_col>gen_power_min, 皆无则不掩 (调用方保证运行态)。阈值/口径见模块 docstring。
  152. """
  153. HONESTY = [
  154. "(a) 相对非绝对疲劳: 无气弹标定/无S-N曲线 → 给fleet内排序, 不给寿命/DEL绝对值/剩余年限。",
  155. "(b) TI是暴露代理非直接损伤: 高TI≠该台一定先坏, 材料/结构裕度/S-N未入模。",
  156. "(c) 单场单月(fushan Oct2023)验证, 跨场泛化未测(n=1场); 迁场须重验TI→DEL弹性符号与量级。",
  157. "(d) 需TI通道(ws_std/ws_mean或ti)或塔振DEL; 两者皆缺→INSUFFICIENT弃权(非静默全零)。",
  158. "(e) fleet-relative→批次盲: 全场一致高TI暴露→稳健z皆≈0→无一flag; 批次嫌疑场须先场型识别/绝对TI基准。",
  159. "(f) DEL代理异质 (RV-1逮): DEL通道跨台常两population (fushan 13台cv≈0.4物理 + 5台cv≈4非物理坏通道); "
  160. "pooled弹性(0.114/0.344)是干净子集(~0.21/0.46)与死通道噪声的稀释均值 → per台cv>del_cv_max已剔(del_excluded), "
  161. "但迁场须核DEL通道质量; premise_holds in-sample约等sign(TI系数), 非强前提检验。",
  162. ]
  163. # NaN-safe: Arrow str backend 下 astype(str) 留 float NaN → sorted 混型崩; dropna + 显式 str()
  164. tids = sorted({str(x) for x in df[turbine_col].dropna().unique()})
  165. def _insufficient(reason: str) -> dict:
  166. return {
  167. "verdict": "INSUFFICIENT",
  168. "per_turbine": {t: {"ti_exposure": None, "z": None, "flag": False, "rank": None,
  169. "n": 0, "note": reason} for t in tids},
  170. "elasticity": None, "honesty": HONESTY, "note": reason,
  171. }
  172. if turbine_col not in df.columns:
  173. return _insufficient("无 turbine_col; abstain (INSUFFICIENT)")
  174. # ---- TI 源解析 (诚实界 d): ti_col 优先, 否则 ws_std/ws_mean 派生; 皆缺 → 弃权 ----
  175. work = pd.DataFrame({turbine_col: df[turbine_col].astype(str).to_numpy()})
  176. if ti_col and ti_col in df.columns:
  177. work["_ti"] = pd.to_numeric(df[ti_col], errors="coerce").to_numpy(float)
  178. ti_src = f"直接 TI 列 '{ti_col}'"
  179. elif ws_std_col and ws_std_col in df.columns and ws_mean_col and ws_mean_col in df.columns:
  180. std = pd.to_numeric(df[ws_std_col], errors="coerce").to_numpy(float)
  181. mean = pd.to_numeric(df[ws_mean_col], errors="coerce").to_numpy(float)
  182. with np.errstate(divide="ignore", invalid="ignore"):
  183. work["_ti"] = np.where(mean > 0, std / mean, np.nan)
  184. ti_src = f"派生 TI = {ws_std_col}/{ws_mean_col}"
  185. else:
  186. return _insufficient(
  187. "无 TI 输入 (ti_col 或 ws_std_col+ws_mean_col 均缺) → 暴露排序无输入; abstain (INSUFFICIENT)")
  188. # ---- gen 掩码 (fraction 优先, 单位无关; 否则 power 阈; 皆无不掩) ----
  189. if gen_frac_col and gen_frac_col in df.columns:
  190. gen = pd.to_numeric(df[gen_frac_col], errors="coerce").to_numpy(float) >= gen_frac_min
  191. elif power_col and power_col in df.columns:
  192. gen = pd.to_numeric(df[power_col], errors="coerce").to_numpy(float) > gen_power_min
  193. else:
  194. gen = np.ones(len(df), dtype=bool)
  195. # 载荷控制列 (within 弹性用; 存在才带)
  196. for src, dst in ((ws_col, "_ws"), (rotor_col, "_rotor"), (power_col, "_power")):
  197. if src and src in df.columns:
  198. work[dst] = pd.to_numeric(df[src], errors="coerce").to_numpy(float)
  199. if del_col and del_col in df.columns:
  200. work["_del"] = pd.to_numeric(df[del_col], errors="coerce").to_numpy(float)
  201. valid = gen & np.isfinite(work["_ti"].to_numpy(float)) \
  202. & (work["_ti"].to_numpy(float) > ti_lo) & (work["_ti"].to_numpy(float) < ti_hi)
  203. sub = work[valid].copy()
  204. # ---- 层1: per台 TI 暴露 + fleet 稳健 z + flag ----
  205. per = {t: {"ti_exposure": None, "z": None, "flag": False, "rank": None, "n": 0} for t in tids}
  206. grp = sub.groupby(turbine_col)["_ti"]
  207. ti_mean = grp.mean()
  208. ti_n = grp.size()
  209. qualified = [t for t in tids if int(ti_n.get(t, 0)) >= min_windows]
  210. for t in tids:
  211. n_t = int(ti_n.get(t, 0))
  212. per[t]["n"] = n_t
  213. if t not in qualified:
  214. per[t]["note"] = f"有效窗 {n_t}<{min_windows} (疑停机/无本工况/TI野值滤尽); abstain"
  215. else:
  216. per[t]["ti_exposure"] = round(float(ti_mean[t]), 4)
  217. # ---- 层2: within-turbine TI→DEL 弹性 (可选, 有 DEL 才算) ----
  218. elasticity = None
  219. if "_del" in sub.columns:
  220. load_cols = [c for c in ("_ws", "_rotor", "_power") if c in sub.columns]
  221. elasticity = _within_elasticity(
  222. sub, del_col="_del", ti_col="_ti", load_cols=load_cols,
  223. turbine_col=turbine_col, min_pool_rows=min_pool_rows, del_log=del_log)
  224. if elasticity is None:
  225. elasticity = {"note": f"DEL 有效行 <{min_pool_rows} → within 弹性不可估 (仅出暴露排序)"}
  226. else:
  227. elasticity = {"note": "无 DEL 代理列 → 跳过 within-turbine 弹性物理校验 (仅出暴露排序)"}
  228. if len(qualified) < min_turb:
  229. note = (f"合格台数 {len(qualified)}<{min_turb} → fleet 稳健 z 不可估; abstain (INSUFFICIENT)。"
  230. f" 已报 per台 ti_exposure/n (信息), 但不可裁排序。")
  231. for t in qualified:
  232. per[t]["note"] = note
  233. return {"verdict": "INSUFFICIENT", "per_turbine": per, "elasticity": elasticity,
  234. "honesty": HONESTY, "note": note}
  235. # fleet 稳健 z (仅合格台参与) + 单侧 flag + rank
  236. q_arr = np.array([float(ti_mean[t]) for t in qualified], float)
  237. z_arr = _robust_z(q_arr)
  238. order = sorted(qualified, key=lambda t: float(ti_mean[t]), reverse=True) # 1=最高
  239. rank_of = {t: i + 1 for i, t in enumerate(order)}
  240. for t, z in zip(qualified, z_arr):
  241. per[t]["z"] = round(float(z), 3)
  242. per[t]["flag"] = bool(z >= z_gate)
  243. per[t]["rank"] = rank_of[t]
  244. n_flag = sum(1 for t in qualified if per[t]["flag"])
  245. premise = elasticity.get("premise_holds") if isinstance(elasticity, dict) else None
  246. note = (f"相对 TI 疲劳暴露排序 (候选级, 非绝对寿命): {ti_src}; 合格 {len(qualified)}/{len(tids)} 台; "
  247. f"高暴露 flag {n_flag} 台 (z≥{z_gate})。")
  248. if premise is True:
  249. note += " within-turbine TI→DEL 弹性正 (dR2>0 ∧ TI系数>0) → 疲劳解读物理前提坐实。"
  250. elif premise is False:
  251. note += (" ⚠ within-turbine TI→DEL 弹性非正 → 可证伪判据触发: 本场 TI 不驱动 DEL, "
  252. "排序仅为湍流环境描述, 不可作疲劳剂量解读 (诚实界 falsifiable)。")
  253. return {"verdict": "CANDIDATE_RANKING", "per_turbine": per, "elasticity": elasticity,
  254. "honesty": HONESTY, "note": note}