"""故障频率峰值证据分析。 在包络谱/速度谱中搜索 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, "machineTypeCode": resolved.get("machineTypeCode"), "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", []), }