1use cauchy_ode::{Method, OdeSystem, Solver};
7use std::error::Error;
8use std::fmt::Write;
9use std::path::PathBuf;
10use std::process::Command;
11
12pub struct Demo {
13 pub slug: &'static str,
14 pub system_name: &'static str,
15 pub shape: &'static str,
16 pub index: &'static str,
17 pub description: &'static str,
18 pub equations: [&'static str; 3],
19 pub equation_html: &'static str,
20 pub parameter_html: &'static str,
21 pub view_config: &'static str,
22 pub duration: f64,
23 pub initial_state: [f64; 3],
24}
25
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 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 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}