Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
ckdtree_decl.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 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_CKDTREE_CKDTREE_DECL_HPP_
24#define VULPES_DATASTRUCTURE_CKDTREE_CKDTREE_DECL_HPP_
25
26// NOLINTBEGIN
27
28// code is **very heavily** inspired by scipy, whose BSD-3-Clause licence and
29// copyright notice are in the LICENSE file of this folder
30// see:
31// https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html
32// https://github.com/scipy/scipy/tree/main/scipy/spatial/ckdtree/src
33
34// 2024-09-19, commit 431dcf3
35
36// Most notable differences:
37// - the space dimension is specified as a template parameter
38// - `_less`, `_greater` are removed from `ckdtreenode` to save space
39// - `p` norm and periodic bounding box are passed as template parameters
40
41#include <algorithm>
42#include <cassert>
43#include <cmath>
44#include <cstdint>
45#include <cstdlib>
46#include <cstring>
47#include <ios>
48#include <limits>
49#include <new>
50#include <numeric>
51#include <sstream>
52#include <stdexcept>
53#include <string>
54#include <typeinfo>
55#include <vector>
56
57#define tree_buffer_root(buf) (&(buf)[0][0])
58#define CKDTREE_LIKELY(x) __builtin_expect(!!(x), 1)
59#define CKDTREE_UNLIKELY(x) __builtin_expect(!!(x), 0)
60#ifdef HAVE___BUILTIN_PREFETCH
61/* unlike _mm_prefetch also works on non-x86 */
62#define CKDTREE_PREFETCH(x, rw, loc) __builtin_prefetch((x), (rw), (loc))
63#else
64#ifdef HAVE__MM_PREFETCH
65/* _MM_HINT_ET[01] (rw = 1) unsupported, only available in gcc >= 4.9 */
66#define CKDTREE_PREFETCH(x, rw, loc) \
67 _mm_prefetch( \
68 (x), loc == 0 ? _MM_HINT_NTA \
69 : (loc == 1 ? _MM_HINT_T2 \
70 : (loc == 2 ? _MM_HINT_T1 \
71 : (loc == 3 ? _MM_HINT_T0 : -1))))
72#else
73#define CKDTREE_PREFETCH(x, rw, loc)
74#endif
75#endif
76#define ckdtree_fmax(x, y) std::max(x, y)
77#define ckdtree_fmin(x, y) std::min(x, y)
78#define ckdtree_fabs(x) std::abs(x)
79
80namespace vulpes {
81namespace scipy {
82using ckdtree_intp_t = intptr_t;
83
89
93
94 bool operator==(const ordered_pair& other) const {
95 return (i == other.i) && (j == other.j);
96 }
97};
98
99inline void add_ordered_pair(
100 std::vector<ordered_pair>* results,
101 const ckdtree_intp_t i,
102 const ckdtree_intp_t j) {
103 if (i > j) {
104 ordered_pair p = {j, i};
105 results->push_back(p);
106 } else {
107 ordered_pair p = {i, j};
108 results->push_back(p);
109 }
110}
111
121
122template <ckdtree_intp_t Dim>
123struct ckdtree {
124 static constexpr ckdtree_intp_t m = Dim;
125 // tree structure
126 std::vector<ckdtreenode>* tree_buffer;
128 // meta data
129 const double* raw_data;
132 double* raw_maxes;
133 double* raw_mins;
136};
137
138/* Build methods in C++ for better speed and GIL release */
139
140template <ckdtree_intp_t Dim>
142 ckdtree<Dim>* self,
143 ckdtree_intp_t start_idx,
144 intptr_t end_idx,
145 double* maxes,
146 double* mins,
147 const int _median,
148 const int _compact) {
149 constexpr ckdtree_intp_t m = self->m;
150 const double* data = self->raw_data;
151 ckdtree_intp_t* indices = reinterpret_cast<intptr_t*>(self->raw_indices);
152
153 ckdtreenode new_node = {}, *n, *root;
154 ckdtree_intp_t node_index, less, greater;
155 ckdtree_intp_t i, j, p, d;
156 double size, split, minval, maxval;
157
158 /* put a new node into the node stack */
159 self->tree_buffer->push_back(new_node);
160 node_index = self->tree_buffer->size() - 1;
161 root = tree_buffer_root(self->tree_buffer);
162 n = root + node_index;
163 memset(n, 0, sizeof(n[0]));
164
165 n->start_idx = start_idx;
166 n->end_idx = end_idx;
167 n->children = end_idx - start_idx;
168
169 if (end_idx - start_idx <= self->leafsize) {
170 /* below brute force limit, return leafnode */
171 n->split_dim = -1;
172 return node_index;
173 } else {
174 if (_compact) {
175 /* Recompute hyperrectangle bounds. This should lead to a more
176 * compact kd-tree but comes at the expense of larger construction
177 * time. However, construction time is usually dwarfed by the
178 * query time by orders of magnitude.
179 */
180 const double* tmp_data_point;
181 tmp_data_point = data + indices[start_idx] * m;
182 for (i = 0; i < m; ++i) {
183 maxes[i] = tmp_data_point[i];
184 mins[i] = tmp_data_point[i];
185 }
186 for (j = start_idx + 1; j < end_idx; ++j) {
187 tmp_data_point = data + indices[j] * m;
188 for (i = 0; i < m; ++i) {
189 double tmp = tmp_data_point[i];
190 maxes[i] = maxes[i] > tmp ? maxes[i] : tmp;
191 mins[i] = mins[i] < tmp ? mins[i] : tmp;
192 }
193 }
194 }
195
196 /* split on the dimension with largest spread */
197 d = 0;
198 size = 0;
199 for (i = 0; i < m; ++i) {
200 if (maxes[i] - mins[i] > size) {
201 d = i;
202 size = maxes[i] - mins[i];
203 }
204 }
205 maxval = maxes[d];
206 minval = mins[d];
207 if (maxval == minval) {
208 /* all points are identical; warn user?
209 * return leafnode
210 */
211 n->split_dim = -1;
212 return node_index;
213 }
214
215 /* construct new inner node */
216 auto index_compare = [=](ckdtree_intp_t a, ckdtree_intp_t b) {
217 const double point_a = data[a * m + d];
218 const double point_b = data[b * m + d];
219 return point_a < point_b;
220 };
221
222 auto partition_pivot = [=](ckdtree_intp_t* first, ckdtree_intp_t* last,
223 double pivot) {
224 const auto partition_ptr = std::partition(
225 first, last,
226 [&](ckdtree_intp_t a) { return !(data[a * m + d] >= pivot); });
227 return partition_ptr - indices;
228 };
229
230 if (_median) {
231 /* split on median to create a balanced tree
232 * adopted from scikit-learn
233 */
234 const auto n_points = end_idx - start_idx;
235 auto* node_indices = indices + start_idx;
236 auto mid = node_indices + n_points / 2;
237 std::nth_element(
238 node_indices, mid, node_indices + n_points, index_compare);
239
240 split = data[*mid * m + d];
241 p = partition_pivot(node_indices, mid, split);
242 } else {
243 /* split with the sliding midpoint rule */
244 split = (maxval + minval) / 2;
245
246 p = partition_pivot(indices + start_idx, indices + end_idx, split);
247 }
248
249 /* slide midpoint if necessary */
250 if (p == start_idx) {
251 /* no points less than split */
252 auto min_idx = *std::min_element(
253 indices + start_idx, indices + end_idx, index_compare);
254 split = std::nextafter(data[min_idx * m + d], HUGE_VAL);
255 p = partition_pivot(indices + start_idx, indices + end_idx, split);
256 } else if (p == end_idx) {
257 /* no points greater than split */
258 auto max_idx = *std::max_element(
259 indices + start_idx, indices + end_idx, index_compare);
260 split = data[max_idx * m + d];
261 p = partition_pivot(indices + start_idx, indices + end_idx, split);
262 }
263
264 if (p == start_idx || p == end_idx) {
265 // All children are equal in this dimension, try again with new bounds
266 assert(!_compact);
267 self->tree_buffer->pop_back();
268 std::array<double, 2 * m> tmp_bounds = {0};
269 double* tmp_mins = &tmp_bounds[0];
270 std::copy_n(mins, m, tmp_mins);
271 double* tmp_maxes = &tmp_bounds[m];
272 std::copy_n(maxes, m, tmp_maxes);
273
274 const auto fixed_val = data[indices[start_idx] * m + d];
275 tmp_mins[d] = fixed_val;
276 tmp_maxes[d] = fixed_val;
277
278 return build_ckdtree<Dim>(
279 self, start_idx, end_idx, tmp_maxes, tmp_mins, _median, _compact);
280 }
281
282 if (_compact) {
283 less = build_ckdtree(self, start_idx, p, maxes, mins, _median, _compact);
284 greater = build_ckdtree(self, p, end_idx, maxes, mins, _median, _compact);
285 } else {
286 std::array<double, m> tmp = {0};
287 double* mids = &tmp[0];
288
289 for (i = 0; i < m; ++i) {
290 mids[i] = maxes[i];
291 }
292 mids[d] = split;
293 less = build_ckdtree(self, start_idx, p, mids, mins, _median, _compact);
294
295 for (i = 0; i < m; ++i) {
296 mids[i] = mins[i];
297 }
298 mids[d] = split;
299 greater = build_ckdtree(self, p, end_idx, maxes, mids, _median, _compact);
300 }
301
302 /* recompute n because std::vector can
303 * reallocate its internal buffer
304 */
305 root = tree_buffer_root(self->tree_buffer);
306 n = root + node_index;
307 /* fill in entries */
308 n->less = reinterpret_cast<decltype(n->less)>(less);
309 n->greater = reinterpret_cast<decltype(n->greater)>(greater);
310 n->split_dim = d;
311 n->split = split;
312
313 return node_index;
314 }
315}
316
317/* Interval arithmetic
318 * ===================
319 */
320
321template <ckdtree_intp_t m>
322struct Rectangle {
323 /* the last const is to allow const Rectangle to use these functions;
324 * also notice we had to mark buf mutable to avoid writing non const version
325 * of the same accessors. */
326 double* maxes() const { return &buf[0]; }
327 double* mins() const { return &buf[0] + m; }
328
329 Rectangle(const double* _mins, const double* _maxes) {
330 /* copy array data */
331 /* FIXME: use std::vector ? */
332 std::memcpy(
333 reinterpret_cast<void*>(mins()), reinterpret_cast<const void*>(_mins),
334 m * sizeof(double));
335 std::memcpy(
336 reinterpret_cast<void*>(maxes()), reinterpret_cast<const void*>(_maxes),
337 m * sizeof(double));
338 };
339
340 private:
341 mutable std::array<double, 2 * m> buf;
342};
343
344/*
345 * Rectangle-to-rectangle distance tracker
346 * =======================================
347 *
348 * The logical unit that repeats over and over is to keep track of the
349 * maximum and minimum distances between points in two hyperrectangles
350 * as these rectangles are successively split.
351 *
352 * Example
353 * -------
354 * node1 encloses points in rect1, node2 encloses those in rect2
355 *
356 * cdef RectRectDistanceTracker dist_tracker
357 * dist_tracker = RectRectDistanceTracker(rect1, rect2, p)
358 *
359 * ...
360 *
361 * if dist_tracker.min_distance < ...:
362 * ...
363 *
364 * dist_tracker.push_less_of(1, node1)
365 * do_something(node1.less, dist_tracker)
366 * dist_tracker.pop()
367 *
368 * dist_tracker.push_greater_of(1, node1)
369 * do_something(node1.greater, dist_tracker)
370 * dist_tracker.pop()
371 *
372 * Notice that Point is just a reduced case of Rectangle where
373 * mins == maxes.
374 *
375 */
376
385
388
389template <typename MinMaxDist, ckdtree_intp_t Dim>
394 double p;
395 double epsfac;
399
402 std::vector<RR_stack_item> stack_arr;
404
405 /* if min/max distance / adjustment is less than this,
406 * we believe the incremental tracking is inaccurate */
408
409 void _resize_stack(const ckdtree_intp_t new_max_size) {
410 stack_arr.resize(new_max_size);
411 stack = &stack_arr[0];
412 stack_max_size = new_max_size;
413 };
414
416 const ckdtree<Dim>* _tree,
417 const Rectangle<Dim>& _rect1,
418 const Rectangle<Dim>& _rect2,
419 const double _p,
420 const double eps,
421 const double _upper_bound)
422 : tree(_tree), rect1(_rect1), rect2(_rect2), stack_arr(8) {
423 p = _p;
424
425 /* internally we represent all distances as distance ** p */
426 if (CKDTREE_LIKELY(p == 2.0)) {
427 upper_bound = _upper_bound * _upper_bound;
428 } else if ((!std::isinf(p)) && (!std::isinf(_upper_bound))) {
429 upper_bound = std::pow(_upper_bound, p);
430 } else {
431 upper_bound = _upper_bound;
432 }
433
434 /* fiddle approximation factor */
435 if (CKDTREE_LIKELY(p == 2.0)) {
436 double tmp = 1. + eps;
437 epsfac = 1. / (tmp * tmp);
438 } else if (eps == 0.) {
439 epsfac = 1.;
440 } else if (std::isinf(p)) {
441 epsfac = 1. / (1. + eps);
442 } else {
443 epsfac = 1. / std::pow((1. + eps), p);
444 }
445
446 stack = &stack_arr[0];
447 stack_max_size = 8;
448 stack_size = 0;
449
450 /* Compute initial min and max distances */
451 MinMaxDist::rect_rect_p(
453 if (std::isinf(max_distance)) {
454 const char* msg =
455 "Encountering floating point overflow. "
456 "The value of p too large for this dataset; "
457 "For such large p, consider using the special case p=np.inf . ";
458 throw std::invalid_argument(msg); // raises ValueError
459 }
461 };
462
463 void push(
464 const ckdtree_intp_t which,
465 const intptr_t direction,
466 const ckdtree_intp_t split_dim,
467 const double split_val) {
468 const double p = this->p;
469 /* subnomial is 1 if round-off is expected to taint the incremental distance
470 * tracking. in that case we always recompute the distances. Recomputing
471 * costs more calls to pow, thus if the round-off error does not seem to
472 * wipe out the value, then we still do the incremental update.
473 * */
474 int subnomial = 0;
475
476 Rectangle<Dim>* rect;
477 if (which == 1) {
478 rect = &rect1;
479 } else {
480 rect = &rect2;
481 }
482
483 /* push onto stack */
484 if (stack_size == stack_max_size) {
486 }
487
489 ++stack_size;
490 item->which = which;
491 item->split_dim = split_dim;
494 item->min_along_dim = rect->mins()[split_dim];
495 item->max_along_dim = rect->maxes()[split_dim];
496
497 /* update min/max distances */
498 double min1, max1;
499 double min2, max2;
500
501 MinMaxDist::interval_interval_p(
502 tree, rect1, rect2, split_dim, p, &min1, &max1);
503
504 if (direction == LESS) {
505 rect->maxes()[split_dim] = split_val;
506 } else {
507 rect->mins()[split_dim] = split_val;
508 }
509
510 MinMaxDist::interval_interval_p(
511 tree, rect1, rect2, split_dim, p, &min2, &max2);
512
513 subnomial = subnomial || (min_distance < inaccurate_distance_limit ||
515
516 subnomial = subnomial || ((min1 != 0 && min1 < inaccurate_distance_limit) ||
518 subnomial = subnomial || ((min2 != 0 && min2 < inaccurate_distance_limit) ||
520 subnomial = subnomial || (min_distance < inaccurate_distance_limit ||
522
523 if (CKDTREE_UNLIKELY(subnomial)) {
524 MinMaxDist::rect_rect_p(
526 } else {
527 min_distance += (min2 - min1);
528 max_distance += (max2 - max1);
529 }
530 };
531
532 inline void push_less_of(
533 const ckdtree_intp_t which, const ckdtreenode* node) {
534 push(which, LESS, node->split_dim, node->split);
535 };
536
537 inline void push_greater_of(
538 const ckdtree_intp_t which, const ckdtreenode* node) {
539 push(which, GREATER, node->split_dim, node->split);
540 };
541
542 inline void pop() {
543 /* pop from stack */
544 --stack_size;
545
546 /* assert stack_size >= 0 */
547 if (CKDTREE_UNLIKELY(stack_size < 0)) {
548 const char* msg = "Bad stack size. This error should never occur.";
549 throw std::logic_error(msg);
550 }
551
555
556 if (item->which == 1) {
557 rect1.mins()[item->split_dim] = item->min_along_dim;
558 rect1.maxes()[item->split_dim] = item->max_along_dim;
559 } else {
560 rect2.mins()[item->split_dim] = item->min_along_dim;
561 rect2.maxes()[item->split_dim] = item->max_along_dim;
562 }
563 };
564};
565
566template <typename Dist1D, ckdtree_intp_t Dim>
568 /* 1-d pieces
569 * These should only be used if p != infinity
570 */
571
572 static inline void interval_interval_p(
573 const ckdtree<Dim>* tree,
574 const Rectangle<Dim>& rect1,
575 const Rectangle<Dim>& rect2,
576 const ckdtree_intp_t k,
577 const double p,
578 double* min,
579 double* max) {
580 /* Compute the minimum/maximum distance along dimension k between points in
581 * two hyperrectangles.
582 */
583 Dist1D::interval_interval(tree, rect1, rect2, k, min, max);
584 *min = std::pow(*min, p);
585 *max = std::pow(*max, p);
586 }
587
588 static inline void rect_rect_p(
589 const ckdtree<Dim>* tree,
590 const Rectangle<Dim>& rect1,
591 const Rectangle<Dim>& rect2,
592 const double p,
593 double* min,
594 double* max) {
595 *min = 0.;
596 *max = 0.;
597 for (ckdtree_intp_t i = 0; i < Dim; ++i) {
598 double min_, max_;
599
600 Dist1D::interval_interval(tree, rect1, rect2, i, &min_, &max_);
601
602 *min += std::pow(min_, p);
603 *max += std::pow(max_, p);
604 }
605 }
606
607 static inline double point_point_p(
608 const ckdtree<Dim>* tree,
609 const double* x,
610 const double* y,
611 const double p,
612 const ckdtree_intp_t k,
613 const double upperbound) {
614 /*
615 * Compute the distance between x and y
616 *
617 * Computes the Minkowski p-distance to the power p between two points.
618 * If the distance**p is larger than upperbound, then any number larger
619 * than upperbound may be returned (the calculation is truncated).
620 */
621
623 double r, r1;
624 r = 0;
625 for (i = 0; i < k; ++i) {
626 r1 = Dist1D::point_point(tree, x, y, i);
627 r += std::pow(r1, p);
628 if (r > upperbound) {
629 return r;
630 }
631 }
632 return r;
633 }
634
635 static inline double distance_p(const double s, const double p) {
636 return std::pow(s, p);
637 }
638};
639
640template <typename Dist1D, ckdtree_intp_t Dim>
641struct BaseMinkowskiDistP1 : public BaseMinkowskiDistPp<Dist1D, Dim> {
642 static inline void interval_interval_p(
643 const ckdtree<Dim>* tree,
644 const Rectangle<Dim>& rect1,
645 const Rectangle<Dim>& rect2,
646 const ckdtree_intp_t k,
647 const double p,
648 double* min,
649 double* max) {
650 /* Compute the minimum/maximum distance along dimension k between points in
651 * two hyperrectangles.
652 */
653 Dist1D::interval_interval(tree, rect1, rect2, k, min, max);
654 }
655
656 static inline void rect_rect_p(
657 const ckdtree<Dim>* tree,
658 const Rectangle<Dim>& rect1,
659 const Rectangle<Dim>& rect2,
660 const double p,
661 double* min,
662 double* max) {
663 *min = 0.;
664 *max = 0.;
665 for (ckdtree_intp_t i = 0; i < Dim; ++i) {
666 double min_, max_;
667
668 Dist1D::interval_interval(tree, rect1, rect2, i, &min_, &max_);
669
670 *min += min_;
671 *max += max_;
672 }
673 }
674
675 static inline double point_point_p(
676 const ckdtree<Dim>* tree,
677 const double* x,
678 const double* y,
679 const double,
680 const ckdtree_intp_t k,
681 const double upperbound) {
683 double r;
684 r = 0;
685 for (i = 0; i < k; ++i) {
686 r += Dist1D::point_point(tree, x, y, i);
687 if (r > upperbound) {
688 return r;
689 }
690 }
691 return r;
692 }
693
694 static inline double distance_p(const double s, const double) { return s; }
695};
696
697template <typename Dist1D, ckdtree_intp_t Dim>
698struct BaseMinkowskiDistPinf : public BaseMinkowskiDistPp<Dist1D, Dim> {
699 static inline void interval_interval_p(
700 const ckdtree<Dim>* tree,
701 const Rectangle<Dim>& rect1,
702 const Rectangle<Dim>& rect2,
703 const ckdtree_intp_t k,
704 double p,
705 double* min,
706 double* max) {
707 return rect_rect_p(tree, rect1, rect2, p, min, max);
708 }
709
710 static inline void rect_rect_p(
711 const ckdtree<Dim>* tree,
712 const Rectangle<Dim>& rect1,
713 const Rectangle<Dim>& rect2,
714 const double p,
715 double* min,
716 double* max) {
717 *min = 0.;
718 *max = 0.;
719 for (ckdtree_intp_t i = 0; i < Dim; ++i) {
720 double min_, max_;
721
722 Dist1D::interval_interval(tree, rect1, rect2, i, &min_, &max_);
723
724 *min = ckdtree_fmax(*min, min_);
725 *max = ckdtree_fmax(*max, max_);
726 }
727 }
728
729 static inline double point_point_p(
730 const ckdtree<Dim>* tree,
731 const double* x,
732 const double* y,
733 const double,
734 const ckdtree_intp_t k,
735 const double upperbound) {
737 double r;
738 r = 0;
739 for (i = 0; i < k; ++i) {
740 r = ckdtree_fmax(r, Dist1D::point_point(tree, x, y, i));
741 if (r > upperbound) {
742 return r;
743 }
744 }
745 return r;
746 }
747 static inline double distance_p(const double s, const double) { return s; }
748};
749
750template <typename Dist1D, ckdtree_intp_t Dim>
751struct BaseMinkowskiDistP2 : public BaseMinkowskiDistPp<Dist1D, Dim> {
752 static inline void interval_interval_p(
753 const ckdtree<Dim>* tree,
754 const Rectangle<Dim>& rect1,
755 const Rectangle<Dim>& rect2,
756 const ckdtree_intp_t k,
757 const double,
758 double* min,
759 double* max) {
760 /* Compute the minimum/maximum distance along dimension k between points in
761 * two hyperrectangles.
762 */
763 Dist1D::interval_interval(tree, rect1, rect2, k, min, max);
764 *min *= *min;
765 *max *= *max;
766 }
767
768 static inline void rect_rect_p(
769 const ckdtree<Dim>* tree,
770 const Rectangle<Dim>& rect1,
771 const Rectangle<Dim>& rect2,
772 const double,
773 double* min,
774 double* max) {
775 *min = 0.;
776 *max = 0.;
777 for (ckdtree_intp_t i = 0; i < Dim; ++i) {
778 double min_, max_;
779
780 Dist1D::interval_interval(tree, rect1, rect2, i, &min_, &max_);
781 min_ *= min_;
782 max_ *= max_;
783
784 *min += min_;
785 *max += max_;
786 }
787 }
788 static inline double
789
791 const ckdtree<Dim>* tree,
792 const double* x,
793 const double* y,
794 const double,
795 const ckdtree_intp_t k,
796 const double upperbound) {
798 double r;
799 r = 0;
800 for (i = 0; i < k; ++i) {
801 double r1 = Dist1D::point_point(tree, x, y, i);
802 r += r1 * r1;
803 if (r > upperbound) {
804 return r;
805 }
806 }
807 return r;
808 }
809 static inline double distance_p(const double s, const double) {
810 return s * s;
811 }
812};
813
814template <ckdtree_intp_t Dim>
816 static inline double side_distance_from_min_max(
817 const ckdtree<Dim>*,
818 const double x,
819 const double min,
820 const double max,
821 const ckdtree_intp_t) {
822 double s, t;
823 s = 0;
824 t = x - max;
825 if (t > s) {
826 s = t;
827 } else {
828 t = min - x;
829 if (t > s) {
830 s = t;
831 }
832 }
833 return s;
834 }
835 static inline void interval_interval(
836 const ckdtree<Dim>*,
837 const Rectangle<Dim>& rect1,
838 const Rectangle<Dim>& rect2,
839 const ckdtree_intp_t k,
840 double* min,
841 double* max) {
842 /* Compute the minimum/maximum distance along dimension k between points in
843 * two hyperrectangles.
844 */
845 *min = ckdtree_fmax(
846 0., fmax(
847 rect1.mins()[k] - rect2.maxes()[k],
848 rect2.mins()[k] - rect1.maxes()[k]));
849 *max = ckdtree_fmax(
850 rect1.maxes()[k] - rect2.mins()[k], rect2.maxes()[k] - rect1.mins()[k]);
851 }
852
853 static inline double point_point(
854 const ckdtree<Dim>*,
855 const double* x,
856 const double* y,
857 const ckdtree_intp_t k) {
858 return ckdtree_fabs(x[k] - y[k]);
859 }
860};
861
862template <ckdtree_intp_t Dim>
864template <ckdtree_intp_t Dim>
866template <ckdtree_intp_t Dim>
868template <ckdtree_intp_t Dim>
870
871/*
872 * Measuring distances
873 * ===================
874 */
876 const double* u, const double* v, ckdtree_intp_t n) {
877 double s;
878 ckdtree_intp_t i = 0;
879 // manually unrolled loop, might be vectorized
880 double acc[4] = {0., 0., 0., 0.};
881 for (; i + 4 <= n; i += 4) {
882 double _u[4] = {u[i], u[i + 1], u[i + 2], u[i + 3]};
883 double _v[4] = {v[i], v[i + 1], v[i + 2], v[i + 3]};
884 double diff[4] = {
885 _u[0] - _v[0], _u[1] - _v[1], _u[2] - _v[2], _u[3] - _v[3]};
886 acc[0] += diff[0] * diff[0];
887 acc[1] += diff[1] * diff[1];
888 acc[2] += diff[2] * diff[2];
889 acc[3] += diff[3] * diff[3];
890 }
891 s = acc[0] + acc[1] + acc[2] + acc[3];
892 if (i < n) {
893 for (; i < n; ++i) {
894 double d = u[i] - v[i];
895 s += d * d;
896 }
897 }
898 return s;
899}
900
901template <ckdtree_intp_t Dim>
903 static inline double point_point_p(
904 const ckdtree<Dim>* tree,
905 const double* x,
906 const double* y,
907 const double p,
908 const ckdtree_intp_t k,
909 const double upperbound) {
910 return sqeuclidean_distance_double(x, y, k);
911 }
912};
913
914template <ckdtree_intp_t Dim>
915struct BoxDist1D {
916 static inline void _interval_interval_1d(
917 double min,
918 double max,
919 double* realmin,
920 double* realmax,
921 const double full,
922 const double half) {
923 /* Minimum and maximum distance of two intervals in a periodic box
924 *
925 * min and max is the nonperiodic distance between the near
926 * and far edges.
927 *
928 * full and half are the box size and 0.5 * box size.
929 *
930 * value is returned in realmin and realmax;
931 *
932 * This function is copied from kdcount, and the convention
933 * of is that
934 *
935 * min = rect1.min - rect2.max
936 * max = rect1.max - rect2.min = - (rect2.min - rect1.max)
937 *
938 * We will fix the convention later.
939 * */
940 if (CKDTREE_UNLIKELY(full <= 0)) {
941 /* A non-periodic dimension */
942 /* \/ */
943 if (max <= 0 || min >= 0) {
944 /* do not pass though 0 */
945 min = ckdtree_fabs(min);
946 max = ckdtree_fabs(max);
947 if (min < max) {
948 *realmin = min;
949 *realmax = max;
950 } else {
951 *realmin = max;
952 *realmax = min;
953 }
954 } else {
955 min = ckdtree_fabs(min);
956 max = ckdtree_fabs(max);
957 *realmax = ckdtree_fmax(max, min);
958 *realmin = 0;
959 }
960 /* done with non-periodic dimension */
961 return;
962 }
963 if (max <= 0 || min >= 0) {
964 /* do not pass through 0 */
965 min = ckdtree_fabs(min);
966 max = ckdtree_fabs(max);
967 if (min > max) {
968 double t = min;
969 min = max;
970 max = t;
971 }
972 if (max < half) {
973 /* all below half*/
974 *realmin = min;
975 *realmax = max;
976 } else if (min > half) {
977 /* all above half */
978 *realmax = full - min;
979 *realmin = full - max;
980 } else {
981 /* min below, max above */
982 *realmax = half;
983 *realmin = ckdtree_fmin(min, full - max);
984 }
985 } else {
986 /* pass though 0 */
987 min = -min;
988 if (min > max) {
989 max = min;
990 }
991 if (max > half) {
992 max = half;
993 }
994 *realmax = max;
995 *realmin = 0;
996 }
997 }
998 static inline void interval_interval(
999 const ckdtree<Dim>* tree,
1000 const Rectangle<Dim>& rect1,
1001 const Rectangle<Dim>& rect2,
1002 const ckdtree_intp_t k,
1003 double* min,
1004 double* max) {
1005 /* Compute the minimum/maximum distance along dimension k between points in
1006 * two hyperrectangles.
1007 */
1009 rect1.mins()[k] - rect2.maxes()[k], rect1.maxes()[k] - rect2.mins()[k],
1010 min, max, tree->raw_boxsize_data[k], tree->raw_boxsize_data[k + Dim]);
1011 }
1012
1013 static inline double point_point(
1014 const ckdtree<Dim>* tree,
1015 const double* x,
1016 const double* y,
1017 const ckdtree_intp_t k) {
1018 double r1;
1019 r1 = wrap_distance(
1020 x[k] - y[k], tree->raw_boxsize_data[k + tree->m],
1021 tree->raw_boxsize_data[k]);
1022 r1 = ckdtree_fabs(r1);
1023 return r1;
1024 }
1025
1026 static inline double wrap_position(const double x, const double boxsize) {
1027 if (boxsize <= 0) {
1028 return x;
1029 }
1030 const double r = std::floor(x / boxsize);
1031 double x1 = x - r * boxsize;
1032 /* ensure result is within the box. */
1033 while (x1 >= boxsize) {
1034 x1 -= boxsize;
1035 }
1036 while (x1 < 0) {
1037 x1 += boxsize;
1038 }
1039 return x1;
1040 }
1041
1042 static inline double side_distance_from_min_max(
1043 const ckdtree<Dim>* tree,
1044 const double x,
1045 const double min,
1046 const double max,
1047 const ckdtree_intp_t k) {
1048 double s, t, tmin, tmax;
1049 double fb = tree->raw_boxsize_data[k];
1050 double hb = tree->raw_boxsize_data[k + tree->m];
1051
1052 if (fb <= 0) {
1053 /* non-periodic dimension */
1054 s = PlainDist1D<Dim>::side_distance_from_min_max(tree, x, min, max, k);
1055 return s;
1056 }
1057
1058 /* periodic */
1059 s = 0;
1060 tmax = x - max;
1061 tmin = x - min;
1062 /* is the test point in this range */
1063 if (CKDTREE_LIKELY(tmax < 0 && tmin > 0)) {
1064 /* yes. min distance is 0 */
1065 return 0;
1066 }
1067
1068 /* no */
1069 tmax = ckdtree_fabs(tmax);
1070 tmin = ckdtree_fabs(tmin);
1071
1072 /* make tmin the closer edge */
1073 if (tmin > tmax) {
1074 t = tmin;
1075 tmin = tmax;
1076 tmax = t;
1077 }
1078
1079 /* both edges are less than half a box. */
1080 /* no wrapping, use the closer edge */
1081 if (tmax < hb) {
1082 return tmin;
1083 }
1084
1085 /* both edge are more than half a box. */
1086 /* wrapping on both edge, use the
1087 * wrapped further edge */
1088 if (tmin > hb) {
1089 return fb - tmax;
1090 }
1091
1092 /* the further side is wrapped */
1093 tmax = fb - tmax;
1094 if (tmin > tmax) {
1095 return tmax;
1096 }
1097 return tmin;
1098 }
1099
1100 private:
1101 static inline double wrap_distance(
1102 const double x, const double hb, const double fb) {
1103 double x1;
1104 if (CKDTREE_UNLIKELY(x < -hb)) {
1105 x1 = fb + x;
1106 } else if (CKDTREE_UNLIKELY(x > hb)) {
1107 x1 = x - fb;
1108 } else {
1109 x1 = x;
1110 }
1111 return x1;
1112 }
1113};
1114
1115/*
1116 * Priority queue
1117 * ==============
1118 */
1119
1124
1129
1130struct heap {
1131 std::vector<heapitem> _heap;
1134
1135 explicit heap(ckdtree_intp_t initial_size) : _heap(initial_size) {
1136 space = initial_size;
1137 n = 0;
1138 }
1139
1140 inline void push(heapitem& item) {
1142 heapitem t;
1143 n++;
1144
1145 if (n > space) {
1146 _heap.resize(2 * space + 1);
1147 }
1148 space = _heap.size();
1149
1150 i = n - 1;
1151 _heap[i] = item;
1152 while ((i > 0) && (_heap[i].priority < _heap[(i - 1) / 2].priority)) {
1153 t = _heap[(i - 1) / 2];
1154 _heap[(i - 1) / 2] = _heap[i];
1155 _heap[i] = t;
1156 i = (i - 1) / 2;
1157 }
1158 }
1159
1160 inline heapitem peek() { return _heap[0]; }
1161
1162 inline void remove() {
1163 heapitem t;
1164 ckdtree_intp_t i, j, k, l, nn;
1165 _heap[0] = _heap[n - 1];
1166 n--;
1167 /*
1168 * No point in freeing up space as the heap empties.
1169 * The whole heap gets deallocated at the end of any
1170 * query below. Just keep the space to avoid unnecessary
1171 * reallocs.
1172 */
1173 nn = n;
1174 i = 0;
1175 j = 1;
1176 k = 2;
1177 while (((j < nn) && (_heap[i].priority > _heap[j].priority)) ||
1178 ((k < nn) && (_heap[i].priority > _heap[k].priority))) {
1179 if ((k < nn) && (_heap[j].priority > _heap[k].priority)) {
1180 l = k;
1181 } else {
1182 l = j;
1183 }
1184 t = _heap[l];
1185 _heap[l] = _heap[i];
1186 _heap[i] = t;
1187 i = l;
1188 j = 2 * i + 1;
1189 k = 2 * i + 2;
1190 }
1191 }
1192
1193 inline heapitem pop() {
1194 heapitem it = _heap[0];
1195 remove();
1196 return it;
1197 }
1198};
1199
1200/*
1201 * nodeinfo
1202 * ========
1203 */
1204
1205template <ckdtree_intp_t m>
1206struct nodeinfo {
1208 double min_distance; /* full min distance */
1209 double buf[1]; // the good old struct hack
1210 /* accessors to 'packed' attributes */
1211 inline double* side_distances() {
1212 /* min distance to the query per side; we
1213 * update this as the query is proceeded */
1214 return buf;
1215 }
1216 inline double* maxes() { return buf + m; }
1217 inline double* mins() { return buf + 2 * m; }
1218
1219 inline void init_box(const struct nodeinfo* from) {
1220 std::memcpy(buf, from->buf, sizeof(double) * (3 * m));
1221 min_distance = from->min_distance;
1222 }
1223
1224 inline void init_plain(const struct nodeinfo* from) {
1225 /* skip copying min and max, because we only need side_distance array in
1226 * this case. */
1227 std::memcpy(buf, from->buf, sizeof(double) * m);
1228 min_distance = from->min_distance;
1229 }
1230
1232 const int d, const double new_side_distance, const double p) {
1233 if (CKDTREE_UNLIKELY(std::isinf(p))) {
1234 min_distance = ckdtree_fmax(min_distance, new_side_distance);
1235 } else {
1236 min_distance += new_side_distance - side_distances()[d];
1237 }
1238 side_distances()[d] = new_side_distance;
1239 }
1240};
1241
1242/*
1243 * Memory pool for nodeinfo structs
1244 * ================================
1245 */
1246
1247template <ckdtree_intp_t m>
1249 static constexpr ckdtree_intp_t alloc_size =
1250 64 * ((sizeof(nodeinfo<m>) + (3 * m - 1) * sizeof(double)) / 64) + 64;
1251 static constexpr ckdtree_intp_t arena_size =
1252 4096 * ((64 * alloc_size) / 4096) + 4096;
1253 std::vector<char> arena;
1254 size_t current_offset = 0;
1255
1256 explicit nodeinfo_pool() { arena.resize(arena_size); }
1257
1259 if (current_offset + alloc_size > arena.size()) {
1260 arena.resize(arena.size() + arena_size);
1261 }
1262 nodeinfo<m>* ni1 = reinterpret_cast<nodeinfo<m>*>(&arena[current_offset]);
1264 return ni1;
1265 }
1266};
1267
1268/* k-nearest neighbor search for a single point x */
1269template <
1270 typename MinMaxDist,
1271 ckdtree_intp_t Dim,
1272 double p,
1273 bool Periodic = false>
1275 const ckdtree<Dim>* self,
1276 double* result_distances,
1277 ckdtree_intp_t* result_indices,
1278 const double* x,
1279 const ckdtree_intp_t* k,
1280 const ckdtree_intp_t nk,
1281 const ckdtree_intp_t kmax,
1282 const double eps,
1283 double distance_upper_bound) {
1284 /* memory pool to allocate and automatically reclaim nodeinfo structs */
1285 nodeinfo_pool<Dim> nipool;
1286
1287 /*
1288 * priority queue for chasing nodes
1289 * entries are:
1290 * - minimum distance between the cell and the target
1291 * - distances between the nearest side of the cell and the target
1292 * the head node of the cell
1293 */
1294 heap q(12);
1295
1296 /*
1297 * priority queue for chasing nodes
1298 * entries are:
1299 * - minimum distance between the cell and the target
1300 * - distances between the nearest side of the cell and the target
1301 * the head node of the cell
1302 */
1303 heap neighbors(kmax);
1304
1306 constexpr ckdtree_intp_t m = self->m;
1307 nodeinfo<Dim>* ni1;
1308 nodeinfo<Dim>* ni2;
1309 double d;
1310 double epsfac;
1311 heapitem it, it2, neighbor;
1312 const ckdtreenode* node;
1313 const ckdtreenode* inode;
1314
1315 /* set up first nodeifo */
1316 ni1 = nipool.allocate();
1317 ni1->node = self->ctree;
1318
1319 /* initialize first node, update min_distance */
1320 ni1->min_distance = 0;
1321
1322 for (i = 0; i < m; ++i) {
1323 ni1->mins()[i] = self->raw_mins[i];
1324 ni1->maxes()[i] = self->raw_maxes[i];
1325
1326 double side_distance;
1327 if (Periodic) {
1329 self, x[i], self->raw_mins[i], self->raw_maxes[i], i);
1330 } else {
1332 self, x[i], self->raw_mins[i], self->raw_maxes[i], i);
1333 }
1334 side_distance = MinMaxDist::distance_p(side_distance, p);
1335
1336 ni1->side_distances()[i] = 0;
1337 ni1->update_side_distance(i, side_distance, p);
1338 }
1339
1340 /* fiddle approximation factor */
1341 if constexpr (CKDTREE_LIKELY(p == 2.0)) {
1342 double tmp = 1. + eps;
1343 epsfac = 1. / (tmp * tmp);
1344 } else if (eps == 0.) {
1345 epsfac = 1.;
1346 } else if constexpr (std::isinf(p)) {
1347 epsfac = 1. / (1. + eps);
1348 } else {
1349 epsfac = 1. / std::pow((1. + eps), p);
1350 }
1351
1352 /* internally we represent all distances as distance**p */
1353 if constexpr (CKDTREE_LIKELY(p == 2.0)) {
1354 double tmp = distance_upper_bound;
1355 distance_upper_bound = tmp * tmp;
1356 } else if ((!std::isinf(p)) && (!std::isinf(distance_upper_bound))) {
1357 distance_upper_bound = std::pow(distance_upper_bound, p);
1358 }
1359
1360 for (;;) {
1361 if (ni1->node->split_dim == -1) {
1362 node = ni1->node;
1363
1364 /* brute-force */
1365 {
1366 const ckdtree_intp_t start_idx = node->start_idx;
1367 const ckdtree_intp_t end_idx = node->end_idx;
1368 const double* data = self->raw_data;
1369 const ckdtree_intp_t* indices = self->raw_indices;
1370
1371 CKDTREE_PREFETCH(data + indices[start_idx] * m, 0, m);
1372 if (start_idx < end_idx - 1) {
1373 CKDTREE_PREFETCH(data + indices[start_idx + 1] * m, 0, m);
1374 }
1375
1376 for (i = start_idx; i < end_idx; ++i) {
1377 if (i < end_idx - 2) {
1378 CKDTREE_PREFETCH(data + indices[i + 2] * m, 0, m);
1379 }
1380
1381 d = MinMaxDist::point_point_p(
1382 self, data + indices[i] * m, x, p, m, distance_upper_bound);
1383 if (d < distance_upper_bound) {
1384 /* replace furthest neighbor */
1385 if (neighbors.n == kmax) {
1386 neighbors.remove();
1387 }
1388 neighbor.priority = -d;
1389 neighbor.contents.intdata = indices[i];
1390 neighbors.push(neighbor);
1391
1392 /* adjust upper bound for efficiency */
1393 if (neighbors.n == kmax) {
1394 distance_upper_bound = -neighbors.peek().priority;
1395 }
1396 }
1397 }
1398 }
1399 /* done with this node, get another */
1400 if (q.n == 0) {
1401 /* no more nodes to visit */
1402 break;
1403 } else {
1404 it = q.pop();
1405 ni1 = reinterpret_cast<nodeinfo<Dim>*>(it.contents.ptrdata);
1406 }
1407
1408 } else {
1409 inode = ni1->node;
1410 const ckdtree_intp_t split_dim = inode->split_dim;
1411 const double split = inode->split;
1412
1413 /*
1414 * we don't push cells that are too far onto the queue at all,
1415 * but since the distance_upper_bound decreases, we might get
1416 * here even if the cell's too far
1417 */
1418 if (ni1->min_distance > distance_upper_bound * epsfac) {
1419 /* since this is the nearest cell, we're done, bail out */
1420 break;
1421 }
1422 // set up children for searching
1423 // ni2 will be pushed to the queue
1424
1425 ni2 = nipool.allocate();
1426
1427 if constexpr (!Periodic) {
1428 /*
1429 * non periodic : the 'near' node is know from the
1430 * relative distance to the split, and
1431 * has the same distance as the parent node.
1432 *
1433 * we set ni1 to 'near', and set ni2 to 'far'.
1434 * we only recalculate the distance of 'far' later.
1435 *
1436 * This code branch doesn't use min and max.
1437 */
1438 ni2->init_plain(ni1);
1439
1440 double side_distance;
1441
1442 if (x[split_dim] < split) {
1443 ni1->node = inode->less;
1444 ni2->node = inode->greater;
1445 side_distance = split - x[split_dim];
1446 } else {
1447 ni1->node = inode->greater;
1448 ni2->node = inode->less;
1449 side_distance = x[split_dim] - split;
1450 }
1451
1452 side_distance = MinMaxDist::distance_p(side_distance, p);
1453
1454 ni2->update_side_distance(split_dim, side_distance, p);
1455 } else {
1456 /*
1457 * for periodic queries, we do not know which node is closer.
1458 * thus re-calculate ni1 and ni2 both.
1459 *
1460 * this branch we need to keep track of mins and maxes;
1461 */
1462 ni2->init_box(ni1);
1463
1464 double side_distance;
1465
1466 ni1->maxes()[split_dim] = split;
1467 ni1->node = inode->less;
1468
1470 self, x[split_dim], ni1->mins()[split_dim], ni1->maxes()[split_dim],
1471 split_dim);
1472 side_distance = MinMaxDist::distance_p(side_distance, p);
1473
1474 ni1->update_side_distance(split_dim, side_distance, p);
1475
1476 ni2->mins()[split_dim] = split;
1477 ni2->node = inode->greater;
1478
1480 self, x[split_dim], ni2->mins()[split_dim], ni2->maxes()[split_dim],
1481 split_dim);
1482 side_distance = MinMaxDist::distance_p(side_distance, p);
1483
1484 ni2->update_side_distance(split_dim, side_distance, p);
1485 }
1486
1487 /* Ensure ni1 is closer than ni2 */
1488 if (ni1->min_distance > ni2->min_distance) {
1489 {
1490 nodeinfo<Dim>* tmp;
1491 tmp = ni1;
1492 ni1 = ni2;
1493 ni2 = tmp;
1494 }
1495 }
1496
1497 /*
1498 * near child is at the same or closer than the distance as the current
1499 * node we're going here next, so no point pushing it on the queue no need
1500 * to recompute the distance or the side_distances
1501 */
1502
1503 /*
1504 * far child can be further
1505 * push it on the queue if it's near enough
1506 */
1507
1508 if (ni2->min_distance <= distance_upper_bound * epsfac) {
1509 it2.priority = ni2->min_distance;
1510 it2.contents.ptrdata = reinterpret_cast<void*>(ni2);
1511 q.push(it2);
1512 }
1513 }
1514 }
1515
1516 /* heapsort */
1517 std::vector<heapitem> sorted_neighbors(kmax);
1518 ckdtree_intp_t nnb = neighbors.n;
1519 for (i = neighbors.n - 1; i >= 0; --i) {
1520 sorted_neighbors[i] = neighbors.pop();
1521 }
1522
1523 /* fill output arrays with sorted neighbors */
1524 for (i = 0; i < nk; ++i) {
1525 if (CKDTREE_UNLIKELY(k[i] - 1 >= nnb)) {
1526 result_indices[i] = self->n;
1527 result_distances[i] = std::numeric_limits<double>::infinity();
1528 } else {
1529 neighbor = sorted_neighbors[k[i] - 1];
1530 result_indices[i] = neighbor.contents.intdata;
1531 if constexpr (CKDTREE_LIKELY(p == 2.0)) {
1532 result_distances[i] = std::sqrt(-neighbor.priority);
1533 } else if constexpr ((p == 1.) || (std::isinf(p))) {
1534 result_distances[i] = -neighbor.priority;
1535 } else {
1536 result_distances[i] = std::pow((-neighbor.priority), (1. / p));
1537 }
1538 }
1539 }
1540}
1541
1542/* Query n points for their k nearest neighbors */
1543
1544template <ckdtree_intp_t Dim, double p, bool Periodic = false>
1546 const ckdtree<Dim>* self,
1547 double* dd,
1548 ckdtree_intp_t* ii,
1549 const double* xx,
1550 const ckdtree_intp_t n,
1551 const ckdtree_intp_t* k,
1552 const ckdtree_intp_t nk,
1553 const ckdtree_intp_t kmax,
1554 const double eps,
1555 const double distance_upper_bound) {
1556#define HANDLE_KNN(cond, kls) \
1557 if constexpr (cond) { \
1558 query_single_point<kls, Dim, p, Periodic>( \
1559 self, dd_row, ii_row, xx_row, k, nk, kmax, eps, distance_upper_bound); \
1560 } else
1561
1562 constexpr ckdtree_intp_t m = self->m;
1564
1569
1570 using BoxMinkowskiDistP2 = BaseMinkowskiDistP2<BoxDist1D<Dim>, Dim>;
1571 using BoxMinkowskiDistP1 = BaseMinkowskiDistP1<BoxDist1D<Dim>, Dim>;
1572 using BoxMinkowskiDistPinf = BaseMinkowskiDistPinf<BoxDist1D<Dim>, Dim>;
1573 using BoxMinkowskiDistPp = BaseMinkowskiDistPp<BoxDist1D<Dim>, Dim>;
1574
1575 if constexpr (!Periodic) {
1576 for (i = 0; i < n; ++i) {
1577 double* dd_row = dd + (i * nk);
1578 ckdtree_intp_t* ii_row = ii + (i * nk);
1579 const double* xx_row = xx + (i * m);
1580 HANDLE_KNN(p == 2.0, MinkowskiDistP2)
1581 HANDLE_KNN(p == 1.0, MinkowskiDistP1)
1582 HANDLE_KNN(std::isinf(p), MinkowskiDistPinf)
1584 }
1585 } else {
1586 std::array<double, m> row = {0};
1587 double* xx_row = &row[0];
1588 int j;
1589 for (i = 0; i < n; ++i) {
1590 double* dd_row = dd + (i * nk);
1591 ckdtree_intp_t* ii_row = ii + (i * nk);
1592 const double* old_xx_row = xx + (i * m);
1593 for (j = 0; j < m; ++j) {
1595 old_xx_row[j], self->raw_boxsize_data[j]);
1596 }
1597 HANDLE_KNN(p == 2.0, BoxMinkowskiDistP2)
1598 HANDLE_KNN(p == 1.0, BoxMinkowskiDistP1)
1599 HANDLE_KNN(std::isinf(p), BoxMinkowskiDistPinf)
1600 HANDLE_KNN(1, BoxMinkowskiDistPp) {}
1601 }
1602 }
1603 return 0;
1604}
1605
1606// ============================================================================
1607
1608template <ckdtree_intp_t Dim>
1610 const ckdtree<Dim>* self,
1611 const int return_length,
1612 std::vector<ckdtree_intp_t>& results,
1613 const ckdtreenode* node) {
1614 const ckdtree_intp_t* indices = self->raw_indices;
1615 const ckdtreenode* lnode;
1617
1618 if (node->split_dim == -1) { /* leaf node */
1619 lnode = node;
1620 const ckdtree_intp_t start = lnode->start_idx;
1621 const ckdtree_intp_t end = lnode->end_idx;
1622 for (i = start; i < end; ++i) {
1623 if (return_length) {
1624 results[0]++;
1625 } else {
1626 results.push_back(indices[i]);
1627 }
1628 }
1629 } else {
1631 self, return_length, results, node->less);
1633 self, return_length, results, node->greater);
1634 }
1635}
1636
1637template <ckdtree_intp_t Dim, typename MinMaxDist>
1639 const ckdtree<Dim>* self,
1640 const int return_length,
1641 std::vector<ckdtree_intp_t>& results,
1642 const ckdtreenode* node,
1644 const ckdtreenode* lnode;
1645 double d;
1647
1648 if (tracker->min_distance > tracker->upper_bound * tracker->epsfac) {
1649 return;
1650 } else if (tracker->max_distance < tracker->upper_bound / tracker->epsfac) {
1651 traverse_no_checking_query_ball_point(self, return_length, results, node);
1652 } else if (node->split_dim == -1) { /* leaf node */
1653 /* brute-force */
1654 lnode = node;
1655 const double p = tracker->p;
1656 const double tub = tracker->upper_bound;
1657 const double* tpt = tracker->rect1.mins();
1658 const double* data = self->raw_data;
1659 const ckdtree_intp_t* indices = self->raw_indices;
1660 constexpr ckdtree_intp_t m = self->m;
1661 const ckdtree_intp_t start = lnode->start_idx;
1662 const ckdtree_intp_t end = lnode->end_idx;
1663
1664 CKDTREE_PREFETCH(data + indices[start] * m, 0, m);
1665 if (start < end - 1) {
1666 CKDTREE_PREFETCH(data + indices[start + 1] * m, 0, m);
1667 }
1668
1669 for (i = start; i < end; ++i) {
1670 if (i < end - 2) {
1671 CKDTREE_PREFETCH(data + indices[i + 2] * m, 0, m);
1672 }
1673
1674 d = MinMaxDist::point_point_p(
1675 self, data + indices[i] * m, tpt, p, m, tub);
1676
1677 if (d <= tub) {
1678 if (return_length) {
1679 results[0]++;
1680 } else {
1681 results.push_back((ckdtree_intp_t)indices[i]);
1682 }
1683 }
1684 }
1685 } else {
1686 tracker->push_less_of(2, node);
1688 self, return_length, results, node->less, tracker);
1689 tracker->pop();
1690
1691 tracker->push_greater_of(2, node);
1693 self, return_length, results, node->greater, tracker);
1694 tracker->pop();
1695 }
1696}
1697
1698template <ckdtree_intp_t Dim, double p, bool Periodic = false>
1700 const ckdtree<Dim>* self,
1701 const double* x,
1702 const double* r,
1703 const double eps,
1704 const ckdtree_intp_t n_queries,
1705 std::vector<ckdtree_intp_t>* results,
1706 const bool return_length,
1707 const bool sort_output) {
1708#define HANDLE_QBP(cond, kls) \
1709 if constexpr (cond) { \
1710 if (return_length) \
1711 results[i].push_back(0); \
1712 RectRectDistanceTracker<kls, Dim> tracker( \
1713 self, point, rect, p, eps, r[i]); \
1714 traverse_checking_query_ball_point( \
1715 self, return_length, results[i], self->ctree, &tracker); \
1716 } else
1717
1722
1723 using BoxMinkowskiDistP2 = BaseMinkowskiDistP2<BoxDist1D<Dim>, Dim>;
1724 using BoxMinkowskiDistP1 = BaseMinkowskiDistP1<BoxDist1D<Dim>, Dim>;
1725 using BoxMinkowskiDistPinf = BaseMinkowskiDistPinf<BoxDist1D<Dim>, Dim>;
1726 using BoxMinkowskiDistPp = BaseMinkowskiDistPp<BoxDist1D<Dim>, Dim>;
1727
1728 for (ckdtree_intp_t i = 0; i < n_queries; ++i) {
1729 constexpr ckdtree_intp_t m = self->m;
1730 Rectangle<Dim> rect(self->raw_mins, self->raw_maxes);
1731 if constexpr (!Periodic) {
1732 Rectangle<Dim> point(x + i * m, x + i * m);
1733 HANDLE_QBP(p == 2.0, MinkowskiDistP2)
1734 HANDLE_QBP(p == 1.0, MinkowskiDistP1)
1735 HANDLE_QBP(std::isinf(p), MinkowskiDistPinf)
1737 } else {
1738 Rectangle<Dim> point(x + i * m, x + i * m);
1739 int j;
1740 for (j = 0; j < m; ++j) {
1741 point.maxes()[j] = point.mins()[j] = BoxDist1D<Dim>::wrap_position(
1742 point.mins()[j], self->raw_boxsize_data[j]);
1743 }
1744 HANDLE_QBP(p == 2.0, BoxMinkowskiDistP2)
1745 HANDLE_QBP(p == 1.0, BoxMinkowskiDistP1)
1746 HANDLE_QBP(std::isinf(p), BoxMinkowskiDistPinf)
1747 HANDLE_QBP(1, BoxMinkowskiDistPp) {}
1748 }
1749
1750 if (!return_length && sort_output) {
1751 std::sort(results[i].begin(), results[i].end());
1752 }
1753 }
1754 return 0;
1755}
1756
1757// ============================================================================
1758
1759template <ckdtree_intp_t Dim>
1761 const ckdtree<Dim>* self,
1762 std::vector<ordered_pair>* results,
1763 const ckdtreenode* node1,
1764 const ckdtreenode* node2) {
1765 const ckdtreenode* lnode1;
1766 const ckdtreenode* lnode2;
1767 ckdtree_intp_t i, j, min_j;
1768 const ckdtree_intp_t* indices = self->raw_indices;
1769
1770 if (node1->split_dim == -1) { /* leaf node */
1771 lnode1 = node1;
1772
1773 if (node2->split_dim == -1) { /* leaf node */
1774 lnode2 = node2;
1775
1776 const ckdtree_intp_t start1 = lnode1->start_idx;
1777 const ckdtree_intp_t start2 = lnode2->start_idx;
1778 const ckdtree_intp_t end1 = lnode1->end_idx;
1779 const ckdtree_intp_t end2 = lnode2->end_idx;
1780
1781 for (i = start1; i < end1; ++i) {
1782 /* Special care here to avoid duplicate pairs */
1783 if (node1 == node2) {
1784 min_j = i + 1;
1785 } else {
1786 min_j = start2;
1787 }
1788
1789 for (j = min_j; j < end2; ++j) {
1790 add_ordered_pair(results, indices[i], indices[j]);
1791 }
1792 }
1793 } else {
1794 traverse_no_checking_query_pairs(self, results, node1, node2->less);
1795 traverse_no_checking_query_pairs(self, results, node1, node2->greater);
1796 }
1797 } else {
1798 if (node1 == node2) {
1799 /*
1800 * Avoid traversing (node1->less, node2->greater) and
1801 * (node1->greater, node2->less) (it's the same node pair twice
1802 * over, which is the source of the complication in the
1803 * original KDTree.query_pairs)
1804 */
1805 traverse_no_checking_query_pairs(self, results, node1->less, node2->less);
1807 self, results, node1->less, node2->greater);
1809 self, results, node1->greater, node2->greater);
1810 } else {
1811 traverse_no_checking_query_pairs(self, results, node1->less, node2);
1812 traverse_no_checking_query_pairs(self, results, node1->greater, node2);
1813 }
1814 }
1815}
1816
1817template <ckdtree_intp_t Dim, typename MinMaxDist>
1819 const ckdtree<Dim>* self,
1820 std::vector<ordered_pair>* results,
1821 const ckdtreenode* node1,
1822 const ckdtreenode* node2,
1824 const ckdtreenode* lnode1;
1825 const ckdtreenode* lnode2;
1826 double d;
1827 ckdtree_intp_t i, j, min_j;
1828
1829 if (tracker->min_distance > tracker->upper_bound * tracker->epsfac) {
1830 return;
1831 } else if (tracker->max_distance < tracker->upper_bound / tracker->epsfac) {
1832 traverse_no_checking_query_pairs(self, results, node1, node2);
1833 } else if (node1->split_dim == -1) { /* 1 is leaf node */
1834 lnode1 = node1;
1835
1836 if (node2->split_dim == -1) { /* 1 & 2 are leaves */
1837 lnode2 = node2;
1838
1839 /* brute-force */
1840 const double p = tracker->p;
1841 const double tub = tracker->upper_bound;
1842 const double* data = self->raw_data;
1843 const double epsfac = tracker->epsfac;
1844 const ckdtree_intp_t* indices = self->raw_indices;
1845 constexpr ckdtree_intp_t m = self->m;
1846 const ckdtree_intp_t start1 = lnode1->start_idx;
1847 const ckdtree_intp_t start2 = lnode2->start_idx;
1848 const ckdtree_intp_t end1 = lnode1->end_idx;
1849 const ckdtree_intp_t end2 = lnode2->end_idx;
1850
1851 CKDTREE_PREFETCH(data + indices[start1] * m, 0, m);
1852 if (start1 < end1 - 1) {
1853 CKDTREE_PREFETCH(data + indices[start1 + 1] * m, 0, m);
1854 }
1855
1856 for (i = start1; i < end1; ++i) {
1857 if (i < end1 - 2) {
1858 CKDTREE_PREFETCH(data + indices[i + 2] * m, 0, m);
1859 }
1860
1861 /* Special care here to avoid duplicate pairs */
1862 if (node1 == node2) {
1863 min_j = i + 1;
1864 } else {
1865 min_j = start2;
1866 }
1867
1868 if (min_j < end2) {
1869 CKDTREE_PREFETCH(data + indices[min_j] * m, 0, m);
1870 }
1871 if (min_j < end2 - 1) {
1872 CKDTREE_PREFETCH(data + indices[min_j + 1] * m, 0, m);
1873 }
1874
1875 for (j = min_j; j < end2; ++j) {
1876 if (j < end2 - 2) {
1877 CKDTREE_PREFETCH(data + indices[j + 2] * m, 0, m);
1878 }
1879
1880 d = MinMaxDist::point_point_p(
1881 self, data + indices[i] * m, data + indices[j] * m, p, m, tub);
1882
1883 if (d <= tub / epsfac) {
1884 add_ordered_pair(results, indices[i], indices[j]);
1885 }
1886 }
1887 }
1888 } else { /* 1 is a leaf node, 2 is inner node */
1889 tracker->push_less_of(2, node2);
1890 traverse_checking_query_pairs(self, results, node1, node2->less, tracker);
1891 tracker->pop();
1892
1893 tracker->push_greater_of(2, node2);
1895 self, results, node1, node2->greater, tracker);
1896 tracker->pop();
1897 }
1898 } else { /* 1 is an inner node */
1899 if (node2->split_dim == -1) { /* 1 is an inner node, 2 is a leaf node */
1900 tracker->push_less_of(1, node1);
1901 traverse_checking_query_pairs(self, results, node1->less, node2, tracker);
1902 tracker->pop();
1903
1904 tracker->push_greater_of(1, node1);
1906 self, results, node1->greater, node2, tracker);
1907 tracker->pop();
1908 } else { /* 1 and 2 are inner nodes */
1909 tracker->push_less_of(1, node1);
1910 tracker->push_less_of(2, node2);
1912 self, results, node1->less, node2->less, tracker);
1913 tracker->pop();
1914
1915 tracker->push_greater_of(2, node2);
1917 self, results, node1->less, node2->greater, tracker);
1918 tracker->pop();
1919 tracker->pop();
1920
1921 tracker->push_greater_of(1, node1);
1922 if (node1 != node2) {
1923 /*
1924 * Avoid traversing (node1->less, node2->greater) and
1925 * (node1->greater, node2->less) (it's the same node pair
1926 * twice over, which is the source of the complication in
1927 * the original KDTree.query_pairs)
1928 */
1929 tracker->push_less_of(2, node2);
1931 self, results, node1->greater, node2->less, tracker);
1932 tracker->pop();
1933 }
1934 tracker->push_greater_of(2, node2);
1936 self, results, node1->greater, node2->greater, tracker);
1937 tracker->pop();
1938 tracker->pop();
1939 }
1940 }
1941}
1942
1943template <ckdtree_intp_t Dim, double p, bool Periodic = false>
1945 const ckdtree<Dim>* self,
1946 const double r,
1947 const double eps,
1948 std::vector<ordered_pair>* results) {
1949#define HANDLE_PAIRS(cond, kls) \
1950 if constexpr (cond) { \
1951 RectRectDistanceTracker<kls, Dim> tracker(self, r1, r2, p, eps, r); \
1952 traverse_checking_query_pairs( \
1953 self, results, self->ctree, self->ctree, &tracker); \
1954 } else
1955
1960
1961 using BoxMinkowskiDistP2 = BaseMinkowskiDistP2<BoxDist1D<Dim>, Dim>;
1962 using BoxMinkowskiDistP1 = BaseMinkowskiDistP1<BoxDist1D<Dim>, Dim>;
1963 using BoxMinkowskiDistPinf = BaseMinkowskiDistPinf<BoxDist1D<Dim>, Dim>;
1964 using BoxMinkowskiDistPp = BaseMinkowskiDistPp<BoxDist1D<Dim>, Dim>;
1965
1966 Rectangle<Dim> r1(self->raw_mins, self->raw_maxes);
1967 Rectangle<Dim> r2(self->raw_mins, self->raw_maxes);
1968
1969 if constexpr (!Periodic) {
1970 HANDLE_PAIRS(p == 2.0, MinkowskiDistP2)
1971 HANDLE_PAIRS(p == 1.0, MinkowskiDistP1)
1972 HANDLE_PAIRS(std::isinf(p), MinkowskiDistPinf)
1974 } else {
1975 HANDLE_PAIRS(p == 2.0, BoxMinkowskiDistP2)
1976 HANDLE_PAIRS(p == 1.0, BoxMinkowskiDistP1)
1977 HANDLE_PAIRS(std::isinf(p), BoxMinkowskiDistPinf)
1978 HANDLE_PAIRS(1, BoxMinkowskiDistPp) {}
1979 }
1980
1981 return 0;
1982}
1983
1984// ============================================================================
1985
1986template <ckdtree_intp_t Dim>
1987
1989 const ckdtree<Dim>* self,
1990 const ckdtree<Dim>* other,
1991 std::vector<ckdtree_intp_t>* results,
1992 const ckdtreenode* node1,
1993 const ckdtreenode* node2) {
1994 const ckdtreenode* lnode1;
1995 const ckdtreenode* lnode2;
1996 const ckdtree_intp_t* sindices = self->raw_indices;
1997 const ckdtree_intp_t* oindices = other->raw_indices;
1998 ckdtree_intp_t i, j;
1999
2000 if (node1->split_dim == -1) { /* leaf node */
2001 lnode1 = node1;
2002
2003 if (node2->split_dim == -1) { /* leaf node */
2004 lnode2 = node2;
2005
2006 const ckdtree_intp_t start1 = lnode1->start_idx;
2007 const ckdtree_intp_t start2 = lnode2->start_idx;
2008 const ckdtree_intp_t end1 = lnode1->end_idx;
2009 const ckdtree_intp_t end2 = lnode2->end_idx;
2010
2011 for (i = start1; i < end1; ++i) {
2012 auto& results_i = results[sindices[i]];
2013 for (j = start2; j < end2; ++j) {
2014 results_i.push_back(oindices[j]);
2015 }
2016 }
2017 } else {
2019 self, other, results, node1, node2->less);
2021 self, other, results, node1, node2->greater);
2022 }
2023 } else {
2025 self, other, results, node1->less, node2);
2027 self, other, results, node1->greater, node2);
2028 }
2029}
2030
2031template <ckdtree_intp_t Dim, typename MinMaxDist>
2033 const ckdtree<Dim>* self,
2034 const ckdtree<Dim>* other,
2035 std::vector<ckdtree_intp_t>* results,
2036 const ckdtreenode* node1,
2037 const ckdtreenode* node2,
2039 const ckdtreenode* lnode1;
2040 const ckdtreenode* lnode2;
2041 double d;
2042 ckdtree_intp_t i, j;
2043
2044 if (tracker->min_distance > tracker->upper_bound * tracker->epsfac) {
2045 return;
2046 } else if (tracker->max_distance < tracker->upper_bound / tracker->epsfac) {
2047 traverse_no_checking_query_ball_tree(self, other, results, node1, node2);
2048 } else if (node1->split_dim == -1) { /* 1 is leaf node */
2049 lnode1 = node1;
2050
2051 if (node2->split_dim == -1) { /* 1 & 2 are leaves */
2052 /* brute-force */
2053 lnode2 = node2;
2054 const double p = tracker->p;
2055 const double tub = tracker->upper_bound;
2056 const double tmd = tracker->max_distance;
2057 const double* sdata = self->raw_data;
2058 const ckdtree_intp_t* sindices = self->raw_indices;
2059 const double* odata = other->raw_data;
2060 const ckdtree_intp_t* oindices = other->raw_indices;
2061 constexpr ckdtree_intp_t m = self->m;
2062 const ckdtree_intp_t start1 = lnode1->start_idx;
2063 const ckdtree_intp_t start2 = lnode2->start_idx;
2064 const ckdtree_intp_t end1 = lnode1->end_idx;
2065 const ckdtree_intp_t end2 = lnode2->end_idx;
2066
2067 CKDTREE_PREFETCH(sdata + sindices[start1] * m, 0, m);
2068
2069 if (start1 < end1 - 1) {
2070 CKDTREE_PREFETCH(sdata + sindices[start1 + 1] * m, 0, m);
2071 }
2072
2073 for (i = start1; i < end1; ++i) {
2074 if (i < end1 - 2) {
2075 CKDTREE_PREFETCH(sdata + sindices[i + 2] * m, 0, m);
2076 }
2077
2078 CKDTREE_PREFETCH(odata + oindices[start2] * m, 0, m);
2079
2080 if (start2 < end2 - 1) {
2081 CKDTREE_PREFETCH(odata + oindices[start2 + 1] * m, 0, m);
2082 }
2083
2084 auto& results_i = results[sindices[i]];
2085
2086 for (j = start2; j < end2; ++j) {
2087 if (j < end2 - 2) {
2088 CKDTREE_PREFETCH(odata + oindices[j + 2] * m, 0, m);
2089 }
2090
2091 d = MinMaxDist::point_point_p(
2092 self, sdata + sindices[i] * m, odata + oindices[j] * m, p, m,
2093 tmd);
2094
2095 if (d <= tub) {
2096 results_i.push_back(other->raw_indices[j]);
2097 }
2098 }
2099 }
2100 } else { /* 1 is a leaf node, 2 is inner node */
2101 tracker->push_less_of(2, node2);
2103 self, other, results, node1, node2->less, tracker);
2104 tracker->pop();
2105
2106 tracker->push_greater_of(2, node2);
2108 self, other, results, node1, node2->greater, tracker);
2109 tracker->pop();
2110 }
2111 } else { /* 1 is an inner node */
2112 if (node2->split_dim == -1) { /* 1 is an inner node, 2 is a leaf node */
2113 tracker->push_less_of(1, node1);
2115 self, other, results, node1->less, node2, tracker);
2116 tracker->pop();
2117
2118 tracker->push_greater_of(1, node1);
2120 self, other, results, node1->greater, node2, tracker);
2121 tracker->pop();
2122 } else { /* 1 & 2 are inner nodes */
2123 tracker->push_less_of(1, node1);
2124 tracker->push_less_of(2, node2);
2126 self, other, results, node1->less, node2->less, tracker);
2127 tracker->pop();
2128
2129 tracker->push_greater_of(2, node2);
2131 self, other, results, node1->less, node2->greater, tracker);
2132 tracker->pop();
2133 tracker->pop();
2134
2135 tracker->push_greater_of(1, node1);
2136 tracker->push_less_of(2, node2);
2138 self, other, results, node1->greater, node2->less, tracker);
2139 tracker->pop();
2140
2141 tracker->push_greater_of(2, node2);
2143 self, other, results, node1->greater, node2->greater, tracker);
2144 tracker->pop();
2145 tracker->pop();
2146 }
2147 }
2148}
2149
2150template <ckdtree_intp_t Dim, double p, bool Periodic = false>
2152 const ckdtree<Dim>* self,
2153 const ckdtree<Dim>* other,
2154 const double r,
2155 const double eps,
2156 std::vector<ckdtree_intp_t>* results) {
2157#define HANDLE_TREE(cond, kls) \
2158 if constexpr (cond) { \
2159 RectRectDistanceTracker<kls, Dim> tracker(self, r1, r2, p, eps, r); \
2160 traverse_checking_query_ball_tree( \
2161 self, other, results, self->ctree, other->ctree, &tracker); \
2162 } else
2163
2168
2169 using BoxMinkowskiDistP2 = BaseMinkowskiDistP2<BoxDist1D<Dim>, Dim>;
2170 using BoxMinkowskiDistP1 = BaseMinkowskiDistP1<BoxDist1D<Dim>, Dim>;
2171 using BoxMinkowskiDistPinf = BaseMinkowskiDistPinf<BoxDist1D<Dim>, Dim>;
2172 using BoxMinkowskiDistPp = BaseMinkowskiDistPp<BoxDist1D<Dim>, Dim>;
2173
2174 Rectangle<Dim> r1(self->raw_mins, self->raw_maxes);
2175 Rectangle<Dim> r2(other->raw_mins, other->raw_maxes);
2176
2177 if constexpr (!Periodic) {
2178 HANDLE_TREE(p == 2.0, MinkowskiDistP2)
2179 HANDLE_TREE(p == 1.0, MinkowskiDistP1)
2180 HANDLE_TREE(std::isinf(p), MinkowskiDistPinf)
2182 } else {
2183 HANDLE_TREE(p == 2.0, BoxMinkowskiDistP2)
2184 HANDLE_TREE(p == 1.0, BoxMinkowskiDistP1)
2185 HANDLE_TREE(std::isinf(p), BoxMinkowskiDistPinf)
2186 HANDLE_TREE(1, BoxMinkowskiDistPp) {}
2187 }
2188
2189 for (ckdtree_intp_t i = 0; i < self->n; ++i) {
2190 std::sort(results[i].begin(), results[i].end());
2191 }
2192
2193 return 0;
2194}
2195
2196} // namespace scipy
2197} // namespace vulpes
2198// NOLINTEND
2199#endif // VULPES_DATASTRUCTURE_CKDTREE_CKDTREE_DECL_HPP_
#define ckdtree_fmax(x, y)
Definition ckdtree_decl.hpp:76
#define ckdtree_fmin(x, y)
Definition ckdtree_decl.hpp:77
#define CKDTREE_PREFETCH(x, rw, loc)
Definition ckdtree_decl.hpp:73
#define tree_buffer_root(buf)
Definition ckdtree_decl.hpp:57
#define HANDLE_PAIRS(cond, kls)
#define HANDLE_KNN(cond, kls)
#define HANDLE_QBP(cond, kls)
#define CKDTREE_LIKELY(x)
Definition ckdtree_decl.hpp:58
#define ckdtree_fabs(x)
Definition ckdtree_decl.hpp:78
#define CKDTREE_UNLIKELY(x)
Definition ckdtree_decl.hpp:59
#define HANDLE_TREE(cond, kls)
Definition ckdtree_decl.hpp:81
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
static void traverse_no_checking_query_pairs(const ckdtree< Dim > *self, std::vector< ordered_pair > *results, const ckdtreenode *node1, const ckdtreenode *node2)
Definition ckdtree_decl.hpp:1760
intptr_t ckdtree_intp_t
Definition ckdtree_decl.hpp:82
BaseMinkowskiDistPp< PlainDist1D< Dim >, Dim > MinkowskiDistPp
Definition ckdtree_decl.hpp:863
BaseMinkowskiDistP2< PlainDist1D< Dim >, Dim > NonOptimizedMinkowskiDistP2
Definition ckdtree_decl.hpp:869
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
double sqeuclidean_distance_double(const double *u, const double *v, ckdtree_intp_t n)
Definition ckdtree_decl.hpp:875
const ckdtree_intp_t LESS
Definition ckdtree_decl.hpp:386
static void traverse_checking_query_ball_point(const ckdtree< Dim > *self, const int return_length, std::vector< ckdtree_intp_t > &results, const ckdtreenode *node, RectRectDistanceTracker< MinMaxDist, Dim > *tracker)
Definition ckdtree_decl.hpp:1638
BaseMinkowskiDistP1< PlainDist1D< Dim >, Dim > MinkowskiDistP1
Definition ckdtree_decl.hpp:867
static void traverse_checking_query_pairs(const ckdtree< Dim > *self, std::vector< ordered_pair > *results, const ckdtreenode *node1, const ckdtreenode *node2, RectRectDistanceTracker< MinMaxDist, Dim > *tracker)
Definition ckdtree_decl.hpp:1818
const ckdtree_intp_t GREATER
Definition ckdtree_decl.hpp:387
static void traverse_no_checking_query_ball_point(const ckdtree< Dim > *self, const int return_length, std::vector< ckdtree_intp_t > &results, const ckdtreenode *node)
Definition ckdtree_decl.hpp:1609
static void traverse_checking_query_ball_tree(const ckdtree< Dim > *self, const ckdtree< Dim > *other, std::vector< ckdtree_intp_t > *results, const ckdtreenode *node1, const ckdtreenode *node2, RectRectDistanceTracker< MinMaxDist, Dim > *tracker)
Definition ckdtree_decl.hpp:2032
static void traverse_no_checking_query_ball_tree(const ckdtree< Dim > *self, const ckdtree< Dim > *other, std::vector< ckdtree_intp_t > *results, const ckdtreenode *node1, const ckdtreenode *node2)
Definition ckdtree_decl.hpp:1988
static void query_single_point(const ckdtree< Dim > *self, double *result_distances, ckdtree_intp_t *result_indices, const double *x, const ckdtree_intp_t *k, const ckdtree_intp_t nk, const ckdtree_intp_t kmax, const double eps, double distance_upper_bound)
Definition ckdtree_decl.hpp:1274
void add_ordered_pair(std::vector< ordered_pair > *results, const ckdtree_intp_t i, const ckdtree_intp_t j)
Definition ckdtree_decl.hpp:99
BaseMinkowskiDistPinf< PlainDist1D< Dim >, Dim > MinkowskiDistPinf
Definition ckdtree_decl.hpp:865
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:641
static void rect_rect_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const double p, double *min, double *max)
Definition ckdtree_decl.hpp:656
static double point_point_p(const ckdtree< Dim > *tree, const double *x, const double *y, const double, const ckdtree_intp_t k, const double upperbound)
Definition ckdtree_decl.hpp:675
static void interval_interval_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, const double p, double *min, double *max)
Definition ckdtree_decl.hpp:642
static double distance_p(const double s, const double)
Definition ckdtree_decl.hpp:694
Definition ckdtree_decl.hpp:751
static double point_point_p(const ckdtree< Dim > *tree, const double *x, const double *y, const double, const ckdtree_intp_t k, const double upperbound)
Definition ckdtree_decl.hpp:790
static double distance_p(const double s, const double)
Definition ckdtree_decl.hpp:809
static void interval_interval_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, const double, double *min, double *max)
Definition ckdtree_decl.hpp:752
static void rect_rect_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const double, double *min, double *max)
Definition ckdtree_decl.hpp:768
Definition ckdtree_decl.hpp:698
static double distance_p(const double s, const double)
Definition ckdtree_decl.hpp:747
static double point_point_p(const ckdtree< Dim > *tree, const double *x, const double *y, const double, const ckdtree_intp_t k, const double upperbound)
Definition ckdtree_decl.hpp:729
static void interval_interval_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, double p, double *min, double *max)
Definition ckdtree_decl.hpp:699
static void rect_rect_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const double p, double *min, double *max)
Definition ckdtree_decl.hpp:710
Definition ckdtree_decl.hpp:567
static double point_point_p(const ckdtree< Dim > *tree, const double *x, const double *y, const double p, const ckdtree_intp_t k, const double upperbound)
Definition ckdtree_decl.hpp:607
static double distance_p(const double s, const double p)
Definition ckdtree_decl.hpp:635
static void interval_interval_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, const double p, double *min, double *max)
Definition ckdtree_decl.hpp:572
static void rect_rect_p(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const double p, double *min, double *max)
Definition ckdtree_decl.hpp:588
Definition ckdtree_decl.hpp:915
static double wrap_distance(const double x, const double hb, const double fb)
Definition ckdtree_decl.hpp:1101
static double wrap_position(const double x, const double boxsize)
Definition ckdtree_decl.hpp:1026
static double side_distance_from_min_max(const ckdtree< Dim > *tree, const double x, const double min, const double max, const ckdtree_intp_t k)
Definition ckdtree_decl.hpp:1042
static void _interval_interval_1d(double min, double max, double *realmin, double *realmax, const double full, const double half)
Definition ckdtree_decl.hpp:916
static double point_point(const ckdtree< Dim > *tree, const double *x, const double *y, const ckdtree_intp_t k)
Definition ckdtree_decl.hpp:1013
static void interval_interval(const ckdtree< Dim > *tree, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, double *min, double *max)
Definition ckdtree_decl.hpp:998
Definition ckdtree_decl.hpp:902
static double point_point_p(const ckdtree< Dim > *tree, const double *x, const double *y, const double p, const ckdtree_intp_t k, const double upperbound)
Definition ckdtree_decl.hpp:903
Definition ckdtree_decl.hpp:815
static void interval_interval(const ckdtree< Dim > *, const Rectangle< Dim > &rect1, const Rectangle< Dim > &rect2, const ckdtree_intp_t k, double *min, double *max)
Definition ckdtree_decl.hpp:835
static double point_point(const ckdtree< Dim > *, const double *x, const double *y, const ckdtree_intp_t k)
Definition ckdtree_decl.hpp:853
static double side_distance_from_min_max(const ckdtree< Dim > *, const double x, const double min, const double max, const ckdtree_intp_t)
Definition ckdtree_decl.hpp:816
Definition ckdtree_decl.hpp:377
double max_distance
Definition ckdtree_decl.hpp:383
double max_along_dim
Definition ckdtree_decl.hpp:381
ckdtree_intp_t which
Definition ckdtree_decl.hpp:378
ckdtree_intp_t split_dim
Definition ckdtree_decl.hpp:379
double min_along_dim
Definition ckdtree_decl.hpp:380
double min_distance
Definition ckdtree_decl.hpp:382
Definition ckdtree_decl.hpp:390
ckdtree_intp_t stack_max_size
Definition ckdtree_decl.hpp:401
void _resize_stack(const ckdtree_intp_t new_max_size)
Definition ckdtree_decl.hpp:409
double p
Definition ckdtree_decl.hpp:394
Rectangle< Dim > rect1
Definition ckdtree_decl.hpp:392
double inaccurate_distance_limit
Definition ckdtree_decl.hpp:407
Rectangle< Dim > rect2
Definition ckdtree_decl.hpp:393
void push_less_of(const ckdtree_intp_t which, const ckdtreenode *node)
Definition ckdtree_decl.hpp:532
double min_distance
Definition ckdtree_decl.hpp:397
RR_stack_item * stack
Definition ckdtree_decl.hpp:403
ckdtree_intp_t stack_size
Definition ckdtree_decl.hpp:400
std::vector< RR_stack_item > stack_arr
Definition ckdtree_decl.hpp:402
void push_greater_of(const ckdtree_intp_t which, const ckdtreenode *node)
Definition ckdtree_decl.hpp:537
const ckdtree< Dim > * tree
Definition ckdtree_decl.hpp:391
void pop()
Definition ckdtree_decl.hpp:542
double upper_bound
Definition ckdtree_decl.hpp:396
double epsfac
Definition ckdtree_decl.hpp:395
RectRectDistanceTracker(const ckdtree< Dim > *_tree, const Rectangle< Dim > &_rect1, const Rectangle< Dim > &_rect2, const double _p, const double eps, const double _upper_bound)
Definition ckdtree_decl.hpp:415
double max_distance
Definition ckdtree_decl.hpp:398
void push(const ckdtree_intp_t which, const intptr_t direction, const ckdtree_intp_t split_dim, const double split_val)
Definition ckdtree_decl.hpp:463
Definition ckdtree_decl.hpp:322
Rectangle(const double *_mins, const double *_maxes)
Definition ckdtree_decl.hpp:329
double * maxes() const
Definition ckdtree_decl.hpp:326
double * mins() const
Definition ckdtree_decl.hpp:327
std::array< double, 2 *m > buf
Definition ckdtree_decl.hpp:341
Definition ckdtree_decl.hpp:123
static constexpr ckdtree_intp_t m
Definition ckdtree_decl.hpp:124
std::vector< ckdtreenode > * tree_buffer
Definition ckdtree_decl.hpp:126
ckdtree_intp_t n
Definition ckdtree_decl.hpp:130
ckdtree_intp_t leafsize
Definition ckdtree_decl.hpp:131
ckdtree_intp_t * raw_indices
Definition ckdtree_decl.hpp:134
const double * raw_data
Definition ckdtree_decl.hpp:129
double * raw_maxes
Definition ckdtree_decl.hpp:132
ckdtreenode * ctree
Definition ckdtree_decl.hpp:127
double * raw_boxsize_data
Definition ckdtree_decl.hpp:135
double * raw_mins
Definition ckdtree_decl.hpp:133
Definition ckdtree_decl.hpp:112
ckdtree_intp_t split_dim
Definition ckdtree_decl.hpp:113
ckdtree_intp_t end_idx
Definition ckdtree_decl.hpp:117
ckdtree_intp_t start_idx
Definition ckdtree_decl.hpp:116
ckdtreenode * greater
Definition ckdtree_decl.hpp:119
double split
Definition ckdtree_decl.hpp:115
ckdtree_intp_t children
Definition ckdtree_decl.hpp:114
ckdtreenode * less
Definition ckdtree_decl.hpp:118
Definition ckdtree_decl.hpp:84
ckdtree_intp_t i
Definition ckdtree_decl.hpp:85
double v
Definition ckdtree_decl.hpp:87
ckdtree_intp_t j
Definition ckdtree_decl.hpp:86
Definition ckdtree_decl.hpp:1130
void remove()
Definition ckdtree_decl.hpp:1162
heap(ckdtree_intp_t initial_size)
Definition ckdtree_decl.hpp:1135
ckdtree_intp_t space
Definition ckdtree_decl.hpp:1133
void push(heapitem &item)
Definition ckdtree_decl.hpp:1140
std::vector< heapitem > _heap
Definition ckdtree_decl.hpp:1131
heapitem pop()
Definition ckdtree_decl.hpp:1193
ckdtree_intp_t n
Definition ckdtree_decl.hpp:1132
heapitem peek()
Definition ckdtree_decl.hpp:1160
Definition ckdtree_decl.hpp:1125
double priority
Definition ckdtree_decl.hpp:1126
heapcontents contents
Definition ckdtree_decl.hpp:1127
Definition ckdtree_decl.hpp:1248
static constexpr ckdtree_intp_t arena_size
Definition ckdtree_decl.hpp:1251
nodeinfo_pool()
Definition ckdtree_decl.hpp:1256
size_t current_offset
Definition ckdtree_decl.hpp:1254
nodeinfo< m > * allocate()
Definition ckdtree_decl.hpp:1258
std::vector< char > arena
Definition ckdtree_decl.hpp:1253
static constexpr ckdtree_intp_t alloc_size
Definition ckdtree_decl.hpp:1249
Definition ckdtree_decl.hpp:1206
double * mins()
Definition ckdtree_decl.hpp:1217
double buf[1]
Definition ckdtree_decl.hpp:1209
double * side_distances()
Definition ckdtree_decl.hpp:1211
double * maxes()
Definition ckdtree_decl.hpp:1216
void update_side_distance(const int d, const double new_side_distance, const double p)
Definition ckdtree_decl.hpp:1231
void init_box(const struct nodeinfo *from)
Definition ckdtree_decl.hpp:1219
const ckdtreenode * node
Definition ckdtree_decl.hpp:1207
double min_distance
Definition ckdtree_decl.hpp:1208
void init_plain(const struct nodeinfo *from)
Definition ckdtree_decl.hpp:1224
Definition ckdtree_decl.hpp:90
ckdtree_intp_t j
Definition ckdtree_decl.hpp:92
ckdtree_intp_t i
Definition ckdtree_decl.hpp:91
bool operator==(const ordered_pair &other) const
Definition ckdtree_decl.hpp:94
Definition ckdtree_decl.hpp:1120
void * ptrdata
Definition ckdtree_decl.hpp:1122
ckdtree_intp_t intdata
Definition ckdtree_decl.hpp:1121