API Reference

The API of jz-tree. Only functions that may be relevant for interfacing and calling the code are listed. For developers we recommend to directly consider the source code.

JAX transformations and convenience methods

Use function.jit(...) where provided to compile with the documented static arguments. function.smap(mesh, jit=True)(...) runs a distributed calculation using the expanding particle layout described in the Advanced Guide: Multi-GPU. These helpers keep the ordinary Python function available for composition. Structural config fields, k, boxsize and FoF linking lengths must be known while tracing; changing them may require recompilation. Regularization thresholds are dynamic values; tree topology remains discrete.

Configs have a nested plain-text representation. Use cfg.print() for optional Rich colours and GitHub source links, or cfg.print(links="local") for local file links when supported by your viewer. links=None disables links. Source links use the checkout remote and commit, or wheel build metadata; no network verification is performed. Missing metadata leaves class names unlinked.

Autodiff support depends on the operation. zsort provides a reverse-mode rule that maps gradients back through the selected permutation; sorting decisions and neighbour/group membership are discrete. For kNN, use result="drad" to recompute differentiable distances for the selected neighbours, or result="drmax" for only the kth distance. The ordinary "rad" output comes from the CUDA search and is not the differentiable-distance path. Periodic distances use the minimum image; gradients are undefined at image boundaries and can be undefined at zero distance. FoF labels and tree topology are not differentiable. Do not assume that a reverse-mode rule also supports forward-mode jax.jvp.

Removing padding can produce data-dependent shapes. Helpers such as squeeze_catalogue need an explicit static output size when used under JIT; otherwise use them outside compiled calculations.

jztree.config

This module contains config dataclasses that bundle arguments that modify low-level details of the code. Relevant configs are always passed through function arguments and trigger jit-recompilation if modified. The main reasons to pass non-default configuartions is if some allocation turned out too small, or to optimize memory usage.

class jztree.config.RegularizationConfig(regularize_percentile=90.0, max_volume_fac=20.0)[source]

Config controlling regularization of the tree.

Regularization splits tree nodes above a dynamically determined size. It is on by default for kNN and off for FoF. With bounding boxes, kNN is fast for most distributions without it (regularization costs 2-8% for grid, uniform and cosmological particles), but it still helps strongly centrally concentrated distributions such as a Gaussian, where it reduces the run time by 14-62%. Switch it off with cfg.tree.regularization = None.

Parameters:
  • regularize_percentile (float)

  • max_volume_fac (float)

print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

class jztree.config.TreeConfig(max_leaf_size=32, coarse_fac=6.0, stop_coarsen=1024, regularization=None, alloc_fac_nodes=1.0, nsamp=1024, mass_centered=False)[source]

Config dataclass controlling tree structure and allocation.

Parameters:
print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

class jztree.config.FofCatalogueConfig(npart_min=20)[source]

Config dataclass controlling aspects of friends-of-friends catalogues

Parameters:

npart_min (int)

print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

class jztree.config.FofConfig(alloc_fac_ilist=32.0, alloc_fac_distr_links=0.01, alloc_fac_comm_nodes=1.5, alloc_fac_comm_particles=1.25, extra_pad_fac=None, tree=<factory>, catalogue=<factory>)[source]

Main nested config for friends-of-friends

Parameters:
print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

class jztree.config.KNNConfig(alloc_fac_ilist=200.0, sort_ilist=True, alloc_fac_comm_nodes=1.5, alloc_fac_comm_particles=1.25, extra_pad_fac=None, tree=<factory>, alloc_fac_neighbours=None)[source]

Main nested config for k nearest neighbour search

Parameters:
print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

class jztree.config.QueryBallConfig(alloc_fac_ilist=256.0, sort_ilist=False, alloc_fac_comm_nodes=1.5, alloc_fac_comm_particles=1.25, extra_pad_fac=None, tree=<factory>, alloc_fac_neighbours=64.0)[source]

Radius-search allocation settings. Reductions ignore alloc_fac_neighbours.

Parameters:
print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

jztree.data

This module contains some dataclasses that define interfaces between different parts of the code. In particular relevant are the particle data classes, like Pos that are needed in multi-GPU setups, to keep track of particle counts.

class jztree.data.Pos(*, pos, num=None, num_total=None)[source]

A dataclass holding positions.

num and num_total are only required for multi-GPU setups where the number of filled entries may be less than the size and run-time dependent

Parameters:
  • pos (object) – Position array of shape (size, dim)

  • num (int | object | None) – Filled count (<=size) on local device, needed for multi-GPU, may be dynamic

  • num_total (int | None) – Total count on all devices, static

class jztree.data.PosMass(*, pos, mass, num=None, num_total=None)[source]

Dataclass holding positions and masses, see Pos for details

Parameters:
class jztree.data.ParticleData(*, pos, mass=None, vel=None, id=None, num=None, num_total=None)[source]

Dataclass holding positions and optional data, see Pos for details

Parameters:
class jztree.data.PackedArray(data, ispl, fill_values=None, levels_filled=<factory>)[source]

A dataclass allowing to stack several dynamic arrays into a single buffer

Parameters:
class jztree.data.LevelInfo(dim, dtype)[source]

