-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathlrn_dtw_gesture_learn.rs
More file actions
509 lines (449 loc) · 17.5 KB
/
lrn_dtw_gesture_learn.rs
File metadata and controls
509 lines (449 loc) · 17.5 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! User-teachable gesture recognition via DTW template learning.
//!
//! ADR-041 adaptive learning module — Event IDs 730-733.
//!
//! Allows users to teach the system new gestures by performing them three times.
//! The learning protocol:
//! 1. Enter learning mode: 3 seconds of stillness (motion < threshold)
//! 2. Perform gesture: record phase trajectory during motion
//! 3. Return to stillness: trajectory captured
//! 4. Repeat 3x — if trajectories are similar (DTW distance < learn_threshold),
//! average them into a template and store it
//!
//! Recognition: DTW distance of incoming phase trajectory against all stored
//! templates. Best match emitted if distance < recognition threshold.
//!
//! Budget: H (heavy, < 10 ms) — DTW is O(n*m) but n=m=64, so 4096 ops.
use libm::fabsf;
/// Maximum phase samples per gesture template.
const TEMPLATE_LEN: usize = 64;
/// Maximum stored gesture templates.
const MAX_TEMPLATES: usize = 16;
/// Number of rehearsals required before a template is committed.
const REHEARSALS_REQUIRED: usize = 3;
/// Stillness threshold (motion energy below this = still).
const STILLNESS_THRESHOLD: f32 = 0.05;
/// Number of consecutive still frames to trigger learning mode (3 s at 20 Hz).
const STILLNESS_FRAMES: u16 = 60;
/// DTW distance threshold for considering two rehearsals "similar".
const LEARN_DTW_THRESHOLD: f32 = 3.0;
/// DTW distance threshold for recognizing a stored gesture.
const RECOGNIZE_DTW_THRESHOLD: f32 = 2.5;
/// Cooldown frames after a gesture match (avoid double-fire, ~2 s at 20 Hz).
const MATCH_COOLDOWN: u16 = 40;
/// Sakoe-Chiba band width to constrain DTW warping.
const BAND_WIDTH: usize = 8;
// ── Event IDs (730-series: Adaptive Learning) ────────────────────────────────
pub const EVENT_GESTURE_LEARNED: i32 = 730;
pub const EVENT_GESTURE_MATCHED: i32 = 731;
pub const EVENT_MATCH_DISTANCE: i32 = 732;
pub const EVENT_TEMPLATE_COUNT: i32 = 733;
/// Learning state machine phases.
#[derive(Clone, Copy, Debug, PartialEq)]
enum LearnPhase {
/// Idle — waiting for stillness to begin learning.
Idle,
/// Counting consecutive stillness frames.
WaitingStill,
/// Recording motion trajectory.
Recording,
/// Motion ended — trajectory captured, waiting for next rehearsal or commit.
Captured,
}
/// A single gesture template: a fixed-length phase-delta trajectory.
#[derive(Clone, Copy)]
struct Template {
samples: [f32; TEMPLATE_LEN],
len: usize,
/// User-assigned gesture ID (starts at 100 to avoid colliding with built-in IDs).
id: u8,
}
impl Template {
const fn empty() -> Self {
Self {
samples: [0.0; TEMPLATE_LEN],
len: 0,
id: 0,
}
}
}
/// User-teachable gesture learner and recognizer.
pub struct GestureLearner {
// ── Stored templates ─────────────────────────────────────────────────
templates: [Template; MAX_TEMPLATES],
template_count: usize,
// ── Learning state ───────────────────────────────────────────────────
learn_phase: LearnPhase,
/// Consecutive stillness frame counter.
still_count: u16,
/// Rehearsal buffer: up to 3 captured trajectories.
rehearsals: [[f32; TEMPLATE_LEN]; REHEARSALS_REQUIRED],
rehearsal_lens: [usize; REHEARSALS_REQUIRED],
rehearsal_count: usize,
/// Current recording buffer.
recording: [f32; TEMPLATE_LEN],
recording_len: usize,
// ── Recognition state ────────────────────────────────────────────────
/// Phase delta sliding window for recognition.
window: [f32; TEMPLATE_LEN],
window_len: usize,
window_idx: usize,
prev_phase: f32,
phase_initialized: bool,
cooldown: u16,
/// Next ID to assign to a learned template.
next_id: u8,
}
impl GestureLearner {
pub const fn new() -> Self {
Self {
templates: [Template::empty(); MAX_TEMPLATES],
template_count: 0,
learn_phase: LearnPhase::Idle,
still_count: 0,
rehearsals: [[0.0; TEMPLATE_LEN]; REHEARSALS_REQUIRED],
rehearsal_lens: [0; REHEARSALS_REQUIRED],
rehearsal_count: 0,
recording: [0.0; TEMPLATE_LEN],
recording_len: 0,
window: [0.0; TEMPLATE_LEN],
window_len: 0,
window_idx: 0,
prev_phase: 0.0,
phase_initialized: false,
cooldown: 0,
next_id: 100,
}
}
/// Process one CSI frame.
///
/// `phases` — per-subcarrier phase values (uses first subcarrier).
/// `motion_energy` — aggregate motion metric from host (Tier 2).
///
/// Returns events as `(event_id, value)` pairs in a static buffer.
pub fn process_frame(&mut self, phases: &[f32], motion_energy: f32) -> &[(i32, f32)] {
static mut EVENTS: [(i32, f32); 4] = [(0, 0.0); 4];
let mut n_ev = 0usize;
if phases.is_empty() {
return &[];
}
// ── Compute phase delta ──────────────────────────────────────────
let primary = phases[0];
if !self.phase_initialized {
self.prev_phase = primary;
self.phase_initialized = true;
return &[];
}
let delta = primary - self.prev_phase;
self.prev_phase = primary;
// ── Push into recognition window ─────────────────────────────────
self.window[self.window_idx] = delta;
self.window_idx = (self.window_idx + 1) % TEMPLATE_LEN;
if self.window_len < TEMPLATE_LEN {
self.window_len += 1;
}
if self.cooldown > 0 {
self.cooldown -= 1;
}
// ── Learning state machine ───────────────────────────────────────
let is_still = motion_energy < STILLNESS_THRESHOLD;
match self.learn_phase {
LearnPhase::Idle => {
if is_still {
self.still_count += 1;
if self.still_count >= STILLNESS_FRAMES {
self.learn_phase = LearnPhase::WaitingStill;
self.rehearsal_count = 0;
}
} else {
self.still_count = 0;
}
}
LearnPhase::WaitingStill => {
if !is_still {
// Motion started — begin recording.
self.learn_phase = LearnPhase::Recording;
self.recording_len = 0;
self.recording[0] = delta;
self.recording_len = 1;
}
}
LearnPhase::Recording => {
if self.recording_len < TEMPLATE_LEN {
self.recording[self.recording_len] = delta;
self.recording_len += 1;
}
if is_still {
// Motion ended — capture this rehearsal.
self.learn_phase = LearnPhase::Captured;
}
}
LearnPhase::Captured => {
// Store captured trajectory as a rehearsal.
if self.rehearsal_count < REHEARSALS_REQUIRED && self.recording_len >= 4 {
let idx = self.rehearsal_count;
let len = self.recording_len;
self.rehearsal_lens[idx] = len;
let mut i = 0;
while i < len {
self.rehearsals[idx][i] = self.recording[i];
i += 1;
}
// Zero remainder.
while i < TEMPLATE_LEN {
self.rehearsals[idx][i] = 0.0;
i += 1;
}
self.rehearsal_count += 1;
}
if self.rehearsal_count >= REHEARSALS_REQUIRED {
// Check if all 3 rehearsals are mutually similar.
if self.rehearsals_are_similar() {
if let Some(id) = self.commit_template() {
unsafe {
EVENTS[n_ev] = (EVENT_GESTURE_LEARNED, id as f32);
n_ev += 1;
EVENTS[n_ev] = (EVENT_TEMPLATE_COUNT, self.template_count as f32);
n_ev += 1;
}
}
}
// Reset learning state regardless.
self.learn_phase = LearnPhase::Idle;
self.still_count = 0;
self.rehearsal_count = 0;
} else {
// Wait for next stillness -> motion cycle.
self.learn_phase = LearnPhase::WaitingStill;
}
}
}
// ── Recognition (only when not in active learning) ───────────────
if self.learn_phase == LearnPhase::Idle && self.cooldown == 0
&& self.template_count > 0 && self.window_len >= 8
{
// Build contiguous observation from ring buffer.
let mut obs = [0.0f32; TEMPLATE_LEN];
for i in 0..self.window_len {
let ri = (self.window_idx + TEMPLATE_LEN - self.window_len + i) % TEMPLATE_LEN;
obs[i] = self.window[ri];
}
let mut best_dist = RECOGNIZE_DTW_THRESHOLD;
let mut best_id: Option<u8> = None;
for t in 0..self.template_count {
let tmpl = &self.templates[t];
if tmpl.len == 0 || self.window_len < tmpl.len {
continue;
}
// Use tail of observation matching template length.
let start = if self.window_len > tmpl.len + 8 {
self.window_len - tmpl.len - 8
} else {
0
};
let dist = dtw_distance(
&obs[start..self.window_len],
&tmpl.samples[..tmpl.len],
);
if dist < best_dist {
best_dist = dist;
best_id = Some(tmpl.id);
}
}
if let Some(id) = best_id {
self.cooldown = MATCH_COOLDOWN;
unsafe {
EVENTS[n_ev] = (EVENT_GESTURE_MATCHED, id as f32);
n_ev += 1;
if n_ev < 4 {
EVENTS[n_ev] = (EVENT_MATCH_DISTANCE, best_dist);
n_ev += 1;
}
}
}
}
unsafe { &EVENTS[..n_ev] }
}
/// Check if all rehearsals are pairwise similar (DTW distance < threshold).
fn rehearsals_are_similar(&self) -> bool {
for i in 0..self.rehearsal_count {
for j in (i + 1)..self.rehearsal_count {
let len_i = self.rehearsal_lens[i];
let len_j = self.rehearsal_lens[j];
if len_i < 4 || len_j < 4 {
return false;
}
let dist = dtw_distance(
&self.rehearsals[i][..len_i],
&self.rehearsals[j][..len_j],
);
if dist >= LEARN_DTW_THRESHOLD {
return false;
}
}
}
true
}
/// Average rehearsals into a new template and store it.
/// Returns the assigned gesture ID, or None if template slots are full.
fn commit_template(&mut self) -> Option<u8> {
if self.template_count >= MAX_TEMPLATES {
return None;
}
// Find the maximum trajectory length among rehearsals.
let mut max_len = 0usize;
for i in 0..self.rehearsal_count {
if self.rehearsal_lens[i] > max_len {
max_len = self.rehearsal_lens[i];
}
}
if max_len < 4 {
return None;
}
// Average the rehearsals sample-by-sample.
let mut avg = [0.0f32; TEMPLATE_LEN];
for s in 0..max_len {
let mut sum = 0.0f32;
let mut count = 0u8;
for r in 0..self.rehearsal_count {
if s < self.rehearsal_lens[r] {
sum += self.rehearsals[r][s];
count += 1;
}
}
if count > 0 {
avg[s] = sum / count as f32;
}
}
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
self.templates[self.template_count] = Template {
samples: avg,
len: max_len,
id,
};
self.template_count += 1;
Some(id)
}
/// Number of currently stored templates.
pub fn template_count(&self) -> usize {
self.template_count
}
}
/// Compute constrained DTW distance between two sequences.
///
/// Uses Sakoe-Chiba band to limit warping path. Result is normalized
/// by path length (n + m) to allow comparison across different lengths.
fn dtw_distance(a: &[f32], b: &[f32]) -> f32 {
let n = a.len();
let m = b.len();
if n == 0 || m == 0 {
return f32::MAX;
}
// Stack-allocated cost matrix: max 64x64 = 4096 cells.
let mut cost = [[f32::MAX; TEMPLATE_LEN]; TEMPLATE_LEN];
cost[0][0] = fabsf(a[0] - b[0]);
for i in 0..n {
for j in 0..m {
let diff = if i > j { i - j } else { j - i };
if diff > BAND_WIDTH {
continue;
}
let c = fabsf(a[i] - b[j]);
if i == 0 && j == 0 {
cost[i][j] = c;
} else {
let mut min_prev = f32::MAX;
if i > 0 && cost[i - 1][j] < min_prev {
min_prev = cost[i - 1][j];
}
if j > 0 && cost[i][j - 1] < min_prev {
min_prev = cost[i][j - 1];
}
if i > 0 && j > 0 && cost[i - 1][j - 1] < min_prev {
min_prev = cost[i - 1][j - 1];
}
cost[i][j] = c + min_prev;
}
}
}
let path_len = (n + m) as f32;
cost[n - 1][m - 1] / path_len
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_state() {
let gl = GestureLearner::new();
assert_eq!(gl.template_count(), 0);
assert_eq!(gl.learn_phase, LearnPhase::Idle);
assert_eq!(gl.cooldown, 0);
}
#[test]
fn test_dtw_identical() {
let a = [0.1, 0.3, 0.5, 0.7, 0.5, 0.3, 0.1];
let b = [0.1, 0.3, 0.5, 0.7, 0.5, 0.3, 0.1];
let d = dtw_distance(&a, &b);
assert!(d < 0.001, "identical sequences should have near-zero DTW distance");
}
#[test]
fn test_dtw_different() {
let a = [0.1, 0.3, 0.5, 0.7, 0.5, 0.3, 0.1];
let b = [-0.5, -0.8, -1.0, -0.8, -0.5, -0.2, 0.0];
let d = dtw_distance(&a, &b);
assert!(d > 0.3, "different sequences should have large DTW distance");
}
#[test]
fn test_dtw_empty() {
let a: [f32; 0] = [];
let b = [1.0, 2.0];
assert_eq!(dtw_distance(&a, &b), f32::MAX);
}
#[test]
fn test_learning_protocol() {
let mut gl = GestureLearner::new();
let phase_still = [0.0f32; 8];
// Phase 1: Stillness for STILLNESS_FRAMES + 1 frames -> enter learning mode.
// (+1 because the very first call returns early to initialise phase tracking.)
for _ in 0..=STILLNESS_FRAMES {
gl.process_frame(&phase_still, 0.01);
}
assert_eq!(gl.learn_phase, LearnPhase::WaitingStill);
// Phase 2: Perform gesture 3 times (motion -> stillness).
let gesture_phases: [f32; 8] = [0.5, 0.3, 0.2, 0.1, 0.4, 0.6, 0.7, 0.8];
for rehearsal in 0..3 {
// Motion frames.
for frame in 0..10 {
let mut p = [0.0f32; 8];
p[0] = gesture_phases[frame % gesture_phases.len()] * (rehearsal as f32 + 1.0) * 0.1;
gl.process_frame(&p, 0.5);
}
// Stillness frame to capture.
let _ = gl.process_frame(&phase_still, 0.01);
if rehearsal == 2 {
// After 3rd rehearsal, should either learn (Idle) or
// still be in Captured if DTW distances were too different.
assert!(
gl.learn_phase == LearnPhase::Idle || gl.learn_phase == LearnPhase::Captured,
"unexpected phase: {:?}", gl.learn_phase
);
}
}
}
#[test]
fn test_template_capacity() {
let mut gl = GestureLearner::new();
// Manually fill templates to max.
for i in 0..MAX_TEMPLATES {
gl.templates[i] = Template {
samples: [0.1; TEMPLATE_LEN],
len: 10,
id: i as u8,
};
}
gl.template_count = MAX_TEMPLATES;
// Commit should return None when full.
assert!(gl.commit_template().is_none());
}
}