Providing Python Barnes-Hut 3D simulation
Here's a concise Python implementation of a 3D Barnes-Hut N-body simulation using an octree to approximate gravitational forces with N·log(N) complexity. It defines particles, constructs the octree, computes forces with a threshold θ, and updates particle motion over time.
Below is a minimal Python implementation of an N‑body gravity simulation using the Barnes–Hut octree. It builds an octree of the particle positions each step, computes centers of mass, and uses a tunable opening angle theta to decide when to approximate a group by its center of mass, bringing the complexity down to roughly O(N log N):
import numpy as np
G = 1.0 # gravitational constant (in simulation units)
THETA = 0.5 # opening angle threshold for Barnes-Hut
SOFTENING = 0.1
TIME_STEP = 0.01
class Body:
def __init__(self, pos, vel, mass=1.0):
self.pos = np.array(pos, dtype=float)
self.vel = np.array(vel, dtype=float)
self.mass = mass
class Octree:
def __init__(self, center, half_width):
self.center = np.array(center, dtype=float) # center of this node
self.hw = half_width # half-width of this cube
self.children = [] # 8 sub-nodes
self.body = None # single body if this is a leaf
self.mass = 0.0
self.com = np.zeros(3) # center of mass
def is_leaf(self):
return len(self.children) == 0
def insert(self, body):
# If empty leaf, place the body here
if self.body is None and self.is_leaf() and self.mass == 0.0:
self.body = body
self.mass = body.mass
self.com = body.pos.copy()
return
# If not subdivided yet and contains a body, subdivide it
if self.is_leaf():
self.subdivide()
old_body = self.body
self.body = None
self._insert_into_child(old_body)
# Insert new body into a child
self._insert_into_child(body)
# Update mass and COM
self.mass += body.mass
self.com = (self.com * (self.mass - body.mass) + body.pos * body.mass) / self.mass
def _insert_into_child(self, body):
idx = 0
offset = []
for i in range(3):
if body.pos[i] > self.center[i]:
idx |= (1 << i)
# The child center is offset by +/- hw/2 in each dimension
dx = ((idx & 1) * 2 - 1) * (self.hw / 2.0)
dy = (((idx >> 1) & 1) * 2 - 1) * (self.hw / 2.0)
dz = (((idx >> 2) & 1) * 2 - 1) * (self.hw / 2.0)
self.children[idx].insert(body)
def subdivide(self):
for i in range(8):
dx = ((i & 1) * 2 - 1) * (self.hw / 2.0)
dy = (((i >> 1) & 1) * 2 - 1) * (self.hw / 2.0)
dz = (((i >> 2) & 1) * 2 - 1) * (self.hw / 2.0)
new_center = self.center + np.array([dx, dy, dz])
self.children.append(Octree(new_center, self.hw / 2.0))
def compute_force(self, body, theta=THETA):
"""Compute gravitational force on 'body' from all masses in this node."""
if self.mass == 0 or (self.is_leaf() and self.body is body):
return np.zeros(3)
r_vec = self.com - body.pos
dist = np.linalg.norm(r_vec) + SOFTENING
# If node is sufficiently far away, approximate as a single mass
if self.is_leaf() or (self.hw / dist) < theta:
return G * self.mass * r_vec / (dist**3)
# Otherwise, recurse into children
force = np.zeros(3)
for child in self.children:
force += child.compute_force(body, theta)
return force
def simulate_step(bodies, root_center, root_half_width):
# Build the octree
root = Octree(root_center, root_half_width)
for b in bodies:
root.insert(b)
# Compute forces and update velocities/positions
for b in bodies:
force = root.compute_force(b)
acc = force # since m cancels out (F = m a)
b.vel += acc * TIME_STEP
b.pos += b.vel * TIME_STEP
# Example usage:
np.random.seed(0)
N = 100
positions = np.random.uniform(-1, 1, (N, 3))
velocities = np.zeros((N, 3))
masses = np.ones(N)
bodies = [Body(pos, vel, m) for pos, vel, m in zip(positions, velocities, masses)]
# Choose a bounding box that contains all bodies
root_center = np.array([0.0, 0.0, 0.0])
root_half_width = 2.0 # covers [-2,2] in each axis
for step in range(100):
simulate_step(bodies, root_center, root_half_width)
# optional: analyze or visualize the positions in 'bodies'
This code defines a Body class for particles and an Octree that partitions space. Each simulation step builds the tree from the current positions, computes forces using the Barnes–Hut criterion (size/distance < theta), and then updates velocities and positions. Adjust THETA, TIME_STEP, and SOFTENING to tune accuracy and stability.