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
//! Types for ODE solver module
//!
//! This module defines the core types used by ODE solvers,
//! including method enums, options, and results.
use crate::common::IntegrateFloat;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use std::fmt::Debug;
use std::sync::Arc;
/// Type alias for time-dependent matrix function
pub type TimeFunction<F> = Arc<dyn Fn(F) -> Array2<F> + Send + Sync>;
/// Type alias for state-dependent matrix function
pub type StateFunction<F> = Arc<dyn Fn(F, ArrayView1<F>) -> Array2<F> + Send + Sync>;
/// ODE solver method
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ODEMethod {
/// Euler method (first-order)
Euler,
/// Fourth-order Runge-Kutta method (fixed step size)
RK4,
/// Dormand-Prince method (variable step size)
/// 5th order method with 4th order error estimate
#[default]
RK45,
/// Bogacki-Shampine method (variable step size)
/// 3rd order method with 2nd order error estimate
RK23,
/// Backward Differentiation Formula (BDF) method
/// Implicit method for stiff equations
/// Default is BDF order 2
Bdf,
/// Dormand-Prince method of order 8(5,3)
/// 8th order method with 5th order error estimate
/// High-accuracy explicit Runge-Kutta method
DOP853,
/// Implicit Runge-Kutta method of Radau IIA family
/// 5th order method with 3rd order error estimate
/// L-stable implicit method for stiff problems
Radau,
/// Livermore Solver for Ordinary Differential Equations with Automatic method switching
/// Automatically switches between Adams methods (non-stiff) and BDF (stiff)
/// Efficiently handles problems that change character during integration
LSODA,
/// Enhanced LSODA method with improved stiffness detection and method switching
/// Features better Jacobian handling, adaptive order selection, and robust error control
/// Provides detailed diagnostics about method switching decisions
EnhancedLSODA,
/// Enhanced BDF method with improved Jacobian handling and error estimation
/// Features intelligent Jacobian strategy selection based on problem size
/// Supports multiple Newton solver variants and provides better convergence
/// Includes specialized handling for banded matrices and adaptive order selection
EnhancedBDF,
}
/// Type of mass matrix for ODE system
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MassMatrixType {
/// Identity mass matrix (standard ODE)
#[default]
Identity,
/// Constant mass matrix
Constant,
/// Time-dependent mass matrix M(t)
TimeDependent,
/// State-dependent mass matrix M(t,y)
StateDependent,
}
/// Mass matrix for ODE system of the form M(t,y)·y' = f(t,y)
pub struct MassMatrix<F: IntegrateFloat> {
/// Type of the mass matrix
pub matrix_type: MassMatrixType,
/// Constant mass matrix (if applicable)
pub constant_matrix: Option<scirs2_core::ndarray::Array2<F>>,
/// Function for time-dependent mass matrix
pub time_function: Option<TimeFunction<F>>,
/// Function for state-dependent mass matrix
pub state_function: Option<StateFunction<F>>,
/// Whether the mass matrix is sparse/banded
pub is_banded: bool,
/// Lower bandwidth for banded matrices
pub lower_bandwidth: Option<usize>,
/// Upper bandwidth for banded matrices
pub upper_bandwidth: Option<usize>,
}
impl<F: IntegrateFloat> Debug for MassMatrix<F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MassMatrix")
.field("matrix_type", &self.matrix_type)
.field("constant_matrix", &self.constant_matrix)
.field("time_function", &self.time_function.is_some())
.field("state_function", &self.state_function.is_some())
.field("is_banded", &self.is_banded)
.field("lower_bandwidth", &self.lower_bandwidth)
.field("upper_bandwidth", &self.upper_bandwidth)
.finish()
}
}
impl<F: IntegrateFloat> Clone for MassMatrix<F> {
fn clone(&self) -> Self {
MassMatrix {
matrix_type: self.matrix_type,
constant_matrix: self.constant_matrix.clone(),
time_function: self.time_function.clone(),
state_function: self.state_function.clone(),
is_banded: self.is_banded,
lower_bandwidth: self.lower_bandwidth,
upper_bandwidth: self.upper_bandwidth,
}
}
}
impl<F: IntegrateFloat> MassMatrix<F> {
/// Create a new identity mass matrix (standard ODE)
pub fn identity() -> Self {
MassMatrix {
matrix_type: MassMatrixType::Identity,
constant_matrix: None,
time_function: None,
state_function: None,
is_banded: false,
lower_bandwidth: None,
upper_bandwidth: None,
}
}
/// Create a new constant mass matrix
pub fn constant(matrix: scirs2_core::ndarray::Array2<F>) -> Self {
MassMatrix {
matrix_type: MassMatrixType::Constant,
constant_matrix: Some(matrix),
time_function: None,
state_function: None,
is_banded: false,
lower_bandwidth: None,
upper_bandwidth: None,
}
}
/// Create a new time-dependent mass matrix M(t)
pub fn time_dependent<Func>(func: Func) -> Self
where
Func: Fn(F) -> scirs2_core::ndarray::Array2<F> + Send + Sync + 'static,
{
MassMatrix {
matrix_type: MassMatrixType::TimeDependent,
constant_matrix: None,
time_function: Some(Arc::new(func)),
state_function: None,
is_banded: false,
lower_bandwidth: None,
upper_bandwidth: None,
}
}
/// Create a new state-dependent mass matrix M(t,y)
pub fn state_dependent<Func>(func: Func) -> Self
where
Func: Fn(F, scirs2_core::ndarray::ArrayView1<F>) -> scirs2_core::ndarray::Array2<F>
+ Send
+ Sync
+ 'static,
{
MassMatrix {
matrix_type: MassMatrixType::StateDependent,
constant_matrix: None,
time_function: None,
state_function: Some(Arc::new(func)),
is_banded: false,
lower_bandwidth: None,
upper_bandwidth: None,
}
}
/// Set the matrix as banded with specified bandwidths
pub fn with_bandwidth(&mut self, lower: usize, upper: usize) -> &mut Self {
self.is_banded = true;
self.lower_bandwidth = Some(lower);
self.upper_bandwidth = Some(upper);
self
}
/// Get the mass matrix at a given time and state
pub fn evaluate(
&self,
t: F,
y: scirs2_core::ndarray::ArrayView1<F>,
) -> Option<scirs2_core::ndarray::Array2<F>> {
match self.matrix_type {
MassMatrixType::Identity => None, // Identity is handled specially
MassMatrixType::Constant => self.constant_matrix.clone(),
MassMatrixType::TimeDependent => self.time_function.as_ref().map(|f| f(t)),
MassMatrixType::StateDependent => self.state_function.as_ref().map(|f| f(t, y)),
}
}
}
/// Options for controlling the behavior of ODE solvers
#[derive(Debug, Clone)]
pub struct ODEOptions<F: IntegrateFloat> {
/// The ODE solver method to use
pub method: ODEMethod,
/// Relative tolerance for error control
pub rtol: F,
/// Absolute tolerance for error control
pub atol: F,
/// Initial step size (optional, if not provided, it will be estimated)
pub h0: Option<F>,
/// Maximum number of steps to take
pub max_steps: usize,
/// Maximum step size (optional)
pub max_step: Option<F>,
/// Minimum step size (optional)
pub min_step: Option<F>,
/// Dense output flag - whether to enable dense output
pub dense_output: bool,
/// Maximum order for BDF method (1-5)
pub max_order: Option<usize>,
/// Jacobian matrix (optional, for implicit methods)
pub jac: Option<Array1<F>>,
/// Whether to use a banded Jacobian matrix
pub use_banded_jacobian: bool,
/// Number of lower diagonals for banded Jacobian
pub ml: Option<usize>,
/// Number of upper diagonals for banded Jacobian
pub mu: Option<usize>,
/// Mass matrix for M(t,y)·y' = f(t,y) form (optional)
pub mass_matrix: Option<MassMatrix<F>>,
/// Strategy for Jacobian approximation/computation
pub jacobian_strategy: Option<crate::ode::utils::jacobian::JacobianStrategy>,
}
impl<F: IntegrateFloat> Default for ODEOptions<F> {
fn default() -> Self {
ODEOptions {
method: ODEMethod::default(),
rtol: F::from_f64(1e-3).expect("Operation failed"),
atol: F::from_f64(1e-6).expect("Operation failed"),
h0: None,
max_steps: 500,
max_step: None,
min_step: None,
dense_output: false,
max_order: None,
jac: None,
use_banded_jacobian: false,
ml: None,
mu: None,
mass_matrix: None,
jacobian_strategy: None, // Defaults to Adaptive in JacobianManager
}
}
}
/// Result of ODE integration
#[derive(Debug, Clone)]
pub struct ODEResult<F: IntegrateFloat> {
/// Time points
pub t: Vec<F>,
/// Solution values at time points
pub y: Vec<Array1<F>>,
/// Whether the integration was successful
pub success: bool,
/// Status message
pub message: Option<String>,
/// Number of function evaluations
pub n_eval: usize,
/// Number of steps taken
pub n_steps: usize,
/// Number of accepted steps
pub n_accepted: usize,
/// Number of rejected steps
pub n_rejected: usize,
/// Number of LU decompositions
pub n_lu: usize,
/// Number of Jacobian evaluations
pub n_jac: usize,
/// The solver method used
pub method: ODEMethod,
}