RustedSciThe 0.4.16

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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
//! BVP task-shell built on top of the generic [`DocumentParser`].
//!
//! This module mirrors the IVP task shell, but targets the historical
//! [`crate::numerical::BVP_api::BVP`] facade.
//!
//! The parser supports two usage modes:
//! - full end-to-end task documents, where equations, boundary conditions,
//!   mesh, initial guess, solver selection, solver options, and postprocessing
//!   live in one DSL document
//! - split mode, where the document contributes only solver settings and the
//!   BVP problem itself is assembled from plain Rust data before the solver is
//!   built
//!
//! The goal is intentionally modest: provide a small, typed, text-facing entry
//! point that is easy to validate and easy to extend later.
//!
//! The shell keeps the problem description compact while exposing the generated
//! BVP backend knobs needed by production runs:
//! - symbolic RHS is accepted as text and parsed into [`Expr`]
//! - numeric parameters are substituted before solver construction
//! - boundary conditions are expressed as `<unknown>_left` / `<unknown>_right`
//! - initial guess is described as constant profiles, not arbitrary matrices
//! - `solver_options` can select Lambdify/AOT, Sparse/Banded matrix assembly,
//!   AOT compiler/build policy, symbolic assembly backend, and native banded
//!   linear solver policy
//! - postprocessing is routed through the unified postprocessing facade, while
//!   the historical plot flag remains available for legacy plotters output

use crate::Utils::postprocessing::PostprocessPlan;
use crate::command_interpreter::task_parser::{DocumentMap, DocumentParser, Value};
use crate::command_interpreter::task_parser_common::{
    SharedEquationParseError, parse_symbolic_equation_system,
};
use crate::numerical::BVP_Damp::generated_solver_handoff::{
    AotBuildPolicy, AotBuildProfile, AotExecutionPolicy, GeneratedBackendConfig,
};
use crate::numerical::BVP_api::BVP;
use crate::somelinalg::banded::{LinearSolverConfig, LinearSolverPolicy};
use crate::symbolic::codegen::codegen_aot_driver::AotCodegenBackend;
use crate::symbolic::codegen::codegen_backend_selection::BackendSelectionPolicy;
use crate::symbolic::codegen::codegen_provider_api::MatrixBackend;
use crate::symbolic::symbolic_engine::Expr;
use crate::symbolic::symbolic_functions_BVP::BvpSymbolicAssemblyBackend;
use nalgebra::DMatrix;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

type GenericSectionMap = HashMap<String, Option<Vec<Value>>>;

/// High-level task kind supported by the BVP task shell.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BvpTaskKindSpec {
    Bvp,
}

/// Damped/frozen/naive solver family chosen by the task document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BvpStrategySpec {
    Damped,
    Frozen,
    Naive,
}

impl BvpStrategySpec {
    fn from_str(raw: &str) -> Result<Self, BvpTaskError> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "damped" => Ok(Self::Damped),
            "frozen" => Ok(Self::Frozen),
            "naive" => Ok(Self::Naive),
            other => Err(BvpTaskError::UnknownStrategy(other.to_string())),
        }
    }

    fn as_solver_string(&self) -> String {
        match self {
            Self::Damped => "Damped",
            Self::Frozen => "Frozen",
            Self::Naive => "Naive",
        }
        .to_string()
    }
}

/// Linear matrix structure requested by the task document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BvpLinearBackendSpec {
    Dense,
    Sparse,
    Banded,
}

impl BvpLinearBackendSpec {
    fn from_str(raw: &str) -> Result<Self, BvpTaskError> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "dense" => Ok(Self::Dense),
            "sparse" => Ok(Self::Sparse),
            "banded" => Ok(Self::Banded),
            other => Err(BvpTaskError::UnknownBackend(other.to_string())),
        }
    }

    fn as_solver_string(&self) -> String {
        match self {
            Self::Dense => "Dense",
            Self::Sparse => "Sparse",
            Self::Banded => "Banded",
        }
        .to_string()
    }
}

/// Top-level solver selection extracted from the DSL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BvpSolverSelectionSpec {
    pub task_kind: BvpTaskKindSpec,
    pub strategy: BvpStrategySpec,
    pub scheme: String,
    pub backend: BvpLinearBackendSpec,
}

/// Symbolic equation system and parameter declarations parsed from the DSL.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpEquationSpec {
    pub arg: String,
    pub unknowns: Vec<String>,
    pub rhs: Vec<Expr>,
    pub parameter_names: Vec<String>,
    pub parameter_values: HashMap<String, f64>,
}

/// Boundary condition map keyed by unknown name.
#[derive(Debug, Clone, PartialEq)]
pub struct BoundaryConditionSpec {
    pub conditions: HashMap<String, Vec<(usize, f64)>>,
}

/// Solver mesh description parsed from the task document.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpMeshSpec {
    pub t0: f64,
    pub t_end: f64,
    pub n_steps: usize,
}

/// Constant initial guess values for each unknown.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpInitialGuessSpec {
    pub values: Vec<f64>,
}

/// Scalar solver options and generated-backend knobs.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BvpSolverOptionsSpec {
    pub tolerance: Option<f64>,
    pub max_iterations: Option<usize>,
    pub linear_sys_method: Option<String>,
    pub loglevel: Option<String>,
    pub generated_backend: BvpGeneratedBackendSpec,
}

/// AOT / backend configuration nested inside solver options.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct BvpGeneratedBackendSpec {
    pub preset: Option<String>,
    pub matrix_backend: Option<String>,
    pub backend_policy: Option<String>,
    pub symbolic_backend: Option<String>,
    pub aot_codegen_backend: Option<String>,
    pub aot_c_compiler: Option<String>,
    pub aot_build_policy: Option<String>,
    pub aot_build_profile: Option<String>,
    pub aot_compile_preset: Option<String>,
    pub aot_execution_policy: Option<String>,
    pub banded_linear_solver: Option<String>,
    pub refinement_steps: Option<usize>,
}

/// Optional postprocessing plan collected from the task document.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BvpPostprocessingSpec {
    pub save_csv: bool,
    pub csv_path: Option<String>,
    pub save_txt: bool,
    pub txt_path: Option<String>,
    pub write_report: bool,
    pub report_path: Option<String>,
    pub plotters_png: bool,
    pub plotters_dir: Option<String>,
    pub gnuplot_png: bool,
    pub gnuplot_dir: Option<String>,
    pub terminal_plot: bool,
    pub plot: bool,
}

