Quickstart

Neighbours within a radius

query_ball finds all sources within a scalar or per-query radius. For a small example using subsets of the positions above:

sources = pos[:10000]
queries = posq[:1000]
neighbours = jz.knn.query_ball.jit(sources, radius=0.05, part_query=queries)

# Extract the first query's source indices outside jit.
start, stop = int(neighbours.offsets[0]), int(neighbours.offsets[1])
ids = neighbours.indices[start:stop]

Results include neighbours on the boundary and are not sorted by distance. The packed output has a fixed capacity; insufficient capacity raises an error rather than truncating a query. See the API reference for offsets, masks, capacity settings and use inside JIT.

If your application only needs to accumulate neighbour contributions, custom reductions can notably reduce memory usage by avoiding full neighbour-list outputs, for both kNN and radius queries.

Kernel density estimation

The experimental KDE interface provides built-in density estimates without full neighbour lists:

from jztree.kde import KNNBandwidth

rho = jz.kde.kde.jit(pos[:10000], bandwidth=KNNBandwidth(k=64))

This returns number density at each source, excluding its own contribution by default. The KDE guide explains weights, bandwidth ownership, separate query points and gradients. Its interface may change in future versions.

Compilation and timing

As usual in JAX, compile functions to get good performance. The .jit helper compiles each entry point with its required static arguments. Use the ordinary function when composing a larger JAX calculation.

Of course you may instead use your own jax.jit, for example:

import time

@jax.jit
def myneighbours(seed):
    pos = jax.random.uniform(jax.random.key(seed), shape=(int(1e7), 3))
    return jz.knn.knn(pos, k=8)

t0 = time.perf_counter()
rnn, inn = jax.block_until_ready(myneighbours(seed=0))
t1 = time.perf_counter()
rnn2, inn2 = jax.block_until_ready(myneighbours(seed=1))
t2 = time.perf_counter()

print(f"Dt1 = {t1-t0:.2f}s, Dt2 = {t2-t1:.2f}s")
Dt1 = 1.50s, Dt2 = 0.14s

The first call takes extra time to compile. Subsequent calls are much faster! These timings are from my laptop.

Let’s verify by comparing to scipy’s KDTree (you may need to install it with pip install scipy)

from scipy.spatial import KDTree
import numpy as np

pos = jax.random.uniform(jax.random.key(0), shape=(int(1e7), 3))
jax.block_until_ready(jz.knn.knn.jit(pos, k=8)) # warm up

t0 = time.perf_counter()
rnn, inn = jax.block_until_ready(jz.knn.knn.jit(pos, k=8))
t1 = time.perf_counter()
kdtree = KDTree(np.array(pos))
rnn2, inn2 = kdtree.query(pos, k=8, workers=8)
t2 = time.perf_counter()

print("All radii identical", np.allclose(rnn, rnn2))
print("Fraction of indices different:", np.mean(inn != inn2))
print("Radius collision fraction:", np.mean(rnn[:,1:] == rnn[:,:-1]))
print(f"jz-tree: {t1-t0:.2f}s, scipy: {t2-t1:.2f}s")
All radii identical True
Fraction of indices different: 1.875e-07
Radius collision fraction: 4.4285713e-07
jz-tree: 0.13s, scipy: 16.14s

Quite a speed-up!

Note that the results agree perfectly within the margin of error: the neighbour radii agree within np.allclose tolerances, but a very small number of indices differ. This is because for 10^7 particles, we already get a notable number of floating-point collisions (where two or more radii in a neighbour list are identical at machine precision). scipy and jz-tree have different tie-breaking behaviour. Feel free to verify that for each differing index, there is a second particle at the same radius.

Friends-of-friends groups

Next, let’s find some friends-of-friends clusters. For convenience, the output from a 2D cosmological N-body simulation (run with DISCO-DJ) is included in the repository. It has $128^2$ particles with a boxsize of 100.

from jztree_utils.ics import cosmo_2d_sample

pos = cosmo_2d_sample()
print(pos.shape)
mean_sep = 100./128

posz, igroup = jz.fof.fof_labels.jit(pos, rlink=0.2*mean_sep, boxsize=100.0)

print(posz.shape, igroup.shape)
print(igroup[0:40])
(16384, 2)
(16384, 2) (16384,)
[ 0  1  2  3  4  5  6  7  6  9 10 11 12 13 14 15 16 16 16 16 20 21 22 23
 24 16 16 27 27 23 30 27 27 33 34 35 35 35 38 39]

