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
use crate::Direction;
#[cfg(feature = "alloc")]
macro_rules! impl_mosum {
($name:ident, $builder:ident, $ty:ty, $zero:expr) => {
/// MOSUM — Moving Sum change detector.
///
/// Windowed complement to CUSUM. Detects transient shifts (spikes)
/// rather than persistent shifts. Uses a ring buffer of deviations
/// from target and tests whether their sum exceeds a threshold.
///
/// The ring buffer is heap-allocated once during `build()` — no
/// allocation after construction.
///
/// Requires the `alloc` feature.
pub struct $name {
target: $ty,
threshold: $ty,
buffer: *mut $ty,
window: usize,
head: usize,
sum: $ty,
count: u64,
min_samples: u64,
}
// SAFETY: buffer is exclusively owned, T is Copy + Send
unsafe impl Send for $name {}
impl $name {
#[inline]
fn ring(&self) -> &[$ty] {
// SAFETY: buffer allocated with capacity `window`, all elements initialized
unsafe { core::slice::from_raw_parts(self.buffer, self.window) }
}
#[inline]
fn ring_mut(&mut self) -> &mut [$ty] {
// SAFETY: buffer exclusively owned, all elements initialized
unsafe { core::slice::from_raw_parts_mut(self.buffer, self.window) }
}
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
target: $ty,
window: Option<usize>,
threshold: Option<$ty>,
min_samples: Option<u64>,
}
impl $name {
/// Creates a builder with the target (expected baseline mean).
#[inline]
#[must_use]
pub fn builder(target: $ty) -> $builder {
$builder {
target,
window: Option::None,
threshold: Option::None,
min_samples: Option::None,
}
}
/// Feeds a sample. Returns shift direction once primed.
#[inline]
#[must_use]
pub fn update(&mut self, sample: $ty) -> Option<Direction> {
let target = self.target;
let head = self.head;
let window = self.window;
let sum = self.sum;
let deviation = sample - target;
let ring = self.ring_mut();
let new_sum = sum - ring[head] + deviation;
ring[head] = deviation;
self.sum = new_sum;
self.head = (head + 1) % window;
self.count += 1;
if self.count < self.min_samples {
return Option::None;
}
if self.sum > self.threshold {
Option::Some(Direction::Rising)
} else if self.sum < -self.threshold {
Option::Some(Direction::Falling)
} else {
Option::Some(Direction::Neutral)
}
}
/// Current moving sum of deviations.
#[inline]
#[must_use]
pub fn sum(&self) -> $ty { self.sum }
/// Window size.
#[inline]
#[must_use]
pub fn window_size(&self) -> usize { self.window }
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 { self.count }
/// Whether the window is full and detection is active.
#[inline]
#[must_use]
pub fn is_primed(&self) -> bool { self.count >= self.min_samples }
/// Resets to empty state. Parameters unchanged.
#[inline]
pub fn reset(&mut self) {
self.ring_mut().fill($zero);
self.head = 0;
self.sum = $zero;
self.count = 0;
}
}
impl Drop for $name {
fn drop(&mut self) {
// SAFETY: buffer was allocated by Vec::with_capacity(window).
// T is Copy so no element drops needed. Reclaim the allocation.
unsafe {
let _ = alloc::vec::Vec::from_raw_parts(self.buffer, 0, self.window);
}
}
}
impl Clone for $name {
fn clone(&self) -> Self {
let mut vec = alloc::vec![$zero; self.window];
vec.copy_from_slice(self.ring());
let mut cloned = core::mem::ManuallyDrop::new(vec);
let buffer = cloned.as_mut_ptr();
Self {
target: self.target,
threshold: self.threshold,
buffer,
window: self.window,
head: self.head,
sum: self.sum,
count: self.count,
min_samples: self.min_samples,
}
}
}
impl core::fmt::Debug for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct(stringify!($name))
.field("window", &self.window)
.field("count", &self.count)
.field("sum", &self.sum)
.finish()
}
}
impl $builder {
/// Window size (number of samples in the ring buffer).
#[inline]
#[must_use]
pub fn window_size(mut self, n: usize) -> Self {
self.window = Option::Some(n);
self
}
/// Decision threshold.
#[inline]
#[must_use]
pub fn threshold(mut self, threshold: $ty) -> Self {
self.threshold = Option::Some(threshold);
self
}
/// Minimum samples before detection activates. Default: window size.
#[inline]
#[must_use]
pub fn min_samples(mut self, min: u64) -> Self {
self.min_samples = Option::Some(min);
self
}
/// Builds the MOSUM detector.
///
/// # Errors
///
/// - Window size must have been set and > 0.
/// - Threshold must have been set and positive.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let window = self.window.ok_or(crate::ConfigError::Missing("window_size"))?;
if window == 0 {
return Err(crate::ConfigError::Invalid("window_size must be > 0"));
}
let threshold = self.threshold.ok_or(crate::ConfigError::Missing("threshold"))?;
if threshold <= $zero {
return Err(crate::ConfigError::Invalid("threshold must be positive"));
}
let min_samples = self.min_samples.unwrap_or(window as u64);
let mut vec = core::mem::ManuallyDrop::new(alloc::vec![$zero; window]);
let buffer = vec.as_mut_ptr();
Ok($name {
target: self.target,
threshold,
buffer,
window,
head: 0,
sum: $zero,
count: 0,
min_samples,
})
}
}
};
}
#[cfg(feature = "alloc")]
impl_mosum!(MosumF64, MosumF64Builder, f64, 0.0);
#[cfg(feature = "alloc")]
impl_mosum!(MosumF32, MosumF32Builder, f32, 0.0);
#[cfg(feature = "alloc")]
impl_mosum!(MosumI64, MosumI64Builder, i64, 0);
#[cfg(feature = "alloc")]
impl_mosum!(MosumI32, MosumI32Builder, i32, 0);
#[cfg(feature = "alloc")]
impl_mosum!(MosumI128, MosumI128Builder, i128, 0);
#[cfg(all(test, feature = "alloc"))]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;
#[test]
fn no_detection_at_target() {
let mut mosum = MosumF64::builder(100.0)
.window_size(10)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..10 {
let _ = mosum.update(100.0);
}
for _ in 0..100 {
assert_eq!(mosum.update(100.0), Some(Direction::Neutral));
}
}
#[test]
fn detects_upward_spike() {
let mut mosum = MosumF64::builder(100.0)
.window_size(10)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..10 {
let _ = mosum.update(100.0);
}
let mut triggered = false;
for _ in 0..10 {
if mosum.update(110.0) == Some(Direction::Rising) {
triggered = true;
break;
}
}
assert!(triggered, "should detect upward spike");
}
#[test]
fn transient_clears_after_window() {
let mut mosum = MosumF64::builder(100.0)
.window_size(5)
.threshold(40.0)
.build()
.unwrap();
for _ in 0..5 {
let _ = mosum.update(100.0);
}
for _ in 0..5 {
let _ = mosum.update(120.0);
}
for _ in 0..5 {
let _ = mosum.update(100.0);
}
assert!(
mosum.sum().abs() < 1e-10,
"sum should return to ~0, got {}",
mosum.sum()
);
}
#[test]
#[allow(clippy::float_cmp)]
fn reset_clears_state() {
let mut mosum = MosumF64::builder(100.0)
.window_size(10)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..20 {
let _ = mosum.update(120.0);
}
mosum.reset();
assert_eq!(mosum.count(), 0);
assert_eq!(mosum.sum(), 0.0);
}
#[test]
fn clone_works() {
let mut mosum = MosumF64::builder(100.0)
.window_size(5)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..5 {
let _ = mosum.update(110.0);
}
let cloned = mosum.clone();
assert_eq!(cloned.count(), mosum.count());
assert_eq!(cloned.sum(), mosum.sum());
}
#[test]
fn i64_basic() {
let mut mosum = MosumI64::builder(1000)
.window_size(5)
.threshold(100)
.build()
.unwrap();
for _ in 0..5 {
let _ = mosum.update(1000);
}
assert_eq!(mosum.update(1000), Some(Direction::Neutral));
}
#[test]
fn errors_without_threshold() {
let result = MosumF64::builder(100.0).window_size(10).build();
assert!(matches!(
result,
Err(crate::ConfigError::Missing("threshold"))
));
}
#[test]
fn errors_without_window() {
let result = MosumF64::builder(100.0).threshold(50.0).build();
assert!(matches!(
result,
Err(crate::ConfigError::Missing("window_size"))
));
}
#[test]
fn i128_basic() {
let mut mosum = MosumI128::builder(1000)
.window_size(5)
.threshold(100)
.build()
.unwrap();
for _ in 0..5 {
let _ = mosum.update(1000);
}
assert_eq!(mosum.update(1000), Some(Direction::Neutral));
}
}