Skip to main content

OdeSystem

Struct OdeSystem 

Source
pub struct OdeSystem<'a> { /* private fields */ }
Expand description

A parsed vector field with named state variables. Matrices are column-major: element (row, column) has index column * dimension + row. Names are explicit: there are no reserved x, x0, or t aliases here.

Implementations§

Source§

impl<'a> OdeSystem<'a>

Source

pub fn general( time: &'a str, names: &[&'a str], rhs: &[&'a str], ) -> Result<Self, SolverError>

Creates x’ = F(t,x). Names and expressions are borrowed; parsing happens only here, so a system can be reused for multiple solves.

Examples found in repository?
examples/precision.rs (line 209)
139fn main() -> Result<(), Box<dyn Error>> {
140    let mut output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/precision");
141    let mut open = true;
142    let mut args = std::env::args().skip(1);
143    while let Some(arg) = args.next() {
144        match arg.as_str() {
145            "--no-open" => open = false,
146            "--output" => output = args.next().ok_or("--output requires a directory")?.into(),
147            "--help" | "-h" => {
148                println!(
149                    "cargo run --release --example precision -- [--no-open] [--output DIRECTORY]\nWrites index.html, 44 SVG error plots, and errors.csv (default: target/precision)."
150                );
151                return Ok(());
152            }
153            _ => return Err(format!("unknown option: {arg}").into()),
154        }
155    }
156    std::fs::create_dir_all(&output)?;
157    let names: Vec<String> = (0..N).map(|i| format!("x{i}")).collect();
158    let names: Vec<&str> = names.iter().map(String::as_str).collect();
159    let mut html = String::from(
160        "<!doctype html><html lang='en'><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>ODE precision comparison</title><style>body{font:16px system-ui;color:#172033;background:#f1f5f9;max-width:1100px;margin:40px auto;padding:0 20px}section{background:white;padding:24px;margin:24px 0;border-radius:12px}img{width:100%;height:auto}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:left;padding:8px;border-bottom:1px solid #ddd}code{font-size:14px}summary{cursor:pointer;padding:15px}a{color:#2563eb}</style><h1>Ten equations. Four system types.</h1><p>Absolute error against an analytic solution at every accepted time. All 15 compatible method/type combinations use t = 0…10, initial step 0.01, maximum step 1, local tolerance 1e-12, and the default mixed relative/absolute error control. The adaptive controller chooses step sizes within these bounds; there is no target step count. This compares accuracy under common controls, not computational cost or general method rankings.</p><p>Logarithmic error plots share a 1e-16…1 scale. Errors below 1e-16 (including zero at the initial point) are displayed at the floor. Near that floor, floating-point evaluation of the analytic solution also affects the comparison. Tables and <a href='errors.csv'>CSV data</a> retain unclipped errors.</p>",
161    );
162    let mut csv = String::from("type,method,step,time,component,numerical,exact,absolute_error\n");
163    for kind in 1..=4 {
164        let mut rhs = vec![String::new(); N];
165        let mut matrix = vec!["0".to_string(); N * N];
166        let mut constant = vec![0.0; N * N];
167        let q: Vec<String> = (0..N)
168            .map(|i| format!("(2+sin({}*t))", 0.2 + 0.02 * i as f64))
169            .collect();
170        for i in 0..N {
171            let next = (i + 1) % N;
172            let w = 0.2 + 0.02 * i as f64;
173            let derivative = format!("{w}*cos({w}*t)");
174            rhs[i] = match kind {
175                1 => format!(
176                    "{derivative}-(1+0.1*sin(t))*(x{i}-{})+0.05*(x{next}-{})^2",
177                    q[i], q[next]
178                ),
179                2 => {
180                    let a = i / 2 * 2;
181                    let b = a + 1;
182                    let omega = 0.2 + 0.04 * (i / 2) as f64;
183                    let rotation = if i.is_multiple_of(2) {
184                        format!("-{omega}*x{b}")
185                    } else {
186                        format!("{omega}*x{a}")
187                    };
188                    format!("{rotation}+0.1*(1-x{a}^2-x{b}^2)*x{i}")
189                }
190                3 => {
191                    matrix[i * N + i] = "-(1+0.1*sin(t))".into();
192                    matrix[next * N + i] = "0.1".into();
193                    format!("{derivative}+(1+0.1*sin(t))*{}-0.1*{}", q[i], q[next])
194                }
195                4 => {
196                    constant[i * N + i] = -1.0;
197                    constant[next * N + i] = 0.1;
198                    format!(
199                        "{derivative}+{}-0.1*{}+0.05*(x{next}-{})^2",
200                        q[i], q[next], q[next]
201                    )
202                }
203                _ => unreachable!(),
204            };
205        }
206        let expressions: Vec<&str> = rhs.iter().map(String::as_str).collect();
207        let entries: Vec<&str> = matrix.iter().map(String::as_str).collect();
208        let system = match kind {
209            1 => OdeSystem::general("t", &names, &expressions)?,
210            2 => OdeSystem::autonomous(&names, &expressions)?,
211            3 => OdeSystem::linear("t", &names, &entries, &expressions)?,
212            4 => OdeSystem::split("t", &names, &constant, &expressions)?,
213            _ => unreachable!(),
214        };
215        let description = match kind {
216            1 => "General: xᵢ′ = qᵢ′ − (1 + 0.1 sin t)(xᵢ − qᵢ) + 0.05(xⱼ − qⱼ)².",
217            2 => {
218                "Autonomous: for k = 0…4, a = x₂ₖ, b = x₂ₖ₊₁, ω = 0.2 + 0.04k: a′ = −ωb + 0.1(1 − a² − b²)a; b′ = ωa + 0.1(1 − a² − b²)b. Exact: a = cos(ωt), b = sin(ωt); initially (a,b) = (1,0). The radial nonlinear terms vanish on these unit circles."
219            }
220            3 => {
221                "Linear: xᵢ′ = −(1 + 0.1 sin t)xᵢ + 0.1xⱼ + φᵢ(t), where φᵢ = qᵢ′ + (1 + 0.1 sin t)qᵢ − 0.1qⱼ."
222            }
223            4 => {
224                "Constant linear part: (Bx)ᵢ = −xᵢ + 0.1xⱼ; uᵢ = qᵢ′ + qᵢ − 0.1qⱼ + 0.05(xⱼ − qⱼ)²; x′ = Bx + u."
225            }
226            _ => unreachable!(),
227        };
228        write!(html, "<section><h2>Type {kind}</h2><p>{description}</p>")?;
229        if kind != 2 {
230            html.push_str("<p>For i = 0…9, j = (i + 1) mod 10, ωᵢ = 0.2 + 0.02i, qᵢ(t) = 2 + sin(ωᵢt), qᵢ′ = ωᵢ cos(ωᵢt). Exact: xᵢ = qᵢ, initially xᵢ = 2. Substitution cancels the correction terms and gives xᵢ′ = qᵢ′.</p>");
231        }
232        html.push_str("<table><tr><th>Method / plot color</th><th>Accepted steps</th><th>Peak error</th><th>Final max error</th></tr>");
233        let initial: Vec<f64> = (0..N).map(|i| exact(kind, i, 0.0)).collect();
234        let mut runs = Vec::new();
235        for (method, color) in METHODS.into_iter().zip(COLORS) {
236            if !method.supports(system.kind()) {
237                continue;
238            }
239            let solver = Solver {
240                method,
241                initial_step: INITIAL_STEP,
242                max_step: MAX_STEP,
243                tolerance: TOLERANCE,
244                ..Solver::default()
245            };
246            let solution = solver.solve_problem(&system, 0.0, &initial, END)?;
247            let mut errors = Vec::new();
248            for (step, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
249                let mut error = [0.0; N];
250                for i in 0..N {
251                    let expected = exact(kind, i, t);
252                    error[i] = (state[i] - expected).abs();
253                    writeln!(
254                        csv,
255                        "{kind},{method:?},{step},{t:.17e},{i},{:.17e},{expected:.17e},{:.17e}",
256                        state[i], error[i]
257                    )?;
258                }
259                errors.push(error);
260            }
261            let peak = errors.iter().flatten().copied().fold(0.0, f64::max);
262            let final_error = errors.last().unwrap().iter().copied().fold(0.0, f64::max);
263            let steps = solution.times.len() - 1;
264            // Catch changes that defeat the purpose of this reproducible demo.
265            if !peak.is_finite() || peak >= 1e-3 || solution.times.last() != Some(&END) {
266                return Err(format!(
267                    "Type {kind} / {method:?}: endpoint not reached or excessive error ({peak:e})"
268                )
269                .into());
270            }
271            println!(
272                "Type {kind} {method:?}: {steps} steps, peak {peak:.3e}, final {final_error:.3e}"
273            );
274            write!(
275                html,
276                "<tr><td style='color:{color}'>{method:?}</td><td>{steps}</td><td>{peak:.3e}</td><td>{final_error:.3e}</td></tr>"
277            )?;
278            runs.push(Run {
279                method,
280                color,
281                solution,
282                errors,
283            });
284        }
285        html.push_str("</table><p>Every figure includes an accepted-step panel: h = |tₙ − tₙ₋₁| over each integration interval, with a separate linear axis. All components share the same steps. Method curves overlap when their steps agree; the final step may be shortened to reach the endpoint. These are actual accepted steps, not recommended next steps.</p>");
286        for component in std::iter::once(None).chain((0..N).map(Some)) {
287            if component == Some(0) {
288                html.push_str("<details><summary>Errors for each of the 10 components</summary>");
289            }
290            let suffix = component.map_or_else(|| "max".into(), |i| format!("x{i}"));
291            let filename = format!("type{kind}-{suffix}.svg");
292            std::fs::write(output.join(&filename), plot(&runs, component))?;
293            write!(
294                html,
295                "<a href='{filename}'><img src='{filename}' alt='Type {kind}, {suffix}: absolute error and accepted step size versus time' loading='lazy'></a>"
296            )?;
297        }
298        html.push_str("</details></section>");
299    }
300    html.push_str("<footer>Distributed under the <a href='https://www.boost.org/LICENSE_1_0.txt'>Boost Software License, Version 1.0</a>.</footer></html>");
301    std::fs::write(output.join("errors.csv"), csv)?;
302    std::fs::write(output.join("index.html"), html)?;
303    let index = output.join("index.html").canonicalize()?;
304    println!("Report: {}", index.display());
305    if open {
306        let browser = if cfg!(target_os = "macos") {
307            "open"
308        } else if cfg!(target_os = "windows") {
309            "explorer"
310        } else {
311            "xdg-open"
312        };
313        if !matches!(Command::new(browser).arg(&index).status(), Ok(s) if s.success()) {
314            eprintln!("Open {} in a browser to view the plots.", index.display());
315        }
316    }
317    Ok(())
318}
Source

pub fn general_with_parameters( time: &'a str, names: &[&'a str], rhs: &[&'a str], parameters: &[(&str, f64)], ) -> Result<Self, SolverError>

Creates a general system with named, finite constant parameters. Bindings are substituted structurally before variable validation and differentiation. Parameter names must be valid identifiers, unique, and distinct from state/time names. Unused bindings are allowed. Rebuild the system to change parameter values; no parameter map is needed at runtime.

use cauchy_ode::{OdeSystem, Solver};
let system = OdeSystem::general_with_parameters(
    "clock", &["position"], &["-rate*position"], &[("rate", 2.0)],
)?;
let trajectory = Solver::default().solve_problem(&system, 0.0, &[1.0], 1.0)?;
assert!((trajectory.states.last().unwrap()[0] - (-2.0_f64).exp()).abs() < 1e-6);
Source

pub fn new( time: &'a str, names: &[&'a str], rhs: &[&'a str], ) -> Result<Self, SolverError>

Compatibility alias for Self::general.

Source

pub fn new_with_parameters( time: &'a str, names: &[&'a str], rhs: &[&'a str], parameters: &[(&str, f64)], ) -> Result<Self, SolverError>

Compatibility alias for Self::general_with_parameters.

Source

pub fn autonomous( names: &[&'a str], rhs: &[&'a str], ) -> Result<Self, SolverError>

Creates x’ = F(x). Time-dependent expressions are rejected.

Examples found in repository?
examples/hello_world.rs (line 8)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let system = OdeSystem::autonomous(&["x", "y"], &["cos(y)", "sin(x)"])?;
9    // Start at (x, y) = (0, 0) and integrate from t = 0 to t = 10.
10    let trajectory = Solver::default().solve_problem(&system, 0.0, &[0.0, 0.0], 10.0)?;
11
12    println!("t,x,y");
13    for (t, state) in trajectory.times.iter().zip(&trajectory.states) {
14        println!("{t:.6},{:.6},{:.6}", state[0], state[1]);
15    }
16    Ok(())
17}
More examples
Hide additional examples
examples/support/mod.rs (line 70)
26pub fn run(demo: Demo) -> Result<(), Box<dyn Error>> {
27    let mut method = Method::England;
28    let mut duration = demo.duration;
29    let mut output =
30        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("target/{}.html", demo.slug));
31    let mut open = true;
32    let mut args = std::env::args().skip(1);
33    while let Some(arg) = args.next() {
34        match arg.as_str() {
35            "--method" => {
36                method = match args.next().ok_or("--method requires a value")?.as_str() {
37                    "england" => Method::England,
38                    "lawson" => Method::Lawson,
39                    "rosenbrock" => Method::Rosenbrock,
40                    "rosenbrock-autonomous" => Method::RosenbrockAutonomous,
41                    _ => {
42                        return Err(
43                            "choose england, lawson, rosenbrock, or rosenbrock-autonomous".into(),
44                        );
45                    }
46                };
47            }
48            "--duration" => duration = args.next().ok_or("--duration requires a value")?.parse()?,
49            "--output" => output = args.next().ok_or("--output requires a path")?.into(),
50            "--no-open" => open = false,
51            "--help" | "-h" => {
52                println!(
53                    "{} {} — computed by cauchy-ode\n\n\
54                    cargo run --release --example {} -- [OPTIONS]\n\n\
55                    --method england|lawson|rosenbrock|rosenbrock-autonomous\n\
56                    --duration SECONDS    Integration interval (default: {}, maximum: 5000000)\n\
57                    --output PATH         HTML output (default: target/{}.html)\n\
58                    --no-open             Generate the viewer without launching a browser",
59                    demo.system_name, demo.shape, demo.slug, demo.duration, demo.slug
60                );
61                return Ok(());
62            }
63            _ => return Err(format!("unknown option: {arg}; use --help").into()),
64        }
65    }
66    if !duration.is_finite() || duration <= 0.0 || duration > 5000000.0 {
67        return Err("duration must be finite, positive, and at most 5000000".into());
68    }
69
70    let system = OdeSystem::autonomous(&["x", "y", "z"], &demo.equations)?;
71    let solver = Solver {
72        method,
73        initial_step: 0.005,
74        max_step: 0.02,
75        tolerance: 1e-9,
76        max_steps: 10_000_000,
77        ..Solver::default()
78    };
79    println!(
80        "Integrating the {} system with {method:?} over t = 0..{duration} …",
81        demo.system_name
82    );
83    let solution = solver.solve_problem(&system, 0.0, &demo.initial_state, duration)?;
84
85    // The viewer receives only finite numeric data, so neither a JSON dependency
86    // nor escaping user-provided strings into executable JavaScript is needed.
87    let mut data = String::with_capacity(solution.times.len() * 90);
88    data.push('[');
89    for (i, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
90        if i != 0 {
91            data.push(',');
92        }
93        write!(data, "[{t},{},{},{}]", state[0], state[1], state[2])?;
94    }
95    data.push(']');
96    // All presentation/configuration strings below are source-controlled demo
97    // constants. CLI values never enter HTML or executable JavaScript.
98    let equation_label = format!(
99        "dx/dt = {}, dy/dt = {}, dz/dt = {}",
100        demo.equations[0], demo.equations[1], demo.equations[2]
101    );
102    let html = include_str!("viewer.html")
103        .replace("__TRAJECTORY_DATA__", &data)
104        .replace("__SYSTEM__", demo.system_name)
105        .replace("__SHAPE__", demo.shape)
106        .replace("__INDEX__", demo.index)
107        .replace("__DESCRIPTION__", demo.description)
108        .replace("__EQUATION_LABEL__", &equation_label)
109        .replace("__EQUATIONS_HTML__", demo.equation_html)
110        .replace("__PARAMETERS_HTML__", demo.parameter_html)
111        .replace("__VIEW_CONFIG__", demo.view_config)
112        .replace(
113            "__INITIAL__",
114            &format!(
115                "({}, {}, {})",
116                demo.initial_state[0], demo.initial_state[1], demo.initial_state[2]
117            ),
118        )
119        .replace("__METHOD__", &format!("{method:?}"));
120    if let Some(parent) = output.parent().filter(|p| !p.as_os_str().is_empty()) {
121        std::fs::create_dir_all(parent)?;
122    }
123    std::fs::write(&output, html)?;
124    let output = output.canonicalize()?;
125    println!(
126        "Saved {} trajectory points to {}",
127        solution.times.len(),
128        output.display()
129    );
130    println!("Drag to rotate · Scroll to zoom · Replay to follow the trajectory");
131    if open {
132        let result = if cfg!(target_os = "macos") {
133            Command::new("open").arg(&output).status()
134        } else if cfg!(target_os = "windows") {
135            Command::new("explorer").arg(&output).status()
136        } else {
137            Command::new("xdg-open").arg(&output).status()
138        };
139        if !matches!(result, Ok(status) if status.success()) {
140            eprintln!(
141                "Could not launch a browser. Open {} manually.",
142                output.display()
143            );
144        }
145    }
146    Ok(())
147}
examples/precision.rs (line 210)
139fn main() -> Result<(), Box<dyn Error>> {
140    let mut output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/precision");
141    let mut open = true;
142    let mut args = std::env::args().skip(1);
143    while let Some(arg) = args.next() {
144        match arg.as_str() {
145            "--no-open" => open = false,
146            "--output" => output = args.next().ok_or("--output requires a directory")?.into(),
147            "--help" | "-h" => {
148                println!(
149                    "cargo run --release --example precision -- [--no-open] [--output DIRECTORY]\nWrites index.html, 44 SVG error plots, and errors.csv (default: target/precision)."
150                );
151                return Ok(());
152            }
153            _ => return Err(format!("unknown option: {arg}").into()),
154        }
155    }
156    std::fs::create_dir_all(&output)?;
157    let names: Vec<String> = (0..N).map(|i| format!("x{i}")).collect();
158    let names: Vec<&str> = names.iter().map(String::as_str).collect();
159    let mut html = String::from(
160        "<!doctype html><html lang='en'><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>ODE precision comparison</title><style>body{font:16px system-ui;color:#172033;background:#f1f5f9;max-width:1100px;margin:40px auto;padding:0 20px}section{background:white;padding:24px;margin:24px 0;border-radius:12px}img{width:100%;height:auto}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:left;padding:8px;border-bottom:1px solid #ddd}code{font-size:14px}summary{cursor:pointer;padding:15px}a{color:#2563eb}</style><h1>Ten equations. Four system types.</h1><p>Absolute error against an analytic solution at every accepted time. All 15 compatible method/type combinations use t = 0…10, initial step 0.01, maximum step 1, local tolerance 1e-12, and the default mixed relative/absolute error control. The adaptive controller chooses step sizes within these bounds; there is no target step count. This compares accuracy under common controls, not computational cost or general method rankings.</p><p>Logarithmic error plots share a 1e-16…1 scale. Errors below 1e-16 (including zero at the initial point) are displayed at the floor. Near that floor, floating-point evaluation of the analytic solution also affects the comparison. Tables and <a href='errors.csv'>CSV data</a> retain unclipped errors.</p>",
161    );
162    let mut csv = String::from("type,method,step,time,component,numerical,exact,absolute_error\n");
163    for kind in 1..=4 {
164        let mut rhs = vec![String::new(); N];
165        let mut matrix = vec!["0".to_string(); N * N];
166        let mut constant = vec![0.0; N * N];
167        let q: Vec<String> = (0..N)
168            .map(|i| format!("(2+sin({}*t))", 0.2 + 0.02 * i as f64))
169            .collect();
170        for i in 0..N {
171            let next = (i + 1) % N;
172            let w = 0.2 + 0.02 * i as f64;
173            let derivative = format!("{w}*cos({w}*t)");
174            rhs[i] = match kind {
175                1 => format!(
176                    "{derivative}-(1+0.1*sin(t))*(x{i}-{})+0.05*(x{next}-{})^2",
177                    q[i], q[next]
178                ),
179                2 => {
180                    let a = i / 2 * 2;
181                    let b = a + 1;
182                    let omega = 0.2 + 0.04 * (i / 2) as f64;
183                    let rotation = if i.is_multiple_of(2) {
184                        format!("-{omega}*x{b}")
185                    } else {
186                        format!("{omega}*x{a}")
187                    };
188                    format!("{rotation}+0.1*(1-x{a}^2-x{b}^2)*x{i}")
189                }
190                3 => {
191                    matrix[i * N + i] = "-(1+0.1*sin(t))".into();
192                    matrix[next * N + i] = "0.1".into();
193                    format!("{derivative}+(1+0.1*sin(t))*{}-0.1*{}", q[i], q[next])
194                }
195                4 => {
196                    constant[i * N + i] = -1.0;
197                    constant[next * N + i] = 0.1;
198                    format!(
199                        "{derivative}+{}-0.1*{}+0.05*(x{next}-{})^2",
200                        q[i], q[next], q[next]
201                    )
202                }
203                _ => unreachable!(),
204            };
205        }
206        let expressions: Vec<&str> = rhs.iter().map(String::as_str).collect();
207        let entries: Vec<&str> = matrix.iter().map(String::as_str).collect();
208        let system = match kind {
209            1 => OdeSystem::general("t", &names, &expressions)?,
210            2 => OdeSystem::autonomous(&names, &expressions)?,
211            3 => OdeSystem::linear("t", &names, &entries, &expressions)?,
212            4 => OdeSystem::split("t", &names, &constant, &expressions)?,
213            _ => unreachable!(),
214        };
215        let description = match kind {
216            1 => "General: xᵢ′ = qᵢ′ − (1 + 0.1 sin t)(xᵢ − qᵢ) + 0.05(xⱼ − qⱼ)².",
217            2 => {
218                "Autonomous: for k = 0…4, a = x₂ₖ, b = x₂ₖ₊₁, ω = 0.2 + 0.04k: a′ = −ωb + 0.1(1 − a² − b²)a; b′ = ωa + 0.1(1 − a² − b²)b. Exact: a = cos(ωt), b = sin(ωt); initially (a,b) = (1,0). The radial nonlinear terms vanish on these unit circles."
219            }
220            3 => {
221                "Linear: xᵢ′ = −(1 + 0.1 sin t)xᵢ + 0.1xⱼ + φᵢ(t), where φᵢ = qᵢ′ + (1 + 0.1 sin t)qᵢ − 0.1qⱼ."
222            }
223            4 => {
224                "Constant linear part: (Bx)ᵢ = −xᵢ + 0.1xⱼ; uᵢ = qᵢ′ + qᵢ − 0.1qⱼ + 0.05(xⱼ − qⱼ)²; x′ = Bx + u."
225            }
226            _ => unreachable!(),
227        };
228        write!(html, "<section><h2>Type {kind}</h2><p>{description}</p>")?;
229        if kind != 2 {
230            html.push_str("<p>For i = 0…9, j = (i + 1) mod 10, ωᵢ = 0.2 + 0.02i, qᵢ(t) = 2 + sin(ωᵢt), qᵢ′ = ωᵢ cos(ωᵢt). Exact: xᵢ = qᵢ, initially xᵢ = 2. Substitution cancels the correction terms and gives xᵢ′ = qᵢ′.</p>");
231        }
232        html.push_str("<table><tr><th>Method / plot color</th><th>Accepted steps</th><th>Peak error</th><th>Final max error</th></tr>");
233        let initial: Vec<f64> = (0..N).map(|i| exact(kind, i, 0.0)).collect();
234        let mut runs = Vec::new();
235        for (method, color) in METHODS.into_iter().zip(COLORS) {
236            if !method.supports(system.kind()) {
237                continue;
238            }
239            let solver = Solver {
240                method,
241                initial_step: INITIAL_STEP,
242                max_step: MAX_STEP,
243                tolerance: TOLERANCE,
244                ..Solver::default()
245            };
246            let solution = solver.solve_problem(&system, 0.0, &initial, END)?;
247            let mut errors = Vec::new();
248            for (step, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
249                let mut error = [0.0; N];
250                for i in 0..N {
251                    let expected = exact(kind, i, t);
252                    error[i] = (state[i] - expected).abs();
253                    writeln!(
254                        csv,
255                        "{kind},{method:?},{step},{t:.17e},{i},{:.17e},{expected:.17e},{:.17e}",
256                        state[i], error[i]
257                    )?;
258                }
259                errors.push(error);
260            }
261            let peak = errors.iter().flatten().copied().fold(0.0, f64::max);
262            let final_error = errors.last().unwrap().iter().copied().fold(0.0, f64::max);
263            let steps = solution.times.len() - 1;
264            // Catch changes that defeat the purpose of this reproducible demo.
265            if !peak.is_finite() || peak >= 1e-3 || solution.times.last() != Some(&END) {
266                return Err(format!(
267                    "Type {kind} / {method:?}: endpoint not reached or excessive error ({peak:e})"
268                )
269                .into());
270            }
271            println!(
272                "Type {kind} {method:?}: {steps} steps, peak {peak:.3e}, final {final_error:.3e}"
273            );
274            write!(
275                html,
276                "<tr><td style='color:{color}'>{method:?}</td><td>{steps}</td><td>{peak:.3e}</td><td>{final_error:.3e}</td></tr>"
277            )?;
278            runs.push(Run {
279                method,
280                color,
281                solution,
282                errors,
283            });
284        }
285        html.push_str("</table><p>Every figure includes an accepted-step panel: h = |tₙ − tₙ₋₁| over each integration interval, with a separate linear axis. All components share the same steps. Method curves overlap when their steps agree; the final step may be shortened to reach the endpoint. These are actual accepted steps, not recommended next steps.</p>");
286        for component in std::iter::once(None).chain((0..N).map(Some)) {
287            if component == Some(0) {
288                html.push_str("<details><summary>Errors for each of the 10 components</summary>");
289            }
290            let suffix = component.map_or_else(|| "max".into(), |i| format!("x{i}"));
291            let filename = format!("type{kind}-{suffix}.svg");
292            std::fs::write(output.join(&filename), plot(&runs, component))?;
293            write!(
294                html,
295                "<a href='{filename}'><img src='{filename}' alt='Type {kind}, {suffix}: absolute error and accepted step size versus time' loading='lazy'></a>"
296            )?;
297        }
298        html.push_str("</details></section>");
299    }
300    html.push_str("<footer>Distributed under the <a href='https://www.boost.org/LICENSE_1_0.txt'>Boost Software License, Version 1.0</a>.</footer></html>");
301    std::fs::write(output.join("errors.csv"), csv)?;
302    std::fs::write(output.join("index.html"), html)?;
303    let index = output.join("index.html").canonicalize()?;
304    println!("Report: {}", index.display());
305    if open {
306        let browser = if cfg!(target_os = "macos") {
307            "open"
308        } else if cfg!(target_os = "windows") {
309            "explorer"
310        } else {
311            "xdg-open"
312        };
313        if !matches!(Command::new(browser).arg(&index).status(), Ok(s) if s.success()) {
314            eprintln!("Open {} in a browser to view the plots.", index.display());
315        }
316    }
317    Ok(())
318}
Source

pub fn autonomous_with_parameters( names: &[&'a str], rhs: &[&'a str], parameters: &[(&str, f64)], ) -> Result<Self, SolverError>

Creates an autonomous system with constant bindings; see Self::general_with_parameters for the binding rules.

Source

pub fn linear( time: &'a str, names: &[&'a str], matrix: &[&'a str], forcing: &[&'a str], ) -> Result<Self, SolverError>

Creates x’ = A(t)x + phi(t). A and phi may depend only on the named time variable. For state-dependent forcing use Self::general with the complete RHS, or split when the linear matrix is constant.

Examples found in repository?
examples/precision.rs (line 211)
139fn main() -> Result<(), Box<dyn Error>> {
140    let mut output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/precision");
141    let mut open = true;
142    let mut args = std::env::args().skip(1);
143    while let Some(arg) = args.next() {
144        match arg.as_str() {
145            "--no-open" => open = false,
146            "--output" => output = args.next().ok_or("--output requires a directory")?.into(),
147            "--help" | "-h" => {
148                println!(
149                    "cargo run --release --example precision -- [--no-open] [--output DIRECTORY]\nWrites index.html, 44 SVG error plots, and errors.csv (default: target/precision)."
150                );
151                return Ok(());
152            }
153            _ => return Err(format!("unknown option: {arg}").into()),
154        }
155    }
156    std::fs::create_dir_all(&output)?;
157    let names: Vec<String> = (0..N).map(|i| format!("x{i}")).collect();
158    let names: Vec<&str> = names.iter().map(String::as_str).collect();
159    let mut html = String::from(
160        "<!doctype html><html lang='en'><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>ODE precision comparison</title><style>body{font:16px system-ui;color:#172033;background:#f1f5f9;max-width:1100px;margin:40px auto;padding:0 20px}section{background:white;padding:24px;margin:24px 0;border-radius:12px}img{width:100%;height:auto}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:left;padding:8px;border-bottom:1px solid #ddd}code{font-size:14px}summary{cursor:pointer;padding:15px}a{color:#2563eb}</style><h1>Ten equations. Four system types.</h1><p>Absolute error against an analytic solution at every accepted time. All 15 compatible method/type combinations use t = 0…10, initial step 0.01, maximum step 1, local tolerance 1e-12, and the default mixed relative/absolute error control. The adaptive controller chooses step sizes within these bounds; there is no target step count. This compares accuracy under common controls, not computational cost or general method rankings.</p><p>Logarithmic error plots share a 1e-16…1 scale. Errors below 1e-16 (including zero at the initial point) are displayed at the floor. Near that floor, floating-point evaluation of the analytic solution also affects the comparison. Tables and <a href='errors.csv'>CSV data</a> retain unclipped errors.</p>",
161    );
162    let mut csv = String::from("type,method,step,time,component,numerical,exact,absolute_error\n");
163    for kind in 1..=4 {
164        let mut rhs = vec![String::new(); N];
165        let mut matrix = vec!["0".to_string(); N * N];
166        let mut constant = vec![0.0; N * N];
167        let q: Vec<String> = (0..N)
168            .map(|i| format!("(2+sin({}*t))", 0.2 + 0.02 * i as f64))
169            .collect();
170        for i in 0..N {
171            let next = (i + 1) % N;
172            let w = 0.2 + 0.02 * i as f64;
173            let derivative = format!("{w}*cos({w}*t)");
174            rhs[i] = match kind {
175                1 => format!(
176                    "{derivative}-(1+0.1*sin(t))*(x{i}-{})+0.05*(x{next}-{})^2",
177                    q[i], q[next]
178                ),
179                2 => {
180                    let a = i / 2 * 2;
181                    let b = a + 1;
182                    let omega = 0.2 + 0.04 * (i / 2) as f64;
183                    let rotation = if i.is_multiple_of(2) {
184                        format!("-{omega}*x{b}")
185                    } else {
186                        format!("{omega}*x{a}")
187                    };
188                    format!("{rotation}+0.1*(1-x{a}^2-x{b}^2)*x{i}")
189                }
190                3 => {
191                    matrix[i * N + i] = "-(1+0.1*sin(t))".into();
192                    matrix[next * N + i] = "0.1".into();
193                    format!("{derivative}+(1+0.1*sin(t))*{}-0.1*{}", q[i], q[next])
194                }
195                4 => {
196                    constant[i * N + i] = -1.0;
197                    constant[next * N + i] = 0.1;
198                    format!(
199                        "{derivative}+{}-0.1*{}+0.05*(x{next}-{})^2",
200                        q[i], q[next], q[next]
201                    )
202                }
203                _ => unreachable!(),
204            };
205        }
206        let expressions: Vec<&str> = rhs.iter().map(String::as_str).collect();
207        let entries: Vec<&str> = matrix.iter().map(String::as_str).collect();
208        let system = match kind {
209            1 => OdeSystem::general("t", &names, &expressions)?,
210            2 => OdeSystem::autonomous(&names, &expressions)?,
211            3 => OdeSystem::linear("t", &names, &entries, &expressions)?,
212            4 => OdeSystem::split("t", &names, &constant, &expressions)?,
213            _ => unreachable!(),
214        };
215        let description = match kind {
216            1 => "General: xᵢ′ = qᵢ′ − (1 + 0.1 sin t)(xᵢ − qᵢ) + 0.05(xⱼ − qⱼ)².",
217            2 => {
218                "Autonomous: for k = 0…4, a = x₂ₖ, b = x₂ₖ₊₁, ω = 0.2 + 0.04k: a′ = −ωb + 0.1(1 − a² − b²)a; b′ = ωa + 0.1(1 − a² − b²)b. Exact: a = cos(ωt), b = sin(ωt); initially (a,b) = (1,0). The radial nonlinear terms vanish on these unit circles."
219            }
220            3 => {
221                "Linear: xᵢ′ = −(1 + 0.1 sin t)xᵢ + 0.1xⱼ + φᵢ(t), where φᵢ = qᵢ′ + (1 + 0.1 sin t)qᵢ − 0.1qⱼ."
222            }
223            4 => {
224                "Constant linear part: (Bx)ᵢ = −xᵢ + 0.1xⱼ; uᵢ = qᵢ′ + qᵢ − 0.1qⱼ + 0.05(xⱼ − qⱼ)²; x′ = Bx + u."
225            }
226            _ => unreachable!(),
227        };
228        write!(html, "<section><h2>Type {kind}</h2><p>{description}</p>")?;
229        if kind != 2 {
230            html.push_str("<p>For i = 0…9, j = (i + 1) mod 10, ωᵢ = 0.2 + 0.02i, qᵢ(t) = 2 + sin(ωᵢt), qᵢ′ = ωᵢ cos(ωᵢt). Exact: xᵢ = qᵢ, initially xᵢ = 2. Substitution cancels the correction terms and gives xᵢ′ = qᵢ′.</p>");
231        }
232        html.push_str("<table><tr><th>Method / plot color</th><th>Accepted steps</th><th>Peak error</th><th>Final max error</th></tr>");
233        let initial: Vec<f64> = (0..N).map(|i| exact(kind, i, 0.0)).collect();
234        let mut runs = Vec::new();
235        for (method, color) in METHODS.into_iter().zip(COLORS) {
236            if !method.supports(system.kind()) {
237                continue;
238            }
239            let solver = Solver {
240                method,
241                initial_step: INITIAL_STEP,
242                max_step: MAX_STEP,
243                tolerance: TOLERANCE,
244                ..Solver::default()
245            };
246            let solution = solver.solve_problem(&system, 0.0, &initial, END)?;
247            let mut errors = Vec::new();
248            for (step, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
249                let mut error = [0.0; N];
250                for i in 0..N {
251                    let expected = exact(kind, i, t);
252                    error[i] = (state[i] - expected).abs();
253                    writeln!(
254                        csv,
255                        "{kind},{method:?},{step},{t:.17e},{i},{:.17e},{expected:.17e},{:.17e}",
256                        state[i], error[i]
257                    )?;
258                }
259                errors.push(error);
260            }
261            let peak = errors.iter().flatten().copied().fold(0.0, f64::max);
262            let final_error = errors.last().unwrap().iter().copied().fold(0.0, f64::max);
263            let steps = solution.times.len() - 1;
264            // Catch changes that defeat the purpose of this reproducible demo.
265            if !peak.is_finite() || peak >= 1e-3 || solution.times.last() != Some(&END) {
266                return Err(format!(
267                    "Type {kind} / {method:?}: endpoint not reached or excessive error ({peak:e})"
268                )
269                .into());
270            }
271            println!(
272                "Type {kind} {method:?}: {steps} steps, peak {peak:.3e}, final {final_error:.3e}"
273            );
274            write!(
275                html,
276                "<tr><td style='color:{color}'>{method:?}</td><td>{steps}</td><td>{peak:.3e}</td><td>{final_error:.3e}</td></tr>"
277            )?;
278            runs.push(Run {
279                method,
280                color,
281                solution,
282                errors,
283            });
284        }
285        html.push_str("</table><p>Every figure includes an accepted-step panel: h = |tₙ − tₙ₋₁| over each integration interval, with a separate linear axis. All components share the same steps. Method curves overlap when their steps agree; the final step may be shortened to reach the endpoint. These are actual accepted steps, not recommended next steps.</p>");
286        for component in std::iter::once(None).chain((0..N).map(Some)) {
287            if component == Some(0) {
288                html.push_str("<details><summary>Errors for each of the 10 components</summary>");
289            }
290            let suffix = component.map_or_else(|| "max".into(), |i| format!("x{i}"));
291            let filename = format!("type{kind}-{suffix}.svg");
292            std::fs::write(output.join(&filename), plot(&runs, component))?;
293            write!(
294                html,
295                "<a href='{filename}'><img src='{filename}' alt='Type {kind}, {suffix}: absolute error and accepted step size versus time' loading='lazy'></a>"
296            )?;
297        }
298        html.push_str("</details></section>");
299    }
300    html.push_str("<footer>Distributed under the <a href='https://www.boost.org/LICENSE_1_0.txt'>Boost Software License, Version 1.0</a>.</footer></html>");
301    std::fs::write(output.join("errors.csv"), csv)?;
302    std::fs::write(output.join("index.html"), html)?;
303    let index = output.join("index.html").canonicalize()?;
304    println!("Report: {}", index.display());
305    if open {
306        let browser = if cfg!(target_os = "macos") {
307            "open"
308        } else if cfg!(target_os = "windows") {
309            "explorer"
310        } else {
311            "xdg-open"
312        };
313        if !matches!(Command::new(browser).arg(&index).status(), Ok(s) if s.success()) {
314            eprintln!("Open {} in a browser to view the plots.", index.display());
315        }
316    }
317    Ok(())
318}
Source

pub fn linear_with_parameters( time: &'a str, names: &[&'a str], matrix: &[&'a str], forcing: &[&'a str], parameters: &[(&str, f64)], ) -> Result<Self, SolverError>

