RustedSciThe 0.4.19

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
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
//! End-to-end AOT parameter-rebind and repeated-warm-solve gates.

use super::aot_trajectory_parity_story_tests::trajectory_config;
use super::solver::Lsode2EvaluationTelemetry;
use super::{
    IvpColdStage, IvpTelemetry, Lsode2AotProfile, Lsode2AotToolchain, Lsode2LinearSystemStructure,
    Lsode2Solver, Lsode2SymbolicAssemblyBackend, Lsode2SymbolicExecutionMode,
};
use crate::symbolic::codegen::rust_backend::codegen_aot_build::AotBuildProfile;
use crate::symbolic::symbolic_ivp_generated::{
    SymbolicIvpAotBuildPolicy, SymbolicIvpGeneratedBackendConfig,
};
use nalgebra::{DMatrix, DVector};
use std::time::Instant;
use tempfile::tempdir;

macro_rules! reportln {
    ($($arg:tt)*) => {
        crate::Utils::test_reporting::capture_test_line(format_args!($($arg)*));
    };
}

fn generated_config(
    output_parent: &std::path::Path,
    policy: SymbolicIvpAotBuildPolicy,
) -> SymbolicIvpGeneratedBackendConfig {
    SymbolicIvpGeneratedBackendConfig::defaults()
        .with_build_policy(policy)
        .with_output_parent_dir(Some(output_parent.to_path_buf()))
        .with_c_tcc()
}

fn parameterized_config(
    structure: Lsode2LinearSystemStructure,
    assembly: Lsode2SymbolicAssemblyBackend,
    execution: Lsode2SymbolicExecutionMode,
    generated: Option<SymbolicIvpGeneratedBackendConfig>,
    telemetry: IvpTelemetry,
    parameter: f64,
) -> super::Lsode2ProblemConfig {
    trajectory_config(structure, assembly, execution, generated, telemetry)
        .with_equation_parameter_values(DVector::from_vec(vec![parameter]))
}

fn max_matrix_diff(left: &DMatrix<f64>, right: &DMatrix<f64>) -> f64 {
    left.iter()
        .zip(right.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0, f64::max)
}

fn telemetry_delta(
    after: Lsode2EvaluationTelemetry,
    before: Lsode2EvaluationTelemetry,
) -> Lsode2EvaluationTelemetry {
    Lsode2EvaluationTelemetry {
        scope: after.scope,
        residual_evaluations: after
            .residual_evaluations
            .saturating_sub(before.residual_evaluations),
        jacobian_evaluations: after
            .jacobian_evaluations
            .saturating_sub(before.jacobian_evaluations),
        linear_solves: after.linear_solves.saturating_sub(before.linear_solves),
        residual_ms_total: (after.residual_ms_total - before.residual_ms_total).max(0.0),
        jacobian_ms_total: (after.jacobian_ms_total - before.jacobian_ms_total).max(0.0),
        linear_ms_total: (after.linear_ms_total - before.linear_ms_total).max(0.0),
        accepted_steps: after.accepted_steps.saturating_sub(before.accepted_steps),
        rejected_steps: after.rejected_steps.saturating_sub(before.rejected_steps),
    }
}

fn cold_stage_delta(
    after: &super::IvpTelemetrySnapshot,
    before: &super::IvpTelemetrySnapshot,
    stage: IvpColdStage,
) -> u64 {
    after
        .cold_stage(stage)
        .calls
        .saturating_sub(before.cold_stage(stage).calls)
}

