Design a gravitational N-body simulation optimization: integrators, GPU acceleration,…
- User
Design a gravitational N-body simulation optimization: integrators, GPU acceleration, softening schemes, reproducibility, and validation.
Assistant
Design a gravitational N-body simulation optimization: integrators, GPU acceleration, softening schemes, reproducibility, and validation.
The user wants me to design a gravitational N-body simulation optimization, covering several key aspects:
This is a technical design document request. I should create a comprehensive, professional document that covers all these topics with practical implementation details.
Let me structure this as a proper technical design document:
Let me write a comprehensive design document with actual code examples and mathematical formulations.
This document outlines a comprehensive design for an optimized gravitational N-body simulation system, covering numerical integrators, GPU acceleration strategies, softening schemes, reproducibility guarantees, and validation methodologies.
| Integrator | Order | Symplectic | Cost/Step | Energy Drift | Best Use Case |
|---|---|---|---|---|---|
| Euler | 1 | No | O(N²) | High | Prototyping only |
| Leapfrog (Kick-Drift-Kick) | 2 | Yes | O(N²) | Low | General purpose |
| RK4 | 4 | No | 4×O(N²) | Moderate | High accuracy needed |
| Hermite (4th order) | 4 | No | 2×O(N²) | Low | Collisional systems |
| Forest-Ruth | 4 | Yes | 3×O(N²) | Very Low | Long-term stability |
| PEFRL | 4 | Yes | 4×O(N²) | Minimal | Long-term integrations |
Algorithm: Adaptive Symmetrized Leapfrog
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Given: positions rᵢ, velocities vᵢ, masses mᵢ, timestep Δt
1. KICK: vᵢ ← vᵢ + ½Δt · aᵢ(r)
2. DRIFT: rᵢ ← rᵢ + Δt · vᵢ
3. KICK: vᵢ ← vᵢ + ½Δt · aᵢ(r)
where aᵢ(r) = Σⱼ≠ᵢ G·mⱼ·(rⱼ - rᵢ) / (|rⱼ - rᵢ|² + ε²)³/²
Timestep Criterion (Aarseth):
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
η · |aᵢ| · |ȧᵢ|
Δtᵢ = ─────────────────
|äᵢ|
Global timestep: Δt = min(Δtᵢ) · safety_factor
Where:
η ≈ 0.01-0.03 (accuracy parameter)
safety_factor ≈ 0.1-0.2
class SymplecticIntegrator:
"""Fourth-order PEFRL integrator for long-term stability."""
# PEFRL coefficients (Position Extended Forest-Ruth Like)
ξ = 0.1786178958448091
λ = -0.2123468682390504
χ = -0.6626458666981849e-1
def __init__(self, bodies, softening=0.01):
self.bodies = bodies
self.softening = softening
def step(self, dt):
"""Single PEFRL integration step."""
c = [
self.ξ,
self.χ,
(1 - 2*self.χ) / 2,
self.χ,
self.ξ
]
d = [
0,
self.λ,
1 - 2*self.λ,
self.λ,
0
]
for i in range(5):
self._kick(d[i] * dt)
self._drift(c[i] * dt)
def _kick(self, dt):
accelerations = self._compute_accelerations()
for body, acc in zip(self.bodies, accelerations):
body.velocity += dt * acc
def _drift(self, dt):
for body in self.bodies:
body.position += dt * body.velocity
┌─────────────────────────────────────────────────────────────┐
│ GPU COMPUTE PIPELINE │
├─────────────────────────────────────────────────────────────┤
│ │
│ Host (CPU) Device (GPU) │
│ ┌─────────────┐ ┌──────────────────────┐ │
│ │ Initialize │─────────────▶│ Position Buffer │ │
│ │ Bodies │ │ Velocity Buffer │ │
│ └─────────────┘ │ Mass Buffer │ │
│ │ │ Acceleration Buffer │ │
│ │ └──────────────────────┘ │
│ ▼ │ │
│ ┌─────────────┐ ▼ │
│ │ Launch │ ┌──────────────────────┐ │
│ │ Kernel │ │ Block i: Body i │ │
│ └─────────────┘ │ - Load body i │ │
│ │ │ - Loop over all j │ │
│ │ │ - Accumulate acc │ │
│ ▼ │ - Store result │ │
│ ┌─────────────┐ └──────────────────────┘ │
│ │ Integrate │ │ │
│ │ (Leapfrog) │◀───────────────────────┘ │
│ └─────────────┘ cudaMemcpyDeviceToHost │
│ │
└─────────────────────────────────────────────────────────────┘
// gravity_kernel.cu
__global__ void compute_accelerations(
const double3* __restrict__ positions,
const double* __restrict__ masses,
double3* __restrict__ accelerations,
const double softening_sq,
const int n_bodies
) {
// Shared memory tile for positions
extern __shared__ double3 spos[];
extern __shared__ double smass[];
const int i = blockIdx.x * blockDim.x + threadIdx.x;
const int tid = threadIdx.x;
if (i >= n_bodies) return;
// Load body i into registers
const double3 ri = positions[i];
double3 ai = {0.0, 0.0, 0.0};
// Tiled computation for better memory access
for (int tile = 0; tile < gridDim.x; tile++) {
// Collaborative loading of tile
int j = tile * blockDim.x + tid;
if (j < n_bodies) {
spos[tid] = positions[j];
smass[tid] = masses[j];
}
__syncthreads();
// Compute interactions within tile
for (int k = 0; k < blockDim.x && (tile * blockDim.x + k) < n_bodies; k++) {
if (tile * blockDim.x + k != i) {
double3 dr;
dr.x = spos[k].x - ri.x;
dr.y = spos[k].y - ri.y;
dr.z = spos[k].z - ri.z;
double dist_sq = dr.x*dr.x + dr.y*dr.y + dr.z*dr.z + softening_sq;
double inv_dist = rsqrt(dist_sq); // Fast inverse sqrt
double inv_dist3 = inv_dist * inv_dist * inv_dist;
ai.x += smass[k] * dr.x * inv_dist3;
ai.y += smass[k] * dr.y * inv_dist3;
ai.z += smass[k] * dr.z * inv_dist3;
}
}
__syncthreads();
}
// Store result (multiply by G on device)
constexpr double G = 6.67430e-11;
accelerations[i].x = G * ai.x;
accelerations[i].y = G * ai.y;
accelerations[i].z = G * ai.z;
}
// Leapfrog integration kernel
__global__ void leapfrog_step(
double3* __restrict__ positions,
double3* __restrict__ velocities,
const double3* __restrict__ accelerations,
const double dt,
const int n_bodies
) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n_bodies) return;
// Kick (half step)
velocities[i].x += 0.5 * dt * accelerations[i].x;
velocities[i].y += 0.5 * dt * accelerations[i].y;
velocities[i].z += 0.5 * dt * accelerations[i].z;
// Drift (full step)
positions[i].x += dt * velocities[i].x;
positions[i].y += dt * velocities[i].y;
positions[i].z += dt * velocities[i].z;
}
import pycuda.autoinit
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
class GPUNBodySimulator:
def __init__(self, bodies, softening=0.01, block_size=256):
self.n = len(bodies)
self.block_size = block_size
self.grid_size = (self.n + block_size - 1) // block_size
# Load and compile CUDA kernel
with open('gravity_kernel.cu', 'r') as f:
kernel_code = f.read()
self.module = SourceModule(kernel_code)
# Get kernel functions
self.acc_kernel = self.module.get_function("compute_accelerations")
self.lf_kernel = self.module.get_function("leapfrog_step")
# Allocate device memory
self._allocate_buffers(bodies, softening)
def _allocate_buffers(self, bodies, softening):
# Host arrays (pinned memory for faster transfer)
self.h_pos = np.zeros((self.n, 3), dtype=np.float64)
self.h_vel = np.zeros((self.n, 3), dtype=np.float64)
self.h_mass = np.zeros(self.n, dtype=np.float64)
for i, body in enumerate(bodies):
self.h_pos[i] = body.position
self.h_vel[i] = body.velocity
self.h_mass[i] = body.mass
# Device allocation
self.d_pos = cuda.mem_alloc(self.h_pos.nbytes)
self.d_vel = cuda.mem_alloc(self.h_vel.nbytes)
self.d_mass = cuda.mem_alloc(self.h_mass.nbytes)
self.d_acc = cuda.mem_alloc(self.h_pos.nbytes)
# Copy to device
cuda.memcpy_htod(self.d_pos, self.h_pos)
cuda.memcpy_htod(self.d_vel, self.h_vel)
cuda.memcpy_htod(self.d_mass, self.h_mass)
self.softening_sq = softening ** 2
def step(self, dt):
"""Perform one complete leapfrog step."""
shared_mem = self.block_size * (3 * 8 + 8) # pos + mass per thread
# Compute accelerations
self.acc_kernel(
self.d_pos, self.d_mass, self.d_acc,
np.float64(self.softening_sq), np.int32(self.n),
block=(self.block_size, 1, 1),
grid=(self.grid_size, 1),
shared=shared_mem
)
# Kick-Drift (we'll need another acceleration for full kick-drift-kick)
self.lf_kernel(
self.d_pos, self.d_vel, self.d_acc,
np.float64(dt), np.int32(self.n),
block=(self.block_size, 1, 1),
grid=(self.grid_size, 1)
)
def sync_to_host(self):
"""Copy current state back to host."""
cuda.memcpy_dtoh(self.h_pos, self.d_pos)
cuda.memcpy_dtoh(self.h_vel, self.d_vel)
return self.h_pos.copy(), self.h_vel.copy()
┌────────────────────────────────────────────────────────────┐
│ GPU OPTIMIZATION CHECKLIST │
├────────────────────────────────────────────────────────────┤
│ │
│ Memory Access Patterns: │
│ ├─ ☑ Coalesced global memory reads │
│ ├─ ☑ Shared memory tiling for repeated accesses │
│ ├─ ☑ Texture cache for position data (optional) │
│ └─ ☑ Pinned host memory for faster transfers │
│ │
│ Computation: │
│ ├─ ☑ Fast math: rsqrt() instead of 1.0/sqrt() │
│ ├─ ☑ Fused multiply-add (FMA) for stability │
│ ├─ ☑ Loop unrolling for small tiles │
│ └─ ☑ Minimize divergence (all threads follow same path) │
│ │
│ Multi-GPU Scaling: │
│ ├─ ☐ Domain decomposition (spatial) │
│ ├─ ☐ Force decomposition (parallel reduction) │
│ └─ ☐ NCCL for GPU-GPU communication │
│ │
│ For N > 10⁵: Consider Barnes-Hut or treecode on GPU │
│ │
└────────────────────────────────────────────────────────────┘
Softening prevents numerical singularities during close encounters by modifying the gravitational potential at short distances.
Standard Potential: Φ(r) = -Gm/r
Softened Potential: Φₑ(r) = -Gm/√(r² + ε²)
Force Magnitude: Fₑ(r) = Gm·r/(r² + ε²)^(3/2)
Behavior:
- r >> ε: Fₑ ≈ Gm/r² (Newtonian limit)
- r << ε: Fₑ ≈ Gm·r/ε³ (linear, bounded)
- r = ε: Fₑ ≈ 0.354 · Gm/r²
┌───────────────────┬──────────────────────────────────────────┐
│ Scheme │ Formula & Properties │
├───────────────────┼──────────────────────────────────────────┤
│ Plummer │ ε² = constant │
│ │ Simple, widely used │
│ │ Energy well-defined │
├───────────────────┼──────────────────────────────────────────┤
│ Spline (Monaghan) │ ε varies with local density │
│ │ Adaptive, better momentum conservation │
├───────────────────┼──────────────────────────────────────────┤
│ Shifted │ F(r) = Gm/r² for r > ε │
│ │ F(r) = 0 for r ≤ ε │
│ │ Discontinuous, not recommended │
├───────────────────┼──────────────────────────────────────────┤
│ Newtonian │ ε(r) = min(ε_max, η·√h³/√m) │
│ Adaptive │ Scales with local smoothing length │
│ (SPH-like) │ Good for collisional systems │
└───────────────────┴──────────────────────────────────────────┘
class AdaptiveSoftener:
"""Adaptive softening based on local particle density."""
def __init__(self, eta=0.1, eps_min=0.001, eps_max=1.0, n_neighbors=32):
self.eta = eta
self.eps_min = eps_min
self.eps_max = eps_max
self.n_neighbors = n_neighbors
self.kdtree = None
def compute_softening(self, positions, masses):
"""
Compute adaptive softening lengths based on local density estimate.
εᵢ = η · (mᵢ / ρᵢ)^(1/3)
where ρᵢ is estimated from nearest neighbors.
"""
from scipy.spatial import cKDTree
n = len(positions)
epsilons = np.zeros(n)
# Build KD-tree for neighbor search
self.kdtree = cKDTree(positions)
for i in range(n):
# Find k nearest neighbors
distances, indices = self.kdtree.query(
positions[i],
k=min(self.n_neighbors + 1, n)
)
# Estimate local density from mean neighbor distance
if len(distances) > 1:
mean_dist = np.mean(distances[1:]) # Exclude self
local_density = np.sum(masses[indices[1:]]) / (4/3 * np.pi * mean_dist**3)
# Compute softening
eps_i = self.eta * (masses[i] / max(local_density, 1e-10))**(1/3)
epsilons[i] = np.clip(eps_i, self.eps_min, self.eps_max)
else:
epsilons[i] = self.eps_min
return epsilons
def compute_softened_acceleration(self, ri, rj, mj, eps_i, eps_j):
"""
Compute softened acceleration with individual softening lengths.
Uses spline kernel interpolation for smoothness.
"""
dr = rj - ri
r2 = np.dot(dr, dr)
# Geometric mean of softening lengths
eps_ij = np.sqrt(eps_i * eps_j)
# Plummer softening
r2_soft = r2 + eps_ij**2
r_soft = np.sqrt(r2_soft)
return mj * dr / (r_soft**3)
┌─────────────────────────────────────────────────────────────┐
│ SOFTENING PARAMETER SELECTION │
├─────────────────────────────────────────────────────────────┤
│ │
│ System Type │ Recommended ε │
│ ─────────────────────────┼──────────────────────────────── │
│ Star clusters │ ε ≈ 0.01 × half-mass radius │
│ Galaxies │ ε ≈ 100-500 pc │
│ Planetary systems │ ε ≈ 10⁻⁶ × orbital radius │
│ Cosmological │ ε ≈ (grid spacing) / 2 │
│ │
│ General Rule: │
│ ε should be << smallest dynamical length scale │
│ ε should be >> typical close-encounter distance │
│ │
│ Validation Check: │
│ Run with ε/2 and 2ε — results should not change │
│ significantly if ε is appropriately chosen │
│ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ NON-DETERMINISM SOURCES │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Floating-Point Associativity │
│ (a + b) + c ≠ a + (b + c) in IEEE 754 │
│ Different summation order → different rounding │
│ │
│ 2. GPU Thread Scheduling │
│ Non-deterministic execution order │
│ Atomic operations order varies │
│ │
│ 3. Parallel Reductions │
│ Sum across threads depends on scheduling │
│ │
│ 4. Compiler Optimizations │
│ -ffast-math breaks IEEE 754 compliance │
│ Instruction reordering │
│ │
│ 5. Random Number Generation │
│ Seed management, parallel RNG │
│ │
└─────────────────────────────────────────────────────────────┘
// Deterministic reduction using sorting + pairwise summation
__global__ void deterministic_force_sum(
const double3* __restrict__ partial_forces,
double3* __restrict__ total_force,
const int n_particles,
const int n_threads
) {
// Sort contributions by magnitude (bitonic sort)
// Then perform pairwise reduction
// This ensures same result regardless of thread order
extern __shared__ double3 sorted_forces[];
const int tid = threadIdx.x;
const int i = blockIdx.x * blockDim.x + tid;
// Load into shared memory
if (i < n_threads) {
sorted_forces[tid] = partial_forces[i];
} else {
sorted_forces[tid] = {0.0, 0.0, 0.0};
}
__syncthreads();
// Bitonic sort by magnitude
for (int k = 2; k <= blockDim.x; k *= 2) {
for (int j = k / 2; j > 0; j /= 2) {
int ixj = tid ^ j;
if (ixj > tid) {
double mag_i = magnitude(sorted_forces[tid]);
double mag_j = magnitude(sorted_forces[ixj]);
bool swap = false;
if ((tid & k) == 0) {
swap = mag_i > mag_j;
} else {
swap = mag_i < mag_j;
}
if (swap && ixj < blockDim.x) {
double3 temp = sorted_forces[tid];
sorted_forces[tid] = sorted_forces[ixj];
sorted_forces[ixj] = temp;
}
}
__syncthreads();
}
}
// Pairwise reduction (deterministic order)
for (int stride = blockDim.x / 2; stride > 0; stride /= 2) {
if (tid < stride) {
sorted_forces[tid].x += sorted_forces[tid + stride].x;
sorted_forces[tid].y += sorted_forces[tid + stride].y;
sorted_forces[tid].z += sorted_forces[tid + stride].z;
}
__syncthreads();
}
// Write result
if (tid == 0) {
*total_force = sorted_forces[0];
}
}
┌─────────────────────────────────────────────────────────────┐
│ VALIDATION TEST HIERARCHY │
├─────────────────────────────────────────────────────────────┤
│ │
│ Level 1: Unit Tests │
│ ├─ Force computation: known two-body configuration │
│ ├─ Integrator symmetry: forward/backward integration │
│ └─ Softening: check force limit at r→0 │
│ │
│ Level 2: Analytical Validation │
│ ├─ Two-body Kepler orbit (analytical solution) │
│ ├─ Restricted three-body (Lagrange points) │
│ └─ Homogeneous sphere (analytical potential) │
│ │
│ Level 3: Conservation Laws │
│ ├─ Energy conservation: ΔE/E < tolerance │
│ ├─ Momentum conservation: Δp/p < machine epsilon │
│ ├─ Angular momentum: ΔL/L < tolerance │
│ └─ Center of mass: should be stationary │
│ │
│ Level 4: Convergence Tests │
│ ├─ Timestep refinement: halving Δt should halve error │
│ ├─ Softening refinement: ε→0 convergence │
│ └─ Particle number scaling │
│ │
│ Level 5: Comparison Tests │
│ ├─ Against published results (e.g., NBODY6 test cases) │
│ ├─ Against independent code (cross-validation) │
│ └─ Against CPU implementation (GPU validation) │
│ │
└─────────────────────────────────────────────────────────────┘
class ValidatedSimulator:
"""Simulator with continuous validation checks."""
def __init__(self, config: SimulationConfig, bodies: List[Body]):
self.config = config
self.bodies = bodies
self.checker = ConservationChecker(bodies, G=1.0)
# Validation thresholds
self.max_energy_drift = 1e-4 # Maximum relative energy drift
self.check_interval = 100 # Check every N steps
self.step_count = 0
self.validation_log = []
def step(self, dt: float) -> bool:
"""Perform step with validation. Returns False if validation fails."""
# Integrate
self._integrate_step(dt)
self.step_count += 1
# Periodic validation
if self.step_count % self.check_interval == 0:
return self._validate()
return True
def _validate(self) -> bool:
"""Run validation checks."""
result = self.checker.check_conservation(
softening=self.config.softening
)
# Log result
self.validation_log.append({
'step': self.step_count,
**result
})
# Check for problems
if result['energy_error'] > self.max_energy_drift:
print(f"WARNING: Energy drift exceeded at step {self.step_count}")
print(f" ΔE/E = {result['energy_error']:.2e}")
return False
if not result['momentum_conserved']:
print(f"WARNING: Momentum not conserved at step {self.step_count}")
return False
return True
def get_validation_report(self) -> str:
"""Generate validation report."""
if not self.validation_log:
return "No validation data collected yet."
energies = [log['energy_error'] for log in self.validation_log]
report = f"""
Validation Report
=================
Total steps: {self.step_count}
Validation checks: {len(self.validation_log)}
Energy Conservation:
Initial: {self.checker.initial_energy:.6e}
Final: {self.checker.total_energy(self.config.softening):.6e}
Max drift: {max(energies):.2e}
Mean drift: {np.mean(energies):.2e}
Momentum Conservation:
All checks passed: {all(log['momentum_conserved'] for log in self.validation_log)}
Angular Momentum:
All checks passed: {all(log['angular_momentum_conserved'] for log in self.validation_log)}
"""
return report
┌─────────────────────────────────────────────────────────────┐
│ IMPLEMENTATION PHASES │
├─────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: Core Implementation (Week 1-2) │
│ ├─ Basic Body class and data structures │
│ ├─ CPU O(N²) force computation │
│ ├─ Leapfrog integrator │
│ └─ Plummer softening │
│ │
│ Phase 2: Validation Framework (Week 2-3) │
│ ├─ Conservation law checks │
│ ├─ Analytical solution comparisons │
│ ├─ Timestep convergence tests │
│ └─ Automated test suite │
│ │
│ Phase 3: GPU Implementation (Week 3-5) │
│ ├─ CUDA kernel for force computation │
│ ├─ Memory management (pinned, coalesced) │
│ ├─ Integration with CPU simulation class │
│ └─ Performance benchmarking │
│ │
│ Phase 4: Advanced Features (Week 5-7) │
│ ├─ Adaptive timestepping │
│ ├─ Adaptive softening │
│ ├─ Higher-order integrators (Hermite, PEFRL) │
│ └─ Checkpoint/restart system │
│ │
│ Phase 5: Reproducibility & Production (Week 7-8) │
│ ├─ Deterministic GPU execution │
│ ├─ Configuration management │
│ ├─ Comprehensive logging │
│ └─ Documentation and examples │
│ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ KEY EQUATIONS SUMMARY │
├─────────────────────────────────────────────────────────────┤
│ │
│ Gravitational Force (Softened): │
│ Fᵢⱼ = G·mᵢ·mⱼ·(rⱼ - rᵢ) / (|rⱼ - rᵢ|² + ε²)^(3/2) │
│ │
│ Leapfrog Integration: │
│ v(t+Δt/2) = v(t) + ½Δt·a(t) │
│ r(t+Δt) = r(t) + Δt·v(t+Δt/2) │
│ v(t+Δt) = v(t+Δt/2) + ½Δt·a(t+Δt) │
│ │
│ Energy: │
│ E = Σᵢ ½mᵢvᵢ² - Σᵢ<ⱼ Gmᵢmⱼ/|rᵢⱼ| │
│ │
│ Adaptive Timestep (Aarseth): │
│ Δt = η·|a|·|ȧ| / |ä| │
│ │
│ Conserved Quantities Check: │
│ ΔE/E < 10⁻⁴ (typical for symplectic integrators) │
│ Δp/p < εₘₐₙ (machine epsilon, exact for momentum) │
│ │
└─────────────────────────────────────────────────────────────┘
This design provides a complete foundation for building a production-quality N-body simulator with all the requested optimizations and safeguards.
import json
import hashlib
import numpy as np
from dataclasses import dataclass, asdict
from typing import Optional
from enum import Enum
class RoundingMode(Enum):
ROUND_TO_NEAREST = "round_to_nearest"
ROUND_DOWN = "round_down"
ROUND_UP = "round_up"
ROUND_TOWARD_ZERO = "round_toward_zero"
@dataclass
class SimulationConfig:
"""Complete configuration for reproducibility."""
# Numerical parameters
integrator: str = "pefrl"
dt: float = 0.001
softening: float = 0.01
softening_scheme: str = "plummer"
# GPU parameters
use_gpu: bool = True
gpu_device_id: int = 0
block_size: int = 256
deterministic_gpu: bool = True
# Reproducibility
seed: int = 42
rounding_mode: RoundingMode = RoundingMode.ROUND_TO_NEAREST
# Compiler flags
use_fast_math: bool = False
opt_level: int = 2
def to_hash(self) -> str:
"""Generate unique hash for this configuration."""
config_str = json.dumps(asdict(self), sort_keys=True)
return hashlib.sha256(config_str.encode()).hexdigest()[:16]
class DeterministicSimulator:
"""Simulation with guaranteed reproducibility."""
def __init__(self, config: SimulationConfig):
self.config = config
self._setup_determinism()
def _setup_determinism(self):
"""Configure all sources of non-determinism."""
# 1. Set random seed with proper initialization
np.random.seed(self.config.seed)
self.rng = np.random.RandomState(self.config.seed)
# 2. Set floating-point rounding mode
if self.config.rounding_mode == RoundingMode.ROUND_TO_NEAREST:
np.seterr(all='raise') # Catch FP issues
# 3. Configure GPU determinism
if self.config.use_gpu:
self._configure_gpu_determinism()
# 4. Store initial state hash
self.initial_hash = self.config.to_hash()
def _configure_gpu_determinism(self):
"""
Configure GPU for deterministic execution.
Note: Some operations are inherently non-deterministic on GPUs.
"""
import pycuda.driver as cuda
# Select specific GPU
cuda.Device(self.config.gpu_device_id).make_context()
# CUDA determinism flags
# Note: This requires custom CUDA compilation
self.cuda_compile_flags = [
f"-DBLOCK_SIZE={self.config.block_size}",
"--use_fast_math=off" if not self.config.use_fast_math else "--use_fast_math=on",
f"-O{self.config.opt_level}",
"-arch=sm_70", # Adjust for your GPU
]
if self.config.deterministic_gpu:
# Force synchronous execution
self.cuda_compile_flags.append("-DDETERMINISTIC_MODE")
def save_checkpoint(self, filename: str, step: int,
positions: np.ndarray, velocities: np.ndarray):
"""Save complete checkpoint with reproducibility info."""
checkpoint = {
'config': asdict(self.config),
'state': {
'step': step,
'positions': positions.tolist(),
'velocities': velocities.tolist(),
},
'checksums': {
'positions': hashlib.md5(positions.tobytes()).hexdigest(),
'velocities': hashlib.md5(velocities.tobytes()).hexdigest(),
},
'rng_state': self.rng.get_state()[1].tolist(),
}
with open(filename, 'w') as f:
json.dump(checkpoint, f, indent=2)
def load_checkpoint(self, filename: str) -> tuple:
"""Load checkpoint and verify reproducibility."""
with open(filename, 'r') as f:
checkpoint = json.load(f)
# Verify configuration matches
loaded_config = SimulationConfig(**checkpoint['config'])
if loaded_config.to_hash() != self.initial_hash:
raise ValueError(
"Configuration mismatch! "
f"Expected {self.initial_hash}, "
f"got {loaded_config.to_hash()}"
)
# Restore state
state = checkpoint['state']
positions = np.array(state['positions'], dtype=np.float64)
velocities = np.array(state['velocities'], dtype=np.float64)
# Verify checksums
pos_hash = hashlib.md5(positions.tobytes()).hexdigest()
vel_hash = hashlib.md5(velocities.tobytes()).hexdigest()
if pos_hash != checkpoint['checksums']['positions']:
raise ValueError("Position data corrupted!")
if vel_hash != checkpoint['checksums']['velocities']:
raise ValueError("Velocity data corrupted!")
# Restore RNG state
self.rng.set_state(('MT19937',
np.array(checkpoint['rng_state'], dtype=np.uint32),
0, 0, 0.0))
return state['step'], positions, velocities
class DeterministicSum:
"""Kahan summation for deterministic results."""
def __init__(self):
self.sum = 0.0
self.compensation = 0.0
def add(self, value: float) -> float:
"""Add value with Kahan compensation."""
y = value - self.compensation
t = self.sum + y
self.compensation = (t - self.sum) - y
self.sum = t
return self.sum
@staticmethod
def sum_array(arr: np.ndarray) -> float:
"""Deterministic sum using pairwise algorithm."""
n = len(arr)
if n == 0:
return 0.0
if n == 1:
return arr[0]
# Sort by magnitude for consistency
sorted_arr = arr[np.argsort(np.abs(arr))]
# Pairwise reduction
while len(sorted_arr) > 1:
if len(sorted_arr) % 2 == 1:
sorted_arr = np.append(sorted_arr, 0.0)
sorted_arr = sorted_arr[0::2] + sorted_arr[1::2]
return sorted_arr[0]
import numpy as np
from dataclasses import dataclass
from typing import List, Tuple, Callable
import unittest
@dataclass
class Body:
position: np.ndarray
velocity: np.ndarray
mass: float
class ConservationChecker:
"""Check conservation laws during simulation."""
def __init__(self, bodies: List[Body], G: float = 1.0):
self.G = G
self.bodies = bodies
self.initial_energy = self.total_energy()
self.initial_momentum = self.total_momentum()
self.initial_angular_momentum = self.angular_momentum()
def kinetic_energy(self) -> float:
"""T = Σ ½ mᵢ vᵢ²"""
T = 0.0
for b in self.bodies:
T += 0.5 * b.mass * np.dot(b.velocity, b.velocity)
return T
def potential_energy(self, softening: float = 0.0) -> float:
"""U = -Σᵢ<ⱼ G·mᵢ·mⱼ / rᵢⱼ"""
U = 0.0
n = len(self.bodies)
for i in range(n):
for j in range(i + 1, n):
r = np.linalg.norm(
self.bodies[j].position - self.bodies[i].position
)
r_soft = np.sqrt(r**2 + softening**2)
U -= self.G * self.bodies[i].mass * self.bodies[j].mass / r_soft
return U
def total_energy(self, softening: float = 0.0) -> float:
"""E = T + U"""
return self.kinetic_energy() + self.potential_energy(softening)
def total_momentum(self) -> np.ndarray:
"""p = Σ mᵢ vᵢ"""
p = np.zeros(3)
for b in self.bodies:
p += b.mass * b.velocity
return p
def angular_momentum(self) -> np.ndarray:
"""L = Σ mᵢ (rᵢ × vᵢ)"""
L = np.zeros(3)
for b in self.bodies:
L += b.mass * np.cross(b.position, b.velocity)
return L
def center_of_mass(self) -> np.ndarray:
"""R_cm = Σ mᵢ rᵢ / Σ mᵢ"""
M = sum(b.mass for b in self.bodies)
R = np.zeros(3)
for b in self.bodies:
R += b.mass * b.position
return R / M
def check_conservation(self, softening: float = 0.0,
atol: float = 1e-10) -> dict:
"""Check all conservation laws."""
current_energy = self.total_energy(softening)
current_momentum = self.total_momentum()
current_L = self.angular_momentum()
return {
'energy_error': abs(current_energy - self.initial_energy) /
abs(self.initial_energy) if self.initial_energy != 0 else 0,
'momentum_error': np.linalg.norm(current_momentum - self.initial_momentum),
'angular_momentum_error': np.linalg.norm(current_L - self.initial_angular_momentum),
'energy_conserved': abs(current_energy - self.initial_energy) < atol,
'momentum_conserved': np.allclose(
current_momentum, self.initial_momentum, atol=atol
),
'angular_momentum_conserved': np.allclose(
current_L, self.initial_angular_momentum, atol=atol
),
}
class AnalyticalSolutions:
"""Analytical solutions for validation."""
@staticmethod
def kepler_orbit(m1: float, m2: float, a: float, e: float,
t: float, G: float = 1.0) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute position and velocity on a Kepler orbit.
Parameters:
m1, m2: masses
a: semi-major axis
e: eccentricity
t: time since perihelion
G: gravitational constant
Returns:
(position, velocity) of m2 relative to m1
"""
M_total = m1 + m2
mu = G * M_total # Standard gravitational parameter
# Mean anomaly
n = np.sqrt(mu / a**3) # Mean motion
M = n * t # Mean anomaly
# Solve Kepler's equation: M = E - e*sin(E)
E = M # Initial guess
for _ in range(50): # Newton-Raphson
E_new = E - (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
if abs(E_new - E) < 1e-12:
break
E = E_new
# True anomaly
cos_nu = (np.cos(E) - e) / (1 - e * np.cos(E))
sin_nu = np.sqrt(1 - e**2) * np.sin(E) / (1 - e * np.cos(E))
nu = np.arctan2(sin_nu, cos_nu)
# Distance
r = a * (1 - e * np.cos(E))
# Position in orbital plane
pos = np.array([
r * np.cos(nu),
r * np.sin(nu),
0.0
])
# Velocity in orbital plane
h = np.sqrt(mu * a * (1 - e**2)) # Specific angular momentum
vel = np.array([
-mu / h * np.sin(nu),
mu / h * (e + np.cos(nu)),
0.0
])
return pos, vel
@staticmethod
def two_body_solution(m1: float, m2: float, a: float, e: float,
t: float, G: float = 1.0) -> Tuple[Body, Body]:
"""
Full two-body solution with both bodies.
"""
M = m1 + m2
# Relative orbit
rel_pos, rel_vel = AnalyticalSolutions.kepler_orbit(
m1, m2, a, e, t, G
)
# Convert to barycentric coordinates
body1 = Body(
position=-m2 / M * rel_pos,
velocity=-m2 / M * rel_vel,
mass=m1
)
body2 = Body(
position=m1 / M * rel_pos,
velocity=m1 / M * rel_vel,
mass=m2
)
return body1, body2
class ValidationTests(unittest.TestCase):
"""Comprehensive validation test suite."""
def setUp(self):
self.G = 1.0
self.tolerance_strict = 1e-10
self.tolerance_loose = 1e-6
def test_two_body_circular(self):
"""Test circular two-body orbit."""
m1, m2 = 1.0, 1.0
a = 1.0 # Semi-major axis
e = 0.0 # Circular
T = 2 * np.pi * np.sqrt(a**3 / (self.G * (m1 + m2))) # Period
# Initial conditions from analytical solution
body1, body2 = AnalyticalSolutions.two_body_solution(
m1, m2, a, e, 0.0, self.G
)
# Run simulation for one period
simulator = CPUSimulator([body1, body2], self.G)
for _ in range(1000):
simulator.step(T / 1000)
# Check if returned to initial position
final1, final2 = simulator.bodies
error1 = np.linalg.norm(final1.position - body1.position)
error2 = np.linalg.norm(final2.position - body2.position)
self.assertLess(error1, self.tolerance_loose * a)
self.assertLess(error2, self.tolerance_loose * a)
def test_conservation(self):
"""Test energy and momentum conservation."""
# Random initial conditions
np.random.seed(42)
bodies = [
Body(
position=np.random.randn(3),
velocity=np.random.randn(3) * 0.1,
mass=np.random.rand() + 0.1
)
for _ in range(10)
]
# Zero out total momentum
total_p = sum(b.mass * b.velocity for b in bodies)
for b in bodies:
b.velocity -= total_p / sum(b.mass for b in bodies)
checker = ConservationChecker(bodies, self.G)
simulator = CPUSimulator(bodies, self.G)
dt = 0.001
for _ in range(10000):
simulator.step(dt)
# Update checker with final state
checker.bodies = simulator.bodies
result = checker.check_conservation()
self.assertTrue(result['momentum_conserved'])
self.assertTrue(result['angular_momentum_conserved'])
self.assertLess(result['energy_error'], 1e-8)
def test_timestep_convergence(self):
"""Test that error decreases with smaller timestep."""
# Two-body elliptical orbit
m1, m2 = 1.0, 0.5
a, e = 1.0, 0.5
T = 2 * np.pi * np.sqrt(a**3 / (self.G * (m1 + m2)))
dt_values = [0.01, 0.005, 0.0025, 0.00125]
errors = []
for dt in dt_values:
body1, body2 = AnalyticalSolutions.two_body_solution(
m1, m2, a, e, 0.0, self.G
)
simulator = CPUSimulator([body1, body2], self.G, integrator='leapfrog')
steps = int(T / dt)
for _ in range(steps):
simulator.step(dt)
# Compare with analytical solution
exact1, exact2 = AnalyticalSolutions.two_body_solution(
m1, m2, a, e, T, self.G
)
error = np.linalg.norm(
simulator.bodies[0].position - exact1.position
) + np.linalg.norm(
simulator.bodies[1].position - exact2.position
)
errors.append(error)
# Check second-order convergence (error ∝ dt²)
for i in range(1, len(errors)):
ratio = errors[i] / errors[i-1]
expected_ratio = (dt_values[i] / dt_values[i-1])**2
self.assertAlmostEqual(ratio, expected_ratio, places=1)
def test_softening_limit(self):
"""Test that softening gives bounded force at r→0."""
body1 = Body(
position=np.array([0.0, 0.0, 0.0]),
velocity=np.zeros(3),
mass=1.0
)
body2 = Body(
position=np.array([0.001, 0.0, 0.0]), # Very close
velocity=np.zeros(3),
mass=1.0
)
eps = 0.1
# Without softening, force would be ~1000 (unbounded)
# With softening, force should be ~eps⁻² = 100 (bounded)
r = np.linalg.norm(body2.position - body1.position)
r_soft = np.sqrt(r**2 + eps**2)
force_mag = self.G * body1.mass / r_soft**2
self.assertLess(force_mag, self.G / eps**2 * 1.01) # Bounded
def run_validation_suite():
"""Run all validation tests."""
loader = unittest.TestLoader()
suite = loader.loadTestsFromTestCase(ValidationTests)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
return result.wasSuccessful()
class CPUSimulator:
"""Simple CPU simulator for validation."""
def __init__(self, bodies, G=1.0, integrator='leapfrog'):
self.bodies = bodies
self.G = G
self.integrator = integrator
def step(self, dt):
if self.integrator == 'leapfrog':
self._leapfrog_step(dt)
else:
raise ValueError(f"Unknown integrator: {self.integrator}")
def _compute_accelerations(self):
n = len(self.bodies)
acc = [np.zeros(3) for _ in range(n)]
for i in range(n):
for j in range(n):
if i != j:
r = self.bodies[j].position - self.bodies[i].position
r_norm = np.linalg.norm(r)
acc[i] += self.G * self.bodies[j].mass * r / r_norm**3
return acc
def _leapfrog_step(self, dt):
# Kick
acc = self._compute_accelerations()
for i, b in enumerate(self.bodies):
b.velocity += 0.5 * dt * acc[i]
# Drift
for b in self.bodies:
b.position += dt * b.velocity
# Kick
acc = self._compute_accelerations()
for i, b in enumerate(self.bodies):
b.velocity += 0.5 * dt * acc[i]