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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Centralized validation tolerances with mathematical justification.
//!
//! Every tolerance threshold used in validation is defined here.
//! No ad-hoc magic numbers. Imitates the neuralSpring hotSpring pattern.
//!
//! # Stability Contract
//!
//! All tolerance constants in this module are **SemVer-stable**: tightening
//! a tolerance (lowering `abs_tol` or `rel_tol`) or removing a constant is a
//! **breaking change** requiring a major version bump or `BREAKING_CHANGES.md`
//! entry. Loosening a tolerance (raising values) is a minor/patch change.
//!
//! Springs depend on these constants for reproducible validation harnesses.
//! If a tolerance needs to change, file a `wateringHole` handoff first so
//! all consuming springs can update their expectations.

pub mod precision;
mod registry;

pub use precision::*;
pub use registry::{all_tolerances, by_name, tier};

/// Tolerance descriptor with absolute and relative bounds plus justification.
#[derive(Debug, Clone, Copy)]
pub struct Tolerance {
    /// Identifier for this tolerance.
    pub name: &'static str,
    /// Absolute tolerance threshold.
    pub abs_tol: f64,
    /// Relative tolerance threshold.
    pub rel_tol: f64,
    /// Mathematical justification for the chosen values.
    pub justification: &'static str,
}

/// Check whether `computed` matches `expected` within the tolerance.
///
/// Uses combined absolute-or-relative: passes if
/// `|computed - expected| <= abs_tol` or
/// `|computed - expected| <= rel_tol * max(|expected|, 1.0)`.
#[must_use]
pub fn check(computed: f64, expected: f64, tol: &Tolerance) -> bool {
    if !computed.is_finite() || !expected.is_finite() {
        return computed == expected;
    }
    let abs = (computed - expected).abs();
    if abs <= tol.abs_tol {
        return true;
    }
    let scale = expected.abs().max(1.0);
    abs <= tol.rel_tol * scale
}

// ═══════════════════════════════════════════════════════════════════
// linalg tolerances
// ═══════════════════════════════════════════════════════════════════

/// Matmul: dot-product accumulation O(√n) rounding for inner dim n.
pub const LINALG_MATMUL: Tolerance = Tolerance {
    name: "linalg_matmul",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "f64 dot-product accumulation; √n rounding for inner dim n",
};

/// Transpose: pure data movement, no arithmetic.
pub const LINALG_TRANSPOSE: Tolerance = Tolerance {
    name: "linalg_transpose",
    abs_tol: 1e-14,
    rel_tol: 1e-14,
    justification: "exact data movement; only f64 representation",
};

/// Frobenius norm: single-pass reduction.
pub const LINALG_FROBENIUS: Tolerance = Tolerance {
    name: "linalg_frobenius",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "f64 sum-of-squares reduction; accumulation order",
};

// ═══════════════════════════════════════════════════════════════════
// reduction tolerances
// ═══════════════════════════════════════════════════════════════════

/// Sum: Kahan or simple accumulation.
pub const REDUCTION_SUM: Tolerance = Tolerance {
    name: "reduction_sum",
    abs_tol: 1e-12,
    rel_tol: 1e-12,
    justification: "f64 accumulation; O(n) rounding for n elements",
};

/// Mean: sum / n.
pub const REDUCTION_MEAN: Tolerance = Tolerance {
    name: "reduction_mean",
    abs_tol: 1e-12,
    rel_tol: 1e-12,
    justification: "f64 sum then division; machine precision",
};

/// Variance: two-pass mean then residual sum.
pub const REDUCTION_VARIANCE: Tolerance = Tolerance {
    name: "reduction_variance",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "two-pass mean; catastrophic cancellation in subtraction",
};

/// Logsumexp: max-subtract + exp + sum + log.
pub const REDUCTION_LOGSUMEXP: Tolerance = Tolerance {
    name: "reduction_logsumexp",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "numerically stable; exp/log round-trip",
};

// ═══════════════════════════════════════════════════════════════════
// bio tolerances
// ═══════════════════════════════════════════════════════════════════