Data class holding info on minimum and maximum Morton level of a tree

Parameters:
class jztree.data.TreeHierarchy(size_leaves, ispl_n2n, ispl_n2l, ispl_l2p_per_type, lvl, bounds, mass=None, mass_cent=None)[source]

Dataclass holding the tree-plane hierarchy

Most properties are stored in PackedArray classes that stack them contingously in a single buffer for all tree-planes

Parameters:
  • size_leaves (int) – Size of the leaf-node level allocation

  • ispl_n2n (PackedArray) – The node-to-node splitting points. Node i on plane p includes all plane p-1 nodes in the range ispl_n2n.get(p)[i] … ispl_n2n.get(p)[i+1]

  • ispl_n2l (PackedArray) – Splitting points that go directly from nodes to leaves.

  • ispl_l2p_per_type (List[object]) – Leaf-to-particle splitting points per particle type.

  • lvl (PackedArray) – Morton-level of nodes. Can be used to define extent of nodes.

  • geom_cent – Morton centers reconstructed on access (not stored)

  • mass (PackedArray | None) – Mass of nodes (only available for mass_centered tree)

  • mass_cent (PackedArray | None) – Mass centers of nodes (only available for mass_centered tree)

  • bounds (PackedArray) – Packed coordinate minima followed by maxima

property geom_cent: PackedArray[source]

Reconstruct Morton centers from lower bounds and Morton levels.

The result preserves the PackedArray interface but is not cached or stored in the tree. Bind it locally when reusing it outside a compiled function.

splits_leaf_to_part(ptype=0, size=None)[source]

Convenience method to get the leaf-to-particle splits for a specific type

Parameters:
  • ptype (int)

  • size (int | None)

Return type:

object

npart(level, ptype=0, size=None)[source]

Number of particles in an node

Parameters:
Return type:

object

center()[source]

Return the selected center; explicit Morton and fitted geometry remain available.

Return type:

PackedArray

poslvl(level, size=None)[source]

Return node centers and Morton levels for one tree plane.

Parameters:
  • level (int)

  • size (int | None)

Return type:

PosLvl

num_planes()[source]

Numer of planes in the tree

Return type:

int

num(level)[source]

Number of nodes in a given plane

Return type:

int

size()[source]

The recommended allocation size at the leaf level

Return type:

int

info()[source]

Info about the minimum and maximum Morton levels of the tree

Return type:

LevelInfo

class jztree.data.InteractionList(ispl, isrc, rad2=None, ids=None, dev_spl=None, has_separate_query_and_source_indices=False)[source]

A dataclass that holds interaction information for dual tree-walks

The interaction list is defined so that a receiving node i needs to interact with all source nodes in the range isrc[ispl[i]:ispl[i+1]]

Parameters:
  • ispl (object) – splitting points of interaction list segments

  • isrc (object) – interaction source indices

  • rad2 (object | None) – interaction radii squared. Optional – so far only used in kNN algorithm

  • ids (object | None) – used in multi-GPU scenarios to define for each source index the origin index

  • dev_spl (object | None) – used in multi-GPU scenarios to define for each unique source index the origin rank. (Sources in range dev_spl[r]:dev_spl[r+1] belong to rank r.)

  • has_separate_query_and_source_indices (bool) – if False, query and source indices share one requested-node index space. If True, ispl is indexed by local query nodes while isrc indexes requested source nodes.

without_remote_query_points(rank, size=None)[source]

By default the interaction list carries remote and local points both on ispl so that query and source indices are consistent. However, this function redefines the interaction list so that ispl is only defined for local query points, but interaction indices may still point to remote points. ispl gets the length size (default: unchanged), e.g. the number of local query nodes + 1 if the node arrays were enlarged to hold remote nodes.

Parameters:
  • rank (int)

  • size (int | None)

Return type:

InteractionList

nfilled()[source]

Number of filled entries

size()[source]

Size of the interaction indices array

dtype()[source]

Index datatype (so far always int32)

class jztree.data.Label(irank, igroup, ilocal_segment=None)[source]

A FoF-group label for multi-GPU, pointing a root particle’s rank and index

Parameters:
class jztree.data.FofCatalogue(ngroups, mass=None, count=None, offset=None, com_pos=None, com_vel=None, com_inertia_radius=None, scale_factor=None, v_rad=None, vel_disp=None, v_rad_disp=None, offset_rank=None)[source]

Friends-of-friends catalogue data

Many properties are optional and will be set to None if calculation was lacking data. To allow jax.jit compatibility the arrays are generally allocated larger than what is actually needed, with ngroups indicating the filled count. You may use squeeze_catalogue() (outside of jax.jit) to obtain a squeezed version.

