const NIL: i32 = -1;
const MAX_CHILDREN: usize = 8;
const MAX_DEPTH: u32 = 40;
struct BhNode<const D: usize> {
center: [f32; D],
half: f32,
mass: f32,
com: [f32; D],
point: [f32; D],
point_idx: u32,
child: [i32; MAX_CHILDREN],
}
impl<const D: usize> BhNode<D> {
fn empty_leaf(center: [f32; D], half: f32) -> Self {
Self {
center,
half,
mass: 0.0,
com: [0.0; D],
point: [0.0; D],
point_idx: u32::MAX,
child: [NIL; MAX_CHILDREN],
}
}
#[inline]
fn is_occupied_leaf(&self) -> bool {
self.child[0] == NIL && self.point_idx != u32::MAX
}
}
pub struct BhTree<const D: usize> {
nodes: Vec<BhNode<D>>,
root: i32,
theta: f32,
}
impl<const D: usize> BhTree<D> {
pub fn with_capacity(capacity: usize, theta: f32) -> Self {
Self {
nodes: Vec::with_capacity(capacity.max(16)),
root: NIL,
theta,
}
}
pub fn clear(&mut self) {
self.nodes.clear();
self.root = NIL;
}
pub fn is_empty(&self) -> bool {
self.root == NIL
}
pub fn build(&mut self, points: &[[f32; D]], masses: &[f32]) {
self.clear();
if points.is_empty() {
return;
}
let mut lo = points[0];
let mut hi = points[0];
for p in points.iter().skip(1) {
for (d, pv) in p.iter().enumerate() {
lo[d] = lo[d].min(*pv);
hi[d] = hi[d].max(*pv);
}
}
let mut half = 0.5f32;
for d in 0..D {
half = half.max((hi[d] - lo[d]) * 0.5);
}
half = (half * 1.02).max(1.0); let mut center = [0.0f32; D];
for d in 0..D {
center[d] = (lo[d] + hi[d]) * 0.5;
}
self.root = self.push_node(BhNode::empty_leaf(center, half));
for (idx, p) in points.iter().enumerate() {
let mass = masses.get(idx).copied().unwrap_or(1.0);
self.insert(idx as u32, *p, mass, masses);
}
}
#[inline]
fn cell_for(node: &BhNode<D>, p: [f32; D]) -> (usize, [f32; D]) {
let mut cell = 0usize;
let mut center = [0.0f32; D];
for d in 0..D {
if p[d] >= node.center[d] {
cell |= 1 << d;
center[d] = node.center[d] + node.half * 0.5;
} else {
center[d] = node.center[d] - node.half * 0.5;
}
}
(cell, center)
}
fn push_node(&mut self, node: BhNode<D>) -> i32 {
self.nodes.push(node);
(self.nodes.len() - 1) as i32
}
fn insert(&mut self, idx: u32, p: [f32; D], mass: f32, point_masses: &[f32]) {
let mut cur = self.root;
let mut depth = 0u32;
loop {
let node = &mut self.nodes[cur as usize];
if node.mass == 0.0 && node.child[0] == NIL {
node.mass = mass;
node.com = p;
node.point = p;
node.point_idx = idx;
return;
}
let total = node.mass + mass;
for (d, pv) in p.iter().enumerate() {
node.com[d] = (node.com[d] * node.mass + pv * mass) / total;
}
node.mass = total;
if depth >= MAX_DEPTH {
return;
}
let (old_cell, old_center, old_point, old_idx) = {
let n = &self.nodes[cur as usize];
if n.is_occupied_leaf() {
let (cell, center) = Self::cell_for(n, n.point);
(cell, center, n.point, n.point_idx)
} else {
(0usize, [0.0f32; D], [0.0f32; D], u32::MAX)
}
};
let had_point = old_idx != u32::MAX;
if had_point {
self.nodes[cur as usize].point_idx = u32::MAX;
let old_mass = point_masses.get(old_idx as usize).copied().unwrap_or(1.0);
let half = self.nodes[cur as usize].half * 0.5;
let slot = self.push_node(BhNode::empty_leaf(old_center, half));
let leaf = &mut self.nodes[slot as usize];
leaf.mass = old_mass;
leaf.point = old_point;
leaf.com = old_point;
leaf.point_idx = old_idx;
self.nodes[cur as usize].child[old_cell] = slot;
}
let (cell, child_center) = Self::cell_for(&self.nodes[cur as usize], p);
let child = self.nodes[cur as usize].child[cell];
if child == NIL {
let half = self.nodes[cur as usize].half * 0.5;
let slot = self.push_node(BhNode::empty_leaf(child_center, half));
let leaf = &mut self.nodes[slot as usize];
leaf.mass = mass;
leaf.com = p;
leaf.point = p;
leaf.point_idx = idx;
self.nodes[cur as usize].child[cell] = slot;
return;
}
cur = child;
depth += 1;
}
}
#[allow(clippy::too_many_arguments)]
pub fn repulsion(
&self,
p: [f32; D],
mass: f32,
self_idx: u32,
strength: f32,
min_dist: f32,
stack: &mut Vec<i32>,
out: &mut [f32; D],
) {
if self.root == NIL {
return;
}
let theta2 = self.theta * self.theta;
stack.clear();
stack.push(self.root);
while let Some(cur) = stack.pop() {
let node = &self.nodes[cur as usize];
if node.mass == 0.0 {
continue;
}
let mut d = [0.0f32; D];
let mut dist2 = 0.0f32;
for i in 0..D {
d[i] = p[i] - node.com[i];
dist2 += d[i] * d[i];
}
let occupied_leaf = node.is_occupied_leaf();
if occupied_leaf && node.point_idx == self_idx {
continue;
}
let size = node.half * 2.0;
let far_enough = size * size < theta2 * dist2;
if occupied_leaf || far_enough {
let dist = dist2.sqrt().max(min_dist);
let inv = 1.0 / (dist * dist * dist);
let f = strength * mass * node.mass * inv;
for i in 0..D {
out[i] += d[i] * f;
}
} else {
for &c in &node.child {
if c != NIL {
stack.push(c);
}
}
}
}
}
pub fn node_count(&self) -> usize {
self.nodes.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tiny_theta_matches_brute_force() {
let mut rng = crate::rng::Rng::new(2026);
let points: Vec<[f32; 2]> = (0..64)
.map(|_| [rng.next_symmetric(100.0), rng.next_symmetric(100.0)])
.collect();
let masses: Vec<f32> = (0..64).map(|i| 1.0 + i as f32 * 0.1).collect();
let mut tree: BhTree<2> = BhTree::with_capacity(64, 1e-9);
tree.build(&points, &masses);
let brute = |i: usize| -> [f32; 2] {
let mut out = [0.0f32; 2];
for (j, q) in points.iter().enumerate() {
if j == i {
continue;
}
let d = [p_diff(points[i][0], q[0]), p_diff(points[i][1], q[1])];
let dist2 = d[0] * d[0] + d[1] * d[1];
let dist = dist2.sqrt().max(1e-4);
let f = 100.0 * masses[i] * masses[j] / (dist * dist * dist);
out[0] += d[0] * f;
out[1] += d[1] * f;
}
out
};
let mut stack = Vec::new();
for i in 0..points.len() {
let mut bh = [0.0f32; 2];
tree.repulsion(
points[i], masses[i], i as u32, 100.0, 1e-4, &mut stack, &mut bh,
);
let bf = brute(i);
assert!(
(bh[0] - bf[0]).abs() / (bf[0].abs() + 1.0) < 1e-3
&& (bh[1] - bf[1]).abs() / (bf[1].abs() + 1.0) < 1e-3,
"point {i}: bh {bh:?} vs brute {bf:?}"
);
}
}
fn p_diff(a: f32, b: f32) -> f32 {
a - b
}
#[test]
fn theta_09_approximates_brute_force_within_5_percent() {
let mut rng = crate::rng::Rng::new(99);
let points: Vec<[f32; 2]> = (0..300)
.map(|_| [rng.next_symmetric(200.0), rng.next_symmetric(200.0)])
.collect();
let masses = vec![1.0; 300];
let mut tree: BhTree<2> = BhTree::with_capacity(300, 0.9);
tree.build(&points, &masses);
let mut total_bh = 0.0f64;
let mut total_bf = 0.0f64;
let mut stack = Vec::new();
for (i, p) in points.iter().enumerate() {
let mut bh = [0.0f32; 2];
tree.repulsion(*p, 1.0, i as u32, 1.0, 1e-4, &mut stack, &mut bh);
let mut bf = [0.0f32; 2];
for (j, q) in points.iter().enumerate() {
if j == i {
continue;
}
let d = [p[0] - q[0], p[1] - q[1]];
let dist = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-4);
let f = 1.0 / (dist * dist);
bf[0] += d[0] * f / dist;
bf[1] += d[1] * f / dist;
}
total_bh += (bh[0].abs() + bh[1].abs()) as f64;
total_bf += (bf[0].abs() + bf[1].abs()) as f64;
}
assert!(
(total_bh - total_bf).abs() / total_bf < 0.05,
"bh {total_bh} vs brute {total_bf}"
);
}
#[test]
fn octree_also_matches_brute_force() {
let mut rng = crate::rng::Rng::new(5);
let points: Vec<[f32; 3]> = (0..64)
.map(|_| {
[
rng.next_symmetric(80.0),
rng.next_symmetric(80.0),
rng.next_symmetric(80.0),
]
})
.collect();
let masses = vec![1.0; 64];
let mut tree: BhTree<3> = BhTree::with_capacity(64, 1e-9);
tree.build(&points, &masses);
let mut stack = Vec::new();
for i in 0..points.len() {
let mut bh = [0.0f32; 3];
tree.repulsion(points[i], 1.0, i as u32, 10.0, 1e-4, &mut stack, &mut bh);
let mut bf = [0.0f32; 3];
for (j, q) in points.iter().enumerate() {
if j == i {
continue;
}
let mut d = [0.0f32; 3];
let mut dist2 = 0.0;
for k in 0..3 {
d[k] = points[i][k] - q[k];
dist2 += d[k] * d[k];
}
let dist = dist2.sqrt().max(1e-4);
let f = 10.0 / (dist * dist * dist);
for k in 0..3 {
bf[k] += d[k] * f;
}
}
for k in 0..3 {
assert!((bh[k] - bf[k]).abs() / (bf[k].abs() + 1.0) < 1e-3);
}
}
}
#[test]
fn duplicate_points_do_not_hang() {
let points: Vec<[f32; 2]> = vec![[1.5, 2.5]; 40];
let masses = vec![1.0; 40];
let mut tree: BhTree<2> = BhTree::with_capacity(64, 0.9);
tree.build(&points, &masses);
let mut out = [0.0f32; 2];
let mut stack = Vec::new();
tree.repulsion(points[0], 1.0, 0, 10.0, 1e-4, &mut stack, &mut out);
assert!(out.iter().all(|v| v.is_finite()));
}
}