scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use scirs2_core::ndarray::{array, Array1, ArrayView1};
use scirs2_integrate::error::IntegrateResult;
use scirs2_integrate::ode::utils::dense_output::{create_dense_solution, DenseSolution};
use scirs2_integrate::ode::utils::interpolation::ContinuousOutputMethod;
use scirs2_integrate::ode::{solve_ivp, ODEMethod, ODEOptions};
use std::f64::consts::PI;
use std::io::Write;

/// This example demonstrates the continuous (dense) output capabilities
/// of the ODE solvers, which allow evaluating the solution at any point
/// within the integration interval.
/// Pendulum system: d²θ/dt² + (g/L)·sin(θ) = 0
///
/// We convert this to a system of first-order ODEs:
/// dθ/dt = ω
/// dω/dt = -(g/L)·sin(θ)
#[allow(dead_code)]
fn pendulum(t: f64, y: ArrayView1<f64>) -> Array1<f64> {
    // State variables:
    // y[0] = θ (angle from vertical, radians)
    // y[1] = ω (angular velocity)

    // Parameters
    let g_over_l = 1.0; // Gravity / Length

    // Equations of motion
    array![y[1], -g_over_l * y[0].sin()]
}

/// Two-body problem (planet orbiting a star)
///
/// We model this as a system of ODEs in Cartesian coordinates:
/// dx/dt = vx
/// dy/dt = vy
/// dvx/dt = -μ·x/r³
/// dvy/dt = -μ·y/r³
///
/// Where r = sqrt(x² + y²) is the distance from the origin
#[allow(dead_code)]
fn two_body(t: f64, y: ArrayView1<f64>) -> Array1<f64> {
    // State variables:
    // y[0] = x (position x)
    // y[1] = y (position y)
    // y[2] = vx (velocity x)
    // y[3] = vy (velocity y)

    // Parameter (gravitational constant * central mass)
    let mu = 1.0;

    // Distance from origin
    let r = (y[0] * y[0] + y[1] * y[1]).sqrt();

    // Avoid division by zero
    if r < 1e-10 {
        return array![y[2], y[3], 0.0, 0.0];
    }

    // Gravitational acceleration
    let r3 = r.powi(3);
    let ax = -mu * y[0] / r3;
    let ay = -mu * y[1] / r3;

    array![
        y[2], // dx/dt = vx
        y[3], // dy/dt = vy
        ax,   // dvx/dt = -μ·x/r³
        ay    // dvy/dt = -μ·y/r³
    ]
}

/// Van der Pol oscillator
///
/// This is a classic non-linear oscillator with limit cycle behavior:
/// d²x/dt² - μ·(1 - x²)·dx/dt + x = 0
///
/// We convert to first-order system:
/// dx/dt = y
/// dy/dt = μ·(1 - x²)·y - x
#[allow(dead_code)]
fn van_der_pol(t: f64, y: ArrayView1<f64>) -> Array1<f64> {
    // State variables:
    // y[0] = x (position)
    // y[1] = y (velocity)

    // Parameter (controls nonlinearity and stiffness)
    let mu = 2.0;

    array![y[1], mu * (1.0 - y[0].powi(2)) * y[1] - y[0]]
}

/// Writes a CSV file with the solution
#[allow(dead_code)]
fn write_solution_csv(
    filename: &str,
    solution: &DenseSolution<f64>,
    component_indices: &[usize],
    n_points: usize,
) -> IntegrateResult<()> {
    // Create a dense output
    let (times, values) = solution.dense_output(n_points)?;

    // Open file for writing
    let mut file = std::fs::File::create(filename)
        .map_err(|e| scirs2_integrate::error::IntegrateError::ComputationError(e.to_string()))?;

    // Write header
    let mut header = String::from("t");
    for &idx in component_indices {
        header.push_str(&format!(",y{idx}"));
    }
    writeln!(file, "{header}")
        .map_err(|e| scirs2_integrate::error::IntegrateError::ComputationError(e.to_string()))?;

    // Write data
    for (i, t) in times.iter().enumerate() {
        let mut line = format!("{t}");
        for &idx in component_indices {
            line.push_str(&format!(",{}", values[i][idx]));
        }
        writeln!(file, "{line}").map_err(|e| {
            scirs2_integrate::error::IntegrateError::ComputationError(e.to_string())
        })?;
    }

    println!("Wrote solution to {filename}");
    Ok(())
}

