In Lecture 3, spatial cell lists reduced short-range cutoff interactions () from to . But what about long-range forces that never cut off, gravitational galaxies, Coulomb plasmas, Biot–Savart vortex sheets (), or global integral convolutions across millions of acoustic/radar samples? Two hierarchical divide-and-conquer methods reduce such sums to (the FFT and the fast multipole method, a refinement of the Barnes–Hut idea, are both on the list of ten algorithms of the twentieth century compiled by Dongarra & Sullivan, 2000): Barnes–Hut Multipole Quadtrees (divide_spatial.barnes_hut_quadtree_2d) lump distant spatial clusters into centers of mass whenever , while Cooley–Tukey Radix-2 FFT (divide_spatial.radix2_fft_convolve) diagonalizes convolution in frequency space (Mental Moves #13–#14).
Learning objectives¶
Construct adaptive 2-D spatial trees via
divide_spatial.barnes_hut_quadtree_2d, verifying exact machine-precision agreement with -body forces at and speedup for .Quantify the Speedup vs. Force-Accuracy Pareto Frontier across multipole opening angles .
Execute exact linear convolution via
divide_spatial.radix2_fft_convolve, relating Cooley–Tukey even/odd index parity to roots-of-unity butterfly stages.Detect deeply buried chirp echoes under negative signal-to-noise ratio () via FFT matched-filter cross-correlation.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Adaptive Spatial Hierarchy: 2-D Barnes–Hut Quadtrees (barnes_hut_quadtree_2d)¶
Unlike short-range Lennard-Jones potentials, gravitational and electrostatic forces couple every body to every other body ( evaluations). Yet if you stand on Earth, you do not sum the gravitational pull of 1011 individual stars in the Andromeda Galaxy, you treat Andromeda as one point mass at its center of mass .
Mental Move #13, Lump Distant Clusters via Multipole Trees (Barnes & Hut, Nature 1986) recursively subdivides occupied 2-D quadrants until every leaf holds 1 body, precomputing at every internal node in . When evaluating force on body from a cell of width at center-of-mass distance :
heading("Demonstration 1: Adaptive 2-D Barnes-Hut quadtree around clustered vortex and star cores")
rng_bh = np.random.default_rng(1986)
cores = np.array([[20.0, 22.0], [76.0, 28.0], [48.0, 78.0]])
core_ids = rng_bh.choice([0, 1, 2], size=240, p=[0.45, 0.35, 0.20])
pts_bh = cores[core_ids] + rng_bh.normal(0.0, 5.2, size=(240, 2))
masses_bh = rng_bh.uniform(0.5, 2.5, size=240)
exact_bh = divide_spatial.barnes_hut_quadtree_2d(pts_bh, masses_bh, theta=0.0, eps_soft=0.15)
fast_bh = divide_spatial.barnes_hut_quadtree_2d(pts_bh, masses_bh, theta=0.55, eps_soft=0.15)
rel_rms_err = float(np.linalg.norm(fast_bh["forces"] - exact_bh["forces"]) / np.linalg.norm(exact_bh["forces"]))
speedup_bh = exact_bh["exact_pair_evaluations"] / fast_bh["force_evaluations"]
print(f"N = 240 clustered bodies | Quadtree max depth = {fast_bh['max_depth']} | Occupied cells = {len(fast_bh['tree_boxes'])}")
print(f"theta = 0.00 (exact tree walk): {exact_bh['force_evaluations']:,d} kernel evals")
print(f"theta = 0.55 (multipole lump) : {fast_bh['force_evaluations']:,d} kernel evals ({speedup_bh:.2f}x fewer) | Rel RMS Force Err = {100*rel_rms_err:.3f}%")
# Also cross-check theta=0.0 against vectorized NumPy O(N^2) all-pairs matrix:
dx = pts_bh[None, :, 0] - pts_bh[:, None, 0]
dy = pts_bh[None, :, 1] - pts_bh[:, None, 1]
inv_r3 = (dx * dx + dy * dy + 0.15 ** 2) ** (-1.5)
np.fill_diagonal(inv_r3, 0.0)
f_vec_exact = np.column_stack([
masses_bh * np.sum(inv_r3 * dx * masses_bh[None, :], axis=1),
masses_bh * np.sum(inv_r3 * dy * masses_bh[None, :], axis=1),
])
assert np.allclose(exact_bh["forces"], f_vec_exact, rtol=1e-12)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.4))
box_xs, box_ys = [], []
for bx, by, bsize in fast_bh["tree_boxes"]:
box_xs.extend([bx, bx + bsize, bx + bsize, bx, bx, np.nan])
box_ys.extend([by, by, by + bsize, by + bsize, by, np.nan])
ax1.plot(box_xs, box_ys, "-", color="#2166AC", lw=0.55, alpha=0.55, label="Quadtree cells")
ax1.scatter(pts_bh[:, 0], pts_bh[:, 1], s=14, c="#C0392B", zorder=4, label="Clustered bodies")
ax1.set_aspect("equal", adjustable="box")
ax1.set_xlabel("Position $x$")
ax1.set_ylabel("Position $y$")
ax1.set_title("Adaptive Barnes-Hut quadtree mesh")
f_mag_ex = np.linalg.norm(exact_bh["forces"], axis=1)
f_mag_ap = np.linalg.norm(fast_bh["forces"], axis=1)
ax2.loglog(f_mag_ex, f_mag_ap, "o", color="#2E8B57", ms=4.5, alpha=0.75, label=r"$\theta = 0.55$ vs exact $\theta = 0$")
ax2.loglog([f_mag_ex.min(), f_mag_ex.max()], [f_mag_ex.min(), f_mag_ex.max()], "k--", lw=1.4, label="1:1 exact parity")
ax2.set_xlabel(r"Exact force magnitude $\|\mathbf{F}_i\|$")
ax2.set_ylabel(r"Barnes-Hut force $\|\tilde{\mathbf{F}}_i\|$")
ax2.set_title(f"Force parity ({speedup_bh:.1f}x fewer kernel evals, {100*rel_rms_err:.2f}% err)")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
assert rel_rms_err < 0.015 and speedup_bh > 4.0
Demonstration 1: Adaptive 2-D Barnes-Hut quadtree around clustered vortex and star cores
========================================================================================
N = 240 clustered bodies | Quadtree max depth = 9 | Occupied cells = 437
theta = 0.00 (exact tree walk): 57,360 kernel evals
theta = 0.55 (multipole lump) : 11,713 kernel evals (4.90x fewer) | Rel RMS Force Err = 0.413%

