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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Generic batched ODE RK4 solver for barracuda.
//!
//! Replaces the 5 domain-specific ODE shaders from wetSpring (`phage_defense`,
//! bistable, `multi_signal`, cooperation, capacitor) with a single generic
//! infrastructure. New ODE systems are added by implementing [`OdeSystem`]
//! without writing a new WGSL shader each time.
//!
//! ## Module structure
//!
//! - [`OdeSystem`] trait, [`BatchedOdeRK4`] solver, [`OdeTrajectory`] recording
//! - `wgsl_templates` — WGSL RK4 kernel code generation (f64 + universal precision)
//!
//! # Example
//!
//! ```ignore
//! use barracuda::numerical::ode_generic::{BatchedOdeRK4, OdeSystem};
//!
//! struct ExponentialDecay;
//! impl OdeSystem for ExponentialDecay {
//!     const N_VARS: usize = 1;
//!     const N_PARAMS: usize = 1;
//!
//!     fn system_name() -> &'static str { "exponential_decay" }
//!
//!     fn wgsl_derivative() -> &'static str {
//!         r#"
//! fn deriv(state: array<f64, 1>, params: array<f64, 1>, t: f64) -> array<f64, 1> {
//!     let k = params[0];
//!     var dy: array<f64, 1>;
//!     dy[0] = -k * state[0];
//!     return dy;
//! }
//! "#
//!     }
//! }
//!
//! let initial = vec![1.0, 1.0];  // 2 batches, 1 var each
//! let params = vec![1.0, 2.0];   // k=1 and k=2
//! let finals = BatchedOdeRK4::<ExponentialDecay>::integrate_cpu(
//!     &initial, &params, 0.01, 100, 2
//! );
//! ```

mod wgsl_templates;

use std::marker::PhantomData;

use crate::error::{BarracudaError, Result};
use wgsl_templates::{wgsl_rk4_template, wgsl_rk4_template_universal};

/// Trait for ODE systems that can be integrated by the generic batched RK4 solver.
///
/// Implement this trait to add new ODE systems without writing a new WGSL shader.
/// The derivative function must have the signature:
/// `fn deriv(state: array<f64, N_VARS>, params: array<f64, N_PARAMS>, t: f64) -> array<f64, N_VARS>`
pub trait OdeSystem {
    /// Number of state variables.
    const N_VARS: usize;
    /// Number of parameters per batch.
    const N_PARAMS: usize;

    /// Name used for WGSL function generation and diagnostics.
    fn system_name() -> &'static str;

    /// WGSL source for the derivative function (f64).
    ///
    /// Must define: `fn deriv(state: array<f64, N_VARS>, params: array<f64, N_PARAMS>, t: f64) -> array<f64, N_VARS>`
    fn wgsl_derivative() -> &'static str;

    /// WGSL source for the derivative function using universal precision (`Scalar`/`op_*`).
    ///
    /// Must define: `fn deriv(state: array<Scalar, N_VARS>, params: array<Scalar, N_PARAMS>, t: Scalar) -> array<Scalar, N_VARS>`
    ///
    /// Default: `None` (falls back to f64 variant). Implement this when evolving
    /// ODE systems to universal precision.
    #[must_use]
    fn wgsl_derivative_universal() -> Option<&'static str> {
        None
    }

    /// CPU implementation of the derivative for testing and small batches.
    ///
    /// Returns dy/dt given time, state, and params. The params slice has length `N_PARAMS`.
    fn cpu_derivative(_t: f64, state: &[f64], params: &[f64]) -> Vec<f64>;
}

/// Result of an ODE integration that records the full trajectory.
///
/// Provides convenience methods for time-series extraction and
/// state interpolation (wetSpring V105 / airSpring V075 request).
#[derive(Debug, Clone)]
pub struct OdeTrajectory {
    /// Flattened state snapshots: `[step][batch][var]` stored as
    /// `[n_steps+1][batch_size][n_vars]` in row-major order.
    pub states: Vec<f64>,
    /// Time at each snapshot.
    pub times: Vec<f64>,
    /// Number of state variables per system.
    pub n_vars: usize,
    /// Number of batched systems.
    pub batch_size: usize,
}

