Skip to main content

hypergraph_rs/geometry/
outline.rs

1//! The weighted outline of a set of points.
2//!
3//! Each member of a set has a position and a number. Only members with a number above zero take part. The outline
4//! is a [`Ring`](Outline::Ring) round one member, a [`Capsule`](Outline::Capsule) round two, or a
5//! [`Membrane`](Outline::Membrane) of closed paths round three or more, drawn from a field that every member
6//! raises to a hill as wide as `reach`, scaled by its number relative to the largest.
7
8use super::contour::{inside_cell, iso_lines, ClosedPath, ScalarGrid};
9use super::{GeometryError, Point, Positions};
10use crate::core::hypergraph::Hypergraph;
11
12/// The default fraction of a member's level that the line of a membrane is drawn at.
13pub const DEFAULT_LEVEL_FRACTION: f64 = 0.5;
14
15/// The default most nodes the outline's grid may hold.
16pub const DEFAULT_MAX_GRID_NODES: usize = 4_194_304;
17
18/// The parameters of [`weighted_outline`].
19#[derive(Clone, Debug, PartialEq)]
20pub struct OutlineParams {
21    /// How far a member's hill reaches: the field of a member is zero at this distance. Finite and above zero.
22    pub reach: f64,
23    /// The distance between grid nodes. Finite, above zero and at most `reach / 2`.
24    pub cell: f64,
25    /// The share of the total number the outline must hold, in `(0, 1]`.
26    pub share: f64,
27    /// The fraction of the level of the last member held at which a membrane's line is drawn, in `(0, 1]`.
28    pub level_fraction: f64,
29    /// The most nodes the grid may hold; a larger grid is [`GeometryError::GridTooLarge`].
30    pub max_grid_nodes: usize,
31}
32
33impl OutlineParams {
34    /// Parameters with [`DEFAULT_LEVEL_FRACTION`] and [`DEFAULT_MAX_GRID_NODES`].
35    #[must_use]
36    pub fn new(reach: f64, cell: f64, share: f64) -> Self {
37        Self {
38            reach,
39            cell,
40            share,
41            level_fraction: DEFAULT_LEVEL_FRACTION,
42            max_grid_nodes: DEFAULT_MAX_GRID_NODES,
43        }
44    }
45
46    fn validate(&self) -> Result<(), GeometryError> {
47        let bad = |name: &'static str, value: f64| Err(GeometryError::BadParameter { name, value });
48        if !(self.reach.is_finite() && self.reach > 0.0) {
49            return bad("reach", self.reach);
50        }
51        if !(self.cell.is_finite() && self.cell > 0.0 && self.cell <= self.reach / 2.0) {
52            return bad("cell", self.cell);
53        }
54        if !(self.share > 0.0 && self.share <= 1.0) {
55            return bad("share", self.share);
56        }
57        if !(self.level_fraction > 0.0 && self.level_fraction <= 1.0) {
58            return bad("level_fraction", self.level_fraction);
59        }
60        Ok(())
61    }
62}
63
64/// The shape of an outline.
65#[derive(Clone, Debug, PartialEq)]
66#[non_exhaustive]
67pub enum Outline {
68    /// A circle round one member.
69    Ring {
70        /// The member's position.
71        center: Point,
72        /// `reach * (0.5 + 0.5 * relative weight)`.
73        radius: f64,
74    },
75    /// The hull of two circles, round two members.
76    Capsule {
77        /// The position of the member with the lower index.
78        a: Point,
79        /// The radius at `a`.
80        radius_a: f64,
81        /// The position of the other member.
82        b: Point,
83        /// The radius at `b`.
84        radius_b: f64,
85    },
86    /// Closed paths round three or more members.
87    Membrane {
88        /// Outer paths run counter-clockwise, holes clockwise; the fill is even-odd.
89        paths: Vec<ClosedPath>,
90    },
91}
92
93/// An outline and what it holds.
94#[derive(Clone, Debug, PartialEq)]
95pub struct WeightedOutline {
96    /// The shape.
97    pub outline: Outline,
98    /// The indices, ascending, of every member with a number above zero that lies inside the outline as drawn.
99    pub held: Vec<usize>,
100    /// The sum of the numbers of the held members, in index order.
101    pub held_weight: f64,
102    /// The sum of the numbers above zero, in index order.
103    pub total_weight: f64,
104}
105
106/// A member with a number above zero.
107struct Part {
108    index: usize,
109    at: Point,
110    weight: f64,
111    relative: f64,
112}
113
114/// The radius of a ring or of an end of a capsule.
115fn radius_of(reach: f64, relative: f64) -> f64 {
116    reach * (0.5 + 0.5 * relative)
117}
118
119fn too_large(limit: usize) -> GeometryError {
120    GeometryError::GridTooLarge {
121        nodes: usize::MAX,
122        limit,
123    }
124}
125
126/// The grid on the lattice of `cell` through the origin that covers every part widened by `reach + cell`, and the
127/// field on it.
128fn build_field(parts: &[Part], params: &OutlineParams) -> Result<ScalarGrid, GeometryError> {
129    let (reach, cell) = (params.reach, params.cell);
130    let margin = reach + cell;
131    let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
132    let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
133    for part in parts {
134        min_x = min_x.min(part.at.0);
135        min_y = min_y.min(part.at.1);
136        max_x = max_x.max(part.at.0);
137        max_y = max_y.max(part.at.1);
138    }
139    let lo_col = ((min_x - margin) / cell).floor();
140    let lo_row = ((min_y - margin) / cell).floor();
141    let hi_col = ((max_x + margin) / cell).floor() + 1.0;
142    let hi_row = ((max_y + margin) / cell).floor() + 1.0;
143    let count = |lo: f64, hi: f64| -> Result<usize, GeometryError> {
144        let n = hi - lo + 1.0;
145        if n.is_finite() && n >= 1.0 && n < usize::MAX as f64 {
146            Ok(n as usize)
147        } else {
148            Err(too_large(params.max_grid_nodes))
149        }
150    };
151    let cols = count(lo_col, hi_col)?;
152    let rows = count(lo_row, hi_row)?;
153    let nodes = cols
154        .checked_mul(rows)
155        .ok_or_else(|| too_large(params.max_grid_nodes))?;
156    if nodes > params.max_grid_nodes {
157        return Err(GeometryError::GridTooLarge {
158            nodes,
159            limit: params.max_grid_nodes,
160        });
161    }
162    let mut grid = ScalarGrid::zeros((lo_col * cell, lo_row * cell), cell, cols, rows)?;
163    let reach2 = reach * reach;
164    let (ox, oy) = grid.origin;
165    let span = |p: f64, o: f64, n: usize| -> (usize, usize) {
166        let last = (n - 1) as f64;
167        let lo = ((p - reach - o) / cell).floor().max(0.0).min(last);
168        let hi = (((p + reach - o) / cell).floor() + 1.0).max(0.0).min(last);
169        (lo as usize, hi as usize)
170    };
171    for part in parts {
172        let (c0, c1) = span(part.at.0, ox, cols);
173        let (r0, r1) = span(part.at.1, oy, rows);
174        for r in r0..=r1 {
175            let dy = oy + r as f64 * cell - part.at.1;
176            for c in c0..=c1 {
177                let dx = ox + c as f64 * cell - part.at.0;
178                let d2 = dx * dx + dy * dy;
179                if d2 < reach2 {
180                    let rest = 1.0 - d2 / reach2;
181                    grid.values[r * cols + c] += part.relative * (rest * rest);
182                }
183            }
184        }
185    }
186    Ok(grid)
187}
188
189/// The held members and their weight, by one pass of `inside` over the parts.
190fn held_by(parts: &[Part], inside: impl Fn(Point) -> bool) -> (Vec<usize>, f64) {
191    let mut held = Vec::new();
192    let mut weight = 0.0;
193    for part in parts {
194        if inside(part.at) {
195            held.push(part.index);
196            weight += part.weight;
197        }
198    }
199    (held, weight)
200}
201
202/// Whether `at` lies within the capsule: its distance to the segment `a b` is at most the radius interpolated along
203/// the segment.
204fn in_capsule(at: Point, a: Point, ra: f64, b: Point, rb: f64) -> bool {
205    let (ex, ey) = (b.0 - a.0, b.1 - a.1);
206    let len2 = ex * ex + ey * ey;
207    let t = if len2 > 0.0 {
208        (((at.0 - a.0) * ex + (at.1 - a.1) * ey) / len2).clamp(0.0, 1.0)
209    } else {
210        0.0
211    };
212    let (dx, dy) = (at.0 - (a.0 + ex * t), at.1 - (a.1 + ey * t));
213    let r = ra + (rb - ra) * t;
214    dx * dx + dy * dy <= r * r
215}
216
217/// The outline of a set of weighted points.
218///
219/// `members` are `(position, number)` pairs. Only members with a number above zero take part; a zero member's
220/// position is never read, so it may be anything. With none above zero the result is `Ok(None)`.
221///
222/// Only the numbers relative to the largest count. A member's field is `w * (1 - q^2)^2` for `q = distance / reach
223/// < 1`, with `w` the number divided by the largest, summed over members on a grid whose nodes lie on the lattice of
224/// `cell` through `(0, 0)`. The members the outline must hold are the shortest prefix, by field level at their own
225/// positions (highest first, ties by index), whose numbers sum to at least `share` of the total. One member gives a
226/// [`Ring`](Outline::Ring) of radius `reach * (0.5 + 0.5 * w)`, two a [`Capsule`](Outline::Capsule) with such a
227/// radius at each end, three or more a [`Membrane`](Outline::Membrane) drawn at `level_fraction` of the level of
228/// the last member of that prefix.
229///
230/// `held` is measured on the outline as drawn. If a membrane holds less than `share` of the total, its level steps
231/// down, to `level_fraction` of the level of the member with the next lower level, until it does (found by
232/// bisection) or every member is the reference; `held` then reports what it holds.
233///
234/// # Errors
235///
236/// [`GeometryError::BadParameter`] naming `reach`, `cell`, `share` or `level_fraction`;
237/// [`GeometryError::BadWeight`] for a number that is negative or not finite, or that makes the running sum of the
238/// numbers overflow (`item` is `#<index>`; `value` is the number, or the sum that is not finite);
239/// [`GeometryError::NonFinitePosition`] for a member above zero whose position is not finite;
240/// [`GeometryError::GridTooLarge`] when the grid would hold more than `max_grid_nodes` nodes, or a count that does
241/// not fit a `usize`. The check comes before anything is allocated.
242pub fn weighted_outline(
243    members: &[(Point, f64)],
244    params: &OutlineParams,
245) -> Result<Option<WeightedOutline>, GeometryError> {
246    params.validate()?;
247    let mut total = 0.0_f64;
248    let mut largest = 0.0_f64;
249    for (index, &(at, weight)) in members.iter().enumerate() {
250        if !(weight.is_finite() && weight >= 0.0) {
251            return Err(GeometryError::BadWeight {
252                item: format!("#{index}"),
253                value: weight,
254            });
255        }
256        if weight > 0.0 {
257            if !(at.0.is_finite() && at.1.is_finite()) {
258                return Err(GeometryError::NonFinitePosition {
259                    item: format!("#{index}"),
260                });
261            }
262            total += weight;
263            if !total.is_finite() {
264                return Err(GeometryError::BadWeight {
265                    item: format!("#{index}"),
266                    value: total,
267                });
268            }
269            largest = largest.max(weight);
270        }
271    }
272    let parts: Vec<Part> = members
273        .iter()
274        .enumerate()
275        .filter(|(_, &(_, weight))| weight > 0.0)
276        .map(|(index, &(at, weight))| Part {
277            index,
278            at,
279            weight,
280            relative: weight / largest,
281        })
282        .collect();
283    if parts.is_empty() {
284        return Ok(None);
285    }
286    let grid = build_field(&parts, params)?;
287    let level = |part: &Part| grid.sample(part.at).unwrap_or(0.0);
288    // Positions in `parts`, by level (highest first), ties by index.
289    let mut order: Vec<usize> = (0..parts.len()).collect();
290    let levels: Vec<f64> = parts.iter().map(level).collect();
291    order.sort_by(|&a, &b| levels[b].total_cmp(&levels[a]).then(a.cmp(&b)));
292    let wanted = params.share * total;
293    let mut prefix = 0.0;
294    let mut k = order.len();
295    for (taken, &p) in order.iter().enumerate() {
296        prefix += parts[p].weight;
297        if prefix >= wanted {
298            k = taken + 1;
299            break;
300        }
301    }
302    let radius = |p: &Part| radius_of(params.reach, p.relative);
303    let (outline, (held, held_weight)) = match k {
304        1 => {
305            let part = &parts[order[0]];
306            let (center, r) = (part.at, radius(part));
307            let held = held_by(&parts, |at| {
308                let (dx, dy) = (at.0 - center.0, at.1 - center.1);
309                dx * dx + dy * dy <= r * r
310            });
311            (Outline::Ring { center, radius: r }, held)
312        }
313        2 => {
314            let (first, second) = (order[0].min(order[1]), order[0].max(order[1]));
315            let (pa, pb) = (&parts[first], &parts[second]);
316            let (a, ra, b, rb) = (pa.at, radius(pa), pb.at, radius(pb));
317            let held = held_by(&parts, |at| in_capsule(at, a, ra, b, rb));
318            (
319                Outline::Capsule {
320                    a,
321                    radius_a: ra,
322                    b,
323                    radius_b: rb,
324                },
325                held,
326            )
327        }
328        _ => {
329            let threshold_of = |j: usize| params.level_fraction * levels[order[j - 1]];
330            let reaches = |j: usize| {
331                held_by(&parts, |at| inside_cell(&grid, threshold_of(j), at)).1 >= wanted
332            };
333            let n = order.len();
334            let chosen = if k == n || reaches(k) {
335                k
336            } else if !reaches(n) {
337                n
338            } else {
339                // `lo` falls short, `hi` reaches: the smallest j that reaches lies in `(lo, hi]`.
340                let (mut lo, mut hi) = (k, n);
341                while hi - lo > 1 {
342                    let mid = lo + (hi - lo) / 2;
343                    if reaches(mid) {
344                        hi = mid;
345                    } else {
346                        lo = mid;
347                    }
348                }
349                hi
350            };
351            let threshold = threshold_of(chosen);
352            let held = held_by(&parts, |at| inside_cell(&grid, threshold, at));
353            (
354                Outline::Membrane {
355                    paths: iso_lines(&grid, threshold),
356                },
357                held,
358            )
359        }
360    };
361    Ok(Some(WeightedOutline {
362        outline,
363        held,
364        held_weight,
365        total_weight: total,
366    }))
367}
368
369/// The outline of one hyperedge, and the members it was drawn from.
370#[derive(Clone, Debug, PartialEq)]
371pub struct EdgeOutline {
372    /// The hyperedge's id.
373    pub edge: String,
374    /// The members with a number above zero, in the order `members_with_data` lists them.
375    /// `outline.held` indexes into this list.
376    pub members: Vec<String>,
377    /// The outline of those members.
378    pub outline: WeightedOutline,
379}
380
381/// The outline of the hyperedge `edge_id`, from the numbers on its memberships and the positions of its members.
382///
383/// Members are read with `members_with_data`, in that order. `weight` reads the number from a membership's value.
384/// A member whose number is zero is skipped before its position is looked up, so it needs none. Otherwise the rules
385/// of [`weighted_outline`] apply. `Ok(None)` when no member has a number above zero.
386///
387/// # Errors
388///
389/// [`GeometryError::UnknownEdge`] when the hypergraph has no such hyperedge;
390/// [`GeometryError::BadWeight`] for a number that is negative or not finite, or that makes the running sum of the
391/// numbers overflow (`item` is the node id; `value` is the number, or the sum that is not finite);
392/// [`GeometryError::NoPosition`] for a member above zero with no entry in `positions`;
393/// [`GeometryError::NonFinitePosition`] for a member above zero whose position is not finite (`item` is the node
394/// id); and any error of [`weighted_outline`] about `params`.
395pub fn edge_outline<N, E, M>(
396    h: &Hypergraph<N, E, M>,
397    edge_id: &str,
398    positions: &Positions,
399    weight: impl Fn(&M) -> f64,
400    params: &OutlineParams,
401) -> Result<Option<EdgeOutline>, GeometryError> {
402    let Some(listing) = h.members_with_data(edge_id) else {
403        return Err(GeometryError::UnknownEdge(edge_id.to_string()));
404    };
405    let mut members = Vec::new();
406    let mut points: Vec<(Point, f64)> = Vec::new();
407    let mut total = 0.0_f64;
408    for (node, data) in listing {
409        let w = weight(data);
410        if !(w.is_finite() && w >= 0.0) {
411            return Err(GeometryError::BadWeight {
412                item: node,
413                value: w,
414            });
415        }
416        if w == 0.0 {
417            continue;
418        }
419        let Some(at) = positions.get(&node) else {
420            return Err(GeometryError::NoPosition {
421                edge: edge_id.to_string(),
422                node,
423            });
424        };
425        if !(at.0.is_finite() && at.1.is_finite()) {
426            return Err(GeometryError::NonFinitePosition { item: node });
427        }
428        total += w;
429        if !total.is_finite() {
430            return Err(GeometryError::BadWeight {
431                item: node,
432                value: total,
433            });
434        }
435        members.push(node);
436        points.push((at, w));
437    }
438    Ok(
439        weighted_outline(&points, params)?.map(|outline| EdgeOutline {
440            edge: edge_id.to_string(),
441            members,
442            outline,
443        }),
444    )
445}