Program Listing for File KDTree.hpp

↰ Return to documentation for file (src/kden/KDTree.hpp)

#ifndef KDTREE_HPP
#define KDTREE_HPP

#include "Bandwidth.hpp"
#include <Eigen/Dense> // NOLINT(misc-include-cleaner) -- provides Eigen::Index; clang-tidy's IWYU mapping doesn't know this header
#include <algorithm>
#include <cassert>
#include <cmath>
#include <concepts>
#include <cstddef>
#include <exception>
#include <functional>
#include <limits>
#include <span>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#ifdef _OPENMP
#   include <omp.h>
#endif

namespace kden {

    inline constexpr std::size_t nullNode = std::numeric_limits<std::size_t>::max();

    inline constexpr std::size_t rootNode = 0;

    struct KDTreeNode
    {
        std::size_t start_ = 0;
        std::size_t count_ = 0;
        std::size_t lchild_ = nullNode;
        std::size_t rchild_ = nullNode;
        std::size_t parent_ = nullNode;
        int splitDim_ = -1;
    };

    template <typename AuxType>
    struct KDTreeAuxStorage
    {
        using View = std::span<AuxType>;
        using Owned = std::vector<AuxType>;
    };
    template <>
    struct KDTreeAuxStorage<void>
    {
        using View = std::monostate;
        using Owned = std::monostate;
    };

    template <typename AuxType = void>
    struct KDTreeData
    {
        using Aux = AuxType;

        static constexpr bool hasAux = !std::is_void_v<AuxType>;

        std::size_t nDim_ = 0;
        std::span<double> x_;
        [[no_unique_address]] typename KDTreeAuxStorage<AuxType>::View aux_;
        [[nodiscard]] auto size() const -> std::size_t { return nDim_ == 0 ? 0 : x_.size() / nDim_; }

        [[nodiscard]] auto position(const std::size_t i) const -> std::span<const double>
        {
            return std::span<const double>(x_).subspan(i * nDim_, nDim_);
        }

        [[nodiscard]] auto aux(const std::size_t i) const -> const auto&
            requires hasAux
        {
            return aux_[i]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
        }

        void validate() const
        {
            if (nDim_ < 1)
            {
                throw std::invalid_argument("KDTreeData: nDim_ must be at least 1");
            }
            if (x_.size() % nDim_ != 0)
            {
                throw std::invalid_argument("KDTreeData: x_ must hold nDim_ coordinates per point");
            }
            if (!std::ranges::all_of(x_, [](const double v) -> bool { return std::isfinite(v); }))
            {
                throw std::invalid_argument("KDTreeData: positions must be finite (NaN is "
                    "supported only in search points)");
            }
            if constexpr (hasAux)
            {
                if (aux_.size() != size())
                {
                    throw std::invalid_argument("KDTreeData: aux_ must hold one element per point");
                }
            }
        }

        void swap(const std::size_t i, const std::size_t j)
        {
            std::swap_ranges(x_.begin() + static_cast<std::ptrdiff_t>(i * nDim_),
                x_.begin() + static_cast<std::ptrdiff_t>((i + 1) * nDim_),
                x_.begin() + static_cast<std::ptrdiff_t>(j * nDim_));
            if constexpr (hasAux)
            {
                std::swap(aux_[i], aux_[j]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            }
        }
    };

    template <typename AuxType = void>
    struct OwnedKDTreeData
    {
        std::size_t nDim_ = 0;
        std::vector<double> x_;
        [[no_unique_address]] typename KDTreeAuxStorage<AuxType>::Owned aux_;
        [[nodiscard]] auto view() -> KDTreeData<AuxType>
        {
            KDTreeData<AuxType> v;
            v.nDim_ = nDim_;
            v.x_ = std::span<double>(x_);
            if constexpr (KDTreeData<AuxType>::hasAux) { v.aux_ = std::span<AuxType>(aux_); }
            return v;
        }
    };

    template <typename Data>
    concept KDTreePoints = std::derived_from<Data, KDTreeData<typename Data::Aux>>;