/// Pendulum simulation with continuous output
#[allow(dead_code)]
fn pendulum_simulation() -> IntegrateResult<()> {
    println!("\n=== Pendulum Simulation ===");

    // Initial state: θ=π/4, ω=0 (start from 45 degrees with no velocity)
    let y0 = array![PI / 4.0, 0.0];
    let t_span = [0.0, 20.0];

    // Use the RK45 method
    let options = ODEOptions {
        method: ODEMethod::RK45,
        rtol: 1e-6,
        atol: 1e-8,
        ..Default::default()
    };

    println!("Solving pendulum ODE...");
    let result = solve_ivp(pendulum, t_span, y0, Some(options))?;

    println!("Solution has {} points", result.t.len());
    println!("First few times: {:?}", &result.t[0..5.min(result.t.len())]);

    // Create a dense solution
    println!("Creating dense solution...");
    let dense_solution = create_dense_solution(
        result.t,
        result.y,
        pendulum,
        Some(ContinuousOutputMethod::CubicHermite),
    )?;

    // Demonstrate dense evaluation by computing energy at many points
    // Energy = T + V = (1/2)mL²ω² + mgL(1-cos(θ))
    // With m=1, L=1, g=1: E = (1/2)ω² + (1-cos(θ))
    let n_points = 1000;
    let (_times, values) = dense_solution.dense_output(n_points)?;

    println!("Computing energy conservation...");
    let mut energies = Vec::with_capacity(n_points);
    for value in values.iter().take(n_points) {
        let theta = value[0];
        let omega = value[1];
        let kinetic = 0.5 * omega.powi(2);
        let potential = 1.0 - theta.cos();
        let energy = kinetic + potential;
        energies.push(energy);
    }

    // Check energy conservation
    let mean_energy: f64 = energies.iter().sum::<f64>() / energies.len() as f64;
    let max_deviation = energies
        .iter()
        .fold(0.0_f64, |max, &e| max.max((e - mean_energy).abs()));

    println!("Energy analysis:");
    println!("  Mean energy: {mean_energy:.8}");
    println!("  Maximum deviation: {max_deviation:.8e}");
    println!("  Relative error: {:.8e}", max_deviation / mean_energy);

    // Write solution to CSV for visualization
    write_solution_csv("pendulum_solution.csv", &dense_solution, &[0, 1], 500)?;

    Ok(())
}

/// Two-body problem simulation (planet orbiting a star)
#[allow(dead_code)]
fn two_body_simulation() -> IntegrateResult<()> {
    println!("\n=== Two-Body Simulation ===");

    // Initial conditions for circular orbit: x=1, y=0, vx=0, vy=1
    let y0 = array![1.0, 0.0, 0.0, 1.0];
    let t_span = [0.0, 12.0]; // integrate for approx. 2 orbits

    // Use the DOP853 method for high accuracy
    let options = ODEOptions {
        method: ODEMethod::DOP853,
        rtol: 1e-10,
        atol: 1e-10,
        ..Default::default()
    };

    println!("Solving two-body ODE...");
    let result = solve_ivp(two_body, t_span, y0, Some(options))?;

    println!("Solution has {} points", result.t.len());

    // Create a dense solution
    println!("Creating dense solution...");
    let dense_solution = create_dense_solution(
        result.t,
        result.y,
        two_body,
        Some(ContinuousOutputMethod::CubicHermite),
    )?;

    // Demonstrate dense output by computing angular momentum at many points
    // L = r × p = x*vy - y*vx
    let n_points = 1000;
    let (_times, values) = dense_solution.dense_output(n_points)?;

    println!("Computing angular momentum conservation...");
    let mut angular_momenta = Vec::with_capacity(n_points);
    for value in values.iter().take(n_points) {
        let x = value[0];
        let y = value[1];
        let vx = value[2];
        let vy = value[3];

        let angular_momentum = x * vy - y * vx;
        angular_momenta.push(angular_momentum);
    }

    // Check angular momentum conservation
    let mean_l: f64 = angular_momenta.iter().sum::<f64>() / angular_momenta.len() as f64;
    let max_deviation = angular_momenta
        .iter()
        .fold(0.0_f64, |max, &l| max.max((l - mean_l).abs()));

    println!("Angular momentum analysis:");
    println!("  Mean angular momentum: {mean_l:.10}");
    println!("  Maximum deviation: {max_deviation:.10e}");
    println!("  Relative error: {:.10e}", max_deviation / mean_l);

    // Write solution to CSV for visualization
    write_solution_csv("two_body_solution.csv", &dense_solution, &[0, 1], 500)?;

    // Also write radius over time to verify circular orbit
    let (t_dense, values_dense) = dense_solution.dense_output(500)?;

    let mut file = std::fs::File::create("two_body_radius.csv")
        .map_err(|e| scirs2_integrate::error::IntegrateError::ComputationError(e.to_string()))?;

    writeln!(file, "t,radius").expect("Operation failed");
    for i in 0..t_dense.len() {
        let x = values_dense[i][0];
        let y = values_dense[i][1];
        let r = (x * x + y * y).sqrt();
        writeln!(file, "{},{}", t_dense[i], r).expect("Operation failed");
    }

    println!("Wrote radius data to two_body_radius.csv");

    Ok(())
}

