use indexmap::IndexMap;
use super::{GeometryError, Placement, Point, Positions};
use crate::core::hypergraph::Hypergraph;
fn check_anchors(anchors: &[Point]) -> Result<(), GeometryError> {
for (k, a) in anchors.iter().enumerate() {
if !(a.0.is_finite() && a.1.is_finite()) {
return Err(GeometryError::NonFinitePosition {
item: format!("#{k}"),
});
}
}
Ok(())
}
#[derive(Clone, Copy, Default)]
struct Sums {
total: f64,
x: f64,
y: f64,
}
impl Sums {
fn add(
&mut self,
w: f64,
at: Point,
name: impl FnOnce() -> String,
) -> Result<(), GeometryError> {
if !(w.is_finite() && w >= 0.0) {
return Err(GeometryError::BadWeight {
item: name(),
value: w,
});
}
self.total += w;
self.x += w * at.0;
self.y += w * at.1;
Ok(())
}
fn finish(self, name: impl FnOnce() -> String) -> Result<Option<Point>, GeometryError> {
if !(self.total.is_finite() && self.x.is_finite() && self.y.is_finite()) {
return Err(GeometryError::NonFinitePosition { item: name() });
}
if self.total > 0.0 {
let at = (self.x / self.total, self.y / self.total);
if !(at.0.is_finite() && at.1.is_finite()) {
return Err(GeometryError::NonFinitePosition { item: name() });
}
Ok(Some(at))
} else {
Ok(None)
}
}
}
fn mix(
anchors: &[Point],
weights: &[f64],
name: &dyn Fn(usize) -> String,
whole: &dyn Fn() -> String,
) -> Result<Option<Point>, GeometryError> {
let mut sums = Sums::default();
for (k, (&w, a)) in weights.iter().zip(anchors).enumerate() {
sums.add(w, *a, || name(k))?;
}
sums.finish(whole)
}
pub fn barycentre(anchors: &[Point], weights: &[f64]) -> Result<Option<Point>, GeometryError> {
if anchors.len() != weights.len() {
return Err(GeometryError::CountMismatch {
item: "weights".to_string(),
expected: anchors.len(),
found: weights.len(),
});
}
check_anchors(anchors)?;
mix(anchors, weights, &|k| format!("#{k}"), &|| {
"barycentre".to_string()
})
}
pub fn corner_mix(
corners: &[Point],
shares: &[(String, Vec<f64>)],
) -> Result<Placement, GeometryError> {
check_anchors(corners)?;
let mut placement = Placement {
positions: Positions::new(),
unplaced: Vec::new(),
};
for (id, row) in shares {
if row.len() != corners.len() {
return Err(GeometryError::CountMismatch {
item: id.clone(),
expected: corners.len(),
found: row.len(),
});
}
match mix(corners, row, &|_| id.clone(), &|| id.clone())? {
Some(at) => {
placement.positions.insert(id.clone(), at);
}
None => placement.unplaced.push(id.clone()),
}
}
Ok(placement)
}
pub fn anchored_placement<N, E, M>(
h: &Hypergraph<N, E, M>,
anchors: &Positions,
weight: impl Fn(&M) -> f64,
) -> Result<Placement, GeometryError> {
let ids = h.node_ids();
let index: IndexMap<&str, usize> = ids
.iter()
.enumerate()
.map(|(k, id)| (id.as_str(), k))
.collect();
let mut sums = vec![Sums::default(); ids.len()];
for (edge, at) in anchors.iter() {
let Some(members) = h.members_with_data(edge) else {
return Err(GeometryError::UnknownEdge(edge.to_string()));
};
if !(at.0.is_finite() && at.1.is_finite()) {
return Err(GeometryError::NonFinitePosition {
item: edge.to_string(),
});
}
for (node, data) in members {
let w = weight(data);
let slot = index.get(node.as_str()).copied();
match slot {
Some(k) => sums[k].add(w, at, || node)?,
None => Sums::default().add(w, at, || node)?,
}
}
}
let mut placement = Placement::default();
for (id, s) in ids.into_iter().zip(sums) {
match s.finish(|| id.clone())? {
Some(at) => {
placement.positions.insert(id, at);
}
None => placement.unplaced.push(id),
}
}
Ok(placement)
}