KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
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
use RustedSciThe::numerical::StiffAPI::{
    PreparedStiffSolver, StiffAttemptError, StiffSolveAttemptReport, StiffSolveOutcome,
    StiffTelemetrySnapshot,
};
use RustedSciThe::numerical::{CancellationToken, SolverTelemetryMode};
use nalgebra::{DMatrix, DVector};
use std::collections::HashMap;
use std::time::Instant;

use super::diagnostics::{NetworkIvpStage, NetworkIvpStageDiagnostics};
use super::error::{NetworkIvpError, invalid};
use super::problem::NetworkProblem;
use super::rate_law::{RateCoefficient, RateCoefficientBinding, RateLaw};
use super::solid_state::validate_conversion;
use super::solver_backend::{
    NetworkIvpAttemptDiagnostics, NetworkIvpAttemptOutcome, NetworkIvpOptions,
    NetworkIvpPartialTrajectory, NetworkIvpSolution, prepare_native,
};
use super::temperature::{TemperatureBinding, check_temperature};

/// A prepared symbolic network and native solver. Repeated runs may change the
/// initial concentrations and numeric temperature parameters, but not the
/// equations, temperature law shape, or interval.
/// Failed runs never replace the last accepted solution.
pub struct PreparedNetworkIvp<'a> {
    problem: &'a NetworkProblem,
    options: &'a NetworkIvpOptions,
    native: PreparedStiffSolver,
    attempted: bool,
    accepted_temperature: Option<TemperatureBinding>,
    native_temperature: Option<TemperatureBinding>,
    parameter_count: usize,
    temperature_parameter_count: usize,
    rate_parameter_schema: Vec<RateCoefficientBinding>,
    rate_binding_indices: HashMap<String, usize>,
    accepted_rate_bindings: Vec<RateCoefficientBinding>,
    native_bindings_match_accepted: bool,
    last_solution: Option<NetworkIvpSolution>,
    last_attempt_diagnostics: Option<NetworkIvpAttemptDiagnostics>,
    stage_diagnostics: Option<NetworkIvpStageDiagnostics>,
}

impl<'a> PreparedNetworkIvp<'a> {
    pub fn new(
        problem: &'a NetworkProblem,
        options: &'a NetworkIvpOptions,
    ) -> Result<Self, NetworkIvpError> {
        options.validate()?;
        let mut stage_diagnostics = NetworkIvpStageDiagnostics::new(options.telemetry);
        let assembly_started = stage_diagnostics
            .as_ref()
            .filter(|diagnostics| diagnostics.records_timings())
            .map(|_| Instant::now());
        let assembled = problem.assemble();
        if let Some(diagnostics) = &mut stage_diagnostics {
            diagnostics.record(
                NetworkIvpStage::EquationAssembly,
                assembly_started.map(|started| started.elapsed()),
            );
        }
        let rate_parameter_schema = rate_parameter_schema(problem);
        let parameter_count = assembled.parameter_names.len();
        let rate_parameter_count = rate_parameter_schema
            .iter()
            .map(|binding| binding.coefficient.parameter_count())
            .sum::<usize>();
        let rate_binding_indices = rate_parameter_schema
            .iter()
            .enumerate()
            .map(|(index, binding)| (binding.reaction_id.clone(), index))
            .collect();

        let preparation_started = stage_diagnostics
            .as_ref()
            .filter(|diagnostics| diagnostics.records_timings())
            .map(|_| Instant::now());
        let native = prepare_native(problem, assembled, options)?;
        if let Some(diagnostics) = &mut stage_diagnostics {
            diagnostics.record(
                NetworkIvpStage::BackendPreparation,
                preparation_started.map(|started| started.elapsed()),
            );
        }
        Ok(Self {
            problem,
            options,
            native,
            attempted: false,
            accepted_temperature: problem.temperature().initial_binding(),
            native_temperature: problem.temperature().initial_binding(),
            parameter_count,
            temperature_parameter_count: parameter_count - rate_parameter_count,
            rate_parameter_schema: rate_parameter_schema.clone(),
            accepted_rate_bindings: rate_parameter_schema,
            native_bindings_match_accepted: true,
            rate_binding_indices,
            last_solution: None,
            last_attempt_diagnostics: None,
            stage_diagnostics,
        })
    }