impl BvpPostprocessingSpec {
    fn to_plan(&self, default_csv_path: &str) -> PostprocessPlan {
        let mut plan = PostprocessPlan::new();
        if self.save_csv {
            plan = plan.save_csv(
                self.csv_path
                    .clone()
                    .unwrap_or_else(|| default_csv_path.to_string()),
            );
        }
        if self.save_txt {
            plan = plan.save_txt(
                self.txt_path
                    .clone()
                    .unwrap_or_else(|| "bvp_result.txt".to_string()),
            );
        }
        if self.write_report {
            plan = plan.write_report(
                self.report_path
                    .clone()
                    .unwrap_or_else(|| "bvp_report.md".to_string()),
            );
        }
        if self.plotters_png {
            plan = plan.plotters_png(
                self.plotters_dir
                    .clone()
                    .unwrap_or_else(|| "bvp_plotters".to_string()),
            );
        }
        if self.gnuplot_png {
            plan = plan.gnuplot_png(
                self.gnuplot_dir
                    .clone()
                    .unwrap_or_else(|| "bvp_gnuplot".to_string()),
            );
        }
        if self.terminal_plot {
            plan = plan.terminal_plot();
        }
        plan
    }
}

/// Fully parsed task document: solver selection, problem, options, and output plan.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpTaskSpec {
    pub solver: BvpSolverSelectionSpec,
    pub equations: BvpEquationSpec,
    pub boundary_conditions: BoundaryConditionSpec,
    pub mesh: BvpMeshSpec,
    pub initial_guess: BvpInitialGuessSpec,
    pub solver_options: BvpSolverOptionsSpec,
    pub postprocessing: BvpPostprocessingSpec,
}

/// Problem-only subset of the BVP task DSL.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpProblemSpec {
    pub equations: BvpEquationSpec,
    pub boundary_conditions: BoundaryConditionSpec,
    pub mesh: BvpMeshSpec,
    pub initial_guess: BvpInitialGuessSpec,
}

/// Solver-settings-only subset of the BVP task DSL.
#[derive(Debug, Clone, PartialEq)]
pub struct BvpSolverSettingsSpec {
    pub solver: BvpSolverSelectionSpec,
    pub solver_options: BvpSolverOptionsSpec,
}

impl BvpTaskSpec {
    /// Extract only the mathematical problem data from a full task document.
    pub fn problem_spec(&self) -> BvpProblemSpec {
        BvpProblemSpec {
            equations: self.equations.clone(),
            boundary_conditions: self.boundary_conditions.clone(),
            mesh: self.mesh.clone(),
            initial_guess: self.initial_guess.clone(),
        }
    }

    /// Extract only the solver-selection and solver-option settings from a full task document.
    pub fn solver_settings_spec(&self) -> BvpSolverSettingsSpec {
        BvpSolverSettingsSpec {
            solver: self.solver.clone(),
            solver_options: self.solver_options.clone(),
        }
    }

    /// Extract only the postprocessing subset from a full task document.
    pub fn postprocessing_spec(&self) -> BvpPostprocessingSpec {
        self.postprocessing.clone()
    }
}

/// Parsed task plus the optional solver output matrix.
#[derive(Debug)]
pub struct BvpTaskRunResult {
    pub specification: BvpTaskSpec,
    pub result: Option<DMatrix<f64>>,
}

/// Parser/build error for BVP task documents.
#[derive(Debug, Clone, PartialEq)]
pub enum BvpTaskError {
    Parser(String),
    MissingSection(&'static str),
    MissingField {
        section: String,
        field: String,
    },
    InvalidField {
        section: String,
        field: String,
        message: String,
    },
    InconsistentEquationCounts {
        unknowns: usize,
        rhs: usize,
    },
    UnknownStrategy(String),
    UnknownBackend(String),
    Semantic(String),
    Solver(String),
}

impl std::fmt::Display for BvpTaskError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Parser(msg) => write!(f, "parser error: {msg}"),
            Self::MissingSection(section) => write!(f, "missing section `{section}`"),
            Self::MissingField { section, field } => {
                write!(f, "missing field `{field}` in section `{section}`")
            }
            Self::InvalidField {
                section,
                field,
                message,
            } => write!(
                f,
                "invalid field `{field}` in section `{section}`: {message}"
            ),
            Self::InconsistentEquationCounts { unknowns, rhs } => write!(
                f,
                "number of unknowns ({unknowns}) does not match number of rhs expressions ({rhs})"
            ),
            Self::UnknownStrategy(strategy) => write!(f, "unknown BVP strategy `{strategy}`"),
            Self::UnknownBackend(method) => write!(f, "unknown BVP backend `{method}`"),
            Self::Semantic(message) => write!(f, "{message}"),
            Self::Solver(message) => write!(f, "{message}"),
        }
    }
}

impl std::error::Error for BvpTaskError {}

/// Parse a full BVP task document from DSL text.
pub fn parse_bvp_task_from_str(input: &str) -> Result<BvpTaskSpec, BvpTaskError> {
    let mut parser = DocumentParser::new(input.to_string());
    let pseudonyms = default_bvp_pseudonyms();
    parser.with_pseudonims(Some(pseudonyms.0), Some(pseudonyms.1));
    parser.parse_document().map_err(BvpTaskError::Parser)?;
    parser.keys_to_lower_case(Some(vec![
        "equations".to_string(),
        "parameters".to_string(),
        "boundary_conditions".to_string(),
        "initial_guess".to_string(),
        "where".to_string(),
        "substitute".to_string(),
    ]));
    let document = parser
        .get_result()
        .ok_or_else(|| BvpTaskError::Parser("document parser returned no result".to_string()))?;
    parse_bvp_task_from_document(document)
}

