From 641ed773cadb9274622dc6fa53a868f97440d492 Mon Sep 17 00:00:00 2001 From: Jiekang Tian Date: Sun, 22 Nov 2026 22:03:14 +0800 Subject: [PATCH] feat(afm): add manual spherical Hertz fitting --- crates/analysis/src/afm_hertz.rs | 337 ++++++++++++++++++ crates/analysis/src/afm_hertz_tests.rs | 166 +++++++++ crates/analysis/src/lib.rs | 1 + crates/app/src/ui/commands/ribbon.rs | 4 +- crates/app/src/ui/commands/roster.rs | 3 + crates/app/src/ui/commands/types.rs | 10 + crates/app/src/ui/commands_afm_tests.rs | 101 ++++++ crates/app/src/ui/tools/afm_fit.rs | 89 +++-- crates/app/src/ui/tools/afm_hertz.rs | 258 ++++++++++++++ crates/app/src/ui/tools/afm_hertz_preview.rs | 313 ++++++++++++++++ crates/app/src/ui/tools/curve_fit.rs | 4 +- crates/app/src/ui/tools/mod.rs | 3 +- crates/app/src/ui/tools/task_card.rs | 8 +- crates/app/src/ui/tools/task_card_tabs.rs | 2 +- crates/core/src/project/lineage_convert.rs | 2 + crates/core/src/state/afm_hertz.rs | 268 ++++++++++++++ crates/core/src/state/lineage.rs | 2 + crates/core/src/state/mod.rs | 2 + crates/core/src/state/ui_state.rs | 2 + crates/core/src/state/ui_state/task_dock.rs | 6 +- crates/core/tests/afm_hertz.rs | 156 ++++++++ .../content/docs/guides/supported-formats.md | 48 ++- .../docs/zh-cn/guides/supported-formats.md | 33 +- 23 files changed, 1769 insertions(+), 49 deletions(-) create mode 100644 crates/analysis/src/afm_hertz.rs create mode 100644 crates/analysis/src/afm_hertz_tests.rs create mode 100644 crates/app/src/ui/tools/afm_hertz.rs create mode 100644 crates/app/src/ui/tools/afm_hertz_preview.rs create mode 100644 crates/core/src/state/afm_hertz.rs create mode 100644 crates/core/tests/afm_hertz.rs diff --git a/crates/analysis/src/afm_hertz.rs b/crates/analysis/src/afm_hertz.rs new file mode 100644 index 00000000..fdc7fdc5 --- /dev/null +++ b/crates/analysis/src/afm_hertz.rs @@ -0,0 +1,337 @@ +//! Manual, nonadhesive spherical Hertz fit for a calibrated AFM approach curve. + +use thiserror::Error; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HertzInput { + pub spring_constant_n_per_m: f64, + pub radius_nm: f64, + /// Inclusive endpoints in increasing relative Z, on the noncontact side. + pub baseline_z_nm: [f64; 2], + pub contact_z_nm: f64, + /// Inclusive endpoints in increasing relative Z, on the compression side. + pub fit_z_nm: [f64; 2], +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HertzResult { + pub reduced_modulus_mpa: f64, + /// Only the selected fit window, in input order. + pub rows: Vec, + pub baseline_rms_nn: f64, + pub baseline_points: usize, + pub baseline_slope_nn_per_nm: f64, + pub baseline_force_at_contact_nn: f64, + pub residual_rms_nn: f64, + pub max_indentation_over_radius: f64, + pub r_squared: Option, + pub contact_sensitivity: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HertzRow { + pub z_nm: f64, + pub indentation_nm: f64, + pub corrected_force_nn: f64, + pub predicted_force_nn: f64, +} + +impl HertzRow { + pub fn residual_nn(&self) -> f64 { + self.corrected_force_nn - self.predicted_force_nn + } +} + +/// A contact-location perturbation, not a confidence interval. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HertzContactSensitivity { + pub shift_nm: f64, + pub lower_contact_modulus_mpa: Option, + pub higher_contact_modulus_mpa: Option, +} + +#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)] +pub enum HertzError { + #[error("A finite, positive spring constant is required.")] + SpringConstant, + #[error("Enter a finite, positive spherical tip radius.")] + Radius, + #[error("Enter a finite contact Z and distinct, ascending interval bounds.")] + Intervals, + #[error("The baseline must be above contact in relative Z and the fit range must be below it.")] + IntervalOrder, + #[error("The approach curve must contain finite relative Z and force samples.")] + Samples, + #[error("Both intervals must stay within the recorded approach curve.")] + OutsideCurve, + #[error("The baseline interval needs at least three samples and distinct Z values.")] + BaselineSamples, + #[error("The fit interval needs at least three samples and distinct Z values.")] + FitSamples, + #[error( + "The fit interval contains nonpositive baseline-corrected force. Check the baseline and fit range." + )] + NonCompressiveForce, + #[error( + "The fit interval contains nonpositive indentation. Check the contact Z and fit range." + )] + NonpositiveIndentation, + #[error("The fit interval needs distinct indentation values.")] + IndentationSpan, + #[error("The Hertz calculation did not produce finite, positive fit parameters.")] + Numerical, +} + +/// Fit force as a function of indentation, with zero force at zero indentation. +/// +/// Input points are `[relative Z in nm, signed force in nN]`. Relative Z must +/// decrease toward the sample, and compression force must be positive after +/// subtracting a linear force baseline estimated from the noncontact window. +pub fn fit_hertz(points: &[[f64; 2]], input: HertzInput) -> Result { + validate(points, input)?; + let baseline = LinearBaseline::fit(points, input.baseline_z_nm)?; + let baseline_force_at_contact_nn = baseline.at(input.contact_z_nm); + if !baseline_force_at_contact_nn.is_finite() { + return Err(HertzError::Numerical); + } + let selected: Vec<_> = points + .iter() + .filter(|[z, _]| contains(input.fit_z_nm, *z)) + .map(|&[z, force]| [z, force - baseline.at(z)]) + .collect(); + if selected.len() < 3 || selected.iter().all(|p| p[0] == selected[0][0]) { + return Err(HertzError::FitSamples); + } + + let (rows, reduced_modulus_mpa) = fit_at_contact(&selected, input, input.contact_z_nm)?; + let n = rows.len() as f64; + let mean_force = rows.iter().map(|row| row.corrected_force_nn).sum::() / n; + let centered_sum = rows + .iter() + .map(|row| (row.corrected_force_nn - mean_force).powi(2)) + .sum::(); + let residual_sum = rows + .iter() + .map(|row| row.residual_nn().powi(2)) + .sum::(); + let residual_rms_nn = (residual_sum / n).sqrt(); + let max_indentation_over_radius = rows + .iter() + .map(|row| row.indentation_nm) + .fold(0.0, f64::max) + / input.radius_nm; + if !residual_rms_nn.is_finite() || !max_indentation_over_radius.is_finite() { + return Err(HertzError::Numerical); + } + let r_squared = (centered_sum.is_finite() && centered_sum > 0.0) + .then(|| 1.0 - residual_sum / centered_sum) + .filter(|value| value.is_finite()); + let contact_sensitivity = contact_spacing(points, input.contact_z_nm).map(|shift_nm| { + let modulus_at = |contact: f64| { + if contact <= input.fit_z_nm[1] || contact >= input.baseline_z_nm[0] { + return None; + } + fit_at_contact(&selected, input, contact) + .ok() + .map(|(_, modulus)| modulus) + }; + HertzContactSensitivity { + shift_nm, + lower_contact_modulus_mpa: modulus_at(input.contact_z_nm - shift_nm), + higher_contact_modulus_mpa: modulus_at(input.contact_z_nm + shift_nm), + } + }); + Ok(HertzResult { + reduced_modulus_mpa, + rows, + baseline_rms_nn: baseline.rms_nn, + baseline_points: baseline.samples, + baseline_slope_nn_per_nm: baseline.slope_nn_per_nm, + baseline_force_at_contact_nn, + residual_rms_nn, + max_indentation_over_radius, + r_squared, + contact_sensitivity, + }) +} + +fn validate(points: &[[f64; 2]], input: HertzInput) -> Result<(), HertzError> { + if !positive_finite(input.spring_constant_n_per_m) { + return Err(HertzError::SpringConstant); + } + if !positive_finite(input.radius_nm) { + return Err(HertzError::Radius); + } + let [lo_baseline, hi_baseline] = input.baseline_z_nm; + let [lo_fit, hi_fit] = input.fit_z_nm; + let contact = input.contact_z_nm; + if [lo_baseline, hi_baseline, lo_fit, hi_fit, contact] + .into_iter() + .any(|value| !value.is_finite()) + || lo_baseline >= hi_baseline + || lo_fit >= hi_fit + { + return Err(HertzError::Intervals); + } + if hi_fit >= contact || lo_baseline <= contact { + return Err(HertzError::IntervalOrder); + } + if points.is_empty() || points.iter().flatten().any(|value| !value.is_finite()) { + return Err(HertzError::Samples); + } + let (lo, hi) = points + .iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &[z, _]| { + (lo.min(z), hi.max(z)) + }); + if lo_fit < lo || hi_baseline > hi { + return Err(HertzError::OutsideCurve); + } + Ok(()) +} + +struct LinearBaseline { + center_z_nm: f64, + center_force_nn: f64, + slope_nn_per_nm: f64, + rms_nn: f64, + samples: usize, +} + +impl LinearBaseline { + 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 { + let selected = points.iter().filter(|[z, _]| contains(interval, *z)); + let (z_sum, force_sum, samples) = selected + .clone() + .fold((0.0, 0.0, 0), |(zs, fs, n), &[z, f]| { + (zs + z, fs + f, n + 1) + }); + if samples < 3 { + return Err(HertzError::BaselineSamples); + } + // Test the sampled coordinates directly: rounding their mean can make + // identical Z values appear to have nonzero variance. + let mut z_values = selected.clone().map(|&[z, _]| z); + if z_values + .next() + .is_none_or(|first| z_values.all(|z| z == first)) + { + return Err(HertzError::BaselineSamples); + } + let (center_z_nm, center_force_nn) = (z_sum / samples as f64, force_sum / samples as f64); + let (zz, zf) = selected.clone().fold((0.0, 0.0), |(zz, zf), &[z, f]| { + let dz = z - center_z_nm; + (zz + dz * dz, zf + dz * (f - center_force_nn)) + }); + if zz == 0.0 { + return Err(HertzError::BaselineSamples); + } + if !zz.is_finite() || !zf.is_finite() { + return Err(HertzError::Numerical); + } + let mut baseline = Self { + center_z_nm, + center_force_nn, + slope_nn_per_nm: zf / zz, + rms_nn: 0.0, + samples, + }; + baseline.rms_nn = (selected + .map(|&[z, f]| (f - baseline.at(z)).powi(2)) + .sum::() + / samples as f64) + .sqrt(); + if !baseline.rms_nn.is_finite() { + return Err(HertzError::Numerical); + } + Ok(baseline) + } +} + +fn fit_at_contact( + points: &[[f64; 2]], + input: HertzInput, + contact_z_nm: f64, +) -> Result<(Vec, f64), HertzError> { + let mut rows = Vec::with_capacity(points.len()); + let (mut xy, mut xx) = (0.0, 0.0); + for &[z_nm, corrected_force_nn] in points { + // 1 nN / (1 N/m) = 1 nm of cantilever deflection. + let indentation_nm = + (contact_z_nm - z_nm) - corrected_force_nn / input.spring_constant_n_per_m; + if !corrected_force_nn.is_finite() || !indentation_nm.is_finite() { + return Err(HertzError::Numerical); + } + if corrected_force_nn <= 0.0 { + return Err(HertzError::NonCompressiveForce); + } + if indentation_nm <= 0.0 { + return Err(HertzError::NonpositiveIndentation); + } + let feature = indentation_nm * indentation_nm.sqrt(); + xy += feature * corrected_force_nn; + xx += feature * feature; + rows.push(HertzRow { + z_nm, + indentation_nm, + corrected_force_nn, + predicted_force_nn: feature, + }); + } + if !rows.split_first().is_some_and(|(first, remaining)| { + remaining + .iter() + .any(|row| row.indentation_nm != first.indentation_nm) + }) { + return Err(HertzError::IndentationSpan); + } + let coefficient = xy / xx; + // F = (4/3) E* sqrt(R) delta^(3/2); 1 nN/nm² = 1000 MPa. + let modulus_mpa = 750.0 * coefficient / input.radius_nm.sqrt(); + if !positive_finite(modulus_mpa) { + return Err(HertzError::Numerical); + } + for row in &mut rows { + row.predicted_force_nn *= coefficient; + if !row.residual_nn().is_finite() { + return Err(HertzError::Numerical); + } + } + Ok((rows, modulus_mpa)) +} + +fn contact_spacing(points: &[[f64; 2]], contact: f64) -> Option { + let (mut below, mut above) = (f64::INFINITY, f64::INFINITY); + let mut exact = false; + for &[z, _] in points { + if z < contact { + below = below.min(contact - z); + } else if z > contact { + above = above.min(z - contact); + } else { + exact = true; + } + } + let spacing = if exact { + below.min(above) + } else { + below + above + }; + positive_finite(spacing).then_some(spacing) +} + +fn contains([low, high]: [f64; 2], value: f64) -> bool { + (low..=high).contains(&value) +} + +fn positive_finite(value: f64) -> bool { + value.is_finite() && value > 0.0 +} + +#[cfg(test)] +#[path = "afm_hertz_tests.rs"] +mod tests; diff --git a/crates/analysis/src/afm_hertz_tests.rs b/crates/analysis/src/afm_hertz_tests.rs new file mode 100644 index 00000000..a1385fb4 --- /dev/null +++ b/crates/analysis/src/afm_hertz_tests.rs @@ -0,0 +1,166 @@ +use super::*; + +const INPUT: HertzInput = HertzInput { + spring_constant_n_per_m: 2.0, + radius_nm: 400.0, + baseline_z_nm: [106.0, 125.0], + contact_z_nm: 100.0, + fit_z_nm: [12.5, 95.0], +}; + +fn baseline(z: f64) -> f64 { + 0.03125 * z - 2.0 +} + +fn reference_curve() -> Vec<[f64; 2]> { + let mut points = [125.0, 119.0, 112.0, 106.0, 101.0, 100.0, 99.0] + .into_iter() + .map(|z| [z, baseline(z)]) + .collect::>(); + // Independent closed-form reference: E*=37.5 MPa and R=400 nm give + // 1 nN / nm^(3/2), so F is [8, 27, 64, 125] nN at these depths. + points.extend( + [92.0, 77.5, 52.0, 12.5] + .into_iter() + .zip([8.0, 27.0, 64.0, 125.0]) + .map(|(z, force)| [z, baseline(z) + force]), + ); + points +} + +#[test] +fn recovers_reduced_modulus_and_indentation_from_raw_z_and_force() { + let result = fit_hertz(&reference_curve(), INPUT).unwrap(); + assert!((result.reduced_modulus_mpa - 37.5).abs() < 1.0e-10); + assert_eq!(result.baseline_points, 4); + assert!(result.baseline_rms_nn < 1.0e-12); + assert_eq!(result.baseline_slope_nn_per_nm, 0.03125); + assert_eq!(result.baseline_force_at_contact_nn, 1.125); + assert!(result.residual_rms_nn < 1.0e-10); + assert_eq!(result.r_squared, Some(1.0)); + assert!((result.max_indentation_over_radius - 0.0625).abs() < 1.0e-12); + for (row, depth) in result.rows.iter().zip([4.0, 9.0, 16.0, 25.0]) { + assert!((row.indentation_nm - depth).abs() < 1.0e-12); + assert!(row.residual_nn().abs() < 1.0e-10); + } + assert_eq!(result.rows.len(), 4); + + let mut reversed = reference_curve(); + reversed.reverse(); + let reversed = fit_hertz(&reversed, INPUT).unwrap(); + assert_eq!(reversed.rows.first(), result.rows.last()); + assert_eq!(reversed.rows.last(), result.rows.first()); +} + +#[test] +fn contact_perturbation_keeps_the_windows_fixed_and_can_be_unavailable() { + let points = reference_curve(); + let result = fit_hertz(&points, INPUT).unwrap(); + let sensitivity = result.contact_sensitivity.unwrap(); + assert_eq!(sensitivity.shift_nm, 1.0); + assert!(sensitivity.lower_contact_modulus_mpa.unwrap() > result.reduced_modulus_mpa); + assert!(sensitivity.higher_contact_modulus_mpa.unwrap() < result.reduced_modulus_mpa); + + let narrow = HertzInput { + baseline_z_nm: [100.5, 125.0], + ..INPUT + }; + let result = fit_hertz(&points, narrow).unwrap(); + let sensitivity = result.contact_sensitivity.unwrap(); + assert!(sensitivity.lower_contact_modulus_mpa.is_some()); + assert!(sensitivity.higher_contact_modulus_mpa.is_none()); +} + +#[test] +fn rejects_invalid_windows_and_calibration() { + let points = reference_curve(); + for (input, expected) in [ + ( + HertzInput { + radius_nm: 0.0, + ..INPUT + }, + HertzError::Radius, + ), + ( + HertzInput { + spring_constant_n_per_m: f64::NAN, + ..INPUT + }, + HertzError::SpringConstant, + ), + ( + HertzInput { + contact_z_nm: 106.0, + ..INPUT + }, + HertzError::IntervalOrder, + ), + ( + HertzInput { + fit_z_nm: [0.0, 95.0], + ..INPUT + }, + HertzError::OutsideCurve, + ), + ( + HertzInput { + fit_z_nm: [77.0, 95.0], + ..INPUT + }, + HertzError::FitSamples, + ), + ( + HertzInput { + baseline_z_nm: [118.0, 125.0], + ..INPUT + }, + HertzError::BaselineSamples, + ), + ( + HertzInput { + fit_z_nm: [95.0, 12.5], + ..INPUT + }, + HertzError::Intervals, + ), + ] { + assert_eq!(fit_hertz(&points, input), Err(expected)); + } +} + +#[test] +fn rejects_a_baseline_with_identical_nonexact_z_values() { + let points = [ + [0.1, 0.0], + [0.1, 0.0], + [0.1, 0.0], + [-1.0, 0.2], + [-2.0, 0.5], + [-3.0, 1.0], + ]; + let input = HertzInput { + baseline_z_nm: [0.05, 0.1], + contact_z_nm: 0.0, + fit_z_nm: [-3.0, -1.0], + ..INPUT + }; + assert_eq!(fit_hertz(&points, input), Err(HertzError::BaselineSamples)); +} + +#[test] +fn rejects_one_noncompressive_or_nonpositive_sample_without_dropping_rows() { + let mut points = reference_curve(); + points.push([70.0, baseline(70.0) - 1.0]); + assert_eq!( + fit_hertz(&points, INPUT), + Err(HertzError::NonCompressiveForce) + ); + *points.last_mut().unwrap() = [70.0, baseline(70.0) + 60.0]; + assert_eq!( + fit_hertz(&points, INPUT), + Err(HertzError::NonpositiveIndentation) + ); + *points.last_mut().unwrap() = [70.0, f64::NAN]; + assert_eq!(fit_hertz(&points, INPUT), Err(HertzError::Samples)); +} diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 7b93956e..3f828fda 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -1,6 +1,7 @@ //! Analysis layer for plotium: detection, quantitative extraction, fitting, and //! scientific parameter estimation over processed data. +pub mod afm_hertz; pub mod alignment; pub mod craft; pub mod diffusion; diff --git a/crates/app/src/ui/commands/ribbon.rs b/crates/app/src/ui/commands/ribbon.rs index 323588e6..a87cef4d 100644 --- a/crates/app/src/ui/commands/ribbon.rs +++ b/crates/app/src/ui/commands/ribbon.rs @@ -100,7 +100,9 @@ pub(super) fn ribbon_placement(id: CommandId) -> Option { Applicability::ToolGroup(ToolGroup::LineFit), ), CommandId::CurveFit | CommandId::RunCurveFit => (Analyze, "Curve Fit", 0, TableOnly), - CommandId::FitAfmForce(_) => (Analyze, "AFM Force Fit", 0, Applicability::AfmOnly), + CommandId::FitAfmForce(_) | CommandId::AfmFit(super::AfmFitCommand::OpenHertz) => { + (Analyze, "AFM Force Fit", 0, Applicability::AfmOnly) + } CommandId::Statistics => (Analyze, "Statistics", 0, TableOnly), CommandId::Integrate | CommandId::Multiplets => ( Analyze, diff --git a/crates/app/src/ui/commands/roster.rs b/crates/app/src/ui/commands/roster.rs index b57b8575..8ad6627f 100644 --- a/crates/app/src/ui/commands/roster.rs +++ b/crates/app/src/ui/commands/roster.rs @@ -129,6 +129,9 @@ pub(super) fn command_ids(recent_files: usize) -> Vec { CommandId::CurveFit, CommandId::FitAfmForce(AfmForceBranch::Approach), CommandId::FitAfmForce(AfmForceBranch::Retract), + CommandId::AfmFit(AfmFitCommand::OpenHertz), + CommandId::AfmFit(AfmFitCommand::RunHertz), + CommandId::AfmFit(AfmFitCommand::HertzDataSheet), CommandId::AfmFit(AfmFitCommand::Run), CommandId::AfmFit(AfmFitCommand::ToggleOverlay), CommandId::AfmFit(AfmFitCommand::ZoomRange), diff --git a/crates/app/src/ui/commands/types.rs b/crates/app/src/ui/commands/types.rs index 739ef80e..961a0949 100644 --- a/crates/app/src/ui/commands/types.rs +++ b/crates/app/src/ui/commands/types.rs @@ -9,6 +9,9 @@ pub enum AfmFitCommand { ResidualPlot, DataSheet, ShowSource, + OpenHertz, + RunHertz, + HertzDataSheet, } impl AfmFitCommand { @@ -46,6 +49,13 @@ impl AfmFitCommand { "analysis.afm_fit_source", icon::ARROW_LEFT, ), + Self::OpenHertz => ("Manual Hertz", "analysis.afm_hertz", icon::CHART_LINE_UP), + Self::RunHertz => ("Calculate Hertz Fit", "analysis.afm_hertz_run", icon::PLAY), + Self::HertzDataSheet => ( + "Create Hertz Data Sheet", + "analysis.afm_hertz_sheet", + icon::TABLE, + ), } } } diff --git a/crates/app/src/ui/commands_afm_tests.rs b/crates/app/src/ui/commands_afm_tests.rs index 2726bdf7..30dc433f 100644 --- a/crates/app/src/ui/commands_afm_tests.rs +++ b/crates/app/src/ui/commands_afm_tests.rs @@ -32,6 +32,107 @@ fn afm_fit_group_is_visible_but_disabled_without_force_data() { assert!(command.disabled_reason.unwrap().contains("force curves")); assert_eq!(command.ribbon.unwrap().group, "AFM Force Fit"); } + let hertz = describe(&app, CommandId::AfmFit(AfmFitCommand::OpenHertz)); + assert!(!hertz.enabled); + assert_eq!(hertz.ribbon.unwrap().group, "AFM Force Fit"); +} + +#[test] +fn manual_hertz_calculates_and_only_exports_current_inputs() { + // At E* = 50 MPa and R = 225 nm, F(nN) = indentation(nm)^1.5. + let z = [64, 88, 98, 100, 104, 110, 116, 120]; + let corrected_force = [27, 8, 1, 0, 0, 0, 0, 0]; + let raw = z + .into_iter() + .zip(corrected_force) + .map(|(z, force)| 100 * force + 2 * z + 100) + .collect::>(); + let samples = z.len(); + let mut app = insert_afm(Some(AfmForceSet { + grid_width: 1, + grid_height: 1, + samples_per_curve: samples * 2, + raw: Arc::from(raw.repeat(2)), + signal_scale: AfmScale { + multiplier: 0.01, + offset: 0.0, + unit: "nm".into(), + }, + sample_period_s: None, + z_positions: Some(Arc::from(z.map(f64::from).repeat(2))), + display_order: Arc::from((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 run = CommandId::AfmFit(AfmFitCommand::RunHertz); + let output = CommandId::AfmFit(AfmFitCommand::HertzDataSheet); + assert!( + catalog(&app) + .iter() + .any(|entry| entry.id == open && entry.enabled) + ); + execute_without_clipboard(open, &mut app, &ctx); + assert_eq!(app.session.ui.task_dock_active, Some(TaskDockTab::CurveFit)); + assert!(!describe(&app, run).enabled); + assert!(!describe(&app, output).enabled); + let draft = app.session.ui.afm_hertz_task.as_mut().unwrap(); + assert_eq!(draft.target.branch, AfmForceBranch::Approach); + draft.spring_confirmed = true; + draft.radius_nm = "225".into(); + draft.contact_z_nm = "100".into(); + draft.baseline_z_nm = ["104".into(), "120".into()]; + draft.fit_z_nm = ["64".into(), "98".into()]; + assert!(describe(&app, run).enabled); + execute_without_clipboard(run, &mut app, &ctx); + let result = app.afm_hertz_result().expect("Hertz result"); + assert!((result.reduced_modulus_mpa - 50.0).abs() < 1.0e-10); + let frame = |app: &mut PlotiumApp, events| { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(600.0, 460.0), + )), + events, + ..Default::default() + }, + |ui| crate::ui::tools::render_curve_fit_task(app, ui), + ) + }; + let output_visible = |output: egui::FullOutput| { + output.shapes.iter().any(|shape| { + matches!(&shape.shape, egui::Shape::Text(text) + if text.galley.text().ends_with("Create Hertz Data Sheet") + && shape.clip_rect.contains(text.pos + egui::vec2(3.0, 5.0))) + }) + }; + for _ in 0..4 { + let _ = frame(&mut app, Vec::new()); + } + assert!(!output_visible(frame(&mut app, Vec::new()))); + let _ = frame( + &mut app, + vec![ + egui::Event::PointerMoved(egui::pos2(450.0, 200.0)), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + phase: egui::TouchPhase::Move, + delta: egui::vec2(0.0, -2500.0), + modifiers: Default::default(), + }, + ], + ); + assert!((0..30).any(|_| output_visible(frame(&mut app, Vec::new())))); + assert!(describe(&app, output).enabled); + execute_without_clipboard(output, &mut app, &ctx); + assert_eq!(app.doc.datasets.len(), 2); + let draft = app.session.ui.afm_hertz_task.as_mut().unwrap(); + draft.contact_z_nm = "99".into(); + assert!(app.afm_hertz_result().is_none()); + assert!(!describe(&app, output).enabled); } #[test] diff --git a/crates/app/src/ui/tools/afm_fit.rs b/crates/app/src/ui/tools/afm_fit.rs index 9652a163..fcd87721 100644 --- a/crates/app/src/ui/tools/afm_fit.rs +++ b/crates/app/src/ui/tools/afm_fit.rs @@ -4,8 +4,8 @@ use egui::Ui; use plotium_analysis::fit_model::{FitModelDefinition, FitSolver, RobustLoss, WeightMode}; use plotium_analysis::models::{LINEAR_ID, builtin_models}; use plotium_core::state::{ - AfmDeflectionSource, AfmFitDraft, AfmForceBranch, AfmForceCurveContext, AfmForceFit, - AfmForceXSource, FrameRef, PlotiumApp, TaskDockTab, + AfmDeflectionSource, AfmFitDraft, AfmFitTarget, AfmForceBranch, AfmForceCurveContext, + AfmForceFit, AfmForceXSource, FrameRef, PlotiumApp, TaskDockTab, }; const TAB: TaskDockTab = TaskDockTab::CurveFit; @@ -17,6 +17,7 @@ pub(in crate::ui) fn open_task(app: &mut PlotiumApp, branch: AfmForceBranch) { let Some(target) = app.afm_fit_target(source.resource_id(), branch) else { return; }; + app.session.ui.afm_hertz_task = None; let result = app.afm_fit_result(target); app.session.ui.afm_fit_task = Some(AfmFitDraft { target, @@ -37,7 +38,35 @@ pub(in crate::ui) fn open_task(app: &mut PlotiumApp, branch: AfmForceBranch) { app.session.ui.open_task_tab(TAB); } +pub(super) fn target(app: &PlotiumApp) -> Option { + let ui = &app.session.ui; + ui.afm_hertz_task + .as_ref() + .map(|draft| draft.target) + .or_else(|| ui.afm_fit_task.as_ref().map(|draft| draft.target)) +} + +pub(super) fn switch_to_table(app: &mut PlotiumApp, di: usize) { + let ui = &mut app.session.ui; + ui.afm_fit_task = None; + ui.afm_hertz_task = None; + ui.curve_fit_task_dataset = Some(di); + ui.open_task_tab(TAB); +} + pub(in crate::ui) fn afm_fit_gate(app: &PlotiumApp, command: Fit) -> Result<(), &'static str> { + match command { + Fit::OpenHertz | Fit::RunHertz | Fit::HertzDataSheet => { + return super::afm_hertz::gate(app, command); + } + Fit::ShowSource => { + return target(app) + .and_then(|target| app.afm_fit_plot(target)) + .map(|_| ()) + .ok_or("Open AFM Force Fit on an available source plot."); + } + _ => {} + } let draft = app .session .ui @@ -46,7 +75,7 @@ pub(in crate::ui) fn afm_fit_gate(app: &PlotiumApp, command: Fit) -> Result<(), .ok_or("Open AFM Force Fit first.")?; app.afm_fit_plot(draft.target) .ok_or("Open AFM Force Fit on an available source plot.")?; - if matches!(command, Fit::Run | Fit::ShowSource) { + if command == Fit::Run { return Ok(()); } let result = app @@ -59,6 +88,19 @@ 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 => { + super::afm_hertz::run_command(app, command); + return; + } + Fit::ShowSource => { + if let Some(target) = target(app) { + show_source(app, target); + } + return; + } + _ => {} + } let Some(draft) = app.session.ui.afm_fit_task.clone() else { return; }; @@ -85,10 +127,7 @@ 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::ShowSource => { - show_source(app, target); - Ok(()) - } + Fit::OpenHertz | 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(); @@ -98,7 +137,7 @@ pub(in crate::ui) fn run_command(app: &mut PlotiumApp, command: Fit) { } } -fn show_source(app: &mut PlotiumApp, target: plotium_core::state::AfmFitTarget) { +fn show_source(app: &mut PlotiumApp, target: AfmFitTarget) { if let Some(ci) = app.doc.canvas_index(target.canvas) { app.doc.canvases[ci].selected_object = Some(target.object); app.reveal_board_frame(FrameRef::Page(ci)); @@ -109,15 +148,14 @@ pub(super) fn render_task(app: &mut PlotiumApp, host: &mut Ui) { if !task_card::is_active(app, TAB) { return; } - let Some(target) = app - .session - .ui - .afm_fit_task - .as_ref() - .map(|draft| draft.target) - else { + let Some(target) = target(app) else { return; }; + let title = if app.session.ui.afm_hertz_task.is_some() { + "Manual Hertz" + } else { + "AFM Force Fit" + }; let collapsed = app.session.ui.curve_fit_task_collapsed; let TaskCardGeometry { pos, @@ -134,12 +172,11 @@ pub(super) fn render_task(app: &mut PlotiumApp, host: &mut Ui) { task_card::header( ui, area_id, - "AFM Force Fit", + title, Some(target.branch.name().to_owned()), |ui| { - close = crate::ui::panel_chrome::close(ui, "Close AFM Force Fit").clicked(); - collapse = - crate::ui::panel_chrome::collapse(ui, collapsed, "AFM Force Fit").clicked(); + close = crate::ui::panel_chrome::close(ui, &format!("Close {title}")).clicked(); + collapse = crate::ui::panel_chrome::collapse(ui, collapsed, title).clicked(); }, ); if task_card::tab_bar(app, TAB, ui) { @@ -166,13 +203,7 @@ pub(super) fn render_task(app: &mut PlotiumApp, host: &mut Ui) { } fn body(app: &mut PlotiumApp, ui: &mut Ui) { - let Some(target) = app - .session - .ui - .afm_fit_task - .as_ref() - .map(|draft| draft.target) - else { + let Some(target) = target(app) else { return; }; let Some((source, context)) = app @@ -195,6 +226,10 @@ fn body(app: &mut PlotiumApp, ui: &mut Ui) { if app.session.active_canvas != app.doc.canvas_index(target.canvas) { command(app, ui, Fit::ShowSource, false); } + if app.session.ui.afm_hertz_task.is_some() { + super::afm_hertz::body(app, ui, target); + return; + } if let Some(range) = app.afm_fit_selection(target) { ui.label(format!( "Selected {x}: {:.4} to {:.4}", @@ -435,7 +470,7 @@ fn unit_suffix(unit: &str) -> String { } } -fn command(app: &mut PlotiumApp, ui: &mut Ui, choice: Fit, primary: bool) -> bool { +pub(super) fn command(app: &mut PlotiumApp, ui: &mut Ui, choice: Fit, primary: bool) -> bool { let id = CommandId::AfmFit(choice); let command = commands::describe(app, id); let label = if choice == Fit::ToggleOverlay { diff --git a/crates/app/src/ui/tools/afm_hertz.rs b/crates/app/src/ui/tools/afm_hertz.rs new file mode 100644 index 00000000..05a85c64 --- /dev/null +++ b/crates/app/src/ui/tools/afm_hertz.rs @@ -0,0 +1,258 @@ +use super::afm_fit::command; +use crate::ui::commands::AfmFitCommand as Fit; +use egui::Ui; +use egui_phosphor::regular as icon; +use plotium_analysis::afm_hertz::HertzResult; +use plotium_core::state::{ + AfmFitTarget, AfmForceBranch, AfmHertzDraft, AxisRange, PlotiumApp, TaskDockTab, +}; + +#[path = "afm_hertz_preview.rs"] +mod preview; + +fn active_target(app: &PlotiumApp) -> Option { + let source = app + .active_dataset() + .and_then(|di| app.doc.datasets.get(di))?; + app.afm_fit_target(source.resource_id(), AfmForceBranch::Approach) +} + +pub(super) fn gate(app: &PlotiumApp, choice: Fit) -> Result<(), &'static str> { + if choice == Fit::OpenHertz { + return active_target(app) + .map(|_| ()) + .ok_or("Show an AFM force plot before opening Manual Hertz."); + } + let draft = app + .session + .ui + .afm_hertz_task + .as_ref() + .ok_or("Open Manual Hertz first.")?; + match choice { + Fit::RunHertz => { + let k = app.afm_hertz_calibration(draft.target)?; + if !draft.spring_confirmed { + return Err("Confirm the file spring constant."); + } + let input = draft + .input(k) + .map_err(|_| "Enter a radius, a contact Z, and both window limits.")?; + (input.radius_nm > 0.0) + .then_some(()) + .ok_or("Enter a positive probe radius.") + } + Fit::HertzDataSheet => app + .afm_hertz_result() + .map(|_| ()) + .ok_or("Calculate a Hertz fit with the current inputs."), + _ => Err("Choose a Manual Hertz command."), + } +} + +pub(super) fn run_command(app: &mut PlotiumApp, choice: Fit) { + if choice == Fit::OpenHertz { + let Some(target) = active_target(app) else { + return; + }; + let ui = &mut app.session.ui; + if ui + .afm_hertz_task + .as_ref() + .is_none_or(|task| task.target != target) + { + ui.afm_hertz_task = Some(AfmHertzDraft::new(target)); + } + ui.afm_fit_task = None; + ui.curve_fit_task_dataset = None; + ui.curve_fit_task_collapsed = false; + ui.open_task_tab(TaskDockTab::CurveFit); + return; + } + let result = match choice { + 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(); + } + if let Err(error) = result { + app.session.status = error; + } +} + +pub(super) fn body(app: &mut PlotiumApp, ui: &mut Ui, target: AfmFitTarget) { + ui.separator(); + ui.weak("Nonadhesive spherical contact"); + if let Some(afm) = app + .doc + .dataset_by_id(target.source) + .and_then(|data| data.as_afm()) + && afm + .data + .forces + .as_ref() + .is_some_and(|f| f.grid_width > 1 || f.grid_height > 1) + { + let [col, row] = afm.selected_pixel; + ui.small(format!("Pixel: column {col}, row {row}")); + } + let calibration = app.afm_hertz_calibration(target); + if let Err(message) = calibration { + ui.colored_label(ui.visuals().warn_fg_color, message); + } + let selection = app.afm_fit_selection(target); + + if let Some(draft) = &mut app.session.ui.afm_hertz_task { + let mut changed = ui + .add_enabled_ui(calibration.is_ok(), |ui| { + ui.checkbox(&mut draft.spring_confirmed, "Use file spring constant") + .changed() + }) + .inner; + egui::Grid::new("hertz_inputs").show(ui, |ui| { + changed |= number_field(ui, "Probe radius (nm)", &mut draft.radius_nm); + ui.end_row(); + changed |= number_field(ui, "Contact Z (nm)", &mut draft.contact_z_nm); + ui.end_row(); + }); + changed |= range_field(ui, "Baseline Z (nm)", &mut draft.baseline_z_nm, selection); + changed |= range_field(ui, "Fit Z (nm)", &mut draft.fit_z_nm, selection); + if changed { + draft.error = None; + } + } + 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), + Err(error) => { + ui.small(error); + None + } + } + }) + .body_returned + .flatten(); + if let Some(z) = contact + && let Some(draft) = &mut app.session.ui.afm_hertz_task + { + draft.contact_z_nm = z.to_string(); + draft.error = None; + } + } + + ui.separator(); + command(app, ui, Fit::RunHertz, true); + if let Some(error) = app + .session + .ui + .afm_hertz_task + .as_ref() + .and_then(|draft| draft.error.as_deref()) + { + ui.colored_label(ui.visuals().error_fg_color, error); + } + if let Some(result) = app.afm_hertz_result() { + summary(ui, result); + } else { + ui.weak("No current result. Calculate a Hertz fit."); + } + command(app, ui, Fit::HertzDataSheet, false); +} + +fn text_box(ui: &mut Ui, value: &mut String, hint: &str) -> egui::Response { + ui.add( + egui::TextEdit::singleline(value) + .desired_width(66.0) + .hint_text(hint), + ) +} + +fn number_field(ui: &mut Ui, label: &str, value: &mut String) -> bool { + let label = ui.label(label); + text_box(ui, value, "").labelled_by(label.id).changed() +} + +fn range_field( + ui: &mut Ui, + label: &str, + limits: &mut [String; 2], + selection: Option, +) -> bool { + let label = ui.label(label); + ui.horizontal_wrapped(|ui| { + let [minimum, maximum] = limits; + let changed = text_box(ui, minimum, "Min").labelled_by(label.id).changed() + | text_box(ui, maximum, "Max").labelled_by(label.id).changed(); + let copy = ui + .add_enabled(selection.is_some(), egui::Button::new(icon::SELECTION)) + .on_hover_text("Use source plot selection") + .on_disabled_hover_text("Select a range on the source plot."); + if copy.clicked() + && let Some(range) = selection + { + *minimum = range.min.to_string(); + *maximum = range.max.to_string(); + return true; + } + changed + }) + .inner +} + +fn summary(ui: &mut Ui, result: &HertzResult) { + crate::typography::headline_label( + ui, + format!( + "Reduced modulus E*: {} MPa", + preview::value(result.reduced_modulus_mpa) + ), + ); + ui.small(format!( + "Baseline RMS: {} nN ({} points)", + preview::value(result.baseline_rms_nn), + result.baseline_points + )); + ui.small(format!( + "Residual RMS: {} nN ({} points)", + preview::value(result.residual_rms_nn), + result.rows.len() + )); + let ratio = format!( + "Maximum indentation / radius: {}", + preview::value(result.max_indentation_over_radius) + ); + if result.max_indentation_over_radius >= 0.1 { + ui.colored_label( + ui.visuals().warn_fg_color, + format!("{ratio} (check shallow indentation)"), + ); + } else { + ui.small(ratio); + } + if let Some(sensitivity) = &result.contact_sensitivity { + let modulus = |value: Option| { + value.map_or_else( + || "unavailable".into(), + |mpa| format!("{} MPa", preview::value(mpa)), + ) + }; + let shift = preview::value(sensitivity.shift_nm); + ui.small(format!( + "Contact sensitivity at +/- {shift} nm (fixed windows, not a confidence interval)" + )); + ui.small(format!( + "-{shift} nm: {} | +{shift} nm: {}", + modulus(sensitivity.lower_contact_modulus_mpa), + modulus(sensitivity.higher_contact_modulus_mpa), + )); + } else { + ui.small("Contact sensitivity unavailable"); + } + preview::result(ui, result); +} diff --git a/crates/app/src/ui/tools/afm_hertz_preview.rs b/crates/app/src/ui/tools/afm_hertz_preview.rs new file mode 100644 index 00000000..5e8234ae --- /dev/null +++ b/crates/app/src/ui/tools/afm_hertz_preview.rs @@ -0,0 +1,313 @@ +use egui::{Align2, Color32, FontId, Pos2, Rect, Response, Sense, Stroke, Ui}; +use plotium_analysis::afm_hertz::HertzResult; +use plotium_core::state::AfmHertzDraft; + +struct Colors { + baseline: Color32, + fit: Color32, + contact: Color32, +} + +impl Colors { + fn from_ui(ui: &Ui) -> Self { + if ui.visuals().dark_mode { + Self { + baseline: Color32::from_rgb(76, 199, 172), + fit: Color32::from_rgb(122, 188, 252), + contact: Color32::from_rgb(252, 164, 82), + } + } else { + Self { + baseline: Color32::from_rgb(6, 113, 91), + fit: Color32::from_rgb(24, 101, 177), + contact: Color32::from_rgb(157, 73, 10), + } + } + } +} + +pub(super) fn approach(ui: &mut Ui, points: &[[f64; 2]], draft: &AfmHertzDraft) -> Option { + let colors = Colors::from_ui(ui); + let contact = finite_number(&draft.contact_z_nm); + let baseline = band(&draft.baseline_z_nm, colors.baseline); + let fit = band(&draft.fit_z_nm, colors.fit); + ui.horizontal_wrapped(|ui| { + key(ui, "Baseline", colors.baseline); + key(ui, "Fit window", colors.fit); + key(ui, "Contact Z", colors.contact); + }); + let trace = Trace { + color: ui.visuals().text_color(), + points, + }; + let (response, scale) = plot( + ui, + ["Relative Z (nm)", "Force (nN)"], + &[trace], + Marks { + bands: [baseline, fit], + vertical: contact.map(|z| (z, colors.contact)), + zero_line: false, + pick: true, + }, + )?; + let response = response + .on_hover_cursor(egui::CursorIcon::Crosshair) + .on_hover_text("Set contact Z at the nearest sample"); + if !response.clicked() { + return None; + } + let pointer = response.interact_pointer_pos()?; + if !scale.rect.contains(pointer) { + return None; + } + let z = scale.data_x(pointer.x); + points + .iter() + .filter(|p| finite(p)) + .map(|p| p[0]) + .min_by(|a, b| (a - z).abs().total_cmp(&(b - z).abs())) +} + +pub(super) fn result(ui: &mut Ui, result: &HertzResult) { + let colors = Colors::from_ui(ui); + let observed = result + .rows + .iter() + .map(|row| [row.indentation_nm, row.corrected_force_nn]) + .collect::>(); + let predicted = result + .rows + .iter() + .map(|row| [row.indentation_nm, row.predicted_force_nn]) + .collect::>(); + let residual = result + .rows + .iter() + .map(|row| [row.indentation_nm, row.residual_nn()]) + .collect::>(); + let observed_color = ui.visuals().text_color(); + ui.horizontal_wrapped(|ui| { + key(ui, "Measured", observed_color); + key(ui, "Hertz", colors.fit); + }); + let _ = plot( + ui, + ["Indentation (nm)", "Corrected force (nN)"], + &[ + Trace { + color: observed_color, + points: &observed, + }, + Trace { + color: colors.fit, + points: &predicted, + }, + ], + Marks::default(), + ); + let _ = plot( + ui, + ["Indentation (nm)", "Residual (nN)"], + &[Trace { + color: colors.contact, + points: &residual, + }], + Marks { + zero_line: true, + ..Default::default() + }, + ); +} + +fn key(ui: &mut Ui, label: &str, color: Color32) { + ui.colored_label(color, label); +} + +#[derive(Clone, Copy)] +struct Trace<'a> { + color: Color32, + points: &'a [[f64; 2]], +} + +#[derive(Default)] +struct Marks { + bands: [Option<([f64; 2], Color32)>; 2], + vertical: Option<(f64, Color32)>, + zero_line: bool, + pick: bool, +} + +#[derive(Clone, Copy)] +struct Scale { + x: [f64; 2], + y: [f64; 2], + rect: Rect, +} + +impl Scale { + fn point(self, [x, y]: [f64; 2]) -> Pos2 { + egui::pos2( + self.screen_x(x), + self.rect.bottom() + - ((y - self.y[0]) / (self.y[1] - self.y[0])) as f32 * self.rect.height(), + ) + } + + fn screen_x(self, x: f64) -> f32 { + self.rect.left() + ((x - self.x[0]) / (self.x[1] - self.x[0])) as f32 * self.rect.width() + } + + fn data_x(self, x: f32) -> f64 { + self.x[0] + f64::from((x - self.rect.left()) / self.rect.width()) * (self.x[1] - self.x[0]) + } +} + +fn plot( + ui: &mut Ui, + [x_name, y_name]: [&str; 2], + traces: &[Trace<'_>], + marks: Marks, +) -> Option<(Response, Scale)> { + let mut lo = [f64::INFINITY; 2]; + let mut hi = [f64::NEG_INFINITY; 2]; + for point in traces + .iter() + .flat_map(|trace| trace.points) + .filter(|point| finite(point)) + { + for j in 0..2 { + lo[j] = lo[j].min(point[j]); + hi[j] = hi[j].max(point[j]); + } + } + let (mut y_min, mut y_max) = (lo[1], hi[1]); + if marks.zero_line { + y_min = y_min.min(0.0); + y_max = y_max.max(0.0); + } + if !lo[0].is_finite() || lo[0] >= hi[0] || !(hi[0] - lo[0]).is_finite() { + ui.weak("Preview unavailable: no finite X span."); + return None; + } + if y_min == y_max { + let pad = (y_min.abs() * 0.01).max(0.01); + y_min -= pad; + y_max += pad; + } + if !(y_max - y_min).is_finite() { + ui.weak("Preview unavailable: no finite Y span."); + return None; + } + ui.small(y_name); + let size = egui::vec2(ui.available_width().max(70.0), 112.0); + let response = ui.allocate_response( + size, + if marks.pick { + Sense::click() + } else { + Sense::hover() + }, + ); + let rect = response.rect; + let plot = Rect::from_min_max( + rect.min + egui::vec2(53.0, 8.0), + rect.max - egui::vec2(6.0, 17.0), + ); + let scale = Scale { + x: [lo[0], hi[0]], + y: [y_min, y_max], + rect: plot, + }; + let painter = ui.painter_at(rect); + let ink = ui.visuals().weak_text_color(); + let axis = Stroke::new(1.0_f32, ui.visuals().widgets.noninteractive.bg_stroke.color); + painter.rect_filled(plot, 0.0, ui.visuals().faint_bg_color); + let chart = painter.with_clip_rect(plot); + for ([min, max], color) in marks.bands.into_iter().flatten() { + let min = scale.screen_x(min.clamp(lo[0], hi[0])); + let max = scale.screen_x(max.clamp(lo[0], hi[0])); + chart.rect_filled( + Rect::from_min_max(egui::pos2(min, plot.top()), egui::pos2(max, plot.bottom())), + 0.0, + color.gamma_multiply(0.21), + ); + } + if marks.zero_line { + chart.line_segment([scale.point([lo[0], 0.0]), scale.point([hi[0], 0.0])], axis); + } + if let Some((z, color)) = marks.vertical + && scale.x[0] <= z + && z <= scale.x[1] + { + let x = scale.screen_x(z); + chart.line_segment( + [egui::pos2(x, plot.top()), egui::pos2(x, plot.bottom())], + Stroke::new(1.5_f32, color), + ); + } + for trace in traces { + // Break the line across invalid points instead of hiding gaps. + for segment in trace.points.split(|point| !finite(point)) { + if segment.len() >= 2 { + chart.add(egui::Shape::line( + segment.iter().map(|&point| scale.point(point)).collect(), + Stroke::new(1.3_f32, trace.color), + )); + } + } + } + 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 [ + ( + plot.left_top() - egui::vec2(4.0, 0.0), + Align2::RIGHT_CENTER, + y_max, + ), + ( + plot.left_bottom() - egui::vec2(4.0, 0.0), + Align2::RIGHT_CENTER, + y_min, + ), + ( + plot.left_bottom() + egui::vec2(0.0, 3.0), + Align2::LEFT_TOP, + lo[0], + ), + ( + plot.right_bottom() + egui::vec2(0.0, 3.0), + Align2::RIGHT_TOP, + hi[0], + ), + ] { + painter.text(anchor, alignment, value(tick), FontId::monospace(9.0), ink); + } + ui.small(x_name); + Some((response, scale)) +} + +fn band(limits: &[String; 2], color: Color32) -> Option<([f64; 2], Color32)> { + let min = finite_number(&limits[0])?; + let max = finite_number(&limits[1])?; + (min < max).then_some(([min, max], color)) +} + +fn finite_number(text: &str) -> Option { + text.trim() + .parse::() + .ok() + .filter(|value| value.is_finite()) +} + +fn finite(point: &[f64; 2]) -> bool { + point[0].is_finite() && point[1].is_finite() +} + +pub(super) fn value(value: f64) -> String { + if value != 0.0 && !(0.01..1000.0).contains(&value.abs()) { + format!("{value:.3e}") + } else { + format!("{value:.3}") + } +} diff --git a/crates/app/src/ui/tools/curve_fit.rs b/crates/app/src/ui/tools/curve_fit.rs index 56074798..4c68bb20 100644 --- a/crates/app/src/ui/tools/curve_fit.rs +++ b/crates/app/src/ui/tools/curve_fit.rs @@ -30,9 +30,7 @@ pub(crate) fn open_task(app: &mut PlotiumApp, di: usize) { return; } ensure_curve_fit_state(app, di); - app.session.ui.afm_fit_task = None; - app.session.ui.curve_fit_task_dataset = Some(di); - app.session.ui.open_task_tab(TaskDockTab::CurveFit); + super::afm_fit::switch_to_table(app, di); } pub(crate) fn render_task(app: &mut PlotiumApp, host: &mut Ui) { diff --git a/crates/app/src/ui/tools/mod.rs b/crates/app/src/ui/tools/mod.rs index 9fa0ec32..80cb831c 100644 --- a/crates/app/src/ui/tools/mod.rs +++ b/crates/app/src/ui/tools/mod.rs @@ -2,6 +2,7 @@ //! in here without touching the sidebar or the toolbar. mod afm_fit; +mod afm_hertz; mod craft; mod cursors; mod curve_fit; @@ -81,7 +82,7 @@ pub(crate) fn render_region_task(app: &mut PlotiumApp, ui: &mut Ui) { } pub(crate) fn render_curve_fit_task(app: &mut PlotiumApp, ui: &mut Ui) { - if app.session.ui.afm_fit_task.is_some() { + if afm_fit::target(app).is_some() { afm_fit::render_task(app, ui); } else { curve_fit::render_task(app, ui); diff --git a/crates/app/src/ui/tools/task_card.rs b/crates/app/src/ui/tools/task_card.rs index c0bd92e5..d13fc696 100644 --- a/crates/app/src/ui/tools/task_card.rs +++ b/crates/app/src/ui/tools/task_card.rs @@ -196,13 +196,7 @@ pub(crate) fn visible_area_id(app: &PlotiumApp) -> Option { .curve_fit_task_dataset .filter(|dataset| Some(*dataset) == active) .map(|_| area_id(TaskDockTab::CurveFit)) - .or_else(|| { - app.session - .ui - .afm_fit_task - .as_ref() - .map(|_| area_id(TaskDockTab::CurveFit)) - }), + .or_else(|| super::afm_fit::target(app).map(|_| area_id(TaskDockTab::CurveFit))), TaskDockTab::Statistics => app .session .ui diff --git a/crates/app/src/ui/tools/task_card_tabs.rs b/crates/app/src/ui/tools/task_card_tabs.rs index 68f2081f..6a6ec6a7 100644 --- a/crates/app/src/ui/tools/task_card_tabs.rs +++ b/crates/app/src/ui/tools/task_card_tabs.rs @@ -53,7 +53,7 @@ pub(in crate::ui::tools) fn tab_bar( icon::CHART_LINE_UP, "Fit", app.session.ui.curve_fit_task_dataset.or_else(|| { - let target = app.session.ui.afm_fit_task.as_ref()?.target; + let target = crate::ui::tools::afm_fit::target(app)?; app.doc .dataset_index(app.afm_fit_plot(target)?.primary_dataset()?) }), diff --git a/crates/core/src/project/lineage_convert.rs b/crates/core/src/project/lineage_convert.rs index 80e7c911..7c2112b9 100644 --- a/crates/core/src/project/lineage_convert.rs +++ b/crates/core/src/project/lineage_convert.rs @@ -17,6 +17,7 @@ pub(super) fn derivation_kind_to_str(kind: DerivationKind) -> &'static str { DerivationKind::StatisticsTable => "statistics_table", DerivationKind::RelationalTransform => "relational_transform", DerivationKind::AfmForceBranchTable => "afm_force_branch_table", + DerivationKind::AfmHertzFitTable => "afm_hertz_fit_table", } } @@ -36,6 +37,7 @@ fn derivation_kind_from_str(value: &str) -> Result { "statistics_table" => Ok(DerivationKind::StatisticsTable), "relational_transform" => Ok(DerivationKind::RelationalTransform), "afm_force_branch_table" => Ok(DerivationKind::AfmForceBranchTable), + "afm_hertz_fit_table" => Ok(DerivationKind::AfmHertzFitTable), other => Err(ProjectError::Invalid(format!( "unknown dataset derivation kind {other}" ))), diff --git a/crates/core/src/state/afm_hertz.rs b/crates/core/src/state/afm_hertz.rs new file mode 100644 index 00000000..2536afad --- /dev/null +++ b/crates/core/src/state/afm_hertz.rs @@ -0,0 +1,268 @@ +use super::*; +use crate::actions::Action; +use plotium_analysis::afm_hertz::{HertzInput, HertzResult, fit_hertz}; +use std::sync::Arc; + +#[derive(Clone)] +pub struct AfmHertzDraft { + pub target: AfmFitTarget, + pub spring_confirmed: bool, + pub radius_nm: String, + pub contact_z_nm: String, + pub baseline_z_nm: [String; 2], + pub fit_z_nm: [String; 2], + pub error: Option, + result: Option>, +} + +struct AfmHertzRun { + target: AfmFitTarget, + pixel: [usize; 2], + data: Arc, + input: HertzInput, + result: HertzResult, +} + +impl AfmHertzDraft { + pub fn new(target: AfmFitTarget) -> Self { + Self { + target, + spring_confirmed: false, + radius_nm: String::new(), + contact_z_nm: String::new(), + baseline_z_nm: Default::default(), + fit_z_nm: Default::default(), + error: None, + result: None, + } + } + + 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()); + } + let number = |value: &str, field| { + value + .trim() + .parse::() + .ok() + .filter(|number| number.is_finite()) + .ok_or_else(|| format!("Enter a finite {field} in nm.")) + }; + let range = |values: &[String; 2], name| { + Ok::<_, String>([number(&values[0], name)?, number(&values[1], name)?]) + }; + Ok(HertzInput { + spring_constant_n_per_m, + radius_nm: number(&self.radius_nm, "tip 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")?, + }) + } +} + +impl PlotiumApp { + fn afm_hertz_source(&self, target: AfmFitTarget) -> Result<(&AfmDataset, f64), &'static str> { + if target.branch != AfmForceBranch::Approach { + return Err("Manual Hertz fitting uses the approach branch."); + } + self.afm_fit_plot(target) + .ok_or("Select the source AFM force curve.")?; + let afm = self + .doc + .dataset_by_id(target.source) + .and_then(Dataset::as_afm) + .ok_or("The AFM source is unavailable.")?; + // The NanoScope loader uses this extension to identify PeakForce Capture. + // Its first displayed half-cycle is not a verified loading branch. + if std::path::Path::new(&afm.data.source) + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("pfc")) + { + return Err( + "Use a calibrated non-PeakForce approach curve. Manual Hertz does not support PeakForce Capture.", + ); + } + let forces = afm.data.forces.as_ref().ok_or("No AFM force curve.")?; + let context = afm.force_curve_context().ok_or("No AFM force curve.")?; + if !forces.z_positions.as_ref().is_some_and(|axis| { + forces.approach_samples >= 6 && axis.len() >= forces.approach_samples + }) { + return Err("Manual Hertz fitting needs an approach curve with relative Z in nm."); + } + let spring = context + .spring_constant_n_per_m + .ok_or("Manual Hertz fitting needs a valid file spring constant.")?; + if !matches!( + context.deflection_source, + AfmDeflectionSource::StoredLength | AfmDeflectionSource::VoltageSensitivity + ) { + return Err("Manual Hertz fitting needs calibrated deflection."); + } + Ok((afm, spring)) + } + + pub fn afm_hertz_calibration(&self, target: AfmFitTarget) -> Result { + self.afm_hertz_source(target).map(|(_, spring)| spring) + } + + pub fn afm_hertz_points(&self, target: AfmFitTarget) -> Result, &'static str> { + let (afm, _) = self.afm_hertz_source(target)?; + afm.field_catalog + .id_for_key("afm.force_curve") + .and_then(|field| afm.force_figure(field)) + .and_then(|figure| { + figure + .series + .into_iter() + .find(|series| series.name == AfmForceBranch::Approach.name()) + }) + .map(|series| series.points) + .filter(|points| { + points.len() == afm.force_branch_sample_count(AfmForceBranch::Approach) + }) + .ok_or("The selected AFM approach curve is incomplete.") + } + + pub fn run_afm_hertz(&mut self) -> Result<(), String> { + let draft = self + .session + .ui + .afm_hertz_task + .as_mut() + .ok_or("Open Manual Hertz first.")?; + draft.result = None; + let target = draft.target; + let (afm, spring) = self.afm_hertz_source(target)?; + let draft = self + .session + .ui + .afm_hertz_task + .as_ref() + .ok_or("Open Manual Hertz first.")?; + let input = draft.input(spring)?; + let result = + fit_hertz(&self.afm_hertz_points(target)?, input).map_err(|error| error.to_string())?; + let run = Arc::new(AfmHertzRun { + target, + pixel: afm.selected_pixel, + data: afm.data.clone(), + input, + result, + }); + self.session + .ui + .afm_hertz_task + .as_mut() + .ok_or("Open Manual Hertz first.")? + .result = Some(run); + Ok(()) + } + + fn current_afm_hertz_run(&self) -> Option<&AfmHertzRun> { + let draft = self.session.ui.afm_hertz_task.as_ref()?; + let run = draft.result.as_deref()?; + let (afm, spring) = self.afm_hertz_source(draft.target).ok()?; + (run.target == draft.target + && run.pixel == afm.selected_pixel + && Arc::ptr_eq(&run.data, &afm.data) + && draft.input(spring).ok()? == run.input) + .then_some(run) + } + + pub fn afm_hertz_result(&self) -> Option<&HertzResult> { + self.current_afm_hertz_run().map(|run| &run.result) + } + + pub fn create_afm_hertz_output(&mut self) -> Result<(), String> { + let run = self + .current_afm_hertz_run() + .ok_or("Calculate a Hertz fit for the current inputs and source curve first.")?; + let source = run.target.source; + let name = format!( + "{} - Approach Hertz Fit", + self.doc + .dataset_by_id(source) + .ok_or("The AFM source is unavailable.")? + .display_name() + ); + let mut table = hertz_table(run)?; + table.name = Some(name); + table.lineage = Some(DatasetLineage::new( + DerivationKind::AfmHertzFitTable, + [source], + )); + let size = table.board_rect_pt(); + table.board_pos = next_board_frame_pos(self, [size.width, size.height]); + let id = table.resource_id; + self.try_execute_action(Action::CreateTableData { + dataset: Box::new(Dataset::Table(Box::new(table))), + }) + .map_err(|error| error.to_string())?; + let index = self + .doc + .dataset_index(id) + .ok_or("The Hertz fit table is unavailable.")?; + self.reveal_board_frame(FrameRef::Sheet(index)); + self.session.ui.sheet_open = Some(index); + Ok(()) + } +} + +fn hertz_table(run: &AfmHertzRun) -> Result { + let rows = &run.result.rows; + let points = |name: &str, unit: &str, f: fn(&plotium_analysis::afm_hertz::HertzRow) -> f64| { + FloatSeries { + name: name.into(), + unit: unit.into(), + values: rows.iter().map(|row| Some(f(row))).collect(), + uncertainty: None, + fit: None, + } + }; + let mut columns = vec![ + points("Measured force", "nN", |row| row.corrected_force_nn), + points("Hertz prediction", "nN", |row| row.predicted_force_nn), + points("Residual", "nN", |row| row.residual_nn()), + points("Relative Z", "nm", |row| row.z_nm), + ]; + let input = run.input; + let result = &run.result; + for (name, unit, value) in [ + ("Reduced modulus E*", "MPa", result.reduced_modulus_mpa), + ("Tip radius", "nm", input.radius_nm), + ("File spring constant", "N/m", input.spring_constant_n_per_m), + ("Contact Z", "nm", input.contact_z_nm), + ("Baseline Z min", "nm", input.baseline_z_nm[0]), + ("Baseline Z max", "nm", input.baseline_z_nm[1]), + ("Baseline slope", "nN/nm", result.baseline_slope_nn_per_nm), + ( + "Baseline force at contact", + "nN", + result.baseline_force_at_contact_nn, + ), + ("Fit Z min", "nm", input.fit_z_nm[0]), + ("Fit Z max", "nm", input.fit_z_nm[1]), + ("Pixel X (zero-based)", "", run.pixel[0] as f64), + ("Pixel Y (zero-based)", "", run.pixel[1] as f64), + ] { + columns.push(FloatSeries { + name: name.into(), + unit: unit.into(), + values: vec![Some(value); rows.len()], + uncertainty: None, + fit: None, + }); + } + materialized_float_series_table( + ( + "Indentation".into(), + "nm".into(), + rows.iter().map(|row| Some(row.indentation_nm)).collect(), + ), + columns, + "plotium.afm.manual-hertz.v1", + ) + .map_err(|error| format!("Could not create a Hertz fit table: {error}")) +} diff --git a/crates/core/src/state/lineage.rs b/crates/core/src/state/lineage.rs index f828c3ff..c9637aca 100644 --- a/crates/core/src/state/lineage.rs +++ b/crates/core/src/state/lineage.rs @@ -22,6 +22,7 @@ pub enum DerivationKind { StatisticsTable, RelationalTransform, AfmForceBranchTable, + AfmHertzFitTable, } impl DerivationKind { @@ -41,6 +42,7 @@ impl DerivationKind { Self::StatisticsTable => "Statistics table", Self::RelationalTransform => "Table transform", Self::AfmForceBranchTable => "AFM force branch", + Self::AfmHertzFitTable => "AFM Hertz fit", } } } diff --git a/crates/core/src/state/mod.rs b/crates/core/src/state/mod.rs index 33f7eba3..4bd6291e 100644 --- a/crates/core/src/state/mod.rs +++ b/crates/core/src/state/mod.rs @@ -21,6 +21,7 @@ use plotium_processing::{ mod afm; mod afm_fit; mod afm_fit_output; +mod afm_hertz; mod app_impl; mod app_impl_align; mod app_impl_analysis; @@ -207,6 +208,7 @@ mod xrd_axis; pub use afm::*; pub use afm_fit::*; +pub use afm_hertz::*; pub use app_impl::*; pub use app_impl_align::*; pub use app_impl_analysis::validate_ilt_params; diff --git a/crates/core/src/state/ui_state.rs b/crates/core/src/state/ui_state.rs index e46518b3..578b6897 100644 --- a/crates/core/src/state/ui_state.rs +++ b/crates/core/src/state/ui_state.rs @@ -247,6 +247,7 @@ pub struct UiState { /// Data table whose Curve Fit workflow is shown in the canvas task card. pub curve_fit_task_dataset: Option, pub afm_fit_task: Option, + pub afm_hertz_task: Option, /// Whether the Curve Fit task card is reduced to its one-line summary. pub curve_fit_task_collapsed: bool, /// Data table whose Statistics workflow is shown in the canvas task card. @@ -472,6 +473,7 @@ impl Default for UiState { region_task_collapsed: false, curve_fit_task_dataset: None, afm_fit_task: None, + afm_hertz_task: None, curve_fit_task_collapsed: false, stat_task_dataset: None, stat_task_collapsed: false, diff --git a/crates/core/src/state/ui_state/task_dock.rs b/crates/core/src/state/ui_state/task_dock.rs index 5817eede..57dd79b3 100644 --- a/crates/core/src/state/ui_state/task_dock.rs +++ b/crates/core/src/state/ui_state/task_dock.rs @@ -34,6 +34,7 @@ impl UiState { TaskDockTab::CurveFit => { self.curve_fit_task_dataset = None; self.afm_fit_task = None; + self.afm_hertz_task = None; self.curve_fit_task_collapsed = false; } TaskDockTab::Statistics => { @@ -62,7 +63,9 @@ impl UiState { (TaskDockTab::Regions, self.region_task_dataset.is_some()), ( TaskDockTab::CurveFit, - self.curve_fit_task_dataset.is_some() || self.afm_fit_task.is_some(), + self.curve_fit_task_dataset.is_some() + || self.afm_fit_task.is_some() + || self.afm_hertz_task.is_some(), ), (TaskDockTab::Statistics, self.stat_task_dataset.is_some()), (TaskDockTab::Protein, self.protein_open), @@ -83,6 +86,7 @@ impl UiState { self.region_task_collapsed = false; self.curve_fit_task_dataset = None; self.afm_fit_task = None; + self.afm_hertz_task = None; self.curve_fit_task_collapsed = false; self.stat_task_dataset = None; self.stat_task_collapsed = false; diff --git a/crates/core/tests/afm_hertz.rs b/crates/core/tests/afm_hertz.rs new file mode 100644 index 00000000..7a3f09f4 --- /dev/null +++ b/crates/core/tests/afm_hertz.rs @@ -0,0 +1,156 @@ +use plotium_core::actions::Action; +use plotium_core::state::{ + AfmDataset, AfmForceBranch, AfmHertzDraft, DEFAULT_CANVAS_SIZE_MM, Dataset, DerivationKind, + PlotiumApp, +}; +use plotium_io::{AfmData, AfmForceSet, AfmScale}; +use std::sync::Arc; + +fn approach(spring: Option, with_z: bool) -> PlotiumApp { + // F = indentation^1.5 / 64 nN, k = 1 N/m, linear detector baseline. + // The displayed force includes a constant 2 nN offset from that baseline. + let mut app = PlotiumApp::default(); + let z = [83., 90.578125, 95.875, 98.984375, 100., 101., 102., 103.]; + let raw = [192, 155, 136, 129, 128, 128, 128, 128]; + let force = AfmForceSet { + grid_width: 2, + grid_height: 1, + samples_per_curve: raw.len(), + raw: Arc::from([raw, raw].concat()), + signal_scale: AfmScale { + multiplier: 1. / 64., + offset: 0., + unit: "nm".into(), + }, + sample_period_s: None, + z_positions: with_z.then(|| Arc::from(z)), + display_order: (0..raw.len()).collect(), + approach_samples: raw.len(), + deflection_sensitivity_m_per_v: None, + spring_constant_n_per_m: spring, + }; + let data = AfmDataset::load(AfmData { + images: vec![], + forces: Some(force), + source: "synthetic.spm".into(), + import_warnings: vec![], + }); + let source = data.resource_id; + app.try_execute_action(Action::insert_dataset_with_default_canvas( + &app, + Dataset::Afm(Box::new(data)), + "Synthetic Hertz".into(), + DEFAULT_CANVAS_SIZE_MM, + )) + .unwrap(); + let target = app + .afm_fit_target(source, AfmForceBranch::Approach) + .unwrap(); + let mut draft = AfmHertzDraft::new(target); + draft.radius_nm = "400".into(); + draft.contact_z_nm = "100".into(); + draft.baseline_z_nm = ["101".into(), "103".into()]; + draft.fit_z_nm = ["83".into(), "99".into()]; + app.session.ui.afm_hertz_task = Some(draft); + app +} + +#[test] +fn manual_hertz_checks_calibration_and_confirmation() { + let mut app = approach(Some(1.), false); + assert!(app.run_afm_hertz().unwrap_err().contains("relative Z")); + let mut app = approach(None, true); + assert!(app.run_afm_hertz().unwrap_err().contains("spring constant")); + let mut app = approach(Some(1.), true); + assert!(app.run_afm_hertz().unwrap_err().contains("Confirm")); + assert!(app.afm_hertz_result().is_none()); +} + +#[test] +fn manual_hertz_rejects_peakforce_capture_even_with_usable_calibration() { + let mut app = approach(Some(1.), true); + let draft = app.session.ui.afm_hertz_task.as_mut().unwrap(); + draft.spring_confirmed = true; + let target = draft.target; + app.run_afm_hertz().unwrap(); + + let Dataset::Afm(afm) = &mut app.doc.datasets[0] else { + panic!("expected AFM"); + }; + Arc::make_mut(&mut afm.data).source = "synthetic.PFC".into(); + assert!( + app.afm_hertz_calibration(target) + .unwrap_err() + .contains("PeakForce Capture") + ); + assert!( + app.run_afm_hertz() + .unwrap_err() + .contains("PeakForce Capture") + ); + assert!(app.afm_hertz_result().is_none()); +} + +#[test] +fn manual_hertz_invalidates_result_and_saves_disclosed_fit_data() { + let mut app = approach(Some(1.), true); + app.session + .ui + .afm_hertz_task + .as_mut() + .unwrap() + .spring_confirmed = true; + app.run_afm_hertz().unwrap(); + let result = app.afm_hertz_result().unwrap(); + assert_eq!(result.rows.len(), 4); + assert!((result.reduced_modulus_mpa - 0.5859375).abs() < 1e-10); + assert!(result.residual_rms_nn < 1e-10); + + app.session.ui.afm_hertz_task.as_mut().unwrap().contact_z_nm = "99".into(); + assert!(app.afm_hertz_result().is_none()); + assert!(app.create_afm_hertz_output().is_err()); + app.session.ui.afm_hertz_task.as_mut().unwrap().contact_z_nm = "100".into(); + + let Dataset::Afm(afm) = &mut app.doc.datasets[0] else { + panic!("expected AFM"); + }; + afm.selected_pixel = [0, 0]; + assert!(app.afm_hertz_result().is_none()); + app.run_afm_hertz().unwrap(); + app.create_afm_hertz_output().unwrap(); + let table = app.doc.datasets[1].as_table().unwrap(); + assert_eq!( + table.lineage.as_ref().unwrap().kind, + DerivationKind::AfmHertzFitTable + ); + let schema = &table.typed_state.envelope.revision.snapshot.schema; + for (name, unit) in [ + ("Indentation", "nm"), + ("Residual", "nN"), + ("Contact Z", "nm"), + ("Reduced modulus E*", "MPa"), + ] { + let column = schema + .columns + .iter() + .find(|column| column.name == name) + .unwrap(); + assert_eq!(column.unit.as_ref().unwrap().display_unit, unit); + } + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hertz.plotium"); + plotium_core::project::save_project(&app, &path, false).unwrap(); + let reopened = plotium_core::project::load_project(&path).unwrap(); + let saved = reopened.doc.datasets[1].as_table().unwrap(); + let lineage = saved.lineage.as_ref().unwrap(); + assert_eq!(lineage.kind, DerivationKind::AfmHertzFitTable); + assert_eq!( + lineage.sources, + vec![reopened.doc.datasets[0].resource_id()] + ); + assert!(reopened.afm_hertz_result().is_none()); + + app.undo(); + assert_eq!(app.doc.datasets.len(), 1); +} diff --git a/docs/src/content/docs/guides/supported-formats.md b/docs/src/content/docs/guides/supported-formats.md index 68ebc7b2..82fea269 100644 --- a/docs/src/content/docs/guides/supported-formats.md +++ b/docs/src/content/docs/guides/supported-formats.md @@ -267,11 +267,11 @@ Without a usable spring constant, calibrated deflection is shown in nanometres. If the signal cannot be converted to deflection, the plot keeps the stored signal and unit. -Use **Analyze → AFM Force Fit → Fit Approach** or **Fit Retract**. The fit -panel identifies the selected branch, its plotted coordinates and units, and -the calibration used or why the signal is not shown as force. This is an -empirical fit of the plotted values: it does not infer a contact point or -calculate a modulus. +For an empirical fit, use **Analyze → AFM Force Fit → Fit Approach** or +**Fit Retract**. The fit panel identifies the selected branch, its plotted +coordinates and units, and the calibration used or why the signal is not +shown as force. An empirical fit does not infer a contact point or calculate +a modulus. To fit part of a branch, use **Analyze → Analysis Range** and drag across the curve plot. The default model is **Linear**. **Run AFM Fit** overlays the @@ -297,6 +297,44 @@ PeakForce Capture curves are the per-pixel signals as acquired. Derived QNM maps such as modulus arrive as their own image channels; Plotium does not recompute them from the curves. +### Manual spherical Hertz fit + +Select a force curve with **Relative Z (nm)** and **Force (nN)**. Open +**Analyze → AFM Force Fit → Manual Hertz** to fit the Approach branch. This +requires calibrated deflection and a valid cantilever spring constant from the +file. Check **Use file spring constant** and enter the verified spherical +tip radius in **Probe radius (nm)**. + +Manual Hertz is unavailable for PeakForce Capture (`.pfc`); its loading branch +has not been verified for this fit. + +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 + **Fit Z (nm)** wholly on the compressive side (smaller relative Z). Each + interval needs at least three samples spanning distinct Z values. To copy + an interval from the source plot, drag a range with **Analyze → Analysis Range**, then use the + **Use source plot selection** button beside the corresponding interval. + Check both intervals and the contact point in the preview. +3. Select **Calculate Hertz Fit**. Plotium subtracts a linear baseline fitted + before contact, then subtracts the cantilever deflection from the piezo + travel since contact to obtain indentation. Every fitted point must have + positive corrected force and indentation. +4. Inspect the corrected force versus indentation, fitted curve, and + residuals. The reported reduced modulus, **E\*** in MPa, is not the + sample's Young's modulus. Contact sensitivity repeats the fit after + shifting contact by about one local sample spacing in both directions + while keeping the intervals fixed. It is not a confidence interval; either + shifted fit may be unavailable. +5. Use **Create Hertz Data Sheet** to keep the fitted values and their inputs + when you save the project. + +Use spherical Hertz for shallow elastic contact with negligible adhesion and +substrate influence. Strong adhesion, thin samples, deep indentation relative +to tip radius, or rate-dependent behavior can make the result unsuitable even +when the residuals are small. See [Dimitriadis et al. on finite thickness and +contact-point sensitivity](https://doi.org/10.1016/S0006-3495%2802%2975620-8). + ## Electrophysiology (ABF2) Plotium reads ABF 2.x files with int16 or float32 samples, multiple channels 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 ee8653f1..9a9b7afc 100644 --- a/docs/src/content/docs/zh-cn/guides/supported-formats.md +++ b/docs/src/content/docs/zh-cn/guides/supported-formats.md @@ -208,9 +208,9 @@ PeakForce Capture `.pfc` 数据立方体。图像通道按文件记录的扫描 力。没有可用的弹簧常数时,显示以纳米计的偏转量。无法转换为偏转量时,保留保存的 信号及其单位。 -选择 **Analyze → AFM Force Fit → Fit Approach** 或 **Fit Retract**。拟合面板会显示 -所选分支、绘图坐标及单位,以及所用的标定或未以力显示信号的原因。这是对绘图数值的 -经验拟合,不推断接触点,也不计算模量。 +进行经验拟合时,选择 **Analyze → AFM Force Fit → Fit Approach** 或 **Fit Retract**。 +拟合面板会显示所选分支、绘图坐标及单位,以及所用的标定或未以力显示信号的原因。 +经验拟合不推断接触点,也不计算模量。 只拟合局部时,用 **Analyze → Analysis Range** 在曲线图上拖选区间。默认模型为 **Linear**。点击 **Run AFM Fit**,拟合曲线会叠加在原图的拟合区间内,不会打开 @@ -229,6 +229,33 @@ PeakForce Capture 文件旁通常保存着一个 AllImages `.spm` 导出文件 PeakForce Capture 曲线是逐像素采集的原始信号。模量等派生 QNM 地图作为独立的 图像通道导入;Plotium 不会从曲线重新计算这些地图。 +### 手动球形 Hertz 拟合 + +选中横轴为 **Relative Z (nm)**、纵轴为 **Force (nN)** 的力曲线,选择 +**Analyze → AFM Force Fit → Manual Hertz** 拟合接近分支。此拟合需要已标定的 +偏转量和文件中的有效悬臂弹簧常数。勾选 **Use file spring constant**,在 +**Probe radius (nm)** 中输入已核实的球形探针半径。 + +手动 Hertz 不适用于 PeakForce Capture(`.pfc`),因为其加载分支尚未针对该拟合验证。 + +1. 在 **Contact Z (nm)** 中输入接触起始位置,或在 **Approach preview** 中 + 点选最接近接触位置的采样点。 +2. 将 **Baseline Z (nm)** 完全设在接触前(相对 Z 较大),将 **Fit Z (nm)** + 完全设在受压侧(相对 Z 较小)。每个区间至少需要三个采样点,且 Z 值不能全部相同。也可用 + **Analyze → Analysis Range** 在原图拖选区间,再点击对应区间旁的 + **Use source plot selection** 按钮。在预览中核对两个区间及接触点的位置。 +3. 选择 **Calculate Hertz Fit**。Plotium 先扣除用接触前数据拟合的线性基线, + 再用接触后的压电位移减去悬臂偏转量,得到压入深度。每个拟合点的校正力和压入 + 深度都必须为正。 +4. 检查校正力随压入深度变化的拟合图和残差。结果以 MPa 报告约化模量 **E\***, + 并非样品的杨氏模量。接触点敏感性分析会保持两个区间不变,将接触点向两侧各移 + 大约一个局部采样间距后重新拟合。它不是置信区间,任一侧的重算都有可能无法完成。 +5. 选择 **Create Hertz Data Sheet**,拟合数据和输入参数即可随项目一同保存。 + +球形 Hertz 模型适用于黏附及基底影响可忽略的浅压入弹性接触。若黏附明显、样品较 +薄、压入深度相对于探针半径较大,或样品响应依赖加载速率,即使残差很小,结果也 +可能不适用。参见 [Dimitriadis 等人关于有限厚度及接触点敏感性的研究](https://doi.org/10.1016/S0006-3495%2802%2975620-8)。 + ## 电生理(ABF2) Plotium 读取 int16 或 float32 采样的 ABF 2.x 文件,支持多通道、多 sweep 以及