primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Agreement metrics and descriptive statistics.
//!
//! Absorbed from airSpring `testutil/stats.rs` and groundSpring `stats/metrics.rs`
//! (Feb 2026, Session 64). These are domain-agnostic statistical measures used
//! across all springs for model validation.
//!
//! # Agreement metrics
//!
//! | Function | Description |
//! |----------|-------------|
//! | [`rmse`] | Root Mean Square Error |
//! | [`mbe`] | Mean Bias Error |
//! | [`nash_sutcliffe`] | Nash-Sutcliffe Efficiency (NSE) |
//! | [`r_squared`] | Coefficient of determination (R²) via SS method |
//! | [`index_of_agreement`] | Willmott Index of Agreement (IA) |
//! | [`hit_rate`] | Threshold-based occurrence agreement |
//!
//! # Descriptive statistics
//!
//! | Function | Description |
//! |----------|-------------|
//! | [`mean`] | Arithmetic mean |
//! | [`percentile`] | Interpolated percentile (0–100 scale) |

// ── Agreement metrics ───────────────────────────────────────────────────

/// Root Mean Square Error.
///
/// RMSE = sqrt(Σ(obs - sim)² / n)
///
/// Returns `0.0` for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn rmse(observed: &[f64], simulated: &[f64]) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let sum_sq: f64 = observed
        .iter()
        .zip(simulated)
        .map(|(o, s)| (o - s).powi(2))
        .sum();
    (sum_sq / n as f64).sqrt()
}

/// Mean Absolute Error.
///
/// MAE = Σ|obs − sim| / n
///
/// Returns `0.0` for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn mae(observed: &[f64], simulated: &[f64]) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let sum_abs: f64 = observed
        .iter()
        .zip(simulated)
        .map(|(o, s)| (o - s).abs())
        .sum();
    sum_abs / n as f64
}

/// Mean Bias Error (simulated − observed).
///
/// Positive MBE indicates the model overestimates.
///
/// Returns `0.0` for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn mbe(observed: &[f64], simulated: &[f64]) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let sum_bias: f64 = observed.iter().zip(simulated).map(|(o, s)| s - o).sum();
    sum_bias / n as f64
}

/// Nash-Sutcliffe Efficiency (Nash & Sutcliffe, 1970).
///
/// NSE = 1 − Σ(obs − sim)² / Σ(obs − obs̄)²
///
/// NSE = 1.0 is perfect; NSE < 0 means the model is worse than the mean.
///
/// Returns `0.0` when `ss_tot` is zero (constant observations) or for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn nash_sutcliffe(observed: &[f64], simulated: &[f64]) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let mean_obs: f64 = observed.iter().sum::<f64>() / n as f64;
    let ss_res: f64 = observed
        .iter()
        .zip(simulated)
        .map(|(o, s)| (o - s).powi(2))
        .sum();
    let ss_tot: f64 = observed.iter().map(|o| (o - mean_obs).powi(2)).sum();
    if ss_tot == 0.0 {
        return 0.0;
    }
    1.0 - ss_res / ss_tot
}

/// Coefficient of determination (R²) via sum-of-squares method.
///
/// R² = 1 − `SS_res` / `SS_tot`
///
/// Can be negative for poor models. Equivalent to [`nash_sutcliffe`].
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn r_squared(observed: &[f64], simulated: &[f64]) -> f64 {
    nash_sutcliffe(observed, simulated)
}

/// Index of Agreement (Willmott, 1981).
///
/// IA = 1 − Σ(obs − sim)² / Σ(|sim − obs̄| + |obs − obs̄|)²
///
/// Values range from 0.0 (no agreement) to 1.0 (perfect).
///
/// Returns `0.0` when denominator is zero or for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn index_of_agreement(observed: &[f64], simulated: &[f64]) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let mean_obs: f64 = observed.iter().sum::<f64>() / n as f64;
    let numerator: f64 = observed
        .iter()
        .zip(simulated)
        .map(|(o, s)| (o - s).powi(2))
        .sum();
    let denominator: f64 = observed
        .iter()
        .zip(simulated)
        .map(|(o, s)| ((s - mean_obs).abs() + (o - mean_obs).abs()).powi(2))
        .sum();
    if denominator == 0.0 {
        return 0.0;
    }
    1.0 - numerator / denominator
}

