diffsol 0.1.9

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
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use std::rc::Rc;

use crate::{
    vector::DefaultDenseMatrix, Closure, ClosureNoJac, ClosureWithSens, ConstantClosure,
    ConstantClosureWithSens, LinearClosure, LinearClosureWithSens, Matrix, OdeEquations,
    OdeSolverProblem, Op, UnitCallable, Vector,
};
use anyhow::Result;

use super::equations::OdeSolverEquations;

/// Builder for ODE problems. Use methods to set parameters and then call one of the build methods when done.
pub struct OdeBuilder {
    t0: f64,
    h0: f64,
    rtol: f64,
    atol: Vec<f64>,
    p: Vec<f64>,
    use_coloring: bool,
    sensitivities: bool,
    sensitivities_error_control: bool,
}

impl Default for OdeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for ODE problems. Use methods to set parameters and then call one of the build methods when done.
///
/// # Example
///  
/// ```rust
/// use diffsol::{OdeBuilder, Bdf, OdeSolverState, OdeSolverMethod};
/// type M = nalgebra::DMatrix<f64>;
///
/// let problem = OdeBuilder::new()
///   .rtol(1e-6)
///   .p([0.1])
///   .build_ode::<M, _, _, _>(
///     // dy/dt = -ay
///     |x, p, t, y| {
///       y[0] = -p[0] * x[0];
///     },
///     // Jv = -av
///     |x, p, t, v, y| {
///       y[0] = -p[0] * v[0];
///     },
///     // y(0) = 1
///    |p, t| {
///       nalgebra::DVector::from_vec(vec![1.0])
///    },
///   ).unwrap();
///
/// let mut solver = Bdf::default();
/// let t = 0.4;
/// let mut state = OdeSolverState::new(&problem, &solver).unwrap();
/// solver.set_problem(state, &problem);
/// while solver.state().unwrap().t <= t {
///     solver.step().unwrap();
/// }
/// let y = solver.interpolate(t);
/// ```
///

impl OdeBuilder {
    /// Create a new builder with default parameters:
    /// - t0 = 0.0
    /// - h0 = 1.0
    /// - rtol = 1e-6
    /// - atol = [1e-6]
    /// - p = []
    /// - use_coloring = false
    /// - constant_mass = false
    pub fn new() -> Self {
        Self {
            t0: 0.0,
            h0: 1.0,
            rtol: 1e-6,
            atol: vec![1e-6],
            p: vec![],
            use_coloring: false,
            sensitivities: false,
            sensitivities_error_control: false,
        }
    }

    /// Set the initial time.
    pub fn t0(mut self, t0: f64) -> Self {
        self.t0 = t0;
        self
    }

    pub fn sensitivities(mut self, sensitivities: bool) -> Self {
        self.sensitivities = sensitivities;
        self
    }

    pub fn sensitivities_error_control(mut self, sensitivities_error_control: bool) -> Self {
        self.sensitivities_error_control = sensitivities_error_control;
        self
    }

    /// Set the initial step size.
    pub fn h0(mut self, h0: f64) -> Self {
        self.h0 = h0;
        self
    }

    /// Set the relative tolerance.
    pub fn rtol(mut self, rtol: f64) -> Self {
        self.rtol = rtol;
        self
    }

    /// Set the absolute tolerance.
    pub fn atol<V, T>(mut self, atol: V) -> Self
    where
        V: IntoIterator<Item = T>,
        f64: From<T>,
    {
        self.atol = atol.into_iter().map(|x| f64::from(x)).collect();
        self
    }

    /// Set the parameters.
    pub fn p<V, T>(mut self, p: V) -> Self
    where
        V: IntoIterator<Item = T>,
        f64: From<T>,
    {
        self.p = p.into_iter().map(|x| f64::from(x)).collect();
        self
    }

