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.

JAX-native CW04 substructure Q parameter

San Diego State University

The Cartwright & Whitworth (2004) Q parameter quantifies the spatial substructure of a stellar distribution as a single scalar derived from the minimum spanning tree (MST). progenax computes Q at multiple stages — during initial-condition validation, during dynamical evolution diagnostics, and during fractal-substructure calibration Goodwin & Whitworth, 2004Allison et al., 2009. The reference scipy implementation in progenax.diagnostics.substructure.compute_q_parameter is correct but non-differentiable, non-JIT-compatible, and O(N2)\mathcal{O}(N^2) in memory. This chapter records the design choice — a kNN-based approximation as the production path, with exact Borůvka MST available for cases that demand it — and the rationale.

What CW04 Q measures

Given NN stellar positions projected onto a plane, the CW04 Q is

Q    mˉsˉ,mˉ  =  LMSTNA,sˉ  =  rijRclusterQ \;\equiv\; \frac{\bar m}{\bar s}, \qquad \bar m \;=\; \frac{L_{\mathrm{MST}}}{\sqrt{N\,A}}, \qquad \bar s \;=\; \frac{\langle r_{ij}\rangle}{R_{\mathrm{cluster}}}

where LMSTL_{\mathrm{MST}} is the total length of the 2D minimum spanning tree, AA is the convex-hull area, rij\langle r_{ij}\rangle is the mean pairwise separation, and RclusterR_{\mathrm{cluster}} is the maximum distance from the centroid. The two normalisations NA\sqrt{N A} and RclusterR_{\mathrm{cluster}} make QQ dimensionless and NN-independent for self-similar distributions.

CW04 Q regimes.

Regime

QQ value

Geometry

Substructured

Q<0.79Q < 0.79

Fractal, clumpy; e.g. Q0.45Q \approx 0.45 for D=2.0D = 2.0 Goodwin & Whitworth, 2004

Uniform sphere

Q0.79Q \approx 0.79

Reference baseline

Centrally concentrated

Q>0.79Q > 0.79

Power-law radial profile

For dynamical N-body evolution, Q(t)Q(t) traces the rate at which initial substructure is erased by two-body relaxation and dynamical mixing Allison et al., 2009Küpper et al., 2011. Tracking ΔQ/Q\Delta Q / Q as a function of crossing time is therefore a primary diagnostic of cluster violent-relaxation and tidal evolution.

Why MST is hard in JAX

A naive port of the scipy implementation to JAX runs into four fundamental obstructions:

  1. Data-dependent control flow. Both Prim’s and Kruskal’s algorithms iterate until the tree completes, with the iteration count depending on edge values. jax.lax.while_loop is not differentiable, and a fixed-iteration scan requires a worst-case bound on the loop count.

  2. Union-find sequentiality. Cycle detection requires path-compressed disjoint-set operations, which are sequential by construction. JAX’s parallelism cannot be applied.

  3. Discrete edge selection. “Include this edge in the tree” is a binary decision; the gradient of LMSTL_{\mathrm{MST}} with respect to particle positions is a sum over a changing edge set, which yields piecewise-linear gradients with no useful smoothing.

  4. Memory scaling. A naive distance matrix is O(N2)\mathcal{O}(N^2) in memory, exhausting GPU memory at N104N \gtrsim 10^4.

MST algorithms ranked for JAX feasibility.

Algorithm

Parallelisable?

JAX feasibility

Notes

Prim’s

No (sequential priority queue)

Poor

Cannot vmap; data-dependent extract-min

Kruskal’s

No (sequential union-find)

Poor

Same union-find bottleneck

Borůvka’s

Yes (phases parallel)

Partial

O(logN)\mathcal{O}(\log N) phases, each parallel; requires fixed-iteration scan

Dual-tree Borůvka

Yes (Morton-coded)

Complex

Best asymptotic performance, hardest to write

Borůvka’s algorithm is the only structurally JAX-friendly choice: each phase does O(E)\mathcal{O}(E) parallel edge comparisons, components halve each phase, and the total depth is O(logN)\mathcal{O}(\log N). Its weakness is the per-phase union-find, which still has sequential bottlenecks even with path compression replaced by scan-based merges.

