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    let frame = transform.frame.expand(cell);
69    let columns = (frame.width() / cell).ceil() as usize + 1;
70    let rows = (frame.height() / cell).ceil() as usize + 1;
71    let mut seen = vec![0u64; (columns * rows).div_ceil(64)];
72    let mut indices = Vec::new();
73    for (index, point) in data.iter().enumerate() {
74        let position = transform.to_screen(*point);
75        if !position.is_finite() || !frame.contains(position) {
76            continue;
77        }
78        let column = ((position.x - frame.left()) / cell) as usize;
79        let row = ((position.y - frame.top()) / cell) as usize;
80        let bit = row.min(rows - 1) * columns + column.min(columns - 1);
81        let (word, mask) = (bit / 64, 1u64 << (bit % 64));
82        if seen[word] & mask == 0 {
83            seen[word] |= mask;
84            indices.push(index);
85        }
86    }
87    indices
88}
89
90/// Every point at least `spacing` points (on screen) from the last one kept, plus the
91/// last point. Non-finite points are kept, so they still break the line.
92pub fn thin(transform: &Transform, data: &[[f64; 2]], spacing: f32) -> Vec<usize> {
93    let mut indices = Vec::new();
94    let mut last: Option<ScreenPoint> = None;
95    let spacing_sq = spacing * spacing;
96    for (index, point) in data.iter().enumerate() {
97        let position = transform.to_screen(*point);
98        if !position.is_finite() {
99            indices.push(index);
100            last = None;
101            continue;
102        }
103        if let Some(previous) = last
104            && (position - previous).length_sq() < spacing_sq
105            && index + 1 != data.len()
106        {
107            continue;
108        }
109        indices.push(index);
110        last = Some(position);
111    }
112    indices
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::axis::Scale;
119    use crate::transform::ScreenRect;
120    use crisol_core::data::Bounds;
121
122    fn transform() -> Transform {
123        Transform {
124            frame: ScreenRect::from_min_size(ScreenPoint::ZERO, 400.0, 300.0),
125            view: Bounds::from_corners([-1.0, -1.0], [1.0, 1.0]),
126            x_scale: Scale::Linear,
127            y_scale: Scale::Linear,
128            y2: None,
129        }
130    }
131
132    #[test]
133    fn unsorted_loops_keep_what_the_screen_can_show() {
134        // A circle traced ten times with 100 000 points: x goes back and forth.
135        let data: Vec<[f64; 2]> = (0..100_000)
136            .map(|index| {
137                let angle = index as f64 * std::f64::consts::TAU * 10.0 / 100_000.0;
138                [angle.cos() * 0.8, angle.sin() * 0.8]
139            })
140            .collect();
141        let kept = thin(&transform(), &data, LINE_SPACING);
142        assert!(kept.len() < 20_000, "{} points kept", kept.len());
143        assert_eq!(kept.first(), Some(&0));
144        assert_eq!(
145            kept.last(),
146            Some(&(data.len() - 1)),
147            "the line still ends at its last point"
148        );
149        let screen: Vec<ScreenPoint> = kept.iter().map(|&index| transform().to_screen(data[index])).collect();
150        assert!(
151            screen.windows(2).all(|pair| pair[0].distance(pair[1]) < 2.0),
152            "no visible jump between kept points"
153        );
154    }
155
156    #[test]
157    fn simplification_keeps_corners_and_drops_collinear_points() {
158        let line: Vec<ScreenPoint> = (0..=100).map(|x| ScreenPoint::new(x as f32, 10.0)).collect();
159        assert_eq!(
160            simplify(line, 0.3),
161            [ScreenPoint::new(0.0, 10.0), ScreenPoint::new(100.0, 10.0)]
162        );
163        let corner = vec![
164            ScreenPoint::new(0.0, 0.0),
165            ScreenPoint::new(5.0, 0.0),
166            ScreenPoint::new(10.0, 0.0),
167            ScreenPoint::new(10.0, 10.0),
168        ];
169        assert_eq!(
170            simplify(corner, 0.3),
171            [
172                ScreenPoint::new(0.0, 0.0),
173                ScreenPoint::new(10.0, 0.0),
174                ScreenPoint::new(10.0, 10.0)
175            ]
176        );
177        // A smooth arc keeps every vertex within the tolerance of the original.
178        let arc: Vec<ScreenPoint> = (0..2000)
179            .map(|index| {
180                let angle = index as f32 / 2000.0 * std::f32::consts::PI;
181                ScreenPoint::new(200.0 * angle.cos(), 200.0 * angle.sin())
182            })
183            .collect();
184        let simple = simplify(arc.clone(), 0.3);
185        assert!(simple.len() < 200, "{} vertices", simple.len());
186        for point in &arc {
187            let nearest = simple
188                .windows(2)
189                .map(|pair| {
190                    let chord = ScreenPoint::new(pair[1].x - pair[0].x, pair[1].y - pair[0].y);
191                    let offset = ScreenPoint::new(point.x - pair[0].x, point.y - pair[0].y);
192                    let t = ((offset.x * chord.x + offset.y * chord.y) / (chord.x * chord.x + chord.y * chord.y))
193                        .clamp(0.0, 1.0);
194                    let nearest = ScreenPoint::new(offset.x - chord.x * t, offset.y - chord.y * t);
195                    (nearest.x * nearest.x + nearest.y * nearest.y).sqrt()
196                })
197                .fold(f32::INFINITY, f32::min);
198            assert!(nearest <= 0.31, "{nearest}");
199        }
200    }
201
202    #[test]
203    fn retraced_markers_are_drawn_once() {
204        let cycle: Vec<[f64; 2]> = (0..1000)
205            .map(|index| {
206                let angle = index as f64 / 1000.0 * std::f64::consts::TAU;
207                [angle.cos() * 0.8, angle.sin() * 0.8]
208            })
209            .collect();
210        let once = one_per_cell(&transform(), &cycle, 2.0).len();
211        let ten: Vec<[f64; 2]> = cycle.iter().copied().cycle().take(10_000).collect();
212        assert_eq!(
213            one_per_cell(&transform(), &ten, 2.0).len(),
214            once,
215            "ten laps draw like one"
216        );
217        assert!(once > 100, "the circle is still drawn: {once}");
218    }
219
220    #[test]
221    fn breaks_survive_thinning() {
222        let data = [[0.0, 0.0], [0.0001, 0.0], [0.0, f64::NAN], [0.5, 0.5], [0.5001, 0.5]];
223        let kept = thin(&transform(), &data, LINE_SPACING);
224        assert_eq!(kept, [0, 2, 3, 4]);
225    }
226}