vib_raw_build.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """振动侧一键摄入: data/raw/<场站>/{windcms,m5_cms_tcm} 的原始件 → 窗索引/谱库 → (可选)CMS 报告与知识库.
  4. ## 为什么需要它 (2026-09-12 用户令)
  5. 用户令: 「数据层里的「CMS 振动评估报告」应遵循 `<安装目录>\\data\\raw\\如东\\windcms`、
  6. 「振动线 handoff」应遵循 `<安装目录>\\data\\raw\\如东\\m5_cms_tcm` 存放; 修改系统支持振动数据参与
  7. 运行、重算」。此前振动侧只有**产物**(`outputs/<场>/m5_cms_tcm` 90 件 + `outputs/<场>/windcms` 53 件),
  8. 源件不在 data/raw, 生成端脚本 (振动线分支的 rudong_tcm_*.py 七件) 也没随包 ⇒ 从零重算时振动侧是断的。
  9. 两个事实把这件事限定得很清楚:
  10. · `src/windcms/pipeline.py` 认的输入就是"含 `*_decode.json` 的目录"(Brande TCM Enterprise 导出),
  11. 这一步**必须能跑**, 否则数据进了 data/raw 也只是躺着;
  12. · 同分支的六层链 (oem_scan / energy_share / model_run / fusion) 脚本仍未随包 —— 本脚本**不假装**
  13. 能把那几步跑出来: 它只做"索引 + 谱 + (可选)报告/知识库", 其余在报告里如实写"缺失"。
  14. ## 这一步跑完, 振动数据就真的参与了运行
  15. data/raw/<场站>/windcms/.../*_decode.json
  16. → outputs/<场>/m5_cms_tcm/windows/<窗>/index.parquet (54 列, 与包内 tcm_index.parquet 同构)
  17. → outputs/<场>/m5_cms_tcm/windows/<窗>/spectra/*.npz + spectra_meta.parquet
  18. 消费者 (无需改一行代码, 窗是自动发现的):
  19. src/windcms/data.py::windows() → 新窗进分析集
  20. src/windcms/data.py::load_scalars() → 标量进 CMS 报告/页面
  21. src/windcms/data.py::spectrum() → 谱图能取到 (此前 spectra 库整个缺失, 谱图是死的)
  22. scripts/windcms.py report / kb → 报告与知识库重生成
  23. ## ★ 报告默认**跑**了 (2026-09-18 用户令后口径翻转)
  24. 2026-09-12 的旧口径是"默认不跑": 那时拿**随包快照**当基准, 重生成会让 `windcms/report.md`
  25. 从 16,857 B 掉到 467 B (−97%), 因为 `data.load_model()` 要读的 `m5/model_run_l6.parquet` 与
  26. `m5/fusion_38.csv` 属六层链 `model_run`/`fusion` 两步, 那两步脚本没随包。
  27. 用户令 2026-09-18「`/detail` 各页面不能用旧版产出补, 必须基于输入数据重算」把这条基准**换掉了**:
  28. 交付包里根本没有旧产物可比, 缺的那个"完整快照"也不该再出现在页面上。于是:
  29. · 报告里少的只有**融合级**那一列(如实写 `—`, 因为 model_run/fusion 两步确实没跑),
  30. 其余判级(状态等级/证据状态/行动等级/逐台页/总览)全部由 `data/raw/<场站>/windcms` 的
  31. `*_decode.json` 现算 —— 实测 2026-09-18: 38 台判级出来(报警 3 / 优秀 35), `/api/vibcms` 立即可用;
  32. · 故本脚本**默认**带报告与知识库 (`--no-report` 可关), `rebuild_all.py` 的 ④b 同步。
  33. ## 用法
  34. python scripts/vib_raw_build.py --farm rudong # 摄入(索引+谱) + 报告/知识库
  35. python scripts/vib_raw_build.py --window w0316 # 指定窗名
  36. python scripts/vib_raw_build.py --jobs 12 --meas FFT_ # 并行/测量过滤
  37. python scripts/vib_raw_build.py --no-report # 只摄入, 不动报告/知识库
  38. python scripts/vib_raw_build.py --dry-run # 只报会做什么
  39. python scripts/vib_raw_build.py --publish-only # ★恢复: 索引/谱已算完但发布被占用过 ⇒ 直接发布
  40. ## ★ 发布(改名)那一步为什么要特殊处理 (2026-09-19 远端实逮)
  41. 服务器上索引(719 s)+谱(894 s) 落进 `windows\\_staging_ingest`(1710 件 / 3.3 GB)后,
  42. `staging.rename(final)` 回 `PermissionError: [WinError 5] 拒绝访问` ⇒ ④b 失败 ⇒ 整条重算链停在第 4 步,
  43. 页面表现为「需要关注 0 台 + 融合面缺件」。Windows 的目录 rename 要求树里没有打开的文件句柄,
  44. 而杀软/索引器正在扫刚写的这批小文件 ⇒ 故本脚本的发布改为 `_move_tree()`:
  45. 整目录 rename 退避重试 → 逐件搬(每件重试, rename 不行就 copy+删) → 仍锁住的如实报出来。
  46. 已经算完的暂存窗可用 `--publish-only` 直接发布,不必重跑那 25 分钟的索引/谱。
  47. """
  48. from __future__ import annotations
  49. import argparse
  50. import json
  51. import os
  52. import pathlib
  53. import shutil
  54. import subprocess
  55. import sys
  56. import time
  57. ROOT = pathlib.Path(__file__).resolve().parents[1]
  58. sys.path.insert(0, str(ROOT))
  59. # ★GBK 控制台/日志重定向不再因 '²' '⇒' 这类字符抛 UnicodeEncodeError (2026-09-19 远端实逮:
  60. # `baseline_38_build.py` 打印 'm/s²' 时在 cp936 下 rc=1, 整条恢复链少一件产物)。
  61. # 只把**不可编码字符替换掉**, 不改流编码 —— 中文照旧可读。
  62. try:
  63. sys.stdout.reconfigure(errors='replace')
  64. except Exception:
  65. pass
  66. from src.console import soft # noqa: E402
  67. soft()
  68. PY = sys.executable
  69. def human(n):
  70. for u in ('B', 'KB', 'MB', 'GB'):
  71. if n < 1024 or u == 'GB':
  72. return f'{n:.1f} {u}'
  73. n /= 1024
  74. def find_roots(station: pathlib.Path):
  75. """→ 振动侧原始件根列表 (含 *_decode.json 的目录或导出 zip)。"""
  76. roots = []
  77. for name in ('windcms', 'm5_cms_tcm'):
  78. d = station / name
  79. if not d.is_dir():
  80. continue
  81. for z in sorted(d.rglob('*.zip')):
  82. if z.name.upper().startswith('CMS') or 'decode' in z.name.lower():
  83. roots.append(z)
  84. for sub in sorted({p.parent for p in d.rglob('*_decode.json')}):
  85. # 取**最上层**那个含 decode 文件的目录 (measurement/), 避免每台机组一个 root
  86. top = sub
  87. while top.parent != d and any(top.parent.rglob('*_decode.json')):
  88. top = top.parent
  89. if top not in roots:
  90. roots.append(top)
  91. return roots
  92. def run(step, cmd, log):
  93. t0 = time.time()
  94. print(f'[{step}] {" ".join(str(c) for c in cmd)}', flush=True)
  95. p = subprocess.run([str(c) for c in cmd], cwd=str(ROOT), capture_output=True, text=True,
  96. encoding='utf-8', errors='replace')
  97. tail = (p.stdout or '') + (p.stderr or '')
  98. rec = dict(step=step, cmd=' '.join(str(c) for c in cmd), rc=p.returncode,
  99. seconds=round(time.time() - t0, 1), tail=tail[-1200:])
  100. log.append(rec)
  101. print(f' rc={p.returncode} {rec["seconds"]}s', flush=True)
  102. if p.returncode != 0:
  103. print(tail[-2000:], flush=True)
  104. raise SystemExit(f'步骤 {step} 失败 (rc={p.returncode})')
  105. return rec
  106. def _move_tree(src, dst, log=print):
  107. """把整个目录搬到 `dst`: 先整目录 rename(退避重试), 再逐件搬, 每件都重试。
  108. ★**2026-09-19 远端实逮, 整条重算链就断在这里**(服务器 `D:\\产品\\app`):
  109. 索引(719 s)+谱(894 s) 刚落进 `windows\\_staging_ingest`(1710 件 / 3.3 GB),
  110. 紧接的 `staging.rename(final)` 回 `PermissionError: [WinError 5] 拒绝访问` ⇒ ④b 失败 ⇒
  111. 链在第 4 步停下 ⇒ 融合面 handoff / 变桨面 / 本体 / 契约全没产出,页面上就是
  112. 「需要关注 0 台 + 融合面缺件」。
  113. 成因不是权限:Windows 的**目录** rename 要求树里没有任何被打开的句柄,而刚写完这么多小文件时
  114. 杀软/桌面搜索/备份正在逐个扫它们(持句柄)⇒ 目录不许改名。等一会儿句柄就放开,所以:
  115. ① 整目录 rename + 退避重试(2/4/8/15/20/30 s)
  116. ② 还不行就**逐件搬**(每件自己重试;rename 不行就 copy+删 —— 读句柄通常允许共享读)
  117. 逐件路径下,个别仍被锁住的文件会在最后如实报出来(不静默丢件)。
  118. """
  119. import shutil as _sh
  120. import time as _t
  121. waits = [2, 4, 8, 15, 20, 30]
  122. last = None
  123. for w in [0] + waits:
  124. if w:
  125. _t.sleep(w)
  126. try:
  127. src.rename(dst)
  128. return 'rename'
  129. except OSError as e: # PermissionError / WinError 5 / 1224 …
  130. last = e
  131. log(f' [!] 目录改名被占({type(last).__name__}: {last})→ 转逐件搬(杀软/索引在扫刚写的文件,'
  132. f'等一会儿就好;逐件搬对读句柄友好)')
  133. dst.mkdir(parents=True, exist_ok=True)
  134. stuck, moved = [], 0
  135. for p in sorted(src.rglob('*')):
  136. rel = p.relative_to(src)
  137. target = dst / rel
  138. if p.is_dir():
  139. target.mkdir(parents=True, exist_ok=True)
  140. continue
  141. target.parent.mkdir(parents=True, exist_ok=True)
  142. ok = False
  143. for w in [0, 1, 2, 5, 10, 20]:
  144. if w:
  145. _t.sleep(w)
  146. try:
  147. p.rename(target)
  148. ok = True
  149. break
  150. except OSError:
  151. pass
  152. try: # rename 不行就复制+删(读一般被允许)
  153. _sh.copy2(p, target)
  154. p.unlink()
  155. ok = True
  156. break
  157. except OSError:
  158. pass
  159. if ok:
  160. moved += 1
  161. else:
  162. stuck.append(str(rel))
  163. for d in sorted([x for x in src.rglob('*') if x.is_dir()], reverse=True):
  164. try:
  165. d.rmdir()
  166. except OSError:
  167. pass
  168. try:
  169. src.rmdir()
  170. except OSError:
  171. pass
  172. if stuck:
  173. raise RuntimeError(
  174. f'暂存窗里还有 {len(stuck)} 件被别的进程占着、搬不动(已搬 {moved} 件): {stuck[:8]}'
  175. f'{" …" if len(stuck) > 8 else ""} —— 把占用方(杀软实时扫描/备份/资源管理器预览)停一下,'
  176. f'或稍后重跑 `python scripts/vib_raw_build.py --publish-only`(不必重跑索引/谱)。')
  177. log(f' 逐件搬完成: {moved} 件')
  178. return 'per-file'
  179. def _rels_of_window(win: pathlib.Path, m5: pathlib.Path) -> dict:
  180. """某窗的产物 → {相对产物仓的路径: 构建器说明}; 供正常摄入与 --register-only 共用 (单一实现)。"""
  181. rels = {f'm5_cms_tcm/windows/{win.name}/index.parquet':
  182. 'scripts/rudong_tcm_index.py (54 列, 与包内 tcm_index.parquet 同列名列序)',
  183. f'm5_cms_tcm/windows/{win.name}/spectra_meta.parquet':
  184. 'scripts/rudong_tcm_spectra.py',
  185. 'm5_cms_tcm/vib_raw_manifest.json': 'scripts/vib_raw_build.py'}
  186. sp = win / 'spectra'
  187. if sp.is_dir():
  188. for p in sp.rglob('*.npz'):
  189. rels[f'm5_cms_tcm/windows/{win.name}/spectra/{p.relative_to(sp).as_posix()}'] = \
  190. 'scripts/rudong_tcm_spectra.py (npz 分片: DataSets.DataSet.Values 空格串 → float 数组)'
  191. # 谱库目录里那份 meta 是同一内容的两条读取路径之一, 也登记
  192. rels[f'm5_cms_tcm/windows/{win.name}/spectra/spectra_meta.parquet'] = \
  193. 'scripts/rudong_tcm_spectra.py (与窗根同名件同内容: 兼顾两种读取约定)'
  194. return rels
  195. def main() -> int:
  196. ap = argparse.ArgumentParser()
  197. ap.add_argument('--farm', default='rudong')
  198. ap.add_argument('--window', default=None, help='窗名 (默认按数据起始日推 wMMDD)')
  199. ap.add_argument('--jobs', type=int, default=min(8, (os.cpu_count() or 4)))
  200. ap.add_argument('--meas', default='FFT_', help="谱摄入的测量过滤 (默认 FFT_; ALL=全转)")
  201. ap.add_argument('--skip-spectra', action='store_true', help='只做索引 (谱很占盘)')
  202. ap.add_argument('--no-report', dest='with_report', action='store_false',
  203. help='只摄入(索引+谱), 不跑 windcms.py report/kb')
  204. ap.set_defaults(with_report=True) # ★2026-09-18 口径翻转: 见文件头"报告默认跑了"
  205. ap.add_argument('--manifest-only', action='store_true', help='只补写 vib_raw_manifest.json(依已存在的窗; 不重跑摄入)')
  206. ap.add_argument('--reimport-as-new', action='store_true',
  207. help='窗同名时**不替换**: 另起 `<窗>_reimport_<时分>`(该名被 data.EXCLUDE_DEFAULT 排除, '
  208. '不参与生产集)。默认口径是**替换同名窗**(旧窗留档为 `_superseded_<时分>`) —— '
  209. '用户令 2026-09-20「重算要按 data/raw 最新变化」')
  210. ap.add_argument('--publish-only', action='store_true',
  211. help='恢复模式: 上次摄入已算完索引/谱但发布(改名)被占用而失败 ⇒ 直接发布暂存窗并接着跑'
  212. '报告链, 不重跑索引/谱 (见 _move_tree 的说明)')
  213. ap.add_argument('--register-only', action='store_true',
  214. help='不摄入, 只把**已存在**的窗体件补进来源自登记 (幂等修复: 例如先前的摄入跑在自登记'
  215. '功能之前, 台账就漏记了那些件)')
  216. ap.add_argument('--limit', type=int, default=0, help='冒烟: 只摄入前 N 个文件')
  217. ap.add_argument('--dry-run', action='store_true')
  218. a = ap.parse_args()
  219. from src.windscada.config import farm, raw_station_dir
  220. from src import paths as P
  221. cfg = farm(a.farm)
  222. station = pathlib.Path(raw_station_dir(a.farm))
  223. m5 = P.m5(a.farm)
  224. roots = find_roots(station)
  225. print(f'场站原始件目录: {station}')
  226. print(f'振动侧产物目录: {m5}')
  227. if a.register_only:
  228. # 只补登记: 找已存在的窗 (--window 指定, 否则取名字最大的那个), 逐件登记。
  229. # 放在"源件存在性检查"之前 —— 补登记不需要重新读原始件。
  230. cands = sorted(p for p in (m5 / 'windows').glob('w[0-9][0-9][0-9][0-9]')
  231. if (p / 'index.parquet').exists())
  232. if a.window:
  233. cands = [p for p in cands if p.name == a.window]
  234. if not cands:
  235. print('没有已存在的窗可登记 (先正常跑一次摄入)')
  236. return 0
  237. win = cands[-1]
  238. rels = _rels_of_window(win, m5)
  239. from src.derived_manifest import record as _rec
  240. p = _rec(P.out_root(a.farm), rels, by='scripts/vib_raw_build.py')
  241. print(f'已登记 {len(rels)} 件 (窗 {win.name}) → {p}')
  242. return 0
  243. if a.manifest_only:
  244. # 2026-09-19: 摄入已跑完、清单却没写成的情形(实测: ④b 在 report 步崩掉 → 本脚本在写清单**之前**
  245. # 就退出 ⇒ `m5_cms_tcm/vib_raw_manifest.json` 缺失, 页面归口审计按"溯源缺失"报 rc=6、整条链报失败)。
  246. # 本模式**只补写清单**, 不重跑摄入(重跑会再花 ~22 分钟并另立一个 _reimport 窗)。
  247. cands = sorted(p for p in (m5 / 'windows').glob('w[0-9][0-9][0-9][0-9]')
  248. if (p / 'index.parquet').exists())
  249. if a.window:
  250. cands = [p for p in cands if p.name == a.window]
  251. if not cands:
  252. print('没有已存在的窗可写清单 (先正常跑一次摄入)')
  253. return 0
  254. win = cands[-1]
  255. import pandas as _pd
  256. ix = _pd.read_parquet(win / 'index.parquet',
  257. columns=[c for c in ('turbine', 'sensor_name', 'meas_name', 'trigger_time')
  258. if c in _pd.read_parquet(win / 'index.parquet').columns])
  259. sm = win / 'spectra_meta.parquet'
  260. n_spec = int(len(_pd.read_parquet(sm, columns=['shard']))) if sm.is_file() else 0
  261. ts = _pd.to_datetime(ix['trigger_time'], errors='coerce') if 'trigger_time' in ix else None
  262. man = dict(farm=a.farm, window=win.name, window_dir=str(win.relative_to(ROOT)),
  263. sources=[str(r.relative_to(ROOT)) if str(r).startswith(str(ROOT)) else str(r) for r in roots],
  264. sources_note='路径相对<安装目录>; ★本清单由 --manifest-only 依**已存在的窗**补写 '
  265. '(2026-09-19), 不是摄入当次的原始记录 —— steps 留空, 时间取窗首末',
  266. rows=int(len(ix)), spectra=n_spec,
  267. time_min=(str(ts.min()) if ts is not None and len(ts) else ''), time_max=(str(ts.max()) if ts is not None and len(ts) else ''),
  268. turbines=int(ix.turbine.nunique()) if 'turbine' in ix else 0,
  269. sensors=int(ix.sensor_name.nunique()) if 'sensor_name' in ix else 0,
  270. meas_names=int(ix.meas_name.nunique()) if 'meas_name' in ix else 0,
  271. steps=[], finished=time.strftime('%Y-%m-%d %H:%M:%S'), seconds=None,
  272. missing_chain=[], missing_note='')
  273. (m5 / 'vib_raw_manifest.json').write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding='utf-8')
  274. print(f'已补写 {P.rel(m5 / "vib_raw_manifest.json")}: 窗 {win.name} · {len(ix)} 行 · {n_spec} 谱')
  275. try:
  276. from src.derived_manifest import record as _rec
  277. rels = _rels_of_window(win, m5)
  278. _rec(P.out_root(a.farm), rels, by='scripts/vib_raw_build.py (manifest-only)')
  279. print(f' 已自登记 {len(rels)} 件')
  280. except Exception as _e:
  281. print(f' [i] 自登记跳过: {type(_e).__name__}: {_e}')
  282. return 0
  283. if not roots:
  284. print('没找到振动原始件 (*_decode.json 目录或 CMS 导出 zip)。'
  285. '先用 scripts/place_raw_data.py --scope vib 从现场包落位。')
  286. return 0
  287. for r in roots:
  288. n = len(list(r.rglob('*_decode.json'))) if r.is_dir() else '(zip)'
  289. sz = sum(p.stat().st_size for p in r.rglob('*_decode.json')) if r.is_dir() else r.stat().st_size
  290. print(f' 源件根: {r} {n} 个 decode 文件, {human(sz)}')
  291. if a.dry_run:
  292. print('(dry-run, 未摄入)')
  293. return 0
  294. windows_dir = m5 / 'windows'
  295. staging = windows_dir / '_staging_ingest' # 'test'/'_reimport' 之外的名字, 会被 data.windows() 看见 → 立即改名
  296. log = []
  297. t0 = time.time()
  298. idx = staging / 'index.parquet'
  299. # ★`root` 必须在两个分支之前定好 (2026-09-19 实逮: 加 --publish-only 时把它挪进了 else 分支,
  300. # 于是"只发布"这条路走到 spectra 那步就 UnboundLocalError —— 远端第一次恢复就撞上, rc=1)
  301. root = roots[0] if len(roots) == 1 else station / 'windcms' # 多个根时交给各自目录 (index 支持 rglob)
  302. if a.publish_only:
  303. # ★恢复通道 (2026-09-19 远端实逮后的补): 上次摄入把索引+谱**已经算完**了, 只是最后的改名被
  304. # 占住失败 ⇒ 别让运维白等 20~30 分钟重跑索引/谱, 直接把暂存窗发布出去, 然后照常接着跑报告链。
  305. if not idx.is_file():
  306. print(f'[X] 没有可发布的暂存窗: {idx} 不存在 —— 正常跑一次摄入 (python scripts/vib_raw_build.py)')
  307. return 4
  308. print(f'恢复模式 --publish-only: 直接发布已算好的暂存窗 {staging}(不重跑索引/谱)')
  309. else:
  310. if staging.exists():
  311. shutil.rmtree(staging)
  312. staging.mkdir(parents=True, exist_ok=True)
  313. run('index', [PY, str(ROOT / 'scripts/rudong_tcm_index.py'), '--root', str(root), '--out', str(idx),
  314. '--jobs', str(a.jobs)] + (['--limit', str(a.limit)] if a.limit else []), log)
  315. n_spectra = 0
  316. if not a.skip_spectra and not a.publish_only:
  317. run('spectra', [PY, str(ROOT / 'scripts/rudong_tcm_spectra.py'), '--root', str(root),
  318. '--out', str(staging / 'spectra'), '--meas', a.meas, '--jobs', str(a.jobs)]
  319. + (['--limit', str(a.limit)] if a.limit else []), log)
  320. # ★谱数在**两种模式**下都要数 (2026-09-19 远端实逮: --publish-only 那条路把 n_spectra 留在 0,
  321. # 于是清单/报告写"谱 0" —— 明明有 1710 件谱件落着; 清单是给审计对账用的, 少报就是账不实)
  322. sm = staging / 'spectra' / 'spectra_meta.parquet'
  323. if sm.exists():
  324. import pandas as pd
  325. n_spectra = len(pd.read_parquet(sm, columns=['shard']))
  326. elif (staging / 'spectra').is_dir():
  327. n_spectra = sum(1 for _ in (staging / 'spectra').rglob('*.npz'))
  328. # 窗名: 用数据自身的起始日 (wMMDD), 与既有 w0127/w0707/w0811 同口径
  329. import pandas as pd
  330. d = pd.read_parquet(idx)
  331. tt = pd.to_datetime(d.trigger_time, errors='coerce')
  332. tmin, tmax = tt.min(), tt.max()
  333. win = a.window or f'w{tmin:%m%d}'
  334. final = windows_dir / win
  335. if final.exists():
  336. # ★2026-09-20 用户令「重算时要根据 <data/raw> 目录**最新的变化**重算」⇒ 默认**替换同名窗**:
  337. # 原先这里一律改叫 `<窗>_reimport_<时分>`, 而 `data.EXCLUDE_DEFAULT` 把 `_reimport` 排除在
  338. # 生产集之外 ⇒ 往 windcms 里补了数据再重算, **生产集用的还是旧窗**, 新数据等于没进系统
  339. # (页面上看不出任何变化, 正是"重算没反映最新变化"的典型)。
  340. # 现在: 旧窗改名为 `<窗>_superseded_<时分>` 留档(按名字排除, 不参与生产), 新窗用**正名**发布;
  341. # 要旧行为(不碰既有窗、另起 _reimport 窗)用 `--reimport-as-new`。
  342. if a.reimport_as_new:
  343. final = windows_dir / f'{win}_reimport_{time.strftime("%m%d%H%M")}'
  344. print(f'⚠ 窗 {win} 已存在 → 按 --reimport-as-new 落到 {final.name} '
  345. f'(data.EXCLUDE_DEFAULT 排除 _reimport 窗, 不参与生产集)')
  346. else:
  347. old_win = windows_dir / f'{win}_superseded_{time.strftime("%m%d%H%M")}'
  348. print(f'窗 {win} 已存在 → 按"重算=按当前数据重算"口径**替换**: 旧窗留档为 {old_win.name}'
  349. f'(按名字排除, 不参与生产), 新窗用正名 {win} 发布')
  350. _move_tree(final, old_win, print)
  351. print(f'\n发布窗目录: {final.name}({_move_tree(staging, final, print)} 方式)'
  352. f' 数据窗 {tmin} → {tmax} 行 {len(d)} 谱 {n_spectra}')
  353. if a.with_report:
  354. # ★2026-09-19 补链序: 六层链的业务顺序是 oem_scan → energy_share → **model_run → fusion** → report,
  355. # 报告要读 model_run_l6.parquet 与 fusion_38.csv 才有"融合级"那一列。原先这里直接跑 report,
  356. # 于是清过产物的机器上报告永远缺融合级(整列 '—')。现在按序补齐(两步都是**按口径重建**, 无标准答案
  357. # 对拍 —— 口径与来路写在各自产物与台账里, 见 docs/振动六层链_接口规格与缺口_v0.1.md §3)。
  358. run('model_run', [PY, str(ROOT / 'scripts/rudong_model_run.py'), '--window', final.name], log)
  359. # 六层链的 energy_share 步(2026-09-19 补上: 此前该脚本未随包 ⇒ 链上少一环):
  360. # 线能量占比 = ±2bin 带内能量 ÷ 全谱能量; 只报占比不定级。
  361. run('energy_share', [PY, str(ROOT / 'scripts/rudong_line_energy_share.py'), '--window', final.name], log)
  362. run('fusion', [PY, str(ROOT / 'scripts/rudong_fusion_run.py'), '--window', final.name], log)
  363. # CMS 掩码阈值件(观澜自算: 中位+3/6×MAD 自适应基线; 现场导出件里没有厂商掩码定义)
  364. run('mask_thresholds', [PY, str(ROOT / 'scripts/tcm_mask_thresholds_build.py'), '--window', final.name], log)
  365. run('report', [PY, str(ROOT / 'scripts/windcms.py'), 'report', '--farm', a.farm], log)
  366. # ★2026-09-19 用户令「所有的计算均要形成观澜的源代码,确保别的电脑装完系统运行正常」:
  367. # 融合面 handoff 此前是**振动线人工交证件**、全库 0 处写入方 ⇒ 新机器上 `/detail/v2` 的
  368. # 「需要关注/全场状态」永远空着。现在由观澜自算生成同结构件(脚本在包内; 盘上若有正本则不覆盖)。
  369. run('fusion_handoff', [PY, str(ROOT / 'scripts/rudong_fusion_handoff.py')], log)
  370. run('kb', [PY, str(ROOT / 'scripts/windcms.py'), 'kb', '--farm', a.farm], log)
  371. # 六层链 fusion 步里**唯一已被标准答案验证过**的那一件 (fleet_scalar_z): 窗索引 → 同工况族中位
  372. # → 稳健 z。上面那次 fusion 已经一并出它 (同一条命令: --window final.name)。
  373. else:
  374. print('(按 --no-report 跳过 CMS 报告/知识库重生成 —— 页面上"振动评估"一栏会显示为无产物)')
  375. man = dict(farm=a.farm, window=final.name, window_dir=str(final.relative_to(ROOT)),
  376. # 源件路径写**相对安装根**的形态: 这文件会随包分发, 绝对路径换机后就是死链
  377. # (check_transferable.py 会把 outputs 下的绝对路径算作"机器相关路径")
  378. sources=[str(r.relative_to(ROOT)) if str(r).startswith(str(ROOT)) else str(r) for r in roots],
  379. sources_note='路径相对<安装目录>', rows=int(len(d)), spectra=int(n_spectra),
  380. time_min=str(tmin), time_max=str(tmax),
  381. turbines=int(d.turbine.nunique()), sensors=int(d.sensor_name.nunique()),
  382. meas_names=int(d.meas_name.nunique()),
  383. steps=[{k: v for k, v in r.items() if k != 'tail'} for r in log],
  384. finished=time.strftime('%Y-%m-%d %H:%M:%S'), seconds=round(time.time() - t0, 1),
  385. missing_chain=['rudong_tcm_oem_scan', 'rudong_line_energy_share', 'rudong_model_run',
  386. 'rudong_fusion_run'],
  387. missing_note='六层链的四步脚本未随包 (振动线分支 claude/vibration-data-diagnosis-32b69e); '
  388. '本脚本只做索引/谱/报告/知识库, 不冒充跑过那四步')
  389. (m5 / 'vib_raw_manifest.json').write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding='utf-8')
  390. # 来源自登记: 让 _provenance.json 把这些件记成 raw-derived (见 src/derived_manifest.py 的说明)
  391. try:
  392. from src.derived_manifest import record as _rec
  393. rels = _rels_of_window(final, m5)
  394. if a.with_report:
  395. for p in (P.cms(a.farm)).glob('报告_CMS振动状态评估报告_*.md'):
  396. # 只登记"今天生成的"这一件 (随包/厂家转录的那些不冒充自算)
  397. if time.strftime('%Y-%m-%d') in p.name:
  398. rels[f'windcms/{p.name}'] = 'scripts/windcms.py report (数据窗: ' + final.name + ')'
  399. _rec(P.out_root(a.farm), rels, by='scripts/vib_raw_build.py')
  400. print(f' 自登记 {len(rels)} 件产物 → {P.out_root(a.farm) / "_derived_manifest.json"}')
  401. except Exception as _e:
  402. print(f' ⚠ 来源自登记失败 ({type(_e).__name__}: {_e}) —— 台账会漏记这些件, 但不影响产物本身')
  403. print(f'\n完成: 用时 {time.time() - t0:.0f}s; 清单 → {m5 / "vib_raw_manifest.json"}')
  404. print(f' 新窗 {final.name} 已进分析集: windcms 的谱图/标量/报告页会自动收录它 '
  405. f'(消费者读取时现扫 m5\\windows\\w????\\index.parquet, 无需改代码)')
  406. print(' windscada 融合面读 handoff (m5_cms_tcm/handoff_vibration_v2.json) —— 那是振动线出件, 本次不动它')
  407. print(' 看效果: python scripts/windcms.py serve --port 8020 → http://127.0.0.1:8020/')
  408. return 0
  409. if __name__ == '__main__':
  410. sys.exit(main())