    /// Set whether to use coloring when computing the Jacobian.
    /// This can speed up the computation of the Jacobian for large sparse systems.
    /// However, it relys on the sparsity of the Jacobian being constant,
    /// and for certain systems it may detect the wrong sparsity pattern.
    pub fn use_coloring(mut self, use_coloring: bool) -> Self {
        self.use_coloring = use_coloring;
        self
    }

    fn build_atol<V: Vector>(atol: Vec<f64>, nstates: usize) -> Result<V> {
        if atol.len() == 1 {
            Ok(V::from_element(nstates, V::T::from(atol[0])))
        } else if atol.len() != nstates {
            Err(anyhow::anyhow!(
                "atol must have length 1 or equal to the number of states"
            ))
        } else {
            let mut v = V::zeros(nstates);
            for (i, &a) in atol.iter().enumerate() {
                v[i] = V::T::from(a);
            }
            Ok(v)
        }
    }

    fn build_p<V: Vector>(p: Vec<f64>) -> V {
        let mut v = V::zeros(p.len());
        for (i, &p) in p.iter().enumerate() {
            v[i] = V::T::from(p);
        }
        v
    }

    /// Build an ODE problem with a mass matrix.
    ///
    /// # Arguments
    ///
    /// - `rhs`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the right-hand side of the ODE.
    /// - `rhs_jac`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the Jacobian of the right-hand side with the vector v.
    /// - `mass`: Function of type Fn(v: &V, p: &V, t: S, beta: S, y: &mut V) that computes a gemv multiplication of the mass matrix with the vector v (i.e. y = M * v + beta * y).
    /// - `init`: Function of type Fn(p: &V, t: S) -> V that computes the initial state.
    ///
    /// # Generic Arguments
    ///
    /// - `M`: Type that implements the `Matrix` trait. Often this must be provided explicitly (i.e. `type M = DMatrix<f64>; builder.build_ode::<M, _, _, _>`).
    ///
    /// # Example
    ///
    /// ```
    /// use diffsol::OdeBuilder;
    /// use nalgebra::DVector;
    /// type M = nalgebra::DMatrix<f64>;
    ///
    /// // dy/dt = y
    /// // 0 = z - y
    /// // y(0) = 0.1
    /// // z(0) = 0.1
    /// let problem = OdeBuilder::new()
    ///   .build_ode_with_mass::<M, _, _, _, _>(
    ///       |x, _p, _t, y| {
    ///           y[0] = x[0];
    ///           y[1] = x[1] - x[0];
    ///       },
    ///       |x, _p, _t, v, y|  {
    ///           y[0] = v[0];
    ///           y[1] = v[1] - v[0];
    ///       },
    ///       |v, _p, _t, beta, y| {
    ///           y[0] = v[0] + beta * y[0];
    ///           y[1] = beta * y[1];
    ///       },
    ///       |p, _t| DVector::from_element(2, 0.1),
    /// );
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn build_ode_with_mass<M, F, G, H, I>(
        self,
        rhs: F,
        rhs_jac: G,
        mass: H,
        init: I,
    ) -> Result<
        OdeSolverProblem<
            OdeSolverEquations<M, Closure<M, F, G>, ConstantClosure<M, I>, LinearClosure<M, H>>,
        >,
    >
    where
        M: Matrix,
        F: Fn(&M::V, &M::V, M::T, &mut M::V),
        G: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        H: Fn(&M::V, &M::V, M::T, M::T, &mut M::V),
        I: Fn(&M::V, M::T) -> M::V,
    {
        let p = Rc::new(Self::build_p(self.p));
        let t0 = M::T::from(self.t0);
        let y0 = init(&p, t0);
        let nstates = y0.len();
        let mut rhs = Closure::new(rhs, rhs_jac, nstates, nstates, p.clone());
        let mut mass = LinearClosure::new(mass, nstates, nstates, p.clone());
        let init = ConstantClosure::new(init, p.clone());
        if self.use_coloring {
            rhs.calculate_sparsity(&y0, t0);
            mass.calculate_sparsity(t0);
        }
        let mass = Some(Rc::new(mass));
        let rhs = Rc::new(rhs);
        let init = Rc::new(init);
        let eqn = OdeSolverEquations::new(rhs, mass, None, init, p);
        let atol = Self::build_atol(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            M::T::from(self.rtol),
            atol,
            M::T::from(self.t0),
            M::T::from(self.h0),
            false,
            self.sensitivities_error_control,
        )
    }