/// Parse a full BVP task document from an on-disk file.
pub fn parse_bvp_task_from_file(path: Option<PathBuf>) -> Result<BvpTaskSpec, BvpTaskError> {
    let mut parser = DocumentParser::new(String::new());
    parser
        .setting_from_file(path)
        .map_err(BvpTaskError::Parser)?;
    parser.parse_document().map_err(BvpTaskError::Parser)?;
    parser.keys_to_lower_case(Some(vec![
        "equations".to_string(),
        "parameters".to_string(),
        "boundary_conditions".to_string(),
        "initial_guess".to_string(),
        "where".to_string(),
        "substitute".to_string(),
    ]));
    let document = parser
        .get_result()
        .ok_or_else(|| BvpTaskError::Parser("document parser returned no result".to_string()))?;
    parse_bvp_task_from_document(document)
}

/// Fallible alias for [`parse_bvp_problem_from_document`].
pub fn try_parse_bvp_problem_from_document(
    document: &DocumentMap,
) -> Result<BvpProblemSpec, BvpTaskError> {
    parse_bvp_problem_from_document(document)
}

/// Fallible alias for [`parse_bvp_solver_settings_from_document`].
pub fn try_parse_bvp_solver_settings_from_document(
    document: &DocumentMap,
) -> Result<BvpSolverSettingsSpec, BvpTaskError> {
    parse_bvp_solver_settings_from_document(document)
}

/// Fallible alias for [`parse_bvp_task_from_document`].
pub fn try_parse_bvp_task_from_document(
    document: &DocumentMap,
) -> Result<BvpTaskSpec, BvpTaskError> {
    parse_bvp_task_from_document(document)
}

/// Fallible alias for [`parse_bvp_task_from_str`].
pub fn try_parse_bvp_task_from_str(input: &str) -> Result<BvpTaskSpec, BvpTaskError> {
    parse_bvp_task_from_str(input)
}

/// Fallible alias for [`parse_bvp_task_from_file`].
pub fn try_parse_bvp_task_from_file(path: Option<PathBuf>) -> Result<BvpTaskSpec, BvpTaskError> {
    parse_bvp_task_from_file(path)
}

/// Parse only the equation/BC/mesh/initial-guess part of the DSL.
pub fn parse_bvp_problem_from_document(
    document: &DocumentMap,
) -> Result<BvpProblemSpec, BvpTaskError> {
    let equations = parse_bvp_equations(document)?;
    let boundary_conditions = parse_boundary_conditions(document, &equations.unknowns)?;
    let mesh = parse_bvp_mesh(document)?;
    let initial_guess = parse_bvp_initial_guess(document, &equations.unknowns)?;

    Ok(BvpProblemSpec {
        equations,
        boundary_conditions,
        mesh,
        initial_guess,
    })
}

/// Parse only the solver-selection and solver-option part of the DSL.
pub fn parse_bvp_solver_settings_from_document(
    document: &DocumentMap,
) -> Result<BvpSolverSettingsSpec, BvpTaskError> {
    Ok(BvpSolverSettingsSpec {
        solver: parse_bvp_solver_selection(document)?,
        solver_options: parse_bvp_solver_options(document)?,
    })
}

/// Parse a full BVP task from an already parsed document map.
pub fn parse_bvp_task_from_document(document: &DocumentMap) -> Result<BvpTaskSpec, BvpTaskError> {
    let problem = parse_bvp_problem_from_document(document)?;
    let solver_settings = parse_bvp_solver_settings_from_document(document)?;
    let postprocessing = parse_bvp_postprocessing(document)?;

    Ok(BvpTaskSpec {
        solver: solver_settings.solver,
        equations: problem.equations,
        boundary_conditions: problem.boundary_conditions,
        mesh: problem.mesh,
        initial_guess: problem.initial_guess,
        solver_options: solver_settings.solver_options,
        postprocessing,
    })
}

/// Build a [`BVP`] solver from a full task specification.
pub fn build_bvp_solver_from_spec(spec: &BvpTaskSpec) -> Result<BVP, BvpTaskError> {
    build_bvp_solver_from_problem_and_settings(&spec.problem_spec(), &spec.solver_settings_spec())
}

/// Build a [`BVP`] solver from the Rust-side problem spec plus task-doc solver settings.
pub fn build_bvp_solver_from_problem_and_settings(
    problem: &BvpProblemSpec,
    settings: &BvpSolverSettingsSpec,
) -> Result<BVP, BvpTaskError> {
    build_bvp_solver_core(
        &problem.equations,
        &problem.boundary_conditions,
        &problem.mesh,
        &problem.initial_guess,
        &settings.solver,
        &settings.solver_options,
    )
}

fn build_bvp_solver_core(
    equations: &BvpEquationSpec,
    boundary_conditions: &BoundaryConditionSpec,
    mesh: &BvpMeshSpec,
    initial_guess_spec: &BvpInitialGuessSpec,
    solver_selection: &BvpSolverSelectionSpec,
    solver_options: &BvpSolverOptionsSpec,
) -> Result<BVP, BvpTaskError> {
    let dimension = equations.unknowns.len();
    if initial_guess_spec.values.len() != dimension {
        return Err(BvpTaskError::Semantic(format!(
            "initial guess dimension {} does not match number of unknowns {}",
            initial_guess_spec.values.len(),
            dimension
        )));
    }

    let initial_guess = DMatrix::from_fn(dimension, mesh.n_steps, |row, _col| {
        initial_guess_spec.values[row]
    });

    let tolerance = solver_options.tolerance.unwrap_or(1e-5);
    let max_iterations = solver_options.max_iterations.unwrap_or(50);
    let (strategy_params, rel_tolerance, bounds) = match solver_selection.strategy {
        BvpStrategySpec::Damped => {
            let rel_tolerance = Some(HashMap::from_iter(
                equations
                    .unknowns
                    .iter()
                    .cloned()
                    .map(|name| (name, 1e-4_f64)),
            ));
            let bounds = Some(HashMap::from_iter(
                equations
                    .unknowns
                    .iter()
                    .cloned()
                    .map(|name| (name, (-1.0e6_f64, 1.0e6_f64))),
            ));
            (
                Some(HashMap::from([
                    ("max_jac".to_string(), None),
                    ("maxDampIter".to_string(), None),
                    ("DampFacor".to_string(), None),
                    ("adaptive".to_string(), None),
                ])),
                rel_tolerance,
                bounds,
            )
        }
        BvpStrategySpec::Frozen | BvpStrategySpec::Naive => (None, None, None),
    };

    let mut bvp = BVP::new(
        equations.rhs.clone(),
        initial_guess,
        equations.unknowns.clone(),
        equations.arg.clone(),
        boundary_conditions.conditions.clone(),
        mesh.t0,
        mesh.t_end,
        mesh.n_steps,
        solver_selection.scheme.clone(),
        solver_selection.strategy.as_solver_string(),
        strategy_params,
        solver_options.linear_sys_method.clone(),
        solver_selection.backend.as_solver_string(),
        tolerance,
        max_iterations,
        rel_tolerance,
        bounds,
        solver_options.loglevel.clone(),
    );

    let generated_config = generated_backend_config_from_spec(
        &solver_options.generated_backend,
        &solver_selection.backend,
    )?;
    if matches!(
        generated_config.backend_policy_override,
        Some(
            BackendSelectionPolicy::NumericOnly
                | BackendSelectionPolicy::PreferAotThenNumeric
                | BackendSelectionPolicy::PreferLambdifyThenNumeric
        )
    ) {
        return Err(BvpTaskError::Semantic(
            "BVP task documents are symbolic inputs and cannot provide Rust numeric_rhs closures; \
             use lambdify/AOT backend policies in task docs, or the damped NRBVP Rust API with \
             set_numeric_rhs/with_numeric_rhs for pure numeric BVP solving"
                .to_string(),
        ));
    }
    if let Some(structure_damp) = &mut bvp.structure_damp {
        structure_damp.set_generated_backend_config(generated_config.clone());
    }
    if let Some(structure) = &mut bvp.structure {
        structure.set_generated_backend_config(generated_config);
    }

    Ok(bvp)
}

