use crate::Thermodynamics::DBhandlers::NISTdata::NISTdata;
use crate::Thermodynamics::DBhandlers::thermo_api::{ThermoCalculator, ThermoEnum, ThermoError};
use crate::Thermodynamics::DBhandlers::transport_api::{
TransportCalculator, TransportEnum, TransportError,
};
use crate::Thermodynamics::User_substances::{
CalculatorType, DataType, LibraryPriority, Phases, PropertySearchState, SearchResult, SubsData,
TransportCalculationMode, WhatIsFound,
};
use crate::Thermodynamics::DBhandlers::Diffusion::MultiSubstanceDiffusion;
use crate::Thermodynamics::User_substances_error::{SubsDataError, SubsDataResult};
use crate::Thermodynamics::physical_state::NistFallbackPolicy;
use crate::Thermodynamics::thermo_lib_api::{LibraryCapability, ThermoData};
use RustedSciThe::symbolic::symbolic_engine::Expr;
use nalgebra::DMatrix;
use tabled::settings::Style;
use tabled::{Table, Tabled};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq, Tabled)]
pub struct SearchSummaryRow {
#[tabled(rename = "Substance")]
substance: String,
#[tabled(rename = "Property")]
property: String,
#[tabled(rename = "State")]
state: String,
#[tabled(rename = "Library")]
library: String,
#[tabled(rename = "Source record")]
record_key: String,
#[tabled(rename = "Priority")]
priority: String,
#[tabled(rename = "Calculator")]
calculator: String,
}
impl SearchSummaryRow {
pub fn substance(&self) -> &str {
&self.substance
}
pub fn property(&self) -> &str {
&self.property
}
pub fn state(&self) -> &str {
&self.state
}
pub fn library(&self) -> &str {
&self.library
}
pub fn record_key(&self) -> &str {
&self.record_key
}
pub fn priority(&self) -> &str {
&self.priority
}
pub fn calculator(&self) -> &str {
&self.calculator
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SearchSummaryReport {
rows: Vec<SearchSummaryRow>,
total_substances: usize,
priority_found: usize,
permitted_found: usize,
not_found: usize,
}
impl SearchSummaryReport {
pub fn rows(&self) -> &[SearchSummaryRow] {
&self.rows
}
pub fn total_substances(&self) -> usize {
self.total_substances
}
pub fn priority_found(&self) -> usize {
self.priority_found
}
pub fn permitted_found(&self) -> usize {
self.permitted_found
}
pub fn not_found(&self) -> usize {
self.not_found
}
pub fn render_table(&self) -> String {
if self.rows.is_empty() {
return "Search summary: no substances have been resolved yet.".to_string();
}
Table::new(self.rows.clone())
.with(Style::modern_rounded())
.to_string()
}
}
impl SubsData {
fn resolve_composition_and_molar_mass_for_substance(
&self,
substance: &str,
groups: Option<&HashMap<String, HashMap<String, usize>>>,
thermo: Option<&ThermoEnum>,
) -> SubsDataResult<(HashMap<String, f64>, f64)> {
use crate::Kinetics::molmass::{
calculate_molar_mass, calculate_molar_mass_for_composition,
};
if let Some(thermo) = thermo {
if let Ok(Some(composition)) = thermo.get_composition() {
let composition_usize: HashMap<String, usize> = composition
.iter()
.map(|(k, v)| (k.clone(), *v as usize))
.collect();
let molar_mass = calculate_molar_mass_for_composition(composition_usize.clone())
.map_err(|error| {
SubsDataError::calculation_failed_with_source(
substance.to_string(),
"molar mass calculation from composition",
error.to_string(),
error,
)
})?;
let composition = composition
.into_iter()
.map(|(k, v)| (k, v as f64))
.collect();
return Ok((composition, molar_mass));
}
}
let (molar_mass, composition) =
calculate_molar_mass(substance.to_string(), groups.cloned()).map_err(|e| {
SubsDataError::calculation_failed_with_source(
substance.to_string(),
"molar mass calculation",
e.to_string(),
e,
)
})?;
let composition = composition
.into_iter()
.map(|(k, v)| (k, v as f64))
.collect();
Ok((composition, molar_mass))
}
pub fn calculate_elem_composition_and_molar_mass(
&mut self,
groups: Option<HashMap<String, HashMap<String, usize>>>,
) -> SubsDataResult<()> {
let (molar_mass_by_substance, vec_of_compositions, hashset_of_elems) =
Self::calculate_elem_composition_and_molar_mass_local(self, groups)?;
let mut unique_vec_of_elems = hashset_of_elems.into_iter().collect::<Vec<_>>();
unique_vec_of_elems.sort();
let num_rows = unique_vec_of_elems.len();
let num_cols = vec_of_compositions.len();
let mut matrix: DMatrix<f64> = DMatrix::zeros(num_rows, num_cols);
for substance_i in 0..self.substances.len() {
for j in 0..unique_vec_of_elems.len() {
let element_j = unique_vec_of_elems[j].clone();
if let Some(count) = vec_of_compositions[substance_i].get(&element_j) {
matrix[(j, substance_i)] += *count as f64;
}
}
}
self.elem_composition_matrix = Some(matrix.transpose());
self.molar_mass_by_substance = molar_mass_by_substance;
self.unique_elements = unique_vec_of_elems;
Ok(())
}
pub fn calculate_elem_composition_and_molar_mass_local(
sd: &mut SubsData,
groups: Option<HashMap<String, HashMap<String, usize>>>,
) -> SubsDataResult<(
HashMap<String, f64>,
Vec<HashMap<String, f64>>,
HashSet<String>,
)> {
let mut vec_of_compositions: Vec<HashMap<String, f64>> = Vec::new();
let mut hashset_of_elems: HashSet<String> = HashSet::new();
let mut molar_mass_by_substance: HashMap<String, f64> = HashMap::new();
for substance in &sd.substances {
let thermo =
sd.get_substance_search_state(substance)
.and_then(|state| match &state.thermo {
PropertySearchState::Found(SearchResult {
calculator: Some(CalculatorType::Thermo(thermo)),
..
}) => Some(thermo),
_ => None,
});
let (composition, molar_mass) = sd.resolve_composition_and_molar_mass_for_substance(
substance,
groups.as_ref(),
thermo,
)?;
molar_mass_by_substance.insert(substance.clone(), molar_mass);
vec_of_compositions.push(composition.clone());
let elements = composition.keys().map(|el| el.clone()).collect::<Vec<_>>();
hashset_of_elems.extend(elements);
}
Ok((
molar_mass_by_substance,
vec_of_compositions,
hashset_of_elems,
))
}
fn with_transport_calculator<F, R>(&mut self, substance: &str, f: F) -> SubsDataResult<R>
where
F: FnOnce(&mut dyn TransportCalculator) -> Result<R, TransportError>,
{
let search_result =
self.get_canonical_search_result_mut(substance, WhatIsFound::Transport)?;
let calculator = search_result.calculator_mut().ok_or_else(|| {
SubsDataError::CalculatorNotAvailable {
substance: substance.to_string(),
calc_type: "Transport".to_string(),
}
})?;
match calculator {
CalculatorType::Transport(transport) => {
let result: SubsDataResult<R> = f(&mut *transport).map_err(Into::into);
if let Err(ref e) = result {
crate::log_error!(self.logger, e, substance, "with_transport_calculator");
}
result
}
CalculatorType::Thermo(_) => Err(SubsDataError::CalculatorNotAvailable {
substance: substance.to_string(),
calc_type: "Transport (found Thermo instead)".to_string(),
}),
}
}
pub fn extract_transport_coeffs(
&mut self,
substance: &str,
temperature: f64,
) -> SubsDataResult<()> {
if temperature <= 0.0 {
let error = SubsDataError::InvalidTemperature(temperature);
return self.log_and_propagate(Err(error), substance, "extract_transport_coeffs");
}
let result = self.with_transport_calculator(substance, |transport| {
transport.extract_coefficients(temperature)
});
self.log_and_propagate(result, substance, "extract_transport_coeffs")
}
pub fn extract_all_transport_coeffs(&mut self, temperature: f64) -> SubsDataResult<()> {
if temperature <= 0.0 {
return Err(SubsDataError::InvalidTemperature(temperature));
}
for substance in self.substances.clone() {
let result = self.extract_transport_coeffs(&substance, temperature);
self.log_and_propagate(result, &substance, "extract_all_transport_coeffs")?;
}
Ok(())
}
pub fn calculate_transport_properties(
&mut self,
substance: &str,
temperature: f64,
Cp: Option<f64>,
ro: Option<f64>,
) -> SubsDataResult<(f64, f64)> {
let result = self._calculate_transport_properties_internal(substance, temperature, Cp, ro);
self.log_and_propagate(result, substance, "calculate_transport_properties")
}
fn _calculate_transport_properties_internal(
&mut self,
substance: &str,
temperature: f64,
Cp: Option<f64>,
ro: Option<f64>,
) -> SubsDataResult<(f64, f64)> {
if temperature <= 0.0 {
return Err(SubsDataError::InvalidTemperature(temperature));
}
let lib_name = self.get_canonical_search_library(substance, WhatIsFound::Transport)?;
let transport_mode = if lib_name == "CEA" {
TransportCalculationMode::Cea
} else {
let pressure = self.P.ok_or(SubsDataError::PressureNotSet)?;
let molar_mass = *self
.molar_mass_by_substance
.get(substance)
.ok_or_else(|| SubsDataError::MolarMassNotFound(substance.to_string()))?;
TransportCalculationMode::Standard {
pressure,
molar_mass,
pressure_unit: self.P_unit.clone(),
molar_mass_unit: self.Molar_mass_unit.clone(),
}
};
self.with_transport_calculator(substance, |transport| {
if matches!(&transport_mode, TransportCalculationMode::Cea) {
let lambda = transport.calculate_lambda(Cp, ro, temperature)?;
let viscosity = transport.calculate_viscosity(temperature)?;
Ok((lambda, viscosity))
} else if let TransportCalculationMode::Standard {
pressure,
molar_mass,
pressure_unit,
molar_mass_unit,
} = &transport_mode
{
transport.set_M(*molar_mass, molar_mass_unit.clone())?;
transport.set_P(*pressure, pressure_unit.clone())?;
let lambda = transport.calculate_lambda(Cp, ro, temperature)?;
let viscosity = transport.calculate_viscosity(temperature)?;
Ok((lambda, viscosity))
} else {
unreachable!("transport_mode is fully covered by the CEA and standard branches")
}
})
}
fn calculate_single_transport_properties(
&mut self,
substance: &str,
temperature: f64,
) -> SubsDataResult<HashMap<DataType, Option<f64>>> {
let Cp = self
.therm_value_state(substance, DataType::Cp)
.value()
.copied()
.ok_or_else(|| SubsDataError::HeatCapacityNotAvailable(substance.to_string()))?;
let ro = self
.ro_map
.as_ref()
.and_then(|ro_map| ro_map.get(substance).cloned());
let (lambda, visc) =
self._calculate_transport_properties_internal(substance, temperature, Some(Cp), ro)?;
let mut property_map = HashMap::new();
property_map.insert(DataType::Lambda, Some(lambda));
property_map.insert(DataType::Visc, Some(visc));
Ok(property_map)
}
pub fn calculate_transport_map_of_properties(
&mut self,
temperature: f64,
) -> SubsDataResult<()> {
let mut temp_map = HashMap::new();
for substance in self.substances.clone() {
let result = self.calculate_single_transport_properties(&substance, temperature);
let properties = self.log_and_propagate(
result,
&substance,
"calculate_transport_map_of_properties",
)?;
temp_map.insert(substance, properties);
}
self.transport_map_of_properties_values = temp_map;
Ok(())
}
fn calculate_single_transport_symbolic(
&mut self,
substance: &str,
) -> SubsDataResult<HashMap<DataType, Option<Box<Expr>>>> {
let Cp = self
.therm_symbolic_state(substance, DataType::Cp_sym)
.value()
.cloned()
.ok_or_else(|| SubsDataError::HeatCapacityNotAvailable(substance.to_string()))?;
let P = self.P.ok_or(SubsDataError::PressureNotSet)?;
let M = *self
.molar_mass_by_substance
.get(substance)
.ok_or_else(|| SubsDataError::MolarMassNotFound(substance.to_string()))?;
let P_unit = self.P_unit.clone();
let M_unit = self.Molar_mass_unit.clone();
let ro_expr = if let Some(ro_map) = &self.ro_map_sym {
ro_map.get(substance).map(|v| *v.clone())
} else {
Some(
RustedSciThe::symbolic::symbolic_engine::Expr::Const(P * M / 8.314)
/ RustedSciThe::symbolic::symbolic_engine::Expr::Var("T".to_string()),
)
};
self.with_transport_calculator(substance, |transport| {
transport.set_M(M, M_unit)?;
transport.set_P(P, P_unit)?;
transport.create_symbolic_lambda(Some(Cp), ro_expr)?;
transport.create_symbolic_viscosity()?;
let mut sym_map = HashMap::new();
sym_map.insert(
DataType::Lambda_sym,
transport.get_lambda_sym().ok().map(Box::new),
);
sym_map.insert(
DataType::Visc_sym,
transport.get_viscosity_sym().ok().map(Box::new),
);
Ok(sym_map)
})
}
pub fn calculate_transport_map_of_sym(&mut self) -> SubsDataResult<()> {
if self.therm_map_of_sym.is_empty() {
return Err(SubsDataError::HeatCapacityNotAvailable(
"therm_map_of_sym is empty - call calculate_therm_map_of_sym first".to_string(),
));
}
let mut temp_map = HashMap::new();
for substance in self.substances.clone() {
let result = self.calculate_single_transport_symbolic(&substance);
let properties =
self.log_and_propagate(result, &substance, "calculate_transport_map_of_sym")?;
temp_map.insert(substance, properties);
}
self.transport_map_of_sym = temp_map;
Ok(())
}
fn calculate_single_transport_functions(
&mut self,
substance: &str,
) -> SubsDataResult<HashMap<DataType, Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>>> {
let Cp = match self.therm_value_state(substance, DataType::Cp).value() {
Some(cp) => *cp,
None => {
let temperature = self.T.ok_or(SubsDataError::TemperatureNotSet)?;
let (cp, _, _) = self.calculate_thermo_properties(substance, temperature)?;
cp
}
};
let P = self.P.ok_or(SubsDataError::PressureNotSet)?;
let M = *self
.molar_mass_by_substance
.get(substance)
.ok_or_else(|| SubsDataError::MolarMassNotFound(substance.to_string()))?;
let P_unit = self.P_unit.clone();
let M_unit = self.Molar_mass_unit.clone();
let T = self.T.ok_or(SubsDataError::TemperatureNotSet)?;
let ro = self
.ro_map
.as_ref()
.and_then(|ro_map| ro_map.get(substance).cloned());
let ro_value = ro.unwrap_or_else(|| P * M / (8.314 * T));
self.with_transport_calculator(substance, |transport| {
transport.set_M(M, M_unit)?;
transport.set_P(P, P_unit)?;
let _ = transport.create_lambda_closure(Some(Cp), Some(ro_value))?;
let _ = transport.create_viscosity_closure()?;
let mut function_map = HashMap::new();
function_map.insert(DataType::Lambda_fun, transport.get_lambda_fun().ok());
function_map.insert(DataType::Visc_fun, transport.get_viscosity_fun().ok());
Ok(function_map)
})
}
pub fn calculate_transport_map_of_functions(&mut self) -> SubsDataResult<()> {
let mut temp_map = HashMap::new();
for substance in self.substances.clone() {
let result = self.calculate_single_transport_functions(&substance);
let properties =
self.log_and_propagate(result, &substance, "calculate_transport_map_of_functions")?;
temp_map.insert(substance, properties);
}
self.transport_map_of_fun = temp_map;
Ok(())
}
pub fn initialize_diffusion_data(&mut self) -> SubsDataResult<()> {
let T = self.T.ok_or(SubsDataError::TemperatureNotSet)?;
let P = self.P.ok_or(SubsDataError::PressureNotSet)?;
let mut multi_diff = MultiSubstanceDiffusion::new(T, P)?;
let mut transport_data_map = HashMap::new();
let M_unit = self.Molar_mass_unit.clone();
let P_unit = self.P_unit.clone();
for substance in &self.substances.clone() {
let M = *self
.molar_mass_by_substance
.get(substance)
.ok_or_else(|| SubsDataError::MolarMassNotFound(substance.to_string()))?;
let result = self.with_transport_calculator(substance, |transport| {
transport.set_M(M, M_unit.clone())?;
transport.set_P(P, P_unit.clone())?;
Ok(())
});
match result {
Ok(_) => {
if let Some(search_result) =
self.get_canonical_search_result(substance, WhatIsFound::Transport)
{
if let Some(CalculatorType::Transport(TransportEnum::Collision(
transport_data,
))) = search_result.calculator()
{
transport_data_map.insert(substance.clone(), transport_data.clone());
}
}
}
Err(_) => {
return Err(SubsDataError::CalculatorNotAvailable {
substance: substance.to_string(),
calc_type: "Transport".to_string(),
});
}
}
}
multi_diff.substances = transport_data_map;
multi_diff.substance_names = self.substances.clone();
self.diffusion_data = Some(multi_diff);
Ok(())
}
pub fn with_diffusion_calculator<F, R>(&mut self, f: F) -> SubsDataResult<R>
where
F: FnOnce(&mut MultiSubstanceDiffusion) -> R,
{
let diffusion_data =
self.diffusion_data
.as_mut()
.ok_or_else(|| SubsDataError::CalculatorNotAvailable {
substance: "diffusion_data".to_string(),
calc_type: "Diffusion".to_string(),
})?;
Ok(f(diffusion_data))
}
pub fn calculate_all_pairs(&mut self) -> SubsDataResult<()> {
self.with_diffusion_calculator(|diff| {
diff.calculate_all_pairs().map_err(SubsDataError::from)
})??;
Ok(())
}
pub fn calculate_all_closures(&mut self) -> SubsDataResult<()> {
self.with_diffusion_calculator(|diff| {
diff.calculate_all_closures().map_err(SubsDataError::from)
})??;
Ok(())
}
pub fn calculate_all_symbolic(&mut self) -> SubsDataResult<()> {
self.with_diffusion_calculator(|diff| {
diff.calculate_all_symbolic().map_err(SubsDataError::from)
})??;
Ok(())
}
pub fn create_diffusion_matrix(&mut self) -> SubsDataResult<Vec<Vec<f64>>> {
self.with_diffusion_calculator(|diff| {
diff.create_diffusion_matrix().map_err(SubsDataError::from)
})?
.map_err(Into::into)
}
pub fn search_summary_report(&self) -> SearchSummaryReport {
let mut rows = Vec::new();
let mut substances = self.search_states.keys().cloned().collect::<Vec<_>>();
substances.sort();
for substance in substances {
if let Some(state) = self.search_states.get(&substance) {
if state.is_missing() {
rows.push(SearchSummaryRow {
substance: substance.clone(),
property: "Thermo/Transport".to_string(),
state: "Missing".to_string(),
library: "-".to_string(),
record_key: "-".to_string(),
priority: "-".to_string(),
calculator: "-".to_string(),
});
continue;
}
for (property_name, property_state) in
[("Thermo", state.thermo()), ("Transport", state.transport())]
{
let row = match property_state {
PropertySearchState::NotSearched => SearchSummaryRow {
substance: substance.clone(),
property: property_name.to_string(),
state: "Pending".to_string(),
library: "-".to_string(),
record_key: "-".to_string(),
priority: "-".to_string(),
calculator: "-".to_string(),
},
PropertySearchState::Missing => SearchSummaryRow {
substance: substance.clone(),
property: property_name.to_string(),
state: "Missing".to_string(),
library: "-".to_string(),
record_key: "-".to_string(),
priority: "-".to_string(),
calculator: "-".to_string(),
},
PropertySearchState::Failed(message) => SearchSummaryRow {
substance: substance.clone(),
property: property_name.to_string(),
state: format!("Failed: {}", message),
library: "-".to_string(),
record_key: "-".to_string(),
priority: "-".to_string(),
calculator: "-".to_string(),
},
PropertySearchState::NistFallbackFailed(message) => SearchSummaryRow {
substance: substance.clone(),
property: property_name.to_string(),
state: format!("NIST fallback failed: {}", message.message()),
library: "-".to_string(),
record_key: "-".to_string(),
priority: "-".to_string(),
calculator: "-".to_string(),
},
PropertySearchState::Found(result) => SearchSummaryRow {
substance: substance.clone(),
property: property_name.to_string(),
state: "Found".to_string(),
library: result.library().to_string(),
record_key: result.record_key().to_string(),
priority: match result.priority_type() {
LibraryPriority::Priority => "Priority".to_string(),
LibraryPriority::Permitted => "Permitted".to_string(),
LibraryPriority::Explicit => "Explicit".to_string(),
},
calculator: match result.calculator() {
Some(CalculatorType::Thermo(_)) => "Thermo".to_string(),
Some(CalculatorType::Transport(_)) => "Transport".to_string(),
None => "None".to_string(),
},
},
};
rows.push(row);
}
}
}
SearchSummaryReport {
rows,
total_substances: self.substances.len(),
priority_found: self.get_priority_found_substances().len(),
permitted_found: self.get_permitted_found_substances().len(),
not_found: self.get_not_found_substances().len(),
}
}
pub fn resolve_search_and_report(&mut self) -> SubsDataResult<SearchSummaryReport> {
self.search_substances()?;
Ok(self.search_summary_report())
}
pub fn search_substances_with_nist_fallback(
&mut self,
policy: NistFallbackPolicy,
) -> SubsDataResult<()> {
self.search_substances()?;
self.if_not_found_go_nist(policy)
}
pub fn print_search_summary(&self) {
let report = self.search_summary_report();
println!("\nSearch Results Summary:");
println!("{}", report.render_table());
println!(
"\nStatistics: total={}, priority_found={}, permitted_found={}, not_found={}",
report.total_substances(),
report.priority_found(),
report.permitted_found(),
report.not_found()
);
}
#[deprecated(
note = "legacy gas-default fallback; use if_not_found_go_nist(NistFallbackPolicy::ExactRequestedState) for phase-aware code"
)]
pub fn if_not_found_go_NIST(&mut self) -> SubsDataResult<()> {
self.if_not_found_go_nist(NistFallbackPolicy::LegacyGasDefault)
}
pub fn if_not_found_go_nist(&mut self, policy: NistFallbackPolicy) -> SubsDataResult<()> {
use crate::Thermodynamics::DBhandlers::NIST_parser::SearchType;
self.if_not_found_go_nist_with(policy, |substance, phase| {
let mut nist = NISTdata::new();
nist.renew_base(substance.to_string(), SearchType::All, phase)?;
Ok(nist)
})
}
fn if_not_found_go_nist_with<F>(
&mut self,
policy: NistFallbackPolicy,
mut retrieve: F,
) -> SubsDataResult<()>
where
F: FnMut(
&str,
crate::Thermodynamics::DBhandlers::NIST_parser::Phase,
) -> Result<NISTdata, ThermoError>,
{
use crate::Thermodynamics::DBhandlers::NIST_parser::Phase;
if matches!(policy, NistFallbackPolicy::Disabled) {
return Ok(());
}
let not_found_substances = self.thermochemistry_fallback_candidates();
if not_found_substances.is_empty() {
return Ok(());
}
let has_thermo_lookup = self.library_priorities.keys().any(|library| {
matches!(
ThermoData::library_capability(library),
Some(LibraryCapability::Thermo)
)
}) || self
.explicit_search_instructions
.values()
.any(|library| ThermoData::canonical_library_name(library) == "NIST");
if !has_thermo_lookup {
let reason = "no thermodynamic libraries are enabled for NIST fallback".to_string();
let substance = not_found_substances
.first()
.cloned()
.unwrap_or_else(|| "unknown".to_string());
return Err(SubsDataError::nist_retrieval_failed(substance, reason));
}
let mut first_error: Option<SubsDataError> = None;
let mut found_any = false;
for substance in not_found_substances {
if self
.explicit_search_instructions
.get(&substance)
.is_some_and(|library| ThermoData::canonical_library_name(library) != "NIST")
{
continue;
}
let requested_state = match policy {
NistFallbackPolicy::ExactRequestedState => {
self.substance_physical_state(&substance)
}
NistFallbackPolicy::LegacyGasDefault => self
.substance_physical_state(&substance)
.or_else(|| self.map_of_phases.get(&substance).and_then(|state| *state)),
NistFallbackPolicy::Disabled => unreachable!("disabled policy returned early"),
};
let phase = match (policy, requested_state) {
(_, Some(Phases::Gas)) => Phase::Gas,
(_, Some(Phases::Solid)) => Phase::Solid,
(_, Some(Phases::Liquid)) => Phase::Liquid,
(NistFallbackPolicy::LegacyGasDefault, None)
| (NistFallbackPolicy::LegacyGasDefault, Some(Phases::Condensed)) => Phase::Gas,
(NistFallbackPolicy::ExactRequestedState, None)
| (NistFallbackPolicy::ExactRequestedState, Some(Phases::Condensed)) => {
let reason = "exact physical-state NIST fallback requires an explicit gas, liquid, or solid requirement";
self.mark_thermo_fallback_failed(
&substance,
SubsDataError::nist_retrieval_failed(substance.clone(), reason),
);
if first_error.is_none() {
first_error = Some(SubsDataError::nist_retrieval_failed(
substance.clone(),
reason,
));
}
continue;
}
(NistFallbackPolicy::Disabled, _) => {
unreachable!("disabled policy returned early")
}
};
match retrieve(&substance, phase) {
Ok(thermo) => {
found_any = true;
self.store_search_result(
&substance,
WhatIsFound::Thermo,
"NIST".to_string(),
LibraryPriority::Permitted,
serde_json::Value::Null,
CalculatorType::Thermo(ThermoEnum::NIST(thermo)),
true,
);
}
Err(source) => {
let source = Arc::new(source);
let reason = source.to_string();
let state_error = SubsDataError::nist_retrieval_failed_with_source(
substance.clone(),
reason.clone(),
Arc::clone(&source),
);
self.mark_thermo_fallback_failed(&substance, state_error);
if first_error.is_none() {
first_error = Some(SubsDataError::nist_retrieval_failed_with_source(
substance.clone(),
reason,
source,
));
}
}
}
}
if found_any {
Ok(())
} else {
Err(first_error.unwrap_or_else(|| {
SubsDataError::nist_retrieval_failed(
"unknown",
"NIST fallback failed for every unresolved substance",
)
}))
}
}
fn mark_thermo_fallback_failed(&mut self, substance: &str, error: SubsDataError) {
let state = self
.search_states
.entry(substance.to_string())
.or_insert_with(crate::Thermodynamics::User_substances::SubstanceSearchState::new);
state.mark_nist_fallback_failed(WhatIsFound::Thermo, error);
self.sync_search_state_view(substance);
}
fn thermochemistry_fallback_candidates(&self) -> Vec<String> {
let mut candidates = self.get_missing_substances_for(WhatIsFound::Thermo);
candidates.extend(self.search_states.iter().filter_map(|(substance, state)| {
state
.thermo()
.is_nist_fallback_failed()
.then(|| substance.clone())
}));
candidates.sort();
candidates.dedup();
candidates
}
}
#[cfg(test)]
mod nist_fallback_tests {
use super::*;
use crate::Thermodynamics::DBhandlers::NIST_parser::Phase;
use crate::Thermodynamics::User_substances::Phases;
use serde_json::json;
use std::error::Error;
fn local_nist_fixture() -> NISTdata {
let mut data = NISTdata::new();
data.from_serde(json!({
"T": [[200.0, 6000.0]],
"cp": [[30.0, 1.0, 0.0, 0.0, 0.0, -10.0, 20.0, 0.0]],
"dh": 0.0,
"ds": 0.0,
"molar_mass": 28.0
}))
.expect("local Shomate fixture should deserialize");
data.parse_coefficients()
.expect("local Shomate fixture should parse");
data
}
#[test]
fn live_nist_fallback_resolves_co_gas_from_webbook() {
let mut data = SubsData::new();
data.substances = vec!["CO".into()];
data.set_library_priority("NASA_gas".into(), LibraryPriority::Priority);
data.set_substance_physical_state("CO".into(), Phases::Gas);
data.insert_not_found_if_absent("CO");
data.if_not_found_go_nist(NistFallbackPolicy::ExactRequestedState)
.expect("live NIST fallback should retrieve CO gas thermochemistry");
let state = data
.get_substance_search_state("CO")
.expect("fallback records a per-substance search state");
let result = state
.result(WhatIsFound::Thermo)
.expect("successful live lookup publishes thermochemistry");
assert_eq!(result.library(), "NIST");
assert_eq!(result.record_key(), "CO");
let Some(CalculatorType::Thermo(ThermoEnum::NIST(nist))) = result.calculator() else {
panic!("NIST fallback should publish an initialized NIST calculator");
};
let intervals = nist
.input
.T
.as_ref()
.expect("WebBook gas data should include temperature ranges");
assert!(!intervals.is_empty());
assert!(intervals.iter().all(|range| {
range.len() == 2 && range.iter().all(|temperature| temperature.is_finite())
}));
assert!(
nist.input
.cp
.as_ref()
.is_some_and(|coefficients| !coefficients.is_empty())
);
assert!(nist.input.dh.is_some());
assert!(nist.input.ds.is_some());
}
#[test]
fn injected_fallback_records_mixed_outcomes_without_network_access() {
let mut data = SubsData::new();
data.substances = vec![
"Xe".into(),
"CO".into(),
"SolidCase".into(),
"Condensed".into(),
"Pinned".into(),
"AlreadyFound".into(),
];
data.set_library_priority("NASA_gas".into(), LibraryPriority::Priority);
data.set_substance_physical_state("CO".into(), Phases::Gas);
data.set_substance_physical_state("Xe".into(), Phases::Liquid);
data.set_substance_physical_state("SolidCase".into(), Phases::Solid);
data.set_substance_physical_state("Condensed".into(), Phases::Condensed);
data.explicit_search_instructions
.insert("Pinned".into(), "NASA_gas".into());
for substance in ["CO", "Xe", "SolidCase", "Condensed", "Pinned"] {
data.insert_not_found_if_absent(substance);
}
data.store_search_result(
"AlreadyFound",
WhatIsFound::Thermo,
"NIST".into(),
LibraryPriority::Permitted,
serde_json::Value::Null,
CalculatorType::Thermo(ThermoEnum::NIST(local_nist_fixture())),
true,
);
let mut calls = Vec::new();
data.if_not_found_go_nist_with(NistFallbackPolicy::ExactRequestedState, |name, phase| {
calls.push((name.to_string(), phase));
if matches!(name, "CO" | "SolidCase") {
Ok(local_nist_fixture())
} else {
Err(ThermoError::CalculationError(
"fixture retrieval failure".into(),
))
}
})
.expect("one successful record preserves the existing partial-success contract");
assert_eq!(calls.len(), 3);
assert!(calls.contains(&("CO".into(), Phase::Gas)));
assert!(calls.contains(&("Xe".into(), Phase::Liquid)));
assert!(calls.contains(&("SolidCase".into(), Phase::Solid)));
assert!(!calls.iter().any(|(name, _)| name == "Pinned"));
assert!(!calls.iter().any(|(name, _)| name == "Condensed"));
assert!(!calls.iter().any(|(name, _)| name == "AlreadyFound"));
let co = data.get_substance_search_state("CO").unwrap();
assert!(matches!(
co.thermo(),
PropertySearchState::Found(result) if result.library() == "NIST"
));
let solid = data.get_substance_search_state("SolidCase").unwrap();
assert!(matches!(
solid.thermo(),
PropertySearchState::Found(result) if result.library() == "NIST"
));
let xe = data.get_substance_search_state("Xe").unwrap();
assert!(xe.thermo().is_nist_fallback_failed());
assert!(xe.failure(WhatIsFound::Thermo).is_some_and(|message| {
message.contains("Xe") && message.contains("fixture retrieval failure")
}));
let typed_xe_error = xe
.nist_fallback_error(WhatIsFound::Thermo)
.expect("mixed-outcome state retains the typed retrieval failure");
assert!(matches!(
typed_xe_error,
SubsDataError::NistRetrievalFailed { substance, .. } if substance == "Xe"
));
assert!(
typed_xe_error
.source()
.is_some_and(|source| source.to_string().contains("fixture retrieval failure"))
);
let condensed = data.get_substance_search_state("Condensed").unwrap();
assert!(condensed.thermo().is_nist_fallback_failed());
assert!(
condensed.failure(WhatIsFound::Thermo).is_some_and(
|message| message.contains("requires an explicit gas, liquid, or solid")
)
);
let pinned = data.get_substance_search_state("Pinned").unwrap();
assert!(pinned.thermo().is_missing());
assert_eq!(
data.get_missing_substances_for(WhatIsFound::Thermo),
vec!["Pinned".to_string()]
);
let preparation_error = data
.calculate_dG0_fun_one_phase()
.err()
.expect("partial fallback must not build a complete Gibbs input");
assert!(matches!(
preparation_error,
SubsDataError::CalculatorNotAvailable { substance, calc_type }
if substance == "Xe" && calc_type == "Thermo"
));
let mut retry_calls = Vec::new();
data.if_not_found_go_nist_with(NistFallbackPolicy::ExactRequestedState, |name, phase| {
retry_calls.push((name.to_string(), phase));
Ok(local_nist_fixture())
})
.expect("a failed fallback record remains retryable");
assert_eq!(retry_calls, vec![("Xe".into(), Phase::Liquid)]);
let xe = data.get_substance_search_state("Xe").unwrap();
assert!(matches!(
xe.thermo(),
PropertySearchState::Found(result) if result.library() == "NIST"
));
}
#[test]
fn injected_all_failure_preserves_typed_source_without_network_access() {
use std::error::Error;
let mut data = SubsData::new();
data.substances = vec!["CO".into()];
data.set_library_priority("NASA_gas".into(), LibraryPriority::Priority);
data.set_substance_physical_state("CO".into(), Phases::Gas);
data.insert_not_found_if_absent("CO");
let error = data
.if_not_found_go_nist_with(NistFallbackPolicy::ExactRequestedState, |_, _| {
Err(ThermoError::CalculationError(
"injected retrieval failure".into(),
))
})
.expect_err("all failed retrievals should return a typed error");
let source = error.source().expect("fallback error keeps its source");
assert!(error.to_string().contains("Failed to retrieve NIST data"));
assert!(source.to_string().contains("injected retrieval failure"));
let state = data.get_substance_search_state("CO").unwrap();
assert!(state.thermo().is_nist_fallback_failed());
}
}