.. _program_listing_file_src_kden_KDTree.hpp: Program Listing for File KDTree.hpp =================================== |exhale_lsh| :ref:`Return to documentation for file ` (``src/kden/KDTree.hpp``) .. |exhale_lsh| unicode:: U+021B0 .. UPWARDS ARROW WITH TIP LEFTWARDS .. code-block:: cpp #ifndef KDTREE_HPP #define KDTREE_HPP #include "Bandwidth.hpp" #include // NOLINT(misc-include-cleaner) -- provides Eigen::Index; clang-tidy's IWYU mapping doesn't know this header #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _OPENMP # include #endif namespace kden { inline constexpr std::size_t nullNode = std::numeric_limits::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 struct KDTreeAuxStorage { using View = std::span; using Owned = std::vector; }; template <> struct KDTreeAuxStorage { using View = std::monostate; using Owned = std::monostate; }; template struct KDTreeData { using Aux = AuxType; static constexpr bool hasAux = !std::is_void_v; std::size_t nDim_ = 0; std::span x_; [[no_unique_address]] typename KDTreeAuxStorage::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 { return std::span(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(i * nDim_), x_.begin() + static_cast((i + 1) * nDim_), x_.begin() + static_cast(j * nDim_)); if constexpr (hasAux) { std::swap(aux_[i], aux_[j]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } } }; template struct OwnedKDTreeData { std::size_t nDim_ = 0; std::vector x_; [[no_unique_address]] typename KDTreeAuxStorage::Owned aux_; [[nodiscard]] auto view() -> KDTreeData { KDTreeData v; v.nDim_ = nDim_; v.x_ = std::span(x_); if constexpr (KDTreeData::hasAux) { v.aux_ = std::span(aux_); } return v; } }; template concept KDTreePoints = std::derived_from>; struct Neighbor { std::size_t idx_ = 0; double dist2_ = 0.0; }; template > 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& noSplitDims = {}) : nDim_(data.nDim_), data_(std::ref(data)), leafSize_(leafSize), euclidean_(Bandwidth::identity(std::max(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 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(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& noSplitDims = {}) : KDTree(data, leafSize, Bandwidth::identity(std::max(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& { return nodes_; } [[nodiscard]] auto nodeLo(const std::size_t idx) const -> std::span { return std::span(nodeLo_).subspan(idx * nDim_, nDim_); } [[nodiscard]] auto nodeHi(const std::size_t idx) const -> std::span { return std::span(nodeHi_).subspan(idx * nDim_, nDim_); } [[nodiscard]] auto data() const -> const Data& { return data_.get(); } [[nodiscard]] auto neighbors(const std::vector& x, const std::size_t nNeighbor, const Bandwidth& bandwidth) const -> std::vector { 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& x, const std::size_t nNeighbor) const -> std::vector { return neighbors(x, nNeighbor, euclidean_); } [[nodiscard]] auto neighbors(const std::vector>& x, const std::vector& nNeighbor, const std::vector& bandwidth) const -> std::vector> { 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& xi, const std::size_t ki, const std::size_t i) -> std::vector { return neighbors(xi, ki, bandwidth[i]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) }); } [[nodiscard]] auto neighbors(const std::vector>& x, const std::vector& nNeighbor, const Bandwidth& bandwidth) const -> std::vector> { // 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& xi, const std::size_t ki, const std::size_t) -> std::vector { return neighbors(xi, ki, bw); }); } [[nodiscard]] auto neighbors(const std::vector>& x, const std::vector& nNeighbor) const -> std::vector> { return neighbors(x, nNeighbor, euclidean_); } [[nodiscard]] auto neighbors(const std::vector>& x, const std::vector& nNeighbor, const std::vector& errDims, const std::vector& errCov, // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by (included above); clang-tidy's IWYU mapping doesn't know that const Bandwidth& bandwidth) const -> std::vector> { checkErrors(x, errDims, errCov, {}, "KDTree::neighbors"); const Bandwidth bw = sharedReduction(x, bandwidth); return batchNeighbors(x, nNeighbor, [this, &bw, &errDims, &errCov](const std::vector& xi, const std::size_t ki, const std::size_t i) -> std::vector { 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>& 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 pattern = Bandwidth::nanPattern(x.front()); const bool shared = std::ranges::all_of(x, [this, &pattern](const std::vector& xi) -> bool { return xi.size() == this->nDim_ && Bandwidth::nanPattern(xi) == pattern; }); return shared ? bandwidth.reduce(pattern) : bandwidth; } void checkErrors(const std::vector>& x, const std::vector& errDims, const std::vector& errCov, const std::vector& 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(errDims.size()); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by (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 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& errDims, const Eigen::MatrixXd& cov) const -> Eigen::MatrixXd { const auto n = static_cast(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(errDims[a]), static_cast(errDims[b])) = // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) cov(static_cast(a), static_cast(b)); } } return full; } [[nodiscard]] auto search(const std::vector& x, const std::size_t nNeighbor, const Bandwidth& bandwidth) const -> std::vector { 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 scratch; std::vector> best; best.reserve(k + 1); auto kth = [&best, k]() -> double { return best.size() < k ? std::numeric_limits::infinity() : best.back().first; }; std::vector> 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& 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 result; result.reserve(best.size()); for (const auto& [r2, i] : best) { result.push_back({.idx_ = i, .dist2_ = r2}); } return result; } template [[nodiscard]] auto batchNeighbors(const std::vector>& x, const std::vector& nNeighbor, const Search& search) const -> std::vector> { if (nNeighbor.size() != x.size()) { throw std::invalid_argument("KDTree::neighbors: x and nNeighbor " "must have the same number of elements"); } std::vector> 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& 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(i), static_cast(i)); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by (included above); clang-tidy's IWYU mapping doesn't know that if (size > bestSize) { best = i; bestSize = size; } } assert(best < nDim_); return static_cast(best); } void setNodeBounds(const std::size_t idx) { const auto& node = nodes_[idx]; const auto offset = static_cast(idx * nDim_); const auto len = static_cast(nDim_); const std::span lo(nodeLo_.begin() + offset, nodeLo_.begin() + offset + len); const std::span 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 blockLo(nBlocks * nDim_); std::vector 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(blockLo).subspan(b * nDim_, nDim_), std::span(blockHi).subspan(b * nDim_, nDim_)); } std::ranges::fill(lo, std::numeric_limits::infinity()); std::ranges::fill(hi, -std::numeric_limits::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 lo, const std::span hi) const { const auto& pts = data_.get(); std::ranges::fill(lo, std::numeric_limits::infinity()); std::ranges::fill(hi, -std::numeric_limits::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(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 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(2.0 * std::sqrt(static_cast(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 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 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 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 low; // failing pred, before mid std::vector 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& 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(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& 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(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_; std::vector nodes_; std::vector nodeLo_; std::vector nodeHi_; std::size_t nLevels_ = 1; std::size_t nLeaves_ = 1; std::size_t leafSize_; Bandwidth euclidean_; }; } // namespace kden #endif // KDTREE_HPP