#[test]
fn aot_parameter_rebind_and_repeated_warm_solve_reject_stale_runtime() {
    let _report = crate::Utils::test_reporting::TestReportCapture::new(
        "LSODE2_AOT",
        "numerical::LSODE2::aot_warm_rebind_story_tests::aot_parameter_rebind_and_repeated_warm_solve_reject_stale_runtime",
    );
    let output_parent = tempdir().expect("AOT output directory should exist");

    reportln!(
        "[LSODE2 AOT warm rebind] initial=BuildIfMissing(Debug); rebound=parameter 3.0; fresh=RequirePrebuilt; stale callback/factor gate"
    );
    reportln!(
        "matrix | route | rebound_vs_fresh_max_state_diff | rebound_vs_fresh_max_time_diff | rebound_counters | fresh_counters | status"
    );

    for (matrix, structure) in [
        ("Sparse", Lsode2LinearSystemStructure::Sparse),
        (
            "Banded",
            Lsode2LinearSystemStructure::Banded { kl: 0, ku: 0 },
        ),
    ] {
        let routes = [
            (
                "ExprLegacy-AOT",
                Lsode2SymbolicAssemblyBackend::ExprLegacy,
                Lsode2SymbolicExecutionMode::Aot {
                    toolchain: Lsode2AotToolchain::CTcc,
                    profile: Lsode2AotProfile::Debug,
                },
                true,
            ),
            (
                "AtomViewNative-AOT",
                Lsode2SymbolicAssemblyBackend::AtomView,
                Lsode2SymbolicExecutionMode::Aot {
                    toolchain: Lsode2AotToolchain::CTcc,
                    profile: Lsode2AotProfile::Debug,
                },
                true,
            ),
            (
                "AtomViewNative-Lambdify",
                Lsode2SymbolicAssemblyBackend::AtomView,
                Lsode2SymbolicExecutionMode::LambdifyExpr,
                false,
            ),
        ];

        for (route, assembly, execution, is_aot) in routes {
            let telemetry = IvpTelemetry::detailed();
            let initial_generated = is_aot.then(|| {
                generated_config(
                    output_parent.path(),
                    SymbolicIvpAotBuildPolicy::BuildIfMissing {
                        profile: AotBuildProfile::Debug,
                    },
                )
            });
            let mut rebound_solver = Lsode2Solver::new(parameterized_config(
                structure,
                assembly,
                execution,
                initial_generated,
                telemetry.clone(),
                2.0,
            ))
            .expect("initial prepared solver should construct");
            let initial_summary = rebound_solver
                .solve_with_summary()
                .expect("initial parameter solve should succeed");
            assert!(
                rebound_solver
                    .set_parameter_values(DVector::from_vec(vec![3.0, 4.0]))
                    .is_err(),
                "{matrix}/{route} invalid rebind must be rejected"
            );
            rebound_solver
                .set_parameter_values(DVector::from_vec(vec![3.0]))
                .expect("numeric parameter rebind should succeed");
            let rebound_summary = rebound_solver
                .solve_with_summary()
                .expect("rebound warm solve should succeed");
            let (rebound_times, rebound_values) = rebound_solver.get_result();

            let fresh_generated = is_aot.then(|| {
                generated_config(
                    output_parent.path(),
                    SymbolicIvpAotBuildPolicy::RequirePrebuilt,
                )
            });
            let fresh_telemetry = IvpTelemetry::detailed();
            let mut fresh_solver = Lsode2Solver::new(parameterized_config(
                structure,
                assembly,
                execution,
                fresh_generated,
                fresh_telemetry.clone(),
                3.0,
            ))
            .expect("fresh parameterized solver should construct");
            let fresh_summary = fresh_solver
                .solve_with_summary()
                .expect("fresh parameter solve should succeed");
            let (fresh_times, fresh_values) = fresh_solver.get_result();

            let max_time_diff = rebound_times
                .iter()
                .zip(fresh_times.iter())
                .map(|(left, right)| (left - right).abs())
                .fold(0.0, f64::max);
            let max_state_diff = max_matrix_diff(&rebound_values, &fresh_values);
            let rebound_counters = telemetry_delta(
                rebound_summary.evaluation_telemetry,
                initial_summary.evaluation_telemetry,
            );
            let fresh_counters = fresh_summary.evaluation_telemetry;
            reportln!(
                "{matrix} | {route} | {max_state_diff:.3e} | {max_time_diff:.3e} | {}/{}/{} | {}/{}/{} | ok",
                rebound_counters.residual_evaluations,
                rebound_counters.jacobian_evaluations,
                rebound_counters.linear_solves,
                fresh_counters.residual_evaluations,
                fresh_counters.jacobian_evaluations,
                fresh_counters.linear_solves,
            );

            assert!(
                max_state_diff <= 1.0e-9,
                "{matrix}/{route} stale state drift"
            );
            assert!(
                max_time_diff <= 1.0e-12,
                "{matrix}/{route} stale time trajectory"
            );
            assert_eq!(
                rebound_counters.scope, fresh_counters.scope,
                "{matrix}/{route} rebind/fresh telemetry scope"
            );
            assert_eq!(
                (
                    rebound_counters.residual_evaluations,
                    rebound_counters.jacobian_evaluations,
                    rebound_counters.linear_solves,
                    rebound_counters.accepted_steps,
                    rebound_counters.rejected_steps,
                ),
                (
                    fresh_counters.residual_evaluations,
                    fresh_counters.jacobian_evaluations,
                    fresh_counters.linear_solves,
                    fresh_counters.accepted_steps,
                    fresh_counters.rejected_steps,
                ),
                "{matrix}/{route} rebind/fresh integer trajectory counters"
            );
            assert_eq!(
                rebound_summary.algorithm, fresh_summary.algorithm,
                "{matrix}/{route} rebind/fresh algorithm trajectory"
            );

            // A linked runtime may be shared through the process registry.
            // Dropping one prepared owner must not invalidate another live solver.
            drop(rebound_solver);
            let before_survivor_rebind = fresh_telemetry.snapshot();
            fresh_solver
                .set_parameter_values(DVector::from_vec(vec![2.5]))
                .expect("surviving solver parameter rebind should succeed");
            let survivor_summary = fresh_solver
                .solve_with_summary()
                .expect("surviving solver should remain executable after peer drop");
            let after_survivor_rebind = fresh_telemetry.snapshot();
            let survivor_finite = survivor_summary
                .final_y
                .as_ref()
                .is_some_and(|state| state.iter().all(|value| value.is_finite()));
            let build_delta = after_survivor_rebind
                .aot_build_attempts
                .saturating_sub(before_survivor_rebind.aot_build_attempts);
            let link_delta = after_survivor_rebind
                .aot_link_attempts
                .saturating_sub(before_survivor_rebind.aot_link_attempts);
            reportln!(
                "[LSODE2 live-runtime lifecycle] matrix={matrix} route={route} peer_dropped=true survivor_finite={survivor_finite} build_delta={build_delta} link_delta={link_delta} artifact_keys_stable={}",
                before_survivor_rebind.aot_artifact_keys == after_survivor_rebind.aot_artifact_keys
            );
            assert!(
                survivor_finite,
                "{matrix}/{route} survivor state must be finite"
            );
            assert_eq!(build_delta, 0, "{matrix}/{route} survivor must not rebuild");
            assert_eq!(link_delta, 0, "{matrix}/{route} survivor must not relink");
            assert_eq!(
                before_survivor_rebind.aot_artifact_keys, after_survivor_rebind.aot_artifact_keys,
                "{matrix}/{route} numeric rebind must preserve artifact provenance"
            );
            assert_eq!(
                before_survivor_rebind.errors, after_survivor_rebind.errors,
                "{matrix}/{route} survivor lifecycle must not record errors"
            );
        }
    }
}

