html_export.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. """用 HTML + ECharts 输出交互图。"""
  2. from __future__ import annotations
  3. import json
  4. from datetime import timedelta
  5. from pathlib import Path
  6. import numpy as np
  7. import pandas as pd
  8. from . import config, data
  9. COLORS = {
  10. "一缸": "#c0392b",
  11. "二缸": "#e67e22",
  12. "三缸": "#16a085",
  13. "四缸": "#2980b9",
  14. "五缸": "#8e44ad",
  15. "六缸": "#7f8c8d",
  16. }
  17. def _nearest_time(times: list[str], target) -> str:
  18. target = pd.Timestamp(target)
  19. parsed = pd.to_datetime(pd.Series(times))
  20. index = (parsed - target).abs().idxmin()
  21. return times[int(index)]
  22. def _aligned(part: pd.DataFrame, times: list[str], cylinder: str, column: str) -> list[float | None]:
  23. group = part[part["cylinder"] == cylinder].sort_values("sample_time")
  24. if group.empty:
  25. return [None] * len(times)
  26. values = dict(zip(group["sample_time"].dt.strftime("%Y-%m-%d %H:%M:%S"), group[column]))
  27. return [None if pd.isna(values.get(time)) else float(values[time]) for time in times]
  28. def _chart_common(times: list[str], fault_time: str, intervals: pd.DataFrame, cylinder: str) -> dict:
  29. areas = []
  30. part = intervals[intervals["cylinder"] == cylinder]
  31. for row in part.itertuples(index=False):
  32. areas.append([
  33. {"xAxis": _nearest_time(times, row.start_time)},
  34. {"xAxis": _nearest_time(times, row.end_time)},
  35. ])
  36. return {
  37. "tooltip": {"trigger": "axis"},
  38. "legend": {"top": 0, "type": "scroll"},
  39. "grid": {"left": 45, "right": 20, "top": 35, "bottom": 55},
  40. "xAxis": {
  41. "type": "category",
  42. "data": times,
  43. "axisLabel": {"rotate": 30, "fontSize": 9},
  44. },
  45. "yAxis": {"type": "value", "scale": True},
  46. "dataZoom": [
  47. {"type": "inside", "start": 0, "end": 100},
  48. {"type": "slider", "height": 18, "bottom": 10},
  49. ],
  50. "markLine": {
  51. "symbol": "none",
  52. "silent": True,
  53. "label": {"formatter": "fault"},
  54. "lineStyle": {"color": "#2c3e50", "width": 1.2},
  55. "data": [{"xAxis": fault_time}],
  56. },
  57. }
  58. def _waveform_option(frame: pd.DataFrame, intervals: pd.DataFrame, event: dict) -> dict | None:
  59. cylinder = event["cylinder"]
  60. candidates = intervals[intervals["cylinder"] == cylinder]
  61. if candidates.empty:
  62. return None
  63. seed = candidates.loc[candidates["max_score"].idxmax()]
  64. seed_time = pd.Timestamp(seed["max_time"])
  65. rows = {}
  66. for name in config.CYLINDERS:
  67. group = frame[frame["cylinder"] == name]
  68. if group.empty:
  69. continue
  70. distance = (group["sample_time"] - seed_time).abs()
  71. index = distance.idxmin()
  72. if distance.loc[index] <= pd.Timedelta(hours=2):
  73. rows[name] = group.loc[index]
  74. if not rows:
  75. return None
  76. samples = data.fetch_samples([int(row["id"]) for row in rows.values()])
  77. series = []
  78. for name, row in rows.items():
  79. signal = samples.get(int(row["id"]))
  80. if signal is None or signal.size == 0:
  81. continue
  82. scale = float(np.sqrt(np.mean(signal ** 2))) or 1.0
  83. fs = float(row["sample_frequency_hz"] or 0) or 25600.0
  84. x = np.arange(signal.size) / fs * 1000.0
  85. series.append(
  86. {
  87. "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
  88. "type": "line",
  89. "showSymbol": False,
  90. "sampling": "lttb",
  91. "lineStyle": {"width": 2.2 if name == cylinder else 1.0},
  92. "itemStyle": {"color": "#c0392b" if name == cylinder else COLORS[name]},
  93. "data": [[round(float(x[i]), 3), round(float(signal[i] / scale), 4)] for i in range(signal.size)],
  94. }
  95. )
  96. return {
  97. "tooltip": {"trigger": "axis"},
  98. "legend": {"top": 0},
  99. "grid": {"left": 50, "right": 20, "top": 35, "bottom": 45},
  100. "xAxis": {"type": "value", "name": "ms", "scale": True},
  101. "yAxis": {"type": "value", "name": "normalized amplitude", "scale": True},
  102. "dataZoom": [{"type": "inside"}, {"type": "slider", "height": 18, "bottom": 10}],
  103. "series": series,
  104. }
  105. def _page(event: dict, frame: pd.DataFrame, intervals: pd.DataFrame, validation: pd.DataFrame) -> str:
  106. center = pd.Timestamp(event["date"])
  107. start = center - pd.Timedelta(days=10)
  108. end = center + pd.Timedelta(days=3)
  109. part = frame[(frame["sample_time"] >= start) & (frame["sample_time"] <= end)].copy()
  110. part["time"] = part["sample_time"].dt.strftime("%Y-%m-%d %H:%M:%S")
  111. times = sorted(part["time"].unique().tolist())
  112. fault_time = _nearest_time(times, center)
  113. base = _chart_common(times, fault_time, intervals, event["cylinder"])
  114. score_series = []
  115. rms_series = []
  116. kurt_series = []
  117. for name in config.CYLINDERS:
  118. color = "#c0392b" if name == event["cylinder"] else COLORS[name]
  119. width = 2.4 if name == event["cylinder"] else 1.0
  120. score_series.append(
  121. {
  122. "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
  123. "type": "line",
  124. "showSymbol": False,
  125. "sampling": "lttb",
  126. "connectNulls": False,
  127. "lineStyle": {"width": width},
  128. "itemStyle": {"color": color},
  129. "data": _aligned(part, times, name, "score"),
  130. }
  131. )
  132. rms_series.append(
  133. {
  134. "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
  135. "type": "line",
  136. "showSymbol": False,
  137. "sampling": "lttb",
  138. "connectNulls": False,
  139. "lineStyle": {"width": width},
  140. "itemStyle": {"color": color},
  141. "data": _aligned(part, times, name, "rms_ratio"),
  142. }
  143. )
  144. kurt_series.append(
  145. {
  146. "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
  147. "type": "line",
  148. "showSymbol": False,
  149. "sampling": "lttb",
  150. "connectNulls": False,
  151. "lineStyle": {"width": width},
  152. "itemStyle": {"color": color},
  153. "data": _aligned(part, times, name, "kurt_ratio"),
  154. }
  155. )
  156. score_series[0]["markArea"] = {
  157. "silent": True,
  158. "itemStyle": {"color": "rgba(230,126,34,0.15)"},
  159. "data": [
  160. [
  161. {"xAxis": _nearest_time(times, row.start_time)},
  162. {"xAxis": _nearest_time(times, row.end_time)},
  163. ]
  164. for row in intervals[intervals["cylinder"] == event["cylinder"]].itertuples(index=False)
  165. ],
  166. }
  167. score_series[0]["markLine"] = base.pop("markLine")
  168. score_option = {**base, "yAxis": {"type": "value", "name": "score", "scale": True}, "series": score_series}
  169. rms_option = {**base, "yAxis": {"type": "value", "name": "RMS / baseline", "scale": True}, "series": rms_series}
  170. kurt_option = {**base, "yAxis": {"type": "value", "name": "kurtosis / baseline", "scale": True}, "series": kurt_series}
  171. wave_option = _waveform_option(frame, intervals, event)
  172. event_rows = validation[validation["event_id"] == event["event_id"]].to_dict("records")
  173. table_rows = "".join(
  174. f"<tr><td>{event['event_id']}</td><td>{row.get('cylinder','')}</td><td>{row.get('start_time','')}</td>"
  175. f"<td>{row.get('end_time','')}</td><td>{row.get('direction','')}</td><td>{row.get('level','')}</td>"
  176. f"<td>{row.get('confirmed','')}</td></tr>"
  177. for row in event_rows
  178. )
  179. return f"""<!doctype html>
  180. <html lang="zh-CN"><head><meta charset="utf-8"><title>{event['event_id']} 缸体振动</title>
  181. <style>
  182. body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;margin:18px;color:#222;background:#fff}}
  183. h1{{font-size:22px;margin:0 0 8px}} h2{{font-size:16px;margin:22px 0 8px}}
  184. .chart{{width:100%;height:380px;border:1px solid #eee;border-radius:6px;margin-bottom:14px}}
  185. .note{{color:#666;font-size:13px;line-height:1.6}} table{{border-collapse:collapse;margin-top:8px;font-size:13px}}
  186. th,td{{border:1px solid #ddd;padding:6px 10px;text-align:left}} th{{background:#f7f7f7}}
  187. a{{color:#1a73e8;text-decoration:none}}
  188. </style></head><body>
  189. <h1>{event['event_id']} · 事件缸 {event['cylinder']} · {event['description']}</h1>
  190. <div class="note">灰色断档 = 停机/无运行数据;橙色区域 = 振动候选时间段;竖线 = 故障表日期。温度不参与这些标签。</div>
  191. <h2>异常分数(6 缸)</h2><div id="score" class="chart"></div>
  192. <h2>实际 RMS / 基线(6 缸)</h2><div id="rms" class="chart"></div>
  193. <h2>实际峭度 / 基线(6 缸)</h2><div id="kurt" class="chart"></div>
  194. <h2>首周期波形对比(种子时刻,归一化)</h2><div id="wave" class="chart"></div>
  195. <h2>事件验证</h2>
  196. <table><thead><tr><th>事件</th><th>缸</th><th>开始</th><th>结束</th><th>方向</th><th>等级</th><th>多特征确认</th></tr></thead>
  197. <tbody>{table_rows}</tbody></table>
  198. <p class="note"><a href="index.html">返回索引</a></p>
  199. <script src="echarts.min.js"></script>
  200. <script>
  201. const scoreOption = {json.dumps(score_option, ensure_ascii=False)};
  202. const rmsOption = {json.dumps(rms_option, ensure_ascii=False)};
  203. const kurtOption = {json.dumps(kurt_option, ensure_ascii=False)};
  204. const waveOption = {json.dumps(wave_option, ensure_ascii=False) if wave_option else 'null'};
  205. const charts = [
  206. [echarts.init(document.getElementById('score')), scoreOption],
  207. [echarts.init(document.getElementById('rms')), rmsOption],
  208. [echarts.init(document.getElementById('kurt')), kurtOption],
  209. ];
  210. if (waveOption) charts.push([echarts.init(document.getElementById('wave')), waveOption]);
  211. for (const [chart, option] of charts) chart.setOption(option);
  212. window.addEventListener('resize', () => charts.forEach(([chart]) => chart.resize()));
  213. </script>
  214. </body></html>"""
  215. def export_html(frame: pd.DataFrame, intervals: pd.DataFrame, validation: pd.DataFrame) -> None:
  216. out_dir = config.OUTPUT_DIR / "html"
  217. out_dir.mkdir(parents=True, exist_ok=True)
  218. for event in config.EVENTS:
  219. path = out_dir / f"event_{event['event_id']}.html"
  220. path.write_text(_page(event, frame, intervals, validation), encoding="utf-8")
  221. print(f"[html] {path}")
  222. links = "".join(
  223. f"<li><a href=\"event_{event['event_id']}.html\">{event['event_id']} · {event['cylinder']} · {event['description']}</a></li>"
  224. for event in config.EVENTS
  225. )
  226. (out_dir / "index.html").write_text(
  227. f"""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>5号机缸体振动</title>
  228. <style>body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;margin:24px}}a{{color:#1a73e8}}</style>
  229. </head><body><h1>5号机缸体振动分析</h1><ul>{links}</ul></body></html>""",
  230. encoding="utf-8",
  231. )
  232. print(f"[html] {out_dir / 'index.html'}")