/// HMM forward: log-likelihood from T matrix-vector products.
pub const BIO_HMM: Tolerance = Tolerance {
    name: "bio_hmm",
    abs_tol: 1e-8,
    rel_tol: 1e-8,
    justification: "forward-backward accumulates rounding from T steps",
};

/// Allele frequency: per-locus variance across populations.
pub const BIO_ALLELE_FREQ: Tolerance = Tolerance {
    name: "bio_allele_freq",
    abs_tol: 1e-6,
    rel_tol: 1e-6,
    justification: "mean/variance over populations; f64 two-pass",
};

/// Nucleotide diversity: pairwise differences.
pub const BIO_NUCLEOTIDE_DIVERSITY: Tolerance = Tolerance {
    name: "bio_nucleotide_diversity",
    abs_tol: 1e-8,
    rel_tol: 1e-8,
    justification: "pairwise counting; exact arithmetic on integers",
};

// ═══════════════════════════════════════════════════════════════════
// special tolerances
// ═══════════════════════════════════════════════════════════════════

/// erf: polynomial/Chebyshev approximation.
pub const SPECIAL_ERF: Tolerance = Tolerance {
    name: "special_erf",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "A&S 7.1.26; ~6 digits accuracy in f64",
};

/// Gamma: Lanczos approximation.
pub const SPECIAL_GAMMA: Tolerance = Tolerance {
    name: "special_gamma",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "Lanczos; ~12 digits for x in [0.5, 2]",
};

/// Bessel: polynomial approximations.
pub const SPECIAL_BESSEL: Tolerance = Tolerance {
    name: "special_bessel",
    abs_tol: 1e-6,
    rel_tol: 1e-6,
    justification: "A&S 9.4.1-9.4.6; ~6 digits in f64",
};

// ═══════════════════════════════════════════════════════════════════
// hydrology tolerances (airSpring, wetSpring cross-spring)
// ═══════════════════════════════════════════════════════════════════

/// ET₀ reference evapotranspiration (Penman-Monteith / Hargreaves).
pub const HYDRO_ET0: Tolerance = Tolerance {
    name: "hydro_et0",
    abs_tol: 0.05,
    rel_tol: 1e-3,
    justification: "FAO-56 PM: ~0.05 mm/day measurement uncertainty; GPU f64 chain",
};

/// Soil moisture (volumetric water content θ).
pub const HYDRO_SOIL_MOISTURE: Tolerance = Tolerance {
    name: "hydro_soil_moisture",
    abs_tol: 1e-4,
    rel_tol: 1e-3,
    justification: "Richards/water balance: iterative solver convergence + sensor noise",
};

/// Water balance (daily depletion/surplus accounting).
pub const HYDRO_WATER_BALANCE: Tolerance = Tolerance {
    name: "hydro_water_balance",
    abs_tol: 0.1,
    rel_tol: 1e-3,
    justification: "cascaded ET₀→Kc→WB accumulates rounding over seasonal pipeline",
};

/// Crop coefficient (Kc interpolation).
pub const HYDRO_CROP_COEFFICIENT: Tolerance = Tolerance {
    name: "hydro_crop_coefficient",
    abs_tol: 1e-6,
    rel_tol: 1e-6,
    justification: "linear interpolation between Kc_prev and Kc_next; exact on f64",
};

// ═══════════════════════════════════════════════════════════════════
// physics tolerances (hotSpring, groundSpring cross-spring)
// ═══════════════════════════════════════════════════════════════════

/// Anderson eigenvalue (Sturm bisection or Lanczos).
pub const PHYSICS_ANDERSON_EIGENVALUE: Tolerance = Tolerance {
    name: "physics_anderson_eigenvalue",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "Sturm bisection converges to machine precision for well-separated eigenvalues",
};

/// Lattice gauge action density.
pub const PHYSICS_LATTICE_ACTION: Tolerance = Tolerance {
    name: "physics_lattice_action",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "plaquette trace accumulation over lattice volume; GPU f64 reduction order",
};

/// Lyapunov exponent from transfer matrix.
pub const PHYSICS_LYAPUNOV: Tolerance = Tolerance {
    name: "physics_lyapunov",
    abs_tol: 1e-4,
    rel_tol: 1e-3,
    justification: "log(norm) accumulation over L steps; statistical averaging over disorder",
};

// ═══════════════════════════════════════════════════════════════════
// RHMC / lattice HMC tolerances (hotSpring absorption, Mar 2026)
// ═══════════════════════════════════════════════════════════════════

/// CG solver tolerance for fermion force computation.
///
/// Moderate precision sufficient for force term; O(100) iterations typical.
/// Tighter than RHMC approx error but looser than Metropolis CG.
pub const LATTICE_CG_FORCE: Tolerance = Tolerance {
    name: "lattice_cg_force",
    abs_tol: 1e-6,
    rel_tol: 1e-6,
    justification: "CG for force term: moderate precision, O(100) iterations typical",
};

/// CG solver tolerance for Metropolis Hamiltonian evaluation.
///
/// High precision required to preserve detailed balance in the accept/reject step.
pub const LATTICE_CG_METROPOLIS: Tolerance = Tolerance {
    name: "lattice_cg_metropolis",
    abs_tol: 1e-8,
    rel_tol: 1e-8,
    justification: "CG for Metropolis: high precision for detailed balance",
};

/// Maximum relative error bound for rational approximation in RHMC.
pub const LATTICE_RHMC_APPROX_ERROR: Tolerance = Tolerance {
    name: "lattice_rhmc_approx_error",
    abs_tol: 1e-3,
    rel_tol: 1e-3,
    justification: "rational approximation max relative error bound (Remez exchange)",
};

/// Plaquette expectation value validation (cold start = 1.0, strong coupling = 0.0).
pub const LATTICE_PLAQUETTE: Tolerance = Tolerance {
    name: "lattice_plaquette",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "plaquette trace from GPU reduction; same as physics_lattice_action",
};

/// Fermion force magnitude validation.
///
/// Force depends on CG solution quality; looser than CG tolerance itself.
pub const LATTICE_FERMION_FORCE: Tolerance = Tolerance {
    name: "lattice_fermion_force",
    abs_tol: 1e-4,
    rel_tol: 1e-3,
    justification: "fermion force depends on CG solution accuracy and gauge fluctuations",
};

/// Metropolis ΔH precision for accept/reject validation.
///
/// Small ΔH indicates reversibility; large ΔH triggers trajectory rejection.
pub const LATTICE_METROPOLIS_DELTA_H: Tolerance = Tolerance {
    name: "lattice_metropolis_delta_h",
    abs_tol: 1.0,
    rel_tol: 0.5,
    justification: "ΔH of O(1) expected for well-tuned HMC; acceptance rate ~70-90%",
};

// ═══════════════════════════════════════════════════════════════════
// diversity tolerances (wetSpring cross-spring)
// ═══════════════════════════════════════════════════════════════════

/// Shannon diversity index H' = -Σ `p_i` `ln(p_i)`.
pub const BIO_DIVERSITY_SHANNON: Tolerance = Tolerance {
    name: "bio_diversity_shannon",
    abs_tol: 1e-8,
    rel_tol: 1e-8,
    justification: "log accumulation over S species; well-conditioned for p_i > 0",
};

/// Simpson diversity index 1 - Σ `p_i²`.
pub const BIO_DIVERSITY_SIMPSON: Tolerance = Tolerance {
    name: "bio_diversity_simpson",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "sum-of-squares; exact integer arithmetic when from counts",
};

/// Phylogenetic distance metrics (`UniFrac`, patristic).
pub const BIO_PHYLOGENETIC: Tolerance = Tolerance {
    name: "bio_phylogenetic",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "branch-length accumulation over tree; float rounding per edge",
};

// ═══════════════════════════════════════════════════════════════════
// Tiered tolerance architecture (absorbed from groundSpring V74)
//
// 13 tiers from strictest (machine precision) to loosest (equilibrium
// convergence).  Each tier has a semantic name and documented purpose.
// Springs select the tier that matches their physics, not an ad-hoc number.
// ═══════════════════════════════════════════════════════════════════

/// Deterministic operations: bit-exact or rounding error only.
pub const DETERMINISM: Tolerance = Tolerance {
    name: "tol::DETERMINISM",
    abs_tol: 0.0,
    rel_tol: f64::EPSILON,
    justification: "pure data movement or integer arithmetic; no floating-point accumulation",
};

/// Machine precision: single f64 operation.
pub const MACHINE: Tolerance = Tolerance {
    name: "tol::MACHINE",
    abs_tol: 1e-15,
    rel_tol: 1e-15,
    justification: "one f64 multiply/add; unit roundoff ~1.1e-16",
};

/// Accumulation: O(sqrt(n)) rounding from n f64 additions.
pub const ACCUMULATION: Tolerance = Tolerance {
    name: "tol::ACCUMULATION",
    abs_tol: 1e-12,
    rel_tol: 1e-12,
    justification: "sum/dot-product of ~10^6 terms; error ~sqrt(n)·eps",
};

/// Transcendental: exp, log, sin, cos minimax polynomials.
pub const TRANSCENDENTAL: Tolerance = Tolerance {
    name: "tol::TRANSCENDENTAL",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "range-reduced minimax with ~12 correct digits",
};

/// Iterative solver: CG, `BiCGSTAB` convergence criterion.
pub const ITERATIVE: Tolerance = Tolerance {
    name: "tol::ITERATIVE",
    abs_tol: 1e-8,
    rel_tol: 1e-8,
    justification: "iterative solver residual; problem-dependent conditioning",
};

/// Statistical: variance, correlation, bootstrap estimation.
pub const STATISTICAL: Tolerance = Tolerance {
    name: "tol::STATISTICAL",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "finite-sample statistics; dominated by sampling error not arithmetic",
};

/// Stochastic: PRNG-dependent quantities (Monte Carlo averages).
pub const STOCHASTIC: Tolerance = Tolerance {
    name: "tol::STOCHASTIC",
    abs_tol: 1e-3,
    rel_tol: 1e-2,
    justification: "Monte Carlo; error ~1/sqrt(N_samples); PRNG seed sensitive",
};

/// Equilibrium: convergence of SCF/MD thermalization.
pub const EQUILIBRIUM: Tolerance = Tolerance {
    name: "tol::EQUILIBRIUM",
    abs_tol: 1.0,
    rel_tol: 1e-2,
    justification: "thermodynamic equilibrium; fluctuations dominate",
};

// ═══════════════════════════════════════════════════════════════════
// Epsilon guards (absorbed from groundSpring V74)
// ═══════════════════════════════════════════════════════════════════

/// Epsilon guard constants for safe arithmetic.
pub mod eps {
    /// Minimum denominator for safe division.
    pub const SAFE_DIV: f64 = 1e-15;

    /// Floor for SSA (stochastic simulation) propensity sums.
    pub const SSA_FLOOR: f64 = 1e-30;

    /// Underflow guard for `exp()` arguments.
    pub const UNDERFLOW: f64 = -700.0;

    /// Overflow guard for `exp()` arguments.
    pub const OVERFLOW: f64 = 700.0;

    /// Guard for `log()` arguments (must be > 0).
    pub const LOG_FLOOR: f64 = 1e-300;

    /// Guard for `sqrt()` arguments (must be >= 0).
    pub const SQRT_FLOOR: f64 = 0.0;

    /// Guard for density values (must be non-negative).
    pub const DENSITY_FLOOR: f64 = 1e-20;

    /// Guard for probability values (must be in [0, 1]).
    pub const PROB_FLOOR: f64 = 1e-15;

    /// Overflow-safe midpoint: `(a + b) / 2` without overflow.
    ///
    /// Uses `a + (b - a) / 2` which is safe even when `a + b` overflows.
    #[must_use]
    pub fn midpoint(a: f64, b: f64) -> f64 {
        (b - a).mul_add(0.5, a)
    }
}

// ═══════════════════════════════════════════════════════════════════
// pharmacology tolerances (healthSpring cross-spring)
// ═══════════════════════════════════════════════════════════════════

/// FOCE population PK objective function.
pub const PHARMA_FOCE: Tolerance = Tolerance {
    name: "pharma_foce",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "FOCE likelihood: per-subject gradient accumulation; Newton step convergence",
};

/// VPC simulation envelope.
pub const PHARMA_VPC: Tolerance = Tolerance {
    name: "pharma_vpc",
    abs_tol: 1e-4,
    rel_tol: 1e-3,
    justification: "VPC Monte Carlo: 1000+ sims; dominated by sampling variance",
};

/// NCA AUC trapezoidal integration.
pub const PHARMA_NCA: Tolerance = Tolerance {
    name: "pharma_nca",
    abs_tol: 1e-8,
    rel_tol: 1e-6,
    justification: "trapezoidal AUC: exact for linear interpolation; f64 accumulation",
};

/// Population PK Monte Carlo: per-patient AUC with stochastic clearance.
///
/// Provenance constants for the reference model:
/// - `BASE_CL` = 10.0 L/hr (typical oral small-molecule clearance)
/// - `CL_CV` = ±50% (coefficient of variation; `cl_factor` in \[0.5, 1.5\])
/// - AUC = F * Dose / CL  (single-compartment)
///
/// GPU/CPU parity is deterministic given the same seed, but absolute
/// AUC values depend on stochastic CL — tolerance is relative only.
pub const PHARMA_POP_PK: Tolerance = Tolerance {
    name: "pharma_pop_pk",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "F*Dose/CL: three f64 multiplies/divides; deterministic PRNG parity",
};

/// Hill dose-response: E(c) = Emax * c^n / (c^n + EC50^n).
///
/// The f32-cast `exp(n*log(c))` path introduces ~6 decimal digits of
/// precision; for typical Hill coefficients 0.5 <= n <= 4 the error is
/// dominated by the `log`/`exp` round-trip through f32.
pub const PHARMA_HILL: Tolerance = Tolerance {
    name: "pharma_hill",
    abs_tol: 1e-6,
    rel_tol: 1e-5,
    justification: "f32 log/exp cast: ~7 sig digits; typical Hill n in [0.5, 4]",
};

/// Michaelis-Menten batch: Euler-integrated PK with per-patient variation.
///
/// Error is dominated by Euler discretisation (O(dt)) and stochastic
/// Vmax variation.
pub const PHARMA_MICHAELIS_MENTEN: Tolerance = Tolerance {
    name: "pharma_michaelis_menten",
    abs_tol: 1e-6,
    rel_tol: 1e-4,
    justification: "Euler integration O(dt); per-patient stochastic Vmax; f64 accumulation",
};

/// SCFA production: element-wise Michaelis-Menten (no accumulation).
pub const PHARMA_SCFA: Tolerance = Tolerance {
    name: "pharma_scfa",
    abs_tol: 1e-12,
    rel_tol: 1e-12,
    justification: "Vmax*S/(Km+S): two f64 multiplies, one divide; no accumulation",
};

// ═══════════════════════════════════════════════════════════════════
// signal processing tolerances (healthSpring, neuralSpring)
// ═══════════════════════════════════════════════════════════════════

/// FFT spectral analysis.
pub const SIGNAL_FFT: Tolerance = Tolerance {
    name: "signal_fft",
    abs_tol: 1e-10,
    rel_tol: 1e-10,
    justification: "radix-2 FFT: O(n log n) butterfly; twiddle factor precision",
};

/// QRS detection (Pan-Tompkins).
pub const SIGNAL_QRS: Tolerance = Tolerance {
    name: "signal_qrs",
    abs_tol: 1e-3,
    rel_tol: 1e-2,
    justification: "streaming filter bank; adaptive threshold; dominated by signal noise",
};

#[cfg(test)]
#[path = "tests.rs"]
mod tests;