use crate::Kinetics::experimental_kinetics::exp_engine_api::GoldenPipelineConfig;
use crate::Kinetics::experimental_kinetics::exp_engine_api::{PlotSeries, Ranges, ViewRange, XY};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
CalibrationSnapshot, ExperimentMeta, TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::experiment_series2::SampledColumns;
use crate::Kinetics::experimental_kinetics::kinetic_methods::KineticDataView;
use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion::IsoconversionalResult;
use crate::Kinetics::experimental_kinetics::kinetic_methods::isoconversion::IsoconversionalMethod;
use crate::Kinetics::experimental_kinetics::math::exp_kinetics_smooth_filter::HampelStrategy;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{
ColumnDataQualityReport, ColumnHistory, ColumnNature, NumericRowMatch, OperationRecord,
PreviewRows, RowSearchDirection, TGADomainError, TimeMonotonicityReport, Unit,
};
use RustedSciThe::numerical::data_processing::LSQSplines::SolverKind;
use RustedSciThe::numerical::data_processing::lowess_wrapper::LowessConfig;
use crate::Kinetics::experimental_kinetics::testing_mod::{AdvancedTGAConfig, VirtualTGA};
use crate::gui::experimental_kinetics_gui::model::{Colours, PlotCurve, PlotModel, TGAGUIError};
use RustedSciThe::numerical::data_processing::splines::SplineKind;
use log::{debug, info};
use std::collections::{HashMap, HashSet};
use std::path::Path;
mod model_handler_results;
fn fresh_column_name(existing: &[String], base: &str) -> String {
if !existing.iter().any(|name| name == base) {
return base.to_string();
}
for suffix in 2_u64.. {
let candidate = format!("{base}_{suffix}");
if !existing.iter().any(|name| name == &candidate) {
return candidate;
}
}
unreachable!("u64 column-name suffix space exhausted")
}
fn resolve_new_column_name(
existing: &[String],
requested: Option<&str>,
base: &str,
) -> Result<String, TGAGUIError> {
if let Some(requested) = requested.map(str::trim).filter(|name| !name.is_empty()) {
if existing.iter().any(|name| name == requested) {
return Err(TGAGUIError::BindingError(format!(
"Resampling output '{requested}' already exists; choose a new column name"
)));
}
Ok(requested.to_string())
} else {
Ok(fresh_column_name(existing, base))
}
}
fn ensure_distinct_new_names(names: &[String]) -> Result<(), TGAGUIError> {
let unique = names.iter().collect::<HashSet<_>>();
if unique.len() != names.len() {
return Err(TGAGUIError::BindingError(
"Resampling output columns must have distinct names".into(),
));
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct SampledColumn {
pub col: Vec<f64>,
pub name: String,
}
pub struct PlotCurveBuilder {
curve: PlotCurve,
}
impl PlotCurveBuilder {
pub fn new_from_plot(
plot: PlotSeries,
id: &str,
index: usize,
ranges: Ranges,
short_name: String,
) -> Self {
let x_name = plot.name_x;
let y_name = plot.name_y;
let segment_starts = plot.segment_starts;
let points: Vec<[f64; 2]> = plot
.x
.into_iter()
.zip(plot.y)
.map(|(xi, yi)| [xi, yi])
.collect();
let mut curve = PlotCurve::default();
curve.experiment_id = id.to_string();
curve.experiment_index = index;
curve.plot_short_name = short_name;
curve.x_name = x_name;
curve.y_name = y_name;
curve.ranges = ranges;
curve.points = points;
curve.segment_starts = segment_starts;
Self { curve }
}
pub fn with_colour(mut self, colour: Colours) -> Self {
self.curve.set_colour(colour);
self
}
pub fn with_colour_rgb(mut self, rgb: [u8; 3]) -> Self {
self.curve.set_colour_rgb(rgb);
self
}
pub fn with_shown(mut self, shown: bool) -> Self {
self.curve.shown = shown;
self
}
pub fn with_selected(mut self, selected: bool) -> Self {
self.curve.selected = selected;
self
}
pub fn with_highlighted(mut self, highlighted: bool) -> Self {
self.curve.highlighted = highlighted;
self
}
pub fn finish(self) -> PlotCurve {
self.curve
}
}
impl PlotModel {
fn is_time_already_in_hours(&self, id: &str) -> Result<bool, TGAGUIError> {
Ok(self.experiment_column_unit(id, self.series.get_time_col(id)?)? == Unit::Hour)
}
fn is_temperature_already_kelvin(&self, id: &str) -> Result<bool, TGAGUIError> {
Ok(self.experiment_column_unit(id, self.series.get_temperature_col(id)?)? == Unit::Kelvin)
}
fn is_mass_already_milligram(&self, id: &str) -> Result<bool, TGAGUIError> {
Ok(self.experiment_column_unit(id, self.series.get_mass_col(id)?)? == Unit::Milligram)
}
fn experiment_column_unit(&self, id: &str, column: String) -> Result<Unit, TGAGUIError> {
let exp = self.series.get_experiment_by_id(id)?;
exp.dataset
.schema
.columns
.get(&column)
.map(|meta| meta.unit)
.ok_or_else(|| {
TGAGUIError::BindingError(format!(
"failed to read unit for column '{}' in experiment '{}'",
column, id
))
})
}
pub fn push_message(&mut self, message: &str) -> Result<(), TGAGUIError> {
self.message = message.to_string();
Ok(())
}
pub fn clear_message(&mut self) -> Result<(), TGAGUIError> {
self.message = String::new();
Ok(())
}
pub fn push_from_file(&mut self, path: &Path) -> Result<(), TGAGUIError> {
self.series.push_from_file(path)?;
Ok(())
}
pub fn push_from_file_with_meta(
&mut self,
path: &Path,
meta: ExperimentMeta,
) -> Result<(), TGAGUIError> {
self.series.push_from_file_with_meta(path, meta)?;
Ok(())
}
pub fn to_csv_series(&self, path: &Path) -> Result<(), TGAGUIError> {
let calibration = self
.settings
.calibration_line()
.map(|line| CalibrationSnapshot::new(line.k(), line.b()));
self.series
.to_csv_series_with_calibration(path, calibration)?;
Ok(())
}
pub fn to_csv_series_selected(
&self,
path: &Path,
experiment_ids: &[String],
columns_by_experiment: &HashMap<String, Vec<String>>,
) -> Result<(), TGAGUIError> {
let calibration = self
.settings
.calibration_line()
.map(|line| CalibrationSnapshot::new(line.k(), line.b()));
self.series.to_csv_series_selected_with_calibration(
path,
experiment_ids,
columns_by_experiment,
calibration,
)?;
Ok(())
}
pub fn to_plain_txt_experiment(
&self,
experiment_id: &str,
path: &Path,
columns: &[String],
) -> Result<(), TGAGUIError> {
self.series
.to_plain_txt_experiment(experiment_id, path, columns)?;
Ok(())
}
pub fn from_csv_series(&mut self, path: &Path) -> Result<(), TGAGUIError> {
self.series = TGASeries::from_csv_series(path)?;
Ok(())
}
pub fn prune_stale_plots(&mut self) -> bool {
let selected_plot = self
.get_selected_curve_index()
.and_then(|idx| self.plots.get(idx))
.map(|curve| curve.plot_short_name.clone());
let valid_columns_by_experiment: HashMap<String, HashSet<String>> = self
.list_of_experiments()
.into_iter()
.map(|experiment_id| {
let columns = self
.list_of_columns(&experiment_id)
.unwrap_or_default()
.into_iter()
.collect::<HashSet<_>>();
(experiment_id, columns)
})
.collect();
let experiment_indices: HashMap<String, usize> = self
.list_of_experiments()
.into_iter()
.enumerate()
.map(|(index, id)| (id, index))
.collect();
let original_len = self.plots.len();
let mut changed = false;
self.plots.retain_mut(|curve| {
let is_valid = valid_columns_by_experiment
.get(&curve.experiment_id)
.is_some_and(|columns| {
columns.contains(&curve.x_name) && columns.contains(&curve.y_name)
});
if !is_valid {
changed = true;
return false;
}
if let Some(&index) = experiment_indices.get(&curve.experiment_id) {
if curve.experiment_index != index {
curve.experiment_index = index;
changed = true;
}
}
true
});
changed |= self.plots.len() != original_len;
if !changed {
return false;
}
let selected_plot_removed = selected_plot
.as_ref()
.map(|short_name| {
!self
.plots
.iter()
.any(|curve| curve.plot_short_name == *short_name)
})
.unwrap_or(false);
if selected_plot_removed {
self.clear_selection();
self.clear_selection_rect();
}
self.reset_view();
true
}
pub fn drop_experiment(&mut self, indx: usize) -> Result<(), TGAGUIError> {
let id = self.series.ids().get(indx).cloned().ok_or_else(|| {
TGAGUIError::BindingError(format!("invalid experiment index {}", indx))
})?;
self.series.drop_experiment(indx)?;
self.clear_active_sources_for_experiment(&id);
self.prune_stale_plots();
Ok(())
}
pub fn drop_experiment_by_id(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.series.drop_experiment_by_id(id)?;
self.clear_active_sources_for_experiment(id);
self.prune_stale_plots();
Ok(())
}
pub fn list_of_experiments(&self) -> Vec<String> {
self.series.ids()
}
pub fn get_list_of_complex_id(&self) -> Vec<String> {
self.series.get_list_of_complex_id()
}
pub fn bind_time_of_experiment(
&mut self,
id: &str,
col: &str,
unit: Unit,
) -> Result<(), TGAGUIError> {
self.series.bind_time(id, col, unit)?;
Ok(())
}
pub fn bind_temperature_of_experiment(
&mut self,
id: &str,
col: &str,
unit: Unit,
) -> Result<(), TGAGUIError> {
self.series.bind_temperature(id, col, unit)?;
self.set_active_temperature_source_for_experiment(id, col);
Ok(())
}
pub fn bind_mass_of_experiment(
&mut self,
id: &str,
col: &str,
unit: Unit,
) -> Result<(), TGAGUIError> {
self.series.bind_mass(id, col, unit)?;
self.set_active_mass_source_for_experiment(id, col);
Ok(())
}
pub fn bind_time_of_selected(&mut self, col: &str, unit: Unit) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.bind_time_of_experiment(&id, col, unit)?;
Ok(())
}
pub fn bind_temperature_of_selected(
&mut self,
col: &str,
unit: Unit,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.bind_temperature_of_experiment(&id, col, unit)?;
Ok(())
}
pub fn bind_mass_of_selected(&mut self, col: &str, unit: Unit) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.bind_mass_of_experiment(&id, col, unit)?;
Ok(())
}
pub fn create_from_synthetic_data(
&mut self,
virtga: &VirtualTGA,
meta: ExperimentMeta,
) -> Result<(), TGAGUIError> {
self.series.create_from_synthetic_data(virtga, meta)?;
Ok(())
}
pub fn generate_synthetic_data_from_config(
&mut self,
config: &AdvancedTGAConfig,
) -> Result<(), TGAGUIError> {
self.series.create_series_from_synthetic_data(config)?;
Ok(())
}
pub fn compare_new_and_old_list_of_columns(
&self,
id: &str,
old_list: Vec<String>,
) -> Result<Vec<String>, TGAGUIError> {
info!("old list of columns: {:?}", old_list);
let new_list = self.list_of_columns(id)?;
let mut diff_list = Vec::new();
for col in new_list {
if !old_list.contains(&col) {
diff_list.push(col);
}
}
Ok(diff_list)
}
pub fn create_plots_with_columns(
&mut self,
id: &str,
new_list: Vec<String>,
preferred_x: Option<&str>,
) -> Result<(), TGAGUIError> {
let mut x_col = self.this_is_x()?;
if let Some(px) = preferred_x {
if new_list.iter().any(|c| c == px) {
x_col = px.to_string();
}
}
self.set_x(id, &x_col)?;
for col in new_list {
if col == x_col {
continue;
}
self.set_y(id, &col)?;
self.create_points_for_curve_with_builder(id, Colours::Red)?;
let short_name = self.create_plot_short_name(id, &x_col, &col);
let curve = self
.plots
.iter_mut()
.find(|curve| curve.plot_short_name == short_name)
.ok_or_else(|| {
TGAGUIError::BindingError(format!(
"created plot curve '{short_name}' could not be found"
))
})?;
curve.shown = true;
info!("created plot for column {}", col);
}
Ok(())
}
pub fn show_column_on_plot(
&mut self,
id: &str,
x_col: &str,
y_col: &str,
) -> Result<bool, TGAGUIError> {
if x_col == y_col {
return Err(TGAGUIError::BindingError(
"X and Y must be different columns".to_string(),
));
}
let short_name = self.create_plot_short_name(id, &x_col.to_string(), &y_col.to_string());
if let Some(index) = self
.plots
.iter()
.position(|curve| curve.plot_short_name == short_name)
{
if self.plots[index].shown {
return Ok(false);
}
self.set_curve_shown(index, true)?;
return Ok(true);
}
let experiment_index = self.index_by_id(id)?;
let experiment = self.series.get_experiment_by_id(id)?.clone();
let experiment = experiment
.set_oneframeplot_x(x_col)?
.set_oneframeplot_y(y_col)?;
let ranges = experiment.plot_xy_ranges()?;
let n_points = self
.settings
.n_points()
.filter(|count| *count > 0)
.ok_or_else(|| {
TGAGUIError::SettingsErrors(
"Plot sample count must be a positive integer.".to_string(),
)
})?;
let sampled = experiment.sample_oneframeplot(
Some(ViewRange {
t_min: ranges.x_min,
t_max: ranges.x_max,
}),
n_points,
)?;
self.push_to_vec_of_curves(sampled, id, experiment_index, ranges)?;
self.reset_view();
Ok(true)
}
pub fn create_plots_with_new_columns(
&mut self,
id: &str,
old_list: Vec<String>,
preferred_x: Option<&str>,
) -> Result<(), TGAGUIError> {
let new_list = self.compare_new_and_old_list_of_columns(id, old_list)?;
info!("new columns: {:?}", new_list);
let old_plot_names = self
.plots
.iter()
.filter(|plot| plot.experiment_id == id)
.map(|plot| plot.plot_short_name.clone())
.collect::<std::collections::HashSet<_>>();
let old_axes = self
.plots
.iter()
.find(|plot| plot.experiment_id == id)
.map(|plot| (plot.x_name.clone(), plot.y_name.clone()));
let old_view = (self.interaction.view_range, self.interaction.view_y_range);
if let Err(error) = self.create_plots_with_columns(id, new_list, preferred_x) {
self.plots.retain(|plot| {
plot.experiment_id != id || old_plot_names.contains(&plot.plot_short_name)
});
if let Some((x_col, y_col)) = old_axes {
let _ = self.set_x(id, &x_col);
let _ = self.set_y(id, &y_col);
}
self.interaction.view_range = old_view.0;
self.interaction.view_y_range = old_view.1;
return Err(TGAGUIError::post_commit_warning(format!(
"experiment '{id}' was updated; new columns remain available, but their curves could not be created ({error})"
)));
}
self.reset_view();
Ok(())
}
pub fn create_experiment_from_columns(
&mut self,
parent_idx: usize,
new_id: String,
columns: &[&str],
) -> Result<(), TGAGUIError> {
self.series
.create_experiment_from_columns(parent_idx, new_id, columns)?;
Ok(())
}
pub fn create_experiment_from_columns_for_experiment(
&mut self,
id: &str,
new_id: String,
columns: &[&str],
) -> Result<(), TGAGUIError> {
let idx = self.index_by_id(id)?;
self.create_experiment_from_columns(idx, new_id, columns)
}
pub fn push_experiment_and_create_plot(
&mut self,
experiment: TGAExperiment,
colour: Colours,
) -> Result<(), TGAGUIError> {
let id = experiment.meta.id.clone();
self.series.push(experiment)?;
let plot_result = (|| -> Result<(), TGAGUIError> {
self.series.set_oneframeplot_x(&id, "time")?;
self.series.set_oneframeplot_y(&id, "conversion")?;
self.create_points_for_curve_with_builder(&id, colour)?;
if let Some(index) = self
.plots
.iter()
.position(|curve| curve.experiment_id == id && curve.y_name == "conversion")
{
self.select_curve(index);
}
self.reset_view();
Ok(())
})();
if let Err(error) = plot_result {
self.plots.retain(|curve| curve.experiment_id != id);
self.reset_view();
return Err(TGAGUIError::post_commit_warning(format!(
"IVP experiment '{id}' was added to the series, but its plot could not be created; the data remain available ({error})"
)));
}
Ok(())
}
pub fn push_network_series_and_create_plots(
&mut self,
runs: Vec<(TGAExperiment, Vec<String>)>,
) -> Result<(), TGAGUIError> {
let mut ids: HashSet<String> = self.series.ids().into_iter().collect();
for (experiment, _) in &runs {
if !ids.insert(experiment.meta.id.clone()) {
return Err(TGAGUIError::BindingError(format!(
"Experiment '{}' already exists in the series",
experiment.meta.id
)));
}
}
let plot_specs: Vec<(String, Vec<String>)> = runs
.iter()
.map(|(experiment, columns)| (experiment.meta.id.clone(), columns.clone()))
.collect();
for (experiment, _) in runs {
self.series.push(experiment)?;
}
let palette = [
Colours::Blue,
Colours::Red,
Colours::Green,
Colours::Orange,
Colours::Purple,
Colours::Cyan,
Colours::Magenta,
Colours::Gray,
];
let mut plot_warnings = Vec::new();
for (id, y_columns) in plot_specs {
let result = (|| -> Result<(), TGAGUIError> {
self.series.set_oneframeplot_x(&id, "time")?;
for (index, y) in y_columns.iter().enumerate() {
self.series.set_oneframeplot_y(&id, y)?;
self.create_points_for_curve_with_builder(&id, palette[index % palette.len()])?;
}
Ok(())
})();
if let Err(error) = result {
self.plots.retain(|curve| curve.experiment_id != id);
plot_warnings.push(format!("{id}: {error}"));
}
}
self.reset_view();
if !plot_warnings.is_empty() {
return Err(TGAGUIError::post_commit_warning(format!(
"The simulated series was added, but some plots could not be created: {}",
plot_warnings.join("; ")
)));
}
Ok(())
}
pub fn apply_by_id<R, F>(&self, id: &str, op: F) -> Result<R, TGAGUIError>
where
F: FnOnce(&TGAExperiment) -> R,
{
let res = self.series.apply_by_id(id, op)?;
Ok(res)
}
pub fn try_apply_by_id<R, F>(&self, id: &str, op: F) -> Result<R, TGAGUIError>
where
F: FnOnce(&TGAExperiment) -> Result<R, TGADomainError>,
{
let res = self.series.try_apply_by_id(id, op)?;
Ok(res)
}
pub fn mutate_by_id<R, F>(&mut self, id: &str, op: F) -> Result<R, TGAGUIError>
where
F: FnOnce(&mut TGAExperiment) -> R,
{
let res = self.series.mutate_by_id(id, op)?;
Ok(res)
}
pub fn try_mutate_by_id<R, F>(&mut self, id: &str, op: F) -> Result<R, TGAGUIError>
where
F: FnOnce(&mut TGAExperiment) -> Result<R, TGADomainError>,
{
let res = self.series.try_mutate_by_id(id, op)?;
Ok(res)
}
pub fn transform_by_id<F>(&mut self, id: &str, op: F) -> Result<(), TGAGUIError>
where
F: FnOnce(TGAExperiment) -> TGAExperiment,
{
self.series.transform_by_id(id, op)?;
Ok(())
}
pub fn try_transform_by_id<F>(&mut self, id: &str, op: F) -> Result<(), TGAGUIError>
where
F: FnOnce(TGAExperiment) -> Result<TGAExperiment, TGADomainError>,
{
self.series.try_transform_by_id(id, op)?;
Ok(())
}
pub fn history_of_operation_for_selected(&self) -> Result<Vec<OperationRecord>, TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let h = self.series.history_of_operations(&id)?;
Ok(h)
}
pub fn history_feed_for_selected(&self) -> Result<String, TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let exp = self.series.get_experiment_by_id(&id)?;
Ok(exp.dataset.history_of_operations.feed_text())
}
pub fn history_feed_for_experiment(&self, id: &str) -> Result<String, TGAGUIError> {
let exp = self.series.get_experiment_by_id(id)?;
Ok(exp.dataset.history_of_operations.feed_text())
}
pub fn reverse_selected(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.series.undo_last(&id)?;
self.prune_stale_plots();
self.select_first_curve_for_experiment_if_needed(&id);
self.rebuild_plots_for_experiment(&id)?;
Ok(())
}
pub fn reverse_experiment(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.series.undo_last(id)?;
self.prune_stale_plots();
self.select_first_curve_for_experiment_if_needed(id);
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
fn select_first_curve_for_experiment_if_needed(&mut self, id: &str) {
if self.get_selected_curve_index().is_some() {
return;
}
if let Some(index) = self
.plots
.iter()
.position(|curve| curve.experiment_id == id && curve.shown)
{
self.select_curve(index);
}
}
pub fn operations_on_column_for_experiment(
&mut self,
id: &str,
col: &str,
) -> Result<Vec<OperationRecord>, TGAGUIError> {
let r = self.series.operations_on_column(id, col)?;
Ok(r)
}
pub fn get_column_history_for_experiment(
&mut self,
id: &str,
col: &str,
) -> Result<ColumnHistory, TGAGUIError> {
let r = self.series.get_column_history(id, col)?;
Ok(r)
}
pub fn column_history_feed_for_experiment(
&self,
id: &str,
col: &str,
) -> Result<String, TGAGUIError> {
Ok(self.series.get_column_history(id, col)?.feed_text())
}
pub fn column_provenance_for_experiment(
&self,
id: &str,
col: &str,
) -> Result<Option<String>, TGAGUIError> {
Ok(self.series.column_provenance_text(id, col)?)
}
pub fn take_column(&mut self, id: &str, col: &str) -> Result<Option<String>, TGAGUIError> {
let name = self.series.take_column(id, col)?;
Ok(name)
}
pub fn list_of_columns_to_recalc(&mut self, id: &str) -> Result<Vec<String>, TGAGUIError> {
let list_of_columns_to_recalc = self.series.list_of_columns_to_recalc(id)?;
Ok(list_of_columns_to_recalc)
}
pub fn list_of_columns_to_recalc_for_all_experiments(
&mut self,
) -> Result<HashMap<String, Vec<String>>, TGAGUIError> {
let mut map_of_columns_to_recalc = HashMap::new();
for id in self.list_of_experiments() {
let list_of_columns_to_recalc = self.list_of_columns_to_recalc(&id)?;
map_of_columns_to_recalc.insert(id, list_of_columns_to_recalc);
}
Ok(map_of_columns_to_recalc)
}
pub fn sample_column(
&self,
id: &str,
col_name: &str,
range: Option<(f64, f64)>,
n_points: usize,
) -> Result<Vec<f64>, TGAGUIError> {
let v = self.series.sample_column(id, col_name, range, n_points)?;
Ok(v)
}
pub fn column_samples_for_all_experiments(
&mut self,
n_points: usize,
) -> Result<HashMap<String, PreviewRows>, TGAGUIError> {
let mut data_map = HashMap::new();
for id in self.list_of_experiments() {
let list_of_columns_to_recalc = &self.list_of_columns_to_recalc(&id)?;
info!(
"this columns will be resampled {:?}",
list_of_columns_to_recalc
);
if !list_of_columns_to_recalc.is_empty() {
let experiment = self.series.get_experiment_by_id(&id)?;
let columns = self.list_of_columns(&id)?;
let names: Vec<_> = columns.iter().map(String::as_str).collect();
let preview = experiment
.dataset
.preview_rows(&names, n_points)
.map_err(|error| TGAGUIError::BindingError(error.to_string()))?;
info!(
"created aligned preview for {id}: {} rows",
preview.row_indices.len()
);
data_map.insert(id, preview);
}
}
Ok(data_map)
}
pub fn column_preview_page_for_experiment(
&self,
id: &str,
offset: usize,
limit: usize,
) -> Result<PreviewRows, TGAGUIError> {
self.column_preview_for_experiment(id, offset, limit, false)
}
pub fn column_sample_preview_for_experiment(
&self,
id: &str,
max_rows: usize,
) -> Result<PreviewRows, TGAGUIError> {
self.column_preview_for_experiment(id, 0, max_rows, true)
}
pub fn find_numeric_row_for_experiment(
&self,
id: &str,
column: &str,
target: f64,
tolerance: f64,
from_row: Option<usize>,
direction: RowSearchDirection,
) -> Result<Option<NumericRowMatch>, TGAGUIError> {
let experiment = self.series.get_experiment_by_id(id)?;
experiment
.dataset
.find_numeric_row(column, target, tolerance, from_row, direction)
.map_err(|error| TGAGUIError::BindingError(error.to_string()))
}
pub fn numeric_column_tsv_for_experiment(
&self,
id: &str,
column: &str,
) -> Result<(String, usize), TGAGUIError> {
let experiment = self.series.get_experiment_by_id(id)?;
experiment
.dataset
.numeric_column_tsv(column)
.map_err(|error| TGAGUIError::BindingError(error.to_string()))
}
pub fn numeric_column_diagnostics_for_experiment(
&self,
id: &str,
column: &str,
) -> Result<ColumnDataQualityReport, TGAGUIError> {
let experiment = self.series.get_experiment_by_id(id)?;
experiment
.dataset
.numeric_column_diagnostics(column)
.map_err(|error| TGAGUIError::BindingError(error.to_string()))
}
pub fn delete_rows_for_experiment(
&mut self,
id: &str,
row_indices: &[usize],
) -> Result<(), TGAGUIError> {
self.series.delete_rows_by_index(id, row_indices)?;
self.rebuild_plots_for_experiment(id)?;
self.reset_view();
Ok(())
}
pub fn replace_numeric_cell_for_experiment(
&mut self,
id: &str,
column: &str,
row_index: usize,
expected_value: f64,
replacement_value: f64,
) -> Result<(), TGAGUIError> {
self.series.replace_numeric_cell_at_row(
id,
column,
row_index,
expected_value,
replacement_value,
)?;
self.rebuild_plots_for_experiment(id)?;
self.reset_view();
Ok(())
}
fn column_preview_for_experiment(
&self,
id: &str,
offset: usize,
limit: usize,
sampled: bool,
) -> Result<PreviewRows, TGAGUIError> {
let experiment = self.series.get_experiment_by_id(id)?;
let columns = self.list_of_columns(id)?;
let names = columns.iter().map(String::as_str).collect::<Vec<_>>();
let preview = if sampled {
experiment.dataset.preview_rows(&names, limit)
} else {
experiment.dataset.preview_rows_page(&names, offset, limit)
};
preview.map_err(|error| TGAGUIError::BindingError(error.to_string()))
}
pub fn column_samples_for_all_experiment_for_plotting(
&mut self,
n_points: usize,
) -> Result<(HashMap<String, Vec<f64>>, SampledColumns), TGAGUIError> {
let res = self
.series
.column_samples_for_all_experiment_for_plotting(n_points)?;
Ok(res)
}
pub fn set_heating_rate(&mut self, id: &str, rate: f64) -> Result<(), TGAGUIError> {
self.series.set_heating_rate(id, rate)?;
Ok(())
}
pub fn set_comment(&mut self, id: &str, comment: &str) -> Result<(), TGAGUIError> {
self.series.set_comment(id, comment)?;
Ok(())
}
#[allow(non_snake_case)]
pub fn set_experiment_temperature(&mut self, id: &str, T: f64) -> Result<(), TGAGUIError> {
self.series.set_experiment_temperature(id, T)?;
Ok(())
}
pub fn monotony_of_time_check_for_experiment(&self, id: &str) -> Result<Vec<f64>, TGAGUIError> {
Ok(self.series.monotony_of_time_check(id)?)
}
pub fn time_monotonicity_report_for_experiment(
&self,
id: &str,
) -> Result<TimeMonotonicityReport, TGAGUIError> {
Ok(self.series.time_monotonicity_report(id)?)
}
pub fn sort_experiment_by_time(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.series.sort_experiment_by_time(id)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn set_x(&mut self, id: &str, x_col: &str) -> Result<(), TGAGUIError> {
self.series.set_oneframeplot_x(id, x_col)?;
Ok(())
}
pub fn set_y(&mut self, id: &str, y_col: &str) -> Result<(), TGAGUIError> {
self.series.set_oneframeplot_y(id, y_col)?;
Ok(())
}
pub fn list_of_columns(&self, id: &str) -> Result<Vec<String>, TGAGUIError> {
let list = self.series.list_of_columns(id)?;
Ok(list)
}
pub fn list_of_columns_for_selected(&self) -> Result<Vec<String>, TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.list_of_columns(&id)
}
pub fn plot_range(&mut self, id: &str) -> Result<Ranges, TGAGUIError> {
debug!("setting plot named {} the range", id);
let ranges = self.series.plot_xy_ranges(id)?;
Ok(ranges)
}
pub fn give_ranges_to_plot(&mut self, id: &str) -> Result<Ranges, TGAGUIError> {
debug!("giving ranges to plot named {}", id);
let ranges = self.plot_range(id)?;
let x_name = self.series.oneframeplot_axis_name(id, XY::X)?;
let y_name = self.series.oneframeplot_axis_name(id, XY::Y)?;
let short_name = self.create_plot_short_name(id, &x_name, &y_name);
let mut x_min = ranges.x_min;
let mut x_max = ranges.x_max;
let mut y_min = ranges.y_min;
let mut y_max = ranges.y_max;
for curve in self.plots.iter().filter(|curve| curve.is_shown()) {
if curve.plot_short_name == short_name {
continue;
}
x_min = x_min.min(curve.ranges.x_min);
x_max = x_max.max(curve.ranges.x_max);
y_min = y_min.min(curve.ranges.y_min);
y_max = y_max.max(curve.ranges.y_max);
}
self.interaction.view_range = (x_min, x_max);
self.interaction.view_y_range = (y_min, y_max);
Ok(ranges)
}
pub fn calculate_samplepoints_for_plot(
&mut self,
id: &str,
x_range: [f64; 2],
) -> Result<PlotSeries, TGAGUIError> {
let range = Some({
ViewRange {
t_min: x_range[0],
t_max: x_range[1],
}
});
let n_points = self
.settings
.n_points()
.filter(|&count| count > 0)
.ok_or_else(|| {
TGAGUIError::SettingsErrors(
"Plot sample count must be a positive integer.".to_string(),
)
})?;
let plot = self.series.sample_oneframeplot(id, range, n_points)?;
Ok(plot)
}
pub fn index_by_id(&self, id: &str) -> Result<usize, TGAGUIError> {
let res = self.series.index_by_id(id)?;
Ok(res)
}
pub fn create_points_for_curve(&mut self, id: &str) -> Result<(), TGAGUIError> {
debug!("calculating points for curve");
let ranges = self.give_ranges_to_plot(id)?;
let x_range = [ranges.x_min, ranges.x_max];
let plot = self.calculate_samplepoints_for_plot(id, x_range)?;
let index = self.index_by_id(id)?;
self.push_to_vec_of_curves(plot, id, index, ranges)?;
Ok(())
}
pub fn create_points_for_selected_curve(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.create_points_for_curve(&id)?;
Ok(())
}
pub(crate) fn rebuild_plots_for_experiment(&mut self, id: &str) -> Result<(), TGAGUIError> {
let selected_plot = self
.get_selected_curve_index()
.and_then(|idx| self.plots.get(idx))
.filter(|curve| curve.experiment_id == id)
.map(|curve| curve.plot_short_name.clone());
let preserved_curves: Vec<(String, String, [u8; 3], bool, bool, bool)> = self
.plots
.iter()
.filter(|curve| curve.experiment_id == id)
.map(|curve| {
(
curve.x_name.clone(),
curve.y_name.clone(),
curve.color,
curve.selected,
curve.highlighted,
curve.shown,
)
})
.collect();
if preserved_curves.is_empty() {
return Ok(());
}
let previous_axes = preserved_curves
.first()
.map(|(x, y, ..)| (x.clone(), y.clone()));
self.plots.retain(|curve| curve.experiment_id != id);
let mut selected_index = None;
let rebuild_result = (|| -> Result<(), TGAGUIError> {
for (x_name, y_name, color, selected, highlighted, shown) in preserved_curves {
self.set_x(id, &x_name)?;
self.set_y(id, &y_name)?;
self.create_points_for_curve(id)?;
let short_name = format!("{id}_{x_name}_{y_name}");
let curve_index = self
.plots
.iter()
.position(|curve| curve.plot_short_name == short_name)
.ok_or_else(|| {
TGAGUIError::BindingError("Failed to rebuild plot curve".to_string())
})?;
let curve = &mut self.plots[curve_index];
curve.color = color;
curve.selected = selected;
curve.highlighted = highlighted;
curve.shown = shown;
if selected
&& selected_plot
.as_ref()
.is_some_and(|name| name == &curve.plot_short_name)
{
selected_index = Some(curve_index);
}
}
Ok(())
})();
if let Err(error) = rebuild_result {
self.plots.retain(|curve| curve.experiment_id != id);
if let Some((previous_x, previous_y)) = previous_axes {
let _ = self.set_x(id, &previous_x);
let _ = self.set_y(id, &previous_y);
}
if selected_plot.is_some() {
self.clear_selection();
self.clear_selection_rect();
}
self.reset_view();
return Err(TGAGUIError::post_commit_warning(format!(
"experiment '{id}' was updated and remains in the series; stale curves were removed ({error})"
)));
}
if let Some(index) = selected_index {
self.select_curve(index);
}
self.reset_view();
Ok(())
}
fn refresh_plots_after_in_place_mutation(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.rebuild_plots_for_experiment(id)
}
pub fn create_points_for_curve_with_builder(
&mut self,
id: &str,
colour: Colours,
) -> Result<(), TGAGUIError> {
debug!("calculating points for curve via builder");
let ranges = self.give_ranges_to_plot(id)?;
let x_range = [ranges.x_min, ranges.x_max];
let plot = self.calculate_samplepoints_for_plot(id, x_range)?;
let index = self.index_by_id(id)?;
self.push_to_vec_of_curves_with_builder(plot, id, index, ranges, colour)?;
Ok(())
}
pub fn create_points_for_selected_curve_with_builder(
&mut self,
colour: Colours,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.create_points_for_curve_with_builder(&id, colour)?;
Ok(())
}
pub fn create_plot_short_name(&self, id: &str, x_name: &String, y_name: &String) -> String {
format!("{}_{}_{}", id.to_string(), x_name, y_name)
}
pub fn push_to_vec_of_curves(
&mut self,
plot: PlotSeries,
id: &str,
index: usize,
ranges: Ranges,
) -> Result<(), TGAGUIError> {
let mut new_curve = PlotCurve::default();
new_curve.experiment_id = id.to_string().clone();
new_curve.experiment_index = index;
let x_name = plot.name_x;
let y_name = plot.name_y;
let short_name = self.create_plot_short_name(id, &x_name, &y_name);
new_curve.x_name = x_name;
new_curve.y_name = y_name;
let x_vec = plot.x;
let y_vec = plot.y;
new_curve.segment_starts = plot.segment_starts;
let mut points = Vec::new();
for (xi, yi) in x_vec.iter().zip(y_vec) {
points.push([*xi, yi]);
}
new_curve.ranges = ranges;
new_curve.points = points;
new_curve.plot_short_name = short_name;
if let Some(existing) = self
.plots
.iter()
.position(|curve| curve.plot_short_name == new_curve.plot_short_name)
{
let prev = &self.plots[existing];
new_curve.color = prev.color;
new_curve.shown = prev.shown;
new_curve.selected = prev.selected;
new_curve.highlighted = prev.highlighted;
self.plots[existing] = new_curve;
} else {
self.plots.push(new_curve);
}
Ok(())
}
pub fn push_to_vec_of_curves_with_builder(
&mut self,
plot: PlotSeries,
id: &str,
index: usize,
ranges: Ranges,
colour: Colours,
) -> Result<(), TGAGUIError> {
let short_name = self.create_plot_short_name(id, &plot.name_x, &plot.name_y);
let base_builder = PlotCurveBuilder::new_from_plot(plot, id, index, ranges, short_name);
let configured_builder = base_builder.with_colour(colour);
let mut new_curve = configured_builder.finish();
if let Some(existing) = self
.plots
.iter()
.position(|curve| curve.plot_short_name == new_curve.plot_short_name)
{
let prev = &self.plots[existing];
new_curve = PlotCurveBuilder { curve: new_curve }
.with_shown(prev.shown)
.with_selected(prev.selected)
.with_highlighted(prev.highlighted)
.finish();
self.plots[existing] = new_curve;
} else {
self.plots.push(new_curve);
}
Ok(())
}
pub fn rename_column_for_experiment(
&mut self,
id: &str,
col_name: &str,
new_name: &str,
) -> Result<(), TGAGUIError> {
self.series.rename_column(id, col_name, new_name)?;
self.remap_active_sources_for_experiment(id, col_name, new_name);
for curve in self
.plots
.iter_mut()
.filter(|curve| curve.experiment_id == id)
{
if curve.x_name == col_name {
curve.x_name = new_name.to_string();
}
if curve.y_name == col_name {
curve.y_name = new_name.to_string();
}
curve.plot_short_name = format!("{id}_{}_{}", curve.x_name, curve.y_name);
}
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn drop_column_for_experiment(
&mut self,
id: &str,
col_name: &str,
) -> Result<(), TGAGUIError> {
self.series.drop_column(id, col_name)?;
self.clear_active_sources_if_column_dropped(id, col_name);
self.prune_stale_plots();
self.reset_view();
Ok(())
}
pub fn drop_columns_for_experiment(
&mut self,
id: &str,
col_names: &[String],
) -> Result<(), TGAGUIError> {
self.series.drop_columns(id, col_names)?;
for col_name in col_names {
self.clear_active_sources_if_column_dropped(id, col_name);
}
self.prune_stale_plots();
self.reset_view();
Ok(())
}
pub fn drop_column_for_selected(&mut self, col_name: &str) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.drop_column_for_experiment(&id, col_name)?;
Ok(())
}
pub fn move_time_to_zero_for_experiment(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.series.move_time_to_zero(id)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn move_time_to_zero_for_selected(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
info!("moving time to zero!");
self.move_time_to_zero_for_experiment(&id)?;
Ok(())
}
#[allow(non_snake_case)]
pub fn from_C_to_K_for_experiment(&mut self, id: &str) -> Result<(), TGAGUIError> {
if self.is_temperature_already_kelvin(id)? {
let _ = self.push_message("Temperature is already in Kelvin; conversion skipped.");
return Ok(());
}
self.series.celsius_to_kelvin(id)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
#[allow(non_snake_case)]
pub fn from_C_to_K_of_selected(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
info!("T converted from C to K");
self.from_C_to_K_for_experiment(&id)?;
Ok(())
}
pub fn from_s_to_h_for_experiment(&mut self, id: &str) -> Result<(), TGAGUIError> {
self.series.seconds_to_hours(id)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn from_s_to_h_of_selected(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
if self.is_time_already_in_hours(&id)? {
let _ = self.push_message("Time is already in hours; conversion skipped.");
return Ok(());
}
info!("time turned from seconds to hours");
self.from_s_to_h_for_experiment(&id)?;
Ok(())
}
pub fn cut_before_time_for_selected(&mut self, time: f64) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
info!("cut all data before time {}", time);
self.series.cut_before_time(&id, time)?;
self.rebuild_plots_for_experiment(&id)?;
Ok(())
}
pub fn delete_selected_curve(&mut self) -> Result<(), TGAGUIError> {
let maybe_index = self.get_selected_curve_index().or_else(|| {
if self.is_only_one_shown() {
self.plots.iter().position(|curve| curve.is_shown())
} else {
None
}
});
if let Some(index) = maybe_index {
self.plots.remove(index);
self.clear_selection_rect();
self.reset_view();
Ok(())
} else {
Err(TGAGUIError::BindingError(
"No selected curve to delete".to_string(),
))
}
}
pub fn set_curve_shown(&mut self, index: usize, shown: bool) -> Result<(), TGAGUIError> {
let curve = self
.plots
.get_mut(index)
.ok_or_else(|| TGAGUIError::BindingError(format!("invalid plot index {index}")))?;
if curve.shown == shown {
return Ok(());
}
curve.shown = shown;
if !shown {
curve.selected = false;
curve.highlighted = false;
self.clear_selection_rect();
}
self.reset_view();
Ok(())
}
pub fn delete_curve(&mut self, index: usize) -> Result<(), TGAGUIError> {
if index >= self.plots.len() {
return Err(TGAGUIError::BindingError(format!(
"invalid plot index {index}"
)));
}
self.plots.remove(index);
self.clear_selection();
self.clear_selection_rect();
self.reset_view();
Ok(())
}
pub fn delete_all_plots(&mut self) -> Result<(), TGAGUIError> {
self.plots.clear();
Ok(())
}
pub fn cut_range_x_or_y_for_experiment(
&mut self,
id: &str,
axis: XY,
) -> Result<(), TGAGUIError> {
if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let x_min = bounds.0;
let x_max = bounds.1;
let y_min = bounds.2;
let y_max = bounds.3;
match axis {
XY::X => {
info!("cutting range {:?} on X axe", (x_min, x_max));
let column = self.selected_curve_axis_name(XY::X)?;
self.series
.cut_range_inverse_on_column(id, &column, x_min, x_max)?;
}
XY::Y => {
info!("cutting range {:?} on Y axe", (y_min, y_max));
let column = self.selected_curve_axis_name(XY::Y)?;
self.series
.cut_range_inverse_on_column(id, &column, y_min, y_max)?;
}
}
self.rebuild_plots_for_experiment(id)?;
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
}
Ok(())
}
pub fn cut_range_x_or_y_for_selected(&mut self, axis: XY) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.cut_range_x_or_y_for_experiment(&id, axis)
}
pub fn dimensionless_mass_for_experiment(
&mut self,
id: String,
t_end: f64,
new_col: &str,
) -> Result<(), TGAGUIError> {
self.series.dimensionless_mass(&id, 0.0, t_end, new_col)?;
Ok(())
}
pub fn dimensionless_mass_from_source_for_experiment(
&mut self,
id: &str,
source_col: &str,
t_end: f64,
new_col: &str,
) -> Result<(), TGAGUIError> {
self.series
.dimensionless_mass_from_column(id, source_col, 0.0, t_end, new_col)?;
Ok(())
}
pub fn relative_mass_for_selected(
&mut self,
t_end: f64,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
if !t_end.is_finite() || t_end <= 0.0 {
let _ = self.push_message(
"Baseline end time must be greater than 0.0; 0.0 would use only one point.",
);
return Ok(());
}
let id = self.get_experiment_by_selected_curve()?;
let source_col = self.active_mass_source_for_experiment(&id)?;
match new_col {
Some(new_col) => {
self.dimensionless_mass_from_source_for_experiment(
&id,
&source_col,
t_end,
new_col,
)?;
}
None => {
self.dimensionless_mass_from_source_for_experiment(
&id,
&source_col,
t_end,
"relative_mass",
)?;
}
}
Ok(())
}
pub fn conversion_for_experiment(
&mut self,
id: String,
t_end: f64,
new_col: &str,
) -> Result<(), TGAGUIError> {
self.series.conversion(&id, 0.0, t_end, new_col)?;
Ok(())
}
pub fn conversion_from_source_for_experiment(
&mut self,
id: &str,
source_col: &str,
t_end: f64,
new_col: &str,
) -> Result<(), TGAGUIError> {
self.series
.conversion_from_column(id, source_col, 0.0, t_end, new_col)?;
Ok(())
}
pub fn conversion_for_selected(
&mut self,
t_end: f64,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
if !t_end.is_finite() || t_end <= 0.0 {
let _ = self.push_message(
"Baseline end time must be greater than 0.0; 0.0 would use only one point.",
);
return Ok(());
}
let id = self.get_experiment_by_selected_curve()?;
let source_col = self.active_mass_source_for_experiment(&id)?;
match new_col {
Some(new_col) => {
self.conversion_from_source_for_experiment(&id, &source_col, t_end, new_col)?;
}
None => {
self.conversion_from_source_for_experiment(&id, &source_col, t_end, "conversion")?;
}
}
Ok(())
}
pub fn calibrate_mass_from_voltage(&mut self, id: &str) -> Result<(), TGAGUIError> {
if self.is_mass_already_milligram(id)? {
let _ = self.push_message("Mass is already in milligrams; conversion skipped.");
return Ok(());
}
let set = self.settings.calibration_line().ok_or_else(|| {
TGAGUIError::BindingError("Mass calibration is not configured".to_string())
})?;
let k = set.k();
let b = set.b();
info!(
"calibrating mass from voltage with coefficients: k= {}, b= {} ",
k, b
);
self.series.calibrate_mass_from_voltage(id, k, b)?;
if let Ok(mass_col) = self.series.get_mass_col(id) {
self.set_active_mass_source_for_experiment(id, &mass_col);
}
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn calibrate_mass_from_voltage_for_selected(&mut self) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.calibrate_mass_from_voltage(&id)?;
Ok(())
}
pub fn calibrate_mass_from_voltage_new_column(
&mut self,
id: &str,
col: &str,
) -> Result<(), TGAGUIError> {
if self.is_mass_already_milligram(id)? {
let _ = self.push_message("Mass is already in milligrams; conversion skipped.");
return Ok(());
}
let set = self.settings.calibration_line().ok_or_else(|| {
TGAGUIError::BindingError("Mass calibration is not configured".to_string())
})?;
let k = set.k();
let b = set.b();
self.series.calibrate_mass(id, k, b, col)?;
self.set_active_mass_source_for_experiment(id, col);
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn calibrate_mass_from_voltage_new_colum_for_selected(
&mut self,
col: &str,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.calibrate_mass_from_voltage_new_column(&id, col)?;
Ok(())
}
pub fn calibrate_mass_from_voltage_with_new_optional_column_for_selected(
&mut self,
col: Option<&str>,
) -> Result<(), TGAGUIError> {
match col {
Some(col) => self.calibrate_mass_from_voltage_new_colum_for_selected(col),
None => self.calibrate_mass_from_voltage_for_selected(),
}
}
pub(crate) fn selected_curve_axis_name(&self, axis: XY) -> Result<String, TGAGUIError> {
let selected_index = self.get_selected_curve_index().or_else(|| {
if self.is_only_one_shown() {
self.plots.iter().position(|curve| curve.is_shown())
} else {
None
}
});
let curve = selected_index
.and_then(|index| self.plots.get(index))
.ok_or_else(|| {
TGAGUIError::BindingError(
"No selected curve. Select a curve before choosing its X/Y column.".into(),
)
})?;
Ok(match axis {
XY::X => curve.x_name.clone(),
XY::Y => curve.y_name.clone(),
})
}
pub fn this_is_x_or_y(&self, xy: XY) -> Result<String, TGAGUIError> {
self.selected_curve_axis_name(xy)
}
pub fn this_is_x(&self) -> Result<String, TGAGUIError> {
self.selected_curve_axis_name(XY::X)
}
pub fn this_is_y(&self) -> Result<String, TGAGUIError> {
self.selected_curve_axis_name(XY::Y)
}
pub fn offset_column(
&mut self,
id: &str,
column: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
self.series.offset_column(id, column, offset)?;
Ok(())
}
pub fn offset_column_for_selected(
&mut self,
column: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("for selected experiment {}", id);
self.series.offset_column(&id, column, offset)?;
self.rebuild_plots_for_experiment(&id)?;
Ok(())
}
pub fn add_column_for_selected(
&mut self,
column: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
info!("add for column {} by {}", column, offset);
self.offset_column_for_selected(column, offset)
}
pub fn sub_column_for_selected(
&mut self,
column: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
info!("subtraction for column {} by {}", column, offset);
self.offset_column_for_selected(column, -offset)
}
pub fn offset_column_in_its_range_for_experiment(
&mut self,
id: &str,
colmn: &str,
offset: f64,
from: f64,
to: f64,
) -> Result<(), TGAGUIError> {
self.series
.offset_column_in_its_range(id, colmn, offset, from, to)?;
Ok(())
}
pub fn offset_column_in_its_range_for_selected(
&mut self,
colmn: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let x_min = bounds.0;
let x_max = bounds.1;
let x_col = self.selected_curve_axis_name(XY::X)?;
self.series
.offset_column_in_range_by_reference(&id, colmn, &x_col, offset, x_min, x_max)?;
self.rebuild_plots_for_experiment(&id)?;
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
}
Ok(())
}
pub fn add_column_in_its_range_for_selected(
&mut self,
colmn: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
self.offset_column_in_its_range_for_selected(colmn, offset)
}
pub fn sub_column_in_its_range_for_selected(
&mut self,
colmn: &str,
offset: f64,
) -> Result<(), TGAGUIError> {
self.offset_column_in_its_range_for_selected(colmn, -offset)
}
pub fn offset_y_column_in_its_range_for_experiment(
&mut self,
id: &str,
offset: f64,
from: f64,
to: f64,
) -> Result<(), TGAGUIError> {
self.series
.offset_y_column_in_its_range(id, offset, from, to)?;
Ok(())
}
pub fn offset_y_column_in_its_range_for_selected(
&mut self,
offset: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let y_min = bounds.2;
let y_max = bounds.3;
let y_col = self.selected_curve_axis_name(XY::Y)?;
self.series
.offset_column_in_range_by_reference(&id, &y_col, &y_col, offset, y_min, y_max)?;
self.rebuild_plots_for_experiment(&id)?;
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
}
Ok(())
}
pub fn add_y_column_in_its_range_for_selected(
&mut self,
offset: f64,
) -> Result<(), TGAGUIError> {
self.offset_y_column_in_its_range_for_selected(offset)
}
pub fn sub_y_column_in_its_range_for_selected(
&mut self,
offset: f64,
) -> Result<(), TGAGUIError> {
self.offset_y_column_in_its_range_for_selected(-offset)
}
pub fn scale_columns(
&mut self,
id: &str,
cols: &[&str],
factor: f64,
) -> Result<(), TGAGUIError> {
self.series.scale_columns(id, cols, factor)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn scale_column(&mut self, id: &str, col: &str, factor: f64) -> Result<(), TGAGUIError> {
self.scale_columns(id, &[col], factor)?;
Ok(())
}
pub fn scale_column_of_selected(&mut self, col: &str, factor: f64) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("for selected experiment {}", id);
self.scale_column(&id, col, factor)?;
Ok(())
}
pub fn mul_column_of_selected(&mut self, col: &str, factor: f64) -> Result<(), TGAGUIError> {
info!("multiplication for column {} by factor {}", col, factor);
self.scale_column_of_selected(col, factor)
}
pub fn div_column_of_selected(&mut self, col: &str, factor: f64) -> Result<(), TGAGUIError> {
if !factor.is_finite() || factor == 0.0 {
return Err(TGAGUIError::BindingError(
"Division requires a finite, non-zero value.".to_string(),
));
}
info!("division for column {} by factor {}", col, factor);
self.scale_column_of_selected(col, 1.0 / factor)
}
pub fn scale_column_in_its_range_for_experiment(
&mut self,
id: &str,
colmn: &str,
scale: f64,
from: f64,
to: f64,
) -> Result<(), TGAGUIError> {
self.series
.scale_column_in_its_range(id, colmn, scale, from, to)?;
Ok(())
}
pub fn scale_column_in_its_range_for_selected(
&mut self,
colmn: &str,
scale: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let x_min = bounds.0;
let x_max = bounds.1;
let x_col = self.selected_curve_axis_name(XY::X)?;
self.series
.scale_column_in_range_by_reference(&id, colmn, &x_col, scale, x_min, x_max)?;
self.rebuild_plots_for_experiment(&id)?;
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
}
Ok(())
}
pub fn mul_column_in_its_range_for_selected(
&mut self,
colmn: &str,
scale: f64,
) -> Result<(), TGAGUIError> {
self.scale_column_in_its_range_for_selected(colmn, scale)
}
pub fn div_column_in_its_range_for_selected(
&mut self,
colmn: &str,
scale: f64,
) -> Result<(), TGAGUIError> {
if !scale.is_finite() || scale == 0.0 {
return Err(TGAGUIError::BindingError(
"Division requires a finite, non-zero value.".to_string(),
));
}
self.scale_column_in_its_range_for_selected(colmn, 1.0 / scale)
}
pub fn scale_y_column_in_its_range_for_experiment(
&mut self,
id: &str,
scale: f64,
from: f64,
to: f64,
) -> Result<(), TGAGUIError> {
self.series
.scale_y_column_in_its_range(id, scale, from, to)?;
Ok(())
}
pub fn scale_y_column_in_its_range_for_selected(
&mut self,
scale: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let y_min = bounds.2;
let y_max = bounds.3;
let y_col = self.selected_curve_axis_name(XY::Y)?;
self.series
.scale_column_in_range_by_reference(&id, &y_col, &y_col, scale, y_min, y_max)?;
self.rebuild_plots_for_experiment(&id)?;
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
}
Ok(())
}
pub fn mul_y_column_in_its_range_for_selected(
&mut self,
scale: f64,
) -> Result<(), TGAGUIError> {
self.scale_y_column_in_its_range_for_selected(scale)
}
pub fn div_y_column_in_its_range_for_selected(
&mut self,
scale: f64,
) -> Result<(), TGAGUIError> {
self.scale_y_column_in_its_range_for_selected(1.0 / scale)
}
pub fn exp_column(&mut self, id: &str, col_name: &str) -> Result<(), TGAGUIError> {
self.series.exp_column(id, col_name)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn exp_column_for_selected(&mut self, col_name: &str) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.exp_column(&id, col_name)?;
Ok(())
}
pub fn ln_column(&mut self, id: &str, col_name: &str) -> Result<(), TGAGUIError> {
self.series.ln_column(id, col_name)?;
self.rebuild_plots_for_experiment(id)?;
Ok(())
}
pub fn ln_column_for_selected(&mut self, col_name: &str) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
debug!("selected experiment {}", id);
self.ln_column(&id, col_name)?;
Ok(())
}
fn remap_active_sources_to_new_column(
&mut self,
id: &str,
source_col: &str,
old_columns: &[String],
) {
let Ok(current_columns) = self.list_of_columns(id) else {
return;
};
let mut added = current_columns
.iter()
.filter(|column| !old_columns.contains(column));
let Some(output_column) = added.next() else {
return;
};
if added.next().is_none() {
self.remap_active_sources_for_experiment(id, source_col, output_column);
}
}
pub fn hampel_filter_for_selected(
&mut self,
col_name: &str,
window: usize,
sigma: f64,
strategy: HampelStrategy,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.hampel_filter(&id, col_name, window, sigma, strategy)?;
if old_cols.iter().any(|name| name == col_name) {
self.refresh_plots_after_in_place_mutation(&id)?;
} else {
self.create_plots_with_new_columns(&id, old_cols, None)?;
}
Ok(())
}
pub fn hampel_filter_for_selected_as(
&mut self,
col_name: &str,
window: usize,
sigma: f64,
strategy: HampelStrategy,
out_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.hampel_filter_for_experiment_as(&id, col_name, window, sigma, strategy, out_col)
}
pub fn hampel_drop_count_for_experiment(
&self,
id: &str,
col_name: &str,
window: usize,
sigma: f64,
) -> Result<usize, TGAGUIError> {
let experiment = self.series.get_experiment_by_id(id)?;
experiment
.dataset
.hampel_drop_count(col_name, window, sigma)
.map_err(TGAGUIError::from)
}
pub fn hampel_filter_for_experiment_as(
&mut self,
id: &str,
col_name: &str,
window: usize,
sigma: f64,
strategy: HampelStrategy,
out_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let old_cols = self.list_of_columns(&id)?;
let is_drop = matches!(&strategy, HampelStrategy::Drop);
self.series
.hampel_filter_as(&id, col_name, window, sigma, strategy, out_col)?;
if is_drop {
self.remap_active_sources_to_new_column(id, col_name, &old_cols);
self.rebuild_plots_for_experiment(id)?;
if self
.list_of_columns(id)?
.iter()
.any(|name| !old_cols.contains(name))
{
self.create_plots_with_new_columns(id, old_cols, None)?;
}
} else if let Some(produced) = out_col {
if produced == col_name {
self.refresh_plots_after_in_place_mutation(id)?;
} else {
self.remap_active_sources_for_experiment(id, col_name, produced);
self.create_plots_with_new_columns(id, old_cols, None)?;
}
} else {
self.remap_active_sources_to_new_column(id, col_name, &old_cols);
self.create_plots_with_new_columns(id, old_cols, None)?;
}
Ok(())
}
pub fn sg_filter_column_for_selected(
&mut self,
col: &str,
window: usize,
poly_order: usize,
deriv: usize,
delta: f64,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.sg_filter_column(&id, col, window, poly_order, deriv, delta)?;
if old_cols.iter().any(|name| name == col) {
self.refresh_plots_after_in_place_mutation(&id)?;
} else {
self.create_plots_with_new_columns(&id, old_cols, None)?;
}
Ok(())
}
pub fn sg_filter_column_for_selected_as(
&mut self,
col: &str,
window: usize,
poly_order: usize,
deriv: usize,
delta: f64,
out_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if deriv > 0 && out_col == Some(col) {
let is_active_source = self
.active_mass_source_for_experiment(&id)
.is_ok_and(|source| source == col)
|| self
.active_temperature_source_for_experiment(&id)
.is_ok_and(|source| source == col);
if is_active_source {
return Err(TGAGUIError::BindingError(format!(
"Refusing to overwrite active signal column '{col}' with its derivative. Choose a new output column."
)));
}
}
let old_cols = self.list_of_columns(&id)?;
self.series
.sg_filter_column_as(&id, col, window, poly_order, deriv, delta, out_col)?;
if deriv > 0 {
self.create_plots_with_new_columns(&id, old_cols, None)?;
} else if let Some(produced) = out_col {
if produced == col {
self.refresh_plots_after_in_place_mutation(&id)?;
} else {
self.remap_active_sources_for_experiment(&id, col, produced);
self.create_plots_with_new_columns(&id, old_cols, None)?;
}
} else {
self.remap_active_sources_to_new_column(&id, col, &old_cols);
self.create_plots_with_new_columns(&id, old_cols, None)?;
}
Ok(())
}
pub fn rolling_mean_for_selected(
&mut self,
col_name: &str,
window: usize,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series.rolling_mean(&id, col_name, window)?;
if old_cols.iter().any(|name| name == col_name) {
self.refresh_plots_after_in_place_mutation(&id)?;
} else {
self.create_plots_with_new_columns(&id, old_cols, None)?;
}
Ok(())
}
pub fn rolling_mean_for_selected_as(
&mut self,
col_name: &str,
window: usize,
out_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.rolling_mean_as(&id, col_name, window, out_col)?;
if let Some(produced) = out_col {
if produced != col_name {
self.remap_active_sources_for_experiment(&id, col_name, produced);
}
self.create_plots_with_new_columns(&id, old_cols, None)?;
self.refresh_plots_after_in_place_mutation(&id)?;
} else {
self.remap_active_sources_to_new_column(&id, col_name, &old_cols);
self.create_plots_with_new_columns(&id, old_cols, None)?;
self.refresh_plots_after_in_place_mutation(&id)?;
}
Ok(())
}
pub fn synchronized_rolling_mean_for_selected_as(
&mut self,
x_column: &str,
columns: &[&str],
out_columns: &[Option<&str>],
window: usize,
output_x_column: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if columns.is_empty() || columns.len() != out_columns.len() {
return Err(TGAGUIError::BindingError(
"Select one or more signal columns and provide one output name per signal.".into(),
));
}
for column in columns {
if !self.plots.iter().any(|curve| {
curve.experiment_id == id && curve.x_name == x_column && curve.y_name == *column
}) {
return Err(TGAGUIError::BindingError(format!(
"Signal '{column}' has no plotted curve on X='{x_column}' in experiment '{id}'. Synchronized rolling cannot mix grids."
)));
}
}
let experiment = self.series.get_experiment_by_id(&id)?;
if experiment.dataset.schema.time.as_deref() != Some(x_column) {
return Err(TGAGUIError::BindingError(format!(
"The selected X column '{x_column}' is not the active time binding. Select a curve on the active time grid before synchronized rolling."
)));
}
let existing = self.list_of_columns(&id)?;
let mut output_names = Vec::with_capacity(columns.len());
for (source, requested) in columns.iter().zip(out_columns) {
let output = match requested.map(str::trim).filter(|name| !name.is_empty()) {
Some(name) if name != *source && existing.iter().any(|item| item == name) => {
return Err(TGAGUIError::BindingError(format!(
"Rolling output '{name}' already exists; choose a new name or use the source name to replace that signal explicitly."
)));
}
Some(name) => name.to_string(),
None => fresh_column_name(&existing, &format!("rolling_{source}")),
};
output_names.push(output);
}
ensure_distinct_new_names(&output_names)?;
let resolved_x = output_x_column
.map(|name| {
resolve_new_column_name(&existing, Some(name), &format!("rolling_{x_column}"))
})
.transpose()?;
if resolved_x
.as_ref()
.is_some_and(|x| output_names.iter().any(|name| name == x))
{
return Err(TGAGUIError::BindingError(
"The averaged X name must be different from every signal output name.".into(),
));
}
let output_refs = output_names
.iter()
.map(|name| Some(name.as_str()))
.collect::<Vec<_>>();
self.series.rolling_mean_columns_synchronized_as(
&id,
x_column,
columns,
&output_refs,
window,
resolved_x.as_deref(),
)?;
for (source, output) in columns.iter().zip(&output_names) {
if source != output {
self.remap_active_sources_for_experiment(&id, source, output);
}
}
let plot_x = resolved_x.as_deref().unwrap_or(x_column);
for output in &output_names {
self.show_column_on_plot(&id, plot_x, output).map_err(|error| {
TGAGUIError::post_commit_warning(format!(
"Synchronized rolling data for '{id}' were committed, but the curve '{output}' against '{plot_x}' could not be shown ({error})"
))
})?;
}
Ok(())
}
pub fn lowess_smooth_columns_for_selected(
&mut self,
time_col: &str,
columns: &[&str],
config: LowessConfig,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.lowess_smooth_columns(&id, time_col, columns, config)?;
self.create_plots_with_new_columns(&id, old_cols, Some(time_col))?;
Ok(())
}
pub fn lowess_smooth_columns_for_selected_as(
&mut self,
time_col: &str,
columns: &[&str],
out_columns: &[Option<&str>],
config: LowessConfig,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if columns.len() != out_columns.len() {
return Err(TGAGUIError::BindingError(
"LOWESS input and output column counts must match".into(),
));
}
let existing = self.list_of_columns(&id)?;
let mut resolved_outputs = Vec::with_capacity(columns.len());
for (source, requested) in columns.iter().zip(out_columns) {
let output = match requested.map(str::trim).filter(|name| !name.is_empty()) {
Some(output) if output == *source => output.to_string(),
Some(output) if existing.iter().any(|name| name == output) => {
return Err(TGAGUIError::BindingError(format!(
"LOWESS output '{output}' already exists; use the source name for explicit in-place replacement or choose a new name"
)));
}
Some(output) => output.to_string(),
None => fresh_column_name(&existing, &format!("lowess_{source}")),
};
resolved_outputs.push(output);
}
ensure_distinct_new_names(&resolved_outputs)?;
let output_refs: Vec<Option<&str>> = resolved_outputs
.iter()
.map(|name| Some(name.as_str()))
.collect();
self.series
.lowess_smooth_columns_as(&id, time_col, columns, &output_refs, config)?;
let mut in_place_mutation = false;
for (source, produced) in columns.iter().zip(&resolved_outputs) {
if source == produced {
in_place_mutation = true;
} else {
self.remap_active_sources_for_experiment(&id, source, produced);
}
}
if in_place_mutation {
self.rebuild_plots_for_experiment(&id).map_err(|error| {
TGAGUIError::post_commit_warning(format!(
"LOWESS data for '{id}' were committed, but existing plots could not be refreshed ({error})"
))
})?;
}
for produced in &resolved_outputs {
self.show_column_on_plot(&id, time_col, produced).map_err(|error| {
TGAGUIError::post_commit_warning(format!(
"LOWESS data for '{id}' were committed, but the curve for '{produced}' could not be shown ({error})"
))
})?;
}
Ok(())
}
pub fn splines_for_selected(
&mut self,
new_time_col: &str,
n_points: usize,
kind: SplineKind,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.spline_resample_oneframeplot(&id, new_time_col, n_points, kind)?;
self.create_plots_with_new_columns(&id, old_cols, Some(new_time_col))?;
Ok(())
}
pub fn splines_for_selected_as(
&mut self,
new_time_col: &str,
n_points: usize,
kind: SplineKind,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let selected_x = self.this_is_x()?;
let selected_y = self.this_is_y()?;
let existing = self.list_of_columns(&id)?;
let new_time_col = resolve_new_column_name(&existing, Some(new_time_col), new_time_col)?;
let new_col = resolve_new_column_name(&existing, new_col, &format!("spline_{selected_y}"))?;
ensure_distinct_new_names(&[new_time_col.clone(), new_col.clone()])?;
self.series.spline_resample_columns_as(
&id,
&selected_x,
&new_time_col,
&[selected_y.as_str()],
&[Some(&new_col)],
n_points,
kind,
)?;
self.remap_active_sources_for_experiment(&id, &selected_y, &new_col);
self.show_column_on_plot(&id, &new_time_col, &new_col)
.map_err(|error| {
TGAGUIError::post_commit_warning(format!(
"Spline data for '{id}' were committed, but the curve for '{new_col}' could not be shown ({error})"
))
})?;
Ok(())
}
pub fn lsq_spline_resample_columns(
&mut self,
time_col: &str,
new_time_col: &str,
columns: &[&str],
n_points: usize,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let old_cols = self.list_of_columns(&id)?;
self.series
.lsq_spline_resample_columns(&id, time_col, new_time_col, columns, n_points)?;
self.create_plots_with_new_columns(&id, old_cols, Some(new_time_col))?;
Ok(())
}
pub fn lsq_spline_resample_columns_as(
&mut self,
time_col: &str,
new_time_col: &str,
columns: &[&str],
out_columns: &[Option<&str>],
n_points: usize,
degree: usize,
n_internal_knots: usize,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
if columns.len() != out_columns.len() {
return Err(TGAGUIError::BindingError(
"LSQ spline input and output column counts must match".into(),
));
}
let existing = self.list_of_columns(&id)?;
let source_natures = columns
.iter()
.map(|source| {
self.series
.get_experiment_by_id(&id)
.ok()
.and_then(|experiment| experiment.dataset.schema.columns.get(*source))
.map(|metadata| metadata.nature)
.unwrap_or(ColumnNature::Unknown)
})
.collect::<Vec<_>>();
let new_time_col = resolve_new_column_name(&existing, Some(new_time_col), new_time_col)?;
let resolved_outputs = columns
.iter()
.zip(out_columns)
.map(|(source, requested)| {
resolve_new_column_name(&existing, *requested, &format!("lsq_spline_{source}"))
})
.collect::<Result<Vec<_>, _>>()?;
let mut all_new_names = vec![new_time_col.clone()];
all_new_names.extend(resolved_outputs.iter().cloned());
ensure_distinct_new_names(&all_new_names)?;
let output_refs: Vec<Option<&str>> = resolved_outputs
.iter()
.map(|name| Some(name.as_str()))
.collect();
self.series.lsq_spline_resample_columns_as(
&id,
time_col,
&new_time_col,
columns,
&output_refs,
n_points,
degree,
n_internal_knots,
SolverKind::Banded,
)?;
for ((source, produced), nature) in
columns.iter().zip(&resolved_outputs).zip(source_natures)
{
match nature {
ColumnNature::Mass => self.set_active_mass_source_for_experiment(&id, produced),
ColumnNature::Temperature => {
self.set_active_temperature_source_for_experiment(&id, produced)
}
_ => self.remap_active_sources_for_experiment(&id, source, produced),
}
self.show_column_on_plot(&id, &new_time_col, produced)
.map_err(|error| {
TGAGUIError::post_commit_warning(format!(
"LSQ spline data for '{id}' were committed, but the curve for '{produced}' could not be shown ({error})"
))
})?;
}
Ok(())
}
pub fn derive_rate(
&mut self,
id: &str,
source_col: &str,
new_col: &str,
new_col_nature: ColumnNature,
) -> Result<(), TGAGUIError> {
self.series
.derive_rate(id, source_col, new_col, new_col_nature)?;
Ok(())
}
pub fn derive_mass_rate(&mut self, id: &str, new_col: Option<&str>) -> Result<(), TGAGUIError> {
let new_col = new_col.unwrap_or("dm_dt");
self.series.derive_mass_rate(id, new_col)?;
Ok(())
}
pub fn derive_temperature_rate(
&mut self,
id: &str,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let new_col = new_col.unwrap_or("dT_dt");
self.series.derive_temperature_rate(id, new_col)?;
Ok(())
}
pub fn derive_dimensionless_rate(
&mut self,
id: &str,
col_name: &str,
out_name: &str,
) -> Result<(), TGAGUIError> {
self.series
.derive_dimensionless_rate(id, col_name, out_name)?;
Ok(())
}
pub fn derive_deta_dt(&mut self, id: &str, out_name: Option<&str>) -> Result<(), TGAGUIError> {
let out_name = out_name.unwrap_or("deta_dt");
self.series.derive_deta_dt(id, out_name)?;
Ok(())
}
pub fn derive_dalpha_dt(
&mut self,
id: &str,
out_name: Option<&str>,
) -> Result<(), TGAGUIError> {
let out_name = out_name.unwrap_or("dalpha_dt");
self.series.derive_dalpha_dt(id, out_name)?;
Ok(())
}
pub fn derive_rate_for_selected(
&mut self,
source_col: &str,
new_col: &str,
new_col_nature: ColumnNature,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.derive_rate(&id, source_col, new_col, new_col_nature)?;
Ok(())
}
pub fn derive_mass_rate_for_selected(
&mut self,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let source_col = self.active_mass_source_for_experiment(&id)?;
let new_col = new_col.unwrap_or("dm_dt");
self.series
.derive_rate(&id, &source_col, new_col, ColumnNature::MassRate)?;
Ok(())
}
pub fn derive_temperature_rate_for_selected(
&mut self,
new_col: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let source_col = self.active_temperature_source_for_experiment(&id)?;
let new_col = new_col.unwrap_or("dT_dt");
self.series
.derive_rate(&id, &source_col, new_col, ColumnNature::TemperatureRate)?;
Ok(())
}
pub fn derive_dimensionless_rate_for_selected(
&mut self,
col_name: &str,
out_name: &str,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.derive_dimensionless_rate(&id, col_name, out_name)?;
Ok(())
}
pub fn derive_deta_dt_for_selected(
&mut self,
out_name: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.derive_deta_dt(&id, out_name)?;
Ok(())
}
pub fn derive_dalpha_dt_for_selected(
&mut self,
out_name: Option<&str>,
) -> Result<(), TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
self.derive_dalpha_dt(&id, out_name)?;
Ok(())
}
pub fn mean_on_interval(
&self,
id: &str,
value_col: &str,
time_col: &str,
from: f64,
to: f64,
) -> Result<f64, TGAGUIError> {
let r = self
.series
.mean_on_interval(id, value_col, time_col, from, to)?;
Ok(r)
}
pub fn mean_on_interval_on_own_range(
&self,
id: &str,
col: &str,
from: f64,
to: f64,
) -> Result<f64, TGAGUIError> {
let r = self
.series
.mean_on_interval_on_own_range(id, col, from, to)?;
Ok(r)
}
pub fn mean_on_interval_on_own_range_for_selected(&self) -> Result<f64, TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let r = if let Some(range) = self.interaction.selection_rect {
let bounds = range.bounds();
let y_min = bounds.2;
let y_max = bounds.3;
let y_col = self.selected_curve_axis_name(XY::Y)?;
let r = self.mean_on_interval_on_own_range(&id, &y_col, y_min, y_max)?;
r
} else {
return Err(TGAGUIError::BindingError(
"No selection rectangle. Drag-select a region on the plot first.".to_string(),
));
};
Ok(r)
}
pub fn mean_on_column(&self, id: &str, col: &str) -> Result<f64, TGAGUIError> {
let r = self.series.mean_on_column(id, col)?;
Ok(r)
}
pub fn mean_on_column_for_selected(&self) -> Result<f64, TGAGUIError> {
let id = self.get_experiment_by_selected_curve()?;
let y_col = self.selected_curve_axis_name(XY::Y)?;
let r = self.mean_on_column(&id, &y_col)?;
Ok(r)
}
pub fn apply_golden_pipeline(
&mut self,
id: &str,
config: GoldenPipelineConfig,
) -> Result<(), TGAGUIError> {
self.apply_golden_pipeline_with_plot_refresh(id, config, |model, output_id, is_new| {
if is_new {
let experiment = model.series.get_experiment_by_id(output_id)?;
let x = experiment.dataset.schema.eta.clone().ok_or_else(|| {
TGAGUIError::BindingError(
"Golden Pipeline output has no conversion column".into(),
)
})?;
let y = experiment.dataset.schema.deta_dt.clone().ok_or_else(|| {
TGAGUIError::BindingError(
"Golden Pipeline output has no conversion rate".into(),
)
})?;
model.set_x(output_id, &x)?;
model.set_y(output_id, &y)?;
model.create_points_for_curve(output_id)?;
} else {
model.rebuild_plots_for_experiment(output_id)?;
}
Ok(())
})
}
fn apply_golden_pipeline_with_plot_refresh<F>(
&mut self,
id: &str,
config: GoldenPipelineConfig,
refresh_plots: F,
) -> Result<(), TGAGUIError>
where
F: FnOnce(&mut Self, &str, bool) -> Result<(), TGAGUIError>,
{
let mut config = config;
let do_we_need_new_exp = config.save_to_new_experiment;
let line = self.settings.calibration_line().ok_or_else(|| {
TGAGUIError::BindingError("Mass calibration is not configured".to_string())
})?;
let k = line.k();
let b = line.b();
config.b = b;
config.k = k;
self.series.apply_golden_pipeline(id, config)?;
let output_id = if do_we_need_new_exp {
format!("proceeded_{id}")
} else {
id.to_string()
};
let plot_result = refresh_plots(self, &output_id, do_we_need_new_exp);
if let Err(error) = plot_result {
self.plots.retain(|plot| plot.experiment_id != output_id);
let warning = TGAGUIError::post_commit_warning(format!(
"Golden Pipeline data for '{output_id}' were committed, but its plot could not be refreshed ({error})"
));
let _ = self.push_message(&warning.to_string());
return Err(warning);
}
let _ = self.push_message(&format!("Golden Pipeline completed for '{output_id}'"));
Ok(())
}
pub fn create_kinetic_data_view(
&self,
what_exp_to_take: Option<&[&str]>,
what_cols_take: Vec<ColumnNature>,
) -> Result<KineticDataView, TGAGUIError> {
let view = self
.series
.create_kinetic_data_view(what_exp_to_take, what_cols_take)?;
Ok(view)
}
pub fn create_kinetic_data_view_for_method(
&self,
what_exp_to_take: Option<&[&str]>,
method: &IsoconversionalMethod,
) -> Result<KineticDataView, TGAGUIError> {
let view = self
.series
.create_kinetic_data_view_for_method(what_exp_to_take, method)?;
Ok(view)
}
pub fn push_isoconversional_result(
&mut self,
result: &IsoconversionalResult,
id: &str,
) -> Result<(), TGAGUIError> {
let mut candidate = self.clone();
candidate.series.push_isoconversional_result(result, id)?;
let x_col = "eta";
let y_col = "Ea";
candidate.set_x(id, x_col)?;
candidate.set_y(id, y_col)?;
candidate.create_points_for_curve_with_builder(id, Colours::Red)?;
let short_name =
candidate.create_plot_short_name(id, &x_col.to_string(), &y_col.to_string());
for curve in &mut candidate.plots {
curve.shown = false;
curve.selected = false;
}
if let Some(curve) = candidate
.plots
.iter_mut()
.find(|curve| curve.plot_short_name == short_name)
{
curve.shown = true;
curve.selected = true;
}
candidate.reset_view();
*self = candidate;
Ok(())
}
pub fn add_column_from_vec(
&mut self,
id: &str,
name: &str,
unit: Unit,
nature: ColumnNature,
data: Vec<f64>,
) -> Result<(), TGAGUIError> {
self.series
.add_column_from_vec(id, name, unit, nature, data)?;
Ok(())
}
pub fn add_formula_column(
&mut self,
id: &str,
name: &str,
x_column: &str,
expression: &str,
unit: Unit,
nature: ColumnNature,
) -> Result<(), TGAGUIError> {
self.series
.add_formula_column(id, name, x_column, expression, unit, nature)?;
Ok(())
}
pub fn add_formula_column_from_columns(
&mut self,
id: &str,
name: &str,
variable_columns: &[(String, String)],
expression: &str,
unit: Unit,
nature: ColumnNature,
) -> Result<(), TGAGUIError> {
self.series.add_formula_column_from_columns(
id,
name,
variable_columns,
expression,
unit,
nature,
)?;
Ok(())
}
}
#[cfg(test)]
mod fitting_gui_model_tests {
use super::*;
use crate::Kinetics::experimental_kinetics::experiment_series_main::ExperimentMeta;
use crate::Kinetics::experimental_kinetics::math::fitting::{
FitColumnRequest, FittingModelName,
};
use crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA;
fn linspace(start: f64, end: f64, len: usize) -> Vec<f64> {
let step = if len > 1 {
(end - start) / (len - 1) as f64
} else {
0.0
};
(0..len).map(|idx| start + idx as f64 * step).collect()
}
#[test]
fn division_rejects_zero_and_non_finite_factors_before_mutation() {
let mut model = PlotModel::default();
for factor in [0.0, f64::NAN, f64::INFINITY] {
let error = model.div_column_of_selected("mass", factor).unwrap_err();
assert!(error.to_string().contains("finite, non-zero"));
assert!(model.series.is_empty());
}
}
#[test]
fn fit_column_and_plot_adds_visible_fitted_curve() {
let time = linspace(0.0, 5.0, 80);
let mass = time
.iter()
.map(|&t| 2.0 * (-0.6 * t).exp())
.collect::<Vec<_>>();
let virtual_tga = VirtualTGA {
temperature: vec![500.0; time.len()],
time,
mass,
};
let mut model = PlotModel::default();
model
.series
.create_from_synthetic_data(
&virtual_tga,
ExperimentMeta {
identity: uuid::Uuid::new_v4().to_string(),
id: "fit_gui".to_string(),
heating_rate: None,
isothermal_temperature: Some(500.0),
thermal_mode: crate::Kinetics::experimental_kinetics::experiment_series_main::ExperimentThermalMode::Isothermal,
comment: Some("fit gui model test".to_string()),
},
)
.unwrap();
let result = model
.fit_column_and_plot(
FitColumnRequest::new("fit_gui", "time", "mass", FittingModelName::DecExp)
.with_output_col("fit_mass"),
)
.unwrap();
assert_eq!(result.output_col, "fit_mass");
let exp = model.series.get_experiment_by_id("fit_gui").unwrap();
assert!(exp.dataset.schema.columns.contains_key("fit_mass"));
assert!(model.plots.iter().any(|curve| {
curve.experiment_id == "fit_gui"
&& curve.x_name == "time"
&& curve.y_name == "fit_mass"
&& curve.shown
&& !curve.points.is_empty()
}));
}
#[test]
fn lowess_uses_the_same_explicit_x_for_calculation_and_plot_for_blank_and_named_outputs() {
use crate::gui::experimental_kinetics_gui::gui_test::load_model_with_two_curves;
let prepare = || {
let mut model = load_model_with_two_curves();
let id = model.list_of_experiments()[0].clone();
let mass_curve = model
.plots
.iter()
.position(|curve| curve.y_name == "m")
.unwrap();
model.select_curve(mass_curve);
let time = model
.series
.get_experiment_by_id(&id)
.unwrap()
.dataset
.column_as_array1("t")
.unwrap();
model
.add_column_from_vec(
&id,
"scaled_time",
Unit::Second,
ColumnNature::Time,
time.into_iter().map(|value| value * 2.0).collect(),
)
.unwrap();
(model, id)
};
let config = LowessConfig {
fraction: 0.2,
iterations: 2,
..LowessConfig::default()
};
let (mut default_named, id) = prepare();
default_named
.lowess_smooth_columns_for_selected_as("scaled_time", &["m"], &[None], config.clone())
.unwrap();
let (mut explicitly_named, explicit_id) = prepare();
explicitly_named
.lowess_smooth_columns_for_selected_as(
"scaled_time",
&["m"],
&[Some("lowess_m")],
config,
)
.unwrap();
for model in [&default_named, &explicitly_named] {
assert!(model.plots.iter().any(|curve| {
curve.experiment_id == id
&& curve.x_name == "scaled_time"
&& curve.y_name == "lowess_m"
}));
assert_eq!(
model.active_mass_source_for_experiment(&id).unwrap(),
"lowess_m"
);
}
assert_eq!(id, explicit_id);
}
#[test]
fn lowess_supports_multiple_outputs_and_explicit_in_place_mapping() {
use crate::gui::experimental_kinetics_gui::gui_test::load_model_with_two_curves;
let mut model = load_model_with_two_curves();
let id = model.list_of_experiments()[0].clone();
let mass_curve = model
.plots
.iter()
.position(|curve| curve.y_name == "m")
.unwrap();
model.select_curve(mass_curve);
let time = model
.series
.get_experiment_by_id(&id)
.unwrap()
.dataset
.column_as_array1("t")
.unwrap();
model
.add_column_from_vec(
&id,
"scaled_time",
Unit::Second,
ColumnNature::Time,
time.into_iter().map(|value| value * 2.0).collect(),
)
.unwrap();
let original_temperature = model
.series
.get_experiment_by_id(&id)
.unwrap()
.dataset
.column_as_array1("T")
.unwrap();
let config = LowessConfig {
fraction: 0.2,
iterations: 2,
..LowessConfig::default()
};
model
.lowess_smooth_columns_for_selected_as(
"scaled_time",
&["m", "T"],
&[None, Some("T")],
config,
)
.unwrap();
let experiment = model.series.get_experiment_by_id(&id).unwrap();
assert_ne!(
experiment.dataset.column_as_array1("T").unwrap(),
original_temperature,
"explicitly selecting the source name should replace that source"
);
assert!(model.plots.iter().any(|curve| {
curve.experiment_id == id && curve.x_name == "scaled_time" && curve.y_name == "lowess_m"
}));
assert!(model.plots.iter().any(|curve| {
curve.experiment_id == id && curve.x_name == "scaled_time" && curve.y_name == "T"
}));
assert_eq!(
model.active_mass_source_for_experiment(&id).unwrap(),
"lowess_m"
);
}
}
#[cfg(test)]
mod golden_pipeline_commit_tests {
use super::*;
use crate::Kinetics::experimental_kinetics::exp_engine_api::{SavGolConfig, SplineConfig};
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment;
fn model_with_two_experiments() -> PlotModel {
let time = (0..241).map(|index| index as f64).collect::<Vec<_>>();
let mass = time
.iter()
.map(|time| 100.0 * (-0.002 * time).exp())
.collect::<Vec<_>>();
let data = VirtualTGA {
temperature: vec![500.0; time.len()],
time,
mass,
};
let dataset = crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset::create_from_synthetic_data(&data).unwrap();
let mut model = PlotModel::default();
model.settings.set_calibration_coeffs(1.0, 0.0);
for id in ["source", "unrelated"] {
model
.series
.push(
TGAExperiment::new(dataset.clone())
.with_id(id)
.with_isothermal_temperature(500.0),
)
.unwrap();
}
model.set_x("source", "time").unwrap();
model.set_y("source", "mass").unwrap();
model.create_points_for_curve("source").unwrap();
model.set_x("unrelated", "time").unwrap();
model.set_y("unrelated", "mass").unwrap();
model.create_points_for_curve("unrelated").unwrap();
model
}
fn config() -> GoldenPipelineConfig {
GoldenPipelineConfig {
sav_gol_config: SavGolConfig {
window_size: 11,
poly_degree: 3,
deriv: 0,
delta: 1.0,
},
averaging_time: 10.0,
isothermal_temperature: Some(500.0),
spline_config: SplineConfig {
n_points: 160,
n_internal_points: 8,
degree: 3,
},
save_to_new_experiment: true,
del_old_experiment: false,
..GoldenPipelineConfig::default()
}
}
#[test]
fn plot_refresh_failure_keeps_committed_data_history_and_unrelated_curve() {
let mut model = model_with_two_experiments();
let unrelated_points = model
.plots
.iter()
.find(|curve| curve.experiment_id == "unrelated")
.unwrap()
.points
.clone();
let source_history_before = model
.series
.get_experiment_by_id("source")
.unwrap()
.dataset
.history_of_operations
.vector_of_operations
.len();
let error = model
.apply_golden_pipeline_with_plot_refresh(
"source",
config(),
|model, output_id, is_new| {
assert!(is_new);
let output = model.series.get_experiment_by_id(output_id).unwrap();
assert!(output.dataset.schema.eta.is_some());
assert!(
output
.dataset
.history_of_operations
.vector_of_operations
.len()
> source_history_before
);
model.plots.push(PlotCurve {
experiment_id: output_id.to_string(),
..PlotCurve::default()
});
Err(TGAGUIError::BindingError(
"injected plot refresh failure".into(),
))
},
)
.unwrap_err();
assert!(matches!(&error, TGAGUIError::PostCommitWarning(_)));
assert!(error.to_string().contains("were committed"));
assert!(
model
.series
.get_experiment_by_id("proceeded_source")
.is_ok()
);
assert!(model.series.get_experiment_by_id("source").is_ok());
assert!(
!model
.plots
.iter()
.any(|curve| curve.experiment_id == "proceeded_source")
);
let unrelated_after = model
.plots
.iter()
.find(|curve| curve.experiment_id == "unrelated")
.unwrap();
assert_eq!(unrelated_after.points, unrelated_points);
assert!(model.message.contains("plot refresh failed"));
}
#[test]
fn save_as_new_pipeline_adds_output_curve_without_removing_other_curves() {
let mut model = model_with_two_experiments();
let unrelated_points = model
.plots
.iter()
.find(|curve| curve.experiment_id == "unrelated")
.unwrap()
.points
.clone();
model.apply_golden_pipeline("source", config()).unwrap();
assert!(
model
.series
.get_experiment_by_id("proceeded_source")
.is_ok()
);
assert!(model.plots.iter().any(|curve| {
curve.experiment_id == "proceeded_source" && !curve.points.is_empty()
}));
let unrelated_after = model
.plots
.iter()
.find(|curve| curve.experiment_id == "unrelated")
.unwrap();
assert_eq!(unrelated_after.points, unrelated_points);
assert!(model.message.contains("Golden Pipeline completed"));
}
}