Skip to main content

crisol_plot/plot/
measure.rs

1//! Distance and area measurements over a plot.
2//!
3//! A measurement is stored in data coordinates in [`PlotState`], so it survives zoom,
4//! pan, and a saved workspace. The plot draws the last frame's geometry and the public
5//! summaries expose the same numbers to the application.
6
7use egui::{Align2, Color32, Pos2, Rect, pos2, vec2};
8
9use super::axis::Bounds;
10use super::scene::{Dash, Measure, Prim, Scene};
11use super::transform::Transform;
12use super::{Plot, PlotState};
13use crisol_ui_kit::theme::Theme;
14
15mod curve;
16
17pub use curve::{CurveAreaSummary, curve_area_summary};
18
19/// How the area tool measures.
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum MeasurementMode {
25    /// Drag a rectangle and measure its area and the series inside it.
26    Rectangle,
27    /// Drag between two points on the same series and integrate the area between the
28    /// curve and the line through them. This is the default tool.
29    #[default]
30    CurveSegment,
31}
32
33/// Which area a curve-segment label shows first.
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum MeasurementAreaStyle {
39    /// Show the signed area (positive above the chord, negative below).
40    Signed,
41    /// Show the absolute area between the curve and the chord.
42    #[default]
43    Absolute,
44}
45
46/// Measurement settings owned by the chart configuration.
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct MeasurementConfig {
50    /// Rectangle or curve-segment area mode.
51    pub mode: MeasurementMode,
52    /// Which area the label emphasizes.
53    pub area_style: MeasurementAreaStyle,
54    /// Snap radius in points.
55    pub snap_radius: f32,
56    /// Draw measurement labels over the data.
57    pub show_labels: bool,
58}
59
60impl Default for MeasurementConfig {
61    fn default() -> Self {
62        Self {
63            mode: MeasurementMode::CurveSegment,
64            area_style: MeasurementAreaStyle::Absolute,
65            snap_radius: 14.0,
66            show_labels: true,
67        }
68    }
69}
70
71/// A persistent measurement drawn over the data.
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73#[derive(Clone, Debug, PartialEq)]
74#[non_exhaustive]
75pub enum PlotMeasurement {
76    /// A line between two data points.
77    Distance {
78        /// First point in data coordinates.
79        start: [f64; 2],
80        /// Second point in data coordinates.
81        end: [f64; 2],
82    },
83    /// A rectangular region in data coordinates.
84    Area {
85        /// Region corners, in any order.
86        bounds: Bounds,
87    },
88    /// The area between one curve segment and its chord, from `start` to `end`.
89    CurveArea {
90        /// Series the segment belongs to.
91        series: String,
92        /// First point in data coordinates.
93        start: [f64; 2],
94        /// Second point in data coordinates.
95        end: [f64; 2],
96        /// Index of `start` in the series data.
97        start_index: usize,
98        /// Index of `end` in the series data.
99        end_index: usize,
100    },
101}
102
103impl PlotMeasurement {
104    /// A distance between two points.
105    pub fn distance(start: [f64; 2], end: [f64; 2]) -> Self {
106        Self::Distance { start, end }
107    }
108
109    /// A rectangular region.
110    pub fn area(bounds: Bounds) -> Self {
111        Self::Area { bounds }
112    }
113
114    /// The area between a curve segment and its chord.
115    pub fn curve_area(
116        series: impl Into<String>,
117        start: [f64; 2],
118        end: [f64; 2],
119        start_index: usize,
120        end_index: usize,
121    ) -> Self {
122        Self::CurveArea {
123            series: series.into(),
124            start,
125            end,
126            start_index,
127            end_index,
128        }
129    }
130
131    /// The region this measurement covers.
132    pub fn bounds(&self) -> Bounds {
133        match self {
134            Self::Distance { start, end } => Bounds::from_corners(*start, *end),
135            Self::Area { bounds } => *bounds,
136            Self::CurveArea { start, end, .. } => Bounds::from_corners(*start, *end),
137        }
138    }
139
140    /// The distance, slope, and angle summary for [`Self::Distance`].
141    pub fn distance_summary(&self) -> Option<DistanceSummary> {
142        let Self::Distance { start, end } = self else {
143            return None;
144        };
145        let dx = end[0] - start[0];
146        let dy = end[1] - start[1];
147        Some(DistanceSummary {
148            start: *start,
149            end: *end,
150            dx,
151            dy,
152            distance: dx.hypot(dy),
153            slope: (dx != 0.0).then_some(dy / dx),
154            angle_deg: dy.atan2(dx).to_degrees(),
155        })
156    }
157}
158
159/// The numbers behind a distance measurement.
160#[derive(Clone, Copy, Debug, PartialEq)]
161pub struct DistanceSummary {
162    /// First point.
163    pub start: [f64; 2],
164    /// Second point.
165    pub end: [f64; 2],
166    /// Horizontal difference.
167    pub dx: f64,
168    /// Vertical difference.
169    pub dy: f64,
170    /// Euclidean distance.
171    pub distance: f64,
172    /// `dy / dx`, or `None` for a vertical line.
173    pub slope: Option<f64>,
174    /// Direction in degrees, from the positive x axis.
175    pub angle_deg: f64,
176}
177
178/// One local extremum of a series inside a region.
179#[derive(Clone, Copy, Debug, PartialEq)]
180pub struct Extremum {
181    /// Index in the series' original data.
182    pub index: usize,
183    /// Point in data coordinates.
184    pub point: [f64; 2],
185    /// Slope through the neighboring points, when both sides exist.
186    pub slope: Option<f64>,
187}
188
189/// What one series contributes to an area measurement.
190#[derive(Clone, Debug, PartialEq)]
191pub struct SeriesMeasurement {
192    /// Series name.
193    pub series: String,
194    /// Lowest point inside the region.
195    pub min: Option<Extremum>,
196    /// Highest point inside the region.
197    pub max: Option<Extremum>,
198    /// Trapezoidal integral over the region, in data units.
199    pub integral: f64,
200    /// Mean y of the points inside the region.
201    pub mean: f64,
202    /// Slope between the first and last in-range points, by increasing x.
203    pub endpoint_slope: Option<f64>,
204}
205
206/// The statistics of every visible series inside `bounds`.
207pub fn region_measurements(plot: &Plot<'_>, state: &PlotState, bounds: Bounds) -> Vec<SeriesMeasurement> {
208    plot.visible(state)
209        .filter(|series| !series.is_reference())
210        .filter_map(|series| {
211            let mut points: Vec<(usize, [f64; 2])> = series
212                .data()
213                .iter()
214                .enumerate()
215                .filter(|(_, point)| {
216                    point[0].is_finite() && point[1].is_finite() && point[0] >= bounds.min_x && point[0] <= bounds.max_x
217                })
218                .map(|(index, point)| (index, *point))
219                .collect();
220            if points.is_empty() {
221                return None;
222            }
223            points.sort_by(|a, b| a.1[0].total_cmp(&b.1[0]));
224            let mut min: Option<(usize, [f64; 2])> = None;
225            let mut max: Option<(usize, [f64; 2])> = None;
226            let mut sum = 0.0;
227            for (position, (_, point)) in points.iter().enumerate() {
228                sum += point[1];
229                if min.is_none_or(|(_, current)| point[1] < current[1]) {
230                    min = Some((position, *point));
231                }
232                if max.is_none_or(|(_, current)| point[1] > current[1]) {
233                    max = Some((position, *point));
234                }
235            }
236            let integral = points
237                .windows(2)
238                .map(|pair| {
239                    let (a, b) = (pair[0].1, pair[1].1);
240                    (b[0] - a[0]) * (a[1] + b[1]) * 0.5
241                })
242                .sum::<f64>();
243            let slope_at = |position: usize| {
244                let point = points[position].1;
245                let left = position.checked_sub(1).and_then(|index| points.get(index));
246                let right = points.get(position + 1);
247                match (left, right) {
248                    (Some(left), Some(right)) => {
249                        let dx = right.1[0] - left.1[0];
250                        (dx != 0.0).then_some((right.1[1] - left.1[1]) / dx)
251                    }
252                    (Some(left), None) => {
253                        let dx = point[0] - left.1[0];
254                        (dx != 0.0).then_some((point[1] - left.1[1]) / dx)
255                    }
256                    (None, Some(right)) => {
257                        let dx = right.1[0] - point[0];
258                        (dx != 0.0).then_some((right.1[1] - point[1]) / dx)
259                    }
260                    (None, None) => None,
261                }
262            };
263            let extremum = |entry: Option<(usize, [f64; 2])>| {
264                entry.map(|(position, point)| Extremum {
265                    index: points[position].0,
266                    point,
267                    slope: slope_at(position),
268                })
269            };
270            let endpoint_slope = match (points.first(), points.last()) {
271                (Some(first), Some(last)) if first.1[0] != last.1[0] => {
272                    Some((last.1[1] - first.1[1]) / (last.1[0] - first.1[0]))
273                }
274                _ => None,
275            };
276            Some(SeriesMeasurement {
277                series: series.name().to_owned(),
278                min: extremum(min),
279                max: extremum(max),
280                integral: integral.abs(),
281                mean: sum / points.len() as f64,
282                endpoint_slope,
283            })
284        })
285        .collect()
286}
287
288/// Draw every measurement and its labels.
289pub(super) fn paint(
290    scene: &mut Scene,
291    measure: &Measure,
292    transform: &Transform,
293    plot: &Plot<'_>,
294    state: &PlotState,
295    theme: &Theme,
296) {
297    for measurement in &state.measurements {
298        match measurement {
299            PlotMeasurement::Distance { start, end } => {
300                let a = transform.to_screen(*start);
301                let b = transform.to_screen(*end);
302                if !a.is_finite() || !b.is_finite() {
303                    continue;
304                }
305                scene.data.push(Prim::Line {
306                    points: vec![a, b],
307                    width: 1.5,
308                    color: theme.warning,
309                    dash: Dash::Dashed(5.0, 4.0),
310                });
311                for point in [a, b] {
312                    scene.data.push(Prim::Circle {
313                        center: point,
314                        radius: 3.0,
315                        fill: theme.warning,
316                        stroke: None,
317                    });
318                }
319                if let Some(summary) = measurement.distance_summary() {
320                    let label = format!(
321                        "d={}  Δx={}  Δy={}  slope={}  {}°",
322                        number(summary.distance),
323                        number(summary.dx),
324                        number(summary.dy),
325                        summary.slope.map_or_else(|| "∞".to_owned(), number),
326                        number(summary.angle_deg)
327                    );
328                    if state.measurement.show_labels {
329                        label_block(
330                            scene,
331                            measure,
332                            pos2((a.x + b.x) * 0.5, (a.y + b.y) * 0.5) + vec2(8.0, -8.0),
333                            &[label],
334                            theme.warning,
335                            theme,
336                        );
337                    }
338                }
339            }
340            PlotMeasurement::Area { bounds } => {
341                let a = transform.to_screen([bounds.min_x, bounds.min_y]);
342                let b = transform.to_screen([bounds.max_x, bounds.max_y]);
343                if !a.is_finite() || !b.is_finite() {
344                    continue;
345                }
346                let rect = Rect::from_two_pos(a, b).intersect(transform.frame);
347                if rect.width() <= 0.0 || rect.height() <= 0.0 {
348                    continue;
349                }
350                scene.data.push(Prim::Rect {
351                    rect,
352                    radius: 0.0,
353                    fill: theme.link.gamma_multiply(0.08),
354                    stroke: Some((1.0, theme.link)),
355                });
356                let width = bounds.max_x - bounds.min_x;
357                let height = bounds.max_y - bounds.min_y;
358                let mut lines = vec![format!(
359                    "area={}  Δx={}  Δy={}",
360                    number(width * height),
361                    number(width),
362                    number(height)
363                )];
364                let stats = region_measurements(plot, state, *bounds);
365                for (index, series) in stats.iter().enumerate() {
366                    if index == 4 {
367                        lines.push("…".to_owned());
368                        break;
369                    }
370                    lines.push(format!(
371                        "{}: min={} max={} ∫={}",
372                        series.series,
373                        series
374                            .min
375                            .map_or_else(|| "—".to_owned(), |value| number(value.point[1])),
376                        series
377                            .max
378                            .map_or_else(|| "—".to_owned(), |value| number(value.point[1])),
379                        number(series.integral)
380                    ));
381                    draw_extrema(scene, measure, transform, series, theme, state.measurement.show_labels);
382                }
383                if state.measurement.show_labels {
384                    label_block(
385                        scene,
386                        measure,
387                        rect.left_top() + vec2(6.0, 6.0),
388                        &lines,
389                        theme.link,
390                        theme,
391                    );
392                }
393            }
394            PlotMeasurement::CurveArea { .. } => {
395                curve::paint(scene, measure, transform, plot, state, theme, measurement);
396            }
397        }
398    }
399}
400
401fn draw_extrema(
402    scene: &mut Scene,
403    measure: &Measure,
404    transform: &Transform,
405    series: &SeriesMeasurement,
406    theme: &Theme,
407    show_labels: bool,
408) {
409    for (extremum, color, name) in [(series.min, theme.success, "min"), (series.max, theme.danger, "max")] {
410        let Some(extremum) = extremum else {
411            continue;
412        };
413        let position = transform.to_screen(extremum.point);
414        if !position.is_finite() {
415            continue;
416        }
417        scene.data.push(Prim::Circle {
418            center: position,
419            radius: 2.5,
420            fill: color,
421            stroke: None,
422        });
423        let slope = extremum.slope.map_or_else(|| "—".to_owned(), number);
424        let text = format!("{name} {} · slope {slope}", number(extremum.point[1]));
425        let (width, height, _) = measure.text(&text, 10.0);
426        if show_labels {
427            scene
428                .over
429                .push(measure.label(position + vec2(4.0, -height), Align2::LEFT_BOTTOM, &text, 10.0, color));
430        }
431        let _ = width;
432    }
433}
434
435fn label_block(scene: &mut Scene, measure: &Measure, at: Pos2, lines: &[String], color: Color32, theme: &Theme) {
436    let (width, height) = lines
437        .iter()
438        .map(|line| measure.text(line, 10.0))
439        .fold((0.0_f32, 0.0_f32), |(width, height), (line_width, line_height, _)| {
440            (width.max(line_width), height + line_height + 2.0)
441        });
442    let frame = scene.frame;
443    let size = vec2(width + 10.0, height + 6.0);
444    let mut origin = pos2(at.x, at.y);
445    if origin.x + size.x > frame.right() - 2.0 {
446        origin.x = frame.right() - size.x - 2.0;
447    }
448    if origin.y + size.y > frame.bottom() - 2.0 {
449        origin.y = frame.bottom() - size.y - 2.0;
450    }
451    origin.x = origin.x.max(frame.left() + 2.0);
452    origin.y = origin.y.max(frame.top() + 2.0);
453    let rect = Rect::from_min_size(origin, size);
454    scene.over.push(Prim::Rect {
455        rect,
456        radius: 3.0,
457        fill: theme.surface.gamma_multiply(0.94),
458        stroke: Some((1.0, color.gamma_multiply(0.6))),
459    });
460    let mut y = rect.top() + 3.0;
461    for line in lines {
462        scene
463            .over
464            .push(measure.label(pos2(rect.left() + 5.0, y), Align2::LEFT_TOP, line, 10.0, theme.text));
465        let (_, line_height, _) = measure.text(line, 10.0);
466        y += line_height + 2.0;
467    }
468}
469
470/// A compact number for labels: fixed decimals for the common range, scientific
471/// notation for very large or very small values, and thousands separators.
472fn number(value: f64) -> String {
473    if !value.is_finite() {
474        return "—".to_owned();
475    }
476    if value == 0.0 {
477        return "0".to_owned();
478    }
479    let magnitude = value.abs();
480    if !(1.0e-3..1.0e6).contains(&magnitude) {
481        return format!("{value:.3e}");
482    }
483    let decimals = if magnitude >= 1000.0 {
484        1
485    } else if magnitude >= 10.0 {
486        2
487    } else {
488        4
489    };
490    let mut text = format!("{value:.decimals$}");
491    if text.contains('.') {
492        text = text.trim_end_matches('0').trim_end_matches('.').to_owned();
493    }
494    text
495}
496
497#[cfg(test)]
498mod tests;