Parameters:
  • ngroups (object) – Actual number of groups. (On multi-GPU the local count.)

  • mass (object | None) – Group masses

  • count (object | None) – Number of particles

  • offset (object | None) – Starting point of each group in the particle array

  • com_pos (object | None) – Center of mass position

  • com_vel (object | None) – Center of mass velocity

  • com_inertia_radius (object | None) – Inertia radius \(\sqrt{\langle (\mathbf{x} - \mathbf{x}_0)^2 \rangle}\).

  • scale_factor (object | None) – For light-cone data: scale factor of light-cone crossing.

  • v_rad (object | None) – For light-cone data: radial (line of sight) velocity

  • vel_disp (object | None) – One-dimensional velocity dispersion \(\sqrt{\langle (\mathbf{v} - \mathbf{v}_0)^2 \rangle / 3}\).

  • v_rad_disp (object | None) – For light-cone data: dispersion of the radial velocity \(\sqrt{\langle (v_r - \bar v_r)^2 \rangle}\).

  • offset_rank (object | None) – Provided for squeezed catalogues to indicate origin rank.

class jztree.data.RankIdx(rank, idx)[source]

Holds a rank and an index – used to point to a particle in multi-GPU setups.

Parameters:
jztree.data.expand_particles(part, ndev)[source]

Expands particles from shape (Ndev*N) -> (Ndev,N)

Useful to interface with shard maps, since (Ndev,N) shape is assumed in general

Parameters:
jztree.data.flatten_particles(part)[source]

Flattens particles from shape (Ndev,N) -> (Ndev*N).

Parameters:

part (Pos)

jztree.data.pad_particles(part, num, float_val=jnp.nan, int_val=0)[source]

Pads particle data (to leave space for communication).

Parameters:
jztree.data.pad_particles_by_fraction(part, frac)[source]

Pads particle data (or a position array) by ceil(frac * length) entries.

Positions are padded with NaN, which marks the extra entries as invalid for arrays without a .num attribute.

Parameters:
jztree.data.squeeze_catalogue(cata, size_out=None, offset_mode='rank', nparts=None)[source]

Squeezes multi-GPU FoF catalogue that was returned from a shard_map (Ndev,size_group) into a dense form (Ntot) and replicates it on every device

Parameters:
  • cata (FofCatalogue) – FoF catalogue

  • size_out (int | None) – Can be provided to allow jit compatibility

  • offset_mode (Literal['rank', 'global']) – Can be “rank” or “global”. Before squeezing offsets indicate locations in the particle array of the same device. Since squeezing looses the device info, we need to indicate either the rank or we need to convert offsets to global offsets that index a squeezed particle array (converts to int64). “global” needs “nparts” as an input, i.e. how many particles were on each device

  • nparts (object | None) – particles that are on each device, needed for “global” offset_mode

Return type:

FofCatalogue

jztree.tree

This module contains functions for sorting particles into z-order, for building a plane-based tree hierarchy and for defining interaction lists.

jztree.tree.zsort(pos)[source]

Brings position vectors into z-order

If x is a pytree, it needs to have a “pos” attribute which will be used as the sorting key. All remaining leaves of the pytrees with the same length will be sorted accordingly along the leading axis

Parameters:

pos (object | Pos) – Can be a jax.Array or a more complicated particle data structure following the jztree.data.Pos interface. All pytree-leaves with the same leading shape as the .pos atribute will be sorted.

Returns:

(posz, idz) – Sorted positions and ids so that posz = pos[idz]

Return type:

Tuple[object | Pos, object]

Notes

zsort.jit(...) compiles the local sort. A custom reverse-mode rule maps gradients through the chosen permutation back to input order; the permutation itself is discrete. Forward-mode JVP is not supported through this custom VJP. Use distr_zsort.smap(mesh, jit=True) for distributed sorting.

jztree.tree.search_sorted_z(posz, posz_query, block_size=64, leaf_search=False)[source]

Finds the indices in xz where elements of xz_query would be inserted to keep order.

This is similar to np.searchsorted, but works for points sorted in Z-order. On equality maintains the rule: xz[idx] < v <= xz[idx+1] if leaf_search is True, it is assumed that xz contains one point per leaf and we return the index of the leaf that the query point belongs to.

Parameters:
jztree.tree.zsort_and_tree(part, cfg_tree=None, data=None, ptype=None, num_types=None, shrink=True)[source]

Brings particles into z-order and creates a tree hierarchy.

In the multi-GPU scenario, particles may be communicated and their balance adjusted to ensure that top-level nodes don’t cross domain boundaries.

For multi-type trees, please use zsort_and_tree_multi_type()

Parameters:
  • part (Pos) – position array or dataclass

  • cfg_tree (TreeConfig | None) – low-level configuration options

  • data (Any | None) – optional: additional particle data that will be carried along through sorting and communication. Can be a pytree and will be provided as an additional output

  • ptype (object | None) – optional, a type-index per particle to distinguish particle types in tree

  • num_types (int | None) – number of particle types

  • shrink (bool) – if False, always return 3 three outputs

Return type:

Tuple[Pos, TreeHierarchy]

jztree.tree.zsort_and_tree_multi_type(part, cfg_tree=None, data=None)[source]

Builds a tree with multiple particle types

The tree’s leaf-to-particle splits jztree.data.TreeHierarchy.ispl_l2p_per_type will be defined separately for each type.

Parameters:
  • part (Tuple[Pos, ...]) – tuple of particle arrays of different types

  • cfg_tree (TreeConfig | None) – config object controlling tree structure and allocation

  • data (Any | None) – additional particle data to be carried along

Returns:

(partz, th) – sorted particles and tree hierarchy. If data is provided additionally returns the sorted data.