/// Parse and run a full BVP task document in one step.
pub fn run_bvp_task_from_str(input: &str) -> Result<BvpTaskRunResult, BvpTaskError> {
    let spec = parse_bvp_task_from_str(input)?;
    run_bvp_task(spec)
}

/// Execute a fully parsed BVP task and apply any requested postprocessing.
pub fn run_bvp_task(spec: BvpTaskSpec) -> Result<BvpTaskRunResult, BvpTaskError> {
    let mut solver = build_bvp_solver_from_spec(&spec)?;
    solver.solve();
    let plan = spec.postprocessing.to_plan("bvp_result.csv");
    if !plan.actions.is_empty() {
        solver
            .execute_postprocessing(&plan)
            .map_err(|err| BvpTaskError::Solver(err.to_string()))?;
    }
    if spec.postprocessing.plot {
        solver.plot_result();
    }
    let result = solver.get_result();
    Ok(BvpTaskRunResult {
        specification: spec,
        result,
    })
}

/// Write a starter BVP task document template to disk or to the current folder.
pub fn create_bvp_template_file(path: Option<PathBuf>) {
    use std::env;
    use std::fs::File;
    use std::io::Write;

    let template = r#"
task
solver: BVP
strategy: Damped
scheme: forward
method: Sparse

equations
arg: x
unknowns: z, y
rhs: y-z, -z^3

boundary_conditions
z_left: 1.0
y_right: 1.0

mesh
t0: 0.0
t_end: 1.0
n_steps: 20

initial_guess
z: 0.0
y: 0.0

solver_options
tolerance: 1e-5
max_iterations: 20
loglevel: warn

postprocessing
save_csv: false
csv_path: bvp_result.csv
save_txt: false
txt_path: bvp_result.txt
write_report: false
report_path: bvp_report.md
plotters_png: false
plotters_dir: bvp_plotters
gnuplot_png: false
gnuplot_dir: bvp_gnuplot
terminal_plot: false
plot: false
"#;

    let file_path = path.unwrap_or_else(|| {
        let mut default_path = env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        default_path.push("bvp_task_template.txt");
        default_path
    });

    match File::create(&file_path) {
        Ok(mut file) => {
            if let Err(err) = file.write_all(template.as_bytes()) {
                eprintln!("Failed to write BVP template file: {err}");
            }
        }
        Err(err) => eprintln!("Failed to create BVP template file: {err}"),
    }
}

fn parse_bvp_solver_selection(
    document: &DocumentMap,
) -> Result<BvpSolverSelectionSpec, BvpTaskError> {
    let task_section = get_required_section(document, "task")?;
    let solver_name = get_required_string(task_section, "task", "solver")?;
    if !solver_name.eq_ignore_ascii_case("bvp") {
        return Err(BvpTaskError::InvalidField {
            section: "task".to_string(),
            field: "solver".to_string(),
            message: format!("expected `BVP`, got `{solver_name}`"),
        });
    }

    let strategy = BvpStrategySpec::from_str(
        &get_optional_string(task_section, "strategy", "task")?.unwrap_or_else(|| "Damped".into()),
    )?;
    let scheme = get_optional_string(task_section, "scheme", "task")?
        .unwrap_or_else(|| "forward".to_string());
    let backend = BvpLinearBackendSpec::from_str(
        &get_optional_string(task_section, "method", "task")?.unwrap_or_else(|| "Sparse".into()),
    )?;

    Ok(BvpSolverSelectionSpec {
        task_kind: BvpTaskKindSpec::Bvp,
        strategy,
        scheme,
        backend,
    })
}

fn parse_bvp_equations(document: &DocumentMap) -> Result<BvpEquationSpec, BvpTaskError> {
    let parsed = parse_symbolic_equation_system(document, "x").map_err(map_equation_error)?;
    Ok(BvpEquationSpec {
        arg: parsed.arg,
        unknowns: parsed.unknowns,
        rhs: parsed.rhs,
        parameter_names: parsed.parameter_names,
        parameter_values: parsed.parameter_values,
    })
}

fn map_equation_error(error: SharedEquationParseError) -> BvpTaskError {
    match error {
        SharedEquationParseError::MissingSection(section) => BvpTaskError::MissingSection(section),
        SharedEquationParseError::MissingField { section, field } => {
            BvpTaskError::MissingField { section, field }
        }
        SharedEquationParseError::InvalidField {
            section,
            field,
            message,
        } => BvpTaskError::InvalidField {
            section,
            field,
            message,
        },
        SharedEquationParseError::InconsistentEquationCounts { unknowns, rhs } => {
            BvpTaskError::InconsistentEquationCounts { unknowns, rhs }
        }
        SharedEquationParseError::Semantic(message) => BvpTaskError::Semantic(message),
    }
}