/// Hit rate: fraction of days where observed and modeled agree on
/// threshold exceedance.
///
/// A day "occurs" if its value exceeds `threshold`. Returns the fraction
/// of entries where both agree (both above or both at-or-below).
///
/// Returns `0.0` for empty slices.
///
/// # Panics
///
/// Panics if `observed` and `simulated` have different lengths.
#[must_use]
pub fn hit_rate(observed: &[f64], simulated: &[f64], threshold: f64) -> f64 {
    assert_eq!(observed.len(), simulated.len(), "length mismatch");
    let n = observed.len();
    if n == 0 {
        return 0.0;
    }
    let agree = observed
        .iter()
        .zip(simulated)
        .filter(|&(o, s)| (*o > threshold) == (*s > threshold))
        .count();
    agree as f64 / n as f64
}

// ── Descriptive statistics ──────────────────────────────────────────────

/// Arithmetic mean of a slice. Returns `0.0` for empty slices.
#[must_use]
pub fn mean(values: &[f64]) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    values.iter().sum::<f64>() / values.len() as f64
}

/// Interpolated percentile (0–100 scale).
///
/// Uses linear interpolation between adjacent ranks.
///
/// Returns `0.0` for empty slices.
///
/// # Panics
///
/// Panics if `p` is not in 0.0..=100.0.
#[must_use]
pub fn percentile(values: &[f64], p: f64) -> f64 {
    assert!((0.0..=100.0).contains(&p), "percentile must be 0–100");
    if values.is_empty() {
        return 0.0;
    }
    let mut sorted: Vec<f64> = values.to_vec();
    sorted.sort_by(f64::total_cmp);
    let rank = p / 100.0 * (sorted.len() - 1) as f64;
    let lo = rank.floor() as usize;
    let hi = rank.ceil() as usize;
    if lo == hi {
        sorted[lo]
    } else {
        let frac = rank - lo as f64;
        sorted[lo].mul_add(1.0 - frac, sorted[hi] * frac)
    }
}

/// CPU dot product: Σ aᵢ·bᵢ.
///
/// For GPU dot product, use [`crate::ops::fused_map_reduce_f64::FusedMapReduceF64::dot`]
/// or [`crate::ops::weighted_dot_f64::WeightedDotF64`].
///
/// # Panics
///
/// Panics if `a` and `b` have different lengths.
#[must_use]
pub fn dot(a: &[f64], b: &[f64]) -> f64 {
    assert_eq!(a.len(), b.len(), "length mismatch");
    a.iter().zip(b).map(|(x, y)| x * y).sum()
}

/// CPU L2 norm: sqrt(Σ xᵢ²).
///
/// For GPU L2 norm, use [`crate::ops::norm_reduce_f64::NormReduceF64::l2`].
#[must_use]
pub fn l2_norm(xs: &[f64]) -> f64 {
    xs.iter().map(|x| x * x).sum::<f64>().sqrt()
}

// ── Kinetics ────────────────────────────────────────────────────────────

/// Hill function: sigmoidal dose-response.
///
/// f(x) = x^n / (k^n + x^n)
///
/// Used in gene regulatory networks, enzyme kinetics, and ecological models.
/// For the GPU WGSL version, see `hill()` in the ODE shader library.
#[inline]
#[must_use]
pub fn hill(x: f64, k: f64, n: f64) -> f64 {
    let xn = x.powf(n);
    xn / (k.powf(n) + xn)
}

/// Hill activation: amplitude-scaled sigmoidal increase.
///
/// f(x) = amplitude * x^n / (k^n + x^n)
///
/// Returns 0 when x ≤ 0, approaches `amplitude` as x → ∞.
/// Used in gene regulatory networks (biofilm production, virulence expression).
///
/// Cross-spring absorption from neuralSpring `primitives::hill_activation`.
#[inline]
#[must_use]
pub fn hill_activation(x: f64, amplitude: f64, k: f64, n: f64) -> f64 {
    if x <= 0.0 {
        return 0.0;
    }
    amplitude * hill(x, k, n)
}