impl OdeTrajectory {
    /// Extract the full time series for a given batch index and variable index.
    ///
    /// Returns `(times, values)` where `times[i]` is the time and `values[i]`
    /// is the state variable at that time.
    #[must_use]
    pub fn time_series(&self, batch: usize, var: usize) -> (Vec<f64>, Vec<f64>) {
        let n_snapshots = self.times.len();
        let stride = self.batch_size * self.n_vars;
        let mut values = Vec::with_capacity(n_snapshots);
        for step in 0..n_snapshots {
            values.push(self.states[step * stride + batch * self.n_vars + var]);
        }
        (self.times.clone(), values)
    }

    /// Interpolate state at an arbitrary time for a given batch.
    ///
    /// Uses linear interpolation between the two nearest snapshots.
    /// Returns `None` if `t` is outside the integration range.
    #[must_use]
    pub fn state_at(&self, batch: usize, t: f64) -> Option<Vec<f64>> {
        if self.times.is_empty() {
            return None;
        }
        let t_start = self.times[0];
        let t_end = *self.times.last()?;
        if t < t_start || t > t_end {
            return None;
        }

        let idx = self
            .times
            .partition_point(|&ti| ti < t)
            .min(self.times.len() - 1);

        if idx == 0 || (self.times[idx] - t).abs() < f64::EPSILON {
            let stride = self.batch_size * self.n_vars;
            let off = idx * stride + batch * self.n_vars;
            return Some(self.states[off..off + self.n_vars].to_vec());
        }

        let t0 = self.times[idx - 1];
        let t1 = self.times[idx];
        let frac = (t - t0) / (t1 - t0);

        let stride = self.batch_size * self.n_vars;
        let off0 = (idx - 1) * stride + batch * self.n_vars;
        let off1 = idx * stride + batch * self.n_vars;

        let mut state = vec![0.0; self.n_vars];
        for (i, s) in state.iter_mut().enumerate() {
            *s = self.states[off0 + i].mul_add(1.0 - frac, self.states[off1 + i] * frac);
        }
        Some(state)
    }

    /// Number of time snapshots (including the initial state).
    #[must_use]
    pub fn n_snapshots(&self) -> usize {
        self.times.len()
    }

    /// Final state for a given batch.
    #[must_use]
    pub fn final_state(&self, batch: usize) -> Option<Vec<f64>> {
        if self.times.is_empty() {
            return None;
        }
        let stride = self.batch_size * self.n_vars;
        let last = (self.times.len() - 1) * stride + batch * self.n_vars;
        Some(self.states[last..last + self.n_vars].to_vec())
    }
}

/// Batched 4th-order Runge-Kutta ODE integrator.
///
/// Integrates multiple parameter sets in parallel. Each batch has its own
/// initial state and parameter vector. Uses fixed-step RK4.
#[must_use]
pub struct BatchedOdeRK4<S: OdeSystem> {
    _marker: PhantomData<S>,
}

impl<S: OdeSystem> BatchedOdeRK4<S> {
    /// Generate complete f64 WGSL shader source by combining the RK4 template with the system's derivative.
    #[must_use]
    pub fn generate_shader() -> String {
        wgsl_rk4_template(S::N_VARS, S::N_PARAMS, S::wgsl_derivative())
    }

    /// Generate universal-precision WGSL shader using `Scalar`/`op_*`.
    ///
    /// Returns `Some(shader)` if the system provides a universal derivative,
    /// `None` otherwise. Prepend a precision-specific `op_preamble()` and compile
    /// via the appropriate pipeline for the target
    /// [`Precision`](crate::shaders::precision::Precision).
    #[must_use]
    pub fn generate_shader_universal() -> Option<String> {
        S::wgsl_derivative_universal()
            .map(|deriv| wgsl_rk4_template_universal(S::N_VARS, S::N_PARAMS, deriv))
    }

