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. Returns each label box, for dragging.
289pub(super) fn paint(
290    scene: &mut Scene,
291    measure: &Measure,
292    transform: &Transform,
293    plot: &Plot<'_>,
294    state: &PlotState,
295    theme: &Theme,
296) -> Vec<(usize, Rect)> {
297    let mut labels = Vec::new();
298    for (index, measurement) in state.measurements.iter().enumerate() {
299        let offset = state.measurement_label_offset(index);
300        match measurement {
301            PlotMeasurement::Distance { start, end } => {
302                let a = transform.to_screen(*start);
303                let b = transform.to_screen(*end);
304                if !a.is_finite() || !b.is_finite() {
305                    continue;
306                }
307                scene.data.push(Prim::Line {
308                    points: vec![a, b],
309                    width: 1.5,
310                    color: theme.warning,
311                    dash: Dash::Dashed(5.0, 4.0),
312                });
313                for point in [a, b] {
314                    scene.data.push(Prim::Circle {
315                        center: point,
316                        radius: 3.0,
317                        fill: theme.warning,
318                        stroke: None,
319                    });
320                }
321                if let Some(summary) = measurement.distance_summary() {
322                    let label = format!(
323                        "d={}  Δx={}  Δy={}  slope={}  {}°",
324                        number(summary.distance),
325                        number(summary.dx),
326                        number(summary.dy),
327                        summary.slope.map_or_else(|| "∞".to_owned(), number),
328                        number(summary.angle_deg)
329                    );
330                    if state.measurement.show_labels {
331                        let rect = label_block(
332                            scene,
333                            measure,
334                            pos2((a.x + b.x) * 0.5, (a.y + b.y) * 0.5) + vec2(8.0, -8.0) + offset,
335                            &[label],
336                            theme.warning,
337                            theme,
338                        );
339                        labels.push((index, rect));
340                    }
341                }
342            }
343            PlotMeasurement::Area { bounds } => {
344                let a = transform.to_screen([bounds.min_x, bounds.min_y]);
345                let b = transform.to_screen([bounds.max_x, bounds.max_y]);
346                if !a.is_finite() || !b.is_finite() {
347                    continue;
348                }
349                let rect = Rect::from_two_pos(a, b).intersect(transform.frame);
350                if rect.width() <= 0.0 || rect.height() <= 0.0 {
351                    continue;
352                }
353                scene.data.push(Prim::Rect {
354                    rect,
355                    radius: 0.0,
356                    fill: theme.link.gamma_multiply(0.08),
357                    stroke: Some((1.0, theme.link)),
358                });
359                let width = bounds.max_x - bounds.min_x;
360                let height = bounds.max_y - bounds.min_y;
361                let mut lines = vec![format!(
362                    "area={}  Δx={}  Δy={}",
363                    number(width * height),
364                    number(width),
365                    number(height)
366                )];
367                let stats = region_measurements(plot, state, *bounds);
368                for (index, series) in stats.iter().enumerate() {
369                    if index == 4 {
370                        lines.push("…".to_owned());
371                        break;
372                    }
373                    lines.push(format!(
374                        "{}: min={} max={} ∫={}",
375                        series.series,
376                        series
377                            .min
378                            .map_or_else(|| "—".to_owned(), |value| number(value.point[1])),
379                        series
380                            .max
381                            .map_or_else(|| "—".to_owned(), |value| number(value.point[1])),
382                        number(series.integral)
383                    ));
384                    draw_extrema(scene, measure, transform, series, theme, state.measurement.show_labels);
385                }
386                if state.measurement.show_labels {
387                    let rect = label_block(
388                        scene,
389                        measure,
390                        rect.left_top() + vec2(6.0, 6.0) + offset,
391                        &lines,
392                        theme.link,
393                        theme,
394                    );
395                    labels.push((index, rect));
396                }
397            }
398            PlotMeasurement::CurveArea { .. } => {
399                if let Some(rect) = curve::paint(scene, measure, transform, plot, state, theme, measurement, offset) {
400                    labels.push((index, rect));
401                }
402            }
403        }
404    }
405    labels
406}
407
408fn draw_extrema(
409    scene: &mut Scene,
410    measure: &Measure,
411    transform: &Transform,
412    series: &SeriesMeasurement,
413    theme: &Theme,
414    show_labels: bool,
415) {
416    for (extremum, color, name) in [(series.min, theme.success, "min"), (series.max, theme.danger, "max")] {
417        let Some(extremum) = extremum else {
418            continue;
419        };
420        let position = transform.to_screen(extremum.point);
421        if !position.is_finite() {
422            continue;
423        }
424        scene.data.push(Prim::Circle {
425            center: position,
426            radius: 2.5,
427            fill: color,
428            stroke: None,
429        });
430        let slope = extremum.slope.map_or_else(|| "—".to_owned(), number);
431        let text = format!("{name} {} · slope {slope}", number(extremum.point[1]));
432        let (width, height, _) = measure.text(&text, 10.0);
433        if show_labels {
434            scene
435                .over
436                .push(measure.label(position + vec2(4.0, -height), Align2::LEFT_BOTTOM, &text, 10.0, color));
437        }
438        let _ = width;
439    }
440}
441
442fn label_block(
443    scene: &mut Scene,
444    measure: &Measure,
445    at: Pos2,
446    lines: &[String],
447    color: Color32,
448    theme: &Theme,
449) -> Rect {
450    let (width, height) = lines
451        .iter()
452        .map(|line| measure.text(line, 10.0))
453        .fold((0.0_f32, 0.0_f32), |(width, height), (line_width, line_height, _)| {
454            (width.max(line_width), height + line_height + 2.0)
455        });
456    let frame = scene.frame;
457    let size = vec2(width + 10.0, height + 6.0);
458    let mut origin = pos2(at.x, at.y);
459    if origin.x + size.x > frame.right() - 2.0 {
460        origin.x = frame.right() - size.x - 2.0;
461    }
462    if origin.y + size.y > frame.bottom() - 2.0 {
463        origin.y = frame.bottom() - size.y - 2.0;
464    }
465    origin.x = origin.x.max(frame.left() + 2.0);
466    origin.y = origin.y.max(frame.top() + 2.0);
467    let rect = Rect::from_min_size(origin, size);
468    scene.over.push(Prim::Rect {
469        rect,
470        radius: 3.0,
471        fill: theme.surface.gamma_multiply(0.94),
472        stroke: Some((1.0, color.gamma_multiply(0.6))),
473    });
474    let mut y = rect.top() + 3.0;
475    for line in lines {
476        scene
477            .over
478            .push(measure.label(pos2(rect.left() + 5.0, y), Align2::LEFT_TOP, line, 10.0, theme.text));
479        let (_, line_height, _) = measure.text(line, 10.0);
480        y += line_height + 2.0;
481    }
482    rect
483}
484
485/// A compact number for labels: fixed decimals for the common range, scientific
486/// notation for very large or very small values, and thousands separators.
487fn number(value: f64) -> String {
488    if !value.is_finite() {
489        return "—".to_owned();
490    }
491    if value == 0.0 {
492        return "0".to_owned();
493    }
494    let magnitude = value.abs();
495    if !(1.0e-3..1.0e6).contains(&magnitude) {
496        return format!("{value:.3e}");
497    }
498    let decimals = if magnitude >= 1000.0 {
499        1
500    } else if magnitude >= 10.0 {
501        2
502    } else {
503        4
504    };
505    let mut text = format!("{value:.decimals$}");
506    if text.contains('.') {
507        text = text.trim_end_matches('0').trim_end_matches('.').to_owned();
508    }
509    text
510}
511
512#[cfg(test)]
513mod tests;