Return type:

Tuple[Tuple[Pos, …], TreeHierarchy]

jztree.tree.build_tree_hierarchy(partz, cfg_tree, lvl_bound=None, ptype=None, num_types=None)[source]

Builds a tree hierarchy from z-order positions

The zeroth level of the tree corresponds to leaves, which contain multiple particles. Nodes (and leaves) are selected so that they are as big as possible while not containing more than a maximum number of particles that starts at cfg_tree.max_leaf_size and increases per level by a factor cfg_tree.coarse_fac.

Nodes are parameterized through a set of splits. For example the particles that lie in the leaf with index i are given py part[ispl_n2n.get(level=0)[i]: ispl_n2n.get(level=0)[i+1]] The ith node of level n contain all level n-1 nodes in the range : ispl_n2n.get(n)[i]: ispl_n2n.get(n)[i+1]

In jax memory size needs to be known at compile time, but the required number of nodes is data dependent on each level. To limit the number of allocations that we need to predict, we use the PackedArray class, that helps us to stack multiple different levels into a single continguous array, but to access it “almost” as if they were separate arrays.

It is recommend to use the zsort_and_tree() interface – especially for Multi-GPU, since the particle distribution needs to be adjusted to acommodate nodes.

Parameters:
Return type:

TreeHierarchy

jztree.tree.grouped_dense_interaction_list(nnodes, size_ilist, ngroup=32, size_super=None, node_range=None, dtype=jnp.int32)[source]

Defines an all-to-all interaction list over super-nodes and a super-node to node relation

This is useful for evaluating all-to-all interactions in a grouped manner on GPU

Parameters:
  • nnodes (object | int) – number of top-level nodes

  • size_ilist (int) – allocation size of the interaction list

  • ngroup (int) – how many top-level nodes should be summarized into one super node

  • size_super (int | None) – size of the super-node allocation

  • node_range (object | None) – can be provided to only include receiving nodes in this range, (but source nodes on the full domain. Useful for multi-GPU scenarios)

  • dtype – data-dtype of the interaction list. So far only int32 supported.

Returns:

A tuple (spl_super, ilist, nsuper_nodes) containing the super node splitting points, the interaction list and the number of super nodes.

Return type:

Tuple[object, InteractionList, object]

jztree.tree.simplify_interaction_list(ilist, always_keep=None)[source]

Reduces an interaction list to skip nodes that don’t appear as receiving our source indices

Useful in multi-GPU scenarios where many non-local nodes will not have any local interactions

Parameters:
Return type:

InteractionList

jztree.kde

The KDE interface is experimental and may change in future versions. See the KDE user guide for examples and bandwidth choices.

jz.kde.kde estimates density at the sources or at separate query points. Mathematical choices are explicit arguments; cfg only controls execution:

from jztree.kde import KNNBandwidth

rho = jz.kde.kde.jit(pos, bandwidth=KNNBandwidth(k=64))
rho_query = jz.kde.kde.jit(pos, bandwidth=0.1, query=output_points,
                          weights=mass, kernel="gaussian", cutoff_sigma=3., exclude_self=False)
rho_query = jz.kde.kde.jit(pos, bandwidth=source_radii, query=output_points,
                          bandwidth_at="source", exclude_self=False)

bandwidth_at="source" assigns a normalized kernel to each source, preserving its integrated weight. "query" assigns the radius to each output point; with spatially varying radii this need not preserve integrated weight. Bandwidth always means the support radius. Arrays match the owning population, and kNN bandwidths always measure distances to sources, counting self when applicable. By default, exclude_self=True removes each particle’s own contribution when query=None. Distinct coincident particles still contribute, and self still counts toward KNNBandwidth(k). Pass exclude_self=False to include self or when supplying explicit query points, for which no identity mapping is available.

Scalar or omitted weights give shape (Nquery,) in input order; vector weights give (Nquery, C) as described below. Weights default to one; divide them by their sum if a probability density is desired.

Reverse-mode gradients include positions, weights and bandwidths. The inferred kth-distance gradient is included, with neighbour selection held fixed. Kernels support 2D and 3D and require positive finite radii. Kernel-parameter gradients are unsupported for now. No full neighbour lists are returned or stored.

Both KNNConfig and QueryBallConfig can supply execution settings. Their alloc_fac_neighbours field only applies to packed query_ball output: it defaults to None for kNN and to 64 for query-ball. Reductions ignore it.

Vector weights

Weights may have shape (N, C) for 1–10 components. Each component is summed independently, sharing the neighbour search and bandwidths. The result has shape (Nquery, C); scalar weights (N,) still give a one-dimensional result. Position and weight gradients are supported for both forms.

# Density and two momentum-density components in one search.
weights = jnp.column_stack((mass, mass * velocity[:, 0], mass * velocity[:, 1]))
fields = jz.kde.kde.jit(pos, KNNBandwidth(k=32), weights=weights)
density = fields[:, 0]
mean_velocity = fields[:, 1:] / density[:, None]

Kernel density estimates with source- or query-owned support radii.

class jztree.kde.KNNBandwidth(k=64)[source]

Use distance to the kth source as the support radius (self counts toward k).