Binds constants in both A(t) and phi(t). After binding, only the named time variable may remain in either expression collection.

Source

pub fn split( time: &'a str, names: &[&'a str], matrix: &[f64], remainder: &[&'a str], ) -> Result<Self, SolverError>

Creates x’ = Bx + u(t,x), with a finite constant column-major matrix B.

Examples found in repository?
examples/precision.rs (line 212)
139fn main() -> Result<(), Box<dyn Error>> {
140    let mut output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/precision");
141    let mut open = true;
142    let mut args = std::env::args().skip(1);
143    while let Some(arg) = args.next() {
144        match arg.as_str() {
145            "--no-open" => open = false,
146            "--output" => output = args.next().ok_or("--output requires a directory")?.into(),
147            "--help" | "-h" => {
148                println!(
149                    "cargo run --release --example precision -- [--no-open] [--output DIRECTORY]\nWrites index.html, 44 SVG error plots, and errors.csv (default: target/precision)."
150                );
151                return Ok(());
152            }
153            _ => return Err(format!("unknown option: {arg}").into()),
154        }
155    }
156    std::fs::create_dir_all(&output)?;
157    let names: Vec<String> = (0..N).map(|i| format!("x{i}")).collect();
158    let names: Vec<&str> = names.iter().map(String::as_str).collect();
159    let mut html = String::from(
160        "<!doctype html><html lang='en'><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>ODE precision comparison</title><style>body{font:16px system-ui;color:#172033;background:#f1f5f9;max-width:1100px;margin:40px auto;padding:0 20px}section{background:white;padding:24px;margin:24px 0;border-radius:12px}img{width:100%;height:auto}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:left;padding:8px;border-bottom:1px solid #ddd}code{font-size:14px}summary{cursor:pointer;padding:15px}a{color:#2563eb}</style><h1>Ten equations. Four system types.</h1><p>Absolute error against an analytic solution at every accepted time. All 15 compatible method/type combinations use t = 0…10, initial step 0.01, maximum step 1, local tolerance 1e-12, and the default mixed relative/absolute error control. The adaptive controller chooses step sizes within these bounds; there is no target step count. This compares accuracy under common controls, not computational cost or general method rankings.</p><p>Logarithmic error plots share a 1e-16…1 scale. Errors below 1e-16 (including zero at the initial point) are displayed at the floor. Near that floor, floating-point evaluation of the analytic solution also affects the comparison. Tables and <a href='errors.csv'>CSV data</a> retain unclipped errors.</p>",
161    );
162    let mut csv = String::from("type,method,step,time,component,numerical,exact,absolute_error\n");
163    for kind in 1..=4 {
164        let mut rhs = vec![String::new(); N];
165        let mut matrix = vec!["0".to_string(); N * N];
166        let mut constant = vec![0.0; N * N];
167        let q: Vec<String> = (0..N)
168            .map(|i| format!("(2+sin({}*t))", 0.2 + 0.02 * i as f64))
169            .collect();
170        for i in 0..N {
171            let next = (i + 1) % N;
172            let w = 0.2 + 0.02 * i as f64;
173            let derivative = format!("{w}*cos({w}*t)");
174            rhs[i] = match kind {
175                1 => format!(
176                    "{derivative}-(1+0.1*sin(t))*(x{i}-{})+0.05*(x{next}-{})^2",
177                    q[i], q[next]
178                ),
179                2 => {
180                    let a = i / 2 * 2;
181                    let b = a + 1;
182                    let omega = 0.2 + 0.04 * (i / 2) as f64;
183                    let rotation = if i.is_multiple_of(2) {
184                        format!("-{omega}*x{b}")
185                    } else {
186                        format!("{omega}*x{a}")
187                    };
188                    format!("{rotation}+0.1*(1-x{a}^2-x{b}^2)*x{i}")
189                }
190                3 => {
191                    matrix[i * N + i] = "-(1+0.1*sin(t))".into();
192                    matrix[next * N + i] = "0.1".into();
193                    format!("{derivative}+(1+0.1*sin(t))*{}-0.1*{}", q[i], q[next])
194                }
195                4 => {
196                    constant[i * N + i] = -1.0;
197                    constant[next * N + i] = 0.1;
198                    format!(
199                        "{derivative}+{}-0.1*{}+0.05*(x{next}-{})^2",
200                        q[i], q[next], q[next]
201                    )
202                }
203                _ => unreachable!(),
204            };
205        }
206        let expressions: Vec<&str> = rhs.iter().map(String::as_str).collect();
207        let entries: Vec<&str> = matrix.iter().map(String::as_str).collect();
208        let system = match kind {
209            1 => OdeSystem::general("t", &names, &expressions)?,
210            2 => OdeSystem::autonomous(&names, &expressions)?,
211            3 => OdeSystem::linear("t", &names, &entries, &expressions)?,
212            4 => OdeSystem::split("t", &names, &constant, &expressions)?,
213            _ => unreachable!(),
214        };
215        let description = match kind {
216            1 => "General: xᵢ′ = qᵢ′ − (1 + 0.1 sin t)(xᵢ − qᵢ) + 0.05(xⱼ − qⱼ)².",
217            2 => {
218                "Autonomous: for k = 0…4, a = x₂ₖ, b = x₂ₖ₊₁, ω = 0.2 + 0.04k: a′ = −ωb + 0.1(1 − a² − b²)a; b′ = ωa + 0.1(1 − a² − b²)b. Exact: a = cos(ωt), b = sin(ωt); initially (a,b) = (1,0). The radial nonlinear terms vanish on these unit circles."
219            }
220            3 => {
221                "Linear: xᵢ′ = −(1 + 0.1 sin t)xᵢ + 0.1xⱼ + φᵢ(t), where φᵢ = qᵢ′ + (1 + 0.1 sin t)qᵢ − 0.1qⱼ."
222            }
223            4 => {
224                "Constant linear part: (Bx)ᵢ = −xᵢ + 0.1xⱼ; uᵢ = qᵢ′ + qᵢ − 0.1qⱼ + 0.05(xⱼ − qⱼ)²; x′ = Bx + u."
225            }
226            _ => unreachable!(),
227        };
228        write!(html, "<section><h2>Type {kind}</h2><p>{description}</p>")?;
229        if kind != 2 {
230            html.push_str("<p>For i = 0…9, j = (i + 1) mod 10, ωᵢ = 0.2 + 0.02i, qᵢ(t) = 2 + sin(ωᵢt), qᵢ′ = ωᵢ cos(ωᵢt). Exact: xᵢ = qᵢ, initially xᵢ = 2. Substitution cancels the correction terms and gives xᵢ′ = qᵢ′.</p>");
231        }
232        html.push_str("<table><tr><th>Method / plot color</th><th>Accepted steps</th><th>Peak error</th><th>Final max error</th></tr>");
233        let initial: Vec<f64> = (0..N).map(|i| exact(kind, i, 0.0)).collect();
234        let mut runs = Vec::new();
235        for (method, color) in METHODS.into_iter().zip(COLORS) {
236            if !method.supports(system.kind()) {
237                continue;
238            }
239            let solver = Solver {
240                method,
241                initial_step: INITIAL_STEP,
242                max_step: MAX_STEP,
243                tolerance: TOLERANCE,
244                ..Solver::default()
245            };
246            let solution = solver.solve_problem(&system, 0.0, &initial, END)?;
247            let mut errors = Vec::new();
248            for (step, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
249                let mut error = [0.0; N];
250                for i in 0..N {
251                    let expected = exact(kind, i, t);
252                    error[i] = (state[i] - expected).abs();
253                    writeln!(
254                        csv,
255                        "{kind},{method:?},{step},{t:.17e},{i},{:.17e},{expected:.17e},{:.17e}",
256                        state[i], error[i]
257                    )?;
258                }
259                errors.push(error);
260            }
261            let peak = errors.iter().flatten().copied().fold(0.0, f64::max);
262            let final_error = errors.last().unwrap().iter().copied().fold(0.0, f64::max);
263            let steps = solution.times.len() - 1;
264            // Catch changes that defeat the purpose of this reproducible demo.
265            if !peak.is_finite() || peak >= 1e-3 || solution.times.last() != Some(&END) {
266                return Err(format!(
267                    "Type {kind} / {method:?}: endpoint not reached or excessive error ({peak:e})"
268                )
269                .into());
270            }
271            println!(
272                "Type {kind} {method:?}: {steps} steps, peak {peak:.3e}, final {final_error:.3e}"
273            );
274            write!(
275                html,
276                "<tr><td style='color:{color}'>{method:?}</td><td>{steps}</td><td>{peak:.3e}</td><td>{final_error:.3e}</td></tr>"
277            )?;
278            runs.push(Run {
279                method,
280                color,
281                solution,
282                errors,
283            });
284        }
285        html.push_str("</table><p>Every figure includes an accepted-step panel: h = |tₙ − tₙ₋₁| over each integration interval, with a separate linear axis. All components share the same steps. Method curves overlap when their steps agree; the final step may be shortened to reach the endpoint. These are actual accepted steps, not recommended next steps.</p>");
286        for component in std::iter::once(None).chain((0..N).map(Some)) {
287            if component == Some(0) {
288                html.push_str("<details><summary>Errors for each of the 10 components</summary>");
289            }
290            let suffix = component.map_or_else(|| "max".into(), |i| format!("x{i}"));
291            let filename = format!("type{kind}-{suffix}.svg");
292            std::fs::write(output.join(&filename), plot(&runs, component))?;
293            write!(
294                html,
295                "<a href='{filename}'><img src='{filename}' alt='Type {kind}, {suffix}: absolute error and accepted step size versus time' loading='lazy'></a>"
296            )?;
297        }
298        html.push_str("</details></section>");
299    }
300    html.push_str("<footer>Distributed under the <a href='https://www.boost.org/LICENSE_1_0.txt'>Boost Software License, Version 1.0</a>.</footer></html>");
301    std::fs::write(output.join("errors.csv"), csv)?;
302    std::fs::write(output.join("index.html"), html)?;
303    let index = output.join("index.html").canonicalize()?;
304    println!("Report: {}", index.display());
305    if open {
306        let browser = if cfg!(target_os = "macos") {
307            "open"
308        } else if cfg!(target_os = "windows") {
309            "explorer"
310        } else {
311            "xdg-open"
312        };
313        if !matches!(Command::new(browser).arg(&index).status(), Ok(s) if s.success()) {
314            eprintln!("Open {} in a browser to view the plots.", index.display());
315        }
316    }
317    Ok(())
318}
Source

pub fn split_with_parameters( time: &'a str, names: &[&'a str], matrix: &[&'a str], remainder: &[&'a str], parameters: &[(&str, f64)], ) -> Result<Self, SolverError>