    struct Neighbor
    {
        std::size_t idx_ = 0;
        double dist2_ = 0.0;
    };

    template <KDTreePoints Data = KDTreeData<>>
    class KDTree
    {
    public:

        // Tree traversal. Node 0 is the root, and the children of node
        // i are 2i + 1 (left, always odd) and 2i + 2 (right, always
        // even), so moving around the tree is pure index arithmetic.

        [[nodiscard]] static constexpr auto left(const std::size_t idx) -> std::size_t
        {
            return (idx << 1) + 1;
        }

        [[nodiscard]] static constexpr auto right(const std::size_t idx) -> std::size_t
        {
            return (idx << 1) + 2;
        }

        [[nodiscard]] static constexpr auto parent(const std::size_t idx) -> std::size_t
        {
            return idx == rootNode ? nullNode : (idx - 1) >> 1;
        }

        [[nodiscard]] static constexpr auto sibling(const std::size_t idx) -> std::size_t
        {
            if (idx == rootNode) { return nullNode; }
            return (idx & 1) != 0 ? idx + 1 : idx - 1;
        }

        [[nodiscard]] static constexpr auto next(std::size_t idx) -> std::size_t
        {
            while (idx != nullNode && (idx & 1) == 0) { idx = parent(idx); }
            return idx == nullNode ? nullNode : idx + 1;
        }

        KDTree(Data& data,
            const std::size_t leafSize,
            const Bandwidth& splitBandwidth,
            const std::vector<std::size_t>& noSplitDims = {}) :
            nDim_(data.nDim_),
            data_(std::ref(data)),
            leafSize_(leafSize),
            euclidean_(Bandwidth::identity(std::max<std::size_t>(data.nDim_, 1)))
        {
            data.validate();
            if (leafSize_ < 1)
            {
                throw std::invalid_argument("KDTree: leafSize must be at least 1");
            }
            if (splitBandwidth.nDim() != nDim_)
            {
                throw std::invalid_argument("KDTree: splitBandwidth must be for nDim dimensions");
            }
            if (std::ranges::any_of(noSplitDims, [this](const std::size_t d) -> bool { return d >= nDim_; }))
            {
                throw std::invalid_argument("KDTree: noSplitDims must contain only dimensions below nDim");
            }
            std::vector<bool> noSplit(nDim_, false);
            for (const std::size_t d : noSplitDims) { noSplit[d] = true; }
            if (std::ranges::all_of(noSplit, [](const bool b) -> bool { return b; }))
            {
                throw std::invalid_argument("KDTree: noSplitDims must leave at least one dimension to split along");
            }

            // Number of leaves, levels, and nodes: keep halving the
            // number of points until it falls below the leaf size,
            // doubling the number of leaves (and adding a level) each time
            std::size_t nNodes = 1;
            for (std::size_t n = data_.get().size(); n >= leafSize_; n >>= 1)
            {
                nLeaves_ <<= 1;
                nLevels_++;
                nNodes += nLeaves_;
            }
            nodes_.resize(nNodes);
            nodeLo_.assign(nNodes * nDim_, 0.0);
            nodeHi_.assign(nNodes * nDim_, 0.0);

            // Root node: covers every point
            nodes_[rootNode].start_ = 0;
            nodes_[rootNode].count_ = data_.get().size();
            setNodeBounds(rootNode);

            // Build the tree breadth first, one level at a time, so each
            // node is split after its parent. Nodes on the same level
            // are independent -- each touches only itself, its own two
            // children, and its own contiguous range of points -- so a
            // level can be split in parallel. Level k holds nodes
            // 2^k - 1 through 2^(k+1) - 2; nodes on the last level have
            // at most leafSize_ points, so splitNode() just marks them
            // as leaves. A level with fewer nodes than threads (the top
            // few) is instead split one node at a time, so that each
            // split can use every thread (see partitionNode() and
            // setNodeBounds()); which way a level is split does not
            // change the tree built.
            std::size_t first = rootNode;
            std::size_t width = 1;
            for (std::size_t level = 0; level < nLevels_; ++level)
            {
#ifdef _OPENMP
                if (width >= static_cast<std::size_t>(omp_get_max_threads()))
                {
#                   pragma omp parallel for
                    for (std::size_t i = first; i < first + width; ++i)
                    {
                        splitNode(i, splitBandwidth, noSplitDims);
                    }
                }
                else
#endif
                {
                    for (std::size_t i = first; i < first + width; ++i)
                    {
                        splitNode(i, splitBandwidth, noSplitDims);
                    }
                }
                first += width;
                width <<= 1;
            }
        }

