Skip to main content

hypergraph_rs/geometry/
spread.rs

1//! Spreading overlapping points apart in a fixed number of steps.
2//!
3//! Points go into square cells of the side `min_distance`; each point meets only the points of the nine cells
4//! around it, at most `max_neighbours` of them, so the cost is `n * max_neighbours * steps` and never `n * n`.
5//! The push between two points on one spot is chosen from their two ids, never from their indices.
6
7use super::{GeometryError, Point, Positions, Rect};
8
9/// The default cap on the points one point examines in a step.
10pub const DEFAULT_MAX_NEIGHBOURS: usize = 32;
11
12/// The parameters of [`spread`].
13#[derive(Clone, Debug, PartialEq)]
14pub struct SpreadParams {
15    /// The distance no two points may be closer than. Finite and above zero.
16    pub min_distance: f64,
17    /// The number of steps. Zero changes nothing.
18    pub steps: u32,
19    /// The most candidate partners one point examines in a step, points and obstacles together (the first ones in
20    /// cell order). At least 1.
21    pub max_neighbours: usize,
22    /// When set, every point is clamped into this rectangle after each step. Its minimum must not exceed its
23    /// maximum on either axis.
24    pub bounds: Option<Rect>,
25}
26
27impl SpreadParams {
28    /// Parameters with [`DEFAULT_MAX_NEIGHBOURS`] and no bounds.
29    #[must_use]
30    pub fn new(min_distance: f64, steps: u32) -> Self {
31        Self {
32            min_distance,
33            steps,
34            max_neighbours: DEFAULT_MAX_NEIGHBOURS,
35            bounds: None,
36        }
37    }
38}
39
40/// What a call of [`spread`] did.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct SpreadReport {
43    /// The pairs and obstacles examined over all steps.
44    pub comparisons: u64,
45    /// The pairs examined after the last step that are still closer than `min_distance` (less a tolerance of 1e-9
46    /// of it). The final count is not part of `comparisons`.
47    pub overlaps_left: usize,
48}
49
50/// The sine and cosine of 45 degrees (a constant, so no trigonometry runs).
51const H: f64 = std::f64::consts::FRAC_1_SQRT_2;
52
53/// Sixteen unit vectors at multiples of 22.5 degrees, as literals so no trigonometry runs.
54const DIRECTIONS: [Point; 16] = [
55    (1.0, 0.0),
56    (0.9238795325112867, 0.3826834323650898),
57    (H, H),
58    (0.3826834323650898, 0.9238795325112867),
59    (0.0, 1.0),
60    (-0.3826834323650898, 0.9238795325112867),
61    (-H, H),
62    (-0.9238795325112867, 0.3826834323650898),
63    (-1.0, 0.0),
64    (-0.9238795325112867, -0.3826834323650898),
65    (-H, -H),
66    (-0.3826834323650898, -0.9238795325112867),
67    (0.0, -1.0),
68    (0.3826834323650898, -0.9238795325112867),
69    (H, -H),
70    (0.9238795325112867, -0.3826834323650898),
71];
72
73/// 64-bit FNV-1a.
74fn fnv1a(bytes: &[u8]) -> u64 {
75    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
76    for byte in bytes {
77        hash ^= u64::from(*byte);
78        hash = hash.wrapping_mul(0x0100_0000_01b3);
79    }
80    hash
81}
82
83fn direction(hash: u64) -> Point {
84    DIRECTIONS[(hash & 15) as usize]
85}
86
87type Cell = (i64, i64, usize);
88
89fn cell_of(at: Point, side: f64) -> (i64, i64) {
90    // Saturating casts: a finite coordinate far from the origin lands in an extreme cell, which is still a cell.
91    ((at.1 / side).floor() as i64, (at.0 / side).floor() as i64)
92}
93
94fn sorted_cells(points: &[Point], side: f64) -> Vec<Cell> {
95    let mut cells: Vec<Cell> = points
96        .iter()
97        .enumerate()
98        .map(|(k, at)| {
99            let (r, c) = cell_of(*at, side);
100            (r, c, k)
101        })
102        .collect();
103    cells.sort_unstable();
104    cells
105}
106
107/// The entries of `cells` in the cell `(row, col)`, in index order.
108fn in_cell(cells: &[Cell], row: i64, col: i64) -> &[Cell] {
109    let start = cells.partition_point(|&(r, c, _)| (r, c) < (row, col));
110    let end = cells.partition_point(|&(r, c, _)| (r, c) <= (row, col));
111    &cells[start..end]
112}
113
114/// Visits, for each point in index order, the points `j > i` of the nine cells around its own (rows first, then
115/// columns), until `max_neighbours` have been examined for `i`. `visit(i, j, distance)` is called for each. Returns
116/// the number of pairs examined.
117fn scan_pairs(
118    points: &[Point],
119    cells: &[Cell],
120    side: f64,
121    max_neighbours: usize,
122    mut visit: impl FnMut(usize, usize, f64),
123) -> u64 {
124    let mut comparisons: u64 = 0;
125    for (i, at) in points.iter().enumerate() {
126        let (row, col) = cell_of(*at, side);
127        let mut examined = 0usize;
128        'cells: for dr in -1i64..=1 {
129            for dc in -1i64..=1 {
130                // Past the last representable cell there is no neighbour; never revisit the edge cell.
131                let (Some(r), Some(c)) = (row.checked_add(dr), col.checked_add(dc)) else {
132                    continue;
133                };
134                let cell = in_cell(cells, r, c);
135                // Entries of a cell are sorted by index: skip straight to the first `j > i`.
136                let cell = &cell[cell.partition_point(|&(_, _, j)| j <= i)..];
137                for &(_, _, j) in cell {
138                    if examined >= max_neighbours {
139                        break 'cells;
140                    }
141                    examined += 1;
142                    comparisons += 1;
143                    let (dx, dy) = (points[j].0 - at.0, points[j].1 - at.1);
144                    visit(i, j, (dx * dx + dy * dy).sqrt());
145                }
146            }
147        }
148    }
149    comparisons
150}
151
152fn validate(
153    positions: &Positions,
154    obstacles: &[Point],
155    params: &SpreadParams,
156) -> Result<(), GeometryError> {
157    let d = params.min_distance;
158    if !(d.is_finite() && d > 0.0) {
159        return Err(GeometryError::BadParameter {
160            name: "min_distance",
161            value: d,
162        });
163    }
164    if params.max_neighbours < 1 {
165        return Err(GeometryError::BadParameter {
166            name: "max_neighbours",
167            value: 0.0,
168        });
169    }
170    if let Some((x0, y0, x1, y1)) = params.bounds {
171        for value in [x0, y0, x1, y1] {
172            if !value.is_finite() {
173                return Err(GeometryError::BadParameter {
174                    name: "bounds",
175                    value,
176                });
177            }
178        }
179        if x0 > x1 {
180            return Err(GeometryError::BadParameter {
181                name: "bounds",
182                value: x0,
183            });
184        }
185        if y0 > y1 {
186            return Err(GeometryError::BadParameter {
187                name: "bounds",
188                value: y0,
189            });
190        }
191    }
192    for (id, at) in positions.iter() {
193        if !(at.0.is_finite() && at.1.is_finite()) {
194            return Err(GeometryError::NonFinitePosition {
195                item: id.to_owned(),
196            });
197        }
198    }
199    for (k, at) in obstacles.iter().enumerate() {
200        if !(at.0.is_finite() && at.1.is_finite()) {
201            return Err(GeometryError::NonFinitePosition {
202                item: format!("#{k}"),
203            });
204        }
205    }
206    Ok(())
207}
208
209/// One step: every point moves at once from the positions at the start of the step. Returns the comparisons.
210fn step(
211    positions: &mut Positions,
212    hashes: &[u64],
213    obstacles: &[Point],
214    obstacle_cells: &[Cell],
215    params: &SpreadParams,
216) -> u64 {
217    let d = params.min_distance;
218    let half = d / 2.0;
219    let points: Vec<Point> = positions.iter().map(|(_, at)| at).collect();
220    let cells = sorted_cells(&points, d);
221    let mut shift: Vec<Point> = vec![(0.0, 0.0); points.len()];
222
223    let mut comparisons = {
224        let view: &Positions = positions;
225        scan_pairs(&points, &cells, d, params.max_neighbours, |i, j, dist| {
226            if dist >= d {
227                return;
228            }
229            let (dx, dy) = (points[j].0 - points[i].0, points[j].1 - points[i].1);
230            // The displacement of `i`; `j` gets its negation.
231            let push = if dist == 0.0 {
232                let (small, large) = if view.id_at(i) < view.id_at(j) {
233                    (i, j)
234                } else {
235                    (j, i)
236                };
237                let u = direction(hashes[small].wrapping_mul(31) ^ hashes[large]);
238                let sign = if i == large { 1.0 } else { -1.0 };
239                (sign * u.0 * half, sign * u.1 * half)
240            } else {
241                let amount = (d - dist) / 2.0;
242                (-(dx / dist) * amount, -(dy / dist) * amount)
243            };
244            shift[i].0 += push.0;
245            shift[i].1 += push.1;
246            shift[j].0 -= push.0;
247            shift[j].1 -= push.1;
248        })
249    };
250
251    for s in &mut shift {
252        let len = (s.0 * s.0 + s.1 * s.1).sqrt();
253        if len > half {
254            let scale = half / len;
255            s.0 *= scale;
256            s.1 *= scale;
257        }
258    }
259
260    if !obstacles.is_empty() {
261        for (i, at) in points.iter().enumerate() {
262            let (row, col) = cell_of(*at, d);
263            let mut examined = 0usize;
264            'cells: for dr in -1i64..=1 {
265                for dc in -1i64..=1 {
266                    let (Some(r), Some(c)) = (row.checked_add(dr), col.checked_add(dc)) else {
267                        continue;
268                    };
269                    // Only the first `max_neighbours` obstacles are examined, so a pile of obstacles on one spot
270                    // costs no more per point than a pile of points.
271                    let cell = in_cell(obstacle_cells, r, c);
272                    let room = params.max_neighbours - examined;
273                    for &(_, _, k) in &cell[..cell.len().min(room)] {
274                        examined += 1;
275                        comparisons += 1;
276                        let (dx, dy) = (at.0 - obstacles[k].0, at.1 - obstacles[k].1);
277                        let dist = (dx * dx + dy * dy).sqrt();
278                        if dist >= d {
279                            continue;
280                        }
281                        if dist == 0.0 {
282                            let u = direction(hashes[i]);
283                            shift[i].0 += u.0 * d;
284                            shift[i].1 += u.1 * d;
285                        } else {
286                            let amount = d - dist;
287                            shift[i].0 += dx / dist * amount;
288                            shift[i].1 += dy / dist * amount;
289                        }
290                    }
291                    if examined >= params.max_neighbours {
292                        break 'cells;
293                    }
294                }
295            }
296        }
297    }
298
299    for (i, s) in shift.iter().enumerate() {
300        let at = positions.point_mut(i);
301        at.0 += s.0;
302        at.1 += s.1;
303        if let Some((x0, y0, x1, y1)) = params.bounds {
304            at.0 = at.0.max(x0).min(x1);
305            at.1 = at.1.max(y0).min(y1);
306        }
307    }
308    comparisons
309}
310
311/// Pushes points apart until none is closer than `min_distance` to another, within a fixed number of steps.
312///
313/// Rules, in order of a step: every point meets the points of the nine cells around it that come later in
314/// insertion order, at most `max_neighbours` of them; a close pair is pushed apart by half the shortfall each along
315/// the line between them; two points on one spot part along a direction chosen from the two ids, so adding a far
316/// node changes no other node's bits; each point's summed push is cut to half the distance; `obstacles` (which
317/// never move) push points out to the distance in full; all points move at once; then `bounds`, if set, clamp.
318///
319/// `steps = 0` changes nothing. Overlaps that remain (for example when `bounds` are narrower than the distance) are
320/// reported in [`SpreadReport::overlaps_left`], never looped on.
321///
322/// # Errors
323///
324/// [`GeometryError::BadParameter`] for a `min_distance` that is not finite and above zero, a `max_neighbours` of
325/// zero, or invalid `bounds`; [`GeometryError::NonFinitePosition`] for a point (named by id) or an obstacle (named
326/// `#<index>`) that is not finite.
327pub fn spread(
328    positions: &mut Positions,
329    obstacles: &[Point],
330    params: &SpreadParams,
331) -> Result<SpreadReport, GeometryError> {
332    spread_counted(positions, obstacles, params).map(|(report, _)| report)
333}
334
335/// [`spread`], also returning every pair and obstacle examined, the final overlap count's included (which
336/// `SpreadReport::comparisons` leaves out). Tests read it to bound the cost.
337fn spread_counted(
338    positions: &mut Positions,
339    obstacles: &[Point],
340    params: &SpreadParams,
341) -> Result<(SpreadReport, u64), GeometryError> {
342    validate(positions, obstacles, params)?;
343    let hashes: Vec<u64> = (0..positions.len())
344        .map(|i| fnv1a(positions.id_at(i).as_bytes()))
345        .collect();
346    let obstacle_cells = sorted_cells(obstacles, params.min_distance);
347    let mut comparisons: u64 = 0;
348    for _ in 0..params.steps {
349        comparisons += step(positions, &hashes, obstacles, &obstacle_cells, params);
350    }
351
352    let d = params.min_distance;
353    let points: Vec<Point> = positions.iter().map(|(_, at)| at).collect();
354    let cells = sorted_cells(&points, d);
355    let mut overlaps_left = 0usize;
356    let final_scan = scan_pairs(&points, &cells, d, params.max_neighbours, |_, _, dist| {
357        if dist < d * (1.0 - 1e-9) {
358            overlaps_left += 1;
359        }
360    });
361    Ok((
362        SpreadReport {
363            comparisons,
364            overlaps_left,
365        },
366        comparisons + final_scan,
367    ))
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn twenty_five_thousand_points_on_one_spot_examine_a_bounded_count_of_pairs() {
376        let mut p = Positions::new();
377        for k in 0..25_000usize {
378            p.insert(format!("n{k:05}"), (1.0, 1.0));
379        }
380        let (_, examined) = spread_counted(&mut p, &[], &SpreadParams::new(0.1, 2)).unwrap();
381        // Two steps and the final count, each at most `max_neighbours` pairs per point; a pass over the whole pile
382        // for each point would be over 600 million pairs.
383        assert!(examined <= 25_000 * 32 * 3, "{examined} pairs");
384    }
385
386    #[test]
387    fn a_pile_of_obstacles_on_one_spot_examines_a_bounded_count() {
388        let mut p = Positions::new();
389        for k in 0..500usize {
390            p.insert(format!("n{k:03}"), (1.0 + k as f64 * 1e-3, 1.0));
391        }
392        let obstacles = vec![(1.0, 1.0); 20_000];
393        let (_, examined) = spread_counted(&mut p, &obstacles, &SpreadParams::new(1.0, 2)).unwrap();
394        // Per point and step: at most 32 obstacles and 32 pairs; the final count adds at most 32 pairs.
395        assert!(
396            examined <= 500 * 32 * 2 * 2 + 500 * 32,
397            "{examined} examined"
398        );
399    }
400}