pynbody.kdtree.KDTree#

class pynbody.kdtree.KDTree(pos, mass, leafsize=32, boxsize=None, num_threads=None, shared_mem=False)[source]#

Bases: object

KDTree can be used for smoothing, interpolating and geometrical queries.

You are unlikely to need to interact with the KDTree directly, instead using the higher-level SPH functionality such as

>>> f = pynbody.load("my_snapshot")
>>> f.gas['smooth'] # will build KDTree and calculate smoothing lengths for gas, if not available on disk
>>> f.gas['rho'] # will calculate densities for gas, if not available on disk
>>> f.dm['rho'] # will calculate densities for dark matter, if not available on disk

KDTree can also be used to accelerate geometrical queries on a snapshot, e.g.:

>>> f = pynbody.load('my_snapshot')
>>> f.build_tree()
>>> f[pynbody.filt.Sphere('10 kpc')]

See performance of filters for more information.

Most KDTree operations proceed in parallel, using the number of threads specified in the pynbody configuration.

Performance statistics can be tested using the performance_kdtree.py script in the tests folder.

Note that the KDTree takes into account periodicity of cosmological volumes if it can. However, as soon as a snapshot has been rotated, this may become impossible. In this case, the KDTree will issue a warning, and will not use periodicity. This is to avoid incorrect results due to the periodicity assumption, but it will lead to artefacts on the edge of the box. If you are working with a cosmological simulation, it is best to perform any KDTree operations (such as smoothing) before rotating the snapshot, e.g.:

>>> f = pynbody.load('my_snapshot')
>>> f['rho']; f['smooth'] # force KDTree to be built and density estimations made
>>> pynbody.analysis.faceon(f) # rotate the snapshot
>>> pynbody.plot.image(f.g, qty='rho', width='10 kpc')
Attributes:
kernel

The SPH kernel currently in use by this tree.

Methods

all_nn([nn])

A list of neighbours information for all the particles in the snapshot.

array_name_to_id(name)

Convert the pynbody name of an array to the corresponding integer ID in the C++ code.

deserialize(pos, mass, serialized_state[, ...])

Reconstruct a KDTree from a serialized state.

get_array_ref(name)

Get the current array reference for a given name ('smooth', 'rho', 'mass', 'qty', or 'qty_sm').

nn([nn])

Generator of neighbour list.

pair_blocks([mode, blocksize, num_threads, ...])

Iterate over neighbour pairs, in blocks, as flat numpy arrays.

pair_reduce(func[, mode, blocksize, dtype, ...])

Accumulate a user-supplied pairwise function over all neighbour pairs.

particles_in_sphere(center, radius)

Find particles within a sphere.

populate(mode, nn[, weighting])

Create the KDTree and perform the operation specified by mode.

serialize()

Produce a serialized description of the tree

set_array_ref(name, ar)

Give the C++ code access to a given array.

set_kernel([kernel])

Set the kernel for smoothing operations.

smooth_operation_to_id(name)

Convert the name of a smoothing operation to the corresponding integer ID in the C++ code.

sph_curl(array[, nsmooth, weighting])

Calculate the curl of a given array using SPH smoothing.

sph_dispersion(array[, nsmooth, weighting])

Calculate the SPH dispersion of a simulation array.

sph_divergence(array[, nsmooth, weighting])

Calculate the divergence of a given array using SPH smoothing.

sph_mean(array[, nsmooth, weighting])

Calculate the SPH mean of a simulation array.

__init__(pos, mass, leafsize=32, boxsize=None, num_threads=None, shared_mem=False)[source]#

Create a KDTree

Most users will not need to call this directly, but will instead use the higher-level functions, either via accessing SPH properties on a snapshot, or calling pynbody.snapshot.simsnap.SimSnap.build_tree().