    pub fn solve(&mut self) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        let initial = self.problem.initial_concentrations();
        let temperature = self.accepted_temperature;
        self.solve_request(&initial, temperature, None)
    }

    pub fn solve_with_initial_concentrations(
        &mut self,
        initial: &[f64],
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        let temperature = self.accepted_temperature;
        self.solve_request(initial, temperature, None)
    }

    /// Rebind only numeric values of the already prepared temperature law.
    /// This is a fresh solve, not continuation from the previous endpoint.
    pub fn solve_with_temperature_binding(
        &mut self,
        initial: &[f64],
        binding: TemperatureBinding,
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        self.solve_request(initial, Some(binding), None)
    }

    /// Rebind the complete set of numeric reaction coefficients by reaction
    /// ID. Input order is irrelevant; omitted or incompatible entries fail
    /// before the native solver is touched.
    pub fn solve_with_rate_coefficients(
        &mut self,
        initial: &[f64],
        bindings: &[RateCoefficientBinding],
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        let temperature = self.accepted_temperature;
        self.solve_request(initial, temperature, Some(bindings))
    }

    /// Rebind temperature and all numeric reaction coefficients atomically
    /// for one fresh solve while reusing the prepared native callbacks.
    pub fn solve_with_temperature_and_rate_coefficients(
        &mut self,
        initial: &[f64],
        temperature: TemperatureBinding,
        bindings: &[RateCoefficientBinding],
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        self.solve_request(initial, Some(temperature), Some(bindings))
    }

    fn solve_request(
        &mut self,
        initial: &[f64],
        temperature: Option<TemperatureBinding>,
        bindings: Option<&[RateCoefficientBinding]>,
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        self.last_attempt_diagnostics = None;
        self.validate_initial(initial)?;
        self.validate_binding(temperature)?;
        let (rate_bindings_to_commit, parameter_values) =
            self.parameter_values_for(bindings, temperature)?;
        self.native_temperature = temperature;
        self.native_bindings_match_accepted = temperature == self.accepted_temperature
            && rate_bindings_to_commit
                .as_ref()
                .is_none_or(|rates| *rates == self.accepted_rate_bindings);
        let original_initial = !self.attempted && self.initial_matches_problem(initial);
        let result = if self.options.telemetry == SolverTelemetryMode::Off {
            let result = if self.parameter_count > 0 {
                let initial = DVector::from_vec(self.problem.initial_state(initial));
                let parameters = DVector::from_vec(parameter_values);
                self.run_integration(|native| {
                    native.try_solve_with_parameter_values(initial, parameters)
                })
            } else if original_initial {
                self.run_integration(PreparedStiffSolver::try_solve)
            } else {
                let initial = DVector::from_vec(self.problem.initial_state(initial));
                self.run_integration(|native| native.try_solve_with_initial_state(initial))
            };
            result.map_err(NetworkIvpError::Integration)
        } else {
            let report = if self.parameter_count > 0 {
                let initial = DVector::from_vec(self.problem.initial_state(initial));
                let parameters = DVector::from_vec(parameter_values);
                self.run_integration(|native| {
                    native.try_solve_with_parameter_values_report(initial, parameters)
                })
            } else if original_initial {
                self.run_integration(|native| native.try_solve_with_report(None))
            } else {
                let initial = DVector::from_vec(self.problem.initial_state(initial));
                self.run_integration(|native| native.try_solve_with_initial_state_report(initial))
            };
            self.record_native_attempt(report)
                .map_err(map_attempt_error)
        };
        self.attempted = true;
        let outcome = result?;
        self.publish_outcome(outcome, initial, temperature, rate_bindings_to_commit)
    }

    pub fn solve_with_cancellation_token(
        &mut self,
        initial: &[f64],
        cancellation: CancellationToken,
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        self.last_attempt_diagnostics = None;
        self.validate_initial(initial)?;
        if self.accepted_temperature != self.native_temperature
            || !self.native_bindings_match_accepted
        {
            return Err(NetworkIvpError::UnsupportedCapability {
                family: self.options.family,
                capability: "cancellation after a failed parameter rebind requires a successful restoration of the accepted bind",
            });
        }
        if self.attempted || !self.initial_matches_problem(initial) {
            let (t0, tf) = self.problem.time_interval();
            self.native
                .try_restart_with_initial_state(
                    t0,
                    DVector::from_vec(self.problem.initial_state(initial)),
                    tf,
                )
                .map_err(NetworkIvpError::Restart)?;
        }
        self.attempted = true;
        let result = if self.options.telemetry == SolverTelemetryMode::Off {
            self.run_integration(|native| native.try_solve_with_cancellation_token(cancellation))
                .map_err(NetworkIvpError::CancellationAwareIntegration)
        } else {
            let report =
                self.run_integration(|native| native.try_solve_with_report(Some(cancellation)));
            self.record_native_attempt(report)
                .map_err(map_attempt_error)
        };
        let outcome = result?;
        self.publish_outcome(outcome, initial, self.accepted_temperature, None)
    }

    fn publish_outcome(
        &mut self,
        outcome: StiffSolveOutcome,
        initial: &[f64],
        binding: Option<TemperatureBinding>,
        rate_bindings: Option<Vec<RateCoefficientBinding>>,
    ) -> Result<&NetworkIvpSolution, NetworkIvpError> {
        let postprocessing_started = self.timer_start();
        let result = make_candidate(self.problem, self.options, &self.native, outcome, binding);
        self.record_stage(
            NetworkIvpStage::OutputPostprocessing,
            postprocessing_started,
        );
        let mut candidate = result?;
        candidate.run_metadata = super::solver_backend::NetworkIvpRunMetadata {
            initial_concentrations: initial.to_vec(),
            time_interval_seconds: self.problem.time_interval(),
            temperature_binding: binding,
            rate_coefficients: rate_bindings
                .as_deref()
                .unwrap_or(&self.accepted_rate_bindings)
                .to_vec(),
        };
        candidate.stage_diagnostics = self.stage_diagnostics.clone();
        self.last_solution = Some(candidate);
        self.accepted_temperature = binding;
        if let Some(rate_bindings) = rate_bindings {
            self.accepted_rate_bindings = rate_bindings;
        }
        self.native_bindings_match_accepted = true;
        Ok(self.last_solution.as_ref().unwrap())
    }

    fn parameter_values_for(
        &self,
        bindings: Option<&[RateCoefficientBinding]>,
        temperature: Option<TemperatureBinding>,
    ) -> Result<(Option<Vec<RateCoefficientBinding>>, Vec<f64>), NetworkIvpError> {
        let mut parameter_values = Vec::with_capacity(self.parameter_count);
        if self.temperature_parameter_count > 0 {
            let Some(binding) = temperature else {
                return Err(NetworkIvpError::UnbindableTemperatureProgram);
            };
            let (values, count) = binding.parameter_values();
            if count != self.temperature_parameter_count {
                return Err(NetworkIvpError::TemperatureBindingMismatch {
                    expected: if self.temperature_parameter_count == 1 {
                        "constant"
                    } else {
                        "linear"
                    },
                    actual: binding.kind(),
                });
            }
            parameter_values.extend_from_slice(&values[..count]);
        }
        let rate_bindings_to_commit = if let Some(bindings) = bindings {
            let normalized = self.validate_rate_bindings(bindings)?;
            for binding in &normalized {
                binding
                    .coefficient
                    .append_parameter_values(&mut parameter_values);
            }
            (normalized != self.accepted_rate_bindings).then_some(normalized)
        } else {
            for binding in &self.accepted_rate_bindings {
                binding
                    .coefficient
                    .append_parameter_values(&mut parameter_values);
            }
            None
        };
        debug_assert_eq!(parameter_values.len(), self.parameter_count);
        Ok((rate_bindings_to_commit, parameter_values))
    }

    fn validate_rate_bindings(
        &self,
        bindings: &[RateCoefficientBinding],
    ) -> Result<Vec<RateCoefficientBinding>, NetworkIvpError> {
        let mut ordered: Vec<Option<&RateCoefficientBinding>> =
            vec![None; self.rate_parameter_schema.len()];
        for binding in bindings {
            let Some(&index) = self.rate_binding_indices.get(&binding.reaction_id) else {
                return Err(NetworkIvpError::UnknownRateBinding {
                    reaction_id: binding.reaction_id.clone(),
                });
            };
            if ordered[index].replace(binding).is_some() {
                return Err(NetworkIvpError::DuplicateRateBinding {
                    reaction_id: binding.reaction_id.clone(),
                });
            }
            let expected = &self.rate_parameter_schema[index].coefficient;
            if expected.kind() != binding.coefficient.kind() {
                return Err(NetworkIvpError::RateBindingKindMismatch {
                    reaction_id: binding.reaction_id.clone(),
                    expected: expected.kind(),
                    actual: binding.coefficient.kind(),
                });
            }
            validate_rate_coefficient(&binding.reaction_id, &binding.coefficient)?;
        }
        if bindings.len() != self.rate_parameter_schema.len() {
            return Err(NetworkIvpError::RateBindingCountMismatch {
                expected: self.rate_parameter_schema.len(),
                actual: bindings.len(),
            });
        }
        Ok(ordered
            .into_iter()
            .map(|binding| {
                binding
                    .expect("complete rate bindings were checked by count and IDs")
                    .clone()
            })
            .collect())
    }

    fn validate_binding(&self, binding: Option<TemperatureBinding>) -> Result<(), NetworkIvpError> {
        match (self.problem.temperature().initial_binding(), binding) {
            (None, None) => Ok(()),
            (None, Some(_)) => Err(NetworkIvpError::UnbindableTemperatureProgram),
            (Some(expected), Some(actual)) if expected.kind() == actual.kind() => {
                let (t0, tf) = self.problem.time_interval();
                actual.to_program().validate(t0, tf)
            }
            (Some(expected), Some(actual)) => Err(NetworkIvpError::TemperatureBindingMismatch {
                expected: expected.kind(),
                actual: actual.kind(),
            }),
            (Some(expected), None) => Err(NetworkIvpError::TemperatureBindingMismatch {
                expected: expected.kind(),
                actual: "none",
            }),
        }
    }

    fn validate_initial(&self, initial: &[f64]) -> Result<(), NetworkIvpError> {
        if initial.len() != self.problem.species().len() {
            return Err(invalid(
                "initial_concentrations",
                "state length differs from species count",
            ));
        }
        if initial
            .iter()
            .any(|value| !value.is_finite() || *value < 0.0)
        {
            return Err(invalid(
                "initial_concentrations",
                "physical state must be finite and non-negative",
            ));
        }
        self.problem.validate_solid_state_resources(initial)?;
        Ok(())
    }

    fn initial_matches_problem(&self, initial: &[f64]) -> bool {
        initial.len() == self.problem.species().len()
            && initial
                .iter()
                .zip(self.problem.species())
                .all(|(value, species)| *value == species.initial_concentration)
    }

    fn run_integration<T>(&mut self, run: impl FnOnce(&mut PreparedStiffSolver) -> T) -> T {
        let started = self.timer_start();
        let result = run(&mut self.native);
        self.record_stage(NetworkIvpStage::Integration, started);
        result
    }

    fn record_native_attempt(
        &mut self,
        report: StiffSolveAttemptReport,
    ) -> Result<StiffSolveOutcome, StiffAttemptError> {
        let outcome = match &report.result {
            Ok(_) => NetworkIvpAttemptOutcome::Completed,
            Err(StiffAttemptError::Solve(_)) => NetworkIvpAttemptOutcome::Failed,
            Err(StiffAttemptError::Cancelled(_)) => NetworkIvpAttemptOutcome::Cancelled,
        };
        let partial_trajectory = report
            .partial_trajectory
            .as_ref()
            .map(network_partial_trajectory);
        self.last_attempt_diagnostics = Some(NetworkIvpAttemptDiagnostics {
            solve_id: report.solve_id,
            outcome,
            cancellation_disposition: report.cancellation_at_return,
            telemetry: report.telemetry.clone(),
            callback_failure: report.callback_failure_diagnostic(),
            partial_trajectory,
        });
        report.result
    }

    fn timer_start(&self) -> Option<Instant> {
        self.stage_diagnostics
            .as_ref()
            .filter(|diagnostics| diagnostics.records_timings())
            .map(|_| Instant::now())
    }

    fn record_stage(&mut self, stage: NetworkIvpStage, started: Option<Instant>) {
        if let Some(diagnostics) = &mut self.stage_diagnostics {
            diagnostics.record(stage, started.map(|started| started.elapsed()));
        }
    }

    pub fn last_solution(&self) -> Option<&NetworkIvpSolution> {
        self.last_solution.as_ref()
    }

    /// Configured numeric binding, initially from the problem and updated only
    /// after an accepted rebind. None means a fixed symbolic law.
    pub fn current_temperature_binding(&self) -> Option<TemperatureBinding> {
        self.accepted_temperature
    }

    /// Complete accepted set of numeric coefficients for rebindable rate
    /// laws, ordered by the original reaction list.
    pub fn current_rate_coefficients(&self) -> &[RateCoefficientBinding] {
        &self.accepted_rate_bindings
    }

    /// Available native diagnostics from the most recent run request. None
    /// may mean Off, pre-validation rejection, or no attributable failure data.
    pub fn last_attempt_telemetry(&self) -> Option<&StiffTelemetrySnapshot> {
        self.last_attempt_diagnostics
            .as_ref()?
            .telemetry
            .as_ref()
            .map(|telemetry| &telemetry.snapshot)
    }

    /// Attempt identity and native diagnostics from the latest call that
    /// reached RST. Validation and restart failures have no attempt report.
    pub fn last_attempt_diagnostics(&self) -> Option<&NetworkIvpAttemptDiagnostics> {
        self.last_attempt_diagnostics.as_ref()
    }

    /// Diagnostic-only partial trajectory from the latest failed attempt.
    pub fn last_failed_trajectory(&self) -> Option<&NetworkIvpPartialTrajectory> {
        self.last_attempt_diagnostics
            .as_ref()?
            .partial_trajectory
            .as_ref()
    }

    /// KiThe-owned cumulative stage data for this prepared session. It is
    /// available after a failed solve as well as after an accepted one.
    pub fn stage_diagnostics(&self) -> Option<&NetworkIvpStageDiagnostics> {
        self.stage_diagnostics.as_ref()
    }
}