    /// Build an ODE problem with a mass matrix and sensitivities.
    ///
    /// # Arguments
    ///
    /// - `rhs`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the right-hand side of the ODE.
    /// - `rhs_jac`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the Jacobian of the right-hand side with the vector v.
    /// - `rhs_sens`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the partial derivative of the rhs wrt the parameters, with the vector v.
    /// - `mass`: Function of type Fn(v: &V, p: &V, t: S, beta: S, y: &mut V) that computes a gemv multiplication of the mass matrix with the vector v (i.e. y = M * v + beta * y).
    /// - `mass_sens`: Function of type Fn(v: &V, p: &V, t: S, y: &mut V) that computes the multiplication of the partial derivative of the mass matrix wrt the parameters, with the vector v.
    /// - `init`: Function of type Fn(p: &V, t: S) -> V that computes the initial state.
    /// - `init_sens`: Function of type Fn(p: &V, t: S, y: &mut V) that computes the multiplication of the partial derivative of the initial state wrt the parameters, with the vector v.
    ///
    /// # Example
    ///
    /// ```
    /// use diffsol::OdeBuilder;
    /// use nalgebra::DVector;
    /// type M = nalgebra::DMatrix<f64>;
    ///
    /// // dy/dt = a y
    /// // 0 = z - y
    /// // y(0) = 0.1
    /// // z(0) = 0.1
    /// let problem = OdeBuilder::new()
    ///   .build_ode_with_mass_and_sens::<M, _, _, _, _, _, _, _>(
    ///       |x, p, _t, y| {
    ///           y[0] = p[0] * x[0];
    ///           y[1] = x[1] - x[0];
    ///       },
    ///       |x, p, _t, v, y|  {
    ///           y[0] = p[0] * v[0];
    ///           y[1] = v[1] - v[0];
    ///       },
    ///       |x, _p, _t, v, y| {
    ///           y[0] = v[0] * x[0];
    ///           y[1] = 0.0;
    ///       },
    ///       |x, _p, _t, beta, y| {
    ///           y[0] = x[0] + beta * y[0];
    ///           y[1] = beta * y[1];
    ///       },
    ///       |x, p, t, v, y| {
    ///           y.fill(0.0);
    ///       },
    ///       |p, _t| DVector::from_element(2, 0.1),
    ///       |p, t, v, y| {
    ///           y.fill(0.0);
    ///       }
    /// );
    /// ```
    #[allow(clippy::type_complexity, clippy::too_many_arguments)]
    pub fn build_ode_with_mass_and_sens<M, F, G, H, I, J, K, L>(
        self,
        rhs: F,
        rhs_jac: G,
        rhs_sens: J,
        mass: H,
        mass_sens: L,
        init: I,
        init_sens: K,
    ) -> Result<
        OdeSolverProblem<
            OdeSolverEquations<
                M,
                ClosureWithSens<M, F, G, J>,
                ConstantClosureWithSens<M, I, K>,
                LinearClosureWithSens<M, H, L>,
            >,
        >,
    >
    where
        M: Matrix,
        F: Fn(&M::V, &M::V, M::T, &mut M::V),
        G: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        H: Fn(&M::V, &M::V, M::T, M::T, &mut M::V),
        I: Fn(&M::V, M::T) -> M::V,
        J: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        K: Fn(&M::V, M::T, &M::V, &mut M::V),
        L: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
    {
        let p = Rc::new(Self::build_p(self.p));
        let t0 = M::T::from(self.t0);
        let y0 = init(&p, t0);
        let nstates = y0.len();
        let mut rhs = ClosureWithSens::new(rhs, rhs_jac, rhs_sens, nstates, nstates, p.clone());
        let mut mass = LinearClosureWithSens::new(mass, mass_sens, nstates, nstates, p.clone());
        let init = ConstantClosureWithSens::new(init, init_sens, nstates, nstates, p.clone());
        if self.use_coloring {
            rhs.calculate_sparsity(&y0, t0);
            mass.calculate_sparsity(t0);
        }
        let mass = Some(Rc::new(mass));
        let rhs = Rc::new(rhs);
        let init = Rc::new(init);
        let eqn = OdeSolverEquations::new(rhs, mass, None, init, p);
        let atol = Self::build_atol(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            M::T::from(self.rtol),
            atol,
            M::T::from(self.t0),
            M::T::from(self.h0),
            true,
            self.sensitivities_error_control,
        )
    }

