Skip to main content

hypergraph_rs/geometry/
place.rs

1//! Placement at a weighted mix of given positions.
2
3use indexmap::IndexMap;
4
5use super::{GeometryError, Placement, Point, Positions};
6use crate::core::hypergraph::Hypergraph;
7
8fn check_anchors(anchors: &[Point]) -> Result<(), GeometryError> {
9    for (k, a) in anchors.iter().enumerate() {
10        if !(a.0.is_finite() && a.1.is_finite()) {
11            return Err(GeometryError::NonFinitePosition {
12                item: format!("#{k}"),
13            });
14        }
15    }
16    Ok(())
17}
18
19/// The running sums of a weighted mean: total weight, weighted x, weighted y.
20#[derive(Clone, Copy, Default)]
21struct Sums {
22    total: f64,
23    x: f64,
24    y: f64,
25}
26
27impl Sums {
28    /// Checks the weight `w` of the item `name` and adds it, with its position `at`, to the sums.
29    fn add(
30        &mut self,
31        w: f64,
32        at: Point,
33        name: impl FnOnce() -> String,
34    ) -> Result<(), GeometryError> {
35        if !(w.is_finite() && w >= 0.0) {
36            return Err(GeometryError::BadWeight {
37                item: name(),
38                value: w,
39            });
40        }
41        self.total += w;
42        self.x += w * at.0;
43        self.y += w * at.1;
44        Ok(())
45    }
46
47    /// The mean, or `None` when the weights sum to zero. A sum or a result that is not finite (finite inputs can
48    /// overflow) is an error naming `name`, never an infinite or NaN point.
49    fn finish(self, name: impl FnOnce() -> String) -> Result<Option<Point>, GeometryError> {
50        if !(self.total.is_finite() && self.x.is_finite() && self.y.is_finite()) {
51            return Err(GeometryError::NonFinitePosition { item: name() });
52        }
53        if self.total > 0.0 {
54            let at = (self.x / self.total, self.y / self.total);
55            if !(at.0.is_finite() && at.1.is_finite()) {
56                return Err(GeometryError::NonFinitePosition { item: name() });
57            }
58            Ok(Some(at))
59        } else {
60            Ok(None)
61        }
62    }
63}
64
65/// Weighted mean of `anchors`, with `weights` already counted and anchors already checked.
66/// `name` gives the item named in a weight error; `whole` the item named when the result is not finite.
67fn mix(
68    anchors: &[Point],
69    weights: &[f64],
70    name: &dyn Fn(usize) -> String,
71    whole: &dyn Fn() -> String,
72) -> Result<Option<Point>, GeometryError> {
73    let mut sums = Sums::default();
74    for (k, (&w, a)) in weights.iter().zip(anchors).enumerate() {
75        sums.add(w, *a, || name(k))?;
76    }
77    sums.finish(whole)
78}
79
80/// The weighted mean of `anchors`: `(Σ wᵢ·xᵢ / Σ wᵢ, Σ wᵢ·yᵢ / Σ wᵢ)`, summed in index order.
81///
82/// Returns `Ok(None)` when every weight is zero or the slices are empty.
83///
84/// # Errors
85///
86/// `CountMismatch` (item `"weights"`) when the slices differ in length, `BadWeight` for a weight that is negative or
87/// not finite, `NonFinitePosition` for an anchor that is not finite. Items are named `#<index>`.
88pub fn barycentre(anchors: &[Point], weights: &[f64]) -> Result<Option<Point>, GeometryError> {
89    if anchors.len() != weights.len() {
90        return Err(GeometryError::CountMismatch {
91            item: "weights".to_string(),
92            expected: anchors.len(),
93            found: weights.len(),
94        });
95    }
96    check_anchors(anchors)?;
97    mix(anchors, weights, &|k| format!("#{k}"), &|| {
98        "barycentre".to_string()
99    })
100}
101
102/// Places each item at the mix of `corners` given by its row of shares.
103///
104/// Each row holds one item's shares over the corners; a row need not sum to one. A row of zeros leaves the item in
105/// `unplaced`. Placed items and unplaced items both keep the input's order.
106///
107/// # Errors
108///
109/// `NonFinitePosition` (item `#<k>`) for a corner that is not finite, `CountMismatch` (item: the row's id) for a row
110/// whose length is not the count of corners, `BadWeight` (item: the row's id) for a share that is negative or not
111/// finite. A row whose sums overflow gives `NonFinitePosition` (item: the row's id).
112pub fn corner_mix(
113    corners: &[Point],
114    shares: &[(String, Vec<f64>)],
115) -> Result<Placement, GeometryError> {
116    check_anchors(corners)?;
117    let mut placement = Placement {
118        positions: Positions::new(),
119        unplaced: Vec::new(),
120    };
121    for (id, row) in shares {
122        if row.len() != corners.len() {
123            return Err(GeometryError::CountMismatch {
124                item: id.clone(),
125                expected: corners.len(),
126                found: row.len(),
127            });
128        }
129        match mix(corners, row, &|_| id.clone(), &|| id.clone())? {
130            Some(at) => {
131                placement.positions.insert(id.clone(), at);
132            }
133            None => placement.unplaced.push(id.clone()),
134        }
135    }
136    Ok(placement)
137}
138
139/// Places each node of `h` at the weighted mean of the positions of the anchored hyperedges it belongs to.
140///
141/// An anchor is a hyperedge with a fixed position in `anchors`. A node's weight on an anchor is
142/// `weight(&membership value)`. Memberships of hyperedges that are not anchors are ignored. A node whose weights on
143/// anchors sum to zero (or that belongs to no anchor) is listed in `unplaced`, never put at the origin.
144///
145/// Sums run over `anchors` in their order, then over each anchor's members in `members_with_data` order.
146/// `positions` lists placed nodes in `node_ids()` order; `unplaced` lists the rest in `node_ids()` order.
147///
148/// # Errors
149///
150/// `UnknownEdge` for an anchor id not in `h`, `NonFinitePosition` (item: the edge id) for an anchor position that is
151/// not finite, `BadWeight` (item: the node id) for a weight that is negative or not finite, `NonFinitePosition`
152/// (item: the node id) for a node whose sums overflow.
153pub fn anchored_placement<N, E, M>(
154    h: &Hypergraph<N, E, M>,
155    anchors: &Positions,
156    weight: impl Fn(&M) -> f64,
157) -> Result<Placement, GeometryError> {
158    let ids = h.node_ids();
159    let index: IndexMap<&str, usize> = ids
160        .iter()
161        .enumerate()
162        .map(|(k, id)| (id.as_str(), k))
163        .collect();
164    // total weight, weighted x, weighted y, per node in node order
165    let mut sums = vec![Sums::default(); ids.len()];
166    for (edge, at) in anchors.iter() {
167        let Some(members) = h.members_with_data(edge) else {
168            return Err(GeometryError::UnknownEdge(edge.to_string()));
169        };
170        if !(at.0.is_finite() && at.1.is_finite()) {
171            return Err(GeometryError::NonFinitePosition {
172                item: edge.to_string(),
173            });
174        }
175        for (node, data) in members {
176            let w = weight(data);
177            let slot = index.get(node.as_str()).copied();
178            match slot {
179                Some(k) => sums[k].add(w, at, || node)?,
180                // A member that is not a node still has its weight checked.
181                None => Sums::default().add(w, at, || node)?,
182            }
183        }
184    }
185    let mut placement = Placement::default();
186    for (id, s) in ids.into_iter().zip(sums) {
187        match s.finish(|| id.clone())? {
188            Some(at) => {
189                placement.positions.insert(id, at);
190            }
191            None => placement.unplaced.push(id),
192        }
193    }
194    Ok(placement)
195}