diffsol-c 0.8.0

A diffsol wrapper featuring runtime scalar/matrix/solver types and a C API
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
//! Checks that the callbacks [`OdeCallbacks`] requires before a solve (its requirement table)
//! are exactly the callbacks that the solve calls.
//!
//! For each model, operation and solver method, each optional derivative callback is removed
//! in turn. The operation is then run directly (not through `GenericSolve`, so without the
//! check before the solve), and the result is compared with the requirement table:
//! - a callback the table does not require must never be found missing during the solve, and
//! - a callback the table requires must be found missing during the solve.

use std::ffi::c_void;
use std::panic::AssertUnwindSafe;

use diffsol::{
    DefaultSolver, DenseMatrix, NalgebraContext, NalgebraMat, OdeBuilder, OdeSolverProblem, Op,
};

use crate::linear_solver_type::LinearSolverType;
use crate::ode_callbacks::{OdeCallbackError, OdeCallbacks, OdeCallbacksDesc};
use crate::ode_solver_type::OdeSolverType;
use crate::solve_eqn::{EqnRequirement, SolveEqn};

type M = NalgebraMat<f64>;
type LS = <M as DefaultSolver>::LS;
type Eqn = OdeCallbacks<M>;

// The logistic model `dy/dt = r y (1 - y)`, `y(0) = 0.1`, with `out = y`, a root at `y = 0.9`
// that resets the state to `y = 0.1`, and an identity mass matrix. Every adjoint callback
// computes the negative transpose product.

unsafe fn get(ptr: *const f64) -> f64 {
    unsafe { *ptr }
}

unsafe fn set(ptr: *mut f64, value: f64) -> i32 {
    unsafe { *ptr = value };
    0
}

unsafe extern "C" fn rhs(x: *const f64, p: *const f64, _: f64, y: *mut f64, _: *mut c_void) -> i32 {
    unsafe { set(y, get(p) * get(x) * (1.0 - get(x))) }
}

unsafe extern "C" fn rhs_jac(
    x: *const f64,
    p: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(p) * (1.0 - 2.0 * get(x)) * get(v)) }
}

unsafe extern "C" fn rhs_sens(
    x: *const f64,
    _: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(x) * (1.0 - get(x)) * get(v)) }
}

unsafe extern "C" fn rhs_adjoint(
    x: *const f64,
    p: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, -get(p) * (1.0 - 2.0 * get(x)) * get(v)) }
}

unsafe extern "C" fn rhs_sens_adjoint(
    x: *const f64,
    _: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, -get(x) * (1.0 - get(x)) * get(v)) }
}

unsafe extern "C" fn init(_: *const f64, _: f64, y: *mut f64, _: *mut c_void) -> i32 {
    unsafe { set(y, 0.1) }
}

unsafe extern "C" fn init_zero(
    _: *const f64,
    _: f64,
    _: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, 0.0) }
}

unsafe extern "C" fn identity(
    x: *const f64,
    _: *const f64,
    _: f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(x)) }
}

unsafe extern "C" fn root(
    x: *const f64,
    _: *const f64,
    _: f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(x) - 0.9) }
}

unsafe extern "C" fn reset(
    _: *const f64,
    _: *const f64,
    _: f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, 0.1) }
}

unsafe extern "C" fn identity_mul(
    _: *const f64,
    _: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(v)) }
}

unsafe extern "C" fn neg_identity_mul(
    _: *const f64,
    _: *const f64,
    _: f64,
    v: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, -get(v)) }
}

unsafe extern "C" fn zero_mul(
    _: *const f64,
    _: *const f64,
    _: f64,
    _: *const f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, 0.0) }
}

unsafe extern "C" fn mass(
    v: *const f64,
    _: *const f64,
    _: f64,
    beta: f64,
    y: *mut f64,
    _: *mut c_void,
) -> i32 {
    unsafe { set(y, get(v) + beta * get(y)) }
}