Creates Bx + u(t,x) with parameters in both B and u. Unlike Self::split, B is supplied as column-major expression strings (e.g. “-rate”). Each matrix entry must evaluate to a finite constant after parameter binding; time/state-dependent matrices are rejected.

Source

pub fn kind(&self) -> SystemKind

Examples found in repository?
examples/precision.rs (line 236)
139fn main() -> Result<(), Box<dyn Error>> {
140    let mut output = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/precision");
141    let mut open = true;
142    let mut args = std::env::args().skip(1);
143    while let Some(arg) = args.next() {
144        match arg.as_str() {
145            "--no-open" => open = false,
146            "--output" => output = args.next().ok_or("--output requires a directory")?.into(),
147            "--help" | "-h" => {
148                println!(
149                    "cargo run --release --example precision -- [--no-open] [--output DIRECTORY]\nWrites index.html, 44 SVG error plots, and errors.csv (default: target/precision)."
150                );
151                return Ok(());
152            }
153            _ => return Err(format!("unknown option: {arg}").into()),
154        }
155    }
156    std::fs::create_dir_all(&output)?;
157    let names: Vec<String> = (0..N).map(|i| format!("x{i}")).collect();
158    let names: Vec<&str> = names.iter().map(String::as_str).collect();
159    let mut html = String::from(
160        "<!doctype html><html lang='en'><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>ODE precision comparison</title><style>body{font:16px system-ui;color:#172033;background:#f1f5f9;max-width:1100px;margin:40px auto;padding:0 20px}section{background:white;padding:24px;margin:24px 0;border-radius:12px}img{width:100%;height:auto}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:left;padding:8px;border-bottom:1px solid #ddd}code{font-size:14px}summary{cursor:pointer;padding:15px}a{color:#2563eb}</style><h1>Ten equations. Four system types.</h1><p>Absolute error against an analytic solution at every accepted time. All 15 compatible method/type combinations use t = 0…10, initial step 0.01, maximum step 1, local tolerance 1e-12, and the default mixed relative/absolute error control. The adaptive controller chooses step sizes within these bounds; there is no target step count. This compares accuracy under common controls, not computational cost or general method rankings.</p><p>Logarithmic error plots share a 1e-16…1 scale. Errors below 1e-16 (including zero at the initial point) are displayed at the floor. Near that floor, floating-point evaluation of the analytic solution also affects the comparison. Tables and <a href='errors.csv'>CSV data</a> retain unclipped errors.</p>",
161    );
162    let mut csv = String::from("type,method,step,time,component,numerical,exact,absolute_error\n");
163    for kind in 1..=4 {
164        let mut rhs = vec![String::new(); N];
165        let mut matrix = vec!["0".to_string(); N * N];
166        let mut constant = vec![0.0; N * N];
167        let q: Vec<String> = (0..N)
168            .map(|i| format!("(2+sin({}*t))", 0.2 + 0.02 * i as f64))
169            .collect();
170        for i in 0..N {
171            let next = (i + 1) % N;
172            let w = 0.2 + 0.02 * i as f64;
173            let derivative = format!("{w}*cos({w}*t)");
174            rhs[i] = match kind {
175                1 => format!(
176                    "{derivative}-(1+0.1*sin(t))*(x{i}-{})+0.05*(x{next}-{})^2",
177                    q[i], q[next]
178                ),
179                2 => {
180                    let a = i / 2 * 2;
181                    let b = a + 1;
182                    let omega = 0.2 + 0.04 * (i / 2) as f64;
183                    let rotation = if i.is_multiple_of(2) {
184                        format!("-{omega}*x{b}")
185                    } else {
186                        format!("{omega}*x{a}")
187                    };
188                    format!("{rotation}+0.1*(1-x{a}^2-x{b}^2)*x{i}")
189                }
190                3 => {
191                    matrix[i * N + i] = "-(1+0.1*sin(t))".into();
192                    matrix[next * N + i] = "0.1".into();
193                    format!("{derivative}+(1+0.1*sin(t))*{}-0.1*{}", q[i], q[next])
194                }
195                4 => {
196                    constant[i * N + i] = -1.0;
197                    constant[next * N + i] = 0.1;
198                    format!(
199                        "{derivative}+{}-0.1*{}+0.05*(x{next}-{})^2",
200                        q[i], q[next], q[next]
201                    )
202                }
203                _ => unreachable!(),
204            };
205        }
206        let expressions: Vec<&str> = rhs.iter().map(String::as_str).collect();
207        let entries: Vec<&str> = matrix.iter().map(String::as_str).collect();
208        let system = match kind {
209            1 => OdeSystem::general("t", &names, &expressions)?,
210            2 => OdeSystem::autonomous(&names, &expressions)?,
211            3 => OdeSystem::linear("t", &names, &entries, &expressions)?,
212            4 => OdeSystem::split("t", &names, &constant, &expressions)?,
213            _ => unreachable!(),
214        };
215        let description = match kind {
216            1 => "General: xᵢ′ = qᵢ′ − (1 + 0.1 sin t)(xᵢ − qᵢ) + 0.05(xⱼ − qⱼ)².",
217            2 => {
218                "Autonomous: for k = 0…4, a = x₂ₖ, b = x₂ₖ₊₁, ω = 0.2 + 0.04k: a′ = −ωb + 0.1(1 − a² − b²)a; b′ = ωa + 0.1(1 − a² − b²)b. Exact: a = cos(ωt), b = sin(ωt); initially (a,b) = (1,0). The radial nonlinear terms vanish on these unit circles."
219            }
220            3 => {
221                "Linear: xᵢ′ = −(1 + 0.1 sin t)xᵢ + 0.1xⱼ + φᵢ(t), where φᵢ = qᵢ′ + (1 + 0.1 sin t)qᵢ − 0.1qⱼ."
222            }
223            4 => {
224                "Constant linear part: (Bx)ᵢ = −xᵢ + 0.1xⱼ; uᵢ = qᵢ′ + qᵢ − 0.1qⱼ + 0.05(xⱼ − qⱼ)²; x′ = Bx + u."
225            }
226            _ => unreachable!(),
227        };
228        write!(html, "<section><h2>Type {kind}</h2><p>{description}</p>")?;
229        if kind != 2 {
230            html.push_str("<p>For i = 0…9, j = (i + 1) mod 10, ωᵢ = 0.2 + 0.02i, qᵢ(t) = 2 + sin(ωᵢt), qᵢ′ = ωᵢ cos(ωᵢt). Exact: xᵢ = qᵢ, initially xᵢ = 2. Substitution cancels the correction terms and gives xᵢ′ = qᵢ′.</p>");
231        }
232        html.push_str("<table><tr><th>Method / plot color</th><th>Accepted steps</th><th>Peak error</th><th>Final max error</th></tr>");
233        let initial: Vec<f64> = (0..N).map(|i| exact(kind, i, 0.0)).collect();
234        let mut runs = Vec::new();
235        for (method, color) in METHODS.into_iter().zip(COLORS) {
236            if !method.supports(system.kind()) {
237                continue;
238            }
239            let solver = Solver {
240                method,
241                initial_step: INITIAL_STEP,
242                max_step: MAX_STEP,
243                tolerance: TOLERANCE,
244                ..Solver::default()
245            };
246            let solution = solver.solve_problem(&system, 0.0, &initial, END)?;
247            let mut errors = Vec::new();
248            for (step, (&t, state)) in solution.times.iter().zip(&solution.states).enumerate() {
249                let mut error = [0.0; N];
250                for i in 0..N {
251                    let expected = exact(kind, i, t);
252                    error[i] = (state[i] - expected).abs();
253                    writeln!(
254                        csv,
255                        "{kind},{method:?},{step},{t:.17e},{i},{:.17e},{expected:.17e},{:.17e}",
256                        state[i], error[i]
257                    )?;
258                }
259                errors.push(error);
260            }
261            let peak = errors.iter().flatten().copied().fold(0.0, f64::max);
262            let final_error = errors.last().unwrap().iter().copied().fold(0.0, f64::max);
263            let steps = solution.times.len() - 1;
264            // Catch changes that defeat the purpose of this reproducible demo.
265            if !peak.is_finite() || peak >= 1e-3 || solution.times.last() != Some(&END) {
266                return Err(format!(
267                    "Type {kind} / {method:?}: endpoint not reached or excessive error ({peak:e})"
268                )
269                .into());
270            }
271            println!(
272                "Type {kind} {method:?}: {steps} steps, peak {peak:.3e}, final {final_error:.3e}"
273            );
274            write!(
275                html,
276                "<tr><td style='color:{color}'>{method:?}</td><td>{steps}</td><td>{peak:.3e}</td><td>{final_error:.3e}</td></tr>"
277            )?;
278            runs.push(Run {
279                method,
280                color,
281                solution,
282                errors,
283            });
284        }
285        html.push_str("</table><p>Every figure includes an accepted-step panel: h = |tₙ − tₙ₋₁| over each integration interval, with a separate linear axis. All components share the same steps. Method curves overlap when their steps agree; the final step may be shortened to reach the endpoint. These are actual accepted steps, not recommended next steps.</p>");
286        for component in std::iter::once(None).chain((0..N).map(Some)) {
287            if component == Some(0) {
288                html.push_str("<details><summary>Errors for each of the 10 components</summary>");
289            }
290            let suffix = component.map_or_else(|| "max".into(), |i| format!("x{i}"));
291            let filename = format!("type{kind}-{suffix}.svg");
292            std::fs::write(output.join(&filename), plot(&runs, component))?;
293            write!(
294                html,
295                "<a href='{filename}'><img src='{filename}' alt='Type {kind}, {suffix}: absolute error and accepted step size versus time' loading='lazy'></a>"
296            )?;
297        }
298        html.push_str("</details></section>");
299    }
300    html.push_str("<footer>Distributed under the <a href='https://www.boost.org/LICENSE_1_0.txt'>Boost Software License, Version 1.0</a>.</footer></html>");
301    std::fs::write(output.join("errors.csv"), csv)?;
302    std::fs::write(output.join("index.html"), html)?;
303    let index = output.join("index.html").canonicalize()?;
304    println!("Report: {}", index.display());
305    if open {
306        let browser = if cfg!(target_os = "macos") {
307            "open"
308        } else if cfg!(target_os = "windows") {
309            "explorer"
310        } else {
311            "xdg-open"
312        };
313        if !matches!(Command::new(browser).arg(&index).status(), Ok(s) if s.success()) {
314            eprintln!("Open {} in a browser to view the plots.", index.display());
315        }
316    }
317    Ok(())
318}
Source

pub fn dimension(&self) -> usize

Source

pub fn variables(&self) -> &[&'a str]

Source

pub fn expressions(&self) -> &[MathExpr<'a, f64>]

Trait Implementations§

Source§

impl<'a> Clone for OdeSystem<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for OdeSystem<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Forget for OdeSystem<'a>

§

impl<'a> Freeze for OdeSystem<'a>

§

impl<'a> RefUnwindSafe for OdeSystem<'a>

§

impl<'a> Send for OdeSystem<'a>

§

impl<'a> Sync for OdeSystem<'a>

§

impl<'a> Unpin for OdeSystem<'a>

§

impl<'a> UnsafeUnpin for OdeSystem<'a>

§

impl<'a> UnwindSafe for OdeSystem<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.