Note that jztree.fof.fof_labels outputs positions and group labels in z-order. For convience, the single-GPU version shown here also supports restoring the input ordering (output_order="input"). However, this is not really a feasible option in the multi-GPU scenario where it is best to continue working with the re-ordered particles.

The igroup labels point towards the first particle that is part of the same group. Many particles just point to themselves which means that they are a single-particle group.

Let’s visualize this data:

posz, igroup = jz.fof.fof_labels.jit(pos, rlink=0.2*100./128, boxsize=100.)

count = jnp.zeros_like(igroup).at[igroup].add(1)

import matplotlib.pyplot as plt
plt.scatter(posz[:,0], posz[:,1], marker=".", alpha=0.2, color="black")

sel = count[igroup] > 10
color = plt.get_cmap("rainbow")((igroup[sel] % 133) / 133)
plt.scatter(posz[sel,0], posz[sel,1], c=color, marker=".", alpha=0.2);

png

Here we have drawn only coloured particles that are in a group with more than 10 particles. The operation

count = jnp.zeros_like(igroup).at[igroup].add(1)

counts the particles in each group. We’ll see more sophisticated catalogue reductions later.

We may again wish to test our output against another library. Let’s setup a larger problem in three dimensions. (Note: By default, jz-tree supports FoF in 2 and 3 dimensions, but if you need a different dimension, you can easily add it, by recompiling from sources).

Running the following requires installing the single-CPU FoF library hfof:

import hfof

pos = jax.random.uniform(jax.random.key(0), shape=(int(1e7), 3))
mean_sep = np.cbrt(1./len(pos))

jax.block_until_ready(jz.fof.fof_labels.jit(pos, rlink=0.7*mean_sep, boxsize=1.0)) # warm up

t0 = time.perf_counter()
posz, igroup = jax.block_until_ready(
    jz.fof.fof_labels.jit(pos, rlink=0.7*mean_sep, boxsize=1.0))
t1 = time.perf_counter()
ihfof = hfof.fof(np.array(posz), 0.7*mean_sep, boxsize=1.)
t2 = time.perf_counter()

print("jz-tree:", igroup[0:20])
print("hfof:", ihfof[0:20])
print("labels consistent:", jz.fof.fof_is_superset(igroup, ihfof), jz.fof.fof_is_superset(ihfof, igroup))
print(f"Dt1 = {t1-t0:.2f}s, Dt2 = {t2-t1:.2f}s")
Loading libhfof - C functions for FoF calculations /home/jens/.virtualenvs/uvjax/lib/python3.12/site-packages/hfof/../build/libhfof.cpython-312-x86_64-linux-gnu.so
jz-tree: [ 0  1  0  0  4  5  6  6  8  8  8 11 11  1 14 14 14 17 18 19]
hfof: [  23968     141   23968   23968       0   23846   23847   23847   23969
   23969   23969       1       1     141     142     142     142 4267019
 4267018 4267020]
labels consistent: True True
Dt1 = 0.10s, Dt2 = 2.60s

Again, a significant speed-up – though the performance of hfof is also quite impressive, given the limited hardware used!

Note that the labels differ, but they represent the same groups. This is verified by calling the jz.fof.fof_is_superset function in both directions.

Friends-of-friends catalogues

Usually FoF algorithms are run as a preparation step to create group catalogues that summarize FoF groups. This is also supported in jz-tree. To allow a convenient group-wise access to the particles they are brought into group order. To simplify visualization, we again use the cosmo 2D dataset:

pos = cosmo_2d_sample()

part = jz.data.ParticleData(
    pos = pos,
    mass = 1., # mass may be a constant or an array with number of particles
    vel = jax.random.normal(jax.random.key(0), pos.shape)
)

cfg = jz.config.FofConfig()
cfg.catalogue.npart_min = 10
mean_sep = 100./128
partf, cata = jz.fof.fof_and_catalogue.jit(part, rlink=0.2*mean_sep, boxsize=100., cfg=cfg)

print("catalogue num, shape:", cata.ngroups, cata.mass.shape)

cata = jz.data.squeeze_catalogue(cata)

print("squeezed catalogue num, shape:", cata.ngroups, cata.mass.shape)

plt.scatter(partf.pos[:,0], partf.pos[:,1], marker=".", alpha=0.2, color="black")

color = plt.get_cmap("viridis")(np.log10(cata.mass) / 2.5)
plt.scatter(cata.com_pos[:,0], cata.com_pos[:,1], c = color,
            s=200.*cata.com_inertia_radius**2, marker="o", alpha=0.8)

