"""用 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"{event['event_id']}{row.get('cylinder','')}{row.get('start_time','')}" f"{row.get('end_time','')}{row.get('direction','')}{row.get('level','')}" f"{row.get('confirmed','')}" for row in event_rows ) return f""" {event['event_id']} 缸体振动

{event['event_id']} · 事件缸 {event['cylinder']} · {event['description']}

灰色断档 = 停机/无运行数据;橙色区域 = 振动候选时间段;竖线 = 故障表日期。温度不参与这些标签。

异常分数(6 缸)

实际 RMS / 基线(6 缸)

实际峭度 / 基线(6 缸)

首周期波形对比(种子时刻,归一化)

事件验证

{table_rows}
事件缸开始结束方向等级多特征确认

返回索引

""" 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"
  • {event['event_id']} · {event['cylinder']} · {event['description']}
  • " for event in config.EVENTS ) (out_dir / "index.html").write_text( f"""5号机缸体振动

    5号机缸体振动分析

    """, encoding="utf-8", ) print(f"[html] {out_dir / 'index.html'}")