use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnalysisResultRecord {
pub id: String,
pub kind: AnalysisResultKind,
pub source_experiment_id: Option<String>,
#[serde(default)]
pub source_experiment_ids: Vec<String>,
#[serde(default)]
pub source_experiments: Vec<AnalysisSourceRef>,
pub parent_result_ids: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnalysisSourceRef {
pub experiment_identity: String,
pub experiment_id_snapshot: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AnalysisResultKind {
ParameterSet(ParameterSetRecord),
ArrheniusFit(ArrheniusFitRecord),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CoefficientValue {
pub name: String,
#[serde(default)]
pub role: Option<String>,
#[serde(default)]
pub stage: Option<String>,
pub value: f64,
pub unit: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnalysisRange {
pub axis: String,
pub start: f64,
pub end: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParameterSetRecord {
pub method: String,
pub model: String,
pub formula: Option<String>,
pub solver: Option<String>,
#[serde(default)]
pub x_column: Option<String>,
#[serde(default)]
pub y_column: Option<String>,
#[serde(default)]
pub x_unit: Option<String>,
#[serde(default)]
pub y_unit: Option<String>,
pub range: Option<AnalysisRange>,
#[serde(default)]
pub excluded_range: Option<AnalysisRange>,
#[serde(default)]
pub conditions: Vec<CoefficientValue>,
#[serde(default)]
pub settings: Vec<(String, String)>,
pub diagnostics: Vec<(String, f64, String)>,
pub coefficients: Vec<CoefficientValue>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArrheniusFitRecord {
pub parent_fit_ids: Vec<String>,
#[serde(default)]
pub coefficient_name: String,
#[serde(default)]
pub coefficient_stage: Option<String>,
#[serde(default)]
pub physical_stage_label: String,
#[serde(default)]
pub selected_components: Vec<ArrheniusComponentSelection>,
pub activation_energy_j_per_mol: f64,
#[serde(default)]
pub ln_pre_exponential: Option<f64>,
#[serde(default)]
pub pre_exponential_per_second: Option<f64>,
#[serde(default)]
pub pre_exponential_status: Option<ArrheniusPreExponentialStatus>,
#[serde(default)]
pub residual_degrees_of_freedom: Option<usize>,
#[serde(default)]
pub r_squared_log_space: Option<f64>,
#[serde(default)]
pub r_squared_status: Option<ArrheniusRSquaredStatus>,
pub points: Vec<ArrheniusPoint>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArrheniusComponentSelection {
pub fit_result_id: String,
pub coefficient_name: String,
#[serde(default)]
pub coefficient_stage: Option<String>,
pub source_rate_value: f64,
pub source_rate_unit: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ArrheniusPreExponentialStatus {
Representable,
Underflow,
Overflow,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ArrheniusRSquaredStatus {
Defined,
UndefinedConstantLogRate,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArrheniusPoint {
pub fit_result_id: String,
#[serde(default)]
pub experiment_identity: String,
pub experiment_id: String,
pub temperature_kelvin: f64,
pub rate_per_second: f64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AnalysisResultCatalog {
records: Vec<AnalysisResultRecord>,
next_id: u64,
}
pub const GAS_CONSTANT_J_PER_MOL_K: f64 = 8.314_462_618_153_24;
fn generated_result_id_number(id: &str) -> Option<u64> {
id.strip_prefix("result-")?.parse().ok()
}
pub fn coefficient_table_csv(catalog: &AnalysisResultCatalog) -> String {
fn cell(value: &str) -> String {
if value
.chars()
.any(|ch| matches!(ch, ',' | '"' | '\n' | '\r'))
{
format!("\"{}\"", value.replace('"', "\"\""))
} else {
value.to_string()
}
}
let mut csv = String::from(
"result_id,source_experiments,source_identities,method,model,formula,solver,range_axis,range_start,range_end,excluded_axis,excluded_start,excluded_end,stage,coefficient,role,value,unit,conditions,settings,diagnostics\n",
);
for record in catalog.records() {
let source = if record.source_experiment_ids.is_empty() {
match &record.kind {
AnalysisResultKind::ArrheniusFit(fit) => fit
.points
.iter()
.map(|point| point.experiment_id.as_str())
.collect::<Vec<_>>()
.join("; "),
_ => record.source_experiment_id.clone().unwrap_or_default(),
}
} else {
record.source_experiment_ids.join("; ")
};
let source_identities = record
.source_experiments
.iter()
.map(|source| {
format!(
"{}@{}",
source.experiment_identity, source.experiment_id_snapshot
)
})
.collect::<Vec<_>>()
.join("; ");
let (
method,
model,
formula,
solver,
range,
excluded_range,
conditions,
settings,
diagnostics,
coefficients,
) = match &record.kind {
AnalysisResultKind::ParameterSet(set) => (
set.method.clone(),
set.model.clone(),
set.formula.clone(),
set.solver.clone(),
set.range.as_ref().map(|r| (r.axis.clone(), r.start, r.end)),
set.excluded_range
.as_ref()
.map(|r| (r.axis.clone(), r.start, r.end)),
set.conditions
.iter()
.map(|c| format!("{}={} {}", c.name, c.value, c.unit))
.collect::<Vec<_>>()
.join("; "),
set.settings
.iter()
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>()
.join("; "),
set.diagnostics
.iter()
.map(|(name, value, unit)| format!("{name}={value} {unit}"))
.collect::<Vec<_>>()
.join("; "),
set.coefficients.clone(),
),
AnalysisResultKind::ArrheniusFit(fit) => (
"Arrhenius regression".into(),
format!(
"ln({}) vs 1/T",
if fit.selected_components.is_empty() {
if fit.coefficient_name.is_empty() {
"k"
} else {
fit.coefficient_name.as_str()
}
} else {
"k"
}
),
Some(format!(
"ln({}) = ln(A) - Ea/(R*T)",
if fit.selected_components.is_empty() && !fit.coefficient_name.is_empty() {
fit.coefficient_name.as_str()
} else {
"k"
}
)),
Some("OLS".into()),
None,
None,
fit.points
.iter()
.map(|point| {
format!(
"{}: T={} K, k={} s^-1, component={}",
point.experiment_id,
point.temperature_kelvin,
point.rate_per_second,
fit.selected_components
.iter()
.find(|component| component.fit_result_id == point.fit_result_id)
.map(|component| format!(
"{}{} ({} {})",
component.coefficient_name,
component
.coefficient_stage
.as_deref()
.map(|stage| format!(" [{stage}]"))
.unwrap_or_default(),
component.source_rate_value,
component.source_rate_unit
))
.unwrap_or_else(|| fit.coefficient_name.clone())
)
})
.collect::<Vec<_>>()
.join("; "),
if fit.selected_components.is_empty() {
format!(
"coefficient={}{}",
if fit.coefficient_name.is_empty() {
"unspecified"
} else {
&fit.coefficient_name
},
fit.coefficient_stage
.as_ref()
.map(|stage| format!("; stage={stage}"))
.unwrap_or_default()
)
} else {
format!(
"physical_stage={}; legacy_coefficient={}{}; selected_components={}",
if fit.physical_stage_label.is_empty() {
"unspecified"
} else {
&fit.physical_stage_label
},
if fit.coefficient_name.is_empty() {
"unspecified"
} else {
&fit.coefficient_name
},
fit.coefficient_stage
.as_ref()
.map(|stage| format!("; stage={stage}"))
.unwrap_or_default(),
fit.selected_components
.iter()
.map(|component| format!(
"{}:{}[{}] {} {}",
component.fit_result_id,
component.coefficient_name,
component
.coefficient_stage
.as_deref()
.unwrap_or("un-staged"),
component.source_rate_value,
component.source_rate_unit
))
.collect::<Vec<_>>()
.join("; ")
)
},
format!(
"R2(log k)={}; R2_status={:?}; residual_dof={}; ln(A)={}; A_status={:?}",
fit.r_squared_log_space
.map_or_else(|| "undefined".into(), |v| v.to_string()),
fit.r_squared_status,
fit.residual_degrees_of_freedom
.map_or_else(|| "unknown".into(), |v| v.to_string()),
fit.ln_pre_exponential
.map_or_else(|| "unknown".into(), |v| v.to_string()),
fit.pre_exponential_status
),
vec![
Some(CoefficientValue {
name: "Ea".into(),
role: Some("activation energy".into()),
stage: None,
value: fit.activation_energy_j_per_mol,
unit: "J/mol".into(),
}),
fit.ln_pre_exponential.map(|value| CoefficientValue {
name: "ln(A)".into(),
role: Some("log pre-exponential factor".into()),
stage: None,
value,
unit: "ln(s^-1)".into(),
}),
fit.pre_exponential_per_second
.map(|value| CoefficientValue {
name: "A".into(),
role: Some("pre-exponential factor".into()),
stage: None,
value,
unit: "s^-1".into(),
}),
]
.into_iter()
.flatten()
.collect(),
),
};
for coefficient in coefficients {
let (axis, start, end) = range
.as_ref()
.map(|(axis, a, b)| (axis.as_str(), a.to_string(), b.to_string()))
.unwrap_or(("", String::new(), String::new()));
let (excluded_axis, excluded_start, excluded_end) = excluded_range
.as_ref()
.map(|(axis, a, b)| (axis.as_str(), a.to_string(), b.to_string()))
.unwrap_or(("", String::new(), String::new()));
let fields = [
record.id.clone(),
source.clone(),
source_identities.clone(),
method.clone(),
model.clone(),
formula.clone().unwrap_or_default(),
solver.clone().unwrap_or_default(),
axis.to_string(),
start,
end,
excluded_axis.to_string(),
excluded_start,
excluded_end,
coefficient.stage.unwrap_or_default(),
coefficient.name,
coefficient.role.unwrap_or_default(),
coefficient.value.to_string(),
coefficient.unit,
conditions.clone(),
settings.clone(),
diagnostics.clone(),
];
csv.push_str(
&fields
.iter()
.map(|field| cell(field))
.collect::<Vec<_>>()
.join(","),
);
csv.push('\n');
}
}
csv
}
pub fn fit_arrhenius(
parent_fit_ids: Vec<String>,
points: Vec<ArrheniusPoint>,
) -> Result<ArrheniusFitRecord, String> {
if points.len() < 2 || points.len() != parent_fit_ids.len() {
return Err("Arrhenius fit requires at least two selected rate results".into());
}
let parent_ids = parent_fit_ids
.iter()
.collect::<std::collections::HashSet<_>>();
let point_ids = points
.iter()
.map(|point| &point.fit_result_id)
.collect::<std::collections::HashSet<_>>();
if parent_ids.len() != parent_fit_ids.len() || parent_ids != point_ids {
return Err("Arrhenius points must refer one-to-one to the selected fit results".into());
}
let unique_experiments = points
.iter()
.map(|point| {
if point.experiment_identity.is_empty() {
format!("legacy:{}", point.experiment_id)
} else {
point.experiment_identity.clone()
}
})
.collect::<std::collections::HashSet<_>>();
if unique_experiments.len() != points.len() {
return Err("Arrhenius selection must contain at most one result per experiment".into());
}
if points.iter().any(|p| {
!p.temperature_kelvin.is_finite()
|| p.temperature_kelvin <= 0.0
|| !p.rate_per_second.is_finite()
|| p.rate_per_second <= 0.0
}) {
return Err("Arrhenius inputs require finite positive temperature and rate".into());
}
let x: Vec<f64> = points.iter().map(|p| 1.0 / p.temperature_kelvin).collect();
let y: Vec<f64> = points.iter().map(|p| p.rate_per_second.ln()).collect();
let x_mean = x.iter().sum::<f64>() / x.len() as f64;
let y_mean = y.iter().sum::<f64>() / y.len() as f64;
let sxx = x.iter().map(|v| (v - x_mean).powi(2)).sum::<f64>();
if !sxx.is_finite() || sxx <= f64::EPSILON * x_mean.abs().max(1.0).powi(2) {
return Err("Arrhenius fit requires distinct temperatures".into());
}
let slope = x
.iter()
.zip(&y)
.map(|(a, b)| (a - x_mean) * (b - y_mean))
.sum::<f64>()
/ sxx;
let intercept = y_mean - slope * x_mean;
let residual = x
.iter()
.zip(&y)
.map(|(a, b)| (b - (intercept + slope * a)).powi(2))
.sum::<f64>();
let total = y.iter().map(|v| (v - y_mean).powi(2)).sum::<f64>();
let r_squared_is_defined = total > f64::EPSILON * y_mean.abs().max(1.0).powi(2);
let r_squared = if !r_squared_is_defined {
None
} else {
Some(1.0 - residual / total)
};
let activation_energy_j_per_mol = -slope * GAS_CONSTANT_J_PER_MOL_K;
if !activation_energy_j_per_mol.is_finite() || !intercept.is_finite() {
return Err("Arrhenius regression produced non-finite Ea or ln(A)".into());
}
let exponentiated = intercept.exp();
let (pre_exponential_per_second, pre_exponential_status) = if exponentiated == 0.0 {
(None, ArrheniusPreExponentialStatus::Underflow)
} else if !exponentiated.is_finite() {
(None, ArrheniusPreExponentialStatus::Overflow)
} else {
(
Some(exponentiated),
ArrheniusPreExponentialStatus::Representable,
)
};
Ok(ArrheniusFitRecord {
parent_fit_ids,
coefficient_name: String::new(),
coefficient_stage: None,
physical_stage_label: String::new(),
selected_components: Vec::new(),
activation_energy_j_per_mol,
ln_pre_exponential: Some(intercept),
pre_exponential_per_second,
pre_exponential_status: Some(pre_exponential_status),
residual_degrees_of_freedom: Some(points.len() - 2),
r_squared_log_space: r_squared,
r_squared_status: Some(if r_squared_is_defined {
ArrheniusRSquaredStatus::Defined
} else {
ArrheniusRSquaredStatus::UndefinedConstantLogRate
}),
points,
})
}
impl AnalysisResultCatalog {
pub fn records(&self) -> &[AnalysisResultRecord] {
&self.records
}
pub fn insert(&mut self, mut record: AnalysisResultRecord) -> Result<String, String> {
if record.id.is_empty() {
self.next_id = self
.next_id
.checked_add(1)
.ok_or("analysis result ID exhausted")?;
record.id = format!("result-{}", self.next_id);
}
if self.records.iter().any(|existing| existing.id == record.id) {
return Err(format!("analysis result ID '{}' already exists", record.id));
}
let id = record.id.clone();
if let Some(number) = generated_result_id_number(&id) {
self.next_id = self.next_id.max(number);
}
self.records.push(record);
Ok(id)
}
pub fn get(&self, id: &str) -> Option<&AnalysisResultRecord> {
self.records.iter().find(|record| record.id == id)
}
pub fn validate_parent_links(&self) -> Result<(), String> {
for record in &self.records {
for parent in &record.parent_result_ids {
if self.get(parent).is_none() {
return Err(format!(
"analysis result '{}' references missing parent '{}'",
record.id, parent
));
}
}
if let AnalysisResultKind::ArrheniusFit(fit) = &record.kind {
let parent_ids = fit
.parent_fit_ids
.iter()
.collect::<std::collections::HashSet<_>>();
let point_ids = fit
.points
.iter()
.map(|point| &point.fit_result_id)
.collect::<std::collections::HashSet<_>>();
let result_parent_ids = record
.parent_result_ids
.iter()
.collect::<std::collections::HashSet<_>>();
if parent_ids.len() != fit.parent_fit_ids.len()
|| point_ids.len() != fit.points.len()
|| parent_ids != point_ids
|| parent_ids != result_parent_ids
{
return Err(format!(
"Arrhenius result '{}' has inconsistent parent fit and point references",
record.id
));
}
for parent in &fit.parent_fit_ids {
let parent_record = self.get(parent).ok_or_else(|| {
format!(
"Arrhenius result '{}' references missing fit result '{}'",
record.id, parent
)
})?;
let AnalysisResultKind::ParameterSet(parent_fit) = &parent_record.kind else {
return Err(format!(
"Arrhenius result '{}' parent '{}' is not a parameter fit",
record.id, parent
));
};
let point = fit
.points
.iter()
.find(|point| &point.fit_result_id == parent)
.ok_or_else(|| {
format!(
"Arrhenius result '{}' has no point for parent fit '{}'",
record.id, parent
)
})?;
let selected_component = fit
.selected_components
.iter()
.find(|component| component.fit_result_id == *parent);
if !fit.selected_components.is_empty() {
let selected_ids = fit
.selected_components
.iter()
.map(|component| &component.fit_result_id)
.collect::<std::collections::HashSet<_>>();
if fit.selected_components.len() != fit.points.len()
|| selected_ids.len() != fit.selected_components.len()
|| selected_ids != parent_ids
{
return Err(format!(
"Arrhenius result '{}' must store one selected component per point",
record.id
));
}
if fit.physical_stage_label.trim().is_empty() {
return Err(format!(
"Arrhenius result '{}' has component mapping but no physical stage label",
record.id
));
}
let component = selected_component.ok_or_else(|| {
format!(
"Arrhenius result '{}' has no selected component for parent '{}'",
record.id, parent
)
})?;
if !parent_fit.coefficients.iter().any(|coefficient| {
coefficient.name == component.coefficient_name
&& coefficient.stage == component.coefficient_stage
&& coefficient.role.as_deref() == Some("rate constant")
&& coefficient.value == component.source_rate_value
&& coefficient.unit == component.source_rate_unit
}) {
return Err(format!(
"Arrhenius result '{}' references missing rate coefficient '{}' at stage {:?} in parent '{}'",
record.id, component.coefficient_name, component.coefficient_stage, parent
));
}
let factor = match component.source_rate_unit.as_str() {
"s^-1" => 1.0,
"min^-1" => 1.0 / 60.0,
"h^-1" => 1.0 / 3600.0,
_ => 0.0,
};
let expected_rate = component.source_rate_value * factor;
let tolerance = f64::EPSILON * expected_rate.abs().max(1.0) * 8.0;
if factor == 0.0
|| !component.source_rate_value.is_finite()
|| component.source_rate_value <= 0.0
|| (point.rate_per_second - expected_rate).abs() > tolerance
{
return Err(format!(
"Arrhenius result '{}' has inconsistent source and normalized rates for parent '{}'",
record.id, parent
));
}
} else if !fit.coefficient_name.trim().is_empty()
&& !parent_fit.coefficients.iter().any(|coefficient| {
coefficient.name == fit.coefficient_name
&& coefficient.stage == fit.coefficient_stage
&& coefficient.role.as_deref() == Some("rate constant")
})
{
return Err(format!(
"Arrhenius result '{}' references missing rate coefficient '{}' at stage {:?} in parent '{}'",
record.id, fit.coefficient_name, fit.coefficient_stage, parent
));
}
}
}
}
Ok(())
}
pub fn merge_from(&mut self, incoming: &Self) -> Result<(), String> {
self.validate_parent_links()?;
incoming.validate_parent_links()?;
let mut merged = self.clone();
if let Some(max_incoming_id) = incoming
.records
.iter()
.filter_map(|record| generated_result_id_number(&record.id))
.max()
{
merged.next_id = merged.next_id.max(max_incoming_id);
}
let mut id_map = std::collections::HashMap::with_capacity(incoming.records.len());
let mut reserved: std::collections::HashSet<String> =
merged.records.iter().map(|r| r.id.clone()).collect();
for record in &incoming.records {
let mut new_id = record.id.clone();
if reserved.contains(&new_id) {
loop {
merged.next_id = merged
.next_id
.checked_add(1)
.ok_or("analysis result ID exhausted")?;
new_id = format!("result-{}", merged.next_id);
if !reserved.contains(&new_id) {
break;
}
}
}
reserved.insert(new_id.clone());
id_map.insert(record.id.clone(), new_id);
}
let mut additions = Vec::with_capacity(incoming.records.len());
for record in &incoming.records {
let mut record = record.clone();
record.id = id_map
.get(&record.id)
.cloned()
.ok_or("missing result ID mapping")?;
for parent in &mut record.parent_result_ids {
*parent = id_map
.get(parent)
.cloned()
.ok_or_else(|| format!("missing result ID mapping for parent '{parent}'"))?;
}
if let AnalysisResultKind::ArrheniusFit(fit) = &mut record.kind {
for parent in &mut fit.parent_fit_ids {
*parent = id_map
.get(parent)
.cloned()
.ok_or_else(|| format!("missing result ID mapping for fit '{parent}'"))?;
}
for point in &mut fit.points {
point.fit_result_id =
id_map.get(&point.fit_result_id).cloned().ok_or_else(|| {
format!(
"missing result ID mapping for Arrhenius point fit '{}'",
point.fit_result_id
)
})?;
}
for component in &mut fit.selected_components {
component.fit_result_id = id_map
.get(&component.fit_result_id)
.cloned()
.ok_or_else(|| {
format!(
"missing result ID mapping for selected Arrhenius component '{}'",
component.fit_result_id
)
})?;
}
}
additions.push(record);
}
merged.records.extend(additions);
merged.validate_parent_links()?;
*self = merged;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> AnalysisResultRecord {
AnalysisResultRecord {
id: String::new(),
source_experiment_id: Some("iso-500K".into()),
source_experiment_ids: vec!["iso-500K".into()],
source_experiments: vec![AnalysisSourceRef {
experiment_identity: "source-uuid".into(),
experiment_id_snapshot: "iso-500K".into(),
}],
parent_result_ids: vec![],
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "Curve fit".into(),
model: "DecExp".into(),
formula: Some("a*exp(-k*x)".into()),
solver: Some("VarPro".into()),
x_column: Some("time".into()),
y_column: Some("conversion".into()),
x_unit: Some("h".into()),
y_unit: Some("1".into()),
range: Some(AnalysisRange {
axis: "time".into(),
start: 0.0,
end: 2.0,
}),
excluded_range: None,
conditions: vec![],
settings: vec![("tolerance".into(), "1e-8".into())],
diagnostics: vec![("R2".into(), 0.99, "1".into())],
coefficients: vec![CoefficientValue {
name: "k".into(),
role: Some("rate constant".into()),
stage: None,
value: 0.4,
unit: "h^-1".into(),
}],
}),
}
}
#[test]
fn generated_ids_are_stable_and_duplicates_are_rejected() {
let mut catalog = AnalysisResultCatalog::default();
let id = catalog.insert(sample()).unwrap();
assert_eq!(id, "result-1");
assert!(catalog.get(&id).is_some());
let duplicate = AnalysisResultRecord {
id: id.clone(),
..sample()
};
assert!(catalog.insert(duplicate).is_err());
assert_eq!(catalog.records().len(), 1);
}
#[test]
fn explicit_sparse_generated_ids_advance_the_next_id() {
let mut catalog = AnalysisResultCatalog::default();
catalog
.insert(AnalysisResultRecord {
id: "result-27".into(),
..sample()
})
.unwrap();
assert_eq!(catalog.insert(sample()).unwrap(), "result-28");
}
#[test]
fn merge_advances_id_counter_past_non_colliding_imported_ids() {
let mut destination = AnalysisResultCatalog::default();
destination.insert(sample()).unwrap();
let mut incoming = AnalysisResultCatalog::default();
incoming
.insert(AnalysisResultRecord {
id: "result-42".into(),
..sample()
})
.unwrap();
destination.merge_from(&incoming).unwrap();
assert_eq!(destination.insert(sample()).unwrap(), "result-43");
}
#[test]
fn catalog_roundtrips_as_typed_json() {
let mut catalog = AnalysisResultCatalog::default();
catalog.insert(sample()).unwrap();
let json = serde_json::to_string(&catalog).unwrap();
let restored: AnalysisResultCatalog = serde_json::from_str(&json).unwrap();
assert_eq!(catalog, restored);
}
#[test]
fn arrhenius_fit_recovers_known_parameters_and_is_order_independent() {
let ea = 82_000.0;
let a = 2.5e7;
let temperatures = [450.0, 500.0, 560.0, 620.0];
let build = |order: &[usize]| {
let points = order
.iter()
.map(|&i| {
let t = temperatures[i];
ArrheniusPoint {
fit_result_id: format!("fit-{i}"),
experiment_identity: format!("uuid-{i}"),
experiment_id: format!("exp-{i}"),
temperature_kelvin: t,
rate_per_second: a * (-ea / (GAS_CONSTANT_J_PER_MOL_K * t)).exp(),
}
})
.collect::<Vec<_>>();
fit_arrhenius(order.iter().map(|i| format!("fit-{i}")).collect(), points).unwrap()
};
let forward = build(&[0, 1, 2, 3]);
let reverse = build(&[3, 2, 1, 0]);
assert!((forward.activation_energy_j_per_mol - ea).abs() < 1e-7);
assert!((forward.pre_exponential_per_second.unwrap() / a - 1.0).abs() < 1e-9);
assert!((forward.r_squared_log_space.unwrap() - 1.0).abs() < 1e-12);
assert!(
(reverse.activation_energy_j_per_mol - forward.activation_energy_j_per_mol).abs()
< 1e-8
);
}
#[test]
fn arrhenius_fit_rejects_duplicate_temperatures_and_invalid_rates() {
let point = ArrheniusPoint {
fit_result_id: "f".into(),
experiment_identity: "uuid-e".into(),
experiment_id: "e".into(),
temperature_kelvin: 500.0,
rate_per_second: 1.0,
};
let duplicate_temperature = ArrheniusPoint {
experiment_id: "e2".into(),
experiment_identity: "uuid-e2".into(),
fit_result_id: "f2".into(),
..point.clone()
};
assert!(fit_arrhenius(
vec!["f".into(), "f2".into()],
vec![point.clone(), duplicate_temperature]
)
.unwrap_err()
.contains("distinct temperatures"));
let invalid = ArrheniusPoint {
experiment_id: "e2".into(),
experiment_identity: "uuid-e2".into(),
fit_result_id: "f2".into(),
rate_per_second: 0.0,
..point.clone()
};
assert!(
fit_arrhenius(vec!["f".into(), "f2".into()], vec![point, invalid])
.unwrap_err()
.contains("positive")
);
}
#[test]
fn arrhenius_reports_zero_residual_degrees_of_freedom_for_two_temperatures() {
let points = vec![
ArrheniusPoint {
fit_result_id: "fit-500".into(),
experiment_identity: "uuid-500".into(),
experiment_id: "500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.1,
},
ArrheniusPoint {
fit_result_id: "fit-600".into(),
experiment_identity: "uuid-600".into(),
experiment_id: "600K".into(),
temperature_kelvin: 600.0,
rate_per_second: 0.2,
},
];
let fit = fit_arrhenius(vec!["fit-500".into(), "fit-600".into()], points).unwrap();
assert_eq!(fit.residual_degrees_of_freedom, Some(0));
assert_eq!(fit.r_squared_log_space, Some(1.0));
}
#[test]
fn constant_log_rate_has_undefined_r_squared() {
let points = [450.0, 500.0, 600.0]
.into_iter()
.enumerate()
.map(|(i, temperature)| ArrheniusPoint {
fit_result_id: format!("fit-{i}"),
experiment_identity: format!("uuid-{i}"),
experiment_id: format!("{temperature}K"),
temperature_kelvin: temperature,
rate_per_second: 0.25,
})
.collect();
let fit =
fit_arrhenius(vec!["fit-0".into(), "fit-1".into(), "fit-2".into()], points).unwrap();
assert_eq!(fit.r_squared_log_space, None);
assert_eq!(fit.residual_degrees_of_freedom, Some(1));
assert!(fit.ln_pre_exponential.unwrap().is_finite());
}
#[test]
fn arrhenius_retains_ln_a_and_distinguishes_exp_underflow_from_overflow() {
let make_points = |rates: [f64; 2]| {
[500.0, 600.0]
.into_iter()
.zip(rates)
.enumerate()
.map(|(i, (temperature, rate))| ArrheniusPoint {
fit_result_id: format!("fit-{i}"),
experiment_identity: format!("uuid-{i}"),
experiment_id: format!("{temperature}K"),
temperature_kelvin: temperature,
rate_per_second: rate,
})
.collect::<Vec<_>>()
};
let ids = vec!["fit-0".into(), "fit-1".into()];
let underflow = fit_arrhenius(
ids.clone(),
make_points([(-10.0_f64).exp(), (-200.0_f64).exp()]),
)
.unwrap();
assert!(underflow.ln_pre_exponential.unwrap() < -745.0);
assert_eq!(underflow.pre_exponential_per_second, None);
assert_eq!(
underflow.pre_exponential_status,
Some(ArrheniusPreExponentialStatus::Underflow)
);
let overflow =
fit_arrhenius(ids, make_points([(-200.0_f64).exp(), (-10.0_f64).exp()])).unwrap();
assert!(overflow.ln_pre_exponential.unwrap() > f64::MAX.ln());
assert_eq!(overflow.pre_exponential_per_second, None);
assert_eq!(
overflow.pre_exponential_status,
Some(ArrheniusPreExponentialStatus::Overflow)
);
}
#[test]
fn old_arrhenius_json_without_new_diagnostics_loads_without_fabricated_values() {
let legacy = serde_json::json!({
"parent_fit_ids": [],
"activation_energy_j_per_mol": 80000.0,
"pre_exponential_per_second": 1000000.0,
"r_squared_log_space": 0.99,
"points": []
});
let fit: ArrheniusFitRecord = serde_json::from_value(legacy).unwrap();
assert_eq!(fit.ln_pre_exponential, None);
assert_eq!(fit.residual_degrees_of_freedom, None);
assert_eq!(fit.pre_exponential_per_second, Some(1.0e6));
assert_eq!(fit.r_squared_log_space, Some(0.99));
}
#[test]
fn arrhenius_fit_rejects_alternative_results_from_the_same_experiment() {
let points = vec![
ArrheniusPoint {
fit_result_id: "fit-a".into(),
experiment_identity: "uuid-1".into(),
experiment_id: "exp-1".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.01,
},
ArrheniusPoint {
fit_result_id: "fit-b".into(),
experiment_identity: "uuid-1".into(),
experiment_id: "exp-1".into(),
temperature_kelvin: 600.0,
rate_per_second: 0.1,
},
];
let error = fit_arrhenius(vec!["fit-a".into(), "fit-b".into()], points).unwrap_err();
assert!(error.contains("one result per experiment"));
}
#[test]
fn arrhenius_uses_immutable_identity_not_reusable_display_id() {
let points = vec![
ArrheniusPoint {
fit_result_id: "fit-a".into(),
experiment_identity: "uuid-a".into(),
experiment_id: "run".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.01,
},
ArrheniusPoint {
fit_result_id: "fit-b".into(),
experiment_identity: "uuid-b".into(),
experiment_id: "run".into(),
temperature_kelvin: 600.0,
rate_per_second: 0.1,
},
];
assert!(fit_arrhenius(vec!["fit-a".into(), "fit-b".into()], points).is_ok());
}
#[test]
fn merge_remaps_colliding_ids_and_keeps_parent_links() {
let mut imported = AnalysisResultCatalog::default();
let parent_id = imported.insert(sample()).unwrap();
imported
.insert(AnalysisResultRecord {
id: "child".into(),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec![parent_id.clone()],
kind: AnalysisResultKind::ArrheniusFit(ArrheniusFitRecord {
parent_fit_ids: vec![parent_id.clone()],
coefficient_name: "k".into(),
coefficient_stage: None,
physical_stage_label: String::new(),
selected_components: vec![],
activation_energy_j_per_mol: 80_000.0,
ln_pre_exponential: Some(1.0e6_f64.ln()),
pre_exponential_per_second: Some(1.0e6),
pre_exponential_status: Some(ArrheniusPreExponentialStatus::Representable),
residual_degrees_of_freedom: Some(0),
r_squared_log_space: Some(1.0),
r_squared_status: Some(ArrheniusRSquaredStatus::Defined),
points: vec![ArrheniusPoint {
fit_result_id: parent_id,
experiment_identity: "source-uuid".into(),
experiment_id: "iso-500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.1,
}],
}),
})
.unwrap();
let mut destination = AnalysisResultCatalog::default();
let collision = destination.insert(sample()).unwrap();
assert_eq!(collision, "result-1");
destination.merge_from(&imported).unwrap();
destination.validate_parent_links().unwrap();
assert_eq!(destination.records().len(), 3);
let child = destination.get("child").unwrap();
let remapped_parent = &child.parent_result_ids[0];
assert_ne!(remapped_parent, &collision);
assert!(destination.get(remapped_parent).is_some());
let AnalysisResultKind::ArrheniusFit(fit) = &child.kind else {
panic!("expected the merged child to remain an Arrhenius record");
};
assert_eq!(fit.parent_fit_ids, vec![remapped_parent.clone()]);
assert_eq!(fit.points[0].fit_result_id, *remapped_parent);
}
#[test]
fn merge_rejects_missing_nested_arrhenius_fit_links_atomically() {
let mut incoming = AnalysisResultCatalog::default();
incoming.insert(sample()).unwrap();
incoming
.insert(AnalysisResultRecord {
id: "arr-child".into(),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec!["result-1".into()],
kind: AnalysisResultKind::ArrheniusFit(ArrheniusFitRecord {
parent_fit_ids: vec!["missing-fit".into()],
coefficient_name: "k".into(),
coefficient_stage: None,
physical_stage_label: String::new(),
selected_components: vec![],
activation_energy_j_per_mol: 80_000.0,
ln_pre_exponential: Some(1.0e6_f64.ln()),
pre_exponential_per_second: Some(1.0e6),
pre_exponential_status: Some(ArrheniusPreExponentialStatus::Representable),
residual_degrees_of_freedom: Some(0),
r_squared_log_space: Some(1.0),
r_squared_status: Some(ArrheniusRSquaredStatus::Defined),
points: vec![ArrheniusPoint {
fit_result_id: "missing-fit".into(),
experiment_identity: "source-uuid".into(),
experiment_id: "iso-500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.1,
}],
}),
})
.unwrap();
let mut destination = AnalysisResultCatalog::default();
destination.insert(sample()).unwrap();
let before = destination.clone();
assert!(destination.merge_from(&incoming).is_err());
assert_eq!(destination, before);
}
#[test]
fn arrhenius_catalog_requires_the_selected_coefficient_and_stage_in_every_parent_fit() {
let mut catalog = AnalysisResultCatalog::default();
let parent_id = catalog.insert(sample()).unwrap();
catalog
.insert(AnalysisResultRecord {
id: "arr-stage-mismatch".into(),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec![parent_id.clone()],
kind: AnalysisResultKind::ArrheniusFit(ArrheniusFitRecord {
parent_fit_ids: vec![parent_id.clone()],
coefficient_name: "k".into(),
coefficient_stage: Some("component 2".into()),
physical_stage_label: String::new(),
selected_components: vec![],
activation_energy_j_per_mol: 80_000.0,
ln_pre_exponential: Some(1.0e6_f64.ln()),
pre_exponential_per_second: Some(1.0e6),
pre_exponential_status: Some(ArrheniusPreExponentialStatus::Representable),
residual_degrees_of_freedom: Some(0),
r_squared_log_space: Some(1.0),
r_squared_status: Some(ArrheniusRSquaredStatus::Defined),
points: vec![ArrheniusPoint {
fit_result_id: parent_id,
experiment_identity: "source-uuid".into(),
experiment_id: "iso-500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.1,
}],
}),
})
.unwrap();
let error = catalog.validate_parent_links().unwrap_err();
assert!(error.contains("missing rate coefficient 'k'"));
assert!(error.contains("component 2"));
}
#[test]
fn arrhenius_catalog_preserves_explicit_cross_fit_component_mapping() {
let mut catalog = AnalysisResultCatalog::default();
let first_id = catalog.insert(sample()).unwrap();
let mut second = sample();
second.source_experiment_id = Some("iso-600K".into());
second.source_experiment_ids = vec!["iso-600K".into()];
second.source_experiments[0].experiment_identity = "source-uuid-600".into();
second.source_experiments[0].experiment_id_snapshot = "iso-600K".into();
if let AnalysisResultKind::ParameterSet(fit) = &mut second.kind {
let rate = &mut fit.coefficients[0];
rate.name = "lambda".into();
rate.stage = Some("component 2".into());
rate.value = 24.0;
rate.unit = "min^-1".into();
}
let second_id = catalog.insert(second).unwrap();
let mut fit = fit_arrhenius(
vec![first_id.clone(), second_id.clone()],
vec![
ArrheniusPoint {
fit_result_id: first_id.clone(),
experiment_identity: "source-uuid".into(),
experiment_id: "iso-500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.4 / 3600.0,
},
ArrheniusPoint {
fit_result_id: second_id.clone(),
experiment_identity: "source-uuid-600".into(),
experiment_id: "iso-600K".into(),
temperature_kelvin: 600.0,
rate_per_second: 24.0 / 60.0,
},
],
)
.unwrap();
fit.physical_stage_label = "slow reaction step".into();
fit.selected_components = vec![
ArrheniusComponentSelection {
fit_result_id: first_id.clone(),
coefficient_name: "k".into(),
coefficient_stage: None,
source_rate_value: 0.4,
source_rate_unit: "h^-1".into(),
},
ArrheniusComponentSelection {
fit_result_id: second_id.clone(),
coefficient_name: "lambda".into(),
coefficient_stage: Some("component 2".into()),
source_rate_value: 24.0,
source_rate_unit: "min^-1".into(),
},
];
catalog
.insert(AnalysisResultRecord {
id: String::new(),
kind: AnalysisResultKind::ArrheniusFit(fit),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec![first_id, second_id],
})
.unwrap();
catalog.validate_parent_links().unwrap();
let mut malformed = catalog.clone();
let AnalysisResultKind::ArrheniusFit(fit) = &mut malformed.records.last_mut().unwrap().kind
else {
panic!("expected Arrhenius fit")
};
fit.selected_components[1].coefficient_name = "not-a-parent-coefficient".into();
assert!(malformed
.validate_parent_links()
.unwrap_err()
.contains("references missing rate coefficient"));
let json = serde_json::to_string(&catalog).unwrap();
let restored: AnalysisResultCatalog = serde_json::from_str(&json).unwrap();
let AnalysisResultKind::ArrheniusFit(restored_fit) =
&restored.get("result-3").unwrap().kind
else {
panic!("expected restored Arrhenius result")
};
assert_eq!(restored_fit.physical_stage_label, "slow reaction step");
assert_eq!(
restored_fit.selected_components[1].coefficient_name,
"lambda"
);
let csv = coefficient_table_csv(&restored);
assert!(csv.contains("slow reaction step"));
assert!(csv.contains("lambda [component 2]"));
}
#[test]
fn merge_rejects_broken_parent_links_without_partial_changes() {
let mut destination = AnalysisResultCatalog::default();
destination.insert(sample()).unwrap();
let before = destination.clone();
let malformed = AnalysisResultCatalog {
records: vec![AnalysisResultRecord {
id: "orphan".into(),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec!["missing".into()],
kind: sample().kind,
}],
next_id: 0,
};
assert!(destination.merge_from(&malformed).is_err());
assert_eq!(destination, before);
}
#[test]
fn one_parameter_result_can_link_many_experiments_and_keep_many_coefficients() {
let record = AnalysisResultRecord {
id: "combined-1".into(),
source_experiment_id: None,
source_experiment_ids: vec!["beta-1".into(), "beta-2".into(), "beta-3".into()],
source_experiments: vec![],
parent_result_ids: vec![],
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "Combined kinetic analysis".into(),
model: "f(alpha)=alpha^m(1-alpha)^n".into(),
formula: None,
solver: Some("grid search".into()),
x_column: None,
y_column: None,
x_unit: None,
y_unit: None,
range: Some(AnalysisRange {
axis: "conversion".into(),
start: 0.1,
end: 0.8,
}),
excluded_range: None,
conditions: vec![],
settings: vec![],
diagnostics: vec![("R2".into(), 0.98, "1".into())],
coefficients: vec![
CoefficientValue {
name: "m".into(),
role: Some("reaction order".into()),
stage: None,
value: 0.7,
unit: "1".into(),
},
CoefficientValue {
name: "n".into(),
role: Some("reaction order".into()),
stage: None,
value: 1.2,
unit: "1".into(),
},
],
}),
};
let json = serde_json::to_string(&record).unwrap();
let restored: AnalysisResultRecord = serde_json::from_str(&json).unwrap();
assert_eq!(restored, record);
assert_eq!(restored.source_experiment_ids.len(), 3);
let AnalysisResultKind::ParameterSet(set) = restored.kind else {
panic!("expected generic parameter set")
};
assert_eq!(
set.coefficients
.iter()
.map(|c| c.name.as_str())
.collect::<Vec<_>>(),
["m", "n"]
);
}
#[test]
fn coefficient_csv_is_flat_and_quotes_delimited_metadata() {
let mut catalog = AnalysisResultCatalog::default();
let mut record = sample();
if let AnalysisResultKind::ParameterSet(fit) = &mut record.kind {
fit.formula = Some("a, b * exp(-k*x)".into());
fit.coefficients.push(CoefficientValue {
name: "a".into(),
role: Some("amplitude".into()),
stage: Some("stage 1".into()),
value: 2.0,
unit: "mg".into(),
});
}
catalog.insert(record).unwrap();
let csv = coefficient_table_csv(&catalog);
assert!(csv.starts_with("result_id,source_experiments,source_identities,method,model,"));
assert!(csv.contains("source-uuid@iso-500K"));
assert_eq!(
csv.lines().count(),
3,
"one header plus two coefficient rows"
);
assert!(csv.contains("\"a, b * exp(-k*x)\""));
assert!(csv.contains(",VarPro,"));
assert!(csv.contains("stage 1,a,amplitude,2"));
assert!(csv.contains("tolerance=1e-8"));
}
#[test]
fn arrhenius_coefficient_csv_includes_parent_experiment_conditions() {
let mut catalog = AnalysisResultCatalog::default();
catalog
.insert(AnalysisResultRecord {
id: "arr-1".into(),
source_experiment_id: None,
source_experiment_ids: vec![],
source_experiments: vec![],
parent_result_ids: vec!["fit-1".into(), "fit-2".into()],
kind: AnalysisResultKind::ArrheniusFit(ArrheniusFitRecord {
parent_fit_ids: vec!["fit-1".into(), "fit-2".into()],
coefficient_name: "k1".into(),
coefficient_stage: Some("component 1".into()),
physical_stage_label: String::new(),
selected_components: vec![],
activation_energy_j_per_mol: 80_000.0,
ln_pre_exponential: Some(1.0e6_f64.ln()),
pre_exponential_per_second: Some(1.0e6),
pre_exponential_status: Some(ArrheniusPreExponentialStatus::Representable),
residual_degrees_of_freedom: Some(0),
r_squared_log_space: Some(0.999),
r_squared_status: Some(ArrheniusRSquaredStatus::Defined),
points: vec![
ArrheniusPoint {
fit_result_id: "fit-1".into(),
experiment_identity: "uuid-500".into(),
experiment_id: "iso-500K".into(),
temperature_kelvin: 500.0,
rate_per_second: 0.01,
},
ArrheniusPoint {
fit_result_id: "fit-2".into(),
experiment_identity: "uuid-600".into(),
experiment_id: "iso-600K".into(),
temperature_kelvin: 600.0,
rate_per_second: 0.1,
},
],
}),
})
.unwrap();
let csv = coefficient_table_csv(&catalog);
assert!(csv.contains("iso-500K; iso-600K"));
assert!(csv.contains("iso-500K: T=500 K, k=0.01 s^-1"));
assert!(csv.contains("ln(k1) = ln(A) - Ea/(R*T)"));
assert!(csv.contains("coefficient=k1; stage=component 1"));
}
}