From 93dcc15c8086eb148ca77df103ef3a5ef0ec0d49 Mon Sep 17 00:00:00 2001 From: Jiekang Tian Date: Sun, 22 Nov 2026 20:22:53 +0800 Subject: [PATCH] fix(afm): clarify curve calibration and fit units --- crates/app/src/ui/canvas/interactions.rs | 10 +- crates/app/src/ui/canvas/mod.rs | 1 + crates/app/src/ui/canvas/selection_status.rs | 21 ++ crates/app/src/ui/commands_afm_tests.rs | 43 ++++- crates/app/src/ui/tools/afm_fit.rs | 108 +++++++++-- crates/core/src/state/afm.rs | 179 ++++++++++++------ crates/core/src/state/afm_fit.rs | 16 +- crates/core/src/state/afm_fit_output.rs | 30 ++- crates/core/tests/afm_canvas.rs | 134 ++++++++++++- crates/io/src/lib.rs | 1 + .../content/docs/guides/supported-formats.md | 42 ++-- .../docs/zh-cn/guides/supported-formats.md | 26 ++- 12 files changed, 475 insertions(+), 136 deletions(-) create mode 100644 crates/app/src/ui/canvas/selection_status.rs diff --git a/crates/app/src/ui/canvas/interactions.rs b/crates/app/src/ui/canvas/interactions.rs index bb33571c..676e3e4a 100644 --- a/crates/app/src/ui/canvas/interactions.rs +++ b/crates/app/src/ui/canvas/interactions.rs @@ -143,15 +143,7 @@ pub(crate) fn finish_selection_drag( unit: None, source_stream: None, }); - let unit = if app.doc.datasets[dataset].as_afm().is_some() { - app.session.status = format!("Selected AFM X range: {:.3}-{:.3}.", x.min, x.max); - return; - } else if app.doc.datasets[dataset].as_mass_spec().is_some() { - "min" - } else { - "ppm" - }; - app.session.status = format!("Selected {:.3}-{:.3} {unit}.", x.min, x.max); + app.session.status = super::selection_status::range_status(&app.doc.datasets[dataset], x); } pub(crate) fn handle_zoom_drag( diff --git a/crates/app/src/ui/canvas/mod.rs b/crates/app/src/ui/canvas/mod.rs index e4c385b8..26cd46a4 100644 --- a/crates/app/src/ui/canvas/mod.rs +++ b/crates/app/src/ui/canvas/mod.rs @@ -49,6 +49,7 @@ mod geometry; mod image_drop; pub(crate) mod image_painting; mod selection_painting; +mod selection_status; pub(crate) use image_drop::{ImagePanelDropTarget, image_drop_target}; mod integrals; mod integrals2d; diff --git a/crates/app/src/ui/canvas/selection_status.rs b/crates/app/src/ui/canvas/selection_status.rs new file mode 100644 index 00000000..aabe28a2 --- /dev/null +++ b/crates/app/src/ui/canvas/selection_status.rs @@ -0,0 +1,21 @@ +use plotium_core::state::{AxisRange, Dataset}; + +pub(super) fn range_status(dataset: &Dataset, x: AxisRange) -> String { + if let Some(context) = dataset.as_afm().and_then(|afm| afm.force_curve_context()) { + let unit = if context.x.unit.is_empty() { + String::new() + } else { + format!(" {}", context.x.unit) + }; + return format!( + "Selected {}: {:.3} to {:.3}{unit}.", + context.x.name, x.min, x.max + ); + } + let unit = if dataset.as_mass_spec().is_some() { + "min" + } else { + "ppm" + }; + format!("Selected {:.3}-{:.3} {unit}.", x.min, x.max) +} diff --git a/crates/app/src/ui/commands_afm_tests.rs b/crates/app/src/ui/commands_afm_tests.rs index dd3f936c..2726bdf7 100644 --- a/crates/app/src/ui/commands_afm_tests.rs +++ b/crates/app/src/ui/commands_afm_tests.rs @@ -66,7 +66,7 @@ fn afm_fit_command_uses_the_selected_branch_and_range() { source_stream: None, }); - let ctx = egui::Context::default(); + let ctx = crate::typography::test_context(); assert!(describe(&app, CommandId::SelectRange).enabled); let command = CommandId::FitAfmForce(AfmForceBranch::Retract); assert!( @@ -80,6 +80,34 @@ fn afm_fit_command_uses_the_selected_branch_and_range() { let draft = app.session.ui.afm_fit_task.as_ref().unwrap(); assert_eq!(draft.model, plotium_analysis::models::LINEAR_ID); let target = draft.target; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1200.0, 900.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 [ + "Retract", + "X: Relative Z (nm), not indentation | Y: Force (nN)", + "Deflection: stored length", + "Spring constant: 1 N/m (file, applied)", + "Empirical model", + ] { + assert!( + rendered.shapes.iter().any(|shape| matches!( + &shape.shape, + egui::Shape::Text(text) if text.galley.job.text == label + )), + "missing AFM fit label: {label}" + ); + } let viewport = app.afm_fit_plot(target).unwrap().viewport.clone(); let active = app.session.active_canvas; let run = |app: &mut PlotiumApp, command| { @@ -139,15 +167,10 @@ fn afm_fit_command_uses_the_selected_branch_and_range() { assert!(!app.afm_fit_result(target).unwrap().shown); run(&mut app, AfmFitCommand::ResidualPlot); assert_eq!(app.session.active_canvas, Some(2)); - assert_eq!( - app.doc.canvases[2].objects[0] - .plot() - .unwrap() - .figure() - .series[0] - .name, - "Residual" - ); + let residual = app.doc.canvases[2].objects[0].plot().unwrap().figure(); + assert_eq!(residual.series[0].name, "Residual"); + assert_eq!(residual.x.label, "Relative Z (nm)"); + assert_eq!(residual.y.label, "Residual (nN)"); assert!(app.session.ui.sheet_open.is_none()); run(&mut app, AfmFitCommand::DataSheet); assert_eq!(app.doc.canvases.len(), 3); diff --git a/crates/app/src/ui/tools/afm_fit.rs b/crates/app/src/ui/tools/afm_fit.rs index 171a017a..9652a163 100644 --- a/crates/app/src/ui/tools/afm_fit.rs +++ b/crates/app/src/ui/tools/afm_fit.rs @@ -4,7 +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::{ - AfmFitDraft, AfmForceBranch, AfmForceFit, FrameRef, PlotiumApp, TaskDockTab, + AfmDeflectionSource, AfmFitDraft, AfmForceBranch, AfmForceCurveContext, AfmForceFit, + AfmForceXSource, FrameRef, PlotiumApp, TaskDockTab, }; const TAB: TaskDockTab = TaskDockTab::CurveFit; @@ -174,20 +175,31 @@ fn body(app: &mut PlotiumApp, ui: &mut Ui) { else { return; }; - let Some(source) = app + let Some((source, context)) = app .afm_fit_plot(target) - .and_then(|plot| plot.primary_dataset()) - .and_then(|id| app.doc.dataset_by_id(id)) + .and_then(|_| app.doc.dataset_by_id(target.source)) + .and_then(|source| Some((source, source.as_afm()?.force_curve_context()?))) else { ui.small("Source plot unavailable. Open AFM Force Fit from a force curve."); return; }; ui.weak(source.display_name()); + let x = context.x.label(); + let x_note = if context.x_source == AfmForceXSource::ReconstructedZ { + ", not indentation" + } else { + "" + }; + ui.small(format!("X: {x}{x_note} | Y: {}", context.y.label())); + calibration(ui, &context); if app.session.active_canvas != app.doc.canvas_index(target.canvas) { command(app, ui, Fit::ShowSource, false); } if let Some(range) = app.afm_fit_selection(target) { - ui.label(format!("Selected X: {:.4} to {:.4}", range.min, range.max)); + ui.label(format!( + "Selected {x}: {:.4} to {:.4}", + range.min, range.max + )); } else { ui.label("Range: Entire branch"); } @@ -199,8 +211,8 @@ fn body(app: &mut PlotiumApp, ui: &mut Ui) { .chain(&app.session.ui.fit_custom_models) .filter(|model| model.independent_variables.len() == 1 && model.responses.len() == 1); let model_name = |model: &FitModelDefinition| model.name.as_str().to_owned(); - ui.horizontal(|ui| { - ui.label("Model"); + ui.horizontal_wrapped(|ui| { + ui.label("Empirical model"); let selected = models .clone() .find(|model| model.id == draft.model) @@ -314,14 +326,66 @@ fn body(app: &mut PlotiumApp, ui: &mut Ui) { } } +fn quantity_label(name: &str, unit: &str) -> String { + if unit.is_empty() { + name.to_owned() + } else { + format!("{name} ({unit})") + } +} + +fn calibration(ui: &mut Ui, context: &AfmForceCurveContext<'_>) { + let sensitivity = context.deflection_sensitivity_m_per_v.map(|value| { + let nm_per_v = value * 1.0e9; + if (0.001..1000.0).contains(&nm_per_v) { + format!("{nm_per_v:.4} nm/V") + } else { + format!("{value:.4e} m/V") + } + }); + let deflection = match context.deflection_source { + AfmDeflectionSource::StoredLength => sensitivity.map_or_else( + || "Deflection: stored length".to_owned(), + |value| format!("Deflection: stored length (file sensitivity {value}, not reapplied)"), + ), + AfmDeflectionSource::VoltageSensitivity => sensitivity.map_or_else( + || "Deflection: converted from voltage".to_owned(), + |value| format!("Deflection: file sensitivity {value} applied"), + ), + AfmDeflectionSource::MissingVoltageSensitivity => { + "Deflection unavailable: missing or invalid voltage sensitivity".to_owned() + } + AfmDeflectionSource::UnsupportedSignalUnit => { + "Deflection unavailable: unrecognized signal units".to_owned() + } + }; + ui.small(deflection); + let converts_deflection = matches!( + context.deflection_source, + AfmDeflectionSource::StoredLength | AfmDeflectionSource::VoltageSensitivity + ); + let spring = match (context.spring_constant_n_per_m, converts_deflection) { + (Some(value), true) => format!("Spring constant: {value} N/m (file, applied)"), + (Some(value), false) => format!("Spring constant: {value} N/m (file, not applied)"), + (None, true) => "Force unavailable: missing or invalid spring constant".to_owned(), + (None, false) => "Spring constant: missing or invalid".to_owned(), + }; + ui.small(spring); +} + fn summary(ui: &mut Ui, result: &AfmForceFit) { let range = result.range(); - crate::typography::headline_label(ui, &result.model.name); + crate::typography::headline_label(ui, format!("Empirical fit: {}", result.model.name)); ui.small(format!( - "{:.4} to {:.4} {} | {} points", + "{} vs {} | No modulus", + quantity_label(&result.y_name, &result.y_unit), + quantity_label(&result.x_name, &result.x_unit), + )); + ui.small(format!( + "X range: {:.4} to {:.4}{} | {} points", range.min, range.max, - result.x_unit, + unit_suffix(&result.x_unit), result.rows.len() )); if result.converged { @@ -335,14 +399,22 @@ fn summary(ui: &mut Ui, result: &AfmForceFit) { |error| super::curve_fit::fmt_val_sigma(p.value, error), ); if result.model.id == LINEAR_ID && p.name == "a" { - ui.label(format!("Intercept (a): {value} {}", result.y_unit)); + ui.label(format!( + "Intercept (a): {value}{}", + unit_suffix(&result.y_unit) + )); } else if result.model.id == LINEAR_ID && p.name == "b" { let unit = if result.x_unit.is_empty() { - format!("{}/sample", result.y_unit) + "sample" } else { - format!("{}/{}", result.y_unit, result.x_unit) + &result.x_unit }; - ui.label(format!("Slope (b): {value} {unit}")); + let response = if result.y_unit.is_empty() { + "1" + } else { + &result.y_unit + }; + ui.label(format!("Slope (b): {value} {response}/{unit}")); } else { ui.label(format!("{}: {value}", p.name)); } @@ -355,6 +427,14 @@ fn summary(ui: &mut Ui, result: &AfmForceFit) { } } +fn unit_suffix(unit: &str) -> String { + if unit.is_empty() { + String::new() + } else { + format!(" {unit}") + } +} + fn command(app: &mut PlotiumApp, ui: &mut Ui, choice: Fit, primary: bool) -> bool { let id = CommandId::AfmFit(choice); let command = commands::describe(app, id); diff --git a/crates/core/src/state/afm.rs b/crates/core/src/state/afm.rs index 071d070f..edc60e64 100644 --- a/crates/core/src/state/afm.rs +++ b/crates/core/src/state/afm.rs @@ -18,6 +18,104 @@ impl AfmForceBranch { } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AfmCurveAxis<'a> { + pub name: &'static str, + pub unit: &'a str, +} + +impl AfmCurveAxis<'_> { + pub fn label(self) -> String { + if self.unit.is_empty() { + self.name.into() + } else { + format!("{} ({})", self.name, self.unit) + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AfmForceXSource { + ReconstructedZ, + SamplePeriod, + SampleIndex, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AfmDeflectionSource { + StoredLength, + VoltageSensitivity, + MissingVoltageSensitivity, + UnsupportedSignalUnit, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AfmForceCurveContext<'a> { + pub x: AfmCurveAxis<'a>, + pub y: AfmCurveAxis<'a>, + pub x_source: AfmForceXSource, + pub deflection_source: AfmDeflectionSource, + pub spring_constant_n_per_m: Option, + pub deflection_sensitivity_m_per_v: Option, + pub signal_unit: &'a str, + deflection_to_metres: Option, +} + +impl<'a> AfmForceCurveContext<'a> { + fn from_force_set(forces: &'a plotium_io::AfmForceSet) -> Self { + let (x_source, x_name, x_unit) = if forces.z_positions.is_some() { + (AfmForceXSource::ReconstructedZ, "Relative Z", "nm") + } else if forces.sample_period_s.is_some() { + (AfmForceXSource::SamplePeriod, "Branch time", "s") + } else { + (AfmForceXSource::SampleIndex, "Sample index", "") + }; + let spring_constant_n_per_m = positive_finite(forces.spring_constant_n_per_m); + let deflection_sensitivity_m_per_v = positive_finite(forces.deflection_sensitivity_m_per_v); + let scale_unit = forces.signal_scale.unit.trim(); + // Applying the channel scale consumes its per-count denominator. + let signal_unit = scale_unit + .split_once('/') + .filter(|(_, denominator)| denominator.trim().eq_ignore_ascii_case("LSB")) + .map_or(scale_unit, |(unit, _)| unit.trim()); + // The stored scale may have already applied the header's sensitivity. + let quantity_unit = scale_unit + .split_once('/') + .map_or(scale_unit, |(unit, _)| unit.trim()); + let (deflection_source, deflection_to_metres) = match physical_length_factor(quantity_unit) + { + Some(factor) => (AfmDeflectionSource::StoredLength, Some(factor)), + None if quantity_unit.eq_ignore_ascii_case("V") => match deflection_sensitivity_m_per_v + { + Some(factor) => (AfmDeflectionSource::VoltageSensitivity, Some(factor)), + None => (AfmDeflectionSource::MissingVoltageSensitivity, None), + }, + None => (AfmDeflectionSource::UnsupportedSignalUnit, None), + }; + let (y_name, y_unit) = match (deflection_to_metres, spring_constant_n_per_m) { + (Some(_), Some(_)) => ("Force", "nN"), + (Some(_), None) => ("Deflection", "nm"), + (None, _) => ("Signal", signal_unit), + }; + Self { + x: AfmCurveAxis { + name: x_name, + unit: x_unit, + }, + y: AfmCurveAxis { + name: y_name, + unit: y_unit, + }, + x_source, + deflection_source, + spring_constant_n_per_m, + deflection_sensitivity_m_per_v, + signal_unit, + deflection_to_metres, + } + } +} + #[derive(Clone)] pub struct AfmDataset { pub resource_id: DatasetId, @@ -132,6 +230,7 @@ impl AfmDataset { pub fn force_figure(&self, field: FieldId) -> Option
{ (self.field_catalog.id_for_key("afm.force_curve") == Some(field)).then_some(())?; let forces = self.data.forces.as_ref()?; + let context = AfmForceCurveContext::from_force_set(forces); let curve = forces.curve_raw(self.selected_pixel[0], self.selected_pixel[1])?; let x_value = |display_index: usize| { forces @@ -156,13 +255,12 @@ impl AfmDataset { } }) }; - let displacement_factor = deflection_length_factor(forces); - let spring_constant = forces - .spring_constant_n_per_m - .filter(|value| value.is_finite() && *value > 0.0); let calibrated = |raw: i32| { let stored = forces.signal_scale.apply(raw); - match (displacement_factor, spring_constant) { + match ( + context.deflection_to_metres, + context.spring_constant_n_per_m, + ) { (Some(to_metres), Some(spring)) => stored * to_metres * spring * 1.0e9, (Some(to_metres), None) => stored * to_metres * 1.0e9, (None, _) => stored, @@ -179,15 +277,6 @@ impl AfmDataset { }) .collect(); let split = forces.approach_samples.min(ordered.len()); - let (x_name, x_unit) = force_x_quantity(forces); - let x_label = axis_label(x_name, x_unit); - let y_label = if displacement_factor.is_some() && spring_constant.is_some() { - "Force (nN)" - } else if displacement_factor.is_some() { - "Deflection (nm)" - } else { - &forces.signal_scale.unit - }; let (x_min, x_max) = ordered .iter() .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), point| { @@ -199,9 +288,9 @@ impl AfmDataset { (lo.min(point[1]), hi.max(point[1])) }); let mut figure = Figure::new( - "Force Curve", - Axis::new(x_label, x_min, x_max), - Axis::new(y_label, y_min, y_max), + format!("{} Curve", context.y.name), + Axis::new(context.x.label(), x_min, x_max), + Axis::new(context.y.label(), y_min, y_max), ); figure.series.push(Series::line( AfmForceBranch::Approach.name(), @@ -214,6 +303,13 @@ impl AfmDataset { Some(figure) } + pub fn force_curve_context(&self) -> Option> { + self.data + .forces + .as_ref() + .map(AfmForceCurveContext::from_force_set) + } + pub fn force_branch_sample_count(&self, branch: AfmForceBranch) -> usize { let Some(forces) = &self.data.forces else { return 0; @@ -245,55 +341,12 @@ impl PlotiumApp { } } -fn axis_label(name: &str, unit: &str) -> String { - if unit.is_empty() { - name.into() - } else { - format!("{name} ({unit})") - } -} - -pub(super) fn force_x_quantity(forces: &plotium_io::AfmForceSet) -> (&'static str, &'static str) { - if forces.z_positions.is_some() { - ("Z", "nm") - } else if forces.sample_period_s.is_some() { - ("Time", "s") - } else { - ("Sample index", "") - } -} - -pub(super) fn force_y_quantity(forces: &plotium_io::AfmForceSet) -> (&'static str, &str) { - if deflection_length_factor(forces).is_none() { - ("Signal", &forces.signal_scale.unit) - } else if forces - .spring_constant_n_per_m - .is_some_and(|v| v.is_finite() && v > 0.0) - { - ("Force", "nN") - } else { - ("Deflection", "nm") - } -} - -fn deflection_length_factor(forces: &plotium_io::AfmForceSet) -> Option { - let unit = forces.signal_scale.unit.split('/').next()?.trim(); - physical_length_factor(unit) - .or_else(|| { - unit.eq_ignore_ascii_case("V") - .then_some(forces.deflection_sensitivity_m_per_v) - .flatten() - }) - .filter(|value| value.is_finite() && *value > 0.0) +fn positive_finite(value: Option) -> Option { + value.filter(|value| value.is_finite() && *value > 0.0) } fn physical_length_factor(unit: &str) -> Option { - let normalized = unit - .split('/') - .next()? - .trim() - .to_ascii_lowercase() - .replace(['µ', '~'], "u"); + let normalized = unit.to_ascii_lowercase().replace(['µ', '~'], "u"); match normalized.as_str() { "m" => Some(1.0), "mm" => Some(1.0e-3), diff --git a/crates/core/src/state/afm_fit.rs b/crates/core/src/state/afm_fit.rs index df66bb77..ca112867 100644 --- a/crates/core/src/state/afm_fit.rs +++ b/crates/core/src/state/afm_fit.rs @@ -153,10 +153,8 @@ impl PlotiumApp { .dataset_by_id(source) .and_then(Dataset::as_afm) .ok_or("The AFM source is unavailable.")?; - let forces = afm - .data - .forces - .as_ref() + let context = afm + .force_curve_context() .ok_or("The AFM source has no force curves.")?; let figure = afm .field_catalog @@ -200,8 +198,6 @@ impl PlotiumApp { }; let result = fit_model(model, vec![data], &[], options) .map_err(|error| format!("AFM fit failed: {error}"))?; - let (x_name, x_unit) = super::afm::force_x_quantity(forces); - let (y_name, y_unit) = super::afm::force_y_quantity(forces); let rows = result .points .iter() @@ -243,10 +239,10 @@ impl PlotiumApp { .is_finite() .then_some(result.statistics.r_squared), notices: result.notices, - x_name: x_name.into(), - x_unit: x_unit.into(), - y_name: y_name.into(), - y_unit: y_unit.into(), + x_name: context.x.name.into(), + x_unit: context.x.unit.into(), + y_name: context.y.name.into(), + y_unit: context.y.unit.into(), rows, })); self.change_afm_fits(target, after)?; diff --git a/crates/core/src/state/afm_fit_output.rs b/crates/core/src/state/afm_fit_output.rs index 84af95af..b5c75b8b 100644 --- a/crates/core/src/state/afm_fit_output.rs +++ b/crates/core/src/state/afm_fit_output.rs @@ -111,12 +111,38 @@ impl PlotiumApp { )); if residual_plot { let index = self.doc.canvases.len(); - let action = Action::insert_dataset_with_default_canvas( + let y_label = AfmCurveAxis { + name: "Residual", + unit: &fit.y_unit, + } + .label(); + let dataset = Dataset::Table(Box::new(table)); + let mut canvas = crate::workflow::build_default_canvas_for_dataset( + &dataset, + self.doc.datasets.len(), + name.clone(), + DEFAULT_CANVAS_SIZE_MM, + ); + let plot = canvas + .objects + .first_mut() + .and_then(CanvasObject::plot_mut) + .ok_or("Could not prepare the AFM residual plot.")?; + plot.axis_overrides.y_label = Some(y_label); + plot.apply_axis_overrides(); + let mut action = Action::insert_dataset_with_default_canvas( self, - Dataset::Table(Box::new(table)), + dataset, name, DEFAULT_CANVAS_SIZE_MM, ); + let Action::InsertDatasetWithCanvas { + prepared_canvas, .. + } = &mut action + else { + return Err("Could not prepare the AFM residual plot action.".into()); + }; + *prepared_canvas = Some(Box::new(canvas)); self.try_execute_action(action) .map_err(|error| error.to_string())?; self.reveal_board_frame(FrameRef::Page(index)); diff --git a/crates/core/tests/afm_canvas.rs b/crates/core/tests/afm_canvas.rs index 4e5bf457..b7384174 100644 --- a/crates/core/tests/afm_canvas.rs +++ b/crates/core/tests/afm_canvas.rs @@ -1,8 +1,8 @@ use plotium_core::actions::Action; use plotium_core::automation::{KIND_FIELD, ProjectResourceProvider, ResourceProvider}; use plotium_core::state::{ - CanvasObjectKind, DEFAULT_CANVAS_SIZE_MM, Dataset, DerivedAxes, NATURE_DOUBLE_COLUMN, - PlotiumApp, StackSpec, + AfmForceBranch, AfmForceXSource, CanvasObjectKind, DEFAULT_CANVAS_SIZE_MM, Dataset, + DerivedAxes, NATURE_DOUBLE_COLUMN, PlotiumApp, StackSpec, }; use plotium_figure::{ContourSpec, SeriesEncoding}; use plotium_io::{AfmData, AfmForceSet, AfmFrameDirection, AfmImageChannel, AfmScale}; @@ -90,7 +90,135 @@ fn map_and_force_plots_survive_project_roundtrip() { let force = objects[1].plot().unwrap(); assert!(map.figure().heatmap.is_some()); assert_eq!(force.figure().series.len(), 2); - assert_eq!(force.figure().x.label, "Z (nm)"); + assert_eq!(force.figure().x.label, "Relative Z (nm)"); +} + +#[test] +fn force_curve_context_matches_calibration_and_axes_used_in_plot() { + use plotium_core::state::AfmDeflectionSource::*; + let cases = [ + // Stored length is already calibrated; the header sensitivity must not be applied again. + ("nm", Some(37e-9), 0.1, StoredLength, "Force (nN)", 0.1), + ( + "V/LSB", + Some(2e-9), + 0.1, + VoltageSensitivity, + "Force (nN)", + 0.2, + ), + ("nm", None, 0.0, StoredLength, "Deflection (nm)", 1.0), + ( + "V/LSB", + None, + 0.1, + MissingVoltageSensitivity, + "Signal (V)", + 1.0, + ), + ( + "Arb/LSB", + None, + 0.1, + UnsupportedSignalUnit, + "Signal (Arb)", + 1.0, + ), + ]; + for (index, (unit, sensitivity, spring, deflection_source, y_label, expected_y)) in + cases.into_iter().enumerate() + { + let mut dataset = afm_dataset(false); + let Dataset::Afm(afm) = &mut dataset else { + unreachable!() + }; + let forces = Arc::make_mut(&mut afm.data).forces.as_mut().unwrap(); + forces.signal_scale.unit = unit.into(); + forces.deflection_sensitivity_m_per_v = sensitivity; + forces.spring_constant_n_per_m = Some(spring); + let (x_source, x_label, expected_x) = match index { + 0 => (AfmForceXSource::ReconstructedZ, "Relative Z (nm)", 0.0), + 1 => { + forces.z_positions = None; + forces.sample_period_s = Some(0.002); + (AfmForceXSource::SamplePeriod, "Branch time (s)", 0.002) + } + _ => { + forces.z_positions = None; + (AfmForceXSource::SampleIndex, "Sample index", 1.0) + } + }; + let context = afm.force_curve_context().unwrap(); + assert_eq!(context.deflection_source, deflection_source); + assert_eq!(context.deflection_sensitivity_m_per_v, sensitivity); + assert_eq!( + context.spring_constant_n_per_m, + (spring > 0.0).then_some(spring) + ); + assert_eq!(context.x_source, x_source); + assert_eq!(context.x.label(), x_label); + assert_eq!(context.y.label(), y_label); + let field = afm.field_catalog.id_for_key("afm.force_curve").unwrap(); + let quantity = y_label.split_whitespace().next().unwrap(); + assert_eq!( + afm.force_figure(field).unwrap().title, + format!("{quantity} Curve") + ); + let app = insert(dataset); + let plot = app.doc.canvases[0].objects[0].plot().unwrap(); + let figure = plot.figure(); + assert_eq!(figure.x.label, x_label); + assert_eq!(figure.y.label, y_label); + assert_eq!(figure.series[0].points[1][0], expected_x); + assert!((figure.series[0].points[0][1] - expected_y).abs() < 1.0e-12); + } +} + +#[test] +fn new_afm_fit_data_preserves_branch_and_curve_quantities() { + let mut dataset = afm_dataset(false); + let Dataset::Afm(afm) = &mut dataset else { + unreachable!() + }; + let forces = Arc::make_mut(&mut afm.data).forces.as_mut().unwrap(); + forces.samples_per_curve = 8; + forces.raw = Arc::from([1, 2, 3, 4, 5, 6, 7, 8]); + forces.signal_scale.unit = "V/LSB".into(); + forces.deflection_sensitivity_m_per_v = None; + forces.z_positions = Some(Arc::from([0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0])); + forces.display_order = Arc::from([0, 1, 2, 3, 4, 5, 6, 7]); + forces.approach_samples = 4; + let mut app = insert(dataset); + let source = app.doc.datasets[0].resource_id(); + let target = app.afm_fit_target(source, AfmForceBranch::Retract).unwrap(); + app.run_afm_fit( + target, + plotium_analysis::models::LINEAR_ID, + Default::default(), + true, + ) + .unwrap(); + let fit = app.afm_fit_result(target).unwrap(); + assert_eq!(fit.branch, AfmForceBranch::Retract); + assert_eq!((&*fit.x_name, &*fit.x_unit), ("Relative Z", "nm")); + assert_eq!((&*fit.y_name, &*fit.y_unit), ("Signal", "V")); + assert_eq!(fit.rows[0][..2], [0.0, 5.0]); + + app.create_afm_fit_output(target, false).unwrap(); + let table = app.doc.datasets.last().unwrap().as_table().unwrap(); + let schema = &table.typed_state.envelope.revision.snapshot.schema; + let quantity = |id| { + let column = schema.column(id).unwrap(); + ( + column.name.as_str(), + column.unit.as_ref().unwrap().display_unit.as_str(), + ) + }; + assert_eq!(quantity(table.x_binding.unwrap()), ("Relative Z", "nm")); + assert_eq!( + quantity(table.series_bindings[0].value_column), + ("Signal", "V") + ); } #[test] diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 740f2e5d..5be2e27a 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -489,6 +489,7 @@ pub struct AfmForceSet { pub raw: std::sync::Arc<[i32]>, pub signal_scale: AfmScale, pub sample_period_s: Option, + /// Reconstructed relative actuator Z in nm, in display order; not indentation. pub z_positions: Option>, /// Sample indices in display order; approach precedes retract. pub display_order: std::sync::Arc<[usize]>, diff --git a/docs/src/content/docs/guides/supported-formats.md b/docs/src/content/docs/guides/supported-formats.md index 6e533010..68ebc7b2 100644 --- a/docs/src/content/docs/guides/supported-formats.md +++ b/docs/src/content/docs/guides/supported-formats.md @@ -253,27 +253,37 @@ See [XPS](/guides/xps/) for energy conversion, processing, and fitting. Plotium imports NanoScope `.spm` images, force curves, and force-volume grids, plus PeakForce Capture `.pfc` data cubes. Image channels plot as maps at the recorded scan size, in the file's physical units, with the aspect ratio locked. -Force curves plot as separate Approach and Retract branches. With calibrated -deflection and a spring constant, the vertical axis is force in nanonewtons; -without the spring constant it is deflection in nanometres. If the signal -cannot be converted to deflection, it stays in its stored unit. For standalone -ramps, Plotium uses the calibrated relative Z ramp when available, then -recorded sample time, then sample index. - -Use **Analyze → AFM Force Fit → Fit Approach** or **Fit Retract**. To fit -part of a branch, use **Analyze → Analysis Range** and drag across the force -plot. The default model is **Linear**. **Run AFM Fit** overlays the prediction -within the fitted interval on the source plot without opening a new page or -sheet. The fitted points, parameters, and convergence status stay with the -plot when you save the project. +Force curves plot as separate Approach and Retract branches. When the +necessary metadata is available, Plotium shows **Relative Z (nm)**, +reconstructed from a linear ramp for standalone curves or a sinusoidal +ramp for PeakForce Capture. Relative Z represents piezo motion, not +tip-sample separation or indentation depth. If relative Z is unavailable, +the plot shows **Branch time (s)** calculated from the sample period, or +sample index when there is no sample period. + +The vertical axis is force in nanonewtons only when Plotium can obtain +calibrated deflection and a valid cantilever spring constant from the file. +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. + +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 +prediction within the fitted interval on the source plot without opening a +new page or sheet. The fitted points, parameters, and convergence status +stay with the plot when you save the project. Clear **Overlay on source plot** to run a fit without changing what the plot shows. After fitting, **Output** lets you toggle the overlay, duplicate the plot with the fit, create a residual plot, or open a new sheet containing observed, predicted, and residual values. **Zoom to Fit Range** magnifies -the fitted interval on the source plot. Z is piezo displacement, not -tip-sample separation or indentation; this fit does not infer a contact -point or calculate a modulus. +the fitted interval on the source plot. A PeakForce Capture file usually has an AllImages `.spm` export saved beside it. Plotium finds that companion, checks that its image grid matches the force 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 9c887799..ee8653f1 100644 --- a/docs/src/content/docs/zh-cn/guides/supported-formats.md +++ b/docs/src/content/docs/zh-cn/guides/supported-formats.md @@ -198,19 +198,27 @@ CasaXPS `.txt` 按八行结构头识别,而不是仅按扩展名识别。其 Plotium 可导入 NanoScope `.spm` 图像、力曲线与 Force Volume 网格,以及 PeakForce Capture `.pfc` 数据立方体。图像通道按文件记录的扫描尺寸和物理单位 绘制成地图,并锁定纵横比。力曲线按 Approach(接近)与 Retract(回撤)两段 -分别绘制。具备偏转标定和弹簧常数时,纵轴为以纳牛计的力;仅具备偏转标定时, -纵轴为以纳米计的偏转量;无法转换为偏转量时,保留信号原始单位。独立斜坡曲线 -优先使用标定后的相对 Z 位移,其次使用采样时间,最后使用采样序号。 +分别绘制。有足够的元数据时,横轴显示 **Relative Z (nm)**(相对 Z 位移): +独立曲线按线性斜坡重建,PeakForce Capture 曲线按正弦斜坡重建。相对 Z 表示 +压电执行器的位移,不是针尖与样品的间距,也不是压痕深度。相对 Z 不可用时, +横轴显示由采样周期计算的 **Branch time (s)**(分支时间);没有采样周期时则 +使用采样序号。 -选择 **Analyze → AFM Force Fit → Fit Approach** 或 **Fit Retract**。只拟合局部时, -用 **Analyze → Analysis Range** 在力曲线图上拖选区间。默认模型为 **Linear**。 -点击 **Run AFM Fit**,拟合曲线会叠加在原图的拟合区间内,不会打开新页面或表格。 -拟合点、参数和收敛状态随图表一同保存到项目。 +只有能从文件获得已标定的偏转量和有效的悬臂弹簧常数时,纵轴才显示以纳牛计的 +力。没有可用的弹簧常数时,显示以纳米计的偏转量。无法转换为偏转量时,保留保存的 +信号及其单位。 + +选择 **Analyze → AFM Force Fit → Fit Approach** 或 **Fit Retract**。拟合面板会显示 +所选分支、绘图坐标及单位,以及所用的标定或未以力显示信号的原因。这是对绘图数值的 +经验拟合,不推断接触点,也不计算模量。 + +只拟合局部时,用 **Analyze → Analysis Range** 在曲线图上拖选区间。默认模型为 +**Linear**。点击 **Run AFM Fit**,拟合曲线会叠加在原图的拟合区间内,不会打开 +新页面或表格。拟合点、参数和收敛状态随图表一同保存到项目。 取消勾选 **Overlay on source plot** 可只计算结果,不改变原图显示。拟合后,可在 **Output** 菜单中切换原图叠加、复制带拟合线的图、创建残差图,或打开包含观测值、 -预测值和残差的新表格。**Zoom to Fit Range** 可在原图上放大拟合区间。Z 是压电 -执行器位移,不是针尖与样品间距或压痕深度;该拟合不推断接触点,也不计算模量。 +预测值和残差的新表格。**Zoom to Fit Range** 可在原图上放大拟合区间。 PeakForce Capture 文件旁通常保存着一个 AllImages `.spm` 导出文件。Plotium 会 找到这个配套文件,核对其图像网格与力网格一致后,把两者作为一个数据集导入;