Figure 5.1. Barnes–Hut on 240 clustered bodies. (a) The quadtree: large cells cover the empty space between the clusters, small cells the dense cores. (b) Force magnitudes from the tree at against the exact forces; the points lie on the diagonal, with an RMS error of 0.41 % and 4.9 times fewer kernel evaluations.
The quadtree adapts to the geometry: the empty regions between clusters are covered by a few large cells, each replaced by one monopole, while the dense cores are subdivided deeply. At the tree walk needs 4.9 times fewer kernel evaluations than the exact walk, for an RMS force error of 0.41 %.
2. The Barnes–Hut Pareto Frontier & Scaling¶
The opening angle acts as a continuous dial trading CPU work against approximation error: opens every internal node down to individual leaves (exact ), and larger gives cheaper, coarser estimates. We sweep and verify scaling across .
heading("Demonstration 2: Opening-angle Pareto curve and O(N log N) evaluation scaling")
thetas = [0.15, 0.30, 0.45, 0.60, 0.80, 1.05]
speedups_th, rms_errs_th = [], []
for th in thetas:
r_th = divide_spatial.barnes_hut_quadtree_2d(pts_bh, masses_bh, theta=th, eps_soft=0.15)
err_t = float(np.linalg.norm(r_th["forces"] - exact_bh["forces"]) / np.linalg.norm(exact_bh["forces"]))
sp_t = exact_bh["exact_pair_evaluations"] / r_th["force_evaluations"]
speedups_th.append(sp_t)
rms_errs_th.append(err_t)
print(f"theta = {th:4.2f} -> evals = {r_th['force_evaluations']:6,d} ({sp_t:5.2f}x speedup) | Rel RMS Force Error = {100*err_t:6.3f}%")
n_scale_bh = np.array([50, 100, 200, 400, 800], dtype=float)
evals_bh_n, evals_exact_n = [], []
for n_s in n_scale_bh:
p_s = rng_bh.uniform(0.0, 100.0, size=(int(n_s), 2))
m_s = np.ones(int(n_s), dtype=float)
out_s = divide_spatial.barnes_hut_quadtree_2d(p_s, m_s, theta=0.65, eps_soft=0.20)
evals_bh_n.append(out_s["force_evaluations"])
evals_exact_n.append(out_s["exact_pair_evaluations"])
fit_bh_n = invariants_complexity.fit_empirical_complexity(n_scale_bh, np.array(evals_bh_n, dtype=float))
print(f"\nBarnes-Hut (theta=0.65) empirical scaling: p = {fit_bh_n['exponent_p']:.3f} ({fit_bh_n['complexity_class']}) vs All-Pairs O(N^2)")
print(f"N = 800: {evals_exact_n[-1]:,} all-pairs vs {evals_bh_n[-1]:,} Barnes-Hut evaluations ({evals_exact_n[-1] / evals_bh_n[-1]:.1f}x fewer)")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
ax1.semilogy(speedups_th, np.array(rms_errs_th) * 100.0, "o-", color="#C0392B", lw=2.1)
for th, sp_v, er_v in zip(thetas, speedups_th, rms_errs_th):
ax1.annotate(f"$\\theta={th:.2f}$", (sp_v, er_v * 100.0), xytext=(7, -9), textcoords="offset points", fontsize=7.8)
ax1.margins(x=0.12)
ax1.set_xlabel(r"Kernel evaluation speedup $N(N-1) / N_{\mathrm{BH}}$")
ax1.set_ylabel("Relative RMS force error [%]")
ax1.set_title("Force error against speed-up")
ax2.loglog(n_scale_bh, evals_exact_n, "o-", color="#C0392B", lw=2.1, label=r"Exact all-pairs $N(N-1)$")
ax2.loglog(n_scale_bh, evals_bh_n, "s--", color="#2166AC", lw=2.1, label=f"Barnes-Hut $\\theta=0.65$ (p={fit_bh_n['exponent_p']:.2f})")
ax2.set_xlabel("Particle count $N$")
ax2.set_ylabel("Force kernel evaluations")
ax2.set_title("Hierarchical grouping against all pairs")
ax2.legend(fontsize=8.2)
log_ticks(ax2, "x", [50, 100, 200, 400, 800])
label_panels(fig)
plt.show()
assert all(speedups_th[i] < speedups_th[i + 1] for i in range(len(speedups_th) - 1))
assert fit_bh_n["complexity_class"] == "O(N log N)" and fit_bh_n["exponent_p"] < 1.45
Demonstration 2: Opening-angle Pareto curve and O(N log N) evaluation scaling
=============================================================================
theta = 0.15 -> evals = 27,810 ( 2.06x speedup) | Rel RMS Force Error = 0.006%
theta = 0.30 -> evals = 18,029 ( 3.18x speedup) | Rel RMS Force Error = 0.066%
theta = 0.45 -> evals = 13,311 ( 4.31x speedup) | Rel RMS Force Error = 0.208%
theta = 0.60 -> evals = 11,016 ( 5.21x speedup) | Rel RMS Force Error = 0.541%
theta = 0.80 -> evals = 7,968 ( 7.20x speedup) | Rel RMS Force Error = 1.380%
theta = 1.05 -> evals = 6,011 ( 9.54x speedup) | Rel RMS Force Error = 2.504%
Barnes-Hut (theta=0.65) empirical scaling: p = 1.402 (O(N log N)) vs All-Pairs O(N^2)
N = 800: 639,200 all-pairs vs 47,785 Barnes-Hut evaluations (13.4x fewer)

