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.

tracerax: design details

The implementation reference behind the tracerax design: the core types, what callers pass in, the algorithms with their pitfalls, JAX behaviour, tests, dependencies, and a survey of the code that moves in.

Core types

The state is a pytree of arrays; the closure is a protocol; a step moves a state; results are small modules. The names below are tracerax’s, at v0.0.4.

# Shapes: N particles in D = 2 or 3 dimensions; nx × ny surface cells

from typing import Protocol

import equinox as eqx
from jaxtyping import Array, Bool, Float


# today (tracerax.particles)
class ParticleState(eqx.Module):
    """An ensemble of N particles; every field is a pytree leaf."""

    # xₚ, in metres in a local frame, or (longitude, latitude) in degrees
    position: Float[Array, "particle axis"]
    # the step's memory: u'ₚ of a Langevin step, the object's velocity of an inertial one
    velocity: Float[Array, "particle axis"]
    # mₚ in kg; a release of rate Q over T gives mₚ = Q T / N
    mass: Float[Array, " particle"]
    # when it is released, in seconds from the run's epoch
    release_time: Float[Array, " particle"]
    # False after leaving the domain
    active: Bool[Array, " particle"]


# today (tracerax.particles)
class ParticleStep(Protocol):
    """What moves a state: each particle over its own duration δ ≥ 0."""

    def noise_shape(self, state): ...
    def __call__(self, state, start, duration, direction, noise): ...


# today (tracerax.advect)
class TurbulenceModel(Protocol):
    """σ(z) and τ_L(z), the closure a Langevin step reads."""

    def at(
        self, height: Float[Array, " particle"]
    ) -> tuple[Float[Array, "particle 3"], Float[Array, "particle 3"]]: ...


# today (tracerax.advect)
class Walls(eqx.Module):
    """Reflecting walls in z: the ground and, optionally, a top."""

    bottom: float = 0.0
    top: float | None = None


# today (tracerax.footprint)
class Footprint(eqx.Module):
    """Fⱼ in s m² kg⁻¹: sensitivity of one receptor to a surface flux in j."""

    sensitivity: Float[Array, "x y"]
    residence: Float[Array, "x y"]
TypeHoldsInvariants
ParticleStatepositions, memories, masses, release times, active flagsevery leaf has the same N; inactive particles keep finite values and are masked, never dropped; mass ≥ 0
ParticleStepa velocity, a closure, parametersa particle with duration 0 is unchanged bit for bit; releases, masks, domains and noise are the loop’s
TurbulenceModela closure’s σ(z) and τ_L(z)σ > 0 and τ_L > 0; at is differentiable in z, because the drift needs ∂σ_w²/∂z, and finite at z = 0
Wallsthe wall heightsbottom < top
Cellsincreasing edges per axis, in the order of the position columnsa cell is [e_i, e_{i+1}); the last edge is outside
Residence, RegionTimeaccumulators: seconds per cell, and per particle and region∑ⱼ Rⱼ ≤ N T, with equality when no particle leaves the cells
Footprinta sensitivity map and the particle-seconds under ita receptor value is y = ∑ⱼ Fⱼ qⱼ for a surface flux q in kg m⁻² s⁻¹

The cells keep plumax’s (x, y, z) axis order so results compare directly with plumax’s; xrops relabels them when it wraps the output.

Types to adhere to

Callers pass three things in: a wind, a turbulence closure, and cell edges.

# Shapes: N particles

from plumax.lagrangian import HannaTurbulence
from tracerax.velocity import GriddedVelocity, cgrid_grids

# today (tracerax)
# u at (xᵢ + Δx/2, yⱼ), v at (xᵢ, yⱼ + Δy/2), w at the T points
wind = GriddedVelocity.fit(cgrid_grids(times, x, y, z), (u, v, w))
wind(t, position)  # (N, 3) → (N, 3)

