forked from celeritas-project/celeritas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Algorithms.hh
643 lines (597 loc) · 20 KB
/
Algorithms.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//----------------------------------*-C++-*----------------------------------//
// Copyright 2020-2024 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file corecel/math/Algorithms.hh
//---------------------------------------------------------------------------//
#pragma once
#include <cmath>
#include <type_traits>
#include "celeritas_config.h"
#include "corecel/Assert.hh"
#include "corecel/Macros.hh"
#include "detail/AlgorithmsImpl.hh"
#include "detail/MathImpl.hh"
namespace celeritas
{
//---------------------------------------------------------------------------//
// Replace/extend <utility>
//---------------------------------------------------------------------------//
//! Implement perfect forwarding with device-friendly functions.
template<class T>
CELER_CONSTEXPR_FUNCTION T&&
forward(typename std::remove_reference<T>::type& v) noexcept
{
return static_cast<T&&>(v);
}
//! \cond
template<class T>
CELER_CONSTEXPR_FUNCTION T&&
forward(typename std::remove_reference<T>::type&& v) noexcept
{
return static_cast<T&&>(v);
}
//! \endcond
//---------------------------------------------------------------------------//
/*!
* Cast a value as an rvalue reference to allow move construction.
*/
template<class T>
CELER_CONSTEXPR_FUNCTION auto move(T&& v) noexcept ->
typename std::remove_reference<T>::type&&
{
return static_cast<typename std::remove_reference<T>::type&&>(v);
}
//---------------------------------------------------------------------------//
/*!
* Support swapping of trivial types.
*/
template<class T>
CELER_FORCEINLINE_FUNCTION void trivial_swap(T& a, T& b) noexcept
{
static_assert(std::is_trivially_move_constructible<T>::value,
"Value is not trivially copyable");
static_assert(std::is_trivially_move_assignable<T>::value,
"Value is not trivially movable");
static_assert(std::is_trivially_destructible<T>::value,
"Value is not trivially destructible");
T temp{::celeritas::move(a)};
a = ::celeritas::move(b);
b = ::celeritas::move(temp);
}
//---------------------------------------------------------------------------//
/*!
* Exchange values on host or device.
*/
template<class T, class U = T>
CELER_FORCEINLINE_FUNCTION T exchange(T& dst, U&& src)
{
T orig = std::move(dst);
dst = std::forward<U>(src);
return orig;
}
//---------------------------------------------------------------------------//
// Replace/extend <functional>
//---------------------------------------------------------------------------//
/*!
* Evaluator for the first argument being less than the second.
*/
template<class T = void>
struct Less
{
CELER_CONSTEXPR_FUNCTION auto
operator()(T const& lhs, T const& rhs) const noexcept -> decltype(auto)
{
return lhs < rhs;
}
};
//! Specialization of less with template deduction
template<>
struct Less<void>
{
template<class T, class U>
CELER_CONSTEXPR_FUNCTION auto operator()(T&& lhs, U&& rhs) const
-> decltype(auto)
{
return ::celeritas::forward<T>(lhs) < ::celeritas::forward<U>(rhs);
}
};
//---------------------------------------------------------------------------//
// Replace/extend <algorithm>
//---------------------------------------------------------------------------//
/*!
* Whether the predicate is true for all items.
*/
template<class InputIt, class Predicate>
inline CELER_FUNCTION bool all_of(InputIt iter, InputIt last, Predicate p)
{
for (; iter != last; ++iter)
{
if (!p(*iter))
return false;
}
return true;
}
//---------------------------------------------------------------------------//
/*!
* Whether the predicate is true for any item.
*/
template<class InputIt, class Predicate>
inline CELER_FUNCTION bool any_of(InputIt iter, InputIt last, Predicate p)
{
for (; iter != last; ++iter)
{
if (p(*iter))
return true;
}
return false;
}
//---------------------------------------------------------------------------//
/*!
* Clamp the value between lo and hi values.
*
* If the value is between lo and hi, return the value. Otherwise, return lo if
* it's below it, or hi above it.
*
* This replaces:
* \code
min(hi, max(lo, v))
* \endcode
* or
* \code
max(v, min(v, lo))
* \endcode
* assuming that the relationship between \c lo and \c hi holds.
*/
template<class T>
inline CELER_FUNCTION T const& clamp(T const& v, T const& lo, T const& hi)
{
CELER_EXPECT(!(hi < lo));
return v < lo ? lo : hi < v ? hi : v;
}
//---------------------------------------------------------------------------//
/*!
* Return the value or (if it's negative) then zero.
*
* This is constructed to correctly propagate \c NaN.
*/
template<class T>
CELER_CONSTEXPR_FUNCTION T clamp_to_nonneg(T v) noexcept
{
return (v < 0) ? 0 : v;
}
//---------------------------------------------------------------------------//
/*!
* Find the insertion point for a value in a sorted list using a binary search.
*/
template<class ForwardIt, class T, class Compare>
CELER_FORCEINLINE_FUNCTION ForwardIt
lower_bound(ForwardIt first, ForwardIt last, T const& value, Compare comp)
{
using CompareRef = std::add_lvalue_reference_t<Compare>;
return ::celeritas::detail::lower_bound_impl<CompareRef>(
first, last, value, comp);
}
//---------------------------------------------------------------------------//
/*!
* Find the insertion point for a value in a sorted list using a binary search.
*/
template<class ForwardIt, class T>
CELER_FORCEINLINE_FUNCTION ForwardIt lower_bound(ForwardIt first,
ForwardIt last,
T const& value)
{
return ::celeritas::lower_bound(first, last, value, Less<>{});
}
//---------------------------------------------------------------------------//
/*!
* Find the insertion point for a value in a sorted list using a linear search.
*/
template<class ForwardIt, class T, class Compare>
CELER_FORCEINLINE_FUNCTION ForwardIt lower_bound_linear(ForwardIt first,
ForwardIt last,
T const& value,
Compare comp)
{
using CompareRef = std::add_lvalue_reference_t<Compare>;
return ::celeritas::detail::lower_bound_linear_impl<CompareRef>(
first, last, value, comp);
}
//---------------------------------------------------------------------------//
/*!
* Find the insertion point for a value in a sorted list using a linear search.
*/
template<class ForwardIt, class T>
CELER_FORCEINLINE_FUNCTION ForwardIt lower_bound_linear(ForwardIt first,
ForwardIt last,
T const& value)
{
return ::celeritas::lower_bound_linear(first, last, value, Less<>{});
}
//---------------------------------------------------------------------------//
/*!
* Find the first element which is greater than <value>
*/
template<class ForwardIt, class T, class Compare>
CELER_FORCEINLINE_FUNCTION ForwardIt
upper_bound(ForwardIt first, ForwardIt last, T const& value, Compare comp)
{
using CompareRef = std::add_lvalue_reference_t<Compare>;
return ::celeritas::detail::upper_bound_impl<CompareRef>(
first, last, value, comp);
}
//---------------------------------------------------------------------------//
/*!
* Find the first element which is greater than <value>
*/
template<class ForwardIt, class T>
CELER_FORCEINLINE_FUNCTION ForwardIt upper_bound(ForwardIt first,
ForwardIt last,
T const& value)
{
return ::celeritas::upper_bound(first, last, value, Less<>{});
}
//---------------------------------------------------------------------------//
/*!
* Find the given element in a sorted range.
*/
template<class ForwardIt, class T, class Compare>
inline CELER_FUNCTION ForwardIt
find_sorted(ForwardIt first, ForwardIt last, T const& value, Compare comp)
{
auto iter = ::celeritas::lower_bound(first, last, value, comp);
if (iter == last || comp(*iter, value) || comp(value, *iter))
{
// Insertion point is off the end, or value is not equal
return last;
}
return iter;
}
//---------------------------------------------------------------------------//
/*!
* Find the given element in a sorted range.
*/
template<class ForwardIt, class T>
CELER_FORCEINLINE_FUNCTION ForwardIt find_sorted(ForwardIt first,
ForwardIt last,
T const& value)
{
return ::celeritas::find_sorted(first, last, value, Less<>{});
}
//---------------------------------------------------------------------------//
/*!
* Partition elements in the given range, "true" before "false".
*
* This is done by swapping elements until the range is partitioned.
*/
template<class ForwardIt, class Predicate>
CELER_FORCEINLINE_FUNCTION ForwardIt partition(ForwardIt first,
ForwardIt last,
Predicate pred)
{
using PredicateRef = std::add_lvalue_reference_t<Predicate>;
return ::celeritas::detail::partition_impl<PredicateRef>(first, last, pred);
}
//---------------------------------------------------------------------------//
/*!
* Sort an array on a single thread.
*
* This implementation is not thread-safe nor cooperative, but it can be called
* from CUDA code.
*/
template<class RandomAccessIt, class Compare>
CELER_FORCEINLINE_FUNCTION void
sort(RandomAccessIt first, RandomAccessIt last, Compare comp)
{
using CompareRef = std::add_lvalue_reference_t<Compare>;
return ::celeritas::detail::heapsort_impl<CompareRef>(first, last, comp);
}
//---------------------------------------------------------------------------//
/*!
* Sort an array on a single thread.
*/
template<class RandomAccessIt>
CELER_FORCEINLINE_FUNCTION void sort(RandomAccessIt first, RandomAccessIt last)
{
::celeritas::sort(first, last, Less<>{});
}
//---------------------------------------------------------------------------//
/*!
* Return the higher of two values.
*
* This function is specialized when building CUDA device code, which has
* special intrinsics for max.
*/
#ifndef __CUDA_ARCH__
template<class T>
#else
template<class T, std::enable_if_t<!std::is_arithmetic<T>::value, bool> = true>
#endif
CELER_CONSTEXPR_FUNCTION T const& max(T const& a, T const& b) noexcept
{
return (b > a) ? b : a;
}
#ifdef __CUDA_ARCH__
template<class T, std::enable_if_t<std::is_arithmetic<T>::value, bool> = true>
CELER_CONSTEXPR_FUNCTION T max(T a, T b) noexcept
{
return ::max(a, b);
}
#endif
//---------------------------------------------------------------------------//
/*!
* Return the lower of two values.
*
* This function is specialized when building CUDA device code, which has
* special intrinsics for min.
*/
#ifndef __CUDA_ARCH__
template<class T>
#else
template<class T, std::enable_if_t<!std::is_arithmetic<T>::value, bool> = true>
#endif
CELER_CONSTEXPR_FUNCTION T const& min(T const& a, T const& b) noexcept
{
return (b < a) ? b : a;
}
#ifdef __CUDA_ARCH__
template<class T, std::enable_if_t<std::is_arithmetic<T>::value, bool> = true>
CELER_CONSTEXPR_FUNCTION T min(T a, T b) noexcept
{
return ::min(a, b);
}
#endif
//---------------------------------------------------------------------------//
/*!
* Return an iterator to the lowest value in the range as defined by Compare.
*/
template<class ForwardIt, class Compare>
inline CELER_FUNCTION ForwardIt min_element(ForwardIt iter,
ForwardIt last,
Compare comp)
{
// Avoid incrementing past the end
if (iter == last)
return last;
ForwardIt result = iter++;
for (; iter != last; ++iter)
{
if (comp(*iter, *result))
result = iter;
}
return result;
}
//---------------------------------------------------------------------------//
/*!
* Return an iterator to the lowest value in the range.
*/
template<class ForwardIt>
CELER_FORCEINLINE_FUNCTION ForwardIt min_element(ForwardIt first,
ForwardIt last)
{
return ::celeritas::min_element(first, last, Less<decltype(*first)>{});
}
//---------------------------------------------------------------------------//
// Replace/extend <cmath>
//---------------------------------------------------------------------------//
//! Generate overloads for a single-argument math function
#define CELER_WRAP_MATH_FLOAT_DBL_1(PREFIX, FUNC) \
CELER_FORCEINLINE_FUNCTION float FUNC(float value) \
{ \
return ::PREFIX##FUNC##f(value); \
} \
CELER_FORCEINLINE_FUNCTION double FUNC(double value) \
{ \
return ::PREFIX##FUNC(value); \
}
#define CELER_WRAP_MATH_FLOAT_DBL_PTR_2(PREFIX, FUNC) \
CELER_FORCEINLINE_FUNCTION void FUNC(float value, float* a, float* b) \
{ \
return ::PREFIX##FUNC##f(value, a, b); \
} \
CELER_FORCEINLINE_FUNCTION void FUNC(double value, double* a, double* b) \
{ \
return ::PREFIX##FUNC(value, a, b); \
}
//---------------------------------------------------------------------------//
/*!
* Return an integer power of the input value.
*
* Example: \code
assert(9.0 == ipow<2>(3.0));
assert(256 == ipow<8>(2));
static_assert(256 == ipow<8>(2));
\endcode
*/
template<unsigned int N, class T>
CELER_CONSTEXPR_FUNCTION T ipow(T v) noexcept
{
if constexpr (N == 0)
{
CELER_DISCARD(v) // Suppress warning in older compilers
return 1;
}
else if constexpr (N % 2 == 0)
{
return ipow<N / 2>(v) * ipow<N / 2>(v);
}
else
{
return v * ipow<(N - 1) / 2>(v) * ipow<(N - 1) / 2>(v);
}
#if (__CUDACC_VER_MAJOR__ < 11) \
|| (__CUDACC_VER_MAJOR__ == 11 && __CUDACC_VER_MINOR__ < 5)
// "error: missing return statement at end of non-void function"
return T{};
#endif
}
//---------------------------------------------------------------------------//
/*!
* Raise a number to a power with simplifying assumptions.
*
* This should be faster than `std::pow` because we don't worry about
* exceptions for zeros, infinities, or negative values for a.
*
* Example: \code
assert(9.0 == fastpow(3.0, 2.0));
\endcode
*/
template<class T, std::enable_if_t<std::is_floating_point<T>::value, bool> = true>
inline CELER_FUNCTION T fastpow(T a, T b)
{
CELER_EXPECT(a > 0 || (a == 0 && b != 0));
return std::exp(b * std::log(a));
}
#ifdef __CUDACC__
CELER_WRAP_MATH_FLOAT_DBL_1(, rsqrt)
#else
//---------------------------------------------------------------------------//
/*!
* Calculate an inverse square root.
*/
inline CELER_FUNCTION double rsqrt(double value)
{
return 1.0 / std::sqrt(value);
}
//---------------------------------------------------------------------------//
/*!
* Calculate an inverse square root.
*/
inline CELER_FUNCTION float rsqrt(float value)
{
return 1.0f / std::sqrt(value);
}
#endif
//---------------------------------------------------------------------------//
/*!
* Use fused multiply-add for generic calculations.
*
* This provides a floating point specialization so that \c fma can be used in
* code that is accelerated for floating point calculations but still works
* correctly with integer arithmetic.
*
* Because of the single template parameter, it may be easier to use \c
* std::fma directly in most cases.
*/
template<class T, std::enable_if_t<std::is_floating_point<T>::value, bool> = true>
inline CELER_FUNCTION T fma(T a, T b, T y)
{
return std::fma(a, b, y);
}
//---------------------------------------------------------------------------//
/*!
* Provide an FMA-like interface for integers.
*/
template<class T, std::enable_if_t<!std::is_floating_point<T>::value, bool> = true>
CELER_CONSTEXPR_FUNCTION T fma(T a, T b, T y)
{
return a * b + y;
}
//---------------------------------------------------------------------------//
/*!
* Integer division, rounding up, for positive numbers.
*/
template<class T>
CELER_CONSTEXPR_FUNCTION T ceil_div(T top, T bottom)
{
static_assert(std::is_unsigned<T>::value, "Value is not an unsigned int");
return (top / bottom) + (top % bottom != 0);
}
//---------------------------------------------------------------------------//
/*!
* Negation that won't return signed zeros.
*/
template<class T>
[[nodiscard]] CELER_CONSTEXPR_FUNCTION T negate(T value)
{
return T{0} - value;
}
//---------------------------------------------------------------------------//
/*!
* Calculate the difference of squares \f$ a^2 - b^2 \f$.
*
* This calculation exchanges one multiplication for one addition, but it does
* not increase the accuracy of the computed result. It is used
* occasionally in Geant4 but is likely a premature optimization... see
* https://github.com/celeritas-project/celeritas/pull/1082
*/
template<class T>
CELER_CONSTEXPR_FUNCTION T diffsq(T a, T b)
{
return (a - b) * (a + b);
}
//---------------------------------------------------------------------------//
/*!
* Calculate the Euclidian modulus of two numbers.
*
* If both numbers are positive, this should be the same as fmod. If the
* sign of the remainder and denominator don't match, the remainder will be
* remapped so that it is between zero and the denominator.
*
* This function is useful for normalizing user-provided angles.
*/
template<class T, std::enable_if_t<std::is_floating_point<T>::value, bool> = true>
CELER_CONSTEXPR_FUNCTION T eumod(T numer, T denom)
{
T r = std::fmod(numer, denom);
if (r < 0)
{
if (denom >= 0)
{
r += denom;
}
else
{
r -= denom;
}
}
return r;
}
//---------------------------------------------------------------------------//
/*!
* Double-precision math constant (POSIX derivative).
*
* These should be used in *host* or *type-dependent* circumstances because, if
* using \c CELERITAS_REAL_TYPE=float, this could have more accuracy than
* \c celeritas::constants::pi .
*/
inline constexpr double m_pi = detail::m_pi;
//---------------------------------------------------------------------------//
//!@{
//! CUDA/HIP equivalent routines
#if CELER_DEVICE_SOURCE
// CUDA and HIP define sinpi and sinpif, and sincospi, sincosf
CELER_WRAP_MATH_FLOAT_DBL_1(, sinpi)
CELER_WRAP_MATH_FLOAT_DBL_1(, cospi)
CELER_WRAP_MATH_FLOAT_DBL_PTR_2(, sincospi)
CELER_WRAP_MATH_FLOAT_DBL_PTR_2(, sincos)
#elif __APPLE__ && !defined(__CLING__)
// Apple defines __sinpi, __sinpif, __sincospi, ...
CELER_WRAP_MATH_FLOAT_DBL_1(__, sinpi)
CELER_WRAP_MATH_FLOAT_DBL_1(__, cospi)
CELER_WRAP_MATH_FLOAT_DBL_PTR_2(__, sincospi)
CELER_WRAP_MATH_FLOAT_DBL_PTR_2(__, sincos)
#else
using ::celeritas::detail::cospi;
using ::celeritas::detail::sinpi;
CELER_FORCEINLINE void sincos(float a, float* s, float* c)
{
return detail::sincos(a, s, c);
}
CELER_FORCEINLINE void sincos(double a, double* s, double* c)
{
return detail::sincos(a, s, c);
}
CELER_FORCEINLINE void sincospi(float a, float* s, float* c)
{
return detail::sincospi(a, s, c);
}
CELER_FORCEINLINE void sincospi(double a, double* s, double* c)
{
return detail::sincospi(a, s, c);
}
#endif
//!@}
//---------------------------------------------------------------------------//
} // namespace celeritas