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
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
use super::*;
use std::fs;
use tempfile::tempdir;

fn parse_document_for_ivp(input: &str) -> DocumentMap {
    let mut parser = DocumentParser::new(input.to_string());
    let pseudonyms = default_ivp_pseudonyms();
    parser.with_pseudonims(Some(pseudonyms.0), Some(pseudonyms.1));
    parser.parse_document().expect("IVP document should parse");
    parser.keys_to_lower_case(Some(vec![
        "equations".to_string(),
        "parameters".to_string(),
        "where".to_string(),
        "substitute".to_string(),
    ]));
    parser
        .get_result()
        .expect("IVP document map should exist")
        .clone()
}

#[test]
fn ivp_task_parser_supports_file_roundtrip() {
    let dir = tempdir().expect("temp dir should be created");
    let path = dir.path().join("ivp_task.txt");
    fs::write(
        &path,
        r#"
task
solver: IVP
method: RK45

equations
arg: t
unknowns: y
rhs: -y

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0

solver_options
step_size: 1e-3
        "#,
    )
    .expect("test task file should be written");

    let spec = parse_ivp_task_from_file(Some(path)).expect("IVP file task should parse");
    assert_eq!(
        spec.solver.method,
        IvpMethodSpec::NonStiff("RK45".to_string())
    );
    assert_eq!(spec.equations.unknowns, vec!["y".to_string()]);
    assert_eq!(spec.initial_conditions.y0, vec![1.0]);
}

#[test]
fn ivp_task_parser_supports_pair_style_equations() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
parameters: a
parameter_values: 2.0
y: -a*y

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0

solver_options
step_size: 1e-3
"#;

    let spec = parse_ivp_task_from_str(input).expect("pair-style IVP task should parse");
    assert_eq!(spec.equations.unknowns, vec!["y".to_string()]);
    assert_eq!(spec.equations.parameter_values["a"], 2.0);
    assert_eq!(spec.initial_conditions.y0, vec![1.0]);
    assert_eq!(
        spec.solver.method,
        IvpMethodSpec::NonStiff("RK45".to_string())
    );
}

#[test]
fn ivp_task_parser_preserves_readable_parameter_section_symbol_case() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
unknowns: T
rhs: -R*T

parameters
R: 2.0

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0
"#;

    let spec = parse_ivp_task_from_str(input)
        .expect("IVP task with a readable parameter section should parse");

    assert_eq!(spec.equations.parameter_names, vec!["R"]);
    assert_eq!(spec.equations.parameter_values["R"], 2.0);
    let rhs = spec.equations.rhs[0].lambdify_borrowed_thread_safe(&["t", "T"]);
    assert!((rhs(&[0.0, 3.0]) + 6.0).abs() < 1e-12);
}

#[test]
fn ivp_task_parser_supports_where_symbolic_substitutions() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
y: heat - y

where
arr: 2.0*t
heat: arr + 1.0

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
step_size: 1e-3
"#;

    let spec = parse_ivp_task_from_str(input).expect("IVP with where substitutions should parse");
    let expr = spec.equations.rhs[0].clone();
    let f = expr.lambdify_borrowed_thread_safe(&["t", "y"]);
    let value = f(&[0.5, 1.0]);
    assert!((value - 1.0).abs() < 1e-12);
}

#[test]
fn ivp_task_parser_resolves_multilevel_where_with_numeric_parameters() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
parameters: gain
parameter_values: 3.0
y: source - y

where
base: gain * t
shifted: base + 1.0
source: 2.0 * shifted

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0

solver_options
step_size: 1e-3
"#;

    let spec = parse_ivp_task_from_str(input)
        .expect("IVP parser should resolve a multilevel symbolic definition chain");
    let rhs = spec.equations.rhs[0].lambdify_borrowed_thread_safe(&["t", "y"]);

    // source = 2 * (gain * t + 1), so source - y = 4 at t=0.5, y=1.
    assert!((rhs(&[0.5, 1.0]) - 4.0).abs() < 1e-12);
}

#[test]
fn ivp_task_parser_reports_bad_where_expression() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
y: heat - y

where
heat: sin(

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
step_size: 1e-3
"#;

    let err = parse_ivp_task_from_str(input)
        .expect_err("bad where expression should be reported as an IVP parser error");
    let message = err.to_string();
    assert!(message.contains("where/substitute"));
    assert!(message.contains("failed to parse symbolic expression"));
}

