소스 검색

feat: add fault frequency peak evidence and attach evidence to alarms

zhouyang.xie 2 주 전
부모
커밋
7deaeca736
3개의 변경된 파일과 263개의 추가작업 그리고 3개의 파일을 삭제
  1. 21 0
      app/routers/fault_frequency.py
  2. 52 3
      app/routers/vibration_alarm.py
  3. 190 0
      app/services/fault_frequency_evidence.py

+ 21 - 0
app/routers/fault_frequency.py

@@ -7,6 +7,7 @@ from fastapi import APIRouter
 from fastapi.responses import JSONResponse
 
 from app.services.fault_frequency import FaultFrequencyService
+from app.services.fault_frequency_evidence import FaultFrequencyEvidenceService
 
 router = APIRouter(prefix="/fault-frequency", tags=["fault-frequency"])
 
@@ -25,3 +26,23 @@ async def resolve(
         return JSONResponse(status_code=400, content={"code": 400, "message": str(exc)})
     except Exception as exc:
         return JSONResponse(status_code=500, content={"code": 500, "message": f"故障频率解析失败:{exc}"})
+
+
+@router.get("/evidence")
+async def evidence(
+    windCode: str,
+    recordId: int,
+    engineCode: str,
+    pointName: str,
+    rpm: float = 0,
+    millTypeCode: Optional[str] = None,
+):
+    try:
+        service = FaultFrequencyEvidenceService(
+            windCode, engineCode, pointName, recordId, rpm, millTypeCode
+        )
+        return service.analyze()
+    except ValueError as exc:
+        return JSONResponse(status_code=400, content={"code": 400, "message": str(exc)})
+    except Exception as exc:
+        return JSONResponse(status_code=500, content={"code": 500, "message": f"峰值证据分析失败:{exc}"})

+ 52 - 3
app/routers/vibration_alarm.py

@@ -14,7 +14,9 @@ import numpy as np
 from fastapi import APIRouter
 from pydantic import BaseModel
 
+from app.logger import logger
 from app.report.collector import business_conn, platform_conn, safe_code
+from app.services.fault_frequency_evidence import FaultFrequencyEvidenceService
 
 router = APIRouter(prefix="/vibration-alarm", tags=["vibration-alarm"])
 
@@ -102,7 +104,7 @@ async def evaluate(inp: EvaluateInput):
         with conn.cursor() as cur:
             cur.execute(
                 f"SELECT id, time_stamp, sampling_frequency, wind_turbine_number, "
-                f"mesure_point_name, mesure_data FROM `{wind_code}_wave` "
+                f"mesure_point_name, rotational_speed, mesure_data FROM `{wind_code}_wave` "
                 f"WHERE {where_sql} ORDER BY id DESC LIMIT %s",
                 params + [limit],
             )
@@ -156,17 +158,59 @@ async def evaluate(inp: EvaluateInput):
                     level, threshold = 1, warn_threshold
                 else:
                     continue
+
+                fault_type = None
+                characteristic_freq = None
+                fault_order = None
+                spec_source = None
+                diagnosis_detail = None
+                # 对已越限的记录补充特征频率峰值证据;失败不影响 RMS 报警
+                try:
+                    evidence = FaultFrequencyEvidenceService(
+                        wind_code,
+                        row["wind_turbine_number"],
+                        row["mesure_point_name"],
+                        row["id"],
+                        float(row.get("rotational_speed") or 0),
+                    ).analyze()
+                    if evidence.get("supported"):
+                        rank = {"normal": 0, "watch": 1, "alarm": 2}
+                        best = max(
+                            evidence.get("evidences") or [],
+                            key=lambda e: rank.get(e.get("status"), -1),
+                            default=None,
+                        )
+                        if best and best.get("status") in ("watch", "alarm"):
+                            fault_type = best.get("faultType")
+                            characteristic_freq = best.get("peakFreq") or best.get("targetFreq")
+                            fault_order = best.get("order")
+                            spec_source = evidence.get("source")
+                            diagnosis_detail = (
+                                f"{fault_type} 目标 {best.get('targetFreq')} Hz,"
+                                f"峰值 {best.get('peakFreq')} Hz,"
+                                f"峰值/基线 {best.get('ratio')},"
+                                f"状态 {best.get('status')}"
+                            )
+                except Exception as exc:
+                    logger.warning("报警特征频率证据失败 id=%s: %s", row.get("id"), exc)
+
                 cur.execute(
                     """
                     INSERT INTO vibration_alarm_event
                     (wind_code, turbine_code, point_name, data_time, alarm_time,
                      alarm_level, alarm_status, trigger_value, threshold_value,
-                     unit, rule_name, batch_code, detail)
+                     unit, rule_name, batch_code, detail,
+                     fault_type, characteristic_freq, fault_order, spec_source, diagnosis_detail)
                     VALUES (%s,%s,%s,%s,%s,%s,'active',%s,%s,'m/s2',
-                            '加速度RMS相对基线',%s,%s)
+                            '加速度RMS相对基线',%s,%s,%s,%s,%s,%s,%s)
                     ON DUPLICATE KEY UPDATE
                       trigger_value=VALUES(trigger_value),
                       threshold_value=VALUES(threshold_value),
+                      fault_type=VALUES(fault_type),
+                      characteristic_freq=VALUES(characteristic_freq),
+                      fault_order=VALUES(fault_order),
+                      spec_source=VALUES(spec_source),
+                      diagnosis_detail=VALUES(diagnosis_detail),
                       updated_at=NOW()
                     """,
                     (
@@ -180,6 +224,11 @@ async def evaluate(inp: EvaluateInput):
                         round(threshold, 6),
                         f"batch-{now:%Y%m%d%H%M%S}",
                         f"RMS={rms:.6f},P90={p90:.6f},P98={p98:.6f}",
+                        fault_type,
+                        characteristic_freq,
+                        fault_order,
+                        spec_source,
+                        diagnosis_detail,
                     ),
                 )
                 inserted += 1

+ 190 - 0
app/services/fault_frequency_evidence.py

@@ -0,0 +1,190 @@
+"""故障频率峰值证据分析。
+
+在包络谱/速度谱中搜索 BPFO/BPFI/BSF/FTF/GMF 及谐波峰值,
+返回峰值频率、幅值、相对基线和判定建议,作为诊断证据。
+"""
+from __future__ import annotations
+
+import ast
+import math
+from typing import Any, Dict, List, Optional
+
+import numpy as np
+from scipy.signal import butter, hilbert, sosfiltfilt
+
+from app.report.collector import business_conn, safe_code
+from app.services.fault_frequency import FaultFrequencyService
+
+
+def _spectrum(values: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
+    values = np.asarray(values, dtype=float)
+    values = values[np.isfinite(values)]
+    values = values - np.mean(values)
+    if values.size < 32:
+        return np.array([]), np.array([])
+    window = np.hanning(values.size)
+    spec = np.abs(np.fft.rfft(values * window)) / max(values.size, 1) * 2
+    freq = np.fft.rfftfreq(values.size, 1.0 / fs)
+    return freq, spec
+
+
+def _peak_near(freq: np.ndarray, spec: np.ndarray, target: float, tolerance: float = 0.05) -> Dict[str, Any]:
+    if freq.size == 0 or target <= 0:
+        return {"found": False, "peak": 0.0, "peakFreq": None, "ratio": 0.0, "noise": 0.0}
+    df = float(freq[1] - freq[0]) if freq.size > 1 else 1.0
+    band = max(target * tolerance, df * 1.5)
+    mask = (freq >= max(0.0, target - band)) & (freq <= target + band)
+    if not mask.any():
+        return {"found": False, "peak": 0.0, "peakFreq": None, "ratio": 0.0, "noise": 0.0}
+    idx = np.where(mask)[0]
+    local = idx[np.argmax(spec[idx])]
+    peak = float(spec[local])
+    # 取目标附近之外的频谱中位数作为噪声基线
+    noise_mask = (freq > max(0.0, target - band * 3)) & (freq < target + band * 3)
+    noise = float(np.median(spec[~noise_mask])) if (~noise_mask).any() else float(np.median(spec))
+    ratio = peak / noise if noise > 0 else 0.0
+    return {
+        "found": True,
+        "peak": round(peak, 6),
+        "peakFreq": round(float(freq[local]), 3),
+        "ratio": round(float(ratio), 2),
+        "noise": round(noise, 6),
+    }
+
+
+def _envelope_spectrum(signal: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
+    signal = np.asarray(signal, dtype=float)
+    signal = signal[np.isfinite(signal)]
+    signal = signal - np.mean(signal)
+    low = 500.0
+    high = min(fs / 2.56, 10000.0)
+    if high <= low or signal.size < 32:
+        return np.array([]), np.array([])
+    sos = butter(4, [low, high], btype="bandpass", fs=fs, output="sos")
+    band = sosfiltfilt(sos, signal)
+    env = np.abs(hilbert(band))
+    return _spectrum(env, fs)
+
+
+def _velocity_spectrum(signal: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
+    signal = np.asarray(signal, dtype=float)
+    signal = signal[np.isfinite(signal)]
+    signal = signal - np.mean(signal)
+    freq, spec = _spectrum(signal, fs)
+    if freq.size == 0:
+        return freq, spec
+    vel = np.zeros_like(spec)
+    nz = freq > 0.5
+    vel[nz] = spec[nz] / (2 * math.pi * freq[nz])
+    return freq, vel
+
+
+def _status_for_ratio(ratio: float, peak: float) -> str:
+    # 相对峰值/中位基线,阈值先保守设置,避免正常数据被误报
+    if ratio >= 20.0 and peak > 0:
+        return "alarm"
+    if ratio >= 10.0 and peak > 0:
+        return "watch"
+    return "normal"
+
+
+class FaultFrequencyEvidenceService:
+    def __init__(self, wind_code: str, engine_code: str, point_name: str,
+                 record_id: int, rpm: float = 0, mill_type_code: Optional[str] = None):
+        self.wind_code = safe_code(wind_code)
+        self.engine_code = engine_code
+        self.point_name = point_name
+        self.record_id = int(record_id)
+        self.rpm = float(rpm or 0)
+        self.mill_type_code = mill_type_code
+
+    def analyze(self) -> Dict[str, Any]:
+        resolved = FaultFrequencyService(
+            self.engine_code, self.point_name, self.rpm, self.mill_type_code
+        ).resolve()
+        if not resolved.get("supported"):
+            return {"code": 200, "supported": False, **resolved}
+
+        conn = business_conn()
+        try:
+            with conn.cursor() as cur:
+                cur.execute(
+                    f"SELECT id, mesure_data, sampling_frequency, rotational_speed "
+                    f"FROM `{self.wind_code}_wave` WHERE id=%s",
+                    (self.record_id,),
+                )
+                row = cur.fetchone()
+        finally:
+            conn.close()
+        if not row:
+            return {"code": 200, "supported": False, "message": "波形记录不存在", "frequencies": {}}
+
+        try:
+            values = ast.literal_eval(row["mesure_data"])
+            signal = np.asarray(values, dtype=float)
+        except Exception as exc:
+            return {"code": 200, "supported": False, "message": f"波形解析失败:{exc}", "frequencies": {}}
+
+        fs = float(row.get("sampling_frequency") or 0)
+        rpm = float(row.get("rotational_speed") or self.rpm or 0)
+        if fs < 12800:
+            return {
+                "code": 200,
+                "supported": False,
+                "message": f"采样频率 {fs:g} Hz 低于 12800 Hz,无法做包络峰值分析",
+                "frequencies": {},
+            }
+
+        # 用波形自身的 rpm 重新计算轴速,避免前端 rpm 与数据不一致
+        resolved = FaultFrequencyService(
+            self.engine_code, self.point_name, rpm, self.mill_type_code
+        ).resolve()
+        if not resolved.get("supported"):
+            return {"code": 200, **resolved}
+
+        env_freq, env_spec = _envelope_spectrum(signal, fs)
+        vel_freq, vel_spec = _velocity_spectrum(signal, fs)
+        fr = max(float(resolved.get("shaftRpm") or rpm) / 60.0, 1e-6)
+        evidences: List[Dict[str, Any]] = []
+        for fault_type, target in (resolved.get("frequencies") or {}).items():
+            if fault_type == "GMF":
+                peak = _peak_near(vel_freq, vel_spec, float(target))
+                method = "velocity"
+            else:
+                peak = _peak_near(env_freq, env_spec, float(target))
+                method = "envelope"
+            harmonics = []
+            for h in (2, 3):
+                hp = _peak_near(env_freq if method == "envelope" else vel_freq,
+                                env_spec if method == "envelope" else vel_spec,
+                                float(target) * h)
+                if hp.get("found"):
+                    harmonics.append({"order": h, **hp})
+            evidences.append({
+                "faultType": fault_type,
+                "targetFreq": round(float(target), 3),
+                "order": round(float(target) / fr, 2) if fr > 0 else None,
+                "method": method,
+                **peak,
+                "harmonics": harmonics,
+                "status": _status_for_ratio(float(peak.get("ratio") or 0), float(peak.get("peak") or 0)),
+            })
+
+        return {
+            "code": 200,
+            "supported": True,
+            "engineCode": self.engine_code,
+            "windCode": self.wind_code,
+            "recordId": self.record_id,
+            "pointName": self.point_name,
+            "samplingFrequency": fs,
+            "rpm": round(rpm, 3),
+            "component": resolved.get("componentType"),
+            "brand": resolved.get("brand"),
+            "model": resolved.get("model"),
+            "shaftRpm": resolved.get("shaftRpm"),
+            "frequencies": resolved.get("frequencies"),
+            "evidences": evidences,
+            "source": resolved.get("source"),
+            "warnings": resolved.get("warnings", []),
+        }