Template Class KDTree
Defined in File KDTree.hpp
Inheritance Relationships
Derived Types
public kden::KernelDensity< void >(Template Class KernelDensity)public kden::KernelDensity< AuxType >(Template Class KernelDensity)
Class Documentation
-
template<KDTreePoints Data = KDTreeData<>>
class KDTree A balanced kd tree indexing a set of points.
A non-owning wrapper around a set of points (a Data) that provides tree-based access to them. The tree is balanced, and its nodes are stored in a single contiguous array: node 0 is the root, and the children of node i are nodes 2i + 1 and 2i + 2, so the tree can be traversed with bit-shifting arithmetic. Building the tree reorders the underlying points in place, so that every node’s points occupy a contiguous range of them.
The number of dimensions, nDim, is a runtime parameter, taken from the data. Distances are measured in a metric defined by an inverse squared bandwidth matrix (see Bandwidth), or the Euclidean one if none is given. The metric used to build the tree (which only affects which dimension each node is split along) is not stored: every search takes its own, so different threads can search the same tree with different metrics at once.
- Template Parameters:
Data – Type of the points: KDTreeData (the default, with no auxiliary data), or a type derived from it (see KDTreePoints)
Subclassed by kden::KernelDensity< void >, kden::KernelDensity< AuxType >
Public Functions
-
inline KDTree(Data &data, const std::size_t leafSize, const Bandwidth &splitBandwidth, const std::vector<std::size_t> &noSplitDims = {})
Construct a KDTree over a set of points.
Sizes the tree, then initializes its root node to cover every point, with their bounding box. Finally builds the rest of the tree by splitting every node, level by level (see splitNode()), in parallel within each level if built with OpenMP – across a level’s nodes, or, for the top few levels, within each large node (see partitionNode() and setNodeBounds()). This reorders data in place; the order produced depends only on the data, not on the number of threads.
- Parameters:
data – The points to index; not copied, so both it and the storage it views must outlive the tree, and the storage is reordered in place as the tree is built. Its dimensionality sets the tree’s. It must pass its own validate(): for KDTreeData, every position coordinate must be finite.
leafSize – Maximum number of points in a leaf; must be at least 1
splitBandwidth – Metric used to choose split dimensions while building the tree (see chooseSplitDim()), for nDim dimensions. Used only during construction and not stored; searches take their own metric.
noSplitDims – Dimensions along which no node is split (see chooseSplitDim()); empty (the default) to allow every dimension. A tree for searches in which some dimensions will always be unspecified (NaN) can be built this way, so that its nodes are split only along the dimensions those searches use.
- Throws:
std::invalid_argument – if data is inconsistent (see Data::validate()), leafSize is 0, splitBandwidth is not for data’s number of dimensions, or noSplitDims contains a dimension not below nDim or contains every dimension
-
inline explicit KDTree(Data &data, const std::size_t leafSize = 16, const std::vector<std::size_t> &noSplitDims = {})
Construct a KDTree, choosing split dimensions with the Euclidean metric.
- Parameters:
data – As for the other constructor
leafSize – As for the other constructor
noSplitDims – As for the other constructor
- Throws:
std::invalid_argument – as for the other constructor
-
inline auto nDim() const -> std::size_t
Number of dimensions of the tree.
- Returns:
The number of dimensions
-
inline auto leafSize() const -> std::size_t
Maximum number of points in a leaf.
- Returns:
The leaf size
-
inline auto nLevels() const -> std::size_t
Number of levels allocated for the tree.
- Returns:
The number of levels (an upper bound on the depth; see splitNode())
-
inline auto nLeaves() const -> std::size_t
Number of leaves allocated for the tree.
- Returns:
The number of leaf slots on the last level (an upper bound on the number of actual leaves)
-
inline auto nodes() const -> const std::vector<KDTreeNode>&
The tree’s nodes, in index order (root first)
- Returns:
The nodes; slots below a leaf are unused, and hold default (empty) nodes
-
inline auto nodeLo(const std::size_t idx) const -> std::span<const double>
Lower corner of a node’s bounding box.
- Parameters:
idx – Index of the node
- Returns:
Its nDim coordinates: the minimum of the node’s points’ positions in each dimension (the actual extent of its points, not the plane that split it from its sibling)
-
inline auto nodeHi(const std::size_t idx) const -> std::span<const double>
Upper corner of a node’s bounding box.
- Parameters:
idx – Index of the node
- Returns:
Its nDim coordinates (see nodeLo())
-
inline auto data() const -> const Data&
The points the tree indexes, in tree order.
- Returns:
The (non-owned) points, reordered so that each node’s points are contiguous; Neighbor::idx_ indexes into these
-
inline auto neighbors(const std::vector<double> &x, const std::size_t nNeighbor, const Bandwidth &bandwidth) const -> std::vector<Neighbor>
Find the nearest neighbors of a point.
Exact k-nearest-neighbor search. The tree is walked depth first, visiting the nearer child of each node first, so that close neighbors are found early; a node is skipped, with its whole subtree, if a rigorous lower bound on the distance from x to any point in its bounding box (see Bandwidth::BoxBounder) exceeds the distance to the current k’th nearest neighbor. Thread-safe: neither the tree nor the bandwidth is modified, so different threads may search at once, sharing a bandwidth or each with its own.
- Parameters:
x – Position to search around; must have nDim elements. Elements may be NaN, to judge nearness only in the other dimensions.
nNeighbor – Number of neighbors to find
bandwidth – The metric, for nDim dimensions. If x has NaN elements and bandwidth has not been reduced for exactly that pattern (see Bandwidth::reduce()), it is reduced here, at O(nDim^3) cost; for many searches with the same metric and pattern, reduce once and pass the result.
- Throws:
std::invalid_argument – if x or bandwidth is not for nDim dimensions, or bandwidth has been reduced for a different pattern of NaNs than x’s
std::domain_error – if reducing bandwidth fails (see Bandwidth::reduce())
- Returns:
The min(nNeighbor, number of points) points nearest to x, in order of increasing distance, each as the index of the point in data() and its squared distance from x (as computed by Bandwidth::dist2(), with the reduced bandwidth if x has NaN elements). Use data().position() and aux() (and any accessors Data adds) to get at the point itself.
-
inline auto neighbors(const std::vector<double> &x, const std::size_t nNeighbor) const -> std::vector<Neighbor>
Find the nearest neighbors of a point, in the Euclidean metric.
- Parameters:
x – As for the other overload
nNeighbor – As for the other overload
- Throws:
std::invalid_argument – if x does not have nDim elements
- Returns:
As for the other overload
-
inline auto neighbors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &nNeighbor, const std::vector<Bandwidth> &bandwidth) const -> std::vector<std::vector<Neighbor>>
Find the nearest neighbors of each of several points, in parallel.
Runs the single-point search for each element, in parallel (dynamically scheduled, since searches can differ widely in cost) if built with OpenMP.
- Parameters:
x – Positions to search around, one per search
nNeighbor – Number of neighbors to find, one per search
bandwidth – Metric to use, one per search
- Throws:
std::invalid_argument – if x, nNeighbor, and bandwidth do not all have the same number of elements; otherwise, any exception the single-point version throws for any one of the searches (the first one caught, if several do)
- Returns:
One result per search, each exactly as returned by the single-point version for the corresponding arguments
-
inline auto neighbors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &nNeighbor, const Bandwidth &bandwidth) const -> std::vector<std::vector<Neighbor>>
Find the nearest neighbors of each of several points, in parallel, sharing one metric.
If bandwidth has not been reduced and every search point has the same pattern of NaNs, it is reduced once for all of them rather than once per search.
- Parameters:
x – Positions to search around, one per search
nNeighbor – Number of neighbors to find, one per search
bandwidth – The metric, shared by every search
- Throws:
As – for the version taking one bandwidth per search
- Returns:
One result per search, each exactly as returned by the single-point version
-
inline auto neighbors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &nNeighbor) const -> std::vector<std::vector<Neighbor>>
Find the nearest neighbors of each of several points, in parallel, in the Euclidean metric.
- Parameters:
x – Positions to search around, one per search
nNeighbor – Number of neighbors to find, one per search
- Throws:
As – for the shared-bandwidth version
- Returns:
One result per search
-
inline auto neighbors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &nNeighbor, const std::vector<std::size_t> &errDims, const std::vector<Eigen::MatrixXd> &errCov, const Bandwidth &bandwidth) const -> std::vector<std::vector<Neighbor>>
Find, in parallel, the nearest neighbors of each of several points measured with errors.
Each point’s metric is convolved with its own errors in the thread that searches around it. If every point has the same pattern of NaNs, bandwidth is reduced for it once, beforehand, and each convolution done in the reduced space.
- Parameters:
x – Positions to search around, one per search
nNeighbor – Number of neighbors to find, one per search
errDims – The dimensions with measurement errors; each must be specified (not NaN) in every point
errCov – The covariance matrix of each point’s errors, in the dimensions errDims (in that order): one per point, each errDims.size() square, symmetric, and positive semi-definite
bandwidth – The metric, shared by every search
- Throws:
std::invalid_argument – if errCov does not have one matrix per point, or one has the wrong size, or errDims has a dimension not below nDim, a repeated one, or one that is NaN in a point; otherwise, as for the shared-bandwidth version, and as for Bandwidth::convolveCov()
- Returns:
One result per search: the neighbors of x[i] in the metric bandwidth convolved with its errors (see Bandwidth::convolveCov()), (M^-1 + 2 C_i)^-1, in which a difference the errors could explain counts for less
Public Static Functions
-
static inline constexpr auto left(const std::size_t idx) -> std::size_t
Index of a node’s left child.
- Parameters:
idx – Index of the node
- Returns:
2 idx + 1
-
static inline constexpr auto right(const std::size_t idx) -> std::size_t
Index of a node’s right child.
- Parameters:
idx – Index of the node
- Returns:
2 idx + 2
-
static inline constexpr auto parent(const std::size_t idx) -> std::size_t
Index of a node’s parent.
- Parameters:
idx – Index of the node
- Returns:
(idx - 1) / 2, or nullNode if idx is the root
-
static inline constexpr auto sibling(const std::size_t idx) -> std::size_t
Index of a node’s sibling.
- Parameters:
idx – Index of the node
- Returns:
idx + 1 if idx is a left (odd) child, idx - 1 if it is a right (even) child, or nullNode if idx is the root, which has no sibling
-
static inline constexpr auto next(std::size_t idx) -> std::size_t
Index of the next node to visit after a node’s whole subtree.
Climbs from idx while it is a right (even) child, then steps to the right sibling of the left child reached. Calling this in place of descending into idx’s children skips its subtree, which is how a traversal prunes nodes it does not need to open.
- Parameters:
idx – Index of the node
- Returns:
The first node after idx and all its descendants in a depth-first, parent-before-children traversal, or nullNode if there is none (idx is on the tree’s rightmost path)
Protected Functions
A shared bandwidth, reduced once for a batch of points if they all share a pattern of NaNs.
- Parameters:
x – The points
bandwidth – The bandwidth
- Returns:
bandwidth reduced for the points’ common pattern of NaNs, if it is not reduced already, is for nDim dimensions, every point has nDim elements and the same pattern, and that pattern has a NaN; otherwise bandwidth itself (each query then reduces it as needed, or reports what is wrong)
-
inline void checkErrors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &errDims, const std::vector<Eigen::MatrixXd> &errCov, const std::vector<std::size_t> &marginalDims, const char *caller) const
Check a batch’s measurement errors.
- Parameters:
x – The points
errDims – The dimensions with errors
errCov – One covariance matrix per point
marginalDims – Dimensions that must not be in errDims
caller – The caller’s name, for messages
- Throws:
std::invalid_argument – if errCov does not have one matrix per point, or one is not errDims.size() square; errDims has a dimension not below nDim, a repeated one, or one in marginalDims; or a dimension in errDims is NaN in a point (points that do not have nDim elements are left to the single-point call to report)
-
inline auto embedErrors(const std::vector<std::size_t> &errDims, const Eigen::MatrixXd &cov) const -> Eigen::MatrixXd
A covariance matrix over some dimensions, embedded in all nDim.
- Parameters:
errDims – The dimensions it covers
cov – The matrix, errDims.size() square
- Returns:
The nDim x nDim matrix with cov in the rows and columns errDims, and zero elsewhere
-
inline auto search(const std::vector<double> &x, const std::size_t nNeighbor, const Bandwidth &bandwidth) const -> std::vector<Neighbor>
The nearest-neighbor search itself.
Depth-first, nearer child first, with an explicit stack of (node, lower bound) pairs: a node popped whose bound now exceeds the current k’th distance is skipped. Candidates are kept as (squared distance, point index) pairs, sorted by distance.
- Parameters:
x – The search point; must match bandwidth (see Bandwidth::matches())
nNeighbor – Number of neighbors to find
bandwidth – The metric
- Returns:
As for neighbors()
-
template<typename Search>
inline auto batchNeighbors(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &nNeighbor, const Search &search) const -> std::vector<std::vector<Neighbor>> Run a batch of neighbor searches in parallel.
Dynamically scheduled OpenMP loop, if built with OpenMP. An exception must not escape an OpenMP parallel region, so each is caught in the loop and the first one rethrown afterwards.
- Template Parameters:
Search – Callable taking (x[i], nNeighbor[i], i) and returning one search’s result
- Parameters:
x – Positions to search around, one per search
nNeighbor – Number of neighbors to find, one per search
search – The search to run for each element
- Throws:
std::invalid_argument – if x and nNeighbor differ in length; otherwise, the first exception any search throws
- Returns:
One result per search
-
inline auto chooseSplitDim(const std::size_t idx, const Bandwidth &bandwidth, const std::vector<std::size_t> &noSplitDims) const -> int
Choose the dimension along which to split a node.
Splits along the dimension in which the node is widest, measured in the tree’s metric: the one maximizing (hi[i] - lo[i])^2 M_ii, the squared metric length of the node’s extent along axis i (for a diagonal bandwidth h_i, its extent in units of the bandwidth, squared), or just (hi[i] - lo[i])^2 for the Euclidean metric, among the dimensions not in noSplitDims. Ties go to the lowest dimension.
- Parameters:
idx – Index of the node; its bounding box must already be set
bandwidth – The metric
noSplitDims – Dimensions not to split along; must leave at least one
- Returns:
The dimension to split along, in [0, nDim) and not in noSplitDims
-
inline void setNodeBounds(const std::size_t idx)
Set a node’s bounding box from its points.
The bounding box (nodeLo()/nodeHi()) is the actual extent of the node’s points, not the planes that split them off from their siblings. A node with no points gets lo = +inf and hi = -inf in every dimension. Writes only this node’s own slices of the flat arrays, so nodes may be processed in parallel. A node with at least blockedMinCount points is scanned in blocks of blockSize, in parallel if built with OpenMP (and not already inside a parallel region), and the blocks’ extents then combined; the result is the same either way.
- Parameters:
idx – Index of the node; its start_ and count_ must already be set
-
inline void rangeBounds(const std::size_t start, const std::size_t end, const std::span<double> lo, const std::span<double> hi) const
Find the extent of a contiguous range of points.
- Parameters:
start – Index of the first point
end – One past the index of the last point
lo – Set to the minimum of each coordinate (+inf if the range is empty)
hi – Set to the maximum of each coordinate (-inf if the range is empty)
-
inline auto coord(const std::size_t i, const std::size_t dim) const -> double
A point’s coordinate along one dimension.
- Parameters:
i – Index of the point
dim – The dimension
- Returns:
The coordinate
-
inline void partitionNode(const std::size_t idx)
Partially sort a node’s points about their median along its split dimension.
Reorders the node’s points (an in-place selection) so that, with m = start_ + (count_ - 1) / 2, the point at index m is the one that would be there if the node’s points were fully sorted by their coordinate along splitDim_, every point before it has a coordinate no larger, and every point after it one no smaller. Points are swapped whole, with Data::swap(), so auxiliary data and any per-point arrays a derived Data adds move with their positions. A node with at least blockedMinCount points is narrowed down with selectBlocked(), which can run in parallel; the rest of the work is done by selectSerial().
- Parameters:
idx – Index of the node; its splitDim_ must already be set
-
inline void selectSerial(const std::size_t first, const std::size_t last, const std::size_t m, const std::size_t dim)
Select, serially, the point of a given rank in a range.
An in-place quickselect (following slug2’s partition_node): afterwards, the points in [first, m) have coordinates no larger than point m’s, and those in (m, last] no smaller.
- Parameters:
first – Index of the first point of the range
last – Index of the last point of the range (inclusive)
m – Index, in [first, last], at which to put the point of rank m - first along dim
dim – The dimension to order by
-
inline void selectBlocked(const std::size_t first, const std::size_t end, const std::size_t m, const std::size_t dim)
Select the point of a given rank in a large range, with passes that can run in parallel.
The same result as selectSerial() (though possibly a different order of the points on either side of m). Each round sorts an evenly spaced sample of the range’s coordinates and takes two of them, a little below and a little above m’s relative rank, as pivots; two partitionBlocked() passes then narrow the range to the points between the pivots, which contain m unless the sample misjudged its rank (in which case the round still narrows the range, to one side of a pivot). Rounds continue until the range has fewer than blockedMinCount points, or consists of equal coordinates, or a round fails to narrow it; selectSerial() finishes the job. The order of points this produces depends only on the data, not on the number of threads.
- Parameters:
first – Index of the first point of the range
end – One past the index of the last point of the range
m – Index, in [first, end), at which to put the point of rank m - first along dim
dim – The dimension to order by
-
template<typename Pred>
inline auto partitionSerial(const std::size_t first, const std::size_t end, const Pred &pred) -> std::size_t Partition, serially, a range of points by a predicate.
- Template Parameters:
Pred – Callable taking a point index and returning bool
- Parameters:
first – Index of the first point of the range
end – One past the index of the last point of the range
pred – The predicate
- Returns:
The index of the first point for which pred is false, after reordering the range so that pred holds for the points before it and not for those from it on
-
template<typename Pred>
inline auto partitionBlocked(const std::size_t first, const std::size_t end, const Pred &pred) -> std::size_t Partition a range of points by a predicate, in blocks that can be processed in parallel.
Each block of blockSize points is partitioned on its own (partitionSerial()). With mid the returned index, the points then out of place – those failing pred before mid, and those passing it from mid on – are equal in number, and lie in at most one interval per block on each side; pairing the k’th of one side with the k’th of the other, the swaps that put them in place touch distinct points, so are made in parallel, in chunks of blockSize. Both stages run in parallel if built with OpenMP (and not already inside a parallel region); the blocks, and so the order of points produced, depend only on the range’s size, not on the number of threads.
- Template Parameters:
Pred – Callable taking a point index and returning bool; called concurrently, so must be safe to call from several threads at once
- Parameters:
first – Index of the first point of the range
end – One past the index of the last point of the range
pred – The predicate
- Returns:
As for partitionSerial()
-
inline void splitNode(const std::size_t idx, const Bandwidth &bandwidth, const std::vector<std::size_t> &noSplitDims)
Split a node into two children, or mark it as a leaf.
A node with at most leafSize_ points becomes a leaf (splitDim_ = -1, no children). Otherwise it is split along chooseSplitDim(idx, bandwidth, noSplitDims): its points are partitioned about their median along that dimension (see partitionNode()), the left child gets the first (count_ + 1) / 2 of them and the right child the rest, and each child’s bounding box is computed from its own points.
- Parameters:
idx – Index of the node; its start_, count_, and bounding box (see setNodeBounds()) must already be set
bandwidth – The metric used to choose the split dimension
noSplitDims – Dimensions not to split along
Protected Attributes
-
std::size_t nDim_
Number of dimensions the tree is built over
-
std::vector<KDTreeNode> nodes_
The tree’s nodes, root first
-
std::vector<double> nodeLo_
Lower corners of the nodes’ bounding boxes, nodes x nDim, node-major
-
std::vector<double> nodeHi_
Upper corners of the nodes’ bounding boxes, likewise
-
std::size_t nLevels_ = 1
Number of levels in the tree
-
std::size_t nLeaves_ = 1
Number of leaves in the tree
-
std::size_t leafSize_
Maximum number of points in a leaf
Protected Static Attributes
-
static constexpr std::size_t blockedMinCount = std::size_t{1} << 16
Nodes with at least this many points are partitioned (selectBlocked()) and have their bounding boxes found (setNodeBounds()) in blocks that can be processed in parallel; smaller ones serially
-
static constexpr std::size_t blockSize = std::size_t{1} << 14
Number of points per block, and per chunk of swaps, in the blocked algorithms
-
static constexpr std::size_t pivotSampleSize = 1024
Number of coordinates sampled to choose each round’s pivots in selectBlocked()