#[test]
fn ivp_task_runner_solves_simple_decay() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
unknowns: y
rhs: -y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
step_size: 1e-3
"#;

    let result = run_ivp_task_from_str(input).expect("simple IVP task should solve");
    assert_eq!(result.status.as_deref(), Some("finished"));
    let y = result.y_result.expect("solver should produce y_result");
    let final_y = y[(y.nrows() - 1, 0)];
    let expected = (-0.2_f64).exp();
    assert!((final_y - expected).abs() < 1e-2);
}

#[test]
fn ivp_task_runner_can_save_csv() {
    let dir = tempdir().expect("tempdir should be created");
    let csv_path = dir.path().join("ivp_task_output.csv");
    let input = format!(
        r#"
task
solver: IVP
method: RK45

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.05
y0: 1.0

solver_options
step_size: 1e-3

postprocessing
save_csv: true
csv_path: {}
"#,
        csv_path.display()
    );

    let result = run_ivp_task_from_str(&input).expect("IVP task should solve and save CSV");
    assert_eq!(result.status.as_deref(), Some("finished"));
    let contents =
        std::fs::read_to_string(&csv_path).expect("CSV file should be readable after solve");
    assert!(contents.contains("t,y"));
}

#[test]
fn ivp_task_runner_can_execute_modern_postprocessing_plan() {
    let dir = tempdir().expect("tempdir should be created");
    let txt_path = dir.path().join("ivp_task_output.txt");
    let report_path = dir.path().join("ivp_task_report.md");
    let input = format!(
        r#"
task
solver: IVP
method: RK45

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.05
y0: 1.0

solver_options
step_size: 1e-3

postprocessing
save_txt: true
txt_path: {}
write_report: true
report_path: {}
"#,
        txt_path.display(),
        report_path.display()
    );

    let result = run_ivp_task_from_str(&input).expect("IVP task should solve and postprocess");
    assert_eq!(result.status.as_deref(), Some("finished"));
    assert!(txt_path.exists());
    let report = std::fs::read_to_string(&report_path)
        .expect("report should be readable after postprocessing");
    assert!(report.contains("Solver Result Report"));
    assert!(report.contains("axis: t"));
}

#[test]
fn ivp_task_runner_supports_backward_euler() {
    let input = r#"
task
solver: IVP
method: BackwardEuler

equations
arg: t
y: -10.0*y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
step_size: 1e-3
tolerance: 1e-8
max_iterations: 100
"#;

    let result = run_ivp_task_from_str(input).expect("Backward Euler IVP task should solve");
    assert_eq!(result.status.as_deref(), Some("finished"));
    assert!(result.y_result.is_some());
}

#[test]
fn ivp_task_runner_supports_bdf() {
    let input = r#"
task
solver: IVP
method: BDF

equations
arg: t
y: -20.0*y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
first_step: Some(1e-3)
rtol: 1e-6
atol: 1e-8
max_step: 0.05
"#;

    let result = run_ivp_task_from_str(input).expect("BDF IVP task should solve");
    assert_eq!(result.status.as_deref(), Some("finished"));
    assert!(result.y_result.is_some());
}

#[test]
fn ivp_task_runner_supports_radau5() {
    let input = r#"
task
solver: IVP
method: Radau5

equations
arg: t
y: -15.0*y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
first_step: Some(1e-3)
rtol: 1e-6
atol: 1e-8
max_step: 0.05
"#;

    let result = run_ivp_task_from_str(input).expect("Radau5 IVP task should solve");
    assert_eq!(result.status.as_deref(), Some("finished"));
    assert!(result.y_result.is_some());
}

#[test]
fn ivp_task_parser_supports_lsode2_method_and_options() {
    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -2.0*y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_assembly: AtomView
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: sparse
lsode2_linear_solver_policy: faer_sparse_lu
lsode2_native_execution: faithful_bdf_solve
lsode2_stop_variable: y
lsode2_stop_comparator: le
lsode2_stop_target: 0.5
"#;

    let spec = parse_ivp_task_from_str(input).expect("LSODE2 document should parse");
    assert_eq!(spec.solver.method, IvpMethodSpec::Lsode2);
    let lsode2 = spec
        .solver_options
        .lsode2
        .as_ref()
        .expect("LSODE2 options should be present");
    assert_eq!(
        lsode2.symbolic_assembly,
        Some(Lsode2SymbolicAssemblyBackend::AtomView)
    );
    assert_eq!(
        lsode2.linear_system_structure,
        Some(Lsode2LinearSystemStructure::Sparse)
    );
    assert_eq!(lsode2.stop_conditions.len(), 1);
    assert_eq!(lsode2.stop_conditions[0].variable, "y");
    assert_eq!(
        lsode2.stop_conditions[0].comparator,
        crate::numerical::LSODE2::Lsode2StopComparator::LessEqual
    );

    let config = build_lsode2_problem_config_from_spec(&spec)
        .expect("parsed LSODE2 stop condition should reach the native config");
    assert_eq!(config.stop_conditions.len(), 1);
    assert_eq!(config.stop_conditions[0].variable, "y");
    assert_eq!(config.stop_conditions[0].target, 0.5);
}

