| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253 |
- """用 HTML + ECharts 输出交互图。"""
- from __future__ import annotations
- import json
- from datetime import timedelta
- from pathlib import Path
- import numpy as np
- import pandas as pd
- from . import config, data
- COLORS = {
- "一缸": "#c0392b",
- "二缸": "#e67e22",
- "三缸": "#16a085",
- "四缸": "#2980b9",
- "五缸": "#8e44ad",
- "六缸": "#7f8c8d",
- }
- def _nearest_time(times: list[str], target) -> str:
- target = pd.Timestamp(target)
- parsed = pd.to_datetime(pd.Series(times))
- index = (parsed - target).abs().idxmin()
- return times[int(index)]
- def _aligned(part: pd.DataFrame, times: list[str], cylinder: str, column: str) -> list[float | None]:
- group = part[part["cylinder"] == cylinder].sort_values("sample_time")
- if group.empty:
- return [None] * len(times)
- values = dict(zip(group["sample_time"].dt.strftime("%Y-%m-%d %H:%M:%S"), group[column]))
- return [None if pd.isna(values.get(time)) else float(values[time]) for time in times]
- def _chart_common(times: list[str], fault_time: str, intervals: pd.DataFrame, cylinder: str) -> dict:
- areas = []
- part = intervals[intervals["cylinder"] == cylinder]
- for row in part.itertuples(index=False):
- areas.append([
- {"xAxis": _nearest_time(times, row.start_time)},
- {"xAxis": _nearest_time(times, row.end_time)},
- ])
- return {
- "tooltip": {"trigger": "axis"},
- "legend": {"top": 0, "type": "scroll"},
- "grid": {"left": 45, "right": 20, "top": 35, "bottom": 55},
- "xAxis": {
- "type": "category",
- "data": times,
- "axisLabel": {"rotate": 30, "fontSize": 9},
- },
- "yAxis": {"type": "value", "scale": True},
- "dataZoom": [
- {"type": "inside", "start": 0, "end": 100},
- {"type": "slider", "height": 18, "bottom": 10},
- ],
- "markLine": {
- "symbol": "none",
- "silent": True,
- "label": {"formatter": "fault"},
- "lineStyle": {"color": "#2c3e50", "width": 1.2},
- "data": [{"xAxis": fault_time}],
- },
- }
- def _waveform_option(frame: pd.DataFrame, intervals: pd.DataFrame, event: dict) -> dict | None:
- cylinder = event["cylinder"]
- candidates = intervals[intervals["cylinder"] == cylinder]
- if candidates.empty:
- return None
- seed = candidates.loc[candidates["max_score"].idxmax()]
- seed_time = pd.Timestamp(seed["max_time"])
- rows = {}
- for name in config.CYLINDERS:
- group = frame[frame["cylinder"] == name]
- if group.empty:
- continue
- distance = (group["sample_time"] - seed_time).abs()
- index = distance.idxmin()
- if distance.loc[index] <= pd.Timedelta(hours=2):
- rows[name] = group.loc[index]
- if not rows:
- return None
- samples = data.fetch_samples([int(row["id"]) for row in rows.values()])
- series = []
- for name, row in rows.items():
- signal = samples.get(int(row["id"]))
- if signal is None or signal.size == 0:
- continue
- scale = float(np.sqrt(np.mean(signal ** 2))) or 1.0
- fs = float(row["sample_frequency_hz"] or 0) or 25600.0
- x = np.arange(signal.size) / fs * 1000.0
- series.append(
- {
- "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
- "type": "line",
- "showSymbol": False,
- "sampling": "lttb",
- "lineStyle": {"width": 2.2 if name == cylinder else 1.0},
- "itemStyle": {"color": "#c0392b" if name == cylinder else COLORS[name]},
- "data": [[round(float(x[i]), 3), round(float(signal[i] / scale), 4)] for i in range(signal.size)],
- }
- )
- return {
- "tooltip": {"trigger": "axis"},
- "legend": {"top": 0},
- "grid": {"left": 50, "right": 20, "top": 35, "bottom": 45},
- "xAxis": {"type": "value", "name": "ms", "scale": True},
- "yAxis": {"type": "value", "name": "normalized amplitude", "scale": True},
- "dataZoom": [{"type": "inside"}, {"type": "slider", "height": 18, "bottom": 10}],
- "series": series,
- }
- def _page(event: dict, frame: pd.DataFrame, intervals: pd.DataFrame, validation: pd.DataFrame) -> str:
- center = pd.Timestamp(event["date"])
- start = center - pd.Timedelta(days=10)
- end = center + pd.Timedelta(days=3)
- part = frame[(frame["sample_time"] >= start) & (frame["sample_time"] <= end)].copy()
- part["time"] = part["sample_time"].dt.strftime("%Y-%m-%d %H:%M:%S")
- times = sorted(part["time"].unique().tolist())
- fault_time = _nearest_time(times, center)
- base = _chart_common(times, fault_time, intervals, event["cylinder"])
- score_series = []
- rms_series = []
- kurt_series = []
- for name in config.CYLINDERS:
- color = "#c0392b" if name == event["cylinder"] else COLORS[name]
- width = 2.4 if name == event["cylinder"] else 1.0
- score_series.append(
- {
- "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
- "type": "line",
- "showSymbol": False,
- "sampling": "lttb",
- "connectNulls": False,
- "lineStyle": {"width": width},
- "itemStyle": {"color": color},
- "data": _aligned(part, times, name, "score"),
- }
- )
- rms_series.append(
- {
- "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
- "type": "line",
- "showSymbol": False,
- "sampling": "lttb",
- "connectNulls": False,
- "lineStyle": {"width": width},
- "itemStyle": {"color": color},
- "data": _aligned(part, times, name, "rms_ratio"),
- }
- )
- kurt_series.append(
- {
- "name": f"cyl{config.CYLINDER_TO_INDEX[name]}",
- "type": "line",
- "showSymbol": False,
- "sampling": "lttb",
- "connectNulls": False,
- "lineStyle": {"width": width},
- "itemStyle": {"color": color},
- "data": _aligned(part, times, name, "kurt_ratio"),
- }
- )
- score_series[0]["markArea"] = {
- "silent": True,
- "itemStyle": {"color": "rgba(230,126,34,0.15)"},
- "data": [
- [
- {"xAxis": _nearest_time(times, row.start_time)},
- {"xAxis": _nearest_time(times, row.end_time)},
- ]
- for row in intervals[intervals["cylinder"] == event["cylinder"]].itertuples(index=False)
- ],
- }
- score_series[0]["markLine"] = base.pop("markLine")
- score_option = {**base, "yAxis": {"type": "value", "name": "score", "scale": True}, "series": score_series}
- rms_option = {**base, "yAxis": {"type": "value", "name": "RMS / baseline", "scale": True}, "series": rms_series}
- kurt_option = {**base, "yAxis": {"type": "value", "name": "kurtosis / baseline", "scale": True}, "series": kurt_series}
- wave_option = _waveform_option(frame, intervals, event)
- event_rows = validation[validation["event_id"] == event["event_id"]].to_dict("records")
- table_rows = "".join(
- f"<tr><td>{event['event_id']}</td><td>{row.get('cylinder','')}</td><td>{row.get('start_time','')}</td>"
- f"<td>{row.get('end_time','')}</td><td>{row.get('direction','')}</td><td>{row.get('level','')}</td>"
- f"<td>{row.get('confirmed','')}</td></tr>"
- for row in event_rows
- )
- return f"""<!doctype html>
- <html lang="zh-CN"><head><meta charset="utf-8"><title>{event['event_id']} 缸体振动</title>
- <style>
- body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;margin:18px;color:#222;background:#fff}}
- h1{{font-size:22px;margin:0 0 8px}} h2{{font-size:16px;margin:22px 0 8px}}
- .chart{{width:100%;height:380px;border:1px solid #eee;border-radius:6px;margin-bottom:14px}}
- .note{{color:#666;font-size:13px;line-height:1.6}} table{{border-collapse:collapse;margin-top:8px;font-size:13px}}
- th,td{{border:1px solid #ddd;padding:6px 10px;text-align:left}} th{{background:#f7f7f7}}
- a{{color:#1a73e8;text-decoration:none}}
- </style></head><body>
- <h1>{event['event_id']} · 事件缸 {event['cylinder']} · {event['description']}</h1>
- <div class="note">灰色断档 = 停机/无运行数据;橙色区域 = 振动候选时间段;竖线 = 故障表日期。温度不参与这些标签。</div>
- <h2>异常分数(6 缸)</h2><div id="score" class="chart"></div>
- <h2>实际 RMS / 基线(6 缸)</h2><div id="rms" class="chart"></div>
- <h2>实际峭度 / 基线(6 缸)</h2><div id="kurt" class="chart"></div>
- <h2>首周期波形对比(种子时刻,归一化)</h2><div id="wave" class="chart"></div>
- <h2>事件验证</h2>
- <table><thead><tr><th>事件</th><th>缸</th><th>开始</th><th>结束</th><th>方向</th><th>等级</th><th>多特征确认</th></tr></thead>
- <tbody>{table_rows}</tbody></table>
- <p class="note"><a href="index.html">返回索引</a></p>
- <script src="echarts.min.js"></script>
- <script>
- const scoreOption = {json.dumps(score_option, ensure_ascii=False)};
- const rmsOption = {json.dumps(rms_option, ensure_ascii=False)};
- const kurtOption = {json.dumps(kurt_option, ensure_ascii=False)};
- const waveOption = {json.dumps(wave_option, ensure_ascii=False) if wave_option else 'null'};
- const charts = [
- [echarts.init(document.getElementById('score')), scoreOption],
- [echarts.init(document.getElementById('rms')), rmsOption],
- [echarts.init(document.getElementById('kurt')), kurtOption],
- ];
- if (waveOption) charts.push([echarts.init(document.getElementById('wave')), waveOption]);
- for (const [chart, option] of charts) chart.setOption(option);
- window.addEventListener('resize', () => charts.forEach(([chart]) => chart.resize()));
- </script>
- </body></html>"""
- def export_html(frame: pd.DataFrame, intervals: pd.DataFrame, validation: pd.DataFrame) -> None:
- out_dir = config.OUTPUT_DIR / "html"
- out_dir.mkdir(parents=True, exist_ok=True)
- for event in config.EVENTS:
- path = out_dir / f"event_{event['event_id']}.html"
- path.write_text(_page(event, frame, intervals, validation), encoding="utf-8")
- print(f"[html] {path}")
- links = "".join(
- f"<li><a href=\"event_{event['event_id']}.html\">{event['event_id']} · {event['cylinder']} · {event['description']}</a></li>"
- for event in config.EVENTS
- )
- (out_dir / "index.html").write_text(
- f"""<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>5号机缸体振动</title>
- <style>body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif;margin:24px}}a{{color:#1a73e8}}</style>
- </head><body><h1>5号机缸体振动分析</h1><ul>{links}</ul></body></html>""",
- encoding="utf-8",
- )
- print(f"[html] {out_dir / 'index.html'}")
|