scirs2-stats 0.4.0

Statistical functions module for SciRS2 (scirs2-stats)
Documentation
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
//! SIMD-optimized dispersion measures
//!
//! This module provides SIMD-accelerated implementations of various
//! dispersion measures using scirs2-core's unified SIMD operations.

use crate::error::{StatsError, StatsResult};
use crate::quantile_simd::{median_simd, quantile_simd};
use scirs2_core::ndarray::{ArrayBase, Data, DataMut, Ix1};
use scirs2_core::numeric::{Float, NumCast};
use scirs2_core::simd_ops::{AutoOptimizer, SimdUnifiedOps};

/// SIMD-optimized Mean Absolute Deviation (MAD)
///
/// Computes the mean absolute deviation from the median using SIMD operations
/// for improved performance on large datasets.
///
/// # Arguments
///
/// * `x` - Input array (will be modified for median computation)
/// * `scale` - Scale factor for normalization (typically 1.4826 for consistency with normal distribution)
/// * `nan_policy` - How to handle NaN values ("propagate", "raise", "omit")
///
/// # Returns
///
/// The mean absolute deviation
#[allow(dead_code)]
pub fn mad_simd<F, D>(x: &mut ArrayBase<D, Ix1>, scale: F, nanpolicy: &str) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: DataMut<Elem = F>,
{
    let n = x.len();
    if n == 0 {
        return Err(StatsError::invalid_argument(
            "Cannot compute MAD of empty array",
        ));
    }

    // Handle NaN values according to policy
    match nanpolicy {
        "propagate" => {
            if x.iter().any(|&v| v.is_nan()) {
                return Ok(F::nan());
            }
        }
        "raise" => {
            if x.iter().any(|&v| v.is_nan()) {
                return Err(StatsError::invalid_argument("Input contains NaN values"));
            }
        }
        "omit" => {
            // Filter out NaN values
            let filtered: scirs2_core::ndarray::Array1<F> =
                x.iter().filter(|&&v| !v.is_nan()).copied().collect();

            if filtered.is_empty() {
                return Ok(F::nan());
            }

            // Compute MAD on filtered data
            let mut filtered_mut = filtered;
            return mad_simd(&mut filtered_mut.view_mut(), scale, "propagate");
        }
        _ => return Err(StatsError::invalid_argument("Invalid nan_policy")),
    }

    // Compute median
    let med = median_simd(x)?;
    let validdata = x.view();

    // Compute absolute deviations using SIMD
    let optimizer = AutoOptimizer::new();
    let n_valid = validdata.len();

    let deviations = if optimizer.should_use_simd(n_valid) {
        // SIMD path
        let med_array = scirs2_core::ndarray::Array1::from_elem(n_valid, med);
        let diff = F::simd_sub(&validdata, &med_array.view());

        // Compute absolute values using SIMD
        F::simd_abs(&diff.view())
    } else {
        // Scalar fallback
        scirs2_core::ndarray::Array1::from_shape_fn(n_valid, |i| (validdata[i] - med).abs())
    };

    // Compute median of absolute deviations
    let mut deviations_mut = deviations;
    let mad = median_simd(&mut deviations_mut.view_mut())?;

    Ok(mad * scale)
}

/// SIMD-optimized Interquartile Range (IQR)
///
/// Computes the interquartile range with optional outlier detection
/// using SIMD-accelerated quantile computation.
///
/// # Arguments
///
/// * `x` - Input array (will be modified)
/// * `rng` - Range multiplier for outlier bounds (typically 1.5)
/// * `interpolation` - Interpolation method for quantile computation
/// * `keep_dims` - Whether to keep dimensions in output
///
/// # Returns
///
/// The interquartile range
#[allow(dead_code)]
pub fn iqr_simd<F, D>(
    x: &mut ArrayBase<D, Ix1>,
    _rng: F,
    interpolation: &str,
    _keep_dims: bool,
) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: DataMut<Elem = F>,
{
    if x.is_empty() {
        return Err(StatsError::invalid_argument(
            "Cannot compute IQR of empty array",
        ));
    }

    // Compute Q1 and Q3
    let q1 = quantile_simd(
        x,
        F::from(0.25).expect("Failed to convert constant to float"),
        interpolation,
    )?;
    let q3 = quantile_simd(
        x,
        F::from(0.75).expect("Failed to convert constant to float"),
        interpolation,
    )?;

    Ok(q3 - q1)
}