#[test]
fn ivp_task_parser_rejects_partial_lsode2_stop_condition() {
    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0

solver_options
lsode2_stop_target: 0.1
"#;

    let error = parse_ivp_task_from_str(input)
        .expect_err("a stop target without its state variable must be rejected");
    assert!(matches!(error, IvpTaskError::MissingField { .. }));
    assert!(error.to_string().contains("lsode2_stop_variable"));
}

#[test]
fn ivp_task_parser_maps_lsode2_method_family_to_controller_config() {
    use crate::numerical::LSODE2::Lsode2ControllerMode;

    let cases = [
        ("LSODA", "auto", Lsode2ControllerMode::AutomaticAdamsBdf),
        ("LSODE", "adams", Lsode2ControllerMode::AdamsOnly),
        ("LSODE", "bdf", Lsode2ControllerMode::BdfOnly),
    ];

    for (method, family, expected_mode) in cases {
        let input = format!(
            r#"
task
solver: IVP
method: {method}

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_method_family: {family}
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: sparse
lsode2_linear_solver_policy: auto
"#
        );
        let spec =
            parse_ivp_task_from_str(&input).expect("LSODE2 controller document should parse");
        let config = build_lsode2_problem_config_from_spec(&spec)
            .expect("LSODE2 controller document should build problem config");
        assert_eq!(
            config.controller.mode, expected_mode,
            "{method}/{family} should map to the expected controller mode"
        );
    }
}

#[test]
fn ivp_task_parser_builds_lsode2_banded_auto_resolved_plan() {
    use crate::numerical::LSODE2::{
        Lsode2ControllerMode, Lsode2LinearSolverBackend, Lsode2LinearSolverChoice,
    };

    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -2.0*y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_method_family: bdf
lsode2_symbolic_assembly: AtomView
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: banded
lsode2_linear_solver_policy: auto
lsode2_native_execution: faithful_bdf_solve
"#;

    let spec = parse_ivp_task_from_str(input).expect("LSODE2 banded document should parse");
    let config = build_lsode2_problem_config_from_spec(&spec)
        .expect("LSODE2 banded document should build problem config");
    let resolved = config.resolve_plan();

    assert_eq!(config.controller.mode, Lsode2ControllerMode::BdfOnly);
    assert_eq!(
        config.residual_jacobian_source,
        Lsode2ResidualJacobianSource::Symbolic {
            assembly: Lsode2SymbolicAssemblyBackend::AtomView,
            execution: Lsode2SymbolicExecutionMode::LambdifyExpr,
        }
    );
    assert_eq!(
        resolved.structure,
        Lsode2LinearSystemStructure::Banded { kl: 0, ku: 0 }
    );
    assert_eq!(
        resolved.linear_solver,
        Lsode2LinearSolverChoice::LapackFaithfulBandedLu
    );
    assert_eq!(
        resolved.linear_solver_reason,
        "auto_from_linear_structure_banded"
    );
    assert_eq!(
        config.backend.linear_solver_backend,
        Lsode2LinearSolverBackend::BandedFaithful
    );
    assert_eq!(
        config.backend.jacobian_backend,
        Lsode2JacobianBackend::SymbolicGenerated
    );
}

#[test]
fn ivp_task_parser_keeps_lsode2_forced_policy_visible_in_resolved_plan() {
    use crate::numerical::LSODE2::{Lsode2LinearSolverBackend, Lsode2LinearSolverChoice};

    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -2.0*y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: sparse
lsode2_linear_solver_policy: lapack_faithful_banded_lu
"#;

    let spec = parse_ivp_task_from_str(input).expect("LSODE2 forced-policy document should parse");
    let config = build_lsode2_problem_config_from_spec(&spec)
        .expect("LSODE2 forced-policy document should build problem config");
    let resolved = config.resolve_plan();

    assert_eq!(resolved.structure, Lsode2LinearSystemStructure::Sparse);
    assert_eq!(
        resolved.linear_solver,
        Lsode2LinearSolverChoice::LapackFaithfulBandedLu
    );
    assert_eq!(
        resolved.linear_solver_reason,
        "forced_by_linear_solver_policy"
    );
    assert_eq!(
        config.backend.linear_solver_backend,
        Lsode2LinearSolverBackend::BandedFaithful
    );
}