Parameters:
  • pos (pynbody.array.SimArray) – Particles positions.

  • mass (pynbody.array.SimArray) – Particles mass.

  • leafsize (int, optional) – The number of particles in leaf nodes (default 32).

  • boxsize (float, optional) – Period of the box. The default, None, gives a non-periodic tree.

  • num_threads (int, optional) –

    Number of threads to use when building the tree and in later operations on it (if None, use configured/detected number of processors). Within a thread_limit block, no more threads than its limit are used, even if the tree was built outside the block.

    Changed in version 2.6.0: Any number of threads is now used in full. Previously the build rounded this down to a power of two, and spent the early part of the build on fewer threads than requested. Building with more than one thread temporarily allocates one extra intp per particle while the top of the tree is laid out. That is freed before the node array fills up, so the effect on peak memory is smaller than the allocation and is often nothing at all; past a million or so particles it adds at most 3 bytes per particle.

    Note

    The tree does not depend on num_threads unless particles share a coordinate value exactly. Where they do, which of them ends up on each side of a split is not defined, so the tree – while still correct – may differ from one thread count to another. Exact ties are common in single precision positions once there are more than a few hundred thousand particles, and essentially absent in double precision. Build with num_threads=1 if you need a bit-for-bit reproducible tree from single precision positions.

  • shared_mem (bool, optional) – Whether to keep kdtree in shared memory so that it can be shared between processes (default False).

all_nn(nn=None)[source]#

A list of neighbours information for all the particles in the snapshot.

static array_name_to_id(name)[source]#

Convert the pynbody name of an array to the corresponding integer ID in the C++ code.

classmethod deserialize(pos, mass, serialized_state, num_threads=None, boxsize=None)[source]#

Reconstruct a KDTree from a serialized state.

get_array_ref(name)[source]#

Get the current array reference for a given name (‘smooth’, ‘rho’, ‘mass’, ‘qty’, or ‘qty_sm’).

property kernel#

The SPH kernel currently in use by this tree.

Added in version 2.6.0.

This is the same kernel object that the C++ smoothing routines are using, so evaluating it from python (via value() and gradient()) is guaranteed to be consistent with results from e.g. sph_mean() or the rho array. This is what makes it possible to write a pair_reduce() callback without re-deriving the kernel normalisation by hand.

See set_kernel() to change it.

nn(nn=None)[source]#

Generator of neighbour list.

Parameters:

nn (int, None) – number of neighbours. If None, default to 64.

Yields:

nbr_list (list[int, float, list[int], list[float]]) – Information about the neighbours of a particle.

List with four elements:

  • nbr_list[0] (int): the index of the particle in the snapshot’s arrays.

  • nbr_list[1] (float): the smoothing length of the particle

  • nbr_list[2] (list[int]): list of the indexes of the nn neighbouring particles.

  • nbr_list[3] (list[float]): list of distances squared of each neighbouring particles.

The lists of particle and of the relative distance squared are not sorted.

pair_blocks(mode='symmetric', blocksize=262144, num_threads=None, reuse_buffer=False)[source]#

Iterate over neighbour pairs, in blocks, as flat numpy arrays.

Added in version 2.6.0.

This is the low-level primitive underlying pair_reduce(). Use it directly when you want to do something with the pairs other than sum over them.

The pairs are gathered in parallel, but handed over one block at a time, so the loop below is an ordinary sequential one.

Each iteration yields a tuple (i, j, dx, r) of arrays with the same leading length nblock <= blocksize:

name

shape / dtype

meaning

i

(nblock,) intp

index of the first particle of each pair

j

(nblock,) intp

index of the second particle of each pair

dx

(nblock, 3) float

periodic-wrapped pos[j] - pos[i]

r

(nblock,) float

|dx|, always strictly positive

Note that i and j are arrays of particle indices, one entry per pair, so per-particle quantities are used via fancy indexing, e.g. rho[i] is the density of the first particle of each pair.

The geometry, dx and r, has the dtype of the positions the tree was built from: float32 for a single-precision snapshot and float64 for a double-precision one. The whole walk is carried out in that precision, so a single-precision tree offers no less accuracy here than it does anywhere else, but a callback that mixes these arrays with per-particle quantities of its own should either work in the same precision or promote them explicitly.

The pair set is fixed by the smoothing lengths associated with the tree. Where pynbody derives those itself, accessing f['smooth'] associates them automatically. Where they instead come from the snapshot file, they must be associated explicitly, since reading them does not involve the tree at all:

f.build_tree()
f.kdtree.set_array_ref('smooth',
                       f['smooth'].in_units(f['pos'].units))
