Skip to main content

precision/
precision.rs

1// SPDX-License-Identifier: BSL-1.0
2// Distributed under the Boost Software License, Version 1.0.
3// See LICENSE or https://www.boost.org/LICENSE_1_0.txt.
4
5//! Compare all supported system/method combinations against exact solutions.
6//! `cargo run --release --example precision -- --no-open`
7use cauchy_ode::{Method, OdeSystem, Solution, Solver};
8use std::{error::Error, fmt::Write, path::PathBuf, process::Command};
9
10const N: usize = 10;
11const END: f64 = 10.0;
12const INITIAL_STEP: f64 = 0.01;
13const MAX_STEP: f64 = 1.0;
14const TOLERANCE: f64 = 1e-12;
15const METHODS: [Method; 6] = [
16    Method::England,
17    Method::Lawson,
18    Method::LawsonLinear,
19    Method::LawsonSplit,
20    Method::Rosenbrock,
21    Method::RosenbrockAutonomous,
22];
23const COLORS: [&str; 6] = [
24    "#2563eb", "#d97706", "#059669", "#9333ea", "#dc2626", "#0891b2",
25];
26
27fn exact(kind: usize, i: usize, t: f64) -> f64 {
28    if kind == 2 {
29        let angle = (0.2 + 0.04 * (i / 2) as f64) * t;
30        if i.is_multiple_of(2) {
31            angle.cos()
32        } else {
33            angle.sin()
34        }
35    } else {
36        2.0 + ((0.2 + 0.02 * i as f64) * t).sin()
37    }
38}
39
40struct Run {
41    method: Method,
42    color: &'static str,
43    solution: Solution,
44    errors: Vec<[f64; N]>,
45}
46
47// Render actual accepted times without interpolation. Zero errors are clipped
48// only for the logarithmic plot; the table and CSV retain the original values.
49fn plot(runs: &[Run], component: Option<usize>) -> String {
50    let title = component.map_or_else(
51        || "Maximum over all 10 components".into(),
52        |i| format!("Component x{i}"),
53    );
54    let mut svg = format!(
55        "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 760 560' role='img' aria-label='{title}: absolute error and accepted step size versus time'><rect width='760' height='560' fill='white'/><text x='80' y='23' font-size='17'>{title}</text>"
56    );
57    for exponent in -16..=0 {
58        let y = 250.0 - (exponent + 16) as f64 / 16.0 * 210.0;
59        write!(svg, "<path d='M80 {y}H730' stroke='#e2e8f0'/>").unwrap();
60        if exponent % 2 == 0 {
61            write!(
62                svg,
63                "<text x='70' y='{}' text-anchor='end' font-size='12'>1e{exponent}</text>",
64                y + 4.0
65            )
66            .unwrap();
67        }
68    }
69    for t in 0..=10 {
70        let x = 80 + t * 65;
71        write!(
72            svg,
73            "<text x='{x}' y='270' text-anchor='middle' font-size='12'>{t}</text>"
74        )
75        .unwrap();
76    }
77    svg.push_str("<text x='400' y='292' font-size='13'>Time t</text><text transform='translate(18 200) rotate(-90)' font-size='13'>Absolute error (log scale)</text>");
78    svg.push_str(
79        "<text x='80' y='325' font-size='15'>Accepted step size · initial = 0.01 · cap = 1</text>",
80    );
81    // A linear axis keeps ordinary adaptations visible even when a final
82    // endpoint step is close to roundoff. Each h spans its own interval.
83    let maximum_step = runs
84        .iter()
85        .flat_map(|run| run.solution.times.windows(2))
86        .map(|pair| (pair[1] - pair[0]).abs())
87        .fold(INITIAL_STEP, f64::max);
88    let step_y = |h: f64| 470.0 - h / (maximum_step * 1.1) * 120.0;
89    for tick in 0..=4 {
90        let h = maximum_step * tick as f64 / 4.0;
91        let y = step_y(h);
92        write!(svg, "<path d='M80 {y}H730' stroke='#e2e8f0'/>").unwrap();
93        write!(
94            svg,
95            "<text x='70' y='{}' text-anchor='end' font-size='12'>{h:.3}</text>",
96            y + 4.0
97        )
98        .unwrap();
99    }
100    for t in 0..=10 {
101        let x = 80 + t * 65;
102        write!(
103            svg,
104            "<text x='{x}' y='490' text-anchor='middle' font-size='12'>{t}</text>"
105        )
106        .unwrap();
107    }
108    svg.push_str("<text x='400' y='512' font-size='13'>Time t</text><text transform='translate(18 455) rotate(-90)' font-size='13'>Step h (linear scale)</text>");
109    for (index, run) in runs.iter().enumerate() {
110        let mut path = String::new();
111        for (k, (&t, errors)) in run.solution.times.iter().zip(&run.errors).enumerate() {
112            let error =
113                component.map_or_else(|| errors.iter().copied().fold(0.0, f64::max), |i| errors[i]);
114            let x = 80.0 + 650.0 * t / END;
115            let y = 250.0 - (error.clamp(1e-16, 1.0).log10() + 16.0) / 16.0 * 210.0;
116            write!(path, "{}{x:.3},{y:.3}", if k == 0 { 'M' } else { 'L' }).unwrap();
117        }
118        write!(svg, "<path d='{path}' fill='none' stroke='{}' stroke-width='1.4'><title>{:?}</title></path>", run.color, run.method).unwrap();
119        let mut step_path = String::new();
120        for (k, pair) in run.solution.times.windows(2).enumerate() {
121            let x0 = 80.0 + 650.0 * pair[0] / END;
122            let x1 = 80.0 + 650.0 * pair[1] / END;
123            let y = step_y((pair[1] - pair[0]).abs());
124            if k == 0 {
125                write!(step_path, "M{x0:.3},{y:.3}").unwrap();
126            } else {
127                write!(step_path, "V{y:.3}").unwrap();
128            }
129            write!(step_path, "H{x1:.3}").unwrap();
130        }
131        write!(svg, "<path d='{step_path}' fill='none' stroke='{}' stroke-width='1.4'><title>{:?}: actual accepted step sizes</title></path>", run.color, run.method).unwrap();
132        let x = 80 + index * 165;
133        write!(svg, "<path d='M{x} 536h15' stroke='{}' stroke-width='2'/><text x='{}' y='540' font-size='11'>{:?}</text>", run.color, x + 20, run.method).unwrap();
134    }
135    svg.push_str("</svg>");
136    svg
137}
138
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}