#[test]
fn ivp_task_parser_builds_lsode2_aot_toolchain_backend_contract() {
    use crate::symbolic::codegen::codegen_aot_driver::AotCodegenBackend;
    use crate::symbolic::codegen::rust_backend::codegen_aot_build::AotBuildProfile;
    use crate::symbolic::symbolic_ivp_generated::SymbolicIvpAotBuildPolicy;

    let output_dir = PathBuf::from("target/lsode2-task-parser-aot-contract");
    let input = format!(
        r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -2.0*y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_assembly: AtomView
lsode2_symbolic_execution: AOT
lsode2_aot_toolchain: zig
lsode2_aot_profile: debug
lsode2_aot_output_dir: {}
lsode2_linear_structure: sparse
lsode2_linear_solver_policy: auto
"#,
        output_dir.display()
    );

    let spec = parse_ivp_task_from_str(&input).expect("LSODE2 AOT document should parse");
    let config = build_lsode2_problem_config_from_spec(&spec)
        .expect("LSODE2 AOT document should build problem config");
    let resolved = config.resolve_plan();

    assert_eq!(
        resolved.source,
        Lsode2ResidualJacobianSource::Symbolic {
            assembly: Lsode2SymbolicAssemblyBackend::AtomView,
            execution: Lsode2SymbolicExecutionMode::Aot {
                toolchain: Lsode2AotToolchain::Zig,
                profile: Lsode2AotProfile::Debug,
            },
        }
    );
    assert_eq!(
        resolved.linear_solver,
        Lsode2LinearSolverChoice::FaerSparseLu
    );
    assert_eq!(
        config.backend.generated_backend.aot_codegen_backend,
        AotCodegenBackend::Zig
    );
    assert_eq!(config.backend.generated_backend.aot_c_compiler, None);
    assert_eq!(
        config.backend.generated_backend.output_parent_dir,
        Some(output_dir)
    );
    assert_eq!(
        config.backend.generated_backend.build_policy,
        SymbolicIvpAotBuildPolicy::BuildIfMissing {
            profile: AotBuildProfile::Debug,
        }
    );
}

#[test]
fn ivp_task_runner_supports_lsode2_lambdify_path() {
    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: dense
lsode2_linear_solver_policy: auto
"#;

    let result = run_ivp_task_from_str(input).expect("LSODE2 task should solve");
    assert!(result.status.is_some());
    assert!(result.y_result.is_some());
}

#[test]
fn ivp_task_runner_executes_lsode2_modern_postprocessing_plan() {
    let dir = tempfile::tempdir().expect("tempdir should be created");
    let csv_path = dir.path().join("lsode2_task_solution.csv");
    let report_path = dir.path().join("lsode2_task_report.md");
    let input = format!(
        r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.1
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: dense
lsode2_linear_solver_policy: auto

postprocessing
save_csv: true
csv_path: {}
write_report: true
report_path: {}
"#,
        csv_path.display(),
        report_path.display()
    );

    let result = run_ivp_task_from_str(&input).expect("LSODE2 task should solve");
    let t = result
        .t_result
        .as_ref()
        .expect("LSODE2 task should return a time mesh");
    let y = result
        .y_result
        .as_ref()
        .expect("LSODE2 task should return a solution matrix");
    assert_eq!(t.len(), y.nrows());
    assert_eq!(y.ncols(), 1);
    assert!(csv_path.exists());
    assert!(report_path.exists());

    let csv = std::fs::read_to_string(&csv_path).expect("CSV should be readable");
    assert!(csv.contains("t,y"));
    let report = std::fs::read_to_string(&report_path).expect("report should be readable");
    assert!(report.contains("Solver Result Report"));
    assert!(report.contains("axis: t"));
}

