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 super::axis::Bounds;
8use super::{Plot, PlotState};
9
10mod curve;
11mod draw;
12
13pub use curve::{CurveAreaSummary, curve_area_summary};
14pub(super) use draw::paint;
15use draw::{label_block, number};
16
17/// How the area tool measures.
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum MeasurementMode {
23    /// Drag a rectangle and measure its area and the series inside it.
24    Rectangle,
25    /// Drag between two points on the same series and integrate the area between the
26    /// curve and the line through them. This is the default tool.
27    #[default]
28    CurveSegment,
29}
30
31/// Which area a curve-segment label shows first.
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum MeasurementAreaStyle {
37    /// Show the signed area (positive above the chord, negative below).
38    Signed,
39    /// Show the absolute area between the curve and the chord.
40    #[default]
41    Absolute,
42}
43
44/// Measurement settings owned by the chart configuration.
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct MeasurementConfig {
48    /// Rectangle or curve-segment area mode.
49    pub mode: MeasurementMode,
50    /// Which area the label emphasizes.
51    pub area_style: MeasurementAreaStyle,
52    /// Snap radius in points.
53    pub snap_radius: f32,
54    /// Draw measurement labels over the data.
55    pub show_labels: bool,
56}
57
58impl Default for MeasurementConfig {
59    fn default() -> Self {
60        Self {
61            mode: MeasurementMode::CurveSegment,
62            area_style: MeasurementAreaStyle::Absolute,
63            snap_radius: 14.0,
64            show_labels: true,
65        }
66    }
67}
68
69/// A persistent measurement drawn over the data.
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[derive(Clone, Debug, PartialEq)]
72#[non_exhaustive]
73pub enum PlotMeasurement {
74    /// A line between two data points.
75    Distance {
76        /// First point in data coordinates.
77        start: [f64; 2],
78        /// Second point in data coordinates.
79        end: [f64; 2],
80    },
81    /// A rectangular region in data coordinates.
82    Area {
83        /// Region corners, in any order.
84        bounds: Bounds,
85    },
86    /// The area between one curve segment and its chord, from `start` to `end`.
87    CurveArea {
88        /// Series the segment belongs to.
89        series: String,
90        /// First point in data coordinates.
91        start: [f64; 2],
92        /// Second point in data coordinates.
93        end: [f64; 2],
94        /// Index of `start` in the series data.
95        start_index: usize,
96        /// Index of `end` in the series data.
97        end_index: usize,
98    },
99}
100
101impl PlotMeasurement {
102    /// A distance between two points.
103    pub fn distance(start: [f64; 2], end: [f64; 2]) -> Self {
104        Self::Distance { start, end }
105    }
106
107    /// A rectangular region.
108    pub fn area(bounds: Bounds) -> Self {
109        Self::Area { bounds }
110    }
111
112    /// The area between a curve segment and its chord.
113    pub fn curve_area(
114        series: impl Into<String>,
115        start: [f64; 2],
116        end: [f64; 2],
117        start_index: usize,
118        end_index: usize,
119    ) -> Self {
120        Self::CurveArea {
121            series: series.into(),
122            start,
123            end,
124            start_index,
125            end_index,
126        }
127    }
128
129    /// The region this measurement covers.
130    pub fn bounds(&self) -> Bounds {
131        match self {
132            Self::Distance { start, end } => Bounds::from_corners(*start, *end),
133            Self::Area { bounds } => *bounds,
134            Self::CurveArea { start, end, .. } => Bounds::from_corners(*start, *end),
135        }
136    }
137
138    /// The distance, slope, and angle summary for [`Self::Distance`].
139    pub fn distance_summary(&self) -> Option<DistanceSummary> {
140        let Self::Distance { start, end } = self else {
141            return None;
142        };
143        let dx = end[0] - start[0];
144        let dy = end[1] - start[1];
145        Some(DistanceSummary {
146            start: *start,
147            end: *end,
148            dx,
149            dy,
150            distance: dx.hypot(dy),
151            slope: (dx != 0.0).then_some(dy / dx),
152            angle_deg: dy.atan2(dx).to_degrees(),
153        })
154    }
155}
156
157/// The numbers behind a distance measurement.
158#[derive(Clone, Copy, Debug, PartialEq)]
159pub struct DistanceSummary {
160    /// First point.
161    pub start: [f64; 2],
162    /// Second point.
163    pub end: [f64; 2],
164    /// Horizontal difference.
165    pub dx: f64,
166    /// Vertical difference.
167    pub dy: f64,
168    /// Euclidean distance.
169    pub distance: f64,
170    /// `dy / dx`, or `None` for a vertical line.
171    pub slope: Option<f64>,
172    /// Direction in degrees, from the positive x axis.
173    pub angle_deg: f64,
174}
175
176/// One local extremum of a series inside a region.
177#[derive(Clone, Copy, Debug, PartialEq)]
178pub struct Extremum {
179    /// Index in the series' original data.
180    pub index: usize,
181    /// Point in data coordinates.
182    pub point: [f64; 2],
183    /// Slope through the neighboring points, when both sides exist.
184    pub slope: Option<f64>,
185}
186
187/// What one series contributes to an area measurement.
188#[derive(Clone, Debug, PartialEq)]
189pub struct SeriesMeasurement {
190    /// Series name.
191    pub series: String,
192    /// Lowest point inside the region.
193    pub min: Option<Extremum>,
194    /// Highest point inside the region.
195    pub max: Option<Extremum>,
196    /// Trapezoidal integral over the region, in data units.
197    pub integral: f64,
198    /// Mean y of the points inside the region.
199    pub mean: f64,
200    /// Slope between the first and last in-range points, by increasing x.
201    pub endpoint_slope: Option<f64>,
202}
203
204/// The statistics of every visible series inside `bounds`.
205pub fn region_measurements(plot: &Plot<'_>, state: &PlotState, bounds: Bounds) -> Vec<SeriesMeasurement> {
206    plot.visible(state)
207        .filter(|series| !series.is_reference())
208        .filter_map(|series| {
209            let mut points: Vec<(usize, [f64; 2])> = series
210                .data()
211                .iter()
212                .enumerate()
213                .filter(|(_, point)| {
214                    point[0].is_finite() && point[1].is_finite() && point[0] >= bounds.min_x && point[0] <= bounds.max_x
215                })
216                .map(|(index, point)| (index, *point))
217                .collect();
218            if points.is_empty() {
219                return None;
220            }
221            points.sort_by(|a, b| a.1[0].total_cmp(&b.1[0]));
222            let mut min: Option<(usize, [f64; 2])> = None;
223            let mut max: Option<(usize, [f64; 2])> = None;
224            let mut sum = 0.0;
225            for (position, (_, point)) in points.iter().enumerate() {
226                sum += point[1];
227                if min.is_none_or(|(_, current)| point[1] < current[1]) {
228                    min = Some((position, *point));
229                }
230                if max.is_none_or(|(_, current)| point[1] > current[1]) {
231                    max = Some((position, *point));
232                }
233            }
234            let integral = points
235                .windows(2)
236                .map(|pair| {
237                    let (a, b) = (pair[0].1, pair[1].1);
238                    (b[0] - a[0]) * (a[1] + b[1]) * 0.5
239                })
240                .sum::<f64>();
241            let slope_at = |position: usize| {
242                let point = points[position].1;
243                let left = position.checked_sub(1).and_then(|index| points.get(index));
244                let right = points.get(position + 1);
245                match (left, right) {
246                    (Some(left), Some(right)) => {
247                        let dx = right.1[0] - left.1[0];
248                        (dx != 0.0).then_some((right.1[1] - left.1[1]) / dx)
249                    }
250                    (Some(left), None) => {
251                        let dx = point[0] - left.1[0];
252                        (dx != 0.0).then_some((point[1] - left.1[1]) / dx)
253                    }
254                    (None, Some(right)) => {
255                        let dx = right.1[0] - point[0];
256                        (dx != 0.0).then_some((right.1[1] - point[1]) / dx)
257                    }
258                    (None, None) => None,
259                }
260            };
261            let extremum = |entry: Option<(usize, [f64; 2])>| {
262                entry.map(|(position, point)| Extremum {
263                    index: points[position].0,
264                    point,
265                    slope: slope_at(position),
266                })
267            };
268            let endpoint_slope = match (points.first(), points.last()) {
269                (Some(first), Some(last)) if first.1[0] != last.1[0] => {
270                    Some((last.1[1] - first.1[1]) / (last.1[0] - first.1[0]))
271                }
272                _ => None,
273            };
274            Some(SeriesMeasurement {
275                series: series.name().to_owned(),
276                min: extremum(min),
277                max: extremum(max),
278                integral: integral.abs(),
279                mean: sum / points.len() as f64,
280                endpoint_slope,
281            })
282        })
283        .collect()
284}
285
286#[cfg(test)]
287mod tests;