The kNN-based approximation

The production path in progenax avoids the MST entirely and approximates QQ from a kk-nearest-neighbour graph:

Qapprox  =  κLNN/NAsˉ,LNN  =  12i=1Ndi,1Q_{\mathrm{approx}} \;=\; \kappa \cdot \frac{L_{\mathrm{NN}} / \sqrt{N\,A}}{\bar s}, \qquad L_{\mathrm{NN}} \;=\; \tfrac{1}{2}\sum_{i=1}^{N} d_{i,1}

where di,1d_{i,1} is each particle’s distance to its single nearest neighbour and κ\kappa is a calibration factor determined empirically against the exact scipy MST on reference distributions. The factor of 1/21/2 deduplicates edges seen from both endpoints.

The physical justification is that for clustered distributions, MST edges are dominated by nearest-neighbour distances within each cluster — the MST connects every point through its cheapest edges, and the cheapest edge from each point is its nearest neighbour modulo inter-cluster bridges. The bridges are the only edges LMSTL_{\mathrm{MST}} captures that LNNL_{\mathrm{NN}} misses, and they enter LMSTL_{\mathrm{MST}} at fixed cost per cluster (one bridge per cluster pair).

The kNN approximation therefore captures the intra-cluster topology exactly and the inter-cluster topology up to a small constant offset folded into κ\kappa. For the relative tracking use case — ΔQ(t)/Q(0)\Delta Q(t)/Q(0) during dynamical evolution — the constant cancels.

Performance comparison: scipy MST vs. JAX kNN, single-snapshot QQ.

Metric

scipy MST

JAX kNN

Speedup

Single snapshot, N=103N = 10^3 (CPU)

50\sim 50 ms

5\sim 5 ms

10×10\times

JIT-compiled (CPU)

n/a

1\sim 1 ms

50×50\times

GPU, N=103N = 10^3

n/a

0.1\sim 0.1 ms

500×500\times

100-snapshot time series

5\sim 5 s (Python loop)

10\sim 10 ms (vmap)

500×500\times

Memory, N=104N = 10^4

O(N2)=800\mathcal{O}(N^2) = 800 MB

O(Nk)=2\mathcal{O}(Nk) = 2 MB

400×400\times

Differentiable

No

Partial (through distances)

Differentiability is “partial” because the choice of nearest neighbour is itself a discrete operation (argmin). The distance through that neighbour is differentiable, but Q/xi\partial Q / \partial \mathbf{x}_i is undefined at the moment ii’s nearest neighbour changes. For HMC use this is acceptable as long as the posterior does not concentrate near a NN-swap surface; in practice this is rare for N30N \gtrsim 30.

Implementation skeleton

The JAX-native implementation lives at progenax.diagnostics.q_jax (planned; current location is progenax.diagnostics.substructure which hosts the scipy reference). The pipeline has three stages:

@jax.jit
def compute_q_approx(positions, k=6, calibration=1.0, Nbins_per_dim=32):
    xy = positions[:, :2]                          # 2D projection per CW04
    grid = build_spatial_grid(xy, Nbins_per_dim)   # Morton-coded bins
    knn = compute_knn_graph(xy, grid, k=k)         # vmap'd kNN
    nn_d = knn.distances[:, 0]                     # Closest neighbour
    L_approx = jnp.sum(nn_d) / 2
    R = jnp.linalg.norm(xy - xy.mean(0), axis=1).max()
    A = jnp.pi * R ** 2                            # Circular hull approx
    s_bar = mean_pairwise_separation(xy, R, max_pairs=10000)
    return calibration * (L_approx / jnp.sqrt(xy.shape[0] * A)) / s_bar

The circular-area approximation AπR2A \approx \pi R^2 replaces the O(NlogN)\mathcal{O}(N \log N) convex-hull computation with O(N)\mathcal{O}(N) work and at most a 5%\sim 5\% bias on mˉ\bar m for non-spherical distributions. The bias is folded into κ\kappa during calibration.

For a time series {Xt}t=1T\{X_t\}_{t=1}^{T}, vectorisation over the time axis is one line:

@jax.jit
def compute_q_approx_timeseries(positions_t, k=6, calibration=1.0):
    return jax.vmap(lambda x: compute_q_approx(x, k=k, calibration=calibration))(positions_t)