Parameters:
  • mode (str) –

    Which pairs to generate.

    • 'symmetric' (default): every unordered pair with \(r \leq \max(2 h_i, 2 h_j)\), exactly once, canonicalised so that i < j. This is what SPH operators involving both smoothing lengths require, such as artificial viscosity or conduction.

    • 'gather': every ordered pair with \(r \leq 2 h_i\), where \(h\) is the smoothing length. A pair appears in both orderings when each particle lies inside the other’s kernel. This is the neighbour set used by the density estimate and by sph_mean().

    The boundary is inclusive, matching the neighbour search used by the density estimate, so that a gather over n neighbours really does yield n of them. This is worth noting because \(r = 2h\) is not a rare edge case: smoothing lengths are half the distance to the nth neighbour, so exactly one neighbour of every particle sits on the boundary. Nothing physical depends on which side they fall, since both \(W\) and \(dW/dr\) vanish there.

  • blocksize (int) – Maximum number of pairs per block. Blocks are arbitrary cuts of the pair set, so a given particle’s pairs will in general straddle a block boundary. Larger blocks amortise the per-block overhead at the cost of memory; in practice throughput is insensitive to this over a wide range, so the default is chosen to keep the buffers small. It counts the whole block however many threads are gathering it, so neither the memory nor the size of the blocks the caller sees depends on the thread count.

  • num_threads (int, optional) –

    How many threads gather pairs at once, defaulting to the tree’s own setting. Each walks a separate range of particles and fills its own slice of the block, so the consumer still sees an ordinary sequence of blocks and is never called from more than one thread. It is capped at blocksize, since each walk needs a slot of its own to write into, and at the number of particles.

    The pair set does not depend on this, but the order the pairs arrive in does, so a sum accumulated over the blocks can differ in its last bits between thread counts. Pass num_threads=1 if that matters.

  • reuse_buffer (bool) –

    Whether each block may be written over the last one.

    By default every block gets memory of its own, so blocks can be kept and used after the iteration has moved on. Setting this to True instead writes them all into a single buffer, which saves allocating and faulting in fresh memory for every block, but means a block is only valid until the next one is generated. Anything that has to outlive the current iteration must then be copied.

    Worth setting for a loop that finishes with each block before asking for the next, which is the usual case; it is what pair_reduce() does internally.

Yields:

tuple – (i, j, dx, r) as described above. The arrays are read-only, and are separate from one block to the next unless reuse_buffer says otherwise.

Examples

Counting the neighbours of each particle. Each block is finished with before the next is asked for, so the buffer may be reused:

>>> counts = np.zeros(len(f), dtype=int)
>>> for i, j, dx, r in f.kdtree.pair_blocks(mode='gather',
...                                         reuse_buffer=True):
...     counts += np.bincount(i, minlength=len(f))
pair_reduce(func, mode='symmetric', blocksize=262144, dtype=<class 'numpy.float64'>, num_threads=None)[source]#

Accumulate a user-supplied pairwise function over all neighbour pairs.

Added in version 2.6.0.

This lets arbitrary pairwise SPH operations be expressed without a python-level loop over particles. The neighbour search runs in C++, while func is called once per block of pairs and works on flat numpy arrays.

For every pair, func returns a contribution \(c_i\) for the first particle and \(c_j\) for the second. Each particle’s result is the sum of the contributions from every pair it takes part in, at whichever end it appears:

