Skip to main content

hypergraph_rs/geometry/
contour.rs

1//! Iso-lines of a scalar grid, by marching squares.
2//!
3//! A [`ScalarGrid`] holds one number at each node of a regular lattice. [`iso_lines`] draws the closed paths that
4//! separate the nodes above a threshold from the rest. One virtual ring of nodes around the grid is always below the
5//! threshold, so every path closes.
6
7use indexmap::IndexMap;
8
9use super::{GeometryError, Point};
10
11/// A closed path: its first vertex is not repeated at the end.
12pub type ClosedPath = Vec<Point>;
13
14/// A regular grid of numbers.
15///
16/// Node `(col, row)` stands at `origin + (col * cell, row * cell)` and holds `values[row * cols + col]`. The fields
17/// are public; a grid whose `values` do not hold exactly `cols * rows` numbers is malformed, and the functions that
18/// read it panic.
19#[derive(Clone, Debug, PartialEq)]
20pub struct ScalarGrid {
21    /// The position of node `(0, 0)`.
22    pub origin: Point,
23    /// The distance between neighbouring nodes.
24    pub cell: f64,
25    /// The count of columns of nodes.
26    pub cols: usize,
27    /// The count of rows of nodes.
28    pub rows: usize,
29    /// The numbers, row by row.
30    pub values: Vec<f64>,
31}
32
33impl ScalarGrid {
34    /// A grid of zeros.
35    ///
36    /// # Errors
37    ///
38    /// [`GeometryError::BadParameter`] for a `cell` that is not finite and above zero, an `origin` that is not
39    /// finite, or `cols` or `rows` of zero, or a `cols * rows` that overflows (named `cols`).
40    pub fn zeros(
41        origin: Point,
42        cell: f64,
43        cols: usize,
44        rows: usize,
45    ) -> Result<Self, GeometryError> {
46        if !(cell.is_finite() && cell > 0.0) {
47            return Err(GeometryError::BadParameter {
48                name: "cell",
49                value: cell,
50            });
51        }
52        for value in [origin.0, origin.1] {
53            if !value.is_finite() {
54                return Err(GeometryError::BadParameter {
55                    name: "origin",
56                    value,
57                });
58            }
59        }
60        if cols == 0 {
61            return Err(GeometryError::BadParameter {
62                name: "cols",
63                value: 0.0,
64            });
65        }
66        if rows == 0 {
67            return Err(GeometryError::BadParameter {
68                name: "rows",
69                value: 0.0,
70            });
71        }
72        let nodes = cols.checked_mul(rows).ok_or(GeometryError::BadParameter {
73            name: "cols",
74            value: cols as f64,
75        })?;
76        Ok(Self {
77            origin,
78            cell,
79            cols,
80            rows,
81            values: vec![0.0; nodes],
82        })
83    }
84
85    /// The number at node `(col, row)`.
86    ///
87    /// # Panics
88    ///
89    /// When `col >= cols`, `row >= rows`, or the grid is malformed.
90    #[must_use]
91    pub fn get(&self, col: usize, row: usize) -> f64 {
92        assert!(col < self.cols && row < self.rows, "node out of range");
93        self.check();
94        self.values[row * self.cols + col]
95    }
96
97    /// The bilinear value at `at`, or `None` outside the extent of the nodes (or for a position that is `NaN`, or on a grid without nodes).
98    ///
99    /// # Panics
100    ///
101    /// When the grid is malformed.
102    #[must_use]
103    pub fn sample(&self, at: Point) -> Option<f64> {
104        self.check();
105        if self.cols == 0 || self.rows == 0 {
106            return None;
107        }
108        let u = (at.0 - self.origin.0) / self.cell;
109        let v = (at.1 - self.origin.1) / self.cell;
110        if !(u >= 0.0 && u <= (self.cols - 1) as f64 && v >= 0.0 && v <= (self.rows - 1) as f64) {
111            return None;
112        }
113        let c0 = (u.floor() as usize).min(self.cols.saturating_sub(2));
114        let r0 = (v.floor() as usize).min(self.rows.saturating_sub(2));
115        let c1 = (c0 + 1).min(self.cols - 1);
116        let r1 = (r0 + 1).min(self.rows - 1);
117        let (fx, fy) = (u - c0 as f64, v - r0 as f64);
118        let at_node = |c: usize, r: usize| self.values[r * self.cols + c];
119        let top = at_node(c0, r0) + (at_node(c1, r0) - at_node(c0, r0)) * fx;
120        let bottom = at_node(c0, r1) + (at_node(c1, r1) - at_node(c0, r1)) * fx;
121        Some(top + (bottom - top) * fy)
122    }
123
124    fn check(&self) {
125        assert!(
126            self.values.len() == self.cols * self.rows,
127            "grid holds {} numbers, expected {} * {}",
128            self.values.len(),
129            self.cols,
130            self.rows
131        );
132    }
133}
134
135/// No crossing.
136const NONE: usize = usize::MAX;
137
138/// The numbering of the crossing edges. Edges run over the grid and its virtual ring: nodes with column in
139/// `-1..=cols` and row in `-1..=rows`. Row by row from row `-1`, a row's horizontal edges (from node `(c, r)` to
140/// `(c + 1, r)`, `c` from `-1`) come first, then the vertical edges from row `r` to row `r + 1` (`c` from `-1`).
141struct Edges {
142    cols: usize,
143    stride: usize,
144}
145
146impl Edges {
147    fn new(grid: &ScalarGrid) -> Self {
148        Self {
149            cols: grid.cols,
150            stride: 2 * grid.cols + 3,
151        }
152    }
153
154    fn count(&self, grid: &ScalarGrid) -> usize {
155        (grid.rows + 2) * self.stride
156    }
157
158    /// The edge from node `(c, r)` to `(c + 1, r)`.
159    fn horizontal(&self, c: i64, r: i64) -> usize {
160        ((r + 1) as usize) * self.stride + (c + 1) as usize
161    }
162
163    /// The edge from node `(c, r)` to `(c, r + 1)`.
164    fn vertical(&self, c: i64, r: i64) -> usize {
165        ((r + 1) as usize) * self.stride + self.cols + 1 + (c + 1) as usize
166    }
167}
168
169/// The value at node `(c, r)`, or `None` for a node of the virtual ring.
170fn node_value(grid: &ScalarGrid, c: i64, r: i64) -> Option<f64> {
171    if c < 0 || r < 0 || c >= grid.cols as i64 || r >= grid.rows as i64 {
172        None
173    } else {
174        Some(grid.values[r as usize * grid.cols + c as usize])
175    }
176}
177
178fn is_inside(grid: &ScalarGrid, threshold: f64, c: i64, r: i64) -> bool {
179    node_value(grid, c, r).is_some_and(|v| v > threshold)
180}
181
182/// Where the line from value `a` (at 0) to value `b` (at 1) meets `threshold`; the middle when that is undefined.
183fn crossing_fraction(threshold: f64, a: f64, b: f64) -> f64 {
184    let t = (threshold - a) / (b - a);
185    if (0.0..=1.0).contains(&t) {
186        t
187    } else {
188        0.5
189    }
190}
191
192/// The vertex of a crossing edge: by linear interpolation between two real nodes, at the middle of an edge to a
193/// virtual node.
194fn edge_vertex(grid: &ScalarGrid, threshold: f64, edges: &Edges, edge: usize) -> Point {
195    let row = (edge / edges.stride) as i64 - 1;
196    let rem = edge % edges.stride;
197    let (ox, oy) = grid.origin;
198    if rem < edges.cols + 1 {
199        let c = rem as i64 - 1;
200        let t = match (node_value(grid, c, row), node_value(grid, c + 1, row)) {
201            (Some(a), Some(b)) => crossing_fraction(threshold, a, b),
202            _ => 0.5,
203        };
204        (ox + (c as f64 + t) * grid.cell, oy + row as f64 * grid.cell)
205    } else {
206        let c = (rem - edges.cols - 1) as i64 - 1;
207        let t = match (node_value(grid, c, row), node_value(grid, c, row + 1)) {
208            (Some(a), Some(b)) => crossing_fraction(threshold, a, b),
209            _ => 0.5,
210        };
211        (ox + c as f64 * grid.cell, oy + (row as f64 + t) * grid.cell)
212    }
213}
214
215/// The segments of the cell whose lower-left node is `(cc, rr)`, as `(from edge, to edge)` pairs with the inside
216/// on the left of each. `emit` is called for each.
217///
218/// Walking the cell's four edges counter-clockwise, a crossing where the walk leaves the inside is an exit and one
219/// where it enters is an entry. A segment joins an exit to the next entry; for a saddle whose centre is not inside,
220/// to the previous entry instead.
221fn cell_segments(
222    grid: &ScalarGrid,
223    threshold: f64,
224    edges: &Edges,
225    cc: i64,
226    rr: i64,
227    mut emit: impl FnMut(usize, usize),
228) {
229    // Corners a, b, c, d counter-clockwise from the lower left.
230    let corners = [(cc, rr), (cc + 1, rr), (cc + 1, rr + 1), (cc, rr + 1)];
231    let inside = corners.map(|(c, r)| is_inside(grid, threshold, c, r));
232    let sides = [
233        edges.horizontal(cc, rr),
234        edges.vertical(cc + 1, rr),
235        edges.horizontal(cc, rr + 1),
236        edges.vertical(cc, rr),
237    ];
238    // (edge, is an exit), in walking order.
239    let mut crossings = [(NONE, false); 4];
240    let mut n = 0;
241    for k in 0..4 {
242        let next = (k + 1) % 4;
243        if inside[k] != inside[next] {
244            crossings[n] = (sides[k], inside[k]);
245            n += 1;
246        }
247    }
248    match n {
249        2 => {
250            let (from, to) = if crossings[0].1 {
251                (crossings[0].0, crossings[1].0)
252            } else {
253                (crossings[1].0, crossings[0].0)
254            };
255            emit(from, to);
256        }
257        4 => {
258            let value = |c: i64, r: i64| node_value(grid, c, r).unwrap_or(f64::NEG_INFINITY);
259            let sum =
260                ((value(cc, rr) + value(cc + 1, rr)) + value(cc + 1, rr + 1)) + value(cc, rr + 1);
261            let joined = sum / 4.0 > threshold;
262            for k in 0..4 {
263                if crossings[k].1 {
264                    let other = if joined { (k + 1) % 4 } else { (k + 3) % 4 };
265                    emit(crossings[k].0, crossings[other].0);
266                }
267            }
268        }
269        _ => {}
270    }
271}
272
273/// The closed paths along which the grid crosses `threshold`.
274///
275/// A node is inside when its value is above `threshold` (a `NaN` is outside). Crossings between two nodes are
276/// placed by linear interpolation; a crossing to the virtual ring around the grid sits half a cell outside it. A
277/// saddle is joined when the mean of its four corners is above `threshold`.
278///
279/// Each path has the inside on its left: outer boundaries run counter-clockwise (positive [`signed_area`]), holes
280/// clockwise. No vertex repeats within a path and no path has fewer than three vertices or zero area: where a line
281/// touches itself at a node holding exactly `threshold`, it is cut there into separate loops. Paths start at the
282/// vertex that comes first in row-major order of the crossing edges (horizontal edges of a row before its vertical
283/// edges) and are listed in that order, except that a loop cut off at a pinch starts at the pinch vertex and is
284/// listed before the rest of its line. The cost is linear in the count of nodes.
285///
286/// # Panics
287///
288/// When `grid.values.len() != grid.cols * grid.rows`.
289#[must_use]
290pub fn iso_lines(grid: &ScalarGrid, threshold: f64) -> Vec<ClosedPath> {
291    grid.check();
292    let edges = Edges::new(grid);
293    let mut next = vec![NONE; edges.count(grid)];
294    for rr in -1..grid.rows as i64 {
295        for cc in -1..grid.cols as i64 {
296            cell_segments(grid, threshold, &edges, cc, rr, |from, to| next[from] = to);
297        }
298    }
299    let mut paths = Vec::new();
300    for start in 0..next.len() {
301        if next[start] == NONE {
302            continue;
303        }
304        let mut path: Vec<Point> = Vec::new();
305        let mut seen: IndexMap<(u64, u64), usize> = IndexMap::new();
306        let mut edge = start;
307        while next[edge] != NONE {
308            let vertex = edge_vertex(grid, threshold, &edges, edge);
309            // `+ 0.0` turns a negative zero into zero, so equal points have equal keys.
310            let key = ((vertex.0 + 0.0).to_bits(), (vertex.1 + 0.0).to_bits());
311            // A node outside the line that holds exactly `threshold` is met by several crossing edges, all
312            // placed on it. When the walk comes back to a vertex it already holds, the path touches itself
313            // there: the part walked since is cut off as a loop of its own.
314            if let Some(&at) = seen.get(&key) {
315                let cut = path.split_off(at + 1);
316                for dropped in &cut {
317                    seen.swap_remove(&((dropped.0 + 0.0).to_bits(), (dropped.1 + 0.0).to_bits()));
318                }
319                keep_loop(&mut paths, std::iter::once(vertex).chain(cut).collect());
320            } else {
321                seen.insert(key, path.len());
322                path.push(vertex);
323            }
324            let following = next[edge];
325            next[edge] = NONE;
326            edge = following;
327        }
328        keep_loop(&mut paths, path);
329    }
330    paths
331}
332
333/// Keeps `path` as a closed path when it has three vertices and a non-zero area.
334fn keep_loop(paths: &mut Vec<ClosedPath>, path: Vec<Point>) {
335    if path.len() >= 3 && signed_area(&path) != 0.0 {
336        paths.push(path);
337    }
338}
339
340/// The signed area of a closed path by the shoelace formula: positive when it runs counter-clockwise.
341#[must_use]
342pub fn signed_area(path: &[Point]) -> f64 {
343    let mut twice = 0.0_f64;
344    for (k, p) in path.iter().enumerate() {
345        let q = path[(k + 1) % path.len()];
346        twice += p.0 * q.1 - q.0 * p.1;
347    }
348    twice / 2.0
349}
350
351/// Whether the segment from `p` to `q` crosses the ray going right from `at`.
352fn crosses_ray(p: Point, q: Point, at: Point) -> bool {
353    if (p.1 > at.1) == (q.1 > at.1) {
354        return false;
355    }
356    let x = p.0 + (at.1 - p.1) * (q.0 - p.0) / (q.1 - p.1);
357    x > at.0
358}
359
360/// Whether `at` is inside the paths by the even-odd rule: a ray from `at` crosses an odd number of segments.
361#[must_use]
362pub fn contains(paths: &[ClosedPath], at: Point) -> bool {
363    let mut inside = false;
364    for path in paths {
365        for (k, p) in path.iter().enumerate() {
366            let q = path[(k + 1) % path.len()];
367            if crosses_ray(*p, q, at) {
368                inside = !inside;
369            }
370        }
371    }
372    inside
373}
374
375/// Whether `contains(&iso_lines(grid, threshold), at)` would be true, decided from the one cell that holds `at`.
376///
377/// It computes the cell's crossings with the same functions `iso_lines` uses and counts the cell's segments that
378/// the ray going right crosses; the side of the cell's right edge, where the ray leaves, is read from the corners.
379/// The two agree bit for bit except for a point lying exactly on a path.
380///
381/// # Panics
382///
383/// When `grid.values.len() != grid.cols * grid.rows`.
384pub(crate) fn inside_cell(grid: &ScalarGrid, threshold: f64, at: Point) -> bool {
385    grid.check();
386    let u = ((at.0 - grid.origin.0) / grid.cell).floor();
387    let v = ((at.1 - grid.origin.1) / grid.cell).floor();
388    // Cells run from -1 to cols - 1 (rows - 1): the virtual ring makes half a cell of margin.
389    if !(u >= -1.0 && u < grid.cols as f64 && v >= -1.0 && v < grid.rows as f64) {
390        return false;
391    }
392    let (cc, rr) = (u as i64, v as i64);
393    let edges = Edges::new(grid);
394    let mut crossed = false;
395    cell_segments(grid, threshold, &edges, cc, rr, |from, to| {
396        let p = edge_vertex(grid, threshold, &edges, from);
397        let q = edge_vertex(grid, threshold, &edges, to);
398        if crosses_ray(p, q, at) {
399            crossed = !crossed;
400        }
401    });
402    // Where the ray meets the cell's right edge, between nodes b (below) and c (above).
403    let below = is_inside(grid, threshold, cc + 1, rr);
404    let above = is_inside(grid, threshold, cc + 1, rr + 1);
405    let at_edge = if below == above {
406        below
407    } else {
408        let y = edge_vertex(grid, threshold, &edges, edges.vertical(cc + 1, rr)).1;
409        if at.1 < y {
410            below
411        } else {
412            above
413        }
414    };
415    at_edge != crossed
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    fn lcg(state: &mut u64) -> f64 {
423        *state = state
424            .wrapping_mul(6_364_136_223_846_793_005)
425            .wrapping_add(1_442_695_040_888_963_407);
426        (*state >> 40) as f64 / (1_u64 << 24) as f64
427    }
428
429    #[test]
430    fn inside_cell_agrees_with_contains() {
431        let mut state = 20_261_121_u64;
432        let mut grid = ScalarGrid::zeros((0.0, 0.0), 1.0, 40, 30).unwrap();
433        for value in &mut grid.values {
434            *value = lcg(&mut state);
435        }
436        let paths = iso_lines(&grid, 0.5);
437        let mut second = 7_u64;
438        let mut inside = 0;
439        for _ in 0..2_000 {
440            let p = (lcg(&mut second) * 39.0, lcg(&mut second) * 29.0);
441            let expected = contains(&paths, p);
442            assert_eq!(inside_cell(&grid, 0.5, p), expected, "at {p:?}");
443            inside += usize::from(expected);
444        }
445        assert!(inside > 300 && inside < 1_700, "{inside} inside");
446        assert!(!inside_cell(&grid, 0.5, (-3.0, 4.0)));
447    }
448}