fn parse_boundary_conditions(
    document: &DocumentMap,
    unknowns: &[String],
) -> Result<BoundaryConditionSpec, BvpTaskError> {
    let section = get_required_section(document, "boundary_conditions")?;
    let unknown_set: HashSet<&str> = unknowns.iter().map(String::as_str).collect();
    let mut conditions: HashMap<String, Vec<(usize, f64)>> = HashMap::new();

    for key in section.keys() {
        let (name, side_index) = if let Some(name) = key.strip_suffix("_left") {
            (name.to_string(), 0usize)
        } else if let Some(name) = key.strip_suffix("_right") {
            (name.to_string(), 1usize)
        } else {
            continue;
        };

        if !unknown_set.contains(name.as_str()) {
            return Err(BvpTaskError::InvalidField {
                section: "boundary_conditions".to_string(),
                field: key.clone(),
                message: format!("`{name}` is not listed in `unknowns`"),
            });
        }

        let value = get_required_float(section, "boundary_conditions", key)?;
        conditions
            .entry(name)
            .or_default()
            .push((side_index, value));
    }

    if conditions.is_empty() {
        return Err(BvpTaskError::Semantic(
            "boundary_conditions must contain keys like `y_left` or `y_right`".to_string(),
        ));
    }

    Ok(BoundaryConditionSpec { conditions })
}

fn parse_bvp_mesh(document: &DocumentMap) -> Result<BvpMeshSpec, BvpTaskError> {
    let section = get_required_section(document, "mesh")?;
    Ok(BvpMeshSpec {
        t0: get_required_float(section, "mesh", "t0")?,
        t_end: get_required_float(section, "mesh", "t_end")?,
        n_steps: get_required_usize(section, "mesh", "n_steps")?,
    })
}

fn parse_bvp_initial_guess(
    document: &DocumentMap,
    unknowns: &[String],
) -> Result<BvpInitialGuessSpec, BvpTaskError> {
    let section = get_required_section(document, "initial_guess")?;
    if section.contains_key("guess") {
        let values = get_required_float_list(section, "initial_guess", "guess")?;
        if values.len() != unknowns.len() {
            return Err(BvpTaskError::InvalidField {
                section: "initial_guess".to_string(),
                field: "guess".to_string(),
                message: format!("expected {} values, got {}", unknowns.len(), values.len()),
            });
        }
        return Ok(BvpInitialGuessSpec { values });
    }

    let mut values = Vec::with_capacity(unknowns.len());
    for unknown in unknowns {
        values.push(get_required_float(section, "initial_guess", unknown)?);
    }
    Ok(BvpInitialGuessSpec { values })
}

fn parse_bvp_solver_options(document: &DocumentMap) -> Result<BvpSolverOptionsSpec, BvpTaskError> {
    let section = match document.get("solver_options") {
        Some(section) => section,
        None => return Ok(BvpSolverOptionsSpec::default()),
    };

    Ok(BvpSolverOptionsSpec {
        tolerance: get_optional_float(section, "tolerance", "solver_options")?,
        max_iterations: get_optional_usize(section, "max_iterations", "solver_options")?,
        linear_sys_method: get_optional_string(section, "linear_sys_method", "solver_options")?,
        loglevel: get_optional_string(section, "loglevel", "solver_options")?,
        generated_backend: parse_generated_backend_options(section)?,
    })
}

fn parse_generated_backend_options(
    section: &GenericSectionMap,
) -> Result<BvpGeneratedBackendSpec, BvpTaskError> {
    Ok(BvpGeneratedBackendSpec {
        preset: get_optional_string(section, "generated_backend", "solver_options")?,
        matrix_backend: get_optional_string(section, "matrix_backend", "solver_options")?,
        backend_policy: get_optional_string(section, "backend_policy", "solver_options")?,
        symbolic_backend: get_optional_string(section, "symbolic_backend", "solver_options")?,
        aot_codegen_backend: get_optional_string(section, "aot_codegen_backend", "solver_options")?,
        aot_c_compiler: get_optional_string(section, "aot_c_compiler", "solver_options")?,
        aot_build_policy: get_optional_string(section, "aot_build_policy", "solver_options")?,
        aot_build_profile: get_optional_string(section, "aot_build_profile", "solver_options")?,
        aot_compile_preset: get_optional_string(section, "aot_compile_preset", "solver_options")?,
        aot_execution_policy: get_optional_string(
            section,
            "aot_execution_policy",
            "solver_options",
        )?,
        banded_linear_solver: get_optional_string(
            section,
            "banded_linear_solver",
            "solver_options",
        )?,
        refinement_steps: get_optional_usize(section, "refinement_steps", "solver_options")?,
    })
}

