diffsol 0.12.4

A library for solving ordinary differential equations (ODEs) in Rust.
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
use crate::{
    ConstantOp, ConstantOpSens, ConstantOpSensAdjoint, Context, LinearOp, LinearOpTranspose,
    Matrix, NonLinearOp, NonLinearOpAdjoint, NonLinearOpSens, NonLinearOpSensAdjoint, Scalar,
    Vector,
};

use nonlinear_op::NonLinearOpJacobian;
use serde::Serialize;

pub mod bdf;
pub mod closure;
pub mod closure_no_jac;
pub mod closure_with_adjoint;
pub mod closure_with_sens;
pub mod constant_closure;
pub mod constant_closure_with_adjoint;
pub mod constant_closure_with_sens;
pub mod constant_op;
pub mod init;
pub mod linear_closure;
pub mod linear_closure_with_adjoint;
pub mod linear_op;
pub mod linearise;
pub mod matrix;
pub mod nonlinear_op;
pub mod sdirk;
pub mod stoch;
pub mod unit;

/// A generic operator trait.
///
/// Op is a trait for operators that, given a paramter vector `p`, operates on an input vector `x` to produce an output vector `y`.
/// It defines the number of states (i.e. length of `x`), the number of outputs (i.e. length of `y`), and number of parameters (i.e. length of `p`) of the operator.
/// It also defines the type of the scalar, vector, and matrices used in the operator.
pub trait Op {
    type T: Scalar;
    type V: Vector<T = Self::T, C = Self::C>;
    type M: Matrix<T = Self::T, V = Self::V, C = Self::C>;
    type C: Context;

    /// return the context of the operator
    fn context(&self) -> &Self::C;

    /// Return the number of input states of the operator.
    fn nstates(&self) -> usize;

    /// Return the number of outputs of the operator.
    fn nout(&self) -> usize;

    /// Return the number of parameters of the operator.
    fn nparams(&self) -> usize;

    /// Return statistics about the operator (e.g. how many times it was called, how many times the jacobian was computed, etc.)
    fn statistics(&self) -> OpStatistics {
        OpStatistics::default()
    }
}

/// A wrapper for an operator that parameterises it with a parameter vector.
pub struct ParameterisedOp<'a, C: Op> {
    pub op: &'a C,
    pub p: &'a C::V,
}

impl<'a, C: Op> ParameterisedOp<'a, C> {
    pub fn new(op: &'a C, p: &'a C::V) -> Self {
        Self { op, p }
    }
}

/// trait interface for operators used in the [builder pattern](crate::OdeBuilder)
pub trait BuilderOp: Op {
    fn set_nstates(&mut self, nstates: usize);
    fn set_nparams(&mut self, nparams: usize);
    fn set_nout(&mut self, nout: usize);
    fn calculate_sparsity(&mut self, y0: &Self::V, t0: Self::T, p: &Self::V);
}

impl<C: Op> Op for ParameterisedOp<'_, C> {
    type V = C::V;
    type T = C::T;
    type M = C::M;
    type C = C::C;
    fn nstates(&self) -> usize {
        self.op.nstates()
    }
    fn nout(&self) -> usize {
        self.op.nout()
    }
    fn nparams(&self) -> usize {
        self.op.nparams()
    }
    fn statistics(&self) -> OpStatistics {
        self.op.statistics()
    }
    fn context(&self) -> &Self::C {
        self.op.context()
    }
}

/// Useful statistics about an operator.
#[derive(Default, Clone, Serialize, Debug)]
pub struct OpStatistics {
    /// number of times the operator was called
    pub number_of_calls: usize,
    /// number of times the jacobian-vector product was computed
    pub number_of_jac_muls: usize,
    /// number of times the jacobian matrix was evaluated
    pub number_of_matrix_evals: usize,
    /// number of times the adjoint jacobian-vector product was computed
    pub number_of_jac_adj_muls: usize,
}

impl OpStatistics {
    pub fn new() -> Self {
        Self {
            number_of_jac_muls: 0,
            number_of_calls: 0,
            number_of_matrix_evals: 0,
            number_of_jac_adj_muls: 0,
        }
    }

