1use super::contour::{inside_cell, iso_lines, ClosedPath, ScalarGrid};
9use super::{GeometryError, Point, Positions};
10use crate::core::hypergraph::Hypergraph;
11
12pub const DEFAULT_LEVEL_FRACTION: f64 = 0.5;
14
15pub const DEFAULT_MAX_GRID_NODES: usize = 4_194_304;
17
18#[derive(Clone, Debug, PartialEq)]
20pub struct OutlineParams {
21 pub reach: f64,
23 pub cell: f64,
25 pub share: f64,
27 pub level_fraction: f64,
29 pub max_grid_nodes: usize,
31}
32
33impl OutlineParams {
34 #[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#[derive(Clone, Debug, PartialEq)]
66#[non_exhaustive]
67pub enum Outline {
68 Ring {
70 center: Point,
72 radius: f64,
74 },
75 Capsule {
77 a: Point,
79 radius_a: f64,
81 b: Point,
83 radius_b: f64,
85 },
86 Membrane {
88 paths: Vec<ClosedPath>,
90 },
91}
92
93#[derive(Clone, Debug, PartialEq)]
95pub struct WeightedOutline {
96 pub outline: Outline,
98 pub held: Vec<usize>,
100 pub held_weight: f64,
102 pub total_weight: f64,
104}
105
106struct Part {
108 index: usize,
109 at: Point,
110 weight: f64,
111 relative: f64,
112}
113
114fn 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
126fn 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
189fn 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
202fn 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
217pub 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 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 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#[derive(Clone, Debug, PartialEq)]
371pub struct EdgeOutline {
372 pub edge: String,
374 pub members: Vec<String>,
377 pub outline: WeightedOutline,
379}
380
381pub 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}