    /// Run batched RK4 integration on CPU (for testing / small batches).
    ///
    /// # Arguments
    /// * `initial_states` — flat `[batch_size × N_VARS]` f64 slice (row-major)
    /// * `params` — flat `[batch_size × N_PARAMS]` f64 slice (row-major)
    /// * `dt` — fixed step size
    /// * `n_steps` — number of RK4 steps
    /// * `batch_size` — number of independent trajectories
    ///
    /// # Returns
    /// Flat `[batch_size × N_VARS]` f64 `Vec` with the final state for each batch.
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if `initial_states` or `params` length does not match
    /// `batch_size × N_VARS` or `batch_size × N_PARAMS` respectively.
    pub fn integrate_cpu(
        initial_states: &[f64],
        params: &[f64],
        dt: f64,
        n_steps: usize,
        batch_size: usize,
    ) -> Result<Vec<f64>> {
        let n_vars = S::N_VARS;
        let n_params = S::N_PARAMS;

        if initial_states.len() != batch_size * n_vars {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "initial_states: expected {} ([batch_size×{}]), got {}",
                    batch_size * n_vars,
                    n_vars,
                    initial_states.len()
                ),
            });
        }
        if params.len() != batch_size * n_params {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "params: expected {} ([batch_size×{}]), got {}",
                    batch_size * n_params,
                    n_params,
                    params.len()
                ),
            });
        }

        let mut state: Vec<f64> = initial_states.to_vec();
        let mut t = 0.0_f64;

        let mut y_buf = vec![0.0_f64; n_vars];
        let mut stage_buf = vec![0.0_f64; n_vars];

        for _step in 0..n_steps {
            for b in 0..batch_size {
                let s_off = b * n_vars;
                let p = &params[b * n_params..b * n_params + n_params];

                y_buf.copy_from_slice(&state[s_off..s_off + n_vars]);

                let k1 = S::cpu_derivative(t, &y_buf, p);

                for i in 0..n_vars {
                    stage_buf[i] = (0.5 * dt).mul_add(k1[i], y_buf[i]);
                }
                let k2 = S::cpu_derivative(0.5f64.mul_add(dt, t), &stage_buf, p);

                for i in 0..n_vars {
                    stage_buf[i] = (0.5 * dt).mul_add(k2[i], y_buf[i]);
                }
                let k3 = S::cpu_derivative(0.5f64.mul_add(dt, t), &stage_buf, p);

                for i in 0..n_vars {
                    stage_buf[i] = dt.mul_add(k3[i], y_buf[i]);
                }
                let k4 = S::cpu_derivative(t + dt, &stage_buf, p);

                let sixth = 1.0 / 6.0;
                for i in 0..n_vars {
                    state[s_off + i] = (dt * sixth).mul_add(
                        2.0f64.mul_add(k3[i], 2.0f64.mul_add(k2[i], k1[i])) + k4[i],
                        y_buf[i],
                    );
                }
            }
            t += dt;
        }

        Ok(state)
    }

    /// CPU integration that records the full trajectory at every step.
    ///
    /// Returns an [`OdeTrajectory`] with state snapshots at each time step,
    /// enabling `.time_series(batch, var)` and `.state_at(batch, t)` queries.
    ///
    /// # Errors
    /// Returns [`Err`] if input dimensions are inconsistent.
    pub fn integrate_cpu_trajectory(
        initial_states: &[f64],
        params: &[f64],
        dt: f64,
        n_steps: usize,
        batch_size: usize,
    ) -> Result<OdeTrajectory> {
        let n_vars = S::N_VARS;
        let n_params = S::N_PARAMS;

        if initial_states.len() != batch_size * n_vars {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "initial_states: expected {} ([batch_size×{n_vars}]), got {}",
                    batch_size * n_vars,
                    initial_states.len()
                ),
            });
        }
        if params.len() != batch_size * n_params {
            return Err(BarracudaError::InvalidInput {
                message: format!(
                    "params: expected {} ([batch_size×{n_params}]), got {}",
                    batch_size * n_params,
                    params.len()
                ),
            });
        }

        let stride = batch_size * n_vars;
        let n_snapshots = n_steps + 1;
        let mut all_states = Vec::with_capacity(n_snapshots * stride);
        let mut times = Vec::with_capacity(n_snapshots);

        let mut state: Vec<f64> = initial_states.to_vec();
        all_states.extend_from_slice(&state);
        times.push(0.0);

        let mut t = 0.0_f64;
        let mut y_buf = vec![0.0_f64; n_vars];
        let mut stage_buf = vec![0.0_f64; n_vars];

        for _step in 0..n_steps {
            for b in 0..batch_size {
                let s_off = b * n_vars;
                let p = &params[b * n_params..b * n_params + n_params];

                y_buf.copy_from_slice(&state[s_off..s_off + n_vars]);

                let k1 = S::cpu_derivative(t, &y_buf, p);
                for i in 0..n_vars {
                    stage_buf[i] = (0.5 * dt).mul_add(k1[i], y_buf[i]);
                }
                let k2 = S::cpu_derivative(0.5f64.mul_add(dt, t), &stage_buf, p);
                for i in 0..n_vars {
                    stage_buf[i] = (0.5 * dt).mul_add(k2[i], y_buf[i]);
                }
                let k3 = S::cpu_derivative(0.5f64.mul_add(dt, t), &stage_buf, p);
                for i in 0..n_vars {
                    stage_buf[i] = dt.mul_add(k3[i], y_buf[i]);
                }
                let k4 = S::cpu_derivative(t + dt, &stage_buf, p);

                let sixth = 1.0 / 6.0;
                for i in 0..n_vars {
                    state[s_off + i] = (dt * sixth).mul_add(
                        2.0f64.mul_add(k3[i], 2.0f64.mul_add(k2[i], k1[i])) + k4[i],
                        y_buf[i],
                    );
                }
            }
            t += dt;
            all_states.extend_from_slice(&state);
            times.push(t);
        }

        Ok(OdeTrajectory {
            states: all_states,
            times,
            n_vars,
            batch_size,
        })
    }
}

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

    /// Exponential decay: dy/dt = -k*y, y(0)=y0 → y(t)=y0*exp(-k*t)
    struct ExponentialDecay;

    impl OdeSystem for ExponentialDecay {
        const N_VARS: usize = 1;
        const N_PARAMS: usize = 1;

        fn system_name() -> &'static str {
            "exponential_decay"
        }

        fn wgsl_derivative() -> &'static str {
            r"
