Kernel density estimation

The KDE interface is experimental and may change in future versions.

jz.kde.kde estimates a density from particles in two or three dimensions, using normalized kernels with fixed or adaptive support radii. It evaluates at the particles themselves or at separate query points, and supports gradients. It accumulates contributions without storing full neighbour lists, which can notably reduce memory usage for applications that only need the density.

A first density estimate

import jax
import jax.numpy as jnp
import jztree as jz
from jztree.kde import KNNBandwidth

pos = jax.random.uniform(jax.random.key(0), (10000, 3))
mass = jnp.full((len(pos),), 1.0 / len(pos), dtype=pos.dtype)

# Fixed support radius, with periodic boundaries on the unit box.
rho = jz.kde.kde.jit(pos, bandwidth=0.1, weights=mass, boxsize=1.0)

# Adaptive support radius: distance to the 64th source neighbour.
rho_adaptive = jz.kde.kde.jit(
    pos, bandwidth=KNNBandwidth(k=64), weights=mass, boxsize=1.0,
)

Both results have shape (10000,), in input order. The default kernel is cubic_spline. Omit boxsize for nonperiodic distances. The same interface accepts positions with shape (N, 2) for a two-dimensional density.

Weights default to one, giving number density. Particle masses give mass density; weights summing to one define a probability-density estimator with source-owned kernels. The function does not normalize the weights for you.

By default, exclude_self=True omits each particle’s own contribution. Self still counts toward k when selecting the adaptive bandwidth. Distinct particles at identical coordinates are not excluded. Set exclude_self=False to include the own contribution. Support radii must be positive and finite; coincident neighbours that give a zero kth radius are rejected.

Where the bandwidth belongs

bandwidth is the kernel’s support radius, supplied as a scalar, a radius array, or KNNBandwidth(k=...). The bandwidth_at argument determines ownership:

  • "source" (the default): each source spreads its weight with its own radius. Each kernel has unit integral, preserving its source’s integrated weight. This is useful when treating particles as an extended density distribution.

  • "query": each evaluation point collects source contributions with its own radius. This is useful for estimates with locally chosen smoothing scales, but spatially varying query radii need not preserve integrated weight.

A scalar radius gives the same estimator in both modes. Radius arrays must have one entry per owning point. Adaptive radii always measure distances to the sources, whether the owning points are sources or queries.

query = jax.random.uniform(jax.random.key(1), (1000, 3))
rho_query = jz.kde.kde.jit(
    pos, bandwidth=KNNBandwidth(k=64), weights=mass, query=query,
    bandwidth_at="query", exclude_self=False, boxsize=1.0,
)

source_radii = jnp.full((len(pos),), 0.1, dtype=pos.dtype)
rho_source = jz.kde.kde.jit(
    pos, bandwidth=source_radii, weights=mass, query=query,
    bandwidth_at="source", exclude_self=False, boxsize=1.0,
)

These return one value per query point. Explicit query points require exclude_self=False: there is no identity mapping to determine which source is a query’s own particle, even if their coordinates match.

Kernels

Available kernels are tophat, linear, quadratic, cubic_spline and gaussian, normalized in the input dimension. The Gaussian is truncated at bandwidth, with standard deviation bandwidth / cutoff_sigma (default cutoff_sigma=3.0), and normalized over that disk or sphere.

rho_gaussian = jz.kde.kde.jit(
    pos, bandwidth=0.1, weights=mass, kernel="gaussian",
    cutoff_sigma=3.0, boxsize=1.0,
)

Radius searches include boundary ties, while kNN reductions retain the search’s selection of k neighbours. Consequently, substituting a measured kth radius for KNNBandwidth need not give identical results when distances tie.

Gradients

Use the ordinary function inside a larger JAX calculation. Reverse-mode differentiation supports positions, weights and supplied radii, including the kth-distance contribution for adaptive bandwidths:

@jax.jit
def density_loss_and_grad(x, w):
    def loss(x, w):
        rho = jz.kde.kde(x, KNNBandwidth(k=64), weights=w, boxsize=1.0)
        return jnp.mean(rho**2)
    return jax.value_and_grad(loss, argnums=(0, 1))(x, w)

loss, (grad_pos, grad_mass) = density_loss_and_grad(pos, mass)

Neighbour membership and periodic image choices are held fixed. Derivatives do not describe jumps at neighbour-selection changes or sharp kernel cutoffs. Forward-mode differentiation, higher derivatives and kernel-parameter gradients such as those of cutoff_sigma are not supported.

Execution and custom reductions

cfg controls tree construction and allocations, not the estimator. KDE uses KNNConfig by default for adaptive kNN bandwidths and QueryBallConfig for supplied radii. No packed neighbour-output buffer is needed, so alloc_fac_neighbours is ignored. See error handling for recovering from insufficient allocations.

Distributed execution uses .smap(mesh, jit=True) and the padded particle layout in the multi-GPU guide. Weight arrays follow the sources; radius arrays follow their owning population. With .smap, supply scalar bandwidths as one scalar per device, or close over a shared scalar inside a composed shard map.

For another application that only needs a sum over neighbours, the custom reductions interface can similarly avoid large neighbour-list outputs. It supports both kNN and radius searches; implementing a new reduction requires CUDA code and a backend rebuild. The built-in KDE interface above requires no custom CUDA implementation. See the API reference for the complete call signature.