fn generated_backend_config_from_spec(
    spec: &BvpGeneratedBackendSpec,
    task_backend: &BvpLinearBackendSpec,
) -> Result<GeneratedBackendConfig, BvpTaskError> {
    let mut config = match normalized_option(spec.preset.as_deref()).as_deref() {
        None | Some("default") | Some("defaults") => match task_backend {
            BvpLinearBackendSpec::Banded => GeneratedBackendConfig::banded_defaults(),
            BvpLinearBackendSpec::Dense | BvpLinearBackendSpec::Sparse => {
                GeneratedBackendConfig::sparse_defaults()
            }
        },
        Some("sparse") | Some("sparse_default") | Some("sparse_defaults") => {
            GeneratedBackendConfig::sparse_defaults()
        }
        Some("sparse_lambdify") | Some("lambdify_sparse") => {
            GeneratedBackendConfig::sparse_defaults()
                .with_backend_policy_override(Some(BackendSelectionPolicy::LambdifyOnly))
        }
        Some("sparse_aot") | Some("sparse_build_if_missing") => {
            GeneratedBackendConfig::sparse_build_if_missing_release()
        }
        Some("sparse_aot_gcc") | Some("sparse_atomview_gcc") => {
            GeneratedBackendConfig::sparse_atomview_build_if_missing_release_gcc()
        }
        Some("sparse_aot_tcc") | Some("sparse_atomview_tcc") | Some("sparse_repeated") => {
            GeneratedBackendConfig::sparse_atomview_build_if_missing_release_tcc()
        }
        Some("sparse_aot_zig") | Some("sparse_atomview_zig") => {
            GeneratedBackendConfig::sparse_atomview_build_if_missing_release_zig()
        }
        Some("banded") | Some("banded_default") | Some("banded_defaults") => {
            GeneratedBackendConfig::banded_defaults()
        }
        Some("banded_lambdify") | Some("lambdify_banded") => {
            GeneratedBackendConfig::banded_lambdify_defaults()
        }
        Some("banded_aot") | Some("banded_build_if_missing") => {
            GeneratedBackendConfig::banded_build_if_missing_release()
        }
        Some("banded_aot_gcc") | Some("banded_atomview_gcc") => {
            GeneratedBackendConfig::banded_atomview_build_if_missing_release_gcc()
        }
        Some("banded_aot_tcc") | Some("banded_atomview_tcc") | Some("banded_repeated") => {
            GeneratedBackendConfig::banded_atomview_build_if_missing_release_tcc()
        }
        Some("banded_aot_zig") | Some("banded_atomview_zig") => {
            GeneratedBackendConfig::banded_atomview_build_if_missing_release_zig()
        }
        Some(other) => {
            return Err(invalid_solver_option(
                "generated_backend",
                format!("unknown generated backend preset `{other}`"),
            ));
        }
    };

    if let Some(matrix_backend) = spec.matrix_backend.as_deref() {
        config = apply_matrix_backend_override(config, matrix_backend)?;
    }
    if let Some(policy) = spec.backend_policy.as_deref() {
        config = config.with_backend_policy_override(Some(parse_backend_policy(policy)?));
    }
    if let Some(symbolic_backend) = spec.symbolic_backend.as_deref() {
        config = config.with_symbolic_assembly_backend(parse_symbolic_backend(symbolic_backend)?);
    }
    if let Some(codegen_backend) = spec.aot_codegen_backend.as_deref() {
        config = config.with_aot_codegen_backend(parse_aot_codegen_backend(codegen_backend)?);
    }
    if let Some(compiler) = spec.aot_c_compiler.as_deref() {
        config = config.with_aot_c_compiler(compiler);
    }
    if spec.aot_build_policy.is_some() || spec.aot_build_profile.is_some() {
        config = config.with_aot_build_policy(parse_aot_build_policy(
            spec.aot_build_policy.as_deref(),
            spec.aot_build_profile.as_deref(),
        )?);
    }
    if let Some(compile_preset) = spec.aot_compile_preset.as_deref() {
        config = apply_aot_compile_preset(config, compile_preset)?;
    }
    if let Some(execution_policy) = spec.aot_execution_policy.as_deref() {
        config = config.with_aot_execution_policy(parse_aot_execution_policy(execution_policy)?);
    }
    if spec.banded_linear_solver.is_some() || spec.refinement_steps.is_some() {
        config = config.with_banded_linear_solver_config(parse_banded_linear_solver_config(
            spec.banded_linear_solver.as_deref(),
            spec.refinement_steps,
        )?);
    }

    Ok(config)
}

fn normalized_option(raw: Option<&str>) -> Option<String> {
    raw.map(normalize_token).filter(|value| !value.is_empty())
}

fn normalize_token(raw: &str) -> String {
    raw.trim().to_ascii_lowercase().replace(['-', ' '], "_")
}

fn invalid_solver_option(field: &str, message: String) -> BvpTaskError {
    BvpTaskError::InvalidField {
        section: "solver_options".to_string(),
        field: field.to_string(),
        message,
    }
}

fn apply_matrix_backend_override(
    config: GeneratedBackendConfig,
    raw: &str,
) -> Result<GeneratedBackendConfig, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "default" | "none" => Ok(config),
        "sparse" | "sparse_col" | "sparsecol" => {
            Ok(config.with_matrix_backend_override(MatrixBackend::SparseCol))
        }
        "banded" => Ok(config.with_matrix_backend_override(MatrixBackend::Banded)),
        "dense" => Ok(config.with_matrix_backend_override(MatrixBackend::Dense)),
        other => Err(invalid_solver_option(
            "matrix_backend",
            format!("unknown matrix backend `{other}`"),
        )),
    }
}

fn parse_backend_policy(raw: &str) -> Result<BackendSelectionPolicy, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "numeric" | "numeric_only" => Ok(BackendSelectionPolicy::NumericOnly),
        "lambdify" | "lambdify_only" => Ok(BackendSelectionPolicy::LambdifyOnly),
        "aot" | "aot_only" => Ok(BackendSelectionPolicy::AotOnly),
        "prefer_aot" | "prefer_aot_then_lambdify" | "aot_then_lambdify" => {
            Ok(BackendSelectionPolicy::PreferAotThenLambdify)
        }
        "prefer_aot_then_numeric" | "aot_then_numeric" => {
            Ok(BackendSelectionPolicy::PreferAotThenNumeric)
        }
        "prefer_lambdify_then_numeric" | "lambdify_then_numeric" => {
            Ok(BackendSelectionPolicy::PreferLambdifyThenNumeric)
        }
        other => Err(invalid_solver_option(
            "backend_policy",
            format!("unknown backend policy `{other}`"),
        )),
    }
}

fn parse_symbolic_backend(raw: &str) -> Result<BvpSymbolicAssemblyBackend, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "exprlegacy" | "expr_legacy" | "legacy" => Ok(BvpSymbolicAssemblyBackend::ExprLegacy),
        "atomview" | "atom_view" | "atom" => Ok(BvpSymbolicAssemblyBackend::AtomView),
        other => Err(invalid_solver_option(
            "symbolic_backend",
            format!("unknown symbolic backend `{other}`"),
        )),
    }
}

fn parse_aot_codegen_backend(raw: &str) -> Result<AotCodegenBackend, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "rust" | "rs" => Ok(AotCodegenBackend::Rust),
        "c" => Ok(AotCodegenBackend::C),
        "zig" => Ok(AotCodegenBackend::Zig),
        other => Err(invalid_solver_option(
            "aot_codegen_backend",
            format!("unknown AOT codegen backend `{other}`"),
        )),
    }
}