#[test]
fn aot_parameter_continuation_fair_warm_performance_and_cache_matrix() {
    let _report = crate::Utils::test_reporting::TestReportCapture::new(
        "LSODE2_AOT",
        "numerical::LSODE2::aot_warm_rebind_story_tests::aot_parameter_continuation_fair_warm_performance_and_cache_matrix",
    );
    let output_parent = tempdir().expect("AOT output directory should exist");
    let targets = [1.5, 2.0, 2.5];

    reportln!(
        "[LSODE2 AOT continuation fair performance] BuildIfMissing once; identical detailed telemetry; numeric rebind must not rebuild"
    );
    reportln!(
        "matrix | route | targets | continuation_ms | fresh_prepare_ms | fresh_solve_ms | fresh_total_ms | continuation_builds | continuation_links | continuation_materialization | fresh_builds | status"
    );

    for (matrix, structure) in [
        ("Sparse", Lsode2LinearSystemStructure::Sparse),
        (
            "Banded",
            Lsode2LinearSystemStructure::Banded { kl: 0, ku: 0 },
        ),
    ] {
        for (route, assembly, execution, is_aot) in [
            (
                "ExprLegacy-AOT",
                Lsode2SymbolicAssemblyBackend::ExprLegacy,
                Lsode2SymbolicExecutionMode::Aot {
                    toolchain: Lsode2AotToolchain::CTcc,
                    profile: Lsode2AotProfile::Debug,
                },
                true,
            ),
            (
                "AtomViewNative-AOT",
                Lsode2SymbolicAssemblyBackend::AtomView,
                Lsode2SymbolicExecutionMode::Aot {
                    toolchain: Lsode2AotToolchain::CTcc,
                    profile: Lsode2AotProfile::Debug,
                },
                true,
            ),
            (
                "AtomViewNative-Lambdify",
                Lsode2SymbolicAssemblyBackend::AtomView,
                Lsode2SymbolicExecutionMode::LambdifyExpr,
                false,
            ),
        ] {
            let continuation_telemetry = IvpTelemetry::detailed();
            let mut continuation = Lsode2Solver::new(parameterized_config(
                structure,
                assembly,
                execution,
                is_aot.then(|| {
                    generated_config(
                        output_parent.path(),
                        SymbolicIvpAotBuildPolicy::BuildIfMissing {
                            profile: AotBuildProfile::Debug,
                        },
                    )
                }),
                continuation_telemetry.clone(),
                1.0,
            ))
            .expect("continuation solver should construct");
            continuation
                .solve_with_summary()
                .expect("initial continuation solve should succeed");
            let before = continuation_telemetry.snapshot();
            let continuation_started = Instant::now();
            for parameter in targets {
                continuation
                    .set_parameter_values(DVector::from_vec(vec![parameter]))
                    .expect("AOT numeric rebind should succeed");
                continuation
                    .solve_with_summary()
                    .expect("continued AOT solve should succeed");
            }
            let continuation_ms = continuation_started.elapsed().as_secs_f64() * 1.0e3;
            let after = continuation_telemetry.snapshot();

            let fresh_telemetry = IvpTelemetry::detailed();
            let mut fresh_prepare_ms = 0.0;
            let mut fresh_solve_ms = 0.0;
            for parameter in targets {
                let prepare_started = Instant::now();
                let mut fresh = Lsode2Solver::new(parameterized_config(
                    structure,
                    assembly,
                    execution,
                    is_aot.then(|| {
                        generated_config(
                            output_parent.path(),
                            SymbolicIvpAotBuildPolicy::RequirePrebuilt,
                        )
                    }),
                    fresh_telemetry.clone(),
                    parameter,
                ))
                .expect("fresh continuation solver should construct");
                fresh_prepare_ms += prepare_started.elapsed().as_secs_f64() * 1.0e3;

                let solve_started = Instant::now();
                fresh
                    .solve_with_summary()
                    .expect("fresh continuation solve should succeed");
                fresh_solve_ms += solve_started.elapsed().as_secs_f64() * 1.0e3;
            }
            let fresh_snapshot = fresh_telemetry.snapshot();
            let continuation_builds = cold_stage_delta(&after, &before, IvpColdStage::AotBuild);
            let continuation_links = cold_stage_delta(&after, &before, IvpColdStage::AotLink);
            let continuation_materialization =
                cold_stage_delta(&after, &before, IvpColdStage::AotMaterialization);
            let fresh_builds = fresh_snapshot.cold_stage(IvpColdStage::AotBuild).calls;
            let fresh_total_ms = fresh_prepare_ms + fresh_solve_ms;

            reportln!(
                "{matrix} | {route} | {} | {continuation_ms:.3} | {fresh_prepare_ms:.3} | {fresh_solve_ms:.3} | {fresh_total_ms:.3} | {continuation_builds} | {continuation_links} | {continuation_materialization} | {fresh_builds} | ok",
                targets.len(),
            );
            assert_eq!(
                continuation_builds, 0,
                "{matrix}/{route} continuation build"
            );
            assert_eq!(continuation_links, 0, "{matrix}/{route} continuation link");
            assert_eq!(
                continuation_materialization, 0,
                "{matrix}/{route} continuation materialization"
            );
            assert_eq!(fresh_builds, 0, "{matrix}/{route} RequirePrebuilt build");
            assert_eq!(
                after.errors, before.errors,
                "{matrix}/{route} continuation errors"
            );
        }
    }
}