    pub fn increment_call(&mut self) {
        self.number_of_calls += 1;
    }

    pub fn increment_jac_mul(&mut self) {
        self.number_of_jac_muls += 1;
    }

    pub fn increment_jac_adj_mul(&mut self) {
        self.number_of_jac_adj_muls += 1;
    }

    pub fn increment_matrix(&mut self) {
        self.number_of_matrix_evals += 1;
    }
}

impl<C: Op> Op for &C {
    type T = C::T;
    type V = C::V;
    type M = C::M;
    type C = C::C;
    fn nstates(&self) -> usize {
        C::nstates(*self)
    }
    fn nout(&self) -> usize {
        C::nout(*self)
    }
    fn nparams(&self) -> usize {
        C::nparams(*self)
    }
    fn statistics(&self) -> OpStatistics {
        C::statistics(*self)
    }
    fn context(&self) -> &Self::C {
        C::context(*self)
    }
}

impl<C: Op> Op for &mut C {
    type T = C::T;
    type V = C::V;
    type M = C::M;
    type C = C::C;
    fn nstates(&self) -> usize {
        C::nstates(*self)
    }
    fn nout(&self) -> usize {
        C::nout(*self)
    }
    fn nparams(&self) -> usize {
        C::nparams(*self)
    }
    fn statistics(&self) -> OpStatistics {
        C::statistics(*self)
    }
    fn context(&self) -> &Self::C {
        C::context(*self)
    }
}

impl<C: NonLinearOp> NonLinearOp for &C {
    fn call_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::V) {
        C::call_inplace(*self, x, t, y)
    }
}

impl<C: NonLinearOpJacobian> NonLinearOpJacobian for &C {
    fn jac_mul_inplace(&self, x: &Self::V, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::jac_mul_inplace(*self, x, t, v, y)
    }
    fn jacobian_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::M) {
        C::jacobian_inplace(*self, x, t, y)
    }
    fn jacobian_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::jacobian_sparsity(*self)
    }
}

impl<C: NonLinearOpAdjoint> NonLinearOpAdjoint for &C {
    fn adjoint_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::M) {
        C::adjoint_inplace(*self, x, t, y)
    }
    fn adjoint_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::adjoint_sparsity(*self)
    }
    fn jac_transpose_mul_inplace(&self, x: &Self::V, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::jac_transpose_mul_inplace(*self, x, t, v, y)
    }
}

impl<C: NonLinearOpSens> NonLinearOpSens for &C {
    fn sens_mul_inplace(&self, x: &Self::V, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::sens_mul_inplace(*self, x, t, v, y)
    }
    fn sens_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::M) {
        C::sens_inplace(*self, x, t, y)
    }

    fn sens_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::sens_sparsity(*self)
    }
}

impl<C: NonLinearOpSensAdjoint> NonLinearOpSensAdjoint for &C {
    fn sens_transpose_mul_inplace(&self, x: &Self::V, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::sens_transpose_mul_inplace(*self, x, t, v, y)
    }
    fn sens_adjoint_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::M) {
        C::sens_adjoint_inplace(*self, x, t, y)
    }
    fn sens_adjoint_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::sens_adjoint_sparsity(*self)
    }
}

impl<C: LinearOp> LinearOp for &C {
    fn gemv_inplace(&self, x: &Self::V, t: Self::T, beta: Self::T, y: &mut Self::V) {
        C::gemv_inplace(*self, x, t, beta, y)
    }
    fn sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::sparsity(*self)
    }
    fn matrix_inplace(&self, t: Self::T, y: &mut Self::M) {
        C::matrix_inplace(*self, t, y)
    }
}

impl<C: LinearOpTranspose> LinearOpTranspose for &C {
    fn gemv_transpose_inplace(&self, x: &Self::V, t: Self::T, beta: Self::T, y: &mut Self::V) {
        C::gemv_transpose_inplace(*self, x, t, beta, y)
    }
    fn transpose_inplace(&self, t: Self::T, y: &mut Self::M) {
        C::transpose_inplace(*self, t, y)
    }
    fn transpose_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::transpose_sparsity(*self)
    }
}

