Module contents
Lesson 6 of 27Core 100 min

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 O(N2)O(N^2). 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

U(r)=4ϵ[(σ/r)12−(σ/r)6].U(r)=4\epsilon\left[(\sigma/r)^{12}-(\sigma/r)^6\right].

The repulsive term dominates at short distances and the attractive term at longer ones. Its minimum occurs at r=21/6σr=2^{1/6}\sigma and equals −ϵ-\epsilon. We use reduced units ϵ=σ=m=kB=1\epsilon=\sigma=m=k_B=1. To cut off at rcr_c, use Ucut(r)=U(r)−U(rc)U_{\rm cut}(r)=U(r)-U(r_c) if r<rcr<r_c 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 rr: condition U′(r)=0U'(r)=0 is equivalent to (σ/r)6=1/2(\sigma/r)^6=1/2. Pair force is the negative gradient of UU, 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 LL, each component’s minimum image is Δx−L⌊Δx/L+1/2⌋\Delta x-L\lfloor\Delta x/L+1/2\rfloor. For finite-range interactions use rc≤L/2r_c\le L/2; 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 rcr_c 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 δ\delta are below δ/2\delta/2, any pair distance can decrease by at most δ\delta, so a pair initially beyond rc+δr_c+\delta 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.

InteractiveLennard-Jones in a periodic box

144 particles on an initial lattice, periodic box of side 15, cutoff 2.5 and BAOAB with step 0.003. Temperature and g(r) fluctuate; identifying a phase requires equilibration, averaging and an appropriate size.

Simulation
0.7
Time0.000
Kinetic temperature0.713
Instantaneous pressure−1.929
Instantaneous energy−147.26
Start BAOAB or advance steps, change temperature and observe particles and instantaneous g(r). The simulation is small and does not certify a phase transition.

The g(r)g(r) 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.

InteractiveEnergy drift by integrator
  • Explicit Euler
  • RK4
  • Velocity Verlet

The second plot changes scale and enlarges only RK4 and Verlet; it excludes Euler.

Two isolated Lennard-Jones particles, without cutoff or thermostat. A curve stops if |E−E₀| exceeds 4 or separation leaves the safety range. Behavior depends on step and system.

0.02
euleroff scale, t=5.08
rk4complete, t=10.00
verletcomplete, t=10.00
Two Lennard-Jones particles start from the same state; compare explicit Euler, RK4 and velocity Verlet as you change the step. Curves show E−E₀ and stop if they go off scale.

The Langevin thermostat adds friction and noise linked by fluctuation–dissipation. In reduced units,

 ⁣dv=F(x)  ⁣dt−γv  ⁣dt+2γT  ⁣dW.\dd v=F(x)\,\dd t-\gamma v\,\dd t+\sqrt{2\gamma T}\,\dd W.

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, v←e−γhv+T(1−e−2γh) ξv\leftarrow e^{-\gamma h}v+\sqrt{T(1-e^{-2\gamma h})}\,\xi 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 mm, equilibrium variance is kBT/mk_BT/m; the O step preserves it because c2(kBT/m)+(1−c2)(kBT/m)=kBT/mc^2(k_BT/m)+(1-c^2)(k_BT/m)=k_BT/m. 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 ss at distance dd can be replaced by its total mass at the center of mass if s/d<θs/d<\theta; otherwise its children are opened. A node containing the target particle must be opened to avoid self-interaction. θ=0\theta=0 opens every node and recovers the direct sum. Typical complexity can approach O(Nlog⁡N)O(N\log N) for favorable distributions, but depends on the tree and distribution.

InteractiveThe Barnes–Hut tree
  • Accepted node
  • Target
  • Other particles

Eighty equal masses, synthetic positions with a fixed seed and softening 0.03. A node containing the target is never approximated; θ=0 opens all branches. Gravitational acceleration, force per unit mass, is compared with this particle’s direct sum.

0.6
0
Accepted interactions40 / 79
Opened nodes21
Relative acceleration error0.01731
Select or hover over a particle. Highlighted boxes are accepted nodes; change θ and compare interactions and acceleration with the direct sum.

Softening replaces r2r^2 with r2+ε2r^2+\varepsilon^2 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 θ\theta 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 ∥aBH−adir∥2/∥adir∥2\norm{a_{\mathrm{BH}}-a_{\mathrm{dir}}}_2/\norm{a_{\mathrm{dir}}}_2: 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 P=(2K+∑i<jrij⋅Fij)/(2L2)P=(2K+\sum_{i<j}r_{ij}\cdot F_{ij})/(2L^2) in two dimensions. The stated instantaneous temperature uses T=K/NT=K/N with 2N2N degrees of freedom; if center-of-mass velocity is removed to estimate thermal temperature, degrees of freedom must be adjusted.

[ ]Lennard-Jones engine and neighborsBrowser
"""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/expected

The 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.

[ ]Verlet and NVE conservationBrowser
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)))
[ ]Thermostat and observablesBrowser
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 g(r)g(r) 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 G=1G=1. 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, θ=0.5\theta=0.5 and softening 0.01; the GPU sum uses float32 and the tree float64.

[ ]Barnes–Hut and direct CUDA sumLocal GPU
"""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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

NCPU tree (s)GPU direct (s)Relative L2 error
10000.2640.00350.0128
50000.4140.02600.0163
200000.4340.35350.0163
1000001.1107.53260.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 θ\theta: 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

NumericLennard-Jones minimum
What is the distance of the minimum in units of σ?
ProofInvariant distribution
Prove: Check the velocity part of Boltzmann invariance for Langevin.
0
Mass m, friction γ, temperature T and Maxwell density f(v)∝exp(−m|v|²/(2kBT)).

Step 1 of 3. What is the derivative of f with respect to v?

QuizTemperature versus distribution
Why does fixing kinetic energy exactly by rescaling not guarantee the canonical ensemble?
CodeMinimum image and cells
Implement minimum_image(dr,L) and cell_list_pairs(x,L,rc) for a periodic 2D box, with 0<rc≤L/2. Return unique pairs i<j whose minimum distance is strictly less than rc. Vectorize distances within each cell combination.
import numpy as np
def minimum_image(dr,L):
  pass
def cell_list_pairs(x,L,rc):
  pass
Shift+Enter to run
Key idea
Particle-simulation fidelity depends on forces and boundaries as well as the integrator, sampling and error validation when accelerating interactions.