This describes the estimator, not its execution settings. k is static under JIT. Coincident neighbours yielding a zero radius are rejected.

Parameters:

k (int)

print(*, file=None, links='github')[source]

Print a config; links may be ‘github’, ‘local’, or None. No network access.

jztree.kde.kde(sources, bandwidth, weights=None, query=None, bandwidth_at='source', kernel='cubic_spline', cutoff_sigma=3., boxsize=None, cfg=None, exclude_self=True)[source]

Estimate a weighted density at query points, or at sources when query is omitted.

bandwidth is a positive support radius, an array with one radius per owning point, or KNNBandwidth(k). Neighbours determining a bandwidth always come from sources. With bandwidth_at=’source’, each source distributes its weight using its own radius; with ‘query’, each output collects source weights using its own radius. A scalar radius makes both choices equivalent. Kernels have unit integral in 2D or 3D; weights default to one. Normalize weights yourself for a probability density.

The Gaussian is truncated at the support radius, with sigma=radius/cutoff_sigma, and normalized within that disk or sphere. Polynomial kernels vanish at and beyond the support boundary; the truncated Gaussian includes the boundary. Fused kNN reductions retain the existing k-neighbour tie selection; radius searches include all boundary ties. For self queries, self counts toward k, even with exclude_self=True. exclude_self=True (the default) skips only the own density contribution and requires query=None; distinct particles at identical coordinates still contribute.

Weights may have shape (Nsource,) or (Nsource, C), with 1 <= C <= 10. Each component is summed independently using the same neighbours and bandwidth. Returns shape (Nquery,) for scalar/omitted weights or (Nquery, C) for vector weights, in input order. Reverse-mode differentiation supports positions, weights and supplied radii, including the kth-distance contribution for inferred bandwidths. Neighbour membership is held fixed. Kernel parameter gradients (cutoff_sigma) and forward-mode differentiation are unsupported for now.

cfg only controls execution: tree construction and buffer allocations. No packed neighbour output is allocated, so alloc_fac_neighbours is ignored. .jit compiles the operation; .smap uses the usual padded, expanding particle layout. For .smap, pass scalar bandwidths as one scalar per device, or close over a shared scalar when composing a shard map. Radius arrays follow their owning population’s layout.

Parameters:
Return type:

object

jztree.knn

This module contains functions for doing k-nearest neighbour search.

Use result="rad" for all neighbour radii, result="globalidx" for all neighbour indices, or result="rmax_imax" for only the kth neighbour’s radius and global index (one value per query). "rmax" and "imax" can also be requested separately. The default remains "rad_globalidx". Unrequested radius/index output buffers are omitted. The search still tracks candidate distances and indices internally; "drad" retains indices to recompute differentiable distances.

For accumulating neighbour contributions directly in CUDA without returning full neighbour lists, see Custom reductions in the developer guides. The tutorial also explains how to supply a VJP for automatic differentiation.

Radius queries

query_ball accepts a scalar radius or one radius per query, and returns packed indices and offsets. It includes all neighbours on the boundary, including self and coincident particles; it does not sort or return distances. For example:

cfg = jz.config.QueryBallConfig(alloc_fac_neighbours=64.)
neighbours = jz.knn.query_ball.jit(
    source_positions, query_radii, part_query=query_positions, boxsize=1., cfg=cfg,
)
# Outside jit: the source indices belonging to query i
ids = neighbours.indices[neighbours.offsets[i]:neighbours.offsets[i + 1]]

The index buffer has ceil(Nquery * cfg.alloc_fac_neighbours) entries. Its valid length is offsets[-1]; unused entries are -1. Capacity is shared across queries, so individual queries can exceed alloc_fac_neighbours neighbours. Too little capacity raises a fixable error rather than returning a truncated list; see Error handling (jz.apply_fix / jz.run_with_fixes). Inside jit, consume the fixed-size buffer with offsets/masks or a segmented operation; variable-length slicing still requires a static size.

query_ball_reduction instead accumulates directly, without a neighbour-output buffer. It uses the same configurations and optional CUDA VJPs as knn_reduction:

from jztree.neighbour_reductions import GaussianKDE

density = jz.knn.query_ball_reduction.jit(
    source_positions, query_radii, GaussianKDE(mode="gather"),
    source_fields=weights[:, None], part_query=query_positions,
)

Radii always belong to queries. Gather writes one row per query using source fields; scatter writes one row per source using query fields. A scalar radius broadcasts over queries, and its gradient sums the individual radius gradients. Reduction dispatch and params receive k=None. Position, field and radius VJPs hold neighbour membership fixed. KDE radii must be positive, whereas plain radius searches also accept zero. Supplying the kth-neighbour radius can include more than k neighbours when distances tie.

Both functions support shard maps. With the standard .smap helpers, pass radii as a per-device array alongside query positions. Packed offsets address each device’s own index buffer and include that device’s final offset. Source indices are global input-order IDs; padded queries have empty segments. The output capacity applies on each device both before and after restoring input order. Like kNN, radius queries can pad multi-GPU inputs internally with cfg.extra_pad_fac.

class jztree.knn.BallNeighbours(indices, offsets)[source]

Packed source indices. Query i occupies offsets[i]:offsets[i+1].

