Skip to main content

crisol_plot/plot/measure/
curve.rs

1//! The curve-vs-chord area measurement.
2
3use egui::{Pos2, Rect, pos2, vec2};
4
5use super::{DistanceSummary, MeasurementAreaStyle, PlotMeasurement};
6use crate::plot::scene::{Dash, Measure, Prim, Scene};
7use crate::plot::transform::Transform;
8use crate::plot::{Plot, PlotState};
9use crisol_ui_kit::theme::Theme;
10
11/// The numbers behind a curve-vs-chord measurement.
12#[derive(Clone, Debug, PartialEq)]
13pub struct CurveAreaSummary {
14    /// Series name.
15    pub series: String,
16    /// Signed area between the curve and the chord (positive above the chord).
17    pub area: f64,
18    /// Absolute area between the curve and the chord.
19    pub absolute_area: f64,
20    /// The chord and its distance/slope/angle.
21    pub chord: DistanceSummary,
22    /// Length along the curve.
23    pub arc_length: f64,
24    /// Largest vertical distance between the curve and the chord.
25    pub max_deviation: f64,
26    /// Point where the curve is farthest from the chord.
27    pub max_deviation_at: [f64; 2],
28}
29
30/// Compute the curve-vs-chord summary for a [`PlotMeasurement::CurveArea`].
31pub fn curve_area_summary(
32    plot: &Plot<'_>,
33    state: &PlotState,
34    measurement: &PlotMeasurement,
35) -> Option<CurveAreaSummary> {
36    let PlotMeasurement::CurveArea {
37        series,
38        start,
39        end,
40        start_index,
41        end_index,
42    } = measurement
43    else {
44        return None;
45    };
46    let series = plot.visible(state).find(|candidate| candidate.name() == series)?;
47    let data = series.data();
48    if data.len() < 2 {
49        return None;
50    }
51    let max = data.len() - 1;
52    let (low, high) = if start_index <= end_index {
53        ((*start_index).min(max), (*end_index).min(max))
54    } else {
55        ((*end_index).min(max), (*start_index).min(max))
56    };
57    let mut points = data[low..=high]
58        .iter()
59        .copied()
60        .filter(|point| point[0].is_finite() && point[1].is_finite())
61        .collect::<Vec<_>>();
62    if points.len() < 2 {
63        return None;
64    }
65    points.sort_by(|a, b| a[0].total_cmp(&b[0]));
66    let (chord_start, chord_end) = if start[0] <= end[0] { (start, end) } else { (end, start) };
67    let chord = PlotMeasurement::distance(*chord_start, *chord_end).distance_summary()?;
68    let chord_dx = chord_end[0] - chord_start[0];
69    let chord_y = |x: f64| {
70        if chord_dx.abs() <= f64::EPSILON {
71            chord_start[1]
72        } else {
73            chord_start[1] + (x - chord_start[0]) * (chord_end[1] - chord_start[1]) / chord_dx
74        }
75    };
76    let mut area = 0.0;
77    let mut absolute_area = 0.0;
78    let mut arc_length = 0.0;
79    for pair in points.windows(2) {
80        let (a, b) = (pair[0], pair[1]);
81        let dx = b[0] - a[0];
82        let da = a[1] - chord_y(a[0]);
83        let db = b[1] - chord_y(b[0]);
84        let strip = dx * (da + db) * 0.5;
85        area += strip;
86        absolute_area += strip.abs();
87        arc_length += (dx * dx + (b[1] - a[1]).powi(2)).sqrt();
88    }
89    let mut max_deviation = 0.0;
90    let mut max_deviation_at = points[0];
91    for point in &points {
92        let deviation = (point[1] - chord_y(point[0])).abs();
93        if deviation > max_deviation {
94            max_deviation = deviation;
95            max_deviation_at = *point;
96        }
97    }
98    Some(CurveAreaSummary {
99        series: series.name().to_owned(),
100        area,
101        absolute_area,
102        chord,
103        arc_length,
104        max_deviation,
105        max_deviation_at,
106    })
107}
108
109pub(super) fn paint(
110    scene: &mut Scene,
111    measure: &Measure,
112    transform: &Transform,
113    plot: &Plot<'_>,
114    state: &PlotState,
115    theme: &Theme,
116    measurement: &PlotMeasurement,
117) {
118    let PlotMeasurement::CurveArea {
119        start_index, end_index, ..
120    } = measurement
121    else {
122        return;
123    };
124    let Some(summary) = curve_area_summary(plot, state, measurement) else {
125        return;
126    };
127    let Some(series) = plot.visible(state).find(|series| series.name() == summary.series) else {
128        return;
129    };
130    let data = series.data();
131    let max = data.len().saturating_sub(1);
132    let (low, high) = if start_index <= end_index {
133        ((*start_index).min(max), (*end_index).min(max))
134    } else {
135        ((*end_index).min(max), (*start_index).min(max))
136    };
137    let points = data[low..=high]
138        .iter()
139        .filter(|point| point[0].is_finite() && point[1].is_finite())
140        .map(|point| transform.to_screen(*point))
141        .collect::<Vec<_>>();
142    if points.len() < 2 {
143        return;
144    }
145    let chord_start = transform.to_screen(summary.chord.start);
146    let chord_end = transform.to_screen(summary.chord.end);
147    let mut polygon = points.clone();
148    polygon.push(chord_end);
149    polygon.push(chord_start);
150    scene.data.push(Prim::Polygon {
151        points: polygon,
152        color: theme.link.gamma_multiply(0.16),
153    });
154    scene.data.push(Prim::Line {
155        points: points.clone(),
156        width: 2.0,
157        color: theme.link,
158        dash: Dash::Solid,
159    });
160    scene.data.push(Prim::Line {
161        points: vec![chord_start, chord_end],
162        width: 1.2,
163        color: theme.warning,
164        dash: Dash::Dashed(5.0, 4.0),
165    });
166    for point in [chord_start, chord_end, transform.to_screen(summary.max_deviation_at)] {
167        scene.data.push(Prim::Circle {
168            center: point,
169            radius: 2.5,
170            fill: theme.warning,
171            stroke: None,
172        });
173    }
174    if !state.measurement.show_labels {
175        return;
176    }
177    let area = match state.measurement.area_style {
178        MeasurementAreaStyle::Signed => summary.area,
179        MeasurementAreaStyle::Absolute => summary.absolute_area,
180    };
181    let label = format!(
182        "{}  area={}  |area|={}",
183        summary.series,
184        number(area),
185        number(summary.absolute_area)
186    );
187    let chord = format!(
188        "chord={}  Δx={}  Δy={}  slope={}  {}°",
189        number(summary.chord.distance),
190        number(summary.chord.dx),
191        number(summary.chord.dy),
192        summary.chord.slope.map_or_else(|| "∞".to_owned(), number),
193        number(summary.chord.angle_deg)
194    );
195    let detail = format!(
196        "arc={}  max dev={} at ({}, {})",
197        number(summary.arc_length),
198        number(summary.max_deviation),
199        number(summary.max_deviation_at[0]),
200        number(summary.max_deviation_at[1])
201    );
202    let at = label_anchor(&points).unwrap_or_else(|| transform.frame.left_top()) + vec2(6.0, 6.0);
203    super::label_block(scene, measure, at, &[label, chord, detail], theme.link, theme);
204}
205
206fn label_anchor(points: &[Pos2]) -> Option<Pos2> {
207    let (mut min, mut max) = (points[0], points[0]);
208    for point in points {
209        min.x = min.x.min(point.x);
210        min.y = min.y.min(point.y);
211        max.x = max.x.max(point.x);
212        max.y = max.y.max(point.y);
213    }
214    let rect = Rect::from_min_max(min, max);
215    Some(pos2(rect.left(), rect.top()))
216}
217
218fn number(value: f64) -> String {
219    super::number(value)
220}