        explicit KDTree(Data& data, const std::size_t leafSize = 16,
            const std::vector<std::size_t>& noSplitDims = {}) :
            KDTree(data, leafSize, Bandwidth::identity(std::max<std::size_t>(data.nDim_, 1)), noSplitDims)
        {}

        // Read-only access to the tree's structure
        [[nodiscard]] auto nDim() const -> std::size_t { return nDim_; }
        [[nodiscard]] auto leafSize() const -> std::size_t { return leafSize_; }
        [[nodiscard]] auto nLevels() const -> std::size_t { return nLevels_; }
        [[nodiscard]] auto nLeaves() const -> std::size_t { return nLeaves_; }
        [[nodiscard]] auto nodes() const -> const std::vector<KDTreeNode>& { return nodes_; }
        [[nodiscard]] auto nodeLo(const std::size_t idx) const -> std::span<const double>
        {
            return std::span<const double>(nodeLo_).subspan(idx * nDim_, nDim_);
        }
        [[nodiscard]] auto nodeHi(const std::size_t idx) const -> std::span<const double>
        {
            return std::span<const double>(nodeHi_).subspan(idx * nDim_, nDim_);
        }
        [[nodiscard]] auto data() const -> const Data& { return data_.get(); }

        [[nodiscard]] auto neighbors(const std::vector<double>& x,
            const std::size_t nNeighbor,
            const Bandwidth& bandwidth) const
            -> std::vector<Neighbor>
        {
            if (x.size() != nDim_ || bandwidth.nDim() != nDim_)
            {
                throw std::invalid_argument("KDTree::neighbors: x and bandwidth must be "
                    "for nDim dimensions");
            }
            if (bandwidth.matches(x)) { return search(x, nNeighbor, bandwidth); }
            if (bandwidth.isReduced())
            {
                throw std::invalid_argument("KDTree::neighbors: bandwidth was reduced for "
                    "a different pattern of NaNs than x's");
            }
            return search(x, nNeighbor, bandwidth.reduce(Bandwidth::nanPattern(x)));
        }

        [[nodiscard]] auto neighbors(const std::vector<double>& x,
            const std::size_t nNeighbor) const
            -> std::vector<Neighbor>
        {
            return neighbors(x, nNeighbor, euclidean_);
        }

        [[nodiscard]] 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>>
        {
            if (bandwidth.size() != x.size())
            {
                throw std::invalid_argument("KDTree::neighbors: x, nNeighbor, and bandwidth "
                    "must all have the same number of elements");
            }
            return batchNeighbors(x, nNeighbor, [this, &bandwidth](const std::vector<double>& xi,
                const std::size_t ki, const std::size_t i) -> std::vector<Neighbor>
            {
                return neighbors(xi, ki, bandwidth[i]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            });
        }

        [[nodiscard]] 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>>
        {
            // Reduce once up front if every point needs the same reduction
            const Bandwidth bw = sharedReduction(x, bandwidth);
            return batchNeighbors(x, nNeighbor, [this, &bw](const std::vector<double>& xi,
                const std::size_t ki, const std::size_t) -> std::vector<Neighbor>
            {
                return neighbors(xi, ki, bw);
            });
        }

        [[nodiscard]] auto neighbors(const std::vector<std::vector<double>>& x,
            const std::vector<std::size_t>& nNeighbor) const
            -> std::vector<std::vector<Neighbor>>
        {
            return neighbors(x, nNeighbor, euclidean_);
        }

        [[nodiscard]] 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, // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by <Eigen/Dense> (included above); clang-tidy's IWYU mapping doesn't know that
            const Bandwidth& bandwidth) const
            -> std::vector<std::vector<Neighbor>>
        {
            checkErrors(x, errDims, errCov, {}, "KDTree::neighbors");
            const Bandwidth bw = sharedReduction(x, bandwidth);
            return batchNeighbors(x, nNeighbor, [this, &bw, &errDims, &errCov](const std::vector<double>& xi,
                const std::size_t ki, const std::size_t i) -> std::vector<Neighbor>
            {
                return neighbors(xi, ki, bw.convolveCov(embedErrors(errDims, errCov[i]))); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            });
        }

