Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
kdtree.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2025 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Matteo Caldana <matteo.caldana@polimi.it>
22
23#ifndef VULPES_DATASTRUCTURE_KDTREE_HPP_
24#define VULPES_DATASTRUCTURE_KDTREE_HPP_
25
26#include <algorithm>
27#include <array>
28#include <cassert>
29#include <cstdint>
30#include <limits>
31#include <numeric>
32#include <utility>
33#include <vector>
34
35#include <Eigen/Core>
36
38
39namespace vulpes {
40namespace datastructure {
41
71template <int64_t Dim>
72class KDTree {
73 public:
82 explicit KDTree(const std::vector<std::array<double, Dim>>& data)
83 : m_indices(data.size()), m_raw_data_size(data.size() * Dim) {
84 std::iota(m_indices.begin(), m_indices.end(), 0);
85 for (const auto& pt : data) {
86 for (double v : pt) {
87 m_data.push_back(v);
88 }
89 }
90 // during the pushback the pointer changes, we cannot initialize it before
91 // NOLINTBEGIN(cppcoreguidelines-prefer-member-initializer)
92 m_raw_data = m_data.data();
93 // NOLINTEND(cppcoreguidelines-prefer-member-initializer)
94 }
95
106 explicit KDTree(const double* data, int64_t size)
107 : m_indices(size / Dim), m_raw_data(data), m_raw_data_size(size) {
108 assert(size % Dim == 0);
109 std::iota(m_indices.begin(), m_indices.end(), 0);
110 }
111
123 explicit KDTree(const double* data, const std::vector<int64_t>& indices)
124 : m_indices(indices),
125 m_raw_data(data),
126 m_raw_data_size(m_indices.size() * Dim) {}
127
142 void build(int64_t leafsize, bool median, bool compact) {
143 m_leafsize = leafsize;
144 m_tree.raw_boxsize_data = nullptr;
145 buildRun(median, compact);
146 }
147
165 void build(
166 const std::array<double, 2 * Dim>& boxsize,
167 int64_t leafsize,
168 bool median,
169 bool compact) {
170 m_leafsize = leafsize;
171 m_boxsize = boxsize;
172 m_tree.raw_boxsize_data = m_boxsize.data();
173 buildRun(median, compact);
174 }
175
195 template <double PNorm, bool Periodic = false>
196 std::pair<Eigen::MatrixXd, Eigen::Matrix<int64_t, -1, -1>> queryKnn(
197 const double* points,
198 int64_t n_points,
199 int64_t k,
200 double eps = 0,
201 double distance_upper_bound = std::numeric_limits<double>::max()) const {
202 assert(m_is_built);
203 // each column is a point
204 Eigen::MatrixXd distances(k, n_points);
205 Eigen::Matrix<int64_t, -1, -1> indices(k, n_points);
206
207 std::vector<int64_t> ks(k);
208 std::iota(ks.begin(), ks.end(), 1);
209
211 &m_tree, distances.data(), indices.data(), points, n_points, ks.data(),
212 k, k, eps, distance_upper_bound);
213
214 return {distances, indices};
215 }
216
233 template <double PNorm, bool Periodic = false>
234 std::pair<Eigen::MatrixXd, Eigen::Matrix<int64_t, -1, -1>> queryKnn(
235 const std::vector<std::array<double, Dim>>& points,
236 int64_t k,
237 double eps = 0,
238 double distance_upper_bound = std::numeric_limits<double>::max()) const {
239 assert(m_is_built);
241 &points[0][0], points.size(), k, eps, distance_upper_bound);
242 }
243
261 template <double PNorm, bool Periodic = false>
262 std::vector<std::vector<scipy::ckdtree_intp_t>> queryBall(
263 const double* points,
264 const double* radiuses,
265 int64_t n_queries,
266 double eps = 0.0,
267 bool return_length = false,
268 bool sort_output = true) const {
269 assert(m_is_built);
270 std::vector<std::vector<scipy::ckdtree_intp_t>> results(n_queries);
272 &m_tree, points, radiuses, eps, n_queries, results.data(),
273 return_length, sort_output);
274 return results;
275 }
276
293 template <double PNorm, bool Periodic = false>
294 std::vector<std::vector<scipy::ckdtree_intp_t>> queryBall(
295 const std::vector<std::array<double, Dim>>& points,
296 const std::vector<double>& radiuses,
297 double eps = 0.0,
298 bool return_length = false,
299 bool sort_output = true) const {
300 assert(m_is_built);
301 assert(points.size() == radiuses.size());
302 std::vector<std::vector<scipy::ckdtree_intp_t>> results(points.size());
304 &m_tree, &points[0][0], radiuses.data(), eps, points.size(),
305 results.data(), return_length, sort_output);
306 return results;
307 }
308
322 template <double PNorm, bool Periodic = false>
323 std::vector<scipy::ordered_pair> queryPairs(
324 double r, double eps = 0.0) const {
325 assert(m_is_built);
326 std::vector<scipy::ordered_pair> result;
328 return result;
329 }
330
346 template <double PNorm, bool Periodic = false>
347 std::vector<std::vector<scipy::ckdtree_intp_t>> queryBallTree(
348 const KDTree<Dim>& other, double r, double eps = 0.0) const {
349 assert(m_is_built);
350 std::vector<std::vector<scipy::ckdtree_intp_t>> result(m_tree.n);
352 &m_tree, &other.m_tree, r, eps, result.data());
353 return result;
354 }
355
356 protected:
368 void buildRun(bool median, bool compact) {
369 double maxs[Dim];
370 double mins[Dim];
371
372 m_tree.raw_data = m_raw_data;
373 m_tree.tree_buffer = &m_tree_buffer;
374 m_tree.leafsize = m_leafsize;
375 m_tree.n = m_raw_data_size / Dim;
376 m_tree.raw_maxes = maxs;
377 m_tree.raw_mins = mins;
378 m_tree.raw_indices = m_indices.data();
380 &m_tree, 0, m_tree.n, m_tree.raw_maxes, m_tree.raw_mins, median,
381 compact);
382 m_tree.ctree = m_tree_buffer.data();
383
385 m_tree.raw_maxes = m_maxs.data();
386 m_tree.raw_mins = m_mins.data();
387 postInitTraverse(m_tree.ctree, m_tree.ctree);
388 m_is_built = true;
389 }
390
404 if (node->split_dim == -1) {
405 node->less = nullptr;
406 node->greater = nullptr;
407 } else {
408 // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
409 using int_t = scipy::ckdtree_intp_t;
410 node->less = root + reinterpret_cast<int_t>(node->less);
411 node->greater = root + reinterpret_cast<int_t>(node->greater);
412 // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
413 postInitTraverse(root, node->less);
414 postInitTraverse(root, node->greater);
415 }
416 }
417
425 if (m_raw_data_size) {
426 for (int64_t i = 0; i < Dim; ++i) {
427 m_maxs[i] = m_raw_data[i];
428 m_mins[i] = m_raw_data[i];
429 }
430 const int64_t size = m_raw_data_size / Dim;
431 for (int64_t i = 1; i < size; ++i) {
432 for (int64_t d = 0; d < Dim; ++d) {
433 m_maxs[d] = std::max(m_maxs[d], m_raw_data[i * Dim + d]);
434 m_mins[d] = std::min(m_mins[d], m_raw_data[i * Dim + d]);
435 }
436 }
437 }
438 }
439
440 // The Kd-tree has been built
441 bool m_is_built = false;
442 // The maximum number of points allowed in a leaf node.
443 int64_t m_leafsize = -1;
444 // Buffer for storing the tree nodes.
445 std::vector<scipy::ckdtreenode> m_tree_buffer;
446 // Internal storage of the data points, is empty if we do not own the data.
447 std::vector<double> m_data;
448 // Indices of the data points.
449 std::vector<int64_t> m_indices;
450 // Pointer to raw data array (external or internal).
451 const double* m_raw_data = nullptr;
452 // The size of the raw data array (number of doubles).
453 int64_t m_raw_data_size = 0;
454
455 // Maximum values in each dimension.
456 std::array<double, Dim> m_maxs{{-std::numeric_limits<double>::max()}};
457 // Minimum values in each dimension.
458 std::array<double, Dim> m_mins{{std::numeric_limits<double>::max()}};
459 // Bounding box size for periodic boundary conditions.
460 std::array<double, 2 * Dim> m_boxsize = {0};
461 // The underlying SciPy KDTree structure.
463};
464
465} // namespace datastructure
466} // namespace vulpes
467
468#endif // VULPES_DATASTRUCTURE_KDTREE_HPP_
int64_t m_raw_data_size
Definition kdtree.hpp:453
std::pair< Eigen::MatrixXd, Eigen::Matrix< int64_t, -1, -1 > > queryKnn(const std::vector< std::array< double, Dim > > &points, int64_t k, double eps=0, double distance_upper_bound=std::numeric_limits< double >::max()) const
Queries the KDTree for k-nearest neighbors (KNN) of a set of points.
Definition kdtree.hpp:234
std::vector< scipy::ordered_pair > queryPairs(double r, double eps=0.0) const
Finds all pairs of points whose distance is within a given radius.
Definition kdtree.hpp:323
scipy::ckdtree< Dim > m_tree
Definition kdtree.hpp:462
void build(int64_t leafsize, bool median, bool compact)
Builds the KDTree.
Definition kdtree.hpp:142
void buildRun(bool median, bool compact)
Internal function to build the KDTree.
Definition kdtree.hpp:368
KDTree(const std::vector< std::array< double, Dim > > &data)
Constructs a KDTree from a vector of data points.
Definition kdtree.hpp:82
void compututeBounds()
Computes the bounding box (max and min values) for the data points.
Definition kdtree.hpp:424
std::vector< scipy::ckdtreenode > m_tree_buffer
Definition kdtree.hpp:445
std::vector< std::vector< scipy::ckdtree_intp_t > > queryBall(const std::vector< std::array< double, Dim > > &points, const std::vector< double > &radiuses, double eps=0.0, bool return_length=false, bool sort_output=true) const
Queries the KDTree for all points within a given radius of a set of input points.
Definition kdtree.hpp:294
const double * m_raw_data
Definition kdtree.hpp:451
KDTree(const double *data, int64_t size)
Constructs a KDTree using a raw pointer to the data.
Definition kdtree.hpp:106
bool m_is_built
Definition kdtree.hpp:441
std::vector< int64_t > m_indices
Definition kdtree.hpp:449
void build(const std::array< double, 2 *Dim > &boxsize, int64_t leafsize, bool median, bool compact)
Builds the KDTree with specified bounding box sizes.
Definition kdtree.hpp:165
std::vector< double > m_data
Definition kdtree.hpp:447
std::pair< Eigen::MatrixXd, Eigen::Matrix< int64_t, -1, -1 > > queryKnn(const double *points, int64_t n_points, int64_t k, double eps=0, double distance_upper_bound=std::numeric_limits< double >::max()) const
Queries the KDTree for k-nearest neighbors (KNN) of a set of points.
Definition kdtree.hpp:196
std::array< double, 2 *Dim > m_boxsize
Definition kdtree.hpp:460
std::array< double, Dim > m_mins
Definition kdtree.hpp:458
KDTree(const double *data, const std::vector< int64_t > &indices)
Constructs a KDTree using a raw pointer to the data.
Definition kdtree.hpp:123
std::vector< std::vector< scipy::ckdtree_intp_t > > queryBall(const double *points, const double *radiuses, int64_t n_queries, double eps=0.0, bool return_length=false, bool sort_output=true) const
Queries the KDTree for all points within a given radius of a set of input points.
Definition kdtree.hpp:262
std::vector< std::vector< scipy::ckdtree_intp_t > > queryBallTree(const KDTree< Dim > &other, double r, double eps=0.0) const
Finds all points within a given radius from another KDTree.
Definition kdtree.hpp:347
int64_t m_leafsize
Definition kdtree.hpp:443
void postInitTraverse(scipy::ckdtreenode *root, scipy::ckdtreenode *node)
Performs post-initialization traversal of the tree to adjust node pointers.
Definition kdtree.hpp:403
std::array< double, Dim > m_maxs
Definition kdtree.hpp:456
Definition crs_map.hpp:36
static ckdtree_intp_t build_ckdtree(ckdtree< Dim > *self, ckdtree_intp_t start_idx, intptr_t end_idx, double *maxes, double *mins, const int _median, const int _compact)
Definition ckdtree_decl.hpp:141
int query_ball_point(const ckdtree< Dim > *self, const double *x, const double *r, const double eps, const ckdtree_intp_t n_queries, std::vector< ckdtree_intp_t > *results, const bool return_length, const bool sort_output)
Definition ckdtree_decl.hpp:1699
int query_ball_tree(const ckdtree< Dim > *self, const ckdtree< Dim > *other, const double r, const double eps, std::vector< ckdtree_intp_t > *results)
Definition ckdtree_decl.hpp:2151
intptr_t ckdtree_intp_t
Definition ckdtree_decl.hpp:82
int query_knn(const ckdtree< Dim > *self, double *dd, ckdtree_intp_t *ii, const double *xx, const ckdtree_intp_t n, const ckdtree_intp_t *k, const ckdtree_intp_t nk, const ckdtree_intp_t kmax, const double eps, const double distance_upper_bound)
Definition ckdtree_decl.hpp:1545
int query_pairs(const ckdtree< Dim > *self, const double r, const double eps, std::vector< ordered_pair > *results)
Definition ckdtree_decl.hpp:1944
Definition cell_manager.hpp:38
Definition ckdtree_decl.hpp:123
Definition ckdtree_decl.hpp:112
ckdtree_intp_t split_dim
Definition ckdtree_decl.hpp:113
ckdtreenode * greater
Definition ckdtree_decl.hpp:119
ckdtreenode * less
Definition ckdtree_decl.hpp:118