Figure 5.2. Accuracy and cost of Barnes–Hut. (a) RMS force error against the reduction in kernel evaluations for opening angles from 0.15 to 1.05. (b) Kernel evaluations against at , with exponent 1.40, compared with all pairs.
At and , Barnes–Hut needs kernel evaluations instead of , 13.4 times fewer. The exponent fitted over to 800 is 1.40, which the doubling test classifies as ; at these small the local slope is still well above 1, so it should not be extrapolated to very large systems.
3. Frequency Hierarchy: Cooley–Tukey Radix-2 FFT Convolution (radix2_fft_convolve)¶
Direct 1-D discrete linear convolution requires multiply-adds. Mental Move #14, Diagonalize Convolution in Frequency Space uses two facts:
Convolution Theorem: Zero-padding and to turns Toeplitz convolution into independent scalar multiplications .
Cooley–Tukey Even/Odd Butterfly Symmetry (1965): Splitting into even indices and odd indices reuses the half-length DFTs across upper and lower halves via ():
heading("Demonstration 3: Exact 1-D acoustic impulse-response convolution via Cooley-Tukey radix-2 FFT")
rng_fft = np.random.default_rng(1965)
n_sig_a, n_ir_b = 2048, 512
t_a = np.linspace(0.0, 2.0, n_sig_a)
dry_pulse = np.sin(2.0 * math.pi * 18.0 * t_a) * np.exp(-((t_a - 0.45) / 0.12) ** 2) + 0.65 * np.exp(-((t_a - 1.25) / 0.05) ** 2)
# Reverberant room / seismic waveguide impulse response h[n]:
t_b = np.arange(n_ir_b, dtype=float) / 1024.0
room_ir = np.exp(-6.5 * t_b) * (0.8 * np.cos(2.0 * math.pi * 42.0 * t_b) + 0.3 * rng_fft.normal(size=n_ir_b))
conv_fft = divide_spatial.radix2_fft_convolve(dry_pulse, room_ir)
conv_direct = np.convolve(dry_pulse, room_ir, mode="full")
max_conv_diff = float(np.max(np.abs(conv_fft - conv_direct)))
n_fft_pad = 1 << (n_sig_a + n_ir_b - 2).bit_length()
direct_macs = n_sig_a * n_ir_b
fft_ops_est = int(3 * 5 * n_fft_pad * math.log2(n_fft_pad))
print(f"Signal N_a = {n_sig_a}, Kernel N_b = {n_ir_b} -> Zero-padded radix-2 N_fft = {n_fft_pad}")
print(f"Max |radix2_fft_convolve - np.convolve| = {max_conv_diff:.2e}")
print(f"Direct MACs = {direct_macs:,d} vs ~3 Radix-2 FFTs = {fft_ops_est:,d} (~{direct_macs/fft_ops_est:.1f}x arithmetic gain, >1000x at N=10^6)")
assert conv_fft.size == n_sig_a + n_ir_b - 1
assert max_conv_diff < 1.0e-11
Demonstration 3: Exact 1-D acoustic impulse-response convolution via Cooley-Tukey radix-2 FFT
=============================================================================================
Signal N_a = 2048, Kernel N_b = 512 -> Zero-padded radix-2 N_fft = 4096
Max |radix2_fft_convolve - np.convolve| = 1.33e-15
Direct MACs = 1,048,576 vs ~3 Radix-2 FFTs = 737,280 (~1.4x arithmetic gain, >1000x at N=10^6)
radix2_fft_convolveagrees withnp.convolveto because zero-padding to leaves a guard band of 1537 samples, so the circular wrap-around never reaches the linear result. At this size the FFT route saves only a factor of 1.4 in arithmetic; the gain grows as .
4. A Weak Echo in Noise: FFT Matched-Filter Radar Echo Detection¶
In radar, sonar, medical ultrasound, and LIGO gravitational-wave astronomy, a known linear FM chirp ( samples) is reflected by a target at an unknown delay, here samples, and returns with amplitude 1.15 under Gaussian noise of standard deviation (synthetic signal; the per-sample signal-to-noise ratio is about , and the echo cannot be seen in the raw trace). Cross-correlating received trace with time-reversed template via radix2_fft_convolve adds the samples of the echo coherently into one correlation peak.
heading("Demonstration 4: Radar chirp matched-filter peak extraction at negative SNR (-8 dB)")
rng_mf = np.random.default_rng(2020)
m_chirp = 512
tau_c = np.linspace(0.0, 1.0, m_chirp)
# Unit-amplitude linear FM chirp sweeping from f0=6 cycles to f1=54 cycles:
chirp_template = np.sin(2.0 * math.pi * (6.0 * tau_c + 24.0 * (tau_c ** 2)))
n_rx = 2048
true_lag = 620
clean_echo = np.zeros(n_rx, dtype=float)
clean_echo[true_lag : true_lag + m_chirp] = 1.15 * chirp_template
heavy_noise = rng_mf.normal(0.0, 2.00, size=n_rx)
rx_noisy = clean_echo + heavy_noise
# Matched filter via FFT linear convolution with time-reversed template:
corr_full = divide_spatial.radix2_fft_convolve(rx_noisy, chirp_template[::-1])
# Alignment offset: peak of conv(rx, s[::-1]) occurs at index true_lag + (m_chirp - 1):
valid_lags = np.arange(n_rx - m_chirp + 1)
corr_aligned = corr_full[m_chirp - 1 : m_chirp - 1 + valid_lags.size]
detected_lag = int(np.argmax(corr_aligned))
peak_zscore = float((corr_aligned[detected_lag] - np.mean(corr_aligned)) / np.std(corr_aligned))
print(f"True echo arrival lag = {true_lag} | FFT Matched-Filter detected lag = {detected_lag} | Peak Z-score = {peak_zscore:.2f} sigma")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
ax1.plot(rx_noisy, color="#6B7280", lw=0.7, alpha=0.8, label=r"Noisy receiver $r[n]$ ($\sigma=2.0$)")
ax1.plot(clean_echo, color="#C0392B", lw=1.3, label="Hidden true echo (amp 1.15)")
ax1.set_xlabel("Sample index $n$")
ax1.set_ylabel("Receiver voltage [V]")
ax1.set_title("Time domain: echo hidden in noise")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.0)
ax2.plot(valid_lags, corr_aligned, color="#2166AC", lw=1.1, label="FFT matched-filter output")
ax2.axvline(detected_lag, color="#C0392B", ls="--", lw=1.6, label=f"Detected lag = {detected_lag} ({peak_zscore:.1f}$\\sigma$)")
ax2.set_xlabel("Candidate delay lag $n_0$ [samples]")
ax2.set_ylabel("Cross-correlation amplitude")
ax2.set_title("Matched-filter output")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
assert detected_lag == true_lag
assert peak_zscore > 6.0
Demonstration 4: Radar chirp matched-filter peak extraction at negative SNR (-8 dB)
===================================================================================
True echo arrival lag = 620 | FFT Matched-Filter detected lag = 620 | Peak Z-score = 6.46 sigma

