1const NIL: i32 = -1;
9const MAX_CHILDREN: usize = 8;
11const MAX_DEPTH: u32 = 40;
13
14struct BhNode<const D: usize> {
15 center: [f32; D],
17 half: f32,
19 mass: f32,
21 com: [f32; D],
23 point: [f32; D],
25 point_idx: u32,
27 child: [i32; MAX_CHILDREN],
30}
31
32impl<const D: usize> BhNode<D> {
33 fn empty_leaf(center: [f32; D], half: f32) -> Self {
34 Self {
35 center,
36 half,
37 mass: 0.0,
38 com: [0.0; D],
39 point: [0.0; D],
40 point_idx: u32::MAX,
41 child: [NIL; MAX_CHILDREN],
42 }
43 }
44
45 #[inline]
47 fn is_occupied_leaf(&self) -> bool {
48 self.child[0] == NIL && self.point_idx != u32::MAX
49 }
50}
51
52pub struct BhTree<const D: usize> {
54 nodes: Vec<BhNode<D>>,
55 root: i32,
56 theta: f32,
58}
59
60impl<const D: usize> BhTree<D> {
61 pub fn with_capacity(capacity: usize, theta: f32) -> Self {
63 Self {
64 nodes: Vec::with_capacity(capacity.max(16)),
65 root: NIL,
66 theta,
67 }
68 }
69
70 pub fn clear(&mut self) {
71 self.nodes.clear();
72 self.root = NIL;
73 }
74
75 pub fn is_empty(&self) -> bool {
76 self.root == NIL
77 }
78
79 pub fn build(&mut self, points: &[[f32; D]], masses: &[f32]) {
81 self.clear();
82 if points.is_empty() {
83 return;
84 }
85 let mut lo = points[0];
87 let mut hi = points[0];
88 for p in points.iter().skip(1) {
89 for (d, pv) in p.iter().enumerate() {
90 lo[d] = lo[d].min(*pv);
91 hi[d] = hi[d].max(*pv);
92 }
93 }
94 let mut half = 0.5f32;
95 for d in 0..D {
96 half = half.max((hi[d] - lo[d]) * 0.5);
97 }
98 half = (half * 1.02).max(1.0); let mut center = [0.0f32; D];
100 for d in 0..D {
101 center[d] = (lo[d] + hi[d]) * 0.5;
102 }
103 self.root = self.push_node(BhNode::empty_leaf(center, half));
104 for (idx, p) in points.iter().enumerate() {
105 let mass = masses.get(idx).copied().unwrap_or(1.0);
106 self.insert(idx as u32, *p, mass, masses);
107 }
108 }
109
110 #[inline]
112 fn cell_for(node: &BhNode<D>, p: [f32; D]) -> (usize, [f32; D]) {
113 let mut cell = 0usize;
114 let mut center = [0.0f32; D];
115 for d in 0..D {
116 if p[d] >= node.center[d] {
117 cell |= 1 << d;
118 center[d] = node.center[d] + node.half * 0.5;
119 } else {
120 center[d] = node.center[d] - node.half * 0.5;
121 }
122 }
123 (cell, center)
124 }
125
126 fn push_node(&mut self, node: BhNode<D>) -> i32 {
127 self.nodes.push(node);
128 (self.nodes.len() - 1) as i32
129 }
130
131 fn insert(&mut self, idx: u32, p: [f32; D], mass: f32, point_masses: &[f32]) {
132 let mut cur = self.root;
133 let mut depth = 0u32;
134 loop {
135 let node = &mut self.nodes[cur as usize];
136 if node.mass == 0.0 && node.child[0] == NIL {
137 node.mass = mass;
139 node.com = p;
140 node.point = p;
141 node.point_idx = idx;
142 return;
143 }
144
145 let total = node.mass + mass;
147 for (d, pv) in p.iter().enumerate() {
148 node.com[d] = (node.com[d] * node.mass + pv * mass) / total;
149 }
150 node.mass = total;
151
152 if depth >= MAX_DEPTH {
154 return;
155 }
156
157 let (old_cell, old_center, old_point, old_idx) = {
159 let n = &self.nodes[cur as usize];
160 if n.is_occupied_leaf() {
161 let (cell, center) = Self::cell_for(n, n.point);
162 (cell, center, n.point, n.point_idx)
163 } else {
164 (0usize, [0.0f32; D], [0.0f32; D], u32::MAX)
165 }
166 };
167 let had_point = old_idx != u32::MAX;
168 if had_point {
169 self.nodes[cur as usize].point_idx = u32::MAX;
170 let old_mass = point_masses.get(old_idx as usize).copied().unwrap_or(1.0);
171 let half = self.nodes[cur as usize].half * 0.5;
172 let slot = self.push_node(BhNode::empty_leaf(old_center, half));
173 let leaf = &mut self.nodes[slot as usize];
174 leaf.mass = old_mass;
175 leaf.point = old_point;
176 leaf.com = old_point;
177 leaf.point_idx = old_idx;
178 self.nodes[cur as usize].child[old_cell] = slot;
179 }
180
181 let (cell, child_center) = Self::cell_for(&self.nodes[cur as usize], p);
183 let child = self.nodes[cur as usize].child[cell];
184 if child == NIL {
185 let half = self.nodes[cur as usize].half * 0.5;
186 let slot = self.push_node(BhNode::empty_leaf(child_center, half));
187 let leaf = &mut self.nodes[slot as usize];
188 leaf.mass = mass;
189 leaf.com = p;
190 leaf.point = p;
191 leaf.point_idx = idx;
192 self.nodes[cur as usize].child[cell] = slot;
193 return;
194 }
195 cur = child;
196 depth += 1;
197 }
198 }
199
200 #[allow(clippy::too_many_arguments)]
205 pub fn repulsion(
206 &self,
207 p: [f32; D],
208 mass: f32,
209 self_idx: u32,
210 strength: f32,
211 min_dist: f32,
212 stack: &mut Vec<i32>,
213 out: &mut [f32; D],
214 ) {
215 if self.root == NIL {
216 return;
217 }
218 let theta2 = self.theta * self.theta;
219 stack.clear();
220 stack.push(self.root);
221 while let Some(cur) = stack.pop() {
222 let node = &self.nodes[cur as usize];
223 if node.mass == 0.0 {
224 continue;
225 }
226 let mut d = [0.0f32; D];
227 let mut dist2 = 0.0f32;
228 for i in 0..D {
229 d[i] = p[i] - node.com[i];
230 dist2 += d[i] * d[i];
231 }
232 let occupied_leaf = node.is_occupied_leaf();
233 if occupied_leaf && node.point_idx == self_idx {
234 continue;
235 }
236 let size = node.half * 2.0;
237 let far_enough = size * size < theta2 * dist2;
238 if occupied_leaf || far_enough {
239 let dist = dist2.sqrt().max(min_dist);
240 let inv = 1.0 / (dist * dist * dist);
241 let f = strength * mass * node.mass * inv;
242 for i in 0..D {
243 out[i] += d[i] * f;
244 }
245 } else {
246 for &c in &node.child {
247 if c != NIL {
248 stack.push(c);
249 }
250 }
251 }
252 }
253 }
254
255 pub fn node_count(&self) -> usize {
257 self.nodes.len()
258 }
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264
265 #[test]
267 fn tiny_theta_matches_brute_force() {
268 let mut rng = crate::rng::Rng::new(2026);
269 let points: Vec<[f32; 2]> = (0..64)
270 .map(|_| [rng.next_symmetric(100.0), rng.next_symmetric(100.0)])
271 .collect();
272 let masses: Vec<f32> = (0..64).map(|i| 1.0 + i as f32 * 0.1).collect();
273
274 let mut tree: BhTree<2> = BhTree::with_capacity(64, 1e-9);
275 tree.build(&points, &masses);
276
277 let brute = |i: usize| -> [f32; 2] {
278 let mut out = [0.0f32; 2];
279 for (j, q) in points.iter().enumerate() {
280 if j == i {
281 continue;
282 }
283 let d = [p_diff(points[i][0], q[0]), p_diff(points[i][1], q[1])];
284 let dist2 = d[0] * d[0] + d[1] * d[1];
285 let dist = dist2.sqrt().max(1e-4);
286 let f = 100.0 * masses[i] * masses[j] / (dist * dist * dist);
287 out[0] += d[0] * f;
288 out[1] += d[1] * f;
289 }
290 out
291 };
292
293 let mut stack = Vec::new();
294 for i in 0..points.len() {
295 let mut bh = [0.0f32; 2];
296 tree.repulsion(
297 points[i], masses[i], i as u32, 100.0, 1e-4, &mut stack, &mut bh,
298 );
299 let bf = brute(i);
300 assert!(
301 (bh[0] - bf[0]).abs() / (bf[0].abs() + 1.0) < 1e-3
302 && (bh[1] - bf[1]).abs() / (bf[1].abs() + 1.0) < 1e-3,
303 "point {i}: bh {bh:?} vs brute {bf:?}"
304 );
305 }
306 }
307
308 fn p_diff(a: f32, b: f32) -> f32 {
309 a - b
310 }
311
312 #[test]
313 fn theta_09_approximates_brute_force_within_5_percent() {
314 let mut rng = crate::rng::Rng::new(99);
316 let points: Vec<[f32; 2]> = (0..300)
317 .map(|_| [rng.next_symmetric(200.0), rng.next_symmetric(200.0)])
318 .collect();
319 let masses = vec![1.0; 300];
320
321 let mut tree: BhTree<2> = BhTree::with_capacity(300, 0.9);
322 tree.build(&points, &masses);
323
324 let mut total_bh = 0.0f64;
325 let mut total_bf = 0.0f64;
326 let mut stack = Vec::new();
327 for (i, p) in points.iter().enumerate() {
328 let mut bh = [0.0f32; 2];
329 tree.repulsion(*p, 1.0, i as u32, 1.0, 1e-4, &mut stack, &mut bh);
330 let mut bf = [0.0f32; 2];
331 for (j, q) in points.iter().enumerate() {
332 if j == i {
333 continue;
334 }
335 let d = [p[0] - q[0], p[1] - q[1]];
336 let dist = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-4);
337 let f = 1.0 / (dist * dist);
338 bf[0] += d[0] * f / dist;
339 bf[1] += d[1] * f / dist;
340 }
341 total_bh += (bh[0].abs() + bh[1].abs()) as f64;
342 total_bf += (bf[0].abs() + bf[1].abs()) as f64;
343 }
344 assert!(
346 (total_bh - total_bf).abs() / total_bf < 0.05,
347 "bh {total_bh} vs brute {total_bf}"
348 );
349 }
350
351 #[test]
352 fn octree_also_matches_brute_force() {
353 let mut rng = crate::rng::Rng::new(5);
354 let points: Vec<[f32; 3]> = (0..64)
355 .map(|_| {
356 [
357 rng.next_symmetric(80.0),
358 rng.next_symmetric(80.0),
359 rng.next_symmetric(80.0),
360 ]
361 })
362 .collect();
363 let masses = vec![1.0; 64];
364 let mut tree: BhTree<3> = BhTree::with_capacity(64, 1e-9);
365 tree.build(&points, &masses);
366 let mut stack = Vec::new();
367 for i in 0..points.len() {
368 let mut bh = [0.0f32; 3];
369 tree.repulsion(points[i], 1.0, i as u32, 10.0, 1e-4, &mut stack, &mut bh);
370 let mut bf = [0.0f32; 3];
371 for (j, q) in points.iter().enumerate() {
372 if j == i {
373 continue;
374 }
375 let mut d = [0.0f32; 3];
376 let mut dist2 = 0.0;
377 for k in 0..3 {
378 d[k] = points[i][k] - q[k];
379 dist2 += d[k] * d[k];
380 }
381 let dist = dist2.sqrt().max(1e-4);
382 let f = 10.0 / (dist * dist * dist);
383 for k in 0..3 {
384 bf[k] += d[k] * f;
385 }
386 }
387 for k in 0..3 {
388 assert!((bh[k] - bf[k]).abs() / (bf[k].abs() + 1.0) < 1e-3);
389 }
390 }
391 }
392
393 #[test]
394 fn duplicate_points_do_not_hang() {
395 let points: Vec<[f32; 2]> = vec![[1.5, 2.5]; 40];
397 let masses = vec![1.0; 40];
398 let mut tree: BhTree<2> = BhTree::with_capacity(64, 0.9);
399 tree.build(&points, &masses);
400 let mut out = [0.0f32; 2];
401 let mut stack = Vec::new();
402 tree.repulsion(points[0], 1.0, 0, 10.0, 1e-4, &mut stack, &mut out);
403 assert!(out.iter().all(|v| v.is_finite()));
404 }
405}