    protected:

        static constexpr std::size_t blockedMinCount = std::size_t{1} << 16;

        static constexpr std::size_t blockSize = std::size_t{1} << 14;

        static constexpr std::size_t pivotSampleSize = 1024;

        [[nodiscard]] auto sharedReduction(const std::vector<std::vector<double>>& x,
            const Bandwidth& bandwidth) const -> Bandwidth
        {
            if (x.empty() || bandwidth.isReduced() || bandwidth.nDim() != this->nDim_ ||
                x.front().size() != this->nDim_ || bandwidth.matches(x.front()))
            {
                return bandwidth;
            }
            const std::vector<bool> pattern = Bandwidth::nanPattern(x.front());
            const bool shared = std::ranges::all_of(x, [this, &pattern](const std::vector<double>& xi) -> bool
                { return xi.size() == this->nDim_ && Bandwidth::nanPattern(xi) == pattern; });
            return shared ? bandwidth.reduce(pattern) : bandwidth;
        }

        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
        {
            const std::string name(caller);
            if (errCov.size() != x.size())
            {
                throw std::invalid_argument(name + ": errCov must have one matrix per point");
            }
            const auto k = static_cast<Eigen::Index>(errDims.size()); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by <Eigen/Dense> (included above); clang-tidy's IWYU mapping doesn't know that
            if (std::ranges::any_of(errCov, [k](const Eigen::MatrixXd& c) -> bool
                { return c.rows() != k || c.cols() != k; }))
            {
                throw std::invalid_argument(name + ": each errCov matrix must be errDims.size() square");
            }
            std::vector<bool> seen(this->nDim_, false);
            for (const std::size_t d : errDims)
            {
                if (d >= this->nDim_ || seen[d]) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                {
                    throw std::invalid_argument(name + ": errDims must hold distinct dimensions below nDim");
                }
                if (std::ranges::find(marginalDims, d) != marginalDims.end())
                {
                    throw std::invalid_argument(name + ": errDims must not include a marginalized dimension");
                }
                seen[d] = true; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            }
            for (const auto& xi : x)
            {
                if (xi.size() != this->nDim_) { continue; }
                if (std::ranges::any_of(errDims, [&xi](const std::size_t d) -> bool
                    { return std::isnan(xi[d]); })) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                {
                    throw std::invalid_argument(name + ": every dimension in errDims must be "
                        "specified (not NaN) in every point");
                }
            }
        }

        [[nodiscard]] auto embedErrors(const std::vector<std::size_t>& errDims,
            const Eigen::MatrixXd& cov) const -> Eigen::MatrixXd
        {
            const auto n = static_cast<Eigen::Index>(this->nDim_);
            Eigen::MatrixXd full = Eigen::MatrixXd::Zero(n, n);
            for (std::size_t a = 0; a < errDims.size(); ++a)
            {
                for (std::size_t b = 0; b < errDims.size(); ++b)
                {
                    full(static_cast<Eigen::Index>(errDims[a]), static_cast<Eigen::Index>(errDims[b])) = // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                        cov(static_cast<Eigen::Index>(a), static_cast<Eigen::Index>(b));
                }
            }
            return full;
        }

