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
//! Univariate outlier / anomaly detection: z-score, IQR (Tukey fence), and
//! modified (MAD-based) z-score detectors.
//!
//! Each detector scores a one-dimensional sample and flags the points that fall
//! outside a chosen rule, returning both the per-point scores and the boolean
//! outlier mask so a caller can threshold or inspect either. The numerics pin the
//! reference-library conventions the equivalence suite checks:
//!
//! * the **z-score** uses the population standard deviation (`ddof = 0`), matching
//! `scipy.stats.zscore`;
//! * the **IQR / Tukey-fence** quartiles use `numpy.percentile`'s default
//! `'linear'` interpolation, so the fences `Q1 − k·IQR .. Q3 + k·IQR` agree with
//! numpy exactly;
//! * the **modified z-score** uses the median and the median absolute deviation
//! (MAD) with the conventional `0.6745` consistency constant (Iglewicz & Hoaglin).
//!
//! These base blocks back both the `OutlierDetection` and `AnomalyDetection`
//! computational methods.
use ;
/// The consistency constant `Φ⁻¹(0.75) ≈ 0.6745` scaling the MAD so the modified
/// z-score is comparable to a standard z-score for normally distributed data
/// (Iglewicz & Hoaglin, 1993).
const MAD_CONSISTENCY: f64 = 0.674_5;
/// The result of running a detector over a sample: the per-point scores and the
/// boolean outlier mask, aligned to the input order.
///
/// Returned by every detector so a caller can threshold, rank, or simply read off
/// which observations were flagged. The two vectors always share the input
/// length; `mask[i]` is the flag for the point with score `scores[i]`.
/// Errors that prevent a detector from scoring a sample.
///
/// Returned (never panicked) so callers stay clear of the crate's `unwrap`/`panic`
/// lint gate and can surface a clean diagnostic.
/// Validates a sample is non-empty and finite, and a threshold is finite-positive.
///
/// Shared front-door check so every detector rejects the same degenerate inputs
/// before any arithmetic runs.
///
/// # Arguments
///
/// * `data` — the sample to validate.
/// * `threshold` — the flagging threshold / fence multiplier to validate.
///
/// # Errors
///
/// Returns [`OutlierError::EmptyInput`], [`OutlierError::NonFinite`], or
/// [`OutlierError::InvalidThreshold`].
/// Flags outliers by the standard z-score `z = (x − mean) / std` (`|z| > threshold`).
///
/// Uses the population standard deviation (`ddof = 0`), so the returned scores
/// reproduce `scipy.stats.zscore` exactly; the mask flags every point whose
/// absolute z-score strictly exceeds `threshold` (3.0 is the textbook default).
///
/// # Arguments
///
/// * `data` — the one-dimensional sample to score; must be non-empty and finite.
/// * `threshold` — the absolute z-score above which a point is flagged; must be
/// finite and `> 0`.
///
/// # Returns
///
/// A [`Detection`] whose `scores` are the signed z-scores and whose `mask` flags
/// `|z| > threshold`.
///
/// # Errors
///
/// Returns [`OutlierError::EmptyInput`], [`OutlierError::NonFinite`],
/// [`OutlierError::InvalidThreshold`], or [`OutlierError::ZeroSpread`] (constant
/// sample).
///
/// # Examples
///
/// ```
/// use stats_claw::algorithms::outlier::zscore_detect;
///
/// // One point sits far from the rest; with threshold 1.5 it is flagged.
/// // (With only five points the maximal |z| caps near 2.0, so 1.5 isolates it.)
/// let det = zscore_detect(&[1.0, 2.0, 3.0, 4.0, 100.0], 1.5)?;
/// assert_eq!(det.mask(), &[false, false, false, false, true]);
/// // The flagged point's z-score reproduces scipy.stats.zscore.
/// let z = det.scores().last().copied().unwrap_or(f64::NAN);
/// assert!((z - 1.999_342_861_818_962_6).abs() < 1e-9, "z was {z}");
/// # Ok::<(), stats_claw::algorithms::outlier::OutlierError>(())
/// ```
/// Flags outliers by the Tukey fence `Q1 − k·IQR .. Q3 + k·IQR` (the IQR rule).
///
/// The quartiles use `numpy.percentile`'s default `'linear'` interpolation, so the
/// fences agree with a numpy reference exactly. A point is flagged when it falls
/// strictly outside the closed fence interval; its score is the signed distance to
/// the nearer fence (`0.0` inside the fences, positive above the upper fence,
/// negative below the lower fence).
///
/// # Arguments
///
/// * `data` — the one-dimensional sample to score; must be non-empty and finite.
/// * `k` — the fence multiplier (`1.5` is Tukey's classic value, `3.0` flags only
/// "far" outliers); must be finite and `> 0`.
///
/// # Returns
///
/// A [`Detection`] whose `scores` are the signed distances past the nearer fence
/// and whose `mask` flags points outside the fences.
///
/// # Errors
///
/// Returns [`OutlierError::EmptyInput`], [`OutlierError::NonFinite`], or
/// [`OutlierError::InvalidThreshold`] (non-finite or non-positive `k`).
///
/// # Examples
///
/// ```
/// use stats_claw::algorithms::outlier::iqr_detect;
///
/// // The extreme value lies far above the upper Tukey fence (k = 1.5).
/// let det = iqr_detect(&[1.0, 2.0, 3.0, 4.0, 100.0], 1.5)?;
/// assert_eq!(det.mask(), &[false, false, false, false, true]);
/// assert_eq!(det.outlier_count(), 1);
/// # Ok::<(), stats_claw::algorithms::outlier::OutlierError>(())
/// ```
/// Flags outliers by the modified (MAD-based) z-score `M = 0.6745·(x − med)/MAD`.
///
/// Robust alternative to the mean/std z-score: it uses the median and the median
/// absolute deviation, which a few extreme points cannot inflate, so the very
/// outliers being sought do not mask themselves. A point is flagged when
/// `|M| > threshold` (Iglewicz & Hoaglin recommend `3.5`).
///
/// # Arguments
///
/// * `data` — the one-dimensional sample to score; must be non-empty and finite.
/// * `threshold` — the absolute modified-z above which a point is flagged; must be
/// finite and `> 0`.
///
/// # Returns
///
/// A [`Detection`] whose `scores` are the signed modified z-scores and whose
/// `mask` flags `|M| > threshold`.
///
/// # Errors
///
/// Returns [`OutlierError::EmptyInput`], [`OutlierError::NonFinite`],
/// [`OutlierError::InvalidThreshold`], or [`OutlierError::ZeroSpread`] (zero MAD,
/// i.e. more than half the sample shares the median).
///
/// # Examples
///
/// ```
/// use stats_claw::algorithms::outlier::modified_zscore_detect;
///
/// // The MAD-based score flags the extreme point at the 3.5 threshold.
/// let det = modified_zscore_detect(&[1.0, 2.0, 3.0, 4.0, 100.0], 3.5)?;
/// assert_eq!(det.mask(), &[false, false, false, false, true]);
/// # Ok::<(), stats_claw::algorithms::outlier::OutlierError>(())
/// ```