# today (plumax)
# σ(z), τ_L(z) from Hanna (1982) boundary-layer scaling
turbulence = HannaTurbulence(u_star=0.4, pbl_height=1000.0, obukhov_length=-50.0)

Algorithms

Deterministic advection

Each particle follows the resolved wind:

dxpdt=u(xp,t)\frac{d x_p}{dt} = u(x_p, t)
  1. deterministic wraps the velocity as a diffrax term over the (N, D) position array, so the ensemble is one state, and solves it in equal steps with an integrix or diffrax solver. Each particle has its own clock, so a release on a step time is exact.

  2. Deterministic is one explicit Runge–Kutta step, unrolled from the solver’s tableau, for the loop. There a release inside a step is exact too, and forward and reverse mode both work.

  3. Save at the requested times, or only the final state.

  4. Deactivate particles that leave the domain: they keep their last position and active = False.

Cost: K steps × s stages × one wind evaluation of N points. Pitfalls: a linearly interpolated wind is only continuous, not smooth, so use fixed steps or a cubic scheme there. A particle outside the wind’s grid is clamped by default. A diffrax right-hand side that switches on at a release is read by the last stage of the step before, so the release is a control with an increment per particle.

The sphere

Positions are (longitude, latitude) in degrees and velocities eastward and northward. With r the unit vector of a position and R the radius:

drdt=ueλ+veφR\frac{d r}{dt} = \frac{u e_\lambda + v e_\varphi}{R}

and r is divided by its norm after each step. Solid-body rotation about an axis tilted by 0.4 rad, one turn in 100 RK4 steps, returns to 1.9 m on a path up to 55.8° and to 0.003 m on one up to 88.8°, where steps in longitude and latitude were off by 1.3 km. Pitfalls: a longitude comes back in [−180°, 180°), so distances along a path are great-circle ones; within √ε of a pole the velocity is read at that distance from it, because a derivative through a longitude is the difference of two numbers of size 1/ε; in float32 a step’s rounding may have the same sign at every step, so a displacement per step of a few metres is lost.

Inertial particles

The Maxey–Riley equation for the surface ocean (Beron-Vera, Olascoaga and Miron, 2019) is linear in the object’s velocity once the flow is frozen over a step, so the step is exact in the drag and the rotation, with the flow evaluated at the middle. In a cellular flow of 50 km and 0.5 m s⁻¹ the error after a day is below 1.6 m at steps of 900 s, for response times from a minute to an hour, and falls about four times per halving. The slow manifold is a velocity without memory, off by order τ².

The Langevin step, well mixed, with reflection

For Gaussian turbulence with σ(z) and τ_L(z) per component, the velocity fluctuation is an Ornstein–Uhlenbeck process plus, for the vertical component, Thomson’s (1987) well-mixed drift. The linear part is integrated with its exact transition over a step Δt, with ξ a standard normal draw:

un+1′=e−Δt/τLun′+σ1−e−2Δt/τLξu'_{n+1} = e^{-\Delta t / \tau_L} u'_n + \sigma \sqrt{1 - e^{-2 \Delta t / \tau_L}} \xi

The vertical drift is added with an Euler step, and the position follows the mean wind plus the fluctuation:

