Skip to main content

crisol_plot_core/
decimate.rs

1//! Fewer points with the same picture: thinning of unsorted lines, one marker per
2//! screen cell for dense scatter, and Ramer–Douglas–Peucker simplification of the
3//! screen polylines. The tolerances are below what a display can show.
4
5use crate::transform::{ScreenPoint, Transform};
6
7/// Points of an unsorted line closer than this to the last drawn point are skipped.
8pub const LINE_SPACING: f32 = 0.5;
9/// Scatter markers keep one per square cell this fraction of their radius wide: a
10/// marker in an occupied cell overlaps the first one almost entirely, and the outline of
11/// a dense band of markers moves by at most 7 % of the radius.
12pub const MARKER_SPACING: f32 = 0.75;
13
14/// Vertices of a line closer than this (in points) to the straight path between their
15/// neighbors are dropped: invisible, and a smooth curve of thousands of samples
16/// tessellates as a few hundred vertices.
17pub const SIMPLIFY_TOLERANCE: f32 = 0.3;
18
19/// Ramer–Douglas–Peucker on screen positions: keep the ends and every vertex farther
20/// than `tolerance` from the chord of the stretch it lies in.
21pub fn simplify(points: Vec<ScreenPoint>, tolerance: f32) -> Vec<ScreenPoint> {
22    if points.len() < 3 {
23        return points;
24    }
25    let mut keep = vec![false; points.len()];
26    keep[0] = true;
27    keep[points.len() - 1] = true;
28    let mut stack = vec![(0, points.len() - 1)];
29    let tolerance_sq = tolerance * tolerance;
30    while let Some((first, last)) = stack.pop() {
31        if last <= first + 1 {
32            continue;
33        }
34        let (a, b) = (points[first], points[last]);
35        let chord = b - a;
36        let length_sq = chord.length_sq();
37        let mut farthest = (0.0, first);
38        for (index, point) in points.iter().enumerate().take(last).skip(first + 1) {
39            let offset = *point - a;
40            // Distance to the segment (to the end point when the chord is degenerate).
41            let distance_sq = if length_sq <= f32::EPSILON {
42                offset.length_sq()
43            } else {
44                let t = (offset.dot(chord) / length_sq).clamp(0.0, 1.0);
45                (offset - chord * t).length_sq()
46            };
47            if distance_sq > farthest.0 {
48                farthest = (distance_sq, index);
49            }
50        }
51        if farthest.0 > tolerance_sq {
52            keep[farthest.1] = true;
53            stack.push((first, farthest.1));
54            stack.push((farthest.1, last));
55        }
56    }
57    points
58        .into_iter()
59        .zip(keep)
60        .filter_map(|(point, keep)| keep.then_some(point))
61        .collect()
62}
63
64/// One marker per `cell`-sized square of the frame: the first point that lands in it.
65/// Unlike [`thin`], a curve that retraces itself (the cycles of a voltammogram) draws
66/// its markers once. Points outside the frame (plus a cell) are skipped.
67pub fn one_per_cell(transform: &Transform, data: &[[f64; 2]], cell: f32) -> Vec<usize> {
68    // At most 4096 x 4096 cells: a forged frame or a tiny `cell` used to multiply out to
69    // an arbitrarily large bit vector.
70    const MAX_CELLS: f32 = 4096.0;
71    let cell = if cell.is_finite() && cell > 0.0 { cell } else { 1.0 };
72    let frame = transform.frame.expand(cell);
73    let cell = cell.max(frame.width() / MAX_CELLS).max(frame.height() / MAX_CELLS);
74    let columns = ((frame.width() / cell).ceil() as usize).saturating_add(1).min(4097);
75    let rows = ((frame.height() / cell).ceil() as usize).saturating_add(1).min(4097);
76    let mut seen = vec![0u64; columns.saturating_mul(rows).div_ceil(64)];
77    let mut indices = Vec::new();
78    for (index, point) in data.iter().enumerate() {
79        let position = transform.to_screen(*point);
80        if !position.is_finite() || !frame.contains(position) {
81            continue;
82        }
83        let column = ((position.x - frame.left()) / cell) as usize;
84        let row = ((position.y - frame.top()) / cell) as usize;
85        let bit = row.min(rows.saturating_sub(1)).saturating_mul(columns) + column.min(columns.saturating_sub(1));
86        let (word, mask) = (bit / 64, 1u64 << (bit % 64));
87        if let Some(slot) = seen.get_mut(word)
88            && *slot & mask == 0
89        {
90            *slot |= mask;
91            indices.push(index);
92        }
93    }
94    indices
95}
96
97/// Every point at least `spacing` points (on screen) from the last one kept, plus the
98/// last point. Non-finite points are kept, so they still break the line.
99pub fn thin(transform: &Transform, data: &[[f64; 2]], spacing: f32) -> Vec<usize> {
100    let mut indices = Vec::new();
101    let mut last: Option<ScreenPoint> = None;
102    let spacing_sq = spacing * spacing;
103    for (index, point) in data.iter().enumerate() {
104        let position = transform.to_screen(*point);
105        if !position.is_finite() {
106            indices.push(index);
107            last = None;
108            continue;
109        }
110        if let Some(previous) = last
111            && (position - previous).length_sq() < spacing_sq
112            && index + 1 != data.len()
113        {
114            continue;
115        }
116        indices.push(index);
117        last = Some(position);
118    }
119    indices
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn a_huge_frame_does_not_allocate_an_unbounded_cell_grid() {
128        let transform = Transform {
129            frame: ScreenRect::from_min_size(ScreenPoint::ZERO, 1.0e30, 1.0e30),
130            view: Bounds::from_corners([-1.0, -1.0], [1.0, 1.0]),
131            x_scale: Scale::Linear,
132            y_scale: Scale::Linear,
133            y2: None,
134        };
135        let data = [[0.0, 0.0], [1.0, 1.0]];
136        let indices = one_per_cell(&transform, &data, 0.000_001);
137        assert!(indices.len() <= data.len());
138    }
139    use crate::axis::Scale;
140    use crate::transform::ScreenRect;
141    use crisol_core::data::Bounds;
142
143    fn transform() -> Transform {
144        Transform {
145            frame: ScreenRect::from_min_size(ScreenPoint::ZERO, 400.0, 300.0),
146            view: Bounds::from_corners([-1.0, -1.0], [1.0, 1.0]),
147            x_scale: Scale::Linear,
148            y_scale: Scale::Linear,
149            y2: None,
150        }
151    }
152
153    #[test]
154    fn unsorted_loops_keep_what_the_screen_can_show() {
155        // A circle traced ten times with 100 000 points: x goes back and forth.
156        let data: Vec<[f64; 2]> = (0..100_000)
157            .map(|index| {
158                let angle = index as f64 * std::f64::consts::TAU * 10.0 / 100_000.0;
159                [angle.cos() * 0.8, angle.sin() * 0.8]
160            })
161            .collect();
162        let kept = thin(&transform(), &data, LINE_SPACING);
163        assert!(kept.len() < 20_000, "{} points kept", kept.len());
164        assert_eq!(kept.first(), Some(&0));
165        assert_eq!(
166            kept.last(),
167            Some(&(data.len() - 1)),
168            "the line still ends at its last point"
169        );
170        let screen: Vec<ScreenPoint> = kept.iter().map(|&index| transform().to_screen(data[index])).collect();
171        assert!(
172            screen.windows(2).all(|pair| pair[0].distance(pair[1]) < 2.0),
173            "no visible jump between kept points"
174        );
175    }
176
177    #[test]
178    fn simplification_keeps_corners_and_drops_collinear_points() {
179        let line: Vec<ScreenPoint> = (0..=100).map(|x| ScreenPoint::new(x as f32, 10.0)).collect();
180        assert_eq!(
181            simplify(line, 0.3),
182            [ScreenPoint::new(0.0, 10.0), ScreenPoint::new(100.0, 10.0)]
183        );
184        let corner = vec![
185            ScreenPoint::new(0.0, 0.0),
186            ScreenPoint::new(5.0, 0.0),
187            ScreenPoint::new(10.0, 0.0),
188            ScreenPoint::new(10.0, 10.0),
189        ];
190        assert_eq!(
191            simplify(corner, 0.3),
192            [
193                ScreenPoint::new(0.0, 0.0),
194                ScreenPoint::new(10.0, 0.0),
195                ScreenPoint::new(10.0, 10.0)
196            ]
197        );
198        // A smooth arc keeps every vertex within the tolerance of the original.
199        let arc: Vec<ScreenPoint> = (0..2000)
200            .map(|index| {
201                let angle = index as f32 / 2000.0 * std::f32::consts::PI;
202                ScreenPoint::new(200.0 * angle.cos(), 200.0 * angle.sin())
203            })
204            .collect();
205        let simple = simplify(arc.clone(), 0.3);
206        assert!(simple.len() < 200, "{} vertices", simple.len());
207        for point in &arc {
208            let nearest = simple
209                .windows(2)
210                .map(|pair| {
211                    let chord = ScreenPoint::new(pair[1].x - pair[0].x, pair[1].y - pair[0].y);
212                    let offset = ScreenPoint::new(point.x - pair[0].x, point.y - pair[0].y);
213                    let t = ((offset.x * chord.x + offset.y * chord.y) / (chord.x * chord.x + chord.y * chord.y))
214                        .clamp(0.0, 1.0);
215                    let nearest = ScreenPoint::new(offset.x - chord.x * t, offset.y - chord.y * t);
216                    (nearest.x * nearest.x + nearest.y * nearest.y).sqrt()
217                })
218                .fold(f32::INFINITY, f32::min);
219            assert!(nearest <= 0.31, "{nearest}");
220        }
221    }
222
223    #[test]
224    fn retraced_markers_are_drawn_once() {
225        let cycle: Vec<[f64; 2]> = (0..1000)
226            .map(|index| {
227                let angle = index as f64 / 1000.0 * std::f64::consts::TAU;
228                [angle.cos() * 0.8, angle.sin() * 0.8]
229            })
230            .collect();
231        let once = one_per_cell(&transform(), &cycle, 2.0).len();
232        let ten: Vec<[f64; 2]> = cycle.iter().copied().cycle().take(10_000).collect();
233        assert_eq!(
234            one_per_cell(&transform(), &ten, 2.0).len(),
235            once,
236            "ten laps draw like one"
237        );
238        assert!(once > 100, "the circle is still drawn: {once}");
239    }
240
241    #[test]
242    fn breaks_survive_thinning() {
243        let data = [[0.0, 0.0], [0.0001, 0.0], [0.0, f64::NAN], [0.5, 0.5], [0.5001, 0.5]];
244        let kept = thin(&transform(), &data, LINE_SPACING);
245        assert_eq!(kept, [0, 2, 3, 4]);
246    }
247}