/// SIMD-optimized coefficient of variation
///
/// Computes the coefficient of variation (CV) using SIMD-accelerated
/// mean and standard deviation calculations.
///
/// # Arguments
///
/// * `x` - Input array
/// * `nan_policy` - How to handle NaN values
///
/// # Returns
///
/// The coefficient of variation (std/mean)
#[allow(dead_code)]
pub fn coefficient_of_variation_simd<F, D>(
    x: &ArrayBase<D, Ix1>,
    nan_policy: &str,
) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: Data<Elem = F>,
{
    use crate::descriptive_simd::{mean_simd, std_simd};

    // Handle NaN values
    let validdata = match nan_policy {
        "propagate" => {
            if x.iter().any(|&v| v.is_nan()) {
                return Ok(F::nan());
            }
            x.view()
        }
        "raise" => {
            if x.iter().any(|&v| v.is_nan()) {
                return Err(StatsError::invalid_argument("Input contains NaN values"));
            }
            x.view()
        }
        "omit" => {
            let filtered: scirs2_core::ndarray::Array1<F> =
                x.iter().filter(|&&v| !v.is_nan()).copied().collect();

            if filtered.is_empty() {
                return Ok(F::nan());
            }

            return coefficient_of_variation_simd(&filtered.view(), "propagate");
        }
        _ => return Err(StatsError::invalid_argument("Invalid nan_policy")),
    };

    let mean = mean_simd(&validdata)?;

    if mean.abs() < F::epsilon() {
        return Err(StatsError::invalid_argument(
            "Cannot compute CV when mean is zero",
        ));
    }

    let std = std_simd(&validdata, 1)?;

    Ok(std / mean.abs())
}

/// SIMD-optimized range calculation
///
/// Computes the range (max - min) using SIMD operations for finding
/// minimum and maximum values.
#[allow(dead_code)]
pub fn range_simd<F, D>(x: &ArrayBase<D, Ix1>) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: Data<Elem = F>,
{
    if x.is_empty() {
        return Err(StatsError::invalid_argument(
            "Cannot compute range of empty array",
        ));
    }

    let optimizer = AutoOptimizer::new();

    if optimizer.should_use_simd(x.len()) {
        // Use SIMD min/max operations
        let min = F::simd_min_element(&x.view());
        let max = F::simd_max_element(&x.view());
        Ok(max - min)
    } else {
        // Scalar fallback
        let mut min = x[0];
        let mut max = x[0];

        for &val in x.iter().skip(1) {
            if val < min {
                min = val;
            }
            if val > max {
                max = val;
            }
        }

        Ok(max - min)
    }
}

/// SIMD-optimized Gini coefficient
///
/// Computes the Gini coefficient using SIMD operations for sorting
/// and cumulative sum calculations.
#[allow(dead_code)]
pub fn gini_simd<F, D>(x: &ArrayBase<D, Ix1>) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: Data<Elem = F>,
{
    let n = x.len();
    if n == 0 {
        return Err(StatsError::invalid_argument(
            "Cannot compute Gini coefficient of empty array",
        ));
    }

    // Check for negative values
    if x.iter().any(|&v| v < F::zero()) {
        return Err(StatsError::invalid_argument(
            "Gini coefficient requires non-negative values",
        ));
    }

    // Sort the data
    let mut sorteddata = x.to_owned();
    let sorted_slice = sorteddata.as_slice_mut().expect("Operation failed");
    crate::quantile_simd::simd_sort(sorted_slice);

    // Compute cumulative sum and weighted sum using SIMD
    let optimizer = AutoOptimizer::new();

    if optimizer.should_use_simd(n) {
        // SIMD path
        let indices = scirs2_core::ndarray::Array1::from_shape_fn(n, |i| {
            F::from(i + 1).expect("Failed to convert to float")
        });
        let weighted = F::simd_mul(&sorteddata.view(), &indices.view());
        let weighted_sum = F::simd_sum(&weighted.view());
        let total_sum = F::simd_sum(&sorteddata.view());

        if total_sum <= F::epsilon() {
            return Ok(F::zero()); // Perfect equality (all zeros)
        }

        let gini = (F::from(2).expect("Failed to convert constant to float") * weighted_sum)
            / (F::from(n).expect("Failed to convert to float") * total_sum)
            - F::from(n + 1).expect("Failed to convert to float")
                / F::from(n).expect("Failed to convert to float");

        Ok(gini)
    } else {
        // Scalar fallback
        let mut cumsum = F::zero();
        let mut weighted_sum = F::zero();

        for (i, &val) in sorted_slice.iter().enumerate() {
            cumsum = cumsum + val;
            weighted_sum = weighted_sum + F::from(i + 1).expect("Failed to convert to float") * val;
        }

        if cumsum <= F::epsilon() {
            return Ok(F::zero());
        }

        let gini = (F::from(2).expect("Failed to convert constant to float") * weighted_sum)
            / (F::from(n).expect("Failed to convert to float") * cumsum)
            - F::from(n + 1).expect("Failed to convert to float")
                / F::from(n).expect("Failed to convert to float");

        Ok(gini)
    }
}

