RustedSciThe 0.4.20

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
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
457
458
459
460
461
462
463
464
465
//! Acceptance tests for the production-facing prepared Lambdify lifecycle.
//!
//! These tests deliberately separate correctness contracts from performance
//! claims. The ignored story prints preparation, bind, solve, and callback
//! metrics; it must be run in release mode before using the numbers as
//! evidence. The ordinary tests are small regression gates and run normally.
//!
//! Debug correctness tests:
//! ```text
//! cargo test --lib numerical::Nonlinear_systems::nonlinear_lambdify_acceptance_tests -- --nocapture --test-threads=1
//! ```
//!
//! Release acceptance tests and story:
//! ```text
//! cargo test --release --lib numerical::Nonlinear_systems::nonlinear_lambdify_acceptance_tests -- --nocapture --test-threads=1
//! cargo test --release --lib numerical::Nonlinear_systems::nonlinear_lambdify_acceptance_tests -- --nocapture --ignored --test-threads=1
//! ```

#[cfg(test)]
mod tests {
    use super::super::engine::{DiagnosticsOptions, SolveOptions, StatisticsAvailability};
    use super::super::error::TerminationReason;
    use super::super::prelude::{DampedNewtonMethod, NonlinearSolverMethod};
    use super::super::problem::{JacobianProvider, NonlinearProblem};
    use super::super::symbolic::{
        LambdifyExecutionPolicy, PreparedSymbolicNonlinearProblem, SymbolicProblemOptions,
    };
    use nalgebra::{DMatrix, DVector};
    use std::time::Instant;

    fn equations() -> Vec<String> {
        vec!["a*x^2-4".to_string(), "y-x".to_string()]
    }

    fn options(policy: LambdifyExecutionPolicy) -> SymbolicProblemOptions {
        SymbolicProblemOptions::new()
            .with_variables(vec!["x".to_string(), "y".to_string()])
            .with_equation_parameters(vec!["a".to_string()])
            .with_lambdify_execution_policy(policy)
    }

    fn solve_options(collect_statistics: bool) -> SolveOptions {
        SolveOptions {
            tolerance: 1e-11,
            max_iterations: 50,
            diagnostics: DiagnosticsOptions {
                collect_history: false,
                collect_statistics,
                enable_logging: false,
                ..DiagnosticsOptions::default()
            },
            ..SolveOptions::default()
        }
    }

    fn expected_solution(a: f64) -> DVector<f64> {
        let x = 2.0 / a.sqrt();
        DVector::from_vec(vec![x, x])
    }

    fn solve_bound(
        problem: &super::super::symbolic::BoundSymbolicNonlinearProblem<'_>,
        initial: DVector<f64>,
        collect_statistics: bool,
    ) -> super::super::engine::SolveResult {
        NonlinearSolverMethod::DampedNewton(DampedNewtonMethod::default())
            .solve(problem, initial, solve_options(collect_statistics))
            .expect("prepared Lambdify solve should succeed")
    }

