use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventoryError;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::NativeSolverStage;
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::{
NativeCallbackKind, native_solver_timing_enabled, record_native_callback,
record_native_jacobian, record_native_linear_system, record_native_residual,
record_native_stage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::SolverAttemptOutcome;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::SolverAttemptReport;
use crate::Thermodynamics::User_substances_error::SubsDataError;
use log::{debug as info, error};
use nalgebra::{DMatrix, DVector};
use std::error::Error;
use std::fmt;
#[derive(Debug, Clone)]
pub enum SolveError {
MaxIterations,
SingularMatrix,
EvalError(String),
}
impl fmt::Display for SolveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MaxIterations => write!(f, "nonlinear solver reached its iteration limit"),
Self::SingularMatrix => write!(f, "nonlinear solver encountered a singular matrix"),
Self::EvalError(message) => write!(f, "nonlinear solver evaluation failed: {message}"),
}
}
}
impl Error for SolveError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendFailureKind {
LinearSolve,
SingularJacobian,
NumericalBreakdown,
}
#[derive(Debug)]
pub struct PhMonolithicSeedFailure {
temperature_seed_k: f64,
cause: Box<ReactionExtentError>,
}
impl PhMonolithicSeedFailure {
pub(crate) fn new(temperature_seed_k: f64, cause: ReactionExtentError) -> Self {
Self {
temperature_seed_k,
cause: Box::new(cause),
}
}
pub fn temperature_seed_k(&self) -> f64 {
self.temperature_seed_k
}
pub fn cause(&self) -> &ReactionExtentError {
&self.cause
}
pub(crate) fn into_cause(self) -> ReactionExtentError {
*self.cause
}
}
#[derive(Debug)]
pub struct MultiStartSeedFailure {
start_index: usize,
cause: Box<ReactionExtentError>,
}
impl MultiStartSeedFailure {
pub(crate) fn new(start_index: usize, cause: ReactionExtentError) -> Self {
Self {
start_index,
cause: Box::new(cause),
}
}
pub fn start_index(&self) -> usize {
self.start_index
}
pub fn cause(&self) -> &ReactionExtentError {
&self.cause
}
}
#[derive(Debug)]
pub enum ReactionExtentError {
Cancelled,
InvalidProblem {
field: &'static str,
message: String,
},
Preparation(EquilibriumPreparationError),
InvalidConditions {
parameter: &'static str,
value: f64,
},
InvalidCandidate {
field: &'static str,
message: String,
},
AllBackendsFailed { attempts: Vec<SolverAttemptReport> },
CascadeAborted {
attempts: Vec<SolverAttemptReport>,
cause: Box<ReactionExtentError>,
},
ExtensiveNormalizationRecoveryFailed {
stage: &'static str,
physical: Box<ReactionExtentError>,
recovery: Box<ReactionExtentError>,
},
SubsDataError(SubsDataError),
SolveError(SolveError),
BackendFailure {
backend: String,
kind: BackendFailureKind,
message: String,
},
SVDError(String),
ValidationNotApplicable {
path: &'static str,
message: String,
},
UnsupportedBackendCapability {
backend: String,
capability: &'static str,
alternatives: String,
},
PhaseControlDidNotConverge {
iterations: usize,
},
PhaseControlCycleDetected {
iteration: usize,
active_phases: Vec<usize>,
},
TemperatureTrialFailed {
trial_index: usize,
temperature: f64,
cause: Box<ReactionExtentError>,
},
TemperatureRangePointFailed {
point_index: usize,
temperature: f64,
cause: Box<ReactionExtentError>,
},
PhAutoFallbackFailed {
monolithic: Box<ReactionExtentError>,
nested: Box<ReactionExtentError>,
},
PhMonolithicSeedRecoveryFailed {
attempts: Vec<PhMonolithicSeedFailure>,
},
MultiStartSeedRecoveryFailed {
attempts: Vec<MultiStartSeedFailure>,
},
PhMonolithicPhaseProbeRejected {
message: String,
},
DimensionMismatch(String),
DuplicateSpecies(usize),
SpeciesNotAssigned { index: usize },
InvalidInitialResiduals(Vec<f64>),
ResidualEvaluation(String),
JacobianEvaluation(String),
InvalidSpeciesAmount { index: usize, value: f64 },
InvalidNPhase { index: usize, value: f64 },
InvalidPhi { index: usize, value: f64 },
InvalidDG0 {
species_index: usize,
dg0: f64,
temperature: f64,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum EquilibriumPreparationError {
EmptySpeciesUniverse,
NonRepresentableInventory { message: String },
FeasibleSeedConstruction { message: String },
ElementInventory(ElementInventoryError),
}
impl fmt::Display for EquilibriumPreparationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySpeciesUniverse => {
write!(
f,
"equilibrium preparation requires at least one real species"
)
}
Self::NonRepresentableInventory { message } => {
write!(f, "elemental inventory is not representable: {message}")
}
Self::FeasibleSeedConstruction { message } => {
write!(f, "element-feasible seed construction failed: {message}")
}
Self::ElementInventory(error) => write!(f, "element inventory is invalid: {error}"),
}
}
}
impl Error for EquilibriumPreparationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ElementInventory(error) => Some(error),
_ => None,
}
}
}
impl From<ElementInventoryError> for ReactionExtentError {
fn from(value: ElementInventoryError) -> Self {
Self::Preparation(EquilibriumPreparationError::ElementInventory(value))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReactionExtentErrorKind {
Cancelled,
InvalidInput,
ThermochemicalLookup,
Formulation,
ResidualEvaluation,
JacobianEvaluation,
BackendFailure,
NonConvergence,
InvalidCandidate,
UnsupportedModel,
ValidationMismatch,
AllBackendsFailed,
CascadeAborted,
}
impl From<SubsDataError> for ReactionExtentError {
fn from(value: SubsDataError) -> Self {
ReactionExtentError::SubsDataError(value)
}
}
impl fmt::Display for ReactionExtentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cancelled => write!(f, "equilibrium solve was cancelled"),
Self::InvalidProblem { field, message } => {
write!(f, "invalid equilibrium problem field '{field}': {message}")
}
Self::Preparation(error) => write!(f, "equilibrium preparation failed: {error}"),
Self::InvalidConditions { parameter, value } => {
write!(f, "invalid equilibrium condition '{parameter}': {value}")
}
Self::InvalidCandidate { field, message } => {
write!(
f,
"equilibrium candidate field '{field}' was rejected: {message}"
)
}
Self::AllBackendsFailed { attempts } => {
write!(
f,
"all equilibrium solver backends failed after {} attempt(s)",
attempts.len()
)
}
Self::CascadeAborted { attempts, cause } => write!(
f,
"equilibrium solver cascade aborted after {} attempt(s): {cause}",
attempts.len()
),
Self::ExtensiveNormalizationRecoveryFailed {
stage,
physical,
recovery,
} => write!(
f,
"extensive-normalization recovery failed during {stage}; physical attempt: {physical}; recovery attempt: {recovery}"
),
Self::SubsDataError(error) => write!(f, "equilibrium data preparation failed: {error}"),
Self::SolveError(error) => write!(f, "equilibrium solver failed: {error}"),
Self::BackendFailure {
backend,
kind,
message,
} => write!(
f,
"equilibrium backend '{backend}' failed ({kind:?}): {message}"
),
Self::SVDError(message) => write!(f, "reaction-basis construction failed: {message}"),
Self::ValidationNotApplicable { path, message } => {
write!(f, "validation path '{path}' is not applicable: {message}")
}
Self::UnsupportedBackendCapability {
backend,
capability,
alternatives,
} => write!(
f,
"backend '{backend}' does not support capability '{capability}'; supported alternatives: {alternatives}"
),
Self::PhaseControlDidNotConverge { iterations } => {
write!(
f,
"phase-control outer loop did not converge after {iterations} iteration(s)"
)
}
Self::PhaseControlCycleDetected {
iteration,
active_phases,
} => write!(
f,
"phase-control cycle detected at iteration {iteration} for active phases {active_phases:?}"
),
Self::TemperatureTrialFailed {
trial_index,
temperature,
cause,
} => write!(
f,
"P,H temperature trial {trial_index} at {temperature} K failed: {cause}"
),
Self::TemperatureRangePointFailed {
point_index,
temperature,
cause,
} => write!(
f,
"equilibrium temperature-range point {point_index} at {temperature} K failed: {cause}"
),
Self::PhAutoFallbackFailed { monolithic, nested } => write!(
f,
"automatic P,H recovery failed; monolithic attempt: {monolithic}; nested recovery: {nested}"
),
Self::PhMonolithicSeedRecoveryFailed { attempts } => write!(
f,
"monolithic P,H temperature-seed recovery failed after {} attempt(s)",
attempts.len()
),
Self::MultiStartSeedRecoveryFailed { attempts } => write!(
f,
"explicit multi-start recovery failed after {} seed attempt(s)",
attempts.len()
),
Self::PhMonolithicPhaseProbeRejected { message } => {
write!(f, "monolithic P,H phase probe was rejected: {message}")
}
Self::DimensionMismatch(message) => {
write!(f, "equilibrium dimension mismatch: {message}")
}
Self::DuplicateSpecies(index) => {
write!(f, "species index {index} belongs to multiple phases")
}
Self::SpeciesNotAssigned { index } => {
write!(f, "species index {index} is not assigned to any phase")
}
Self::InvalidInitialResiduals(values) => {
write!(
f,
"initial equilibrium residual contains non-finite values: {values:?}"
)
}
Self::ResidualEvaluation(message) => {
write!(f, "equilibrium residual evaluation failed: {message}")
}
Self::JacobianEvaluation(message) => {
write!(f, "equilibrium Jacobian evaluation failed: {message}")
}
Self::InvalidSpeciesAmount { index, value } => {
write!(f, "invalid mole amount at species index {index}: {value}")
}
Self::InvalidNPhase { index, value } => {
write!(f, "invalid total mole amount for phase {index}: {value}")
}
Self::InvalidPhi { index, value } => {
write!(f, "invalid phase correction at phase {index}: {value}")
}
Self::InvalidDG0 {
species_index,
dg0,
temperature,
} => {
write!(
f,
"invalid standard Gibbs energy {dg0} for species index {species_index} at temperature {temperature}"
)
}
}
}
}
impl Error for ReactionExtentError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Cancelled => None,
Self::Preparation(error) => Some(error),
Self::SubsDataError(error) => Some(error),
Self::SolveError(error) => Some(error),
Self::CascadeAborted { cause, .. } => Some(cause.as_ref()),
Self::ExtensiveNormalizationRecoveryFailed { recovery, .. } => Some(recovery.as_ref()),
Self::TemperatureTrialFailed { cause, .. } => Some(cause.as_ref()),
Self::TemperatureRangePointFailed { cause, .. } => Some(cause.as_ref()),
Self::PhAutoFallbackFailed { nested, .. } => Some(nested.as_ref()),
Self::PhMonolithicSeedRecoveryFailed { attempts } => {
attempts.last().map(|attempt| attempt.cause() as _)
}
Self::MultiStartSeedRecoveryFailed { attempts } => {
attempts.last().map(|attempt| attempt.cause() as _)
}
_ => None,
}
}
}
impl ReactionExtentError {
pub fn kind(&self) -> ReactionExtentErrorKind {
match self {
Self::Cancelled => ReactionExtentErrorKind::Cancelled,
Self::Preparation(_) => ReactionExtentErrorKind::InvalidInput,
Self::InvalidProblem { .. }
| Self::InvalidConditions { .. }
| Self::DimensionMismatch(_)
| Self::DuplicateSpecies(_)
| Self::SpeciesNotAssigned { .. }
| Self::InvalidInitialResiduals(_)
| Self::InvalidSpeciesAmount { .. }
| Self::InvalidNPhase { .. }
| Self::InvalidPhi { .. } => ReactionExtentErrorKind::Formulation,
Self::SubsDataError(_) => ReactionExtentErrorKind::ThermochemicalLookup,
Self::InvalidCandidate { .. } => ReactionExtentErrorKind::InvalidCandidate,
Self::InvalidDG0 { .. } => ReactionExtentErrorKind::ThermochemicalLookup,
Self::SolveError(SolveError::MaxIterations) => ReactionExtentErrorKind::NonConvergence,
Self::SolveError(_) => ReactionExtentErrorKind::BackendFailure,
Self::BackendFailure { .. } => ReactionExtentErrorKind::BackendFailure,
Self::SVDError(_) => ReactionExtentErrorKind::UnsupportedModel,
Self::ValidationNotApplicable { .. } => ReactionExtentErrorKind::ValidationMismatch,
Self::UnsupportedBackendCapability { .. } => ReactionExtentErrorKind::UnsupportedModel,
Self::PhaseControlDidNotConverge { .. } | Self::PhaseControlCycleDetected { .. } => {
ReactionExtentErrorKind::NonConvergence
}
Self::ResidualEvaluation(_) => ReactionExtentErrorKind::ResidualEvaluation,
Self::JacobianEvaluation(_) => ReactionExtentErrorKind::JacobianEvaluation,
Self::AllBackendsFailed { .. } => ReactionExtentErrorKind::AllBackendsFailed,
Self::CascadeAborted { .. } => ReactionExtentErrorKind::CascadeAborted,
Self::ExtensiveNormalizationRecoveryFailed { recovery, .. } => recovery.kind(),
Self::TemperatureTrialFailed { cause, .. } => cause.kind(),
Self::TemperatureRangePointFailed { cause, .. } => cause.kind(),
Self::PhAutoFallbackFailed { nested, .. } => nested.kind(),
Self::PhMonolithicSeedRecoveryFailed { .. } => {
ReactionExtentErrorKind::AllBackendsFailed
}
Self::MultiStartSeedRecoveryFailed { .. } => ReactionExtentErrorKind::AllBackendsFailed,
Self::PhMonolithicPhaseProbeRejected { .. } => {
ReactionExtentErrorKind::InvalidCandidate
}
}
}
pub fn started_backend_attempts(&self) -> usize {
match self {
Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
attempts
.iter()
.filter(|attempt| {
!matches!(attempt.outcome, SolverAttemptOutcome::Skipped { .. })
})
.count()
}
Self::TemperatureTrialFailed { cause, .. }
| Self::TemperatureRangePointFailed { cause, .. } => cause.started_backend_attempts(),
Self::ExtensiveNormalizationRecoveryFailed {
physical, recovery, ..
} => physical
.started_backend_attempts()
.saturating_add(recovery.started_backend_attempts()),
Self::PhAutoFallbackFailed { monolithic, nested } => monolithic
.started_backend_attempts()
.saturating_add(nested.started_backend_attempts()),
Self::PhMonolithicSeedRecoveryFailed { attempts } => attempts
.iter()
.map(|attempt| attempt.cause().started_backend_attempts())
.sum(),
Self::MultiStartSeedRecoveryFailed { attempts } => attempts
.iter()
.map(|attempt| attempt.cause().started_backend_attempts())
.sum(),
_ => 0,
}
}
pub fn backend_attempt_reports(&self) -> Vec<SolverAttemptReport> {
let mut reports = Vec::new();
self.collect_backend_attempt_reports(&mut reports);
reports
}
fn collect_backend_attempt_reports(&self, output: &mut Vec<SolverAttemptReport>) {
match self {
Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
output.extend(attempts.iter().cloned());
}
Self::TemperatureTrialFailed { cause, .. }
| Self::TemperatureRangePointFailed { cause, .. } => {
cause.collect_backend_attempt_reports(output);
}
Self::ExtensiveNormalizationRecoveryFailed {
physical, recovery, ..
} => {
physical.collect_backend_attempt_reports(output);
recovery.collect_backend_attempt_reports(output);
}
Self::PhAutoFallbackFailed { monolithic, nested } => {
monolithic.collect_backend_attempt_reports(output);
nested.collect_backend_attempt_reports(output);
}
Self::PhMonolithicSeedRecoveryFailed { attempts } => {
for attempt in attempts {
attempt.cause().collect_backend_attempt_reports(output);
}
}
Self::MultiStartSeedRecoveryFailed { attempts } => {
for attempt in attempts {
attempt.cause().collect_backend_attempt_reports(output);
}
}
_ => {}
}
}
pub fn nonlinear_iterations(&self) -> usize {
match self {
Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
attempts
.iter()
.filter_map(|attempt| attempt.metrics.as_ref())
.map(|metrics| metrics.iterations)
.sum()
}
Self::TemperatureTrialFailed { cause, .. }
| Self::TemperatureRangePointFailed { cause, .. } => cause.nonlinear_iterations(),
Self::ExtensiveNormalizationRecoveryFailed {
physical, recovery, ..
} => physical
.nonlinear_iterations()
.saturating_add(recovery.nonlinear_iterations()),
Self::PhAutoFallbackFailed { monolithic, nested } => monolithic
.nonlinear_iterations()
.saturating_add(nested.nonlinear_iterations()),
Self::PhMonolithicSeedRecoveryFailed { attempts } => attempts
.iter()
.map(|attempt| attempt.cause().nonlinear_iterations())
.sum(),
Self::MultiStartSeedRecoveryFailed { attempts } => attempts
.iter()
.map(|attempt| attempt.cause().nonlinear_iterations())
.sum(),
_ => 0,
}
}
pub fn is_retryable_backend_failure(&self) -> bool {
matches!(
self.kind(),
ReactionExtentErrorKind::NonConvergence
| ReactionExtentErrorKind::BackendFailure
| ReactionExtentErrorKind::ResidualEvaluation
| ReactionExtentErrorKind::JacobianEvaluation
)
}
pub fn is_retryable_formulation_failure(&self) -> bool {
match self {
Self::AllBackendsFailed { attempts } => {
!attempts.is_empty()
&& attempts.iter().all(|attempt| {
matches!(attempt.outcome, SolverAttemptOutcome::Failed { .. })
})
}
Self::CascadeAborted { cause, .. } => cause.is_retryable_formulation_failure(),
Self::PhMonolithicSeedRecoveryFailed { attempts } => {
!attempts.is_empty()
&& attempts
.iter()
.all(|attempt| attempt.cause().is_retryable_formulation_failure())
}
Self::MultiStartSeedRecoveryFailed { attempts } => {
!attempts.is_empty()
&& attempts
.iter()
.all(|attempt| attempt.cause().is_retryable_formulation_failure())
}
Self::PhMonolithicPhaseProbeRejected { .. } => true,
_ => self.is_retryable_backend_failure(),
}
}
pub fn is_non_retryable_input_error(&self) -> bool {
if matches!(self, Self::PhMonolithicPhaseProbeRejected { .. }) {
return false;
}
matches!(
self.kind(),
ReactionExtentErrorKind::InvalidInput
| ReactionExtentErrorKind::ThermochemicalLookup
| ReactionExtentErrorKind::Formulation
| ReactionExtentErrorKind::InvalidCandidate
| ReactionExtentErrorKind::UnsupportedModel
| ReactionExtentErrorKind::ValidationMismatch
)
}
}
#[cfg(test)]
mod error_contract_tests {
use super::{
EquilibriumPreparationError, MultiStartSeedFailure, PhMonolithicSeedFailure,
ReactionExtentError, ReactionExtentErrorKind, SolveError,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventoryError;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::Solvers;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
SolverAttemptFailureKind, SolverAttemptMetrics, SolverAttemptOutcome, SolverAttemptReport,
SolverBackend, SolverTermination,
};
use crate::Thermodynamics::User_substances_error::SubsDataError;
use std::error::Error;
#[test]
fn equilibrium_errors_are_displayable_and_preserve_nested_sources() {
let solve_error = ReactionExtentError::SolveError(SolveError::MaxIterations);
assert_eq!(
solve_error.to_string(),
"equilibrium solver failed: nonlinear solver reached its iteration limit"
);
assert!(solve_error.source().is_some());
let data_error =
ReactionExtentError::from(SubsDataError::SubstanceNotFound("O2".to_string()));
assert!(data_error.to_string().contains("O2"));
assert!(data_error.source().is_some());
}
#[test]
fn preparation_errors_keep_typed_inventory_causes_and_fail_fast_classification() {
let error = ReactionExtentError::from(ElementInventoryError::EmptyInventory);
assert!(matches!(
&error,
ReactionExtentError::Preparation(EquilibriumPreparationError::ElementInventory(
ElementInventoryError::EmptyInventory
))
));
assert_eq!(error.kind(), ReactionExtentErrorKind::InvalidInput);
assert!(error.is_non_retryable_input_error());
assert!(error.source().is_some());
assert!(error.to_string().contains("at least one positive amount"));
}
#[test]
fn multi_start_failure_preserves_each_typed_cascade_and_aggregates_work() {
let cascade_failure = |solver| ReactionExtentError::AllBackendsFailed {
attempts: vec![SolverAttemptReport {
backend: SolverBackend::Native(solver),
outcome: SolverAttemptOutcome::Failed {
kind: SolverAttemptFailureKind::Solver,
reason: "iteration limit".to_string(),
elapsed_micros: 0,
},
metrics: Some(SolverAttemptMetrics {
termination: SolverTermination::MaxIterations,
backend_converged: false,
iterations: 3,
backend_progress_available: true,
residual_evaluations: 4,
jacobian_evaluations: 3,
linear_solves: 3,
counters_collected: true,
timings_collected: false,
elapsed_millis: 1,
elapsed_micros: 1_000,
evaluation_timing: None,
}),
}],
};
let error = ReactionExtentError::MultiStartSeedRecoveryFailed {
attempts: vec![
MultiStartSeedFailure::new(0, cascade_failure(Solvers::LM)),
MultiStartSeedFailure::new(1, cascade_failure(Solvers::NR)),
],
};
assert_eq!(error.kind(), ReactionExtentErrorKind::AllBackendsFailed);
assert_eq!(error.started_backend_attempts(), 2);
assert_eq!(error.nonlinear_iterations(), 6);
assert!(error.is_retryable_formulation_failure());
assert!(error.source().is_some());
assert!(error.to_string().contains("2 seed attempt(s)"));
let ReactionExtentError::MultiStartSeedRecoveryFailed { attempts } = error else {
panic!("expected typed multi-start recovery failure");
};
assert_eq!(attempts[0].start_index(), 0);
assert!(matches!(
attempts[0].cause(),
ReactionExtentError::AllBackendsFailed { attempts } if attempts.len() == 1
));
}
#[test]
fn all_backend_failure_display_reports_the_attempt_count() {
let error = ReactionExtentError::AllBackendsFailed {
attempts: Vec::new(),
};
assert_eq!(
error.to_string(),
"all equilibrium solver backends failed after 0 attempt(s)"
);
assert!(error.source().is_none());
assert_eq!(error.kind(), ReactionExtentErrorKind::AllBackendsFailed);
assert!(!error.is_retryable_backend_failure());
assert!(!error.is_retryable_formulation_failure());
}
#[test]
fn auto_formulation_retry_requires_only_started_numerical_failures() {
let backend = SolverBackend::Native(Solvers::NR);
let failed = || SolverAttemptReport {
backend,
outcome: SolverAttemptOutcome::Failed {
kind: SolverAttemptFailureKind::Solver,
reason: "iteration limit".to_string(),
elapsed_micros: 0,
},
metrics: None,
};
let rejected = SolverAttemptReport {
backend,
outcome: SolverAttemptOutcome::RejectedCandidate {
reason: "candidate residual is too large".to_string(),
},
metrics: None,
};
let skipped = SolverAttemptReport {
backend,
outcome: SolverAttemptOutcome::Skipped {
reason: "cascade budget exhausted".to_string(),
},
metrics: None,
};
let retryable = ReactionExtentError::AllBackendsFailed {
attempts: vec![failed(), failed()],
};
assert!(retryable.is_retryable_formulation_failure());
for attempts in [
vec![rejected.clone()],
vec![skipped.clone()],
vec![failed(), rejected],
Vec::new(),
] {
let error = ReactionExtentError::AllBackendsFailed { attempts };
assert!(!error.is_retryable_formulation_failure());
}
}
#[test]
fn rejected_monolithic_phase_probe_allows_only_formulation_fallback() {
let error = ReactionExtentError::PhMonolithicPhaseProbeRejected {
message: "TPD did not authorize the probed phase".to_string(),
};
assert_eq!(error.kind(), ReactionExtentErrorKind::InvalidCandidate);
assert!(!error.is_retryable_backend_failure());
assert!(error.is_retryable_formulation_failure());
assert!(!error.is_non_retryable_input_error());
assert!(error.to_string().contains("phase probe was rejected"));
}
#[test]
fn aggregate_ph_errors_report_started_backend_work_recursively() {
let backend = SolverBackend::Native(Solvers::NR);
let failed_seed = |temperature| {
PhMonolithicSeedFailure::new(
temperature,
ReactionExtentError::AllBackendsFailed {
attempts: vec![SolverAttemptReport {
backend,
outcome: SolverAttemptOutcome::Failed {
kind: SolverAttemptFailureKind::Solver,
reason: "iteration limit".to_string(),
elapsed_micros: 0,
},
metrics: None,
}],
},
)
};
let monolithic = ReactionExtentError::PhMonolithicSeedRecoveryFailed {
attempts: vec![failed_seed(600.0), failed_seed(1_000.0)],
};
assert_eq!(monolithic.started_backend_attempts(), 2);
assert_eq!(monolithic.nonlinear_iterations(), 0);
let auto = ReactionExtentError::PhAutoFallbackFailed {
monolithic: Box::new(monolithic),
nested: Box::new(ReactionExtentError::AllBackendsFailed {
attempts: vec![SolverAttemptReport {
backend,
outcome: SolverAttemptOutcome::Failed {
kind: SolverAttemptFailureKind::Solver,
reason: "nested iteration limit".to_string(),
elapsed_micros: 0,
},
metrics: None,
}],
}),
};
assert_eq!(auto.started_backend_attempts(), 3);
}
#[test]
fn aborted_cascade_preserves_the_non_retryable_cause() {
let error = ReactionExtentError::CascadeAborted {
attempts: Vec::new(),
cause: Box::new(ReactionExtentError::InvalidProblem {
field: "solver_policy",
message: "missing backend".to_string(),
}),
};
assert!(
error
.to_string()
.contains("cascade aborted after 0 attempt(s)")
);
assert!(error.source().is_some());
assert_eq!(error.kind(), ReactionExtentErrorKind::CascadeAborted);
}
#[test]
fn auto_ph_failure_retains_primary_and_recovery_causes() {
let error = ReactionExtentError::PhAutoFallbackFailed {
monolithic: Box::new(ReactionExtentError::AllBackendsFailed {
attempts: Vec::new(),
}),
nested: Box::new(ReactionExtentError::SolveError(SolveError::MaxIterations)),
};
assert!(error.to_string().contains("monolithic attempt"));
assert!(error.to_string().contains("nested recovery"));
assert!(error.source().is_some());
assert_eq!(error.kind(), ReactionExtentErrorKind::NonConvergence);
assert!(error.is_retryable_backend_failure());
}
#[test]
fn species_not_assigned_display_reports_the_missing_index() {
let error = ReactionExtentError::SpeciesNotAssigned { index: 3 };
assert_eq!(
error.to_string(),
"species index 3 is not assigned to any phase"
);
}
#[test]
fn error_kind_classifies_core_families() {
assert_eq!(
ReactionExtentError::InvalidProblem {
field: "solver_policy",
message: "missing backend".to_string(),
}
.kind(),
ReactionExtentErrorKind::Formulation
);
assert_eq!(
ReactionExtentError::from(SubsDataError::SubstanceNotFound("O2".to_string())).kind(),
ReactionExtentErrorKind::ThermochemicalLookup
);
assert_eq!(
ReactionExtentError::ResidualEvaluation("bad residual".to_string()).kind(),
ReactionExtentErrorKind::ResidualEvaluation
);
assert_eq!(
ReactionExtentError::SolveError(SolveError::MaxIterations).kind(),
ReactionExtentErrorKind::NonConvergence
);
assert_eq!(
ReactionExtentError::ValidationNotApplicable {
path: "keq_solver",
message: "too many reactions".to_string(),
}
.kind(),
ReactionExtentErrorKind::ValidationMismatch
);
let phase_error = ReactionExtentError::PhaseControlDidNotConverge { iterations: 3 };
assert_eq!(phase_error.kind(), ReactionExtentErrorKind::NonConvergence);
assert!(phase_error.to_string().contains("phase-control outer loop"));
}
#[test]
fn unsupported_backend_capability_is_typed_and_non_retryable() {
let error = ReactionExtentError::UnsupportedBackendCapability {
backend: "RustedSciThe".to_string(),
capability: "monolithic_p_h",
alternatives: "native LM, NR, or trust-region backends".to_string(),
};
assert_eq!(error.kind(), ReactionExtentErrorKind::UnsupportedModel);
assert!(!error.is_retryable_backend_failure());
let message = error.to_string();
assert!(message.contains("RustedSciThe"));
assert!(message.contains("monolithic_p_h"));
assert!(message.contains("native LM"));
}
#[test]
fn cancellation_is_a_non_retryable_typed_error() {
let error = ReactionExtentError::Cancelled;
assert_eq!(error.to_string(), "equilibrium solve was cancelled");
assert_eq!(error.kind(), ReactionExtentErrorKind::Cancelled);
assert!(!error.is_retryable_backend_failure());
assert!(!error.is_non_retryable_input_error());
assert!(error.source().is_none());
}
#[test]
fn temperature_trial_error_preserves_location_source_and_kind() {
let cause = ReactionExtentError::InvalidProblem {
field: "inner",
message: "synthetic endpoint failure".to_string(),
};
let error = ReactionExtentError::TemperatureTrialFailed {
trial_index: 3,
temperature: 812.5,
cause: Box::new(cause),
};
assert!(error.to_string().contains("trial 3"));
assert!(error.to_string().contains("812.5 K"));
assert!(error.source().is_some());
assert_eq!(error.kind(), ReactionExtentErrorKind::Formulation);
assert!(error.is_non_retryable_input_error());
}
}
pub struct LMSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub f: F,
pub jacobian: J,
pub feasible: C,
pub lambda: f64,
pub tol: f64,
pub max_iter: usize,
pub alpha_min: f64,
}
impl<F, J, C> LMSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub fn solve(&mut self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
let n = x.len();
let mut lambda = self.lambda;
for _iter in 0..self.max_iter {
let f_val = timed_native_residual(&self.f, &x).map_err(|error| {
SolveError::EvalError(format!("residual evaluation failed: {error}"))
})?;
info!("Iteration {}, x = {:?}, f = {:?}", _iter, x, f_val);
let f_norm = l2_norm(&f_val);
info!(" ||f|| = {}", f_norm);
if f_norm < self.tol {
return Ok(x);
}
if f_norm.is_nan() || f_norm.is_infinite() {
return Err(SolveError::SingularMatrix);
}
let j = timed_native_jacobian(&self.jacobian, &x).map_err(|error| {
SolveError::EvalError(format!("Jacobian evaluation failed: {error}"))
})?;
info!(" Jacobian:\n{}", j);
if j.nrows() != n || j.ncols() != n {
error!(
"Jacobian nrows = {} ncols = {}, state length = {}",
j.nrows(),
j.ncols(),
n
);
return Err(SolveError::EvalError(
"Jacobian dimension mismatch".to_string(),
));
}
if j.iter().any(|value| !value.is_finite()) {
return Err(SolveError::SingularMatrix);
}
let jt = timed_native_stage(NativeSolverStage::MatrixOperations, || j.transpose());
let mut lhs = timed_native_stage(NativeSolverStage::MatrixOperations, || &jt * &j);
let jtj = &lhs;
info!(" Jᵀ·J:\n{}", jtj);
timed_native_stage(NativeSolverStage::MatrixOperations, || {
for i in 0..n {
lhs[(i, i)] += lambda;
}
});
let rhs = timed_native_stage(NativeSolverStage::MatrixOperations, || {
-(&jt * DVector::from_vec(f_val))
});
let delta_result = timed_native_linear_system(|| lhs.lu().solve(&rhs));
let delta = delta_result.ok_or(SolveError::SingularMatrix)?;
info!(" Step delta: {:?}", delta);
let mut alpha = 1.0;
let mut accepted = false;
while alpha >= self.alpha_min {
let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
x.iter()
.zip(delta.iter())
.map(|(xi, dxi)| xi + alpha * dxi)
.collect()
});
info!(" Trial x (alpha={}): {:?}", alpha, x_trial);
let feasible = timed_native_stage(NativeSolverStage::Feasibility, || {
(self.feasible)(&x_trial)
});
if !feasible {
alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
continue;
}
let f_trial = timed_native_residual(&self.f, &x_trial).map_err(|error| {
SolveError::EvalError(format!("residual evaluation failed: {error}"))
})?;
info!(" Trial f: {:?}", f_trial);
let f_trial_norm = l2_norm(&f_trial);
info!(" ||f_trial|| = {}", f_trial_norm);
if f_trial_norm < f_norm {
x = x_trial;
lambda = timed_native_stage(NativeSolverStage::Globalization, || lambda * 0.3);
accepted = true;
break;
} else {
alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
}
}
if !accepted {
lambda = timed_native_stage(NativeSolverStage::Globalization, || lambda * 10.0);
info!(
" No acceptable step found; increasing lambda to {}",
lambda
);
}
}
Err(SolveError::MaxIterations)
}
}
pub struct NRSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub f: F,
pub jacobian: J,
pub feasible: C,
pub tol: f64,
pub max_iter: usize,
pub alpha_min: f64,
}
impl<F, J, C> NRSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub fn solve(&mut self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
let n = x.len();
for iter in 0..self.max_iter {
let f_val = timed_native_residual(&self.f, &x)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
info!("NR Iteration {}, x = {:?}, f = {:?}", iter, x, f_val);
let f_norm = l2_norm(&f_val);
info!(" ||f|| = {}", f_norm);
if f_norm < self.tol {
return Ok(x);
}
if f_norm.is_nan() || f_norm.is_infinite() {
return Err(SolveError::SingularMatrix);
}
let j = timed_native_jacobian(&self.jacobian, &x)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
info!(" Jacobian:\n{}", j);
if j.nrows() != n || j.ncols() != n {
error!(
"Jacobian nrows = {} ncols ={}, initial guess length {}",
j.nrows(),
j.ncols(),
n
);
return Err(SolveError::EvalError(
"Jacobian dimension mismatch".to_string(),
));
}
let rhs = timed_native_stage(NativeSolverStage::MatrixOperations, || {
-DVector::from_vec(f_val)
});
let delta_result = timed_native_linear_system(|| j.lu().solve(&rhs));
let delta_vec = delta_result.ok_or(SolveError::SingularMatrix)?;
let delta = delta_vec.data.as_vec();
info!(" Step delta: {:?}", delta_vec);
let mut alpha = 1.0;
info!("bounded step {}", alpha);
let mut accepted = false;
while alpha >= self.alpha_min {
let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
x.iter()
.zip(delta.iter())
.map(|(xi, dxi)| xi + alpha * dxi)
.collect()
});
info!(" Trial x (alpha={}): {:?}", alpha, x_trial);
let feasible = timed_native_stage(NativeSolverStage::Feasibility, || {
(self.feasible)(&x_trial)
});
if !feasible {
alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
continue;
}
let f_trial = timed_native_residual(&self.f, &x_trial)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
info!(" Trial f: {:?}", f_trial);
let f_trial_norm = l2_norm(&f_trial);
info!(" ||f_trial|| = {}", f_trial_norm);
if f_trial_norm < f_norm {
x = x_trial;
accepted = true;
break;
}
alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
if !accepted {
info!(" No acceptable step found; continuing to next iteration");
}
}
if !accepted {
error!(
"NR solver exhausted iteration {} without an acceptable step",
iter
);
return Err(SolveError::MaxIterations);
}
}
error!("NR solver reached the iteration limit without convergence");
Err(SolveError::MaxIterations)
}
}
#[inline]
fn timed_native_residual<F>(f: &F, values: &[f64]) -> Result<Vec<f64>, ReactionExtentError>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
{
#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
{
return f(values);
}
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
{
if native_solver_timing_enabled() {
record_native_callback(NativeCallbackKind::Residual, values);
}
let started = native_solver_timing_enabled().then(std::time::Instant::now);
let result = f(values);
if let Some(started) = started {
record_native_residual(started.elapsed());
}
result
}
}
#[inline]
fn timed_native_jacobian<F>(
jacobian: &F,
values: &[f64],
) -> Result<DMatrix<f64>, ReactionExtentError>
where
F: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
{
#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
{
return jacobian(values);
}
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
{
if native_solver_timing_enabled() {
record_native_callback(NativeCallbackKind::Jacobian, values);
}
let started = native_solver_timing_enabled().then(std::time::Instant::now);
let result = jacobian(values);
if let Some(started) = started {
record_native_jacobian(started.elapsed());
}
result
}
}
#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
#[inline]
fn timed_native_linear_system<F, T>(solve: F) -> T
where
F: FnOnce() -> T,
{
solve()
}
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
fn timed_native_linear_system<F, T>(solve: F) -> T
where
F: FnOnce() -> T,
{
let started = std::time::Instant::now();
let result = solve();
record_native_linear_system(started.elapsed());
result
}
#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
#[inline]
fn timed_native_stage<T, F>(_: NativeSolverStage, operation: F) -> T
where
F: FnOnce() -> T,
{
operation()
}
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
#[inline]
fn timed_native_stage<T, F>(stage: NativeSolverStage, operation: F) -> T
where
F: FnOnce() -> T,
{
let started = native_solver_timing_enabled().then(std::time::Instant::now);
let result = operation();
if let Some(started) = started {
record_native_stage(stage, started.elapsed());
}
result
}
fn l2_norm(v: &[f64]) -> f64 {
timed_native_stage(NativeSolverStage::Norm, || {
v.iter().map(|x| x * x).sum::<f64>().sqrt()
})
}
pub struct TrustRegionSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub f: F,
pub jacobian: J,
pub feasible: C,
pub tol: f64,
pub max_iter: usize,
pub delta_init: f64,
pub delta_max: f64,
pub eta: f64, }
impl<F, J, C> TrustRegionSolver<F, J, C>
where
F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
C: Fn(&[f64]) -> bool,
{
pub fn solve(&self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
let n = x.len();
let mut delta = self.delta_init;
for _iter in 0..self.max_iter {
let f_val = timed_native_residual(&self.f, &x)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
if f_val.len() != n {
return Err(SolveError::EvalError("residual dimension mismatch".into()));
}
if f_val.iter().any(|value| !value.is_finite()) {
return Err(SolveError::SingularMatrix);
}
let f_norm = l2_norm(&f_val);
if f_norm < self.tol {
return Ok(x);
}
let J = timed_native_jacobian(&self.jacobian, &x)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
if J.nrows() != n || J.ncols() != n {
error!(
"Trust region Jacobian nrows = {} ncols = {}, state length = {}",
J.nrows(),
J.ncols(),
n
);
return Err(SolveError::EvalError("Jacobian not square".into()));
}
if J.iter().any(|value| !value.is_finite()) {
return Err(SolveError::SingularMatrix);
}
let fvec = timed_native_stage(NativeSolverStage::MatrixOperations, || {
DVector::from_vec(f_val)
});
let g = timed_native_stage(NativeSolverStage::MatrixOperations, || {
&J.transpose() * &fvec
});
let g_norm_sq = timed_native_stage(NativeSolverStage::Norm, || g.dot(&g));
let jg = timed_native_stage(NativeSolverStage::MatrixOperations, || &J * &g);
let jg_norm_sq = timed_native_stage(NativeSolverStage::Norm, || jg.dot(&jg));
let alpha = g_norm_sq / jg_norm_sq.max(1e-16);
let cauchy_step =
timed_native_stage(NativeSolverStage::MatrixOperations, || -alpha * g.clone());
let cauchy_norm = timed_native_stage(NativeSolverStage::Norm, || cauchy_step.norm());
let p = if cauchy_norm >= delta {
timed_native_stage(NativeSolverStage::MatrixOperations, || {
delta / cauchy_norm * cauchy_step
})
} else {
let newton_step_result =
timed_native_linear_system(|| J.clone().lu().solve(&(-&fvec)));
let newton_step = newton_step_result.ok_or(SolveError::SingularMatrix)?;
let newton_norm =
timed_native_stage(NativeSolverStage::Norm, || newton_step.norm());
timed_native_stage(NativeSolverStage::MatrixOperations, || {
if newton_norm <= delta {
newton_step
} else {
let p_u = cauchy_step;
let p_b = newton_step;
let d = &p_b - &p_u;
let a = d.dot(&d);
let b = 2.0 * p_u.dot(&d);
let c = p_u.dot(&p_u) - delta * delta;
let tau = (-b + (b * b - 4.0 * a * c).sqrt()) / (2.0 * a);
p_u + tau * d
}
})
};
let p_norm = timed_native_stage(NativeSolverStage::Norm, || p.norm());
let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
x.iter().zip(p.iter()).map(|(xi, pi)| xi + pi).collect()
});
let feasible =
timed_native_stage(NativeSolverStage::Feasibility, || (self.feasible)(&x_trial));
if !feasible {
timed_native_stage(NativeSolverStage::Globalization, || delta *= 0.25);
continue;
}
let f_trial = timed_native_residual(&self.f, &x_trial)
.map_err(|error| SolveError::EvalError(error.to_string()))?;
if l2_norm(&f_trial) < self.tol {
return Ok(x_trial);
}
let actual_reduction = f_norm.powi(2) - l2_norm(&f_trial).powi(2);
if !actual_reduction.is_finite() {
return Err(SolveError::SingularMatrix);
}
let jacobian_trial =
timed_native_stage(NativeSolverStage::MatrixOperations, || &J * &p);
let linear_model_term = timed_native_stage(NativeSolverStage::Norm, || g.dot(&p));
let quadratic_model_term = timed_native_stage(NativeSolverStage::Norm, || {
jacobian_trial.dot(&jacobian_trial)
});
let model_reduction = -2.0 * linear_model_term - quadratic_model_term;
if !model_reduction.is_finite() || model_reduction <= 0.0 {
timed_native_stage(NativeSolverStage::Globalization, || delta *= 0.25);
continue;
}
let rho = actual_reduction / model_reduction;
timed_native_stage(NativeSolverStage::Globalization, || {
if rho < 0.25 {
delta *= 0.25;
} else if rho > 0.75 && (p_norm - delta).abs() < 1e-12 {
delta = (2.0 * delta).min(self.delta_max);
}
});
if rho > self.eta {
x = x_trial;
}
if delta < 1e-14 {
error!("Trust region solver exhausted the trust radius before convergence");
return Err(SolveError::SingularMatrix);
}
}
error!("Trust region solver reached the iteration limit without convergence");
Err(SolveError::MaxIterations)
}
}
#[derive(Debug, Clone)]
pub struct ReactionBasis {
pub rank: usize,
pub num_reactions: usize,
pub reactions: DMatrix<f64>,
}
pub fn compute_reaction_basis(
a: &DMatrix<f64>,
tol: f64,
) -> Result<ReactionBasis, ReactionExtentError> {
use nalgebra::linalg::SVD;
if !tol.is_finite() || tol <= 0.0 {
return Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_tolerance",
message: "reaction-basis tolerance must be finite and strictly positive".to_string(),
});
}
if a.nrows() == 0 || a.ncols() == 0 {
return Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_matrix",
message: "element composition matrix must have positive dimensions".to_string(),
});
}
if a.iter().any(|value| !value.is_finite()) {
return Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_matrix",
message: "element composition matrix must contain only finite values".to_string(),
});
}
let m = a.nrows();
let at = a.transpose();
let svd = SVD::new(at, true, true);
let v_t = match svd.v_t {
Some(v) => v,
None => {
let msg = "SVD failed: Vᵀ".to_string();
error!("{}", msg);
return Err(ReactionExtentError::SVDError(msg));
}
};
let singular_values = svd.singular_values;
let rank = singular_values.iter().filter(|&&s| s > tol).count();
let num_reactions = if rank <= m { m - rank } else { 0 };
let mut reactions = DMatrix::<f64>::zeros(m, num_reactions);
let p = v_t.nrows();
let mut v_rows: Vec<DVector<f64>> = Vec::new();
for i in 0..p {
v_rows.push(v_t.row(i).transpose());
}
let mut col = 0;
for i in rank..p {
if col >= num_reactions {
break;
}
reactions.set_column(col, &v_rows[i]);
col += 1;
}
if col < num_reactions {
let orth_span: Vec<&DVector<f64>> = v_rows.iter().take(rank).collect();
let mut null_basis: Vec<DVector<f64>> = v_rows[rank..p].to_vec();
for j in 0..m {
if col >= num_reactions {
break;
}
let mut cand = DVector::<f64>::from_element(m, 0.0);
cand[j] = 1.0;
for rvec in &orth_span {
let dot = rvec.dot(&cand);
cand -= *rvec * dot;
}
for u in &null_basis {
let dot = u.dot(&cand);
cand -= u * dot;
}
let norm = cand.norm();
if norm > tol {
let u = cand / norm;
reactions.set_column(col, &u);
null_basis.push(u);
col += 1;
}
}
}
if col != num_reactions {
return Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_nullspace",
message: format!(
"constructed {col} independent nullspace vectors, expected {num_reactions}"
),
});
}
let reactions = -1.0 * reactions;
Ok(ReactionBasis {
rank,
num_reactions,
reactions,
})
}
#[cfg(test)]
mod tests {
fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() < tol
}
use super::*;
#[test]
fn lm_solves_scalar_quadratic() {
let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 2.0]) as Result<Vec<f64>, ReactionExtentError>;
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let mut solver = LMSolver {
f,
jacobian: j,
feasible,
lambda: 1e-3,
tol: 1e-12,
max_iter: 50,
alpha_min: 1e-6,
};
let x0 = vec![1.0];
let sol = solver.solve(x0).unwrap();
assert!(approx_eq(sol[0], 2.0_f64.sqrt(), 1e-8));
}
#[test]
fn lm_solves_2d_nonlinear_system() {
let f = |x: &[f64]| {
Ok(vec![x[0] * x[0] + x[1] * x[1] - 1.0, x[0] - x[1]])
as Result<Vec<f64>, ReactionExtentError>
};
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(
2,
2,
&[2.0 * x[0], 2.0 * x[1], 1.0, -1.0],
)) as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let mut solver = LMSolver {
f,
jacobian: j,
feasible,
lambda: 1e-3,
tol: 1e-12,
max_iter: 50,
alpha_min: 1e-6,
};
let x0 = vec![0.8, 0.3];
let sol = solver.solve(x0).unwrap();
let expected = 1.0 / 2.0_f64.sqrt();
assert!(approx_eq(sol[0], expected, 1e-8));
assert!(approx_eq(sol[1], expected, 1e-8));
}
#[test]
fn lm_respects_feasibility_constraint() {
let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 1.0]) as Result<Vec<f64>, ReactionExtentError>;
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |x: &[f64]| x[0] >= 0.0;
let mut solver = LMSolver {
f,
jacobian: j,
feasible,
lambda: 1e-3,
tol: 1e-12,
max_iter: 50,
alpha_min: 1e-6,
};
let x0 = vec![0.1];
let sol = solver.solve(x0).unwrap();
assert!(approx_eq(sol[0], 1.0, 1e-8));
}
#[test]
fn lm_handles_flat_jacobian() {
let f = |x: &[f64]| Ok(vec![x[0].powi(3)]) as Result<Vec<f64>, ReactionExtentError>;
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(
1,
1,
&[3.0 * x[0] * x[0]],
)) as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let mut solver = LMSolver {
f,
jacobian: j,
feasible,
lambda: 1e-4,
tol: 1e-15,
max_iter: 1000,
alpha_min: 1e-8,
};
let x0 = vec![0.5];
let sol = solver.solve(x0).unwrap();
info!("{:?}", &sol);
assert!(sol[0].abs() < 1e-5);
}
#[test]
fn lm_reports_max_iterations() {
let f = |_x: &[f64]| Ok(vec![1.0]); let j = |_x: &[f64]| Ok(nalgebra::DMatrix::identity(1, 1));
let feasible = |_x: &[f64]| true;
let mut solver = LMSolver {
f,
jacobian: j,
feasible,
lambda: 1e-3,
tol: 1e-12,
max_iter: 5,
alpha_min: 1e-6,
};
let res = solver.solve(vec![0.0]);
assert!(matches!(res, Err(SolveError::MaxIterations)));
}
}
#[cfg(test)]
mod tests_reaction_basis {
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
ReactionExtentError, compute_reaction_basis,
};
use log::info;
use nalgebra::DMatrix;
const TOL: f64 = 1e-10;
#[test]
fn diatomic_dissociation_o2_o() {
let a = DMatrix::from_row_slice(
2,
1,
&[
2.0, 1.0, ],
);
let basis = compute_reaction_basis(&a, TOL).unwrap();
info!("basis: {:?}", basis);
assert_eq!(basis.rank, 1);
assert_eq!(basis.num_reactions, 1);
let residual = a.transpose() * &basis.reactions;
assert!(residual.norm() < 1e-12);
}
#[test]
fn nitrogen_oxygen_system() {
let a = DMatrix::from_row_slice(
4,
2,
&[
2.0, 0.0, 0.0, 2.0, 1.0, 1.0, 1.0, 2.0, ],
);
let basis = compute_reaction_basis(&a, TOL).unwrap();
assert_eq!(basis.rank, 2);
assert_eq!(basis.num_reactions, 2);
let residual = a.transpose() * &basis.reactions;
assert!(residual.norm() < 1e-12);
}
#[test]
fn methane_combustion_species() {
let a = DMatrix::from_row_slice(
4,
3,
&[
1.0, 4.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 2.0, 0.0, 2.0, 1.0, ],
);
let basis = compute_reaction_basis(&a, TOL).unwrap();
assert_eq!(basis.rank, 3);
assert_eq!(basis.num_reactions, 1);
let residual = a.transpose() * &basis.reactions;
assert!(residual.norm() < 1e-12);
}
#[test]
fn reaction_basis_o2_not_zero() {
use nalgebra::DMatrix;
let a = DMatrix::from_row_slice(2, 1, &[2.0, 1.0]);
let rb = compute_reaction_basis(&a, 1e-12).unwrap();
assert_eq!(rb.num_reactions, 1);
let nu = rb.reactions.column(0);
assert!(
nu.iter().any(|&x| x.abs() > 1e-6),
"Reaction vector is zero!"
);
assert!((2.0 * nu[0] + 1.0 * nu[1]).abs() < 1e-10);
}
#[test]
fn rectangular_rank_deficient_basis_has_complete_independent_nullspace() {
let a = DMatrix::from_row_slice(4, 2, &[1.0, 0.0, 2.0, 0.0, 3.0, 0.0, 4.0, 0.0]);
let basis = compute_reaction_basis(&a, 1e-12).unwrap();
assert_eq!(basis.rank, 1);
assert_eq!(basis.num_reactions, 3);
assert!(
(basis.reactions.transpose() * &basis.reactions)
.svd(false, false)
.singular_values
.iter()
.all(|value| *value > 1e-8),
"reaction columns must be independent: {:?}",
basis.reactions
);
assert!((a.transpose() * &basis.reactions).norm() < 1e-10);
}
#[test]
fn reaction_basis_rejects_invalid_matrix_and_rank_tolerances() {
let a = DMatrix::from_row_slice(2, 1, &[2.0, 1.0]);
assert!(matches!(
compute_reaction_basis(&a, 0.0),
Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_tolerance",
..
})
));
assert!(matches!(
compute_reaction_basis(&DMatrix::from_row_slice(1, 1, &[f64::NAN]), 1e-12),
Err(ReactionExtentError::InvalidProblem {
field: "reaction_basis_matrix",
..
})
));
let nearly_dependent = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1e-14]);
assert_eq!(
compute_reaction_basis(&nearly_dependent, 1e-12)
.unwrap()
.rank,
1
);
assert_eq!(
compute_reaction_basis(&nearly_dependent, 1e-16)
.unwrap()
.rank,
2
);
}
}
#[cfg(test)]
mod nr_tests {
use super::*;
use nalgebra::DMatrix;
#[test]
fn nr_solver_respects_bounds_and_converges() {
let f = |x: &[f64]| Ok(vec![x[0]]) as Result<Vec<f64>, ReactionExtentError>;
let j = |_: &[f64]| {
Ok(DMatrix::from_row_slice(1, 1, &[1.0])) as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |x: &[f64]| x[0] >= 0.0;
let mut solver = NRSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 100,
alpha_min: 1e-12,
};
let sol = solver.solve(vec![0.01]).unwrap();
assert!(sol[0] >= 0.0);
assert!(sol[0].abs() < 1e-8);
}
}
#[cfg(test)]
mod trust_region_tests {
use super::*;
use approx::assert_relative_eq;
#[allow(dead_code)]
fn vec_norm(v: &[f64]) -> f64 {
v.iter().map(|x| x * x).sum::<f64>().sqrt()
}
fn approx_eq(a: &[f64], b: &[f64], tol: f64) -> bool {
a.iter().zip(b.iter()).all(|(x, y)| (*x - *y).abs() < tol)
}
#[test]
fn trust_region_linear_system() {
let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> {
Ok(vec![3.0 * x[0] + 1.0 * x[1] - 1.0, 1.0 * x[0] + 2.0 * x[1]])
};
let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
Ok(DMatrix::from_row_slice(2, 2, &[3.0, 1.0, 1.0, 2.0]))
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 10,
delta_init: 1.0,
delta_max: 10.0,
eta: 0.1,
};
let x0 = vec![0.0, 0.0];
let sol = solver.solve(x0).unwrap();
assert!(approx_eq(&sol, &[0.4, -0.2], 1e-10));
}
#[test]
fn trust_region_scalar_nonlinear() {
let f =
|x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![x[0] * x[0] - 2.0]) };
let j = |x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
Ok(DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 50,
delta_init: 0.1, delta_max: 10.0,
eta: 0.1,
};
let sol = solver.solve(vec![0.1]).unwrap();
assert!((sol[0] - 2.0_f64.sqrt()).abs() < 1e-10);
}
#[test]
fn trust_region_ill_conditioned() {
let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> {
Ok(vec![1e6 * x[0] - 1.0, x[1] - 1.0])
};
let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
Ok(DMatrix::from_row_slice(2, 2, &[1e6, 0.0, 0.0, 1.0]))
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 50,
delta_init: 0.01,
delta_max: 1.0,
eta: 0.1,
};
let sol = solver.solve(vec![0.0, 0.0]).unwrap();
assert!((sol[0] - 1e-6).abs() < 1e-10);
assert!((sol[1] - 1.0).abs() < 1e-10);
}
#[test]
fn trust_region_feasibility_constraint() {
let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![x[0] - 1.0]) };
let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
Ok(DMatrix::from_row_slice(1, 1, &[1.0]))
};
let feasible = |x: &[f64]| x[0] >= 0.0;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 50,
delta_init: 10.0,
delta_max: 10.0,
eta: 0.1,
};
let sol = solver.solve(vec![-10.0]).unwrap();
assert!((sol[0] - 1.0).abs() < 1e-10);
}
#[test]
fn trust_region_singular_jacobian() {
let f = |_x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![1.0]) };
let j =
|_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> { Ok(DMatrix::zeros(1, 1)) };
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 5,
delta_init: 1.0,
delta_max: 1.0,
eta: 0.1,
};
let res = solver.solve(vec![0.0]);
assert!(matches!(res, Err(SolveError::SingularMatrix)));
}
#[test]
fn tr_solves_scalar_quadratic() {
let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 2.0]) as Result<Vec<f64>, ReactionExtentError>;
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 50,
delta_init: 0.1,
delta_max: 10.0,
eta: 0.0,
};
let x0 = vec![0.1];
let sol = solver.solve(x0).unwrap();
assert_relative_eq!(sol[0], 2.0_f64.sqrt(), epsilon = 1e-8);
}
#[test]
fn tr_solves_2d_nonlinear_system() {
let f = |x: &[f64]| {
Ok(vec![x[0] * x[0] + x[1] * x[1] - 1.0, x[0] - x[1]])
as Result<Vec<f64>, ReactionExtentError>
};
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(
2,
2,
&[2.0 * x[0], 2.0 * x[1], 1.0, -1.0],
)) as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 1000,
delta_init: 0.1,
delta_max: 10.0,
eta: 0.0,
};
let x0 = vec![0.5, 0.5];
let sol = solver.solve(x0).unwrap();
let expected = 1.0 / 2.0_f64.sqrt();
assert_relative_eq!(sol[0], expected, epsilon = 1e-8);
assert_relative_eq!(sol[1], expected, epsilon = 1e-8);
}
#[test]
fn tr_respects_feasibility_constraint() {
let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 1.0]) as Result<Vec<f64>, ReactionExtentError>;
let j = |x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 50,
delta_init: 1.0,
delta_max: 10.0,
eta: 0.1,
};
let x0 = vec![0.1];
let sol = solver.solve(x0).unwrap();
assert_relative_eq!(sol[0].abs(), 1.0, epsilon = 1e-8);
}
#[test]
fn tr_reports_max_iterations() {
let f = |_x: &[f64]| Ok(vec![1.0]); let j = |_x: &[f64]| Ok(nalgebra::DMatrix::identity(1, 1));
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 5,
delta_init: 1.0,
delta_max: 10.0,
eta: 0.1,
};
let res = solver.solve(vec![0.0]);
assert!(matches!(res, Err(SolveError::MaxIterations)));
}
#[test]
fn tr_reports_jacobian_dimension_mismatch() {
let f = |_x: &[f64]| Ok(vec![1.0]) as Result<Vec<f64>, ReactionExtentError>;
let j = |_x: &[f64]| {
Ok(nalgebra::DMatrix::from_row_slice(1, 2, &[1.0, 0.0]))
as Result<DMatrix<f64>, ReactionExtentError>
};
let feasible = |_x: &[f64]| true;
let solver = TrustRegionSolver {
f,
jacobian: j,
feasible,
tol: 1e-12,
max_iter: 5,
delta_init: 1.0,
delta_max: 10.0,
eta: 0.1,
};
let res = solver.solve(vec![0.0]);
assert!(matches!(res, Err(SolveError::EvalError(_))));
}
}