fn deriv(state: array<f64, 1>, params: array<f64, 1>, t: f64) -> array<f64, 1> {
    let k = params[0];
    var dy: array<f64, 1>;
    dy[0] = -k * state[0];
    return dy;
}
"
        }

        fn wgsl_derivative_universal() -> Option<&'static str> {
            Some(
                r"
fn deriv(state: array<Scalar, 1>, params: array<Scalar, 1>, t: Scalar) -> array<Scalar, 1> {
    let k = params[0];
    var dy: array<Scalar, 1>;
    dy[0] = op_neg(op_mul(k, state[0]));
    return dy;
}
",
            )
        }

        fn cpu_derivative(_t: f64, state: &[f64], params: &[f64]) -> Vec<f64> {
            let k = params[0];
            vec![-k * state[0]]
        }
    }

    #[test]
    fn test_exponential_decay_cpu_matches_analytical() {
        // dy/dt = -k*y, y(0)=1 → y(t)=exp(-k*t)
        let k = 1.0_f64;
        let t_final = 1.0_f64;
        let dt = 0.001_f64;
        let n_steps = (t_final / dt).round() as usize;

        let initial = vec![1.0];
        let params = vec![k];

        let result =
            BatchedOdeRK4::<ExponentialDecay>::integrate_cpu(&initial, &params, dt, n_steps, 1)
                .expect("integrate_cpu should succeed");

        let expected = (-k * t_final).exp();
        assert!(
            (result[0] - expected).abs() < 1e-6,
            "y(1) = {}, expected {}",
            result[0],
            expected
        );
    }

    #[test]
    fn test_exponential_decay_batched() {
        let initial = vec![1.0, 2.0]; // 2 batches
        let params = vec![1.0, 0.5]; // k=1 and k=0.5
        let dt = 0.01;
        let n_steps = 100;

        let result =
            BatchedOdeRK4::<ExponentialDecay>::integrate_cpu(&initial, &params, dt, n_steps, 2)
                .expect("integrate_cpu should succeed");

        let expected_0 = (-1.0_f64).exp();
        let expected_1 = 2.0 * (-0.5_f64).exp();
        assert!(
            (result[0] - expected_0).abs() < 1e-4,
            "batch 0: got {}, expected {}",
            result[0],
            expected_0
        );
        assert!(
            (result[1] - expected_1).abs() < 1e-4,
            "batch 1: got {}, expected {}",
            result[1],
            expected_1
        );
    }

    #[test]
    fn test_generated_wgsl_has_expected_structure() {
        let shader = BatchedOdeRK4::<ExponentialDecay>::generate_shader();
        assert!(shader.contains("fn main"));
        assert!(shader.contains("fn deriv"));
        assert!(shader.contains("fn rk4_step"));
        assert!(shader.contains("@compute @workgroup_size(64)"));
        assert!(shader.contains("const N_VARS:   u32 = 1u"));
        assert!(shader.contains("const N_PARAMS: u32 = 1u"));
    }

    #[test]
    fn test_generated_universal_wgsl_has_expected_structure() {
        let shader = BatchedOdeRK4::<ExponentialDecay>::generate_shader_universal()
            .expect("ExponentialDecay should have a universal derivative");
        assert!(shader.contains("fn main"));
        assert!(shader.contains("fn deriv"));
        assert!(shader.contains("fn rk4_step"));
        assert!(shader.contains("Scalar"));
        assert!(shader.contains("op_add"));
        assert!(shader.contains("op_mul"));
        assert!(shader.contains("op_from_f32"));
        assert!(
            !shader.contains("f64"),
            "universal template must not contain raw f64"
        );
    }

    #[test]
    #[cfg(feature = "gpu")]
    fn test_generated_wgsl_compiles() {
        let Some(device) = crate::device::test_pool::get_test_device_if_f64_gpu_available_sync()
        else {
            return;
        };
        let shader = BatchedOdeRK4::<ExponentialDecay>::generate_shader();
        let _ = device.compile_shader_f64(&shader, Some("ode_generic_exponential_decay"));
    }

    #[test]
    fn test_integrate_cpu_invalid_initial_states_len() {
        let initial = vec![1.0, 2.0, 3.0]; // wrong size for batch_size=1
        let params = vec![1.0];
        let result =
            BatchedOdeRK4::<ExponentialDecay>::integrate_cpu(&initial, &params, 0.01, 10, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_integrate_cpu_invalid_params_len() {
        let initial = vec![1.0];
        let params = vec![1.0, 2.0]; // wrong size for batch_size=1
        let result =
            BatchedOdeRK4::<ExponentialDecay>::integrate_cpu(&initial, &params, 0.01, 10, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_trajectory_time_series() {
        let initial = vec![1.0];
        let params = vec![1.0]; // k=1
        let traj = BatchedOdeRK4::<ExponentialDecay>::integrate_cpu_trajectory(
            &initial, &params, 0.01, 100, 1,
        )
        .unwrap();

        assert_eq!(traj.n_snapshots(), 101);

        let (times, values) = traj.time_series(0, 0);
        assert_eq!(times.len(), 101);
        assert!((times[0] - 0.0).abs() < 1e-14);
        assert!((times[100] - 1.0).abs() < 1e-10);

        // Exponential decay: y(1) = exp(-1) ≈ 0.3679
        let expected = (-1.0_f64).exp();
        assert!(
            (values[100] - expected).abs() < 1e-6,
            "y(1) = {}, expected {}",
            values[100],
            expected
        );
    }

    #[test]
    fn test_trajectory_state_at_interpolation() {
        let initial = vec![1.0];
        let params = vec![1.0];
        let traj = BatchedOdeRK4::<ExponentialDecay>::integrate_cpu_trajectory(
            &initial, &params, 0.1, 10, 1,
        )
        .unwrap();

        // Interpolate at t=0.55 (between step 5 at t=0.5 and step 6 at t=0.6)
        let state = traj.state_at(0, 0.55).unwrap();
        let expected = (-0.55_f64).exp();
        assert!(
            (state[0] - expected).abs() < 1e-3,
            "y(0.55) = {}, expected {}",
            state[0],
            expected
        );

        // Outside range returns None
        assert!(traj.state_at(0, -0.1).is_none());
        assert!(traj.state_at(0, 1.1).is_none());
    }

    #[test]
    fn test_trajectory_final_state() {
        let initial = vec![1.0, 2.0]; // 2 batches
        let params = vec![1.0, 0.5]; // k=1 and k=0.5
        let traj = BatchedOdeRK4::<ExponentialDecay>::integrate_cpu_trajectory(
            &initial, &params, 0.01, 100, 2,
        )
        .unwrap();

        let final_0 = traj.final_state(0).unwrap();
        let final_1 = traj.final_state(1).unwrap();

        let expected_0 = (-1.0_f64).exp();
        let expected_1 = 2.0 * (-0.5_f64).exp();

        assert!(
            (final_0[0] - expected_0).abs() < 1e-6,
            "batch 0: {} vs {}",
            final_0[0],
            expected_0
        );
        assert!(
            (final_1[0] - expected_1).abs() < 1e-6,
            "batch 1: {} vs {}",
            final_1[0],
            expected_1
        );
    }
}