\[\mathrm{out}[k] = \sum_{\mathrm{pairs}\ (k,\, j)} c_i \;+ \sum_{\mathrm{pairs}\ (i,\, k)} c_j\]
Parameters:
  • func (callable) –

    Called as func(i, j, dx, r) with one block of pairs at a time; see pair_blocks() for the meaning and shapes of the arguments. Per-particle quantities are reached by closing over them and indexing with i or j.

    It must return either

    • a single array, of shape (nblock,) or (nblock, k), whose values are accumulated at i; or

    • a tuple (contrib_i, contrib_j) of two such arrays, which are accumulated at i and at j respectively.

    The trailing shape is fixed by the first block and may not vary.

    func must be a pure function of its arguments: it must not mutate them, carry state between calls, or assume anything about which pairs are grouped into a block. In particular it cannot perform a reduction over all of a particle’s neighbours, since they need not all be present in the same block; compute such quantities in a separate pass first. Nor may it keep hold of the arrays it is passed.

    Use pair_blocks() directly if you need blocks that last beyond the function lifetime.

  • mode (str) – 'symmetric' (default) or 'gather'; see pair_blocks().

  • blocksize (int) – Maximum number of pairs handed to func at once.

  • dtype (numpy dtype) – Data type of the output array. Accumulation is always performed in double precision, and the result converted on return, so that the answer does not depend on blocksize.

  • num_threads (int, optional) – How many threads gather pairs at once; see pair_blocks(). This only affects the internal pair production; only one call to func is made per block, on the calling thread. The result can differ in its last bits between thread counts, since they change the order in which pairs are summed.

Returns:

Shape (N,) or (N, k), where N is the number of particles in the tree.

Return type:

numpy.ndarray

Notes

The pairs are gathered in parallel: several threads walk separate ranges of the particles and fill a block between them. func itself cannot be run that way, since a python callback holds the GIL, so it gets each block on a single thread.

That makes func worth optimising for any serious work with large numbers of particles. For example, a numba function may be appropriate, perhaps using @numba.njit(parallel=True) to enable threading within the block-processing part of the overall algorithm:

>>> @numba.njit(parallel=True)                       
... def kernel(i, j, dx, r, q, out):
...     for k in numba.prange(len(i)):
...         out[k] = q[j[k]] - q[i[k]]

Such a kernel writes its result into an array the caller supplies, which func then returns.

In 'symmetric' mode each pair is visited exactly once and both ends are accumulated from that single visit. Returning an antisymmetric contribution (m[j] * c, -m[i] * c) therefore conserves \(\sum_a m_a\, \mathrm{out}[a]\) to roundoff as an algebraic identity, rather than approximately.

Examples

SPH artificial conduction, which requires both smoothing lengths and so uses the symmetric pair set:

>>> m, rho, p, u, h = (f.g[k] for k in ('mass','rho','p','u','smooth'))
>>> W = f.g.kdtree.kernel
>>> def conduction(i, j, dx, r):
...     mu = np.einsum('kl,kl->k', f.g['vel'][j] - f.g['vel'][i], dx) / r
...     v_d = 0.5 * (np.abs(mu)
...                  + np.sqrt(2 * np.abs(p[i] - p[j]) / (rho[i] + rho[j])))
...     # note gradient() is dW/dr, which is negative; the usual form of
...     # this equation is written in terms of its magnitude
...     g = -(W.gradient(r, h[i]) / rho[i] + W.gradient(r, h[j]) / rho[j])
...     c = v_d * (u[j] - u[i]) * g
...     return m[j] * c, -m[i] * c
>>> du_dt = f.g.kdtree.pair_reduce(conduction)

The returned contributions are antisymmetric, so this conserves energy exactly; (m * du_dt).sum() vanishes to roundoff.

The same calculation with a compiled kernel, which is worth doing for anything but a one-off: each of those numpy expressions allocates an array the length of the block, and there are a dozen of them, whereas the loop below allocates nothing and threads over the pairs. buffered_kernel() provides the two output arrays and reuses them from block to block, so the kernel need only fill them in:

>>> import numba                                     
>>> @numba.njit                                      
... def abs_grad_w(r, h):
...     # |dW/dr| for the kernel in use, written out for numba
...     ...
>>> @numba.njit(parallel=True)                       
... def conduction(i, j, dx, r, m, rho, p, u, h, vel, out_i, out_j):
...     for k in numba.prange(len(i)):
...         a, b = i[k], j[k]
...         mu = ((vel[b, 0] - vel[a, 0]) * dx[k, 0]
...               + (vel[b, 1] - vel[a, 1]) * dx[k, 1]
...               + (vel[b, 2] - vel[a, 2]) * dx[k, 2]) / r[k]
...         v_d = 0.5 * (abs(mu) + np.sqrt(2 * abs(p[a] - p[b])
...                                        / (rho[a] + rho[b])))
...         g = (abs_grad_w(r[k], h[a]) / rho[a]
...              + abs_grad_w(r[k], h[b]) / rho[b])
...         c = v_d * (u[b] - u[a]) * g
...         out_i[k] = m[b] * c
...         out_j[k] = -m[a] * c
>>> du_dt = f.g.kdtree.pair_reduce(                  
...     buffered_kernel(conduction, m, rho, p, u, h, f.g['vel']),
...     mode='symmetric')