#[test]
fn ivp_task_parser_can_split_problem_and_solver_settings() {
    let input = r#"
task
solver: IVP
method: RK45

equations
arg: t
parameters: a
parameter_values: 2.0
y: -a*y

initial_conditions
t0: 0.0
t_end: 1.0
y0: 1.0

solver_options
step_size: 1e-3
parallel: false
"#;

    let document = parse_document_for_ivp(input);
    let problem = parse_ivp_problem_from_document(&document)
        .expect("problem subset should parse independently");
    let settings = parse_ivp_solver_settings_from_document(&document)
        .expect("solver settings subset should parse independently");

    assert_eq!(problem.equations.unknowns, vec!["y".to_string()]);
    assert_eq!(problem.equations.parameter_values["a"], 2.0);
    assert_eq!(
        settings.solver.method,
        IvpMethodSpec::NonStiff("RK45".to_string())
    );

    let solver = build_ivp_solver_from_problem_and_settings(&problem, &settings)
        .expect("split IVP mode should build a solver");
    let _ = solver;
}

#[test]
fn ivp_task_parser_reads_solver_settings_without_problem_sections() {
    let input = r#"
task
solver: IVP
method: LSODE2

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: dense
lsode2_linear_solver_policy: auto
"#;

    let document = parse_document_for_ivp(input);
    let settings = parse_ivp_solver_settings_from_document(&document)
        .expect("settings-only document should parse");

    assert_eq!(settings.solver.method, IvpMethodSpec::Lsode2);
    assert!(settings.solver_options.lsode2.is_some());
}

#[test]
fn ivp_task_parser_supports_full_end_to_end_document_with_lsode2_settings() {
    let input = r#"
task
solver: IVP
method: LSODE2

equations
arg: t
y: -y

initial_conditions
t0: 0.0
t_end: 0.2
y0: 1.0

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_method_family: bdf
lsode2_symbolic_assembly: AtomView
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: banded
lsode2_linear_solver_policy: auto
lsode2_native_execution: faithful_bdf_solve
"#;

    let spec = parse_ivp_task_from_str(input).expect("full IVP task doc should parse");
    assert_eq!(spec.solver.method, IvpMethodSpec::Lsode2);
    assert_eq!(
        spec.solver_options
            .lsode2
            .as_ref()
            .and_then(|opts| opts.symbolic_assembly.clone()),
        Some(Lsode2SymbolicAssemblyBackend::AtomView)
    );
    assert_eq!(spec.problem_spec().initial_conditions.t0, 0.0);
}

#[test]
fn ivp_task_parser_can_build_solver_from_rust_problem_and_task_doc_settings() {
    let problem = IvpProblemSpec {
        equations: EquationSpec {
            arg: "t".to_string(),
            unknowns: vec!["y".to_string()],
            rhs: vec![Expr::parse_expression("-y")],
            parameter_names: vec![],
            parameter_values: HashMap::new(),
        },
        initial_conditions: InitialConditionSpec {
            t0: 0.0,
            t_end: 1.0,
            y0: vec![1.0],
        },
    };

    let settings_doc = r#"
task
solver: IVP
method: RK45

solver_options
step_size: 1e-3
parallel: false
"#;
    let document = parse_document_for_ivp(settings_doc);
    let settings =
        parse_ivp_solver_settings_from_document(&document).expect("solver settings should parse");
    let solver = build_ivp_solver_from_problem_and_settings(&problem, &settings)
        .expect("Rust problem + DSL settings should build");
    let _ = solver;
}

#[test]
fn ivp_task_parser_reports_missing_parameter_values_during_lsode2_build() {
    let problem = IvpProblemSpec {
        equations: EquationSpec {
            arg: "t".to_string(),
            unknowns: vec!["y".to_string()],
            rhs: vec![Expr::parse_expression("-a*y")],
            parameter_names: vec!["a".to_string()],
            parameter_values: HashMap::new(),
        },
        initial_conditions: InitialConditionSpec {
            t0: 0.0,
            t_end: 1.0,
            y0: vec![1.0],
        },
    };

    let settings_doc = r#"
task
solver: IVP
method: LSODE2

solver_options
rtol: 1e-6
atol: 1e-8
max_step: 0.05
lsode2_symbolic_execution: LambdifyExpr
lsode2_linear_structure: sparse
lsode2_linear_solver_policy: auto
"#;
    let document = parse_document_for_ivp(settings_doc);
    let settings =
        parse_ivp_solver_settings_from_document(&document).expect("solver settings should parse");

    match build_ivp_solver_from_problem_and_settings(&problem, &settings) {
        Ok(_) => panic!("missing parameter values should be reported"),
        Err(err) => {
            let message = err.to_string();
            assert!(message.contains("parameter_values[a]"));
        }
    }
}