Indices are global input-order source IDs; unused entries are -1. Inside a shard map, offsets and capacity are local to each device. The .smap helper adds a leading device axis to both arrays; each offsets row addresses the corresponding device’s index buffer.

Parameters:
indices: object[source]

Alias for field number 0

offsets: object[source]

Alias for field number 1

jztree.knn.knn(part, k, boxsize=None, th=None, part_query=None, result='rad_globalidx', reduce_func=None, output_order='input', cfg=None)[source]

The main function executing the nearest neighbour search.

By default this returns (rnn, inn) – the radii and indices of the k nearest neighbours. Arguments may modify returned results and their ordering.

Parameters:
  • part (object | Pos) – Source positions, may be a jax.Array or a more complex dataclass following the jztree.data.Pos interface.

  • k (int) – Number of neighbours to calculate per particle

  • boxsize (float | None) – If provided, distance calculations are wrapped periodically.

  • th (TreeHierarchy | None) – May be provided to skip building a new tree-hierarchy inside of this function. See jztree.tree.zsort_and_tree(). If this argument is provided, particles are assumed to be already in z-order.

  • part_query (object | Pos | None) – Query positions, defaults to part.

  • result (str | object | Any) – String indicating the desired return values. May have any of the following separated by underscores: “rad” (radii), “drad” (differentible radii), “rankidx” (origin rank and index jztree.data.RankIdx), “globalidx” (linear global index), “part” (mapped source particles), “reduce” (see reduce_func) or the name of any attribute on the particle data structure. Alternatively, “rmax”, “imax”, or “rmax_imax” return only the kth neighbour radius and/or global index, with shape (N,). “drmax” recomputes the kth distance with position gradients, retaining only one index per query. These cannot be mixed with full neighbour results. Unrequested radius/index output buffers are not allocated; candidate distances and indices are still tracked internally.

  • reduce_func (Callable | None) – Will be called with the neighbour list in z-order to get a summary statistic per query particle. Useful to avoid communicating the neighbour list to origin tasks in distributed setups. Requires “reduce” inside of result.

  • output_order (Literal['input', 'z']) – May be “input” or “z”.

  • cfg (KNNConfig | None) – Config object that controls lower-level details of the algorithm. With cfg.extra_pad_fac (multi-GPU), the inputs are padded internally; outputs in input order keep the input length, z-ordered outputs have the padded length.

Returns:

Requested results, or a tuple when multiple result keys are selected. The default is (rnn, inn), containing neighbour radii and indices.

Return type:

Tuple[object, object]

Notes

Use knn.jit(...) or knn.smap(mesh, jit=True)(...). k, boxsize, result, reduce_func and output_order are static; config fields declare their own static/dynamic behavior. result="drad" recomputes distances in JAX for reverse-mode differentiation with neighbour selection held fixed; periodic distances use the minimum image. Ordinary "rad" results and discrete neighbour indices are not differentiable outputs.

jztree.knn.knn_reduction(part, k, reduction_type, source_fields=None, query_fields=None, boxsize=None, th=None, part_query=None, output_order='input', cfg=None)[source]

Kernel-weighted sums with one output per input field.

Both source_fields and query_fields may be supplied independently. KDE gather consumes source fields; scatter consumes query fields. Arrays have shape (capacity, nfields), with matching position dtype. Output order refers to the receiving population. Omitted fields have width zero. For KDE, omitting the consumed fields represents unit weights and produces one output field. Supported field counts are compiled specializations.

Reverse-mode gradients require an optional CUDA VJP. Config gradients are unsupported. See Custom kNN reductions.

Parameters:
jztree.knn.query_ball(part, radius, boxsize=None, part_query=None, cfg=None)[source]

Find every source within each query’s radius, without sorting neighbours.

radius is scalar or has shape (Nquery,). Sources and queries may differ; omitted queries mean self-query. All boundary ties, self interactions and coincident points are included. Distances are not returned.

indices has capacity ceil(Nquery * cfg.alloc_fac_neighbours) and offsets has shape (Nquery + 1,). Query order and source IDs refer to the input order. The final offset is the valid entry count; trailing index entries are -1. Too little capacity raises an error that jztree.apply_fix() and jztree.run_with_fixes() can fix. Under shard_map the same capacity is used on each device, both in tree order and after returning results to their input owners. Offsets are local to each device.

Radius values may vary without recompiling; boxsize and the config are static. Use query_ball_reduction to reduce without allocating these lists.

Parameters:
Return type:

BallNeighbours

jztree.knn.query_ball_reduction(part, radius, reduction_type, source_fields=None, query_fields=None, boxsize=None, part_query=None, output_order='input', cfg=None)[source]

Reduce all neighbours within query-owned radii without storing their IDs.

Gather writes to queries; scatter writes to sources. Fields, output order and optional CUDA VJP follow knn_reduction. Config dispatch and params receive k=None. Radius gradients are returned directly, with membership held fixed. KDE reductions require positive radii; query_ball itself also accepts zero.

Parameters:

jztree.fof

This module contains functions to calculate friends-of-friends (FoF) group labels, for bringing particles into group order and for calculating a group catalogue.