/// Hill repression: amplitude-scaled sigmoidal decrease.
///
/// f(x) = amplitude * k^n / (k^n + x^n)
///
/// Returns `amplitude` when x ≤ 0, approaches 0 as x → ∞.
/// Used in gene regulatory networks (motility suppression by quorum sensing).
///
/// Cross-spring absorption from neuralSpring `primitives::hill_repression`.
#[inline]
#[must_use]
pub fn hill_repression(x: f64, amplitude: f64, k: f64, n: f64) -> f64 {
    if x <= 0.0 {
        return amplitude;
    }
    amplitude * (1.0 - hill(x, k, n))
}

/// Monod kinetics: saturation growth rate.
///
/// f(x) = r * x / (k + x)
///
/// Special case of Hill with n=1 and a maximum rate r.
/// Standard in microbial ecology and wastewater modeling.
#[inline]
#[must_use]
pub fn monod(x: f64, r: f64, k: f64) -> f64 {
    r * x / (k + x)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rmse_identical_is_zero() {
        let x = [1.0, 2.0, 3.0];
        assert!(rmse(&x, &x) < 1e-12);
    }

    #[test]
    fn rmse_known_value() {
        let obs = [1.0, 2.0, 3.0];
        let sim = [1.0, 3.0, 3.0];
        let expected = (1.0_f64 / 3.0).sqrt();
        assert!((rmse(&obs, &sim) - expected).abs() < 1e-10);
    }

    #[test]
    fn rmse_empty() {
        assert!(rmse(&[], &[]) < 1e-12);
    }

    #[test]
    fn mae_identical_is_zero() {
        let x = [1.0, 2.0, 3.0];
        assert!(mae(&x, &x) < 1e-12);
    }

    #[test]
    fn mae_known_value() {
        let obs = [1.0, 2.0, 3.0];
        let sim = [2.0, 1.0, 5.0];
        assert!((mae(&obs, &sim) - 4.0 / 3.0).abs() < 1e-10);
    }

    #[test]
    fn mae_empty() {
        assert!(mae(&[], &[]) < 1e-12);
    }

    #[test]
    fn mae_symmetric() {
        let obs = [1.0, 5.0, 3.0];
        let sim = [2.0, 3.0, 4.0];
        assert!((mae(&obs, &sim) - mae(&sim, &obs)).abs() < 1e-12);
    }

    #[test]
    fn mbe_positive_bias() {
        let obs = [1.0, 2.0, 3.0];
        let sim = [2.0, 3.0, 4.0];
        assert!((mbe(&obs, &sim) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn mbe_negative_bias() {
        let obs = [5.0, 6.0, 7.0];
        let sim = [4.0, 5.0, 6.0];
        assert!((mbe(&obs, &sim) + 1.0).abs() < 1e-12);
    }

    #[test]
    fn nash_sutcliffe_perfect() {
        let x = [1.0, 2.0, 3.0, 4.0, 5.0];
        assert!((nash_sutcliffe(&x, &x) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn nash_sutcliffe_worse_than_mean_is_negative() {
        let obs = [1.0, 2.0, 3.0, 4.0, 5.0];
        let sim = [5.0, 4.0, 3.0, 2.0, 1.0];
        assert!(nash_sutcliffe(&obs, &sim) < 0.0);
    }

    #[test]
    fn nash_sutcliffe_mean_predictor_is_zero() {
        let obs = [1.0, 2.0, 3.0, 4.0, 5.0];
        let pred = vec![3.0; 5];
        assert!(nash_sutcliffe(&obs, &pred).abs() < 1e-10);
    }

    #[test]
    fn index_of_agreement_perfect() {
        let x = [1.0, 2.0, 3.0, 4.0];
        assert!((index_of_agreement(&x, &x) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn hit_rate_perfect() {
        let obs = [0.0, 5.0, 0.0, 3.0];
        assert!((hit_rate(&obs, &obs, 0.1) - 1.0).abs() < 1e-12);
    }

    #[test]
    fn hit_rate_known() {
        let obs = [0.0, 5.0, 0.0, 3.0];
        let sim = [0.0, 4.0, 0.0, 0.0];
        assert!((hit_rate(&obs, &sim, 0.1) - 0.75).abs() < 1e-12);
    }

    #[test]
    fn percentile_median() {
        let vals = [1.0, 2.0, 3.0, 4.0, 5.0];
        assert!((percentile(&vals, 50.0) - 3.0).abs() < 1e-12);
    }

    #[test]
    fn percentile_interpolation() {
        let vals = [1.0, 2.0, 3.0, 4.0];
        assert!((percentile(&vals, 25.0) - 1.75).abs() < 1e-12);
    }

    #[test]
    fn mean_known() {
        assert!((mean(&[2.0, 4.0, 6.0]) - 4.0).abs() < 1e-12);
    }

    #[test]
    fn mean_empty() {
        assert!(mean(&[]).abs() < 1e-12);
    }

    #[test]
    fn dot_known() {
        assert!((dot(&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]) - 32.0).abs() < 1e-12);
    }

    #[test]
    fn l2_norm_known() {
        assert!((l2_norm(&[3.0, 4.0]) - 5.0).abs() < 1e-12);
    }

    #[test]
    fn l2_norm_empty() {
        assert!(l2_norm(&[]).abs() < 1e-12);
    }

    #[test]
    fn hill_midpoint() {
        assert!((hill(5.0, 5.0, 1.0) - 0.5).abs() < 1e-12);
    }

    #[test]
    fn hill_steep() {
        assert!((hill(5.0, 5.0, 10.0) - 0.5).abs() < 1e-10);
        assert!(hill(10.0, 5.0, 10.0) > 0.999);
        assert!(hill(2.5, 5.0, 10.0) < 0.001);
    }

    #[test]
    fn hill_zero_input() {
        assert!(hill(0.0, 5.0, 2.0).abs() < 1e-12);
    }

    #[test]
    fn hill_activation_zero_input() {
        assert!(hill_activation(0.0, 10.0, 5.0, 2.0).abs() < 1e-12);
    }

    #[test]
    fn hill_activation_midpoint() {
        assert!((hill_activation(5.0, 10.0, 5.0, 1.0) - 5.0).abs() < 1e-12);
    }

    #[test]
    fn hill_activation_large_x() {
        assert!((hill_activation(1000.0, 1.0, 5.0, 2.0) - 1.0).abs() < 0.001);
    }

    #[test]
    fn hill_activation_negative_input() {
        assert!(hill_activation(-1.0, 10.0, 5.0, 2.0).abs() < 1e-12);
    }

    #[test]
    fn hill_repression_zero_input() {
        assert!((hill_repression(0.0, 10.0, 5.0, 2.0) - 10.0).abs() < 1e-12);
    }

    #[test]
    fn hill_repression_midpoint() {
        assert!((hill_repression(5.0, 10.0, 5.0, 1.0) - 5.0).abs() < 1e-12);
    }

    #[test]
    fn hill_repression_large_x() {
        assert!(hill_repression(1000.0, 1.0, 5.0, 2.0) < 0.001);
    }

    #[test]
    fn hill_repression_negative_input() {
        assert!((hill_repression(-1.0, 10.0, 5.0, 2.0) - 10.0).abs() < 1e-12);
    }

    #[test]
    fn hill_activation_repression_complement() {
        let x = 3.0;
        let a = 7.0;
        let k = 4.0;
        let n = 2.5;
        assert!((hill_activation(x, a, k, n) + hill_repression(x, a, k, n) - a).abs() < 1e-12);
    }

    #[test]
    fn monod_saturation() {
        assert!((monod(1000.0, 1.0, 1.0) - 1.0).abs() < 0.01);
    }

    #[test]
    fn monod_half_saturation() {
        assert!((monod(5.0, 1.0, 5.0) - 0.5).abs() < 1e-12);
    }

    #[test]
    fn monod_is_hill_n1() {
        let x = 7.0;
        let k = 3.0;
        let r = 2.0;
        assert!((monod(x, r, k) - r * hill(x, k, 1.0)).abs() < 1e-12);
    }
}