        [[nodiscard]] auto search(const std::vector<double>& x,
            const std::size_t nNeighbor,
            const Bandwidth& bandwidth) const
            -> std::vector<Neighbor>
        {
            const auto& pts = data_.get();
            const std::size_t k = std::min(nNeighbor, pts.size());
            if (k == 0) { return {}; }

            const auto bound = bandwidth.boxBounder(x);
            std::vector<double> scratch;
            std::vector<std::pair<double, std::size_t>> best;
            best.reserve(k + 1);
            auto kth = [&best, k]() -> double
            {
                return best.size() < k ? std::numeric_limits<double>::infinity() : best.back().first;
            };

            std::vector<std::pair<std::size_t, double>> stack;
            stack.reserve((2 * nLevels_) + 2);
            const auto& root = nodes_[rootNode];
            stack.emplace_back(rootNode, bound.lower(nodeLo(rootNode), nodeHi(rootNode)));
            while (!stack.empty())
            {
                const auto [idx, nodeBound] = stack.back();
                stack.pop_back();
                if (nodeBound > kth()) { continue; }
                const auto& node = nodes_[idx];

                // A leaf: check each of its points, inserting any closer
                // than the current k'th neighbor into the sorted list
                if (node.splitDim_ < 0)
                {
                    for (std::size_t i = node.start_; i < node.start_ + node.count_; ++i)
                    {
                        const double r2 = bandwidth.dist2(x, pts.position(i), scratch);
                        if (r2 > kth()) { continue; }
                        const auto pos = std::lower_bound(best.begin(), best.end(), r2,
                            [](const std::pair<double, std::size_t>& entry, const double value) -> bool { return entry.first < value; });
                        best.insert(pos, {r2, i});
                        if (best.size() > k) { best.pop_back(); }
                    }
                    continue;
                }

                // An interior node: push both children, nearer one last
                // so that it is searched first
                const double lBound = bound.lower(nodeLo(node.lchild_), nodeHi(node.lchild_));
                const double rBound = bound.lower(nodeLo(node.rchild_), nodeHi(node.rchild_));
                if (lBound <= rBound)
                {
                    stack.emplace_back(node.rchild_, rBound);
                    stack.emplace_back(node.lchild_, lBound);
                }
                else
                {
                    stack.emplace_back(node.lchild_, lBound);
                    stack.emplace_back(node.rchild_, rBound);
                }
            }

            std::vector<Neighbor> result;
            result.reserve(best.size());
            for (const auto& [r2, i] : best) { result.push_back({.idx_ = i, .dist2_ = r2}); }
            return result;
        }

        template <typename Search>
        [[nodiscard]] 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>>
        {
            if (nNeighbor.size() != x.size())
            {
                throw std::invalid_argument("KDTree::neighbors: x and nNeighbor "
                    "must have the same number of elements");
            }
            std::vector<std::vector<Neighbor>> result(x.size());
            std::exception_ptr error = nullptr;
#ifdef _OPENMP
#           pragma omp parallel for schedule(dynamic)
#endif
            for (std::size_t i = 0; i < x.size(); ++i)
            {
                try
                {
                    result[i] = search(x[i], nNeighbor[i], i); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                }
                catch (...)
                {
#ifdef _OPENMP
#                   pragma omp critical(kdtreeNeighborsError)
#endif
                    {
                        if (!error) { error = std::current_exception(); }
                    }
                }
            }
            if (error) { std::rethrow_exception(error); }
            return result;
        }

        [[nodiscard]] auto chooseSplitDim(const std::size_t idx,
            const Bandwidth& bandwidth,
            const std::vector<std::size_t>& noSplitDims) const -> int
        {
            const auto lo = nodeLo(idx);
            const auto hi = nodeHi(idx);
            std::size_t best = nDim_;
            double bestSize = -1.0;
            for (std::size_t i = 0; i < nDim_; ++i)
            {
                if (std::ranges::find(noSplitDims, i) != noSplitDims.end()) { continue; }
                const double width = hi[i] - lo[i]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                double size = width * width;
                size *= bandwidth.h2Inv()(static_cast<Eigen::Index>(i), static_cast<Eigen::Index>(i)); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by <Eigen/Dense> (included above); clang-tidy's IWYU mapping doesn't know that
                if (size > bestSize)
                {
                    best = i;
                    bestSize = size;
                }
            }
            assert(best < nDim_);
            return static_cast<int>(best);
        }