fn parse_aot_build_policy(
    raw_policy: Option<&str>,
    raw_profile: Option<&str>,
) -> Result<AotBuildPolicy, BvpTaskError> {
    let profile = parse_aot_build_profile(raw_profile.unwrap_or("release"))?;
    match normalized_option(raw_policy).as_deref() {
        None | Some("use_if_available") | Some("use") | Some("auto") => {
            Ok(AotBuildPolicy::UseIfAvailable)
        }
        Some("build_if_missing") | Some("build") => Ok(AotBuildPolicy::BuildIfMissing { profile }),
        Some("require_prebuilt") | Some("require") | Some("prebuilt") => {
            Ok(AotBuildPolicy::RequirePrebuilt)
        }
        Some("rebuild_always") | Some("rebuild") => Ok(AotBuildPolicy::RebuildAlways { profile }),
        Some(other) => Err(invalid_solver_option(
            "aot_build_policy",
            format!("unknown AOT build policy `{other}`"),
        )),
    }
}

fn parse_aot_build_profile(raw: &str) -> Result<AotBuildProfile, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "release" => Ok(AotBuildProfile::Release),
        "debug" => Ok(AotBuildProfile::Debug),
        other => Err(invalid_solver_option(
            "aot_build_profile",
            format!("unknown AOT build profile `{other}`"),
        )),
    }
}

fn apply_aot_compile_preset(
    config: GeneratedBackendConfig,
    raw: &str,
) -> Result<GeneratedBackendConfig, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "production" | "prod" | "release" => Ok(config.with_aot_compile_production()),
        "fast_build" | "fastbuild" => Ok(config.with_aot_compile_fast_build()),
        "dev_fastest" | "devfastest" | "debug_fast" => Ok(config.with_aot_compile_dev_fastest()),
        other => Err(invalid_solver_option(
            "aot_compile_preset",
            format!("unknown AOT compile preset `{other}`"),
        )),
    }
}

fn parse_aot_execution_policy(raw: &str) -> Result<AotExecutionPolicy, BvpTaskError> {
    match normalize_token(raw).as_str() {
        "auto" => Ok(AotExecutionPolicy::Auto),
        "sequential" | "sequential_only" | "seq" => Ok(AotExecutionPolicy::SequentialOnly),
        "parallel" => Err(invalid_solver_option(
            "aot_execution_policy",
            "`parallel` requires a ParallelExecutorConfig and is not yet exposed in task files"
                .to_string(),
        )),
        other => Err(invalid_solver_option(
            "aot_execution_policy",
            format!("unknown AOT execution policy `{other}`"),
        )),
    }
}

fn parse_banded_linear_solver_config(
    raw_solver: Option<&str>,
    refinement_steps: Option<usize>,
) -> Result<LinearSolverConfig, BvpTaskError> {
    let refinement_steps = refinement_steps.unwrap_or(0);
    let config = match normalized_option(raw_solver).as_deref() {
        None | Some("default") | Some("auto") => {
            LinearSolverConfig::auto().with_iterative_refinement_steps(refinement_steps)
        }
        Some("faithful") | Some("lapack") | Some("lapack_style_banded_lu") => {
            LinearSolverConfig::faithful_banded_with_refinement(refinement_steps)
        }
        Some("block_tridiagonal") | Some("block_tridiagonal_lu") => LinearSolverConfig {
            policy: LinearSolverPolicy::ForceBlockTridiagonal,
            iterative_refinement_steps: refinement_steps,
            ..LinearSolverConfig::default()
        },
        Some("block_tridiagonal_consistent")
        | Some("block_tridiagonal_lu_consistent")
        | Some("consistent") => LinearSolverConfig {
            policy: LinearSolverPolicy::ForceBlockTridiagonalConsistent,
            iterative_refinement_steps: refinement_steps,
            ..LinearSolverConfig::default()
        },
        Some("faer_sparse") | Some("faer_sparse_lu") => LinearSolverConfig {
            policy: LinearSolverPolicy::ForceFaerSparse,
            iterative_refinement_steps: refinement_steps,
            ..LinearSolverConfig::default()
        },
        Some("general_partial_pivot") | Some("dense_general_pivot") => LinearSolverConfig {
            policy: LinearSolverPolicy::ForceGeneralBandedPartialPivot,
            iterative_refinement_steps: refinement_steps,
            ..LinearSolverConfig::default()
        },
        Some(other) => {
            return Err(invalid_solver_option(
                "banded_linear_solver",
                format!("unknown banded linear solver `{other}`"),
            ));
        }
    };
    Ok(config)
}

fn parse_bvp_postprocessing(document: &DocumentMap) -> Result<BvpPostprocessingSpec, BvpTaskError> {
    let section = match document.get("postprocessing") {
        Some(section) => section,
        None => return Ok(BvpPostprocessingSpec::default()),
    };

    Ok(BvpPostprocessingSpec {
        save_csv: get_optional_bool(section, "save_csv", "postprocessing")?.unwrap_or(false),
        csv_path: get_optional_string(section, "csv_path", "postprocessing")?,
        save_txt: get_optional_bool(section, "save_txt", "postprocessing")?.unwrap_or(false),
        txt_path: get_optional_string(section, "txt_path", "postprocessing")?,
        write_report: get_optional_bool(section, "write_report", "postprocessing")?
            .unwrap_or(false),
        report_path: get_optional_string(section, "report_path", "postprocessing")?,
        plotters_png: get_optional_bool(section, "plotters_png", "postprocessing")?
            .unwrap_or(false),
        plotters_dir: get_optional_string(section, "plotters_dir", "postprocessing")?,
        gnuplot_png: get_optional_bool(section, "gnuplot_png", "postprocessing")?.unwrap_or(false),
        gnuplot_dir: get_optional_string(section, "gnuplot_dir", "postprocessing")?,
        terminal_plot: get_optional_bool(section, "terminal_plot", "postprocessing")?
            .unwrap_or(false),
        plot: get_optional_bool(section, "plot", "postprocessing")?.unwrap_or(false),
    })
}