imax = np.argmax(cata.count)
pmax = partf.pos[cata.offset[imax]: cata.offset[imax]+cata.count[imax]]
plt.scatter(pmax[:,0], pmax[:,1], marker=".", color="red", alpha=0.1);
catalogue num, shape: 164 (1639,)
squeezed catalogue num, shape: 164 (164,)

png

This example shows a few relevant details:

  • To be able to calculate group properties like masses or velocities, we should input a particle data structure with those fields.

  • We create and pass a config object to configure the minimal number of particles for groups (default is 20). Many functions in jz-tree have such a config interface for defining lower-level details.

  • jztree.fof.fof_and_catalogue() returns particles in group-prder and an instance of the dataclass jztree.data.FofCatalogue.

  • The returned catalogue is larger than the actual number of groups. This is necessary, because the number of groups is data-dependent, but allocations need to be known at jit-compile time. jz-tree uses a worst-case estimate of the allocation size.

  • The function jztree.data.squeeze_catalogue() can be used to squeeze the catalogue. (This cannot be done inside of a jitted context.)

  • We plot the haloes centers, with size given by their inertia radius and coloured by their mass. You can find all available fields (here)

  • Particles can be accessed per group as a continuous range cata.offset[gid]: cata.offset[gid]+cata.count[gid]. Here, we have plotted the particles of the most massive halo in red.

Error handling

If you are going far enough away from the scenarios that we have tested, you may sometimes encounter error messages like the following:

import jax
import jztree as jz

pos = jax.random.uniform(jax.random.key(0), shape=(50000, 3))
rnn, inn = jz.knn.knn.jit(pos, k=2000)
rnn.block_until_ready()
JaxRuntimeError: FAILED_PRECONDITION: Check failed (trace-time call chain, most recent call last):
  File "<ipython-input>", line 5, in <module>
    rnn, inn = jz.knn.knn.jit(pos, k=2000)
  File ".../jztree/knn.py", line 334, in knn
    ilist = _knn_dual_walk(th, k, boxsize=boxsize, alloc_fac_ilist=cfg.alloc_fac_ilist,
  File ".../jztree/knn.py", line 213, in _knn_dual_walk
    ilist, counts = jax.lax.fori_loop(0, nlevels, handle_level,
  File ".../jztree/knn.py", line 201, in handle_level
    ilist = _knn_node2node_ilist(ilist, parent_spl, node_data, k=k, boxsize=boxsize,
  File ".../jztree/knn.py", line 112, in _knn_node2node_ilist
    ispl = ispl + raise_if(ispl[-1] > ilist.size(),
CheckFailed: The interaction list allocation is too small (need: 633252, have: 533760)
Fix: increase alloc_fac_ilist by a factor >= 1.19 (jz.apply_fix(cfg, error))
[jztree-check 4: 633252, 533760, 1.18639839] [executable_name='jit_knn']

For returning 2000 neighbours a much larger region needs to be checked than in typical scenarios, so the code needs a larger allocation for the interaction list. As mentioned earlier, jax’s jit compilation requires that allocations are predicted in advance. jz-tree tries its best to provide robust defaults, but it is of course not possible to provide a good estimate for every possible scenario.

The computation was stopped before anything could overflow. The message shows where the check was traced and which configuration value to increase. You can do this yourself, or let jz.run_with_fixes retry with increased allocations until the computation succeeds:

(rnn, inn), cfg = jz.run_with_fixes(
    lambda cfg: jz.knn.knn.jit(pos, k=2000, cfg=cfg), jz.config.KNNConfig()
)
print(rnn.shape, inn.shape, cfg.alloc_fac_ilist)

Output format (schematic; capacities depend on the input and configuration):

jztree: cfg.alloc_fac_ilist: <old value> -> <new value> (need <required>, have <capacity>)
(50000, 2000) (50000, 2000) <new value>

The error handling guide explains how to catch such errors, fix configurations automatically and what changes for multi-GPU runs.

JIT, distributed execution, and differentiation

Many entry points provide .jit(...) and .smap(mesh, jit=True)(...) helpers. For example, jztree.knn.knn.jit(pos, k=8) compiles a neighbour search with k treated as static. Use the ordinary function inside a larger JAX calculation. See the API reference for transformation limits and available helpers, and the multi-GPU guide for distributed particle layouts.

For gradients of neighbour distances, request result="drad". This differentiates distances with the selected neighbours held fixed, not the neighbour-selection decisions. FoF labels and tree topology are discrete.