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