pub enum Method {
England,
Lawson,
LawsonLinear,
LawsonSplit,
Rosenbrock,
RosenbrockAutonomous,
}Variants§
Implementations§
Source§impl Method
impl Method
Sourcepub fn supports(self, kind: SystemKind) -> bool
pub fn supports(self, kind: SystemKind) -> bool
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}Trait Implementations§
impl Copy for Method
impl Eq for Method
impl StructuralPartialEq for Method
Auto Trait Implementations§
impl Forget for Method
impl Freeze for Method
impl RefUnwindSafe for Method
impl Send for Method
impl Sync for Method
impl Unpin for Method
impl UnsafeUnpin for Method
impl UnwindSafe for Method
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more