impl<C: ConstantOp> ConstantOp for &C {
    fn call_inplace(&self, t: Self::T, y: &mut Self::V) {
        C::call_inplace(*self, t, y)
    }
}

impl<C: ConstantOpSens> ConstantOpSens for &C {
    fn sens_mul_inplace(&self, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::sens_mul_inplace(*self, t, v, y)
    }
    fn sens_inplace(&self, t: Self::T, y: &mut Self::M) {
        C::sens_inplace(*self, t, y)
    }
    fn sens_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::sens_sparsity(*self)
    }
}

impl<C: ConstantOpSensAdjoint> ConstantOpSensAdjoint for &C {
    fn sens_transpose_mul_inplace(&self, t: Self::T, v: &Self::V, y: &mut Self::V) {
        C::sens_transpose_mul_inplace(*self, t, v, y)
    }
    fn sens_adjoint_inplace(&self, t: Self::T, y: &mut Self::M) {
        C::sens_adjoint_inplace(*self, t, y)
    }
    fn sens_adjoint_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
        C::sens_adjoint_sparsity(*self)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use crate::{
        context::nalgebra::NalgebraContext, matrix::dense_nalgebra_serial::NalgebraMat, ConstantOp,
        ConstantOpSens, ConstantOpSensAdjoint, LinearOp, LinearOpTranspose, NonLinearOp,
        NonLinearOpAdjoint, NonLinearOpJacobian, NonLinearOpSens, NonLinearOpSensAdjoint, Vector,
    };

    use super::{Op, OpStatistics, ParameterisedOp};

    type M = NalgebraMat<f64>;

    struct ForwardingOp {
        ctx: NalgebraContext,
        stats: RefCell<OpStatistics>,
    }

    impl ForwardingOp {
        fn new() -> Self {
            Self {
                ctx: NalgebraContext,
                stats: RefCell::new(OpStatistics::new()),
            }
        }
    }

    impl Op for ForwardingOp {
        type T = f64;
        type V = crate::NalgebraVec<f64>;
        type M = M;
        type C = NalgebraContext;

        fn context(&self) -> &Self::C {
            &self.ctx
        }
        fn nstates(&self) -> usize {
            2
        }
        fn nout(&self) -> usize {
            2
        }
        fn nparams(&self) -> usize {
            2
        }
        fn statistics(&self) -> OpStatistics {
            self.stats.borrow().clone()
        }
    }

    impl NonLinearOp for ForwardingOp {
        fn call_inplace(&self, x: &Self::V, _t: Self::T, y: &mut Self::V) {
            self.stats.borrow_mut().increment_call();
            y.copy_from(x);
        }
    }

    impl NonLinearOpJacobian for ForwardingOp {
        fn jac_mul_inplace(&self, _x: &Self::V, _t: Self::T, v: &Self::V, y: &mut Self::V) {
            self.stats.borrow_mut().increment_jac_mul();
            y.copy_from(v);
        }
    }

    impl NonLinearOpAdjoint for ForwardingOp {
        fn jac_transpose_mul_inplace(
            &self,
            _x: &Self::V,
            _t: Self::T,
            v: &Self::V,
            y: &mut Self::V,
        ) {
            self.stats.borrow_mut().increment_jac_adj_mul();
            y.copy_from(v);
        }
    }

    impl NonLinearOpSens for ForwardingOp {
        fn sens_mul_inplace(&self, _x: &Self::V, _t: Self::T, _v: &Self::V, y: &mut Self::V) {
            y.fill(0.0);
        }
    }

    impl NonLinearOpSensAdjoint for ForwardingOp {
        fn sens_transpose_mul_inplace(
            &self,
            _x: &Self::V,
            _t: Self::T,
            _v: &Self::V,
            y: &mut Self::V,
        ) {
            y.fill(0.0);
        }
    }

    impl LinearOp for ForwardingOp {
        fn gemv_inplace(&self, x: &Self::V, _t: Self::T, beta: Self::T, y: &mut Self::V) {
            self.stats.borrow_mut().increment_call();
            y.axpy(1.0, x, beta);
        }
    }