jztree.fof.fof_is_superset(igroup_sup, igroup, mask=None)[source]

Checks whether every FoF group in igroup_sup is a superset of sets in igroup_low

Useful for comparing different FoF implementations where labels may differ even when they represent the same groups.

jztree.fof.fof_labels(part, rlink, boxsize=0., cfg=None, th=None, output_order='z')[source]

Calculates the friends-of-friends group relation ship for single-GPU cases

For multi-GPU, please use distr_fof_labels()

Parameters:
  • part (object | Pos) – particles, can be a jax.Array or any particle data structure with a .pos atribute

  • rlink (float) – (absolute) linking length

  • boxsize (float) – if provided, distances use periodic wrapping

  • cfg (FofConfig | None) – controls low-level details

  • th (TreeHierarchy | None) – May be provided to skip building a new tree-hierarchy inside of this function. See jztree.tree.zsort_and_tree(). If this argument is provided, particles are assumed to be already in z-order.

  • output_order (Literal['input', 'z']) – may be “z” or “input”

Returns:

(part, igroup) – (possibly) reordered particles and group labels – igroup points to the first particle in z-order that belongs to the same group.

Return type:

Tuple[object | Pos, object]

jztree.fof.distr_fof_labels(part, rlink, boxsize=0., cfg=None, th=None, linearize_labels=False)[source]

Calculates the friends-of-friends group relation ship for multi-GPU cases.

For single-GPU, please use fof_labels()

Parameters:
  • part (Pos) – particles, should have some padding and follow the jztree.data.Pos interface

  • rlink (float) – (absolute) linking length

  • boxsize (float) – if provided, distances use periodic wrapping

  • cfg (FofConfig | None) – controls low-level details. With cfg.extra_pad_fac, part is padded internally and the z-ordered outputs have the padded length.

  • th (TreeHierarchy | None) – May be provided to skip building a new tree-hierarchy inside of this function. See jztree.tree.zsort_and_tree(). If this argument is provided, particles are assumed to be already in z-order.

  • linearize_labels (bool) – if true, group labels will be output as a scalar global index. Only use this for comparing small setups against single-GPU.

Returns:

(partz, label) – z-ordered particles and group labels – label points to the rank and index of the first particle in z-order that belongs to the same group.

Return type:

Tuple[Pos, Label]

jztree.fof.fof_and_catalogue(part, rlink, boxsize=0., cfg=None, th=None)[source]

Puts particles in FoF-order and calculates the FoF-catalogue

Supports single- and multi-GPU.

Parameters:
  • part (ParticleData) – particles, should follow at least the interface of jztree.data.Pos and may optionally contain additional elments as in jztree.data.ParticleData for calculating additional data in the catalogue. For multi-GPU, particles need to be padded to allow space for communication, or cfg.extra_pad_fac set (the FoF-ordered output particles then have the padded length).

  • rlink (float) – (absolute) linking length

  • boxsize (float) – if provided, distances use periodic wrapping

  • cfg (FofConfig | None) – controls low-level details

  • th (TreeHierarchy | None) – May be provided to skip building a new tree-hierarchy inside of this function. See jztree.tree.zsort_and_tree(). If this argument is provided, particles are assumed to be already in z-order.

Returns:

(partf, catalogue) – particles in FoF-order and the group catalogue. Each group forms a continous segment in the particle array, but the last group on each rank may continue on the next rank.

Return type:

Tuple[ParticleData, FofCatalogue]

Runtime checks

Runtime checks inside jitted code that raise catchable errors, and automatic config fixes.

raise_if() stops a jitted program before operations that depend on its result run (e.g. kernels that would overflow an allocation) and raises a jax.errors.JaxRuntimeError (a RuntimeError) with the values involved. JAX dispatches asynchronously, so the error surfaces when results are used or awaited, e.g. at block_until_ready().

Checks name the config field that controls the failing allocation (fix="alloc_fac_ilist") or "padding". apply_fix() then increases it, run_with_fixes() retries until a function succeeds, and CheckInfo.suggest_fixes() returns the factors (see check_info()).

Set the environment variable JZ_SKIP_CHECKS=1 to remove all checks.

jztree.checks.set_skip_checks(skip)[source]

Programmatic version of JZ_SKIP_CHECKS. Only affects functions traced afterwards.

Parameters:

skip (bool)

jztree.checks.raise_if(pred, msg, *fmt_args, fix=None, max_trace_depth=8, **fmt_kwargs)[source]

Stop the program with a readable error if pred is True.

Returns an int32 zero; adding it to an input of the operations that must not run after a failure (e.g. ispl = ispl + raise_if(...)) guarantees that they are not launched.

Parameters:
  • pred – boolean, the check fails if any element is true (the values shown in the message are their first elements). A Python/NumPy False creates no check.

  • msg – message with {name} (or {}) placeholders for fmt_args / fmt_kwargs

  • fix (str | None) – name of the config field that controls the allocation (e.g. "alloc_fac_ilist"), or "padding". Requires need and have in fmt_kwargs.

  • max_trace_depth – frames of the trace-time call chain in the message

Under shard_map, the check is reduced over all ranks first, so that every rank raises the same error. Kernels inside CUDA graphs must not fail, so check their sizes with raise_if first.