    /// Build an ODE problem with a mass matrix that is the identity matrix.
    ///
    /// # Arguments
    ///
    /// - `rhs`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the right-hand side of the ODE.
    /// - `rhs_jac`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the Jacobian of the right-hand side with the vector v.
    /// - `init`: Function of type Fn(p: &V, t: S) -> V that computes the initial state.
    ///
    /// # Generic Arguments
    ///
    /// - `M`: Type that implements the `Matrix` trait. Often this must be provided explicitly (i.e. `type M = DMatrix<f64>; builder.build_ode::<M, _, _, _>`).
    ///
    /// # Example
    ///
    ///
    ///
    /// ```
    /// use diffsol::OdeBuilder;
    /// use nalgebra::DVector;
    /// type M = nalgebra::DMatrix<f64>;
    ///
    ///
    /// // dy/dt = y
    /// // y(0) = 0.1
    /// let problem = OdeBuilder::new()
    ///    .build_ode::<M, _, _, _>(
    ///        |x, _p, _t, y| y[0] = x[0],
    ///        |x, _p, _t, v , y| y[0] = v[0],
    ///        |p, _t| DVector::from_element(1, 0.1),
    ///    );
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn build_ode<M, F, G, I>(
        self,
        rhs: F,
        rhs_jac: G,
        init: I,
    ) -> Result<OdeSolverProblem<OdeSolverEquations<M, Closure<M, F, G>, ConstantClosure<M, I>>>>
    where
        M: Matrix,
        F: Fn(&M::V, &M::V, M::T, &mut M::V),
        G: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        I: Fn(&M::V, M::T) -> M::V,
    {
        let p = Rc::new(Self::build_p(self.p));
        let t0 = M::T::from(self.t0);
        let y0 = init(&p, t0);
        let nstates = y0.len();
        let mut rhs = Closure::new(rhs, rhs_jac, nstates, nstates, p.clone());
        let init = ConstantClosure::new(init, p.clone());
        if self.use_coloring {
            rhs.calculate_sparsity(&y0, t0);
        }
        let rhs = Rc::new(rhs);
        let init = Rc::new(init);
        let eqn = OdeSolverEquations::new(rhs, None, None, init, p);
        let atol = Self::build_atol(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            M::T::from(self.rtol),
            atol,
            M::T::from(self.t0),
            M::T::from(self.h0),
            false,
            self.sensitivities_error_control,
        )
    }