fn map_attempt_error(error: StiffAttemptError) -> NetworkIvpError {
    match error {
        StiffAttemptError::Solve(error) => NetworkIvpError::Integration(error),
        StiffAttemptError::Cancelled(error) => NetworkIvpError::CancellationAwareIntegration(error),
    }
}

fn network_partial_trajectory(
    trajectory: &RustedSciThe::numerical::StiffAPI::StiffDiagnosticTrajectory,
) -> NetworkIvpPartialTrajectory {
    let omitted_samples = trajectory.axis.len().saturating_sub(32);
    let first = omitted_samples;
    NetworkIvpPartialTrajectory {
        solve_id: trajectory.solve_id,
        solver: trajectory.solver,
        accepted_steps: trajectory.accepted_steps,
        time_seconds: trajectory.axis.iter().skip(first).copied().collect(),
        states: (first..trajectory.values.nrows())
            .map(|row| trajectory.values.row(row).iter().copied().collect())
            .collect(),
        omitted_samples,
    }
}

fn rate_parameter_schema(problem: &NetworkProblem) -> Vec<RateCoefficientBinding> {
    problem
        .reactions()
        .iter()
        .filter_map(|reaction| {
            let coefficient = match &reaction.rate_law {
                RateLaw::MassAction { coefficient }
                | RateLaw::EmpiricalMassAction { coefficient, .. }
                | RateLaw::SolidState { coefficient, .. } => coefficient.clone(),
                RateLaw::CustomExpr(_) => return None,
            };
            Some(RateCoefficientBinding::new(
                reaction.id.clone(),
                coefficient,
            ))
        })
        .collect()
}

