use super::support::{click_menu_entry, empty_app, import_csv, with_app};
use crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind;
use crate::Kinetics::experimental_kinetics::math::fitting::CustomFitBackend;
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGASeries;
use eframe::egui;
use egui_kittest::kittest::Queryable;
use tempfile::tempdir;
fn exact_exponential_csv() -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempdir().unwrap();
let path = dir.path().join("custom_fit.csv");
let mut csv = String::from("t,m\n");
for index in 0..80 {
let x = index as f64 * 0.1;
let y = 2.0 * (-0.3 * x).exp() + 0.5;
csv.push_str(&format!("{x:.8},{y:.12}\n"));
}
std::fs::write(&path, csv).unwrap();
(dir, path)
}
fn open_custom_fit(
harness: &mut egui_kittest::Harness<super::support::StoryState>,
path: &std::path::Path,
) {
import_csv(harness, path, "custom_fit", Some(500.0), None);
click_menu_entry(harness, "Kinetic Methods", "Fit Model");
{
let state = &mut harness.state_mut().app.kinetic_methods_state;
state.fit_model_experiment_id = "custom_fit".to_string();
state.fit_model_x_col = "t".to_string();
state.fit_model_y_col = "m".to_string();
state.fit_model_custom_backend = CustomFitBackend::LM;
}
harness.run();
harness.get_by_label("Custom model").click();
harness.run();
}
fn replace_text(
harness: &mut egui_kittest::Harness<super::support::StoryState>,
label: &str,
value: &str,
) {
let input = harness.get_by_label(label);
input.focus();
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.key_press(egui::Key::Backspace);
harness.get_by_label(label).type_text(value);
harness.run();
}
fn click_fit(harness: &mut egui_kittest::Harness<super::support::StoryState>) {
harness.get_by_label("Fit").scroll_to_me();
harness.run();
harness.get_by_label("Fit").click();
harness.run();
}
#[test]
fn story_custom_formula_input_fit_reports_parameters_and_publishes_curve() {
let (_dir, path) = exact_exponential_csv();
with_app(empty_app(), |harness| {
open_custom_fit(harness, &path);
{
let state = &mut harness.state_mut().app.kinetic_methods_state;
state.fit_training_range_enabled = true;
state.fit_training_start = 1.0;
state.fit_training_end = 6.0;
}
replace_text(harness, "Formula (y = f(x, parameters)):", "a*exp(-k*x)+b");
replace_text(harness, "Fitted parameters (ordered):", "a,k,b");
replace_text(harness, "Initial guess (required):", "2,0.3,0.5");
replace_text(harness, "Output column:", "custom_fitted_mass");
click_fit(harness);
let state = &harness.state().app.kinetic_methods_state;
let result = state
.fit_model_result
.as_ref()
.unwrap_or_else(|| panic!("custom fit result missing: {}", state.fit_model_status));
assert_eq!(result.model_name, "Custom formula");
assert_eq!(result.method, "LM");
assert_eq!(result.equation, "a*exp(-k*x)+b");
assert_eq!(result.initial_guess, [2.0, 0.3, 0.5]);
assert!(result.r2 > 0.999_99);
let coefficients = result
.coefficients
.iter()
.cloned()
.collect::<std::collections::HashMap<_, _>>();
assert!((coefficients["a"] - 2.0).abs() < 1e-4);
assert!((coefficients["k"] - 0.3).abs() < 1e-5);
assert!((coefficients["b"] - 0.5).abs() < 1e-4);
assert!(
state
.fit_model_status
.contains("Fit added 'custom_fitted_mass'")
);
let experiment = harness
.state()
.app
.model
.series
.get_experiment_by_id("custom_fit")
.unwrap();
assert!(
experiment
.dataset
.schema
.columns
.contains_key("custom_fitted_mass")
);
let provenance = experiment
.dataset
.column_provenance_text("custom_fitted_mass")
.unwrap();
assert!(provenance.contains("equation=a*exp(-k*x)+b"));
assert!(provenance.contains("method=LM"));
assert!(
harness
.state()
.app
.model
.message
.contains("Fit added 'custom_fitted_mass'")
);
harness.get_by_label("Save fit").click_accesskit();
harness.run();
assert!(
harness
.state()
.app
.kinetic_methods_state
.fit_model_status
.starts_with("Saved fit result"),
"{}",
harness.state().app.kinetic_methods_state.fit_model_status
);
let series = &harness.state().app.model.series;
let record = series.analysis_results().records().last().unwrap();
let AnalysisResultKind::ParameterSet(set) = &record.kind else {
panic!("custom formula fit should be archived as a parameter set");
};
assert_eq!(set.model, "Custom formula");
assert_eq!(set.solver.as_deref(), Some("LM"));
assert_eq!(set.formula.as_deref(), Some("a*exp(-k*x)+b"));
assert!(set.settings.iter().any(|(key, value)| {
key == "initial_guess_used" && value == "2;0.3;0.5"
}));
let range = set.range.as_ref().unwrap();
assert_eq!((range.start, range.end), (1.0, 6.0));
assert_eq!(set.coefficients.len(), 3);
assert!(record.source_experiments[0].experiment_identity.len() > 20);
assert!(harness
.state()
.app
.kinetic_methods_state
.fit_saved_session_keys
.contains(&("custom_fit".into(), "t".into(), "m".into())));
assert!(harness.query_by_label("Save fit").is_none());
let file = tempfile::NamedTempFile::new().unwrap();
series.to_csv_series(file.path()).unwrap();
let reopened = TGASeries::from_csv_series(file.path()).unwrap();
let archived = reopened.analysis_results().records().last().unwrap();
let AnalysisResultKind::ParameterSet(archived_set) = &archived.kind else {
panic!("typed round-trip lost the custom fit record");
};
assert_eq!(archived_set.range.as_ref().unwrap().start, 1.0);
assert_eq!(archived_set.range.as_ref().unwrap().end, 6.0);
assert_eq!(archived_set.formula.as_deref(), Some("a*exp(-k*x)+b"));
assert_eq!(archived_set.solver.as_deref(), Some("LM"));
assert_eq!(archived_set.settings, set.settings);
assert_eq!(archived.source_experiments, record.source_experiments);
replace_text(harness, "Output column:", "custom_fitted_mass_second");
click_fit(harness);
assert!(harness
.state()
.app
.kinetic_methods_state
.fit_model_status
.starts_with("Fit added"));
assert!(harness.query_by_label("Save fit").is_some());
harness.get_by_label("Save fit").click_accesskit();
harness.run();
assert_eq!(
harness
.state()
.app
.model
.series
.analysis_results()
.records()
.len(),
2,
"a new fit session on the same experiment and axes can be saved independently"
);
});
}
#[test]
fn story_custom_gavin_fit_is_archived_with_its_solver_and_coefficients() {
let (_dir, path) = exact_exponential_csv();
with_app(empty_app(), |harness| {
open_custom_fit(harness, &path);
replace_text(harness, "Formula (y = f(x, parameters)):", "a*exp(-k*x)+b");
replace_text(harness, "Fitted parameters (ordered):", "a,k,b");
replace_text(harness, "Initial guess (required):", "2,0.3,0.5");
replace_text(harness, "Output column:", "gavin_fitted_mass");
harness
.state_mut()
.app
.kinetic_methods_state
.fit_model_custom_backend = CustomFitBackend::Gavin;
click_fit(harness);
let result = harness
.state()
.app
.kinetic_methods_state
.fit_model_result
.as_ref()
.expect("Gavin custom fit should produce a result");
assert_eq!(result.method, "GAVIN");
assert!(result.r2 > 0.999_99);
harness.get_by_label("Save fit").click_accesskit();
harness.run();
let record = harness
.state()
.app
.model
.series
.analysis_results()
.records()
.last()
.unwrap();
let AnalysisResultKind::ParameterSet(set) = &record.kind else {
panic!("Gavin fit should be archived as a parameter set");
};
assert_eq!(set.solver.as_deref(), Some("GAVIN"));
assert_eq!(set.model, "Custom formula");
assert_eq!(set.coefficients.len(), 3);
assert!(set.coefficients.iter().any(|coefficient| {
coefficient.name == "k" && coefficient.unit == "model-dependent"
}));
});
}
#[test]
fn two_exponential_varpro_coefficients_keep_component_roles_and_fit_interval() {
let dir = tempdir().unwrap();
let path = dir.path().join("two_exp.csv");
let mut csv = String::from("t,m\n");
for index in 0..120 {
let x = index as f64 * 0.1;
let y = 1.1 * (-0.8 * x).exp() + 0.7 * (-0.25 * x).exp();
csv.push_str(&format!("{x:.8},{y:.12}\n"));
}
std::fs::write(&path, csv).unwrap();
with_app(empty_app(), |harness| {
import_csv(harness, &path, "two_exp", Some(500.0), None);
click_menu_entry(harness, "Kinetic Methods", "Fit Model");
{
let state = &mut harness.state_mut().app.kinetic_methods_state;
state.fit_model_experiment_id = "two_exp".into();
state.fit_model_x_col = "t".into();
state.fit_model_y_col = "m".into();
state.fit_model_output_col = "fitted_two_exp".into();
state.fit_model_model = crate::Kinetics::experimental_kinetics::math::fitting::FittingModelName::TwoExp;
state.fit_model_initial_guess = "1,0.5,1,0.2".into();
state.fit_training_range_enabled = true;
state.fit_training_start = 0.5;
state.fit_training_end = 9.5;
}
harness.run();
click_fit(harness);
let result = harness.state().app.kinetic_methods_state.fit_model_result.as_ref().unwrap();
assert_eq!(result.model_name, "TwoExp");
assert!(result.method.to_ascii_uppercase().contains("VARPRO"));
assert!(result.r2 > 0.999_99, "two-exponential R2={}", result.r2);
assert_eq!(result.initial_guess, [0.5, 0.2]);
let original_identity = {
let series = &mut harness.state_mut().app.model.series;
let original_identity = series
.get_experiment_by_id("two_exp")
.unwrap()
.meta
.identity
.clone();
series
.bind_time(
"two_exp",
"t",
crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Hour,
)
.unwrap();
let index = series.index_by_id("two_exp").unwrap();
series.set_experiment_id(index, "renamed_after_fit").unwrap();
let replacement_dataset = series
.get_experiment_by_id("renamed_after_fit")
.unwrap()
.dataset
.clone();
series
.push(
crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment::new(
replacement_dataset,
)
.with_id("two_exp")
.with_isothermal_temperature(700.0),
)
.unwrap();
assert_ne!(
series.get_experiment_by_id("two_exp").unwrap().meta.identity,
original_identity
);
original_identity
};
harness.get_by_label("Save fit").click_accesskit();
harness.run();
let series = &harness.state().app.model.series;
let record = series.analysis_results().records().last().unwrap();
assert_eq!(record.source_experiment_id.as_deref(), Some("two_exp"));
assert_eq!(record.source_experiment_ids, ["two_exp"]);
assert_eq!(
record.source_experiments[0].experiment_id_snapshot,
"two_exp"
);
assert_eq!(
record.source_experiments[0].experiment_identity,
original_identity
);
let AnalysisResultKind::ParameterSet(set) = &record.kind else {
panic!("built-in TwoExp fit should be archived as a parameter set");
};
assert_eq!(set.model, "TwoExp");
assert_eq!(set.x_unit.as_deref(), Some("Second"));
assert!(set.conditions.iter().any(|condition| {
condition.role.as_deref() == Some("isothermal temperature")
&& condition.value == 500.0
&& condition.unit == "K"
}));
assert!(set.solver.as_deref().unwrap().to_ascii_uppercase().contains("VARPRO"));
assert!(set.settings.iter().any(|(key, value)| {
key == "initial_guess_used" && value == "0.5;0.2"
}));
assert_eq!(
set.range.as_ref().map(|range| (range.start, range.end)),
Some((0.5, 9.5))
);
for (name, role, stage) in [
("a", "amplitude", "component 1"),
("p", "rate constant", "component 1"),
("b", "amplitude", "component 2"),
("k", "rate constant", "component 2"),
] {
assert!(set.coefficients.iter().any(|coefficient| {
coefficient.name == name
&& coefficient.role.as_deref() == Some(role)
&& coefficient.stage.as_deref() == Some(stage)
}), "missing typed {name} coefficient for {stage}");
}
assert!(set
.coefficients
.iter()
.filter(|coefficient| coefficient.role.as_deref() == Some("rate constant"))
.all(|coefficient| coefficient.unit == "s^-1"));
let file = tempfile::NamedTempFile::new().unwrap();
series.to_csv_series(file.path()).unwrap();
let reopened = TGASeries::from_csv_series(file.path()).unwrap();
let archived = reopened.analysis_results().records().last().unwrap();
let AnalysisResultKind::ParameterSet(archived_set) = &archived.kind else {
panic!("typed round-trip lost the TwoExp result");
};
assert_eq!(archived_set.model, "TwoExp");
assert_eq!(archived_set.coefficients.len(), 4);
assert_eq!(archived.source_experiments, record.source_experiments);
});
}
#[test]
fn story_corrupted_custom_formula_is_reported_without_panic_or_data_change() {
let (_dir, path) = exact_exponential_csv();
with_app(empty_app(), |harness| {
open_custom_fit(harness, &path);
replace_text(harness, "Formula (y = f(x, parameters)):", "a*exp(");
replace_text(harness, "Fitted parameters (ordered):", "a");
replace_text(harness, "Initial guess (required):", "1");
replace_text(harness, "Output column:", "must_not_be_added");
let dataset = harness
.state()
.app
.model
.series
.get_experiment_by_id("custom_fit")
.unwrap();
let history_before = dataset.dataset.history_of_operations.feed_lines();
let height_before = dataset.dataset.frame.clone().collect().unwrap().height();
click_fit(harness);
let state = &harness.state().app.kinetic_methods_state;
assert!(state.fit_model_result.is_none());
assert!(state.fit_model_status.starts_with("Error:"));
assert!(state.fit_model_status.contains("parse"));
assert!(harness.state().app.model.message.contains("Error:"));
assert!(harness.state().app.model.message.contains("parse"));
let dataset_after = &harness
.state()
.app
.model
.series
.get_experiment_by_id("custom_fit")
.unwrap()
.dataset;
assert!(
!dataset_after
.schema
.columns
.contains_key("must_not_be_added")
);
assert_eq!(
dataset_after.history_of_operations.feed_lines(),
history_before
);
assert_eq!(
dataset_after.frame.clone().collect().unwrap().height(),
height_before
);
});
}