1use crate::{MathExpr, SolverError};
7use std::collections::{HashMap, HashSet};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum SystemKind {
11 General,
12 Autonomous,
13 TimeLinear,
15 ConstantLinear,
17}
18
19#[derive(Clone, Debug)]
23pub struct OdeSystem<'a> {
24 pub(crate) time: Option<&'a str>,
25 pub(crate) names: Vec<&'a str>,
26 pub(crate) rhs: Vec<MathExpr<'a, f64>>,
27 pub(crate) matrix: Vec<MathExpr<'a, f64>>,
28 pub(crate) forcing: Vec<MathExpr<'a, f64>>,
29 pub(crate) constant_matrix: Vec<f64>,
30 kind: SystemKind,
31}
32
33impl<'a> OdeSystem<'a> {
34 pub fn general(time: &'a str, names: &[&'a str], rhs: &[&'a str]) -> Result<Self, SolverError> {
37 Self::general_with_parameters(time, names, rhs, &[])
38 }
39
40 pub fn general_with_parameters(
56 time: &'a str,
57 names: &[&'a str],
58 rhs: &[&'a str],
59 parameters: &[(&str, f64)],
60 ) -> Result<Self, SolverError> {
61 Self::parse(Some(time), names, rhs, SystemKind::General, parameters)
62 }
63
64 pub fn new(time: &'a str, names: &[&'a str], rhs: &[&'a str]) -> Result<Self, SolverError> {
66 Self::general(time, names, rhs)
67 }
68
69 pub fn new_with_parameters(
71 time: &'a str,
72 names: &[&'a str],
73 rhs: &[&'a str],
74 parameters: &[(&str, f64)],
75 ) -> Result<Self, SolverError> {
76 Self::general_with_parameters(time, names, rhs, parameters)
77 }
78
79 pub fn autonomous(names: &[&'a str], rhs: &[&'a str]) -> Result<Self, SolverError> {
81 Self::autonomous_with_parameters(names, rhs, &[])
82 }
83
84 pub fn autonomous_with_parameters(
87 names: &[&'a str],
88 rhs: &[&'a str],
89 parameters: &[(&str, f64)],
90 ) -> Result<Self, SolverError> {
91 Self::parse(None, names, rhs, SystemKind::Autonomous, parameters)
92 }
93
94 pub fn linear(
98 time: &'a str,
99 names: &[&'a str],
100 matrix: &[&'a str],
101 forcing: &[&'a str],
102 ) -> Result<Self, SolverError> {
103 Self::linear_with_parameters(time, names, matrix, forcing, &[])
104 }
105
106 pub fn linear_with_parameters(
109 time: &'a str,
110 names: &[&'a str],
111 matrix: &[&'a str],
112 forcing: &[&'a str],
113 parameters: &[(&str, f64)],
114 ) -> Result<Self, SolverError> {
115 let mut system = Self::parse(
116 Some(time),
117 names,
118 forcing,
119 SystemKind::TimeLinear,
120 parameters,
121 )?;
122 Self::check_matrix_size(names.len(), matrix.len())?;
123 system.forcing = system.rhs.clone();
124 system.matrix = Self::parse_expressions(matrix, parameters)?;
125 for (equation, expression) in system.matrix.iter().chain(&system.forcing).enumerate() {
126 Self::check_variables(expression, &[time], equation)?;
127 }
128 system.rhs = system.assemble_rhs(&system.matrix, &system.forcing);
129 Ok(system)
130 }
131
132 pub fn split(
134 time: &'a str,
135 names: &[&'a str],
136 matrix: &[f64],
137 remainder: &[&'a str],
138 ) -> Result<Self, SolverError> {
139 let mut system = Self::parse(
140 Some(time),
141 names,
142 remainder,
143 SystemKind::ConstantLinear,
144 &[],
145 )?;
146 Self::check_matrix_size(names.len(), matrix.len())?;
147 if !matrix.iter().all(|v| v.is_finite()) {
148 return Err(SolverError::InvalidInput("constant matrix must be finite"));
149 }
150 system.constant_matrix = matrix.to_vec();
151 system.forcing = system.rhs.clone();
152 system.matrix = matrix.iter().map(|&v| MathExpr::new_const(v)).collect();
153 system.rhs = system.assemble_rhs(&system.matrix, &system.forcing);
154 Ok(system)
155 }
156
157 pub fn split_with_parameters(
162 time: &'a str,
163 names: &[&'a str],
164 matrix: &[&'a str],
165 remainder: &[&'a str],
166 parameters: &[(&str, f64)],
167 ) -> Result<Self, SolverError> {
168 let mut system = Self::parse(
169 Some(time),
170 names,
171 remainder,
172 SystemKind::ConstantLinear,
173 parameters,
174 )?;
175 Self::check_matrix_size(names.len(), matrix.len())?;
176 let entries = Self::parse_expressions(matrix, parameters)?;
177 let args = HashMap::new();
178 for (equation, entry) in entries.iter().enumerate() {
179 Self::check_variables(entry, &[], equation)?;
180 let value = entry
181 .evaluate(&args)
182 .map_err(|error| SolverError::Evaluation {
183 equation,
184 message: format!("{error:?}"),
185 })?;
186 if !value.is_finite() {
187 return Err(SolverError::InvalidInput("constant matrix must be finite"));
188 }
189 system.constant_matrix.push(value);
190 }
191 system.forcing = system.rhs.clone();
192 system.matrix = system
193 .constant_matrix
194 .iter()
195 .map(|&v| MathExpr::new_const(v))
196 .collect();
197 system.rhs = system.assemble_rhs(&system.matrix, &system.forcing);
198 Ok(system)
199 }
200
201 pub fn kind(&self) -> SystemKind {
202 self.kind
203 }
204 pub fn dimension(&self) -> usize {
205 self.names.len()
206 }
207 pub fn variables(&self) -> &[&'a str] {
208 &self.names
209 }
210 pub fn expressions(&self) -> &[MathExpr<'a, f64>] {
211 &self.rhs
212 }
213
214 fn parse(
215 time: Option<&'a str>,
216 names: &[&'a str],
217 rhs: &[&'a str],
218 kind: SystemKind,
219 parameters: &[(&str, f64)],
220 ) -> Result<Self, SolverError> {
221 let mut used: HashSet<_> = names.iter().copied().chain(time).collect();
222 for &(name, value) in parameters {
223 if !Self::valid_identifier(name) || !used.insert(name) {
224 return Err(SolverError::InvalidInput(
225 "parameter names must be valid, unique, and distinct from time/state names",
226 ));
227 }
228 if !value.is_finite() {
229 return Err(SolverError::InvalidInput("parameter values must be finite"));
230 }
231 }
232 Self::from_expressions(time, names, Self::parse_expressions(rhs, parameters)?, kind)
233 }
234
235 pub(crate) fn from_expressions(
238 time: Option<&'a str>,
239 names: &[&'a str],
240 expressions: Vec<MathExpr<'a, f64>>,
241 kind: SystemKind,
242 ) -> Result<Self, SolverError> {
243 if names.is_empty() || names.len() != expressions.len() {
244 return Err(SolverError::InvalidInput(
245 "provide one RHS per named state component",
246 ));
247 }
248 let mut unique = HashSet::new();
249 for name in names.iter().copied().chain(time) {
250 if !Self::valid_identifier(name) || !unique.insert(name) {
251 return Err(SolverError::InvalidInput(
252 "time and state names must be distinct identifiers, not numeric literals",
253 ));
254 }
255 }
256 let allowed: Vec<_> = unique.into_iter().collect();
257 for (equation, expression) in expressions.iter().enumerate() {
258 Self::check_variables(expression, &allowed, equation)?;
259 }
260 Ok(Self {
261 time,
262 names: names.to_vec(),
263 rhs: expressions,
264 matrix: vec![],
265 forcing: vec![],
266 constant_matrix: vec![],
267 kind,
268 })
269 }
270
271 fn valid_identifier(name: &str) -> bool {
272 let mut chars = name.chars();
273 matches!(chars.next(), Some(c) if c.is_alphabetic() || c == '_')
274 && chars.all(|c| c.is_alphanumeric() || c == '_')
275 && name.parse::<f64>().is_err()
276 }
277
278 fn parse_expressions(
279 sources: &[&'a str],
280 parameters: &[(&str, f64)],
281 ) -> Result<Vec<MathExpr<'a, f64>>, SolverError> {
282 sources
283 .iter()
284 .enumerate()
285 .map(|(equation, source)| {
286 let mut expression = MathExpr::parse(source)
287 .map_err(|source| SolverError::Parse { equation, source })?;
288 for &(name, value) in parameters {
289 expression = expression.substitute(name, &MathExpr::new_const(value));
290 }
291 Ok(expression)
292 })
293 .collect()
294 }
295
296 fn check_variables(
297 expression: &MathExpr<'_, f64>,
298 allowed: &[&str],
299 equation: usize,
300 ) -> Result<(), SolverError> {
301 if let Some(name) = expression
302 .variables()
303 .into_iter()
304 .filter(|name| !allowed.contains(name))
305 .min()
306 {
307 return Err(SolverError::Evaluation {
308 equation,
309 message: format!("variable '{name}' is not allowed in this system expression"),
310 });
311 }
312 Ok(())
313 }
314
315 fn check_matrix_size(dimension: usize, len: usize) -> Result<(), SolverError> {
316 if dimension.checked_mul(dimension) != Some(len) {
317 return Err(SolverError::InvalidInput(
318 "matrix must contain dimension * dimension elements",
319 ));
320 }
321 Ok(())
322 }
323
324 fn assemble_rhs(
325 &self,
326 matrix: &[MathExpr<'a, f64>],
327 forcing: &[MathExpr<'a, f64>],
328 ) -> Vec<MathExpr<'a, f64>> {
329 forcing
330 .iter()
331 .enumerate()
332 .map(|(row, force)| {
333 self.names
334 .iter()
335 .enumerate()
336 .fold(force.clone(), |rhs, (column, name)| {
337 MathExpr::new_add(
338 rhs,
339 MathExpr::new_multiply(
340 matrix[column * self.dimension() + row].clone(),
341 MathExpr::new_var(name),
342 ),
343 )
344 })
345 })
346 .collect()
347 }
348}