信号处理领域模型¶
领域驱动设计规范¶
基于 ADR-014(SOTA 信号处理)和 wifi-densepose-signal crate。
通用语言¶
| 术语 | 定义 |
|---|---|
| CsiFrame | 单个 CSI 测量:每个天线、每个子载波在一个时间戳处的幅度 + 相位 |
| 共轭乘法 | H_ref[k] * conj(H_target[k]) — 抵消 CFO/SFO/PDD,分离由环境引起的相位 |
| CSI 比值 | 两个天线流之间共轭乘法的复数结果 |
| Hampel 滤波器 | 运行中位数 +/- 缩放 MAD 异常值检测器;可抵抗高达 50% 的污染 |
| 相位净化 | 对原始 CSI 相位进行解卷绕、异常值去除、平滑和噪声滤波的流水线 |
| 频谱图 | 来自 STFT 的二维时频矩阵,是 WiFi 活动识别的标准 CNN 输入 |
| 子载波敏感度 | 方差比(运动方差 / 静态方差),用于对子载波对运动的响应程度进行排序 |
| 人体速度剖面(BVP) | 由多普勒导出的速度 x 时间二维矩阵;领域无关的运动表示 |
| 菲涅尔区 | TX 和 RX 之间发生信号反射/衍射的椭球区域 |
| 呼吸估计 | 由菲涅尔区边界穿越导出的 BPM + 幅度 + 置信度 |
| 运动评分 | 由方差、相关性、相位以及可选多普勒分量组成的综合值(0.0-1.0) |
| 存在状态 | 二元检测结果:有人/无人,并带有平滑后的置信度 |
| 校准 | 在已知空场期间记录基线方差,用于自适应检测 |
限界上下文¶
1. CSI 预处理上下文¶
职责:从原始测量中生成干净的、无硬件伪影的 CSI 数据。
+-----------------------------------------------------------+
| CSI Preprocessing Context |
+-----------------------------------------------------------+
| |
| +--------------+ +--------------+ +------------+ |
| | Conjugate | | Hampel | | Phase | |
| | Multiplication| | Filter | | Sanitizer | |
| +------+-------+ +------+-------+ +-----+------+ |
| | | | |
| v v v |
| +------+-------+ +------+-------+ +-----+------+ |
| | CsiRatio | | HampelResult | | Sanitized | |
| | (clean phase)| |(outlier-free)| | Phase | |
| +--------------+ +--------------+ +------------+ |
| | | | |
| +-------------------+------------------+ |
| | |
| v |
| +-------+--------+ |
| | CsiProcessor |--> CleanedCsiData |
| +----------------+ |
| |
+-----------------------------------------------------------+
聚合:CsiProcessor(聚合根)
值对象:CsiData、CsiRatio、HampelResult、HampelConfig、PhaseSanitizerConfig
领域服务:CsiPreprocessor、PhaseSanitizer
2. 特征提取上下文¶
职责:将干净的 CSI 数据转换为可用于机器学习的特征表示。
+-----------------------------------------------------------+
| Feature Extraction Context |
+-----------------------------------------------------------+
| |
| +--------------+ +--------------+ +------------+ |
| | STFT | | Subcarrier | | Doppler | |
| | Spectrogram | | Selection | | BVP Engine | |
| +------+-------+ +------+-------+ +-----+------+ |
| | | | |
| v v v |
| +------+-------+ +------+-------+ +-----+------+ |
| | Spectrogram | | Subcarrier | | BodyVel | |
| | (2D TF) | | Selection | | Profile | |
| +--------------+ +--------------+ +------------+ |
| | | | |
| +-------------------+------------------+ |
| | |
| v |
| +----------+----------+ |
| | FeatureExtractor |--> CsiFeatures |
| +---------------------+ |
| |
+-----------------------------------------------------------+
聚合:FeatureExtractor(聚合根)
值对象:Spectrogram、SubcarrierSelection、BodyVelocityProfile、CsiFeatures
领域服务:SpectrogramConfig、SubcarrierSelectionConfig、BvpConfig
3. 运动分析上下文¶
职责:从 CSI 特征中检测并分类人体运动和生命体征。
+-----------------------------------------------------------+
| Motion Analysis Context |
+-----------------------------------------------------------+
| |
| +--------------+ +--------------+ |
| | Motion | | Fresnel | |
| | Detector | | Breathing | |
| +------+-------+ +------+-------+ |
| | | |
| v v |
| +------+-------+ +------+-------+ |
| | MotionScore | | Breathing | |
| |+ Detection | | Estimate | |
| +--------------+ +--------------+ |
| | | |
| +-------------------+ |
| | |
| v |
| +--------+--------+ |
| | HumanDetection |--> PresenceState |
| | Result | |
| +-----------------+ |
| |
+-----------------------------------------------------------+
聚合:MotionDetector(聚合根)
值对象:MotionScore、MotionAnalysis、HumanDetectionResult、BreathingEstimate、FresnelGeometry
领域服务:FresnelBreathingEstimator
聚合¶
CsiProcessor (CSI 预处理根)¶
pub struct CsiProcessor {
config: CsiProcessorConfig,
preprocessor: CsiPreprocessor,
history: VecDeque<CsiData>,
previous_detection_confidence: f64,
statistics: ProcessingStatistics,
}
impl CsiProcessor {
/// Create with validated configuration
pub fn new(config: CsiProcessorConfig) -> Result<Self, CsiProcessorError>;
/// Full preprocessing pipeline: noise removal -> windowing -> normalization
pub fn preprocess(&self, csi_data: &CsiData) -> Result<CsiData, CsiProcessorError>;
/// Maintain temporal history for downstream feature extraction
pub fn add_to_history(&mut self, csi_data: CsiData);
/// Apply exponential moving average to detection confidence
pub fn apply_temporal_smoothing(&mut self, raw_confidence: f64) -> f64;
}
FeatureExtractor (特征提取根)¶
pub struct FeatureExtractor {
config: FeatureExtractorConfig,
}
impl FeatureExtractor {
/// Extract all feature types from a single CsiData snapshot
pub fn extract(&self, csi_data: &CsiData) -> CsiFeatures;
}
MotionDetector (运动分析根)¶
pub struct MotionDetector {
config: MotionDetectorConfig,
previous_confidence: f64,
motion_history: VecDeque<MotionScore>,
baseline_variance: Option<f64>,
}
impl MotionDetector {
/// Analyze motion from extracted features
pub fn analyze_motion(&self, features: &CsiFeatures) -> MotionAnalysis;
/// Full detection pipeline: analyze -> score -> smooth -> threshold
pub fn detect_human(&mut self, features: &CsiFeatures) -> HumanDetectionResult;
/// Record baseline variance for adaptive detection
pub fn calibrate(&mut self, features: &CsiFeatures);
}
值对象¶
CsiData¶
pub struct CsiData {
pub timestamp: DateTime<Utc>,
pub amplitude: Array2<f64>, // (num_antennas x num_subcarriers)
pub phase: Array2<f64>, // (num_antennas x num_subcarriers), radians
pub frequency: f64, // center frequency in Hz
pub bandwidth: f64, // bandwidth in Hz
pub num_subcarriers: usize,
pub num_antennas: usize,
pub snr: f64, // signal-to-noise ratio in dB
pub metadata: CsiMetadata,
}
Spectrogram¶
pub struct Spectrogram {
pub data: Array2<f64>, // (n_freq x n_time) power/magnitude
pub n_freq: usize, // frequency bins (window_size/2 + 1)
pub n_time: usize, // time frames
pub freq_resolution: f64, // Hz per bin
pub time_resolution: f64, // seconds per frame
}
SubcarrierSelection¶
pub struct SubcarrierSelection {
pub selected_indices: Vec<usize>, // ranked by sensitivity, descending
pub sensitivity_scores: Vec<f64>, // variance ratio for ALL subcarriers
pub selected_data: Option<Array2<f64>>, // filtered matrix (optional)
}
BodyVelocityProfile¶
pub struct BodyVelocityProfile {
pub data: Array2<f64>, // (n_velocity_bins x n_time_frames)
pub velocity_bins: Vec<f64>, // velocity value for each row (m/s)
pub n_time: usize,
pub time_resolution: f64, // seconds per frame
pub velocity_resolution: f64, // m/s per bin
}
BreathingEstimate¶
pub struct BreathingEstimate {
pub rate_bpm: f64, // breaths per minute
pub confidence: f64, // combined confidence (0.0-1.0)
pub period_seconds: f64, // estimated breathing period
pub autocorrelation_peak: f64, // periodicity quality
pub fresnel_confidence: f64, // Fresnel model match
pub amplitude_variation: f64, // observed amplitude variation
}
MotionScore¶
pub struct MotionScore {
pub total: f64, // weighted composite (0.0-1.0)
pub variance_component: f64,
pub correlation_component: f64,
pub phase_component: f64,
pub doppler_component: Option<f64>,
}
HampelResult¶
pub struct HampelResult {
pub filtered: Vec<f64>, // outliers replaced with local median
pub outlier_indices: Vec<usize>,
pub medians: Vec<f64>, // local median at each sample
pub sigma_estimates: Vec<f64>, // estimated local sigma at each sample
}
FresnelGeometry¶
pub struct FresnelGeometry {
pub d_tx_body: f64, // TX to body distance (meters)
pub d_body_rx: f64, // body to RX distance (meters)
pub frequency: f64, // carrier frequency (Hz)
}
impl FresnelGeometry {
pub fn wavelength(&self) -> f64;
pub fn fresnel_radius(&self, n: u32) -> f64;
pub fn phase_change(&self, displacement_m: f64) -> f64;
pub fn expected_amplitude_variation(&self, displacement_m: f64) -> f64;
}
领域事件¶
预处理事件¶
pub enum PreprocessingEvent {
/// Raw CSI frame cleaned through the full pipeline
FrameCleaned {
timestamp: DateTime<Utc>,
num_antennas: usize,
num_subcarriers: usize,
noise_filtered: bool,
windowed: bool,
normalized: bool,
},
/// Outliers detected and replaced by Hampel filter
OutliersDetected {
subcarrier_indices: Vec<usize>,
replacement_values: Vec<f64>,
contamination_ratio: f64,
},
/// Phase sanitization completed
PhaseSanitized {
method: UnwrappingMethod,
outliers_removed: usize,
smoothing_applied: bool,
},
}
特征提取事件¶
pub enum FeatureExtractionEvent {
/// Spectrogram computed from temporal CSI stream
SpectrogramGenerated {
n_time: usize,
n_freq: usize,
window_size: usize,
window_fn: WindowFunction,
},
/// Top-K sensitive subcarriers selected
SubcarriersSelected {
top_k_indices: Vec<usize>,
sensitivity_scores: Vec<f64>,
min_sensitivity_threshold: f64,
},
/// Body Velocity Profile extracted
BvpExtracted {
n_velocity_bins: usize,
n_time_frames: usize,
max_velocity: f64,
carrier_frequency: f64,
},
}
运动分析事件¶
pub enum MotionAnalysisEvent {
/// Human motion detected above threshold
MotionDetected {
score: MotionScore,
confidence: f64,
threshold: f64,
timestamp: DateTime<Utc>,
},
/// Breathing detected via Fresnel zone model
BreathingDetected {
rate_bpm: f64,
amplitude_variation: f64,
fresnel_confidence: f64,
autocorrelation_peak: f64,
},
/// Presence state changed (entered or left)
PresenceChanged {
previous: bool,
current: bool,
smoothed_confidence: f64,
timestamp: DateTime<Utc>,
},
/// Detector calibrated with baseline variance
BaselineCalibrated {
baseline_variance: f64,
timestamp: DateTime<Utc>,
},
}
不变量¶
CSI 预处理不变量¶
-
共轭乘法需要 >= 2 个天线单元。 如果
n_ant < 2,compute_ratio_matrix返回CsiRatioError::InsufficientAntennas。没有两个天线时,没有可配对以抵消共模偏移的天线对。 -
Hampel 滤波器窗口必须 >= 1(half_window > 0)。 零宽度窗口无法计算局部中位数。由
HampelError::InvalidWindow强制。 -
相位数据在清洗前必须位于配置范围内。 默认范围为
[-pi, pi]。由PhaseSanitizer::validate_phase_data强制。 -
共轭乘法要求天线流长度匹配。 如果
h_ref.len() != h_target.len(),conjugate_multiply返回CsiRatioError::LengthMismatch。
特征提取不变量¶
-
频谱图窗口大小必须 > 0,且信号必须 >= window_size 个采样点。 由
SpectrogramError::SignalTooShort和SpectrogramError::InvalidWindowSize强制。 -
子载波选择必须接收匹配的子载波数量。 运动和静态数据必须具有相同数量的列。由
SelectionError::SubcarrierCountMismatch强制。 -
BVP 需要 >= window_size 个时间采样点。 历史数据不足会阻止 STFT 计算。由
BvpError::InsufficientSamples强制。 -
BVP 载波频率必须 > 0 才能计算波长。 零频率会在多普勒到速度映射中产生除以零错误。
运动分析不变量¶
-
菲涅尔几何要求正距离(d_tx_body > 0,d_body_rx > 0)。 零或负距离在物理上不可能。由
FresnelError::InvalidDistance强制。 -
菲涅尔频率必须为正。 波长计算需要该条件。由
FresnelError::InvalidFrequency强制。 -
呼吸估计需要 >= 10 个幅度采样点。 更少的采样点无法支持自相关分析。由
FresnelError::InsufficientData强制。 -
运动检测器历史不超过配置的最大大小。 达到容量时,通过
VecDeque::pop_front淘汰最旧条目。
领域服务¶
CsiPreprocessor¶
编排单个 CSI 帧的清洗流水线。
pub struct CsiPreprocessor {
noise_threshold: f64,
}
impl CsiPreprocessor {
/// Remove subcarriers below noise floor (amplitude in dB < threshold)
pub fn remove_noise(&self, csi_data: &CsiData) -> Result<CsiData, CsiProcessorError>;
/// Apply Hamming window to reduce spectral leakage
pub fn apply_windowing(&self, csi_data: &CsiData) -> Result<CsiData, CsiProcessorError>;
/// Normalize amplitude to unit variance
pub fn normalize_amplitude(&self, csi_data: &CsiData) -> Result<CsiData, CsiProcessorError>;
}
PhaseSanitizer¶
完整的相位清洗流水线:解卷绕 -> 异常值移除 -> 平滑 -> 噪声过滤。
pub struct PhaseSanitizer {
config: PhaseSanitizerConfig,
statistics: SanitizationStatistics,
}
impl PhaseSanitizer {
/// Complete sanitization pipeline (all four stages)
pub fn sanitize_phase(
&mut self,
phase_data: &Array2<f64>,
) -> Result<Array2<f64>, PhaseSanitizationError>;
}
FresnelBreathingEstimator¶
基于菲涅尔区几何的物理呼吸检测。
pub struct FresnelBreathingEstimator {
geometry: FresnelGeometry,
min_displacement: f64, // 3mm default
max_displacement: f64, // 15mm default
}
impl FresnelBreathingEstimator {
/// Check if amplitude variation matches Fresnel breathing model
pub fn breathing_confidence(&self, observed_amplitude_variation: f64) -> f64;
/// Estimate breathing rate via autocorrelation + Fresnel validation
pub fn estimate_breathing_rate(
&self,
amplitude_signal: &[f64],
sample_rate: f64,
) -> Result<BreathingEstimate, FresnelError>;
}
上下文映射¶
+--------------------------------------------------------------+
| Signal Processing System |
+--------------------------------------------------------------+
| |
| +----------------+ Published +------------------+ |
| | CSI | Language | Feature | |
| | Preprocessing |------------>| Extraction | |
| | Context | CsiData | Context | |
| +-------+--------+ +--------+---------+ |
| | | |
| | Publishes | Publishes |
| | CleanedCsiData | CsiFeatures |
| v v |
| +-------+-------------------------------+---------+ |
| | Event Bus (Domain Events) | |
| +---------------------------+---------------------+ |
| | |
| | Subscribes |
| v |
| +---------+---------+ |
| | Motion | |
| | Analysis | |
| | Context | |
| +-------------------+ |
| |
+---------------------------------------------------------------+
| DOWNSTREAM (Customer/Supplier) |
| +-----------------+ +------------------+ +--------------+ |
| | wifi-densepose | | wifi-densepose | |wifi-densepose| |
| | -nn | | -mat | | -train | |
| | (consumes | | (consumes | |(consumes | |
| | CsiFeatures, | | BreathingEst, | | CsiFeatures) | |
| | Spectrogram) | | MotionScore) | | | |
| +-----------------+ +------------------+ +--------------+ |
+---------------------------------------------------------------+
| UPSTREAM (Conformist) |
| +-----------------+ +------------------+ |
| | wifi-densepose | | wifi-densepose | |
| | -core | | -hardware | |
| | (CsiFrame | | (ESP32 raw CSI | |
| | primitives) | | data ingestion) | |
| +-----------------+ +------------------+ |
+---------------------------------------------------------------+
关系类型: - Preprocessing -> Feature Extraction: 已发布语言(CsiData 是共享契约) - Preprocessing -> Motion Analysis: 客户/供应商(Preprocessing 提供清洗后的数据) - Feature Extraction -> Motion Analysis: 客户/供应商(Features 提供 CsiFeatures) - Signal -> wifi-densepose-nn: 客户/供应商(Signal 发布 Spectrogram、BVP) - Signal -> wifi-densepose-mat: 客户/供应商(Signal 发布 BreathingEstimate、MotionScore) - Signal <- wifi-densepose-core: 追随者(Signal 适配 core 的 CsiFrame 类型) - Signal <- wifi-densepose-hardware: 追随者(Signal 适配原始 ESP32 CSI 格式)
防腐层¶
硬件 ACL(上游)¶
将原始 ESP32 CSI 数据包转换为 signal crate 的 CsiData 值对象,并规范化硬件特定差异(LLTF/HT-LTF 格式差异、天线映射、空子载波处理)。
/// Normalizes vendor-specific CSI frames to canonical CsiData
pub struct HardwareNormalizer {
hardware_type: HardwareType,
}
impl HardwareNormalizer {
/// Convert raw hardware bytes to canonical CsiData
pub fn normalize(
&self,
raw_csi: &[u8],
hardware_type: HardwareType,
) -> Result<CanonicalCsiFrame, HardwareNormError>;
}
pub enum HardwareType {
Esp32S3,
Intel5300,
AtherosAr9580,
Simulation,
}
神经网络 ACL(下游)¶
将信号处理输出(Spectrogram、BVP、CsiFeatures)适配为 wifi-densepose-nn crate 所期望的张量格式。该边界可防止神经网络模型细节泄漏到信号处理领域。
/// Adapts signal crate types to neural network tensor format
pub struct SignalToTensorAdapter;
impl SignalToTensorAdapter {
/// Convert Spectrogram to CNN-ready 2D tensor
pub fn spectrogram_to_tensor(spec: &Spectrogram) -> Array2<f32> {
spec.data.mapv(|v| v as f32)
}
/// Convert BVP to domain-independent velocity tensor
pub fn bvp_to_tensor(bvp: &BodyVelocityProfile) -> Array2<f32> {
bvp.data.mapv(|v| v as f32)
}
/// Convert selected subcarrier data to reduced-dimension input
pub fn selected_csi_to_tensor(
selection: &SubcarrierSelection,
data: &Array2<f64>,
) -> Result<Array2<f32>, SelectionError> {
let extracted = extract_selected(data, selection)?;
Ok(extracted.mapv(|v| v as f32))
}
}
MAT ACL(下游)¶
为大规模伤亡评估工具适配运动分析输出,将领域通用的运动评分和呼吸估计转换为灾难场景下的生命体征。
/// Adapts signal processing outputs for disaster assessment
pub struct SignalToMatAdapter;
impl SignalToMatAdapter {
/// Convert BreathingEstimate to MAT-domain BreathingPattern
pub fn to_breathing_pattern(est: &BreathingEstimate) -> BreathingPattern {
BreathingPattern {
rate_bpm: est.rate_bpm as f32,
amplitude: est.amplitude_variation as f32,
regularity: est.autocorrelation_peak as f32,
pattern_type: classify_breathing_type(est.rate_bpm),
}
}
/// Convert MotionScore to MAT-domain presence indicator
pub fn to_presence_indicator(score: &MotionScore) -> PresenceIndicator {
PresenceIndicator {
detected: score.total > 0.3,
confidence: score.total,
motion_level: classify_motion_level(score),
}
}
}
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView