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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Runge-Kutta Stage Evaluation — CPU-Orchestrated RK4/RK45
//!
//! Single-trajectory ODE integration with Dormand-Prince adaptive stepping.
//!
//! **Use cases**:
//! - Soil dynamics and crop growth models (airSpring)
//! - Time-dependent nuclear physics ODEs (hotSpring)
//! - Population dynamics and ecosystem models (wetSpring)
//!
//! **Architecture**:
//! - CPU evaluates arbitrary `f(t, y)` closures (cannot be GPU-dispatched)
//! - For GPU-native structured ODEs, see [`Rk45AdaptiveGpu`](super::rk45_adaptive::Rk45AdaptiveGpu)
//! - For batched parameter sweeps, see [`BatchedRK4F64`](super::batched_rk4_sweep::BatchedRK4F64)
//!
//! **Deep Debt Principles**:
//! - Safe Rust (zero unsafe code)
//! - Hardware-agnostic (no vendor lock-in)

use crate::device::WgpuDevice;
use crate::error::{BarracudaError, Result};
use std::sync::Arc;

/// WGSL kernel for GPU-parallel multi-system RK4 integration (f32).
///
/// For f64 structured ODE batches, see [`BatchedOdeRK4F64`].
#[must_use]
pub fn wgsl_rk4_parallel() -> &'static str {
    static SHADER: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
        include_str!("../shaders/numerical/rk4_parallel_f64.wgsl").to_string()
    });
    std::sync::LazyLock::force(&SHADER).as_str()
}

/// RK45 (Dormand-Prince) coefficients
const DP_C: [f64; 6] = [0.0, 0.2, 0.3, 0.8, 8.0 / 9.0, 1.0];

const DP_B5: [f64; 6] = [
    35.0 / 384.0,
    0.0,
    500.0 / 1113.0,
    125.0 / 192.0,
    -2187.0 / 6784.0,
    11.0 / 84.0,
];

const DP_B4: [f64; 6] = [
    5179.0 / 57_600.0,
    0.0,
    7571.0 / 16_695.0,
    393.0 / 640.0,
    -92_097.0 / 339_200.0,
    187.0 / 2100.0,
];

/// Step-size control constants (Dormand-Prince adaptive stepping)
const STEP_SAFETY: f64 = 0.9;
const STEP_MAX_GROWTH: f64 = 2.0;
const STEP_GROW_EXPONENT: f64 = 0.2; // 1/p for RK5 (p=5)
const STEP_SHRINK_EXPONENT: f64 = 0.25; // 1/p for RK4 (p=4)

/// CPU-orchestrated RK45 integrator with GPU state update path.
///
/// The ODE right-hand-side `f(t, y)` is evaluated on CPU (arbitrary closures
/// cannot run on GPU). Linear-combination stage updates can be GPU-dispatched
/// for large state dimensions via [`Rk45AdaptiveGpu`](super::rk45_adaptive::Rk45AdaptiveGpu).
pub struct RkIntegrator {
    device: Arc<WgpuDevice>,
}

/// ODE function type: f(t, y) -> dy/dt
pub type OdeFunction = Box<dyn Fn(f64, &[f64]) -> Vec<f64> + Send + Sync>;

impl RkIntegrator {
    /// Create a new RK integrator backed by the given GPU device.
    /// The device is stored for future GPU-accelerated linear combination
    /// kernels (stage preparation, error estimation) when state dimension
    /// is large enough to amortize dispatch overhead.
    /// # Errors
    /// Returns [`Err`] if device initialization fails.
    pub fn new(device: Arc<WgpuDevice>) -> Result<Self> {
        Ok(Self { device })
    }

    /// Access the underlying device (for callers that need it for batched dispatch).
    #[must_use]
    pub fn device(&self) -> &Arc<WgpuDevice> {
        &self.device
    }

    /// Integrate ODE system using RK45 (Dormand-Prince) with adaptive stepping
    /// # Arguments
    /// * `f` - ODE function: dy/dt = f(t, y)
    /// * `t0` - Initial time
    /// * `y0` - Initial state vector
    /// * `t_end` - Final time
    /// * `h_init` - Initial step size
    /// * `tol` - Error tolerance for adaptive stepping
    /// # Returns
    /// (times, states) - Vectors of time points and corresponding states
    /// # Errors
    /// Returns [`Err`] if state vector is empty.
    pub fn integrate_adaptive(
        &self,
        f: &(impl Fn(f64, &[f64]) -> Vec<f64> + Send + Sync),
        t0: f64,
        y0: &[f64],
        t_end: f64,
        h_init: f64,
        tol: f64,
    ) -> Result<(Vec<f64>, Vec<Vec<f64>>)> {
        let n = y0.len();
        if n == 0 {
            return Err(BarracudaError::InvalidInput {
                message: "State vector must have at least 1 dimension".to_string(),
            });
        }

        self.integrate_hybrid(f, t0, y0, t_end, h_init, tol)
    }

    /// Fixed-step RK4 integration (simpler, no error estimation)
    /// # Errors
    /// Returns [`Err`] if state vector is empty.
    pub fn integrate_fixed(
        &self,
        f: &impl Fn(f64, &[f64]) -> Vec<f64>,
        t0: f64,
        y0: &[f64],
        t_end: f64,
        h: f64,
    ) -> Result<(Vec<f64>, Vec<Vec<f64>>)> {
        let n = y0.len();
        if n == 0 {
            return Err(BarracudaError::InvalidInput {
                message: "State vector must have at least 1 dimension".to_string(),
            });
        }

        let n_steps = ((t_end - t0) / h).ceil() as usize;
        let mut times = Vec::with_capacity(n_steps + 1);
        let mut states = Vec::with_capacity(n_steps + 1);

        let mut t = t0;
        let mut y = y0.to_vec();

        times.push(t);
        states.push(y.clone());

        for _ in 0..n_steps {
            let h_actual = (t_end - t).min(h);

            // RK4 stages
            let k1 = f(t, &y);
            let y1: Vec<f64> = y
                .iter()
                .zip(&k1)
                .map(|(yi, k)| yi + 0.5 * h_actual * k)
                .collect();

            let k2 = f(0.5f64.mul_add(h_actual, t), &y1);
            let y2: Vec<f64> = y
                .iter()
                .zip(&k2)
                .map(|(yi, k)| yi + 0.5 * h_actual * k)
                .collect();

            let k3 = f(0.5f64.mul_add(h_actual, t), &y2);
            let y3: Vec<f64> = y.iter().zip(&k3).map(|(yi, k)| yi + h_actual * k).collect();

            let k4 = f(t + h_actual, &y3);

            // Update
            for i in 0..n {
                y[i] = (h_actual / 6.0).mul_add(
                    2.0f64.mul_add(k3[i], 2.0f64.mul_add(k2[i], k1[i])) + k4[i],
                    y[i],
                );
            }
            t += h_actual;

            times.push(t);
            states.push(y.clone());

            if t >= t_end - 1e-10 {
                break;
            }
        }

        Ok((times, states))
    }

    /// CPU RK45 with adaptive stepping
    fn integrate_cpu(
        &self,
        f: &impl Fn(f64, &[f64]) -> Vec<f64>,
        t0: f64,
        y0: &[f64],
        t_end: f64,
        h_init: f64,
        tol: f64,
    ) -> (Vec<f64>, Vec<Vec<f64>>) {
        let n = y0.len();
        let mut times = vec![t0];
        let mut states = vec![y0.to_vec()];

        let mut t = t0;
        let mut y = y0.to_vec();
        let mut h = h_init;

        while t < t_end - 1e-10 {
            h = h.min(t_end - t);

            // RK45 Dormand-Prince stages
            let k1 = f(t, &y);

            let y1: Vec<f64> = (0..n).map(|i| (h * DP_C[1]).mul_add(k1[i], y[i])).collect();
            let k2 = f(h.mul_add(DP_C[1], t), &y1);

            let y2: Vec<f64> = (0..n)
                .map(|i| h.mul_add((3.0_f64 / 40.0).mul_add(k1[i], 9.0 / 40.0 * k2[i]), y[i]))
                .collect();
            let k3 = f(h.mul_add(DP_C[2], t), &y2);

            let y3: Vec<f64> = (0..n)
                .map(|i| {
                    h.mul_add(
                        (32.0_f64 / 9.0).mul_add(
                            k3[i],
                            (44.0_f64 / 45.0).mul_add(k1[i], -(56.0 / 15.0 * k2[i])),
                        ),
                        y[i],
                    )
                })
                .collect();
            let k4 = f(h.mul_add(DP_C[3], t), &y3);

            let y4: Vec<f64> = (0..n)
                .map(|i| {
                    h.mul_add(
                        (212.0_f64 / 729.0).mul_add(
                            -k4[i],
                            (64_448.0_f64 / 6561.0).mul_add(
                                k3[i],
                                (19_372.0_f64 / 6561.0)
                                    .mul_add(k1[i], -(25_360.0 / 2187.0 * k2[i])),
                            ),
                        ),
                        y[i],
                    )
                })
                .collect();
            let k5 = f(h.mul_add(DP_C[4], t), &y4);

            let y5: Vec<f64> = (0..n)
                .map(|i| {
                    h.mul_add(
                        (5103.0_f64 / 18_656.0).mul_add(
                            -k5[i],
                            (49.0_f64 / 176.0).mul_add(
                                k4[i],
                                (46_732.0_f64 / 5247.0).mul_add(
                                    k3[i],
                                    (9017.0_f64 / 3168.0).mul_add(k1[i], -(355.0 / 33.0 * k2[i])),
                                ),
                            ),
                        ),
                        y[i],
                    )
                })
                .collect();
            let k6 = f(h.mul_add(DP_C[5], t), &y5);

            // 5th order solution
            let y_new: Vec<f64> = (0..n)
                .map(|i| {
                    h.mul_add(
                        DP_B5[5].mul_add(
                            k6[i],
                            DP_B5[4].mul_add(
                                k5[i],
                                DP_B5[3].mul_add(k4[i], DP_B5[0].mul_add(k1[i], DP_B5[2] * k3[i])),
                            ),
                        ),
                        y[i],
                    )
                })
                .collect();

            // 4th order solution for error estimate
            let y_4th: Vec<f64> = (0..n)
                .map(|i| {
                    h.mul_add(
                        DP_B4[5].mul_add(
                            k6[i],
                            DP_B4[4].mul_add(
                                k5[i],
                                DP_B4[3].mul_add(k4[i], DP_B4[0].mul_add(k1[i], DP_B4[2] * k3[i])),
                            ),
                        ),
                        y[i],
                    )
                })
                .collect();

            // Error estimate
            let err: f64 = (0..n)
                .map(|i| (y_new[i] - y_4th[i]).powi(2))
                .sum::<f64>()
                .sqrt();

            if err < tol || h < 1e-12 {
                // Accept step
                t += h;
                y = y_new;
                times.push(t);
                states.push(y.clone());

                // Increase step size
                if err > 1e-15 {
                    h *= STEP_SAFETY * (tol / err).powf(STEP_GROW_EXPONENT);
                } else {
                    h *= STEP_MAX_GROWTH;
                }
            } else {
                // Reject step, decrease h
                h *= STEP_SAFETY * (tol / err).powf(STEP_SHRINK_EXPONENT);
            }

            h = h.min(t_end - t);
        }

        (times, states)
    }

    /// Hybrid GPU/CPU integration (GPU for stage prep, CPU for f evaluation)
    fn integrate_hybrid(
        &self,
        f: &(impl Fn(f64, &[f64]) -> Vec<f64> + Send + Sync),
        t0: f64,
        y0: &[f64],
        t_end: f64,
        h_init: f64,
        tol: f64,
    ) -> Result<(Vec<f64>, Vec<Vec<f64>>)> {
        // CPU adaptive RK45 — the error-controlled step rejection loop is
        // inherently serial (next step depends on error of current step).
        // GPU acceleration applies to the stage evaluations within each step,
        // which is handled by `BatchedOdeRK45F64` for large ODE systems.
        // 2. User-provided GPU f(t,y) kernel or CPU callback
        // 3. GPU error estimation kernel
        //
        // This is more complex due to the need for custom f(t,y) kernels
        // per problem. The CPU fallback is used for correctness.
        Ok(self.integrate_cpu(f, t0, y0, t_end, h_init, tol))
    }
}

// Re-export BatchedOdeRK4F64 from its dedicated module.
// See `batched_ode_rk4.rs` for implementation and documentation.
pub use super::batched_ode_rk4::{BatchedOdeRK4F64, BatchedRk4Config};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::test_pool::get_test_device_sync;

    #[test]
    fn test_exponential_decay() {
        let device = get_test_device_sync();
        let integrator = RkIntegrator::new(device).unwrap();

        // dy/dt = -y, y(0) = 1 → y(t) = e^(-t)
        let f = |_t: f64, y: &[f64]| vec![-y[0]];

        let (times, states) = integrator
            .integrate_adaptive(&f, 0.0, &[1.0], 2.0, 0.1, 1e-6)
            .unwrap();

        let final_y = states.last().unwrap()[0];
        let expected = (-2.0_f64).exp();

        assert!(
            (final_y - expected).abs() < 1e-4,
            "y(2) = {final_y}, expected {expected}"
        );
        assert!(*times.last().unwrap() >= 2.0 - 1e-10);
    }

    #[test]
    fn test_harmonic_oscillator() {
        let device = get_test_device_sync();
        let integrator = RkIntegrator::new(device).unwrap();

        // d²x/dt² = -x → x'' + x = 0
        // y = [x, x'] → y' = [x', -x]
        // x(0) = 1, x'(0) = 0 → x(t) = cos(t)
        let f = |_t: f64, y: &[f64]| vec![y[1], -y[0]];

        let (times, states) = integrator
            .integrate_fixed(&f, 0.0, &[1.0, 0.0], std::f64::consts::PI, 0.01)
            .unwrap();

        // At t = π, x should be -1
        let final_x = states.last().unwrap()[0];
        assert!(
            (final_x + 1.0).abs() < 0.01,
            "x(π) = {final_x}, expected -1"
        );

        // Check conservation: x² + (x')² = 1
        for state in &states {
            let energy = state[1].mul_add(state[1], state[0].powi(2));
            assert!((energy - 1.0).abs() < 0.01, "Energy = {energy}, expected 1");
        }

        assert!(*times.last().unwrap() >= std::f64::consts::PI - 0.01);
    }

    #[test]
    fn test_lotka_volterra() {
        let device = get_test_device_sync();
        let integrator = RkIntegrator::new(device).unwrap();

        // Predator-prey model
        // dx/dt = αx - βxy  (prey)
        // dy/dt = δxy - γy  (predator)
        let alpha = 1.1;
        let beta = 0.4;
        let delta = 0.1;
        let gamma = 0.4;

        let f = move |_t: f64, y: &[f64]| {
            vec![
                (beta * y[0]).mul_add(-y[1], alpha * y[0]),
                (delta * y[0]).mul_add(y[1], -(gamma * y[1])),
            ]
        };

        let (times, states) = integrator
            .integrate_adaptive(&f, 0.0, &[10.0, 10.0], 50.0, 0.1, 1e-4)
            .unwrap();

        // Check that populations remain positive
        for state in &states {
            assert!(state[0] > 0.0, "Prey went negative");
            assert!(state[1] > 0.0, "Predator went negative");
        }

        // Check that simulation completed
        assert!(*times.last().unwrap() >= 49.9);
    }
}