    /// Build an ODE problem with a mass matrix that is the identity matrix and sensitivities.
    ///
    /// # Arguments
    ///
    /// - `rhs`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the right-hand side of the ODE.
    /// - `rhs_jac`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the Jacobian of the right-hand side with the vector v.
    /// - `rhs_sens`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the partial derivative of the rhs wrt the parameters, with the vector v.
    /// - `init`: Function of type Fn(p: &V, t: S) -> V that computes the initial state.
    /// - `init_sens`: Function of type Fn(p: &V, t: S, y: &mut V) that computes the multiplication of the partial derivative of the initial state wrt the parameters, with the vector v.
    ///
    /// # Example
    ///
    /// ```
    /// use diffsol::OdeBuilder;
    /// use nalgebra::DVector;
    /// type M = nalgebra::DMatrix<f64>;
    ///
    ///
    /// // dy/dt = a y
    /// // y(0) = 0.1
    /// let problem = OdeBuilder::new()
    ///    .build_ode_with_sens::<M, _, _, _, _, _>(
    ///        |x, p, _t, y| y[0] = p[0] * x[0],
    ///        |x, p, _t, v, y| y[0] = p[0] * v[0],
    ///        |x, p, _t, v, y| y[0] = v[0] * x[0],
    ///        |p, _t| DVector::from_element(1, 0.1),
    ///        |p, t, v, y| y.fill(0.0),
    ///    );
    /// ```

    #[allow(clippy::type_complexity)]
    pub fn build_ode_with_sens<M, F, G, I, J, K>(
        self,
        rhs: F,
        rhs_jac: G,
        rhs_sens: J,
        init: I,
        init_sens: K,
    ) -> Result<
        OdeSolverProblem<
            OdeSolverEquations<M, ClosureWithSens<M, F, G, J>, ConstantClosureWithSens<M, I, K>>,
        >,
    >
    where
        M: Matrix,
        F: Fn(&M::V, &M::V, M::T, &mut M::V),
        G: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        I: Fn(&M::V, M::T) -> M::V,
        J: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        K: Fn(&M::V, M::T, &M::V, &mut M::V),
    {
        let p = Rc::new(Self::build_p(self.p));
        let t0 = M::T::from(self.t0);
        let y0 = init(&p, t0);
        let nstates = y0.len();
        let init = ConstantClosureWithSens::new(init, init_sens, nstates, nstates, p.clone());
        let mut rhs = ClosureWithSens::new(rhs, rhs_jac, rhs_sens, nstates, nstates, p.clone());
        if self.use_coloring {
            rhs.calculate_sparsity(&y0, t0);
        }
        let rhs = Rc::new(rhs);
        let init = Rc::new(init);
        let eqn = OdeSolverEquations::new(rhs, None, None, init, p);
        let atol = Self::build_atol(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            M::T::from(self.rtol),
            atol,
            M::T::from(self.t0),
            M::T::from(self.h0),
            true,
            self.sensitivities_error_control,
        )
    }

    /// Build an ODE problem with an event.
    ///
    /// # Arguments
    ///
    /// - `rhs`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the right-hand side of the ODE.
    /// - `rhs_jac`: Function of type Fn(x: &V, p: &V, t: S, v: &V, y: &mut V) that computes the multiplication of the Jacobian of the right-hand side with the vector v.
    /// - `init`: Function of type Fn(p: &V, t: S) -> V that computes the initial state.
    /// - `root`: Function of type Fn(x: &V, p: &V, t: S, y: &mut V) that computes the root function.
    /// - `nroots`: Number of roots (i.e. number of elements in the `y` arg in `root`), an event is triggered when any of the roots changes sign.
    ///
    /// # Generic Arguments
    ///
    /// - `M`: Type that implements the `Matrix` trait. Often this must be provided explicitly (i.e. `type M = DMatrix<f64>; builder.build_ode::<M, _, _, _, _>`).
    ///
    /// # Example
    ///
    ///
    ///
    /// ```
    /// use diffsol::OdeBuilder;
    /// use nalgebra::DVector;
    /// type M = nalgebra::DMatrix<f64>;
    ///
    ///
    /// // dy/dt = y
    /// // y(0) = 0.1
    /// // event at y = 0.5
    /// let problem = OdeBuilder::new()
    ///    .build_ode_with_root::<M, _, _, _, _>(
    ///        |x, _p, _t, y| y[0] = x[0],
    ///        |x, _p, _t, v , y| y[0] = v[0],
    ///        |p, _t| DVector::from_element(1, 0.1),
    ///        |x, _p, _t, y| y[0] = x[0] - 0.5,
    ///        1,
    ///    );
    /// ```

