diff --git a/crates/analysis/src/afm_hertz.rs b/crates/analysis/src/afm_hertz.rs index fdc7fdc..bb2ce7c 100644 --- a/crates/analysis/src/afm_hertz.rs +++ b/crates/analysis/src/afm_hertz.rs @@ -190,20 +190,20 @@ fn validate(points: &[[f64; 2]], input: HertzInput) -> Result<(), HertzError> { Ok(()) } -struct LinearBaseline { +pub(super) struct LinearBaseline { center_z_nm: f64, center_force_nn: f64, - slope_nn_per_nm: f64, - rms_nn: f64, + pub(super) slope_nn_per_nm: f64, + pub(super) rms_nn: f64, samples: usize, } impl LinearBaseline { - fn at(&self, z: f64) -> f64 { + pub(super) fn at(&self, z: f64) -> f64 { self.center_force_nn + self.slope_nn_per_nm * (z - self.center_z_nm) } - fn fit(points: &[[f64; 2]], interval: [f64; 2]) -> Result { + pub(super) fn fit(points: &[[f64; 2]], interval: [f64; 2]) -> Result { let selected = points.iter().filter(|[z, _]| contains(interval, *z)); let (z_sum, force_sum, samples) = selected .clone() diff --git a/crates/analysis/src/afm_hertz_suggestion.rs b/crates/analysis/src/afm_hertz_suggestion.rs new file mode 100644 index 0000000..fc7014c --- /dev/null +++ b/crates/analysis/src/afm_hertz_suggestion.rs @@ -0,0 +1,235 @@ +//! Conservative screening for a manual spherical Hertz fit, not a contact or modulus estimator. + +use super::afm_hertz::{HertzInput, LinearBaseline}; +use thiserror::Error; + +const MIN_SAMPLES: usize = 32; +const MIN_BASELINE_SAMPLES: usize = 8; +const SUSTAINED_SAMPLES: usize = 5; +const MIN_FIT_SAMPLES: usize = 8; +const MAX_INDENTATION_RADIUS_RATIO: f64 = 0.1; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HertzSuggestion { + pub input: HertzInput, + /// RMS of the preliminary linear force baseline. + pub baseline_rms_nn: f64, + /// Baseline-corrected force at the start of the sustained loading run. + pub onset_force_nn: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)] +pub enum SuggestionError { + #[error( + "Use a valid force calibration, positive spring constant, and positive spherical probe radius." + )] + Calibration, + #[error("Use manual picks: the approach curve has too few finite samples.")] + Samples, + #[error("Use manual picks: relative Z is not a single regularly sampled ramp.")] + Ramp, + #[error("Use manual picks: the far-field baseline is unstable.")] + Baseline, + #[error("Use manual picks: no clear sustained loading onset was found.")] + Onset, + #[error("Use manual picks: an isolated excursion or possible adhesion obscures the onset.")] + Excursion, + #[error("Use manual picks: no sustained shallow compressive fit window was found.")] + Window, +} + +/// Propose one candidate from a verified loading branch with compression-positive force. +/// +/// Each point is `[relative actuator Z in nm, signed force in nN]`; larger Z +/// is farther from the sample. Array order may be reversed for display. +/// `force_increment_nn` is the magnitude of one detector count in nN, or +/// zero for unquantized inputs. +/// This screening only supports well-sampled curves with a quiet pre-contact +/// tail. It does not fit a modulus or test whether Hertz is the right model. +pub fn suggest_hertz( + points: &[[f64; 2]], + spring_constant_n_per_m: f64, + radius_nm: f64, + force_increment_nn: f64, +) -> Result { + if !spring_constant_n_per_m.is_finite() + || spring_constant_n_per_m <= 0.0 + || !radius_nm.is_finite() + || radius_nm <= 0.0 + || !force_increment_nn.is_finite() + || force_increment_nn < 0.0 + { + return Err(SuggestionError::Calibration); + } + let ordered = ordered_ramp(points)?; + // Fix the baseline support before looking for an onset. Fitting through a + // detected onset could instead absorb early loading into the force baseline. + let n_baseline = (ordered.len() / 5).max(MIN_BASELINE_SAMPLES); + let baseline_z_nm = [ordered[n_baseline - 1][0], ordered[0][0]]; + let baseline = LinearBaseline::fit(&ordered[..n_baseline], baseline_z_nm) + .map_err(|_| SuggestionError::Baseline)?; + // Refuse a tail with a slope comparable to the calibrated cantilever + // stiffness; a small linear detector drift is still permitted. + if baseline.slope_nn_per_nm.abs() > 0.1 * spring_constant_n_per_m { + return Err(SuggestionError::Baseline); + } + let corrected: Vec<_> = ordered + .iter() + .map(|&[z, force]| [z, force - baseline.at(z)]) + .collect(); + if corrected.iter().any(|point| !point[1].is_finite()) { + return Err(SuggestionError::Baseline); + } + let noise = noise_scale( + &ordered[..n_baseline], + &corrected[..n_baseline], + force_increment_nn, + )?; + let (contact, onset) = find_onset(&corrected, n_baseline, noise)?; + let contact_z_nm = corrected[contact][0]; + let fit_z_nm = fit_window( + &corrected[onset..], + contact_z_nm, + spring_constant_n_per_m, + radius_nm, + noise, + )?; + Ok(HertzSuggestion { + input: HertzInput { + spring_constant_n_per_m, + radius_nm, + baseline_z_nm, + contact_z_nm, + fit_z_nm, + }, + baseline_rms_nn: baseline.rms_nn, + onset_force_nn: corrected[onset][1], + }) +} + +fn ordered_ramp(points: &[[f64; 2]]) -> Result, SuggestionError> { + if points.len() < MIN_SAMPLES || !points.iter().flatten().all(|value| value.is_finite()) { + return Err(SuggestionError::Samples); + } + let reverse = points[0][0] < points[1][0]; + let (mut smallest, mut largest) = (f64::INFINITY, 0.0_f64); + for pair in points.windows(2) { + let step = if reverse { + pair[1][0] - pair[0][0] + } else { + pair[0][0] - pair[1][0] + }; + if !step.is_finite() || step <= 0.0 { + return Err(SuggestionError::Ramp); + } + smallest = smallest.min(step); + largest = largest.max(step); + } + // Don't interpret a discontinuity or a highly undersampled interval as an onset. + if largest / smallest > 4.0 { + return Err(SuggestionError::Ramp); + } + let mut ordered = points.to_vec(); + if reverse { + ordered.reverse(); + } + Ok(ordered) +} + +fn noise_scale( + raw: &[[f64; 2]], + corrected: &[[f64; 2]], + force_increment_nn: f64, +) -> Result { + let mut residuals: Vec<_> = corrected.iter().map(|point| point[1]).collect(); + let center = median(&mut residuals); + for residual in &mut residuals { + *residual = (*residual - center).abs(); + } + let mad = median(&mut residuals); + // The Gaussian scaling provides a useful screening scale without letting + // one spike inflate an RMS estimate. A flat baseline can have zero MAD + // even when the detector resolves only whole counts. + let force_scale = raw.iter().map(|point| point[1].abs()).fold(0.0, f64::max); + let noise = (1.4826 * mad) + .max(force_increment_nn) + .max(64.0 * f64::EPSILON * force_scale.max(f64::MIN_POSITIVE)); + if !noise.is_finite() || residuals.iter().any(|&value| value > 5.0 * noise) { + return Err(SuggestionError::Baseline); + } + Ok(noise) +} + +fn median(values: &mut [f64]) -> f64 { + values.sort_unstable_by(f64::total_cmp); + let middle = values.len() / 2; + if values.len().is_multiple_of(2) { + values[middle - 1].midpoint(values[middle]) + } else { + values[middle] + } +} + +fn find_onset( + points: &[[f64; 2]], + n_baseline: usize, + noise: f64, +) -> Result<(usize, usize), SuggestionError> { + let threshold = 5.0 * noise; + let tail = &points[n_baseline..]; + let onset = tail + .iter() + .position(|point| point[1] > threshold) + .ok_or(SuggestionError::Onset)?; + if tail[..onset].iter().any(|point| point[1] < -threshold) + || tail + .get(onset..onset + SUSTAINED_SAMPLES) + .is_none_or(|run| run.iter().any(|point| point[1] <= threshold)) + { + return Err(SuggestionError::Excursion); + } + let onset = n_baseline + onset; + let contact = (n_baseline..onset) + .rfind(|&index| points[index][1].abs() <= 1.5 * noise) + .ok_or(SuggestionError::Onset)?; + // A long transition between the last quiet sample and the sustained rise + // makes the contact too ambiguous to propose. + if onset - contact > MIN_FIT_SAMPLES { + return Err(SuggestionError::Onset); + } + Ok((contact, onset)) +} + +fn fit_window( + points: &[[f64; 2]], + contact_z_nm: f64, + k: f64, + radius_nm: f64, + noise: f64, +) -> Result<[f64; 2], SuggestionError> { + let mut previous_force = 0.0_f64; + let mut previous_indentation = 0.0_f64; + let mut end = 0; + for &[z, force] in points { + let indentation = contact_z_nm - z - force / k; + if !indentation.is_finite() + || indentation <= previous_indentation + || indentation > MAX_INDENTATION_RADIUS_RATIO * radius_nm + || force <= 0.0 + || force < previous_force - 2.0 * noise + { + break; + } + previous_force = force; + previous_indentation = indentation; + end += 1; + } + if end < MIN_FIT_SAMPLES || previous_force - points[0][1] < 5.0 * noise { + return Err(SuggestionError::Window); + } + Ok([points[end - 1][0], points[0][0]]) +} + +#[cfg(test)] +#[path = "afm_hertz_suggestion_tests.rs"] +mod tests; diff --git a/crates/analysis/src/afm_hertz_suggestion_tests.rs b/crates/analysis/src/afm_hertz_suggestion_tests.rs new file mode 100644 index 0000000..3113a9e --- /dev/null +++ b/crates/analysis/src/afm_hertz_suggestion_tests.rs @@ -0,0 +1,154 @@ +use super::*; +use crate::afm_hertz::fit_hertz; + +const K: f64 = 20.0; +const RADIUS: f64 = 400.0; +const CONTACT: f64 = 100.0; + +fn baseline(z: f64) -> f64 { + 1.25 + 0.002 * z +} + +fn reference_curve() -> Vec<[f64; 2]> { + let mut points: Vec<_> = (0..=60) + .rev() + .map(|i| { + let z = CONTACT + f64::from(i); + [z, baseline(z)] + }) + .collect(); + points.extend((1..=30).map(|i| { + // F = delta^(3/2) in nN corresponds to E* = 37.5 MPa at R = 400 nm. + let delta = f64::from(i); + let force = delta * delta.sqrt(); + let z = CONTACT - delta - force / K; + [z, baseline(z) + force] + })); + points +} + +#[test] +fn starts_at_a_known_noiseless_contact_and_yields_a_manual_hertz_window() { + let mut points = reference_curve(); + let suggested = suggest_hertz(&points, K, RADIUS, 0.0).unwrap(); + assert_eq!(suggested.input.contact_z_nm, CONTACT); + assert_eq!(suggested.input.baseline_z_nm, [143.0, 160.0]); + assert_eq!( + suggested.input.fit_z_nm, + [points.last().unwrap()[0], points[61][0]] + ); + assert!(suggested.baseline_rms_nn < 1e-12); + assert!((suggested.onset_force_nn - 1.0).abs() < 1e-12); + let fit = fit_hertz(&points, suggested.input).unwrap(); + assert_eq!(fit.rows.len(), 30); + assert!((fit.reduced_modulus_mpa - 37.5).abs() < 1e-10); + + points.reverse(); + assert_eq!(suggest_hertz(&points, K, RADIUS, 0.0), Ok(suggested)); +} + +#[test] +fn tolerates_small_baseline_noise_and_caps_the_window_by_radius() { + let mut points = reference_curve(); + for (i, point) in points.iter_mut().enumerate() { + point[1] += [0.03, -0.015, -0.03, 0.015][i % 4]; + } + let radius = 150.0; + let suggested = suggest_hertz(&points, K, radius, 0.0).unwrap(); + assert!((suggested.input.contact_z_nm - CONTACT).abs() <= 1.1); + assert!(suggested.baseline_rms_nn > 0.01); + let fit = fit_hertz(&points, suggested.input).unwrap(); + assert!(fit.rows.len() < 30); + assert!(fit.max_indentation_over_radius <= 0.1); + assert!(fit.max_indentation_over_radius >= 0.08); +} + +#[test] +fn does_not_propose_on_flat_force_noisy_force_or_insufficient_shallow_data() { + let mut points = reference_curve(); + assert_eq!( + suggest_hertz(&points, K, 1.0, 0.0), + Err(SuggestionError::Window) + ); + for [z, f] in &mut points { + *f = baseline(*z); + } + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Onset) + ); + for (i, [z, f]) in points.iter_mut().enumerate() { + *f = baseline(*z) + if i % 2 == 0 { 1.0 } else { -1.0 }; + } + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Onset) + ); + assert_eq!( + suggest_hertz(&points[..31], K, RADIUS, 0.0), + Err(SuggestionError::Samples) + ); + assert_eq!( + suggest_hertz(&points, K, f64::NAN, 0.0), + Err(SuggestionError::Calibration) + ); +} + +#[test] +fn ignores_one_count_before_clear_loading() { + let increment = 0.01; + for sign in [-1.0, 1.0] { + let mut points = reference_curve(); + for [z, force] in &mut points { + *force = 2.0 + ((*force - baseline(*z)) / increment).round() * increment; + } + points[55][1] += sign * increment; + let suggestion = suggest_hertz(&points, K, RADIUS, increment).unwrap(); + assert_eq!(suggestion.input.contact_z_nm, CONTACT); + assert_eq!(suggestion.baseline_rms_nn, 0.0); + assert!(suggestion.onset_force_nn > 5.0 * increment); + } +} + +#[test] +fn rejects_premature_spikes_and_adhesive_excursions() { + for sign in [-1.0, 1.0] { + let mut points = reference_curve(); + points[55][1] += sign; + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.01), + Err(SuggestionError::Excursion) + ); + } +} + +#[test] +fn rejects_bad_ramps_and_unstable_baseline() { + let mut points = reference_curve(); + points.swap(30, 31); + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Ramp) + ); + points.swap(30, 31); + points.drain(30..34); + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Ramp) + ); + + let mut points = reference_curve(); + points[4][1] += 1.0; + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Baseline) + ); + let mut points = reference_curve(); + for [z, f] in &mut points { + *f += *z * K; + } + assert_eq!( + suggest_hertz(&points, K, RADIUS, 0.0), + Err(SuggestionError::Baseline) + ); +} diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 3f828fd..cdf0d5a 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -2,6 +2,7 @@ //! scientific parameter estimation over processed data. pub mod afm_hertz; +pub mod afm_hertz_suggestion; pub mod alignment; pub mod craft; pub mod diffusion; diff --git a/crates/app/src/ui/commands/roster.rs b/crates/app/src/ui/commands/roster.rs index 8ad6627..9fd1807 100644 --- a/crates/app/src/ui/commands/roster.rs +++ b/crates/app/src/ui/commands/roster.rs @@ -130,6 +130,8 @@ pub(super) fn command_ids(recent_files: usize) -> Vec { CommandId::FitAfmForce(AfmForceBranch::Approach), CommandId::FitAfmForce(AfmForceBranch::Retract), CommandId::AfmFit(AfmFitCommand::OpenHertz), + CommandId::AfmFit(AfmFitCommand::SuggestHertz), + CommandId::AfmFit(AfmFitCommand::ApplyHertzSuggestion), CommandId::AfmFit(AfmFitCommand::RunHertz), CommandId::AfmFit(AfmFitCommand::HertzDataSheet), CommandId::AfmFit(AfmFitCommand::Run), diff --git a/crates/app/src/ui/commands/types.rs b/crates/app/src/ui/commands/types.rs index 961a094..3b30387 100644 --- a/crates/app/src/ui/commands/types.rs +++ b/crates/app/src/ui/commands/types.rs @@ -10,6 +10,8 @@ pub enum AfmFitCommand { DataSheet, ShowSource, OpenHertz, + SuggestHertz, + ApplyHertzSuggestion, RunHertz, HertzDataSheet, } @@ -50,6 +52,16 @@ impl AfmFitCommand { icon::ARROW_LEFT, ), Self::OpenHertz => ("Manual Hertz", "analysis.afm_hertz", icon::CHART_LINE_UP), + Self::SuggestHertz => ( + "Suggest Hertz Inputs", + "analysis.afm_hertz_suggest", + icon::LIGHTBULB, + ), + Self::ApplyHertzSuggestion => ( + "Use Suggested Inputs", + "analysis.afm_hertz_apply_suggestion", + icon::CHECK, + ), Self::RunHertz => ("Calculate Hertz Fit", "analysis.afm_hertz_run", icon::PLAY), Self::HertzDataSheet => ( "Create Hertz Data Sheet", diff --git a/crates/app/src/ui/commands_afm_tests.rs b/crates/app/src/ui/commands_afm_tests.rs index 30dc433..bf25c89 100644 --- a/crates/app/src/ui/commands_afm_tests.rs +++ b/crates/app/src/ui/commands_afm_tests.rs @@ -135,6 +135,95 @@ fn manual_hertz_calculates_and_only_exports_current_inputs() { assert!(!describe(&app, output).enabled); } +#[test] +fn hertz_suggestion_requires_explicit_acceptance_and_calculation() { + let z = 0i32..=100; + let samples = z.clone().count(); + let raw = z.clone().map(|value| 1000 + (40 - value).max(0).pow(2)); + let mut app = insert_afm(Some(AfmForceSet { + grid_width: 1, + grid_height: 1, + samples_per_curve: samples * 2, + raw: raw.clone().chain(raw).collect(), + signal_scale: AfmScale { + multiplier: 0.001, + offset: 0.0, + unit: "nm".into(), + }, + sample_period_s: None, + z_positions: Some(z.clone().chain(z).map(f64::from).collect()), + display_order: (0..samples * 2).collect(), + approach_samples: samples, + deflection_sensitivity_m_per_v: None, + spring_constant_n_per_m: Some(1.0), + })); + let ctx = crate::typography::test_context(); + let open = CommandId::AfmFit(AfmFitCommand::OpenHertz); + let suggest = CommandId::AfmFit(AfmFitCommand::SuggestHertz); + let apply = CommandId::AfmFit(AfmFitCommand::ApplyHertzSuggestion); + let run = CommandId::AfmFit(AfmFitCommand::RunHertz); + let output = CommandId::AfmFit(AfmFitCommand::HertzDataSheet); + execute_without_clipboard(open, &mut app, &ctx); + assert!(!describe(&app, suggest).enabled); + let draft = app.session.ui.afm_hertz_task.as_mut().unwrap(); + draft.spring_confirmed = true; + draft.radius_nm = "1000".into(); + draft.contact_z_nm = "42".into(); + assert!( + catalog(&app) + .iter() + .any(|entry| entry.id == suggest && entry.enabled) + ); + assert!(!describe(&app, apply).enabled); + execute_without_clipboard(suggest, &mut app, &ctx); + let draft = app.session.ui.afm_hertz_task.as_ref().unwrap(); + assert_eq!(draft.contact_z_nm, "42"); + assert_eq!(draft.baseline_z_nm, ["", ""]); + assert_eq!(draft.fit_z_nm, ["", ""]); + let candidate = app.afm_hertz_suggestion().expect("Hertz suggestion").input; + assert!( + catalog(&app) + .iter() + .any(|entry| entry.id == apply && entry.enabled) + ); + assert!(!describe(&app, run).enabled); + + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(900.0, 800.0), + )), + ..Default::default() + }; + let _ = ctx.run_ui(input.clone(), |ui| { + crate::ui::tools::render_curve_fit_task(&mut app, ui); + }); + let rendered = ctx.run_ui(input, |ui| { + crate::ui::tools::render_curve_fit_task(&mut app, ui); + }); + for label in ["Suggested inputs (not applied)", "Dashed: suggested inputs"] { + assert!( + rendered.shapes.iter().any(|shape| { + matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == label) + }), + "missing proposal preview label: {label}" + ); + } + + execute_without_clipboard(apply, &mut app, &ctx); + let draft = app.session.ui.afm_hertz_task.as_ref().unwrap(); + assert_eq!(draft.contact_z_nm, candidate.contact_z_nm.to_string()); + assert_eq!( + draft.baseline_z_nm, + candidate.baseline_z_nm.map(|v| v.to_string()) + ); + assert_eq!(draft.fit_z_nm, candidate.fit_z_nm.map(|v| v.to_string())); + assert!(app.afm_hertz_suggestion().is_none()); + assert!(describe(&app, run).enabled); + assert!(!describe(&app, output).enabled); + assert!(app.afm_hertz_result().is_none()); +} + #[test] fn afm_fit_command_uses_the_selected_branch_and_range() { let mut app = insert_afm(Some(AfmForceSet { diff --git a/crates/app/src/ui/tools/afm_fit.rs b/crates/app/src/ui/tools/afm_fit.rs index fcd8772..8fdeab3 100644 --- a/crates/app/src/ui/tools/afm_fit.rs +++ b/crates/app/src/ui/tools/afm_fit.rs @@ -56,7 +56,11 @@ pub(super) fn switch_to_table(app: &mut PlotiumApp, di: usize) { pub(in crate::ui) fn afm_fit_gate(app: &PlotiumApp, command: Fit) -> Result<(), &'static str> { match command { - Fit::OpenHertz | Fit::RunHertz | Fit::HertzDataSheet => { + Fit::OpenHertz + | Fit::SuggestHertz + | Fit::ApplyHertzSuggestion + | Fit::RunHertz + | Fit::HertzDataSheet => { return super::afm_hertz::gate(app, command); } Fit::ShowSource => { @@ -89,7 +93,11 @@ pub(in crate::ui) fn afm_fit_gate(app: &PlotiumApp, command: Fit) -> Result<(), pub(in crate::ui) fn run_command(app: &mut PlotiumApp, command: Fit) { match command { - Fit::OpenHertz | Fit::RunHertz | Fit::HertzDataSheet => { + Fit::OpenHertz + | Fit::SuggestHertz + | Fit::ApplyHertzSuggestion + | Fit::RunHertz + | Fit::HertzDataSheet => { super::afm_hertz::run_command(app, command); return; } @@ -127,7 +135,12 @@ pub(in crate::ui) fn run_command(app: &mut PlotiumApp, command: Fit) { Fit::Duplicate => app.duplicate_afm_fit_plot(target), Fit::ResidualPlot => app.create_afm_fit_output(target, true), Fit::DataSheet => app.create_afm_fit_output(target, false), - Fit::OpenHertz | Fit::RunHertz | Fit::HertzDataSheet | Fit::ShowSource => return, + Fit::OpenHertz + | Fit::SuggestHertz + | Fit::ApplyHertzSuggestion + | Fit::RunHertz + | Fit::HertzDataSheet + | Fit::ShowSource => return, }; if let Some(task) = &mut app.session.ui.afm_fit_task { task.error = result.as_ref().err().cloned(); diff --git a/crates/app/src/ui/tools/afm_hertz.rs b/crates/app/src/ui/tools/afm_hertz.rs index 05a85c6..8b37f17 100644 --- a/crates/app/src/ui/tools/afm_hertz.rs +++ b/crates/app/src/ui/tools/afm_hertz.rs @@ -30,6 +30,17 @@ pub(super) fn gate(app: &PlotiumApp, choice: Fit) -> Result<(), &'static str> { .as_ref() .ok_or("Open Manual Hertz first.")?; match choice { + Fit::SuggestHertz => { + app.afm_hertz_calibration(draft.target)?; + if !draft.spring_confirmed { + return Err("Confirm the file spring constant."); + } + draft.radius().map(|_| ()) + } + Fit::ApplyHertzSuggestion => app + .afm_hertz_suggestion() + .map(|_| ()) + .ok_or("Suggest inputs for the current curve first."), Fit::RunHertz => { let k = app.afm_hertz_calibration(draft.target)?; if !draft.spring_confirmed { @@ -69,13 +80,21 @@ pub(super) fn run_command(app: &mut PlotiumApp, choice: Fit) { ui.open_task_tab(TaskDockTab::CurveFit); return; } + let suggestion_action = matches!(choice, Fit::SuggestHertz | Fit::ApplyHertzSuggestion); let result = match choice { + Fit::SuggestHertz => app.suggest_afm_hertz(), + Fit::ApplyHertzSuggestion => app.apply_afm_hertz_suggestion(), Fit::RunHertz => app.run_afm_hertz(), Fit::HertzDataSheet => app.create_afm_hertz_output(), _ => return, }; if let Some(task) = &mut app.session.ui.afm_hertz_task { - task.error = result.as_ref().err().cloned(); + let error = result.as_ref().err().cloned(); + if suggestion_action { + task.suggestion_error = error; + } else { + task.error = error; + } } if let Err(error) = result { app.session.status = error; @@ -113,6 +132,9 @@ pub(super) fn body(app: &mut PlotiumApp, ui: &mut Ui, target: AfmFitTarget) { .inner; egui::Grid::new("hertz_inputs").show(ui, |ui| { changed |= number_field(ui, "Probe radius (nm)", &mut draft.radius_nm); + if changed { + draft.suggestion_error = None; + } ui.end_row(); changed |= number_field(ui, "Contact Z (nm)", &mut draft.contact_z_nm); ui.end_row(); @@ -123,13 +145,45 @@ pub(super) fn body(app: &mut PlotiumApp, ui: &mut Ui, target: AfmFitTarget) { draft.error = None; } } + ui.horizontal_wrapped(|ui| { + command(app, ui, Fit::SuggestHertz, false); + command(app, ui, Fit::ApplyHertzSuggestion, false); + }); + if let Some(message) = app + .session + .ui + .afm_hertz_task + .as_ref() + .and_then(|draft| draft.suggestion_error.as_deref()) + { + ui.colored_label(ui.visuals().warn_fg_color, message); + } + if let Some(candidate) = app.afm_hertz_suggestion() { + let limits = + |[lo, hi]: [f64; 2]| format!("{} to {} nm", preview::value(lo), preview::value(hi)); + ui.strong("Suggested inputs (not applied)"); + ui.small(format!( + "Contact Z: {} nm", + preview::value(candidate.input.contact_z_nm) + )); + ui.small(format!( + "Baseline Z: {}", + limits(candidate.input.baseline_z_nm) + )); + ui.small(format!("Fit Z: {}", limits(candidate.input.fit_z_nm))); + } if calibration.is_ok() { let contact = egui::CollapsingHeader::new("Approach preview") .default_open(true) .show(ui, |ui| { let draft = app.session.ui.afm_hertz_task.as_ref()?; match app.afm_hertz_points(target) { - Ok(points) => preview::approach(ui, &points, draft), + Ok(points) => preview::approach( + ui, + &points, + draft, + app.afm_hertz_suggestion().map(|candidate| candidate.input), + ), Err(error) => { ui.small(error); None diff --git a/crates/app/src/ui/tools/afm_hertz_preview.rs b/crates/app/src/ui/tools/afm_hertz_preview.rs index 5e8234a..f42b658 100644 --- a/crates/app/src/ui/tools/afm_hertz_preview.rs +++ b/crates/app/src/ui/tools/afm_hertz_preview.rs @@ -1,5 +1,5 @@ use egui::{Align2, Color32, FontId, Pos2, Rect, Response, Sense, Stroke, Ui}; -use plotium_analysis::afm_hertz::HertzResult; +use plotium_analysis::afm_hertz::{HertzInput, HertzResult}; use plotium_core::state::AfmHertzDraft; struct Colors { @@ -26,7 +26,12 @@ impl Colors { } } -pub(super) fn approach(ui: &mut Ui, points: &[[f64; 2]], draft: &AfmHertzDraft) -> Option { +pub(super) fn approach( + ui: &mut Ui, + points: &[[f64; 2]], + draft: &AfmHertzDraft, + suggestion: Option, +) -> Option { let colors = Colors::from_ui(ui); let contact = finite_number(&draft.contact_z_nm); let baseline = band(&draft.baseline_z_nm, colors.baseline); @@ -35,6 +40,9 @@ pub(super) fn approach(ui: &mut Ui, points: &[[f64; 2]], draft: &AfmHertzDraft) key(ui, "Baseline", colors.baseline); key(ui, "Fit window", colors.fit); key(ui, "Contact Z", colors.contact); + if suggestion.is_some() { + ui.weak("Dashed: suggested inputs"); + } }); let trace = Trace { color: ui.visuals().text_color(), @@ -47,8 +55,9 @@ pub(super) fn approach(ui: &mut Ui, points: &[[f64; 2]], draft: &AfmHertzDraft) Marks { bands: [baseline, fit], vertical: contact.map(|z| (z, colors.contact)), - zero_line: false, + suggestion, pick: true, + ..Default::default() }, )?; let response = response @@ -134,6 +143,7 @@ struct Trace<'a> { struct Marks { bands: [Option<([f64; 2], Color32)>; 2], vertical: Option<(f64, Color32)>, + suggestion: Option, zero_line: bool, pick: bool, } @@ -257,6 +267,9 @@ fn plot( } } } + if let Some(suggestion) = marks.suggestion { + draw_suggestion(&chart, scale, suggestion, &Colors::from_ui(ui)); + } painter.line_segment([plot.left_top(), plot.left_bottom()], axis); painter.line_segment([plot.left_bottom(), plot.right_bottom()], axis); for (anchor, alignment, tick) in [ @@ -287,6 +300,45 @@ fn plot( Some((response, scale)) } +fn draw_suggestion(chart: &egui::Painter, scale: Scale, input: HertzInput, colors: &Colors) { + let dashed = |points: &[Pos2], color| { + chart.extend(egui::Shape::dashed_line( + points, + Stroke::new(1.75_f32, color), + 4.0, + 3.0, + )); + }; + let plot = scale.rect; + for ([lo, hi], color) in [ + (input.baseline_z_nm, colors.baseline), + (input.fit_z_nm, colors.fit), + ] { + let left = scale.screen_x(lo.clamp(scale.x[0], scale.x[1])); + let right = scale.screen_x(hi.clamp(scale.x[0], scale.x[1])); + if left < right { + // Inset the outline so the dash pattern is visible at plot limits. + let top = plot.top() + 2.0; + let bottom = plot.bottom() - 2.0; + dashed( + &[ + egui::pos2(left, top), + egui::pos2(right, top), + egui::pos2(right, bottom), + egui::pos2(left, bottom), + egui::pos2(left, top), + ], + color, + ); + } + } + let x = scale.screen_x(input.contact_z_nm); + dashed( + &[egui::pos2(x, plot.top()), egui::pos2(x, plot.bottom())], + colors.contact, + ); +} + fn band(limits: &[String; 2], color: Color32) -> Option<([f64; 2], Color32)> { let min = finite_number(&limits[0])?; let max = finite_number(&limits[1])?; diff --git a/crates/core/src/state/afm.rs b/crates/core/src/state/afm.rs index edc60e6..02347df 100644 --- a/crates/core/src/state/afm.rs +++ b/crates/core/src/state/afm.rs @@ -132,6 +132,17 @@ pub struct AfmDataset { } impl AfmDataset { + pub(super) fn force_increment_nn(&self) -> Option { + let forces = self.data.forces.as_ref()?; + let context = self.force_curve_context()?; + // The scale offset cancels when taking the difference for one count. + positive_finite(Some(force_nn( + forces.signal_scale.multiplier.abs(), + context.deflection_to_metres?, + context.spring_constant_n_per_m?, + ))) + } + pub fn load(data: AfmData) -> Self { let acquisition_identity = plotium_io::AcquisitionIdentity::from_path(std::path::Path::new(&data.source)); @@ -261,7 +272,7 @@ impl AfmDataset { context.deflection_to_metres, context.spring_constant_n_per_m, ) { - (Some(to_metres), Some(spring)) => stored * to_metres * spring * 1.0e9, + (Some(to_metres), Some(spring)) => force_nn(stored, to_metres, spring), (Some(to_metres), None) => stored * to_metres * 1.0e9, (None, _) => stored, } @@ -341,6 +352,10 @@ impl PlotiumApp { } } +fn force_nn(stored: f64, to_metres: f64, spring: f64) -> f64 { + stored * to_metres * spring * 1.0e9 +} + fn positive_finite(value: Option) -> Option { value.filter(|value| value.is_finite() && *value > 0.0) } diff --git a/crates/core/src/state/afm_hertz.rs b/crates/core/src/state/afm_hertz.rs index 2536afa..c665021 100644 --- a/crates/core/src/state/afm_hertz.rs +++ b/crates/core/src/state/afm_hertz.rs @@ -3,6 +3,9 @@ use crate::actions::Action; use plotium_analysis::afm_hertz::{HertzInput, HertzResult, fit_hertz}; use std::sync::Arc; +#[path = "afm_hertz_suggestion.rs"] +mod suggestion; + #[derive(Clone)] pub struct AfmHertzDraft { pub target: AfmFitTarget, @@ -12,7 +15,9 @@ pub struct AfmHertzDraft { pub baseline_z_nm: [String; 2], pub fit_z_nm: [String; 2], pub error: Option, + pub suggestion_error: Option, result: Option>, + suggestion: Option, } struct AfmHertzRun { @@ -33,10 +38,21 @@ impl AfmHertzDraft { baseline_z_nm: Default::default(), fit_z_nm: Default::default(), error: None, + suggestion_error: None, result: None, + suggestion: None, } } + pub fn radius(&self) -> Result { + self.radius_nm + .trim() + .parse::() + .ok() + .filter(|radius| radius.is_finite() && *radius > 0.0) + .ok_or("Enter a finite, positive spherical tip radius in nm.") + } + pub fn input(&self, spring_constant_n_per_m: f64) -> Result { if !self.spring_confirmed { return Err("Confirm the file's spring constant before calculating.".into()); @@ -54,7 +70,7 @@ impl AfmHertzDraft { }; Ok(HertzInput { spring_constant_n_per_m, - radius_nm: number(&self.radius_nm, "tip radius")?, + radius_nm: self.radius()?, contact_z_nm: number(&self.contact_z_nm, "contact Z")?, baseline_z_nm: range(&self.baseline_z_nm, "baseline bound")?, fit_z_nm: range(&self.fit_z_nm, "fit bound")?, diff --git a/crates/core/src/state/afm_hertz_suggestion.rs b/crates/core/src/state/afm_hertz_suggestion.rs new file mode 100644 index 0000000..2b58f7b --- /dev/null +++ b/crates/core/src/state/afm_hertz_suggestion.rs @@ -0,0 +1,80 @@ +use super::{AfmFitTarget, Arc, PlotiumApp}; +use plotium_analysis::afm_hertz_suggestion::{HertzSuggestion, suggest_hertz}; + +#[derive(Clone)] +pub(super) struct AfmHertzProposal { + target: AfmFitTarget, + pixel: [usize; 2], + data: Arc, + candidate: HertzSuggestion, +} + +impl PlotiumApp { + pub fn suggest_afm_hertz(&mut self) -> Result<(), String> { + let draft = self + .session + .ui + .afm_hertz_task + .as_mut() + .ok_or("Open Manual Hertz first.")?; + draft.suggestion = None; + if !draft.spring_confirmed { + return Err("Confirm the file spring constant first.".into()); + } + let radius = draft.radius()?; + let target = draft.target; + let (afm, spring) = self.afm_hertz_source(target)?; + let force_increment = afm + .force_increment_nn() + .ok_or("Use an AFM curve with a valid force scale for suggestions.")?; + let points = self.afm_hertz_points(target)?; + let candidate = suggest_hertz(&points, spring, radius, force_increment) + .map_err(|error| error.to_string())?; + let proposal = AfmHertzProposal { + target, + pixel: afm.selected_pixel, + data: afm.data.clone(), + candidate, + }; + self.session + .ui + .afm_hertz_task + .as_mut() + .ok_or("Open Manual Hertz first.")? + .suggestion = Some(proposal); + Ok(()) + } + + pub fn afm_hertz_suggestion(&self) -> Option<&HertzSuggestion> { + let draft = self.session.ui.afm_hertz_task.as_ref()?; + let proposal = draft.suggestion.as_ref()?; + let (afm, spring) = self.afm_hertz_source(draft.target).ok()?; + (draft.spring_confirmed + && proposal.target == draft.target + && proposal.pixel == afm.selected_pixel + && Arc::ptr_eq(&proposal.data, &afm.data) + && proposal.candidate.input.spring_constant_n_per_m == spring + && proposal.candidate.input.radius_nm == draft.radius().ok()?) + .then_some(&proposal.candidate) + } + + pub fn apply_afm_hertz_suggestion(&mut self) -> Result<(), String> { + let input = self + .afm_hertz_suggestion() + .ok_or("Generate a suggestion for the current curve and probe radius first.")? + .input; + let draft = self + .session + .ui + .afm_hertz_task + .as_mut() + .ok_or("Open Manual Hertz first.")?; + draft.contact_z_nm = input.contact_z_nm.to_string(); + draft.baseline_z_nm = input.baseline_z_nm.map(|bound| bound.to_string()); + draft.fit_z_nm = input.fit_z_nm.map(|bound| bound.to_string()); + draft.suggestion = None; + draft.result = None; + draft.error = None; + Ok(()) + } +} diff --git a/crates/core/tests/afm_hertz.rs b/crates/core/tests/afm_hertz.rs index 7a3f09f..e9c86d7 100644 --- a/crates/core/tests/afm_hertz.rs +++ b/crates/core/tests/afm_hertz.rs @@ -154,3 +154,64 @@ fn manual_hertz_invalidates_result_and_saves_disclosed_fit_data() { app.undo(); assert_eq!(app.doc.datasets.len(), 1); } + +#[test] +fn hertz_suggestion_is_bound_to_current_curve_and_applied_only_on_request() { + let mut app = approach(Some(1.0), true); + let Dataset::Afm(afm) = &mut app.doc.datasets[0] else { + panic!("expected AFM"); + }; + let force = Arc::make_mut(&mut afm.data).forces.as_mut().unwrap(); + let raw: Vec<_> = (0_i32..=100) + .map(|z| 1000 + 2 * (40 - z).max(0).pow(2) + i32::from(z == 60)) + .collect(); + force.samples_per_curve = raw.len(); + force.approach_samples = raw.len(); + force.display_order = (0..raw.len()).collect(); + force.z_positions = Some((0..=100).map(f64::from).collect()); + force.raw = Arc::from([raw.as_slice(), raw.as_slice()].concat()); + force.signal_scale.multiplier = 0.001; + + let draft = app.session.ui.afm_hertz_task.as_mut().unwrap(); + draft.radius_nm = "1000".into(); + assert!(app.suggest_afm_hertz().is_err()); + app.session + .ui + .afm_hertz_task + .as_mut() + .unwrap() + .spring_confirmed = true; + app.suggest_afm_hertz().unwrap(); + let suggestion = app.afm_hertz_suggestion().unwrap().input; + assert_eq!(suggestion.contact_z_nm, 40.0); + assert_eq!( + app.session.ui.afm_hertz_task.as_ref().unwrap().contact_z_nm, + "100" + ); + assert!(app.afm_hertz_result().is_none()); + + app.session.ui.afm_hertz_task.as_mut().unwrap().radius_nm = "900".into(); + assert!(app.apply_afm_hertz_suggestion().is_err()); + app.session.ui.afm_hertz_task.as_mut().unwrap().radius_nm = "1000".into(); + let Dataset::Afm(afm) = &mut app.doc.datasets[0] else { + panic!("expected AFM"); + }; + afm.selected_pixel = [0, 0]; + assert!(app.apply_afm_hertz_suggestion().is_err()); + app.suggest_afm_hertz().unwrap(); + app.apply_afm_hertz_suggestion().unwrap(); + assert!(app.afm_hertz_suggestion().is_none()); + assert!(app.afm_hertz_result().is_none()); + assert_eq!( + app.session + .ui + .afm_hertz_task + .as_ref() + .unwrap() + .input(1.0) + .unwrap(), + suggestion + ); + app.run_afm_hertz().unwrap(); + assert!(app.afm_hertz_result().is_some()); +} diff --git a/docs/src/content/docs/guides/supported-formats.md b/docs/src/content/docs/guides/supported-formats.md index 82fea26..fbf9388 100644 --- a/docs/src/content/docs/guides/supported-formats.md +++ b/docs/src/content/docs/guides/supported-formats.md @@ -308,6 +308,16 @@ tip radius in **Probe radius (nm)**. Manual Hertz is unavailable for PeakForce Capture (`.pfc`); its loading branch has not been verified for this fit. +After confirming the spring constant and entering the radius, you can select +**Suggest Hertz Inputs** to review a candidate contact point, baseline, and +fit window. The **Approach preview** shows these candidates with dashed +markers, separate from the current inputs. Select **Use Suggested Inputs** +to fill the fields; you can still edit them before selecting +**Calculate Hertz Fit**. A suggestion neither calculates a modulus nor +establishes that Hertz is appropriate. If there is no clear force onset, +the trace is noisy or irregular, or too few suitable shallow-indentation +points are available, continue with manual selection. + 1. Set **Contact Z (nm)** where contact begins, either by typing the value or clicking the nearest sample in the **Approach preview**. 2. Set **Baseline Z (nm)** wholly before contact (larger relative Z), and diff --git a/docs/src/content/docs/zh-cn/guides/supported-formats.md b/docs/src/content/docs/zh-cn/guides/supported-formats.md index 9a9b7af..ee790ba 100644 --- a/docs/src/content/docs/zh-cn/guides/supported-formats.md +++ b/docs/src/content/docs/zh-cn/guides/supported-formats.md @@ -238,6 +238,13 @@ PeakForce Capture 曲线是逐像素采集的原始信号。模量等派生 QNM 手动 Hertz 不适用于 PeakForce Capture(`.pfc`),因为其加载分支尚未针对该拟合验证。 +确认弹簧常数并输入半径后,可选择 **Suggest Hertz Inputs** 查看候选接触点、 +基线和拟合区间。**Approach preview** 用虚线标出候选值,与当前输入区分。 +选择 **Use Suggested Inputs** 才会填入这些值,之后仍可修改,再选择 +**Calculate Hertz Fit**。建议不会计算模量,也不能证明 Hertz 模型适用。 +如果力的起始上升不明显、曲线噪声大或不规则,或符合条件的浅压入点不足, +可继续手动选择。 + 1. 在 **Contact Z (nm)** 中输入接触起始位置,或在 **Approach preview** 中 点选最接近接触位置的采样点。 2. 将 **Baseline Z (nm)** 完全设在接触前(相对 Z 较大),将 **Fit Z (nm)**