fn validate_rate_coefficient(
    reaction_id: &str,
    coefficient: &RateCoefficient,
) -> Result<(), NetworkIvpError> {
    let valid = match coefficient {
        RateCoefficient::Constant(value) => value.is_finite() && *value >= 0.0,
        RateCoefficient::Arrhenius {
            prefactor,
            activation_energy,
        } => prefactor.is_finite() && *prefactor >= 0.0 && activation_energy.is_finite(),
    };
    if !valid {
        return Err(invalid(
            format!("rate_bindings[{reaction_id}]"),
            "rate parameters must be finite and prefactor non-negative",
        ));
    }
    Ok(())
}

/// Prepare and solve one physical network without retaining its native solver.
pub fn solve_network(
    problem: &NetworkProblem,
    options: &NetworkIvpOptions,
) -> Result<NetworkIvpSolution, NetworkIvpError> {
    let mut prepared = PreparedNetworkIvp::new(problem, options)?;
    prepared.solve()?;
    Ok(prepared.last_solution.take().unwrap())
}

fn make_candidate(
    problem: &NetworkProblem,
    options: &NetworkIvpOptions,
    native: &PreparedStiffSolver,
    outcome: StiffSolveOutcome,
    binding: Option<TemperatureBinding>,
) -> Result<NetworkIvpSolution, NetworkIvpError> {
    match outcome {
        StiffSolveOutcome::Radau(solution) => {
            let trajectory = solution
                .output_trajectory()
                .map_err(NetworkIvpError::RadauExtraction)?;
            let telemetry = (options.telemetry != SolverTelemetryMode::Off)
                .then(|| StiffTelemetrySnapshot::from_radau_solution(&solution));
            validate_candidate(problem, binding, &trajectory.0, &trajectory.1, telemetry)
        }
        _ => {
            let view = native
                .trajectory_view()
                .map_err(NetworkIvpError::Postprocessing)?;
            let candidate = validate_candidate(problem, binding, view.axis, view.values, None)?;
            let telemetry = if options.telemetry == SolverTelemetryMode::Off {
                None
            } else {
                Some(
                    native
                        .telemetry_snapshot()
                        .map_err(NetworkIvpError::Telemetry)?,
                )
            };
            Ok(NetworkIvpSolution {
                telemetry,
                ..candidate
            })
        }
    }
}