uw,n+1′←uw,n+1′+12(1+uw,n+1′2σw2)∂σw2∂zΔtu'_{w,n+1} \leftarrow u'_{w,n+1} + \frac{1}{2} \left( 1 + \frac{u'^2_{w,n+1}}{\sigma_w^2} \right) \frac{\partial \sigma_w^2}{\partial z} \Delta t
xn+1=xn+(u(xn,tn)+un+1′)Δtx_{n+1} = x_n + (u(x_n, t_n) + u'_{n+1}) \Delta t
  1. Read σ, τ_L from the closure at each particle’s height; floor σ at a small positive value.

  2. Draw ξ from this step’s key and apply the exact OU transition to all three components.

  3. Compute ∂σ_w²/∂z by forward mode of the closure, and add the drift to u’_w.

  4. Move the particles.

  5. Reflect by a triangle-wave fold of period 2h, with u’_w changing sign when the number of folds is odd. One reflection per wall is not enough: with a 50 m layer, σ = 1.5 m s⁻¹ and τ = 100 s, plumax’s step leaves 6.8 % of the particles outside the layer at Δt = 30 s and 39 % at 60 s (plumax#392); the fold leaves none.

  6. Shorten the last step so the run ends exactly at the horizon (plumax’s step_durations).

Cost: O(N) per step, plus one gradient of σ_w² per particle. Pitfalls:

Binning by scatter-add

With edges e₀ < … < eₙ per axis, a particle’s cell index is i = max{j : eⱼ ≤ x}, kept when 0 ≤ i < n. The indices flatten to one, and the transpose of a functax stencil accumulates the weight:

Rj←Rj+∑pΔtk1[xp(tk)∈j]R_j \leftarrow R_j + \sum_p \Delta t_k \mathbb{1}[x_p(t_k) \in j]

For a continuous source of rate Q released as N particles at t = 0 in a steady flow, the steady concentration is cⱼ = Q Rⱼ / (N Vⱼ), with Vⱼ the cell volume. Cost: O(N) per step with a single .at[].add. Pitfalls: a histogram is piecewise constant in the positions, so its gradient with respect to them is zero almost everywhere. Gradients with respect to the wind or the closure’s parameters need kind="linear", cloud-in-cell weights, which spread each particle over the 2ᵈ nearest cells. functax’s Binning alone does not do either: the nearest one ignores an axis’s explicit edges, so stretched cells get the wrong samples (functax#168), and the linear one drops what falls between an end centre and its wall, which is the ground of a footprint (functax#169). tracerax locates the cells itself, and folds ghost cells back, until they close; a particle inside the edges then deposits its whole weight.

Backward footprints

Particles released at a receptor and integrated backward in time give the receptor’s sensitivity to a surface flux. With h_s = f h the surface-layer depth and ρ the air density:

Fj=1Nρhs∑p∑kΔtk1[xp(tk)∈j,zp(tk)<hs]F_j = \frac{1}{N \rho h_s} \sum_p \sum_k \Delta t_k \mathbb{1}[x_p(t_k) \in j, z_p(t_k) < h_s]
  1. Run the loop with a negative duration from the receptor time; the Langevin step takes −u.

  2. The loop reverses the order of the step durations, so the partial step comes first, and the wind is read at the physical start of each forward interval.

  3. Run the Langevin step; accumulate residence of the particles below h_s per surface cell.

  4. Divide by N ρ h_s. There is no division by cell area: F pairs with a flux in kg m⁻² s⁻¹.

Pitfall: reusing the forward integrator with the wind reversed is exact for the OU part when the turbulence is stationary, because that process is time-reversible. In inhomogeneous turbulence the backward-time drift is not the forward one with the wind reversed Flesch et al., 1995; so a footprint in inhomogeneous turbulence is approximate, as plumax’s is. In homogeneous turbulence the reciprocity test of Wave 2 agrees to its sampling error.

Finite-time Lyapunov exponents

With Φ the flow map of the deterministic advection from t₀ to t₁ and ∇Φ its Jacobian at a seed x₀:

C(x0)=∇Φ(x0)⊤∇Φ(x0)C(x_0) = \nabla\Phi(x_0)^\top \nabla\Phi(x_0)
Λ(x0)=1∣t1−t0∣ln⁡λmax⁡(C(x0))\Lambda(x_0) = \frac{1}{|t_1 - t_0|} \ln \sqrt{\lambda_{\max}(C(x_0))}
  1. Solve every seed’s path once, with one tangent per position column pushed through the solve: a seed’s velocity depends on its own position only, so the seeds share them. The solve needs diffrax.ForwardMode(), because diffrax’s default adjoint has no forward mode (integrix.march.run does too).

  2. Split the duration in windows, multiply their Jacobians, and divide by the largest entry after each, accumulating the logarithm, so that nothing overflows.

  3. Form C with einx and take the largest eigenvalue with jnp.linalg.eigvalsh.

On the sphere the Jacobian is taken in the local east–north frames at both ends. Cost: one solve with d tangents, against 2d extra trajectories per seed for central differences. Pitfalls: a linear read’s gradient jumps at cell faces, so the ridges depend on the scheme; FTLE is defined for the deterministic flow only: no turbulence draw.

Residence time and connectivity

With regions labelled on the bins, residence in region A is τ_A = ∑ₖ Δtₖ 1[xₚ(tₖ) ∈ A] per particle, and the connectivity from release region i to region j is the fraction of i’s particles found in j at the end (or ever, for a visiting matrix):

Cij=1Ni∑p∈i1[xp(t1)∈j]C_{ij} = \frac{1}{N_i} \sum_{p \in i} \mathbb{1}[x_p(t_1) \in j]

Regions are an integer label per cell of a Cells, with −1 for none. RegionTime sums per particle and region inside the loop, right to one step per crossing, and connectivity is a one-hot contraction over particles at the end; visited_connectivity counts every region a particle has spent time in.

Dispersion and skill

Absolute and pair dispersion are mean squared distances, along great circles on the sphere. The normalised cumulative separation of a trajectory (Liu and Weisberg, 2011) is the sum of its separations from an observed one over the sum of the observed path’s lengths; its gradient is finite where the two coincide, so it is a loss. Missing observations are NaN, left out of both sums, and the length bridges the gap.

JAX compatibility

FunctionjitvmapgradNotes
deterministic, deterministic_sphereyesyes, over ensembles or seedsyes, through diffrax (wind parameters, initial positions)Forward mode needs diffrax.ForwardMode()
Deterministic, DeterministicSphere, Inertialyesyesyes, both modesUnrolled stages, with a duration per particle
Langevin, RandomDisplacementyesyesyes, with respect to the closure’s parameters (pathwise, fixed noise)Walls are a fold, piecewise linear
integrateyes, step count staticyes, over keys for independent ensemblesyes, reverse mode through the scan, checkpointed or truncatedThe number of steps comes from the duration and the step on the host
deposit, Residenceyes, edges as arraysyeszero for "nearest"; smooth for "linear" between cell centresOut-of-range particles masked, not dropped, so shapes stay static
surfaceyesyes, over receptors, times and keysin the wind, with kind="linear"Nothing flows through the step of the surface layer, so the gradient in the receptor’s height or the closure is not the footprint’s
ftleyesyes, over seedswith adjoint=diffrax.DirectAdjoint()One solve carries the tangents
connectivityyesyeszero with respect to positionsRegion labels are integer arrays
dispersion, separation, skillyesyesyes, finite where two points coincideMissing positions are NaN

Keys: one key per run, split up front into one key per step, or the noise itself, one array per step, for antithetic pairs or common random numbers. A step takes its noise as an argument; nothing reads numpy.random.

Scan carry: (ParticleState, accumulator), where the accumulator is the residence array of the cells, or any Accumulator. Saving trajectories adds the position every few steps as a scan output.

Memory: O(N + bins) for an accumulating run; O(K N) when the trajectory is saved, which is the usual way a long run runs out of memory. Reverse-mode gradients through a long scan store every step’s carry; use integrix.adjoint.Checkpointed(every=k), which stores O(K/k + k) of them, or forward mode when the parameters are few.

Precision: positions in metres far from the origin lose resolution in float32 (a 1 cm step at 10⁶ m is below float32’s resolution). Run in a local frame with the origin near the source (xrops’ LocalFrame), or in float64. Times have the same limit: the loop raises when a concrete time is too coarse for the step.

Testing

Var[z(t)]=2σ2τL(t−τL(1−e−t/τL))\mathrm{Var}[z(t)] = 2 \sigma^2 \tau_L \left( t - \tau_L (1 - e^{-t / \tau_L}) \right)

External dependencies

LibraryUsed forRequired or optional
JAXarrays, lax.scan, PRNG, vmap, grad, jvprequired
Equinoxthe state, the steps, the velocities and the results as modulesrequired
einx, jaxtypingcontractions, broadcasts and reductions; annotationsrequired
functax (functax[jax])reading a gridded wind at particles, the cells’ axes and volumes, stencil transposes, unit vectors and east–north framesrequired
integrix, and diffraxRunge–Kutta solvers, checkpointed and truncated scansrequired
geophysixthe sphere’s radius and great-circle distances; it brings pipekit-arrayrequired, since Wave 3
gridaxstaggered coordinates and masks, for an adapteroptional ([gridax])
plumaxthe oracle’s stored valuesnone: never imported, not even by a test

functax and integrix are pinned to tags and move together, as integrix fixes functax’s tag; geophysix and gridax too, as gridax fixes geophysix’s.

Where it stands

tracerax v0.0.4 holds Waves 0 to 3. The code that moves in is plumax’s lagrangian subpackage at plumax 96449d2, under lagrangian/_src/ since plumax#306, and plumax still has its own copy until Wave 4:

FileWhat it holdsMoves to
particles.pyParticleState (position and velocity only), the TurbulenceModel protocol, langevin_step, n_steps_for_horizon, step_durations, integrate_particles, uniform_wind, wind_from_speed_directiontracerax.particles, tracerax.advect, tracerax.velocity; wind_from_speed_direction stays
wind_interp.pyGriddedWind and its helpers; the functions that build one from meteorologytracerax.velocity.GriddedVelocity; the builders stay
concentration.pybin_positions, _accumulate_residence, simulate_lagrangian (returns an xarray Dataset)tracerax.bin; simulate_lagrangian stays, on the loop and Residence
footprint.pycompute_footprint and its helpers; returns NumPy arraystracerax.footprint.surface, behind a thin call
emulator.py, met_ensemble.pyFootprintSimulator, ensembles of meteorologystay; the simulator runs surface under vmap
turbulence.pyHomogeneousTurbulence, hanna_profiles, HannaTurbulence (with z_floor = 0.1)stays, as eqx.Modules
inversion.pyGaussianPosterior, matern32_covariance, observation_covariancestays

What tracerax added rather than carried over: releases over time and inside a step, walls that fold any number of times, deposits that keep the mass at walls, random displacement, the sphere, inertial particles, FTLE, residence times per region, connectivity, dispersion and trajectory skill.

Neighbours checked and left alone: integrix.march.semi_lagrangian_step (field in, field out at departure points) is Eulerian transport and stays there; xrops has metrics/_src/lagrangian.py, a stub reserved for a later view, and nothing to move.

References
  1. Hanna, S. R. (1982). Applications in air pollution modeling. In F. T. M. Nieuwstadt & H. van Dop (Eds.), Atmospheric Turbulence and Air Pollution Modelling (pp. 275–310). Reidel.
  2. Wilson, J. D., & Flesch, T. K. (1993). Flow boundaries in random-flight dispersion models: enforcing the well-mixed condition. Journal of Applied Meteorology, 32, 1695–1707.
  3. Flesch, T. K., Wilson, J. D., & Yee, E. (1995). Backward-time Lagrangian stochastic dispersion models and their application to estimate gaseous emissions. Journal of Applied Meteorology, 34, 1320–1332.
  4. Taylor, G. I. (1921). Diffusion by continuous movements. Proceedings of the London Mathematical Society, s2-20(1), 196–212.
  5. Shadden, S. C., Lekien, F., & Marsden, J. E. (2005). Definition and properties of Lagrangian coherent structures from finite-time Lyapunov exponents in two-dimensional aperiodic flows. Physica D, 212, 271–304.