/// Van der Pol oscillator simulation with continuous output
#[allow(dead_code)]
fn van_der_pol_simulation() -> IntegrateResult<()> {
    println!("\n=== Van der Pol Simulation ===");

    // Initial state: x=2, y=0
    let y0 = array![2.0, 0.0];
    let t_span = [0.0, 20.0];

    // Use the enhanced BDF method for stiff problems
    let options = ODEOptions {
        method: ODEMethod::EnhancedBDF,
        rtol: 1e-6,
        atol: 1e-8,
        ..Default::default()
    };

    println!("Solving Van der Pol ODE...");
    let result = solve_ivp(van_der_pol, t_span, y0, Some(options))?;

    println!(
        "Solution has {} points with {} steps",
        result.t.len(),
        result.n_steps
    );

    // Create a dense solution
    println!("Creating dense solution...");
    let _dense_solution = create_dense_solution(
        result.t.clone(),
        result.y.clone(),
        van_der_pol,
        Some(ContinuousOutputMethod::CubicHermite),
    )?;

    // Compare different interpolation methods
    println!("\nInterpolation Method Comparison at t=7.5:");
    let t_test = 7.5;

    // Find closest actual solution points
    let mut closest_i = 0;
    let mut min_dist = f64::MAX;
    for (i, &t) in result.t.iter().enumerate() {
        let dist = (t - t_test).abs();
        if dist < min_dist {
            min_dist = dist;
            closest_i = i;
        }
    }

    // Get closest times
    let t_before = if closest_i > 0 {
        result.t[closest_i - 1]
    } else {
        result.t[0]
    };
    let t_at = result.t[closest_i];
    let t_after = if closest_i < result.t.len() - 1 {
        result.t[closest_i + 1]
    } else {
        t_at
    };

    println!("Closest solution points: t = {t_before:.6}, {t_at:.6}, {t_after:.6}");

    // Create dense solutions with different interpolation methods
    let linear_solution = create_dense_solution(
        result.t.clone(),
        result.y.clone(),
        van_der_pol,
        Some(ContinuousOutputMethod::Linear),
    )?;

    let cubic_solution = create_dense_solution(
        result.t.clone(),
        result.y.clone(),
        van_der_pol,
        Some(ContinuousOutputMethod::CubicHermite),
    )?;

    // Evaluate at test point
    let linear_y = linear_solution.evaluate(t_test)?;
    let cubic_y = cubic_solution.evaluate(t_test)?;

    println!(
        "Linear interpolation:    x = {:.8}, y = {:.8}",
        linear_y[0], linear_y[1]
    );
    println!(
        "Cubic Hermite interp.:   x = {:.8}, y = {:.8}",
        cubic_y[0], cubic_y[1]
    );

    // Generate very high resolution "truth" solution to compare against
    let fine_options = ODEOptions {
        method: ODEMethod::EnhancedBDF,
        rtol: 1e-10,
        atol: 1e-12,
        max_steps: 10000,
        ..Default::default()
    };

    // Solve just around the test point
    let fine_result = solve_ivp(
        van_der_pol,
        [t_test - 0.1, t_test + 0.1],
        array![cubic_y[0], cubic_y[1]], // Start from our interpolated solution
        Some(fine_options),
    )?;

    // Find closest point to t_test in fine solution
    let mut reference_y = None;
    let mut min_dist = f64::MAX;
    for i in 0..fine_result.t.len() {
        let dist = (fine_result.t[i] - t_test).abs();
        if dist < min_dist {
            min_dist = dist;
            reference_y = Some(fine_result.y[i].clone());
        }
    }

    if let Some(ref_y) = reference_y {
        println!(
            "Reference solution:      x = {:.8}, y = {:.8}",
            ref_y[0], ref_y[1]
        );

        println!("\nInterpolation errors:");
        println!(
            "Linear: {:.2e} (x), {:.2e} (y)",
            (linear_y[0] - ref_y[0]).abs(),
            (linear_y[1] - ref_y[1]).abs()
        );
        println!(
            "Cubic:  {:.2e} (x), {:.2e} (y)",
            (cubic_y[0] - ref_y[0]).abs(),
            (cubic_y[1] - ref_y[1]).abs()
        );
    }

    // Write solution to CSV for visualization
    write_solution_csv("van_der_pol_solution.csv", &cubic_solution, &[0, 1], 1000)?;

    // Generate phase plane for Van der Pol
    println!("\nGenerating phase plane visualization...");
    let mut phase_file = std::fs::File::create("van_der_pol_phase.csv")
        .map_err(|e| scirs2_integrate::error::IntegrateError::ComputationError(e.to_string()))?;

    writeln!(phase_file, "x,y").expect("Operation failed");

    // Use dense output with many points
    let (_, values) = cubic_solution.dense_output(2000)?;
    for v in values {
        writeln!(phase_file, "{},{}", v[0], v[1]).expect("Operation failed");
    }

    println!("Wrote phase plane data to van_der_pol_phase.csv");

    Ok(())
}

#[allow(dead_code)]
fn main() -> IntegrateResult<()> {
    println!("Continuous Output Demonstrations");
    println!("================================");

    // Run all simulations
    pendulum_simulation()?;
    two_body_simulation()?;
    van_der_pol_simulation()?;

    println!("\nFinished all demonstrations.");
    println!("\nSummary of Continuous Output Benefits:");
    println!("1. Enables accurate solution evaluation at any point within the integration range");
    println!("2. Useful for visualization and post-processing of solutions");
    println!("3. Helps verify conservation properties of dynamical systems");
    println!("4. Allows comparison of different interpolation methods");
    println!("5. More efficient than re-solving with smaller step sizes");

    Ok(())
}