Compadre 1.7.6
Loading...
Searching...
No Matches
Compadre_PointCloudSearch.hpp
Go to the documentation of this file.
1// @HEADER
2// *****************************************************************************
3// Compadre: COMpatible PArticle Discretization and REmap Toolkit
4//
5// Copyright 2018 NTESS and the Compadre contributors.
6// SPDX-License-Identifier: BSD-2-Clause
7// *****************************************************************************
8// @HEADER
9#ifndef _COMPADRE_POINTCLOUDSEARCH_HPP_
10#define _COMPADRE_POINTCLOUDSEARCH_HPP_
11
12#include "Compadre_Typedefs.hpp"
14#include "nanoflann.hpp"
15#include <Kokkos_Core.hpp>
16#include <memory>
17
18namespace Compadre {
19
20//class sort_indices
21//{
22// private:
23// double* mparr;
24// public:
25// sort_indices(double* parr) : mparr(parr) {}
26// bool operator()(int i, int j) const { return mparr[i]<mparr[j]; }
27//};
28
29//! Custom RadiusResultSet for nanoflann that uses pre-allocated space for indices and radii
30//! instead of using std::vec for std::pairs
31template <typename _DistanceType, typename _IndexType = size_t>
33
34 public:
35
36 typedef _DistanceType DistanceType;
37 typedef _IndexType IndexType;
38
44
46 DistanceType radius_,
47 DistanceType* r_dist_, IndexType* i_dist_, const IndexType max_size_)
48 : radius(radius_), count(0), r_dist(r_dist_), i_dist(i_dist_), max_size(max_size_) {
49 init();
50 }
51
52 void init() {}
53
54 void clear() { count = 0; }
55
56 size_t size() const { return count; }
57
58 bool full() const { return true; }
59
60 bool addPoint(DistanceType dist, IndexType index) {
61
62 if (dist < radius) {
63 // would throw an exception here if count>=max_size, but this code is
64 // called inside of a parallel region so only an abort is possible,
65 // but this situation is recoverable
66 //
67 // instead, we increase count, but there is nowhere to store neighbors
68 // since we are working with pre-allocated space
69 // this will be discovered after returning from the search by comparing
70 // the count against the pre-allocate space dimensions
71 if (count<max_size) {
72 i_dist[count] = index;
73 r_dist[count] = dist;
74 }
75 count++;
76 }
77 return true;
78
79 }
80
81 DistanceType worstDist() const { return radius; }
82
83 std::pair<IndexType, DistanceType> worst_item() const {
84 // just to verify this isn't ever called
85 compadre_kernel_assert_release(false && "worst_item() should not be called.");
86 }
87
88 void sort() {
89 // puts closest neighbor as the first entry in the neighbor list
90 // leaves the rest unsorted
91
92 if (count > 0) {
93
94 // alternate sort for every entry, not currently being used
95 //int indices[count];
96 //for (int i=0; i<count; ++i) {
97 // indices[i] = i;
98 //}
99 //std::sort(indices, indices+count, sort_indices(r_dist));
100 //std::vector<IndexType> tmp_indices(count);
101 //std::vector<DistanceType> tmp_r(count);
102 //for (int i=0; i<count; ++i) {
103 // tmp_indices[i] = i_dist[indices[i]];
104 // tmp_r[i] = r_dist[indices[i]];
105 //}
106 //for (int i=0; i<count; ++i) {
107 // i_dist[i] = tmp_indices[i];
108 // r_dist[i] = tmp_r[i];
109 //}
110 IndexType loop_max = (count < max_size) ? count : max_size;
111
112 DistanceType best_distance = std::numeric_limits<DistanceType>::max();
113 IndexType best_distance_index = 0;
114 IndexType best_index = 0;
115 for (IndexType i=0; i<loop_max; ++i) {
116 if (r_dist[i] < best_distance) {
117 best_distance = r_dist[i];
118 best_distance_index = i_dist[i];
119 best_index = i;
120 }
121 }
122
123 if (best_index != 0) {
124 auto tmp_ind = i_dist[0];
125 i_dist[0] = best_distance_index;
126 i_dist[best_index] = tmp_ind;
127 auto tmp_dist = r_dist[0];
128 r_dist[0] = best_distance;
129 r_dist[best_index] = tmp_dist;
130 }
131 }
132 }
133};
134
135
136//! PointCloudSearch generates neighbor lists and window sizes for each target site
137/*!
138* Search methods can be run in dry-run mode, or not.
139*
140* #### When in dry-run mode:
141*
142* `neighbors_list` will be populated with number of neighbors found for each target site.
143*
144* This allows a user to know memory allocation needed before storage of neighbor indices.
145*
146* #### When not in dry-run mode:
147*
148* `neighbors_list_offsets` will be populated with offsets for values (dependent on method) determined by neighbor_list.
149* If a 2D view for `neighbors_list` is used, then \f$ N(i,j+1) \f$ will store the \f$ j^{th} \f$ neighbor of \f$ i \f$,
150* and \f$ N(i,0) \f$ will store the number of neighbors for target \f$ i \f$.
151*
152*/
153template <typename view_type>
155
156 public:
157
158 typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloudSearch<view_type> >,
160 typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloudSearch<view_type> >,
162 typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloudSearch<view_type> >,
164
165 protected:
166
167 //! source site coordinates
168 view_type _src_pts_view;
171
172 std::shared_ptr<tree_type_1d> _tree_1d;
173 std::shared_ptr<tree_type_2d> _tree_2d;
174 std::shared_ptr<tree_type_3d> _tree_3d;
175
176 public:
177
178 PointCloudSearch(view_type src_pts_view, const local_index_type dimension = -1,
179 const local_index_type max_leaf = -1)
180 : _src_pts_view(src_pts_view),
181 _dim((dimension < 0) ? src_pts_view.extent(1) : dimension),
182 _max_leaf((max_leaf < 0) ? 10 : max_leaf) {
183 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename view_type::memory_space>::accessible==1)
184 && "Views passed to PointCloudSearch at construction should be accessible from the host.");
185 };
186
188
189 //! Returns a liberal estimated upper bound on number of neighbors to be returned by a neighbor search
190 //! for a given choice of dimension, basis size, and epsilon_multiplier. Assumes quasiuniform distribution
191 //! of points. This result can be used to size a preallocated neighbor_lists kokkos view.
192 static inline int getEstimatedNumberNeighborsUpperBound(int unisolvency_size, const int dimension, const double epsilon_multiplier) {
193 int multiplier = 1;
194 if (dimension==1) multiplier = 2;
195 return multiplier * 2.0 * unisolvency_size * std::pow(epsilon_multiplier, dimension) + 1; // +1 is for the number of neighbors entry needed in the first entry of each row
196 }
197
198 //! Bounding box query method required by Nanoflann.
199 template <class BBOX> bool kdtree_get_bbox(BBOX& bb) const {return false;}
200
201 //! Returns the number of source sites
202 inline int kdtree_get_point_count() const {return _src_pts_view.extent(0);}
203
204 //! Returns the coordinate value of a point
205 inline double kdtree_get_pt(const int idx, int dim) const {return _src_pts_view(idx,dim);}
206
207 //! Returns the distance between a point and a source site, given its index
208 inline double kdtree_distance(const double* queryPt, const int idx, long long sz) const {
209
210 double distance = 0;
211 for (int i=0; i<_dim; ++i) {
212 distance += (_src_pts_view(idx,i)-queryPt[i])*(_src_pts_view(idx,i)-queryPt[i]);
213 }
214 return std::sqrt(distance);
215
216 }
217
219 if (_dim==1) {
220 _tree_1d = std::make_shared<tree_type_1d>(1, *this, nanoflann::KDTreeSingleIndexAdaptorParams(_max_leaf));
221 _tree_1d->buildIndex();
222 } else if (_dim==2) {
223 _tree_2d = std::make_shared<tree_type_2d>(2, *this, nanoflann::KDTreeSingleIndexAdaptorParams(_max_leaf));
224 _tree_2d->buildIndex();
225 } else if (_dim==3) {
226 _tree_3d = std::make_shared<tree_type_3d>(3, *this, nanoflann::KDTreeSingleIndexAdaptorParams(_max_leaf));
227 _tree_3d->buildIndex();
228 }
229 }
230
231 /*! \brief Generates neighbor lists of 2D view by performing a radius search
232 where the radius to be searched is in the epsilons view.
233 If uniform_radius is given, then this overrides the epsilons view radii sizes.
234 Accepts 2D neighbor_lists without number_of_neighbors_list.
235 \param is_dry_run [in] - whether to do a dry-run (find neighbors, but don't store)
236 \param trg_pts_view [in] - target coordinates from which to seek neighbors
237 \param neighbor_lists [out] - 2D view of neighbor lists to be populated from search
238 \param epsilons [in/out] - radius to search, overwritten if uniform_radius != 0
239 \param uniform_radius [in] - double != 0 determines whether to overwrite all epsilons for uniform search
240 \param max_search_radius [in] - largest valid search (useful only for MPI jobs if halo size exists)
241 */
242 template <typename trg_view_type, typename neighbor_lists_view_type, typename epsilons_view_type>
243 size_t generate2DNeighborListsFromRadiusSearch(bool is_dry_run, trg_view_type trg_pts_view,
244 neighbor_lists_view_type neighbor_lists, epsilons_view_type epsilons,
245 const double uniform_radius = 0.0, double max_search_radius = 0.0) {
246
247 // function does not populate epsilons, they must be prepopulated
248
249 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename trg_view_type::memory_space>::accessible==1) &&
250 "Target coordinates view passed to generate2DNeighborListsFromRadiusSearch should be accessible from the host.");
251 compadre_assert_release((((int)trg_pts_view.extent(1))>=_dim) &&
252 "Target coordinates view passed to generate2DNeighborListsFromRadiusSearch must have \
253 second dimension as large as _dim.");
254 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename neighbor_lists_view_type::memory_space>::accessible==1) &&
255 "Views passed to generate2DNeighborListsFromRadiusSearch should be accessible from the host.");
256 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename epsilons_view_type::memory_space>::accessible==1) &&
257 "Views passed to generate2DNeighborListsFromRadiusSearch should be accessible from the host.");
258
259 // loop size
260 const size_t num_target_sites = trg_pts_view.extent(0);
261
262 if ((!_tree_1d && _dim==1) || (!_tree_2d && _dim==2) || (!_tree_3d && _dim==3)) {
263 this->generateKDTree();
264 }
265
266 // check neighbor lists and epsilons view sizes
267 compadre_assert_release((neighbor_lists.extent(0)==num_target_sites
268 && neighbor_lists.extent(1)>=1)
269 && "neighbor lists View does not have large enough dimensions");
270 compadre_assert_release((neighbor_lists_view_type::rank==2) && "neighbor_lists must be a 2D Kokkos view.");
271
272 compadre_assert_release((epsilons.extent(0)==num_target_sites)
273 && "epsilons View does not have the correct dimension");
274
275 typedef Kokkos::View<double*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
276 scratch_double_view;
277
278 typedef Kokkos::View<size_t*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
279 scratch_int_view;
280
281 // determine scratch space size needed
282 size_t team_scratch_size = 0;
283 team_scratch_size += scratch_double_view::shmem_size(neighbor_lists.extent(1)); // distances
284 team_scratch_size += scratch_int_view::shmem_size(neighbor_lists.extent(1)); // indices
285 team_scratch_size += scratch_double_view::shmem_size(_dim); // target coordinate
286
287 auto dim = _dim;
288 // maximum number of neighbors found over all target sites' neighborhoods
289 size_t max_num_neighbors = 0;
290 // part 2. do radius search using window size from knn search
291 // each row of neighbor lists is a neighbor list for the target site corresponding to that row
292 auto scratch_level = (team_scratch_size > 32000) ? 1 : 0;
293 // respects serial scratch size limit of 32k
294 // from kokkos/core/src/Serial/Kokkos_Serial_Parallel_Team.hpp
295 auto policy = host_team_policy(num_target_sites, Kokkos::AUTO)
296 .set_scratch_size(scratch_level /*shared memory level*/, Kokkos::PerTeam(team_scratch_size));
297 auto radius_search = [=,*this](const host_member_type& teamMember, size_t& t_max_num_neighbors) {
298
299 // make unmanaged scratch views
300 scratch_double_view neighbor_distances(teamMember.team_scratch(scratch_level /*shared memory*/), neighbor_lists.extent(1));
301 scratch_int_view neighbor_indices(teamMember.team_scratch(scratch_level /*shared memory*/), neighbor_lists.extent(1));
302 scratch_double_view this_target_coord(teamMember.team_scratch(scratch_level /*shared memory*/), dim);
303
304 size_t neighbors_found = 0;
305
306 const int i = teamMember.league_rank();
307
308 // set epsilons if radius is specified
309 if (uniform_radius > 0) epsilons(i) = uniform_radius;
310
311 // needs furthest neighbor's distance for next portion
312 compadre_kernel_assert_release((epsilons(i)<=max_search_radius || max_search_radius==0) && "max_search_radius given (generally derived from the size of a halo region), and search radius needed would exceed this max_search_radius.");
313
314 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, neighbor_lists.extent(1)), [&](const int j) {
315 neighbor_indices(j) = 0;
316 neighbor_distances(j) = -1.0;
317 });
318 teamMember.team_barrier();
319
320 Kokkos::single(Kokkos::PerTeam(teamMember), [&] () {
321 // target_coords is LayoutLeft on device and its HostMirror, so giving a pointer to
322 // this data would lead to a wrong result if the device is a GPU
323
324 for (int j=0; j<dim; ++j) {
325 this_target_coord(j) = trg_pts_view(i,j);
326 }
327
328 nanoflann::SearchParams sp; // default parameters
329 Compadre::RadiusResultSet<double> rrs(epsilons(i)*epsilons(i), neighbor_distances.data(), neighbor_indices.data(), neighbor_lists.extent(1));
330 if (dim==1) {
331 neighbors_found = _tree_1d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
332 } else if (dim==2) {
333 neighbors_found = _tree_2d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
334 } else if (dim==3) {
335 neighbors_found = _tree_3d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
336 }
337
338 t_max_num_neighbors = (neighbors_found > t_max_num_neighbors) ? neighbors_found : t_max_num_neighbors;
339
340 // the number of neighbors is stored in column zero of the neighbor lists 2D array
341 neighbor_lists(i,0) = neighbors_found;
342
343 // epsilons already scaled and then set by search radius
344 });
345 teamMember.team_barrier();
346
347 // loop_bound so that we don't write into memory we don't have allocated
348 int loop_bound = (neighbors_found < neighbor_lists.extent(1)-1) ? neighbors_found : neighbor_lists.extent(1)-1;
349 // loop over each neighbor index and fill with a value
350 if (!is_dry_run) {
351 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, loop_bound), [&](const int j) {
352 // cast to an whatever data type the 2D array of neighbor lists is using
353 neighbor_lists(i,j+1) = static_cast<typename std::remove_pointer<typename std::remove_pointer<typename neighbor_lists_view_type::data_type>::type>::type>(neighbor_indices(j));
354 });
355 teamMember.team_barrier();
356 }
357
358 };
359 Kokkos::parallel_reduce("radius search 2D", policy, radius_search, Kokkos::Max<size_t>(max_num_neighbors));
360 Kokkos::fence();
361
362 // check if max_num_neighbors will fit onto pre-allocated space
363 compadre_assert_release((neighbor_lists.extent(1) >= (max_num_neighbors+1) || is_dry_run)
364 && "neighbor_lists does not contain enough columns for the maximum number of neighbors needing to be stored.");
365
366 return max_num_neighbors;
367 }
368
369 /*! \brief Generates compressed row neighbor lists by performing a radius search
370 where the radius to be searched is in the epsilons view.
371 If uniform_radius is given, then this overrides the epsilons view radii sizes.
372 Accepts 1D neighbor_lists with 1D number_of_neighbors_list.
373 \param is_dry_run [in] - whether to do a dry-run (find neighbors, but don't store)
374 \param trg_pts_view [in] - target coordinates from which to seek neighbors
375 \param neighbor_lists [out] - 1D view of neighbor lists to be populated from search
376 \param number_of_neighbors_list [in/out] - number of neighbors for each target site
377 \param epsilons [in/out] - radius to search, overwritten if uniform_radius != 0
378 \param uniform_radius [in] - double != 0 determines whether to overwrite all epsilons for uniform search
379 \param max_search_radius [in] - largest valid search (useful only for MPI jobs if halo size exists)
380 */
381 template <typename trg_view_type, typename neighbor_lists_view_type, typename epsilons_view_type>
382 size_t generateCRNeighborListsFromRadiusSearch(bool is_dry_run, trg_view_type trg_pts_view,
383 neighbor_lists_view_type neighbor_lists, neighbor_lists_view_type number_of_neighbors_list,
384 epsilons_view_type epsilons, const double uniform_radius = 0.0, double max_search_radius = 0.0) {
385
386 // function does not populate epsilons, they must be prepopulated
387
388 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename trg_view_type::memory_space>::accessible==1) &&
389 "Target coordinates view passed to generateCRNeighborListsFromRadiusSearch should be accessible from the host.");
390 compadre_assert_release((((int)trg_pts_view.extent(1))>=_dim) &&
391 "Target coordinates view passed to generateCRNeighborListsFromRadiusSearch must have \
392 second dimension as large as _dim.");
393 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename neighbor_lists_view_type::memory_space>::accessible==1) &&
394 "Views passed to generateCRNeighborListsFromRadiusSearch should be accessible from the host.");
395 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename epsilons_view_type::memory_space>::accessible==1) &&
396 "Views passed to generateCRNeighborListsFromRadiusSearch should be accessible from the host.");
397
398 // loop size
399 const size_t num_target_sites = trg_pts_view.extent(0);
400
401 if ((!_tree_1d && _dim==1) || (!_tree_2d && _dim==2) || (!_tree_3d && _dim==3)) {
402 this->generateKDTree();
403 }
404
405 compadre_assert_release((number_of_neighbors_list.extent(0)==num_target_sites)
406 && "number_of_neighbors_list or neighbor lists View does not have large enough dimensions");
407 compadre_assert_release((neighbor_lists_view_type::rank==1) && "neighbor_lists must be a 1D Kokkos view.");
408
409 typedef Kokkos::View<global_index_type*, typename neighbor_lists_view_type::array_layout,
410 typename neighbor_lists_view_type::memory_space, typename neighbor_lists_view_type::memory_traits> row_offsets_view_type;
411 row_offsets_view_type row_offsets;
412 int max_neighbor_list_row_storage_size = 1;
413 if (!is_dry_run) {
414 auto nla = CreateNeighborLists(neighbor_lists, number_of_neighbors_list);
415 max_neighbor_list_row_storage_size = nla.getMaxNumNeighbors();
416 Kokkos::resize(row_offsets, num_target_sites);
417 Kokkos::fence();
418 Kokkos::parallel_for(Kokkos::RangePolicy<host_execution_space>(0,num_target_sites), [&](const int i) {
419 row_offsets(i) = nla.getRowOffsetHost(i);
420 });
421 Kokkos::fence();
422 }
423
424 compadre_assert_release((epsilons.extent(0)==num_target_sites)
425 && "epsilons View does not have the correct dimension");
426
427 typedef Kokkos::View<double*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
428 scratch_double_view;
429
430 typedef Kokkos::View<size_t*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
431 scratch_int_view;
432
433 // determine scratch space size needed
434 size_t team_scratch_size = 0;
435 team_scratch_size += scratch_double_view::shmem_size(max_neighbor_list_row_storage_size); // distances
436 team_scratch_size += scratch_int_view::shmem_size(max_neighbor_list_row_storage_size); // indices
437 team_scratch_size += scratch_double_view::shmem_size(_dim); // target coordinate
438
439 auto dim = _dim;
440 // part 2. do radius search using window size from knn search
441 // each row of neighbor lists is a neighbor list for the target site corresponding to that row
442 auto scratch_level = (team_scratch_size > 32000) ? 1 : 0;
443 // respects serial scratch size limit of 32k
444 // from kokkos/core/src/Serial/Kokkos_Serial_Parallel_Team.hpp
445 auto policy = host_team_policy(num_target_sites, Kokkos::AUTO)
446 .set_scratch_size(scratch_level /*shared memory level*/, Kokkos::PerTeam(team_scratch_size));
447 auto radius_search = [=,*this](const host_member_type& teamMember) {
448
449 // make unmanaged scratch views
450 scratch_double_view neighbor_distances(teamMember.team_scratch(scratch_level /*shared memory*/), max_neighbor_list_row_storage_size);
451 scratch_int_view neighbor_indices(teamMember.team_scratch(scratch_level /*shared memory*/), max_neighbor_list_row_storage_size);
452 scratch_double_view this_target_coord(teamMember.team_scratch(scratch_level /*shared memory*/), dim);
453
454 size_t neighbors_found = 0;
455
456 const int i = teamMember.league_rank();
457
458 // set epsilons if radius is specified
459 if (uniform_radius > 0) epsilons(i) = uniform_radius;
460
461 // needs furthest neighbor's distance for next portion
462 compadre_kernel_assert_release((epsilons(i)<=max_search_radius || max_search_radius==0) && "max_search_radius given (generally derived from the size of a halo region), and search radius needed would exceed this max_search_radius.");
463
464 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, max_neighbor_list_row_storage_size), [&](const int j) {
465 neighbor_indices(j) = 0;
466 neighbor_distances(j) = -1.0;
467 });
468 teamMember.team_barrier();
469
470 Kokkos::single(Kokkos::PerTeam(teamMember), [&] () {
471 // target_coords is LayoutLeft on device and its HostMirror, so giving a pointer to
472 // this data would lead to a wrong result if the device is a GPU
473
474 for (int j=0; j<dim; ++j) {
475 this_target_coord(j) = trg_pts_view(i,j);
476 }
477
478 nanoflann::SearchParams sp; // default parameters
479 Compadre::RadiusResultSet<double> rrs(epsilons(i)*epsilons(i), neighbor_distances.data(), neighbor_indices.data(), max_neighbor_list_row_storage_size);
480 if (dim==1) {
481 neighbors_found = _tree_1d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
482 } else if (dim==2) {
483 neighbors_found = _tree_2d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
484 } else if (dim==3) {
485 neighbors_found = _tree_3d->template radiusSearchCustomCallback<Compadre::RadiusResultSet<double> >(this_target_coord.data(), rrs, sp) ;
486 }
487
488 // we check that neighbors found doesn't differ from dry-run or we store neighbors_found
489 // no check that neighbors found stay the same if uniform_radius specified (!=0)
490 if (is_dry_run || uniform_radius!=0.0) {
491 number_of_neighbors_list(i) = neighbors_found;
492 } else {
493 compadre_kernel_assert_release((neighbors_found==(size_t)number_of_neighbors_list(i))
494 && "Number of neighbors found changed since dry-run.");
495 }
496
497 // epsilons already scaled and then set by search radius
498 });
499 teamMember.team_barrier();
500
501 // loop_bound so that we don't write into memory we don't have allocated
502 int loop_bound = neighbors_found;
503 // loop over each neighbor index and fill with a value
504 if (!is_dry_run) {
505 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, loop_bound), [&](const int j) {
506 // cast to an whatever data type the 2D array of neighbor lists is using
507 neighbor_lists(row_offsets(i)+j) = static_cast<typename std::remove_pointer<typename std::remove_pointer<typename neighbor_lists_view_type::data_type>::type>::type>(neighbor_indices(j));
508 });
509 teamMember.team_barrier();
510 }
511
512 };
513 Kokkos::parallel_for("radius search CR", policy, radius_search);
514 Kokkos::fence();
515 size_t total_neighbors = 0;
516 for (size_t i=0; i<num_target_sites; ++i) {
517 total_neighbors += static_cast<size_t>(number_of_neighbors_list(i));
518 }
519
520 return total_neighbors;
521 }
522
523
524 /*! \brief Generates neighbor lists as 2D view by performing a k-nearest neighbor search
525 Only accepts 2D neighbor_lists without number_of_neighbors_list.
526 \param is_dry_run [in] - whether to do a dry-run (find neighbors, but don't store)
527 \param trg_pts_view [in] - target coordinates from which to seek neighbors
528 \param neighbor_lists [out] - 2D view of neighbor lists to be populated from search
529 \param epsilons [in/out] - radius to search, overwritten if uniform_radius != 0
530 \param neighbors_needed [in] - k neighbors needed as a minimum
531 \param epsilon_multiplier [in] - distance to kth neighbor multiplied by epsilon_multiplier for follow-on radius search
532 \param max_search_radius [in] - largest valid search (useful only for MPI jobs if halo size exists)
533 \param verify_unisolvency [in] - verify at least neighbors_needed for unisolvency are found
534 */
535 template <typename trg_view_type, typename neighbor_lists_view_type, typename epsilons_view_type>
536 size_t generate2DNeighborListsFromKNNSearch(bool is_dry_run, trg_view_type trg_pts_view,
537 neighbor_lists_view_type neighbor_lists, epsilons_view_type epsilons,
538 const int neighbors_needed, const double epsilon_multiplier = 1.6,
539 double max_search_radius = 0.0, const bool verify_unisolvency = true) {
540
541 // First, do a knn search (removes need for guessing initial search radius)
542
543 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename trg_view_type::memory_space>::accessible==1) &&
544 "Target coordinates view passed to generate2DNeighborListsFromKNNSearch should be accessible from the host.");
545 compadre_assert_release((((int)trg_pts_view.extent(1))>=_dim) &&
546 "Target coordinates view passed to generate2DNeighborListsFromRadiusSearch must have \
547 second dimension as large as _dim.");
548 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename neighbor_lists_view_type::memory_space>::accessible==1) &&
549 "Views passed to generate2DNeighborListsFromKNNSearch should be accessible from the host.");
550 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename epsilons_view_type::memory_space>::accessible==1) &&
551 "Views passed to generate2DNeighborListsFromKNNSearch should be accessible from the host.");
552
553 // loop size
554 const size_t num_target_sites = trg_pts_view.extent(0);
555
556 if ((!_tree_1d && _dim==1) || (!_tree_2d && _dim==2) || (!_tree_3d && _dim==3)) {
557 this->generateKDTree();
558 }
559 Kokkos::fence();
560
561 compadre_assert_release((num_target_sites==0 || // sizes don't matter when there are no targets
562 (neighbor_lists.extent(0)==num_target_sites
563 && neighbor_lists.extent(1)>=(size_t)(neighbors_needed+1)))
564 && "neighbor lists View does not have large enough dimensions");
565 compadre_assert_release((neighbor_lists_view_type::rank==2) && "neighbor_lists must be a 2D Kokkos view.");
566
567 compadre_assert_release((epsilons.extent(0)==num_target_sites)
568 && "epsilons View does not have the correct dimension");
569
570 typedef Kokkos::View<double*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
571 scratch_double_view;
572
573 typedef Kokkos::View<size_t*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
574 scratch_int_view;
575
576 // determine scratch space size needed
577 size_t team_scratch_size = 0;
578 team_scratch_size += scratch_double_view::shmem_size(neighbor_lists.extent(1)); // distances
579 team_scratch_size += scratch_int_view::shmem_size(neighbor_lists.extent(1)); // indices
580 team_scratch_size += scratch_double_view::shmem_size(_dim); // target coordinate
581
582 auto dim = _dim;
583 // minimum number of neighbors found over all target sites' neighborhoods
584 size_t min_num_neighbors = 0;
585 //
586 // part 1. do knn search for neighbors needed for unisolvency
587 // each row of neighbor lists is a neighbor list for the target site corresponding to that row
588 //
589 // as long as neighbor_lists can hold the number of neighbors_needed, we don't need to check
590 // that the maximum number of neighbors will fit into neighbor_lists
591 //
592 auto scratch_level = (team_scratch_size > 32000) ? 1 : 0;
593 // respects serial scratch size limit of 32k
594 // from kokkos/core/src/Serial/Kokkos_Serial_Parallel_Team.hpp
595 auto policy = host_team_policy(num_target_sites, Kokkos::AUTO)
596 .set_scratch_size(scratch_level /*shared memory level*/, Kokkos::PerTeam(team_scratch_size));
597 auto knn_search = [=,*this](const host_member_type& teamMember, size_t& t_min_num_neighbors) {
598
599 // make unmanaged scratch views
600 scratch_double_view neighbor_distances(teamMember.team_scratch(scratch_level /*shared memory*/), neighbor_lists.extent(1));
601 scratch_int_view neighbor_indices(teamMember.team_scratch(scratch_level /*shared memory*/), neighbor_lists.extent(1));
602 scratch_double_view this_target_coord(teamMember.team_scratch(scratch_level /*shared memory*/), dim);
603
604 size_t neighbors_found = 0;
605
606 const int i = teamMember.league_rank();
607
608 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, neighbor_lists.extent(1)), [=](const int j) {
609 neighbor_indices(j) = 0;
610 neighbor_distances(j) = -1.0;
611 });
612
613 teamMember.team_barrier();
614 Kokkos::single(Kokkos::PerTeam(teamMember), [&] () {
615 // target_coords is LayoutLeft on device and its HostMirror, so giving a pointer to
616 // this data would lead to a wrong result if the device is a GPU
617
618 for (int j=0; j<dim; ++j) {
619 this_target_coord(j) = trg_pts_view(i,j);
620 }
621
622 if (dim==1) {
623 neighbors_found = _tree_1d->knnSearch(this_target_coord.data(), neighbors_needed,
624 neighbor_indices.data(), neighbor_distances.data()) ;
625 } else if (dim==2) {
626 neighbors_found = _tree_2d->knnSearch(this_target_coord.data(), neighbors_needed,
627 neighbor_indices.data(), neighbor_distances.data()) ;
628 } else if (dim==3) {
629 neighbors_found = _tree_3d->knnSearch(this_target_coord.data(), neighbors_needed,
630 neighbor_indices.data(), neighbor_distances.data()) ;
631 }
632
633 // get minimum number of neighbors found over all target sites' neighborhoods
634 t_min_num_neighbors = (neighbors_found < t_min_num_neighbors) ? neighbors_found : t_min_num_neighbors;
635
636 // scale by epsilon_multiplier to window from location where the last neighbor was found
637 epsilons(i) = (neighbor_distances(neighbors_found-1) > 0) ?
638 std::sqrt(neighbor_distances(neighbors_found-1))*epsilon_multiplier : 1e-14*epsilon_multiplier;
639 // the only time the second case using 1e-14 is used is when either zero neighbors or exactly one
640 // neighbor (neighbor is target site) is found. when the follow on radius search is conducted, the one
641 // neighbor (target site) will not be found if left at 0, so any positive amount will do, however 1e-14
642 // should be small enough to ensure that other neighbors are not found
643
644 // needs furthest neighbor's distance for next portion
645 compadre_kernel_assert_release((neighbors_found<neighbor_lists.extent(1) || is_dry_run)
646 && "Neighbors found exceeded storage capacity in neighbor list.");
647 compadre_kernel_assert_release((epsilons(i)<=max_search_radius || max_search_radius==0 || is_dry_run)
648 && "max_search_radius given (generally derived from the size of a halo region), \
649 and search radius needed would exceed this max_search_radius.");
650 // neighbor_distances stores squared distances from neighbor to target, as returned by nanoflann
651 });
652 };
653 Kokkos::parallel_reduce("knn search 2D", policy, knn_search, Kokkos::Min<size_t>(min_num_neighbors));
654
655 // if no target sites, then min_num_neighbors is set to neighbors_needed
656 // which also avoids min_num_neighbors being improperly set by min reduction
657 if (num_target_sites==0) min_num_neighbors = neighbors_needed;
658
659 if (verify_unisolvency) {
660 // Next, check that we found the neighbors_needed number that we require for unisolvency
661 compadre_assert_release((num_target_sites==0 || (min_num_neighbors>=(size_t)neighbors_needed))
662 && "Neighbor search failed to find number of neighbors needed for unisolvency.");
663 }
664
665 // call a radius search using values now stored in epsilons
666 size_t max_num_neighbors = generate2DNeighborListsFromRadiusSearch(is_dry_run, trg_pts_view, neighbor_lists,
667 epsilons, 0.0 /*don't set uniform radius*/, max_search_radius);
668
669 return max_num_neighbors;
670 }
671
672 /*! \brief Generates compressed row neighbor lists by performing a k-nearest neighbor search
673 Only accepts 1D neighbor_lists with 1D number_of_neighbors_list.
674 \param is_dry_run [in] - whether to do a dry-run (find neighbors, but don't store)
675 \param trg_pts_view [in] - target coordinates from which to seek neighbors
676 \param neighbor_lists [out] - 1D view of neighbor lists to be populated from search
677 \param number_of_neighbors_list [in/out] - number of neighbors for each target site
678 \param epsilons [in/out] - radius to search, overwritten if uniform_radius != 0
679 \param neighbors_needed [in] - k neighbors needed as a minimum
680 \param epsilon_multiplier [in] - distance to kth neighbor multiplied by epsilon_multiplier for follow-on radius search
681 \param max_search_radius [in] - largest valid search (useful only for MPI jobs if halo size exists)
682 \param verify_unisolvency [in] - verify at least neighbors_needed for unisolvency are found
683 */
684 template <typename trg_view_type, typename neighbor_lists_view_type, typename epsilons_view_type>
685 size_t generateCRNeighborListsFromKNNSearch(bool is_dry_run, trg_view_type trg_pts_view,
686 neighbor_lists_view_type neighbor_lists, neighbor_lists_view_type number_of_neighbors_list,
687 epsilons_view_type epsilons, const int neighbors_needed, const double epsilon_multiplier = 1.6,
688 double max_search_radius = 0.0, const bool verify_unisolvency = true) {
689
690 // First, do a knn search (removes need for guessing initial search radius)
691
692 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename trg_view_type::memory_space>::accessible==1) &&
693 "Target coordinates view passed to generateCRNeighborListsFromKNNSearch should be accessible from the host.");
694 compadre_assert_release((((int)trg_pts_view.extent(1))>=_dim) &&
695 "Target coordinates view passed to generateCRNeighborListsFromRadiusSearch must have \
696 second dimension as large as _dim.");
697 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename neighbor_lists_view_type::memory_space>::accessible==1) &&
698 "Views passed to generateCRNeighborListsFromKNNSearch should be accessible from the host.");
699 compadre_assert_release((Kokkos::SpaceAccessibility<host_execution_space, typename epsilons_view_type::memory_space>::accessible==1) &&
700 "Views passed to generateCRNeighborListsFromKNNSearch should be accessible from the host.");
701
702 // loop size
703 const size_t num_target_sites = trg_pts_view.extent(0);
704
705 if ((!_tree_1d && _dim==1) || (!_tree_2d && _dim==2) || (!_tree_3d && _dim==3)) {
706 this->generateKDTree();
707 }
708 Kokkos::fence();
709
710 compadre_assert_release((number_of_neighbors_list.extent(0)==num_target_sites )
711 && "number_of_neighbors_list or neighbor lists View does not have large enough dimensions");
712 compadre_assert_release((neighbor_lists_view_type::rank==1) && "neighbor_lists must be a 1D Kokkos view.");
713
714 // if dry-run, neighbors_needed, else max over previous dry-run
715 int max_neighbor_list_row_storage_size = neighbors_needed;
716 if (!is_dry_run) {
717 auto nla = CreateNeighborLists(neighbor_lists, number_of_neighbors_list);
718 max_neighbor_list_row_storage_size = nla.getMaxNumNeighbors();
719 }
720
721 compadre_assert_release((epsilons.extent(0)==num_target_sites)
722 && "epsilons View does not have the correct dimension");
723
724 typedef Kokkos::View<double*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
725 scratch_double_view;
726
727 typedef Kokkos::View<size_t*, host_scratch, Kokkos::MemoryTraits<Kokkos::Unmanaged> >
728 scratch_int_view;
729
730 // determine scratch space size needed
731 size_t team_scratch_size = 0;
732 team_scratch_size += scratch_double_view::shmem_size(max_neighbor_list_row_storage_size); // distances
733 team_scratch_size += scratch_int_view::shmem_size(max_neighbor_list_row_storage_size); // indices
734 team_scratch_size += scratch_double_view::shmem_size(_dim); // target coordinate
735
736 auto dim = _dim;
737 // minimum number of neighbors found over all target sites' neighborhoods
738 size_t min_num_neighbors = 0;
739 //
740 // part 1. do knn search for neighbors needed for unisolvency
741 // each row of neighbor lists is a neighbor list for the target site corresponding to that row
742 //
743 // as long as neighbor_lists can hold the number of neighbors_needed, we don't need to check
744 // that the maximum number of neighbors will fit into neighbor_lists
745 //
746 auto scratch_level = (team_scratch_size > 32000) ? 1 : 0;
747 // respects serial scratch size limit of 32k
748 // from kokkos/core/src/Serial/Kokkos_Serial_Parallel_Team.hpp
749 auto policy = host_team_policy(num_target_sites, Kokkos::AUTO)
750 .set_scratch_size(scratch_level /*shared memory level*/, Kokkos::PerTeam(team_scratch_size));
751 auto knn_search = [=,*this](const host_member_type& teamMember, size_t& t_min_num_neighbors) {
752
753 // make unmanaged scratch views
754 scratch_double_view neighbor_distances(teamMember.team_scratch(scratch_level /*shared memory*/), max_neighbor_list_row_storage_size);
755 scratch_int_view neighbor_indices(teamMember.team_scratch(scratch_level /*shared memory*/), max_neighbor_list_row_storage_size);
756 scratch_double_view this_target_coord(teamMember.team_scratch(scratch_level /*shared memory*/), dim);
757
758 size_t neighbors_found = 0;
759
760 const int i = teamMember.league_rank();
761
762 Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, max_neighbor_list_row_storage_size), [=](const int j) {
763 neighbor_indices(j) = 0;
764 neighbor_distances(j) = -1.0;
765 });
766
767 teamMember.team_barrier();
768 Kokkos::single(Kokkos::PerTeam(teamMember), [&] () {
769 // target_coords is LayoutLeft on device and its HostMirror, so giving a pointer to
770 // this data would lead to a wrong result if the device is a GPU
771
772 for (int j=0; j<dim; ++j) {
773 this_target_coord(j) = trg_pts_view(i,j);
774 }
775
776 if (dim==1) {
777 neighbors_found = _tree_1d->knnSearch(this_target_coord.data(), neighbors_needed,
778 neighbor_indices.data(), neighbor_distances.data()) ;
779 } else if (dim==2) {
780 neighbors_found = _tree_2d->knnSearch(this_target_coord.data(), neighbors_needed,
781 neighbor_indices.data(), neighbor_distances.data()) ;
782 } else if (dim==3) {
783 neighbors_found = _tree_3d->knnSearch(this_target_coord.data(), neighbors_needed,
784 neighbor_indices.data(), neighbor_distances.data()) ;
785 }
786
787 // get minimum number of neighbors found over all target sites' neighborhoods
788 t_min_num_neighbors = (neighbors_found < t_min_num_neighbors) ? neighbors_found : t_min_num_neighbors;
789
790 // scale by epsilon_multiplier to window from location where the last neighbor was found
791 // Guard the zero-neighbor case before indexing neighbor_distances(neighbors_found-1).
792 if (neighbors_found > 0 && neighbor_distances(neighbors_found-1) > 0) {
793 epsilons(i) = std::sqrt(neighbor_distances(neighbors_found-1))*epsilon_multiplier;
794 } else {
795 epsilons(i) = 1e-14*epsilon_multiplier;
796 }
797 // The 1e-14 case is used when either zero neighbors or exactly one
798 // neighbor (the target site) is found. When the follow-on radius search is conducted, the one
799 // neighbor (target site) will not be found if left at 0, so any positive amount will do, however 1e-14
800 // should be small enough to ensure that other neighbors are not found
801
802 compadre_kernel_assert_release((epsilons(i)<=max_search_radius || max_search_radius==0 || is_dry_run)
803 && "max_search_radius given (generally derived from the size of a halo region), \
804 and search radius needed would exceed this max_search_radius.");
805 // neighbor_distances stores squared distances from neighbor to target, as returned by nanoflann
806 });
807 };
808 Kokkos::parallel_reduce("knn search CR", policy, knn_search, Kokkos::Min<size_t>(min_num_neighbors));
809
810 // if no target sites, then min_num_neighbors is set to neighbors_needed
811 // which also avoids min_num_neighbors being improperly set by min reduction
812 if (num_target_sites==0) min_num_neighbors = neighbors_needed;
813
814 if (verify_unisolvency) {
815 // Next, check that we found the neighbors_needed number that we require for unisolvency
816 compadre_assert_release((num_target_sites==0 || (min_num_neighbors>=(size_t)neighbors_needed))
817 && "Neighbor search failed to find number of neighbors needed for unisolvency.");
818 }
819
820 // call a radius search using values now stored in epsilons
821 generateCRNeighborListsFromRadiusSearch(is_dry_run, trg_pts_view, neighbor_lists,
822 number_of_neighbors_list, epsilons, 0.0 /*don't set uniform radius*/, max_search_radius);
823
824 size_t total_neighbors = 0;
825 for (size_t i=0; i<num_target_sites; ++i) {
826 total_neighbors += static_cast<size_t>(number_of_neighbors_list(i));
827 }
828
829 return total_neighbors;
830 }
831}; // PointCloudSearch
832
833//! CreatePointCloudSearch allows for the construction of an object of type PointCloudSearch with template deduction
834template <typename view_type>
835PointCloudSearch<view_type> CreatePointCloudSearch(view_type src_view, const local_index_type dimensions = -1, const local_index_type max_leaf = -1) {
836 return PointCloudSearch<view_type>(src_view, dimensions, max_leaf);
837}
838
839} // Compadre
840
841#endif
#define compadre_kernel_assert_release(condition)
compadre_kernel_assert_release is similar to compadre_assert_release, but is a call on the device,...
#define compadre_assert_release(condition)
compadre_assert_release is used for assertions that should always be checked, but generally are not e...
PointCloudSearch generates neighbor lists and window sizes for each target site.
bool kdtree_get_bbox(BBOX &bb) const
Bounding box query method required by Nanoflann.
double kdtree_get_pt(const int idx, int dim) const
Returns the coordinate value of a point.
std::shared_ptr< tree_type_1d > _tree_1d
size_t generateCRNeighborListsFromRadiusSearch(bool is_dry_run, trg_view_type trg_pts_view, neighbor_lists_view_type neighbor_lists, neighbor_lists_view_type number_of_neighbors_list, epsilons_view_type epsilons, const double uniform_radius=0.0, double max_search_radius=0.0)
Generates compressed row neighbor lists by performing a radius search where the radius to be searched...
double kdtree_distance(const double *queryPt, const int idx, long long sz) const
Returns the distance between a point and a source site, given its index.
view_type _src_pts_view
source site coordinates
nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor< double, PointCloudSearch< view_type > >, PointCloudSearch< view_type >, 1 > tree_type_1d
nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor< double, PointCloudSearch< view_type > >, PointCloudSearch< view_type >, 2 > tree_type_2d
static int getEstimatedNumberNeighborsUpperBound(int unisolvency_size, const int dimension, const double epsilon_multiplier)
Returns a liberal estimated upper bound on number of neighbors to be returned by a neighbor search fo...
size_t generate2DNeighborListsFromRadiusSearch(bool is_dry_run, trg_view_type trg_pts_view, neighbor_lists_view_type neighbor_lists, epsilons_view_type epsilons, const double uniform_radius=0.0, double max_search_radius=0.0)
Generates neighbor lists of 2D view by performing a radius search where the radius to be searched is ...
int kdtree_get_point_count() const
Returns the number of source sites.
size_t generateCRNeighborListsFromKNNSearch(bool is_dry_run, trg_view_type trg_pts_view, neighbor_lists_view_type neighbor_lists, neighbor_lists_view_type number_of_neighbors_list, epsilons_view_type epsilons, const int neighbors_needed, const double epsilon_multiplier=1.6, double max_search_radius=0.0, const bool verify_unisolvency=true)
Generates compressed row neighbor lists by performing a k-nearest neighbor search Only accepts 1D nei...
nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor< double, PointCloudSearch< view_type > >, PointCloudSearch< view_type >, 3 > tree_type_3d
PointCloudSearch(view_type src_pts_view, const local_index_type dimension=-1, const local_index_type max_leaf=-1)
size_t generate2DNeighborListsFromKNNSearch(bool is_dry_run, trg_view_type trg_pts_view, neighbor_lists_view_type neighbor_lists, epsilons_view_type epsilons, const int neighbors_needed, const double epsilon_multiplier=1.6, double max_search_radius=0.0, const bool verify_unisolvency=true)
Generates neighbor lists as 2D view by performing a k-nearest neighbor search Only accepts 2D neighbo...
std::shared_ptr< tree_type_3d > _tree_3d
std::shared_ptr< tree_type_2d > _tree_2d
Custom RadiusResultSet for nanoflann that uses pre-allocated space for indices and radii instead of u...
RadiusResultSet(DistanceType radius_, DistanceType *r_dist_, IndexType *i_dist_, const IndexType max_size_)
std::pair< IndexType, DistanceType > worst_item() const
bool addPoint(DistanceType dist, IndexType index)
PointCloudSearch< view_type > CreatePointCloudSearch(view_type src_view, const local_index_type dimensions=-1, const local_index_type max_leaf=-1)
CreatePointCloudSearch allows for the construction of an object of type PointCloudSearch with templat...
NeighborLists< view_type > CreateNeighborLists(view_type number_of_neighbors_list)
CreateNeighborLists allows for the construction of an object of type NeighborLists with template dedu...
Kokkos::TeamPolicy< host_execution_space > host_team_policy
host_team_policy::member_type host_member_type
std::size_t global_index_type