class jztree.checks.CheckInfo(message, values, fix, ratio, rank, nfailed, callsite, trace)[source]

Details of a failed check, see check_info().

Parameters:
suggest_fixes(margin=0.1)[source]

Factors by which to increase quantities, e.g. {"alloc_fac_ilist": 1.3}.

For “padding” the factor applies to the length of the particle arrays per rank. Raises ValueError if the check has no automatic fix.

Parameters:

margin (float)

Return type:

dict[str, float]

jztree.checks.check_info(error)[source]

Details of the failed check that caused error, or None for other errors.

Parameters:

error (BaseException)

Return type:

CheckInfo | None

jztree.checks.apply_fix(cfg, error, margin=0.1, verbose=True)[source]

Return a copy of cfg with the field that caused error increased by need/have * (1+margin).

The field is searched by name in cfg and its nested configs. Too little padding increases extra_pad_fac (kNN, FoF), which pads the inputs internally. Raises error again if it is not a failed check, and ValueError if the check cannot be fixed in cfg.

Parameters:
Return type:

_Config

jztree.checks.run_with_fixes(f, cfg, max_tries=10, margin=0.1, verbose=True)[source]

Call f(cfg), increasing allocations with apply_fix() until it succeeds.

Returns (result, cfg) with the config that worked. Errors that are not failed checks (or cannot be fixed in cfg) are raised.

Parameters:
Return type:

tuple[Any, _Config]

JAX helpers

jztree.jax_ext.tree_map_by_len(fn, tree, N, axis=0)[source]

Like jax.tree_map, but only applies fn to array-like leaves with shape[axis] == N. Everything else is copied unchanged.

Parameters:
Return type:

Any

jztree.jax_ext.expanding_shard_map(f, *, out_specs=None, in_specs=None, mesh=None, axis_names=None, check_vma=True, input_tiled=False, output_tiled=False, jit=False)[source]

Like jax.shard_map, but allows to choose whether inputs/outputs well be tiled or not

input_tiled: e.g. input (Ndev*N) -> (N) inside mapped function not input_tiled: (Ndev,N) -> (N) output_tiled: (N) inside mapped function -> (Ndev*N) outside not output_tiled: (N) -> (Ndev,N) (or no N and (,N) if partition spec is empty)

Additionally, P(-1) may be used to define a sharding over all axes of the mesh

These rules will only be applied to arguments with a varying partition spec Inputs and outputs with partition spec P() will be kept unchanged

jztree.jax_ext.jitable(*, static_argnames: tuple[str, ...] = (), smap: None = None, jit: Literal[True] = True) → Callable[[Callable[[_Args], _Result]], _Jitable[_Args, _Result]][source]
jztree.jax_ext.jitable(*, static_argnames: tuple[str, ...] = (), smap: dict, jit: Literal[True] = True) → Callable[[Callable[[_Args], _Result]], _JitableSharded[_Args, _Result]]
jztree.jax_ext.jitable(*, static_argnames: tuple[str, ...] = (), smap: dict, jit: Literal[False]) → Callable[[Callable[[_Args], _Result]], _Shardable[_Args, _Result]]

Attach compiled convenience methods while keeping the original function.

Parameters:
  • static_argnames – Static arguments shared by .jit and .smap.

  • smap – Options for shard_map_constructor; {} enables its defaults. Its static_argnames may override the shared setting when necessary.

  • jit – False preserves interfaces that expose only .smap.

Returns:

A decorator adding .jit and optionally .smap to the original function. Calls, signatures, docstrings and differentiation remain unchanged.

Particle and catalogue helpers

jztree.data.squeeze_particles(part)[source]

Squeezes multi-gpu output particles (Ndev,N) into a dense form (Ntot)

Parameters:

part (Pos)

jztree.data.sort_catalogue(cata, by='count', descending=True)[source]
Parameters:
jztree.data.get_pos(part)[source]
Parameters:

part (Pos)

jztree.data.get_num(part, default_to_length=False, default_to_nancount=True)[source]
Parameters:

part (Pos)

Config field declarations

Use @config_dataclass (or @config_dataclass(slots=True)) from jztree.config_utils for config classes and their subclasses. Ordinary fields, including nested configs, are pytree children. Mark structural values with static_field(default=...); these are JAX metadata and must be hashable. The config objects themselves need neither hashing nor static_argnames. This follows DISCO-DJ’s field-level convention without importing its full configuration framework. String selectors should be declared as static fields.

Distributed failure handling

jztree.distributed.configure_distributed_fail_fast()[source]

Disable JAX cooperative preemption before distributed initialization.

JAX’s preemption service can consume the launcher’s SIGTERM instead of terminating a blocked peer. This explicit policy chooses prompt termination over cooperative preemption/checkpoint handling. Call on every rank before jax.distributed.initialize; it does not install signal handlers itself.

jztree.distributed.fatal_distributed_errors(*, rank=None, failure_dir=None)[source]

Terminate this rank on an escaping exception, including interrupts.

Place initialization, execution and final jax.block_until_ready inside the context. Successful execution and SystemExit(0) are unchanged. Exceptions intentionally caught inside the context remain recoverable.