    #[allow(clippy::type_complexity)]
    pub fn build_ode_with_root<M, F, G, I, H>(
        self,
        rhs: F,
        rhs_jac: G,
        init: I,
        root: H,
        nroots: usize,
    ) -> Result<
        OdeSolverProblem<
            OdeSolverEquations<
                M,
                Closure<M, F, G>,
                ConstantClosure<M, I>,
                UnitCallable<M>,
                ClosureNoJac<M, H>,
            >,
        >,
    >
    where
        M: Matrix,
        F: Fn(&M::V, &M::V, M::T, &mut M::V),
        G: Fn(&M::V, &M::V, M::T, &M::V, &mut M::V),
        H: Fn(&M::V, &M::V, M::T, &mut M::V),
        I: Fn(&M::V, M::T) -> M::V,
    {
        let p = Rc::new(Self::build_p(self.p));
        let t0 = M::T::from(self.t0);
        let y0 = init(&p, t0);
        let nstates = y0.len();
        let mut rhs = Closure::new(rhs, rhs_jac, nstates, nstates, p.clone());
        let root = Rc::new(ClosureNoJac::new(root, nstates, nroots, p.clone()));
        let init = ConstantClosure::new(init, p.clone());
        if self.use_coloring {
            rhs.calculate_sparsity(&y0, t0);
        }
        let rhs = Rc::new(rhs);
        let init = Rc::new(init);
        let eqn = OdeSolverEquations::new(rhs, None, Some(root), init, p);
        let atol = Self::build_atol(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            M::T::from(self.rtol),
            atol,
            M::T::from(self.t0),
            M::T::from(self.h0),
            false,
            self.sensitivities_error_control,
        )
    }

    /// Build an ODE problem using the default dense matrix (see [Self::build_ode]).
    #[allow(clippy::type_complexity)]
    pub fn build_ode_dense<V, F, G, I>(
        self,
        rhs: F,
        rhs_jac: G,
        init: I,
    ) -> Result<
        OdeSolverProblem<OdeSolverEquations<V::M, Closure<V::M, F, G>, ConstantClosure<V::M, I>>>,
    >
    where
        V: Vector + DefaultDenseMatrix,
        F: Fn(&V, &V, V::T, &mut V),
        G: Fn(&V, &V, V::T, &V, &mut V),
        I: Fn(&V, V::T) -> V,
    {
        self.build_ode(rhs, rhs_jac, init)
    }

    /// Build an ODE problem using the DiffSL language (requires the `diffsl` feature).
    /// The source code is provided as a string, please see the [DiffSL documentation](https://martinjrobins.github.io/diffsl/) for more information.
    #[cfg(feature = "diffsl")]
    pub fn build_diffsl(
        self,
        context: &crate::ode_solver::diffsl::DiffSlContext,
    ) -> Result<OdeSolverProblem<crate::ode_solver::diffsl::DiffSl<'_>>> {
        use crate::ode_solver::diffsl;
        type V = diffsl::V;
        type T = diffsl::T;
        let p = Self::build_p::<V>(self.p);
        let mut eqn = diffsl::DiffSl::new(context, self.use_coloring);
        eqn.set_params(p);
        let atol = Self::build_atol::<V>(self.atol, eqn.rhs().nstates())?;
        OdeSolverProblem::new(
            eqn,
            T::from(self.rtol),
            atol,
            T::from(self.t0),
            T::from(self.h0),
            self.sensitivities,
            self.sensitivities_error_control,
        )
    }
}