numba.prange is safe here because iteration k writes only element k. Note that it would not be safe to accumulate onto particles this way – out[i[k]] += ... – since a particle belongs to many pairs and the iterations would race; that accumulation is what pair_reduce does for you, serially.

particles_in_sphere(center, radius)[source]#

Find particles within a sphere.

Most users will not need to call this directly, but will instead use pynbody.filt.Sphere.

Parameters:
  • center (array_like) – Center of the sphere.

  • radius (float) – Radius of the sphere.

Returns:

indices – Indices of the particles within the sphere.

Return type:

array_like

populate(mode, nn, weighting='volume')[source]#

Create the KDTree and perform the operation specified by mode.

Parameters:
  • mode (str) – Operation to perform; see smooth_operation_to_id() for the accepted names, which cover smoothing lengths, density, SPH mean, dispersion, divergence and curl.

  • nn (int) – Number of neighbours the smoothing lengths correspond to. Note this does not itself select the neighbours: except when computing smoothing lengths, those are whichever particles lie within the kernel. See sph_mean().

  • weighting (str) –

    Whether to take the volume-weighted or the mass-weighted average over the kernel; see sph_mean() for what the two mean and when they differ.

    Added in version 2.6.0.

serialize()[source]#

Produce a serialized description of the tree

set_array_ref(name, ar)[source]#

Give the C++ code access to a given array.

Parameters:
  • name (str) – Name of the array to set (can be ‘smooth’, ‘rho’, ‘mass’, ‘qty’, ‘qty_sm’)

  • ar (pynbody.array.SimArray) – Array that the C++ code will access. Note that INCREF is called on the array, so it will be kept alive as long as the KDTree object is alive (or until another set_array_ref call replaces it.)

set_kernel(kernel=None)[source]#

Set the kernel for smoothing operations.

Parameters:

kernel (various) – Kernel to use for smoothing operations. Can be a string (e.g. ‘CubicSplineKernel’) or a pynbody.sph.kernels.KernelBase instance. If None, the pynbody default kernel is used. For more information see the documentation for pynbody.sph.kernels.create_kernel.

smooth_operation_to_id(name)[source]#

Convert the name of a smoothing operation to the corresponding integer ID in the C++ code.

Valid names are:

  • ‘hsm’ : compute smoothing lengths

  • ‘rho’ : compute density

  • ‘qty_mean’ : compute SPH mean of the ‘qty’ array

  • ‘qty_disp’ : compute SPH dispersion of the ‘qty’ array

  • ‘qty_div’ : compute divergence of the ‘qty’ array

  • ‘qty_curl’ : compute curl of the ‘qty’ array

sph_curl(array, nsmooth=64, weighting='volume')[source]#

Calculate the curl of a given array using SPH smoothing.

Parameters:
  • array (pynbody.array.SimArray) – Quantity to compute curl of.

  • nsmooth (int) – Number of neighbours the smoothing lengths correspond to. Note that this does not itself select the neighbours: those are whichever particles lie within the kernel, as set by the smoothing lengths. It sizes the internal neighbour buffer, and sets the neighbour count that kernels needing one (such as Wendland C2) are normalised for.

  • weighting (str) –

    Whether to take the volume-weighted or the mass-weighted average over the kernel; see sph_mean() for what the two mean and when they differ.

    Added in version 2.6.0.

Returns:

The curl of the input array.

Return type:

pynbody.array.SimArray

sph_dispersion(array, nsmooth=64, weighting='volume')[source]#

Calculate the SPH dispersion of a simulation array.

Given a kernel W, this routine computes the smoothed quantity:

\[r_i = \sum_{j=0}^{N_{smooth}}\left( \frac{m_j}{\rho_j} q_j W(|x_i - x_j|, s_i) \right)\]