/// SIMD-optimized standard error of the mean
///
/// Computes SEM = std / sqrt(n) using SIMD operations
#[allow(dead_code)]
pub fn sem_simd<F, D>(x: &ArrayBase<D, Ix1>, ddof: usize) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: Data<Elem = F>,
{
    use crate::descriptive_simd::std_simd;

    let n = x.len();
    if n <= ddof {
        return Err(StatsError::invalid_argument(
            "Not enough data points for the given degrees of freedom",
        ));
    }

    let std_dev = std_simd(x, ddof)?;
    Ok(std_dev / F::from(n).expect("Failed to convert to float").sqrt())
}

/// SIMD-optimized median absolute deviation from median (MAD)
///
/// Alternative implementation that allows choosing the center (mean or median)
#[allow(dead_code)]
pub fn median_abs_deviation_simd<F, D>(
    x: &mut ArrayBase<D, Ix1>,
    center: Option<F>,
    scale: F,
) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: DataMut<Elem = F>,
{
    let n = x.len();
    if n == 0 {
        return Err(StatsError::invalid_argument(
            "Cannot compute MAD of empty array",
        ));
    }

    // Compute center if not provided
    let center_val = match center {
        Some(c) => c,
        None => median_simd(x)?,
    };

    // Compute absolute deviations using SIMD
    let optimizer = AutoOptimizer::new();

    let deviations = if optimizer.should_use_simd(n) {
        // SIMD path
        let center_array = scirs2_core::ndarray::Array1::from_elem(n, center_val);
        let diff = F::simd_sub(&x.view(), &center_array.view());
        F::simd_abs(&diff.view())
    } else {
        // Scalar fallback
        scirs2_core::ndarray::Array1::from_shape_fn(n, |i| (x[i] - center_val).abs())
    };

    // Compute median of absolute deviations
    let mut deviations_mut = deviations;
    let mad = median_simd(&mut deviations_mut.view_mut())?;

    Ok(mad * scale)
}

/// SIMD-optimized percentile range
///
/// Computes the range between two percentiles
#[allow(dead_code)]
pub fn percentile_range_simd<F, D>(
    x: &mut ArrayBase<D, Ix1>,
    lower_pct: F,
    upper_pct: F,
    interpolation: &str,
) -> StatsResult<F>
where
    F: Float + NumCast + SimdUnifiedOps + std::fmt::Display,
    D: DataMut<Elem = F>,
{
    if lower_pct < F::zero()
        || lower_pct > F::from(100).expect("Failed to convert constant to float")
        || upper_pct < F::zero()
        || upper_pct > F::from(100).expect("Failed to convert constant to float")
    {
        return Err(StatsError::invalid_argument(
            "Percentiles must be between 0 and 100",
        ));
    }

    if lower_pct >= upper_pct {
        return Err(StatsError::invalid_argument(
            "Lower percentile must be less than upper percentile",
        ));
    }

    let lower_q = lower_pct / F::from(100).expect("Failed to convert constant to float");
    let upper_q = upper_pct / F::from(100).expect("Failed to convert constant to float");

    let lower_val = quantile_simd(x, lower_q, interpolation)?;
    let upper_val = quantile_simd(x, upper_q, interpolation)?;

    Ok(upper_val - lower_val)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use scirs2_core::ndarray::array;

    #[test]
    fn test_mad_simd() {
        let mut data = array![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
        let result = mad_simd(&mut data.view_mut(), 1.0, "propagate").expect("Operation failed");

        // MAD should be median(|x - median(x)|) = median(|x - 5|) = 2
        assert_relative_eq!(result, 2.0, epsilon = 1e-10);
    }

    #[test]
    fn test_coefficient_of_variation_simd() {
        let data = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
        let cv =
            coefficient_of_variation_simd(&data.view(), "propagate").expect("Operation failed");

        // Mean = 5, Std ≈ 2, CV ≈ 0.4
        assert_relative_eq!(cv, 0.4, epsilon = 0.1);
    }

    #[test]
    fn test_range_simd() {
        let data = array![1.0, 5.0, 3.0, 9.0, 2.0, 7.0];
        let range = range_simd(&data.view()).expect("Operation failed");
        assert_relative_eq!(range, 8.0, epsilon = 1e-10); // 9 - 1 = 8
    }

    #[test]
    fn test_gini_simd() {
        // Test perfect equality
        let equaldata = array![5.0, 5.0, 5.0, 5.0];
        let gini_equal = gini_simd(&equaldata.view()).expect("Operation failed");
        assert_relative_eq!(gini_equal, 0.0, epsilon = 1e-10);

        // Test some inequality
        let unequaldata = array![1.0, 2.0, 3.0, 4.0, 5.0];
        let gini_unequal = gini_simd(&unequaldata.view()).expect("Operation failed");
        assert!(gini_unequal > 0.0 && gini_unequal < 1.0);
    }

    #[test]
    fn test_sem_simd() {
        let data = array![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
        let sem = sem_simd(&data.view(), 1).expect("Operation failed");

        // SEM = std/sqrt(n) ≈ 2/sqrt(8) ≈ 0.707
        assert_relative_eq!(sem, 0.707, epsilon = 0.1);
    }
}