Physical modeling with particles: N-body and molecular dynamics
Simulate interacting particles for gravity and molecular dynamics: build Lennard-Jones forces, periodic boundaries, neighbor lists and a thermostat, and study Barnes–Hut acceleration and numerical validation.
After this lesson you can
- Implement Verlet integration for N Lennard-Jones particles and check energy conservation.
- Apply periodic boundaries with the minimum-image convention and cell or Verlet lists.
- Control temperature with a Langevin thermostat and measure radial distribution and pressure.
- Implement Barnes–Hut and analyze its opening-parameter accuracy–cost trade-off.
Before you start
Interactions between particles
A galaxy, a gas and a molecule have very different scales and forces, but share a structure: compute forces from positions and integrate the equations of motion. Direct N-body simulation sums pair contributions and costs . Gravity is long-range; in a simple liquid, a local cutoff can reduce work if its effect is stated. In Hamiltonian Monte Carlo, analogous dynamics explore a probability distribution with a potential that need not represent physical energy.
The Lennard-Jones potential is
The repulsive term dominates at short distances and the attractive term at longer ones. Its minimum occurs at and equals . We use reduced units . To cut off at , use if and zero outside: energy is continuous at the cutoff, but force still jumps there. A shifted-force cutoff can remove that jump too, changing the model.
To find the minimum, differentiate with respect to : condition is equivalent to . Pair force is the negative gradient of , equal in magnitude and opposite in direction on the two particles. This antisymmetry conserves total momentum without external forces. Initializing positions too close produces enormous forces from the repulsive power; reducing the step may not fix a physically unsuitable initial configuration.
Periodic box and neighbors
Periodic boundaries identify opposite edges. In a square box of side , each component’s minimum image is . For finite-range interactions use ; otherwise a single image does not unambiguously represent all contributions. Long-range gravity requires different techniques: this local cutoff is insufficient.
A neighbor list stores nearby pairs. A cell list divides the box into cells of width at least and searches the current cell and eight neighbors. In boxes with only two cells per side, several periodic neighbors coincide: deduplicate them and count each pair once. A Verlet list adds a skin to the cutoff and is rebuilt before accumulated displacement can bring an omitted pair inside. The lab rebuilds the cell list at each evaluation; it does not claim a persistent skin.
If all displacements since constructing a list with skin are below , any pair distance can decrease by at most , so a pair initially beyond cannot enter the cutoff. At fixed density and cutoff, lists usually reduce candidate counts per particle; extreme concentrations or crowded cells degrade that benefit. Comparing with direct search in small boxes detects missed and duplicate pairs.
The plot compares pairs observed in a shell with the expected number for uniform positions in the same box. A single configuration is noisy. Inferring gas, liquid or solid requires equilibration, averaging many configurations, uncertainty and finite-size checks; visually cooling a small box does not prove a transition.
Integration and temperature
Velocity Verlet performs a half velocity step, a position step and another half velocity step with the new force. It is a symplectic integrator: for a separable Hamiltonian and fixed step in a stable regime, it often shows oscillatory energy error over long times, not exact conservation or stability at every step size. The discontinuous-force cutoff and close collisions also affect error.
The Langevin thermostat adds friction and noise linked by fluctuation–dissipation. In reduced units,
BAOAB alternates a half force kick (B), half drift (A), an exact Ornstein–Uhlenbeck step (O), and the reverse half steps A and B. In O, for unit masses. Noise and friction exchange energy with a bath: mechanical energy is not expected to be conserved on each trajectory. Rescaling velocities or using Berendsen can control temperature, but does not guarantee correct canonical-ensemble fluctuations.
The relationship between noise amplitude and friction is not an independently adjustable constant if the canonical distribution is intended. For a velocity with mass , equilibrium variance is ; the O step preserves it because . Complete integration still has step error and needs a convergence check. Fixing kinetic energy exactly at every step instead removes its fluctuations rather than sampling them.
Long range: Barnes–Hut
The Barnes–Hut algorithm groups particles in a 2D quadtree or 3D octree. A node of size at distance can be replaced by its total mass at the center of mass if ; otherwise its children are opened. A node containing the target particle must be opened to avoid self-interaction. opens every node and recovers the direct sum. Typical complexity can approach for favorable distributions, but depends on the tree and distribution.
Softening replaces with in the force: it avoids near singularities but changes the model. The fast multipole method (FMM) uses higher-order expansions and a different organization of interactions; Barnes–Hut is not automatically FMM.
Decreasing opens more nodes and usually improves the approximation, but cost increases. Relative error for one particle can be large when direct acceleration nearly vanishes through cancellation. The lab therefore also reports the global relative norm : the two measures answer different questions. Softening must be identical in both methods so the comparison measures the tree rather than two different physical laws.
Lab: 2D molecular dynamics
The following implementation uses Lennard-Jones with shifted potential, a periodic box and cell list; functions accept and return NumPy arrays. Pressure is calculated as in two dimensions. The stated instantaneous temperature uses with degrees of freedom; if center-of-mass velocity is removed to estimate thermal temperature, degrees of freedom must be adjusted.
"""Lennard-Jones 2D en unidades reducidas, con celdas periódicas."""
import numpy as np
def minimum_image(dr,L):
if L<=0: raise ValueError('L debe ser positiva')
dr=np.asarray(dr,dtype=float)
return dr-L*np.floor(dr/L+.5)
def cell_list_pairs(x,L,rc):
x=np.mod(np.asarray(x,dtype=float),L)
if x.ndim!=2 or x.shape[1]!=2 or not np.all(np.isfinite(x)) or rc<=0 or rc>L/2: raise ValueError('se requiere x (N,2) y 0<rc≤L/2')
nc=int(np.floor(L/rc));cell=np.floor(x/(L/nc)).astype(int)%nc
ids=cell[:,0]*nc+cell[:,1];groups={i:np.flatnonzero(ids==i) for i in np.unique(ids)}
pieces=[]
for key,first in groups.items():
a,b=divmod(int(key),nc)
neighbors={((a+da)%nc)*nc+(b+db)%nc for da in (-1,0,1) for db in (-1,0,1)}
for neighbor in neighbors:
if neighbor not in groups or neighbor<key: continue
second=groups[neighbor]
if neighbor==key:
ii,jj=np.triu_indices(len(first),1);i,j=first[ii],first[jj]
else:
i=np.repeat(first,len(second));j=np.tile(second,len(first))
if not len(i): continue
dr=minimum_image(x[i]-x[j],L);keep=np.sum(dr*dr,axis=1)<rc*rc
pairs=np.sort(np.column_stack((i[keep],j[keep])),axis=1)
if len(pairs):pieces.append(pairs)
return np.unique(np.vstack(pieces),axis=0) if pieces else np.empty((0,2),dtype=int)
def lj_forces(x,L,rc=2.5):
pairs=cell_list_pairs(x,L,rc);F=np.zeros_like(x,dtype=float)
if not len(pairs): return F,0.,0.
i,j=pairs.T;dr=minimum_image(x[i]-x[j],L);r2=np.sum(dr*dr,axis=1)
if np.any(r2<1e-16): raise ValueError('partículas superpuestas')
inv2=1/r2;inv6=inv2**3;inv12=inv6**2
force=(24*(2*inv12-inv6)*inv2)[:,None]*dr
np.add.at(F,i,force);np.add.at(F,j,-force)
shift=4*(rc**-12-rc**-6)
U=np.sum(4*(inv12-inv6)-shift);virial=np.sum(dr*force)
return F,float(U),float(virial)
def verlet(x,v,L,dt,rc=2.5):
F,_,_=lj_forces(x,L,rc);vh=v+.5*dt*F
x=np.mod(x+dt*vh,L);F2,_,_=lj_forces(x,L,rc)
return x,vh+.5*dt*F2
def baoab(x,v,L,dt,temp,gamma,rng,rc=2.5):
if temp<0 or gamma<0: raise ValueError('temperatura o fricción negativas')
F,_,_=lj_forces(x,L,rc);v=v+.5*dt*F
x=np.mod(x+.5*dt*v,L);c=np.exp(-gamma*dt)
v=c*v+np.sqrt(temp*(1-c*c))*rng.normal(size=v.shape)
x=np.mod(x+.5*dt*v,L);F,_,_=lj_forces(x,L,rc)
return x,v+.5*dt*F
def observables(x,v,L,rc=2.5):
_,U,virial=lj_forces(x,L,rc);K=.5*np.sum(v*v);n=len(x)
return {'energy':K+U,'temperature':K/n,'pressure':(2*K+virial)/(2*L*L)}
def radial_distribution(x,L,bins=40):
x=np.asarray(x,dtype=float);n=len(x)
if n<2: raise ValueError('se necesitan dos partículas')
i,j=np.triu_indices(n,1);r=np.linalg.norm(minimum_image(x[i]-x[j],L),axis=1)
edges=np.linspace(0,L/2,bins+1);counts,_=np.histogram(r,bins=edges)
area=np.pi*(edges[1:]**2-edges[:-1]**2)
expected=.5*n*(n-1)*area/L**2
return (edges[:-1]+edges[1:])/2,counts/expectedThe next test starts on a regular lattice with reproducible velocities. It checks force balance and energy variation over a short NVE trajectory, not a guarantee for every step size or density.
rng=np.random.default_rng(33);grid=np.arange(6)*8/6+.2
xx,yy=np.meshgrid(grid,grid);x=np.column_stack((xx.ravel(),yy.ravel()))
v=rng.normal(size=x.shape);v-=v.mean(axis=0)
v*=np.sqrt(.4/(np.mean(np.sum(v*v,axis=1))/2))
force,U,virial=lj_forces(x,8.);E0=observables(x,v,8.)['energy'];energies=[E0]
for _ in range(200):
x,v=verlet(x,v,8.,.002)
energies.append(observables(x,v,8.)['energy'])
print('fuerza total:',force.sum(axis=0))
print('desviación máxima de energía:',np.max(np.abs(np.array(energies)-E0)))gs=[];temperatures=[];pressures=[]
for _ in range(10):
for _ in range(20): x,v=baoab(x,v,8.,.002,.5,1.,rng)
radius,g=radial_distribution(x,8.,20);obs=observables(x,v,8.)
gs.append(g);temperatures.append(obs['temperature']);pressures.append(obs['pressure'])
print('medias de temperatura y presión:',np.mean(temperatures),np.mean(pressures))
print('primeros valores de g(r) medio:',np.column_stack((radius,np.mean(gs,axis=0)))[:8])The ten configurations are close in time and the sample is too short to estimate equilibrium or error bars. A physical study discards transients, averages and pressure, estimates autocorrelation and repeats with different steps and sizes. Pressure can be negative due to attraction; it should not be forced positive.
Local lab: tree and GPU
The next cell implements a Numba quadtree and a direct PyTorch CUDA sum. It computes gravitational acceleration, meaning force per unit target mass, with . The comparison includes constructing and traversing the CPU tree and transferring GPU data and results. It requires local Python with NumPy, Numba, PyTorch and CUDA; without a GPU it prints the limitation and does not attribute results to a nonexistent run. Its maximum size is 100000 bodies and it can take several minutes. The test uses uniformly distributed synthetic points, equal masses, and softening 0.01; the GPU sum uses float32 and the tree float64.
"""Quadtree Barnes-Hut 2D para puntos distintos en [0,1)²; gravedad suavizada."""
import numpy as np
from numba import njit,prange
@njit
def build_tree(pos,masses):
n=len(pos);capacity=max(8*n+1,16)
children=np.full((capacity,4),-1,np.int32);body=np.full(capacity,-1,np.int32)
center=np.zeros((capacity,2));size=np.zeros(capacity);mass=np.zeros(capacity);com=np.zeros((capacity,2))
center[0]=[.5,.5];size[0]=1.;used=1
for i in range(n):
node=0;depth=0
while True:
old=body[node]
if old==-1:
body[node]=i;break
if old>=0:
if pos[old,0]==pos[i,0] and pos[old,1]==pos[i,1]: raise ValueError('coordenadas coincidentes')
body[node]=-2
quadrant=(1 if pos[old,0]>=center[node,0] else 0)+(2 if pos[old,1]>=center[node,1] else 0)
if used>=capacity: raise RuntimeError('capacidad del árbol insuficiente')
child=used;used+=1;children[node,quadrant]=child;size[child]=size[node]/2
center[child,0]=center[node,0]+size[node]*(.25 if quadrant&1 else -.25)
center[child,1]=center[node,1]+size[node]*(.25 if quadrant&2 else -.25)
body[child]=old
quadrant=(1 if pos[i,0]>=center[node,0] else 0)+(2 if pos[i,1]>=center[node,1] else 0)
child=children[node,quadrant]
if child<0:
if used>=capacity: raise RuntimeError('capacidad del árbol insuficiente')
child=used;used+=1;children[node,quadrant]=child;size[child]=size[node]/2
center[child,0]=center[node,0]+size[node]*(.25 if quadrant&1 else -.25)
center[child,1]=center[node,1]+size[node]*(.25 if quadrant&2 else -.25)
body[child]=i;break
node=child;depth+=1
if depth>64: raise RuntimeError('árbol demasiado profundo')
for node in range(used-1,-1,-1):
if body[node]>=0:
i=body[node];mass[node]=masses[i];com[node]=pos[i]
elif body[node]==-2:
for j in range(4):
child=children[node,j]
if child>=0:
mass[node]+=mass[child];com[node,0]+=mass[child]*com[child,0];com[node,1]+=mass[child]*com[child,1]
if mass[node]>0:com[node]/=mass[node]
return children[:used],body[:used],center[:used],size[:used],mass[:used],com[:used]
@njit(parallel=True)
def tree_force(pos,children,body,center,size,mass,com,theta,eps):
n=len(pos);force=np.zeros((n,2));interactions=np.zeros(n,np.int64)
for i in prange(n):
stack=np.empty(512,np.int32);stack[0]=0;top=1;overflow=False
while top:
top-=1;node=stack[top]
if mass[node]==0:continue
if body[node]==i:continue
dx=com[node,0]-pos[i,0];dy=com[node,1]-pos[i,1];r2=dx*dx+dy*dy
contains=abs(pos[i,0]-center[node,0])<=size[node]/2 and abs(pos[i,1]-center[node,1])<=size[node]/2
if body[node]>=0 or (not contains and r2>0 and size[node]/np.sqrt(r2)<theta):
fac=mass[node]/(r2+eps*eps)**1.5
force[i,0]+=fac*dx;force[i,1]+=fac*dy;interactions[i]+=1
else:
for q in range(4):
child=children[node,q]
if child>=0:
if top>=len(stack):overflow=True;break
stack[top]=child;top+=1
if overflow:break
if overflow:interactions[i]=-1
return force,interactions
def barnes_hut(pos,masses,theta=.5,eps=.01):
pos=np.asarray(pos,dtype=float);masses=np.asarray(masses,dtype=float)
if pos.ndim!=2 or pos.shape[1]!=2 or masses.shape!=(len(pos),) or len(pos)==0 or not np.all(np.isfinite(pos)) or not np.all(np.isfinite(masses)) or np.any(pos<0) or np.any(pos>=1) or np.any(masses<=0) or theta<0 or eps<=0:raise ValueError('entradas inválidas')
tree=build_tree(pos,masses)
force,count=tree_force(pos,*tree,theta,eps)
if np.any(count<0):raise RuntimeError('pila del árbol insuficiente')
return force,count,len(tree[0])
import time, torch, numba
numba.set_num_threads(min(8,numba.config.NUMBA_NUM_THREADS))
torch.set_grad_enabled(False)
def direct_gpu(x,m,eps,block=128):
p=torch.as_tensor(x,dtype=torch.float32,device='cuda')
w=torch.as_tensor(m,dtype=torch.float32,device='cuda')
outputs=[]
for begin in range(0,len(p),block):
delta=p[None,:,:]-p[begin:begin+block,None,:]
r2=(delta*delta).sum(dim=2)+eps*eps
scale=w[None,:]*torch.rsqrt(r2)**3
outputs.append((delta*scale[:,:,None]).sum(dim=1))
return torch.cat(outputs).cpu().numpy()
if not torch.cuda.is_available():
print('CUDA no disponible: no se ejecutó la comparación GPU')
else:
rng=np.random.default_rng(42); warm=rng.random((1000,2));mass=np.full(1000,.001)
barnes_hut(warm,mass,.5,.01);direct_gpu(warm,mass,.01);torch.cuda.synchronize()
print('GPU:',torch.cuda.get_device_name(0),'hilos Numba:',numba.get_num_threads())
for n in (1000,5000,20000,100000):
x=rng.random((n,2));mass=np.full(n,1/n)
start=time.perf_counter();approx,count,nodes=barnes_hut(x,mass,.5,.01);cpu=time.perf_counter()-start
torch.cuda.synchronize();start=time.perf_counter();exact=direct_gpu(x,mass,.01);torch.cuda.synchronize();gpu=time.perf_counter()-start
error=np.linalg.norm(approx-exact)/np.linalg.norm(exact)
print('N, CPU árbol, GPU directa, error L2 relativo, interacciones medias:',n,cpu,gpu,error,count.mean())npm run lab and open the connection link.A real run on this machine with NVIDIA GeForce RTX 3060, PyTorch 2.11.0+cu128, Numba 0.68.0 and eight threads produced the following single-pass times after warmup with a synchronized GPU. These are not RTX 4060 measurements or a comparison of both algorithms on the same hardware; concurrent load and implementation matter.
| N | CPU tree (s) | GPU direct (s) | Relative L2 error |
|---|---|---|---|
| 1000 | 0.264 | 0.0035 | 0.0128 |
| 5000 | 0.414 | 0.0260 | 0.0163 |
| 20000 | 0.434 | 0.3535 | 0.0163 |
| 100000 | 1.110 | 7.5326 | 0.0160 |
In this sample the time ordering changes between 20000 and 100000, without identifying an exact crossover. A later QA run under concurrent loads took 18.94 s for the GPU sum of 20000 and 17.39 s for 100000: this variation prevents treating one pass as a stable benchmark. Repeat, report dispersion and test several : fewer interactions do not imply the same error for every particle. The original paper is Barnes and Hut (1986). LAMMPS, OpenMM and JAX MD provide professional tools with broader models and scope.
Exercises
Step 1 of 3. What is the derivative of f with respect to v?
import numpy as np
def minimum_image(dr,L):
pass
def cell_list_pairs(x,L,rc):
pass