use crate::Kinetics::experimental_kinetics::catalog::{
ArtifactHashProgress, CatalogArtifact, CatalogArtifactFile, CatalogArtifactPurpose,
CatalogExperiment, CatalogId, CatalogObjectKind, CatalogPublication,
CatalogPublicationSnapshot, CatalogSample, CatalogSeries, CatalogStore, CatalogStudy,
CatalogSubstance, CatalogThermalMode, LocalArtifactIntegrity, LocalArtifactResolution,
PublishedSeriesMember, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
ExperimentThermalMode, TGAExperiment,
};
use crate::Kinetics::experimental_kinetics::testing_mod::{
AdvancedTGAConfig, ExperimentMode, KineticModel, NoiseConfig, NoiseKind, SpikeModel,
};
use crate::gui::experimental_kinetics_gui::catalog_transfers::CatalogTransferUi;
use crate::gui::experimental_kinetics_gui::controller_buttons_and_panels::NewExperimentDialogState;
use crate::gui::experimental_kinetics_gui::gui_test::try_load_model_with_one_curve;
use crate::gui::experimental_kinetics_gui::help_view::{HelpDoc, HelpLanguage};
use crate::gui::experimental_kinetics_gui::model::PlotModel;
use crate::gui::experimental_kinetics_gui::settings::{CalibrationLine, Settings};
use log::{info, warn};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::Path;
use std::process::Command;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::{Arc, Mutex};
#[derive(Clone, Debug)]
pub(super) struct CatalogArtifactListing {
pub(super) artifact: CatalogArtifact,
pub(super) local_resolution: LocalArtifactResolution,
}
#[derive(Clone, Debug, Default)]
struct CatalogPublishUiProgress {
snapshot: ArtifactHashProgress,
cancellation_requested: bool,
committing: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CatalogPendingScope {
library_path: std::path::PathBuf,
library_id: Option<String>,
kind: CatalogObjectKind,
target_id: String,
}
impl CatalogPendingScope {
fn kind_label(&self) -> &'static str {
match &self.kind {
CatalogObjectKind::Experiment => "experiment",
CatalogObjectKind::Series => "series",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CatalogMembershipShrinkConfirmation {
library_path: std::path::PathBuf,
library_id: String,
series_id: String,
current_member_ids: Vec<String>,
removed_member_ids: Vec<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CatalogResultLevel {
#[default]
All,
Studies,
Series,
Experiments,
}
#[derive(Default)]
struct CatalogRawSourceDraft {
open: bool,
id: Option<CatalogId>,
display_name: String,
date: String,
sample: String,
instrument: String,
operator: String,
comment: String,
tags: String,
files: Vec<std::path::PathBuf>,
}
pub struct TestOptions {
pub(crate) show_settings_window: bool,
temp_k: String,
temp_b: String,
temp_instrument_name: String,
temp_operator_name: String,
temp_n_points: String,
temp_log_level: String,
temp_catalog_path: String,
catalog_status: Option<String>,
catalog_library_id: Option<String>,
catalog_loaded_path: Option<std::path::PathBuf>,
catalog_pending_file_formats: HashMap<std::path::PathBuf, String>,
catalog_membership_shrink_confirmation: Option<CatalogMembershipShrinkConfirmation>,
catalog_window_open: bool,
catalog_transfer_ui: CatalogTransferUi,
catalog_refresh_requested: bool,
catalog_series_name: String,
catalog_publish_kind: CatalogObjectKind,
catalog_experiment_identity: String,
catalog_entries: Vec<CatalogSeries>,
catalog_experiment_entries: Vec<CatalogExperiment>,
catalog_studies: Vec<CatalogStudy>,
catalog_substances: Vec<CatalogSubstance>,
catalog_samples: Vec<CatalogSample>,
catalog_study_substances: Vec<CatalogSubstance>,
catalog_study_series: Vec<CatalogSeries>,
catalog_contents_study_id: Option<CatalogId>,
catalog_study_id: Option<CatalogId>,
catalog_substance_id: Option<CatalogId>,
catalog_sample_id: Option<CatalogId>,
catalog_study_name: String,
catalog_study_description: String,
catalog_substance_name: String,
catalog_substance_formula: String,
catalog_substance_cas_number: String,
catalog_substance_inchi_key: String,
catalog_substance_description: String,
catalog_sample_name: String,
catalog_sample_batch: String,
catalog_sample_preparation_note: String,
catalog_publications: Vec<CatalogPublication>,
catalog_publication_index: HashMap<(CatalogObjectKind, CatalogId), Vec<usize>>,
catalog_artifacts: HashMap<CatalogId, CatalogArtifactListing>,
catalog_result_level: CatalogResultLevel,
catalog_publish_author: String,
catalog_publish_description: String,
catalog_pending_files: Vec<CatalogArtifactFile>,
catalog_pending_scope: Option<CatalogPendingScope>,
catalog_parent_publication: Option<CatalogId>,
catalog_raw_source: CatalogRawSourceDraft,
catalog_search: String,
catalog_method_filter: String,
catalog_origin_filter: String,
catalog_tag_filter: String,
catalog_thermal_filter: Option<CatalogThermalMode>,
catalog_temperature_min: String,
catalog_temperature_max: String,
catalog_heating_rate_min: String,
catalog_heating_rate_max: String,
catalog_date_from: String,
catalog_date_to: String,
catalog_sample_filter: Option<CatalogId>,
catalog_attachment_filter: Option<CatalogArtifactPurpose>,
catalog_show_publication_history: bool,
catalog_browse_study_filter: Option<CatalogId>,
catalog_browse_substance_filter: Option<CatalogId>,
catalog_study_series_ids: HashMap<CatalogId, HashSet<CatalogId>>,
catalog_study_substance_ids: HashMap<CatalogId, HashSet<CatalogId>>,
catalog_series_substance_ids: HashMap<CatalogId, CatalogId>,
catalog_experiment_series_ids: HashMap<CatalogId, HashSet<CatalogId>>,
catalog_experiment_substance_ids: HashMap<CatalogId, CatalogId>,
catalog_experiment_sample_ids: HashMap<CatalogId, CatalogId>,
catalog_metadata_identity: String,
catalog_comment: String,
catalog_tags: String,
catalog_publish_result: Option<
Receiver<
Result<
CatalogPublication,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>,
>,
>,
catalog_publish_progress: Option<Arc<Mutex<CatalogPublishUiProgress>>>,
catalog_verify_result: Option<
Receiver<
Result<
(CatalogId, LocalArtifactIntegrity),
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>,
>,
>,
catalog_verify_in_progress: Option<CatalogId>,
catalog_root_relink_result: Option<
Receiver<
Result<
(String, usize),
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>,
>,
>,
catalog_root_relink_in_progress: Option<String>,
catalog_integrity: HashMap<CatalogId, LocalArtifactIntegrity>,
catalog_publish_library_path: Option<std::path::PathBuf>,
catalog_publish_kind_in_progress: Option<CatalogObjectKind>,
catalog_raw_source_in_progress: bool,
#[cfg(test)]
pub(crate) test_catalog_directory: Option<std::path::PathBuf>,
#[cfg(test)]
pub(crate) test_catalog_files: Option<Vec<std::path::PathBuf>>,
#[cfg(test)]
pub(crate) test_catalog_relink_directory: Option<std::path::PathBuf>,
#[cfg(test)]
pub(crate) test_catalog_manifest_path: Option<std::path::PathBuf>,
pub(crate) show_help_window: bool,
pub(crate) help_lang: HelpLanguage,
pub(crate) parsed_help: HelpDoc,
pub(crate) help_error: Option<String>,
pub(crate) help_status: Option<String>,
pub(crate) help_search_query: String,
pub(crate) help_selected_section: Option<usize>,
pub(crate) help_edit_mode: bool,
pub(crate) help_editor_buffer: String,
pub(crate) help_expanded_sections: std::collections::HashSet<usize>,
pub(crate) show_logs_window: bool,
pub(crate) confirm_load_testing_data: bool,
pub(crate) show_synthetic_data: bool,
syn_n_points: String,
syn_dt: String,
syn_seed: String,
syn_mode: usize,
syn_iso_temperatures: String, syn_ni_t0: String,
syn_ni_heating_rates: String,
syn_kmodel: usize,
syn_m0: String,
syn_k0: String,
syn_e: String,
syn_r: String,
syn_m01: String,
syn_k01: String,
syn_e1: String,
syn_m02: String,
syn_k02: String,
syn_e2: String,
syn_r2: String,
syn_mass_noise_enabled: bool,
syn_mass_noise_kind: usize, syn_mass_sigma: String,
syn_mass_ampl: String,
syn_mass_slope: String,
syn_temp_noise_enabled: bool,
syn_temp_noise_kind: usize,
syn_temp_sigma: String,
syn_temp_ampl: String,
syn_temp_slope: String,
syn_spikes_enabled: bool,
syn_spike_prob: String,
syn_spike_ampl: String,
syn_status: Option<String>,
}
impl Default for TestOptions {
fn default() -> Self {
Self {
show_settings_window: false,
temp_k: String::new(),
temp_b: String::new(),
temp_instrument_name: String::new(),
temp_operator_name: String::new(),
temp_n_points: String::new(),
temp_log_level: String::new(),
temp_catalog_path: String::new(),
catalog_status: None,
catalog_library_id: None,
catalog_loaded_path: None,
catalog_pending_file_formats: HashMap::new(),
catalog_membership_shrink_confirmation: None,
catalog_window_open: false,
catalog_transfer_ui: CatalogTransferUi::default(),
catalog_refresh_requested: false,
catalog_series_name: String::new(),
catalog_publish_kind: CatalogObjectKind::Series,
catalog_experiment_identity: String::new(),
catalog_entries: Vec::new(),
catalog_experiment_entries: Vec::new(),
catalog_studies: Vec::new(),
catalog_substances: Vec::new(),
catalog_samples: Vec::new(),
catalog_study_substances: Vec::new(),
catalog_study_series: Vec::new(),
catalog_contents_study_id: None,
catalog_study_id: None,
catalog_substance_id: None,
catalog_sample_id: None,
catalog_study_name: String::new(),
catalog_study_description: String::new(),
catalog_substance_name: String::new(),
catalog_substance_formula: String::new(),
catalog_substance_cas_number: String::new(),
catalog_substance_inchi_key: String::new(),
catalog_substance_description: String::new(),
catalog_sample_name: String::new(),
catalog_sample_batch: String::new(),
catalog_sample_preparation_note: String::new(),
catalog_publications: Vec::new(),
catalog_publication_index: HashMap::new(),
catalog_artifacts: HashMap::new(),
catalog_result_level: CatalogResultLevel::All,
catalog_publish_author: String::new(),
catalog_publish_description: String::new(),
catalog_pending_files: Vec::new(),
catalog_pending_scope: None,
catalog_parent_publication: None,
catalog_raw_source: CatalogRawSourceDraft::default(),
catalog_search: String::new(),
catalog_method_filter: String::new(),
catalog_origin_filter: String::new(),
catalog_tag_filter: String::new(),
catalog_thermal_filter: None,
catalog_temperature_min: String::new(),
catalog_temperature_max: String::new(),
catalog_heating_rate_min: String::new(),
catalog_heating_rate_max: String::new(),
catalog_date_from: String::new(),
catalog_date_to: String::new(),
catalog_sample_filter: None,
catalog_attachment_filter: None,
catalog_show_publication_history: false,
catalog_browse_study_filter: None,
catalog_browse_substance_filter: None,
catalog_study_series_ids: HashMap::new(),
catalog_study_substance_ids: HashMap::new(),
catalog_series_substance_ids: HashMap::new(),
catalog_experiment_series_ids: HashMap::new(),
catalog_experiment_substance_ids: HashMap::new(),
catalog_experiment_sample_ids: HashMap::new(),
catalog_metadata_identity: String::new(),
catalog_comment: String::new(),
catalog_tags: String::new(),
catalog_publish_result: None,
catalog_publish_progress: None,
catalog_verify_result: None,
catalog_verify_in_progress: None,
catalog_root_relink_result: None,
catalog_root_relink_in_progress: None,
catalog_integrity: HashMap::new(),
catalog_publish_library_path: None,
catalog_publish_kind_in_progress: None,
catalog_raw_source_in_progress: false,
#[cfg(test)]
test_catalog_directory: None,
#[cfg(test)]
test_catalog_files: None,
#[cfg(test)]
test_catalog_relink_directory: None,
#[cfg(test)]
test_catalog_manifest_path: None,
show_help_window: false,
help_lang: HelpLanguage::Eng,
parsed_help: HelpDoc::default(),
help_error: None,
help_status: None,
help_search_query: String::new(),
help_selected_section: None,
help_edit_mode: false,
help_editor_buffer: String::new(),
help_expanded_sections: HashSet::new(),
show_logs_window: false,
confirm_load_testing_data: false,
show_synthetic_data: false,
syn_n_points: "70000".to_string(),
syn_dt: "0.1".to_string(),
syn_seed: "42".to_string(),
syn_mode: 1,
syn_iso_temperatures: "400.0".to_string(),
syn_ni_t0: "400.0".to_string(),
syn_ni_heating_rates: "1.0, 2.0, 3.0".to_string(),
syn_kmodel: 0,
syn_m0: "100.0".to_string(),
syn_k0: "1e6".to_string(),
syn_e: "80000.0".to_string(),
syn_r: "8.314".to_string(),
syn_m01: "50.0".to_string(),
syn_k01: "1e6".to_string(),
syn_e1: "90000.0".to_string(),
syn_m02: "50.0".to_string(),
syn_k02: "1e3".to_string(),
syn_e2: "60000.0".to_string(),
syn_r2: "8.314".to_string(),
syn_mass_noise_enabled: false,
syn_mass_noise_kind: 0,
syn_mass_sigma: "5.0".to_string(),
syn_mass_ampl: "1.0".to_string(),
syn_mass_slope: "0.0".to_string(),
syn_temp_noise_enabled: false,
syn_temp_noise_kind: 0,
syn_temp_sigma: "0.1".to_string(),
syn_temp_ampl: "0.0".to_string(),
syn_temp_slope: "0.0".to_string(),
syn_spikes_enabled: false,
syn_spike_prob: "0.01".to_string(),
syn_spike_ampl: "1.0".to_string(),
syn_status: None,
}
}
}
impl TestOptions {
fn load_catalog_metadata_draft(&mut self, _model: &PlotModel) {
let selected = self
.catalog_experiment_entries
.iter()
.find(|entry| entry.source_identity == self.catalog_experiment_identity);
if let Some(entry) = selected {
self.catalog_comment = entry.comment.clone().unwrap_or_default();
self.catalog_tags = entry.tags.join(", ");
} else {
self.catalog_comment.clear();
self.catalog_tags.clear();
}
self.catalog_metadata_identity = self.catalog_experiment_identity.clone();
}
fn catalog_experiment_snapshot(
&self,
experiment: &TGAExperiment,
existing: Option<CatalogExperiment>,
) -> Result<CatalogExperiment, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError>
{
let identity = experiment.meta.identity().to_string();
let id = CatalogId::parse(identity.clone())
.map_err(crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from)?;
let thermal_mode = match experiment.meta.resolved_thermal_mode() {
ExperimentThermalMode::Isothermal => Some(CatalogThermalMode::Isothermal),
ExperimentThermalMode::NonIsothermal => Some(CatalogThermalMode::NonIsothermal),
ExperimentThermalMode::Unspecified => Some(CatalogThermalMode::Unspecified),
};
let is_selected = identity == self.catalog_experiment_identity;
let acquisition = &experiment.meta.acquisition;
let (comment, tags) = if is_selected {
(
optional_trimmed(&self.catalog_comment),
parse_catalog_tags(&self.catalog_tags),
)
} else if let Some(existing) = existing {
(existing.comment, existing.tags)
} else {
(None, Vec::new())
};
let snapshot = CatalogExperiment {
id,
source_identity: identity,
display_name: experiment.meta.id.clone(),
source_kind: crate::Kinetics::experimental_kinetics::catalog::source_kind_from_lineage(
experiment.dataset.data_lineage(),
),
date: acquisition.measurement_date.map(|date| date.to_string()),
sample: acquisition.sample_description.clone(),
instrument: acquisition.instrument.clone(),
operator: acquisition.operator.clone(),
thermal_mode,
temperature_k: experiment.meta.isothermal_temperature,
heating_rate_k_per_min: experiment.meta.heating_rate,
comment,
tags,
};
snapshot.validate()?;
Ok(snapshot)
}
fn start_catalog_publication<F>(
&mut self,
library_path: std::path::PathBuf,
kind: CatalogObjectKind,
operation: F,
) where
F: FnOnce(
&mut CatalogStore,
&mut dyn FnMut(ArtifactHashProgress) -> bool,
) -> Result<
CatalogPublication,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
> + Send
+ 'static,
{
if self.catalog_publish_result.is_some() {
self.catalog_status = Some("A catalog publication is already running.".into());
return;
}
let expected_library_id = match CatalogStore::open_existing(&library_path) {
Ok(store) => store.library_id().to_owned(),
Err(error) => {
self.catalog_status = Some(format!("Could not open publication library: {error}"));
return;
}
};
let (sender, receiver) = mpsc::channel();
let progress = Arc::new(Mutex::new(CatalogPublishUiProgress::default()));
let worker_path = library_path.clone();
let worker_progress = Arc::clone(&progress);
let spawn = std::thread::Builder::new()
.name("kithe-catalog-publish".into())
.spawn(move || {
let result = CatalogStore::open_existing(worker_path).and_then(|mut store| {
store.ensure_library_identity(&expected_library_id)?;
let mut report = |snapshot: ArtifactHashProgress| {
if let Ok(mut current) = worker_progress.lock() {
if current.cancellation_requested {
return false;
}
current.committing =
snapshot.file_name == "Committing catalog metadata";
current.snapshot = snapshot;
true
} else {
false
}
};
operation(&mut store, &mut report)
});
let _ = sender.send(result);
});
match spawn {
Ok(_) => {
self.catalog_publish_result = Some(receiver);
self.catalog_publish_progress = Some(progress);
self.catalog_publish_library_path = Some(library_path);
self.catalog_publish_kind_in_progress = Some(kind);
self.catalog_status = Some(
"Local publication started. Files remain at their original locations.".into(),
);
}
Err(error) => {
warn!("Could not start catalog publication worker: {error}");
self.catalog_status = Some(format!("Could not start publication: {error}"));
}
}
}
fn poll_catalog_publication(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
let completed = match self.catalog_publish_result.as_ref() {
Some(receiver) => match receiver.try_recv() {
Ok(result) => Some(Some(result)),
Err(TryRecvError::Disconnected) => Some(None),
Err(TryRecvError::Empty) => None,
},
None => None,
};
let Some(completed) = completed else {
return;
};
self.catalog_publish_result = None;
self.catalog_publish_progress = None;
let library_path = self.catalog_publish_library_path.take();
let kind = self.catalog_publish_kind_in_progress.take();
let raw_source = std::mem::take(&mut self.catalog_raw_source_in_progress);
match completed {
Some(Ok(publication)) => {
if raw_source {
self.catalog_raw_source = CatalogRawSourceDraft::default();
} else {
self.catalog_pending_files.clear();
self.catalog_pending_file_formats.clear();
self.catalog_pending_scope = None;
self.catalog_parent_publication = None;
}
let changed_paths = library_path
.as_deref()
.map(|path| self.changed_paths_from_earlier_publications(path, &publication));
let normal_status = format!(
"Published local {} snapshot {} with {} external file references. No files were copied.",
match kind {
Some(CatalogObjectKind::Experiment) => "experiment",
_ => "series",
},
publication.id.as_str(),
publication.artifact_ids.len()
);
self.catalog_status = Some(match changed_paths {
Some(Ok(paths)) if !paths.is_empty() => format!(
"{normal_status} WARNING: {} previously published file path(s) now have a different checksum: {}. Earlier file contents are not recoverable from the catalog.",
paths.len(),
paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ")
),
Some(Err(error)) => {
warn!("Could not compare publication paths with prior snapshots: {error}");
format!(
"{normal_status} Warning: could not compare against older file references: {error}"
)
}
_ => normal_status,
});
let warning_status = self
.catalog_status
.as_deref()
.filter(|status| status.contains("WARNING:"))
.map(str::to_owned);
if let Some(status) = warning_status.as_deref() {
let _ = model.push_message(status);
}
if model.settings.catalog().local_library_path == library_path {
self.refresh_catalog(library_path.as_deref());
if warning_status.is_some() {
self.catalog_status = warning_status;
}
}
info!(
"Local catalog publication completed: {}",
publication.id.as_str()
);
}
Some(Err(error)) => {
warn!("Local catalog publication failed: {error}");
if matches!(error, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::PublicationCancelled) {
self.catalog_status = Some("Publication cancelled; no catalog records were written.".into());
let _ = model.push_message("Catalog publication cancelled before database commit; no records were written.");
} else {
self.catalog_status = Some(format!("Could not publish snapshot: {error}"));
let _ = model.push_message(&format!("Catalog publication failed: {error}"));
}
if raw_source {
self.catalog_raw_source.open = true;
}
}
None => {
self.catalog_status = Some(
"Catalog publication worker stopped before returning a result. No success was recorded; refresh the catalog before retrying.".into(),
);
if raw_source {
self.catalog_raw_source.open = true;
}
let _ = model.push_message("Catalog publication stopped before completion.");
}
}
ctx.request_repaint();
}
fn changed_paths_from_earlier_publications(
&self,
library_path: &Path,
publication: &CatalogPublication,
) -> Result<
Vec<std::path::PathBuf>,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
> {
let store = CatalogStore::open_existing(library_path)?;
let mut changed_paths = Vec::new();
for artifact_id in &publication.artifact_ids {
let Some(current_artifact) = store.get_artifact(artifact_id)? else {
continue;
};
let LocalArtifactResolution::Available(current_path) =
store.resolve_local_artifact(artifact_id)?
else {
continue;
};
let has_prior_different_checksum = self.catalog_artifacts.values().any(|previous| {
previous.artifact.sha256 != current_artifact.sha256
&& previous
.local_resolution
.eq(&LocalArtifactResolution::Available(current_path.clone()))
});
if has_prior_different_checksum && !changed_paths.contains(¤t_path) {
changed_paths.push(current_path);
}
}
Ok(changed_paths)
}
fn start_catalog_verification(&mut self, id: CatalogId, library_path: std::path::PathBuf) {
if self.catalog_verify_result.is_some() {
return;
}
let (sender, receiver) = mpsc::channel();
let worker_id = id.clone();
let spawn = std::thread::Builder::new()
.name("kithe-catalog-verify".into())
.spawn(move || {
let result = CatalogStore::open_existing(library_path)
.and_then(|store| store.verify_local_artifact(&worker_id))
.map(|integrity| (worker_id, integrity));
let _ = sender.send(result);
});
match spawn {
Ok(_) => {
self.catalog_verify_result = Some(receiver);
self.catalog_verify_in_progress = Some(id.clone());
self.catalog_integrity.remove(&id);
self.catalog_status = Some(format!("Verifying attachment {}...", id.as_str()));
}
Err(error) => {
let message = format!("Could not start checksum verification: {error}");
warn!("{message}");
self.catalog_status = Some(message);
}
}
}
fn poll_catalog_verification(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
let completed = match self.catalog_verify_result.as_ref() {
Some(receiver) => match receiver.try_recv() {
Ok(result) => Some(Some(result)),
Err(TryRecvError::Disconnected) => Some(None),
Err(TryRecvError::Empty) => None,
},
None => None,
};
let Some(completed) = completed else {
return;
};
self.catalog_verify_result = None;
self.catalog_verify_in_progress = None;
match completed {
Some(Ok((id, integrity))) => {
let message = local_integrity_status(&integrity);
if matches!(integrity, LocalArtifactIntegrity::Modified { .. }) {
warn!(
"Catalog attachment integrity check failed for {}: {message}",
id.as_str()
);
let _ =
model.push_message(&format!("Catalog attachment was modified: {message}"));
} else {
info!(
"Catalog attachment integrity check for {}: {message}",
id.as_str()
);
}
self.catalog_integrity.insert(id, integrity);
self.catalog_status = Some(message);
}
Some(Err(error)) => {
warn!("Catalog checksum verification failed: {error}");
let message = format!("Could not verify catalog attachment: {error}");
self.catalog_status = Some(message.clone());
let _ = model.push_message(&message);
}
None => {
let message = "Checksum verification worker stopped before returning a result.";
warn!("{message}");
self.catalog_status = Some(message.into());
let _ = model.push_message(message);
}
}
ctx.request_repaint();
}
fn start_catalog_root_relink(
&mut self,
root_id: String,
new_root: std::path::PathBuf,
library_path: std::path::PathBuf,
) {
if self.catalog_root_relink_result.is_some() {
return;
}
let (sender, receiver) = mpsc::channel();
let worker_root_id = root_id.clone();
let spawn = std::thread::Builder::new()
.name("kithe-catalog-relink".into())
.spawn(move || {
let result = CatalogStore::open_existing(library_path).and_then(|mut store| {
store
.relink_local_root(&worker_root_id, new_root)
.map(|count| (worker_root_id, count))
});
let _ = sender.send(result);
});
match spawn {
Ok(_) => {
self.catalog_root_relink_result = Some(receiver);
self.catalog_root_relink_in_progress = Some(root_id);
self.catalog_status = Some(
"Checking every attachment in the selected folder before relinking...".into(),
);
}
Err(error) => {
let message = format!("Could not start catalog folder relink: {error}");
warn!("{message}");
self.catalog_status = Some(message.clone());
}
}
}
fn poll_catalog_root_relink(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
let completed = match self.catalog_root_relink_result.as_ref() {
Some(receiver) => match receiver.try_recv() {
Ok(result) => Some(Some(result)),
Err(TryRecvError::Disconnected) => Some(None),
Err(TryRecvError::Empty) => None,
},
None => None,
};
let Some(completed) = completed else {
return;
};
self.catalog_root_relink_result = None;
self.catalog_root_relink_in_progress = None;
match completed {
Some(Ok((root_id, count))) => {
self.catalog_status = Some(format!(
"Relinked {count} catalog attachment(s) after verifying their saved checksums."
));
self.catalog_integrity.clear();
self.catalog_refresh_requested = true;
info!("Relinked local catalog artifact root {root_id} ({count} attachments)");
}
Some(Err(error)) => {
let message = format!("Could not relink catalog folder: {error}");
warn!("{message}");
self.catalog_status = Some(message.clone());
let _ = model.push_message(&message);
}
None => {
let message = "Catalog folder relink stopped before verification completed.";
warn!("{message}");
self.catalog_status = Some(message.into());
let _ = model.push_message(message);
}
}
ctx.request_repaint();
}
pub fn open_settings_window(&mut self) {
self.show_settings_window = true;
}
pub fn open_catalog_window(&mut self) {
self.catalog_window_open = true;
self.catalog_refresh_requested = true;
}
pub fn open_catalog_browser(&mut self) {
self.catalog_window_open = true;
self.catalog_refresh_requested = true;
}
pub fn show_catalog_window(
&mut self,
ctx: &egui::Context,
model: &mut PlotModel,
document_dialog: &mut NewExperimentDialogState,
) {
self.show_catalog_window_with_plot_editor(ctx, model, document_dialog, None);
}
pub fn show_catalog_window_with_plot_editor(
&mut self,
ctx: &egui::Context,
model: &mut PlotModel,
document_dialog: &mut NewExperimentDialogState,
mut plot_editor: Option<
&mut crate::gui::experimental_kinetics_gui::kitheplot_wrapper::KiThePlotWindowState,
>,
) {
if !self.catalog_window_open {
return;
}
self.poll_catalog_publication(ctx, model);
self.poll_catalog_verification(ctx, model);
self.poll_catalog_root_relink(ctx, model);
let configured_library_path = model.settings.catalog().local_library_path.clone();
if self.catalog_loaded_path != configured_library_path {
self.catalog_refresh_requested = true;
if self.catalog_loaded_path.is_some() {
self.catalog_metadata_identity.clear();
self.catalog_membership_shrink_confirmation = None;
}
}
if self.catalog_refresh_requested {
self.refresh_catalog(configured_library_path.as_deref());
self.catalog_refresh_requested = false;
}
if self.catalog_contents_study_id != self.catalog_study_id {
let path = model.settings.catalog().local_library_path.clone();
self.refresh_selected_study(path.as_deref());
}
if !model
.series
.experiments()
.iter()
.any(|experiment| experiment.meta.identity() == self.catalog_experiment_identity)
{
self.catalog_experiment_identity = model
.series
.experiments()
.first()
.map(|experiment| experiment.meta.identity().to_string())
.unwrap_or_default();
}
if self.catalog_metadata_identity != self.catalog_experiment_identity {
self.load_catalog_metadata_draft(model);
}
let mut open = self.catalog_window_open;
let mut close_catalog = false;
let mut verify_requested = None;
let mut relink_requested = None;
let mut browse_navigation = None;
let library_path_for_verify = model.settings.catalog().local_library_path.clone();
egui::Window::new("Catalog")
.open(&mut open)
.resizable(true)
.vscroll(true)
.default_size([560.0, 480.0])
.show(ctx, |ui| {
let path = model.settings.catalog().local_library_path.clone();
match path.as_ref() {
Some(path) => {
ui.label(format!("Local library: {}", path.display()));
if let Some(library_id) = &self.catalog_library_id {
ui.small(format!("Library ID: {library_id}"));
}
}
None => {
ui.label(
"No local library selected. Choose one in Test Options > TGA Settings.",
);
}
}
ui.separator();
egui::CollapsingHeader::new("Research studies, substances, and samples")
.id_salt("catalog_research_entities")
.default_open(false)
.show(ui, |ui| {
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
ui.strong("Research studies, substances, and samples");
ui.label("A study groups related substances. Each kinetic series belongs to one substance; it remains a separate analysis input.");
ui.horizontal(|ui| {
ui.label("Study:");
egui::ComboBox::from_id_salt("catalog_study_selection")
.selected_text(self.catalog_study_id.as_ref()
.and_then(|id| self.catalog_studies.iter().find(|item| &item.id == id))
.map(|item| item.display_name.as_str()).unwrap_or("Select study"))
.show_ui(ui, |ui| {
for study in &self.catalog_studies {
ui.selectable_value(
&mut self.catalog_study_id,
Some(study.id.clone()),
&study.display_name,
);
}
});
});
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.catalog_study_name)
.hint_text("Study name"))
.on_hover_text("Name for a research campaign grouping related substances.");
if ui.add_enabled(path.is_some() && !self.catalog_study_name.trim().is_empty(), egui::Button::new("Create study")).clicked() {
self.create_catalog_study(path.as_deref());
}
});
ui.horizontal(|ui| {
ui.label("Study description:");
ui.text_edit_singleline(&mut self.catalog_study_description);
});
ui.horizontal(|ui| {
ui.label("Substance:");
egui::ComboBox::from_id_salt("catalog_substance_selection")
.selected_text(self.catalog_substance_id.as_ref()
.and_then(|id| self.catalog_substances.iter().find(|item| &item.id == id))
.map(|item| item.display_name.as_str()).unwrap_or("Select substance"))
.show_ui(ui, |ui| {
for substance in &self.catalog_substances {
ui.selectable_value(
&mut self.catalog_substance_id,
Some(substance.id.clone()),
&substance.display_name,
);
}
});
if ui.add_enabled(path.is_some() && self.catalog_study_id.is_some() && self.catalog_substance_id.is_some(), egui::Button::new("Add substance to study")).clicked() {
self.add_catalog_substance_to_study(path.as_deref());
}
});
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.catalog_substance_name)
.hint_text("Chemical name"))
.on_hover_text("Chemical identity, not a prepared batch/sample.");
ui.add(egui::TextEdit::singleline(&mut self.catalog_substance_formula)
.hint_text("Formula (optional)"));
if ui.add_enabled(path.is_some() && !self.catalog_substance_name.trim().is_empty(), egui::Button::new("Create substance")).clicked() {
self.create_catalog_substance(path.as_deref());
}
});
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.catalog_substance_cas_number)
.hint_text("CAS number (optional)"));
ui.add(egui::TextEdit::singleline(&mut self.catalog_substance_inchi_key)
.hint_text("InChIKey (optional)"));
});
ui.horizontal(|ui| {
ui.label("Substance note:");
ui.text_edit_singleline(&mut self.catalog_substance_description);
});
let current_series_id = CatalogId::parse(model.series.identity().to_string()).ok();
let current_series_registered = current_series_id.as_ref().is_some_and(|id| self.catalog_entries.iter().any(|entry| &entry.id == id));
ui.horizontal(|ui| {
if ui.add_enabled(path.is_some() && current_series_registered && self.catalog_substance_id.is_some(), egui::Button::new("Assign current series to substance")).clicked() {
self.assign_current_series_substance(path.as_deref(), model);
}
if ui.add_enabled(path.is_some() && current_series_registered && self.catalog_study_id.is_some(), egui::Button::new("Add current series to study")).clicked() {
self.add_current_series_to_study(path.as_deref(), model);
}
});
if let Some(study_id) = self.catalog_study_id.clone() {
let studies = &self.catalog_studies;
if let Some(study) = studies.iter().find(|study| study.id == study_id) {
ui.small(format!("Selected study: {}", study.display_name));
if let Some(description) = study.description.as_deref() {
ui.small(description);
}
}
self.show_catalog_study_contents(ui);
let can_export_manifest = path.is_some()
&& self.catalog_studies.iter().any(|study| study.id == study_id);
if ui
.add_enabled(
can_export_manifest,
egui::Button::new("Export study manifest..."),
)
.on_hover_text("Exports study, substance, series, membership, and publication references as JSON. Numerical data files are not included or copied.")
.clicked()
{
#[cfg(test)]
let destination = self.test_catalog_manifest_path.take();
#[cfg(not(test))]
let destination = rfd::FileDialog::new()
.set_file_name("study-manifest.json")
.add_filter("JSON manifest", &["json"])
.save_file();
if let Some(destination) = destination {
self.export_catalog_study_manifest(
path.as_deref(),
&study_id,
&destination,
);
}
}
}
ui.separator();
ui.label("Prepared sample for the selected experiment");
let samples_for_substance: Vec<_> = self.catalog_samples.iter()
.filter(|sample| Some(&sample.substance_id) == self.catalog_substance_id.as_ref())
.cloned()
.collect();
ui.horizontal(|ui| {
ui.label("Existing sample:");
egui::ComboBox::from_id_salt("catalog_sample_selection")
.selected_text(self.catalog_sample_id.as_ref()
.and_then(|id| samples_for_substance.iter().find(|sample| &sample.id == id))
.map(|sample| sample.display_name.as_str()).unwrap_or("Select sample"))
.show_ui(ui, |ui| {
for sample in &samples_for_substance {
ui.selectable_value(
&mut self.catalog_sample_id,
Some(sample.id.clone()),
&sample.display_name,
);
}
});
let can_assign_existing = path.is_some()
&& self.catalog_sample_id.as_ref().is_some_and(|id| samples_for_substance.iter().any(|sample| &sample.id == id))
&& self.catalog_experiment_entries.iter().any(|entry| entry.source_identity == self.catalog_experiment_identity);
if ui.add_enabled(can_assign_existing, egui::Button::new("Assign selected sample")).clicked() {
self.assign_existing_catalog_sample(path.as_deref(), model);
}
});
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.catalog_sample_name)
.hint_text("Sample / batch name"));
ui.add(egui::TextEdit::singleline(&mut self.catalog_sample_batch)
.hint_text("Batch label (optional)"));
let can_assign_sample = path.is_some()
&& self.catalog_substance_id.is_some()
&& self.catalog_experiment_entries.iter().any(|entry| entry.source_identity == self.catalog_experiment_identity);
if ui.add_enabled(can_assign_sample && !self.catalog_sample_name.trim().is_empty(), egui::Button::new("Create and assign sample")).clicked() {
self.create_and_assign_catalog_sample(path.as_deref(), model);
}
});
ui.horizontal(|ui| {
ui.label("Preparation note:");
ui.text_edit_singleline(&mut self.catalog_sample_preparation_note);
});
if !current_series_registered {
ui.small("Register the current series first to assign it to a substance or study.");
}
});
});
ui.separator();
ui.horizontal(|ui| {
ui.label("Series name:");
ui.text_edit_singleline(&mut self.catalog_series_name);
});
let can_register = path.is_some()
&& !model.series.is_empty()
&& self.catalog_publish_result.is_none();
let selected_current_experiment_name = model
.series
.experiments()
.iter()
.find(|experiment| {
experiment.meta.identity() == self.catalog_experiment_identity
})
.map(|experiment| experiment.meta.id.clone());
ui.horizontal(|ui| {
ui.label("Experiment:");
egui::ComboBox::from_id_salt("catalog_current_experiment")
.selected_text(
selected_current_experiment_name
.as_deref()
.unwrap_or("No experiment"),
)
.show_ui(ui, |ui| {
for experiment in model.series.experiments() {
ui.selectable_value(
&mut self.catalog_experiment_identity,
experiment.meta.identity().to_string(),
&experiment.meta.id,
);
}
});
});
ui.collapsing("Selected experiment metadata", |ui| {
let experiment = model
.series
.experiments()
.iter()
.find(|experiment| {
experiment.meta.identity() == self.catalog_experiment_identity
});
let origin = experiment
.map(|experiment| {
crate::Kinetics::experimental_kinetics::catalog::source_kind_from_lineage(
experiment.dataset.data_lineage(),
)
})
.unwrap_or(SourceKind::Unknown);
ui.label(format!(
"Data origin: {} (derived from row lineage)",
source_kind_label(&origin)
));
if let Some(experiment) = experiment {
let acquisition = &experiment.meta.acquisition;
ui.label(format!(
"Measurement date: {}",
acquisition
.measurement_date
.map(|date| date.to_string())
.unwrap_or_else(|| "not set".into())
));
ui.label(format!(
"Measurement time: {}",
acquisition
.measurement_time
.map(|time| time.format("%H:%M:%S").to_string())
.unwrap_or_else(|| "not set".into())
));
ui.label(format!(
"Sample description: {}",
acquisition.sample_description.as_deref().unwrap_or("not set")
));
ui.label(format!(
"Initial sample mass: {}",
acquisition
.initial_sample_mass
.map(|mass| {
let unit = match mass.unit {
crate::Kinetics::experimental_kinetics::experiment_series_main::SampleMassUnit::Gram => "g",
crate::Kinetics::experimental_kinetics::experiment_series_main::SampleMassUnit::Milligram => "mg",
};
format!("{} {unit}", mass.value)
})
.unwrap_or_else(|| "not set".into())
));
ui.label(format!(
"Instrument: {}",
acquisition.instrument.as_deref().unwrap_or("not set")
));
ui.label(format!(
"Operator: {}",
acquisition.operator.as_deref().unwrap_or("not set")
));
}
ui.small("Acquisition metadata comes from the typed experiment. Edit it in Column Manager; registration will not create a second conflicting copy.");
ui.horizontal(|ui| {
ui.label("Tags (comma-separated):");
ui.text_edit_singleline(&mut self.catalog_tags);
});
ui.label("Catalog-only note:");
ui.text_edit_multiline(&mut self.catalog_comment);
ui.small("Tags and this note are stored only in the catalog; they do not alter the typed experiment.");
});
ui.horizontal(|ui| {
if ui
.add_enabled(can_register, egui::Button::new("Register Current Series"))
.clicked()
{
self.register_current_series(model, path.as_deref(), false);
}
if ui
.add_enabled(
can_register && selected_current_experiment_name.is_some(),
egui::Button::new("Register Selected Experiment"),
)
.clicked()
{
self.register_current_experiment(
model,
path.as_deref(),
self.catalog_experiment_identity.clone(),
);
}
});
if let Some(confirmation) = self.catalog_membership_shrink_confirmation.clone() {
ui.group(|ui| {
ui.strong("Confirm series membership change");
ui.small(format!(
"Library {} | series {}",
confirmation.library_id, confirmation.series_id
));
ui.label(format!(
"Registering this series will remove {} experiment(s) from its catalog membership:",
confirmation.removed_member_ids.len()
));
ui.label(confirmation.removed_member_ids.join(", "));
ui.horizontal(|ui| {
if ui.button("Confirm and register series").clicked() {
self.register_current_series(model, path.as_deref(), true);
}
if ui.button("Cancel").clicked() {
self.catalog_membership_shrink_confirmation = None;
}
});
});
}
if ui
.add_enabled(
path.is_some() && self.catalog_publish_result.is_none(),
egui::Button::new("Register raw source..."),
)
.clicked()
{
if self.catalog_raw_source.id.is_none() {
self.catalog_raw_source.id = Some(CatalogId::new());
}
self.catalog_raw_source.open = true;
}
ui.add_enabled_ui(self.catalog_publish_result.is_none(), |ui| {
ui.collapsing("Publish snapshot...", |ui| {
egui::ComboBox::from_label("Publication target")
.selected_text(match self.catalog_publish_kind {
CatalogObjectKind::Experiment => "Single experiment",
CatalogObjectKind::Series => "Whole series",
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.catalog_publish_kind,
CatalogObjectKind::Series,
"Whole series",
);
ui.selectable_value(
&mut self.catalog_publish_kind,
CatalogObjectKind::Experiment,
"Single experiment",
);
});
match self.catalog_publish_kind {
CatalogObjectKind::Series => {
ui.small(format!(
"Target series ID: {} ({} experiments)",
model.series.identity(),
model.series.len()
));
}
CatalogObjectKind::Experiment => {
if let Some(experiment) = model
.series
.experiments()
.iter()
.find(|experiment| {
experiment.meta.identity() == self.catalog_experiment_identity
})
{
ui.small(format!(
"Target experiment ID: {}",
experiment.meta.identity()
));
} else {
ui.colored_label(
egui::Color32::YELLOW,
"No current experiment is available to publish.",
);
}
}
}
ui.label("Creates an immutable metadata snapshot. Selected files are referenced, not copied.");
ui.horizontal(|ui| {
ui.label("Author:");
let response = ui.text_edit_singleline(&mut self.catalog_publish_author);
if response.changed() && self.catalog_pending_scope.is_none() {
self.catalog_pending_scope = path.as_ref().map(|library_path| {
CatalogPendingScope {
library_path: library_path.clone(),
library_id: self.catalog_library_id.clone(),
kind: self.catalog_publish_kind,
target_id: match self.catalog_publish_kind {
CatalogObjectKind::Series => {
model.series.identity().to_string()
}
CatalogObjectKind::Experiment => {
self.catalog_experiment_identity.clone()
}
},
}
});
}
});
ui.label("Publication description / interpretation:");
let description_response =
ui.text_edit_multiline(&mut self.catalog_publish_description);
let active_target_id = match self.catalog_publish_kind {
CatalogObjectKind::Series => model.series.identity().to_string(),
CatalogObjectKind::Experiment => self.catalog_experiment_identity.clone(),
};
let active_scope = path.as_ref().map(|library_path| CatalogPendingScope {
library_path: library_path.clone(),
library_id: self.catalog_library_id.clone(),
kind: self.catalog_publish_kind,
target_id: active_target_id,
});
if description_response.changed() && self.catalog_pending_scope.is_none() {
self.catalog_pending_scope = active_scope.clone();
}
let has_publication_draft = !self.catalog_pending_files.is_empty()
|| !self.catalog_publish_author.trim().is_empty()
|| !self.catalog_publish_description.trim().is_empty()
|| self.catalog_parent_publication.is_some();
if has_publication_draft && self.catalog_pending_scope.is_none() {
self.catalog_pending_scope = active_scope.clone();
}
if !has_publication_draft {
self.catalog_pending_scope = None;
}
let pending_scope_mismatch = has_publication_draft
&& self.catalog_pending_scope.as_ref() != active_scope.as_ref();
if pending_scope_mismatch {
ui.colored_label(
egui::Color32::YELLOW,
"This publication draft belongs to another library or target. Files, author, description, and parent link will not be published here until you explicitly move the entire draft.",
);
if let Some(scope) = &self.catalog_pending_scope {
ui.small(format!(
"Draft target: {} {} in {}",
scope.kind_label(),
scope.target_id,
scope.library_path.display()
));
}
if ui.button("Move entire publication draft to current target").clicked() {
self.catalog_pending_scope = active_scope.clone();
}
}
if ui
.add_enabled(!pending_scope_mismatch, egui::Button::new("Add files..."))
.clicked()
{
#[cfg(test)]
let selected = self.test_catalog_files.take();
#[cfg(not(test))]
let selected = rfd::FileDialog::new().pick_files();
if let Some(paths) = selected {
if self.catalog_pending_files.is_empty() {
self.catalog_pending_scope = active_scope.clone();
}
for path in paths {
if !self.catalog_pending_files.iter().any(|entry| entry.path == path) {
self.catalog_pending_file_formats.insert(
path.clone(),
detect_catalog_file_format(&path),
);
self.catalog_pending_files.push(CatalogArtifactFile {
path,
purpose: CatalogArtifactPurpose::Other,
});
}
}
}
}
let mut remove_index = None;
for (index, entry) in self.catalog_pending_files.iter_mut().enumerate() {
ui.horizontal(|ui| {
egui::ComboBox::from_label(format!("Purpose for file {}", index + 1))
.selected_text(artifact_purpose_label(&entry.purpose))
.show_ui(ui, |ui| {
for purpose in [
CatalogArtifactPurpose::RawInstrumentData,
CatalogArtifactPurpose::TypedKiTheDocument,
CatalogArtifactPurpose::ProcessedResults,
CatalogArtifactPurpose::PlotImage,
CatalogArtifactPurpose::EditableKiThePlot,
CatalogArtifactPurpose::Other,
] {
ui.selectable_value(
&mut entry.purpose,
purpose.clone(),
artifact_purpose_label(&purpose),
);
}
});
ui.label(entry.path.display().to_string())
.on_hover_text(entry.path.display().to_string());
if ui.small_button("Remove").clicked() {
remove_index = Some(index);
}
});
let detected = self
.catalog_pending_file_formats
.get(&entry.path)
.cloned()
.unwrap_or_else(|| detect_catalog_file_format(&entry.path));
let target_id = match self.catalog_publish_kind {
CatalogObjectKind::Series => model.series.identity(),
CatalogObjectKind::Experiment => self.catalog_experiment_identity.as_str(),
};
ui.small(format!("Detected: {detected} | Target: {target_id}"));
}
if let Some(index) = remove_index {
let removed = self.catalog_pending_files.remove(index);
self.catalog_pending_file_formats.remove(&removed.path);
}
if self.catalog_pending_files.is_empty() {
self.catalog_pending_scope = None;
}
let has_plot_artifact = self.catalog_pending_files.iter().any(|file| {
matches!(
file.purpose,
CatalogArtifactPurpose::PlotImage
| CatalogArtifactPurpose::EditableKiThePlot
)
});
let mut parent_selection_valid = true;
if has_plot_artifact {
let target_id = match self.catalog_publish_kind {
CatalogObjectKind::Series => model.series.identity().to_string(),
CatalogObjectKind::Experiment => {
self.catalog_experiment_identity.clone()
}
};
let parent_options = self
.catalog_publications
.iter()
.filter(|publication| {
publication.object_kind == self.catalog_publish_kind
&& publication.object_id.as_str() == target_id.as_str()
})
.collect::<Vec<_>>();
let previous_parent = self.catalog_parent_publication.clone();
let parent_is_available = self.catalog_parent_publication.as_ref().is_none_or(
|selected| parent_options.iter().any(|item| item.id == *selected),
);
parent_selection_valid = parent_is_available;
egui::ComboBox::from_label("Parent publication (optional)")
.selected_text(
if self.catalog_parent_publication.is_none() {
"None"
} else if !parent_is_available {
"Selected parent is unavailable for this target"
} else {
self.catalog_parent_publication
.as_ref()
.and_then(|id| {
parent_options.iter().find(|item| item.id == *id)
})
.and_then(|item| item.description.as_deref())
.unwrap_or("Selected parent")
},
)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.catalog_parent_publication,
None,
"None",
);
for publication in &parent_options {
let label = publication
.description
.as_deref()
.filter(|text| !text.trim().is_empty())
.map(str::to_owned)
.unwrap_or_else(|| {
format!("Publication {}", publication.id.as_str())
});
ui.selectable_value(
&mut self.catalog_parent_publication,
Some(publication.id.clone()),
label,
);
}
});
if self.catalog_parent_publication != previous_parent {
parent_selection_valid = self
.catalog_parent_publication
.as_ref()
.is_none_or(|selected| {
parent_options.iter().any(|item| item.id == *selected)
});
if self.catalog_pending_scope.is_none() {
self.catalog_pending_scope = active_scope.clone();
}
}
if !parent_selection_valid {
ui.colored_label(
egui::Color32::YELLOW,
"Choose None or a parent publication belonging to the current target.",
);
}
}
let publish_enabled = can_register
&& !pending_scope_mismatch
&& parent_selection_valid
&& (self.catalog_publish_kind == CatalogObjectKind::Series
|| selected_current_experiment_name.is_some());
let publish_label = match self.catalog_publish_kind {
CatalogObjectKind::Experiment => "Publish Current Experiment",
CatalogObjectKind::Series => "Publish Current Series",
};
if ui
.add_enabled(publish_enabled, egui::Button::new(publish_label))
.clicked()
{
match self.catalog_publish_kind {
CatalogObjectKind::Experiment => self.publish_current_experiment(
model,
path.as_deref(),
self.catalog_experiment_identity.clone(),
),
CatalogObjectKind::Series => {
self.publish_current_series(model, path.as_deref())
}
}
}
});
});
if self.catalog_publish_result.is_some() {
let progress = self
.catalog_publish_progress
.as_ref()
.and_then(|progress| progress.lock().ok().map(|value| value.clone()))
.unwrap_or_default();
let snapshot = progress.snapshot;
let fraction = if snapshot.total_bytes == 0 {
0.0
} else {
(snapshot.bytes_total as f64 / snapshot.total_bytes as f64)
.clamp(0.0, 1.0) as f32
};
ui.label(if progress.committing {
"Committing the catalog snapshot..."
} else if snapshot.file_count == 0 {
"Preparing publication..."
} else {
"Hashing external files before the atomic database commit:"
});
ui.add(egui::ProgressBar::new(fraction).show_percentage());
if snapshot.file_count > 0 && !progress.committing {
ui.small(format!(
"File {}/{}: {} ({:.1} / {:.1} MiB total)",
snapshot.file_index,
snapshot.file_count,
snapshot.file_name,
snapshot.bytes_total as f64 / 1_048_576.0,
snapshot.total_bytes as f64 / 1_048_576.0
));
}
ui.horizontal(|ui| {
let cancelling = progress.cancellation_requested;
if ui
.add_enabled(
!cancelling && !progress.committing,
egui::Button::new(if cancelling {
"Cancelling..."
} else if progress.committing {
"Committing..."
} else {
"Cancel publication"
}),
)
.clicked()
{
if let Some(progress) = &self.catalog_publish_progress {
if let Ok(mut progress) = progress.lock()
&& !progress.committing
{
progress.cancellation_requested = true;
}
}
}
ui.small("Cancellation is checked between 64 KiB blocks; no snapshot is committed on cancel.");
});
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
ui.horizontal(|ui| {
if ui.button("Refresh").clicked() {
self.refresh_catalog(path.as_deref());
}
if ui
.button("Transfers...")
.on_hover_text("Exercise file transfer with an in-memory test server. No network connection is made.")
.clicked()
{
self.catalog_transfer_ui.open();
}
ui.add(
egui::TextEdit::singleline(&mut self.catalog_search)
.hint_text("Search experiment or series"),
);
});
ui.checkbox(
&mut self.catalog_show_publication_history,
"Search and show older publication versions",
)
.on_hover_text("Off: search and show only each object's latest publication. On: search all immutable versions and identify the version that matched.");
if self
.catalog_browse_study_filter
.as_ref()
.is_some_and(|id| !self.catalog_studies.iter().any(|study| &study.id == id))
{
self.catalog_browse_study_filter = None;
}
if self
.catalog_browse_substance_filter
.as_ref()
.is_some_and(|id| !self.catalog_substances.iter().any(|substance| &substance.id == id))
{
self.catalog_browse_substance_filter = None;
}
ui.horizontal_wrapped(|ui| {
egui::ComboBox::from_label("Study filter")
.selected_text(
self.catalog_browse_study_filter
.as_ref()
.and_then(|id| self.catalog_studies.iter().find(|study| &study.id == id))
.map(|study| study.display_name.as_str())
.unwrap_or("All studies"),
)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.catalog_browse_study_filter,
None,
"All studies",
);
for study in &self.catalog_studies {
ui.selectable_value(
&mut self.catalog_browse_study_filter,
Some(study.id.clone()),
&study.display_name,
);
}
});
egui::ComboBox::from_label("Substance filter")
.selected_text(
self.catalog_browse_substance_filter
.as_ref()
.and_then(|id| self.catalog_substances.iter().find(|item| &item.id == id))
.map(|substance| substance.display_name.as_str())
.unwrap_or("All substances"),
)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.catalog_browse_substance_filter,
None,
"All substances",
);
for substance in &self.catalog_substances {
ui.selectable_value(
&mut self.catalog_browse_substance_filter,
Some(substance.id.clone()),
&substance.display_name,
);
}
});
});
let methods = self
.catalog_publication_index
.values()
.flat_map(|indices| {
indices.iter().take(if self.catalog_show_publication_history {
usize::MAX
} else {
1
})
})
.filter_map(|index| self.catalog_publications.get(*index))
.flat_map(|publication| &publication.typed_documents)
.flat_map(|document| {
document
.kinetic_method_outputs
.iter()
.map(|output| output.method.clone())
.chain(document.analysis_results.iter().map(|record| match &record.kind {
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ParameterSet(result) => result.method.clone(),
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ArrheniusFit(_) => "Arrhenius".to_string(),
}))
})
.collect::<BTreeSet<_>>();
let tags = self
.catalog_experiment_entries
.iter()
.flat_map(|experiment| experiment.tags.iter().cloned())
.collect::<BTreeSet<_>>();
ui.horizontal_wrapped(|ui| {
egui::ComboBox::from_label("Method")
.selected_text(if self.catalog_method_filter.is_empty() {
"All methods"
} else {
&self.catalog_method_filter
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_method_filter, String::new(), "All methods");
for method in &methods {
ui.selectable_value(
&mut self.catalog_method_filter,
method.clone(),
method,
);
}
});
egui::ComboBox::from_label("Origin")
.selected_text(if self.catalog_origin_filter.is_empty() {
"All origins"
} else {
&self.catalog_origin_filter
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_origin_filter, String::new(), "All origins");
for origin in ["Measured", "Synthetic", "Reconstructed", "Mixed", "Unspecified"] {
ui.selectable_value(
&mut self.catalog_origin_filter,
origin.to_string(),
origin,
);
}
});
egui::ComboBox::from_label("Tag")
.selected_text(if self.catalog_tag_filter.is_empty() {
"All tags"
} else {
&self.catalog_tag_filter
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_tag_filter, String::new(), "All tags");
for tag in &tags {
ui.selectable_value(
&mut self.catalog_tag_filter,
tag.clone(),
tag,
);
}
});
if ui.button("Clear filters").clicked() {
self.catalog_search.clear();
self.catalog_browse_study_filter = None;
self.catalog_browse_substance_filter = None;
self.catalog_method_filter.clear();
self.catalog_origin_filter.clear();
self.catalog_tag_filter.clear();
self.catalog_thermal_filter = None;
self.catalog_temperature_min.clear();
self.catalog_temperature_max.clear();
self.catalog_heating_rate_min.clear();
self.catalog_heating_rate_max.clear();
self.catalog_date_from.clear();
self.catalog_date_to.clear();
self.catalog_sample_filter = None;
self.catalog_attachment_filter = None;
}
});
egui::CollapsingHeader::new("More filters")
.default_open(false)
.show(ui, |ui| {
egui::ComboBox::from_label("Thermal mode")
.selected_text(match self.catalog_thermal_filter {
None => "All modes",
Some(CatalogThermalMode::Isothermal) => "Isothermal",
Some(CatalogThermalMode::NonIsothermal) => "Non-isothermal",
Some(CatalogThermalMode::Unspecified) => "Unspecified",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_thermal_filter, None, "All modes");
ui.selectable_value(&mut self.catalog_thermal_filter, Some(CatalogThermalMode::Isothermal), "Isothermal");
ui.selectable_value(&mut self.catalog_thermal_filter, Some(CatalogThermalMode::NonIsothermal), "Non-isothermal");
ui.selectable_value(&mut self.catalog_thermal_filter, Some(CatalogThermalMode::Unspecified), "Unspecified");
});
ui.horizontal_wrapped(|ui| {
ui.label("Temperature K:");
ui.add(egui::TextEdit::singleline(&mut self.catalog_temperature_min).hint_text("min"));
ui.add(egui::TextEdit::singleline(&mut self.catalog_temperature_max).hint_text("max"));
ui.label("Heating rate K/min:");
ui.add(egui::TextEdit::singleline(&mut self.catalog_heating_rate_min).hint_text("min"));
ui.add(egui::TextEdit::singleline(&mut self.catalog_heating_rate_max).hint_text("max"));
});
ui.horizontal(|ui| {
ui.label("Date YYYY-MM-DD:");
ui.add(egui::TextEdit::singleline(&mut self.catalog_date_from).hint_text("from"));
ui.add(egui::TextEdit::singleline(&mut self.catalog_date_to).hint_text("to"));
});
egui::ComboBox::from_label("Sample / batch")
.selected_text(
self.catalog_sample_filter
.as_ref()
.and_then(|id| self.catalog_samples.iter().find(|sample| &sample.id == id))
.map(catalog_sample_filter_label)
.unwrap_or_else(|| "All samples".to_string()),
)
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_sample_filter, None, "All samples");
for sample in &self.catalog_samples {
ui.selectable_value(
&mut self.catalog_sample_filter,
Some(sample.id.clone()),
catalog_sample_filter_label(sample),
);
}
});
egui::ComboBox::from_label("Required attachment")
.selected_text(self.catalog_attachment_filter.as_ref()
.map(artifact_purpose_label)
.unwrap_or("Any attachment"))
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.catalog_attachment_filter, None, "Any attachment");
for purpose in [
CatalogArtifactPurpose::RawInstrumentData,
CatalogArtifactPurpose::TypedKiTheDocument,
CatalogArtifactPurpose::ProcessedResults,
CatalogArtifactPurpose::PlotImage,
CatalogArtifactPurpose::EditableKiThePlot,
CatalogArtifactPurpose::Other,
] {
ui.selectable_value(
&mut self.catalog_attachment_filter,
Some(purpose.clone()),
artifact_purpose_label(&purpose),
);
}
});
});
let advanced_filters_valid = catalog_numeric_bounds_valid(
&self.catalog_temperature_min,
&self.catalog_temperature_max,
) && catalog_numeric_bounds_valid(
&self.catalog_heating_rate_min,
&self.catalog_heating_rate_max,
) && catalog_date_bounds_valid(&self.catalog_date_from, &self.catalog_date_to);
if !advanced_filters_valid {
ui.colored_label(
egui::Color32::YELLOW,
"Check filter bounds: enter finite numbers with min <= max and dates as YYYY-MM-DD.",
);
}
if let Some(substance_id) = self.catalog_browse_substance_filter.as_ref() {
let counts = catalog_substance_result_counts(
substance_id,
&self.catalog_studies,
&self.catalog_entries,
&self.catalog_experiment_entries,
&self.catalog_study_series_ids,
&self.catalog_series_substance_ids,
&self.catalog_experiment_series_ids,
&self.catalog_experiment_substance_ids,
);
if let Some(substance) = self
.catalog_substances
.iter()
.find(|substance| &substance.id == substance_id)
{
ui.label(format!(
"{}: {} studies | {} series | {} experiments",
substance.display_name, counts.0, counts.1, counts.2
));
}
}
ui.horizontal(|ui| {
ui.label("Results:");
for (level, label) in [
(CatalogResultLevel::All, "All"),
(CatalogResultLevel::Studies, "Studies"),
(CatalogResultLevel::Series, "Series"),
(CatalogResultLevel::Experiments, "Experiments"),
] {
ui.selectable_value(&mut self.catalog_result_level, level, label);
}
});
if self.catalog_result_level == CatalogResultLevel::Studies {
ui.small("Studies are grouping records; method, origin, tag and measurement filters apply to their series and experiments.");
}
let query = self.catalog_search.trim().to_lowercase();
let active_filter_labels = self.active_catalog_filter_labels();
ui.separator();
egui::ScrollArea::vertical()
.id_salt("catalog_series_list")
.show(ui, |ui| {
if self.catalog_entries.is_empty()
&& self.catalog_experiment_entries.is_empty()
&& self.catalog_studies.is_empty()
{
ui.label("No experiments or series are registered in this library yet.");
}
let mut visible_entries = 0;
if matches!(
self.catalog_result_level,
CatalogResultLevel::All | CatalogResultLevel::Studies
) {
for study in &self.catalog_studies {
let study_substances =
self.catalog_study_substance_ids.get(&study.id);
if self
.catalog_browse_study_filter
.as_ref()
.is_some_and(|id| id != &study.id)
|| self.catalog_browse_substance_filter.as_ref().is_some_and(
|substance_id| {
!study_substances.is_some_and(|ids| ids.contains(substance_id))
},
)
{
continue;
}
let mut search_fields = vec![
study.display_name.as_str(),
study.id.as_str(),
study.description.as_deref().unwrap_or_default(),
];
for substance_id in study_substances.into_iter().flatten() {
if let Some(substance) = self
.catalog_substances
.iter()
.find(|substance| &substance.id == substance_id)
{
search_fields.push(&substance.display_name);
search_fields.push(
substance.formula.as_deref().unwrap_or_default(),
);
}
}
if !catalog_text_matches(&query, &search_fields) {
continue;
}
visible_entries += 1;
let series_count = self
.catalog_study_series_ids
.get(&study.id)
.map_or(0, HashSet::len);
ui.group(|ui| {
ui.strong(&study.display_name);
ui.small(format!("Study ID: {}", study.id));
if let Some(description) = &study.description {
ui.label(description);
}
let substances = study_substances
.into_iter()
.flatten()
.filter_map(|id| {
self.catalog_substances
.iter()
.find(|substance| &substance.id == id)
})
.map(|substance| substance.display_name.as_str())
.collect::<Vec<_>>();
if !substances.is_empty() {
ui.small(format!(
"Substances: {}",
substances.join(", ")
));
}
ui.small(format!("Current series: {series_count}"));
ui.horizontal(|ui| {
if ui
.button(format!(
"Browse series: {}",
study.display_name
))
.clicked()
{
browse_navigation = Some((
study.id.clone(),
CatalogResultLevel::Series,
));
}
if ui
.button(format!(
"Browse experiments: {}",
study.display_name
))
.clicked()
{
browse_navigation = Some((
study.id.clone(),
CatalogResultLevel::Experiments,
));
}
});
});
}
}
for entry in &self.catalog_entries {
if !matches!(
self.catalog_result_level,
CatalogResultLevel::All | CatalogResultLevel::Series
) {
break;
}
if !catalog_series_matches_identity_filters(
&entry.id,
self.catalog_browse_study_filter.as_ref(),
self.catalog_browse_substance_filter.as_ref(),
&self.catalog_study_series_ids,
&self.catalog_series_substance_ids,
) {
continue;
}
let member_names = self
.catalog_experiment_entries
.iter()
.filter(|experiment| {
self.catalog_experiment_series_ids
.get(&experiment.id)
.is_some_and(|series_ids| series_ids.contains(&entry.id))
})
.map(|experiment| experiment.display_name.as_str())
.collect::<Vec<_>>();
let search_publication_indices = publication_search_scope(
&self.catalog_publication_index,
CatalogObjectKind::Series,
&entry.id,
self.catalog_show_publication_history,
);
let publication_summaries_match = !query.is_empty()
&& search_publication_indices.iter().any(|index| {
self.catalog_publications
.get(*index)
.is_some_and(|publication| {
publication.typed_documents.iter().any(|document| {
typed_document_matches_query(&query, document)
})
})
});
let method_matches = self.catalog_method_filter.is_empty()
|| search_publication_indices.iter().any(|index| {
self.catalog_publications
.get(*index)
.is_some_and(|publication| {
publication.typed_documents.iter().any(|document| {
typed_document_has_method(
document,
&self.catalog_method_filter,
)
})
})
});
let current_series_text_match = catalog_text_matches(
&query,
&[
&entry.display_name,
entry.id.as_str(),
entry.description.as_deref().unwrap_or_default(),
],
);
let current_member_text_match = member_names
.iter()
.any(|name| name.to_lowercase().contains(&query));
let member_filters_match =
self.catalog_series_matches_member_filters(&entry.id);
if !current_series_text_match
&& !current_member_text_match
&& !publication_summaries_match
|| !method_matches
|| !member_filters_match
{
continue;
}
visible_entries += 1;
ui.group(|ui| {
ui.strong(&entry.display_name);
ui.small(format!("Series ID: {}", entry.id.as_str()));
if !query.is_empty() {
if current_series_text_match {
ui.small("Search matched current series metadata.");
}
if current_member_text_match {
ui.small("Search matched a current member experiment.");
}
if publication_summaries_match {
ui.small("Search matched a typed-document summary in a displayed publication version.");
}
}
if !active_filter_labels.is_empty() {
ui.small(format!(
"Matched with filters: {}",
active_filter_labels.join("; ")
));
}
for link in catalog_series_context_labels(
&entry.id,
&self.catalog_studies,
&self.catalog_substances,
&self.catalog_study_series_ids,
&self.catalog_series_substance_ids,
&self.catalog_experiment_series_ids,
) {
ui.small(link);
}
if let Some(description) = &entry.description {
ui.label(description);
}
let publications = target_publication_indices(
&self.catalog_publication_index,
CatalogObjectKind::Series,
&entry.id,
)
.iter()
.filter_map(|index| self.catalog_publications.get(*index))
.collect::<Vec<_>>();
if !self.catalog_show_publication_history && publications.len() > 1 {
ui.small(format!(
"{} older publication versions hidden. Enable history to view them.",
publications.len() - 1
));
}
for publication in publications.iter().take(if self.catalog_show_publication_history {
usize::MAX
} else {
1
}) {
let publication_text_match = !query.is_empty()
&& publication.typed_documents.iter().any(|document| {
typed_document_matches_query(&query, document)
});
let publication_method_match = !self.catalog_method_filter.is_empty()
&& publication.typed_documents.iter().any(|document| {
typed_document_has_method(
document,
&self.catalog_method_filter,
)
});
if publication_text_match || publication_method_match {
let mut reasons = Vec::new();
if publication_text_match {
reasons.push("search text");
}
if publication_method_match {
reasons.push("method filter");
}
ui.colored_label(
egui::Color32::LIGHT_GREEN,
format!(
"Matched in this publication version: {} ({})",
reasons.join(", "),
publication.created_at_rfc3339
),
);
}
ui.small(format!(
"Published {} | {} experiments | {} files | {} bytes linked",
publication.created_at_rfc3339,
publication.series_members.len(),
publication.artifact_ids.len(),
publication_total_bytes(
publication,
&self.catalog_artifacts
)
));
if let Some(description) = &publication.description {
ui.label(description);
}
if let Some(author) = &publication.author {
ui.small(format!("Author: {author}"));
}
match &publication.snapshot {
Some(CatalogPublicationSnapshot::Series {
series: snapshot_series,
experiments,
}) => {
ui.small(format!(
"Published series snapshot: {}",
snapshot_series.display_name
));
for experiment in experiments {
show_catalog_experiment_snapshot(ui, experiment);
}
}
Some(CatalogPublicationSnapshot::Experiment(_)) => {
ui.colored_label(
egui::Color32::YELLOW,
"Snapshot metadata does not match this series publication.",
);
}
None => {
ui.small("Legacy publication: metadata snapshot unavailable.");
}
}
for document in &publication.typed_documents {
show_catalog_typed_document_summary(ui, document);
}
for artifact_id in &publication.artifact_ids {
if let Some(listing) =
self.catalog_artifacts.get(artifact_id)
{
ui.group(|ui| {
ui.strong(&listing.artifact.file_name);
ui.small(format!(
"{} | {} | {} bytes",
artifact_purpose_label(
&listing.artifact.purpose
),
listing.artifact.format,
listing.artifact.size_bytes
));
ui.small(format!(
"SHA-256: {}",
listing.artifact.sha256
));
ui.small(local_artifact_status(
&listing.local_resolution,
));
if matches!(
listing.local_resolution,
LocalArtifactResolution::Missing(_)
) {
if let Some(root_id) =
local_artifact_root_id(&listing.artifact)
{
let enabled = self
.catalog_root_relink_in_progress
.is_none();
if ui
.add_enabled(
enabled,
egui::Button::new(
"Relink moved folder...",
),
)
.clicked()
{
#[cfg(test)]
let selected = self
.test_catalog_relink_directory
.take();
#[cfg(not(test))]
let selected = rfd::FileDialog::new()
.pick_folder();
if let Some(folder) = selected {
relink_requested =
Some((root_id, folder));
}
}
}
}
if let Some(integrity) =
self.catalog_integrity.get(artifact_id)
{
ui.small(local_integrity_status(integrity));
}
if matches!(
listing.local_resolution,
LocalArtifactResolution::Available(_)
) {
let enabled = self
.catalog_verify_in_progress
.is_none();
if ui
.add_enabled(
enabled,
egui::Button::new("Verify checksum"),
)
.clicked()
{
verify_requested = Some(artifact_id.clone());
}
}
if listing.artifact.purpose
== CatalogArtifactPurpose::TypedKiTheDocument
{
if let LocalArtifactResolution::Available(
path,
) = &listing.local_resolution
{
let open_label = catalog_open_action_label(
&listing.artifact.purpose,
self.catalog_integrity.get(artifact_id),
);
if let Some(label) = open_label {
if ui.button(label).clicked() {
match document_dialog
.open_typed_document_from_catalog(
model, path,
)
{
Ok(()) => close_catalog = true,
Err(error) => {
warn!("Catalog typed-document action failed: {error}");
self.catalog_status = Some(error.clone());
let _ = model.push_message(&error);
}
}
}
} else {
ui.small("Verify checksum before opening. If it differs, opening the current disk file will be a separate explicit action.");
}
}
}
if listing.artifact.purpose
== CatalogArtifactPurpose::RawInstrumentData
{
if let LocalArtifactResolution::Available(
path,
) = &listing.local_resolution
{
let open_label = catalog_open_action_label(
&listing.artifact.purpose,
self.catalog_integrity.get(artifact_id),
);
if let Some(label) = open_label {
if ui.button(label).clicked() {
match document_dialog
.import_raw_file_from_catalog(model, path)
{
Ok(()) => close_catalog = true,
Err(error) => {
warn!("Catalog raw import failed: {error}");
let _ = model.push_message(&format!("Could not import catalog file: {error}"));
}
}
}
} else {
ui.small("Verify checksum before importing. If it differs, importing the current disk file will be a separate explicit action.");
}
}
}
show_external_artifact_actions(
ui,
listing,
model,
&mut self.catalog_status,
self.catalog_integrity.get(artifact_id),
plot_editor.as_deref_mut(),
);
});
} else {
ui.label(format!(
"Artifact {}: metadata unavailable",
artifact_id.as_str()
));
}
}
}
});
}
for entry in &self.catalog_experiment_entries {
if !matches!(
self.catalog_result_level,
CatalogResultLevel::All | CatalogResultLevel::Experiments
) {
break;
}
if !catalog_experiment_matches_identity_filters(
&entry.id,
self.catalog_browse_study_filter.as_ref(),
self.catalog_browse_substance_filter.as_ref(),
&self.catalog_study_series_ids,
&self.catalog_series_substance_ids,
&self.catalog_experiment_series_ids,
&self.catalog_experiment_substance_ids,
) {
continue;
}
let mode = thermal_mode_label(entry.thermal_mode);
let temperature = entry
.temperature_k
.map(|value| value.to_string())
.unwrap_or_default();
let heating_rate = entry
.heating_rate_k_per_min
.map(|value| value.to_string())
.unwrap_or_default();
let date = entry.date.as_deref().unwrap_or_default();
let tags = entry.tags.join(" ");
let search_publication_indices = experiment_publication_search_scope(
&entry.id,
&self.catalog_experiment_series_ids,
&self.catalog_publication_index,
self.catalog_show_publication_history,
);
let method_matches = self.catalog_method_filter.is_empty()
|| search_publication_indices.iter().any(|index| {
self.catalog_publications
.get(*index)
.is_some_and(|publication| {
publication.typed_documents.iter().any(|document| {
typed_document_method_mentions_experiment(
document,
&self.catalog_method_filter,
&entry.id,
)
})
})
});
let publication_summaries_match = !query.is_empty()
&& search_publication_indices.iter().any(|index| {
self.catalog_publications
.get(*index)
.is_some_and(|publication| {
publication.typed_documents.iter().any(|document| {
typed_document_matches_query(&query, document)
})
})
});
let related_series_publication_matches = search_publication_indices
.iter()
.filter_map(|index| self.catalog_publications.get(*index))
.filter(|publication| {
publication.object_kind == CatalogObjectKind::Series
&& ((!query.is_empty()
&& publication.typed_documents.iter().any(|document| {
typed_document_matches_query(&query, document)
}))
|| (!self.catalog_method_filter.is_empty()
&& publication.typed_documents.iter().any(
|document| {
typed_document_method_mentions_experiment(
document,
&self.catalog_method_filter,
&entry.id,
)
},
)))
})
.map(|publication| {
let series_name = self
.catalog_entries
.iter()
.find(|series| series.id == publication.object_id)
.map(|series| series.display_name.as_str())
.unwrap_or(publication.object_id.as_str());
format!(
"Related series '{series_name}' publication matched: {}",
publication.created_at_rfc3339
)
})
.collect::<Vec<_>>();
let current_experiment_text_match = catalog_text_matches(
&query,
&[
&entry.display_name,
entry.id.as_str(),
date,
&tags,
source_kind_label(&entry.source_kind),
entry.sample.as_deref().unwrap_or_default(),
entry.instrument.as_deref().unwrap_or_default(),
entry.operator.as_deref().unwrap_or_default(),
entry.comment.as_deref().unwrap_or_default(),
mode,
&temperature,
&heating_rate,
],
);
let origin_matches = self.catalog_origin_filter.is_empty()
|| source_kind_label(&entry.source_kind)
.eq_ignore_ascii_case(&self.catalog_origin_filter);
let tag_matches = self.catalog_tag_filter.is_empty()
|| entry.tags.iter().any(|tag| {
tag.eq_ignore_ascii_case(&self.catalog_tag_filter)
});
if !(current_experiment_text_match || publication_summaries_match)
|| !method_matches
|| !origin_matches
|| !tag_matches
|| !advanced_filters_valid
|| !catalog_experiment_matches_advanced_filters(
entry,
self.catalog_thermal_filter,
&self.catalog_temperature_min,
&self.catalog_temperature_max,
&self.catalog_heating_rate_min,
&self.catalog_heating_rate_max,
&self.catalog_date_from,
&self.catalog_date_to,
)
|| !catalog_experiment_matches_sample_and_attachment(
&entry.id,
self.catalog_sample_filter.as_ref(),
self.catalog_attachment_filter.as_ref(),
&self.catalog_experiment_sample_ids,
&self.catalog_experiment_series_ids,
&self.catalog_publication_index,
self.catalog_show_publication_history,
&self.catalog_publications,
&self.catalog_artifacts,
)
{
continue;
}
visible_entries += 1;
ui.group(|ui| {
ui.strong(&entry.display_name);
ui.small(format!("Experiment ID: {}", entry.id.as_str()));
if !query.is_empty() {
if current_experiment_text_match {
ui.small("Search matched current experiment metadata.");
}
if publication_summaries_match {
ui.small("Search matched a typed-document summary.");
}
}
for match_reason in &related_series_publication_matches {
ui.small(match_reason);
}
if !active_filter_labels.is_empty() {
ui.small(format!(
"Matched with filters: {}",
active_filter_labels.join("; ")
));
}
ui.label(format!(
"Source: {} | Thermal mode: {}",
source_kind_label(&entry.source_kind),
thermal_mode_label(entry.thermal_mode)
));
for link in catalog_experiment_context_labels(
&entry.id,
&self.catalog_entries,
&self.catalog_studies,
&self.catalog_substances,
&self.catalog_study_series_ids,
&self.catalog_series_substance_ids,
&self.catalog_experiment_series_ids,
&self.catalog_experiment_substance_ids,
) {
ui.small(link);
}
if let Some(date) = &entry.date {
ui.label(format!("Date: {date}"));
}
if !entry.tags.is_empty() {
ui.label(format!("Tags: {}", entry.tags.join(", ")));
}
if let Some(sample) = &entry.sample {
ui.label(format!("Sample label: {sample}"));
}
if let Some(instrument) = &entry.instrument {
ui.label(format!("Instrument: {instrument}"));
}
if let Some(operator) = &entry.operator {
ui.label(format!("Operator: {operator}"));
}
if let Some(temperature) = entry.temperature_k {
ui.label(format!("Isothermal temperature: {temperature} K"));
}
if let Some(rate) = entry.heating_rate_k_per_min {
ui.label(format!("Heating rate: {rate} K/min"));
}
if let Some(comment) = &entry.comment {
ui.label(comment);
}
let publications = target_publication_indices(
&self.catalog_publication_index,
CatalogObjectKind::Experiment,
&entry.id,
)
.iter()
.filter_map(|index| self.catalog_publications.get(*index))
.collect::<Vec<_>>();
if !self.catalog_show_publication_history && publications.len() > 1 {
ui.small(format!(
"{} older publication versions hidden. Enable history to view them.",
publications.len() - 1
));
}
for publication in publications.iter().take(if self.catalog_show_publication_history {
usize::MAX
} else {
1
}) {
let publication_text_match = !query.is_empty()
&& publication.typed_documents.iter().any(|document| {
typed_document_matches_query(&query, document)
});
let publication_method_match = !self.catalog_method_filter.is_empty()
&& publication.typed_documents.iter().any(|document| {
typed_document_method_mentions_experiment(
document,
&self.catalog_method_filter,
&entry.id,
)
});
if publication_text_match || publication_method_match {
let mut reasons = Vec::new();
if publication_text_match {
reasons.push("search text");
}
if publication_method_match {
reasons.push("method filter");
}
ui.colored_label(
egui::Color32::LIGHT_GREEN,
format!(
"Matched in this publication version: {} ({})",
reasons.join(", "),
publication.created_at_rfc3339
),
);
}
ui.small(format!(
"Published {} | {} files | {} bytes linked",
publication.created_at_rfc3339,
publication.artifact_ids.len(),
publication_total_bytes(
publication,
&self.catalog_artifacts
)
));
if let Some(description) = &publication.description {
ui.label(description);
}
if let Some(author) = &publication.author {
ui.small(format!("Author: {author}"));
}
match &publication.snapshot {
Some(CatalogPublicationSnapshot::Experiment(snapshot)) => {
show_catalog_experiment_snapshot(ui, snapshot);
}
Some(CatalogPublicationSnapshot::Series { .. }) => {
ui.colored_label(
egui::Color32::YELLOW,
"Snapshot metadata does not match this experiment publication.",
);
}
None => {
ui.small("Legacy publication: metadata snapshot unavailable.");
}
}
for artifact_id in &publication.artifact_ids {
if let Some(listing) =
self.catalog_artifacts.get(artifact_id)
{
ui.group(|ui| {
ui.strong(&listing.artifact.file_name);
ui.small(format!(
"{} | {} | {} bytes | SHA-256 {}",
artifact_purpose_label(
&listing.artifact.purpose
),
listing.artifact.format,
listing.artifact.size_bytes,
listing.artifact.sha256
));
ui.small(local_artifact_status(
&listing.local_resolution,
));
if matches!(
listing.local_resolution,
LocalArtifactResolution::Missing(_)
) {
if let Some(root_id) =
local_artifact_root_id(&listing.artifact)
{
let enabled = self
.catalog_root_relink_in_progress
.is_none();
if ui
.add_enabled(
enabled,
egui::Button::new(
"Relink moved folder...",
),
)
.clicked()
{
#[cfg(test)]
let selected = self
.test_catalog_relink_directory
.take();
#[cfg(not(test))]
let selected = rfd::FileDialog::new()
.pick_folder();
if let Some(folder) = selected {
relink_requested =
Some((root_id, folder));
}
}
}
}
if let Some(integrity) =
self.catalog_integrity.get(artifact_id)
{
ui.small(local_integrity_status(integrity));
}
if matches!(
listing.local_resolution,
LocalArtifactResolution::Available(_)
) {
let enabled =
self.catalog_verify_in_progress.is_none();
if ui
.add_enabled(
enabled,
egui::Button::new("Verify checksum"),
)
.clicked()
{
verify_requested = Some(artifact_id.clone());
}
}
if let LocalArtifactResolution::Available(path) =
&listing.local_resolution
{
let open_label = catalog_open_action_label(
&listing.artifact.purpose,
self.catalog_integrity.get(artifact_id),
);
if listing.artifact.purpose
== CatalogArtifactPurpose::TypedKiTheDocument
{
if let Some(label) = open_label {
if ui.button(label).clicked() {
match document_dialog
.open_typed_document_from_catalog(
model, path,
)
{
Ok(()) => close_catalog = true,
Err(error) => {
warn!("Catalog typed-document action failed: {error}");
self.catalog_status = Some(error.clone());
let _ = model.push_message(&error);
}
}
}
} else {
ui.small("Verify checksum before opening. If it differs, opening the current disk file will be a separate explicit action.");
}
}
if listing.artifact.purpose
== CatalogArtifactPurpose::RawInstrumentData
{
if let Some(label) = open_label {
if ui.button(label).clicked() {
match document_dialog
.import_raw_file_from_catalog(model, path)
{
Ok(()) => close_catalog = true,
Err(error) => {
warn!("Catalog raw import failed: {error}");
let _ = model.push_message(&format!("Could not import catalog file: {error}"));
}
}
}
} else {
ui.small("Verify checksum before importing. If it differs, importing the current disk file will be a separate explicit action.");
}
}
}
show_external_artifact_actions(
ui,
listing,
model,
&mut self.catalog_status,
self.catalog_integrity.get(artifact_id),
plot_editor.as_deref_mut(),
);
});
}
}
}
});
}
if visible_entries == 0
&& (!self.catalog_entries.is_empty()
|| !self.catalog_experiment_entries.is_empty())
{
ui.label("No catalog entries match this search.");
}
ui.separator();
ui.small(format!("{visible_entries} matching catalog entries"));
});
if let Some(status) = &self.catalog_status {
ui.separator();
ui.label(status);
}
});
self.catalog_window_open = open && !close_catalog;
self.catalog_transfer_ui
.show(ctx, &self.catalog_publications, &self.catalog_artifacts);
if let Some((study_id, level)) = browse_navigation {
self.catalog_browse_study_filter = Some(study_id);
self.catalog_result_level = level;
}
self.show_catalog_raw_source_dialog(ctx, model);
if self.catalog_verify_result.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
if let (Some(id), Some(path)) = (verify_requested, library_path_for_verify) {
self.start_catalog_verification(id, path);
}
if let (Some((root_id, new_root)), Some(library_path)) = (
relink_requested,
model.settings.catalog().local_library_path.clone(),
) {
self.start_catalog_root_relink(root_id, new_root, library_path);
}
if self.catalog_root_relink_result.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
}
fn show_catalog_raw_source_dialog(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
if !self.catalog_raw_source.open {
return;
}
let library_path = model.settings.catalog().local_library_path.clone();
let mut open = self.catalog_raw_source.open;
egui::Window::new("Register raw instrument source")
.open(&mut open)
.collapsible(false)
.resizable(true)
.show(ctx, |ui| {
ui.label("This records an external raw file without importing or modifying it. No DataLineage is required.");
ui.horizontal(|ui| {
ui.label("Source name:");
ui.text_edit_singleline(&mut self.catalog_raw_source.display_name);
});
ui.horizontal(|ui| {
ui.label("Date (YYYY-MM-DD):");
ui.text_edit_singleline(&mut self.catalog_raw_source.date);
});
ui.horizontal(|ui| {
ui.label("Sample:");
ui.text_edit_singleline(&mut self.catalog_raw_source.sample);
});
ui.horizontal(|ui| {
ui.label("Instrument:");
ui.text_edit_singleline(&mut self.catalog_raw_source.instrument);
});
ui.horizontal(|ui| {
ui.label("Operator:");
ui.text_edit_singleline(&mut self.catalog_raw_source.operator);
});
ui.label("Notes:");
ui.text_edit_multiline(&mut self.catalog_raw_source.comment);
ui.horizontal(|ui| {
ui.label("Tags:");
ui.text_edit_singleline(&mut self.catalog_raw_source.tags);
});
if ui.button("Add raw file...").clicked() {
#[cfg(test)]
let selected = self.test_catalog_files.take();
#[cfg(not(test))]
let selected = rfd::FileDialog::new().pick_files();
if let Some(paths) = selected {
for path in paths {
if !self.catalog_raw_source.files.contains(&path) {
self.catalog_raw_source.files.push(path);
}
}
}
}
let mut remove_index = None;
for (index, path) in self.catalog_raw_source.files.iter().enumerate() {
ui.horizontal(|ui| {
ui.label(path.file_name().unwrap_or_default().to_string_lossy());
if ui.small_button("Remove").clicked() {
remove_index = Some(index);
}
});
}
if let Some(index) = remove_index {
self.catalog_raw_source.files.remove(index);
}
let can_publish = !self.catalog_raw_source.display_name.trim().is_empty()
&& !self.catalog_raw_source.files.is_empty()
&& library_path.is_some()
&& self.catalog_publish_result.is_none();
if ui
.add_enabled(can_publish, egui::Button::new("Register raw source"))
.clicked()
{
self.publish_raw_source(model, library_path.as_deref());
if self.catalog_publish_result.is_some() {
self.catalog_raw_source.open = false;
}
}
});
if !open {
self.catalog_raw_source.open = false;
}
}
fn publish_raw_source(&mut self, model: &mut PlotModel, path: Option<&Path>) {
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
let Some(id) = self.catalog_raw_source.id.clone() else {
self.catalog_status = Some("Start a new raw-source registration first.".into());
return;
};
let experiment = CatalogExperiment {
id: id.clone(),
source_identity: id.as_str().to_owned(),
display_name: self.catalog_raw_source.display_name.trim().to_owned(),
source_kind: SourceKind::Unknown,
date: optional_trimmed(&self.catalog_raw_source.date),
sample: optional_trimmed(&self.catalog_raw_source.sample),
instrument: optional_trimmed(&self.catalog_raw_source.instrument),
operator: optional_trimmed(&self.catalog_raw_source.operator),
thermal_mode: Some(CatalogThermalMode::Unspecified),
temperature_k: None,
heating_rate_k_per_min: None,
comment: optional_trimmed(&self.catalog_raw_source.comment),
tags: parse_catalog_tags(&self.catalog_raw_source.tags),
};
if let Err(error) = experiment.validate() {
self.catalog_status = Some(format!("Raw-source metadata is invalid: {error}"));
return;
}
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("Raw instrument source registration".into()),
series_members: Vec::new(),
artifact_ids: Vec::new(),
snapshot: Some(CatalogPublicationSnapshot::Experiment(experiment.clone())),
typed_documents: Vec::new(),
};
let files = self
.catalog_raw_source
.files
.iter()
.cloned()
.map(|path| CatalogArtifactFile {
path,
purpose: CatalogArtifactPurpose::RawInstrumentData,
})
.collect::<Vec<_>>();
let result = publication.validate();
if let Err(error) = result {
self.catalog_status = Some(format!("Raw-source publication is invalid: {error}"));
return;
}
self.start_catalog_publication(
path.to_path_buf(),
CatalogObjectKind::Experiment,
move |store, progress| {
store.register_and_publish_experiment_snapshot_with_progress(
&experiment,
&publication,
&files,
progress,
)
},
);
if self.catalog_publish_result.is_some() {
self.catalog_raw_source_in_progress = true;
info!("Started catalog registration of a raw instrument source");
} else {
let _ = model.push_message("Could not start raw-source catalog registration.");
}
}
fn register_current_series(
&mut self,
model: &PlotModel,
path: Option<&std::path::Path>,
confirmed_shrink: bool,
) {
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
let name = self.catalog_series_name.trim().to_owned();
if name.is_empty() {
self.catalog_status = Some("Enter a name for the series card.".into());
return;
}
let snapshot = (|| {
let mut store = CatalogStore::open_existing(path)?;
let series_id = CatalogId::parse(model.series.identity().to_string()).map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let current_member_ids = model
.series
.experiments()
.iter()
.map(|experiment| experiment.meta.identity().to_string())
.collect::<Vec<_>>();
let existing_members = store.list_series_members(&series_id)?;
let removed_member_ids = existing_members
.iter()
.map(|member| member.experiment_id.as_str().to_string())
.filter(|id| !current_member_ids.iter().any(|current| current == id))
.collect::<Vec<_>>();
if confirmed_shrink {
let expected = CatalogMembershipShrinkConfirmation {
library_path: path.to_path_buf(),
library_id: store.library_id().to_owned(),
series_id: series_id.to_string(),
current_member_ids: current_member_ids.clone(),
removed_member_ids: removed_member_ids.clone(),
};
if removed_member_ids.is_empty()
|| self.catalog_membership_shrink_confirmation.as_ref() != Some(&expected)
{
self.catalog_membership_shrink_confirmation = None;
return Err(crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::MembershipConfirmationStale);
}
} else if !removed_member_ids.is_empty() {
let expected = CatalogMembershipShrinkConfirmation {
library_path: path.to_path_buf(),
library_id: store.library_id().to_owned(),
series_id: series_id.to_string(),
current_member_ids: current_member_ids.clone(),
removed_member_ids: removed_member_ids.clone(),
};
{
self.catalog_membership_shrink_confirmation = Some(expected);
self.catalog_status = Some(format!(
"Registration would remove {} experiment(s) from catalog series membership. Confirm to continue.",
removed_member_ids.len()
));
return Ok(());
}
}
let catalog_series = CatalogSeries {
id: series_id,
display_name: name,
description: Some(format!("{} experiments", model.series.len())),
};
let experiments = model
.series
.experiments()
.iter()
.map(|experiment| {
let identity = CatalogId::parse(experiment.meta.identity().to_string())
.map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let existing = store.get_experiment(&identity)?;
self.catalog_experiment_snapshot(experiment, existing)
})
.collect::<Result<
Vec<_>,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>>()?;
store.register_series_snapshot(&catalog_series, &experiments)?;
Ok::<_, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError>(())
})();
match snapshot {
Ok(()) if self.catalog_membership_shrink_confirmation.is_some() => {}
Ok(()) => {
self.catalog_membership_shrink_confirmation = None;
self.refresh_catalog(Some(path));
self.catalog_status =
Some("Series metadata registered locally. No files were copied.".into());
}
Err(error) => {
warn!("Catalog registration failed: {error}");
self.catalog_status = Some(format!("Could not register series: {error}"));
}
}
}
fn active_catalog_filter_labels(&self) -> Vec<String> {
let mut labels = Vec::new();
if let Some(id) = &self.catalog_browse_study_filter
&& let Some(study) = self.catalog_studies.iter().find(|item| &item.id == id)
{
labels.push(format!("Study: {}", study.display_name));
}
if let Some(id) = &self.catalog_browse_substance_filter
&& let Some(substance) = self.catalog_substances.iter().find(|item| &item.id == id)
{
labels.push(format!("Substance: {}", substance.display_name));
}
if !self.catalog_method_filter.is_empty() {
labels.push(format!("Method: {}", self.catalog_method_filter));
}
if !self.catalog_origin_filter.is_empty() {
labels.push(format!("Origin: {}", self.catalog_origin_filter));
}
if !self.catalog_tag_filter.is_empty() {
labels.push(format!("Tag: {}", self.catalog_tag_filter));
}
if let Some(mode) = self.catalog_thermal_filter {
labels.push(format!("Thermal mode: {}", thermal_mode_label(Some(mode))));
}
if !self.catalog_temperature_min.is_empty() || !self.catalog_temperature_max.is_empty() {
labels.push(format!(
"Temperature K: {}..{}",
self.catalog_temperature_min, self.catalog_temperature_max
));
}
if !self.catalog_heating_rate_min.is_empty() || !self.catalog_heating_rate_max.is_empty() {
labels.push(format!(
"Heating rate K/min: {}..{}",
self.catalog_heating_rate_min, self.catalog_heating_rate_max
));
}
if !self.catalog_date_from.is_empty() || !self.catalog_date_to.is_empty() {
labels.push(format!(
"Date: {}..{}",
self.catalog_date_from, self.catalog_date_to
));
}
if let Some(id) = &self.catalog_sample_filter
&& let Some(sample) = self.catalog_samples.iter().find(|item| &item.id == id)
{
labels.push(format!(
"Sample / batch: {}",
catalog_sample_filter_label(sample)
));
}
if let Some(purpose) = &self.catalog_attachment_filter {
labels.push(format!("Attachment: {}", artifact_purpose_label(purpose)));
}
labels
}
fn catalog_series_matches_member_filters(&self, series_id: &CatalogId) -> bool {
let valid_bounds =
catalog_numeric_bounds_valid(
&self.catalog_temperature_min,
&self.catalog_temperature_max,
) && catalog_numeric_bounds_valid(
&self.catalog_heating_rate_min,
&self.catalog_heating_rate_max,
) && catalog_date_bounds_valid(&self.catalog_date_from, &self.catalog_date_to);
let requires_member_match = !self.catalog_origin_filter.is_empty()
|| !self.catalog_tag_filter.is_empty()
|| self.catalog_thermal_filter.is_some()
|| !self.catalog_temperature_min.is_empty()
|| !self.catalog_temperature_max.is_empty()
|| !self.catalog_heating_rate_min.is_empty()
|| !self.catalog_heating_rate_max.is_empty()
|| !self.catalog_date_from.is_empty()
|| !self.catalog_date_to.is_empty()
|| self.catalog_sample_filter.is_some()
|| self.catalog_attachment_filter.is_some();
valid_bounds
&& (!requires_member_match
|| self.catalog_experiment_entries.iter().any(|experiment| {
let is_member = self
.catalog_experiment_series_ids
.get(&experiment.id)
.is_some_and(|series_ids| series_ids.contains(series_id));
is_member
&& (self.catalog_origin_filter.is_empty()
|| source_kind_label(&experiment.source_kind)
.eq_ignore_ascii_case(&self.catalog_origin_filter))
&& (self.catalog_tag_filter.is_empty()
|| experiment
.tags
.iter()
.any(|tag| tag.eq_ignore_ascii_case(&self.catalog_tag_filter)))
&& catalog_experiment_matches_advanced_filters(
experiment,
self.catalog_thermal_filter,
&self.catalog_temperature_min,
&self.catalog_temperature_max,
&self.catalog_heating_rate_min,
&self.catalog_heating_rate_max,
&self.catalog_date_from,
&self.catalog_date_to,
)
&& catalog_experiment_matches_sample_and_attachment(
&experiment.id,
self.catalog_sample_filter.as_ref(),
self.catalog_attachment_filter.as_ref(),
&self.catalog_experiment_sample_ids,
&self.catalog_experiment_series_ids,
&self.catalog_publication_index,
self.catalog_show_publication_history,
&self.catalog_publications,
&self.catalog_artifacts,
)
}))
}
fn refresh_catalog(&mut self, path: Option<&std::path::Path>) {
self.catalog_integrity.clear();
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
let result = (|| {
let store = CatalogStore::open_existing(path)?;
let library_id = store.library_id().to_owned();
let entries = store.list_series()?;
let experiment_entries = store.list_experiments()?;
let studies = store.list_studies()?;
let substances = store.list_substances()?;
let samples = store.list_samples()?;
let mut study_series_ids = HashMap::<CatalogId, HashSet<CatalogId>>::new();
for study in &studies {
let ids = store
.list_study_series(&study.id)?
.into_iter()
.map(|series| series.id)
.collect();
study_series_ids.insert(study.id.clone(), ids);
}
let mut study_substance_ids = HashMap::<CatalogId, HashSet<CatalogId>>::new();
for study in &studies {
let ids = store
.list_study_substances(&study.id)?
.into_iter()
.map(|substance| substance.id)
.collect();
study_substance_ids.insert(study.id.clone(), ids);
}
let mut series_substance_ids = HashMap::new();
let mut experiment_series_ids = HashMap::<CatalogId, HashSet<CatalogId>>::new();
for series in &entries {
if let Some(substance_id) = store.substance_for_series(&series.id)? {
series_substance_ids.insert(series.id.clone(), substance_id);
}
for member in store.list_series_members(&series.id)? {
experiment_series_ids
.entry(member.experiment_id)
.or_default()
.insert(series.id.clone());
}
}
let experiment_substance_ids = store
.list_experiment_sample_substances()?
.into_iter()
.collect::<HashMap<_, _>>();
let experiment_sample_ids = store
.list_experiment_samples()?
.into_iter()
.collect::<HashMap<_, _>>();
let mut publications = store.list_publications()?;
sort_catalog_publications(&mut publications);
let publication_index = index_catalog_publications(&publications);
let mut artifacts = HashMap::new();
for artifact_id in publications
.iter()
.flat_map(|publication| &publication.artifact_ids)
{
let Some(artifact) = store.get_artifact(artifact_id)? else {
continue;
};
let local_resolution = store.resolve_local_artifact(artifact_id)?;
artifacts.insert(
artifact_id.clone(),
CatalogArtifactListing {
artifact,
local_resolution,
},
);
}
Ok::<_, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError>((
entries,
experiment_entries,
studies,
substances,
samples,
study_series_ids,
study_substance_ids,
series_substance_ids,
experiment_series_ids,
experiment_substance_ids,
experiment_sample_ids,
publications,
publication_index,
artifacts,
library_id,
))
})();
match result {
Ok((
entries,
experiment_entries,
studies,
substances,
samples,
study_series_ids,
study_substance_ids,
series_substance_ids,
experiment_series_ids,
experiment_substance_ids,
experiment_sample_ids,
publications,
publication_index,
artifacts,
library_id,
)) => {
self.catalog_entries = entries;
self.catalog_experiment_entries = experiment_entries;
self.catalog_studies = studies;
self.catalog_substances = substances;
self.catalog_samples = samples;
self.catalog_study_series_ids = study_series_ids;
self.catalog_study_substance_ids = study_substance_ids;
self.catalog_series_substance_ids = series_substance_ids;
self.catalog_experiment_series_ids = experiment_series_ids;
self.catalog_experiment_substance_ids = experiment_substance_ids;
self.catalog_experiment_sample_ids = experiment_sample_ids;
self.catalog_publications = publications;
self.catalog_publication_index = publication_index;
self.catalog_artifacts = artifacts;
if self
.catalog_browse_study_filter
.as_ref()
.is_some_and(|id| !self.catalog_studies.iter().any(|study| &study.id == id))
{
self.catalog_browse_study_filter = None;
}
if self
.catalog_browse_substance_filter
.as_ref()
.is_some_and(|id| {
!self
.catalog_substances
.iter()
.any(|substance| &substance.id == id)
})
{
self.catalog_browse_substance_filter = None;
}
self.catalog_library_id = Some(library_id);
self.catalog_loaded_path = Some(path.to_path_buf());
if !self
.catalog_study_id
.as_ref()
.is_some_and(|id| self.catalog_studies.iter().any(|item| &item.id == id))
{
self.catalog_study_id =
self.catalog_studies.first().map(|item| item.id.clone());
}
if !self
.catalog_substance_id
.as_ref()
.is_some_and(|id| self.catalog_substances.iter().any(|item| &item.id == id))
{
self.catalog_substance_id =
self.catalog_substances.first().map(|item| item.id.clone());
}
if !self
.catalog_sample_id
.as_ref()
.is_some_and(|id| self.catalog_samples.iter().any(|item| &item.id == id))
{
self.catalog_sample_id = None;
}
if !self
.catalog_sample_filter
.as_ref()
.is_some_and(|id| self.catalog_samples.iter().any(|item| &item.id == id))
{
self.catalog_sample_filter = None;
}
self.catalog_contents_study_id = None;
self.catalog_status = Some(format!(
"Loaded {} studies, {} substances, {} series and {} experiment cards.",
self.catalog_studies.len(),
self.catalog_substances.len(),
self.catalog_entries.len(),
self.catalog_experiment_entries.len()
));
}
Err(error) => {
self.catalog_entries.clear();
self.catalog_experiment_entries.clear();
self.catalog_studies.clear();
self.catalog_substances.clear();
self.catalog_samples.clear();
self.catalog_study_substances.clear();
self.catalog_study_series.clear();
self.catalog_study_series_ids.clear();
self.catalog_study_substance_ids.clear();
self.catalog_series_substance_ids.clear();
self.catalog_experiment_series_ids.clear();
self.catalog_experiment_substance_ids.clear();
self.catalog_experiment_sample_ids.clear();
self.catalog_sample_filter = None;
self.catalog_contents_study_id = None;
self.catalog_publications.clear();
self.catalog_publication_index.clear();
self.catalog_artifacts.clear();
self.catalog_library_id = None;
self.catalog_loaded_path = None;
warn!("Catalog browsing failed: {error}");
self.catalog_status = Some(format!("Could not read catalog: {error}"));
}
}
}
fn create_catalog_study(&mut self, path: Option<&Path>) {
let Some(path) = path else { return };
let name = self.catalog_study_name.trim();
if name.is_empty() {
self.catalog_status = Some("Enter a study name first.".into());
return;
}
let study = CatalogStudy {
id: CatalogId::new(),
display_name: name.to_owned(),
description: (!self.catalog_study_description.trim().is_empty())
.then(|| self.catalog_study_description.trim().to_owned()),
};
match CatalogStore::open_existing(path).and_then(|mut store| store.insert_study(&study)) {
Ok(()) => {
self.catalog_study_id = Some(study.id);
self.catalog_study_name.clear();
self.catalog_study_description.clear();
self.refresh_catalog(Some(path));
self.catalog_status = Some("Study created.".into());
}
Err(error) => self.catalog_status = Some(format!("Could not create study: {error}")),
}
}
fn create_catalog_substance(&mut self, path: Option<&Path>) {
let Some(path) = path else { return };
let name = self.catalog_substance_name.trim();
if name.is_empty() {
self.catalog_status = Some("Enter a substance name first.".into());
return;
}
let substance = CatalogSubstance {
id: CatalogId::new(),
display_name: name.to_owned(),
formula: (!self.catalog_substance_formula.trim().is_empty())
.then(|| self.catalog_substance_formula.trim().to_owned()),
cas_number: (!self.catalog_substance_cas_number.trim().is_empty())
.then(|| self.catalog_substance_cas_number.trim().to_owned()),
inchi_key: (!self.catalog_substance_inchi_key.trim().is_empty())
.then(|| self.catalog_substance_inchi_key.trim().to_owned()),
description: (!self.catalog_substance_description.trim().is_empty())
.then(|| self.catalog_substance_description.trim().to_owned()),
};
let result = CatalogStore::open_existing(path)
.and_then(|mut store| store.insert_substance(&substance));
match result {
Ok(()) => {
self.catalog_substance_id = Some(substance.id);
self.catalog_substance_name.clear();
self.catalog_substance_formula.clear();
self.catalog_substance_cas_number.clear();
self.catalog_substance_inchi_key.clear();
self.catalog_substance_description.clear();
self.refresh_catalog(Some(path));
self.catalog_status = Some(
"Substance created. Add it to the selected study explicitly if needed.".into(),
);
}
Err(error) => {
self.catalog_status = Some(format!("Could not create substance: {error}"))
}
}
}
fn add_catalog_substance_to_study(&mut self, path: Option<&Path>) {
let (Some(path), Some(study_id), Some(substance_id)) = (
path,
self.catalog_study_id.as_ref(),
self.catalog_substance_id.as_ref(),
) else {
return;
};
match CatalogStore::open_existing(path)
.and_then(|mut store| store.add_substance_to_study(study_id, substance_id))
{
Ok(()) => {
self.refresh_catalog(Some(path));
self.catalog_status = Some("Substance added to study.".into());
}
Err(error) => self.catalog_status = Some(format!("Could not link substance: {error}")),
}
}
fn assign_current_series_substance(&mut self, path: Option<&Path>, model: &PlotModel) {
let (Some(path), Some(substance_id)) = (path, self.catalog_substance_id.as_ref()) else {
return;
};
let series_id = match CatalogId::parse(model.series.identity().to_string()) {
Ok(id) => id,
Err(error) => {
self.catalog_status =
Some(format!("Current series has no catalog identity: {error}"));
return;
}
};
match CatalogStore::open_existing(path)
.and_then(|mut store| store.assign_substance_to_series(&series_id, substance_id))
{
Ok(()) => {
self.refresh_catalog(Some(path));
self.catalog_status =
Some("Current series assigned to the selected substance.".into());
}
Err(error) => self.catalog_status = Some(format!("Could not assign series: {error}")),
}
}
fn add_current_series_to_study(&mut self, path: Option<&Path>, model: &PlotModel) {
let (Some(path), Some(study_id)) = (path, self.catalog_study_id.as_ref()) else {
return;
};
let series_id = match CatalogId::parse(model.series.identity().to_string()) {
Ok(id) => id,
Err(error) => {
self.catalog_status =
Some(format!("Current series has no catalog identity: {error}"));
return;
}
};
match CatalogStore::open_existing(path)
.and_then(|mut store| store.add_series_to_study(study_id, &series_id))
{
Ok(()) => {
self.refresh_catalog(Some(path));
self.catalog_status = Some("Current series added to study.".into());
}
Err(error) => {
self.catalog_status = Some(format!("Could not link series to study: {error}"))
}
}
}
fn create_and_assign_catalog_sample(&mut self, path: Option<&Path>, model: &PlotModel) {
let (Some(path), Some(substance_id)) = (path, self.catalog_substance_id.as_ref()) else {
return;
};
let Some(experiment) = model
.series
.experiments()
.iter()
.find(|experiment| experiment.meta.identity() == self.catalog_experiment_identity)
else {
self.catalog_status = Some("Select an experiment in the Catalog window first.".into());
return;
};
let experiment_id = match CatalogId::parse(experiment.meta.identity().to_string()) {
Ok(id) => id,
Err(error) => {
self.catalog_status = Some(format!(
"Selected experiment has no catalog identity: {error}"
));
return;
}
};
let name = self.catalog_sample_name.trim();
if name.is_empty() {
self.catalog_status = Some("Enter a sample name first.".into());
return;
}
let sample = CatalogSample {
id: CatalogId::new(),
substance_id: substance_id.clone(),
display_name: name.to_owned(),
batch_label: (!self.catalog_sample_batch.trim().is_empty())
.then(|| self.catalog_sample_batch.trim().to_owned()),
preparation_note: (!self.catalog_sample_preparation_note.trim().is_empty())
.then(|| self.catalog_sample_preparation_note.trim().to_owned()),
};
match CatalogStore::open_existing(path)
.and_then(|mut store| store.insert_sample_for_experiment(&sample, &experiment_id))
{
Ok(()) => {
self.catalog_sample_id = Some(sample.id);
self.catalog_sample_name.clear();
self.catalog_sample_batch.clear();
self.catalog_sample_preparation_note.clear();
self.refresh_catalog(Some(path));
self.catalog_status =
Some("Sample created and assigned to the selected experiment.".into());
}
Err(error) => self.catalog_status = Some(format!("Could not assign sample: {error}")),
}
}
fn assign_existing_catalog_sample(&mut self, path: Option<&Path>, model: &PlotModel) {
let (Some(path), Some(sample_id), Some(substance_id)) = (
path,
self.catalog_sample_id.as_ref(),
self.catalog_substance_id.as_ref(),
) else {
return;
};
let Some(experiment) = model
.series
.experiments()
.iter()
.find(|experiment| experiment.meta.identity() == self.catalog_experiment_identity)
else {
self.catalog_status = Some("Select an experiment in the Catalog window first.".into());
return;
};
let experiment_id = match CatalogId::parse(experiment.meta.identity().to_string()) {
Ok(id) => id,
Err(error) => {
self.catalog_status = Some(format!(
"Selected experiment has no catalog identity: {error}"
));
return;
}
};
let mut store = match CatalogStore::open_existing(path) {
Ok(store) => store,
Err(error) => {
self.catalog_status = Some(format!("Could not open catalog: {error}"));
return;
}
};
let sample = match store.get_sample(sample_id) {
Ok(sample) => sample,
Err(error) => {
self.catalog_status = Some(format!("Could not read sample: {error}"));
return;
}
};
if !sample
.as_ref()
.is_some_and(|sample| &sample.substance_id == substance_id)
{
self.catalog_status =
Some("Selected sample does not belong to the selected substance.".into());
return;
}
match store.assign_sample_to_experiment(&experiment_id, sample_id) {
Ok(()) => {
self.catalog_status = Some("Selected sample assigned to the experiment.".into());
}
Err(error) => self.catalog_status = Some(format!("Could not assign sample: {error}")),
}
}
fn refresh_selected_study(&mut self, path: Option<&Path>) {
self.catalog_study_substances.clear();
self.catalog_study_series.clear();
self.catalog_contents_study_id = self.catalog_study_id.clone();
let (Some(path), Some(study_id)) = (path, self.catalog_study_id.as_ref()) else {
return;
};
match CatalogStore::open_existing(path).and_then(|store| {
Ok((
store.list_study_substances(study_id)?,
store.list_study_series(study_id)?,
))
}) {
Ok((substances, series)) => {
self.catalog_study_substances = substances;
self.catalog_study_series = series;
}
Err(error) => {
warn!("Could not load catalog study contents: {error}");
self.catalog_status = Some(format!("Could not read study contents: {error}"));
}
}
}
fn show_catalog_study_contents(&self, ui: &mut egui::Ui) {
ui.small(format!(
"{} substances · {} series",
self.catalog_study_substances.len(),
self.catalog_study_series.len()
));
for substance in &self.catalog_study_substances {
let formula = substance
.formula
.as_ref()
.map(|value| format!(" ({value})"))
.unwrap_or_default();
let cas = substance
.cas_number
.as_ref()
.map(|value| format!(" | CAS {value}"))
.unwrap_or_default();
ui.label(format!(
"Substance: {}{formula}{cas}",
substance.display_name
));
}
for series in &self.catalog_study_series {
ui.label(format!("Series: {}", series.display_name));
}
}
fn export_catalog_study_manifest(
&mut self,
library_path: Option<&Path>,
study_id: &CatalogId,
destination: &Path,
) {
let Some(library_path) = library_path else {
self.catalog_status = Some("Choose a local catalog library first.".into());
return;
};
let result = (|| {
let manifest = CatalogStore::open_existing(library_path)?.study_manifest(study_id)?;
let json = manifest.to_json()?;
let parent = destination
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
use std::io::Write;
temporary.write_all(json.as_bytes())?;
temporary.as_file().sync_all()?;
temporary
.persist(destination)
.map_err(|error| error.error)?;
Ok::<_, Box<dyn std::error::Error>>(())
})();
match result {
Ok(()) => {
self.catalog_status = Some(format!(
"Study manifest exported to {}.",
destination.display()
));
}
Err(error) => {
warn!("Could not export catalog study manifest: {error}");
self.catalog_status = Some(format!("Could not export study manifest: {error}"));
}
}
}
fn publish_current_series(&mut self, model: &mut PlotModel, path: Option<&std::path::Path>) {
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
if model.series.is_empty() {
self.catalog_status = Some("There are no experiments to publish.".into());
return;
}
let name = self.catalog_series_name.trim();
if name.is_empty() {
self.catalog_status = Some("Enter a name for the series card.".into());
return;
}
let snapshot = (|| {
let store = CatalogStore::open_existing(path)?;
let series_id = CatalogId::parse(model.series.identity().to_string()).map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let catalog_series = CatalogSeries {
id: series_id.clone(),
display_name: name.to_string(),
description: Some(format!("{} experiments", model.series.len())),
};
let catalog_experiments = model
.series
.experiments()
.iter()
.map(|experiment| {
let identity = CatalogId::parse(experiment.meta.identity().to_string())
.map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let existing = store.get_experiment(&identity)?;
self.catalog_experiment_snapshot(experiment, existing)
})
.collect::<Result<
Vec<_>,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>>()?;
let series_members = model
.series
.experiments()
.iter()
.enumerate()
.map(|(index, experiment)| {
let ordinal = u32::try_from(index).map_err(|_| {
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::SeriesTooManyExperiments(index)
})?;
let experiment_id = CatalogId::parse(experiment.meta.identity().to_string())
.map_err(crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from)?;
Ok(PublishedSeriesMember { experiment_id, ordinal })
})
.collect::<Result<
Vec<_>,
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError,
>>()?;
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id,
parent_publication_id: self
.catalog_pending_files
.iter()
.any(|file| {
matches!(
file.purpose,
CatalogArtifactPurpose::PlotImage
| CatalogArtifactPurpose::EditableKiThePlot
)
})
.then(|| self.catalog_parent_publication.clone())
.flatten(),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: (!self.catalog_publish_author.trim().is_empty())
.then(|| self.catalog_publish_author.trim().to_string()),
description: (!self.catalog_publish_description.trim().is_empty())
.then(|| self.catalog_publish_description.trim().to_string()),
series_members,
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Series {
series: catalog_series.clone(),
experiments: catalog_experiments.clone(),
}),
typed_documents: vec![],
};
Ok::<_, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError>((
catalog_series,
catalog_experiments,
publication,
self.catalog_pending_files.clone(),
))
})();
match snapshot {
Ok((series, experiments, publication, files)) => {
self.start_catalog_publication(
path.to_path_buf(),
CatalogObjectKind::Series,
move |store, progress| {
store.register_and_publish_series_snapshot_with_progress(
&series,
&experiments,
&publication,
&files,
progress,
)
},
);
}
Err(error) => {
warn!("Local series publication failed: {error}");
self.catalog_status = Some(format!("Could not publish series: {error}"));
let _ = model.push_message(&format!("Catalog publication failed: {error}"));
}
}
}
fn publish_current_experiment(
&mut self,
model: &mut PlotModel,
path: Option<&std::path::Path>,
source_identity: String,
) {
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
let Some(experiment) = model
.series
.experiments()
.iter()
.find(|experiment| experiment.meta.identity() == source_identity)
else {
self.catalog_status = Some(
"The selected experiment is no longer in the current workspace. Refresh the selection and try again.".into(),
);
return;
};
let snapshot = (|| {
let store = CatalogStore::open_existing(path)?;
let id = CatalogId::parse(experiment.meta.identity().to_string()).map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let existing = store.get_experiment(&id)?;
let catalog_experiment = self.catalog_experiment_snapshot(experiment, existing)?;
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: id,
parent_publication_id: self
.catalog_pending_files
.iter()
.any(|file| {
matches!(
file.purpose,
CatalogArtifactPurpose::PlotImage
| CatalogArtifactPurpose::EditableKiThePlot
)
})
.then(|| self.catalog_parent_publication.clone())
.flatten(),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: (!self.catalog_publish_author.trim().is_empty())
.then(|| self.catalog_publish_author.trim().to_string()),
description: (!self.catalog_publish_description.trim().is_empty())
.then(|| self.catalog_publish_description.trim().to_string()),
series_members: vec![],
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Experiment(
catalog_experiment.clone(),
)),
typed_documents: vec![],
};
Ok::<_, crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError>((
catalog_experiment,
publication,
self.catalog_pending_files.clone(),
))
})();
match snapshot {
Ok((experiment, publication, files)) => {
self.start_catalog_publication(
path.to_path_buf(),
CatalogObjectKind::Experiment,
move |store, progress| {
store.register_and_publish_experiment_snapshot_with_progress(
&experiment,
&publication,
&files,
progress,
)
},
);
}
Err(error) => {
warn!("Local experiment publication failed: {error}");
self.catalog_status = Some(format!("Could not publish experiment: {error}"));
let _ = model.push_message(&format!("Catalog publication failed: {error}"));
}
}
}
fn register_current_experiment(
&mut self,
model: &PlotModel,
path: Option<&std::path::Path>,
source_identity: String,
) {
let Some(path) = path else {
self.catalog_status =
Some("Choose a local catalog library in TGA Settings first.".into());
return;
};
let Some(experiment) = model
.series
.experiments()
.iter()
.find(|experiment| experiment.meta.identity() == source_identity)
else {
self.catalog_status = Some(
"The selected experiment is no longer in the current workspace. Refresh the selection and try again.".into(),
);
return;
};
let result = (|| {
let mut store = CatalogStore::open_existing(path)?;
let id = CatalogId::parse(experiment.meta.identity().to_string()).map_err(
crate::Kinetics::experimental_kinetics::catalog::CatalogStoreError::from,
)?;
let existing = store.get_experiment(&id)?;
let snapshot = self.catalog_experiment_snapshot(experiment, existing)?;
store.register_experiment_snapshot(&snapshot)
})();
match result {
Ok(()) => {
self.refresh_catalog(Some(path));
self.catalog_status =
Some("Experiment metadata registered locally. No files were copied.".into());
}
Err(error) => {
warn!("Catalog experiment registration failed: {error}");
self.catalog_status = Some(format!("Could not register experiment: {error}"));
}
}
}
pub(crate) fn close_window_on_layer(&mut self, layer: Option<egui::LayerId>) -> bool {
let Some(layer) = layer else { return false };
let windows = [
("TGA Settings", &mut self.show_settings_window),
("Help", &mut self.show_help_window),
("Create Synthetic TGA Data", &mut self.show_synthetic_data),
("Operation History", &mut self.show_logs_window),
];
for (title, is_open) in windows {
if layer.id == egui::Id::unique(Some(title)) && *is_open {
*is_open = false;
return true;
}
}
false
}
pub fn new() -> Self {
Self::default()
}
pub fn show(ui: &mut egui::Ui, model: &mut PlotModel, test_options: &mut TestOptions) {
if ui.button("Load testing data").clicked() {
test_options.confirm_load_testing_data = true;
}
if ui.button("Create synthetic data").clicked() {
test_options.show_synthetic_data = true;
}
if ui.button("TGA Settings...").clicked() {
test_options.show_settings_window = true;
test_options.load_current_settings(&model.settings);
}
if ui.button("Show Logs").clicked() {
test_options.show_logs_window = true;
}
ui.separator();
if ui.button("Help").clicked() {
info!("Opening help window");
test_options.show_help_window = true;
let _ = test_options.reload_help();
ui.ctx().request_repaint();
}
}
pub fn show_load_testing_data_confirmation(
&mut self,
ctx: &egui::Context,
model: &mut PlotModel,
document: &mut crate::gui::experimental_kinetics_gui::controller_buttons_and_panels::NewExperimentDialogState,
) {
if !self.confirm_load_testing_data {
return;
}
let mut confirm_open = true;
let mut confirmed = false;
let mut canceled = false;
egui::Window::new("Replace workspace with test data?")
.open(&mut confirm_open)
.collapsible(false)
.show(ctx, |ui| {
ui.label("This replaces all current experiments. The current Save target will be cleared.");
ui.horizontal(|ui| {
if ui.button("Replace with test data").clicked() {
confirmed = true;
}
if ui.button("Cancel").clicked() {
canceled = true;
}
});
});
self.confirm_load_testing_data = confirm_open && !canceled;
if confirmed {
match try_load_model_with_one_curve() {
Ok(test_model) => {
*model = test_model;
document.reset_save_target_after_external_replacement(model);
let _ = model
.push_message("Loaded test data; use Save As to choose a destination.");
info!("Loaded packaged test data into a clean document session");
}
Err(error) => {
warn!("Could not load packaged test data: {error}");
let _ = model.push_message(&format!("Could not load test data: {error}"));
}
}
self.confirm_load_testing_data = false;
}
}
pub fn show_settings_window(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
let mut is_open = self.show_settings_window;
let mut close_clicked = false;
egui::Window::new("TGA Settings")
.open(&mut is_open)
.resizable(true)
.vscroll(true)
.default_width(400.0)
.show(ctx, |ui| {
ui.heading("Current Settings");
ui.separator();
ui.group(|ui| {
ui.label("Active Configuration:");
if let Some(cal) = model.settings.calibration_line() {
ui.label(format!("Calibration k: {}", cal.k()));
ui.label(format!("Calibration b: {}", cal.b()));
}
ui.label(format!(
"Default instrument: {}",
model.settings.default_instrument_name().unwrap_or("not set")
));
ui.label(format!(
"Default operator: {}",
model.settings.default_operator_name().unwrap_or("not set")
));
if let Some(n) = model.settings.n_points() {
ui.label(format!("Number of points: {}", n));
}
if let Some(log) = model.settings.log_level() {
ui.label(format!("Log level: {}", log));
}
});
ui.add_space(8.0);
ui.separator();
ui.heading("Local Catalog Library");
ui.label("Choose a folder for the local SQLite catalog. Experimental files remain outside the database.");
if self.temp_catalog_path.is_empty() {
if let Some(path) = model.settings.catalog().local_library_path.as_ref() {
self.temp_catalog_path = path.display().to_string();
}
}
ui.horizontal(|ui| {
ui.label("Library folder:");
ui.add(
egui::TextEdit::singleline(&mut self.temp_catalog_path)
.desired_width(220.0)
.id_salt("catalog_library_path"),
);
if ui.button("Browse...").clicked() {
#[cfg(test)]
let selected = self.test_catalog_directory.take();
#[cfg(not(test))]
let selected = rfd::FileDialog::new().pick_folder();
if let Some(path) = selected {
self.temp_catalog_path = path.display().to_string();
}
}
});
if let Some(library_id) = model.settings.catalog().local_library_id.as_deref() {
ui.small(format!("Configured library ID: {library_id}"));
}
if ui.button("Open / Create local library").clicked() {
let path = std::path::PathBuf::from(self.temp_catalog_path.trim());
if self.temp_catalog_path.trim().is_empty() {
self.catalog_status = Some("Choose a library folder first.".into());
} else {
match CatalogStore::open(&path) {
Ok(store) => {
let mut catalog = model.settings.catalog().clone();
catalog.local_library_id = Some(store.library_id().to_string());
catalog.local_library_path = Some(path);
model.settings.set_catalog(catalog);
self.catalog_status = Some(
"Local catalog is ready. Save Settings to remember this location.".into(),
);
}
Err(error) => {
self.catalog_status = Some(format!("Could not open local catalog: {error}"));
}
}
}
}
if let Some(status) = &self.catalog_status {
ui.label(status);
}
ui.add_space(10.0);
ui.separator();
ui.heading("Edit Settings");
ui.group(|ui| {
ui.label("New-experiment defaults (stored on this computer):");
ui.label("Instrument name / inventory number:");
ui.text_edit_singleline(&mut self.temp_instrument_name);
ui.label("Operator:");
ui.text_edit_singleline(&mut self.temp_operator_name);
});
ui.group(|ui| {
ui.label("This computer's calibration (mass = k * voltage + b):");
ui.horizontal(|ui| {
ui.label("k:");
ui.text_edit_singleline(&mut self.temp_k);
});
ui.horizontal(|ui| {
ui.label("b:");
ui.text_edit_singleline(&mut self.temp_b);
});
});
ui.add_space(5.0);
ui.horizontal(|ui| {
ui.label("Number of plot points:");
ui.text_edit_singleline(&mut self.temp_n_points);
});
ui.add_space(5.0);
ui.horizontal(|ui| {
ui.label("Log level:");
egui::ComboBox::from_id_salt("log_level_combo")
.selected_text(&self.temp_log_level)
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.temp_log_level, "off".to_string(), "off");
ui.selectable_value(
&mut self.temp_log_level,
"error".to_string(),
"error",
);
ui.selectable_value(
&mut self.temp_log_level,
"warn".to_string(),
"warn",
);
ui.selectable_value(
&mut self.temp_log_level,
"info".to_string(),
"info",
);
ui.selectable_value(
&mut self.temp_log_level,
"debug".to_string(),
"debug",
);
ui.selectable_value(
&mut self.temp_log_level,
"trace".to_string(),
"trace",
);
});
});
ui.add_space(10.0);
ui.separator();
ui.horizontal(|ui| {
if ui.button("Save Settings").clicked() {
if let Err(e) = self.apply_settings(model) {
warn!("Error applying settings: {:?}", e);
model.push_message(&format!("Error: {:?}", e)).ok();
} else {
model.push_message("Settings saved successfully").ok();
}
}
if ui.button("Reset to Defaults").clicked() {
model.settings = Settings::default();
self.load_current_settings(&model.settings);
model.push_message("Settings reset to defaults").ok();
}
if ui.button("Close").clicked() {
close_clicked = true;
}
});
if !model.message.is_empty() {
ui.add_space(5.0);
ui.colored_label(egui::Color32::GREEN, &model.message);
}
});
self.show_settings_window = is_open && !close_clicked;
}
pub fn show_synthetic_data_window(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
if !self.show_synthetic_data {
return;
}
let mut open = self.show_synthetic_data;
let mut close_clicked = false;
egui::Window::new("Create Synthetic TGA Data")
.open(&mut open)
.resizable(true)
.vscroll(true)
.default_width(720.0)
.default_height(620.0)
.show(ctx, |ui| {
ui.heading("AdvancedTGAConfig");
ui.separator();
ui.group(|ui| {
ui.heading("General");
ui.horizontal(|ui| {
ui.label("n_points:");
ui.text_edit_singleline(&mut self.syn_n_points);
ui.label("dt (s):");
ui.text_edit_singleline(&mut self.syn_dt);
ui.label("seed:");
ui.text_edit_singleline(&mut self.syn_seed);
});
});
ui.add_space(6.0);
ui.group(|ui| {
ui.heading("Experiment Mode");
egui::ComboBox::from_id_salt("syn_mode")
.selected_text(match self.syn_mode {
0 => "Isothermal",
_ => "NonIsothermal",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.syn_mode, 0, "Isothermal");
ui.selectable_value(&mut self.syn_mode, 1, "NonIsothermal");
});
match self.syn_mode {
0 => {
ui.horizontal(|ui| {
ui.label("temperatures (K, csv):");
ui.text_edit_singleline(&mut self.syn_iso_temperatures);
});
}
_ => {
ui.horizontal(|ui| {
ui.label("t0 (K):");
ui.text_edit_singleline(&mut self.syn_ni_t0);
ui.label("heating_rates (K/min, csv):");
ui.text_edit_singleline(&mut self.syn_ni_heating_rates);
});
}
}
});
ui.add_space(6.0);
ui.group(|ui| {
ui.heading("Kinetic Model");
egui::ComboBox::from_id_salt("syn_kmodel")
.selected_text(match self.syn_kmodel {
0 => "ArrheniusSingle",
_ => "ArrheniusTwoComponent",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.syn_kmodel, 0, "ArrheniusSingle");
ui.selectable_value(&mut self.syn_kmodel, 1, "ArrheniusTwoComponent");
});
match self.syn_kmodel {
0 => {
egui::Grid::new("km_single").num_columns(8).show(ui, |ui| {
ui.label("m0");
ui.text_edit_singleline(&mut self.syn_m0);
ui.label("k0");
ui.text_edit_singleline(&mut self.syn_k0);
ui.label("E");
ui.text_edit_singleline(&mut self.syn_e);
ui.label("R");
ui.text_edit_singleline(&mut self.syn_r);
});
}
_ => {
egui::Grid::new("km_two").num_columns(14).show(ui, |ui| {
ui.label("m01");
ui.text_edit_singleline(&mut self.syn_m01);
ui.label("k01");
ui.text_edit_singleline(&mut self.syn_k01);
ui.label("E1");
ui.text_edit_singleline(&mut self.syn_e1);
ui.label("m02");
ui.text_edit_singleline(&mut self.syn_m02);
ui.label("k02");
ui.text_edit_singleline(&mut self.syn_k02);
ui.label("E2");
ui.text_edit_singleline(&mut self.syn_e2);
ui.label("R");
ui.text_edit_singleline(&mut self.syn_r2);
});
}
}
});
ui.add_space(6.0);
ui.group(|ui| {
ui.heading("Mass noise");
ui.checkbox(&mut self.syn_mass_noise_enabled, "enabled");
egui::ComboBox::from_id_salt("mass_noise_kind")
.selected_text(match self.syn_mass_noise_kind {
0 => "Gaussian",
1 => "Uniform",
_ => "Drift",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.syn_mass_noise_kind, 0, "Gaussian");
ui.selectable_value(&mut self.syn_mass_noise_kind, 1, "Uniform");
ui.selectable_value(&mut self.syn_mass_noise_kind, 2, "Drift");
});
match self.syn_mass_noise_kind {
0 => {
ui.horizontal(|ui| {
ui.label("sigma");
ui.text_edit_singleline(&mut self.syn_mass_sigma);
});
}
1 => {
ui.horizontal(|ui| {
ui.label("amplitude");
ui.text_edit_singleline(&mut self.syn_mass_ampl);
});
}
_ => {
ui.horizontal(|ui| {
ui.label("slope");
ui.text_edit_singleline(&mut self.syn_mass_slope);
});
}
}
ui.separator();
ui.heading("Temperature noise");
ui.checkbox(&mut self.syn_temp_noise_enabled, "enabled");
egui::ComboBox::from_id_salt("temp_noise_kind")
.selected_text(match self.syn_temp_noise_kind {
0 => "Gaussian",
1 => "Uniform",
_ => "Drift",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut self.syn_temp_noise_kind, 0, "Gaussian");
ui.selectable_value(&mut self.syn_temp_noise_kind, 1, "Uniform");
ui.selectable_value(&mut self.syn_temp_noise_kind, 2, "Drift");
});
match self.syn_temp_noise_kind {
0 => {
ui.horizontal(|ui| {
ui.label("sigma");
ui.text_edit_singleline(&mut self.syn_temp_sigma);
});
}
1 => {
ui.horizontal(|ui| {
ui.label("amplitude");
ui.text_edit_singleline(&mut self.syn_temp_ampl);
});
}
_ => {
ui.horizontal(|ui| {
ui.label("slope");
ui.text_edit_singleline(&mut self.syn_temp_slope);
});
}
}
ui.separator();
ui.heading("Spikes");
ui.checkbox(&mut self.syn_spikes_enabled, "enabled");
ui.horizontal(|ui| {
ui.label("probability");
ui.text_edit_singleline(&mut self.syn_spike_prob);
ui.label("amplitude");
ui.text_edit_singleline(&mut self.syn_spike_ampl);
});
});
if let Some(status) = &self.syn_status {
ui.colored_label(egui::Color32::YELLOW, status);
}
ui.separator();
ui.horizontal(|ui| {
if ui.button("Generate synthetic data").clicked() {
match self.try_build_config() {
Ok(cfg) => {
match model.generate_synthetic_data_from_config(&cfg) {
Ok(()) => {
self.syn_status =
Some("Synthetic data generated".to_string());
}
Err(e) => {
self.syn_status =
Some(format!("Error generating data: {:?}", e));
}
}
}
Err(err) => {
self.syn_status = Some(err);
}
}
}
if ui.button("Close").clicked() {
close_clicked = true;
}
});
});
self.show_synthetic_data = open && !close_clicked;
}
pub fn show_logs_window(&mut self, ctx: &egui::Context, model: &mut PlotModel) {
if !self.show_logs_window {
return;
}
let mut open = self.show_logs_window;
let mut feed = model
.history_feed_for_selected()
.unwrap_or_else(|err| format!("No history available: {:?}", err));
egui::Window::new("Operation History")
.open(&mut open)
.resizable(true)
.default_width(760.0)
.default_height(420.0)
.show(ctx, |ui| {
ui.label("Selected experiment history");
ui.separator();
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.show(ui, |ui| {
ui.add(
egui::TextEdit::multiline(&mut feed)
.code_editor()
.desired_rows(20)
.interactive(false),
);
});
});
self.show_logs_window = open;
}
fn parse_csv_f64(s: &str) -> Result<Vec<f64>, String> {
let t = s.trim();
if t.is_empty() {
return Ok(Vec::new());
}
t.split([',', ';', ' '])
.filter(|p| !p.trim().is_empty())
.map(|p| {
p.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid float: {}", p))
})
.collect()
}
fn parse_bool_opt_noise(
kind: usize,
sigma: &str,
ampl: &str,
slope: &str,
) -> Result<NoiseConfig, String> {
let k = match kind {
0 => {
let s = sigma
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid sigma: {}", sigma))?;
NoiseKind::Gaussian { sigma: s }
}
1 => {
let a = ampl
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid amplitude: {}", ampl))?;
NoiseKind::Uniform { amplitude: a }
}
2 => {
let sl = slope
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid slope: {}", slope))?;
NoiseKind::Drift { slope: sl }
}
_ => return Err("Unknown noise kind".to_string()),
};
Ok(NoiseConfig { kind: k })
}
fn try_build_config(&self) -> Result<AdvancedTGAConfig, String> {
let n_points = self
.syn_n_points
.trim()
.parse::<usize>()
.map_err(|_| format!("Invalid n_points: {}", self.syn_n_points))?;
let dt = self
.syn_dt
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid dt: {}", self.syn_dt))?;
let seed = self
.syn_seed
.trim()
.parse::<u64>()
.map_err(|_| format!("Invalid seed: {}", self.syn_seed))?;
let experiment_mode = match self.syn_mode {
0 => {
let temps = Self::parse_csv_f64(&self.syn_iso_temperatures)?;
if temps.is_empty() {
return Err("Isothermal mode requires non-empty temperatures".to_string());
}
ExperimentMode::Isothermal {
temperatures: temps,
}
}
_ => {
let t0 = self
.syn_ni_t0
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid t0: {}", self.syn_ni_t0))?;
let betas = Self::parse_csv_f64(&self.syn_ni_heating_rates)?;
if betas.is_empty() {
return Err("NonIsothermal mode requires non-empty heating_rates".to_string());
}
ExperimentMode::NonIsothermal {
t0,
heating_rates: betas,
}
}
};
let kinetic_model = match self.syn_kmodel {
0 => {
let m0 = self
.syn_m0
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid m0: {}", self.syn_m0))?;
let k0 = self
.syn_k0
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid k0: {}", self.syn_k0))?;
let e = self
.syn_e
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid E: {}", self.syn_e))?;
let r = self
.syn_r
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid R: {}", self.syn_r))?;
KineticModel::ArrheniusSingle { m0, k0, e, r }
}
_ => {
let m01 = self
.syn_m01
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid m01: {}", self.syn_m01))?;
let k01 = self
.syn_k01
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid k01: {}", self.syn_k01))?;
let e1 = self
.syn_e1
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid e1: {}", self.syn_e1))?;
let m02 = self
.syn_m02
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid m02: {}", self.syn_m02))?;
let k02 = self
.syn_k02
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid k02: {}", self.syn_k02))?;
let e2 = self
.syn_e2
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid e2: {}", self.syn_e2))?;
let r = self
.syn_r2
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid R: {}", self.syn_r2))?;
KineticModel::ArrheniusTwoComponent {
m01,
k01,
e1,
m02,
k02,
e2,
r,
}
}
};
let mass_noise = if self.syn_mass_noise_enabled {
Some(Self::parse_bool_opt_noise(
self.syn_mass_noise_kind,
&self.syn_mass_sigma,
&self.syn_mass_ampl,
&self.syn_mass_slope,
)?)
} else {
None
};
let temp_noise = if self.syn_temp_noise_enabled {
Some(Self::parse_bool_opt_noise(
self.syn_temp_noise_kind,
&self.syn_temp_sigma,
&self.syn_temp_ampl,
&self.syn_temp_slope,
)?)
} else {
None
};
let spikes = if self.syn_spikes_enabled {
let p = self
.syn_spike_prob
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid spike probability: {}", self.syn_spike_prob))?;
let a = self
.syn_spike_ampl
.trim()
.parse::<f64>()
.map_err(|_| format!("Invalid spike amplitude: {}", self.syn_spike_ampl))?;
Some(SpikeModel {
probability: p,
amplitude: a,
})
} else {
None
};
Ok(AdvancedTGAConfig {
n_points,
dt,
experiment_mode,
kinetic_model,
mass_noise,
temp_noise,
spikes,
seed,
})
}
fn load_current_settings(&mut self, settings: &Settings) {
if let Some(cal) = settings.calibration_line() {
self.temp_k = cal.k().to_string();
self.temp_b = cal.b().to_string();
} else {
self.temp_k = "40.0".to_string();
self.temp_b = "-1.0".to_string();
}
self.temp_instrument_name = settings
.default_instrument_name()
.unwrap_or_default()
.into();
self.temp_operator_name = settings.default_operator_name().unwrap_or_default().into();
self.temp_n_points = settings
.n_points()
.map(|n| n.to_string())
.unwrap_or_else(|| "1000".to_string());
self.temp_log_level = settings.log_level().unwrap_or("info").to_string();
}
fn apply_settings(&self, model: &mut PlotModel) -> Result<(), String> {
self.apply_settings_to_path(model, Path::new("tgasettings.json"))
}
fn apply_settings_to_path(&self, model: &mut PlotModel, path: &Path) -> Result<(), String> {
let k = self
.temp_k
.parse::<f64>()
.map_err(|_| format!("Invalid k value: '{}'", self.temp_k))?;
let b = self
.temp_b
.parse::<f64>()
.map_err(|_| format!("Invalid b value: '{}'", self.temp_b))?;
let n_points = self
.temp_n_points
.parse::<usize>()
.map_err(|_| format!("Invalid n_points value: '{}'", self.temp_n_points))?;
if !k.is_finite() || !b.is_finite() {
return Err("Calibration coefficients must be finite".into());
}
if n_points == 0 {
return Err("Number of plot points must be greater than zero".into());
}
let mut candidate = model.settings.clone();
candidate.set_calibration_line(Some(CalibrationLine::new(k, b)));
candidate.set_acquisition_defaults(
Some(self.temp_instrument_name.clone()),
Some(self.temp_operator_name.clone()),
);
candidate.set_n_points(Some(n_points));
candidate.set_log_level(Some(self.temp_log_level.clone()));
candidate
.save_to_file(path)
.map_err(|e| format!("Failed to save settings: {:?}", e))?;
model.settings = candidate;
Ok(())
}
pub fn is_settings_window_open(&self) -> bool {
self.show_settings_window
}
}
fn artifact_purpose_label(purpose: &CatalogArtifactPurpose) -> &'static str {
match purpose {
CatalogArtifactPurpose::RawInstrumentData => "Raw instrument data",
CatalogArtifactPurpose::TypedKiTheDocument => "Typed KiThe document",
CatalogArtifactPurpose::ProcessedResults => "Processed results",
CatalogArtifactPurpose::PlotImage => "Plot image",
CatalogArtifactPurpose::EditableKiThePlot => "Editable .kplot",
CatalogArtifactPurpose::Other => "Other",
}
}
fn show_catalog_experiment_snapshot(ui: &mut egui::Ui, experiment: &CatalogExperiment) {
ui.collapsing(&experiment.display_name, |ui| {
ui.label(format!(
"Origin: {} | Thermal mode: {}",
source_kind_label(&experiment.source_kind),
thermal_mode_label(experiment.thermal_mode)
));
if let Some(date) = &experiment.date {
ui.label(format!("Date: {date}"));
}
if let Some(sample) = &experiment.sample {
ui.label(format!("Sample label: {sample}"));
}
if let Some(instrument) = &experiment.instrument {
ui.label(format!("Instrument: {instrument}"));
}
if let Some(operator) = &experiment.operator {
ui.label(format!("Operator: {operator}"));
}
if let Some(temperature) = experiment.temperature_k {
ui.label(format!("Isothermal temperature: {temperature} K"));
}
if let Some(rate) = experiment.heating_rate_k_per_min {
ui.label(format!("Heating rate: {rate} K/min"));
}
if let Some(note) = &experiment.comment {
ui.label(note);
}
if !experiment.tags.is_empty() {
ui.small(format!("Tags: {}", experiment.tags.join(", ")));
}
});
}
fn show_catalog_typed_document_summary(
ui: &mut egui::Ui,
document: &crate::Kinetics::experimental_kinetics::catalog::CatalogTypedDocumentSummary,
) {
use crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind;
ui.collapsing(
format!("Scientific results: {}", document.file_name),
|ui| {
for output in &document.kinetic_method_outputs {
ui.collapsing(
format!(
"{}: {} -> {} ({})",
output.method,
output.experiment_id_snapshot,
output.output_column,
output.output_unit
),
|ui| {
if let Some(model) = &output.model {
ui.label(format!("Model: {model}"));
}
if let Some(solver) = &output.solver {
ui.label(format!("Solver: {solver}"));
}
ui.label(format!("Source identity: {}", output.experiment_identity));
for source in &output.sources {
ui.label(format!(
"Input: {} [{}]",
source.experiment_id_snapshot,
source.columns.join(", ")
));
for (column, unit) in &source.column_units {
ui.small(format!("{column}: {unit}"));
}
for (name, value) in &source.conditions {
ui.small(format!("Condition: {name} = {value:.6}"));
}
}
if let Some((axis, start, end)) = &output.value_range {
ui.label(format!("Range: {axis} = {start:.6} .. {end:.6}"));
}
for (name, value) in &output.parameters {
ui.label(format!("{name} = {value:.8}"));
}
for diagnostic in &output.diagnostics {
ui.small(diagnostic);
}
},
);
}
for record in &document.analysis_results {
match &record.kind {
AnalysisResultKind::ParameterSet(result) => {
ui.collapsing(format!("{} / {}", result.method, result.model), |ui| {
if let Some(formula) = &result.formula {
ui.label(format!("Formula: {formula}"));
}
if let Some(solver) = &result.solver {
ui.label(format!("Solver: {solver}"));
}
if let Some(range) = &result.range {
ui.label(format!(
"Fit range: {} = {:.6} .. {:.6}",
range.axis, range.start, range.end
));
}
if let Some(range) = &result.excluded_range {
ui.label(format!(
"Excluded range: {} = {:.6} .. {:.6}",
range.axis, range.start, range.end
));
}
if let (Some(x), Some(y)) = (&result.x_column, &result.y_column) {
ui.label(format!(
"Fit columns: {} ({}) vs {} ({})",
x,
result.x_unit.as_deref().unwrap_or("unit unknown"),
y,
result.y_unit.as_deref().unwrap_or("unit unknown")
));
}
for condition in &result.conditions {
ui.label(format!(
"Condition {} = {:.8} {}",
condition.name, condition.value, condition.unit
));
}
for (name, value) in &result.settings {
ui.small(format!("Setting: {name} = {value}"));
}
for source in &record.source_experiments {
ui.label(format!(
"Source: {} ({})",
source.experiment_id_snapshot, source.experiment_identity
));
}
for coefficient in &result.coefficients {
let stage = coefficient
.stage
.as_deref()
.map(|stage| format!(" [{stage}]"))
.unwrap_or_default();
ui.label(format!(
"{}{} = {:.8} {}",
coefficient.name, stage, coefficient.value, coefficient.unit
));
}
for (name, value, unit) in &result.diagnostics {
ui.small(format!("{name}: {value:.6} {unit}"));
}
});
}
AnalysisResultKind::ArrheniusFit(fit) => {
ui.collapsing("Arrhenius fit", |ui| {
ui.label(format!(
"Activation energy: {:.6} kJ/mol",
fit.activation_energy_j_per_mol / 1000.0
));
if let Some(rate) = fit.pre_exponential_per_second {
ui.label(format!("Pre-exponential factor: {rate:.8} 1/s"));
}
ui.label(format!("Data points: {}", fit.points.len()));
for point in &fit.points {
ui.small(format!(
"{}: T = {:.4} K, k = {:.8} 1/s",
point.experiment_id,
point.temperature_kelvin,
point.rate_per_second
));
}
});
}
}
}
},
);
}
fn typed_document_matches_query(
query: &str,
document: &crate::Kinetics::experimental_kinetics::catalog::CatalogTypedDocumentSummary,
) -> bool {
if query.is_empty() {
return true;
}
if catalog_text_matches(query, &[&document.file_name]) {
return true;
}
document.kinetic_method_outputs.iter().any(|output| {
let fields = [
output.method.as_str(),
output.model.as_deref().unwrap_or_default(),
output.solver.as_deref().unwrap_or_default(),
output.output_column.as_str(),
output.experiment_id_snapshot.as_str(),
];
catalog_text_matches(query, &fields)
|| output
.parameters
.iter()
.any(|(name, value)| format!("{name} {value}").to_lowercase().contains(query))
|| output
.value_range
.as_ref()
.is_some_and(|(axis, start, end)| {
format!("{axis} {start} {end}")
.to_lowercase()
.contains(query)
})
|| output
.diagnostics
.iter()
.any(|diagnostic| diagnostic.to_lowercase().contains(query))
|| output.sources.iter().any(|source| {
source.experiment_id_snapshot.to_lowercase().contains(query)
|| source
.columns
.iter()
.any(|column| column.to_lowercase().contains(query))
|| source.conditions.iter().any(|(name, value)| {
format!("{name} {value}").to_lowercase().contains(query)
})
|| source.column_units.iter().any(|(column, unit)| {
format!("{column} {unit}").to_lowercase().contains(query)
})
})
}) || document.analysis_results.iter().any(|record| {
match &record.kind {
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ParameterSet(
result,
) => {
catalog_text_matches(query, &[&result.method, &result.model])
|| result.formula.as_deref().is_some_and(|formula| {
formula.to_lowercase().contains(query)
})
|| result.coefficients.iter().any(|coefficient| {
format!(
"{} {} {} {}",
coefficient.name,
coefficient.stage.as_deref().unwrap_or_default(),
coefficient.value,
coefficient.unit
)
.to_lowercase()
.contains(query)
})
}
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ArrheniusFit(
_,
) => "arrhenius".contains(query),
}
})
}
fn typed_document_has_method(
document: &crate::Kinetics::experimental_kinetics::catalog::CatalogTypedDocumentSummary,
method: &str,
) -> bool {
document
.kinetic_method_outputs
.iter()
.any(|output| output.method.eq_ignore_ascii_case(method))
|| document.analysis_results.iter().any(|record| match &record.kind {
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ParameterSet(result) => {
result.method.eq_ignore_ascii_case(method)
}
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ArrheniusFit(_) => {
method.eq_ignore_ascii_case("Arrhenius")
}
})
}
fn typed_document_method_mentions_experiment(
document: &crate::Kinetics::experimental_kinetics::catalog::CatalogTypedDocumentSummary,
method: &str,
experiment: &CatalogId,
) -> bool {
document.kinetic_method_outputs.iter().any(|output| {
output.method.eq_ignore_ascii_case(method)
&& (output.experiment_identity == experiment.as_str()
|| output
.sources
.iter()
.any(|source| source.experiment_identity == experiment.as_str()))
}) || document.analysis_results.iter().any(|record| {
let method_matches = match &record.kind {
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ParameterSet(result) => {
result.method.eq_ignore_ascii_case(method)
}
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ArrheniusFit(fit) => {
method.eq_ignore_ascii_case("Arrhenius")
&& fit.points.iter().any(|point| point.experiment_identity == experiment.as_str())
}
};
let source_matches = record
.source_experiments
.iter()
.any(|source| source.experiment_identity == experiment.as_str())
|| matches!(
&record.kind,
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ArrheniusFit(fit)
if fit.points.iter().any(|point| point.experiment_identity == experiment.as_str())
);
method_matches && source_matches
})
}
fn source_kind_label(kind: &SourceKind) -> &'static str {
match kind {
SourceKind::Measured => "Measured",
SourceKind::Synthetic => "Synthetic",
SourceKind::Reconstructed => "Reconstructed",
SourceKind::Mixed => "Mixed",
SourceKind::Unknown => "Unspecified",
}
}
fn optional_trimmed(value: &str) -> Option<String> {
let value = value.trim();
(!value.is_empty()).then(|| value.to_string())
}
fn parse_catalog_tags(input: &str) -> Vec<String> {
let mut seen = HashSet::new();
input
.split(',')
.map(str::trim)
.filter(|tag| !tag.is_empty())
.filter(|tag| seen.insert(tag.to_lowercase()))
.map(str::to_string)
.collect()
}
fn thermal_mode_label(mode: Option<CatalogThermalMode>) -> &'static str {
match mode {
Some(CatalogThermalMode::Isothermal) => "Isothermal",
Some(CatalogThermalMode::NonIsothermal) => "Non-isothermal",
Some(CatalogThermalMode::Unspecified) | None => "Unspecified",
}
}
fn catalog_text_matches(query: &str, candidates: &[&str]) -> bool {
let query = query.to_lowercase();
query.is_empty()
|| candidates
.iter()
.any(|candidate| candidate.to_lowercase().contains(&query))
}
fn show_external_artifact_actions(
ui: &mut egui::Ui,
listing: &CatalogArtifactListing,
model: &mut PlotModel,
status: &mut Option<String>,
integrity: Option<&LocalArtifactIntegrity>,
plot_editor: Option<
&mut crate::gui::experimental_kinetics_gui::kitheplot_wrapper::KiThePlotWindowState,
>,
) {
let LocalArtifactResolution::Available(path) = &listing.local_resolution else {
return;
};
if ui.button("Show folder").clicked() {
let result = path
.parent()
.ok_or_else(|| "The catalog attachment has no parent folder.".to_string())
.and_then(open_with_system_application);
report_external_open_result(result, status, model);
}
if listing.artifact.purpose == CatalogArtifactPurpose::PlotImage {
if let Some(label) = catalog_open_action_label(&listing.artifact.purpose, integrity) {
if ui.button(label).clicked() {
report_external_open_result(open_with_system_application(path), status, model);
}
} else {
ui.small("Verify checksum before opening this image.");
}
}
if listing.artifact.purpose == CatalogArtifactPurpose::EditableKiThePlot {
if let Some(label) = catalog_open_action_label(&listing.artifact.purpose, integrity) {
if ui.button(label).clicked() {
let result = plot_editor
.ok_or_else(|| {
"The KiThe Plot Editor is not available in this window.".to_string()
})
.and_then(|editor| editor.open_catalog_project(ui.ctx(), path));
report_external_open_result(result, status, model);
}
} else {
ui.small("Verify checksum before opening this KiThePlot project.");
}
}
}
fn catalog_open_action_label(
purpose: &CatalogArtifactPurpose,
integrity: Option<&LocalArtifactIntegrity>,
) -> Option<&'static str> {
let is_modified = matches!(integrity, Some(LocalArtifactIntegrity::Modified { .. }));
if !is_modified && !matches!(integrity, Some(LocalArtifactIntegrity::Verified)) {
return None;
}
match (purpose, is_modified) {
(CatalogArtifactPurpose::TypedKiTheDocument, false) => {
Some("Open / Import typed document...")
}
(CatalogArtifactPurpose::TypedKiTheDocument, true) => {
Some("Open current file from disk...")
}
(CatalogArtifactPurpose::RawInstrumentData, false) => Some("Import raw data..."),
(CatalogArtifactPurpose::RawInstrumentData, true) => {
Some("Import current file from disk...")
}
(CatalogArtifactPurpose::PlotImage, false) => Some("Open image with system app"),
(CatalogArtifactPurpose::PlotImage, true) => Some("Open current image from disk..."),
(CatalogArtifactPurpose::EditableKiThePlot, false) => Some("Open in KiThe Plot Editor"),
(CatalogArtifactPurpose::EditableKiThePlot, true) => {
Some("Open current file in KiThe Plot Editor...")
}
_ => None,
}
}
fn open_with_system_application(path: &Path) -> Result<(), String> {
if !path.exists() {
return Err(format!(
"Catalog path is no longer available: {}",
path.display()
));
}
#[cfg(target_os = "windows")]
let result = Command::new("explorer.exe").arg(path).spawn();
#[cfg(target_os = "macos")]
let result = Command::new("open").arg(path).spawn();
#[cfg(all(unix, not(target_os = "macos")))]
let result = Command::new("xdg-open").arg(path).spawn();
#[cfg(not(any(target_os = "windows", target_os = "macos", unix)))]
return Err("Opening paths with a system application is unsupported on this platform.".into());
result
.map(|_| ())
.map_err(|error| format!("Could not open '{}': {error}", path.display()))
}
fn report_external_open_result(
result: Result<(), String>,
status: &mut Option<String>,
model: &mut PlotModel,
) {
if let Err(message) = result {
warn!("Catalog external open failed: {message}");
*status = Some(message.clone());
let _ = model.push_message(&message);
}
}
fn local_artifact_status(resolution: &LocalArtifactResolution) -> String {
match resolution {
LocalArtifactResolution::Available(path) => format!(
"Local file found (checksum not checked): {}",
path.display()
),
LocalArtifactResolution::Missing(path) => {
format!("Local file is missing: {}", path.display())
}
LocalArtifactResolution::NoLocalCopy => "No local copy".into(),
}
}
fn local_artifact_root_id(artifact: &CatalogArtifact) -> Option<String> {
artifact
.locations
.iter()
.find_map(|location| match location {
crate::Kinetics::experimental_kinetics::catalog::ArtifactLocation::Local {
root_id,
..
} => Some(root_id.clone()),
crate::Kinetics::experimental_kinetics::catalog::ArtifactLocation::Server {
..
} => None,
})
}
fn local_integrity_status(integrity: &LocalArtifactIntegrity) -> String {
match integrity {
LocalArtifactIntegrity::Verified => {
"Last checksum verification: file matched the published snapshot.".into()
}
LocalArtifactIntegrity::Modified {
path,
expected_sha256,
actual_sha256,
} => format!(
"Checksum mismatch for {}: expected {}, found {}. Verify the changed source before creating a new publication; the existing publication is unchanged.",
path.display(),
expected_sha256,
actual_sha256
),
LocalArtifactIntegrity::Missing(path) => {
format!(
"Checksum not checked: file is missing at {}.",
path.display()
)
}
LocalArtifactIntegrity::NoLocalCopy => {
"Checksum not checked: no local file is available.".into()
}
}
}
fn detect_catalog_file_format(path: &Path) -> String {
let extension = path
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
match std::fs::File::open(path) {
Ok(file) => {
use std::io::BufRead;
let lines = std::io::BufReader::new(file)
.lines()
.take(16)
.collect::<Result<Vec<_>, _>>();
match lines {
Ok(lines)
if lines.iter().any(|line| line.starts_with("#META\t"))
|| lines
.first()
.is_some_and(|line| line.starts_with("# format_version=")) =>
{
"typed KiThe series CSV".into()
}
Ok(lines) if lines.iter().any(|line| line == "# KiThe TGA Dataset") => {
"typed KiThe dataset CSV".into()
}
Ok(_) => match extension.as_str() {
"csv" => "CSV (raw/untyped unless header says otherwise)".into(),
"txt" | "tsv" => "delimited text (raw/untyped)".into(),
"kplot" => "KiThePlot project".into(),
"png" | "jpg" | "jpeg" | "bmp" | "webp" => "plot image".into(),
"xlsx" | "xls" => "Excel workbook".into(),
_ => "unrecognized file format".into(),
},
Err(_) => "could not read file header".into(),
}
}
Err(_) => "file unavailable".into(),
}
}
fn publication_total_bytes(
publication: &CatalogPublication,
artifacts: &HashMap<CatalogId, CatalogArtifactListing>,
) -> u64 {
publication
.artifact_ids
.iter()
.filter_map(|id| artifacts.get(id))
.fold(0_u64, |total, listing| {
total.saturating_add(listing.artifact.size_bytes)
})
}
fn sort_catalog_publications(publications: &mut [CatalogPublication]) {
publications.sort_by(|left, right| {
let left_time = chrono::DateTime::parse_from_rfc3339(&left.created_at_rfc3339).ok();
let right_time = chrono::DateTime::parse_from_rfc3339(&right.created_at_rfc3339).ok();
let order = match (left_time, right_time) {
(Some(left_time), Some(right_time)) => right_time.cmp(&left_time),
_ => right.created_at_rfc3339.cmp(&left.created_at_rfc3339),
};
order.then_with(|| left.id.as_str().cmp(right.id.as_str()))
});
}
fn index_catalog_publications(
publications: &[CatalogPublication],
) -> HashMap<(CatalogObjectKind, CatalogId), Vec<usize>> {
let mut index = HashMap::new();
for (position, publication) in publications.iter().enumerate() {
index
.entry((publication.object_kind, publication.object_id.clone()))
.or_insert_with(Vec::new)
.push(position);
}
index
}
fn target_publication_indices<'a>(
index: &'a HashMap<(CatalogObjectKind, CatalogId), Vec<usize>>,
kind: CatalogObjectKind,
target_id: &CatalogId,
) -> &'a [usize] {
index
.get(&(kind, target_id.clone()))
.map(Vec::as_slice)
.unwrap_or_default()
}
fn publication_search_scope<'a>(
index: &'a HashMap<(CatalogObjectKind, CatalogId), Vec<usize>>,
kind: CatalogObjectKind,
target_id: &CatalogId,
include_history: bool,
) -> &'a [usize] {
let indices = target_publication_indices(index, kind, target_id);
if include_history {
indices
} else {
&indices[..indices.len().min(1)]
}
}
fn experiment_publication_search_scope(
experiment_id: &CatalogId,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
publication_index: &HashMap<(CatalogObjectKind, CatalogId), Vec<usize>>,
include_history: bool,
) -> Vec<usize> {
let mut indices = publication_search_scope(
publication_index,
CatalogObjectKind::Experiment,
experiment_id,
include_history,
)
.to_vec();
if let Some(series_ids) = experiment_series_ids.get(experiment_id) {
for series_id in series_ids {
indices.extend(publication_search_scope(
publication_index,
CatalogObjectKind::Series,
series_id,
include_history,
));
}
}
indices.sort_unstable();
indices.dedup();
indices
}
fn catalog_series_matches_identity_filters(
series_id: &CatalogId,
study_filter: Option<&CatalogId>,
substance_filter: Option<&CatalogId>,
study_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
series_substance_ids: &HashMap<CatalogId, CatalogId>,
) -> bool {
let study_matches = study_filter.is_none_or(|study_id| {
study_series_ids
.get(study_id)
.is_some_and(|series_ids| series_ids.contains(series_id))
});
let substance_matches = substance_filter
.is_none_or(|substance_id| series_substance_ids.get(series_id) == Some(substance_id));
study_matches && substance_matches
}
fn catalog_experiment_matches_identity_filters(
experiment_id: &CatalogId,
study_filter: Option<&CatalogId>,
substance_filter: Option<&CatalogId>,
study_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
series_substance_ids: &HashMap<CatalogId, CatalogId>,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
experiment_substance_ids: &HashMap<CatalogId, CatalogId>,
) -> bool {
let Some(series_ids) = experiment_series_ids.get(experiment_id) else {
return study_filter.is_none()
&& substance_filter.is_none_or(|substance_id| {
experiment_substance_ids.get(experiment_id) == Some(substance_id)
});
};
series_ids.iter().any(|series_id| {
let in_study = study_filter.is_none_or(|study_id| {
study_series_ids
.get(study_id)
.is_some_and(|study_series| study_series.contains(series_id))
});
let has_substance = substance_filter.is_none_or(|substance_id| {
series_substance_ids.get(series_id) == Some(substance_id)
|| experiment_substance_ids.get(experiment_id) == Some(substance_id)
});
in_study && has_substance
})
}
#[cfg(test)]
fn catalog_series_member_facets_match(
series_id: &CatalogId,
experiments: &[crate::Kinetics::experimental_kinetics::catalog::CatalogExperiment],
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
origin_filter: &str,
tag_filter: &str,
) -> bool {
if origin_filter.is_empty() && tag_filter.is_empty() {
return true;
}
experiments.iter().any(|experiment| {
let is_member = experiment_series_ids
.get(&experiment.id)
.is_some_and(|series_ids| series_ids.contains(series_id));
is_member
&& (origin_filter.is_empty()
|| source_kind_label(&experiment.source_kind).eq_ignore_ascii_case(origin_filter))
&& (tag_filter.is_empty()
|| experiment
.tags
.iter()
.any(|tag| tag.eq_ignore_ascii_case(tag_filter)))
})
}
fn catalog_numeric_bounds_valid(min: &str, max: &str) -> bool {
let parse = |value: &str| {
if value.trim().is_empty() {
Some(None)
} else {
value
.trim()
.parse::<f64>()
.ok()
.filter(|number| number.is_finite())
.map(Some)
}
};
match (parse(min), parse(max)) {
(Some(min), Some(max)) => match (min, max) {
(Some(min), Some(max)) => min <= max,
_ => true,
},
_ => false,
}
}
fn catalog_date_bounds_valid(from: &str, to: &str) -> bool {
let parse = |value: &str| {
if value.trim().is_empty() {
Some(None)
} else {
chrono::NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d")
.ok()
.map(Some)
}
};
match (parse(from), parse(to)) {
(Some(from), Some(to)) => match (from, to) {
(Some(from), Some(to)) => from <= to,
_ => true,
},
_ => false,
}
}
fn catalog_experiment_matches_advanced_filters(
experiment: &CatalogExperiment,
thermal_mode: Option<CatalogThermalMode>,
temperature_min: &str,
temperature_max: &str,
heating_rate_min: &str,
heating_rate_max: &str,
date_from: &str,
date_to: &str,
) -> bool {
let thermal_matches = thermal_mode.is_none_or(|mode| match mode {
CatalogThermalMode::Unspecified => experiment
.thermal_mode
.is_none_or(|value| value == CatalogThermalMode::Unspecified),
_ => experiment.thermal_mode == Some(mode),
});
if !thermal_matches
|| !catalog_numeric_bounds_valid(temperature_min, temperature_max)
|| !catalog_numeric_bounds_valid(heating_rate_min, heating_rate_max)
|| !catalog_date_bounds_valid(date_from, date_to)
{
return false;
}
let within = |value: Option<f64>, min: &str, max: &str| {
let min = min.trim().parse::<f64>().ok();
let max = max.trim().parse::<f64>().ok();
if min.is_none() && max.is_none() {
return true;
}
value.is_some_and(|value| {
min.is_none_or(|bound| value >= bound) && max.is_none_or(|bound| value <= bound)
})
};
if !within(experiment.temperature_k, temperature_min, temperature_max)
|| !within(
experiment.heating_rate_k_per_min,
heating_rate_min,
heating_rate_max,
)
{
return false;
}
if date_from.trim().is_empty() && date_to.trim().is_empty() {
return true;
}
let Some(date) = experiment
.date
.as_deref()
.and_then(|date| chrono::NaiveDate::parse_from_str(date.get(..10)?, "%Y-%m-%d").ok())
else {
return false;
};
let from = chrono::NaiveDate::parse_from_str(date_from.trim(), "%Y-%m-%d").ok();
let to = chrono::NaiveDate::parse_from_str(date_to.trim(), "%Y-%m-%d").ok();
from.is_none_or(|bound| date >= bound) && to.is_none_or(|bound| date <= bound)
}
fn catalog_experiment_matches_sample_and_attachment(
experiment_id: &CatalogId,
sample_filter: Option<&CatalogId>,
attachment_filter: Option<&CatalogArtifactPurpose>,
experiment_sample_ids: &HashMap<CatalogId, CatalogId>,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
publication_index: &HashMap<(CatalogObjectKind, CatalogId), Vec<usize>>,
include_history: bool,
publications: &[CatalogPublication],
artifacts: &HashMap<CatalogId, CatalogArtifactListing>,
) -> bool {
if sample_filter
.is_some_and(|sample_id| experiment_sample_ids.get(experiment_id) != Some(sample_id))
{
return false;
}
let Some(required_purpose) = attachment_filter else {
return true;
};
let target_has_attachment = |kind, target_id: &CatalogId| {
publication_search_scope(publication_index, kind, target_id, include_history)
.iter()
.filter_map(|index| publications.get(*index))
.any(|publication| {
publication.artifact_ids.iter().any(|artifact_id| {
artifacts
.get(artifact_id)
.is_some_and(|listing| &listing.artifact.purpose == required_purpose)
})
})
};
target_has_attachment(CatalogObjectKind::Experiment, experiment_id)
|| experiment_series_ids
.get(experiment_id)
.is_some_and(|series_ids| {
series_ids
.iter()
.any(|series_id| target_has_attachment(CatalogObjectKind::Series, series_id))
})
}
fn catalog_sample_filter_label(
sample: &crate::Kinetics::experimental_kinetics::catalog::CatalogSample,
) -> String {
let batch = sample
.batch_label
.as_deref()
.map(|batch| format!(" | batch {batch}"))
.unwrap_or_default();
format!("{}{} [{}]", sample.display_name, batch, sample.id)
}
fn catalog_series_context_labels(
series_id: &CatalogId,
studies: &[crate::Kinetics::experimental_kinetics::catalog::CatalogStudy],
substances: &[crate::Kinetics::experimental_kinetics::catalog::CatalogSubstance],
study_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
series_substance_ids: &HashMap<CatalogId, CatalogId>,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
) -> Vec<String> {
let study_names = studies
.iter()
.filter(|study| {
study_series_ids
.get(&study.id)
.is_some_and(|series_ids| series_ids.contains(series_id))
})
.map(|study| study.display_name.as_str())
.collect::<Vec<_>>();
let substance_name = series_substance_ids
.get(series_id)
.and_then(|substance_id| substances.iter().find(|item| &item.id == substance_id))
.map(|substance| substance.display_name.as_str());
let experiment_count = experiment_series_ids
.values()
.filter(|series_ids| series_ids.contains(series_id))
.count();
let mut labels = Vec::with_capacity(3);
if let Some(substance) = substance_name {
labels.push(format!("Substance: {substance}"));
}
if !study_names.is_empty() {
labels.push(format!("Studies: {}", study_names.join(", ")));
}
labels.push(format!("Current experiments: {experiment_count}"));
labels
}
fn catalog_experiment_context_labels(
experiment_id: &CatalogId,
series: &[crate::Kinetics::experimental_kinetics::catalog::CatalogSeries],
studies: &[crate::Kinetics::experimental_kinetics::catalog::CatalogStudy],
substances: &[crate::Kinetics::experimental_kinetics::catalog::CatalogSubstance],
study_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
series_substance_ids: &HashMap<CatalogId, CatalogId>,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
experiment_substance_ids: &HashMap<CatalogId, CatalogId>,
) -> Vec<String> {
let substance_name = |id: &CatalogId| {
substances
.iter()
.find(|substance| &substance.id == id)
.map(|substance| substance.display_name.as_str())
};
let mut labels = Vec::new();
if let Some(substance_id) = experiment_substance_ids.get(experiment_id) {
if let Some(name) = substance_name(substance_id) {
labels.push(format!("Sample substance: {name}"));
}
}
if let Some(series_ids) = experiment_series_ids.get(experiment_id) {
let mut paths = series_ids
.iter()
.filter_map(|series_id| {
let series_name = series
.iter()
.find(|item| &item.id == series_id)
.map(|item| item.display_name.as_str())?;
let study_names = studies
.iter()
.filter(|study| {
study_series_ids
.get(&study.id)
.is_some_and(|ids| ids.contains(series_id))
})
.map(|study| study.display_name.as_str())
.collect::<Vec<_>>();
let series_substance = series_substance_ids.get(series_id).and_then(substance_name);
let mut path = series_name.to_owned();
if !study_names.is_empty() {
path.push_str(&format!(" | studies: {}", study_names.join(", ")));
}
if let Some(name) = series_substance {
path.push_str(&format!(" | substance: {name}"));
}
Some(path)
})
.collect::<Vec<_>>();
paths.sort();
if !paths.is_empty() {
labels.push(format!("Series: {}", paths.join("; ")));
}
}
labels
}
fn catalog_substance_result_counts(
substance_id: &CatalogId,
studies: &[crate::Kinetics::experimental_kinetics::catalog::CatalogStudy],
series: &[crate::Kinetics::experimental_kinetics::catalog::CatalogSeries],
experiments: &[crate::Kinetics::experimental_kinetics::catalog::CatalogExperiment],
study_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
series_substance_ids: &HashMap<CatalogId, CatalogId>,
experiment_series_ids: &HashMap<CatalogId, HashSet<CatalogId>>,
experiment_substance_ids: &HashMap<CatalogId, CatalogId>,
) -> (usize, usize, usize) {
let matching_series = series_substance_ids
.iter()
.filter_map(|(series_id, assigned_substance)| {
(assigned_substance == substance_id).then_some(series_id.clone())
})
.collect::<HashSet<_>>();
let matching_studies = studies
.iter()
.filter(|study| {
study_series_ids.get(&study.id).is_some_and(|ids| {
ids.iter()
.any(|series_id| matching_series.contains(series_id))
})
})
.count();
let matching_experiments = experiments
.iter()
.filter(|experiment| {
experiment_substance_ids.get(&experiment.id) == Some(substance_id)
|| experiment_series_ids
.get(&experiment.id)
.is_some_and(|ids| ids.iter().any(|id| matching_series.contains(id)))
})
.count();
let matching_series_count = series
.iter()
.filter(|entry| matching_series.contains(&entry.id))
.count();
(
matching_studies,
matching_series_count,
matching_experiments,
)
}
#[cfg(test)]
fn catalog_publications_for_target<'a>(
publications: &'a [CatalogPublication],
kind: CatalogObjectKind,
target_id: &CatalogId,
) -> Vec<&'a CatalogPublication> {
publications
.iter()
.filter(|publication| {
publication.object_kind == kind && &publication.object_id == target_id
})
.collect()
}
#[cfg(test)]
mod catalog_search_tests {
use super::{
CatalogArtifact, CatalogArtifactListing, CatalogArtifactPurpose, CatalogId,
CatalogObjectKind, CatalogPublication, LocalArtifactResolution, catalog_date_bounds_valid,
catalog_experiment_context_labels, catalog_experiment_matches_advanced_filters,
catalog_experiment_matches_identity_filters,
catalog_experiment_matches_sample_and_attachment, catalog_numeric_bounds_valid,
catalog_publications_for_target, catalog_sample_filter_label,
catalog_series_context_labels, catalog_series_matches_identity_filters,
catalog_series_member_facets_match, catalog_substance_result_counts, catalog_text_matches,
index_catalog_publications, open_with_system_application, parse_catalog_tags,
publication_total_bytes, sort_catalog_publications, typed_document_has_method,
typed_document_matches_query, typed_document_method_mentions_experiment,
};
use std::collections::{HashMap, HashSet};
#[test]
fn sample_filter_labels_disambiguate_same_named_batches() {
use crate::Kinetics::experimental_kinetics::catalog::CatalogSample;
let first = CatalogSample {
id: CatalogId::new(),
substance_id: CatalogId::new(),
display_name: "Sample".into(),
batch_label: Some("batch-1".into()),
preparation_note: None,
};
let second = CatalogSample {
id: CatalogId::new(),
substance_id: first.substance_id.clone(),
display_name: "Sample".into(),
batch_label: Some("batch-1".into()),
preparation_note: None,
};
let first_label = catalog_sample_filter_label(&first);
let second_label = catalog_sample_filter_label(&second);
assert_ne!(first_label, second_label);
assert!(first_label.contains("batch-1"));
assert!(first_label.contains(first.id.as_str()));
}
#[test]
fn catalog_search_is_case_insensitive_and_matches_metadata_only() {
let fields = ["β = 2 K/min", "sample-17", "Non-isothermal"];
assert!(catalog_text_matches("SAMPLE-17", &fields));
assert!(catalog_text_matches("2 k/min", &fields));
assert!(!catalog_text_matches("processed-results", &fields));
assert!(catalog_text_matches("", &fields));
}
#[test]
fn catalog_search_finds_series_method_and_source_column_summaries() {
let source_identity = crate::Kinetics::experimental_kinetics::catalog::CatalogId::new();
let document = crate::Kinetics::experimental_kinetics::catalog::CatalogTypedDocumentSummary {
file_name: "series.csv".into(),
analysis_results: vec![],
kinetic_method_outputs: vec![
crate::Kinetics::experimental_kinetics::catalog::CatalogKineticMethodOutput {
experiment_identity: "stable-result-id".into(),
experiment_id_snapshot: "series-Ea-eta".into(),
output_column: "Ea".into(),
method: "KAS".into(),
model: Some("Ea(eta)".into()),
solver: Some("linear regression".into()),
output_unit: "J/mol".into(),
parameters: vec![],
sources: vec![
crate::Kinetics::experimental_kinetics::column_provenance::KineticSourceRef {
experiment_identity: source_identity.as_str().into(),
experiment_id_snapshot: "run-500K".into(),
columns: vec!["mass_sg".into()],
column_units: vec![("mass_sg".into(), "Milligram".into())],
conditions: vec![("temperature_K".into(), 500.0)],
},
],
value_range: Some(("eta".into(), 0.1, 0.9)),
diagnostics: vec![],
},
],
};
assert!(typed_document_matches_query("kas", &document));
assert!(typed_document_matches_query("mass_sg", &document));
assert!(typed_document_matches_query("500k", &document));
assert!(!typed_document_matches_query("friedman", &document));
assert!(typed_document_has_method(&document, "kas"));
assert!(!typed_document_has_method(&document, "friedman"));
let experiment_id = crate::Kinetics::experimental_kinetics::catalog::CatalogId::new();
assert!(typed_document_method_mentions_experiment(
&document,
"KAS",
&source_identity
));
assert!(!typed_document_method_mentions_experiment(
&document,
"KAS",
&experiment_id
));
}
#[test]
fn catalog_tags_are_trimmed_and_deduplicated_without_changing_order() {
assert_eq!(
parse_catalog_tags(" batch-4, measured, BATCH-4, , measured "),
vec!["batch-4", "measured"]
);
assert!(parse_catalog_tags(" , , ").is_empty());
}
#[test]
fn publication_size_counts_only_known_attachments_and_saturates() {
let first = crate::Kinetics::experimental_kinetics::catalog::CatalogId::new();
let missing = crate::Kinetics::experimental_kinetics::catalog::CatalogId::new();
let publication = CatalogPublication {
id: crate::Kinetics::experimental_kinetics::catalog::CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: crate::Kinetics::experimental_kinetics::catalog::CatalogId::new(),
parent_publication_id: None,
created_at_rfc3339: String::new(),
author: None,
description: None,
series_members: Vec::new(),
artifact_ids: vec![first.clone(), missing],
snapshot: None,
typed_documents: vec![],
};
let artifacts = HashMap::from([(
first.clone(),
CatalogArtifactListing {
artifact: CatalogArtifact {
id: first.clone(),
purpose: CatalogArtifactPurpose::Other,
format: "txt".into(),
file_name: "data.txt".into(),
size_bytes: u64::MAX,
sha256: "0".repeat(64),
locations: Vec::new(),
},
local_resolution: LocalArtifactResolution::NoLocalCopy,
},
)]);
assert_eq!(publication_total_bytes(&publication, &artifacts), u64::MAX);
}
#[test]
fn publication_history_is_filtered_by_target_and_sorted_newest_first() {
let target = CatalogId::new();
let other_target = CatalogId::new();
let make_publication = |target_id: CatalogId, created_at: &str| CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: target_id,
parent_publication_id: None,
created_at_rfc3339: created_at.into(),
author: None,
description: None,
series_members: Vec::new(),
artifact_ids: Vec::new(),
snapshot: None,
typed_documents: Vec::new(),
};
let older = make_publication(target.clone(), "2026-01-01T10:00:00Z");
let newer = make_publication(target.clone(), "2026-02-01T10:00:00Z");
let unrelated = make_publication(other_target, "2026-03-01T10:00:00Z");
let publications = vec![older.clone(), unrelated, newer.clone()];
let mut ordered = publications;
sort_catalog_publications(&mut ordered);
let matching =
catalog_publications_for_target(&ordered, CatalogObjectKind::Series, &target);
assert_eq!(matching, vec![&newer, &older]);
}
#[test]
fn browse_identity_filters_keep_studies_substances_and_samples_distinct() {
use std::collections::{HashMap, HashSet};
let study = CatalogId::new();
let substance_a = CatalogId::new();
let substance_b = CatalogId::new();
let series_a = CatalogId::new();
let series_b = CatalogId::new();
let experiment_a = CatalogId::new();
let experiment_b = CatalogId::new();
let standalone_experiment = CatalogId::new();
let study_series = HashMap::from([(study.clone(), HashSet::from([series_a.clone()]))]);
let series_substances = HashMap::from([
(series_a.clone(), substance_a.clone()),
(series_b.clone(), substance_b.clone()),
]);
let experiment_series = HashMap::from([
(experiment_a.clone(), HashSet::from([series_a.clone()])),
(experiment_b.clone(), HashSet::from([series_b.clone()])),
]);
let experiment_substances =
HashMap::from([(standalone_experiment.clone(), substance_b.clone())]);
assert!(catalog_series_matches_identity_filters(
&series_a,
Some(&study),
Some(&substance_a),
&study_series,
&series_substances,
));
assert!(!catalog_series_matches_identity_filters(
&series_b,
Some(&study),
None,
&study_series,
&series_substances,
));
assert!(catalog_experiment_matches_identity_filters(
&experiment_a,
Some(&study),
Some(&substance_a),
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
));
assert!(!catalog_experiment_matches_identity_filters(
&experiment_b,
Some(&study),
None,
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
));
assert!(catalog_experiment_matches_identity_filters(
&standalone_experiment,
None,
Some(&substance_b),
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
));
assert!(!catalog_experiment_matches_identity_filters(
&standalone_experiment,
Some(&study),
Some(&substance_b),
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
));
}
#[test]
fn series_origin_and_tag_filters_must_match_the_same_current_experiment() {
use crate::Kinetics::experimental_kinetics::catalog::{CatalogExperiment, SourceKind};
use std::collections::{HashMap, HashSet};
let series = CatalogId::new();
let measured = CatalogId::new();
let synthetic = CatalogId::new();
let experiments = vec![
CatalogExperiment {
id: measured.clone(),
source_identity: measured.as_str().to_owned(),
display_name: "Measured run".into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec!["batch-7".into()],
},
CatalogExperiment {
id: synthetic.clone(),
source_identity: synthetic.as_str().to_owned(),
display_name: "Synthetic run".into(),
source_kind: SourceKind::Synthetic,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec!["validation".into()],
},
];
let memberships = HashMap::from([
(measured.clone(), HashSet::from([series.clone()])),
(synthetic.clone(), HashSet::from([series.clone()])),
]);
assert!(catalog_series_member_facets_match(
&series,
&experiments,
&memberships,
"Measured",
"batch-7",
));
assert!(!catalog_series_member_facets_match(
&series,
&experiments,
&memberships,
"Measured",
"validation",
));
assert!(!catalog_series_member_facets_match(
&series,
&experiments,
&memberships,
"Synthetic",
"batch-7",
));
}
#[test]
fn series_context_shows_reused_substance_across_studies_without_duplicate_series() {
use crate::Kinetics::experimental_kinetics::catalog::{CatalogStudy, CatalogSubstance};
use std::collections::{HashMap, HashSet};
let series = CatalogId::new();
let substance_id = CatalogId::new();
let first_study = CatalogId::new();
let second_study = CatalogId::new();
let exp_a = CatalogId::new();
let exp_b = CatalogId::new();
let studies = vec![
CatalogStudy {
id: first_study.clone(),
display_name: "Temperature study".into(),
description: None,
},
CatalogStudy {
id: second_study.clone(),
display_name: "Instrument comparison".into(),
description: None,
},
];
let substances = vec![CatalogSubstance {
id: substance_id.clone(),
display_name: "Catalyst A".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
}];
let study_series = HashMap::from([
(first_study, HashSet::from([series.clone()])),
(second_study, HashSet::from([series.clone()])),
]);
let series_substance = HashMap::from([(series.clone(), substance_id)]);
let experiment_series = HashMap::from([
(exp_a, HashSet::from([series.clone()])),
(exp_b, HashSet::from([series.clone()])),
]);
let labels = catalog_series_context_labels(
&series,
&studies,
&substances,
&study_series,
&series_substance,
&experiment_series,
);
assert_eq!(labels.len(), 3);
assert_eq!(labels[0], "Substance: Catalyst A");
assert_eq!(
labels[1],
"Studies: Temperature study, Instrument comparison"
);
assert_eq!(labels[2], "Current experiments: 2");
}
#[test]
fn experiment_context_distinguishes_sample_substance_from_series_links() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogSeries, CatalogStudy, CatalogSubstance,
};
use std::collections::{HashMap, HashSet};
let experiment = CatalogId::new();
let series = CatalogId::new();
let study = CatalogId::new();
let sample_substance = CatalogId::new();
let series_substance = CatalogId::new();
let series_items = vec![CatalogSeries {
id: series.clone(),
display_name: "Heating-rate series".into(),
description: None,
}];
let studies = vec![CatalogStudy {
id: study.clone(),
display_name: "Catalyst study".into(),
description: None,
}];
let substances = vec![
CatalogSubstance {
id: sample_substance.clone(),
display_name: "Catalyst A, batch material".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
},
CatalogSubstance {
id: series_substance.clone(),
display_name: "Reference substance".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
},
];
let study_series = HashMap::from([(study, HashSet::from([series.clone()]))]);
let series_substances = HashMap::from([(series.clone(), series_substance)]);
let experiment_series = HashMap::from([(experiment.clone(), HashSet::from([series]))]);
let experiment_substances = HashMap::from([(experiment.clone(), sample_substance)]);
let labels = catalog_experiment_context_labels(
&experiment,
&series_items,
&studies,
&substances,
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
);
assert_eq!(labels.len(), 2);
assert_eq!(labels[0], "Sample substance: Catalyst A, batch material");
assert_eq!(
labels[1],
"Series: Heating-rate series | studies: Catalyst study | substance: Reference substance"
);
}
#[test]
fn substance_entry_counts_include_reused_series_and_sample_only_experiments() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogSeries, CatalogStudy, SourceKind,
};
use std::collections::{HashMap, HashSet};
let substance = CatalogId::new();
let series = CatalogId::new();
let study_a = CatalogId::new();
let study_b = CatalogId::new();
let exp_a = CatalogId::new();
let exp_b = CatalogId::new();
let experiment = |id: CatalogId, name: &str| CatalogExperiment {
source_identity: id.as_str().to_owned(),
id,
display_name: name.into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let studies = vec![
CatalogStudy {
id: study_a.clone(),
display_name: "Study A".into(),
description: None,
},
CatalogStudy {
id: study_b.clone(),
display_name: "Study B".into(),
description: None,
},
];
let series_entries = vec![CatalogSeries {
id: series.clone(),
display_name: "Shared series".into(),
description: None,
}];
let experiments = vec![
experiment(exp_a.clone(), "Series member"),
experiment(exp_b.clone(), "Sample-only"),
];
let study_series = HashMap::from([
(study_a, HashSet::from([series.clone()])),
(study_b, HashSet::from([series.clone()])),
]);
let series_substances = HashMap::from([(series.clone(), substance.clone())]);
let experiment_series = HashMap::from([
(exp_a, HashSet::from([series])),
(exp_b.clone(), HashSet::new()),
]);
let experiment_substances = HashMap::from([(exp_b, substance.clone())]);
assert_eq!(
catalog_substance_result_counts(
&substance,
&studies,
&series_entries,
&experiments,
&study_series,
&series_substances,
&experiment_series,
&experiment_substances,
),
(2, 1, 2)
);
}
#[test]
fn advanced_catalog_filters_validate_ranges_and_match_inclusive_conditions() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogThermalMode, SourceKind,
};
assert!(catalog_numeric_bounds_valid("", ""));
assert!(catalog_numeric_bounds_valid("400", "500"));
assert!(!catalog_numeric_bounds_valid("NaN", "500"));
assert!(!catalog_numeric_bounds_valid("600", "500"));
assert!(catalog_date_bounds_valid("2026-01-01", "2026-12-31"));
assert!(!catalog_date_bounds_valid("2026-02-30", ""));
let experiment = CatalogExperiment {
id: CatalogId::new(),
source_identity: "stable-id".into(),
display_name: "isothermal run".into(),
source_kind: SourceKind::Measured,
date: Some("2026-05-10T12:30:00Z".into()),
sample: None,
instrument: None,
operator: None,
thermal_mode: Some(CatalogThermalMode::Isothermal),
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
assert!(catalog_experiment_matches_advanced_filters(
&experiment,
Some(CatalogThermalMode::Isothermal),
"500",
"500",
"",
"",
"2026-05-10",
"2026-05-10",
));
assert!(!catalog_experiment_matches_advanced_filters(
&experiment,
Some(CatalogThermalMode::NonIsothermal),
"",
"",
"",
"",
"",
"",
));
assert!(!catalog_experiment_matches_advanced_filters(
&experiment,
None,
"501",
"",
"",
"",
"",
"",
));
}
#[test]
fn sample_and_attachment_filters_follow_series_publications() {
use crate::Kinetics::experimental_kinetics::catalog::CatalogArtifact;
let experiment = CatalogId::new();
let series = CatalogId::new();
let sample = CatalogId::new();
let artifact_id = CatalogId::new();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.clone(),
parent_publication_id: None,
created_at_rfc3339: String::new(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![artifact_id.clone()],
snapshot: None,
typed_documents: vec![],
};
let artifacts = HashMap::from([(
artifact_id.clone(),
CatalogArtifactListing {
artifact: CatalogArtifact {
id: artifact_id,
purpose: CatalogArtifactPurpose::PlotImage,
format: "png".into(),
file_name: "curve.png".into(),
size_bytes: 10,
sha256: "0".repeat(64),
locations: vec![],
},
local_resolution: LocalArtifactResolution::NoLocalCopy,
},
)]);
let samples = HashMap::from([(experiment.clone(), sample.clone())]);
let memberships = HashMap::from([(experiment.clone(), HashSet::from([series]))]);
let publications = [publication.clone()];
let publication_index = index_catalog_publications(&publications);
assert!(catalog_experiment_matches_sample_and_attachment(
&experiment,
Some(&sample),
Some(&CatalogArtifactPurpose::PlotImage),
&samples,
&memberships,
&publication_index,
true,
&publications,
&artifacts,
));
assert!(!catalog_experiment_matches_sample_and_attachment(
&experiment,
None,
Some(&CatalogArtifactPurpose::RawInstrumentData),
&samples,
&memberships,
&publication_index,
true,
&publications,
&artifacts,
));
}
#[test]
fn opening_a_missing_catalog_path_returns_a_clear_error() {
let missing =
std::env::temp_dir().join(format!("kithe-catalog-missing-{}", uuid::Uuid::new_v4()));
let error = open_with_system_application(&missing).unwrap_err();
assert!(error.contains("no longer available"));
assert!(error.contains(&missing.display().to_string()));
}
}
#[cfg(test)]
mod settings_apply_tests {
use super::*;
#[test]
fn acquisition_defaults_are_saved_and_loaded_with_settings() {
let directory = tempfile::tempdir().unwrap();
let settings_path = directory.path().join("tgasettings.json");
let mut model = PlotModel::default();
model
.settings
.set_acquisition_defaults(Some("old instrument".into()), Some("old operator".into()));
let mut options = TestOptions::default();
options.load_current_settings(&model.settings);
assert_eq!(options.temp_instrument_name, "old instrument");
assert_eq!(options.temp_operator_name, "old operator");
options.temp_instrument_name = " TGA-04 / INV-882 ".into();
options.temp_operator_name = " A. User ".into();
options.temp_k = "-1.25".into();
options.temp_b = "40.5".into();
options.temp_n_points = "500".into();
options.temp_log_level = "info".into();
options
.apply_settings_to_path(&mut model, &settings_path)
.unwrap();
let restored = Settings::load_from_path(&settings_path).unwrap();
assert_eq!(restored.default_instrument_name(), Some("TGA-04 / INV-882"));
assert_eq!(restored.default_operator_name(), Some("A. User"));
assert_eq!(restored.calibration_line().unwrap().k(), -1.25);
assert_eq!(restored.calibration_line().unwrap().b(), 40.5);
}
#[test]
fn invalid_calibration_does_not_change_live_settings() {
let mut model = PlotModel::default();
let before = model.settings.calibration_line().unwrap();
let mut options = TestOptions::default();
options.temp_k = "NaN".into();
options.temp_b = "12".into();
options.temp_n_points = "100".into();
options.temp_log_level = "info".into();
assert!(options.apply_settings(&mut model).is_err());
let after = model.settings.calibration_line().unwrap();
assert_eq!(before.k(), after.k());
assert_eq!(before.b(), after.b());
}
#[test]
fn registering_current_series_is_idempotent_and_preserves_workspace_data() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
CatalogStore::open(directory.path()).unwrap();
let mut model = PlotModel::default();
model.settings.set_catalog(CatalogSettings {
local_library_id: Some("test-library".into()),
local_library_path: Some(directory.path().to_path_buf()),
..Default::default()
});
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("run-1"))
.unwrap();
let series_identity = series.identity().to_string();
model.series = series;
let mut options = TestOptions::new();
options.catalog_series_name = "Test series".into();
options.register_current_series(
&model,
model.settings.catalog().local_library_path.as_deref(),
false,
);
options.register_current_series(
&model,
model.settings.catalog().local_library_path.as_deref(),
false,
);
let store = CatalogStore::open(directory.path()).unwrap();
let entries = store.list_series().unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].id.as_str(), series_identity);
assert_eq!(entries[0].display_name, "Test series");
assert_eq!(model.series.identity(), series_identity);
assert_eq!(model.series.len(), 1);
}
#[test]
fn registering_shortened_series_requires_confirmation_before_membership_is_replaced() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
let directory = tempfile::tempdir().unwrap();
CatalogStore::open(directory.path()).unwrap();
let mut model = PlotModel::default();
model.series = TGASeries::new();
model
.series
.push(TGAExperiment::new(TGADataset::default()).with_id("keep"))
.unwrap();
model
.series
.push(TGAExperiment::new(TGADataset::default()).with_id("remove"))
.unwrap();
let mut options = TestOptions::new();
options.catalog_series_name = "series".into();
options.register_current_series(&model, Some(directory.path()), false);
assert_eq!(
CatalogStore::open_existing(directory.path())
.unwrap()
.list_series_members(
&CatalogId::parse(model.series.identity().to_string()).unwrap()
)
.unwrap()
.len(),
2,
"initial registration failed: {:?}",
options.catalog_status
);
model.series.drop_experiment(1).unwrap();
options.register_current_series(&model, Some(directory.path()), false);
let current_ids = model
.series
.experiments()
.iter()
.map(|experiment| experiment.meta.identity().to_string())
.collect::<Vec<_>>();
let existing_ids = CatalogStore::open_existing(directory.path())
.unwrap()
.list_series_members(&CatalogId::parse(model.series.identity().to_string()).unwrap())
.unwrap()
.into_iter()
.map(|member| member.experiment_id.to_string())
.collect::<Vec<_>>();
let removed_count = options
.catalog_membership_shrink_confirmation
.as_ref()
.unwrap_or_else(|| {
panic!("membership reduction did not ask for confirmation: current={current_ids:?}, existing={existing_ids:?}, status={:?}", options.catalog_status)
});
assert_eq!(removed_count.removed_member_ids.len(), 1);
let store = CatalogStore::open_existing(directory.path()).unwrap();
let series_id = CatalogId::parse(model.series.identity().to_string()).unwrap();
assert_eq!(store.list_series_members(&series_id).unwrap().len(), 2);
options.register_current_series(&model, Some(directory.path()), true);
let store = CatalogStore::open_existing(directory.path()).unwrap();
assert_eq!(store.list_series_members(&series_id).unwrap().len(), 1);
}
#[test]
fn pending_catalog_file_format_detection_identifies_typed_and_raw_documents() {
let directory = tempfile::tempdir().unwrap();
let typed_series = directory.path().join("series.csv");
std::fs::write(&typed_series, "# format_version=10\n#META\\tseries\n").unwrap();
assert_eq!(
detect_catalog_file_format(&typed_series),
"typed KiThe series CSV"
);
let typed_dataset = directory.path().join("dataset.csv");
std::fs::write(&typed_dataset, "# KiThe TGA Dataset\n").unwrap();
assert_eq!(
detect_catalog_file_format(&typed_dataset),
"typed KiThe dataset CSV"
);
let raw = directory.path().join("raw.csv");
std::fs::write(&raw, "time,mass\n0,1\n").unwrap();
assert!(detect_catalog_file_format(&raw).contains("raw/untyped"));
}
#[test]
fn catalog_attachment_open_label_distinguishes_verified_from_modified_files() {
let purpose = CatalogArtifactPurpose::TypedKiTheDocument;
assert_eq!(catalog_open_action_label(&purpose, None), None);
assert_eq!(
catalog_open_action_label(&purpose, Some(&LocalArtifactIntegrity::Verified)),
Some("Open / Import typed document...")
);
assert_eq!(
catalog_open_action_label(
&purpose,
Some(&LocalArtifactIntegrity::Modified {
path: std::path::PathBuf::from("current.csv"),
expected_sha256: "old".into(),
actual_sha256: "new".into(),
})
),
Some("Open current file from disk...")
);
}
}
#[cfg(test)]
mod window_close_tests {
use super::{CatalogArtifactListing, TestOptions, local_artifact_status};
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactFile, CatalogArtifactPurpose, CatalogId, CatalogObjectKind,
CatalogPublication, CatalogPublicationSnapshot, CatalogSeries, CatalogStore,
LocalArtifactIntegrity, LocalArtifactResolution,
};
use crate::gui::experimental_kinetics_gui::controller_buttons_and_panels::NewExperimentDialogState;
use crate::gui::experimental_kinetics_gui::model::PlotModel;
use egui_kittest::{Harness, kittest::Queryable};
struct State {
options: TestOptions,
model: PlotModel,
document_dialog: NewExperimentDialogState,
}
#[test]
fn catalog_method_facet_keeps_matching_typed_series_visible() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, CatalogKineticMethodOutput, CatalogObjectKind,
CatalogPublication, CatalogSeries, CatalogTypedDocumentSummary, PublishedSeriesMember,
SourceKind,
};
use std::collections::{HashMap, HashSet};
let series_id = CatalogId::new();
let experiment_id = CatalogId::new();
let synthetic_experiment_id = CatalogId::new();
let experiment = CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().into(),
display_name: "run-500K".into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(400.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec!["batch-7".into()],
};
let series = CatalogSeries {
id: series_id.clone(),
display_name: "Current series card".into(),
description: None,
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id.clone(),
parent_publication_id: None,
created_at_rfc3339: "2026-12-02T10:00:00Z".into(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: experiment_id.clone(),
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Series {
series: CatalogSeries {
id: series_id.clone(),
display_name: "Series at publication".into(),
description: Some("immutable snapshot note".into()),
},
experiments: vec![CatalogExperiment {
display_name: "Run at publication".into(),
..experiment.clone()
}],
}),
typed_documents: vec![CatalogTypedDocumentSummary {
file_name: "typed-series.csv".into(),
analysis_results: vec![],
kinetic_method_outputs: vec![CatalogKineticMethodOutput {
experiment_identity: series_id.as_str().into(),
experiment_id_snapshot: "series-Ea-eta".into(),
output_column: "Ea".into(),
method: "KAS".into(),
model: Some("Ea(eta)".into()),
solver: Some("linear regression".into()),
output_unit: "J/mol".into(),
parameters: vec![],
sources: vec![],
value_range: Some(("eta".into(), 0.1, 0.9)),
diagnostics: vec![],
}],
}],
};
let mut older_publication = publication.clone();
older_publication.id = CatalogId::new();
older_publication.created_at_rfc3339 = "2026-11-02T10:00:00Z".into();
older_publication.typed_documents[0].kinetic_method_outputs[0]
.diagnostics
.push("legacy-only-marker".into());
let mut publications = vec![publication, older_publication];
super::sort_catalog_publications(&mut publications);
let publication_index = super::index_catalog_publications(&publications);
let options = TestOptions {
catalog_window_open: true,
catalog_entries: vec![series],
catalog_experiment_entries: vec![
experiment,
CatalogExperiment {
id: synthetic_experiment_id.clone(),
source_identity: synthetic_experiment_id.as_str().into(),
display_name: "synthetic-hot-without-tag".into(),
source_kind: SourceKind::Synthetic,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(600.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
},
],
catalog_temperature_min: "500".into(),
catalog_experiment_series_ids: HashMap::from([
(experiment_id, HashSet::from([series_id.clone()])),
(synthetic_experiment_id, HashSet::from([series_id])),
]),
catalog_publication_index: publication_index,
catalog_publications: publications,
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model: PlotModel::default(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Method")
.click();
harness.run();
harness.get_by_label("KAS").click();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Origin")
.click();
harness.run();
harness.get_by_label("Measured").click();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Tag")
.click();
harness.run();
harness.get_by_label("batch-7").click();
harness.run();
assert_eq!(harness.state().options.catalog_method_filter, "KAS");
assert_eq!(harness.state().options.catalog_origin_filter, "Measured");
assert_eq!(harness.state().options.catalog_tag_filter, "batch-7");
assert!(harness.query_by_label("Current series card").is_none());
harness.state_mut().options.catalog_experiment_entries[0].temperature_k = Some(550.0);
harness.run();
harness.get_by_label("Current series card");
harness.get_by_label("Published series snapshot: Series at publication");
harness
.get_by_label("Scientific results: typed-series.csv")
.scroll_to_me();
harness.run();
harness
.get_by_label("Scientific results: typed-series.csv")
.click();
harness.run();
harness
.get_by_label("KAS: series-Ea-eta -> Ea (J/mol)")
.scroll_to_me();
harness.run();
harness
.get_by_label("KAS: series-Ea-eta -> Ea (J/mol)")
.click();
harness.run();
harness.get_by_label("Range: eta = 0.100000 .. 0.900000");
harness.state_mut().options.catalog_search = "legacy-only-marker".into();
harness.run();
assert!(harness.query_by_label("Current series card").is_none());
harness
.get_by_label("Search and show older publication versions")
.click();
harness.run();
harness.get_by_label("Current series card");
harness.get_by_label(
"Matched in this publication version: search text, method filter (2026-11-02T10:00:00Z)",
);
}
#[test]
fn series_filters_must_match_the_same_current_experiment() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, SourceKind,
};
use std::collections::{HashMap, HashSet};
let series_id = CatalogId::new();
let measured_id = CatalogId::new();
let hot_id = CatalogId::new();
let measured = CatalogExperiment {
id: measured_id.clone(),
source_identity: measured_id.as_str().into(),
display_name: "measured-cool".into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(400.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let hot = CatalogExperiment {
id: hot_id.clone(),
source_identity: hot_id.as_str().into(),
display_name: "synthetic-hot".into(),
source_kind: SourceKind::Synthetic,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(600.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let mut options = TestOptions::default();
options.catalog_experiment_entries = vec![measured.clone(), hot];
options.catalog_experiment_series_ids = HashMap::from([
(measured_id.clone(), HashSet::from([series_id.clone()])),
(hot_id, HashSet::from([series_id.clone()])),
]);
options.catalog_origin_filter = "Measured".into();
options.catalog_temperature_min = "500".into();
assert!(
!options.catalog_series_matches_member_filters(&series_id),
"origin and temperature matches from different members must not combine"
);
let mut measured_hot = measured;
measured_hot.temperature_k = Some(550.0);
options.catalog_experiment_entries[0] = measured_hot;
assert!(options.catalog_series_matches_member_filters(&series_id));
}
#[test]
fn catalog_sample_and_attachment_filters_work_through_the_gui() {
use crate::Kinetics::experimental_kinetics::catalog::{
ArtifactLocation, CatalogArtifact, CatalogArtifactPurpose, CatalogExperiment,
CatalogId, CatalogObjectKind, CatalogPublication, CatalogPublicationSnapshot,
CatalogSample, CatalogSeries, PublishedSeriesMember, SourceKind,
};
use std::collections::{HashMap, HashSet};
let series_id = CatalogId::new();
let experiment_id = CatalogId::new();
let sample_id = CatalogId::new();
let artifact_id = CatalogId::new();
let experiment = CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().into(),
display_name: "run with image".into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let series = CatalogSeries {
id: series_id.clone(),
display_name: "Current series card".into(),
description: None,
};
let sample = CatalogSample {
id: sample_id.clone(),
substance_id: CatalogId::new(),
display_name: "Powder A".into(),
batch_label: Some("Batch-42".into()),
preparation_note: None,
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id.clone(),
parent_publication_id: None,
created_at_rfc3339: "2026-12-01T10:00:00Z".into(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: experiment_id.clone(),
ordinal: 0,
}],
artifact_ids: vec![artifact_id.clone()],
snapshot: Some(CatalogPublicationSnapshot::Series {
series: series.clone(),
experiments: vec![experiment.clone()],
}),
typed_documents: vec![],
};
let publications = vec![publication];
let publication_index = super::index_catalog_publications(&publications);
let options = TestOptions {
catalog_window_open: true,
catalog_entries: vec![series],
catalog_experiment_entries: vec![experiment],
catalog_samples: vec![sample.clone()],
catalog_experiment_series_ids: HashMap::from([(
experiment_id.clone(),
HashSet::from([series_id]),
)]),
catalog_experiment_sample_ids: HashMap::from([(experiment_id, sample_id.clone())]),
catalog_publication_index: publication_index,
catalog_publications: publications,
catalog_artifacts: HashMap::from([(
artifact_id.clone(),
CatalogArtifactListing {
artifact: CatalogArtifact {
id: artifact_id,
purpose: CatalogArtifactPurpose::PlotImage,
format: "png".into(),
file_name: "curve.png".into(),
size_bytes: 32,
sha256: "a".repeat(64),
locations: vec![ArtifactLocation::Server {
storage_key: "plots/curve.png".into(),
}],
},
local_resolution: LocalArtifactResolution::NoLocalCopy,
},
)]),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model: PlotModel::default(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("More filters").click();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Sample / batch")
.scroll_to_me();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Sample / batch")
.click();
harness.run();
harness
.get_by_label(&super::catalog_sample_filter_label(&sample))
.click();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Required attachment")
.click();
harness.run();
harness.get_by_label("Plot image").click();
harness.run();
assert_eq!(
harness.state().options.catalog_sample_filter,
Some(sample_id)
);
assert_eq!(
harness.state().options.catalog_attachment_filter,
Some(CatalogArtifactPurpose::PlotImage)
);
harness.get_by_label("Current series card");
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Required attachment")
.click();
harness.run();
harness.get_by_label("Raw instrument data").click();
harness.run();
assert!(harness.query_by_label("Current series card").is_none());
harness.get_by_label("Clear filters").click();
harness.run();
assert_eq!(harness.state().options.catalog_sample_filter, None);
assert_eq!(harness.state().options.catalog_attachment_filter, None);
harness.get_by_label("Current series card");
}
#[test]
fn catalog_transfers_command_opens_the_explicit_virtual_client_window() {
let options = TestOptions {
catalog_window_open: true,
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model: PlotModel::default(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Transfers...").click();
harness.run();
harness.get_by_label("Catalog transfers: virtual server");
harness.get_by_label("In-memory test endpoint. Nothing is sent over the network or stored in the local SQLite catalog.");
}
#[test]
fn catalog_study_results_navigate_to_scoped_series_and_experiments() {
use super::CatalogResultLevel;
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, CatalogSeries, CatalogStudy, CatalogSubstance, SourceKind,
};
use std::collections::{HashMap, HashSet};
let study_id = CatalogId::new();
let other_study_id = CatalogId::new();
let substance_id = CatalogId::new();
let series_id = CatalogId::new();
let other_series_id = CatalogId::new();
let experiment_id = CatalogId::new();
let other_experiment_id = CatalogId::new();
let options = TestOptions {
catalog_window_open: true,
catalog_search: "CatA".into(),
catalog_studies: vec![
CatalogStudy {
id: study_id.clone(),
display_name: "Catalyst study A".into(),
description: Some("First study".into()),
},
CatalogStudy {
id: other_study_id.clone(),
display_name: "Catalyst study B".into(),
description: Some("Second study".into()),
},
],
catalog_substances: vec![CatalogSubstance {
id: substance_id.clone(),
display_name: "Catalyst A".into(),
formula: Some("CatA".into()),
cas_number: None,
inchi_key: None,
description: None,
}],
catalog_entries: vec![
CatalogSeries {
id: series_id.clone(),
display_name: "Isothermal series A".into(),
description: None,
},
CatalogSeries {
id: other_series_id.clone(),
display_name: "Isothermal series B".into(),
description: None,
},
],
catalog_experiment_entries: [
(experiment_id.clone(), "run-400K-A"),
(other_experiment_id.clone(), "run-400K-B"),
]
.into_iter()
.map(|(id, name)| CatalogExperiment {
source_identity: id.as_str().into(),
id,
display_name: name.into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: Some(400.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
})
.collect(),
catalog_study_substance_ids: HashMap::from([
(study_id.clone(), HashSet::from([substance_id.clone()])),
(
other_study_id.clone(),
HashSet::from([substance_id.clone()]),
),
]),
catalog_study_series_ids: HashMap::from([
(study_id.clone(), HashSet::from([series_id.clone()])),
(other_study_id, HashSet::from([other_series_id.clone()])),
]),
catalog_series_substance_ids: HashMap::from([
(series_id.clone(), substance_id.clone()),
(other_series_id.clone(), substance_id.clone()),
]),
catalog_experiment_series_ids: HashMap::from([
(experiment_id, HashSet::from([series_id])),
(other_experiment_id, HashSet::from([other_series_id])),
]),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model: PlotModel::default(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Studies").click();
harness.run();
harness.get_by_label("Catalyst study A");
harness.get_by_label("Catalyst study B");
harness.state_mut().options.catalog_search.clear();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Substance filter")
.click();
harness.run();
harness.get_by_label("Catalyst A").click();
harness.run();
assert_eq!(
harness.state().options.catalog_browse_substance_filter,
Some(substance_id)
);
harness
.get_by_label("Browse series: Catalyst study A")
.scroll_to_me();
harness.run();
harness
.get_by_role_and_label(
egui::accesskit::Role::Button,
"Browse series: Catalyst study A",
)
.click();
harness.run();
assert_eq!(
harness.state().options.catalog_result_level,
CatalogResultLevel::Series
);
assert_eq!(
harness.state().options.catalog_browse_study_filter,
Some(study_id.clone())
);
harness.get_by_label("Isothermal series A");
assert!(harness.query_by_label("Isothermal series B").is_none());
harness.get_by_label("Studies").click();
harness.run();
harness
.get_by_label("Browse experiments: Catalyst study A")
.scroll_to_me();
harness.run();
harness
.get_by_role_and_label(
egui::accesskit::Role::Button,
"Browse experiments: Catalyst study A",
)
.click();
harness.run();
assert_eq!(
harness.state().options.catalog_result_level,
CatalogResultLevel::Experiments
);
assert_eq!(
harness.state().options.catalog_browse_study_filter,
Some(study_id)
);
harness.get_by_label("run-400K-A");
assert!(harness.query_by_label("run-400K-B").is_none());
}
#[test]
fn catalog_registers_mixed_lineage_and_filters_it_as_mixed() {
use crate::Kinetics::experimental_kinetics::catalog::{CatalogId, SourceKind};
use crate::Kinetics::experimental_kinetics::data_lineage::{
DataContribution, DataSource, RowIdRange,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let raw_path = directory.path().join("measured.txt");
std::fs::write(&raw_path, "time\tmass\n0\t10\n1\t9\n").unwrap();
let mut dataset = TGADataset::from_csv_universal(&raw_path).unwrap();
let namespace = dataset.data_lineage.row_namespace.clone();
let rows = vec![RowIdRange {
namespace,
first: 0,
last: 1,
}];
dataset.data_lineage.contributions = vec![
DataContribution {
source: DataSource::Measured { artifact_id: None },
columns: vec!["mass".into()],
row_ranges: rows.clone(),
input_refs: vec![],
operation_id: None,
},
DataContribution {
source: DataSource::Reconstructed {
method: "fit reconstruction".into(),
parameters: vec![("slope".into(), -1.0)],
},
columns: vec!["mass".into()],
row_ranges: rows,
input_refs: vec![],
operation_id: None,
},
];
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(dataset).with_id("mixed-run"))
.unwrap();
let source_identity = series.experiments()[0].meta.identity().to_string();
let mut model = PlotModel::new();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library.clone()),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Register Selected Experiment").click();
harness.run();
let store = CatalogStore::open_existing(&library).unwrap();
let catalog_id = CatalogId::parse(source_identity).unwrap();
let experiment = store.get_experiment(&catalog_id).unwrap().unwrap();
assert_eq!(experiment.source_kind, SourceKind::Mixed);
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Origin")
.click();
harness.run();
harness.get_by_label("Mixed").click();
harness.run();
harness.get_by_label("mixed-run");
}
#[test]
fn settings_close_button_clears_open_state() {
let mut options = TestOptions::new();
options.show_settings_window = true;
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.options
.show_settings_window(ui.ctx(), &mut state.model)
},
State {
options,
model: PlotModel::new(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Close").scroll_to_me();
harness.run();
harness.get_by_label("Close").click();
harness.run();
assert!(!harness.state().options.show_settings_window);
}
#[test]
fn synthetic_data_close_button_clears_open_state() {
let mut options = TestOptions::new();
options.show_synthetic_data = true;
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.options
.show_synthetic_data_window(ui.ctx(), &mut state.model)
},
State {
options,
model: PlotModel::new(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Close").scroll_to_me();
harness.run();
harness.get_by_label("Close").click();
harness.run();
assert!(!harness.state().options.show_synthetic_data);
}
#[test]
fn settings_can_open_a_user_selected_local_catalog_without_touching_workspace() {
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("local-library");
let mut options = TestOptions::new();
options.show_settings_window = true;
options.test_catalog_directory = Some(library.clone());
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.options
.show_settings_window(ui.ctx(), &mut state.model)
},
State {
options,
model: PlotModel::new(),
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Browse...").scroll_to_me();
harness.run();
harness.get_by_label("Browse...").click();
harness.run();
harness
.get_by_label("Open / Create local library")
.scroll_to_me();
harness.run();
harness.get_by_label("Open / Create local library").click();
harness.run();
assert!(library.join("catalog.sqlite3").is_file());
assert_eq!(
harness
.state()
.model
.settings
.catalog()
.local_library_path
.as_deref(),
Some(library.as_path())
);
assert!(harness.state().model.list_of_experiments().is_empty());
}
#[test]
fn cancelling_system_folder_picker_preserves_the_configured_catalog_path() {
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let configured_path = directory.path().join("already-selected-library");
std::fs::create_dir(&configured_path).unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(configured_path.clone()),
..Default::default()
});
let options = TestOptions {
show_settings_window: true,
temp_catalog_path: configured_path.display().to_string(),
test_catalog_directory: None,
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.options
.show_settings_window(ui.ctx(), &mut state.model)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Browse...").scroll_to_me();
harness.run();
harness.get_by_label("Browse...").click();
harness.run();
assert_eq!(
harness.state().options.temp_catalog_path,
configured_path.display().to_string()
);
assert_eq!(
harness
.state()
.model
.settings
.catalog()
.local_library_path
.as_deref(),
Some(configured_path.as_path())
);
assert!(!configured_path.join("catalog.sqlite3").exists());
}
#[test]
fn catalog_without_selected_library_shows_setup_guidance_and_keeps_workspace_unchanged() {
let mut model = PlotModel::new();
model.settings.set_catalog(Default::default());
let options = TestOptions {
catalog_window_open: true,
..TestOptions::new()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness
.get_by_label("No local library selected. Choose one in Test Options > TGA Settings.");
assert!(harness.state().model.series.is_empty());
assert!(harness.state().options.catalog_status.is_none());
}
#[test]
fn catalog_window_register_action_creates_one_series_card() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
CatalogStore::open(directory.path()).unwrap();
let expected_library_id = CatalogStore::open_existing(directory.path())
.unwrap()
.library_id()
.to_owned();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_id: Some("ui-test-library".into()),
local_library_path: Some(directory.path().to_path_buf()),
..Default::default()
});
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("ui-run"))
.unwrap();
model.series = series;
let options = TestOptions {
catalog_series_name: "UI series".into(),
..TestOptions::new()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.state_mut().options.open_catalog_window();
harness.run();
assert_eq!(
harness.state().options.catalog_library_id.as_deref(),
Some(expected_library_id.as_str())
);
harness.get_by_label("Register Current Series").click();
harness.run();
let store = CatalogStore::open(directory.path()).unwrap();
let entries = store.list_series().unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].display_name, "UI series");
}
#[test]
fn registering_series_refreshes_acquisition_metadata_and_preserves_catalog_fields() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, CatalogThermalMode, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let mut store = CatalogStore::open(&library).unwrap();
let mut series = TGASeries::new();
let mut existing_experiment =
TGAExperiment::new(TGADataset::default()).with_id("existing-card");
existing_experiment.meta.acquisition =
crate::Kinetics::experimental_kinetics::experiment_series_main::AcquisitionMetadata {
measurement_date: Some(chrono::NaiveDate::from_ymd_opt(2026, 10, 13).unwrap()),
sample_description: Some("typed sample".into()),
instrument: Some("typed instrument".into()),
operator: Some("typed operator".into()),
..Default::default()
};
series.push(existing_experiment).unwrap();
let mut selected_experiment =
TGAExperiment::new(TGADataset::default()).with_id("selected-card");
selected_experiment.meta.acquisition =
crate::Kinetics::experimental_kinetics::experiment_series_main::AcquisitionMetadata {
measurement_date: Some(chrono::NaiveDate::from_ymd_opt(2026, 12, 1).unwrap()),
sample_description: Some("selected typed sample".into()),
instrument: Some("selected instrument".into()),
operator: Some("selected operator".into()),
..Default::default()
};
series.push(selected_experiment).unwrap();
let existing_identity = series.experiments()[0].meta.identity().to_string();
let existing_id = CatalogId::parse(existing_identity.clone()).unwrap();
store
.register_experiment_snapshot(&CatalogExperiment {
id: existing_id,
source_identity: existing_identity.clone(),
display_name: "existing-card".into(),
source_kind: SourceKind::Measured,
date: Some("2026-10-12".into()),
sample: Some("reference sample".into()),
instrument: Some("instrument-5".into()),
operator: Some("operator-A".into()),
thermal_mode: Some(CatalogThermalMode::Isothermal),
temperature_k: Some(550.0),
heating_rate_k_per_min: None,
comment: Some("preserve me".into()),
tags: vec!["reference".into()],
})
.unwrap();
let selected_identity = series.experiments()[1].meta.identity().to_string();
let mut model = PlotModel::new();
model.series = series;
let mut options = TestOptions {
catalog_series_name: "refreshed series".into(),
catalog_experiment_identity: selected_identity.clone(),
catalog_metadata_identity: selected_identity,
catalog_tags: "new-run".into(),
..TestOptions::default()
};
options.register_current_series(&model, Some(&library), false);
let store = CatalogStore::open_existing(&library).unwrap();
let existing = store
.get_experiment(&CatalogId::parse(existing_identity).unwrap())
.unwrap()
.unwrap();
assert_eq!(existing.source_kind, SourceKind::Unknown);
assert_eq!(existing.date.as_deref(), Some("2026-10-13"));
assert_eq!(existing.sample.as_deref(), Some("typed sample"));
assert_eq!(existing.instrument.as_deref(), Some("typed instrument"));
assert_eq!(existing.operator.as_deref(), Some("typed operator"));
assert_eq!(existing.comment.as_deref(), Some("preserve me"));
assert_eq!(existing.tags, vec!["reference"]);
let registered_selected = store
.list_experiments()
.unwrap()
.into_iter()
.find(|entry| entry.source_identity == options.catalog_experiment_identity)
.unwrap();
assert_eq!(registered_selected.source_kind, SourceKind::Unknown);
assert_eq!(registered_selected.date.as_deref(), Some("2026-12-01"));
assert_eq!(
registered_selected.sample.as_deref(),
Some("selected typed sample")
);
assert_eq!(
registered_selected.instrument.as_deref(),
Some("selected instrument")
);
assert_eq!(
registered_selected.operator.as_deref(),
Some("selected operator")
);
assert_eq!(registered_selected.tags, vec!["new-run"]);
}
#[test]
fn registration_does_not_accept_a_separate_catalog_acquisition_date() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("invalid-date-run"))
.unwrap();
let identity = series.experiments()[0].meta.identity().to_string();
let mut model = PlotModel::new();
model.series = series;
let mut options = TestOptions {
catalog_experiment_identity: identity.clone(),
catalog_metadata_identity: identity.clone(),
..TestOptions::default()
};
options.register_current_experiment(&model, Some(&library), identity);
assert!(
options
.catalog_status
.as_deref()
.unwrap_or_default()
.contains("registered locally"),
"unexpected registration result: {:?}",
options.catalog_status
);
let store = CatalogStore::open_existing(&library).unwrap();
let card = store.list_experiments().unwrap().pop().unwrap();
assert_eq!(card.date, None);
assert!(store.list_publications().unwrap().is_empty());
}
#[test]
fn catalog_series_registration_loads_existing_note_and_tags_and_allows_explicit_clear() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, CatalogThermalMode, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
CatalogStore::open(directory.path()).unwrap();
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("metadata-run"))
.unwrap();
let experiment_identity = series.experiments()[0].meta.identity().to_string();
let experiment_id = CatalogId::parse(experiment_identity.clone()).unwrap();
CatalogStore::open_existing(directory.path())
.unwrap()
.register_experiment_snapshot(&CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_identity.clone(),
display_name: "metadata-run".into(),
source_kind: SourceKind::Unknown,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: Some(CatalogThermalMode::Isothermal),
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: Some("retained note".into()),
tags: vec!["batch-9".into(), "measured".into()],
})
.unwrap();
let mut model = PlotModel::new();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(directory.path().to_path_buf()),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
catalog_series_name: "metadata series".into(),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
assert_eq!(harness.state().options.catalog_comment, "retained note");
assert_eq!(harness.state().options.catalog_tags, "batch-9, measured");
harness.get_by_label("Register Current Series").click();
harness.run();
let store = CatalogStore::open_existing(directory.path()).unwrap();
let registered = store.get_experiment(&experiment_id).unwrap().unwrap();
assert_eq!(registered.comment.as_deref(), Some("retained note"));
assert_eq!(registered.tags, vec!["batch-9", "measured"]);
harness.state_mut().options.catalog_comment.clear();
harness.state_mut().options.catalog_tags.clear();
harness.get_by_label("Register Current Series").click();
harness.run();
let cleared = CatalogStore::open_existing(directory.path())
.unwrap()
.get_experiment(&experiment_id)
.unwrap()
.unwrap();
assert_eq!(cleared.comment, None);
assert!(cleared.tags.is_empty());
}
#[test]
fn catalog_window_publishes_series_with_external_file_reference() {
use crate::Kinetics::experimental_kinetics::catalog::CatalogArtifactPurpose;
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let source_folder = directory.path().join("measurement-files");
std::fs::create_dir(&source_folder).unwrap();
let source_file = source_folder.join("raw.csv");
std::fs::write(&source_file, "time,mass\n0,10\n1,9\n").unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_id: None,
local_library_path: Some(library.clone()),
..Default::default()
});
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("publish-run"))
.unwrap();
model.series = series;
let series_identity = model.series.identity().to_string();
let options = TestOptions {
catalog_window_open: true,
catalog_series_name: "Published from UI".into(),
test_catalog_files: Some(vec![source_file.clone()]),
..TestOptions::new()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
let save_target_before = harness
.state()
.document_dialog
.current_document_path()
.map(std::path::Path::to_path_buf);
harness.get_by_label("Register Selected Experiment").click();
harness.run();
let registered = CatalogStore::open_existing(&library).unwrap();
assert_eq!(registered.list_experiments().unwrap().len(), 1);
assert!(registered.list_publications().unwrap().is_empty());
harness.get_by_label("Publish snapshot...").scroll_to_me();
harness.run();
harness.get_by_label("Publish snapshot...").click();
harness.run();
harness.get_by_label("Add files...").click();
harness.run();
harness
.get_by_label("Publish Current Series")
.scroll_to_me();
harness.run();
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(harness.state().options.catalog_publish_result.is_none());
let store = CatalogStore::open_existing(&library).unwrap();
let publications = store.list_publications().unwrap();
assert_eq!(publications.len(), 1);
assert_eq!(publications[0].object_id.as_str(), series_identity);
assert_eq!(publications[0].artifact_ids.len(), 1);
assert!(matches!(
&publications[0].snapshot,
Some(CatalogPublicationSnapshot::Series { series, experiments })
if series.display_name == "Published from UI"
&& experiments.len() == 1
&& experiments[0].display_name == "publish-run"
));
harness.get_by_label("Refresh").click();
harness.run();
harness.get_by_label("Published series snapshot: Published from UI");
let artifact = store
.get_artifact(&publications[0].artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(artifact.purpose, CatalogArtifactPurpose::Other);
assert_eq!(artifact.file_name, "raw.csv");
let listing = harness
.state()
.options
.catalog_artifacts
.get(&artifact.id)
.unwrap();
assert_eq!(listing.artifact, artifact);
let local_status = local_artifact_status(&listing.local_resolution);
assert!(local_status.contains("Local file found"));
assert!(local_status.contains("checksum not checked"));
harness.get_by_label("raw.csv").scroll_to_me();
harness.run();
let _artifact_name_rect = harness.get_by_label("raw.csv").rect();
let _file_status_rect = harness.get_by_label(&local_status).rect();
std::fs::write(&source_file, "altered after publication").unwrap();
harness.get_by_label("Verify checksum").scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_verify_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(
matches!(
harness.state().options.catalog_integrity.get(&artifact.id),
Some(LocalArtifactIntegrity::Modified { .. })
),
"checksum result missing or unexpected: status={:?}, message={}, in_progress={:?}",
harness.state().options.catalog_status,
harness.state().model.message,
harness.state().options.catalog_verify_in_progress
);
assert!(harness.state().model.message.contains("modified"));
assert!(source_file.is_file());
assert!(!library.join("artifacts").exists());
assert_eq!(harness.state().model.series.identity(), series_identity);
assert_eq!(
harness
.state()
.document_dialog
.current_document_path()
.map(std::path::Path::to_path_buf),
save_target_before
);
std::fs::write(&source_file, "time,mass\n0,10\n1,9\n").unwrap();
let moved_folder = directory.path().join("measurement-files-moved");
std::fs::rename(&source_folder, &moved_folder).unwrap();
harness.get_by_label("Refresh").click();
harness.run();
harness.state_mut().options.test_catalog_relink_directory = None;
harness
.get_by_label("Relink moved folder...")
.scroll_to_me();
harness.run();
harness.get_by_label("Relink moved folder...").click();
harness.run();
assert!(harness.state().options.catalog_root_relink_result.is_none());
assert!(matches!(
CatalogStore::open_existing(&library)
.unwrap()
.resolve_local_artifact(&artifact.id)
.unwrap(),
crate::Kinetics::experimental_kinetics::catalog::LocalArtifactResolution::Missing(_)
));
harness.state_mut().options.test_catalog_relink_directory = Some(moved_folder.clone());
harness
.get_by_label("Relink moved folder...")
.scroll_to_me();
harness.run();
harness.get_by_label("Relink moved folder...").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_root_relink_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(harness.state().options.catalog_root_relink_result.is_none());
let refreshed = CatalogStore::open_existing(&library).unwrap();
assert_eq!(
refreshed.resolve_local_artifact(&artifact.id).unwrap(),
crate::Kinetics::experimental_kinetics::catalog::LocalArtifactResolution::Available(
std::fs::canonicalize(moved_folder.join("raw.csv")).unwrap()
)
);
let plot_path = directory.path().join("publication-plot.png");
std::fs::write(&plot_path, b"test image payload").unwrap();
harness.state_mut().options.catalog_pending_files.clear();
harness.state_mut().options.test_catalog_files = Some(vec![plot_path]);
harness.state_mut().options.catalog_parent_publication = Some(publications[0].id.clone());
harness.run();
harness.get_by_label("Add files...").click();
harness.run();
harness.get_by_label("Purpose for file 1").click();
harness.run();
harness.get_by_label("Plot image").click();
harness.run();
harness.get_by_label("Parent publication (optional)");
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
let child_publication = CatalogStore::open_existing(&library)
.unwrap()
.list_publications()
.unwrap()
.into_iter()
.find(|item| item.parent_publication_id.is_some())
.unwrap();
assert_eq!(
child_publication.parent_publication_id,
Some(publications[0].id.clone())
);
let kplot_path = directory.path().join("publication-plot.kplot");
std::fs::write(&kplot_path, b"test editable plot payload").unwrap();
harness.state_mut().options.catalog_pending_files.clear();
harness.state_mut().options.test_catalog_files = Some(vec![kplot_path]);
harness.state_mut().options.catalog_parent_publication = Some(child_publication.id.clone());
harness.run();
harness.get_by_label("Add files...").click();
harness.run();
harness.get_by_label("Purpose for file 1").click();
harness.run();
harness.get_by_label("Editable .kplot").click();
harness.run();
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
let child_store = CatalogStore::open_existing(&library).unwrap();
let child_publications = child_store
.list_publications()
.unwrap()
.into_iter()
.filter(|item| item.parent_publication_id.is_some())
.collect::<Vec<_>>();
assert_eq!(child_publications.len(), 2);
assert!(child_publications.iter().any(|item| {
item.parent_publication_id == Some(publications[0].id.clone())
&& item.artifact_ids.iter().any(|id| {
child_store
.get_artifact(id)
.unwrap()
.is_some_and(|artifact| {
artifact.purpose == CatalogArtifactPurpose::PlotImage
})
})
}));
assert!(child_publications.iter().any(|item| {
item.parent_publication_id == Some(child_publication.id.clone())
&& item.artifact_ids.iter().any(|id| {
child_store
.get_artifact(id)
.unwrap()
.is_some_and(|artifact| {
artifact.purpose == CatalogArtifactPurpose::EditableKiThePlot
})
})
}));
}
#[test]
fn publishing_changed_file_path_warns_that_previous_bytes_are_not_recoverable() {
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let source_file = directory.path().join("typed-series.csv");
std::fs::write(&source_file, "version one").unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "isothermal series".into(),
description: None,
};
let mut store = CatalogStore::open(&library).unwrap();
store.insert_series(&series).unwrap();
let make_publication = || CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: "2026-12-02T10:00:00Z".into(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let files = || {
vec![CatalogArtifactFile {
path: source_file.clone(),
purpose: CatalogArtifactPurpose::Other,
}]
};
let first = store
.publish_with_local_files(&make_publication(), &files())
.unwrap();
let old_artifact = store.get_artifact(&first.artifact_ids[0]).unwrap().unwrap();
let old_path = match store.resolve_local_artifact(&old_artifact.id).unwrap() {
LocalArtifactResolution::Available(path) => path,
other => panic!("expected a local artifact, got {other:?}"),
};
std::fs::write(&source_file, "version two with changed bytes").unwrap();
let second = store
.publish_with_local_files(&make_publication(), &files())
.unwrap();
assert_ne!(
old_artifact.sha256,
store
.get_artifact(&second.artifact_ids[0])
.unwrap()
.unwrap()
.sha256
);
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Ok(second)).unwrap();
let mut options = TestOptions {
catalog_publish_result: Some(receiver),
catalog_publish_library_path: Some(library),
catalog_publish_kind_in_progress: Some(CatalogObjectKind::Series),
catalog_artifacts: [(
old_artifact.id.clone(),
CatalogArtifactListing {
artifact: old_artifact,
local_resolution: LocalArtifactResolution::Available(old_path),
},
)]
.into_iter()
.collect(),
..TestOptions::default()
};
let mut model = PlotModel::new();
options.poll_catalog_publication(&egui::Context::default(), &mut model);
let status = options.catalog_status.as_deref().unwrap();
assert!(status.contains("WARNING:"), "unexpected status: {status}");
assert!(
status.contains("different checksum"),
"unexpected status: {status}"
);
assert!(
status.contains("not recoverable"),
"unexpected status: {status}"
);
assert!(model.message.contains("different checksum"));
}
#[test]
fn catalog_publish_progress_exposes_cancel_action() {
use super::{ArtifactHashProgress, CatalogPublishUiProgress};
use crate::Kinetics::experimental_kinetics::catalog::CatalogObjectKind;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
use std::sync::{Arc, Mutex};
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let (sender, receiver) = std::sync::mpsc::channel();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
catalog_publish_result: Some(receiver),
catalog_publish_progress: Some(Arc::new(Mutex::new(CatalogPublishUiProgress {
snapshot: ArtifactHashProgress {
file_index: 1,
file_count: 2,
file_name: "large-data.csv".into(),
bytes_in_file: 512 * 1024,
bytes_total: 512 * 1024,
total_bytes: 2 * 1024 * 1024,
},
..CatalogPublishUiProgress::default()
}))),
catalog_publish_kind_in_progress: Some(CatalogObjectKind::Series),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Hashing external files before the atomic database commit:");
harness.get_by_label("File 1/2: large-data.csv (0.5 / 2.0 MiB total)");
harness.get_by_label("Cancel publication").click();
harness.run();
assert!(
harness
.state()
.options
.catalog_publish_progress
.as_ref()
.unwrap()
.lock()
.unwrap()
.cancellation_requested
);
harness.get_by_label("Cancelling...");
drop(sender);
}
#[test]
fn typed_series_catalog_lifecycle_keeps_stable_identity_across_publications() {
use crate::Kinetics::experimental_kinetics::catalog::CatalogArtifactPurpose;
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let raw_path = directory.path().join("raw-source.csv");
std::fs::write(&raw_path, "time,mass\n0,10\n1,9.5\n2,9\n").unwrap();
let dataset = TGADataset::from_csv_universal(&raw_path)
.unwrap()
.bind_time("time", Unit::Second)
.unwrap();
let mut initial_series = TGASeries::new();
initial_series
.push(TGAExperiment::new(dataset.clone()).with_id("run-1"))
.unwrap();
let stable_series_id = initial_series.identity().to_string();
let first_typed_path = directory.path().join("series-v1.csv");
initial_series.to_csv_series(&first_typed_path).unwrap();
let mut model = PlotModel::new();
model.series = initial_series;
model.settings.set_catalog(
crate::gui::experimental_kinetics_gui::settings::CatalogSettings {
local_library_path: Some(library.clone()),
..CatalogSettings::default()
},
);
let mut options = TestOptions {
catalog_series_name: "isothermal runs".into(),
catalog_pending_files: vec![CatalogArtifactFile {
path: first_typed_path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
..TestOptions::default()
};
options.register_current_series(&model, Some(&library), false);
let store = CatalogStore::open_existing(&library).unwrap();
assert_eq!(store.list_series().unwrap().len(), 1);
assert!(store.list_publications().unwrap().is_empty());
let context = egui::Context::default();
options.publish_current_series(&mut model, Some(&library));
wait_for_catalog_publication(&mut options, &mut model, &context);
let first_store = CatalogStore::open_existing(&library).unwrap();
let first_publications = first_store.list_publications().unwrap();
assert_eq!(first_publications.len(), 1);
assert_eq!(first_publications[0].object_id.as_str(), stable_series_id);
assert_eq!(first_publications[0].series_members.len(), 1);
assert_eq!(first_publications[0].artifact_ids.len(), 1);
assert_eq!(
first_store
.get_artifact(&first_publications[0].artifact_ids[0])
.unwrap()
.unwrap()
.purpose,
CatalogArtifactPurpose::TypedKiTheDocument
);
let mut continued_series = TGASeries::from_csv_series(&first_typed_path).unwrap();
assert_eq!(continued_series.identity().to_string(), stable_series_id);
continued_series
.push(TGAExperiment::new(dataset).with_id("run-2"))
.unwrap();
let second_typed_path = directory.path().join("series-v2.csv");
continued_series.to_csv_series(&second_typed_path).unwrap();
model.series = TGASeries::from_csv_series(&second_typed_path).unwrap();
options.catalog_pending_files = vec![CatalogArtifactFile {
path: second_typed_path,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}];
assert_eq!(
CatalogStore::open_existing(&library)
.unwrap()
.list_publications()
.unwrap()
.len(),
1,
"append/save must not create a historical publication"
);
options.publish_current_series(&mut model, Some(&library));
wait_for_catalog_publication(&mut options, &mut model, &context);
let final_store = CatalogStore::open_existing(&library).unwrap();
let publications = final_store.list_publications().unwrap();
assert_eq!(publications.len(), 2);
assert!(
publications
.iter()
.all(|publication| publication.object_id.as_str() == stable_series_id)
);
assert_eq!(publications[0].series_members.len(), 2);
assert_eq!(publications[1].series_members.len(), 1);
assert!(matches!(
&publications[0].snapshot,
Some(CatalogPublicationSnapshot::Series { experiments, .. }) if experiments.len() == 2
));
assert!(matches!(
&publications[1].snapshot,
Some(CatalogPublicationSnapshot::Series { experiments, .. }) if experiments.len() == 1
));
}
fn wait_for_catalog_publication(
options: &mut TestOptions,
model: &mut PlotModel,
context: &egui::Context,
) {
for _ in 0..100 {
if options.catalog_publish_result.is_none() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(10));
options.poll_catalog_publication(context, model);
}
assert!(
options.catalog_publish_result.is_none(),
"catalog publish worker did not finish"
);
}
#[test]
fn failed_background_publish_keeps_pending_files_and_creates_no_partial_publication() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let missing_file = directory.path().join("missing-measurement.csv");
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library.clone()),
..Default::default()
});
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("publish-failure-run"))
.unwrap();
model.series = series;
let options = TestOptions {
catalog_window_open: true,
catalog_series_name: "failed publication".into(),
test_catalog_files: Some(vec![missing_file.clone()]),
..TestOptions::new()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Publish snapshot...").scroll_to_me();
harness.run();
harness.get_by_label("Publish snapshot...").click();
harness.run();
harness.get_by_label("Add files...").click();
harness.run();
harness
.get_by_label("Publish Current Series")
.scroll_to_me();
harness.run();
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(harness.state().options.catalog_publish_result.is_none());
assert_eq!(harness.state().options.catalog_pending_files.len(), 1);
assert!(
harness
.state()
.model
.message
.contains("Catalog publication failed")
);
let store = CatalogStore::open_existing(&library).unwrap();
assert!(store.list_publications().unwrap().is_empty());
assert!(store.list_series().unwrap().is_empty());
std::fs::write(&missing_file, "time,mass\n0,10\n1,9\n").unwrap();
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(harness.state().options.catalog_publish_result.is_none());
assert!(harness.state().options.catalog_pending_files.is_empty());
let store = CatalogStore::open_existing(&library).unwrap();
assert_eq!(store.list_publications().unwrap().len(), 1);
assert_eq!(store.list_series().unwrap().len(), 1);
}
#[test]
fn catalog_window_publishes_selected_single_experiment() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactPurpose, CatalogObjectKind, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let attachment = directory.path().join("one-run.txt");
std::fs::write(&attachment, "t\tm\n0\t1\n").unwrap();
let mut series = TGASeries::new();
let mut experiment = TGAExperiment::new(TGADataset::default()).with_id("selected-run");
experiment.meta.acquisition =
crate::Kinetics::experimental_kinetics::experiment_series_main::AcquisitionMetadata {
measurement_date: Some(chrono::NaiveDate::from_ymd_opt(2026, 11, 30).unwrap()),
sample_description: Some("powder-A".into()),
instrument: Some("TGA-7".into()),
operator: Some("operator-1".into()),
..Default::default()
};
series.push(experiment).unwrap();
let experiment_identity = series.experiments()[0].meta.identity().to_string();
let mut model = PlotModel::new();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library.clone()),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
catalog_publish_kind: CatalogObjectKind::Experiment,
catalog_experiment_identity: experiment_identity.clone(),
catalog_metadata_identity: experiment_identity.clone(),
catalog_comment: "metadata note".into(),
catalog_tags: "batch-2, measured".into(),
test_catalog_files: Some(vec![attachment]),
..TestOptions::new()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.with_max_steps(8)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
let save_target_before = harness
.state()
.document_dialog
.current_document_path()
.map(std::path::Path::to_path_buf);
harness.get_by_label("Register Selected Experiment").click();
harness.run();
harness.get_by_label("Publish snapshot...").scroll_to_me();
harness.run();
harness.get_by_label("Publish snapshot...").click();
harness.run();
harness.get_by_label(&format!("Target experiment ID: {experiment_identity}"));
harness.get_by_label("Add files...").click();
harness.run();
harness.get_by_label(&format!(
"Detected: delimited text (raw/untyped) | Target: {experiment_identity}"
));
harness
.get_by_label("Publish Current Experiment")
.scroll_to_me();
harness.run();
harness.get_by_label("Publish Current Experiment").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
assert!(harness.state().options.catalog_publish_result.is_none());
let store = CatalogStore::open_existing(&library).unwrap();
let experiments = store.list_experiments().unwrap();
assert_eq!(experiments.len(), 1);
assert_eq!(experiments[0].source_identity, experiment_identity);
assert_eq!(experiments[0].source_kind, SourceKind::Unknown);
assert_eq!(experiments[0].date.as_deref(), Some("2026-11-30"));
assert_eq!(experiments[0].sample.as_deref(), Some("powder-A"));
assert_eq!(experiments[0].instrument.as_deref(), Some("TGA-7"));
assert_eq!(experiments[0].operator.as_deref(), Some("operator-1"));
assert_eq!(experiments[0].comment.as_deref(), Some("metadata note"));
assert_eq!(experiments[0].tags, vec!["batch-2", "measured"]);
let publications = store.list_publications().unwrap();
assert_eq!(publications.len(), 1);
assert_eq!(publications[0].object_kind, CatalogObjectKind::Experiment);
assert_eq!(publications[0].artifact_ids.len(), 1);
assert!(matches!(
&publications[0].snapshot,
Some(CatalogPublicationSnapshot::Experiment(snapshot))
if snapshot.display_name == "selected-run"
&& snapshot.date.as_deref() == Some("2026-11-30")
&& snapshot.tags == vec!["batch-2", "measured"]
));
let artifact = store
.get_artifact(&publications[0].artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(artifact.purpose, CatalogArtifactPurpose::Other);
assert_eq!(harness.state().model.series.len(), 1);
assert_eq!(harness.state().options.catalog_pending_files.len(), 0);
assert_eq!(
harness
.state()
.document_dialog
.current_document_path()
.map(std::path::Path::to_path_buf),
save_target_before
);
}
#[test]
fn catalog_publish_target_switch_creates_only_selected_scope() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactPurpose, CatalogId, CatalogObjectKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let other_library = directory.path().join("other-catalog");
let mut other_store = CatalogStore::open(&other_library).unwrap();
let other_series_id = CatalogId::new();
other_store
.register_series_snapshot(
&CatalogSeries {
id: other_series_id,
display_name: "Only in other library".into(),
description: None,
},
&[],
)
.unwrap();
let attachment = directory.path().join("attached-to-a.png");
std::fs::write(&attachment, "attachment payload").unwrap();
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("target-a"))
.unwrap();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("target-b"))
.unwrap();
let series_identity = series.identity().to_string();
let selected_identity = series.experiments()[0].meta.identity().to_string();
let mut model = PlotModel::new();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library.clone()),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
catalog_publish_kind: CatalogObjectKind::Series,
catalog_series_name: "Target series".into(),
catalog_experiment_identity: selected_identity.clone(),
catalog_publish_author: "operator-A".into(),
catalog_publish_description: "Series-run interpretation".into(),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Publish snapshot...").scroll_to_me();
harness.run();
harness.get_by_label("Publish snapshot...").click();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Publication target")
.click();
harness.run();
harness.get_by_label("Single experiment").click();
harness.run();
harness.get_by_label(&format!("Target experiment ID: {selected_identity}"));
harness.get_by_label("Publication description / interpretation:");
harness.state_mut().options.test_catalog_files = Some(vec![attachment]);
harness.get_by_label("Add files...").click();
harness.run();
harness.get_by_label("Purpose for file 1").click();
harness.run();
harness.get_by_label("Plot image").click();
harness.run();
assert_eq!(
harness.state().options.catalog_pending_files[0].purpose,
CatalogArtifactPurpose::PlotImage
);
let stale_parent = CatalogId::new();
harness.state_mut().options.catalog_parent_publication = Some(stale_parent.clone());
harness.run();
let mut catalog_settings = harness.state().model.settings.catalog().clone();
catalog_settings.local_library_path = Some(other_library.clone());
harness
.state_mut()
.model
.settings
.set_catalog(catalog_settings);
harness.run();
assert_eq!(
harness.state().options.catalog_library_id.as_deref(),
Some(other_store.library_id())
);
harness
.get_by_label("1 matching catalog entries")
.scroll_to_me();
harness.run();
harness.get_by_label("Only in other library");
harness.get_by_label("This publication draft belongs to another library or target. Files, author, description, and parent link will not be published here until you explicitly move the entire draft.");
assert_eq!(
harness.state().options.catalog_parent_publication,
Some(stale_parent.clone())
);
assert_eq!(harness.state().options.catalog_pending_files.len(), 1);
assert_eq!(
harness.state().options.catalog_publish_description,
"Series-run interpretation"
);
assert_eq!(harness.state().options.catalog_publish_author, "operator-A");
let mut catalog_settings = harness.state().model.settings.catalog().clone();
catalog_settings.local_library_path = Some(library.clone());
harness
.state_mut()
.model
.settings
.set_catalog(catalog_settings);
harness.run();
let expected_library_id = CatalogStore::open_existing(&library)
.unwrap()
.library_id()
.to_owned();
assert_eq!(
harness.state().options.catalog_library_id.as_deref(),
Some(expected_library_id.as_str())
);
assert_eq!(harness.state().options.catalog_pending_files.len(), 1);
assert_eq!(
harness.state().options.catalog_publish_description,
"Series-run interpretation"
);
assert_eq!(harness.state().options.catalog_publish_author, "operator-A");
assert!(harness
.query_by_label("This publication draft belongs to another library or target. Files, author, description, and parent link will not be published here until you explicitly move the entire draft.")
.is_none());
harness
.get_by_role_and_label(
egui::accesskit::Role::ComboBox,
"Parent publication (optional)",
)
.scroll_to_me();
harness.run();
harness
.get_by_role_and_label(
egui::accesskit::Role::ComboBox,
"Parent publication (optional)",
)
.click();
harness.run();
harness.get_by_label("None").click();
harness.run();
assert_eq!(harness.state().options.catalog_parent_publication, None);
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Publication target")
.scroll_to_me();
harness.run();
harness
.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Publication target")
.click();
harness.run();
harness.get_by_label("Whole series").click();
harness.run();
harness.get_by_label("This publication draft belongs to another library or target. Files, author, description, and parent link will not be published here until you explicitly move the entire draft.");
harness
.get_by_label("Publish Current Series")
.scroll_to_me();
harness.run();
harness.get_by_label("Publish Current Series").click();
harness.run();
assert!(
CatalogStore::open_existing(&library)
.unwrap()
.list_publications()
.unwrap()
.is_empty()
);
harness
.get_by_label("Move entire publication draft to current target")
.scroll_to_me();
harness.run();
harness
.get_by_label("Move entire publication draft to current target")
.click();
harness.run();
harness
.get_by_label("Publish Current Series")
.scroll_to_me();
harness.run();
harness.get_by_label("Publish Current Series").click();
harness.run();
for _ in 0..100 {
if harness.state().options.catalog_publish_result.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
let store = CatalogStore::open_existing(&library).unwrap();
assert_eq!(store.list_series().unwrap().len(), 1);
let publications = store.list_publications().unwrap();
assert_eq!(publications.len(), 1);
assert_eq!(publications[0].object_kind, CatalogObjectKind::Series);
assert_eq!(publications[0].object_id.as_str(), series_identity);
assert_eq!(publications[0].series_members.len(), 2);
assert_eq!(publications[0].artifact_ids.len(), 1);
assert_eq!(
publications[0].description.as_deref(),
Some("Series-run interpretation")
);
}
#[test]
fn catalog_membership_reduction_requires_visible_confirmation_and_cancel_is_safe() {
use crate::Kinetics::experimental_kinetics::catalog::{CatalogId, CatalogObjectKind};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
CatalogStore::open(directory.path()).unwrap();
let mut model = PlotModel::new();
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("member-a"))
.unwrap();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("member-b"))
.unwrap();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(directory.path().to_path_buf()),
..Default::default()
});
let mut options = TestOptions {
catalog_window_open: true,
catalog_publish_kind: CatalogObjectKind::Series,
catalog_series_name: "shortened series".into(),
..TestOptions::default()
};
options.register_current_series(&model, Some(directory.path()), false);
model.series.drop_experiment(1).unwrap();
let series_id = CatalogId::parse(model.series.identity().to_string()).unwrap();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Register Current Series").click();
harness.run();
harness.get_by_label("Confirm series membership change");
harness.get_by_label("Confirm and register series");
harness.get_by_label("Cancel").click();
harness.run();
assert_eq!(
CatalogStore::open_existing(directory.path())
.unwrap()
.list_series_members(&series_id)
.unwrap()
.len(),
2
);
}
#[test]
fn catalog_opens_a_typed_series_through_the_document_loader() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactFile, CatalogArtifactPurpose, CatalogExperiment, CatalogId,
CatalogObjectKind, CatalogPublication, CatalogSeries, CatalogThermalMode,
PublishedSeriesMember, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let mut store = CatalogStore::open(&library).unwrap();
let raw_path = directory.path().join("source.csv");
std::fs::write(&raw_path, "time,mass\n0,10\n1,9\n").unwrap();
let dataset = TGADataset::from_csv_universal(&raw_path)
.unwrap()
.bind_time("time", Unit::Second)
.unwrap();
let mut archived_series = TGASeries::new();
archived_series
.push(TGAExperiment::new(dataset).with_id("archived-run"))
.unwrap();
let typed_path = directory.path().join("typed-series.csv");
archived_series.to_csv_series(&typed_path).unwrap();
let catalog_series = CatalogSeries {
id: CatalogId::parse(archived_series.identity().to_string()).unwrap(),
display_name: "Archived series".into(),
description: None,
};
let archived_experiment = &archived_series.experiments()[0];
let experiment_id =
CatalogId::parse(archived_experiment.meta.identity().to_string()).unwrap();
let catalog_experiment = CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().to_owned(),
display_name: archived_experiment.meta.id.clone(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: Some(CatalogThermalMode::Isothermal),
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: catalog_series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("typed document open test".into()),
series_members: vec![PublishedSeriesMember {
experiment_id,
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
store
.register_and_publish_series_snapshot(
&catalog_series,
&[catalog_experiment],
&publication,
&[CatalogArtifactFile {
path: typed_path,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.unwrap();
let mut model = PlotModel::new();
let mut current_series = TGASeries::new();
current_series
.push(TGAExperiment::new(TGADataset::default()).with_id("current-run"))
.unwrap();
model.series = current_series;
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library),
..Default::default()
});
let mut options = TestOptions::new();
options.open_catalog_browser();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
state
.document_dialog
.show_unsaved_changes_dialog(ui.ctx(), &mut state.model);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
assert!(
harness
.query_by_label("Open / Import typed document...")
.is_none()
);
let artifact_id = harness
.state()
.options
.catalog_artifacts
.iter()
.find(|(_, listing)| {
listing.artifact.purpose == CatalogArtifactPurpose::TypedKiTheDocument
})
.map(|(id, _)| id.clone())
.unwrap();
harness
.get_by_label("2 matching catalog entries")
.scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").click();
for _ in 0..100 {
if matches!(
harness.state().options.catalog_integrity.get(&artifact_id),
Some(LocalArtifactIntegrity::Verified)
) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
harness
.get_by_label("Open / Import typed document...")
.scroll_to_me();
harness.run();
harness
.get_by_label("Open / Import typed document...")
.click();
harness.run();
harness.get_by_label("Unsaved document changes");
assert_eq!(
harness.state().model.series.experiments()[0].meta.id,
"current-run"
);
harness.get_by_label("Discard").click();
harness.run();
assert_eq!(harness.state().model.series.len(), 1);
assert_eq!(
harness.state().model.series.experiments()[0].meta.id,
"archived-run"
);
}
#[test]
fn catalog_raw_attachment_opens_existing_binding_import_form() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactFile, CatalogArtifactPurpose, CatalogId, CatalogObjectKind,
CatalogPublication, CatalogSeries,
};
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let raw_path = directory.path().join("measured-run.txt");
std::fs::write(&raw_path, "time\tmass\n0\t10\n1\t9\n").unwrap();
let mut store = CatalogStore::open(&library).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "raw source series".into(),
description: None,
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
store
.register_and_publish_series_snapshot(
&series,
&[],
&publication,
&[CatalogArtifactFile {
path: raw_path.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
}],
)
.unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library),
..Default::default()
});
let mut options = TestOptions::new();
options.open_catalog_browser();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.document_dialog
.show_new_experiment_dialogue(ui.ctx(), &mut state.model);
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
let artifact_id = harness
.state()
.options
.catalog_artifacts
.iter()
.find(|(_, listing)| {
listing.artifact.purpose == CatalogArtifactPurpose::RawInstrumentData
})
.map(|(id, _)| id.clone())
.unwrap();
harness
.get_by_label("1 matching catalog entries")
.scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").click();
for _ in 0..100 {
if matches!(
harness.state().options.catalog_integrity.get(&artifact_id),
Some(LocalArtifactIntegrity::Verified)
) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
harness.get_by_label("Show folder");
harness.get_by_label("Import raw data...").click();
harness.run();
assert!(harness.state().document_dialog.open);
let expected_path = std::fs::canonicalize(&raw_path).unwrap();
assert_eq!(
harness.state().document_dialog.selected_file.as_deref(),
Some(expected_path.as_path())
);
harness.get_by_label("Experiment ID:");
assert!(!harness.state().options.catalog_window_open);
assert!(harness.state().model.series.is_empty());
}
#[test]
fn raw_file_can_be_catalogued_before_an_experiment_is_imported() {
use crate::Kinetics::experimental_kinetics::catalog::{CatalogArtifactPurpose, SourceKind};
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let raw_path = directory.path().join("instrument-run.txt");
std::fs::write(
&raw_path,
"time\ttemperature\tmass\n0\t500\t10\n1\t500\t9.9\n",
)
.unwrap();
let queued_series_attachment = directory.path().join("series-result.csv");
std::fs::write(&queued_series_attachment, "series publication draft").unwrap();
CatalogStore::open(&library).unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library.clone()),
..Default::default()
});
let mut options = TestOptions::new();
options.test_catalog_files = Some(vec![raw_path.clone()]);
options.catalog_pending_files = vec![CatalogArtifactFile {
path: queued_series_attachment.clone(),
purpose: CatalogArtifactPurpose::Other,
}];
options.catalog_publish_description = "Keep this series draft".into();
options.open_catalog_browser();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness.get_by_label("Register raw source...").click();
harness.run();
harness.state_mut().options.catalog_raw_source.display_name =
"Unprocessed instrument run".into();
harness.get_by_label("Add raw file...").click();
harness.run();
harness.get_by_label("Register raw source").click();
for _ in 0..100 {
harness.run_steps(8);
if harness.state().options.catalog_publish_result.is_none()
&& harness
.state()
.options
.catalog_status
.as_deref()
.is_some_and(|status| status.starts_with("Published local experiment snapshot"))
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
let store = CatalogStore::open_existing(&library).unwrap();
let experiment = store.list_experiments().unwrap().pop().unwrap();
assert_eq!(experiment.display_name, "Unprocessed instrument run");
assert_eq!(experiment.source_kind, SourceKind::Unknown);
let publication = store.list_publications().unwrap().pop().unwrap();
assert_eq!(publication.object_id, experiment.id);
assert_eq!(publication.artifact_ids.len(), 1);
let artifact = store
.get_artifact(&publication.artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(artifact.purpose, CatalogArtifactPurpose::RawInstrumentData);
assert_eq!(artifact.file_name, "instrument-run.txt");
assert_eq!(
harness.state().options.catalog_pending_files[0].path,
queued_series_attachment
);
assert_eq!(
harness.state().options.catalog_publish_description,
"Keep this series draft"
);
assert!(harness.state().model.series.is_empty());
}
#[test]
fn catalog_opens_kplot_attachment_in_the_embedded_editor() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactFile, CatalogArtifactPurpose, CatalogExperiment, CatalogId,
CatalogObjectKind, CatalogPublication, CatalogPublicationSnapshot, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series2::SampledColumns;
use crate::gui::experimental_kinetics_gui::kitheplot_wrapper::KiThePlotWindowState;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
use kithe_plot::controller::PlotController;
use kithe_plot::controller::action::Action;
use kithe_plot::model::PublicationDimensions;
struct PlotCatalogState {
options: TestOptions,
model: PlotModel,
document_dialog: NewExperimentDialogState,
plot_editor: KiThePlotWindowState,
}
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let plot_path = directory.path().join("publication.kplot");
let mut writer = PlotController::new();
writer
.load_from_data_source(&SampledColumns::new(
vec![vec![0.0, 1.0], vec![10.0, 9.0]],
vec!["time".into(), "mass".into()],
))
.unwrap();
writer
.dispatch(Action::SaveProject {
path: plot_path.to_string_lossy().into_owned(),
dimensions: PublicationDimensions::default(),
})
.unwrap();
let experiment_id = CatalogId::new();
let experiment = CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().into(),
display_name: "plot source".into(),
source_kind: SourceKind::Unknown,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment_id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Experiment(experiment.clone())),
typed_documents: vec![],
};
let mut store = CatalogStore::open(&library).unwrap();
store
.register_and_publish_experiment_snapshot(
&experiment,
&publication,
&[CatalogArtifactFile {
path: plot_path,
purpose: CatalogArtifactPurpose::EditableKiThePlot,
}],
)
.unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library),
..Default::default()
});
let mut options = TestOptions::new();
options.open_catalog_browser();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut PlotCatalogState| {
state.options.show_catalog_window_with_plot_editor(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
Some(&mut state.plot_editor),
);
},
PlotCatalogState {
options,
model,
document_dialog: NewExperimentDialogState::new(),
plot_editor: KiThePlotWindowState::default(),
},
);
harness.run();
let artifact_id = harness
.state()
.options
.catalog_artifacts
.iter()
.find(|(_, listing)| {
listing.artifact.purpose == CatalogArtifactPurpose::EditableKiThePlot
})
.map(|(id, _)| id.clone())
.unwrap();
harness.get_by_label("Verify checksum").scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").click();
for _ in 0..100 {
if matches!(
harness.state().options.catalog_integrity.get(&artifact_id),
Some(LocalArtifactIntegrity::Verified)
) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
harness
.get_by_label("Open in KiThe Plot Editor")
.scroll_to_me();
harness.run();
harness.get_by_label("Open in KiThe Plot Editor").click();
harness.run();
let plot_editor = &harness.state().plot_editor;
assert!(
plot_editor.open,
"catalog plot open failed: model_message={:?}, catalog_status={:?}",
harness.state().model.message,
harness.state().options.catalog_status
);
}
#[test]
fn catalog_typed_dataset_attachment_opens_dataset_import_not_series_open() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactFile, CatalogArtifactPurpose, CatalogExperiment, CatalogId,
CatalogObjectKind, CatalogPublication, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::TGAExperiment;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::{TGADataset, Unit};
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let raw_path = directory.path().join("raw-source.csv");
std::fs::write(&raw_path, "time,mass\n0,10\n1,9\n").unwrap();
let typed_path = directory.path().join("typed-dataset.csv");
let typed_experiment = TGAExperiment::new(
TGADataset::from_csv_universal(&raw_path)
.unwrap()
.bind_time("time", Unit::Second)
.unwrap(),
)
.with_id("typed dataset attachment");
typed_experiment.to_csv_with_units(&typed_path).unwrap();
let mut store = CatalogStore::open(&library).unwrap();
let source_identity = typed_experiment.meta.identity().to_string();
let experiment = CatalogExperiment {
id: CatalogId::parse(source_identity.clone()).unwrap(),
source_identity,
display_name: "typed dataset attachment".into(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
store
.register_and_publish_experiment_snapshot(
&experiment,
&publication,
&[CatalogArtifactFile {
path: typed_path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.unwrap();
let mut model = PlotModel::new();
model.settings.set_catalog(CatalogSettings {
local_library_path: Some(library),
..Default::default()
});
let mut options = TestOptions::new();
options.open_catalog_browser();
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state
.document_dialog
.show_new_experiment_dialogue(ui.ctx(), &mut state.model);
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
);
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
let artifact_id = harness
.state()
.options
.catalog_artifacts
.iter()
.find(|(_, listing)| {
listing.artifact.purpose == CatalogArtifactPurpose::TypedKiTheDocument
})
.map(|(id, _)| id.clone())
.unwrap();
harness.get_by_label("Verify checksum").scroll_to_me();
harness.run();
harness.get_by_label("Verify checksum").click();
for _ in 0..100 {
if matches!(
harness.state().options.catalog_integrity.get(&artifact_id),
Some(LocalArtifactIntegrity::Verified)
) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
harness.run();
}
harness
.get_by_label("Open / Import typed document...")
.click();
harness.run();
assert!(harness.state().document_dialog.open);
assert_eq!(
harness.state().document_dialog.selected_file.as_deref(),
Some(std::fs::canonicalize(&typed_path).unwrap().as_path())
);
assert_eq!(harness.state().model.series.len(), 0);
assert!(!harness.state().options.catalog_window_open);
harness.get_by_label("Experiment ID:");
harness.get_by_label("Import experiment");
}
#[test]
fn catalog_window_creates_study_and_substance_and_assigns_current_series() {
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogExperiment, CatalogId, CatalogSeries, CatalogThermalMode, SourceKind,
};
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
use crate::gui::experimental_kinetics_gui::settings::CatalogSettings;
use egui_kittest::{Harness, kittest::Queryable};
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
let mut store = CatalogStore::open(&library).unwrap();
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(TGADataset::default()).with_id("campaign-run"))
.unwrap();
let series_id = CatalogId::parse(series.identity().to_string()).unwrap();
let experiment = &series.experiments()[0];
let experiment_id = CatalogId::parse(experiment.meta.identity().to_string()).unwrap();
store
.register_series_snapshot(
&CatalogSeries {
id: series_id.clone(),
display_name: "Campaign run".into(),
description: None,
},
&[CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().to_owned(),
display_name: experiment.meta.id.clone(),
source_kind: SourceKind::Measured,
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: Some(CatalogThermalMode::Isothermal),
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: None,
tags: Vec::new(),
}],
)
.unwrap();
let mut model = PlotModel::new();
model.series = series;
model.settings.set_catalog(CatalogSettings {
local_library_id: None,
local_library_path: Some(library.clone()),
..Default::default()
});
let options = TestOptions {
catalog_window_open: true,
catalog_refresh_requested: true,
catalog_study_name: "Catalyst comparison".into(),
catalog_substance_name: "Catalyst A".into(),
catalog_sample_name: "Catalyst batch 7".into(),
catalog_sample_batch: "B-7".into(),
test_catalog_manifest_path: Some(directory.path().join("campaign.json")),
..TestOptions::default()
};
let mut harness = Harness::builder()
.with_accessibility_check(false)
.build_ui_state(
|ui, state: &mut State| {
state.options.show_catalog_window(
ui.ctx(),
&mut state.model,
&mut state.document_dialog,
)
},
State {
options,
model,
document_dialog: NewExperimentDialogState::new(),
},
);
harness.run();
harness
.get_by_label("Research studies, substances, and samples")
.click();
harness.run();
harness.get_by_label("Create study").click();
harness.run();
harness.get_by_label("Create substance").click();
harness.run();
harness.get_by_label("Add substance to study").click();
harness.run();
harness
.get_by_label("Assign current series to substance")
.click();
harness.run();
harness.get_by_label("Add current series to study").click();
harness.run();
harness
.get_by_label("Create and assign sample")
.scroll_to_me();
harness.run();
harness.get_by_label("Create and assign sample").click();
harness.run();
let store = CatalogStore::open_existing(&library).unwrap();
let substance_id = store.substance_for_series(&series_id).unwrap().unwrap();
let study = store.list_studies().unwrap().pop().unwrap();
assert_eq!(study.display_name, "Catalyst comparison");
assert_eq!(
store.list_study_substances(&study.id).unwrap()[0].id,
substance_id
);
assert_eq!(store.list_study_series(&study.id).unwrap().len(), 1);
let sample_id = store
.sample_for_experiment(&experiment_id)
.unwrap()
.unwrap();
let sample = store.get_sample(&sample_id).unwrap().unwrap();
assert_eq!(sample.display_name, "Catalyst batch 7");
assert_eq!(sample.batch_label.as_deref(), Some("B-7"));
assert_eq!(sample.substance_id, substance_id);
std::fs::write(directory.path().join("campaign.json"), "previous contents").unwrap();
harness
.get_by_label("Export study manifest...")
.scroll_to_me();
harness.run();
harness.get_by_label("Export study manifest...").click();
harness.run();
let manifest_path = directory.path().join("campaign.json");
let manifest =
crate::Kinetics::experimental_kinetics::catalog::CatalogStudyManifest::from_json(
&std::fs::read_to_string(&manifest_path).unwrap(),
)
.unwrap();
assert_eq!(manifest.study.display_name, "Catalyst comparison");
assert_eq!(manifest.substances.len(), 1);
assert_eq!(manifest.samples.len(), 1);
assert_eq!(manifest.series.len(), 1);
assert_eq!(
manifest.series[0].substance_id.as_ref(),
Some(&substance_id)
);
assert_eq!(manifest.series[0].current_members.len(), 1);
assert_eq!(manifest.series[0].experiment_samples.len(), 1);
assert_eq!(
manifest.series[0].experiment_samples[0].experiment_id,
experiment_id
);
assert_eq!(
manifest.series[0].experiment_samples[0].sample_id,
manifest.samples[0].id
);
}
#[test]
fn failed_study_manifest_export_preserves_existing_destination() {
use crate::Kinetics::experimental_kinetics::catalog::CatalogId;
let directory = tempfile::tempdir().unwrap();
let library = directory.path().join("catalog");
CatalogStore::open(&library).unwrap();
let destination = directory.path().join("study.json");
std::fs::write(&destination, "keep this file").unwrap();
let mut options = TestOptions::default();
options.export_catalog_study_manifest(Some(&library), &CatalogId::new(), &destination);
assert_eq!(
std::fs::read_to_string(destination).unwrap(),
"keep this file"
);
assert!(
options
.catalog_status
.as_deref()
.is_some_and(|status| status.starts_with("Could not export study manifest:"))
);
}
}