1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
| """ RuView WiFi CSI 感知系统仿真 座舱应用: 无摄像头 CPD/存在/呼吸检测
依赖: pip install numpy scipy scikit-learn matplotlib """
import numpy as np from scipy.signal import butter, filtfilt, find_peaks from typing import Tuple, List, Optional from dataclasses import dataclass import json
@dataclass class CSIFrame: """单帧 CSI 数据""" timestamp: float amplitudes: np.ndarray phases: np.ndarray
class CSISimulator: """ 模拟 WiFi CSI 信号 仿真座舱场景: - 乘员存在/不存在 - 呼吸引起的 CSI 相位变化 - 心跳微振动 - 多人干扰 """ NUM_SUBCARRIERS = 56 CSI_RATE = 1000 def __init__(self, sample_rate: int = 1000, duration_sec: float = 10.0): self.fs = sample_rate self.N = int(duration_sec * sample_rate) self.t = np.linspace(0, duration_sec, self.N) def generate_csi(self, presence: bool = True, breathing_rate: float = 0.25, heart_rate: float = 1.2, num_persons: int = 1, noise_level: float = 0.1) -> np.ndarray: """ 生成模拟 CSI 信号 Args: presence: 是否有人 breathing_rate: 呼吸频率 heart_rate: 心率 num_persons: 人数 noise_level: 噪声水平 Returns: csi: shape=(N_subcarriers, N_samples) CSI 振幅时间序列 """ csi = np.zeros((self.NUM_SUBCARRIERS, self.N)) for sc in range(self.NUM_SUBCARRIERS): signal = np.ones(self.N) * 0.5 if presence: breath_mod = 0.02 * np.sin(2 * np.pi * breathing_rate * self.t) breath_mod *= np.sin(sc * 0.3 + 0.5) heart_mod = 0.002 * np.sin(2 * np.pi * heart_rate * self.t) heart_mod *= np.cos(sc * 0.5) if num_persons > 1: for p in range(1, num_persons): breath_mod += 0.015 * np.sin( 2 * np.pi * (breathing_rate + 0.02*p) * self.t + p ) breath_mod *= 0.8 signal += breath_mod + heart_mod noise = np.random.normal(0, noise_level, self.N) csi[sc] = signal + noise return csi def extract_phase(self, csi: np.ndarray) -> np.ndarray: """提取相位信息 (简化: 从振幅变化推断)""" return np.angle(np.fft.fft(csi, axis=1))
class RuViewProcessor: """ RuView CSI 信号处理器 功能: 1. 存在检测 2. 呼吸率估计 3. 心率估计 4. 多人计数 5. 跌倒检测 """ def __init__(self, sample_rate: int = 1000): self.fs = sample_rate def detect_presence(self, csi: np.ndarray, threshold: float = 0.005) -> dict: """ 存在检测: 基于 CSI 方差 有人 → 方差大 (呼吸/心跳引起波动) 无人 → 方差小 (仅环境噪声) """ variance = np.var(csi, axis=1).mean() is_present = variance > threshold if variance > 0.05: confidence = 0.95 elif variance > threshold: confidence = 0.82 else: confidence = 0.10 return { 'present': is_present, 'confidence': float(confidence), 'variance': float(variance), 'threshold': threshold } def estimate_breathing_rate(self, csi: np.ndarray) -> dict: """ 呼吸率估计 方法: 带通滤波 0.1-0.5 Hz → FFT 峰值 """ variances = np.var(csi, axis=1) best_sc = np.argmax(variances) signal = csi[best_sc] nyq = self.fs / 2 b, a = butter(4, [0.1/nyq, 0.5/nyq], btype='band') filtered = filtfilt(b, a, signal) fft = np.abs(np.fft.rfft(filtered)) freqs = np.fft.rfftfreq(len(filtered), d=1/self.fs) mask = (freqs >= 0.1) & (freqs <= 0.5) if mask.sum() > 0: peak_idx = np.argmax(fft[mask]) breath_freq = freqs[mask][peak_idx] breath_bpm = breath_freq * 60 snr = fft[mask][peak_idx] / (np.mean(fft[mask]) + 1e-8) else: breath_bpm = 0 snr = 0 return { 'breathing_rate_bpm': float(breath_bpm), 'breathing_rate_hz': float(breath_freq) if mask.sum() > 0 else 0, 'snr': float(snr), 'best_subcarrier': int(best_sc) } def estimate_heart_rate(self, csi: np.ndarray) -> dict: """ 心率估计 方法: 带通 0.8-2.0 Hz → FFT 峰值 """ variances = np.var(csi, axis=1) best_sc = np.argmax(variances) signal = csi[best_sc] nyq = self.fs / 2 b, a = butter(4, [0.8/nyq, 2.0/nyq], btype='band') filtered = filtfilt(b, a, signal) fft = np.abs(np.fft.rfft(filtered)) freqs = np.fft.rfftfreq(len(filtered), d=1/self.fs) mask = (freqs >= 0.8) & (freqs <= 2.0) if mask.sum() > 0: peak_idx = np.argmax(fft[mask]) heart_freq = freqs[mask][peak_idx] heart_bpm = heart_freq * 60 snr = fft[mask][peak_idx] / (np.mean(fft[mask]) + 1e-8) else: heart_bpm = 0 snr = 0 return { 'heart_rate_bpm': float(heart_bpm), 'snr': float(snr) } def count_persons(self, csi: np.ndarray, dedup_factor: float = 0.7) -> dict: """ 多人计数 方法: 自适应 P95 归一化 + 去重因子 """ variances = np.var(csi, axis=1) p95 = np.percentile(variances, 95) normalized = variances / (p95 + 1e-8) total_energy = np.sum(normalized) raw_count = total_energy / 0.5 estimated_count = max(1, int(raw_count * dedup_factor)) return { 'count': estimated_count, 'confidence': float(min(1.0, total_energy / 3.0)), 'raw_energy': float(total_energy) } def detect_fall(self, csi: np.ndarray, threshold: float = 0.5, debounce_frames: int = 3) -> dict: """ 跌倒检测 方法: 相位加速度阈值 + 去抖 """ variances = np.var(csi, axis=1) best_sc = np.argmax(variances) signal = csi[best_sc] accel = np.diff(signal, n=2) accel_power = np.abs(accel) ** 2 fall_events = accel_power > threshold fall_detected = False fall_time = None for i in range(len(fall_events)): if fall_events[i]: consecutive = np.sum(fall_events[i:i+debounce_frames]) if consecutive >= debounce_frames: fall_detected = True fall_time = i / self.fs break return { 'fall_detected': fall_detected, 'fall_time': fall_time, 'max_acceleration': float(np.max(accel_power)), 'threshold': threshold }
if __name__ == "__main__": print("=" * 70) print("RuView WiFi CSI 座舱感知系统测试") print("=" * 70) sim = CSISimulator(sample_rate=1000, duration_sec=10.0) proc = RuViewProcessor(sample_rate=1000) print("\n=== 场景1: 空座 ===") csi_empty = sim.generate_csi(presence=False, noise_level=0.01) presence = proc.detect_presence(csi_empty) breath = proc.estimate_breathing_rate(csi_empty) print(f"存在: {presence}") print(f"呼吸: {breath['breathing_rate_bpm']:.0f} bpm (SNR={breath['snr']:.2f})") print("\n=== 场景2: 正常驾驶 (1人) ===") csi_normal = sim.generate_csi( presence=True, breathing_rate=0.25, heart_rate=1.2, num_persons=1, noise_level=0.05 ) presence = proc.detect_presence(csi_normal) breath = proc.estimate_breathing_rate(csi_normal) heart = proc.estimate_heart_rate(csi_normal) count = proc.count_persons(csi_normal) print(f"存在: {presence}") print(f"呼吸: {breath['breathing_rate_bpm']:.0f} bpm (SNR={breath['snr']:.2f})") print(f"心率: {heart['heart_rate_bpm']:.0f} bpm (SNR={heart['snr']:.2f})") print(f"人数: {count}") print("\n=== 场景3: 儿童睡眠 (后排) ===") csi_child = sim.generate_csi( presence=True, breathing_rate=0.35, heart_rate=1.5, num_persons=1, noise_level=0.08 ) presence = proc.detect_presence(csi_child) breath = proc.estimate_breathing_rate(csi_child) heart = proc.estimate_heart_rate(csi_child) print(f"存在: {presence}") print(f"呼吸: {breath['breathing_rate_bpm']:.0f} bpm (儿童正常: 20-30)") print(f"心率: {heart['heart_rate_bpm']:.0f} bpm (儿童正常: 80-120)") print("\n=== 场景4: 多人 (2大1小) ===") csi_multi = sim.generate_csi( presence=True, breathing_rate=0.25, heart_rate=1.2, num_persons=3, noise_level=0.1 ) count = proc.count_persons(csi_multi) presence = proc.detect_presence(csi_multi) print(f"存在: {presence}") print(f"人数: {count} (实际: 3)") print("\n=== 场景5: 跌倒检测 ===") csi_fall = sim.generate_csi( presence=True, breathing_rate=0.25, heart_rate=1.2, noise_level=0.3 ) csi_fall[20, 3000:3020] += 2.0 fall = proc.detect_fall(csi_fall) print(f"跌倒检测: {fall}") print(f"\n=== 技术对比 ===") print(f"{'技术':<15s} {'成本':>8s} {'隐私':>6s} {'穿透':>6s} {'部署':>6s}") print(f"{'WiFi CSI':<15s} {'$9/节点':>8s} {'✅':>6s} {'✅':>6s} {'简单':>6s}") print(f"{'毫米波雷达':<15s} {'$8-50':>8s} {'✅':>6s} {'✅':>6s} {'中等':>6s}") print(f"{'摄像头':<15s} {'$15-30':>8s} {'❌':>6s} {'❌':>6s} {'中等':>6s}") print(f"{'PIR传感器':<15s} {'$2-5':>8s} {'✅':>6s} {'❌':>6s} {'简单':>6s}") print(f"{'UWB雷达':<15s} {'$10-20':>8s} {'✅':>6s} {'部分':>6s} {'中等':>6s}")
|