Figure 5.3. Matched filtering of a synthetic radar echo. (a) The received trace (grey) with the echo of amplitude 1.15 (red) under noise of standard deviation 2.0. (b) The correlation with the time-reversed chirp, computed with the radix-2 FFT, peaks at the true delay of 620 samples (dashed).
Inside the algorithm¶
We inspect divide_spatial._fft_radix2 and divide_spatial.barnes_hut_quadtree_2d, and implement an In-Place Iterative Bit-Reversal Cooley–Tukey FFT (iterative_bitrev_fft) that eliminates all recursive array allocations by permuting input indices via bit-reversal first and sweeping contiguous butterfly stages.
Check against the library¶
heading("Inside the algorithm: Recursive against iterative bit-reversal Cooley-Tukey radix-2 FFT")
print(show_source(divide_spatial._fft_radix2))
print(show_source(divide_spatial.barnes_hut_quadtree_2d))
def iterative_bitrev_fft(x: np.ndarray, inverse: bool = False) -> np.ndarray:
"""Non-recursive in-place radix-2 Cooley-Tukey FFT using bit-reversed permutation + log2(N) butterfly stages."""
arr = np.asarray(x, dtype=np.complex128).ravel()
n = arr.size
if n == 0 or (n & (n - 1)) != 0:
raise ValueError("Length N must be a positive power of two.")
bits = n.bit_length() - 1
# 1. Bit-reversal index permutation in vectorized NumPy:
indices = np.arange(n, dtype=np.int64)
rev_idx = np.zeros(n, dtype=np.int64)
for b_i in range(bits):
rev_idx = (rev_idx << 1) | ((indices >> b_i) & 1)
buf = arr[rev_idx].copy()
# 2. Bottom-up butterfly stages m = 2, 4, 8, ..., N:
sign = +2.0j if inverse else -2.0j
m = 2
while m <= n:
half = m // 2
w_m = np.exp((sign * math.pi / m) * np.arange(half, dtype=float))
for k0 in range(0, n, m):
u = buf[k0 : k0 + half].copy()
t = w_m * buf[k0 + half : k0 + m]
buf[k0 : k0 + half] = u + t
buf[k0 + half : k0 + m] = u - t
m *= 2
return (buf / float(n)) if inverse else buf
rng_it = np.random.default_rng(512)
sig_c = rng_it.normal(size=512) + 1.0j * rng_it.normal(size=512)
fft_rec = divide_spatial._fft_radix2(sig_c, inverse=False)
fft_itr = iterative_bitrev_fft(sig_c, inverse=False)
fft_np = np.fft.fft(sig_c)
roundtrip_sig = iterative_bitrev_fft(fft_itr, inverse=True)
print(f"Max |iterative_fft - _fft_radix2| : {np.max(np.abs(fft_itr - fft_rec)):.2e}")
print(f"Max |iterative_fft - np.fft.fft| : {np.max(np.abs(fft_itr - fft_np)):.2e}")
print(f"Max |IFFT(FFT(x)) - x| roundtrip : {np.max(np.abs(roundtrip_sig - sig_c)):.2e}")
assert np.allclose(fft_itr, fft_rec, atol=1.0e-12)
assert np.allclose(fft_itr, fft_np, atol=1.0e-12)
assert np.allclose(roundtrip_sig, sig_c, atol=1.0e-13)
Inside the algorithm: Recursive against iterative bit-reversal Cooley-Tukey radix-2 FFT
=======================================================================================
def _fft_radix2(x: np.ndarray, inverse: bool = False) -> np.ndarray:
"""Pure-NumPy recursive Cooley-Tukey radix-2 FFT (power-of-two length N)."""
n = x.size
if n == 1:
return x.astype(np.complex128)
even = _fft_radix2(x[0::2], inverse=inverse)
odd = _fft_radix2(x[1::2], inverse=inverse)
sign = +2.0j if inverse else -2.0j
k = np.arange(n // 2, dtype=float)
twiddle = np.exp((sign * math.pi / n) * k) * odd
out = np.empty(n, dtype=np.complex128)
out[: n // 2] = even + twiddle
out[n // 2 :] = even - twiddle
return out
def barnes_hut_quadtree_2d(
coords: np.ndarray,
masses: np.ndarray,
theta: float = 0.5,
eps_soft: float = 0.05,
) -> dict:
"""Build a 2-D Barnes-Hut Quadtree and evaluate softened N-body forces in O(N log N) with opening angle theta."""
pts = np.asarray(coords, dtype=float)
m_arr = np.asarray(masses, dtype=float).ravel()
if pts.ndim != 2 or pts.shape[1] != 2 or pts.shape[0] != m_arr.size or pts.shape[0] < 2:
raise ValueError("Require (N, 2) coords and length-N positive masses with N >= 2.")
if np.any(m_arr <= 0.0) or theta < 0.0 or eps_soft <= 0.0:
raise ValueError("Require masses > 0, theta >= 0, and eps_soft > 0.")
n = pts.shape[0]
xmin, ymin = np.min(pts, axis=0)
xmax, ymax = np.max(pts, axis=0)
span = max(float(xmax - xmin), float(ymax - ymin), 1e-6) * 1.02
root = _QuadNode(0.5 * float(xmin + xmax), 0.5 * float(ymin + ymax), span, depth=0)
max_depth = [0]
def _quadrant(node: _QuadNode, px: float, py: float) -> int:
east = 1 if px >= node.cx else 0
north = 2 if py >= node.cy else 0
return east + north
def _make_child(node: _QuadNode, q: int) -> _QuadNode:
q_size = 0.5 * node.size
quarter = 0.25 * node.size
dx = quarter if (q & 1) else -quarter
dy = quarter if (q & 2) else -quarter
max_depth[0] = max(max_depth[0], node.depth + 1)
return _QuadNode(node.cx + dx, node.cy + dy, q_size, node.depth + 1)
def _insert(node: _QuadNode, p_idx: int) -> None:
px, py, pm = float(pts[p_idx, 0]), float(pts[p_idx, 1]), float(m_arr[p_idx])
if node.mass == 0.0 and node.children is None:
node.mass = pm
node.com_x = px
node.com_y = py
node.idx = p_idx
return
if node.children is None:
old_idx = node.idx
node.idx = -1
node.children = [None, None, None, None]
if node.depth < 40:
q_old = _quadrant(node, float(pts[old_idx, 0]), float(pts[old_idx, 1]))
node.children[q_old] = _make_child(node, q_old)
_insert(node.children[q_old], old_idx) # type: ignore[arg-type]
new_mass = node.mass + pm
node.com_x = (node.mass * node.com_x + pm * px) / new_mass
node.com_y = (node.mass * node.com_y + pm * py) / new_mass
node.mass = new_mass
if node.children is not None and node.depth < 40:
q_new = _quadrant(node, px, py)
if node.children[q_new] is None:
node.children[q_new] = _make_child(node, q_new)
_insert(node.children[q_new], p_idx) # type: ignore[arg-type]
for i in range(n):
_insert(root, i)
boxes: list[tuple[float, float, float]] = []
def _collect_boxes(node: _QuadNode | None) -> None:
if node is None or node.mass == 0.0:
return
boxes.append((node.cx - 0.5 * node.size, node.cy - 0.5 * node.size, node.size))
if node.children is not None:
for ch in node.children:
_collect_boxes(ch)
_collect_boxes(root)
eps2 = float(eps_soft) ** 2
forces = np.zeros((n, 2), dtype=float)
eval_counter = [0]
def _accum_force(node: _QuadNode | None, target_i: int, tx: float, ty: float, tm: float) -> tuple[float, float]:
if node is None or node.mass == 0.0:
return 0.0, 0.0
if node.children is None:
if node.idx == target_i:
return 0.0, 0.0
dx = node.com_x - tx
dy = node.com_y - ty
inv_r3 = (dx * dx + dy * dy + eps2) ** (-1.5)
eval_counter[0] += 1
fac = tm * node.mass * inv_r3
return fac * dx, fac * dy
dx = node.com_x - tx
dy = node.com_y - ty
dist = math.hypot(dx, dy)
if theta > 0.0 and dist > 0.0 and (node.size / dist) < theta:
inv_r3 = (dx * dx + dy * dy + eps2) ** (-1.5)
eval_counter[0] += 1
fac = tm * node.mass * inv_r3
return fac * dx, fac * dy
fx_tot = 0.0
fy_tot = 0.0
for ch in node.children:
dfx, dfy = _accum_force(ch, target_i, tx, ty, tm)
fx_tot += dfx
fy_tot += dfy
return fx_tot, fy_tot
for i in range(n):
fx, fy = _accum_force(root, i, float(pts[i, 0]), float(pts[i, 1]), float(m_arr[i]))
forces[i, 0] = fx
forces[i, 1] = fy
return {
"forces": forces,
"force_evaluations": eval_counter[0],
"exact_pair_evaluations": n * (n - 1),
"tree_boxes": boxes,
"max_depth": max_depth[0],
}
Max |iterative_fft - _fft_radix2| : 0.00e+00
Max |iterative_fft - np.fft.fft| : 4.02e-14
Max |IFFT(FFT(x)) - x| roundtrip : 1.34e-15
Exercises¶
Worked solutions are in 05_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify Discrete Parseval’s Energy Theorem using
divide_spatial._fft_radix2across 20 random complex signals (), and verify the exact modulo- folding relation between circular FFT product anddivide_spatial.radix2_fft_convolve.Find how it fails. Quantify (a) non-causal wrap-around pre-echo energy at when an impulse at () is convolved with a 128-tap exponential filter without zero-padding, and (b) net system force drift (Newton’s 3rd Law violation) in
barnes_hut_quadtree_2dat vs. .Implement it yourself. Implement
quadtree_range_count(coords, rect_queries)building a 2-D Quadtree with exact subtree countsnode.countand answering each rectangle(xmin, ymin, xmax, ymax)by pruning disjoint quadrants (0) and short-circuiting wholly contained quadrants (+node.count). Verify exact counts against brute force across 80 random rectangles on clustered points while achieving reduction in point/node inspections.
heading("Self-check for the exercises")
assert rel_rms_err < 0.015 and speedup_bh > 4.0
assert max_conv_diff < 1.0e-11 and detected_lag == true_lag
assert np.allclose(fft_itr, fft_rec, atol=1.0e-12)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.