This replaces a Python loop over scipy MST calls — the dominant cost in the existing diagnostic pipeline — with a single vmapped device call.

Calibration procedure

κ\kappa is determined by computing both QexactQ_{\mathrm{exact}} (scipy MST) and QapproxQ_{\mathrm{approx}} (kNN) on a reference set of distributions spanning the physically relevant range of substructure: uniform spheres, fractals at D{1.6,2.0,2.4,2.8}D \in \{1.6, 2.0, 2.4, 2.8\} Goodwin & Whitworth, 2004, and centrally-concentrated profiles at p{0.5,1.0,1.5}p \in \{0.5, 1.0, 1.5\}. A least-squares fit QexactκQapproxQ_{\mathrm{exact}} \approx \kappa \cdot Q_{\mathrm{approx}} yields κ\kappa to better than 5% across the range. The calibration is NN-stable for N[100,104]N \in [100, 10^4], which spans the production regime.

When to use the exact Borůvka path

Three use cases require the exact MST rather than the kNN approximation:

  1. Reproducing published Q values. Cross-checking a CW04 Q against Cartwright & Whitworth (2004) Table 1 or Allison et al. (2009) Figure 4 needs the exact algorithm.

  2. Calibrating κ\kappa. The calibration procedure above requires the scipy MST; this is a one-time cost paid offline.

  3. Survey-grade absolute Q. When the absolute value of QQ enters a published quantitative claim, the kNN approximation’s 5%\sim 5\% bias is the limiting systematic.

For these, progenax retains the scipy reference implementation. A JAX-native Borůvka MST is feasible (the parallel-phase structure maps to fixed-iteration scan) but adds substantial code complexity for 5%\sim 5\% improvement in the calibration regime. The current decision is to defer Borůvka until a concrete use case requires it.

Connection to other substructure diagnostics

CW04 Q is one of three substructure metrics implemented in progenax:

Metric

What it measures

Status in progenax

CW04 Q (this chapter)

MST + mean separation

scipy reference + JAX kNN approximation

Azimuthal variation σΣ/Σ\sigma_\Sigma / \langle\Sigma\rangle

Surface-density fluctuation

JAX-native; correlates with fractal dimension via D(1.45σΣ/Σ)/0.46D \approx (1.45 - \sigma_\Sigma/\langle\Sigma\rangle)/0.46 Küpper et al., 2011

Local-density variance σρ/ρ\sigma_\rho / \langle\rho\rangle

Density-PDF dispersion

JAX-native; correlates with QQ but not 1-to-1

Q and the azimuthal-variation metric agree on the trend with substructure but use different absolute scales. The fractal-substructure chapter (Fractal substructure) lays out the conversion table.

References

The CW04 Q definition follows Cartwright & Whitworth (2004). The kNN approximation is original to this work; the parallel Borůvka structure is standard (Cartwright & Whitworth (2004)’s reference list cites the 1926 original). The fractal calibration uses Goodwin & Whitworth (2004); the azimuthal-variation alternative uses Küpper et al. (2011).

References
  1. Cartwright, A., & Whitworth, A. P. (2004). The statistical analysis of star clusters. Monthly Notices of the Royal Astronomical Society, 348, 589–598. 10.1111/j.1365-2966.2004.07360.x
  2. Goodwin, S. P., & Whitworth, A. P. (2004). The dynamical evolution of fractal star clusters: The survival of substructure. Astronomy and Astrophysics, 413, 929–937. 10.1051/0004-6361:20031529
  3. Allison, R. J., Goodwin, S. P., Parker, R. J., Portegies Zwart, S. F., de Grijs, R., & Kouwenhoven, M. B. N. (2009). Using the minimum spanning tree to trace mass segregation. Monthly Notices of the Royal Astronomical Society, 395, 1449–1454. 10.1111/j.1365-2966.2009.14508.x
  4. Küpper, A. H. W., Maschberger, T., Kroupa, P., & Baumgardt, H. (2011). Mass segregation and fractal substructure in young massive clusters. Monthly Notices of the Royal Astronomical Society, 417, 2300–2317. 10.1111/j.1365-2966.2011.19412.x