    impl LinearOpTranspose for ForwardingOp {
        fn gemv_transpose_inplace(&self, x: &Self::V, _t: Self::T, beta: Self::T, y: &mut Self::V) {
            self.stats.borrow_mut().increment_jac_adj_mul();
            y.axpy(1.0, x, beta);
        }
    }

    impl ConstantOp for ForwardingOp {
        fn call_inplace(&self, _t: Self::T, y: &mut Self::V) {
            self.stats.borrow_mut().increment_call();
            y.copy_from(&Self::V::from_vec(vec![1.0, 2.0], self.ctx));
        }
    }

    impl ConstantOpSens for ForwardingOp {
        fn sens_mul_inplace(&self, _t: Self::T, _v: &Self::V, y: &mut Self::V) {
            y.fill(0.0);
        }
    }

    impl ConstantOpSensAdjoint for ForwardingOp {
        fn sens_transpose_mul_inplace(&self, _t: Self::T, _v: &Self::V, y: &mut Self::V) {
            y.fill(0.0);
        }
    }

    #[test]
    fn op_statistics_increment_methods_update_counters() {
        let mut stats = OpStatistics::new();
        stats.increment_call();
        stats.increment_jac_mul();
        stats.increment_jac_adj_mul();
        stats.increment_matrix();
        assert_eq!(stats.number_of_calls, 1);
        assert_eq!(stats.number_of_jac_muls, 1);
        assert_eq!(stats.number_of_jac_adj_muls, 1);
        assert_eq!(stats.number_of_matrix_evals, 1);
    }

    #[test]
    fn parameterised_op_and_reference_forwarding_delegate_to_inner_operator() {
        let op = ForwardingOp::new();
        let p = crate::NalgebraVec::from_vec(vec![1.0, 2.0], NalgebraContext);
        let pop = ParameterisedOp::new(&op, &p);
        assert_eq!(pop.nstates(), 2);
        assert_eq!(pop.nout(), 2);
        assert_eq!(pop.nparams(), 2);

        let x = crate::NalgebraVec::from_vec(vec![3.0, 4.0], NalgebraContext);
        let mut y = crate::NalgebraVec::zeros(2, NalgebraContext);
        NonLinearOp::call_inplace(&&op, &x, 0.0, &mut y);
        y.assert_eq_st(&x, 1e-12);

        op.jac_mul_inplace(&x, 0.0, &x, &mut y);
        y.assert_eq_st(&x, 1e-12);

        op.jac_transpose_mul_inplace(&x, 0.0, &x, &mut y);
        y.assert_eq_st(&x, 1e-12);

        NonLinearOpSens::sens_mul_inplace(&&op, &x, 0.0, &x, &mut y);
        y.assert_eq_st(&crate::NalgebraVec::zeros(2, NalgebraContext), 1e-12);

        NonLinearOpSensAdjoint::sens_transpose_mul_inplace(&&op, &x, 0.0, &x, &mut y);
        y.assert_eq_st(&crate::NalgebraVec::zeros(2, NalgebraContext), 1e-12);

        op.gemv_inplace(&x, 0.0, 0.0, &mut y);
        y.assert_eq_st(&x, 1e-12);

        op.gemv_transpose_inplace(&x, 0.0, 0.0, &mut y);
        y.assert_eq_st(&x, 1e-12);

        let mut y_const = crate::NalgebraVec::zeros(2, NalgebraContext);
        <&ForwardingOp as ConstantOp>::call_inplace(&&op, 0.0, &mut y_const);
        y_const.assert_eq_st(
            &crate::NalgebraVec::from_vec(vec![1.0, 2.0], NalgebraContext),
            1e-12,
        );

        let op_ref_stats = pop.statistics();
        assert!(op_ref_stats.number_of_calls >= 1);

        let op_mut = ForwardingOp::new();
        assert_eq!(op_mut.nstates(), 2);
        assert_eq!(op_mut.nout(), 2);
        assert_eq!(op_mut.nparams(), 2);
    }
}