/// The logistic model with every derivative callback. `out`, `hybrid` (root and reset) and
/// `mass` add those parts of the model.
fn model(out: bool, hybrid: bool, with_mass: bool) -> OdeCallbacksDesc<f64> {
    let mut d = OdeCallbacksDesc::new(1, 1, rhs, init);
    d.rhs_jac = Some(rhs_jac);
    d.rhs_sens = Some(rhs_sens);
    d.rhs_adjoint = Some(rhs_adjoint);
    d.rhs_sens_adjoint = Some(rhs_sens_adjoint);
    d.init_sens = Some(init_zero);
    d.init_sens_adjoint = Some(init_zero);
    if out {
        d.nout = 1;
        d.out = Some(identity);
        d.out_jac = Some(identity_mul);
        d.out_sens = Some(zero_mul);
        d.out_adjoint = Some(neg_identity_mul);
        d.out_sens_adjoint = Some(zero_mul);
    }
    if hybrid {
        d.nroots = 1;
        d.root = Some(root);
        d.root_jac = Some(identity_mul);
        d.root_sens = Some(zero_mul);
        d.root_adjoint = Some(neg_identity_mul);
        d.root_sens_adjoint = Some(zero_mul);
        d.reset = Some(reset);
        d.reset_jac = Some(zero_mul);
        d.reset_sens = Some(zero_mul);
        d.reset_adjoint = Some(zero_mul);
        d.reset_sens_adjoint = Some(zero_mul);
    }
    if with_mass {
        d.mass = Some(mass);
        d.mass_adjoint = Some(mass);
    }
    d
}

/// The optional derivative callbacks, which are removed in turn.
const OPTIONAL: [&str; 19] = [
    "rhs_jac",
    "rhs_sens",
    "rhs_adjoint",
    "rhs_sens_adjoint",
    "init_sens",
    "init_sens_adjoint",
    "mass_adjoint",
    "out_jac",
    "out_sens",
    "out_adjoint",
    "out_sens_adjoint",
    "root_jac",
    "root_sens",
    "root_adjoint",
    "root_sens_adjoint",
    "reset_jac",
    "reset_sens",
    "reset_adjoint",
    "reset_sens_adjoint",
];

/// `desc` without the callback `name`, or `None` if `desc` does not have it.
fn without(mut d: OdeCallbacksDesc<f64>, name: &str) -> Option<OdeCallbacksDesc<f64>> {
    let present = match name {
        "rhs_jac" => d.rhs_jac.take().is_some(),
        "rhs_sens" => d.rhs_sens.take().is_some(),
        "rhs_adjoint" => d.rhs_adjoint.take().is_some(),
        "rhs_sens_adjoint" => d.rhs_sens_adjoint.take().is_some(),
        "init_sens" => d.init_sens.take().is_some(),
        "init_sens_adjoint" => d.init_sens_adjoint.take().is_some(),
        "mass_adjoint" => d.mass_adjoint.take().is_some(),
        "out_jac" => d.out_jac.take().is_some(),
        "out_sens" => d.out_sens.take().is_some(),
        "out_adjoint" => d.out_adjoint.take().is_some(),
        "out_sens_adjoint" => d.out_sens_adjoint.take().is_some(),
        "root_jac" => d.root_jac.take().is_some(),
        "root_sens" => d.root_sens.take().is_some(),
        "root_adjoint" => d.root_adjoint.take().is_some(),
        "root_sens_adjoint" => d.root_sens_adjoint.take().is_some(),
        "reset_jac" => d.reset_jac.take().is_some(),
        "reset_sens" => d.reset_sens.take().is_some(),
        "reset_adjoint" => d.reset_adjoint.take().is_some(),
        "reset_sens_adjoint" => d.reset_sens_adjoint.take().is_some(),
        _ => unreachable!("unknown callback {name}"),
    };
    present.then_some(d)
}

#[derive(Clone, Copy, Debug)]
enum Operation {
    Solve,
    FwdSens,
    ContinuousAdjoint,
    SplitAdjoint,
}

impl Operation {
    fn requirement(self, method: OdeSolverType) -> EqnRequirement {
        match self {
            Operation::Solve => EqnRequirement::Solve(method),
            Operation::FwdSens => EqnRequirement::FwdSens,
            Operation::ContinuousAdjoint | Operation::SplitAdjoint => {
                EqnRequirement::Adjoint(method)
            }
        }
    }
}

const FINAL_TIME: f64 = 5.0;
const T_EVAL: [f64; 6] = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];

fn problem(desc: OdeCallbacksDesc<f64>) -> OdeSolverProblem<Eqn> {
    // SAFETY: the test callbacks are valid and use the documented lengths
    let eqn = unsafe { OdeCallbacks::<M>::new(desc, NalgebraContext::default()) }.unwrap();
    OdeBuilder::<M>::new()
        .p(vec![2.0])
        .build_from_eqn(eqn)
        .unwrap()
}