pub(super) fn validate_candidate(
    problem: &NetworkProblem,
    binding: Option<TemperatureBinding>,
    axis: &DVector<f64>,
    values: &DMatrix<f64>,
    telemetry: Option<StiffTelemetrySnapshot>,
) -> Result<NetworkIvpSolution, NetworkIvpError> {
    if axis.is_empty()
        || values.nrows() != axis.len()
        || values.ncols() != problem.species().len() + problem.solid_state_count()
    {
        return Err(NetworkIvpError::InvalidOutput {
            reason: "trajectory shape differs from problem",
        });
    }
    let mut time_seconds = Vec::with_capacity(axis.len());
    let mut concentrations = Vec::with_capacity(axis.len());
    let mut conversions = Vec::with_capacity(axis.len());
    let mut temperature_kelvin = Vec::with_capacity(axis.len());
    let rebound_temperature = binding.map(TemperatureBinding::to_program);
    let temperature_program = rebound_temperature
        .as_ref()
        .unwrap_or(problem.temperature());
    for (row_index, time) in axis.iter().copied().enumerate() {
        let previous_time = time_seconds.last().copied();
        if !time.is_finite() || previous_time.is_some_and(|previous| time <= previous) {
            return Err(NetworkIvpError::InvalidTimeSample {
                index: row_index,
                time,
                previous_time,
            });
        }
        let temperature = temperature_program.at(time);
        check_temperature(time, temperature)?;
        for (species_index, value) in values
            .row(row_index)
            .columns(0, problem.species().len())
            .iter()
            .copied()
            .enumerate()
        {
            if !value.is_finite() || value < 0.0 {
                return Err(NetworkIvpError::InvalidConcentration {
                    species_id: problem.species()[species_index].id.clone(),
                    time,
                    value,
                });
            }
        }
        let mut alpha_row = Vec::with_capacity(problem.solid_state_count());
        for (conversion_index, (reaction, value)) in problem
            .reactions()
            .iter()
            .filter(|reaction| matches!(reaction.rate_law, RateLaw::SolidState { .. }))
            .zip(
                values
                    .row(row_index)
                    .columns(problem.species().len(), problem.solid_state_count())
                    .iter()
                    .copied(),
            )
            .enumerate()
        {
            let model = match &reaction.rate_law {
                RateLaw::SolidState { model, .. } => model,
                _ => unreachable!(),
            };
            validate_conversion(&reaction.id, model, value).map_err(|_| {
                NetworkIvpError::InvalidConversion {
                    reaction_id: reaction.id.clone(),
                    time,
                    value,
                }
            })?;
            if conversions
                .last()
                .is_some_and(|previous: &Vec<f64>| value < previous[conversion_index])
            {
                return Err(NetworkIvpError::InvalidConversion {
                    reaction_id: reaction.id.clone(),
                    time,
                    value,
                });
            }
            alpha_row.push(value);
        }
        time_seconds.push(time);
        concentrations.push(
            values
                .row(row_index)
                .columns(0, problem.species().len())
                .iter()
                .copied()
                .collect(),
        );
        conversions.push(alpha_row);
        temperature_kelvin.push(temperature);
    }
    let (t0, tf) = problem.time_interval();
    let coverage_tolerance = 1e-9 * (tf - t0).abs().max(1.0);
    if (time_seconds[0] - t0).abs() > coverage_tolerance
        || (time_seconds.last().unwrap() - tf).abs() > coverage_tolerance
    {
        return Err(NetworkIvpError::InvalidOutput {
            reason: "trajectory does not cover requested time interval",
        });
    }
    Ok(NetworkIvpSolution {
        run_metadata: super::solver_backend::NetworkIvpRunMetadata {
            initial_concentrations: problem.initial_concentrations(),
            time_interval_seconds: (t0, tf),
            temperature_binding: binding,
            rate_coefficients: rate_parameter_schema(problem),
        },
        species_ids: problem.species().iter().map(|s| s.id.clone()).collect(),
        solid_state_reaction_ids: problem
            .reactions()
            .iter()
            .filter(|reaction| matches!(reaction.rate_law, RateLaw::SolidState { .. }))
            .map(|reaction| reaction.id.clone())
            .collect(),
        time_seconds,
        concentrations,
        conversions,
        temperature_kelvin,
        telemetry,
        stage_diagnostics: None,
    })
}