        void setNodeBounds(const std::size_t idx)
        {
            const auto& node = nodes_[idx];
            const auto offset = static_cast<std::ptrdiff_t>(idx * nDim_);
            const auto len = static_cast<std::ptrdiff_t>(nDim_);
            const std::span<double> lo(nodeLo_.begin() + offset, nodeLo_.begin() + offset + len);
            const std::span<double> hi(nodeHi_.begin() + offset, nodeHi_.begin() + offset + len);
            if (node.count_ < blockedMinCount)
            {
                rangeBounds(node.start_, node.start_ + node.count_, lo, hi);
                return;
            }

            // Each block's extent, then their combination
            const std::size_t nBlocks = (node.count_ + blockSize - 1) / blockSize;
            std::vector<double> blockLo(nBlocks * nDim_);
            std::vector<double> blockHi(nBlocks * nDim_);
#ifdef _OPENMP
#           pragma omp parallel for if(!omp_in_parallel())
#endif
            for (std::size_t b = 0; b < nBlocks; ++b)
            {
                const std::size_t start = node.start_ + (b * blockSize);
                const std::size_t end = std::min(start + blockSize, node.start_ + node.count_);
                rangeBounds(start, end, std::span<double>(blockLo).subspan(b * nDim_, nDim_),
                    std::span<double>(blockHi).subspan(b * nDim_, nDim_));
            }
            std::ranges::fill(lo, std::numeric_limits<double>::infinity());
            std::ranges::fill(hi, -std::numeric_limits<double>::infinity());
            for (std::size_t b = 0; b < nBlocks; ++b)
            {
                for (std::size_t d = 0; d < nDim_; ++d)
                {
                    lo[d] = std::min(lo[d], blockLo[(b * nDim_) + d]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    hi[d] = std::max(hi[d], blockHi[(b * nDim_) + d]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                }
            }
        }

        void rangeBounds(const std::size_t start, const std::size_t end,
            const std::span<double> lo, const std::span<double> hi) const
        {
            const auto& pts = data_.get();
            std::ranges::fill(lo, std::numeric_limits<double>::infinity());
            std::ranges::fill(hi, -std::numeric_limits<double>::infinity());
            for (std::size_t i = start; i < end; ++i)
            {
                const auto pos = pts.position(i);
                for (std::size_t d = 0; d < nDim_; ++d)
                {
                    const double x = pos[d]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    lo[d] = std::min(lo[d], x); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    hi[d] = std::max(hi[d], x); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                }
            }
        }

        [[nodiscard]] auto coord(const std::size_t i, const std::size_t dim) const -> double
        {
            return data_.get().x_[(i * nDim_) + dim]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
        }

        void partitionNode(const std::size_t idx)
        {
            const auto& node = nodes_[idx];
            const auto dim = static_cast<std::size_t>(node.splitDim_);
            const std::size_t m = node.start_ + ((node.count_ - 1) >> 1);
            if (node.count_ >= blockedMinCount)
            {
                selectBlocked(node.start_, node.start_ + node.count_, m, dim);
            }
            else
            {
                selectSerial(node.start_, node.start_ + node.count_ - 1, m, dim);
            }
        }

        void selectSerial(const std::size_t first, const std::size_t last, const std::size_t m,
            const std::size_t dim)
        {
            auto& pts = data_.get();
            auto key = [this, dim](const std::size_t i) -> double { return coord(i, dim); };
            std::size_t l = first;
            std::size_t r = last;

            // Iterate until the part of the list containing the middle
            // index has been narrowed down to that index alone
            while (l < r)
            {
                std::size_t lptr = l;
                std::size_t rptr = r;
                const double splitVal = key((lptr + rptr) / 2);

                // Put points below the partition value to the left, and
                // points above it to the right
                while (true)
                {
                    while (key(lptr) < splitVal && lptr < rptr) { lptr++; }
                    while (key(rptr) > splitVal && lptr <= rptr) { rptr--; }
                    if (lptr >= rptr) { break; }
                    pts.swap(lptr, rptr);
                    lptr++;
                    rptr--;
                }

                // Make rptr the first point above the partition value
                if (key(rptr) > splitVal && lptr <= rptr) { rptr--; }
                rptr++;

                // Keep whichever side of the partition holds the middle index
                if (rptr > m) { r = rptr - 1; }
                else { l = rptr; }
            }
        }

        void selectBlocked(const std::size_t first, const std::size_t end, const std::size_t m,
            const std::size_t dim)
        {
            std::size_t l = first;
            std::size_t r = end;
            std::vector<double> sample;
            while (r - l >= blockedMinCount)
            {
                // Pivots bracketing m's rank, from a sorted sample; the
                // sample's ranks scatter by about sqrt(nSample) / 2, so
                // a gap of twice sqrt(nSample) brackets m's rank with
                // high probability
                const std::size_t n = r - l;
                const std::size_t nSample = std::min(pivotSampleSize, n);
                sample.resize(nSample);
                for (std::size_t k = 0; k < nSample; ++k)
                {
                    sample[k] = coord(l + ((k * n) / nSample), dim); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                }
                std::ranges::sort(sample);
                const auto gap = static_cast<std::size_t>(2.0 * std::sqrt(static_cast<double>(nSample)));
                const std::size_t rank = ((m - l) * nSample) / n;
                const double pivotLo = sample[rank >= gap ? rank - gap : 0]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                const double pivotHi = sample[std::min(rank + gap, nSample - 1)]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)

                // Points below pivotLo first, then those up to pivotHi;
                // keep whichever part holds m
                const std::size_t oldL = l;
                const std::size_t oldR = r;
                const std::size_t below = partitionBlocked(l, r,
                    [this, dim, pivotLo](const std::size_t i) -> bool { return coord(i, dim) < pivotLo; });
                if (m < below)
                {
                    r = below;
                }
                else
                {
                    l = below;
                    const std::size_t upTo = partitionBlocked(l, r,
                        [this, dim, pivotHi](const std::size_t i) -> bool { return coord(i, dim) <= pivotHi; });
                    if (m >= upTo)
                    {
                        l = upTo;
                    }
                    else
                    {
                        r = upTo;
                        // Every point left has coordinate pivotLo, so
                        // any order is sorted
                        if (pivotLo == pivotHi) { return; }
                    }
                }
                if (l == oldL && r == oldR) { break; }
            }
            selectSerial(l, r - 1, m, dim);
        }

        template <typename Pred>
        auto partitionSerial(const std::size_t first, const std::size_t end, const Pred& pred) -> std::size_t
        {
            auto& pts = data_.get();
            std::size_t i = first;
            std::size_t j = end;
            while (true)
            {
                while (i < j && pred(i)) { ++i; }
                while (i < j && !pred(j - 1)) { --j; }
                if (i >= j) { return i; }
                pts.swap(i, j - 1);
                ++i;
                --j;
            }
        }

        template <typename Pred>
        auto partitionBlocked(const std::size_t first, const std::size_t end, const Pred& pred) -> std::size_t
        {
            const std::size_t nBlocks = (end - first + blockSize - 1) / blockSize;
            std::vector<std::size_t> split(nBlocks);
#ifdef _OPENMP
#           pragma omp parallel for if(!omp_in_parallel())
#endif
            for (std::size_t b = 0; b < nBlocks; ++b)
            {
                const std::size_t start = first + (b * blockSize);
                split[b] = partitionSerial(start, std::min(start + blockSize, end), pred); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            }
            std::size_t mid = first;
            for (std::size_t b = 0; b < nBlocks; ++b)
            {
                mid += split[b] - (first + (b * blockSize)); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
            }

            // The out-of-place points, as runs [start, start + length)
            // in increasing order, with the number in earlier runs
            struct Run
            {
                std::size_t start_;
                std::size_t length_;
                std::size_t before_;
            };
            std::vector<Run> low;   // failing pred, before mid
            std::vector<Run> high;  // passing pred, from mid on
            std::size_t nLow = 0;
            std::size_t nHigh = 0;
            for (std::size_t b = 0; b < nBlocks; ++b)
            {
                const std::size_t start = first + (b * blockSize);
                const std::size_t stop = std::min(start + blockSize, end);
                const std::size_t s = split[b]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                if (s < mid && stop > s)
                {
                    const std::size_t length = std::min(stop, mid) - s;
                    low.push_back({.start_ = s, .length_ = length, .before_ = nLow});
                    nLow += length;
                }
                if (s > mid && s > start)
                {
                    const std::size_t runStart = std::max(start, mid);
                    high.push_back({.start_ = runStart, .length_ = s - runStart, .before_ = nHigh});
                    nHigh += s - runStart;
                }
            }
            assert(nLow == nHigh);

            // Swap the k'th out-of-place point on each side, for every k
            auto& pts = data_.get();
            const std::size_t nChunks = (nLow + blockSize - 1) / blockSize;
#ifdef _OPENMP
#           pragma omp parallel for if(!omp_in_parallel())
#endif
            for (std::size_t c = 0; c < nChunks; ++c)
            {
                const std::size_t k0 = c * blockSize;
                const std::size_t k1 = std::min(k0 + blockSize, nLow);
                auto runOf = [k0](const std::vector<Run>& runs) -> std::size_t
                {
                    const auto it = std::upper_bound(runs.begin(), runs.end(), k0,
                        [](const std::size_t k, const Run& run) -> bool { return k < run.before_; });
                    return static_cast<std::size_t>(it - runs.begin()) - 1;
                };
                std::size_t a = runOf(low);
                std::size_t h = runOf(high);
                std::size_t offA = k0 - low[a].before_; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                std::size_t offH = k0 - high[h].before_; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                for (std::size_t k = k0; k < k1; ++k)
                {
                    while (offA == low[a].length_) { ++a; offA = 0; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    while (offH == high[h].length_) { ++h; offH = 0; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    pts.swap(low[a].start_ + offA, high[h].start_ + offH); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
                    ++offA;
                    ++offH;
                }
            }
            return mid;
        }

        void splitNode(const std::size_t idx, const Bandwidth& bandwidth,
            const std::vector<std::size_t>& noSplitDims)
        {
            auto& node = nodes_[idx];
            if (node.count_ <= leafSize_)
            {
                node.splitDim_ = -1;
                node.lchild_ = nullNode;
                node.rchild_ = nullNode;
                return;
            }

            // Partition the points along the split dimension
            node.splitDim_ = chooseSplitDim(idx, bandwidth, noSplitDims);
            assert(node.splitDim_ >= 0 && static_cast<std::size_t>(node.splitDim_) < nDim_);
            partitionNode(idx);

            // Assign points to the children
            const std::size_t lIdx = left(idx);
            const std::size_t rIdx = right(idx);
            assert(rIdx < nodes_.size());
            node.lchild_ = lIdx;
            node.rchild_ = rIdx;
            auto& lNode = nodes_[lIdx];
            auto& rNode = nodes_[rIdx];
            lNode.parent_ = idx;
            rNode.parent_ = idx;
            lNode.start_ = node.start_;
            lNode.count_ = (node.count_ + 1) / 2;
            rNode.start_ = lNode.start_ + lNode.count_;
            rNode.count_ = node.count_ - lNode.count_;

            // Children's bounding boxes
            setNodeBounds(lIdx);
            setNodeBounds(rIdx);
        }

        std::size_t nDim_;
        std::reference_wrapper<Data> data_;
        std::vector<KDTreeNode> nodes_;
        std::vector<double> nodeLo_;
        std::vector<double> nodeHi_;
        std::size_t nLevels_ = 1;
        std::size_t nLeaves_ = 1;
        std::size_t leafSize_;
        Bandwidth euclidean_;
    };

} // namespace kden

#endif // KDTREE_HPP