Solutions · 5. Spatial and frequency hierarchies: Barnes–Hut quadtrees and the fast Fourier transform
Worked solutions to the three exercises of Lecture 5. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify Discrete Parseval’s Energy Theorem using divide_spatial._fft_radix2 across 20 random complex signals (), and verify the exact modulo- folding relation between circular FFT product and divide_spatial.radix2_fft_convolve.
heading("Exercise 1: Parseval energy conservation and modulo-N circular convolution folding")
rng_p1 = np.random.default_rng(91)
max_parseval_rel_err = 0.0
for _ in range(20):
x_sig = rng_p1.normal(size=512) + 1.0j * rng_p1.normal(size=512)
X_freq = divide_spatial._fft_radix2(x_sig, inverse=False)
e_time = float(np.sum(np.abs(x_sig) ** 2))
e_freq = float(np.sum(np.abs(X_freq) ** 2)) / 512.0
max_parseval_rel_err = max(max_parseval_rel_err, abs(e_time - e_freq) / e_time)
# Verify exact identity: N-point circular convolution == length-(2N-1) linear convolution folded modulo N
n_circ = 256
sig_a = rng_p1.normal(size=n_circ)
sig_b = rng_p1.normal(size=n_circ)
fa = divide_spatial._fft_radix2(sig_a.astype(np.complex128), inverse=False)
fb = divide_spatial._fft_radix2(sig_b.astype(np.complex128), inverse=False)
circ_conv = np.real(divide_spatial._fft_radix2(fa * fb, inverse=True)) / n_circ
lin_conv = divide_spatial.radix2_fft_convolve(sig_a, sig_b) # Length 2*N - 1 = 511
folded_lin = lin_conv[:n_circ].copy()
folded_lin[: n_circ - 1] += lin_conv[n_circ:]
fold_diff = float(np.max(np.abs(circ_conv - folded_lin)))
print(f"Max Parseval energy relative error across 20 complex signals : {max_parseval_rel_err:.2e}")
print(f"Max |Circular FFT(N) - Modulo-N Folded Linear Convolution| : {fold_diff:.2e}")
assert max_parseval_rel_err < 1.0e-14
assert fold_diff < 1.0e-12
Exercise 1: Parseval energy conservation and modulo-N circular convolution folding
==================================================================================
Max Parseval energy relative error across 20 complex signals : 2.19e-16
Max |Circular FFT(N) - Modulo-N Folded Linear Convolution| : 7.11e-15
Explanation. Up to normalization , the DFT matrix is unitary (), preserving inner products and total physical wave energy. Without zero-padding, sampling frequency domain at enforces periodic boundary conditions , folding index of the linear convolution directly onto .
Exercise 2¶
Problem. 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_2d at vs. .
heading("Exercise 2: Audit of unpadded FFT causal wrap-around and Barnes-Hut momentum drift")
# (a) Causal shock at n0 = 980 in N = 1024 convolved with 128-tap filter WITHOUT zero-padding:
n_buf = 1024
x_causal = np.zeros(n_buf, dtype=float)
x_causal[980] = 10.0 # Zero signal everywhere before n = 980
h_filt = np.zeros(n_buf, dtype=float)
h_filt[:128] = np.exp(-np.arange(128) / 28.0)
fx = divide_spatial._fft_radix2(x_causal.astype(np.complex128))
fh = divide_spatial._fft_radix2(h_filt.astype(np.complex128))
y_unpadded = np.real(divide_spatial._fft_radix2(fx * fh, inverse=True)) / n_buf
y_linear = divide_spatial.radix2_fft_convolve(x_causal, h_filt[:128])[:n_buf]
ghost_preecho_energy = float(np.sum(y_unpadded[:90] ** 2))
true_early_energy = float(np.sum(y_linear[:90] ** 2))
print("(a) Causal output energy on n in [0..89] (before shock at n=980):")
print(f" True zero-padded linear conv = {true_early_energy:.2e} | Unpadded circular FFT = {ghost_preecho_energy:.2f} <-- wrap-around before the impulse")
# (b) Net internal force sum_i F_i (Newton's 3rd law requires sum_i F_i == [0, 0] in isolated N-body system):
rng_m = np.random.default_rng(71)
pts_asym = np.vstack([rng_m.normal([0.0, 0.0], 1.2, size=(90, 2)), rng_m.normal([14.0, 5.0], 4.8, size=(30, 2))])
m_asym = rng_m.uniform(0.5, 3.0, size=120)
bh_th0 = divide_spatial.barnes_hut_quadtree_2d(pts_asym, m_asym, theta=0.0, eps_soft=0.10)
bh_th12 = divide_spatial.barnes_hut_quadtree_2d(pts_asym, m_asym, theta=1.2, eps_soft=0.10)
net_f_exact = float(np.linalg.norm(np.sum(bh_th0["forces"], axis=0)))
net_f_th12 = float(np.linalg.norm(np.sum(bh_th12["forces"], axis=0)))
char_f = float(np.mean(np.linalg.norm(bh_th0["forces"], axis=1)))
print("\n(b) Net system momentum-drift force ||sum F_i||:")
print(f" Exact theta = 0.0 : {net_f_exact:.2e} | Aggressive theta = 1.2 : {net_f_th12:.4f} ({100*net_f_th12/char_f:.2f}% of mean particle force)")
assert true_early_energy < 1.0e-26 and ghost_preecho_energy > 50.0
assert net_f_exact < 1.0e-12 and net_f_th12 > 1.0e-2
Exercise 2: Audit of unpadded FFT causal wrap-around and Barnes-Hut momentum drift
==================================================================================
(a) Causal output energy on n in [0..89] (before shock at n=980):
True zero-padded linear conv = 3.05e-30 | Unpadded circular FFT = 62.45 <-- wrap-around before the impulse
(b) Net system momentum-drift force ||sum F_i||:
Exact theta = 0.0 : 1.52e-13 | Aggressive theta = 1.2 : 114.5613 (119.44% of mean particle force)
Explanation. Because , output samples wrap modulo 1024 onto , so the circular result shows signal before the impulse arrives. In Barnes–Hut, particle in a tight cluster may lump a wide cell (), while particles open ’s parent cell differently, breaking pairwise antisymmetry so the centre of mass of an isolated system drifts unless symmetric cell–cell interactions (Fast Multipole Method) are used.
Exercise 3¶
Problem. Implement quadtree_range_count(coords, rect_queries) building a 2-D Quadtree with exact subtree counts node.count and 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("Exercise 3: Implement it yourself — sublinear 2-D quadtree orthogonal range counting")
class _CountQuadNode:
__slots__ = ("xmin", "ymin", "xmax", "ymax", "count", "pt_idx", "children", "depth")
def __init__(self, xmin: float, ymin: float, xmax: float, ymax: float, depth: int) -> None:
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.count = 0
self.pt_idx = -1
self.children: list[_CountQuadNode | None] | None = None
self.depth = depth
def quadtree_range_count(coords: np.ndarray, rect_queries: list[tuple[float, float, float, float]]) -> dict:
"""Build 2-D count-annotated Quadtree and evaluate exact orthogonal box counts via containment + disjoint pruning."""
pts = np.asarray(coords, dtype=float)
if pts.ndim != 2 or pts.shape[1] != 2 or pts.shape[0] == 0:
raise ValueError("coords must be non-empty of shape (N, 2).")
n = pts.shape[0]
x0, y0 = np.min(pts, axis=0) - 1.0e-6
x1, y1 = np.max(pts, axis=0) + 1.0e-6
root = _CountQuadNode(float(x0), float(y0), float(x1), float(y1), depth=0)
def _spawn(nd: _CountQuadNode, q: int) -> _CountQuadNode:
mx, my = 0.5 * (nd.xmin + nd.xmax), 0.5 * (nd.ymin + nd.ymax)
xa, xb = (mx, nd.xmax) if (q & 1) else (nd.xmin, mx)
ya, yb = (my, nd.ymax) if (q & 2) else (nd.ymin, my)
return _CountQuadNode(xa, ya, xb, yb, nd.depth + 1)
def _which_q(nd: _CountQuadNode, px: float, py: float) -> int:
mx, my = 0.5 * (nd.xmin + nd.xmax), 0.5 * (nd.ymin + nd.ymax)
return (1 if px >= mx else 0) + (2 if py >= my else 0)
def _insert(nd: _CountQuadNode, idx: int) -> None:
if nd.count == 0 and nd.children is None:
nd.count = 1
nd.pt_idx = idx
return
if nd.children is None and nd.depth < 36:
old_i = nd.pt_idx
nd.pt_idx = -1
nd.children = [None, None, None, None]
q_old = _which_q(nd, float(pts[old_i, 0]), float(pts[old_i, 1]))
nd.children[q_old] = _spawn(nd, q_old)
_insert(nd.children[q_old], old_i) # type: ignore[arg-type]
nd.count += 1
if nd.children is not None:
q_new = _which_q(nd, float(pts[idx, 0]), float(pts[idx, 1]))
if nd.children[q_new] is None:
nd.children[q_new] = _spawn(nd, q_new)
_insert(nd.children[q_new], idx) # type: ignore[arg-type]
for i in range(n):
_insert(root, i)
counts = np.zeros(len(rect_queries), dtype=int)
visited_nodes = 0
def _query(nd: _CountQuadNode | None, qx0: float, qy0: float, qx1: float, qy1: float) -> int:
nonlocal visited_nodes
if nd is None or nd.count == 0:
return 0
visited_nodes += 1
# Invariant 1 (Disjoint Prune): zero overlap -> 0 points
if nd.xmax < qx0 or nd.xmin > qx1 or nd.ymax < qy0 or nd.ymin > qy1:
return 0
# Invariant 2 (Wholly Contained Short-Circuit): return entire subtree count in O(1)
if qx0 <= nd.xmin and nd.xmax <= qx1 and qy0 <= nd.ymin and nd.ymax <= qy1:
return nd.count
# Leaf node partially overlapping query rectangle:
if nd.children is None:
px, py = float(pts[nd.pt_idx, 0]), float(pts[nd.pt_idx, 1])
return 1 if (qx0 <= px <= qx1 and qy0 <= py <= qy1) else 0
tot = 0
for ch in nd.children:
tot += _query(ch, qx0, qy0, qx1, qy1)
return tot
for q_idx, (qx0, qy0, qx1, qy1) in enumerate(rect_queries):
counts[q_idx] = _query(root, qx0, qy0, qx1, qy1)
brute_checks = n * len(rect_queries)
return {
"counts": counts,
"visited_nodes": visited_nodes,
"brute_point_checks": brute_checks,
"pruning_speedup": brute_checks / max(1, visited_nodes),
}
rng_qt = np.random.default_rng(2025)
centers_qt = np.array([[15.0, 20.0], [80.0, 25.0], [35.0, 80.0], [75.0, 75.0]])
pts_2000 = centers_qt[rng_qt.integers(0, 4, size=2000)] + rng_qt.normal(0.0, 8.5, size=(2000, 2))
rects_80 = []
oracle_counts = np.zeros(80, dtype=int)
for r_i in range(80):
xs = sorted(rng_qt.uniform(-5.0, 105.0, size=2).tolist())
ys = sorted(rng_qt.uniform(-5.0, 105.0, size=2).tolist())
rects_80.append((xs[0], ys[0], xs[1], ys[1]))
inside_mask = (pts_2000[:, 0] >= xs[0]) & (pts_2000[:, 0] <= xs[1]) & (pts_2000[:, 1] >= ys[0]) & (pts_2000[:, 1] <= ys[1])
oracle_counts[r_i] = int(np.sum(inside_mask))
qt_out = quadtree_range_count(pts_2000, rects_80)
print(f"80 range queries on N = 2,000 points -> Exact match: {np.array_equal(qt_out['counts'], oracle_counts)}")
print(f"Brute-force point checks = {qt_out['brute_point_checks']:,d} vs Quadtree node visits = {qt_out['visited_nodes']:,d} ({qt_out['pruning_speedup']:.1f}x speedup)")
assert np.array_equal(qt_out["counts"], oracle_counts)
assert qt_out["pruning_speedup"] > 10.0
Exercise 3: Implement it yourself — sublinear 2-D quadtree orthogonal range counting
====================================================================================
80 range queries on N = 2,000 points -> Exact match: True
Brute-force point checks = 160,000 vs Quadtree node visits = 12,508 (12.8x speedup)
Summary. Small query boxes are answered by pruning disjoint quadrants near the root, and large boxes by accepting whole interior subtrees in through node.count. Only cells that straddle the edge of the query rectangle are opened further, so the work scales with the perimeter of the box rather than its area; here 12,508 node visits replace 160,000 point checks.