Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 1 addition & 9 deletions crates/app/src/ui/canvas/interactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions crates/app/src/ui/canvas/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions crates/app/src/ui/canvas/selection_status.rs
Original file line number Diff line number Diff line change
@@ -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)
}
43 changes: 33 additions & 10 deletions crates/app/src/ui/commands_afm_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -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| {
Expand Down Expand Up @@ -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);
Expand Down
108 changes: 94 additions & 14 deletions crates/app/src/ui/tools/afm_fit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
}
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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));
}
Expand All @@ -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);
Expand Down
Loading
Loading