Then the squared root of the SPH smoothed variance:

\[d_i = \left\{ \sum_{j=0}^{N_{smooth}} \frac{m_j}{\rho_j} (q_j - r_i)^2 W(|x_i - x_j|, s_i) \right\}^{1/2}\]

where d_i is the calculated dispersion, m is the mass array, rho is the density array, q is the input array, s_i is the smoothing length, and W is the kernel function.

Actual computation is done in the C++-extension functions smooth.cpp::smDispQty[1,N]D.

Parameters:
  • array (pynbody.array.SimArray) – Quantity to compute dispersion of.

  • nsmooth (int) – Number of neighbours the smoothing lengths correspond to. Note that this does not itself select the neighbours: those are whichever particles lie within the kernel, as set by the smoothing lengths. It sizes the internal neighbour buffer, and sets the neighbour count that kernels needing one (such as Wendland C2) are normalised for.

  • weighting (str) –

    Whether to take the volume-weighted or the mass-weighted average over the kernel; see sph_mean() for what the two mean and when they differ.

    Added in version 2.6.0.

Returns:

output – The dispersion of the input array.

Return type:

pynbody.array.SimArray

sph_divergence(array, nsmooth=64, weighting='volume')[source]#

Calculate the divergence of a given array using SPH smoothing.

Parameters:
  • array (pynbody.array.SimArray) – Quantity to compute the divergence of.

  • nsmooth (int) – Number of neighbours the smoothing lengths correspond to. Note that this does not itself select the neighbours: those are whichever particles lie within the kernel, as set by the smoothing lengths. It sizes the internal neighbour buffer, and sets the neighbour count that kernels needing one (such as Wendland C2) are normalised for.

  • weighting (str) –

    Whether to take the volume-weighted or the mass-weighted average over the kernel; see sph_mean() for what the two mean and when they differ.

    Added in version 2.6.0.

Returns:

The divergence of the input array.

Return type:

pynbody.array.SimArray

sph_mean(array, nsmooth=64, weighting='volume')[source]#

Calculate the SPH mean of a simulation array.

Given a kernel W, this calculates

\[r_i = \sum_{j=0}^{N_{smooth}}\left( \frac{m_j}{\rho_j} q_j W(|x_i - x_j|, s_i) \right)\]

where r is the result of the smoothing, m is the mass array, rho is the density array, q is the input array, s_i is the smoothing length, and W is the kernel function.

The actual computation is done in the C++-extension function smooth.cpp::smMeanQty[1,N]D.

Parameters:
  • array (pynbody.array.SimArray) – Quantity to smooth (compute SPH interpolation at particles position).

  • nsmooth – Number of neighbours the smoothing lengths correspond to. Note that this does not itself select the neighbours: those are whichever particles lie within the kernel, as set by the smoothing lengths. It sizes the internal neighbour buffer, and sets the neighbour count that kernels needing one (such as Wendland C2) are normalised for.

  • weighting (str) –

    Which average over the kernel to compute.

    Writing \(i\) for the particle whose value is being computed and \(j\) for each of its neighbours, both options evaluate \(\sum_j V_j q_j W(|x_i - x_j|, s_i)\), differing only in the volume \(V_j\) given to each neighbour:

    • 'volume' (default): \(V_j = m_j/\rho_j\), each neighbour’s own volume. The sum is then the direct discretisation of the smoothing integral, giving the volume-weighted average \(\int q W \, dV\).

    • 'mass': \(V_j = m_j/\rho_i\), using the density at the particle being evaluated, which gives the mass-weighted average \(\int q \rho W \, dV / \int \rho W \, dV\). Since \(\rho_i\) is itself \(\sum_j m_j W(|x_i - x_j|, s_i)\), the weights here sum to one exactly, so this reproduces a constant field exactly and can never return a value outside the range of its input.

    The two agree where the density is nearly constant across a kernel, and differ where it is not.

    For a divergence, 'mass' is the form that satisfies the continuity equation exactly, and so is the one appearing in the SPH equations of motion. Use it to reproduce a quantity as the simulation code itself computed it.

    Added in version 2.6.0.

Returns:

output – The SPH mean of the input array.

Return type:

pynbody.array.SimArray