1use 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#[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 Rectangle,
25 #[default]
28 CurveSegment,
29}
30
31#[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 Signed,
39 #[default]
41 Absolute,
42}
43
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct MeasurementConfig {
48 pub mode: MeasurementMode,
50 pub area_style: MeasurementAreaStyle,
52 pub snap_radius: f32,
54 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#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[derive(Clone, Debug, PartialEq)]
72#[non_exhaustive]
73pub enum PlotMeasurement {
74 Distance {
76 start: [f64; 2],
78 end: [f64; 2],
80 },
81 Area {
83 bounds: Bounds,
85 },
86 CurveArea {
88 series: String,
90 start: [f64; 2],
92 end: [f64; 2],
94 start_index: usize,
96 end_index: usize,
98 },
99}
100
101impl PlotMeasurement {
102 pub fn distance(start: [f64; 2], end: [f64; 2]) -> Self {
104 Self::Distance { start, end }
105 }
106
107 pub fn area(bounds: Bounds) -> Self {
109 Self::Area { bounds }
110 }
111
112 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
159pub struct DistanceSummary {
160 pub start: [f64; 2],
162 pub end: [f64; 2],
164 pub dx: f64,
166 pub dy: f64,
168 pub distance: f64,
170 pub slope: Option<f64>,
172 pub angle_deg: f64,
174}
175
176#[derive(Clone, Copy, Debug, PartialEq)]
178pub struct Extremum {
179 pub index: usize,
181 pub point: [f64; 2],
183 pub slope: Option<f64>,
185}
186
187#[derive(Clone, Debug, PartialEq)]
189pub struct SeriesMeasurement {
190 pub series: String,
192 pub min: Option<Extremum>,
194 pub max: Option<Extremum>,
196 pub integral: f64,
198 pub mean: f64,
200 pub endpoint_slope: Option<f64>,
202}
203
204pub 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;