Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

5. Spatial and frequency hierarchies: Barnes–Hut quadtrees and the fast Fourier transform

School of Engineering, Nazarbayev University

In Lecture 3, spatial cell lists reduced short-range cutoff interactions (r≤rcr \le r_c) from O(N2)\mathcal{O}(N^2) to O(N)\mathcal{O}(N). But what about long-range forces that never cut off, gravitational galaxies, Coulomb plasmas, Biot–Savart vortex sheets (F∝1/r2F \propto 1/r^2), or global integral convolutions across millions of acoustic/radar samples? Two hierarchical divide-and-conquer methods reduce such O(N2)\mathcal{O}(N^2) sums to O(Nlog⁡N)\mathcal{O}(N \log N) (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 s/d<θs / d < \theta, while Cooley–Tukey Radix-2 FFT (divide_spatial.radix2_fft_convolve) diagonalizes convolution in frequency space (Mental Moves #13–#14).

Learning objectives

  1. Construct adaptive 2-D spatial trees via divide_spatial.barnes_hut_quadtree_2d, verifying exact machine-precision agreement with O(N2)\mathcal{O}(N^2) NN-body forces at θ=0\theta = 0 and O(Nlog⁡N)\mathcal{O}(N\log N) speedup for θ>0\theta > 0.

  2. Quantify the Speedup vs. Force-Accuracy Pareto Frontier across multipole opening angles θ∈[0,1.1]\theta \in [0, 1.1].

  3. Execute exact O(Nlog⁡N)\mathcal{O}(N\log N) linear convolution via divide_spatial.radix2_fft_convolve, relating Cooley–Tukey even/odd index parity to roots-of-unity butterfly stages.

  4. Detect deeply buried chirp echoes under negative signal-to-noise ratio (SNR<0 dB\mathrm{SNR} < 0\,\mathrm{dB}) via FFT matched-filter cross-correlation.

Time: about 60 min

1. Adaptive Spatial Hierarchy: 2-D Barnes–Hut Quadtrees (barnes_hut_quadtree_2d)

Unlike short-range Lennard-Jones potentials, gravitational and electrostatic forces Fij=mimj(xj−xi)/(∥xj−xi∥2+ε2)3/2\mathbf{F}_{ij} = m_i m_j (\mathbf{x}_j - \mathbf{x}_i) / (\|\mathbf{x}_j - \mathbf{x}_i\|^2 + \varepsilon^2)^{3/2} couple every body to every other body (N(N−1)N(N-1) 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 M=∑mjM = \sum m_j at its center of mass Xcm=1M∑mjxj\mathbf{X}_{\mathrm{cm}} = \frac{1}{M}\sum m_j \mathbf{x}_j.

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 (M,Xcm)(M, \mathbf{X}_{\mathrm{cm}}) at every internal node in O(Nlog⁡N)\mathcal{O}(N \log N). When evaluating force on body ii from a cell of width ss at center-of-mass distance dd:

sd<θ  ⟹  accept monopole (M,Xcm) in O(1);otherwise recurse into its 4 children(1.1)\frac{s}{d} < \theta \implies \text{accept monopole } (M, \mathbf{X}_{\mathrm{cm}}) \text{ in } \mathcal{O}(1); \qquad \text{otherwise recurse into its } 4 \text{ children} \tag{1.1}

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 size 1265x484 with 2 Axes>

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 θ=0.55\theta = 0.55 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 θ=0.55\theta = 0.55 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 & O(Nlog⁡N)\mathcal{O}(N \log N) Scaling

The opening angle θ≥0\theta \ge 0 acts as a continuous dial trading CPU work against approximation error: θ=0\theta = 0 opens every internal node down to individual leaves (exact O(N2)\mathcal{O}(N^2)), and larger θ\theta gives cheaper, coarser estimates. We sweep θ\theta and verify O(Nlog⁡N)\mathcal{O}(N \log N) scaling across N∈[50,800]N \in [50, 800].


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 size 1265x451 with 2 Axes>

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 NN at θ=0.65\theta = 0.65, with exponent 1.40, compared with all N(N−1)N(N-1) pairs.

  • At N=800N = 800 and θ=0.65\theta = 0.65, Barnes–Hut needs 47,78547{,}785 kernel evaluations instead of 639,200639{,}200, 13.4 times fewer. The exponent fitted over N=50N = 50 to 800 is 1.40, which the doubling test classifies as O(Nlog⁡N)\mathcal{O}(N \log N); at these small NN 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 (a∗b)n=∑mambn−m(a * b)_n = \sum_{m} a_m b_{n-m} requires NaNb∼O(N2)N_a N_b \sim \mathcal{O}(N^2) multiply-adds. Mental Move #14, Diagonalize Convolution in Frequency Space uses two facts:

  1. Convolution Theorem: Zero-padding aa and bb to Nfft=2⌈log⁡2(Na+Nb−1)⌉N_{\mathrm{fft}} = 2^{\lceil \log_2(N_a + N_b - 1) \rceil} turns Toeplitz convolution into NfftN_{\mathrm{fft}} independent scalar multiplications (a∗b)^k=a^k⋅b^k\widehat{(a * b)}_k = \hat{a}_k \cdot \hat{b}_k.

  2. Cooley–Tukey Even/Odd Butterfly Symmetry (1965): Splitting xx into even indices x2mx_{2m} and odd indices x2m+1x_{2m+1} reuses the half-length DFTs across upper and lower halves via ωNk+N/2=−ωNk\omega_N^{k + N/2} = -\omega_N^k (ωN=e−2πi/N\omega_N = e^{-2\pi i / N}):

X^k=Ek+ωNkOk,X^k+N/2=Ek−ωNkOk  ⟹  T(N)=2 T(N/2)+O(N)=O(Nlog⁡N)(3.1)\hat{X}_k = E_k + \omega_N^k O_k, \qquad \hat{X}_{k + N/2} = E_k - \omega_N^k O_k \qquad \implies T(N) = 2\,T(N/2) + \mathcal{O}(N) = \mathcal{O}(N \log N) \tag{3.1}

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_convolve agrees with np.convolve to 1.3×10−151.3 \times 10^{-15} because zero-padding to Nfft=4096≥2048+512−1=2559N_{\mathrm{fft}} = 4096 \ge 2048 + 512 - 1 = 2559 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 N/log⁡2NN / \log_2 N.


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 s[n]s[n] (M=512M = 512 samples) is reflected by a target at an unknown delay, here n0=620n_0 = 620 samples, and returns with amplitude 1.15 under Gaussian noise of standard deviation σ=2.0\sigma = 2.0 (synthetic signal; the per-sample signal-to-noise ratio is about −8 dB-8\,\mathrm{dB}, and the echo cannot be seen in the raw trace). Cross-correlating received trace r[n]r[n] with time-reversed template h[n]=s[M−1−n]h[n] = s[M - 1 - n] via radix2_fft_convolve adds the MM samples of the echo coherently into one correlation peak.


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 size 1265x451 with 2 Axes>

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 log⁡2N\log_2 N contiguous butterfly stages.

Check against the library


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.

  1. Verify a result. Verify Discrete Parseval’s Energy Theorem ∑∣xn∣2=1N∑∣X^k∣2\sum |x_n|^2 = \frac{1}{N}\sum |\hat{X}_k|^2 using divide_spatial._fft_radix2 across 20 random complex signals (N=512N = 512), and verify the exact modulo-NN folding relation between circular FFT product and divide_spatial.radix2_fft_convolve.

  2. Find how it fails. Quantify (a) non-causal wrap-around pre-echo energy at n<90n < 90 when an impulse at n0=980n_0 = 980 (N=1024N = 1024) is convolved with a 128-tap exponential filter without zero-padding, and (b) net system force drift ∥∑iFi∥\left\|\sum_i \mathbf{F}_i\right\| (Newton’s 3rd Law violation) in barnes_hut_quadtree_2d at θ=1.2\theta = 1.2 vs. θ=0.0\theta = 0.0.

  3. Implement it yourself. 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 100%100\% exact counts against brute force across 80 random rectangles on N=2,000N = 2{,}000 clustered points while achieving >10×>10\times reduction in point/node inspections.


Self-check for the exercises
============================
All checks passed.