fn default_bvp_pseudonyms() -> (HashMap<String, Vec<String>>, HashMap<String, Vec<String>>) {
    let headers = HashMap::from([
        (
            "task".to_string(),
            vec!["problem".to_string(), "solver_selection".to_string()],
        ),
        (
            "equations".to_string(),
            vec!["system".to_string(), "bvp_system".to_string()],
        ),
        (
            "where".to_string(),
            vec!["substitute".to_string(), "aliases".to_string()],
        ),
        (
            "boundary_conditions".to_string(),
            vec!["boundary".to_string(), "bc".to_string()],
        ),
        (
            "mesh".to_string(),
            vec!["grid".to_string(), "domain".to_string()],
        ),
        (
            "initial_guess".to_string(),
            vec!["guess".to_string(), "initial".to_string()],
        ),
        (
            "solver_options".to_string(),
            vec!["solver_settings".to_string(), "options".to_string()],
        ),
        (
            "postprocessing".to_string(),
            vec!["output".to_string(), "postprocess".to_string()],
        ),
    ]);
    let fields = HashMap::from([
        (
            "parameters".to_string(),
            vec!["params".to_string(), "parameter_names".to_string()],
        ),
        (
            "parameter_values".to_string(),
            vec!["params_values".to_string(), "param_values".to_string()],
        ),
        (
            "t_end".to_string(),
            vec!["x_end".to_string(), "tbound".to_string()],
        ),
    ]);
    (headers, fields)
}

fn get_required_section<'a>(
    document: &'a DocumentMap,
    section: &'static str,
) -> Result<&'a GenericSectionMap, BvpTaskError> {
    document
        .get(section)
        .ok_or(BvpTaskError::MissingSection(section))
}

fn get_required_values<'a>(
    section: &'a GenericSectionMap,
    section_name: &str,
    field: &str,
) -> Result<&'a Vec<Value>, BvpTaskError> {
    section
        .get(field)
        .ok_or_else(|| BvpTaskError::MissingField {
            section: section_name.to_string(),
            field: field.to_string(),
        })?
        .as_ref()
        .ok_or_else(|| BvpTaskError::MissingField {
            section: section_name.to_string(),
            field: field.to_string(),
        })
}

fn get_required_string(
    section: &GenericSectionMap,
    section_name: &str,
    field: &str,
) -> Result<String, BvpTaskError> {
    let values = get_required_values(section, section_name, field)?;
    if values.len() != 1 {
        return Err(BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected a single string value".to_string(),
        });
    }
    value_to_string(&values[0], section_name, field)
}

fn get_optional_string(
    section: &GenericSectionMap,
    field: &str,
    section_name: &str,
) -> Result<Option<String>, BvpTaskError> {
    match section.get(field) {
        Some(Some(values)) if !values.is_empty() => {
            if values.len() != 1 {
                return Err(BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected a single string value".to_string(),
                });
            }
            Ok(Some(value_to_string(&values[0], section_name, field)?))
        }
        _ => Ok(None),
    }
}

fn get_required_float(
    section: &GenericSectionMap,
    section_name: &str,
    field: &str,
) -> Result<f64, BvpTaskError> {
    let values = get_required_values(section, section_name, field)?;
    if values.len() != 1 {
        return Err(BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected a single numeric value".to_string(),
        });
    }
    value_to_float(&values[0], section_name, field)
}

fn get_optional_float(
    section: &GenericSectionMap,
    field: &str,
    section_name: &str,
) -> Result<Option<f64>, BvpTaskError> {
    match section.get(field) {
        Some(Some(values)) if !values.is_empty() => {
            if values.len() != 1 {
                return Err(BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected a single numeric value".to_string(),
                });
            }
            Ok(Some(value_to_float(&values[0], section_name, field)?))
        }
        _ => Ok(None),
    }
}

fn get_required_usize(
    section: &GenericSectionMap,
    section_name: &str,
    field: &str,
) -> Result<usize, BvpTaskError> {
    let values = get_required_values(section, section_name, field)?;
    if values.len() != 1 {
        return Err(BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected a single integer value".to_string(),
        });
    }
    values[0]
        .as_usize()
        .ok_or_else(|| BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected usize".to_string(),
        })
}

fn get_optional_usize(
    section: &GenericSectionMap,
    field: &str,
    section_name: &str,
) -> Result<Option<usize>, BvpTaskError> {
    match section.get(field) {
        Some(Some(values)) if !values.is_empty() => {
            if values.len() != 1 {
                return Err(BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected a single integer value".to_string(),
                });
            }
            values[0]
                .as_usize()
                .ok_or_else(|| BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected usize".to_string(),
                })
                .map(Some)
        }
        _ => Ok(None),
    }
}

fn get_optional_bool(
    section: &GenericSectionMap,
    field: &str,
    section_name: &str,
) -> Result<Option<bool>, BvpTaskError> {
    match section.get(field) {
        Some(Some(values)) if !values.is_empty() => {
            if values.len() != 1 {
                return Err(BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected a single boolean value".to_string(),
                });
            }
            values[0]
                .as_boolean()
                .ok_or_else(|| BvpTaskError::InvalidField {
                    section: section_name.to_string(),
                    field: field.to_string(),
                    message: "expected bool".to_string(),
                })
                .map(Some)
        }
        _ => Ok(None),
    }
}

fn get_required_float_list(
    section: &GenericSectionMap,
    section_name: &str,
    field: &str,
) -> Result<Vec<f64>, BvpTaskError> {
    let values = get_required_values(section, section_name, field)?;
    values_to_float_list(values, section_name, field)
}

fn values_to_float_list(
    values: &[Value],
    section_name: &str,
    field: &str,
) -> Result<Vec<f64>, BvpTaskError> {
    if values.len() == 1 {
        if let Some(vector) = values[0].as_vector() {
            return Ok(vector.clone());
        }
    }
    values
        .iter()
        .map(|value| value_to_float(value, section_name, field))
        .collect()
}

fn value_to_string(value: &Value, section_name: &str, field: &str) -> Result<String, BvpTaskError> {
    if let Some(text) = value.as_string() {
        Ok(text.clone())
    } else {
        Err(BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected string".to_string(),
        })
    }
}

fn value_to_float(value: &Value, section_name: &str, field: &str) -> Result<f64, BvpTaskError> {
    if let Some(number) = value.as_float() {
        Ok(number)
    } else if let Some(integer) = value.as_usize() {
        Ok(integer as f64)
    } else {
        Err(BvpTaskError::InvalidField {
            section: section_name.to_string(),
            field: field.to_string(),
            message: "expected numeric value".to_string(),
        })
    }
}

#[cfg(test)]
#[path = "task_parser_bvp_tests.rs"]
mod task_parser_bvp_tests;