use crate::Kinetics::experimental_kinetics::column_provenance::QualityReference;
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
ExperimentThermalMode, TGASeries,
};
use crate::Kinetics::experimental_kinetics::math::ndarray_statistics::{
FilterQualityReport, filter_quality_from_arrays,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{
ColumnDataQualityReport, ColumnNature, PreviewRows, RowSearchDirection, TGADomainError,
TGASchema, TimeOrderViolation, Unit,
};
use crate::gui::experimental_kinetics_gui::controller_methods::KineticMethodsWindowState;
use crate::gui::experimental_kinetics_gui::help_view::contextual_help_link;
use crate::gui::experimental_kinetics_gui::model::PlotModel;
use egui_extras::{Column, TableBuilder};
use log::info;
use std::collections::{HashMap, HashSet};
const PAGE_SIZE: usize = 100;
fn format_sample_value(value: f64) -> String {
if value.is_finite() && value != 0.0 && (value.abs() < 0.001 || value.abs() >= 1_000_000.0) {
format!("{value:.4e}")
} else {
format!("{value:.4}")
}
}
fn format_time_order_examples(examples: &[TimeOrderViolation]) -> String {
examples
.iter()
.map(|violation| {
format!(
"row {}: {} -> {}",
violation.index,
format_sample_value(violation.previous),
format_sample_value(violation.current)
)
})
.collect::<Vec<_>>()
.join("; ")
}
fn render_column_diagnostics(ui: &mut egui::Ui, report: &ColumnDataQualityReport) {
ui.label(format!(
"{} rows | finite: {} | null: {} | NaN: {} | infinite: {}",
report.row_count,
report.finite_count,
report.null_count,
report.nan_count,
report.infinite_count
));
match (report.finite_min, report.finite_max) {
(Some(min), Some(max)) => ui.label(format!(
"Finite range: {} to {}",
format_sample_value(min),
format_sample_value(max)
)),
_ => ui.weak("No finite values are available for a range."),
};
if let Some(order) = &report.time_order {
ui.label(format!(
"Time ordering: {} duplicate pair(s), {} decreasing pair(s)",
order.duplicate_count, order.decreasing_count
));
if !order.duplicate_examples.is_empty() {
ui.label(format!(
"Duplicate examples: {}",
format_time_order_examples(&order.duplicate_examples)
));
}
if !order.decreasing_examples.is_empty() {
ui.label(format!(
"Decreasing examples: {}",
format_time_order_examples(&order.decreasing_examples)
));
}
}
}
#[derive(Default)]
struct ColumnDeletionImpact {
schema_roles: Vec<&'static str>,
plot_references: Vec<String>,
active_sources: Vec<&'static str>,
derived_descendants: Vec<String>,
}
impl ColumnDeletionImpact {
fn has_references(&self) -> bool {
!self.schema_roles.is_empty()
|| !self.plot_references.is_empty()
|| !self.active_sources.is_empty()
|| !self.derived_descendants.is_empty()
}
}
fn schema_role_bindings(schema: &TGASchema) -> [(&'static str, Option<&str>); 11] {
[
("time", schema.time.as_deref()),
("temperature", schema.temperature.as_deref()),
("mass", schema.mass.as_deref()),
("relative mass (alpha)", schema.alpha.as_deref()),
("conversion (eta)", schema.eta.as_deref()),
("mass rate", schema.dm_dt.as_deref()),
("conversion rate", schema.deta_dt.as_deref()),
("relative-mass rate", schema.dalpha_dt.as_deref()),
("temperature rate", schema.dT_dt.as_deref()),
("activation energy", schema.E.as_deref()),
("R2", schema.R2.as_deref()),
]
}
fn column_deletion_impact(
model: &PlotModel,
experiment_id: &str,
column: &str,
) -> Result<ColumnDeletionImpact, String> {
let experiment = model
.series
.get_experiment_by_id(experiment_id)
.map_err(|error| error.to_string())?;
let schema = &experiment.dataset.schema;
let mut impact = ColumnDeletionImpact::default();
for (role, binding) in schema_role_bindings(schema) {
if binding == Some(column) {
impact.schema_roles.push(role);
}
}
for curve in model
.plots
.iter()
.filter(|curve| curve.experiment_id == experiment_id)
{
if curve.x_name == column {
impact
.plot_references
.push(format!("X axis of '{}'", curve.plot_short_name));
}
if curve.y_name == column {
impact
.plot_references
.push(format!("Y axis of '{}'", curve.plot_short_name));
}
}
impact.plot_references.sort();
if model
.active_mass_source_for_experiment(experiment_id)
.is_ok_and(|source| source == column)
{
impact.active_sources.push("mass");
}
if model
.active_temperature_source_for_experiment(experiment_id)
.is_ok_and(|source| source == column)
{
impact.active_sources.push("temperature");
}
let mut affected = HashSet::from([column.to_string()]);
loop {
let newly_affected = schema
.columns
.values()
.filter(|meta| !affected.contains(&meta.name))
.filter(|meta| {
meta.provenance
.root_columns
.iter()
.any(|root| affected.contains(root))
|| meta.provenance.steps.iter().any(|step| {
step.input_columns
.iter()
.any(|input| affected.contains(input))
})
})
.map(|meta| meta.name.clone())
.collect::<Vec<_>>();
if newly_affected.is_empty() {
break;
}
affected.extend(newly_affected);
}
impact.derived_descendants = affected.into_iter().filter(|name| name != column).collect();
impact.derived_descendants.sort();
Ok(impact)
}
fn display_experiment_id(id: &str) -> &str {
if id.is_empty() { "(unnamed)" } else { id }
}
fn data_column_width(available_width: f32, column_count: usize) -> f32 {
if column_count == 0 {
return 120.0;
}
(available_width / column_count as f32).clamp(88.0, 220.0)
}
fn comparison_grid_error(model: &PlotModel, experiment_ids: &[String]) -> Option<String> {
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit;
if experiment_ids.len() < 2 {
return None;
}
let mut reference: Option<(String, Unit, Vec<f64>)> = None;
for id in experiment_ids {
let experiment = match model.series.get_experiment_by_id(id) {
Ok(experiment) => experiment,
Err(error) => return Some(format!("Cannot compare experiment '{id}': {error}")),
};
let Some(time_column) = experiment.dataset.schema.time.as_deref() else {
return Some(format!(
"Cannot compare samples: experiment '{}' has no bound time column.",
display_experiment_id(id)
));
};
let Some(time_meta) = experiment.dataset.schema.columns.get(time_column) else {
return Some(format!(
"Cannot compare samples: bound time column '{time_column}' is missing from experiment '{}'.",
display_experiment_id(id)
));
};
let values = match experiment
.dataset
.numeric_column_values_with_nulls(time_column)
{
Ok(values) => values,
Err(error) => return Some(format!("Cannot read time grid for '{id}': {error}")),
};
let mut grid = Vec::with_capacity(values.len());
for (row, value) in values.iter().enumerate() {
let Some(value) = value else {
return Some(format!(
"Cannot compare samples: time column '{time_column}' in '{}' has a null at source row {row}.",
display_experiment_id(id)
));
};
if !value.is_finite() {
return Some(format!(
"Cannot compare samples: time column '{time_column}' in '{}' is non-finite at source row {row}.",
display_experiment_id(id)
));
}
if grid.last().is_some_and(|previous| value <= previous) {
return Some(format!(
"Cannot compare samples: time column '{time_column}' in '{}' is not strictly increasing at source row {row}.",
display_experiment_id(id)
));
}
grid.push(*value);
}
if let Some((reference_id, reference_unit, reference_grid)) = &reference {
if time_meta.unit != *reference_unit {
return Some(format!(
"Cannot compare samples: time units differ ('{}': {:?}, '{}': {:?}).",
display_experiment_id(reference_id),
reference_unit,
display_experiment_id(id),
time_meta.unit
));
}
if grid.len() != reference_grid.len() {
return Some(format!(
"Cannot compare samples: time-grid lengths differ ('{}': {}, '{}': {}).",
display_experiment_id(reference_id),
reference_grid.len(),
display_experiment_id(id),
grid.len()
));
}
if let Some((index, (left, right))) = reference_grid
.iter()
.zip(&grid)
.enumerate()
.find(|(_, (left, right))| left != right)
{
return Some(format!(
"Cannot compare samples: time grids differ at source row {index} ('{}': {}, '{}': {}). Resample explicitly to a shared grid first.",
display_experiment_id(reference_id),
format_sample_value(*left),
display_experiment_id(id),
format_sample_value(*right)
));
}
} else {
reference = Some((id.clone(), time_meta.unit, grid));
}
}
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MessageKind {
Info,
Success,
Warning,
Error,
}
#[derive(Clone, Debug)]
struct SystemMessage {
kind: MessageKind,
text: String,
}
impl SystemMessage {
fn new(kind: MessageKind, text: impl Into<String>) -> Self {
Self {
kind,
text: text.into(),
}
}
fn accessible_text(&self) -> String {
let level = match self.kind {
MessageKind::Info => "Info",
MessageKind::Success => "Success",
MessageKind::Warning => "Warning",
MessageKind::Error => "Error",
};
format!("{level}: {}", self.text)
}
}
#[cfg(test)]
mod sample_format_tests {
use super::{
MessageKind, SystemMessage, compare_columns_for_experiment, comparison_grid_error,
data_column_width, format_sample_value,
};
use crate::gui::experimental_kinetics_gui::model::PlotModel;
#[test]
fn table_column_width_adapts_to_number_of_columns() {
let few_columns = data_column_width(800.0, 2);
let many_columns = data_column_width(800.0, 12);
assert!(few_columns > many_columns);
assert_eq!(many_columns, 88.0);
}
#[test]
fn small_nonzero_values_remain_visible() {
assert_eq!(format_sample_value(0.000_012_3), "1.2300e-5");
assert_eq!(format_sample_value(-0.000_012_3), "-1.2300e-5");
}
#[test]
fn ordinary_values_keep_compact_decimal_format() {
assert_eq!(format_sample_value(12.345_67), "12.3457");
assert_eq!(format_sample_value(0.0), "0.0000");
}
#[test]
fn system_messages_have_distinct_severity() {
assert_eq!(
SystemMessage::new(MessageKind::Success, "Column renamed").accessible_text(),
"Success: Column renamed"
);
assert_eq!(
SystemMessage::new(MessageKind::Warning, "Time already uses hours").kind,
MessageKind::Warning
);
assert_eq!(
SystemMessage::new(MessageKind::Error, "Could not rename").kind,
MessageKind::Error
);
assert_eq!(
SystemMessage::new(MessageKind::Info, "Ready").accessible_text(),
"Info: Ready"
);
}
#[test]
fn column_manager_status_is_published_to_the_main_message_label() {
let mut state = super::ColumnManagerState::default();
let mut model = crate::gui::experimental_kinetics_gui::model::PlotModel::new();
state.set_message(MessageKind::Error, "Could not drop column: busy");
state.publish_message_to_main_status(&mut model);
assert_eq!(model.message, "Error: Could not drop column: busy");
state.set_message(MessageKind::Success, "Column dropped");
state.publish_message_to_main_status(&mut model);
assert_eq!(model.message, "Success: Column dropped");
model.message = "Saved another file".to_string();
state.set_message(MessageKind::Error, "Could not drop column: busy");
state.publish_message_to_main_status(&mut model);
assert_eq!(model.message, "Error: Could not drop column: busy");
state.set_message_if_changed(MessageKind::Error, "Column sample refresh failed");
let revision = state.message_revision;
state.set_message_if_changed(MessageKind::Error, "Column sample refresh failed");
assert_eq!(state.message_revision, revision);
}
#[test]
fn drop_impact_reports_binding_plot_active_source_and_provenance_descendants() {
let synthetic = crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA {
time: vec![0.0, 1.0, 2.0, 3.0, 4.0],
temperature: vec![300.0, 301.0, 302.0, 303.0, 304.0],
mass: vec![10.0, 9.0, 8.0, 7.0, 6.0],
};
let dataset = crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset::create_from_synthetic_data(&synthetic)
.unwrap()
.add_column_from_vec(
"mass_sg",
crate::Kinetics::experimental_kinetics::one_experiment_dataset::Unit::Milligram,
crate::Kinetics::experimental_kinetics::one_experiment_dataset::ColumnNature::Mass,
vec![10.0, 9.0, 8.0, 7.0, 6.0],
)
.unwrap();
let mut dataset = dataset;
dataset
.schema
.columns
.get_mut("mass_sg")
.unwrap()
.provenance
.root_columns = vec!["mass".to_string()];
let mut model = PlotModel::new();
model
.series
.push(
crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment::new(
dataset,
)
.with_id("drop_impact"),
)
.unwrap();
model.set_x("drop_impact", "time").unwrap();
model.set_y("drop_impact", "mass").unwrap();
model.create_points_for_curve("drop_impact").unwrap();
model.set_active_mass_source_for_experiment("drop_impact", "mass");
let impact = super::column_deletion_impact(&model, "drop_impact", "mass").unwrap();
assert_eq!(impact.schema_roles, vec!["mass"]);
assert_eq!(impact.active_sources, vec!["mass"]);
assert_eq!(impact.plot_references.len(), 1);
assert!(impact.plot_references[0].starts_with("Y axis of '"));
assert_eq!(impact.derived_descendants, vec!["mass_sg"]);
assert!(impact.has_references());
}
#[test]
fn column_comparison_uses_one_complete_case_mask_and_rejects_unit_mismatch() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
let file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(
file.path(),
"reference,candidate_a,candidate_b\n1.0,1.1,0.9\n2.0,2.1,2.2\n,4.4,4.1\n7.0,7.1,6.8\n11.0,11.2,11.1\n16.0,,15.8\n22.0,22.1,22.2\n29.0,29.4,\n",
)
.unwrap();
let dataset = TGADataset::from_csv_universal(file.path()).unwrap();
let mut model = PlotModel::new();
model
.series
.push(TGAExperiment::new(dataset).with_id("common_mask"))
.unwrap();
let (points_used, reports) = compare_columns_for_experiment(
&model,
"common_mask",
"reference",
&["candidate_a".to_string(), "candidate_b".to_string()],
)
.unwrap();
assert_eq!(points_used, 5);
assert_eq!(reports.len(), 2);
let mut mismatched_dataset = model
.series
.get_experiment_by_id("common_mask")
.unwrap()
.dataset
.clone();
mismatched_dataset
.schema
.columns
.get_mut("candidate_b")
.unwrap()
.unit = Unit::Kelvin;
let mut mismatched_model = PlotModel::new();
mismatched_model
.series
.push(TGAExperiment::new(mismatched_dataset).with_id("unit_mismatch"))
.unwrap();
let error = compare_columns_for_experiment(
&mismatched_model,
"unit_mismatch",
"reference",
&["candidate_b".to_string()],
)
.unwrap_err();
assert!(error.contains("requires the same unit"));
let sparse_file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(
sparse_file.path(),
"reference,candidate\n1.0,1.1\n2.0,2.1\n3.0,\n4.0,\n",
)
.unwrap();
let mut sparse_model = PlotModel::new();
sparse_model
.series
.push(
TGAExperiment::new(TGADataset::from_csv_universal(sparse_file.path()).unwrap())
.with_id("too_few_rows"),
)
.unwrap();
let error = compare_columns_for_experiment(
&sparse_model,
"too_few_rows",
"reference",
&["candidate".to_string()],
)
.unwrap_err();
assert!(error.contains("at least three points"));
let non_finite_file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(
non_finite_file.path(),
"reference,candidate\n1.0,1.1\n2.0,2.1\n3.0,NaN\n4.0,4.1\n",
)
.unwrap();
let mut non_finite_model = PlotModel::new();
non_finite_model
.series
.push(
TGAExperiment::new(TGADataset::from_csv_universal(non_finite_file.path()).unwrap())
.with_id("non_finite_value"),
)
.unwrap();
let error = compare_columns_for_experiment(
&non_finite_model,
"non_finite_value",
"reference",
&["candidate".to_string()],
)
.unwrap_err();
assert!(error.contains("non-finite value"));
}
#[test]
fn cross_experiment_comparison_requires_identical_full_time_grids() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
use std::fmt::Write as _;
let mut first_csv = String::from("time,mass\n");
let mut second_csv = String::from("time,mass\n");
for row in 0..101 {
let time = row as f64;
writeln!(&mut first_csv, "{time:.1},{}", 100.0 - time).unwrap();
let other_time = if row == 1 { 1.25 } else { time };
writeln!(&mut second_csv, "{other_time:.2},{}", 100.0 - other_time).unwrap();
}
let first_file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
let second_file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(first_file.path(), first_csv).unwrap();
std::fs::write(second_file.path(), second_csv).unwrap();
let first = TGADataset::from_csv_universal(first_file.path())
.unwrap()
.bind_time("time", Unit::Second)
.unwrap();
let second = TGADataset::from_csv_universal(second_file.path())
.unwrap()
.bind_time("time", Unit::Second)
.unwrap();
let first_preview = first.preview_rows(&["time"], 50).unwrap();
let second_preview = second.preview_rows(&["time"], 50).unwrap();
assert_eq!(first_preview.row_indices, second_preview.row_indices);
assert_eq!(
first_preview.columns["time"],
second_preview.columns["time"]
);
let mut model = PlotModel::new();
model
.series
.push(TGAExperiment::new(first.clone()).with_id("grid_a"))
.unwrap();
model
.series
.push(TGAExperiment::new(second).with_id("grid_b"))
.unwrap();
let error = comparison_grid_error(&model, &["grid_a".into(), "grid_b".into()])
.expect("an unsampled interior grid mismatch must block comparison");
assert!(
error.contains("time grids differ at source row 1"),
"{error}"
);
let mut matching_model = PlotModel::new();
matching_model
.series
.push(TGAExperiment::new(first.clone()).with_id("grid_a"))
.unwrap();
matching_model
.series
.push(TGAExperiment::new(first).with_id("grid_b"))
.unwrap();
assert_eq!(
comparison_grid_error(&matching_model, &["grid_a".into(), "grid_b".into()]),
None
);
}
#[test]
fn cross_experiment_comparison_rejects_invalid_or_incompatible_time_axes() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
let make_dataset = |contents: &str, unit: Unit| {
let file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(file.path(), contents).unwrap();
let dataset = TGADataset::from_csv_universal(file.path())
.unwrap()
.bind_time("time", unit)
.unwrap();
(file, dataset)
};
let (first_file, first) =
make_dataset("time,mass\n0.0,4.0\n1.0,3.0\n2.0,2.0\n", Unit::Second);
let (null_file, null_time) =
make_dataset("time,mass\n0.0,4.0\n,3.0\n2.0,2.0\n", Unit::Second);
let (nan_file, nan_time) =
make_dataset("time,mass\n0.0,4.0\nNaN,3.0\n2.0,2.0\n", Unit::Second);
let (decreasing_file, decreasing) =
make_dataset("time,mass\n0.0,4.0\n2.0,3.0\n1.0,2.0\n", Unit::Second);
let (duplicate_file, duplicate) =
make_dataset("time,mass\n0.0,4.0\n1.0,3.0\n1.0,2.0\n", Unit::Second);
let (unit_file, different_unit) =
make_dataset("time,mass\n0.0,4.0\n1.0,3.0\n2.0,2.0\n", Unit::Minute);
let (short_file, short) = make_dataset("time,mass\n0.0,4.0\n1.0,3.0\n", Unit::Second);
let unbound_file = tempfile::Builder::new().suffix(".csv").tempfile().unwrap();
std::fs::write(
unbound_file.path(),
"time,mass\n0.0,4.0\n1.0,3.0\n2.0,2.0\n",
)
.unwrap();
let unbound = TGADataset::from_csv_universal(unbound_file.path()).unwrap();
let _keep_files_alive = (
first_file,
null_file,
nan_file,
decreasing_file,
duplicate_file,
unit_file,
short_file,
);
let check_pair = |other| {
let mut model = PlotModel::new();
model
.series
.push(TGAExperiment::new(first.clone()).with_id("reference"))
.unwrap();
model
.series
.push(TGAExperiment::new(other).with_id("candidate"))
.unwrap();
comparison_grid_error(&model, &["reference".into(), "candidate".into()]).unwrap()
};
let error = check_pair(null_time);
assert!(error.contains("has a null at source row 1"), "{error}");
let error = check_pair(nan_time);
assert!(error.contains("non-finite at source row 1"), "{error}");
let error = check_pair(decreasing);
assert!(
error.contains("not strictly increasing at source row 2"),
"{error}"
);
let error = check_pair(duplicate);
assert!(
error.contains("not strictly increasing at source row 2"),
"{error}"
);
let error = check_pair(different_unit);
assert!(error.contains("time units differ"), "{error}");
let error = check_pair(short);
assert!(error.contains("time-grid lengths differ"), "{error}");
let mut unbound_model = PlotModel::new();
unbound_model
.series
.push(TGAExperiment::new(first).with_id("reference"))
.unwrap();
unbound_model
.series
.push(TGAExperiment::new(unbound).with_id("unbound"))
.unwrap();
assert!(
comparison_grid_error(&unbound_model, &["reference".into(), "unbound".into()])
.unwrap()
.contains("has no bound time column")
);
}
#[test]
fn replacing_document_clears_all_pending_delete_confirmations() {
let mut state = super::ColumnManagerState::default();
state.confirm_drop_experiment = Some("same_id".to_string());
state.confirm_drop_columns = vec![("same_id".to_string(), "mass".to_string())];
state.confirm_drop_row = Some(super::PendingRowDeletion {
experiment_id: "same_id".to_string(),
row_index: 2,
match_column: "mass".to_string(),
match_value: 1.0,
data_revision: 0,
});
state.confirm_replace_cell = Some(super::PendingCellReplacement {
experiment_id: "same_id".to_string(),
row_index: 2,
column: "mass".to_string(),
expected_value: 1.0,
replacement_value: "2.0".to_string(),
data_revision: 0,
});
state.confirm_delete_all = true;
state.clear_pending_confirmations();
assert!(state.confirm_drop_experiment.is_none());
assert!(state.confirm_drop_columns.is_empty());
assert!(state.confirm_drop_row.is_none());
assert!(state.confirm_replace_cell.is_none());
assert!(!state.confirm_delete_all);
}
}
#[derive(Default)]
pub struct ColumnManagerState {
cached_samples: HashMap<String, PreviewRows>,
sample_signatures: HashMap<String, TablePreviewSignature>,
comparison_grid_signature: Option<Vec<(String, TablePreviewSignature)>>,
comparison_grid_error: Option<String>,
current_page: Option<CachedTablePage>,
page_start: usize,
search_target: String,
search_tolerance: String,
search_key: Option<(String, String, u64, u64, u64)>,
search_cursor: Option<usize>,
search_result: Option<VersionedNumericRowMatch>,
search_message: Option<String>,
column_checkboxes: HashMap<(String, String), bool>,
new_column_name: String,
system_message: Option<SystemMessage>,
message_revision: u64,
last_published_revision: u64,
metadata_window_open: bool,
selected_experiment: Option<String>,
table_experiment: Option<String>,
compare_mode: bool,
compare_experiments: HashSet<String>,
selected_column: Option<(String, String)>,
plot_x_column: Option<String>,
selected_row_interval: Option<SelectedSourceRowInterval>,
comment_input: String,
heating_rate_input: String,
temperature_input: String,
confirm_drop_experiment: Option<String>,
confirm_drop_columns: Vec<(String, String)>,
confirm_drop_row: Option<PendingRowDeletion>,
confirm_replace_cell: Option<PendingCellReplacement>,
confirm_delete_all: bool,
formula_window_open: bool,
formula_experiment: Option<String>,
formula_x_column: Option<String>,
formula_multiple_inputs: bool,
formula_variable_bindings: Vec<FormulaVariableBinding>,
formula_output_name: String,
formula_expression: String,
formula_output_unit: Option<Unit>,
formula_output_nature: Option<ColumnNature>,
details_tab: DetailsTab,
column_diagnostics: Option<CachedColumnDiagnostics>,
comparison_reference: Option<String>,
comparison_candidates: HashSet<String>,
column_comparison: Option<CachedColumnComparison>,
}
#[derive(Default, Clone)]
struct FormulaVariableBinding {
name: String,
column: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct TablePreviewSignature {
data_revision: u64,
columns: Vec<String>,
bound_time_column: Option<String>,
}
#[derive(Clone, Copy)]
struct VersionedNumericRowMatch {
row_index: usize,
value: f64,
data_revision: u64,
}
struct CachedTablePage {
experiment_id: String,
signature: TablePreviewSignature,
preview: PreviewRows,
has_next: bool,
}
struct CachedColumnDiagnostics {
experiment_id: String,
column: String,
signature: TablePreviewSignature,
report: ColumnDataQualityReport,
}
struct CachedColumnComparison {
experiment_id: String,
signature: TablePreviewSignature,
reference: QualityReference,
candidates: Vec<String>,
points_used: usize,
reports: Vec<FilterQualityReport>,
}
fn compare_columns_for_experiment(
model: &PlotModel,
experiment_id: &str,
reference: &str,
candidates: &[String],
) -> Result<(usize, Vec<FilterQualityReport>), String> {
if candidates.is_empty() {
return Err("Select at least one candidate column".to_string());
}
if candidates.iter().any(|column| column == reference) {
return Err("Reference column cannot also be a candidate".to_string());
}
let experiment = model
.series
.get_experiment_by_id(experiment_id)
.map_err(|error| error.to_string())?;
let reference_unit = experiment
.dataset
.schema
.columns
.get(reference)
.ok_or_else(|| format!("Reference column '{reference}' does not exist"))?
.unit;
for candidate in candidates {
let candidate_unit = experiment
.dataset
.schema
.columns
.get(candidate)
.ok_or_else(|| format!("Candidate column '{candidate}' does not exist"))?
.unit;
if candidate_unit != reference_unit {
return Err(format!(
"Column '{candidate}' has unit {candidate_unit:?}; comparison with '{reference}' requires the same unit ({reference_unit:?})"
));
}
}
let candidate_names = candidates.iter().map(String::as_str).collect::<Vec<_>>();
let block = experiment
.dataset
.materialize(reference, &candidate_names)
.map_err(|error| error.to_string())?;
let reference_values = ndarray::Array1::from_vec(block.grid.as_ref().clone());
let mut reports = Vec::with_capacity(candidates.len());
for candidate in candidates {
let values = block
.columns
.get(candidate)
.ok_or_else(|| format!("Column '{candidate}' was not included in the comparison"))?;
let candidate_values = ndarray::Array1::from_vec(values.as_ref().clone());
reports.push(
filter_quality_from_arrays(&reference_values, &candidate_values, reference, candidate)
.map_err(|error| error.to_string())?,
);
}
Ok((reference_values.len(), reports))
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct SelectedSourceRowInterval {
experiment_id: String,
anchor: usize,
end: usize,
}
impl SelectedSourceRowInterval {
fn bounds(&self) -> (usize, usize) {
(self.anchor.min(self.end), self.anchor.max(self.end))
}
fn contains(&self, row: usize) -> bool {
let (start, end) = self.bounds();
(start..=end).contains(&row)
}
}
#[derive(Clone)]
struct PendingRowDeletion {
experiment_id: String,
row_index: usize,
match_column: String,
match_value: f64,
data_revision: u64,
}
#[derive(Clone)]
struct PendingCellReplacement {
experiment_id: String,
row_index: usize,
column: String,
expected_value: f64,
replacement_value: String,
data_revision: u64,
}
#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum DetailsTab {
#[default]
Overview,
Processing,
Quality,
Comparison,
History,
}
impl ColumnManagerState {
fn open_formula_window(&mut self, model: &PlotModel) {
let experiments = model.list_of_experiments();
let experiment_id = self
.table_experiment
.clone()
.filter(|id| experiments.contains(id))
.or_else(|| experiments.first().cloned());
self.formula_experiment = experiment_id.clone();
self.formula_x_column = experiment_id.as_deref().and_then(|id| {
model
.series
.get_experiment_by_id(id)
.ok()
.and_then(|experiment| experiment.dataset.schema.time.clone())
.or_else(|| model.list_of_columns(id).ok()?.first().cloned())
});
self.formula_output_name.clear();
self.formula_expression = "x".to_string();
self.formula_multiple_inputs = false;
self.formula_variable_bindings = vec![FormulaVariableBinding {
name: "x".to_string(),
column: self.formula_x_column.clone(),
}];
self.formula_output_unit = Some(Unit::Unknown);
self.formula_output_nature = Some(ColumnNature::Unknown);
self.formula_window_open = true;
}
fn show_formula_window(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
if !self.formula_window_open {
return;
}
const UNITS: &[Unit] = &[
Unit::Second,
Unit::Minute,
Unit::Hour,
Unit::Kelvin,
Unit::Celsius,
Unit::MilliVolt,
Unit::Milligram,
Unit::MolePerCubicMeter,
Unit::MilligramPerSecond,
Unit::MilligramPerMinute,
Unit::MilligramPerHour,
Unit::KelvinPerSecond,
Unit::KelvinPerMinute,
Unit::KelvinPerHour,
Unit::CelsiusPerSecond,
Unit::CelsiusPerMinute,
Unit::CelsiusPerHour,
Unit::PerSecond,
Unit::PerMinute,
Unit::PerHour,
Unit::Gram,
Unit::Dimensionless,
Unit::Unknown,
];
const NATURES: &[ColumnNature] = &[
ColumnNature::Time,
ColumnNature::Temperature,
ColumnNature::Mass,
ColumnNature::Concentration,
ColumnNature::Conversion,
ColumnNature::DimensionlessMass,
ColumnNature::MassRate,
ColumnNature::ConversionRate,
ColumnNature::TemperatureRate,
ColumnNature::DimensionlessMassRate,
ColumnNature::Unknown,
ColumnNature::ActivationEnergy,
ColumnNature::PredexFactor,
ColumnNature::R2,
ColumnNature::FittedCurve,
];
let experiment_ids = model.list_of_experiments();
if self
.formula_experiment
.as_ref()
.is_none_or(|id| !experiment_ids.contains(id))
{
self.formula_experiment = experiment_ids.first().cloned();
self.formula_x_column = None;
}
let columns = self
.formula_experiment
.as_deref()
.and_then(|id| model.list_of_columns(id).ok())
.unwrap_or_default();
if self
.formula_x_column
.as_ref()
.is_none_or(|name| !columns.contains(name))
{
self.formula_x_column = columns.first().cloned();
}
let mut apply = false;
let mut close = false;
egui::Window::new("Create Formula Column")
.open(&mut self.formula_window_open)
.collapsible(false)
.resizable(true)
.default_size([460.0, 390.0])
.show(ctx, |ui| {
contextual_help_link(ui, "Formula Column");
ui.label("Create a new numeric column from one or more source columns.");
ui.colored_label(
egui::Color32::YELLOW,
"Source data and active schema bindings are left unchanged. The result must be finite for every row.",
);
ui.separator();
egui::ComboBox::from_label("Experiment")
.selected_text(
self.formula_experiment
.as_deref()
.unwrap_or("Select experiment"),
)
.show_ui(ui, |ui| {
for id in &experiment_ids {
if ui
.selectable_value(&mut self.formula_experiment, Some(id.clone()), id)
.changed()
{
self.formula_x_column = None;
self.formula_variable_bindings.iter_mut().for_each(|binding| {
binding.column = None;
});
}
}
});
let columns = self
.formula_experiment
.as_deref()
.and_then(|id| model.list_of_columns(id).ok())
.unwrap_or_default();
ui.horizontal(|ui| {
ui.selectable_value(
&mut self.formula_multiple_inputs,
false,
"One source column",
);
ui.selectable_value(
&mut self.formula_multiple_inputs,
true,
"Multiple source columns",
);
});
ui.separator();
if self.formula_multiple_inputs {
ui.label("Bind each formula variable to a numeric source column:");
let mut remove_row = None;
let binding_count = self.formula_variable_bindings.len();
for (index, binding) in self.formula_variable_bindings.iter_mut().enumerate() {
ui.horizontal(|ui| {
let label = ui.label(format!("Variable name {}", index + 1));
ui.text_edit_singleline(&mut binding.name).labelled_by(label.id);
egui::ComboBox::from_label(format!("Source column {}", index + 1))
.selected_text(
binding.column.as_deref().unwrap_or("Select column"),
)
.show_ui(ui, |ui| {
for column in &columns {
ui.selectable_value(
&mut binding.column,
Some(column.clone()),
column,
);
}
});
if binding_count > 1 && ui.small_button("Remove").clicked() {
remove_row = Some(index);
}
});
}
if let Some(index) = remove_row {
self.formula_variable_bindings.remove(index);
}
if ui.button("Add variable").clicked() {
let next_name = format!("v{}", self.formula_variable_bindings.len() + 1);
self.formula_variable_bindings.push(FormulaVariableBinding {
name: next_name,
column: None,
});
}
ui.separator();
ui.label("Formula uses the variable names above, e.g. x + y or x * y.");
} else {
egui::ComboBox::from_label("X source column")
.selected_text(
self.formula_x_column
.as_deref()
.unwrap_or("Select X column"),
)
.show_ui(ui, |ui| {
for column in &columns {
ui.selectable_value(
&mut self.formula_x_column,
Some(column.clone()),
column,
);
}
});
ui.label("Use x in the formula, for example: 2*x + 1, ln(x), or 1/x.");
}
ui.horizontal(|ui| {
let label = ui.label("Formula");
ui.text_edit_singleline(&mut self.formula_expression)
.labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label("New column name");
ui.text_edit_singleline(&mut self.formula_output_name)
.labelled_by(label.id);
});
ui.horizontal(|ui| {
egui::ComboBox::from_label("Output unit")
.selected_text(
self.formula_output_unit
.map(|unit| format!("{unit:?}"))
.unwrap_or_else(|| "Select unit".to_string()),
)
.show_ui(ui, |ui| {
for unit in UNITS {
ui.selectable_value(
&mut self.formula_output_unit,
Some(*unit),
format!("{unit:?}"),
);
}
});
egui::ComboBox::from_label("Output nature")
.selected_text(
self.formula_output_nature
.map(|nature| format!("{nature:?}"))
.unwrap_or_else(|| "Select nature".to_string()),
)
.show_ui(ui, |ui| {
for nature in NATURES {
ui.selectable_value(
&mut self.formula_output_nature,
Some(*nature),
format!("{nature:?}"),
);
}
});
});
let experiment_label = self
.formula_experiment
.as_deref()
.unwrap_or("no experiment selected");
let output_label = if self.formula_output_name.trim().is_empty() {
"enter a required output name"
} else {
self.formula_output_name.trim()
};
let source_summary = if self.formula_multiple_inputs {
self.formula_variable_bindings
.iter()
.map(|binding| {
format!(
"{} = {}",
if binding.name.trim().is_empty() {
"<variable>"
} else {
binding.name.trim()
},
binding.column.as_deref().unwrap_or("<choose column>")
)
})
.collect::<Vec<_>>()
.join(", ")
} else {
format!(
"x = {}",
self.formula_x_column.as_deref().unwrap_or("<choose column>")
)
};
ui.group(|ui| {
ui.label(format!(
"Action preview: add '{output_label}' to '{experiment_label}' from [{source_summary}]."
));
ui.small("Source columns and active schema bindings remain unchanged; no rows are removed.");
});
ui.separator();
ui.horizontal(|ui| {
let source_valid = if self.formula_multiple_inputs {
!self.formula_variable_bindings.is_empty()
&& self.formula_variable_bindings.iter().all(|binding| {
!binding.name.trim().is_empty() && binding.column.is_some()
})
} else {
self.formula_x_column.is_some()
};
let valid = self.formula_experiment.is_some()
&& source_valid
&& !self.formula_output_name.trim().is_empty()
&& !self.formula_expression.trim().is_empty()
&& self.formula_output_unit.is_some()
&& self.formula_output_nature.is_some();
if ui
.add_enabled(valid, egui::Button::new("Create column"))
.on_hover_text("Evaluates the formula for every row and adds one new column. Inputs must be numeric, aligned and finite. Does not replace or rebind existing columns.")
.on_disabled_hover_text("Choose an experiment, bind every formula variable, enter a formula and output name, and select output unit and nature.")
.clicked()
{
apply = true;
}
if ui.button("Cancel").clicked() {
close = true;
}
});
});
if close {
self.formula_window_open = false;
}
if apply {
let experiment_id = self.formula_experiment.as_deref().unwrap_or_default();
let x_column = self.formula_x_column.as_deref().unwrap_or_default();
let variable_columns = self
.formula_variable_bindings
.iter()
.filter_map(|binding| {
binding
.column
.as_ref()
.map(|column| (binding.name.trim().to_string(), column.clone()))
})
.collect::<Vec<_>>();
let output_name = self.formula_output_name.trim();
let expression = self.formula_expression.trim();
let unit = self.formula_output_unit.unwrap_or(Unit::Unknown);
let nature = self.formula_output_nature.unwrap_or(ColumnNature::Unknown);
let result = if self.formula_multiple_inputs {
model.add_formula_column_from_columns(
experiment_id,
output_name,
&variable_columns,
expression,
unit,
nature,
)
} else {
model.add_formula_column(
experiment_id,
output_name,
x_column,
expression,
unit,
nature,
)
};
match result {
Ok(()) => {
self.cached_samples.remove(experiment_id);
self.sample_signatures.remove(experiment_id);
self.current_page = None;
self.selected_column =
Some((experiment_id.to_string(), output_name.to_string()));
self.details_tab = DetailsTab::Overview;
self.set_message(
MessageKind::Success,
format!(
"Created formula column '{output_name}' in experiment '{experiment_id}'"
),
);
self.formula_window_open = false;
}
Err(error) => self.set_message(
MessageKind::Error,
format!("Formula column was not created: {error}"),
),
}
}
}
#[cfg(test)]
pub(crate) fn select_column_for_test(&mut self, experiment_id: &str, column: &str) {
self.column_checkboxes
.insert((experiment_id.to_string(), column.to_string()), true);
}
#[cfg(test)]
pub(crate) fn select_inspector_column_for_test(&mut self, experiment_id: &str, column: &str) {
self.selected_column = Some((experiment_id.to_string(), column.to_string()));
}
#[cfg(test)]
pub(crate) fn select_source_row_interval_for_test(
&mut self,
experiment_id: &str,
start: usize,
end: usize,
) {
self.selected_row_interval = Some(SelectedSourceRowInterval {
experiment_id: experiment_id.to_string(),
anchor: start,
end,
});
}
#[cfg(test)]
pub(crate) fn configure_comparison_for_test(&mut self, reference: &str, candidates: &[&str]) {
self.details_tab = DetailsTab::Comparison;
self.comparison_reference = Some(reference.to_string());
self.comparison_candidates = candidates.iter().map(|name| (*name).to_string()).collect();
}
fn select_source_row(&mut self, experiment_id: &str, row: usize, extend: bool) {
let anchor = if extend {
self.selected_row_interval
.as_ref()
.filter(|selection| selection.experiment_id == experiment_id)
.map(|selection| selection.anchor)
.unwrap_or(row)
} else {
row
};
self.selected_row_interval = Some(SelectedSourceRowInterval {
experiment_id: experiment_id.to_string(),
anchor,
end: row,
});
}
pub(crate) fn clear_pending_confirmations(&mut self) {
self.confirm_drop_experiment = None;
self.confirm_drop_columns.clear();
self.confirm_drop_row = None;
self.confirm_replace_cell = None;
self.confirm_delete_all = false;
}
fn set_message(&mut self, kind: MessageKind, text: impl Into<String>) {
self.system_message = Some(SystemMessage::new(kind, text));
self.message_revision = self.message_revision.wrapping_add(1);
}
fn set_message_if_changed(&mut self, kind: MessageKind, text: impl Into<String>) {
let text = text.into();
if self
.system_message
.as_ref()
.is_some_and(|current| current.kind == kind && current.text == text)
{
return;
}
self.set_message(kind, text);
}
fn publish_message_to_main_status(&mut self, model: &mut PlotModel) {
if self.message_revision == self.last_published_revision {
return;
}
let Some(message) = &self.system_message else {
return;
};
let text = message.accessible_text();
model.message = text;
self.last_published_revision = self.message_revision;
}
pub(crate) fn close_window_on_layer(&mut self, layer: Option<egui::LayerId>) -> bool {
let Some(layer) = layer else { return false };
if layer.id == egui::Id::unique(Some("Confirm Drop Experiment"))
&& self.confirm_drop_experiment.is_some()
{
self.confirm_drop_experiment = None;
return true;
}
if layer.id == egui::Id::unique(Some("Confirm Drop Columns"))
&& !self.confirm_drop_columns.is_empty()
{
self.confirm_drop_columns.clear();
return true;
}
if layer.id == egui::Id::unique(Some("Confirm Delete Source Row"))
&& self.confirm_drop_row.is_some()
{
self.confirm_drop_row = None;
return true;
}
if layer.id == egui::Id::unique(Some("Confirm Replace Cell Value"))
&& self.confirm_replace_cell.is_some()
{
self.confirm_replace_cell = None;
return true;
}
if layer.id == egui::Id::unique(Some("Confirm Delete All Workspace"))
&& self.confirm_delete_all
{
self.confirm_delete_all = false;
return true;
}
if layer.id == egui::Id::unique(Some("Edit Metadata")) && self.metadata_window_open {
self.metadata_window_open = false;
return true;
}
false
}
pub fn new() -> Self {
Self::default()
}
fn update_cache(&mut self, model: &mut PlotModel) -> Result<(), String> {
let experiments = model.list_of_experiments();
self.cached_samples
.retain(|exp_id, _| experiments.contains(exp_id));
self.sample_signatures
.retain(|exp_id, _| experiments.contains(exp_id));
if self.compare_mode {
let mut selected = self.compare_experiments.iter().cloned().collect::<Vec<_>>();
selected.sort();
self.cached_samples
.retain(|exp_id, _| selected.contains(exp_id));
self.sample_signatures
.retain(|exp_id, _| selected.contains(exp_id));
let mut signatures = Vec::with_capacity(selected.len());
for exp_id in selected {
let signature = Self::preview_signature(model, &exp_id)?;
signatures.push((exp_id.clone(), signature.clone()));
let is_current = self.sample_signatures.get(&exp_id) == Some(&signature)
&& self.cached_samples.contains_key(&exp_id);
if !is_current {
let preview = model
.column_sample_preview_for_experiment(&exp_id, 50)
.map_err(|error| format!("{error:?}"))?;
self.cached_samples.insert(exp_id.clone(), preview);
self.sample_signatures.insert(exp_id, signature);
}
}
if self.comparison_grid_signature.as_ref() != Some(&signatures) {
let selected_ids = signatures
.iter()
.map(|(id, _)| id.clone())
.collect::<Vec<_>>();
self.comparison_grid_error = comparison_grid_error(model, &selected_ids);
self.comparison_grid_signature = Some(signatures);
}
self.current_page = None;
return Ok(());
}
self.cached_samples.clear();
self.sample_signatures.clear();
self.comparison_grid_signature = None;
self.comparison_grid_error = None;
let active_id = self
.table_experiment
.as_ref()
.filter(|id| experiments.contains(id))
.cloned()
.or_else(|| experiments.first().cloned());
let Some(exp_id) = active_id else {
self.current_page = None;
return Ok(());
};
let signature = Self::preview_signature(model, &exp_id)?;
if self
.current_page
.as_ref()
.is_some_and(|page| page.experiment_id == exp_id && page.signature != signature)
{
self.reset_numeric_search();
self.selected_row_interval = None;
}
let page_is_current = self.current_page.as_ref().is_some_and(|page| {
page.experiment_id == exp_id
&& page.signature == signature
&& page
.preview
.row_indices
.first()
.copied()
.unwrap_or(self.page_start)
== self.page_start
});
if !page_is_current {
let mut preview = model
.column_preview_page_for_experiment(&exp_id, self.page_start, PAGE_SIZE + 1)
.map_err(|error| format!("{error:?}"))?;
let has_next = preview.row_indices.len() > PAGE_SIZE;
preview.row_indices.truncate(PAGE_SIZE);
for values in preview.columns.values_mut() {
values.truncate(PAGE_SIZE);
}
self.current_page = Some(CachedTablePage {
experiment_id: exp_id,
signature,
preview,
has_next,
});
}
Ok(())
}
fn preview_signature(model: &PlotModel, exp_id: &str) -> Result<TablePreviewSignature, String> {
let experiment = model
.series
.get_experiment_by_id(exp_id)
.map_err(|error| format!("{error:?}"))?;
let mut columns = model
.list_of_columns(exp_id)
.map_err(|error| format!("{error:?}"))?;
columns.sort();
Ok(TablePreviewSignature {
data_revision: model.series.data_revision(),
columns,
bound_time_column: experiment.dataset.schema.time.clone(),
})
}
fn run_column_diagnostics(&mut self, model: &PlotModel, exp_id: &str, column: &str) {
let signature = match Self::preview_signature(model, exp_id) {
Ok(signature) => signature,
Err(error) => {
self.set_message(
MessageKind::Error,
format!("Could not prepare data diagnostics: {error}"),
);
return;
}
};
match model.numeric_column_diagnostics_for_experiment(exp_id, column) {
Ok(report) => {
self.column_diagnostics = Some(CachedColumnDiagnostics {
experiment_id: exp_id.to_string(),
column: column.to_string(),
signature,
report,
});
self.set_message(
MessageKind::Success,
format!("Data diagnostics completed for '{column}'"),
);
}
Err(error) => self.set_message(
MessageKind::Error,
format!("Could not inspect column data: {error}"),
),
}
}
fn render_controls(&mut self, ui: &mut egui::Ui, model: &mut PlotModel) {
let experiments = model.list_of_experiments();
let previous_experiment = self.table_experiment.clone();
if self
.table_experiment
.as_ref()
.is_none_or(|id| !experiments.contains(id))
{
self.table_experiment = experiments.first().cloned();
}
self.compare_experiments
.retain(|id| experiments.contains(id));
let mut comparison_mode_changed = false;
ui.horizontal(|ui| {
comparison_mode_changed = ui.checkbox(&mut self.compare_mode, "Compare experiments")
.on_hover_text("Read-only side-by-side samples. With multiple experiments, the table is shown only when every selected experiment has the same complete, strictly increasing bound-time grid and time unit; no implicit interpolation is performed.")
.changed();
contextual_help_link(ui, "Column Manager");
if !self.compare_mode {
egui::ComboBox::from_label("Experiment")
.selected_text(
self.table_experiment
.as_deref()
.unwrap_or("Select experiment"),
)
.show_ui(ui, |ui| {
for id in &experiments {
ui.selectable_value(&mut self.table_experiment, Some(id.clone()), id);
}
});
}
});
if comparison_mode_changed {
self.selected_row_interval = None;
}
if !self.compare_mode && self.table_experiment != previous_experiment {
self.page_start = 0;
self.current_page = None;
self.selected_column = None;
self.selected_row_interval = None;
self.comparison_reference = None;
self.comparison_candidates.clear();
self.column_comparison = None;
self.reset_numeric_search();
}
if self.compare_mode {
egui::CollapsingHeader::new("Experiments to compare")
.default_open(true)
.show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
for id in &experiments {
let mut selected = self.compare_experiments.contains(id);
let label = if id.is_empty() {
"(unnamed experiment)"
} else {
id
};
if ui.checkbox(&mut selected, label).changed() {
if selected {
self.compare_experiments.insert(id.clone());
} else {
self.compare_experiments.remove(id);
}
}
}
});
});
}
let mutation_enabled = !self.compare_mode && self.table_experiment.is_some();
ui.horizontal(|ui| {
let selected_count = self.selected_column_checkboxes().len();
if ui
.add_enabled(
mutation_enabled && selected_count > 0,
egui::Button::new(format!("Delete columns ({selected_count})")),
)
.on_hover_text(
"Deletes the checked columns from the current experiment after confirmation.",
)
.on_disabled_hover_text(if self.compare_mode {
"Compare mode is read-only. Return to the single-experiment view to delete columns."
} else if selected_count == 0 {
"Check one or more column headers first; the column name itself only opens details."
} else {
"Select one experiment before changing its columns."
})
.clicked()
{
self.handle_drop_columns();
}
if ui
.add_enabled(mutation_enabled, egui::Button::new("Create formula column"))
.on_hover_text("Enter a formula, bind its variables to numeric columns, and provide a new output name. The operation adds one column and leaves source columns and active bindings unchanged.")
.on_disabled_hover_text("Formula columns can only be created for one experiment at a time; leave Compare mode and select an experiment.")
.clicked()
{
self.open_formula_window(model);
}
if let Some(id) = self.table_experiment.clone() {
if ui
.add_enabled(
mutation_enabled,
egui::Button::new(format!(
"Delete experiment: {}",
display_experiment_id(&id)
)),
)
.on_hover_text(
"Deletes the current experiment and its plots after confirmation.",
)
.on_disabled_hover_text("Compare mode is read-only. Return to the single-experiment view to delete an experiment.")
.clicked()
{
self.confirm_drop_experiment = Some(id);
}
}
ui.menu_button("More", |ui| {
if ui
.add_enabled(mutation_enabled, egui::Button::new("Edit Metadata"))
.on_hover_text("Edit the current experiment's comment and thermal metadata. This does not change columns.")
.on_disabled_hover_text("Select one experiment and leave Compare mode to edit its metadata.")
.clicked()
{
self.selected_experiment = self.table_experiment.clone();
self.metadata_window_open = true;
ui.close();
}
ui.separator();
if ui
.add_enabled(
mutation_enabled,
egui::Button::new("Check time monotonicity"),
)
.on_hover_text("Checks the current experiment's bound time column. Enter no values; data is not modified.")
.on_disabled_hover_text("Select one experiment and leave Compare mode to inspect its bound time column.")
.clicked()
{
self.handle_check_time_monotonity(model);
ui.close();
}
if ui
.add_enabled(mutation_enabled, egui::Button::new("Sort by time"))
.on_hover_text("Sorts every row in the current experiment by its bound time column. No new column is created.")
.on_disabled_hover_text("Select one experiment and leave Compare mode to sort its rows.")
.clicked()
{
self.handle_sort_by_time(model);
ui.close();
}
});
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
if ui
.button("Delete All")
.on_hover_text("Clear every experiment, plot, and selection from the workspace after an explicit confirmation.")
.clicked()
{
self.confirm_delete_all = true;
}
},
);
});
if let Some(message) = &self.system_message {
let color = match message.kind {
MessageKind::Info => ui.visuals().text_color(),
MessageKind::Success => egui::Color32::LIGHT_GREEN,
MessageKind::Warning => egui::Color32::YELLOW,
MessageKind::Error => egui::Color32::LIGHT_RED,
};
ui.colored_label(color, message.accessible_text());
}
ui.separator();
}
fn render_page_controls(&mut self, ui: &mut egui::Ui) {
if self.compare_mode {
ui.horizontal(|ui| {
ui.strong("Sampled comparison");
if let Some(error) = &self.comparison_grid_error {
ui.colored_label(egui::Color32::LIGHT_RED, error);
} else {
ui.weak(
"Up to 50 shared-grid rows per experiment; source data is not modified.",
);
}
});
return;
}
let has_next = self.current_page.as_ref().is_some_and(|page| page.has_next);
let mut changed = false;
ui.horizontal(|ui| {
ui.strong("Source rows");
if ui
.add_enabled(self.page_start > 0, egui::Button::new("First page"))
.on_hover_text("Return to the first 100 original source rows.")
.clicked()
{
self.page_start = 0;
changed = true;
}
if ui
.add_enabled(self.page_start > 0, egui::Button::new("Previous page"))
.on_hover_text("Show the previous 100 original source rows.")
.clicked()
{
self.page_start = self.page_start.saturating_sub(PAGE_SIZE);
changed = true;
}
if ui
.add_enabled(has_next, egui::Button::new("Next page"))
.on_hover_text("Show the next 100 original source rows, if available.")
.clicked()
{
self.page_start = self.page_start.saturating_add(PAGE_SIZE);
changed = true;
}
if let Some(page) = &self.current_page {
let Some(first) = page.preview.row_indices.first() else {
ui.weak("No source rows in this range.");
return;
};
let last = page.preview.row_indices.last().copied().unwrap_or(*first);
ui.label(format!(
"Rows {}-{} (source {}-{}) | {}",
first + 1,
last + 1,
first,
last,
if page.has_next {
"more rows available"
} else {
"end of data"
}
));
} else {
ui.weak("Loading page...");
}
});
if changed {
self.current_page = None;
self.selected_row_interval = None;
}
}
fn reset_numeric_search(&mut self) {
self.search_key = None;
self.search_cursor = None;
self.search_result = None;
self.search_message = None;
}
fn execute_numeric_search(&mut self, model: &PlotModel, direction: RowSearchDirection) {
let Some(exp_id) = self.table_experiment.as_deref() else {
self.search_message = Some("Select an experiment first.".to_string());
return;
};
let Some((selected_exp, column)) = self.selected_column.as_ref() else {
self.search_message = Some("Select a column heading to search it.".to_string());
return;
};
if selected_exp != exp_id {
self.search_message = Some("Select a column from the current experiment.".to_string());
return;
}
let target = match self.search_target.trim().parse::<f64>() {
Ok(value) if value.is_finite() => value,
_ => {
self.search_message = Some("Enter a finite numeric target value.".to_string());
return;
}
};
let tolerance = match self.search_tolerance.trim().parse::<f64>() {
Ok(value) if value.is_finite() && value >= 0.0 => value,
_ => {
self.search_message = Some(
"Tolerance must be a finite number greater than or equal to 0.".to_string(),
);
return;
}
};
let key = (
exp_id.to_string(),
column.clone(),
target.to_bits(),
tolerance.to_bits(),
model.series.data_revision(),
);
if self.search_key.as_ref() != Some(&key) {
self.search_cursor = None;
self.search_result = None;
self.search_key = Some(key);
}
match model.find_numeric_row_for_experiment(
exp_id,
column,
target,
tolerance,
self.search_cursor,
direction,
) {
Ok(Some(found)) => {
self.search_cursor = Some(found.row_index);
self.search_result = Some(VersionedNumericRowMatch {
row_index: found.row_index,
value: found.value,
data_revision: model.series.data_revision(),
});
self.page_start = (found.row_index / PAGE_SIZE) * PAGE_SIZE;
self.current_page = None;
self.search_message = Some(format!(
"Found {} = {} at source row {} (display row {}).",
column,
format_sample_value(found.value),
found.row_index,
found.row_index + 1
));
}
Ok(None) => {
self.search_message = Some(match direction {
RowSearchDirection::Forward => {
"No next match; end of data reached (search does not wrap).".to_string()
}
RowSearchDirection::Backward => {
"No previous match; beginning of data reached (search does not wrap)."
.to_string()
}
});
}
Err(error) => {
self.search_message = Some(format!("Search failed: {error}"));
}
}
}
fn prepare_delete_found_row(&mut self, model: &PlotModel) {
if self.compare_mode {
self.set_message(
MessageKind::Error,
"Row deletion is unavailable in comparison mode",
);
return;
}
let (Some((experiment_id, column)), Some(found)) =
(self.selected_column.as_ref(), self.search_result)
else {
self.set_message(MessageKind::Error, "Find a row before requesting deletion");
return;
};
if self.table_experiment.as_ref() != Some(experiment_id) {
self.set_message(
MessageKind::Error,
"The found row does not belong to the current experiment",
);
return;
}
if model.series.data_revision() != found.data_revision {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"Data changed after the search; search again before deleting a row",
);
return;
}
let current_value =
match model
.series
.get_experiment_by_id(experiment_id)
.and_then(|experiment| {
experiment
.dataset
.numeric_value_at_row(column, found.row_index)
.map_err(TGADomainError::PolarsError)
}) {
Ok(value) => value,
Err(error) => {
self.set_message(
MessageKind::Error,
format!("Could not verify the found row: {error}"),
);
return;
}
};
if current_value.is_none_or(|value| value.to_bits() != found.value.to_bits()) {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"The found cell no longer matches the search result; search again",
);
return;
}
self.confirm_drop_row = Some(PendingRowDeletion {
experiment_id: experiment_id.clone(),
row_index: found.row_index,
match_column: column.clone(),
match_value: found.value,
data_revision: found.data_revision,
});
}
fn prepare_replace_found_value(&mut self, model: &PlotModel) {
if self.compare_mode {
self.set_message(
MessageKind::Error,
"Cell replacement is unavailable in comparison mode",
);
return;
}
let (Some((experiment_id, column)), Some(found)) =
(self.selected_column.as_ref(), self.search_result)
else {
self.set_message(
MessageKind::Error,
"Find a value before requesting replacement",
);
return;
};
if self.table_experiment.as_ref() != Some(experiment_id) {
self.set_message(
MessageKind::Error,
"The found value does not belong to the current experiment",
);
return;
}
if model.series.data_revision() != found.data_revision {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"Data changed after the search; search again before replacing a value",
);
return;
}
let current_value =
match model
.series
.get_experiment_by_id(experiment_id)
.and_then(|experiment| {
experiment
.dataset
.numeric_value_at_row(column, found.row_index)
.map_err(TGADomainError::PolarsError)
}) {
Ok(value) => value,
Err(error) => {
self.set_message(
MessageKind::Error,
format!("Could not verify the found cell: {error}"),
);
return;
}
};
if current_value.is_none_or(|value| value.to_bits() != found.value.to_bits()) {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"The found cell no longer matches the search result; search again",
);
return;
}
self.confirm_replace_cell = Some(PendingCellReplacement {
experiment_id: experiment_id.clone(),
row_index: found.row_index,
column: column.clone(),
expected_value: found.value,
replacement_value: String::new(),
data_revision: found.data_revision,
});
}
fn commit_replace_found_value(&mut self, model: &mut PlotModel) {
let Some(pending) = self.confirm_replace_cell.take() else {
return;
};
let replacement_value = match pending.replacement_value.trim().parse::<f64>() {
Ok(value) if value.is_finite() => value,
_ => {
self.set_message(
MessageKind::Error,
"Replacement must be a finite numeric value",
);
return;
}
};
if replacement_value.to_bits() == pending.expected_value.to_bits() {
self.set_message(
MessageKind::Error,
"Replacement equals the current value; no change was made",
);
return;
}
if model.series.data_revision() != pending.data_revision {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"Data changed while confirmation was open; search again before replacing a value",
);
return;
}
match model.replace_numeric_cell_for_experiment(
&pending.experiment_id,
&pending.column,
pending.row_index,
pending.expected_value,
replacement_value,
) {
Ok(()) => {
self.current_page = None;
self.reset_numeric_search();
self.set_message(
MessageKind::Success,
format!(
"Replaced {} at source row {} in experiment '{}'; Undo is available",
pending.column,
pending.row_index,
display_experiment_id(&pending.experiment_id)
),
);
}
Err(crate::gui::experimental_kinetics_gui::model::TGAGUIError::PostCommitWarning(
warning,
)) => {
self.current_page = None;
self.reset_numeric_search();
self.set_message(MessageKind::Warning, warning);
}
Err(error) => self.set_message(
MessageKind::Error,
format!("Could not replace the found value: {error}"),
),
}
}
fn commit_delete_found_row(&mut self, model: &mut PlotModel) {
let Some(pending) = self.confirm_drop_row.take() else {
return;
};
if model.series.data_revision() != pending.data_revision {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"Data changed while confirmation was open; search again before deleting a row",
);
return;
}
let current_value = match model
.series
.get_experiment_by_id(&pending.experiment_id)
.and_then(|experiment| {
experiment
.dataset
.numeric_value_at_row(&pending.match_column, pending.row_index)
.map_err(TGADomainError::PolarsError)
}) {
Ok(value) => value,
Err(error) => {
self.set_message(MessageKind::Error, format!("Could not delete row: {error}"));
return;
}
};
if current_value.is_none_or(|value| value.to_bits() != pending.match_value.to_bits()) {
self.reset_numeric_search();
self.set_message(
MessageKind::Warning,
"The found cell no longer matches the search result; search again before deleting a row",
);
return;
}
let deleting_only_row_on_last_page = self.current_page.as_ref().is_some_and(|page| {
page.experiment_id == pending.experiment_id
&& !page.has_next
&& page.preview.row_indices.len() == 1
&& page.preview.row_indices[0] == pending.row_index
});
match model.delete_rows_for_experiment(&pending.experiment_id, &[pending.row_index]) {
Ok(()) => {
self.finish_row_deletion_view(deleting_only_row_on_last_page);
self.set_message(
MessageKind::Success,
format!(
"Deleted source row {} from experiment '{}' across all columns; Undo is available",
pending.row_index,
display_experiment_id(&pending.experiment_id)
),
);
}
Err(crate::gui::experimental_kinetics_gui::model::TGAGUIError::PostCommitWarning(
warning,
)) => {
self.finish_row_deletion_view(deleting_only_row_on_last_page);
self.set_message(MessageKind::Warning, warning);
}
Err(error) => {
self.set_message(
MessageKind::Error,
format!("Could not delete source row: {error}"),
);
}
}
}
fn finish_row_deletion_view(&mut self, deleted_only_row_on_last_page: bool) {
if deleted_only_row_on_last_page {
self.page_start = self.page_start.saturating_sub(PAGE_SIZE);
}
self.current_page = None;
self.reset_numeric_search();
}
fn render_search_controls(&mut self, ui: &mut egui::Ui, model: &PlotModel) {
if self.compare_mode {
return;
}
if self.search_tolerance.is_empty() {
self.search_tolerance = "0".to_string();
}
ui.separator();
let selected_column = self
.selected_column
.as_ref()
.filter(|(exp_id, _)| Some(exp_id) == self.table_experiment.as_ref())
.cloned();
let mut find_next = false;
let mut find_previous = false;
let mut request_delete = false;
let mut request_replace = false;
let mut parsed_target = None;
let mut parsed_tolerance = None;
ui.horizontal_wrapped(|ui| {
ui.strong("Find numeric value");
if let Some((_, column)) = &selected_column {
ui.label(format!("Column: {column}"));
} else {
ui.weak("Select a column heading first");
}
let target_label = ui.label("Target");
let target_edit = ui.add(
egui::TextEdit::singleline(&mut self.search_target).desired_width(100.0),
);
target_edit.labelled_by(target_label.id);
let tolerance_label = ui.label("Tolerance");
let tolerance_edit = ui.add(
egui::TextEdit::singleline(&mut self.search_tolerance).desired_width(80.0),
);
tolerance_edit.labelled_by(tolerance_label.id);
parsed_target = self
.search_target
.trim()
.parse::<f64>()
.ok()
.filter(|value| value.is_finite());
parsed_tolerance = self
.search_tolerance
.trim()
.parse::<f64>()
.ok()
.filter(|value| value.is_finite() && *value >= 0.0);
let inputs_valid = parsed_target.is_some() && parsed_tolerance.is_some();
let can_search = selected_column.is_some() && inputs_valid;
if ui
.add_enabled(can_search, egui::Button::new("Find next"))
.on_hover_text("Searches the entire selected column after the current match. Does not change data and does not wrap at the end.")
.on_disabled_hover_text(if selected_column.is_none() {
"Select a column in the table before searching."
} else {
"Enter a finite target and a finite, non-negative tolerance."
})
.clicked()
{
find_next = true;
}
if ui
.add_enabled(can_search, egui::Button::new("Find previous"))
.on_hover_text("Searches backward through the entire selected column; the first backward search starts at the end. Does not change data or wrap at the beginning.")
.on_disabled_hover_text(if selected_column.is_none() {
"Select a column in the table before searching."
} else {
"Enter a finite target and a finite, non-negative tolerance."
})
.clicked()
{
find_previous = true;
}
});
let current_key = selected_column
.as_ref()
.zip(parsed_target)
.zip(parsed_tolerance)
.map(|(((exp_id, column), target), tolerance)| {
(
exp_id.clone(),
column.clone(),
target.to_bits(),
tolerance.to_bits(),
model.series.data_revision(),
)
});
if self
.search_key
.as_ref()
.is_some_and(|previous| current_key.as_ref() != Some(previous))
{
self.reset_numeric_search();
}
if let Some(message) = &self.search_message {
if message.starts_with("Search failed:") {
ui.colored_label(egui::Color32::LIGHT_RED, message);
} else if message.starts_with("No ") {
ui.colored_label(egui::Color32::YELLOW, message);
} else {
ui.label(message);
}
} else if parsed_target.is_none() {
ui.colored_label(
egui::Color32::YELLOW,
"Enter a finite numeric target value.",
);
} else if parsed_tolerance.is_none() {
ui.colored_label(
egui::Color32::YELLOW,
"Tolerance must be finite and greater than or equal to 0.",
);
}
if self.search_result.is_some() && selected_column.is_some() {
if ui
.button("Replace found value...")
.on_hover_text("Replaces only the selected numeric cell after confirmation. Other rows and columns stay unchanged; the edit is undoable.")
.clicked()
{
request_replace = true;
}
if ui
.button("Delete found row...")
.on_hover_text("Deletes the entire data row across every column after confirmation. This is undoable; no cell-only deletion occurs.")
.clicked()
{
request_delete = true;
}
}
if find_next {
self.execute_numeric_search(model, RowSearchDirection::Forward);
}
if find_previous {
self.execute_numeric_search(model, RowSearchDirection::Backward);
}
if request_delete {
self.prepare_delete_found_row(model);
}
if request_replace {
self.prepare_replace_found_value(model);
}
}
fn selected_column_checkboxes(&self) -> Vec<(String, String)> {
let Some(active_id) = self.table_experiment.as_deref() else {
return Vec::new();
};
let mut selected = self
.column_checkboxes
.iter()
.filter(|((exp_id, _), checked)| exp_id == active_id && **checked)
.map(|((exp_id, name), _)| (exp_id.clone(), name.clone()))
.collect::<Vec<_>>();
selected.sort();
selected
}
fn handle_drop_columns(&mut self) {
if self.compare_mode {
self.set_message(
MessageKind::Error,
"Column deletion is unavailable in comparison mode",
);
return;
}
let selected = self.selected_column_checkboxes();
if selected.is_empty() {
self.set_message(MessageKind::Error, "No columns selected for dropping");
return;
}
self.confirm_drop_columns = selected;
}
fn commit_drop_columns(&mut self, model: &mut PlotModel) {
let selected = std::mem::take(&mut self.confirm_drop_columns);
let Some((exp_id, _)) = selected.first() else {
self.set_message(MessageKind::Error, "No columns selected for dropping");
return;
};
if selected
.iter()
.any(|(selected_exp, _)| selected_exp != exp_id)
{
self.set_message(
MessageKind::Error,
"A column-delete batch must target one experiment",
);
return;
}
let col_names = selected
.iter()
.map(|(_, name)| name.clone())
.collect::<Vec<_>>();
if let Err(error) = model.drop_columns_for_experiment(exp_id, &col_names) {
self.set_message(
MessageKind::Error,
format!("Could not drop columns: {error:?}"),
);
return;
}
if let Some(preview) = self.cached_samples.get_mut(exp_id) {
for name in &col_names {
preview.columns.remove(name);
}
}
for name in col_names {
self.column_checkboxes.remove(&(exp_id.clone(), name));
}
if self
.selected_column
.as_ref()
.is_some_and(|(selected_exp, selected_name)| {
selected_exp == exp_id && selected.iter().any(|(_, name)| name == selected_name)
})
{
self.selected_column = None;
self.reset_numeric_search();
}
self.current_page = None;
self.set_message(MessageKind::Success, "Columns dropped successfully");
}
fn handle_rename_column(&mut self, model: &mut PlotModel, exp_id: &str, old_name: &str) {
if self.compare_mode {
self.set_message(
MessageKind::Error,
"Column renaming is unavailable in comparison mode",
);
return;
}
if self.new_column_name.trim().is_empty() {
self.set_message(MessageKind::Error, "Enter new column name");
return;
}
if let Err(e) =
model.rename_column_for_experiment(exp_id, old_name, self.new_column_name.trim())
{
self.set_message(
MessageKind::Error,
format!("Could not rename column: {e:?}"),
);
return;
}
if let Some(preview) = self.cached_samples.get_mut(exp_id) {
preview.columns.remove(old_name);
}
self.column_checkboxes
.remove(&(exp_id.to_string(), old_name.to_string()));
if self
.selected_column
.as_ref()
.map(|(selected_exp, selected_col)| selected_exp == exp_id && selected_col == old_name)
.unwrap_or(false)
{
self.selected_column =
Some((exp_id.to_string(), self.new_column_name.trim().to_string()));
}
self.set_message(MessageKind::Success, "Column renamed successfully");
self.new_column_name.clear();
}
fn handle_check_time_monotonity(&mut self, model: &mut PlotModel) {
let selected_experiments = self.table_experiment.iter().cloned().collect::<Vec<_>>();
if selected_experiments.is_empty() {
self.set_message(MessageKind::Error, "Select an experiment first");
info!("Select an experiment first");
return;
}
let mut per_experiment_messages = Vec::new();
for exp_id in selected_experiments {
match model.time_monotonicity_report_for_experiment(&exp_id) {
Ok(report) if report.is_strictly_increasing => {
let msg = format!(
"Experiment '{}': time monotonicity OK for '{}'",
exp_id, report.time_column
);
info!("{}", msg);
per_experiment_messages.push(msg);
}
Ok(report) => {
let mut details = Vec::new();
if !report.null_indices.is_empty() {
details.push(format!("nulls at {:?}", report.null_indices));
}
if !report.nan_indices.is_empty() {
details.push(format!("NaNs at {:?}", report.nan_indices));
}
if !report.infinite_indices.is_empty() {
details.push(format!("infinities at {:?}", report.infinite_indices));
}
if !report.duplicate_pairs.is_empty() {
details.push(format!("duplicates at {:?}", report.duplicate_pairs));
}
if !report.decreasing_pairs.is_empty() {
details.push(format!("decreasing at {:?}", report.decreasing_pairs));
}
let msg = format!(
"Experiment '{}': time monotonicity FAILED for '{}' ({})",
exp_id,
report.time_column,
details.join("; ")
);
info!("{}", msg);
per_experiment_messages.push(msg);
}
Err(e) => {
let msg = format!(
"Experiment '{}': time monotonicity check error: {}",
exp_id, e
);
info!("{}", msg);
per_experiment_messages.push(msg);
}
}
}
let kind = if per_experiment_messages
.iter()
.any(|message| message.contains("FAILED") || message.contains("error:"))
{
MessageKind::Warning
} else {
MessageKind::Success
};
self.set_message(kind, per_experiment_messages.join(" | "));
}
fn handle_sort_by_time(&mut self, model: &mut PlotModel) {
let selected_experiments = self.table_experiment.iter().cloned().collect::<Vec<_>>();
if selected_experiments.is_empty() {
self.set_message(MessageKind::Error, "Select an experiment first");
info!("Select an experiment first");
return;
}
let mut per_experiment_messages = Vec::new();
for exp_id in selected_experiments {
match model.time_monotonicity_report_for_experiment(&exp_id) {
Ok(report) if !report.sortable_without_data_loss => {
let msg = format!(
"Experiment '{}': cannot sort time column '{}' because it contains null/NaN/inf values",
exp_id, report.time_column
);
info!("{}", msg);
per_experiment_messages.push(msg);
}
Ok(report) if report.is_strictly_increasing => {
let msg = format!("Experiment '{}': time already monotonic", exp_id);
info!("{}", msg);
per_experiment_messages.push(msg);
}
Ok(report) => match model.sort_experiment_by_time(&exp_id) {
Ok(()) => {
let msg = if !report.duplicate_pairs.is_empty() {
format!(
"Experiment '{}': sorted by time; duplicate time values remain in '{}'",
exp_id, report.time_column
)
} else {
format!(
"Experiment '{}': sorted by time column '{}'",
exp_id, report.time_column
)
};
info!("{}", msg);
per_experiment_messages.push(msg);
}
Err(e) => {
let msg = format!("Experiment '{}': sort by time failed: {}", exp_id, e);
info!("{}", msg);
per_experiment_messages.push(msg);
}
},
Err(e) => {
let msg = format!(
"Experiment '{}': time monotonicity report error: {}",
exp_id, e
);
info!("{}", msg);
per_experiment_messages.push(msg);
}
}
}
let kind = if per_experiment_messages
.iter()
.any(|message| message.contains("failed") || message.contains("cannot sort"))
{
MessageKind::Error
} else if per_experiment_messages
.iter()
.any(|message| message.contains("duplicates remain"))
{
MessageKind::Warning
} else if per_experiment_messages
.iter()
.any(|message| message.contains("sorted by time"))
{
MessageKind::Success
} else {
MessageKind::Info
};
self.set_message(kind, per_experiment_messages.join(" | "));
}
fn render_table(&mut self, ui: &mut egui::Ui, model: &PlotModel) {
if self.compare_mode {
if self.comparison_grid_error.is_some() {
return;
}
}
let experiments = if self.compare_mode {
let mut selected = self.compare_experiments.iter().cloned().collect::<Vec<_>>();
selected.sort();
selected
} else {
self.table_experiment.iter().cloned().collect()
};
if experiments.is_empty() {
ui.label(if self.compare_mode {
"Select experiments to compare"
} else {
"No experiments loaded"
});
return;
}
let mut all_columns = Vec::new();
for exp_id in &experiments {
if let Ok(cols) = model.list_of_columns(exp_id) {
for col_name in cols {
all_columns.push((exp_id.clone(), col_name));
}
}
}
let show_row_index = !self.compare_mode;
let row_index_width = if show_row_index { 58.0 } else { 0.0 };
let column_width = data_column_width(
(ui.available_width() - row_index_width).max(1.0),
all_columns.len(),
);
ui.push_id("column_manager_table", |ui| {
egui::ScrollArea::both()
.id_salt("column_manager_table_scroll")
.auto_shrink([false, false])
.max_height(ui.available_height().max(1.0))
.show(ui, |ui| {
let mut table = TableBuilder::new(ui).striped(true);
if show_row_index {
table = table.column(Column::initial(58.0).resizable(true));
}
table
.columns(
Column::initial(column_width).resizable(false),
all_columns.len(),
)
.header(48.0, |mut header| {
if show_row_index {
header.col(|ui| {
ui.heading("Source row");
});
}
for (exp_id, col_name) in &all_columns {
header.col(|ui| {
ui.vertical(|ui| {
let key = (exp_id.clone(), col_name.clone());
let checked =
self.column_checkboxes.entry(key).or_insert(false);
let is_selected = self
.selected_column
.as_ref()
.is_some_and(|(selected_exp, selected_col)| {
selected_exp == exp_id && selected_col == col_name
});
let header_text = if self.compare_mode {
format!("{}::{}", display_experiment_id(exp_id), col_name)
} else {
col_name.clone()
};
let title = ui
.selectable_label(is_selected, header_text)
.on_hover_text(format!(
"Experiment: {}\nColumn: {}",
display_experiment_id(exp_id),
col_name
));
let checkbox = ui.add_enabled(
!self.compare_mode,
egui::Checkbox::new(checked, ""),
).on_hover_text(if self.compare_mode {
"Column selection and data-changing actions are disabled in comparison mode."
} else {
"Select this column for the confirmed bulk-delete action. Clicking the column name only opens its details."
});
let _ = checkbox.labelled_by(title.id);
if title.clicked() {
let selection = (exp_id.clone(), col_name.clone());
if self.selected_column.as_ref() != Some(&selection) {
self.reset_numeric_search();
self.selected_column = Some(selection);
}
}
if let Ok(Some(provenance)) =
model.column_provenance_for_experiment(exp_id, col_name)
{
title.on_hover_text(provenance);
}
});
});
}
})
.body(|mut body| {
let preview_lengths = experiments
.iter()
.filter_map(|id| {
let preview = if self.compare_mode {
self.cached_samples.get(id)
} else {
self.current_page
.as_ref()
.filter(|page| page.experiment_id == *id)
.map(|page| &page.preview)
};
preview.map(|preview| preview.row_indices.len())
})
.collect::<Vec<_>>();
let row_count = if self.compare_mode {
preview_lengths.into_iter().min().unwrap_or(0)
} else {
preview_lengths.into_iter().max().unwrap_or(0)
};
for row_idx in 0..row_count {
body.row(23.0, |mut row| {
if show_row_index {
row.col(|ui| {
let row_sources = experiments
.iter()
.filter_map(|id| {
let preview = if self.compare_mode {
self.cached_samples.get(id)
} else {
self.current_page
.as_ref()
.filter(|page| page.experiment_id == *id)
.map(|page| &page.preview)
}?;
preview.row_indices.get(row_idx).map(|source_row| {
(id.clone(), *source_row)
})
})
.collect::<Vec<_>>();
let indices = row_sources
.iter()
.map(|(_, source_row)| source_row.to_string())
.collect::<Vec<_>>()
.join(" | ");
let selected_interval = self.selected_row_interval.as_ref();
let row_is_in_interval = row_sources.iter().any(|(id, source_row)| {
selected_interval.is_some_and(|selection| {
selection.experiment_id == *id
&& selection.contains(*source_row)
})
});
let is_search_hit = self
.current_page
.as_ref()
.filter(|page| page.experiment_id == experiments[0])
.and_then(|page| page.preview.row_indices.get(row_idx))
.is_some_and(|&source_row| {
self.search_result.is_some_and(|hit| hit.row_index == source_row)
});
if !self.compare_mode && row_sources.len() == 1 {
let (id, source_row) = &row_sources[0];
let response = ui.selectable_label(
row_is_in_interval,
source_row.to_string(),
).on_hover_text(format!(
"Source row {source_row}. Click to set the interval start; Shift-click another row to set its end."
));
if response.clicked() {
let extend = ui.input(|input| input.modifiers.shift);
self.select_source_row(id, *source_row, extend);
}
if is_search_hit {
response.on_hover_text("Current numeric-search result.");
}
} else if is_search_hit {
ui.strong(indices);
} else {
ui.label(indices);
}
});
}
for (exp_id, col_name) in &all_columns {
row.col(|ui| {
let preview = if self.compare_mode {
self.cached_samples.get(exp_id)
} else {
self.current_page
.as_ref()
.filter(|page| page.experiment_id == *exp_id)
.map(|page| &page.preview)
};
if let Some(preview) = preview {
let sample_idx = row_idx;
let text = match preview.columns.get(col_name) {
None => "-".to_string(),
Some(values) => values
.get(sample_idx)
.copied()
.flatten()
.map(format_sample_value)
.unwrap_or_else(|| "null".to_string()),
};
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
ui.monospace(text);
},
);
} else {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
ui.monospace("-");
},
);
}
});
}
});
}
});
});
});
}
fn render_column_comparison(
&mut self,
ui: &mut egui::Ui,
model: &PlotModel,
experiment_id: &str,
) {
if self.compare_mode {
ui.weak("Column comparison is for multiple columns within one experiment; comparison mode across experiments is read-only.");
return;
}
let columns = match model.list_of_columns(experiment_id) {
Ok(columns) => columns,
Err(error) => {
ui.colored_label(
egui::Color32::LIGHT_RED,
format!("Could not list columns: {error}"),
);
return;
}
};
let default_reference = model
.series
.get_experiment_by_id(experiment_id)
.ok()
.and_then(|experiment| experiment.dataset.schema.mass.clone())
.filter(|name| columns.contains(name))
.or_else(|| columns.first().cloned());
if self
.comparison_reference
.as_ref()
.is_none_or(|name| !columns.contains(name))
{
self.comparison_reference = default_reference;
}
let Some(reference) = self.comparison_reference.clone() else {
ui.weak("This experiment has no numeric columns to compare.");
return;
};
let experiment = match model.series.get_experiment_by_id(experiment_id) {
Ok(experiment) => experiment,
Err(error) => {
ui.colored_label(egui::Color32::LIGHT_RED, error.to_string());
return;
}
};
let reference_unit = experiment
.dataset
.schema
.columns
.get(&reference)
.map(|meta| meta.unit);
let candidate_count_before_prune = self.comparison_candidates.len();
self.comparison_candidates.retain(|candidate| {
columns.contains(candidate)
&& candidate != &reference
&& experiment
.dataset
.schema
.columns
.get(candidate)
.zip(reference_unit)
.is_some_and(|(candidate, reference)| candidate.unit == reference)
});
if self.comparison_candidates.len() != candidate_count_before_prune {
self.column_comparison = None;
}
ui.label(
"Compare several columns from this experiment on one shared set of valid source rows.",
);
let mut reference_changed = false;
egui::ComboBox::from_label("Reference column")
.selected_text(&reference)
.show_ui(ui, |ui| {
for column in &columns {
if ui
.selectable_value(
&mut self.comparison_reference,
Some(column.clone()),
column,
)
.changed()
{
self.comparison_candidates.remove(column);
reference_changed = true;
}
}
});
if reference_changed {
self.column_comparison = None;
}
ui.label("Candidate columns");
let mut candidates_changed = false;
egui::ScrollArea::vertical()
.id_salt(("column_comparison_candidates", experiment_id))
.max_height(110.0)
.show(ui, |ui| {
for column in &columns {
if column == &reference {
continue;
}
let same_unit = reference_unit.is_some_and(|reference_unit| {
experiment
.dataset
.schema
.columns
.get(column)
.is_some_and(|candidate| candidate.unit == reference_unit)
});
let mut selected = self.comparison_candidates.contains(column);
let candidate_label = experiment
.dataset
.schema
.columns
.get(column)
.map(|meta| format!("{column} [{:?}]", meta.unit))
.unwrap_or_else(|| column.clone());
let checkbox = ui.add_enabled(
same_unit,
egui::Checkbox::new(&mut selected, candidate_label),
);
let checkbox = if same_unit {
checkbox
} else {
checkbox.on_hover_text(
"Columns must have the same unit to compare values directly.",
)
};
if checkbox.changed() {
candidates_changed = true;
if selected {
self.comparison_candidates.insert(column.clone());
} else {
self.comparison_candidates.remove(column);
}
}
}
});
if candidates_changed {
self.column_comparison = None;
}
let mut candidates = self
.comparison_candidates
.iter()
.cloned()
.collect::<Vec<_>>();
candidates.sort();
ui.horizontal(|ui| {
ui.label(format!("Reference: {reference} | Candidates: {}", candidates.len()));
if ui
.add_enabled(!candidates.is_empty(), egui::Button::new("Compare columns"))
.on_hover_text("Calculates similarity and roughness metrics on rows complete for the reference and every selected candidate. No data is modified or resampled.")
.on_disabled_hover_text("Select at least one candidate column distinct from the reference.")
.clicked()
{
self.column_comparison = None;
match (
Self::preview_signature(model, experiment_id),
compare_columns_for_experiment(model, experiment_id, &reference, &candidates),
) {
(Ok(signature), Ok((points_used, reports))) => {
self.column_comparison = Some(CachedColumnComparison {
experiment_id: experiment_id.to_string(),
signature,
reference: QualityReference::NamedColumn(reference.clone()),
candidates: candidates.clone(),
points_used,
reports,
});
self.set_message(
MessageKind::Success,
format!("Compared {} column(s) against '{reference}'", candidates.len()),
);
}
(Err(error), _) | (_, Err(error)) => self.set_message(
MessageKind::Error,
format!("Column comparison failed: {error}"),
),
}
}
});
let signature = Self::preview_signature(model, experiment_id).ok();
let data_changed = self.column_comparison.as_ref().is_some_and(|result| {
result.experiment_id == experiment_id && signature.as_ref() != Some(&result.signature)
});
if data_changed {
self.column_comparison = None;
let message =
"Comparison report invalidated because data or schema changed; compare again.";
ui.weak(message);
self.set_message(MessageKind::Warning, message);
}
let current = self.column_comparison.as_ref().filter(|result| {
result.experiment_id == experiment_id
&& matches!(
&result.reference,
QualityReference::NamedColumn(name) if name == &reference
)
&& result.candidates == candidates
&& signature.as_ref() == Some(&result.signature)
});
if let Some(result) = current {
ui.separator();
ui.strong(format!(
"Reference: {} | common valid rows: {}",
result.reference, result.points_used
));
ui.weak("The reference is a comparison choice, not a known true signal. Metrics are not an automatic filter ranking.");
egui::Grid::new(("column_comparison_metrics", experiment_id))
.striped(true)
.show(ui, |ui| {
ui.strong("Candidate");
ui.strong("RMSE")
.on_hover_text("Root-mean-square difference from the selected reference, in the column's unit.");
ui.strong("Normalized RMSE")
.on_hover_text("RMSE divided by the reference standard deviation; useful for comparing scale, not a truth/accuracy score.");
ui.strong("Correlation")
.on_hover_text("Shape similarity to the selected reference; closer to 1 means stronger positive linear association.");
ui.end_row();
for report in &result.reports {
ui.label(&report.column_filtered);
ui.label(format!("{:.6}", report.rmse));
ui.label(format!("{:.6}", report.normalized_rmse));
ui.label(format!("{:.6}", report.correlation));
ui.end_row();
}
});
ui.separator();
ui.strong("Change in smoothness relative to reference");
egui::Grid::new(("column_comparison_roughness", experiment_id))
.striped(true)
.show(ui, |ui| {
ui.strong("Candidate");
ui.strong("First differences")
.on_hover_text("Standard-deviation ratio of adjacent-point differences: candidate divided by reference.");
ui.strong("Second differences")
.on_hover_text("Standard-deviation ratio of second differences: candidate divided by reference.");
ui.end_row();
for report in &result.reports {
ui.label(&report.column_filtered);
ui.label(format!("{:.6}", report.roughness_ratio_1st));
ui.label(format!("{:.6}", report.roughness_ratio_2nd));
ui.end_row();
}
});
ui.weak("Roughness ratios below 1 indicate smoother differences than the selected reference; this alone does not prove greater accuracy.");
}
}
fn render_selected_column_details(&mut self, ui: &mut egui::Ui, model: &mut PlotModel) {
ui.push_id("column_manager_details", |ui| {
ui.separator();
ui.horizontal(|ui| {
ui.heading("Column details");
if ui.small_button("Clear").on_hover_text("Close the column inspector; this does not change data.").clicked() {
self.selected_column = None;
}
});
let Some((exp_id, col_name)) = self.selected_column.clone() else {
ui.label("Click a column title to inspect its provenance and operation history.");
return;
};
ui.horizontal(|ui| {
for (tab, label) in [
(DetailsTab::Overview, "Overview"),
(DetailsTab::Processing, "Processing"),
(DetailsTab::Quality, "Quality"),
(DetailsTab::Comparison, "Compare"),
(DetailsTab::History, "History"),
] {
ui.add_enabled_ui(tab != DetailsTab::Comparison || !self.compare_mode, |ui| {
ui.selectable_value(&mut self.details_tab, tab, label);
});
}
});
let details_height = ui.available_height().max(140.0);
egui::ScrollArea::vertical()
.id_salt(format!(
"column_manager_details_scroll:{}:{}",
exp_id, col_name
))
.max_height(details_height)
.show(ui, |ui| {
if self.details_tab == DetailsTab::Comparison {
self.render_column_comparison(ui, model, &exp_id);
return;
}
if self.details_tab == DetailsTab::Overview {
ui.strong(format!("{} / {}", display_experiment_id(&exp_id), col_name));
if let Ok(experiment) = model.series.get_experiment_by_id(&exp_id) {
if let Some(meta) = experiment.dataset.schema.columns.get(&col_name) {
ui.label(format!("Unit: {:?} | Nature: {:?}", meta.unit, meta.nature));
let bound = schema_role_bindings(&experiment.dataset.schema)
.into_iter()
.filter_map(|(role, name)| (name == Some(col_name.as_str())).then_some(role))
.collect::<Vec<_>>();
ui.label(format!("Schema binding: {}", if bound.is_empty() { "none".to_string() } else { bound.join(", ") }));
}
}
ui.label(format!("On plot: {}", model.plots.iter().any(|curve| curve.experiment_id == exp_id && (curve.x_name == col_name || curve.y_name == col_name))));
let columns = model.list_of_columns(&exp_id).unwrap_or_default();
let default_x = model
.series
.get_experiment_by_id(&exp_id)
.ok()
.and_then(|experiment| experiment.dataset.schema.time.clone())
.filter(|time| time != &col_name)
.or_else(|| columns.iter().find(|name| *name != &col_name).cloned());
if self.plot_x_column.as_ref().is_none_or(|x| !columns.contains(x) || x == &col_name) {
self.plot_x_column = default_x;
}
ui.horizontal(|ui| {
egui::ComboBox::from_label("X column")
.selected_text(self.plot_x_column.as_deref().unwrap_or("Select X column"))
.show_ui(ui, |ui| {
for x in columns.iter().filter(|name| *name != &col_name) {
ui.selectable_value(&mut self.plot_x_column, Some(x.clone()), x);
}
});
let can_plot = self.plot_x_column.as_ref().is_some_and(|x| x != &col_name);
if ui.add_enabled(can_plot, egui::Button::new("Show on plot"))
.on_hover_text("Plots this column as Y against the selected X. Creates no data column and does not change bindings or calculation sources.")
.on_disabled_hover_text("Choose an X column different from the column being plotted.")
.clicked()
{
let x = self.plot_x_column.as_deref().unwrap_or_default();
match model.show_column_on_plot(&exp_id, x, &col_name) {
Ok(true) => self.set_message(MessageKind::Success, format!("Showing {col_name} vs {x}")),
Ok(false) => self.set_message(MessageKind::Info, format!("{col_name} vs {x} is already shown")),
Err(error) => self.set_message(MessageKind::Error, format!("Could not show column on plot: {error}")),
}
}
});
if let Some(interval) = self
.selected_row_interval
.as_ref()
.filter(|interval| interval.experiment_id == exp_id)
{
let (start, end) = interval.bounds();
ui.horizontal(|ui| {
ui.label(format!(
"Selected source rows: {}-{}",
start + 1,
end + 1
));
if ui
.button("Zoom plot to interval")
.on_hover_text("Changes only the shared graph viewport to the selected source rows. Does not edit data or create a curve. The interval must be on the currently displayed page.")
.clicked()
{
let x_column = self.plot_x_column.as_deref().or_else(|| {
model
.series
.get_experiment_by_id(&exp_id)
.ok()
.and_then(|experiment| experiment.dataset.schema.time.as_deref())
});
let result = x_column
.ok_or_else(|| "Select an X column first".to_string())
.and_then(|x_column| {
let page = self.current_page.as_ref()
.filter(|page| page.experiment_id == exp_id)
.ok_or_else(|| "The source-row page is not available".to_string())?;
let x_values = page.preview.columns.get(x_column)
.ok_or_else(|| format!("X column '{x_column}' is not in the current preview"))?;
let finite = page.preview.row_indices.iter()
.enumerate()
.filter(|(_, row)| (start..=end).contains(row))
.filter_map(|(index, _)| x_values.get(index).copied().flatten())
.filter(|value| value.is_finite())
.collect::<Vec<_>>();
if finite.is_empty() {
return Err(format!("No finite '{x_column}' values in selected rows"));
}
let x_min = finite.iter().copied().fold(f64::INFINITY, f64::min);
let x_max = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let x_margin = ((x_max - x_min).abs() * 0.05)
.max(x_min.abs().max(x_max.abs()) * 1e-6 + 1e-9);
model.interaction.view_range = (x_min - x_margin, x_max + x_margin);
let y_values = model.plots.iter()
.filter(|curve| curve.shown && curve.experiment_id == exp_id && curve.x_name == x_column)
.flat_map(|curve| curve.points.iter())
.filter(|point| point[0] >= x_min && point[0] <= x_max)
.map(|point| point[1])
.filter(|value| value.is_finite())
.collect::<Vec<_>>();
if let (Some(y_min), Some(y_max)) = (
y_values.iter().copied().min_by(f64::total_cmp),
y_values.iter().copied().max_by(f64::total_cmp),
) {
let y_margin = ((y_max - y_min).abs() * 0.05)
.max(y_min.abs().max(y_max.abs()) * 1e-6 + 1e-9);
model.interaction.view_y_range = (y_min - y_margin, y_max + y_margin);
}
model.reset_view_requested = true;
Ok(format!("Graph viewport focused on source rows {}-{} using X column '{x_column}'", start + 1, end + 1))
});
match result {
Ok(message) => self.set_message(MessageKind::Success, message),
Err(error) => self.set_message(MessageKind::Error, error),
}
}
});
ui.weak("Select a start row, then Shift-click an end row on this page.");
}
let mass_active = model.active_mass_source_for_experiment(&exp_id).is_ok_and(|source| source == col_name);
let temp_active = model.active_temperature_source_for_experiment(&exp_id).is_ok_and(|source| source == col_name);
ui.label(format!("Calculation source: {}", match (mass_active, temp_active) { (true, true) => "mass and temperature", (true, false) => "mass", (false, true) => "temperature", _ => "none" }));
if ui
.button("Copy full column")
.on_hover_text("Copies every source row, including nulls, with row indices and the column unit. Does not modify data.")
.clicked()
{
match model.numeric_column_tsv_for_experiment(&exp_id, &col_name) {
Ok((text, row_count)) => {
ui.ctx().copy_text(text);
self.set_message(
MessageKind::Success,
format!("Copied {row_count} values from '{col_name}' with source row indices and unit"),
);
}
Err(error) => self.set_message(
MessageKind::Error,
format!("Could not copy column: {error}"),
),
}
}
if self.compare_mode { ui.label("Comparison mode is read-only."); }
else {
ui.horizontal(|ui| {
let label = ui.label("Rename to:");
let input = ui.text_edit_singleline(&mut self.new_column_name);
let _ = input.labelled_by(label.id);
if ui.add_enabled(!self.new_column_name.trim().is_empty(), egui::Button::new("Rename"))
.on_hover_text("Renames this column; no new column is created.")
.on_disabled_hover_text("Enter a non-empty new column name.")
.clicked() { self.handle_rename_column(model, &exp_id, &col_name); }
});
}
}
let provenance = model
.series
.get_experiment_by_id(&exp_id)
.ok()
.and_then(|experiment| experiment.dataset.column_provenance(&col_name))
.cloned();
let history = model
.column_history_feed_for_experiment(&exp_id, &col_name)
.unwrap_or_else(|e| format!("Failed to read history: {:?}", e));
if self.details_tab == DetailsTab::Processing { ui.label("Provenance"); }
if let Some(provenance) = provenance {
if self.details_tab == DetailsTab::Processing { ui.label(format!("Source columns: {}", provenance.root_columns.join(", "))); }
for (index, step) in provenance.steps.iter().enumerate() {
if matches!(self.details_tab, DetailsTab::Processing | DetailsTab::Quality) {
if let Some(coverage) = &step.coverage {
ui.label(format!("Data coverage: {}", coverage.summary()));
}
}
if self.details_tab == DetailsTab::Processing {
ui.separator();
ui.label(format!(
"Step {}: {} -> {}",
index + 1,
step.input_columns.join(", "),
step.output_column
));
ui.label(step.kind.to_string());
}
if self.details_tab == DetailsTab::Quality { if let Some(quality) = &step.quality {
ui.label(format!("Quality: {}", step.kind));
if let Some(report) = &quality.report {
ui.label(format!("Compared {} vs {} ({}, {})", report.column_raw, report.column_filtered, quality.compared_to, quality.status));
egui::Grid::new(("column_quality", &exp_id, &col_name, index))
.striped(true)
.show(ui, |ui| {
ui.strong("Metric");
ui.strong("Value");
ui.strong("Interpretation");
ui.end_row();
for (name, value, meaning) in [
(
"RMSE",
report.rmse,
"Difference from the comparison column; lower is closer.",
),
(
"Normalized RMSE",
report.normalized_rmse,
"Scale-normalized difference; lower is closer.",
),
(
"Correlation",
report.correlation,
"Shape similarity; values closer to 1 indicate stronger agreement.",
),
(
"First-difference roughness ratio",
report.roughness_ratio_1st,
"Output/input first-difference roughness; below 1 is smoother.",
),
(
"Second-difference roughness ratio",
report.roughness_ratio_2nd,
"Output/input second-difference roughness; below 1 is smoother.",
),
] {
ui.label(name);
ui.label(format!("{value:.6}"));
ui.label(meaning);
ui.end_row();
}
});
ui.label(
"These metrics describe change relative to the comparison column; they do not establish accuracy against a true signal.",
);
} else {
ui.label(format!("Quality metrics unavailable: {}", quality.status));
}
}}
}
} else {
if matches!(self.details_tab, DetailsTab::Processing | DetailsTab::Quality) { ui.label("No provenance available"); }
}
if self.details_tab == DetailsTab::Quality {
ui.separator();
ui.strong("Data integrity");
if ui
.button("Run data diagnostics")
.on_hover_text("Scans this complete numeric column once for nulls, NaN, infinities and finite range. For the bound time column it also checks ordering. Results are cached until data or schema changes.")
.clicked()
{
self.run_column_diagnostics(model, &exp_id, &col_name);
}
let current_signature = Self::preview_signature(model, &exp_id).ok();
let cached_is_stale = self.column_diagnostics.as_ref().is_some_and(
|cached| {
cached.experiment_id == exp_id
&& cached.column == col_name
&& current_signature.as_ref() != Some(&cached.signature)
},
);
if cached_is_stale {
self.column_diagnostics = None;
}
if let Some(cached) = self.column_diagnostics.as_ref().filter(|cached| {
cached.experiment_id == exp_id
&& cached.column == col_name
&& current_signature.as_ref() == Some(&cached.signature)
}) {
render_column_diagnostics(ui, &cached.report);
} else {
ui.weak("Run diagnostics to inspect all source rows. Results refresh after the next data/schema change.");
}
}
if self.details_tab == DetailsTab::History {
ui.label("Operation history");
ui.monospace(history);
}
});
});
}
fn show_metadata_window(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
if !self.metadata_window_open {
return;
}
egui::Window::new("Edit Metadata")
.open(&mut self.metadata_window_open.clone())
.resizable(true)
.default_size([400.0, 300.0])
.show(ctx, |ui| {
let experiments = model.list_of_experiments();
egui::ComboBox::from_label("Select Experiment")
.selected_text(self.selected_experiment.as_deref().unwrap_or("None"))
.show_ui(ui, |ui| {
for exp_id in &experiments {
ui.selectable_value(
&mut self.selected_experiment,
Some(exp_id.clone()),
exp_id,
);
}
});
ui.separator();
let comment_label = ui.label("Comment:").on_hover_text(
"Optional experiment note. Leave blank to keep the current comment.",
);
ui.text_edit_multiline(&mut self.comment_input)
.labelled_by(comment_label.id);
let rate_label = ui.label("Heating Rate (K/min):").on_hover_text(
"Optional numeric metadata in K/min; leave blank to keep the current value.",
);
ui.text_edit_singleline(&mut self.heating_rate_input)
.labelled_by(rate_label.id);
let temperature_label = ui.label("Temperature (K):").on_hover_text(
"Optional numeric metadata in K; leave blank to keep the current value.",
);
ui.text_edit_singleline(&mut self.temperature_input)
.labelled_by(temperature_label.id);
ui.separator();
if ui
.button("Apply")
.on_hover_text(
"Saves experiment metadata only; no data columns are created or changed.",
)
.clicked()
{
if let Some(exp_id) = self.selected_experiment.clone() {
match apply_metadata_draft(
&mut model.series,
&exp_id,
&self.comment_input,
&self.heating_rate_input,
&self.temperature_input,
) {
Ok(()) => {
self.set_message(
MessageKind::Success,
"Metadata updated successfully",
);
self.metadata_window_open = false;
}
Err(error) => self.set_message(
MessageKind::Error,
format!("Metadata update failed: {error}"),
),
}
} else {
self.set_message(MessageKind::Error, "Select an experiment first");
}
}
});
}
}
fn parse_optional_finite_positive(input: &str, label: &str) -> Result<Option<f64>, String> {
if input.trim().is_empty() {
return Ok(None);
}
let value = input
.trim()
.parse::<f64>()
.map_err(|_| format!("{label} must be a number"))?;
if !value.is_finite() || value <= 0.0 {
return Err(format!("{label} must be finite and greater than zero"));
}
Ok(Some(value))
}
fn apply_metadata_draft(
series: &mut TGASeries,
experiment_id: &str,
comment: &str,
heating_rate_input: &str,
temperature_input: &str,
) -> Result<(), String> {
let heating_rate = parse_optional_finite_positive(heating_rate_input, "Heating rate")?;
let temperature = parse_optional_finite_positive(temperature_input, "Temperature")?;
if heating_rate.is_some() && temperature.is_some() {
return Err("Set either heating rate or isothermal temperature, not both".to_string());
}
series
.try_mutate_by_id(experiment_id, |experiment| {
if !comment.trim().is_empty() {
experiment.meta.comment = Some(comment.trim().to_string());
}
if let Some(rate) = heating_rate {
experiment.meta.heating_rate = Some(rate);
experiment.meta.thermal_mode = ExperimentThermalMode::NonIsothermal;
experiment.meta.isothermal_temperature = None;
}
if let Some(temperature) = temperature {
experiment.meta.isothermal_temperature = Some(temperature);
experiment.meta.thermal_mode = ExperimentThermalMode::Isothermal;
experiment.meta.heating_rate = None;
}
Ok(())
})
.map_err(|error| error.to_string())
}
#[cfg(test)]
mod metadata_input_tests {
use super::{apply_metadata_draft, parse_optional_finite_positive};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
ExperimentMeta, ExperimentThermalMode, TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA;
use crate::gui::experimental_kinetics_gui::model::PlotModel;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
struct MetadataUiState {
model: PlotModel,
manager: super::ColumnManagerState,
}
fn series_with_metadata() -> TGASeries {
let mut series = TGASeries::new();
let data = VirtualTGA {
time: vec![0.0, 1.0, 2.0],
temperature: vec![500.0; 3],
mass: vec![10.0, 9.0, 8.0],
};
let dataset = crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset::create_from_synthetic_data(&data).unwrap();
series
.push(TGAExperiment::new(dataset).with_id("meta"))
.unwrap();
series
.try_mutate_by_id("meta", |experiment| {
experiment.meta = ExperimentMeta {
identity: experiment.meta.identity.clone(),
id: "meta".into(),
heating_rate: Some(4.0),
isothermal_temperature: None,
thermal_mode: ExperimentThermalMode::NonIsothermal,
comment: Some("keep me".into()),
};
Ok(())
})
.unwrap();
series
}
#[test]
fn metadata_numeric_inputs_reject_invalid_values_before_commit() {
assert_eq!(
parse_optional_finite_positive("", "Temperature").unwrap(),
None
);
assert_eq!(
parse_optional_finite_positive("523.15", "Temperature").unwrap(),
Some(523.15)
);
for input in ["abc", "NaN", "inf", "0", "-2"] {
assert!(
parse_optional_finite_positive(input, "Temperature").is_err(),
"accepted {input}"
);
}
}
#[test]
fn invalid_metadata_draft_preserves_all_existing_fields() {
let mut series = series_with_metadata();
let before = series.get_experiment_by_id("meta").unwrap().meta.clone();
let error = apply_metadata_draft(&mut series, "meta", "changed", "5", "NaN").unwrap_err();
assert!(error.contains("finite and greater than zero"));
let after = &series.get_experiment_by_id("meta").unwrap().meta;
assert_eq!(after.id, before.id);
assert_eq!(after.heating_rate, before.heating_rate);
assert_eq!(after.isothermal_temperature, before.isothermal_temperature);
assert_eq!(after.thermal_mode, before.thermal_mode);
assert_eq!(after.comment, before.comment);
}
#[test]
fn valid_metadata_draft_commits_mode_and_comment_together() {
let mut series = series_with_metadata();
apply_metadata_draft(&mut series, "meta", " updated ", "", "523.15").unwrap();
let meta = &series.get_experiment_by_id("meta").unwrap().meta;
assert_eq!(meta.comment.as_deref(), Some("updated"));
assert_eq!(meta.thermal_mode, ExperimentThermalMode::Isothermal);
assert_eq!(meta.isothermal_temperature, Some(523.15));
assert!(meta.heating_rate.is_none());
}
#[test]
fn egui_apply_with_invalid_metadata_keeps_the_original_record() {
let mut model = PlotModel::default();
model.series = series_with_metadata();
let mut manager = super::ColumnManagerState::new();
manager.metadata_window_open = true;
manager.selected_experiment = Some("meta".into());
manager.comment_input = "must not partially apply".into();
manager.heating_rate_input = "5".into();
manager.temperature_input = "NaN".into();
let before = model
.series
.get_experiment_by_id("meta")
.unwrap()
.meta
.clone();
let mut harness = Harness::new_ui_state(
|ui, state: &mut MetadataUiState| {
state
.manager
.show_metadata_window(ui.ctx(), &mut state.model);
},
MetadataUiState { model, manager },
);
harness.get_by_label("Apply").click();
harness.run();
let state = harness.state();
let after = &state
.model
.series
.get_experiment_by_id("meta")
.unwrap()
.meta;
assert_eq!(after.comment, before.comment);
assert_eq!(after.heating_rate, before.heating_rate);
assert_eq!(after.isothermal_temperature, before.isothermal_temperature);
assert_eq!(after.thermal_mode, before.thermal_mode);
assert!(
state
.manager
.system_message
.as_ref()
.unwrap()
.text
.contains("Metadata update failed")
);
}
#[test]
fn egui_apply_commits_valid_metadata_and_comment_together() {
let mut model = PlotModel::default();
model.series = series_with_metadata();
let mut manager = super::ColumnManagerState::new();
manager.metadata_window_open = true;
manager.selected_experiment = Some("meta".into());
manager.comment_input = "updated from GUI".into();
manager.temperature_input = "523.15".into();
let mut harness = Harness::new_ui_state(
|ui, state: &mut MetadataUiState| {
state
.manager
.show_metadata_window(ui.ctx(), &mut state.model);
},
MetadataUiState { model, manager },
);
harness.get_by_label("Apply").click();
harness.run();
let state = harness.state();
let meta = &state
.model
.series
.get_experiment_by_id("meta")
.unwrap()
.meta;
assert_eq!(meta.comment.as_deref(), Some("updated from GUI"));
assert_eq!(meta.thermal_mode, ExperimentThermalMode::Isothermal);
assert_eq!(meta.isothermal_temperature, Some(523.15));
assert!(meta.heating_rate.is_none());
assert!(
state
.manager
.system_message
.as_ref()
.unwrap()
.text
.contains("Metadata updated successfully")
);
}
}
#[cfg(test)]
mod stale_search_revision_tests {
use super::{
ColumnManagerState, PendingCellReplacement, PendingRowDeletion, VersionedNumericRowMatch,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::ExperimentMeta;
use crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA;
use crate::gui::experimental_kinetics_gui::model::PlotModel;
fn model_with_experiment() -> PlotModel {
let mut model = PlotModel::new();
let data = VirtualTGA {
time: vec![0.0, 1.0, 2.0, 3.0],
temperature: vec![500.0, 501.0, 502.0, 503.0],
mass: vec![10.0, 9.0, 8.0, 7.0],
};
model
.series
.create_from_synthetic_data(
&data,
ExperimentMeta {
id: "revision_guard".into(),
..ExperimentMeta::default()
},
)
.unwrap();
model
}
fn mutate_undo_mutate(model: &mut PlotModel) {
model
.series
.replace_numeric_cell_at_row("revision_guard", "mass", 1, 9.0, 8.5)
.unwrap();
model.series.undo_last("revision_guard").unwrap();
model
.series
.replace_numeric_cell_at_row("revision_guard", "mass", 2, 8.0, 7.5)
.unwrap();
}
#[test]
fn stale_found_row_is_rejected_after_undo_and_a_new_mutation() {
let mut model = model_with_experiment();
let old_revision = model.series.data_revision();
let mut manager = ColumnManagerState::default();
manager.table_experiment = Some("revision_guard".into());
manager.selected_column = Some(("revision_guard".into(), "mass".into()));
manager.search_result = Some(VersionedNumericRowMatch {
row_index: 1,
value: 9.0,
data_revision: old_revision,
});
mutate_undo_mutate(&mut model);
let height_before = model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height();
manager.prepare_delete_found_row(&model);
assert!(manager.confirm_drop_row.is_none());
assert!(manager.search_result.is_none());
assert!(
manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("Data changed after the search"))
);
assert_eq!(
model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height(),
height_before
);
}
#[test]
fn pending_row_delete_and_preview_cache_are_invalidated_by_data_revision() {
let mut model = model_with_experiment();
let before = ColumnManagerState::preview_signature(&model, "revision_guard").unwrap();
let mut manager = ColumnManagerState::default();
manager.confirm_drop_row = Some(PendingRowDeletion {
experiment_id: "revision_guard".into(),
row_index: 1,
match_column: "mass".into(),
match_value: 9.0,
data_revision: model.series.data_revision(),
});
mutate_undo_mutate(&mut model);
let after = ColumnManagerState::preview_signature(&model, "revision_guard").unwrap();
let height_before = model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height();
manager.commit_delete_found_row(&mut model);
assert_ne!(before.data_revision, after.data_revision);
assert!(manager.confirm_drop_row.is_none());
assert!(manager.search_result.is_none());
assert_eq!(
model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height(),
height_before,
"a confirmation captured before a data change must not delete a row"
);
}
#[test]
fn row_delete_rechecks_the_matched_cell_before_mutating() {
let mut model = model_with_experiment();
let height_before = model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height();
let mut manager = ColumnManagerState::default();
manager.confirm_drop_row = Some(PendingRowDeletion {
experiment_id: "revision_guard".into(),
row_index: 1,
match_column: "mass".into(),
match_value: 123.0,
data_revision: model.series.data_revision(),
});
manager.commit_delete_found_row(&mut model);
assert!(manager.confirm_drop_row.is_none());
assert!(manager.search_result.is_none());
assert!(
manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("no longer matches"))
);
assert_eq!(
model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.frame
.clone()
.collect()
.unwrap()
.height(),
height_before
);
}
#[test]
fn stale_cell_replacement_confirmation_is_rejected_after_data_revision_changes() {
let mut model = model_with_experiment();
let captured_revision = model.series.data_revision();
let mut manager = ColumnManagerState::default();
manager.confirm_replace_cell = Some(PendingCellReplacement {
experiment_id: "revision_guard".into(),
row_index: 1,
column: "mass".into(),
expected_value: 9.0,
replacement_value: "99.0".into(),
data_revision: captured_revision,
});
mutate_undo_mutate(&mut model);
manager.commit_replace_found_value(&mut model);
assert!(manager.confirm_replace_cell.is_none());
let data = model
.series
.get_experiment_by_id("revision_guard")
.unwrap()
.dataset
.column_as_array1("mass")
.unwrap();
assert_eq!(data[1], 9.0);
assert_eq!(data[2], 7.5);
assert!(
manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("Data changed while confirmation"))
);
}
}
#[cfg(test)]
mod formula_column_gui_tests {
use super::ColumnManagerState;
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{
ColumnNature, TGADataset, Unit,
};
use crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA;
use crate::gui::experimental_kinetics_gui::controller_methods::KineticMethodsWindowState;
use crate::gui::experimental_kinetics_gui::model::PlotModel;
use egui_kittest::{Harness, kittest::Queryable};
struct FormulaUiState {
model: PlotModel,
manager: ColumnManagerState,
methods: KineticMethodsWindowState,
open: bool,
}
fn formula_ui_state(expression: &str) -> FormulaUiState {
let mut series = TGASeries::new();
let dataset = TGADataset::create_from_synthetic_data(&VirtualTGA {
time: vec![0.0, 1.0, 2.0],
temperature: vec![500.0, 501.0, 502.0],
mass: vec![10.0, 9.0, 8.0],
})
.unwrap();
series
.push(TGAExperiment::new(dataset).with_id("formula_ui"))
.unwrap();
let mut model = PlotModel::new();
model.series = series;
let mut manager = ColumnManagerState::default();
manager.formula_window_open = true;
manager.formula_experiment = Some("formula_ui".into());
manager.formula_x_column = Some("time".into());
manager.formula_variable_bindings = vec![super::FormulaVariableBinding {
name: "x".into(),
column: Some("time".into()),
}];
manager.formula_output_name = "formula_value".into();
manager.formula_expression = expression.into();
manager.formula_output_unit = Some(Unit::Dimensionless);
manager.formula_output_nature = Some(ColumnNature::Unknown);
FormulaUiState {
model,
manager,
methods: KineticMethodsWindowState::default(),
open: true,
}
}
#[test]
fn formula_window_adds_a_column_and_reports_success() {
let mut harness = Harness::new_ui_state(
|ui, state: &mut FormulaUiState| {
super::show_column_manager_window(
ui.ctx(),
&mut state.model,
&mut state.manager,
&mut state.methods,
&mut state.open,
);
},
formula_ui_state("x^2 + 1"),
);
harness.get_by_label("Create formula column").click();
harness.run();
replace_text(&mut harness, "New column name", "formula_result");
harness.get_by_label("Create column").click();
harness.run();
let state = harness.state();
let dataset = &state
.model
.series
.get_experiment_by_id("formula_ui")
.unwrap()
.dataset;
let values = dataset.column_as_array1("formula_result").unwrap();
assert_eq!(values.as_slice().unwrap(), &[0.0, 1.0, 2.0]);
assert_eq!(dataset.schema.mass.as_deref(), Some("mass"));
assert!(
state
.manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("Created formula column"))
);
assert!(!state.manager.formula_window_open);
}
#[test]
fn formula_window_reports_non_finite_result_and_keeps_data_unchanged() {
let mut harness = Harness::new_ui_state(
|ui, state: &mut FormulaUiState| {
state
.manager
.show_formula_window(ui.ctx(), &mut state.model);
},
formula_ui_state("1/x"),
);
harness.get_by_label("Create column").click();
harness.run();
let state = harness.state();
let dataset = &state
.model
.series
.get_experiment_by_id("formula_ui")
.unwrap()
.dataset;
assert!(!dataset.schema.columns.contains_key("formula_value"));
assert!(state.manager.formula_window_open);
assert!(
state
.manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("non-finite value"))
);
}
fn replace_text(harness: &mut Harness<FormulaUiState>, 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();
}
#[test]
fn multiple_column_formula_ui_binds_variables_and_creates_result() {
let mut harness = Harness::new_ui_state(
|ui, state: &mut FormulaUiState| {
state
.manager
.show_formula_window(ui.ctx(), &mut state.model);
},
formula_ui_state("x + m"),
);
harness.get_by_label("Multiple source columns").click();
harness.run();
harness.get_by_label("Add variable").click();
harness.run();
replace_text(&mut harness, "Variable name 2", "m");
harness.get_by_label("Source column 2").click();
harness.run();
harness.get_by_label("mass").click();
harness.run();
replace_text(&mut harness, "Formula", "2*x + m");
replace_text(&mut harness, "New column name", "combined_signal");
harness.get_by_label(
"Action preview: add 'combined_signal' to 'formula_ui' from [x = time, m = mass].",
);
harness.get_by_label("Create column").click();
harness.run();
let state = harness.state();
let dataset = &state
.model
.series
.get_experiment_by_id("formula_ui")
.unwrap()
.dataset;
assert_eq!(
dataset
.column_as_array1("combined_signal")
.unwrap()
.as_slice()
.unwrap(),
&[10.0, 11.0, 12.0]
);
assert!(
dataset
.column_provenance_text("combined_signal")
.unwrap()
.contains("x=time, m=mass")
);
assert!(
state
.manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("Created formula column"))
);
}
#[test]
fn multiple_column_formula_ui_reports_unbound_variable_without_mutation() {
let mut harness = Harness::new_ui_state(
|ui, state: &mut FormulaUiState| {
state
.manager
.show_formula_window(ui.ctx(), &mut state.model);
},
formula_ui_state("x + m"),
);
let state = harness.state_mut();
state.manager.formula_multiple_inputs = true;
state.manager.formula_variable_bindings = vec![
super::FormulaVariableBinding {
name: "x".into(),
column: Some("time".into()),
},
super::FormulaVariableBinding {
name: "m".into(),
column: Some("mass".into()),
},
];
harness.run();
replace_text(&mut harness, "Formula", "x + temperature");
harness.get_by_label("Create column").click();
harness.run();
let state = harness.state();
let dataset = &state
.model
.series
.get_experiment_by_id("formula_ui")
.unwrap()
.dataset;
assert!(!dataset.schema.columns.contains_key("formula_value"));
assert!(state.manager.formula_window_open);
assert!(
state
.manager
.system_message
.as_ref()
.is_some_and(|message| message.text.contains("do not match declared bindings"))
);
}
}
#[cfg(test)]
mod schema_role_tests {
use super::schema_role_bindings;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGASchema;
#[test]
fn overview_role_mapping_uses_alpha_eta_contract_and_includes_rates() {
let mut schema = TGASchema::default();
schema.alpha = Some("alpha_col".into());
schema.eta = Some("eta_col".into());
schema.dm_dt = Some("mass_rate_col".into());
schema.deta_dt = Some("conversion_rate_col".into());
schema.dalpha_dt = Some("relative_mass_rate_col".into());
schema.dT_dt = Some("temperature_rate_col".into());
let roles = schema_role_bindings(&schema);
let role_for = |column| {
roles
.iter()
.find_map(|(role, bound)| (*bound == Some(column)).then_some(*role))
.unwrap()
};
assert_eq!(role_for("alpha_col"), "relative mass (alpha)");
assert_eq!(role_for("eta_col"), "conversion (eta)");
assert_eq!(role_for("mass_rate_col"), "mass rate");
assert_eq!(role_for("conversion_rate_col"), "conversion rate");
assert_eq!(role_for("relative_mass_rate_col"), "relative-mass rate");
assert_eq!(role_for("temperature_rate_col"), "temperature rate");
}
}
pub fn show_column_manager_window(
ctx: &egui::Context,
model: &mut PlotModel,
state: &mut ColumnManagerState,
methods_state: &mut KineticMethodsWindowState,
open: &mut bool,
) -> bool {
state.show_metadata_window(ctx, model);
let mut clear_workspace = false;
let viewport = ctx.content_rect();
let default_width = (viewport.width() * 0.94).max(640.0).min(viewport.width());
let default_height = (viewport.height() * 0.92).max(440.0).min(viewport.height());
let default_size = egui::vec2(default_width, default_height);
let default_position = egui::pos2(
viewport.center().x - default_size.x * 0.5,
viewport.center().y - default_size.y * 0.5,
);
egui::Window::new("Column Manager")
.open(open)
.resizable(true)
.default_size(default_size)
.min_size([viewport.width().min(640.0), viewport.height().min(440.0)])
.default_pos(default_position)
.constrain_to(viewport)
.show(ctx, |ui| {
let mut commit_reconstruction = false;
let mut discard_reconstruction = false;
let mut confirm_columns = false;
let mut cancel_columns = false;
let mut confirm_row_delete = false;
let mut cancel_row_delete = false;
let mut confirm_cell_replace = false;
let mut cancel_cell_replace = false;
if let Err(e) = state.update_cache(model) {
let text = format!("Could not refresh column samples: {e}");
state.set_message_if_changed(MessageKind::Error, text.clone());
ui.colored_label(egui::Color32::LIGHT_RED, text);
return;
}
if let Some(batch) = methods_state.fit_pending_batch.as_ref() {
ui.separator();
ui.heading("Fit reconstruction preview");
ui.label(format!(
"Source: {} | X: {} | {} rows | {} fitted column(s) | {:?}",
batch.source_experiment_id,
batch.x_col,
batch.x_values.len(),
batch.columns.len(),
batch.mode,
));
for column in &batch.columns {
let coefficients = column.fit.coefficients.iter()
.map(|(name, value)| format!("{name}={value:.5e}"))
.collect::<Vec<_>>().join(", ");
ui.label(format!(
"{}: R2={:.6}, model={}, Y={}, parameters: {}",
column.name,
column.fit.r2,
column.fit.model_name.clone(),
column.fit.y_col,
coefficients,
));
}
ui.horizontal(|ui| {
let label = ui.label("New experiment ID:");
let input = ui.text_edit_singleline(&mut methods_state.fit_reconstructed_experiment_id);
let _ = input.labelled_by(label.id);
if ui.button("Add reconstructed experiment")
.on_hover_text("Creates a separate complete experiment and plots its fitted columns. The source experiment is not modified.")
.clicked()
{
commit_reconstruction = true;
}
if ui.button("Discard preview")
.on_hover_text("Discard only the evaluated reconstruction preview. Stored fitted models and their fit results remain available.")
.clicked() {
discard_reconstruction = true;
}
});
egui::CollapsingHeader::new("Sample values")
.default_open(true)
.show(ui, |ui| {
let (start, end) = match batch.mode {
crate::Kinetics::experimental_kinetics::math::fitting::FitEvaluationMode::Extrapolate { start, end, .. }
| crate::Kinetics::experimental_kinetics::math::fitting::FitEvaluationMode::FillGap { start, end, .. } => (start, end),
};
let preview_indices = batch.x_values.iter().enumerate()
.filter(|(_, x)| **x >= start && **x <= end)
.map(|(index, _)| index)
.take(8)
.collect::<Vec<_>>();
egui::ScrollArea::both().max_height(140.0).show(ui, |ui| {
egui::Grid::new("fit_reconstruction_preview_values")
.striped(true)
.show(ui, |ui| {
ui.strong(&batch.x_col);
for column in &batch.columns { ui.strong(&column.name); }
ui.end_row();
for index in &preview_indices {
ui.label(format!("{:.6}", batch.x_values[*index]));
for column in &batch.columns {
ui.label(format!("{:.6}", column.values[*index]));
}
ui.end_row();
}
});
});
});
}
if commit_reconstruction {
if let Some(batch) = methods_state.fit_pending_batch.as_ref() {
let id = methods_state.fit_reconstructed_experiment_id.trim().to_string();
match model.push_fitted_evaluation_batch_and_plot(batch, id) {
Ok(()) => {
methods_state.fit_pending_batch = None;
methods_state.fit_sessions.clear();
state.set_message(MessageKind::Success, "Reconstructed experiment added; source data unchanged");
}
Err(crate::gui::experimental_kinetics_gui::model::TGAGUIError::PostCommitWarning(warning)) => {
methods_state.fit_pending_batch = None;
methods_state.fit_sessions.clear();
state.set_message(MessageKind::Warning, warning);
}
Err(error) => state.set_message(MessageKind::Error, format!("Reconstruction was not added: {error:?}")),
}
}
}
if discard_reconstruction {
methods_state.fit_pending_batch = None;
}
if !state.confirm_drop_columns.is_empty() {
egui::Window::new("Confirm Drop Columns")
.collapsible(false)
.resizable(true)
.show(ctx, |ui| {
ui.label(format!("Delete {} column(s) from {}?", state.confirm_drop_columns.len(), display_experiment_id(&state.confirm_drop_columns[0].0)));
ui.colored_label(
egui::Color32::YELLOW,
"Review dependencies before confirming. Plots using deleted columns will be removed; schema and active-source bindings will be cleared. Derived columns are not deleted automatically.",
);
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
for (experiment_id, name) in &state.confirm_drop_columns {
ui.separator();
ui.strong(name);
match column_deletion_impact(model, experiment_id, name) {
Ok(impact) if impact.has_references() => {
if !impact.schema_roles.is_empty() {
ui.colored_label(
egui::Color32::LIGHT_RED,
format!("Schema binding: {}", impact.schema_roles.join(", ")),
);
}
if !impact.plot_references.is_empty() {
ui.colored_label(
egui::Color32::YELLOW,
format!("Used by plots: {}", impact.plot_references.join(", ")),
);
}
if !impact.active_sources.is_empty() {
ui.colored_label(
egui::Color32::LIGHT_RED,
format!("Active calculation source: {}", impact.active_sources.join(", ")),
);
}
if !impact.derived_descendants.is_empty() {
ui.label(format!(
"Derived descendants retained: {}",
impact.derived_descendants.join(", ")
));
}
}
Ok(_) => {
ui.weak("No current schema, plot, active-source, or provenance references.");
}
Err(error) => {
ui.colored_label(
egui::Color32::LIGHT_RED,
format!("Could not inspect dependencies: {error}"),
);
}
};
}
});
ui.label("The deletion is undoable from the action bar.");
ui.horizontal(|ui| {
if ui.button("Delete columns")
.on_hover_text("Deletes only the listed columns. Referencing plots and bindings are removed; derived descendants remain. Undo is available.")
.clicked() { confirm_columns = true; }
if ui.button("Cancel").on_hover_text("Close this confirmation without changing data.").clicked() { cancel_columns = true; }
});
});
}
if let Some(pending) = state.confirm_drop_row.as_ref() {
egui::Window::new("Confirm Delete Source Row")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.heading("Delete the complete data row?");
ui.label(format!(
"Experiment: {}",
display_experiment_id(&pending.experiment_id)
));
ui.label(format!(
"Source row {} (display row {})",
pending.row_index,
pending.row_index + 1
));
ui.label(format!(
"Found by {} = {}",
pending.match_column,
format_sample_value(pending.match_value)
));
ui.colored_label(
egui::Color32::YELLOW,
"This removes that row from every column in the experiment. Undo is available from the action bar.",
);
ui.horizontal(|ui| {
if ui
.button("Delete entire row")
.on_hover_text("Commits a history-tracked, undoable deletion of this row across all columns.")
.clicked()
{
confirm_row_delete = true;
}
if ui.button("Cancel").clicked() {
cancel_row_delete = true;
}
});
});
}
if let Some(pending) = state.confirm_replace_cell.as_mut() {
egui::Window::new("Confirm Replace Cell Value")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.heading("Replace one numeric cell?");
ui.label(format!(
"Experiment: {}",
display_experiment_id(&pending.experiment_id)
));
ui.label(format!(
"{} at source row {} (display row {}) currently equals {}",
pending.column,
pending.row_index,
pending.row_index + 1,
format_sample_value(pending.expected_value)
));
let value_label = ui.label("New value");
let value_edit = ui.add(
egui::TextEdit::singleline(&mut pending.replacement_value)
.desired_width(160.0),
);
value_edit.labelled_by(value_label.id);
let replacement = pending
.replacement_value
.trim()
.parse::<f64>()
.ok()
.filter(|value| value.is_finite());
let can_replace = replacement.is_some_and(|value| {
value.to_bits() != pending.expected_value.to_bits()
});
ui.colored_label(
egui::Color32::YELLOW,
"Only this cell changes. The operation is recorded and can be undone.",
);
ui.horizontal(|ui| {
if ui
.add_enabled(can_replace, egui::Button::new("Replace cell"))
.on_hover_text("Writes the finite numeric value into this cell only.")
.on_disabled_hover_text("Enter a finite numeric value before replacing the selected cell.")
.clicked()
{
confirm_cell_replace = true;
}
if ui.button("Cancel").clicked() {
cancel_cell_replace = true;
}
});
});
}
if state.confirm_delete_all {
egui::Window::new("Confirm Delete All Workspace")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.heading(
egui::RichText::new("DELETE ALL WORKSPACE DATA?")
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_RED),
);
ui.label(format!(
"This will permanently remove {} experiment(s) and {} plotted curve(s).",
model.list_of_experiments().len(),
model.plots.len(),
));
ui.label("This action cannot be undone.");
ui.horizontal(|ui| {
if ui
.add_sized(
[230.0, 48.0],
egui::Button::new(
egui::RichText::new("DELETE EVERYTHING")
.strong()
.color(egui::Color32::WHITE),
)
.fill(egui::Color32::DARK_RED),
)
.clicked()
{
clear_workspace = true;
}
if ui.button("Cancel").clicked() {
state.confirm_delete_all = false;
}
});
});
}
if confirm_columns {
state.commit_drop_columns(model);
}
if cancel_columns {
state.confirm_drop_columns.clear();
}
if confirm_row_delete {
state.commit_delete_found_row(model);
}
if cancel_row_delete {
state.confirm_drop_row = None;
}
if confirm_cell_replace {
state.commit_replace_found_value(model);
}
if cancel_cell_replace {
state.confirm_replace_cell = None;
}
if let Some(exp_id) = state.confirm_drop_experiment.clone() {
let mut confirmed = false;
let mut cancelled = false;
egui::Window::new("Confirm Drop Experiment")
.collapsible(false)
.resizable(false)
.show(ctx, |ui| {
ui.label(format!("Delete experiment {} and its plots?", display_experiment_id(&exp_id)));
ui.horizontal(|ui| {
if ui.button("Yes").on_hover_text("Deletes this experiment and all its plots.").clicked() {
confirmed = true;
}
if ui.button("No").on_hover_text("Keep the experiment unchanged.").clicked() {
cancelled = true;
}
});
});
if confirmed {
if let Err(e) = model.drop_experiment_by_id(&exp_id) {
state.set_message(MessageKind::Error, format!("Could not drop experiment: {e:?}"));
} else {
state.set_message(MessageKind::Success, format!("Experiment {} dropped successfully", exp_id));
state.cached_samples.remove(&exp_id);
state.sample_signatures.remove(&exp_id);
if state
.current_page
.as_ref()
.is_some_and(|page| page.experiment_id == exp_id)
{
state.current_page = None;
}
state.column_checkboxes.retain(|(eid, _), _| eid != &exp_id);
if state
.selected_column
.as_ref()
.map(|(selected_exp, _)| selected_exp == &exp_id)
.unwrap_or(false)
{
state.selected_column = None;
}
}
state.confirm_drop_experiment = None;
}
if cancelled {
state.confirm_drop_experiment = None;
}
}
state.render_controls(ui, model);
state.render_search_controls(ui, model);
state.render_page_controls(ui);
let max_samples_height = (ui.available_height() - 180.0).max(120.0);
egui::Resize::default()
.id_salt("column_manager_samples_resize")
.default_height((max_samples_height * 0.82).min(max_samples_height))
.min_size(egui::vec2(300.0, 110.0))
.max_height(max_samples_height)
.resizable(egui::Vec2b::new(false, true))
.show(ui, |ui| state.render_table(ui, model));
state.render_selected_column_details(ui, model);
});
state.show_formula_window(ctx, model);
if clear_workspace {
model.clear_workspace();
model.message = "Workspace cleared. All experiments and plots were removed.".to_string();
*state = ColumnManagerState::default();
*methods_state = KineticMethodsWindowState::default();
*open = false;
return true;
}
state.publish_message_to_main_status(model);
false
}