    #[test]
    fn prepared_lambdify_sequential_and_parallel_solver_contracts_match() {
        let sequential = PreparedSymbolicNonlinearProblem::from_strings(
            equations(),
            options(LambdifyExecutionPolicy::Sequential),
        )
        .expect("sequential preparation should succeed");
        let parallel = PreparedSymbolicNonlinearProblem::from_strings(
            equations(),
            options(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("parallel preparation should succeed");
        let sequential = sequential
            .bind_values(DVector::from_vec(vec![1.0]))
            .expect("sequential binding should succeed");
        let parallel = parallel
            .bind_values(DVector::from_vec(vec![1.0]))
            .expect("parallel binding should succeed");

        let sequential_result = solve_bound(&sequential, DVector::from_vec(vec![1.5, 1.5]), true);
        let parallel_result = solve_bound(&parallel, DVector::from_vec(vec![1.5, 1.5]), true);

        assert!(matches!(
            sequential_result.termination,
            TerminationReason::Converged
        ));
        assert!(matches!(
            parallel_result.termination,
            TerminationReason::Converged
        ));
        assert!((sequential_result.x - expected_solution(1.0)).norm() < 1e-9);
        assert!((parallel_result.x - expected_solution(1.0)).norm() < 1e-9);

        let sequential_stats = sequential_result.statistics;
        let parallel_stats = parallel_result.statistics;
        assert_eq!(
            sequential_stats.availability,
            StatisticsAvailability::Collected
        );
        assert_eq!(
            parallel_stats.availability,
            StatisticsAvailability::Collected
        );
        assert_eq!(
            (
                sequential_stats.iterations,
                sequential_stats.residual_evaluations,
                sequential_stats.jacobian_evaluations,
                sequential_stats.linear_solves,
                sequential_stats.accepted_steps,
                sequential_stats.rejected_steps,
            ),
            (
                parallel_stats.iterations,
                parallel_stats.residual_evaluations,
                parallel_stats.jacobian_evaluations,
                parallel_stats.linear_solves,
                parallel_stats.accepted_steps,
                parallel_stats.rejected_steps,
            ),
            "execution policy must not change solver-level work"
        );
    }

    #[test]
    fn prepared_lambdify_telemetry_off_is_explicit_and_solution_equivalent() {
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            equations(),
            options(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("preparation should succeed");
        let bound = prepared
            .bind_values(DVector::from_vec(vec![2.0]))
            .expect("binding should succeed");

        let measured = solve_bound(&bound, DVector::from_vec(vec![1.0, 1.0]), true);
        let unmeasured = solve_bound(&bound, DVector::from_vec(vec![1.0, 1.0]), false);

        assert!(matches!(measured.termination, TerminationReason::Converged));
        assert!(matches!(
            unmeasured.termination,
            TerminationReason::Converged
        ));
        assert!((measured.x.clone() - unmeasured.x).norm() < 1e-12);
        assert_eq!(
            measured.statistics.availability,
            StatisticsAvailability::Collected
        );
        assert_eq!(
            unmeasured.statistics.availability,
            StatisticsAvailability::NotCollected
        );
        assert_eq!(unmeasured.statistics.residual_evaluations, 0);
        assert_eq!(unmeasured.statistics.jacobian_evaluations, 0);
        assert_eq!(unmeasured.statistics.linear_solves, 0);
        assert_eq!(
            unmeasured.statistics.residual_duration,
            std::time::Duration::ZERO
        );
        assert_eq!(
            unmeasured.statistics.jacobian_duration,
            std::time::Duration::ZERO
        );
        assert_eq!(
            unmeasured.statistics.linear_solve_duration,
            std::time::Duration::ZERO
        );
        assert_eq!(
            unmeasured.statistics.total_duration,
            std::time::Duration::ZERO
        );
    }

    #[test]
    fn prepared_lambdify_many_parameters_preserves_order_and_sparse_layout() {
        const DIMENSION: usize = 96;
        let variables = (0..DIMENSION)
            .map(|index| format!("x{index}"))
            .collect::<Vec<_>>();
        let parameters = (0..DIMENSION)
            .map(|index| format!("p{index}"))
            .collect::<Vec<_>>();
        let equations = (0..DIMENSION)
            .map(|index| format!("p{index}*x{index}-p{index}"))
            .collect::<Vec<_>>();
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            equations,
            SymbolicProblemOptions::new()
                .with_variables(variables)
                .with_equation_parameters(parameters.clone())
                .with_lambdify_execution_policy(LambdifyExecutionPolicy::Parallel { min_work: 1 }),
        )
        .expect("many-parameter Lambdify preparation should succeed");

        let schema = prepared
            .parameter_schema()
            .expect("parameter schema should be present");
        assert_eq!(schema.names(), &parameters);

        let point = DVector::from_iterator(
            DIMENSION,
            (0..DIMENSION).map(|index| 0.25 + index as f64 * 0.001),
        );
        let first_values = DVector::from_iterator(
            DIMENSION,
            (0..DIMENSION).map(|index| 1.0 + index as f64 * 0.01),
        );
        let second_values = DVector::from_iterator(
            DIMENSION,
            (0..DIMENSION).map(|index| 2.0 + index as f64 * 0.02),
        );
        let first = prepared
            .bind_values(first_values.clone())
            .expect("first many-parameter binding should succeed");
        let second = prepared
            .bind_values(second_values.clone())
            .expect("second many-parameter binding should succeed");

        let mut residual = DVector::zeros(DIMENSION);
        let mut jacobian = DMatrix::zeros(DIMENSION, DIMENSION);
        first
            .residual_into(&point, &mut residual)
            .expect("first many-parameter residual should succeed");
        first
            .jacobian_into(&point, &mut jacobian)
            .expect("first many-parameter Jacobian should succeed");
        for index in 0..DIMENSION {
            assert!(
                (residual[index] - first_values[index] * (point[index] - 1.0)).abs() < 1e-13,
                "first residual mismatch at index {index}"
            );
            for column in 0..DIMENSION {
                let expected = if index == column {
                    first_values[index]
                } else {
                    0.0
                };
                assert_eq!(jacobian[(index, column)], expected);
            }
        }

        second
            .residual_into(&point, &mut residual)
            .expect("second many-parameter residual should succeed");
        second
            .jacobian_into(&point, &mut jacobian)
            .expect("second many-parameter Jacobian should succeed");
        for index in 0..DIMENSION {
            assert!(
                (residual[index] - second_values[index] * (point[index] - 1.0)).abs() < 1e-13,
                "second residual mismatch at index {index}"
            );
            assert_eq!(jacobian[(index, index)], second_values[index]);
        }
    }

    #[test]
    #[ignore = "release-oriented high-cardinality Lambdify callback story"]
    fn high_cardinality_parameter_callback_story() {
        let runs = std::env::var("NONLINEAR_LAMBDIFY_PARAMETER_RUNS")
            .ok()
            .and_then(|value| value.parse::<usize>().ok())
            .filter(|runs| *runs >= 3)
            .unwrap_or(5);

        fn summarize(values: &[f64]) -> String {
            let mean = values.iter().sum::<f64>() / values.len() as f64;
            let variance = values
                .iter()
                .map(|value| (value - mean).powi(2))
                .sum::<f64>()
                / values.len() as f64;
            let min = values.iter().copied().fold(f64::INFINITY, f64::min);
            let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            format!("{mean:.3}+/-{:.3}[{min:.3},{max:.3}]", variance.sqrt())
        }

        println!(
            "[Nonlinear Lambdify parameter hot path] runs={runs}; times are microseconds mean+/-std[min,max]"
        );
        println!(
            "parameter_count | seq_residual_us | seq_jacobian_us | parallel_residual_us | parallel_jacobian_us"
        );

        for dimension in [8, 64, 256] {
            let variables = (0..dimension)
                .map(|index| format!("x{index}"))
                .collect::<Vec<_>>();
            let parameters = (0..dimension)
                .map(|index| format!("p{index}"))
                .collect::<Vec<_>>();
            let equations = (0..dimension)
                .map(|index| format!("p{index}*x{index}-p{index}"))
                .collect::<Vec<_>>();
            let prepare = |policy| {
                PreparedSymbolicNonlinearProblem::from_strings(
                    equations.clone(),
                    SymbolicProblemOptions::new()
                        .with_variables(variables.clone())
                        .with_equation_parameters(parameters.clone())
                        .with_lambdify_execution_policy(policy),
                )
                .expect("parameter hot-path preparation should succeed")
            };
            let prepared_sequential = prepare(LambdifyExecutionPolicy::Sequential);
            let sequential = prepared_sequential
                .bind_values(DVector::from_iterator(
                    dimension,
                    (0..dimension).map(|index| 1.0 + index as f64 * 0.01),
                ))
                .expect("sequential hot-path binding should succeed");
            let prepared_parallel = prepare(LambdifyExecutionPolicy::Parallel { min_work: 1 });
            let parallel = prepared_parallel
                .bind_values(DVector::from_iterator(
                    dimension,
                    (0..dimension).map(|index| 1.0 + index as f64 * 0.01),
                ))
                .expect("parallel hot-path binding should succeed");
            let point = DVector::from_iterator(
                dimension,
                (0..dimension).map(|index| 0.25 + index as f64 * 0.001),
            );
            let mut sequential_residual = DVector::zeros(dimension);
            let mut sequential_jacobian = DMatrix::zeros(dimension, dimension);
            let mut parallel_residual = DVector::zeros(dimension);
            let mut parallel_jacobian = DMatrix::zeros(dimension, dimension);

            sequential
                .residual_into(&point, &mut sequential_residual)
                .expect("sequential warm residual should succeed");
            sequential
                .jacobian_into(&point, &mut sequential_jacobian)
                .expect("sequential warm Jacobian should succeed");
            parallel
                .residual_into(&point, &mut parallel_residual)
                .expect("parallel warm residual should succeed");
            parallel
                .jacobian_into(&point, &mut parallel_jacobian)
                .expect("parallel warm Jacobian should succeed");
            assert_eq!(sequential_residual, parallel_residual);
            assert_eq!(sequential_jacobian, parallel_jacobian);

            let mut seq_residual_us = Vec::with_capacity(runs);
            let mut seq_jacobian_us = Vec::with_capacity(runs);
            let mut parallel_residual_us = Vec::with_capacity(runs);
            let mut parallel_jacobian_us = Vec::with_capacity(runs);
            for _ in 0..runs {
                let started = Instant::now();
                sequential
                    .residual_into(&point, &mut sequential_residual)
                    .expect("sequential residual should succeed");
                seq_residual_us.push(started.elapsed().as_secs_f64() * 1e6);

                let started = Instant::now();
                sequential
                    .jacobian_into(&point, &mut sequential_jacobian)
                    .expect("sequential Jacobian should succeed");
                seq_jacobian_us.push(started.elapsed().as_secs_f64() * 1e6);

                let started = Instant::now();
                parallel
                    .residual_into(&point, &mut parallel_residual)
                    .expect("parallel residual should succeed");
                parallel_residual_us.push(started.elapsed().as_secs_f64() * 1e6);

                let started = Instant::now();
                parallel
                    .jacobian_into(&point, &mut parallel_jacobian)
                    .expect("parallel Jacobian should succeed");
                parallel_jacobian_us.push(started.elapsed().as_secs_f64() * 1e6);
            }
            assert_eq!(sequential_residual, parallel_residual);
            assert_eq!(sequential_jacobian, parallel_jacobian);
            println!(
                "{:>15} | {:<16} | {:<16} | {:<21} | {}",
                dimension,
                summarize(&seq_residual_us),
                summarize(&seq_jacobian_us),
                summarize(&parallel_residual_us),
                summarize(&parallel_jacobian_us),
            );
        }
    }

    #[test]
    #[ignore = "release-oriented prepared-vs-rebuild Lambdify lifecycle story"]
    fn prepared_lambdify_reuse_vs_rebuild_parameter_story() {
        const PARAMETER_VALUES: [f64; 5] = [0.5, 0.75, 1.0, 1.5, 2.0];
        let prepared = PreparedSymbolicNonlinearProblem::from_strings(
            equations(),
            options(LambdifyExecutionPolicy::Sequential),
        )
        .expect("prepared Lambdify problem should succeed");

        let mut reuse_prepare_ms = Vec::new();
        let mut reuse_solve_ms = Vec::new();
        let mut rebuild_prepare_ms = Vec::new();
        let mut rebuild_solve_ms = Vec::new();
        let mut reuse_errors = Vec::new();
        let mut rebuild_errors = Vec::new();

        for a in PARAMETER_VALUES {
            let bind_started = Instant::now();
            let bound = prepared
                .bind_values(DVector::from_vec(vec![a]))
                .expect("reuse binding should succeed");
            reuse_prepare_ms.push(bind_started.elapsed().as_secs_f64() * 1e3);
            let solve_started = Instant::now();
            let reused = solve_bound(&bound, DVector::from_vec(vec![1.0, 1.0]), true);
            reuse_solve_ms.push(solve_started.elapsed().as_secs_f64() * 1e3);
            reuse_errors.push((reused.x - expected_solution(a)).norm());

            let rebuild_started = Instant::now();
            let rebuilt = PreparedSymbolicNonlinearProblem::from_strings(
                equations(),
                options(LambdifyExecutionPolicy::Sequential),
            )
            .expect("rebuild preparation should succeed");
            let rebuilt = rebuilt
                .bind_values(DVector::from_vec(vec![a]))
                .expect("rebuild binding should succeed");
            rebuild_prepare_ms.push(rebuild_started.elapsed().as_secs_f64() * 1e3);
            let solve_started = Instant::now();
            let rebuilt_result = solve_bound(&rebuilt, DVector::from_vec(vec![1.0, 1.0]), true);
            rebuild_solve_ms.push(solve_started.elapsed().as_secs_f64() * 1e3);
            rebuild_errors.push((rebuilt_result.x - expected_solution(a)).norm());
        }

        assert!(reuse_errors.iter().all(|error| *error < 1e-9));
        assert!(rebuild_errors.iter().all(|error| *error < 1e-9));
        assert!(reuse_prepare_ms.iter().all(|value| value.is_finite()));
        assert!(rebuild_prepare_ms.iter().all(|value| value.is_finite()));

        fn mean(values: &[f64]) -> f64 {
            values.iter().sum::<f64>() / values.len() as f64
        }

        println!(
            "[Nonlinear Lambdify lifecycle] parameter_values={PARAMETER_VALUES:?}; prepared object is reused for every bind"
        );
        println!("path | prepare_or_bind_ms_mean | solve_ms_mean | max_solution_error");
        println!(
            "prepared-reuse | {:.3} | {:.3} | {:.3e}",
            mean(&reuse_prepare_ms),
            mean(&reuse_solve_ms),
            reuse_errors.iter().copied().fold(0.0, f64::max),
        );
        println!(
            "rebuild-each-time | {:.3} | {:.3} | {:.3e}",
            mean(&rebuild_prepare_ms),
            mean(&rebuild_solve_ms),
            rebuild_errors.iter().copied().fold(0.0, f64::max),
        );
    }
}