/// Run `op` with `method` directly, without the check before the solve. Return whether the
/// solve succeeded, and the error the callbacks recorded (if any).
fn run(
    desc: OdeCallbacksDesc<f64>,
    op: Operation,
    method: OdeSolverType,
) -> (bool, Option<OdeCallbackError>) {
    let mut problem = problem(desc);
    let ok = match op {
        Operation::Solve => method
            .solve_dense::<M, Eqn, LS>(&mut problem, &T_EVAL)
            .is_ok(),
        Operation::FwdSens => method
            .solve_fwd_sens::<M, Eqn, LS>(&mut problem, &T_EVAL)
            .is_ok(),
        Operation::ContinuousAdjoint => {
            problem.integrate_out = true;
            method
                .solve_continuous_adjoint::<M, Eqn, LS>(&mut problem, FINAL_TIME)
                .is_ok()
        }
        Operation::SplitAdjoint => {
            let fwd = method.solve_adjoint_fwd::<M, Eqn, LS>(
                &mut problem,
                &T_EVAL,
                &[2.0],
                LinearSolverType::Default,
            );
            let error = problem.eqn.take_callback_error();
            let checkpoint = match (fwd, error) {
                (Ok((_, checkpoint)), None) => checkpoint,
                (fwd, error) => return (fwd.is_ok(), error),
            };
            let nout = problem.eqn.nout();
            let dgdu = M::from_vec(
                nout,
                T_EVAL.len(),
                vec![1.0; nout * T_EVAL.len()],
                NalgebraContext::default(),
            );
            method
                .solve_adjoint_bkwd::<M, Eqn, LS>(&mut problem, checkpoint.as_ref(), &dgdu, &T_EVAL)
                .is_ok()
        }
    };
    (ok, problem.eqn.take_callback_error())
}

const METHODS: [OdeSolverType; 4] = [
    OdeSolverType::Bdf,
    OdeSolverType::Esdirk34,
    OdeSolverType::TrBdf2,
    OdeSolverType::Tsit45,
];

const OPERATIONS: [Operation; 4] = [
    Operation::Solve,
    Operation::FwdSens,
    Operation::ContinuousAdjoint,
    Operation::SplitAdjoint,
];

#[test]
fn requirement_table_matches_the_callbacks_each_solve_calls() {
    let models = [
        ("plain", model(false, false, false)),
        ("out", model(true, false, false)),
        ("out + root/reset", model(true, true, false)),
        ("out + mass", model(true, false, true)),
        ("out + root/reset + mass", model(true, true, true)),
    ];
    let mut mismatches = Vec::new();
    let mut checked = 0;
    for (model_name, full) in models {
        for op in OPERATIONS {
            for method in METHODS {
                // only compare where the solve works with every callback provided
                let baseline = std::panic::catch_unwind(AssertUnwindSafe(|| run(full, op, method)));
                match baseline {
                    Ok((true, None)) => {}
                    Ok(_) => continue,
                    Err(_) => {
                        mismatches.push(format!(
                            "{model_name}, {op:?}, {method:?}: panics with every callback"
                        ));
                        continue;
                    }
                }
                for name in OPTIONAL {
                    let Some(desc) = without(full, name) else {
                        continue;
                    };
                    let required = problem(desc)
                        .eqn
                        .check_requirement(op.requirement(method))
                        .is_err();
                    let Ok((_, error)) =
                        std::panic::catch_unwind(AssertUnwindSafe(|| run(desc, op, method)))
                    else {
                        mismatches.push(format!(
                            "{model_name}, {op:?}, {method:?}, without '{name}': panics"
                        ));
                        continue;
                    };
                    let called = matches!(
                        error,
                        Some(OdeCallbackError::Missing { callback }) if callback == name
                    );
                    checked += 1;
                    if required != called {
                        mismatches.push(format!(
                            "{model_name}, {op:?}, {method:?}, without '{name}': \
                             the table {} it, the solve {} it",
                            if required {
                                "requires"
                            } else {
                                "does not require"
                            },
                            if called { "calls" } else { "does not call" },
                        ));
                    }
                }
            }
        }
    }
    assert!(checked > 0);
    assert!(
        mismatches.is_empty(),
        "{} mismatches:\n{}",
        mismatches.len(),
        mismatches.join("\n")
    );
}