use crate::gui::experimental_kinetics_gui::controller_buttons_and_panels::NewExperimentDialogState;
use crate::gui::experimental_kinetics_gui::help_view::contextual_help_link;
use crate::gui::experimental_kinetics_gui::model::{PlotModel, TGAGUIError};
use crate::Kinetics::experimental_kinetics::analysis_results::{
fit_arrhenius, AnalysisRange, AnalysisResultKind, AnalysisResultRecord, AnalysisSourceRef,
ArrheniusPoint, CoefficientValue, ParameterSetRecord,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::combined::CombinedKineticAnalysis;
use crate::Kinetics::experimental_kinetics::kinetic_methods::is_this_a_sublimation::{
IsThisASublimationResult, SublimationMethod, SublimationResult,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::isoconversion::{
IsoconversionalKineticMethod, IsoconversionalMethod,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::KineticMethod;
use crate::Kinetics::experimental_kinetics::kinetic_methods::Kissinger::Kissinger;
use crate::Kinetics::experimental_kinetics::math::fitting::{
evaluate_fit_batch, CustomFitBackend, CustomFitDefinition, CustomVarProBasis, FitColumnRequest,
FitColumnResult, FitColumnSession, FitEvaluationMode, FittedEvaluationBatch, FittingModelName,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADomainError;
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGASeries;
use eframe::egui;
use std::collections::HashSet;
pub struct KineticMethodsWindowState {
pub isoconversional_open: bool,
pub isoconversional_method: IsoconversionalMethod,
pub isoconversional_status: String,
pub isoconversional_use_selected_experiments: bool,
pub isoconversional_selected_experiments: Vec<String>,
pub isoconversional_output_id: String,
pub kissinger_open: bool,
pub kissinger_status: String,
pub kissinger_ea_kj: Option<f64>,
pub kissinger_r2: Option<f64>,
pub kissinger_pending_result: Option<AnalysisResultRecord>,
pub combined_kinetics_open: bool,
pub combined_status: String,
pub combined_n_min: f64,
pub combined_n_max: f64,
pub combined_n_steps: usize,
pub combined_m_min: f64,
pub combined_m_max: f64,
pub combined_m_steps: usize,
pub combined_eta_min: f64,
pub combined_eta_max: f64,
pub combined_refinement_steps: usize,
pub combined_result_n: Option<f64>,
pub combined_result_m: Option<f64>,
pub combined_result_ea_kj: Option<f64>,
pub combined_result_r2: Option<f64>,
pub combined_pending_result: Option<AnalysisResultRecord>,
pub fit_model_open: bool,
pub fit_model_experiment_id: String,
pub fit_model_x_col: String,
pub fit_model_y_col: String,
pub fit_model_output_col: String,
pub fit_model_model: FittingModelName,
pub fit_model_custom_enabled: bool,
pub fit_model_custom_equation: String,
pub fit_model_custom_parameters: String,
pub fit_model_custom_backend: CustomFitBackend,
pub fit_model_custom_varpro: bool,
pub fit_model_custom_varpro_parameters: String,
pub fit_model_custom_varpro_basis: Vec<CustomVarProBasis>,
pub fit_model_polynomial_degree: usize,
pub fit_model_initial_guess: String,
pub fit_model_tolerance: f64,
pub fit_model_max_iter: usize,
pub fit_model_status: String,
pub fit_model_result: Option<FitColumnResult>,
pub fit_sessions: Vec<FitColumnSession>,
pub fit_saved_session_keys: HashSet<(String, String, String)>,
pub fit_training_range_enabled: bool,
pub fit_training_start: f64,
pub fit_training_end: f64,
pub fit_gap_enabled: bool,
pub fit_gap_start: f64,
pub fit_gap_end: f64,
pub fit_evaluation_start: f64,
pub fit_evaluation_end: f64,
pub fit_evaluation_points: usize,
pub fit_pending_batch: Option<FittedEvaluationBatch>,
pub fit_reconstructed_experiment_id: String,
pub coefficients_open: bool,
pub coefficients_selected: Vec<CoefficientSelection>,
pub coefficients_physical_stage: String,
pub coefficients_status: String,
pub coefficients_pending_result: Option<AnalysisResultRecord>,
pub coefficients_archive_filter_experiment: String,
pub coefficients_archive_filter_model: String,
pub coefficients_archive_filter_parameter: String,
pub coefficients_archive_height: f32,
pub coefficients_archive_plot_result_id: Option<String>,
pub coefficients_archive_plot_mode: ArrheniusPlotMode,
pub sublimation_check_open: bool,
pub sublimation_status: String,
pub sublimation_ea_kj: Option<f64>,
pub sublimation_k: Option<f64>,
pub sublimation_verdict: Option<String>,
pub sublimation_pending_result: Option<AnalysisResultRecord>,
pub sublimation_pending_rates: Option<Vec<SublimationResult>>,
pub sublimation_output_column: String,
pub sublimation_x_min: String,
pub sublimation_x_max: String,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ArrheniusPlotMode {
#[default]
RateVsTemperature,
LogRateVsInverseTemperature,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CoefficientSelection {
pub result_id: String,
pub coefficient_name: String,
pub stage: Option<String>,
}
impl Default for KineticMethodsWindowState {
fn default() -> Self {
Self {
isoconversional_open: false,
isoconversional_method: IsoconversionalMethod::default(),
isoconversional_status: String::new(),
isoconversional_use_selected_experiments: false,
isoconversional_selected_experiments: Vec::new(),
isoconversional_output_id: "isoconversional_result".to_string(),
kissinger_open: false,
kissinger_status: String::new(),
kissinger_ea_kj: None,
kissinger_r2: None,
kissinger_pending_result: None,
combined_kinetics_open: false,
combined_status: String::new(),
combined_n_min: CombinedKineticAnalysis::default().n_min,
combined_n_max: CombinedKineticAnalysis::default().n_max,
combined_n_steps: CombinedKineticAnalysis::default().n_steps,
combined_m_min: CombinedKineticAnalysis::default().m_min,
combined_m_max: CombinedKineticAnalysis::default().m_max,
combined_m_steps: CombinedKineticAnalysis::default().m_steps,
combined_eta_min: CombinedKineticAnalysis::default().eta_min,
combined_eta_max: CombinedKineticAnalysis::default().eta_max,
combined_refinement_steps: CombinedKineticAnalysis::default().refinement_steps,
combined_result_n: None,
combined_result_m: None,
combined_result_ea_kj: None,
combined_result_r2: None,
combined_pending_result: None,
fit_model_open: false,
fit_model_experiment_id: String::new(),
fit_model_x_col: String::new(),
fit_model_y_col: String::new(),
fit_model_output_col: String::new(),
fit_model_model: FittingModelName::DecExp,
fit_model_custom_enabled: false,
fit_model_custom_equation: "a*exp(-k*x)+b".to_string(),
fit_model_custom_parameters: "a,k,b".to_string(),
fit_model_custom_backend: CustomFitBackend::LM,
fit_model_custom_varpro: false,
fit_model_custom_varpro_parameters: "k".to_string(),
fit_model_custom_varpro_basis: vec![CustomVarProBasis {
coefficient_name: "a".to_string(),
parameter_name: "k".to_string(),
expression: "exp(-k*x)".to_string(),
}],
fit_model_polynomial_degree: 2,
fit_model_initial_guess: String::new(),
fit_model_tolerance: 1e-6,
fit_model_max_iter: 300,
fit_model_status: String::new(),
fit_model_result: None,
fit_sessions: Vec::new(),
fit_saved_session_keys: HashSet::new(),
fit_training_range_enabled: false,
fit_training_start: 0.0,
fit_training_end: 1.0,
fit_gap_enabled: false,
fit_gap_start: 0.0,
fit_gap_end: 1.0,
fit_evaluation_start: 0.0,
fit_evaluation_end: 1.0,
fit_evaluation_points: 20,
fit_pending_batch: None,
fit_reconstructed_experiment_id: String::new(),
coefficients_open: false,
coefficients_selected: Vec::new(),
coefficients_physical_stage: String::new(),
coefficients_status: String::new(),
coefficients_pending_result: None,
coefficients_archive_filter_experiment: String::new(),
coefficients_archive_filter_model: String::new(),
coefficients_archive_filter_parameter: String::new(),
coefficients_archive_height: 220.0,
coefficients_archive_plot_result_id: None,
coefficients_archive_plot_mode: ArrheniusPlotMode::RateVsTemperature,
sublimation_check_open: false,
sublimation_status: String::new(),
sublimation_ea_kj: None,
sublimation_k: None,
sublimation_verdict: None,
sublimation_pending_result: None,
sublimation_pending_rates: None,
sublimation_output_column: "fitted_sublim_rate".into(),
sublimation_x_min: String::new(),
sublimation_x_max: String::new(),
}
}
}
impl KineticMethodsWindowState {
pub(crate) fn on_document_replaced(&mut self) {
self.fit_sessions.clear();
self.fit_saved_session_keys.clear();
self.fit_pending_batch = None;
self.fit_model_result = None;
self.fit_model_status.clear();
self.fit_model_experiment_id.clear();
self.fit_model_x_col.clear();
self.fit_model_y_col.clear();
self.fit_reconstructed_experiment_id.clear();
self.isoconversional_selected_experiments.clear();
self.kissinger_pending_result = None;
self.kissinger_ea_kj = None;
self.kissinger_r2 = None;
self.kissinger_status.clear();
self.combined_pending_result = None;
self.combined_result_n = None;
self.combined_result_m = None;
self.combined_result_ea_kj = None;
self.combined_result_r2 = None;
self.combined_status.clear();
self.coefficients_selected.clear();
self.coefficients_physical_stage.clear();
self.coefficients_pending_result = None;
self.coefficients_status.clear();
self.coefficients_archive_plot_result_id = None;
self.sublimation_pending_result = None;
self.sublimation_pending_rates = None;
self.sublimation_ea_kj = None;
self.sublimation_k = None;
self.sublimation_verdict = None;
self.sublimation_status.clear();
}
pub(crate) fn close_window_on_layer(&mut self, layer: Option<egui::LayerId>) -> bool {
let Some(layer) = layer else { return false };
let windows = [
("Isoconversional", &mut self.isoconversional_open),
("Kissinger", &mut self.kissinger_open),
(
"Combined Kinetics Analysis",
&mut self.combined_kinetics_open,
),
("Is this a sublimation?", &mut self.sublimation_check_open),
("Fit Model", &mut self.fit_model_open),
("Coefficients Handling", &mut self.coefficients_open),
];
for (title, is_open) in windows {
if layer.id == egui::Id::unique(Some(title)) && *is_open {
*is_open = false;
return true;
}
}
false
}
}
#[cfg(test)]
mod document_lifecycle_tests {
use super::*;
fn pending_result() -> AnalysisResultRecord {
AnalysisResultRecord {
id: "pending".into(),
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "test".into(),
model: "test".into(),
formula: None,
solver: None,
x_column: None,
y_column: None,
x_unit: None,
y_unit: None,
range: None,
excluded_range: None,
conditions: vec![],
settings: vec![],
diagnostics: vec![],
coefficients: vec![],
}),
source_experiment_id: Some("old-document".into()),
source_experiment_ids: vec!["old-document".into()],
source_experiments: vec![],
parent_result_ids: vec![],
}
}
#[test]
fn replacing_document_clears_every_document_bound_kinetic_result() {
let mut state = KineticMethodsWindowState::default();
let result = pending_result();
state.kissinger_pending_result = Some(result.clone());
state.combined_pending_result = Some(result.clone());
state.coefficients_pending_result = Some(result.clone());
state.sublimation_pending_result = Some(result);
state.coefficients_selected.push(CoefficientSelection {
result_id: "old-fit".into(),
coefficient_name: "k".into(),
stage: None,
});
state.fit_pending_batch = Some(FittedEvaluationBatch {
source_experiment_id: "old-document".into(),
source_history_len: 0,
x_col: "t".into(),
x_unit: crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Second,
x_nature:
crate::Kinetics::experimental_kinetics::one_experiment_dataset::ColumnNature::Time,
mode: FitEvaluationMode::Extrapolate {
start: 0.0,
end: 1.0,
points: 2,
},
evaluation_x: vec![0.0, 1.0],
source_x: vec![],
x_values: vec![],
columns: vec![],
});
state.on_document_replaced();
assert!(state.kissinger_pending_result.is_none());
assert!(state.combined_pending_result.is_none());
assert!(state.coefficients_pending_result.is_none());
assert!(state.sublimation_pending_result.is_none());
assert!(state.coefficients_selected.is_empty());
assert!(state.fit_pending_batch.is_none());
}
#[test]
fn pending_result_survives_failed_insert_and_clears_after_retry() {
let mut state = KineticMethodsWindowState::default();
let mut pending = pending_result();
pending.parent_result_ids = vec!["missing-parent".into()];
state.combined_pending_result = Some(pending);
let original = state.combined_pending_result.clone();
let mut series = TGASeries::new();
let error = KineticMethods::accept_pending_result(
&mut series,
&mut state.combined_pending_result,
)
.unwrap_err();
assert!(error.contains("missing-parent"));
assert_eq!(state.combined_pending_result, original);
assert!(series.analysis_results().records().is_empty());
state
.combined_pending_result
.as_mut()
.unwrap()
.parent_result_ids
.clear();
assert_eq!(
KineticMethods::accept_pending_result(
&mut series,
&mut state.combined_pending_result,
)
.unwrap(),
"pending"
);
assert!(state.combined_pending_result.is_none());
assert_eq!(series.analysis_results().records().len(), 1);
}
#[test]
fn replacing_document_clears_saved_fit_session_markers() {
let mut state = KineticMethodsWindowState::default();
state.fit_saved_session_keys.insert((
"old-exp".into(),
"time".into(),
"mass".into(),
));
state.on_document_replaced();
assert!(state.fit_saved_session_keys.is_empty());
}
}
pub struct KineticMethods;
impl KineticMethods {
fn publish_status(model: &mut PlotModel, status: &str) {
let _ = model.push_message(status);
}
fn accept_pending_result(
series: &mut TGASeries,
pending: &mut Option<AnalysisResultRecord>,
) -> Result<String, String> {
let record = pending
.as_ref()
.cloned()
.ok_or_else(|| "There is no calculated result waiting to be saved.".to_string())?;
let id = series
.add_analysis_result(record)
.map_err(|error| error.to_string())?;
*pending = None;
Ok(id)
}
fn fit_session_key(result: &FitColumnResult) -> (String, String, String) {
(
result.experiment_id.clone(),
result.x_col.clone(),
result.y_col.clone(),
)
}
pub fn show_menu(ui: &mut egui::Ui, state: &mut KineticMethodsWindowState) {
if ui.button("Isoconversional").on_hover_text("Non-isothermal activation-energy analysis over conversion; can create a result experiment.").clicked() {
state.isoconversional_open = true;
}
if ui.button("Kissinger").on_hover_text("Non-isothermal peak-temperature method; reports Ea only (no pre-exponential factor) and can save the typed result to the series.").clicked() {
state.kissinger_open = true;
}
if ui.button("Combined Kinetics Analysis").on_hover_text("Non-isothermal model-parameter search; numeric search ranges are configured in its window.").clicked() {
state.combined_kinetics_open = true;
}
ui.label("Criado Master Curve: unavailable pending scientific validation");
if ui.button("Fit Model").on_hover_text("General single-experiment curve fitting, not a kinetic method; adds a fitted output column.").clicked() {
state.fit_model_open = true;
}
if ui.button("Coefficients Handling").on_hover_text("Select saved rate constants, compare them by experimental temperature, and fit an Arrhenius relation.").clicked() {
state.coefficients_open = true;
}
if ui.button("Is this a sublimation?").on_hover_text("Fit one selected experiment or conversion interval. The fit is kept separately; publish its predicted rate as a new column only with the explicit publish command.").clicked() {
state.sublimation_check_open = true;
}
}
pub fn show_isoconversional_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
) -> Result<(), TGAGUIError> {
if !state.isoconversional_open {
return Ok(());
}
egui::Window::new("Isoconversional")
.open(&mut state.isoconversional_open)
.default_size([540.0, 360.0])
.show(ui.ctx(), |ui| {
contextual_help_link(ui, "Isoconversional");
ui.vertical(|ui| {
if state.isoconversional_method == IsoconversionalMethod::FriedmanIntegral {
ui.label("Isothermal Friedman method: uses the setpoint temperature from experiment metadata, so a measured T column is optional. Requires conversion data from at least three isothermal experiments.");
} else {
ui.label("Non-isothermal method: estimates activation energy versus conversion from experiments run at different heating rates. Requires a measured temperature column and heating-rate metadata; isothermal experiments are rejected.");
}
ui.add_space(4.0);
ui.horizontal(|ui| {
let label = ui.label("Method:");
let combo = egui::ComboBox::from_id_salt("isoconv_method")
.selected_text(state.isoconversional_method.display_name())
.show_ui(ui, |ui| {
for method in IsoconversionalMethod::all() {
ui.selectable_value(
&mut state.isoconversional_method,
*method,
method.display_name(),
);
}
});
let _ = combo.response.labelled_by(label.id);
});
ui.add_space(6.0);
let exp_ids = model.list_of_experiments();
state
.isoconversional_selected_experiments
.retain(|id| exp_ids.iter().any(|exp| exp == id));
ui.horizontal(|ui| {
ui.label("Experiments:");
ui.checkbox(
&mut state.isoconversional_use_selected_experiments,
"Use selected only",
);
});
if state.isoconversional_use_selected_experiments {
if exp_ids.is_empty() {
ui.label("No experiments available.");
} else {
ui.vertical(|ui| {
for id in &exp_ids {
let mut selected = state
.isoconversional_selected_experiments
.iter()
.any(|v| v == id);
if ui.checkbox(&mut selected, id).changed() {
if selected {
if !state
.isoconversional_selected_experiments
.contains(id)
{
state
.isoconversional_selected_experiments
.push(id.clone());
}
} else {
state
.isoconversional_selected_experiments
.retain(|v| v != id);
}
}
}
});
}
}
ui.add_space(6.0);
ui.horizontal(|ui| {
let label = ui.label("Output ID:");
let input = ui.text_edit_singleline(&mut state.isoconversional_output_id);
let _ = input.labelled_by(label.id);
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label("Status:");
ui.label(&state.isoconversional_status);
});
ui.add_space(8.0);
let calculate_help = if state.isoconversional_method == IsoconversionalMethod::FriedmanIntegral {
"Requires at least three isothermal experiments with a finite setpoint temperature and conversion data. Adds a result experiment; source data are unchanged."
} else {
"Requires non-isothermal experiments with a measured temperature column and heating-rate metadata. Isothermal experiments are rejected. Adds a result experiment; source data are unchanged."
};
if ui.button("Calculate").on_hover_text(calculate_help).clicked() {
let status = (|| -> Result<String, TGAGUIError> {
if exp_ids.is_empty() {
return Ok("No experiments to analyze.".to_string());
}
let selected_ids: Vec<&str> = state
.isoconversional_selected_experiments
.iter()
.map(|s| s.as_str())
.collect();
let what_exp_to_take = if state.isoconversional_use_selected_experiments
{
if selected_ids.is_empty() {
return Ok("Select at least one experiment.".to_string());
}
Some(selected_ids.as_slice())
} else {
None
};
let output_id = if state.isoconversional_output_id.trim().is_empty() {
"isoconversional_result".to_string()
} else {
state.isoconversional_output_id.trim().to_string()
};
let view = model.create_kinetic_data_view_for_method(
what_exp_to_take,
&state.isoconversional_method,
)?;
let method = IsoconversionalKineticMethod {
method: state.isoconversional_method.clone(),
};
method.check_input(&view)?;
let result = method.compute(&view)?;
let warnings = result.warnings.clone();
model.push_isoconversional_result(&result, &output_id)?;
if warnings.is_empty() {
Ok(format!("Done. Result saved as '{}'.", output_id))
} else {
Ok(format!(
"Result saved as '{}'; {} diagnostic warning(s): {}",
output_id,
warnings.len(),
warnings.join(" | ")
))
}
})();
state.isoconversional_status = match status {
Ok(msg) => msg,
Err(err) => format!("Error: {err}"),
};
Self::publish_status(model, &state.isoconversional_status);
}
});
});
Ok(())
}
pub fn show_kissinger_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
) -> Result<(), TGAGUIError> {
if !state.kissinger_open {
return Ok(());
}
egui::Window::new("Kissinger")
.open(&mut state.kissinger_open)
.default_size([520.0, 300.0])
.show(ui.ctx(), |ui| {
contextual_help_link(ui, "Kissinger");
ui.vertical(|ui| {
ui.label("Non-isothermal Kissinger peak method: estimates one activation energy from peak temperatures measured at different heating rates. No numeric or text input is required; results appear below and source data is unchanged.");
ui.add_space(4.0);
let ea_label = state
.kissinger_ea_kj
.map(|v| format!("{:.2}", v))
.unwrap_or_else(|| "-".to_string());
let r2_label = state
.kissinger_r2
.map(|v| format!("{:.4}", v))
.unwrap_or_else(|| "-".to_string());
ui.horizontal(|ui| {
ui.label("Ea (kJ/mol):");
ui.label(ea_label);
});
ui.horizontal(|ui| {
ui.label("R2:");
ui.label(r2_label);
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label("System messages:");
ui.label(&state.kissinger_status);
});
ui.add_space(8.0);
if ui.button("Calculate").on_hover_text("Requires multiple non-isothermal experiments with different heating rates. Updates Ea/R2 labels only; no column or experiment is created.").clicked() {
state.kissinger_ea_kj = None;
state.kissinger_r2 = None;
state.kissinger_pending_result = None;
let status = (|| -> Result<String, TGAGUIError> {
let view = model.create_kinetic_data_view_for_method(
None,
&IsoconversionalMethod::OFW,
)?;
let (result, peaks) = Kissinger::compute_with_peaks(&view)?;
if peaks.len() != view.experiments.len() {
return Err(TGADomainError::InvalidOperation(format!(
"Kissinger returned {} peak observations for {} source experiments",
peaks.len(),
view.experiments.len()
)).into());
}
let source_ids = view.experiments.iter().map(|experiment| experiment.meta.id.clone()).collect::<Vec<_>>();
let source_refs = view.experiments.iter().map(|experiment| AnalysisSourceRef {
experiment_identity: experiment.meta.identity.clone(),
experiment_id_snapshot: experiment.meta.id.clone(),
}).collect();
let conditions = view.experiments.iter().zip(&peaks).flat_map(|(experiment, peak)| {
[
experiment.meta.heating_rate.map(|value| CoefficientValue {
name: format!("heating_rate ({})", experiment.meta.id),
role: Some("heating rate".into()), stage: None, value, unit: "K/min".into(),
}),
Some(CoefficientValue {
name: format!("T_peak ({})", experiment.meta.id),
role: Some("reaction-rate peak temperature".into()), stage: None,
value: peak.temperature, unit: "K".into(),
}),
].into_iter().flatten()
}).collect();
state.kissinger_pending_result = Some(AnalysisResultRecord {
id: String::new(), source_experiment_id: None,
source_experiment_ids: source_ids, source_experiments: source_refs, parent_result_ids: vec![],
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "Kissinger".into(), model: "peak-rate Arrhenius relation".into(),
formula: Some("ln(beta/T_peak^2) = intercept - Ea/(R*T_peak)".into()),
solver: Some("ordinary least squares".into()),
x_column: Some("1/T_peak".into()), y_column: Some("ln(beta/T_peak^2)".into()),
x_unit: Some("K^-1".into()), y_unit: Some("dimensionless".into()),
range: None, excluded_range: None, conditions,
settings: vec![("peak_detection".into(), "maximum d(conversion)/dt on common conversion grid".into())],
diagnostics: vec![
("R2".into(), result.regression.r2, "1".into()),
("slope".into(), result.regression.slope, "K".into()),
("intercept".into(), result.regression.intercept, "1".into()),
],
coefficients: vec![CoefficientValue {
name: "Ea".into(), role: Some("activation energy".into()), stage: None,
value: result.ea, unit: "J/mol".into(),
}],
}),
});
let ea_kj = result.ea / 1000.0;
state.kissinger_ea_kj = Some(ea_kj);
state.kissinger_r2 = Some(result.regression.r2);
Ok("Done.".to_string())
})();
state.kissinger_status = match status {
Ok(msg) => msg,
Err(err) => format!("Error: {err}"),
};
Self::publish_status(model, &state.kissinger_status);
}
});
if state.kissinger_pending_result.is_some() && ui.button("Save Kissinger result")
.on_hover_text("Stores the calculated Kissinger activation energy and source heating-rate conditions in the typed series document.")
.clicked()
{
state.kissinger_status = match Self::accept_pending_result(
&mut model.series,
&mut state.kissinger_pending_result,
) {
Ok(id) => format!("Saved Kissinger result {id} to the series document."),
Err(error) => format!("Error: {error}"),
};
Self::publish_status(model, &state.kissinger_status);
}
});
Ok(())
}
pub fn show_sublimation_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
) -> Result<(), TGAGUIError> {
if !state.sublimation_check_open {
return Ok(());
}
egui::Window::new("Is this a sublimation?")
.open(&mut state.sublimation_check_open)
.default_size([560.0, 320.0])
.show(ui.ctx(), |ui| {
contextual_help_link(ui, "Is this a sublimation?");
ui.vertical(|ui| {
ui.label("Fit one selected experiment. Leave Conversion X bounds empty to use the whole experiment, enter both bounds to restrict the fit, or drag-select an X interval on a conversion-vs-rate curve. Calculate only creates a pending fit result; it does not change the dataset. Save stores coefficients. Publish explicitly adds and plots the predicted rate as a new column over the full experiment.");
ui.horizontal(|ui| {
let min_label = ui.label("Conversion X min (optional):");
let min_input = ui.add(
egui::TextEdit::singleline(&mut state.sublimation_x_min)
.hint_text("empty = full range"),
);
let _ = min_input.labelled_by(min_label.id);
let max_label = ui.label("Conversion X max (optional):");
let max_input = ui.add(
egui::TextEdit::singleline(&mut state.sublimation_x_max)
.hint_text("empty = full range"),
);
let _ = max_input.labelled_by(max_label.id);
});
ui.add_space(4.0);
let ea_label = state
.sublimation_ea_kj
.map(|v| format!("{:.2}", v))
.unwrap_or_else(|| "-".to_string());
let k_label = state
.sublimation_k
.map(|v| format!("{:.4e}", v))
.unwrap_or_else(|| "-".to_string());
let verdict_label = state
.sublimation_verdict
.clone()
.unwrap_or_else(|| "-".to_string());
ui.horizontal(|ui| {
ui.label("Ea (kJ/mol):");
ui.label(ea_label);
});
ui.horizontal(|ui| {
ui.label("Pre-exponential factor k:");
ui.label(k_label);
});
ui.horizontal(|ui| {
ui.label("Verdict:");
ui.label(verdict_label);
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label("System messages:");
ui.label(&state.sublimation_status);
});
ui.add_space(8.0);
if ui.button("Calculate").on_hover_text("Requires one selected experiment with conversion, conversion rate and temperature. Optional bounds or the selected X interval restrict the fit. Calculates and retains a fit only; no column is added until Publish is pressed.").clicked() {
state.sublimation_pending_result = None;
state.sublimation_pending_rates = None;
state.sublimation_ea_kj = None;
state.sublimation_k = None;
state.sublimation_verdict = None;
let status = (|| -> Result<String, TGAGUIError> {
let selected_index = model.get_selected_curve_index().ok_or_else(|| TGAGUIError::BindingError("Select one curve for the experiment to diagnose.".into()))?;
let curve = model.plots.get(selected_index).ok_or_else(|| TGAGUIError::BindingError("Selected curve is no longer available.".into()))?;
let exp_id = curve.experiment_id.clone();
let x_name = curve.x_name.clone();
let parse_bound = |text: &str| -> Result<Option<f64>, TGAGUIError> {
if text.trim().is_empty() { Ok(None) } else {
let value = text.trim().parse::<f64>().map_err(|_| TGAGUIError::BindingError("Conversion X bounds must be numbers.".into()))?;
if value.is_finite() { Ok(Some(value)) } else { Err(TGAGUIError::BindingError("Conversion X bounds must be finite.".into())) }
}
};
let lower = parse_bound(&state.sublimation_x_min)?;
let upper = parse_bound(&state.sublimation_x_max)?;
if lower.is_some() != upper.is_some() {
return Err(TGAGUIError::BindingError("Enter both conversion X bounds, or leave both empty.".into()));
}
let selected_range = if lower.is_none() {
if let Some(rect) = model.interaction.selection_rect {
let (x_min, x_max, _, _) = rect.bounds();
let intersecting = model.plots.iter().filter(|plot| plot.highlighted).count();
if intersecting != 1 || !curve.highlighted {
return Err(TGAGUIError::BindingError(format!("The selected region intersects {intersecting} plotted curves; narrow it so exactly the selected curve is included.")));
}
let experiment = model.series.get_experiment_by_id(&exp_id)?;
if experiment.dataset.schema.eta.as_deref() != Some(x_name.as_str()) {
return Err(TGAGUIError::BindingError("For a plot selection, the curve X column must be the experiment's bound conversion column. Otherwise enter conversion X bounds above.".into()));
}
Some((x_min, x_max))
} else {
None
}
} else {
None
};
let cols = SublimationMethod::default().required_columns_by_nature();
let view = model.series.create_kinetic_data_view(Some(&[exp_id.as_str()]), cols)?;
let exp_data = view.experiments.first().ok_or_else(|| TGAGUIError::BindingError("Selected experiment has no usable kinetic data.".into()))?;
let (x_min, x_max) = if let (Some(a), Some(b)) = (lower, upper) {
(a, b)
} else if let Some((a, b)) = selected_range {
(a, b)
} else {
(
exp_data.conversion.iter().copied().fold(f64::INFINITY, f64::min),
exp_data.conversion.iter().copied().fold(f64::NEG_INFINITY, f64::max),
)
};
let method = SublimationMethod::new(x_min, x_max);
let results = method.compute(&view)?;
let result = results.first().ok_or_else(|| TGAGUIError::BindingError("The selected experiment produced no sublimation result.".into()))?;
state.sublimation_ea_kj = Some(result.ea / 1000.0);
state.sublimation_k = Some(result.k);
let verdict_text = match result.resume {
IsThisASublimationResult::Yes(r2) => {
format!("Yes (R2={:.4})", r2)
}
IsThisASublimationResult::MayBe(r2) => {
format!("Maybe (R2={:.4})", r2)
}
IsThisASublimationResult::No(r2) => {
format!("No (R2={:.4})", r2)
}
};
state.sublimation_verdict = Some(verdict_text);
let source_experiment = model.series.get_experiment_by_id(&exp_id)?;
let schema = source_experiment.dataset.schema();
let source_temperature = schema.temperature.clone();
let source_conversion = schema.eta.clone();
let source_rate = schema.deta_dt.clone();
let range_source = if lower.is_some() { "manual bounds" }
else if selected_range.is_some() { "plot selection" }
else { "full conversion range" };
let record = AnalysisResultRecord {
id: String::new(),
source_experiment_id: Some(exp_id.clone()),
source_experiment_ids: vec![exp_id.clone()],
source_experiments: vec![AnalysisSourceRef {
experiment_identity: source_experiment.meta.identity.clone(),
experiment_id_snapshot: source_experiment.meta.id.clone(),
}],
parent_result_ids: vec![],
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "Sublimation diagnosis".into(),
model: "ln(d(conversion)/dt) = ln(k0) - Ea/(R*T)".into(),
formula: Some("ln(deta/dt) = ln(k0) - Ea/(R*T)".into()),
solver: Some("ordinary least squares".into()),
x_column: source_temperature, y_column: source_rate,
x_unit: Some("K".into()), y_unit: Some("s^-1".into()),
range: Some(AnalysisRange { axis: "conversion".into(), start: x_min, end: x_max }),
excluded_range: None,
conditions: source_experiment.meta.heating_rate.map(|value| CoefficientValue {
name: "heating_rate".into(), role: Some("heating rate".into()), stage: None,
value, unit: "K/min".into(),
}).into_iter().collect(),
settings: vec![
("fit_range_source".into(), range_source.into()),
("prediction_range".into(), "full experiment".into()),
("conversion_column".into(), source_conversion.unwrap_or_else(|| "unknown".into())),
],
diagnostics: vec![
("R2".into(), result.regression.r2, "1".into()),
("slope".into(), result.regression.slope, "K".into()),
("intercept".into(), result.regression.intercept, "ln(s^-1)".into()),
],
coefficients: vec![
CoefficientValue { name: "Ea".into(), role: Some("activation energy".into()), stage: None, value: result.ea, unit: "J/mol".into() },
CoefficientValue { name: "k0".into(), role: Some("pre-exponential factor".into()), stage: None, value: result.k, unit: "s^-1".into() },
],
}),
};
state.sublimation_pending_result = Some(record);
state.sublimation_pending_rates = Some(results);
Ok("Fit complete. Save its coefficients or explicitly publish the fitted-rate column.".to_string())
})();
state.sublimation_status = match status {
Ok(msg) => msg,
Err(TGAGUIError::PostCommitWarning(warning)) => {
format!("Warning: {warning}")
}
Err(err) => format!("Error: {err}"),
};
Self::publish_status(model, &state.sublimation_status);
}
if state.sublimation_pending_rates.is_some() {
ui.horizontal(|ui| {
let output_label = ui.label("New rate column:");
let output_input =
ui.text_edit_singleline(&mut state.sublimation_output_column);
let _ = output_input.labelled_by(output_label.id);
if ui.button("Publish fitted rate column")
.on_hover_text("Adds a new column and plots it over the full experiment. Existing columns are never overwritten; on a name conflict, choose another name and retry. The fit result remains available for saving.")
.clicked()
{
let output = state.sublimation_output_column.trim();
state.sublimation_status = match state.sublimation_pending_rates.as_ref() {
Some(results) => match model.push_sublimation_fitted_rates(results, output) {
Ok(()) => format!("Published fitted rate as new column '{output}'."),
Err(crate::gui::experimental_kinetics_gui::model::TGAGUIError::PostCommitWarning(warning)) => format!("Warning: {warning}"),
Err(error) => format!("Error: {error}"),
},
None => "Error: no fitted rate is waiting to be published.".into(),
};
Self::publish_status(model, &state.sublimation_status);
}
});
}
if state.sublimation_pending_result.is_some() && ui.button("Save sublimation result")
.on_hover_text("Stores the fitted Ea and k0, selected conversion range, diagnostics, and source experiment in the typed series document.")
.clicked()
{
state.sublimation_status = match Self::accept_pending_result(
&mut model.series,
&mut state.sublimation_pending_result,
) {
Ok(id) => format!("Saved sublimation result {id} to the series document."),
Err(error) => format!("Error: {error}"),
};
Self::publish_status(model, &state.sublimation_status);
}
});
});
Ok(())
}
pub fn show_combined_kinetics_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
) -> Result<(), TGAGUIError> {
if !state.combined_kinetics_open {
return Ok(());
}
egui::Window::new("Combined Kinetics Analysis")
.open(&mut state.combined_kinetics_open)
.default_size([560.0, 420.0])
.show(ui.ctx(), |ui| {
contextual_help_link(ui, "Combined Kinetics Analysis");
ui.vertical(|ui| {
ui.label("Non-isothermal combined analysis: searches model exponents and activation energy using conversion, conversion rate and temperature. Set the numeric search ranges below; calculation updates result labels without adding columns.");
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.label("n_min:");
ui.add(egui::DragValue::new(&mut state.combined_n_min).speed(0.1));
ui.label("n_max:");
ui.add(egui::DragValue::new(&mut state.combined_n_max).speed(0.1));
ui.label("n_steps:");
ui.add(egui::DragValue::new(&mut state.combined_n_steps).speed(1.0));
});
ui.horizontal(|ui| {
ui.label("m_min:");
ui.add(egui::DragValue::new(&mut state.combined_m_min).speed(0.1));
ui.label("m_max:");
ui.add(egui::DragValue::new(&mut state.combined_m_max).speed(0.1));
ui.label("m_steps:");
ui.add(egui::DragValue::new(&mut state.combined_m_steps).speed(1.0));
});
ui.horizontal(|ui| {
ui.label("Conversion η min:").on_hover_text(
"Lower conversion bound used in the fit; enter a fraction from 0 to 1, not relative mass α.",
);
ui.add(egui::DragValue::new(&mut state.combined_eta_min).speed(0.01));
ui.label("η max:").on_hover_text(
"Upper conversion bound used in the fit; enter a fraction from 0 to 1, not relative mass α.",
);
ui.add(egui::DragValue::new(&mut state.combined_eta_max).speed(0.01));
ui.label("refinement_steps:");
ui.add(
egui::DragValue::new(&mut state.combined_refinement_steps).speed(1.0),
);
});
ui.add_space(6.0);
let n_label = state
.combined_result_n
.map(|v| format!("{:.4}", v))
.unwrap_or_else(|| "-".to_string());
let m_label = state
.combined_result_m
.map(|v| format!("{:.4}", v))
.unwrap_or_else(|| "-".to_string());
let ea_label = state
.combined_result_ea_kj
.map(|v| format!("{:.2}", v))
.unwrap_or_else(|| "-".to_string());
let r2_label = state
.combined_result_r2
.map(|v| format!("{:.4}", v))
.unwrap_or_else(|| "-".to_string());
ui.horizontal(|ui| {
ui.label("n:");
ui.label(n_label);
ui.label("m:");
ui.label(m_label);
});
ui.horizontal(|ui| {
ui.label("Ea (kJ/mol):");
ui.label(ea_label);
ui.label("R2:");
ui.label(r2_label);
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label("System messages:");
ui.label(&state.combined_status);
});
if state.combined_pending_result.is_some() && ui.button("Save result to series")
.on_hover_text("Archives m, n, Ea, fit range, quality, and all contributing experiments in the typed series document.")
.clicked()
{
state.combined_status = match Self::accept_pending_result(
&mut model.series,
&mut state.combined_pending_result,
) {
Ok(id) => format!("Saved Combined analysis result {id}."),
Err(error) => format!("Error: {error}"),
};
Self::publish_status(model, &state.combined_status);
}
ui.add_space(8.0);
if ui.button("Calculate").on_hover_text("Requires non-isothermal temperature, conversion and conversion-rate data. Uses the numeric search settings; updates result labels only, with no new column.").clicked() {
state.combined_result_n = None;
state.combined_result_m = None;
state.combined_result_ea_kj = None;
state.combined_result_r2 = None;
state.combined_pending_result = None;
let status = (|| -> Result<String, TGAGUIError> {
let analysis = CombinedKineticAnalysis {
n_min: state.combined_n_min,
n_max: state.combined_n_max,
n_steps: state.combined_n_steps,
m_min: state.combined_m_min,
m_max: state.combined_m_max,
m_steps: state.combined_m_steps,
eta_min: state.combined_eta_min,
eta_max: state.combined_eta_max,
refinement_steps: state.combined_refinement_steps,
};
let cols = analysis.required_columns_by_nature();
let view = model.create_kinetic_data_view(None, cols)?;
let result = analysis.compute(&view)?;
let source_ids = view.experiments.iter().map(|experiment| experiment.meta.id.clone()).collect::<Vec<_>>();
let source_refs = view.experiments.iter().map(|experiment| AnalysisSourceRef {
experiment_identity: experiment.meta.identity.clone(),
experiment_id_snapshot: experiment.meta.id.clone(),
}).collect();
let input_columns = view.experiments.iter().map(|experiment| {
let id = &experiment.meta.id;
let bindings = model.series.get_experiment_by_id(id)?.dataset.schema().clone();
Ok::<_, TGADomainError>(format!(
"{id}: conversion={}, conversion_rate={}, temperature={}",
bindings.eta.as_deref().unwrap_or("unbound"),
bindings.deta_dt.as_deref().unwrap_or("unbound"),
bindings.temperature.as_deref().unwrap_or("unbound"),
))
}).collect::<Result<Vec<_>, TGADomainError>>()?.join("; ");
let conditions = view.experiments.iter().flat_map(|experiment| {
experiment.meta.heating_rate.map(|beta| CoefficientValue {
name: format!("beta ({})", experiment.meta.id), role: Some("heating rate".into()),
stage: None, value: beta, unit: "K/min".into(),
})
}).collect();
state.combined_pending_result = Some(AnalysisResultRecord {
id: String::new(), source_experiment_id: None,
source_experiment_ids: source_ids, source_experiments: source_refs, 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 with local refinement".into()),
x_column: Some("conversion (η)".into()), y_column: Some("conversion rate (dη/dt)".into()), x_unit: Some("1".into()), y_unit: Some("s^-1".into()),
range: Some(AnalysisRange { axis: "conversion".into(), start: state.combined_eta_min, end: state.combined_eta_max }),
excluded_range: None,
conditions,
settings: vec![
("n_min".into(), state.combined_n_min.to_string()),
("n_max".into(), state.combined_n_max.to_string()),
("n_steps".into(), state.combined_n_steps.to_string()),
("m_min".into(), state.combined_m_min.to_string()),
("m_max".into(), state.combined_m_max.to_string()),
("m_steps".into(), state.combined_m_steps.to_string()),
("refinement_steps".into(), state.combined_refinement_steps.to_string()),
("input_columns".into(), input_columns),
("model_inputs".into(), "dη/dt, conversion η, and absolute temperature T".into()),
],
diagnostics: vec![("R2".into(), result.regression.r2, "1".into())],
coefficients: vec![
CoefficientValue { name: "m".into(), role: Some("reaction order".into()), stage: None, value: result.m, unit: "1".into() },
CoefficientValue { name: "n".into(), role: Some("reaction order".into()), stage: None, value: result.n, unit: "1".into() },
CoefficientValue { name: "Ea".into(), role: Some("activation energy".into()), stage: None, value: result.ea, unit: "J/mol".into() },
],
}),
});
state.combined_result_n = Some(result.n);
state.combined_result_m = Some(result.m);
state.combined_result_ea_kj = Some(result.ea / 1000.0);
state.combined_result_r2 = Some(result.regression.r2);
Ok("Done.".to_string())
})();
state.combined_status = match status {
Ok(msg) => msg,
Err(err) => format!("Error: {err}"),
};
Self::publish_status(model, &state.combined_status);
}
});
});
Ok(())
}
pub fn show_fit_model_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
) -> Result<(), TGAGUIError> {
if !state.fit_model_open {
return Ok(());
}
egui::Window::new("Fit Model")
.open(&mut state.fit_model_open)
.default_size([620.0, 430.0])
.max_height(520.0)
.vscroll(true)
.show(ui.ctx(), |ui| {
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.strong("Single-experiment curve fit, not a kinetic method.");
contextual_help_link(ui, "Fit Model");
});
ui.label("Fit adds and plots a fitted-Y column; Evaluate prepares a preview; explicit commit creates a separate experiment.");
ui.horizontal(|ui| {
ui.label("Status:");
ui.label(&state.fit_model_status);
if let Some(current_result) = state.fit_model_result.clone() {
let session_key = Self::fit_session_key(¤t_result);
let already_saved = state.fit_saved_session_keys.contains(&session_key);
if ui.add_enabled(!already_saved, egui::Button::new(if already_saved { "Fit saved" } else { "Save fit" }))
.on_hover_text("Stores the latest successful fit snapshot in the series document; measurement columns are unchanged.")
.clicked()
{
let saved = state.fit_sessions.iter()
.find(|session| session.result == current_result)
.ok_or_else(|| "The latest fit session is no longer available.".to_string())
.and_then(fit_session_result_record);
match saved.and_then(|record| model.series.add_analysis_result(record).map_err(|error| error.to_string())) {
Ok(id) => {
state.fit_saved_session_keys.insert(session_key);
state.fit_model_status = format!("Saved fit result {id} to the series document.");
Self::publish_status(model, &state.fit_model_status);
}
Err(error) => {
state.fit_model_status = format!("Error: {error}");
Self::publish_status(model, &state.fit_model_status);
}
}
}
}
});
ui.add_space(4.0);
let exp_ids = model.list_of_experiments();
if state.fit_model_experiment_id.is_empty()
|| !exp_ids
.iter()
.any(|id| id == &state.fit_model_experiment_id)
{
state.fit_model_experiment_id = model
.get_experiment_by_selected_curve()
.ok()
.filter(|id| exp_ids.is_empty() || exp_ids.contains(id))
.or_else(|| exp_ids.first().cloned())
.unwrap_or_default();
}
ui.horizontal(|ui| {
let label = ui.label("Experiment:");
let combo = egui::ComboBox::from_id_salt("fit_model_experiment")
.selected_text(if state.fit_model_experiment_id.is_empty() {
"-"
} else {
&state.fit_model_experiment_id
})
.show_ui(ui, |ui| {
for id in &exp_ids {
ui.selectable_value(
&mut state.fit_model_experiment_id,
id.clone(),
id,
);
}
});
let _ = combo.response.labelled_by(label.id);
});
let columns = if state.fit_model_experiment_id.is_empty() {
Ok(Vec::new())
} else {
model.list_of_columns(&state.fit_model_experiment_id)
};
let selected_curve_axes = model
.get_experiment_by_selected_curve()
.ok()
.filter(|id| id == &state.fit_model_experiment_id)
.and_then(|_| Some((model.this_is_x().ok()?, model.this_is_y().ok()?)));
match columns {
Ok(columns) => {
if state.fit_model_x_col.is_empty()
|| !columns.iter().any(|col| col == &state.fit_model_x_col)
{
state.fit_model_x_col = selected_curve_axes
.as_ref()
.map(|(x, _)| x)
.filter(|x| columns.contains(x))
.cloned()
.or_else(|| {
columns.iter().find(|c| c.as_str() == "time").cloned()
})
.or_else(|| columns.iter().min().cloned())
.unwrap_or_default();
}
if state.fit_model_y_col.is_empty()
|| !columns.iter().any(|col| col == &state.fit_model_y_col)
{
state.fit_model_y_col = selected_curve_axes
.as_ref()
.map(|(_, y)| y)
.filter(|y| **y != state.fit_model_x_col && columns.contains(y))
.cloned()
.or_else(|| {
columns
.iter()
.find(|c| {
c.as_str() == "mass" && **c != state.fit_model_x_col
})
.cloned()
})
.or_else(|| {
columns
.iter()
.filter(|c| c.as_str() != state.fit_model_x_col)
.min()
.cloned()
})
.or_else(|| columns.iter().min().cloned())
.unwrap_or_default();
}
ui.horizontal(|ui| {
let label = ui.label("X:");
let combo = egui::ComboBox::from_id_salt("fit_model_x")
.selected_text(if state.fit_model_x_col.is_empty() {
"-"
} else {
&state.fit_model_x_col
})
.show_ui(ui, |ui| {
for col in &columns {
ui.selectable_value(
&mut state.fit_model_x_col,
col.clone(),
col,
);
}
});
let _ = combo.response.labelled_by(label.id);
let label = ui.label("Y:");
let combo = egui::ComboBox::from_id_salt("fit_model_y")
.selected_text(if state.fit_model_y_col.is_empty() {
"-"
} else {
&state.fit_model_y_col
})
.show_ui(ui, |ui| {
for col in &columns {
ui.selectable_value(
&mut state.fit_model_y_col,
col.clone(),
col,
);
}
});
let _ = combo.response.labelled_by(label.id);
});
ui.horizontal(|ui| {
ui.selectable_value(
&mut state.fit_model_custom_enabled,
false,
"Built-in model",
);
ui.selectable_value(
&mut state.fit_model_custom_enabled,
true,
"Custom model",
);
});
if !state.fit_model_custom_enabled {
ui.horizontal(|ui| {
let label = ui.label("Model:");
let combo = egui::ComboBox::from_id_salt("fit_model_kind")
.selected_text(state.fit_model_model.display_name())
.show_ui(ui, |ui| {
for fit_model in FittingModelName::all_for_gui() {
let changed = ui
.selectable_value(
&mut state.fit_model_model,
fit_model,
fit_model.display_name(),
)
.changed();
if changed {
if let Some(n) = fit_model.polynomial_degree() {
state.fit_model_polynomial_degree = n;
}
}
}
});
let _ = combo.response.labelled_by(label.id);
});
if state.fit_model_model.polynomial_degree().is_some() {
ui.horizontal(|ui| {
let label = ui.label("Polynomial degree:");
let response = ui.add(
egui::DragValue::new(&mut state.fit_model_polynomial_degree)
.speed(1.0)
.range(1..=12),
);
let changed = response.changed();
let _ = response.labelled_by(label.id);
if changed
|| state.fit_model_model.polynomial_degree()
!= Some(state.fit_model_polynomial_degree)
{
state.fit_model_model = FittingModelName::Polynom {
n: state.fit_model_polynomial_degree,
};
}
});
}
ui.horizontal(|ui| {
ui.label("Formula:");
ui.monospace(state.fit_model_model.equation_str());
});
egui::CollapsingHeader::new("Model equations")
.default_open(false)
.show(ui, |ui| {
egui::Grid::new("fit_model_equation_table")
.striped(true)
.show(ui, |ui| {
ui.strong("Model");
ui.strong("Formula");
ui.end_row();
for mut fit_model in FittingModelName::all_for_gui() {
if fit_model.polynomial_degree().is_some() {
fit_model = FittingModelName::Polynom {
n: state.fit_model_polynomial_degree,
};
}
ui.label(fit_model.display_name());
ui.monospace(fit_model.equation_str());
ui.end_row();
}
});
});
} else {
ui.horizontal(|ui| {
ui.selectable_value(&mut state.fit_model_custom_varpro, false, "Formula");
ui.selectable_value(&mut state.fit_model_custom_varpro, true, "Separable VarPro");
});
if state.fit_model_custom_varpro {
ui.label("VarPro fits sum(c_i * basis_i(x, parameters)); coefficients are solved linearly.");
ui.horizontal(|ui| {
let label = ui.label("Nonlinear parameters:");
let input = ui.text_edit_singleline(&mut state.fit_model_custom_varpro_parameters);
let _ = input.labelled_by(label.id);
});
ui.label("Initial guess applies to nonlinear parameters in the listed order.");
let mut remove_basis = None;
for (index, basis) in state.fit_model_custom_varpro_basis.iter_mut().enumerate() {
ui.horizontal(|ui| {
let label = ui.label("Coefficient:");
let input = ui.text_edit_singleline(&mut basis.coefficient_name);
let _ = input.labelled_by(label.id);
let label = ui.label("Parameter:");
let input = ui.text_edit_singleline(&mut basis.parameter_name);
let _ = input.labelled_by(label.id);
let label = ui.label("Basis:");
let input = ui.text_edit_singleline(&mut basis.expression);
let _ = input.labelled_by(label.id);
if ui.small_button("Remove").clicked() {
remove_basis = Some(index);
}
});
}
if let Some(index) = remove_basis {
state.fit_model_custom_varpro_basis.remove(index);
}
if ui.button("Add basis term").clicked() {
state.fit_model_custom_varpro_basis.push(CustomVarProBasis {
coefficient_name: format!("c{}", state.fit_model_custom_varpro_basis.len()),
parameter_name: "k".to_string(),
expression: "exp(-k*x)".to_string(),
});
}
} else {
ui.label("Use x for the selected X column; list all fitted symbols except x, separated by commas.");
ui.horizontal(|ui| {
let label = ui.label("Formula (y = f(x, parameters)):");
let input = ui.text_edit_singleline(&mut state.fit_model_custom_equation);
let _ = input.labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label("Fitted parameters (ordered):");
let input = ui.text_edit_singleline(&mut state.fit_model_custom_parameters);
let _ = input.labelled_by(label.id);
});
ui.horizontal(|ui| {
ui.label("Solver:");
ui.selectable_value(&mut state.fit_model_custom_backend, CustomFitBackend::LM, "LM");
ui.selectable_value(&mut state.fit_model_custom_backend, CustomFitBackend::Gavin, "Gavin");
});
}
}
ui.horizontal(|ui| {
let label = ui.label("Output column:");
let input =
ui.text_edit_singleline(&mut state.fit_model_output_col);
let _ = input.labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label("Tolerance:");
let input = ui.add(
egui::DragValue::new(&mut state.fit_model_tolerance)
.speed(1e-7)
.range(1e-12..=1e-1),
);
let _ = input.labelled_by(label.id);
let label = ui.label("Max iter:");
let input = ui.add(
egui::DragValue::new(&mut state.fit_model_max_iter)
.speed(10.0)
.range(1..=100_000),
);
let _ = input.labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(if state.fit_model_custom_enabled {
"Initial guess (required):"
} else {
"Initial guess (optional):"
});
let input =
ui.text_edit_singleline(&mut state.fit_model_initial_guess);
let _ = input.labelled_by(label.id);
});
ui.separator();
ui.strong("Fit data");
ui.horizontal(|ui| {
ui.checkbox(&mut state.fit_training_range_enabled, "Limit fit range")
.on_hover_text("Restricts measured X/Y points used to estimate model parameters. These bounds do not control Evaluate.");
if state.fit_training_range_enabled {
let label = ui.label("X start:");
let response = ui.add(egui::DragValue::new(&mut state.fit_training_start).speed(0.1));
let _ = response.labelled_by(label.id);
let label = ui.label("end:");
let response = ui.add(egui::DragValue::new(&mut state.fit_training_end).speed(0.1));
let _ = response.labelled_by(label.id);
}
});
ui.horizontal(|ui| {
ui.checkbox(&mut state.fit_gap_enabled, "Exclude missing interval from fit")
.on_hover_text("Excludes measured points in this X interval from fitting and makes Evaluate generate values for this gap. If the gap has no recorded rows, nothing is deleted.");
if state.fit_gap_enabled {
let label = ui.label("Gap start:");
let response = ui.add(egui::DragValue::new(&mut state.fit_gap_start).speed(0.1));
let _ = response.labelled_by(label.id);
let label = ui.label("end:");
let response = ui.add(egui::DragValue::new(&mut state.fit_gap_end).speed(0.1));
let _ = response.labelled_by(label.id);
}
});
ui.add_space(8.0);
if ui.button("Fit").on_hover_text("Requires an experiment and X/Y columns. Built-in models may use their default initial guess. Custom fits require one finite initial value per listed parameter; VarPro requires explicit separable basis terms. Adds a new fitted column to the same experiment, plots it, and keeps the model available for Evaluate. Existing columns are not overwritten.").clicked() {
state.fit_model_result = None;
let status = (|| -> Result<String, TGAGUIError> {
if state.fit_model_experiment_id.is_empty()
|| state.fit_model_x_col.is_empty()
|| state.fit_model_y_col.is_empty()
{
return Err(TGAGUIError::BindingError(
"Choose experiment, X and Y columns first.".to_string(),
));
}
let mut request = FitColumnRequest::new(
state.fit_model_experiment_id.clone(),
state.fit_model_x_col.clone(),
state.fit_model_y_col.clone(),
state.fit_model_model,
)
.with_tolerance(state.fit_model_tolerance)
.with_max_iterations(state.fit_model_max_iter);
if state.fit_model_custom_enabled {
let custom = if state.fit_model_custom_varpro {
CustomFitDefinition::VarPro {
nonlinear_parameters: parse_fit_names(
&state.fit_model_custom_varpro_parameters,
),
basis: state.fit_model_custom_varpro_basis.clone(),
}
} else {
CustomFitDefinition::Formula {
equation: state.fit_model_custom_equation.clone(),
parameters: parse_fit_names(
&state.fit_model_custom_parameters,
),
backend: state.fit_model_custom_backend,
}
};
request = request.with_custom_model(custom);
}
if state.fit_training_range_enabled {
request = request.with_training_range(
state.fit_training_start,
state.fit_training_end,
);
}
if state.fit_gap_enabled {
request = request.excluding_range(
state.fit_gap_start,
state.fit_gap_end,
);
}
let output = state.fit_model_output_col.trim();
if !output.is_empty() {
request = request.with_output_col(output.to_string());
}
if let Some(initial_guess) =
parse_fit_initial_guess(&state.fit_model_initial_guess)?
{
request = request.with_initial_guess(initial_guess);
}
let session = model.fit_session_and_plot(request)?;
let result = session.result.clone();
let used_pairs = session.training_x.len();
let skipped_null_rows = session.skipped_null_rows;
state
.fit_saved_session_keys
.remove(&Self::fit_session_key(&result));
state.fit_model_result = Some(result.clone());
state.fit_sessions.retain(|existing| {
existing.result.experiment_id != result.experiment_id
|| existing.result.y_col != result.y_col
|| existing.result.x_col != result.x_col
});
state.fit_sessions.push(session);
state.fit_pending_batch = None;
Ok(format!("Fit added '{}' and plotted. R2={:.6}; used pairs: {}; source rows with null inputs: {}; measured data unchanged.", result.output_col, result.r2, used_pairs, skipped_null_rows))
})();
state.fit_model_status = match status {
Ok(msg) => msg,
Err(err) => format!("Error: {err}"),
};
Self::publish_status(model, &state.fit_model_status);
}
if !state.fit_sessions.is_empty() {
ui.separator();
ui.strong("Stored fits");
egui::Grid::new("fit_model_session_results")
.striped(true)
.show(ui, |ui| {
ui.strong("Y");
ui.strong("Experiment");
ui.strong("Model");
ui.strong("Equation");
ui.strong("R2");
ui.strong("Coefficients");
ui.strong("Side RMSE");
ui.strong("Archive");
ui.end_row();
for session in &state.fit_sessions {
let result = &session.result;
let coefficients = result.coefficients.iter()
.map(|(name, value)| format!("{name}={value:.5e}"))
.collect::<Vec<_>>().join(", ");
let residuals = match (session.left_rmse, session.right_rmse) {
(Some(left), Some(right)) => format!("{left:.3e} / {right:.3e}"),
_ => "-".to_string(),
};
ui.label(&result.y_col);
ui.label(&result.experiment_id);
ui.label(&result.model_name);
ui.monospace(&result.equation);
ui.label(format!("{:.6}", result.r2));
ui.monospace(coefficients);
ui.label(residuals);
let session_key = Self::fit_session_key(result);
let already_saved = state.fit_saved_session_keys.contains(&session_key);
if ui.add_enabled(
!already_saved,
egui::Button::new(if already_saved {
format!("Saved {}", result.experiment_id)
} else {
format!("Save {}", result.experiment_id)
}),
)
.on_hover_text("Stores this successful fit and its source conditions in the current series document; measurement columns are unchanged.")
.clicked()
{
match fit_session_result_record(session) {
Ok(record) => match model.series.add_analysis_result(record) {
Ok(id) => {
state.fit_saved_session_keys.insert(session_key);
state.fit_model_status = format!("Saved fit result {id} to the series document.");
Self::publish_status(model, &state.fit_model_status);
}
Err(error) => Self::publish_status(model, &error.to_string()),
},
Err(error) => Self::publish_status(model, &error),
}
}
ui.end_row();
}
});
}
ui.separator();
ui.horizontal(|ui| {
ui.strong("Evaluate on a new X grid");
});
ui.label("This is optional reconstruction, not required to inspect the fitted curve.");
ui.horizontal(|ui| {
if state.fit_gap_enabled {
ui.label(format!("Fill excluded interval [{:.4}, {:.4}]", state.fit_gap_start, state.fit_gap_end));
} else {
let label = ui.label("Extrapolation X start:");
let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_start).speed(0.1));
let _ = response.labelled_by(label.id);
let label = ui.label("end:");
let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_end).speed(0.1));
let _ = response.labelled_by(label.id);
}
let label = ui.label("Points:");
let response = ui.add(egui::DragValue::new(&mut state.fit_evaluation_points).range(1..=100_000));
let _ = response.labelled_by(label.id);
});
ui.horizontal(|ui| {
if ui.button("Evaluate fitted columns")
.on_hover_text("Evaluates the retained fit models on a shared new X grid for extrapolation or gap reconstruction. This does not replace the fitted column; review the preview and explicitly create a reconstructed experiment.")
.clicked()
{
state.fit_pending_batch = None;
let matching_sessions: Vec<_> = state
.fit_sessions
.iter()
.filter(|session| {
session.result.experiment_id
== state.fit_model_experiment_id
&& session.result.x_col == state.fit_model_x_col
})
.cloned()
.collect();
let mode = if state.fit_gap_enabled {
FitEvaluationMode::FillGap {
start: state.fit_gap_start,
end: state.fit_gap_end,
missing_points: state.fit_evaluation_points,
}
} else {
FitEvaluationMode::Extrapolate {
start: state.fit_evaluation_start,
end: state.fit_evaluation_end,
points: state.fit_evaluation_points,
}
};
if matching_sessions.is_empty() {
state.fit_model_status = format!(
"Evaluation failed: no fitted model for experiment '{}' and X column '{}'.",
state.fit_model_experiment_id,
state.fit_model_x_col
);
} else {
match evaluate_fit_batch(&matching_sessions, mode) {
Ok(batch) => {
state.fit_reconstructed_experiment_id = format!(
"{}_reconstructed",
batch.source_experiment_id
);
state.fit_pending_batch = Some(batch);
state.fit_model_status = "Evaluation ready. Review and commit it in Column Manager.".to_string();
}
Err(error) => {
state.fit_model_status =
format!("Evaluation failed: {error}")
}
}
}
}
if ui.button("Clear fit sessions").clicked() {
state.fit_sessions.clear();
state.fit_model_result = None;
state.fit_pending_batch = None;
}
ui.label(format!("{} fitted column(s)", state.fit_sessions.len()));
});
}
Err(err) => {
ui.label(format!("Cannot read columns: {err}"));
}
}
});
});
Ok(())
}
pub fn show_windows(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
file_manager: &mut NewExperimentDialogState,
) -> Result<(), TGAGUIError> {
Self::show_isoconversional_window(ui, model, state)?;
Self::show_kissinger_window(ui, model, state)?;
Self::show_combined_kinetics_window(ui, model, state)?;
Self::show_sublimation_window(ui, model, state)?;
Self::show_fit_model_window(ui, model, state)?;
Self::show_coefficients_window(ui, model, state, file_manager);
Ok(())
}
fn show_coefficients_window(
ui: &mut egui::Ui,
model: &mut PlotModel,
state: &mut KineticMethodsWindowState,
file_manager: &mut NewExperimentDialogState,
) {
if !state.coefficients_open {
return;
}
egui::Window::new("Coefficients Handling")
.open(&mut state.coefficients_open)
.default_size([720.0, 460.0])
.vscroll(true)
.show(ui.ctx(), |ui| {
ui.horizontal(|ui| {
ui.label("Select the same explicitly typed rate coefficient and stage from independent experiments. Rates are converted to s^-1 before regression.")
.on_hover_text("Arrhenius analysis uses only coefficients explicitly typed as rate constants, with known absolute temperature and supported time units. Two alternative fits from one experiment cannot be used as independent points.");
contextual_help_link(ui, "Coefficients Handling");
});
if ui.button("Export coefficient table as CSV")
.on_hover_text("Exports one row per coefficient for spreadsheets. Use Save for the complete typed series document.")
.clicked()
{
let csv = crate::Kinetics::experimental_kinetics::analysis_results::coefficient_table_csv(model.series.analysis_results());
file_manager.export_coefficient_table(model, csv);
}
ui.separator();
ui.strong("Archived coefficients")
.on_hover_text("Expand a result to inspect its source, model, fit interval, conditions, settings, diagnostics, and all named coefficients.");
ui.horizontal(|ui| {
ui.label("Experiment:");
ui.add(
egui::TextEdit::singleline(
&mut state.coefficients_archive_filter_experiment,
)
.hint_text("Filter by experiment")
.desired_width(150.0),
)
.on_hover_text("Filter archive records by their saved source experiment names.");
ui.label("Model/method:");
ui.add(
egui::TextEdit::singleline(&mut state.coefficients_archive_filter_model)
.hint_text("Filter by method or model")
.desired_width(170.0),
);
ui.label("Coefficient:");
ui.add(
egui::TextEdit::singleline(
&mut state.coefficients_archive_filter_parameter,
)
.hint_text("Filter by coefficient")
.desired_width(150.0),
);
});
let archive_max_height = (ui.available_height() - 230.0).max(120.0);
egui::Resize::default()
.id_salt("coefficients_archive_resize")
.default_height(state.coefficients_archive_height.min(archive_max_height))
.min_size(egui::vec2(340.0, 120.0))
.max_height(archive_max_height)
.resizable(egui::Vec2b::new(false, true))
.show(ui, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
for record in model.series.analysis_results().records() {
let source = archived_source_label(record);
let (method, model_name, solver, range, formula, conditions, settings, diagnostics, x_columns, excluded_range, coefficients): (String, String, String, String, Option<String>, Vec<CoefficientValue>, Vec<(String, String)>, Vec<(String, f64, String)>, String, String, Vec<CoefficientValue>) = match &record.kind {
AnalysisResultKind::ParameterSet(set) => {
let range = set.range.as_ref().map(|r| format!("{}: [{:.4}, {:.4}]", r.axis, r.start, r.end)).unwrap_or_else(|| "not specified".into());
let x_columns = format!("X: {} ({}) · Y: {} ({})", set.x_column.as_deref().unwrap_or("-"), set.x_unit.as_deref().unwrap_or("-"), set.y_column.as_deref().unwrap_or("-"), set.y_unit.as_deref().unwrap_or("-"));
let excluded_range = set.excluded_range.as_ref().map(|r| format!("{}: [{:.4}, {:.4}]", r.axis, r.start, r.end)).unwrap_or_else(|| "none".into());
(set.method.clone(), set.model.clone(), set.solver.clone().unwrap_or_else(|| "not specified".into()), range, set.formula.clone(), set.conditions.clone(), set.settings.clone(), set.diagnostics.clone(), x_columns, excluded_range, set.coefficients.clone())
}
AnalysisResultKind::ArrheniusFit(fit) => {
let mut diagnostics = Vec::new();
if let Some(r2) = fit.r_squared_log_space {
diagnostics.push(("R2(log k)".into(), r2, "1".into()));
}
if let Some(dof) = fit.residual_degrees_of_freedom {
diagnostics.push(("Residual degrees of freedom".into(), dof as f64, "points".into()));
}
if let Some(ln_a) = fit.ln_pre_exponential {
diagnostics.push(("ln(A)".into(), ln_a, "ln(s^-1)".into()));
}
let mut coefficients = vec![CoefficientValue {
name: "Ea".into(), role: Some("activation energy".into()), stage: None,
value: fit.activation_energy_j_per_mol, unit: "J/mol".into(),
}];
if let Some(ln_a) = fit.ln_pre_exponential {
coefficients.push(CoefficientValue {
name: "ln(A)".into(), role: Some("log pre-exponential factor".into()), stage: None,
value: ln_a, unit: "ln(s^-1)".into(),
});
}
if let Some(a) = fit.pre_exponential_per_second {
coefficients.push(CoefficientValue {
name: "A".into(), role: Some("pre-exponential factor".into()), stage: None,
value: a, unit: "s^-1".into(),
});
}
(
"Arrhenius regression".into(),
format!("ln(k) vs 1/T [{}]", if fit.physical_stage_label.is_empty() { &fit.coefficient_name } else { &fit.physical_stage_label }),
"OLS".into(), "selected coefficient points".into(), None, vec![],
vec![("Fit status".into(), format!("physical stage={}; residual_dof={}; R2={}; R2_status={:?}; A={:?}",
if fit.physical_stage_label.is_empty() { "unspecified".into() } else { fit.physical_stage_label.clone() },
fit.residual_degrees_of_freedom.map_or_else(|| "unknown".into(), |n| n.to_string()),
fit.r_squared_log_space.map_or_else(|| "undefined".into(), |v| format!("{v:.6}")),
fit.r_squared_status,
fit.pre_exponential_status))],
diagnostics,
fit.selected_components.iter().map(|component| format!(
"{}: {} [{}] = {:.5e} {}",
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("; "),
"none".into(), coefficients,
)
},
};
let search_matches = |query: &str, text: &str| {
query.trim().is_empty()
|| text.to_lowercase().contains(&query.trim().to_lowercase())
};
let parameter_names = coefficients
.iter()
.map(|coefficient| coefficient.name.as_str())
.collect::<Vec<_>>()
.join(" ");
if !search_matches(&state.coefficients_archive_filter_experiment, &source)
|| !search_matches(
&state.coefficients_archive_filter_model,
&format!("{method} {model_name}"),
)
|| !search_matches(
&state.coefficients_archive_filter_parameter,
¶meter_names,
)
{
continue;
}
egui::CollapsingHeader::new(format!("{} | {} | {} | {}", record.id, source, method, model_name))
.show(ui, |ui| {
ui.label(format!("Range: {range}"));
ui.label(format!("Solver: {solver}"));
ui.label(&x_columns);
ui.label(format!("Excluded range: {excluded_range}"));
if let Some(formula) = formula { ui.monospace(formula); }
if !conditions.is_empty() {
ui.label(format!("Conditions: {}", conditions.iter().map(|c| format!("{}={:.5e} {}", c.name, c.value, c.unit)).collect::<Vec<_>>().join(", ")));
}
if !settings.is_empty() { ui.label(format!("Settings: {}", settings.iter().map(|(name, value)| format!("{name}={value}")).collect::<Vec<_>>().join(", "))); }
if !diagnostics.is_empty() { ui.label(format!("Diagnostics: {}", diagnostics.iter().map(|(name, value, unit)| format!("{name}={value:.6e} {unit}")).collect::<Vec<_>>().join(", "))); }
if let AnalysisResultKind::ParameterSet(set) = &record.kind {
if let Some(reason) = arrhenius_unavailable_reason(set) {
ui.label(format!("Not available as Arrhenius input: {reason}."));
}
}
if method == "Combined kinetic analysis" {
for (name, value) in &settings {
if name == "input_columns" || name == "model_inputs" {
ui.label(format!("Inputs: {value}"));
}
}
}
if method == "Kissinger" {
let peaks = conditions.iter().filter(|condition| {
condition.role.as_deref() == Some("reaction-rate peak temperature")
}).collect::<Vec<_>>();
if !peaks.is_empty() {
ui.strong("Peak observations");
egui::Grid::new(format!("kissinger_peaks_{}", record.id))
.striped(true)
.show(ui, |ui| {
ui.strong("Experiment");
ui.strong("Heating rate");
ui.strong("T peak (K)");
ui.end_row();
for peak in peaks {
let experiment = peak.name.strip_prefix("T_peak (").and_then(|name| name.strip_suffix(')')).unwrap_or("-");
let beta_name = format!("heating_rate ({experiment})");
let beta = conditions.iter().find(|condition| condition.name == beta_name);
ui.label(experiment);
ui.label(beta.map(|value| format!("{:.4} {}", value.value, value.unit)).unwrap_or_else(|| "-".into()));
ui.label(format!("{:.4} {}", peak.value, peak.unit));
ui.end_row();
}
});
}
}
if let AnalysisResultKind::ArrheniusFit(_) = &record.kind {
if ui.button("Show archived Arrhenius plot").clicked() {
state.coefficients_archive_plot_result_id = Some(record.id.clone());
}
}
egui::Grid::new(format!("coefficients_{}", record.id)).striped(true).show(ui, |ui| {
ui.strong("Stage"); ui.strong("Coefficient"); ui.strong("Role"); ui.strong("Value"); ui.strong("Unit"); ui.end_row();
for coefficient in coefficients {
ui.label(coefficient.stage.as_deref().unwrap_or("-"));
ui.label(coefficient.name);
ui.label(coefficient.role.as_deref().unwrap_or("-"));
ui.label(format!("{:.7e}", coefficient.value));
ui.label(coefficient.unit);
ui.end_row();
}
});
});
}
});
});
ui.separator();
if let Some(result_id) = state.coefficients_archive_plot_result_id.clone() {
let archived = model
.series
.analysis_results()
.get(&result_id)
.and_then(|record| match &record.kind {
AnalysisResultKind::ArrheniusFit(fit) => {
Some((fit.clone(), archived_source_label(record)))
}
AnalysisResultKind::ParameterSet(_) => None,
});
if let Some((fit, source_names)) = archived {
ui.horizontal(|ui| {
ui.heading("Archived Arrhenius plot");
ui.label(format!("Result: {result_id}"));
if ui.button("Close archived plot").clicked() {
state.coefficients_archive_plot_result_id = None;
}
});
ui.horizontal(|ui| {
ui.selectable_value(
&mut state.coefficients_archive_plot_mode,
ArrheniusPlotMode::RateVsTemperature,
"k(T)",
);
ui.selectable_value(
&mut state.coefficients_archive_plot_mode,
ArrheniusPlotMode::LogRateVsInverseTemperature,
"ln(k) vs 1/T",
);
});
let min_temperature = fit
.points
.iter()
.map(|point| point.temperature_kelvin)
.fold(f64::INFINITY, f64::min);
let max_temperature = fit
.points
.iter()
.map(|point| point.temperature_kelvin)
.fold(f64::NEG_INFINITY, f64::max);
let stage = if fit.physical_stage_label.is_empty() {
if fit.coefficient_name.is_empty() {
"unspecified".to_string()
} else {
fit.coefficient_name.clone()
}
} else {
fit.physical_stage_label.clone()
};
let r2 = fit.r_squared_log_space.map_or_else(
|| format!("undefined ({:?})", fit.r_squared_status),
|value| format!("{value:.6} ({:?})", fit.r_squared_status),
);
ui.label(format!(
"Sources: {source_names} | Physical stage: {stage} | N={} | T=[{min_temperature:.3}, {max_temperature:.3}] K | R²(log k)={r2}",
fit.points.len(),
));
let (points, regression_line, x_label, y_label) = match state.coefficients_archive_plot_mode {
ArrheniusPlotMode::RateVsTemperature => {
let points = fit.points.iter().map(|point| {
[point.temperature_kelvin, point.rate_per_second]
}).collect::<Vec<_>>();
let line = fit.pre_exponential_per_second.map(|a| {
(0..100).map(|index| {
let temperature = min_temperature
+ (max_temperature - min_temperature)
* index as f64 / 99.0;
let rate = a * (-fit.activation_energy_j_per_mol
/ (crate::Kinetics::experimental_kinetics::analysis_results::GAS_CONSTANT_J_PER_MOL_K
* temperature)).exp();
[temperature, rate]
}).collect::<Vec<_>>()
});
(points, line, "Temperature (K)", "Rate constant k (s^-1)")
}
ArrheniusPlotMode::LogRateVsInverseTemperature => {
let points = fit.points.iter().filter_map(|point| {
(point.rate_per_second > 0.0).then_some([
1.0 / point.temperature_kelvin,
point.rate_per_second.ln(),
])
}).collect::<Vec<_>>();
let mut bounds = points.iter().map(|point| point[0]);
let x_min = bounds.next().unwrap_or(0.0).min(
points.iter().map(|point| point[0]).fold(f64::INFINITY, f64::min),
);
let x_max = points.iter().map(|point| point[0]).fold(f64::NEG_INFINITY, f64::max);
let line = fit.ln_pre_exponential.map(|ln_a| {
(0..100).map(|index| {
let inverse_temperature = x_min
+ (x_max - x_min) * index as f64 / 99.0;
[inverse_temperature, ln_a
- fit.activation_energy_j_per_mol
/ crate::Kinetics::experimental_kinetics::analysis_results::GAS_CONSTANT_J_PER_MOL_K
* inverse_temperature]
}).collect::<Vec<_>>()
});
(points, line, "1 / Temperature (K^-1)", "ln(k / s^-1)")
}
};
egui_plot::Plot::new(format!("archived_arrhenius_plot_{result_id}"))
.height(250.0)
.x_axis_label(x_label)
.y_axis_label(y_label)
.show(ui, |plot_ui| {
plot_ui.points(egui_plot::Points::new("Archived data", points));
if let Some(line) = regression_line {
plot_ui.line(egui_plot::Line::new("Arrhenius regression", line));
}
});
if state.coefficients_archive_plot_mode == ArrheniusPlotMode::RateVsTemperature
&& fit.pre_exponential_per_second.is_none()
{
ui.label(format!(
"k(T) regression line unavailable: A is not representable ({:?}); the ln(k) plot remains available.",
fit.pre_exponential_status
));
}
} else {
ui.label("The selected archived Arrhenius result is no longer available.");
state.coefficients_archive_plot_result_id = None;
}
ui.separator();
}
ui.strong("Arrhenius analysis (optional)")
.on_hover_text("Choose one rate component per independent experiment, then assign the selected components to one physical stage. Component names may differ between fits; no stage is inferred from rate magnitude.");
let entries: Vec<_> = model.series.analysis_results().records().iter().flat_map(|record| {
let AnalysisResultKind::ParameterSet(fit) = &record.kind else { return Vec::new() };
let Some(temperature) = fit.conditions.iter().find(|condition| condition.name == "temperature" && condition.unit == "K").map(|condition| condition.value) else { return Vec::new() };
let experiment_id = record.source_experiment_ids.first().cloned().or_else(|| record.source_experiment_id.clone()).unwrap_or_default();
let experiment_identity = record.source_experiments.first().map(|source| source.experiment_identity.clone()).filter(|identity| !identity.is_empty()).unwrap_or_else(|| experiment_id.clone());
fit.coefficients.iter().filter_map(move |rate| {
if rate.role.as_deref() != Some("rate constant") { return None; }
let factor = match rate.unit.as_str() { "s^-1" => 1.0, "min^-1" => 1.0 / 60.0, "h^-1" => 1.0 / 3600.0, _ => return None };
let amplitude = fit.coefficients.iter().find(|coefficient| {
coefficient.role.as_deref() == Some("amplitude") && coefficient.stage == rate.stage
}).map(|coefficient| format!("{} = {:.5e} {}", coefficient.name, coefficient.value, coefficient.unit)).unwrap_or_else(|| "-".into());
Some((CoefficientSelection { result_id: record.id.clone(), coefficient_name: rate.name.clone(), stage: rate.stage.clone() }, experiment_id.clone(), experiment_identity.clone(), temperature, rate.value, rate.unit.clone(), rate.value * factor, fit.model.clone(), amplitude))
}).collect::<Vec<_>>()
}).collect();
if entries.is_empty() {
ui.label("No explicitly typed rate coefficients with known temperature and supported time units.");
} else {
ui.horizontal(|ui| {
ui.label("Physical stage represented by selected components:");
if ui.text_edit_singleline(&mut state.coefficients_physical_stage)
.on_hover_text("This is your scientific assignment, e.g. 'fast reaction step'. It is stored with the Arrhenius result.").changed() {
state.coefficients_pending_result = None;
}
});
egui::Grid::new("coefficient_handling_entries").striped(true).show(ui, |ui| {
ui.strong("Use"); ui.strong("Experiment"); ui.strong("Fit model"); ui.strong("Component / stage"); ui.strong("Amplitude"); ui.strong("T (K)");
ui.strong("Rate (source)"); ui.strong("Rate (s^-1)"); ui.end_row();
for (selection, exp, identity, temp, rate, unit, normalized, fit_model, amplitude) in &entries {
let mut selected = state.coefficients_selected.contains(selection);
if ui.checkbox(&mut selected, format!("Select {} · {} · {}", selection.result_id, selection.coefficient_name, selection.stage.as_deref().unwrap_or("un-staged"))).changed() {
state.coefficients_pending_result = None;
state.coefficients_status.clear();
if selected {
state.coefficients_selected.retain(|existing| {
!entries.iter().any(|(candidate, _, candidate_identity, ..)| {
candidate == existing && candidate_identity == identity
})
});
state.coefficients_selected.push(selection.clone());
} else { state.coefficients_selected.retain(|existing| existing != selection); }
}
ui.label(exp); ui.label(fit_model); ui.label(format!("{} / {}", selection.coefficient_name, selection.stage.as_deref().unwrap_or("-"))); ui.label(amplitude); ui.label(format!("{temp:.4}"));
ui.label(format!("{rate:.5e} {unit}")); ui.label(format!("{normalized:.5e}")); ui.end_row();
}
});
}
ui.horizontal(|ui| {
if ui.button("Calculate Arrhenius fit").clicked() {
let selected: Vec<_> = entries.iter().filter(|(selection, ..)| state.coefficients_selected.contains(selection)).collect();
let result = (|| -> Result<AnalysisResultRecord, String> {
if state.coefficients_physical_stage.trim().is_empty() {
return Err("Enter the physical stage represented by these rate components".into());
}
if selected.len() != state.coefficients_selected.len() {
return Err("A selected coefficient is no longer available in the current catalogue".into());
}
let points = selected.iter().map(|(selection, exp, identity, temp, _, _, normalized, ..)| ArrheniusPoint {
fit_result_id: selection.result_id.clone(), experiment_identity: identity.clone(),
experiment_id: exp.clone(), temperature_kelvin: *temp, rate_per_second: *normalized,
}).collect::<Vec<_>>();
let ids = selected.iter().map(|(selection, ..)| selection.result_id.clone()).collect();
let mut fit = fit_arrhenius(ids, points)?;
fit.physical_stage_label = state.coefficients_physical_stage.trim().to_string();
fit.selected_components = selected.iter().map(|(selection, _, _, _, rate, unit, _, ..)| {
crate::Kinetics::experimental_kinetics::analysis_results::ArrheniusComponentSelection {
fit_result_id: selection.result_id.clone(),
coefficient_name: selection.coefficient_name.clone(),
coefficient_stage: selection.stage.clone(),
source_rate_value: *rate,
source_rate_unit: unit.clone(),
}
}).collect();
let source_experiments = selected.iter().map(|(_, exp, identity, ..)| AnalysisSourceRef {
experiment_identity: identity.clone(), experiment_id_snapshot: exp.clone(),
}).collect();
Ok(AnalysisResultRecord { id: String::new(), source_experiment_id: None, source_experiment_ids: vec![],
source_experiments, parent_result_ids: fit.parent_fit_ids.clone(), kind: AnalysisResultKind::ArrheniusFit(fit) })
})();
match result {
Ok(record) => {
if let AnalysisResultKind::ArrheniusFit(ref fit) = record.kind {
let a_text = fit.pre_exponential_per_second.map_or_else(
|| format!("not representable ({:?})", fit.pre_exponential_status),
|a| format!("{a:.5e} s^-1"),
);
let r2_text = fit.r_squared_log_space.map_or_else(
|| "undefined for constant log(rate)".to_string(),
|r2| format!("{r2:.6}"),
);
let dof_text = fit.residual_degrees_of_freedom.map_or_else(
|| "unknown".to_string(),
|dof| dof.to_string(),
);
state.coefficients_status = format!(
"Ea = {:.5} kJ/mol; A = {a_text}; R²(log k) = {r2_text}; R² status = {:?}; residual d.f. = {dof_text}",
fit.activation_energy_j_per_mol / 1000.0,
fit.r_squared_status,
);
}
state.coefficients_pending_result = Some(record);
}
Err(error) => { state.coefficients_status = error; state.coefficients_pending_result = None; }
}
}
if state.coefficients_pending_result.is_some() && ui.button("Save Arrhenius result").clicked() {
state.coefficients_status = match Self::accept_pending_result(
&mut model.series,
&mut state.coefficients_pending_result,
) {
Ok(id) => format!("Saved Arrhenius result {id} to the series document."),
Err(error) => format!("Error: {error}"),
};
}
});
if !state.coefficients_status.is_empty() { ui.label(&state.coefficients_status); }
if let Some(AnalysisResultRecord { kind: AnalysisResultKind::ArrheniusFit(fit), .. }) = &state.coefficients_pending_result {
let points: Vec<[f64; 2]> = fit.points.iter().map(|point| [point.temperature_kelvin, point.rate_per_second]).collect();
let min_t = fit.points.iter().map(|point| point.temperature_kelvin).fold(f64::INFINITY, f64::min);
let max_t = fit.points.iter().map(|point| point.temperature_kelvin).fold(f64::NEG_INFINITY, f64::max);
let curve = fit.pre_exponential_per_second.map(|a| (0..100).map(|i| {
let t = min_t + (max_t - min_t) * i as f64 / 99.0;
let k = a * (-fit.activation_energy_j_per_mol / (crate::Kinetics::experimental_kinetics::analysis_results::GAS_CONSTANT_J_PER_MOL_K * t)).exp();
[t, k]
}).collect::<Vec<_>>());
let coefficient_label = if fit.physical_stage_label.is_empty() { "k" } else { &fit.physical_stage_label };
ui.label(format!("Physical stage {coefficient_label}: selected rate components versus absolute temperature"));
egui_plot::Plot::new("coefficients_arrhenius_plot")
.height(240.0)
.x_axis_label("Temperature (K)")
.y_axis_label("Rate constant (s^-1)")
.show(ui, |plot_ui| {
plot_ui.points(egui_plot::Points::new("Selected fit results", points));
if let Some(curve) = curve {
plot_ui.line(egui_plot::Line::new("Arrhenius regression", curve));
}
});
if fit.pre_exponential_per_second.is_none() {
ui.label(format!(
"Regression curve omitted: A is not representable ({:?}); ln(A) remains stored.",
fit.pre_exponential_status
));
}
}
});
}
}
fn archived_source_label(record: &AnalysisResultRecord) -> String {
if !record.source_experiment_ids.is_empty() {
return record.source_experiment_ids.join(", ");
}
if let Some(source) = &record.source_experiment_id {
return source.clone();
}
if !record.source_experiments.is_empty() {
return record
.source_experiments
.iter()
.map(|source| source.experiment_id_snapshot.as_str())
.collect::<Vec<_>>()
.join(", ");
}
if let AnalysisResultKind::ArrheniusFit(fit) = &record.kind {
let names = fit
.points
.iter()
.map(|point| point.experiment_id.as_str())
.collect::<Vec<_>>();
if !names.is_empty() {
return names.join(", ");
}
}
"historical source unavailable".into()
}
fn arrhenius_unavailable_reason(fit: &ParameterSetRecord) -> Option<&'static str> {
let Some(temperature) = fit
.conditions
.iter()
.find(|condition| condition.name == "temperature" && condition.unit == "K")
else {
return Some("no stored absolute temperature in kelvin");
};
if !temperature.value.is_finite() || temperature.value <= 0.0 {
return Some("stored absolute temperature is not finite and positive");
}
let typed_rates = fit
.coefficients
.iter()
.filter(|coefficient| coefficient.role.as_deref() == Some("rate constant"))
.collect::<Vec<_>>();
if typed_rates.is_empty() {
return Some("no coefficient is typed as a rate constant");
}
if !typed_rates
.iter()
.any(|coefficient| matches!(coefficient.unit.as_str(), "s^-1" | "min^-1" | "h^-1"))
{
return Some("rate-constant units are unsupported; expected s^-1, min^-1, or h^-1");
}
None
}
fn parse_fit_initial_guess(raw: &str) -> Result<Option<Vec<f64>>, TGAGUIError> {
let raw = raw.trim();
if raw.is_empty() {
return Ok(None);
}
let mut values = Vec::new();
for token in raw
.split(|ch: char| ch == ',' || ch == ';' || ch.is_whitespace())
.filter(|token| !token.trim().is_empty())
{
let value = token.trim().parse::<f64>().map_err(|err| {
TGAGUIError::BindingError(format!(
"Cannot parse initial guess value '{}': {}",
token, err
))
})?;
values.push(value);
}
Ok(Some(values))
}
fn fit_session_result_record(session: &FitColumnSession) -> Result<AnalysisResultRecord, String> {
let result = &session.result;
let coefficient_unit = |name: &str| {
let name_lower = name.to_ascii_lowercase();
let known_rate_parameter = match result.model_name.as_str() {
"DecExp" => name_lower == "k",
"TwoExp" => name_lower == "p" || name_lower == "k",
"ThreeExp" => ["p", "k", "r"].contains(&name_lower.as_str()),
_ => false,
};
if known_rate_parameter {
match session.x_unit {
crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Second => {
"s^-1"
}
crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Minute => {
"min^-1"
}
crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Hour => {
"h^-1"
}
_ => "unknown",
}
.to_string()
} else {
"model-dependent".to_string()
}
};
Ok(AnalysisResultRecord {
id: String::new(),
source_experiment_id: Some(result.experiment_id.clone()),
source_experiment_ids: vec![result.experiment_id.clone()],
source_experiments: vec![AnalysisSourceRef {
experiment_identity: session.source_experiment_identity.clone(),
experiment_id_snapshot: session.source_experiment_id_snapshot.clone(),
}],
parent_result_ids: vec![],
kind: AnalysisResultKind::ParameterSet(ParameterSetRecord {
method: "Curve fit".into(),
model: result.model_name.clone(),
formula: Some(result.equation.clone()),
solver: Some(result.method.clone()),
x_column: Some(result.x_col.clone()),
y_column: Some(result.y_col.clone()),
x_unit: Some(format!("{:?}", session.x_unit)),
y_unit: Some(format!("{:?}", session.y_unit)),
range: Some(AnalysisRange {
axis: result.x_col.clone(),
start: session.training_range.0,
end: session.training_range.1,
}),
excluded_range: session.excluded_range.map(|(start, end)| AnalysisRange {
axis: result.x_col.clone(),
start,
end,
}),
conditions: [
session
.source_isothermal_temperature
.map(|value| CoefficientValue {
name: "temperature".into(),
role: Some("isothermal temperature".into()),
stage: None,
value,
unit: "K".into(),
}),
session.source_heating_rate.map(|value| CoefficientValue {
name: "heating_rate".into(),
role: Some("heating rate".into()),
stage: None,
value,
unit: "K/min".into(),
}),
]
.into_iter()
.flatten()
.collect(),
settings: vec![
("tolerance".into(), result.tolerance.to_string()),
("max_iterations".into(), result.max_iter.to_string()),
(
"initial_guess_used".into(),
result
.initial_guess
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(";"),
),
],
diagnostics: [
Some(("R2".into(), result.r2, "1".into())),
session
.left_rmse
.map(|value| ("left_gap_RMSE".into(), value, session.y_unit.to_string())),
session
.right_rmse
.map(|value| ("right_gap_RMSE".into(), value, session.y_unit.to_string())),
]
.into_iter()
.flatten()
.collect(),
coefficients: result
.coefficients
.iter()
.map(|(name, value)| {
let normalized = name.to_ascii_lowercase();
let digit_start = normalized
.trim_end_matches(|ch: char| ch.is_ascii_digit())
.len();
let suffix = &normalized[digit_start..];
let (role, component) = match result.model_name.as_str() {
"DecExp" if normalized == "k" => (Some("rate constant"), None),
"DecExp" if normalized == "c" => (Some("amplitude"), None),
"TwoExp" if normalized == "p" => {
(Some("rate constant"), Some("component 1"))
}
"TwoExp" if normalized == "a" => (Some("amplitude"), Some("component 1")),
"TwoExp" if normalized == "k" => {
(Some("rate constant"), Some("component 2"))
}
"TwoExp" if normalized == "b" => (Some("amplitude"), Some("component 2")),
"ThreeExp" if normalized == "p" => {
(Some("rate constant"), Some("component 1"))
}
"ThreeExp" if normalized == "a" => (Some("amplitude"), Some("component 1")),
"ThreeExp" if normalized == "k" => {
(Some("rate constant"), Some("component 2"))
}
"ThreeExp" if normalized == "b" => (Some("amplitude"), Some("component 2")),
"ThreeExp" if normalized == "r" => {
(Some("rate constant"), Some("component 3"))
}
"ThreeExp" if normalized == "c" => (Some("amplitude"), Some("component 3")),
_ => (None, None),
};
CoefficientValue {
name: name.clone(),
role: role.map(str::to_string),
stage: component
.map(str::to_string)
.or_else(|| (!suffix.is_empty()).then(|| format!("stage {suffix}"))),
value: *value,
unit: coefficient_unit(name),
}
})
.collect(),
}),
})
}
fn parse_fit_names(raw: &str) -> Vec<String> {
raw.split([',', ';'])
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_string)
.collect()
}