bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
bi_kappa_distribution.H
Go to the documentation of this file.
1#ifndef _BI_KAPPA_DISTRIBUTION_H_
2#define _BI_KAPPA_DISTRIBUTION_H_
3
7#define BI_KAPPA_VERSION_MAJOR 3
8#define BI_KAPPA_VERSION_MINOR 0
9#define BI_KAPPA_VERSION_PATCH 0
10#define BI_KAPPA_VERSION_STRING "3.0.0"
11
12#include <array>
13#include <algorithm>
14#include <cmath>
15#include <limits>
16#include <random>
17#include <stdexcept>
18
19// This sampler decides what it may return by materializing a value and asking whether it is
20// finite, and no_cap() is +infinity. `-ffast-math` (which defines __FAST_MATH__) licenses a
21// compiler to assume that no infinity or NaN occurs, and so to fold `mag <= max()` to `true`:
22// an overflowed component could then be returned as if it were a number, n_nonfinite() would
23// read zero, and no_cap() would not be reliable. A finite cap (the default of 20) still
24// rejects such draws, because it compares against a finite bound. The header therefore
25// compiles under fast-math but says so; define BI_KAPPA_ALLOW_FAST_MATH to silence the note.
26#if defined(__FAST_MATH__) && !defined(BI_KAPPA_ALLOW_FAST_MATH)
27#pragma message("bi_kappa_distribution.H: compiled with -ffast-math; no_cap() and the overflow " \
28 "counters are unreliable in this mode. Define BI_KAPPA_ALLOW_FAST_MATH to " \
29 "silence this note.")
30#endif
31
53{
54
56template <typename GeneratorType> inline int engineBits()
57{
58 unsigned long long range= static_cast<unsigned long long>(GeneratorType::max()) -
59 static_cast<unsigned long long>(GeneratorType::min());
60 int bits= 0;
61 while (range >= 1ULL)
62 {
63 ++bits;
64 range>>= 1;
65 }
66 return bits;
67}
68
83template <typename RealType, typename GeneratorType> RealType openCanonical(GeneratorType &gen)
84{
85 const int bits= std::numeric_limits<RealType>::digits - 1;
86 const int per= engineBits<GeneratorType>();
87 unsigned long long k= 0;
88 int have= 0;
89 while (have < bits)
90 {
91 const unsigned long long word= static_cast<unsigned long long>(gen()) -
92 static_cast<unsigned long long>(GeneratorType::min());
93 const int take= (bits - have < per) ? (bits - have) : per;
94 k= (k << take) | (word & ((1ULL << take) - 1ULL));
95 have+= take;
96 }
97 return (static_cast<RealType>(k) + RealType(0.5)) * std::ldexp(RealType(1.0), -bits);
98}
99
103template <typename RealType, typename GeneratorType>
104RealType polarNormal(GeneratorType &gen, RealType &cache, bool &cached)
105{
106 if (cached)
107 {
108 cached= false;
109 return cache;
110 }
111 RealType x, y, s;
112 do
113 {
114 x= RealType(2.0) * openCanonical<RealType, GeneratorType>(gen) - RealType(1.0);
115 y= RealType(2.0) * openCanonical<RealType, GeneratorType>(gen) - RealType(1.0);
116 s= x * x + y * y;
117 } while (s >= RealType(1.0));
118 // s == 0 is unreachable: openCanonical never returns exactly 1/2, so neither x nor y is
119 // ever exactly zero.
120 const RealType f= std::sqrt(RealType(-2.0) * std::log(s) / s);
121 cache= y * f;
122 cached= true;
123 return x * f;
124}
125
129template <typename RealType, typename GeneratorType>
130RealType marsagliaTsangGamma(RealType shape, GeneratorType &gen, RealType &ncache, bool &ncached)
131{
132 const RealType d= shape - RealType(1.0) / RealType(3.0);
133 const RealType c= RealType(1.0) / std::sqrt(RealType(9.0) * d);
134 for (;;)
135 {
136 RealType x, v;
137 do
138 {
139 x= polarNormal<RealType, GeneratorType>(gen, ncache, ncached);
140 v= RealType(1.0) + c * x;
141 } while (v <= RealType(0.0));
142 v= v * v * v;
143 const RealType u= openCanonical<RealType, GeneratorType>(gen);
144 const RealType xx= x * x;
145 if (u < RealType(1.0) - RealType(0.0331) * xx * xx)
146 {
147 return d * v;
148 }
149 if (std::log(u) < RealType(0.5) * xx + d * (RealType(1.0) - v + std::log(v)))
150 {
151 return d * v;
152 }
153 }
154}
155
183template <typename RealType, typename GeneratorType>
184RealType logGamma(RealType a, GeneratorType &gen, RealType &ncache, bool &ncached)
185{
186 const RealType y=
187 marsagliaTsangGamma<RealType, GeneratorType>(a + RealType(1.0), gen, ncache, ncached);
188 const RealType u= openCanonical<RealType, GeneratorType>(gen);
189 return std::log(y) + std::log(u) / a;
190}
191
230template <typename RealType>
231bool materializeComponents(RealType logR, const std::array<RealType, 3> &g,
232 std::array<RealType, 3> &point)
233{
234 const RealType maxFinite= std::numeric_limits<RealType>::max();
235 const RealType rTry= std::exp(logR);
236 // `false` for +infinity and for NaN, both of which fail every comparison.
237 const bool radiusRepresentable= (rTry <= maxFinite);
238 const RealType R= radiusRepresentable ? rTry : RealType(0.0);
239
240 bool anyOverflow= false;
241 for (int j= 0; j < 3; ++j)
242 {
243 if (g[j] == RealType(0.0))
244 {
245 point[j]= RealType(0.0);
246 continue;
247 }
248 const RealType absG= std::abs(g[j]);
249 // What decides representability is the number the caller will receive. A
250 // magnitude that rounds past `max()` becomes an infinity here and is counted;
251 // deciding from a logarithm instead would be wrong in both directions at once.
252 const RealType mag= radiusRepresentable ? R * absG
253 : std::exp(logR + std::log(absG));
254 if (!(mag <= maxFinite))
255 {
256 anyOverflow= true;
257 point[j]= (g[j] < RealType(0.0)) ? -std::numeric_limits<RealType>::infinity()
258 : std::numeric_limits<RealType>::infinity();
259 continue;
260 }
261 point[j]= (g[j] < RealType(0.0)) ? -mag : mag;
262 }
263 return anyOverflow;
264}
265
266} // namespace bikappa_detail
267
314template <typename RealType= double> class bi_kappa_distribution
315{
316 public:
317 using result_type= std::array<RealType, 3>;
319
325 {
326 public:
328
331 param_type(RealType kappa= RealType(2.0), RealType theta_perp= RealType(1.0),
332 RealType theta_par= RealType(1.0),
333 point_type ub= point_type({RealType(0.0), RealType(0.0), RealType(1.0)}),
334 RealType max_normalized_velocity= RealType(20.0))
335 : m_kappa(kappa), m_theta_perp(theta_perp), m_theta_par(theta_par), m_ub(ub),
336 m_maxNormalizedVelocity(max_normalized_velocity)
337 {
338 // Each test is written so that NaN fails it. `x <= 0.5` is false for a NaN,
339 // so the natural spelling admits one, and a NaN parameter then propagates into
340 // log R, where it can no longer be told from an unrepresentable velocity: the
341 // sampler would report a non-finite draw and count it as an overflow, which it
342 // is not. Rejecting the parameter is the only point at which the two are
343 // still distinguishable.
344 if (!(m_kappa > RealType(0.5)))
345 {
346 throw std::invalid_argument("kappa must be > 0.5 for normalization");
347 }
348 if (!(m_theta_perp > RealType(0.0)) || !(m_theta_par > RealType(0.0)) ||
349 !(m_theta_perp <= std::numeric_limits<RealType>::max()) ||
350 !(m_theta_par <= std::numeric_limits<RealType>::max()))
351 {
352 throw std::invalid_argument(
353 "Temperature parameters must be positive and finite");
354 }
355 {
356 // The field direction is validated here rather than inside the rotation, so
357 // that an axis-aligned-looking NaN cannot slip past the fast path.
358 RealType n2= RealType(0.0);
359 for (int j= 0; j < 3; ++j)
360 {
361 if (!(std::abs(m_ub[j]) <= std::numeric_limits<RealType>::max()))
362 {
363 throw std::invalid_argument("ub components must be finite");
364 }
365 n2+= m_ub[j] * m_ub[j];
366 }
367 if (!(n2 > RealType(0.0)))
368 {
369 throw std::invalid_argument("ub must be a non-zero vector");
370 }
371 }
372 // A positive finite value selects the capped mode. no_cap() (= +inf)
373 // selects the untruncated mode, in which no acceptance-rejection loop
374 // runs at all and samples follow the full bi-Kappa law.
375 if (!(m_maxNormalizedVelocity > RealType(0.0)))
376 {
377 throw std::invalid_argument(
378 "max_normalized_velocity must be positive, or no_cap() for the "
379 "untruncated distribution");
380 }
381 }
382
383 RealType kappa() const { return m_kappa; }
384 RealType theta_perp() const { return m_theta_perp; }
385 RealType theta_par() const { return m_theta_par; }
386 point_type ub() const { return m_ub; }
388 RealType max_normalized_velocity() const { return m_maxNormalizedVelocity; }
389
393 bool capped() const { return std::isfinite(m_maxNormalizedVelocity); }
394
396 bool operator==(const param_type &other) const
397 {
398 return m_kappa == other.m_kappa && m_theta_perp == other.m_theta_perp &&
399 m_theta_par == other.m_theta_par && m_ub == other.m_ub &&
400 m_maxNormalizedVelocity == other.m_maxNormalizedVelocity;
401 }
402
404 bool operator!=(const param_type &other) const { return !(*this == other); }
405
406 private:
407 RealType m_kappa;
408 RealType m_theta_perp;
409 RealType m_theta_par;
410 point_type m_ub;
411 RealType m_maxNormalizedVelocity;
412 };
413
436 static constexpr RealType no_cap()
437 {
438 return std::numeric_limits<RealType>::infinity();
439 }
440
441 // ====================================================================
442 // Construction
443 // ====================================================================
447 : m_params(), m_gen(std::random_device{}()), m_normalCache(RealType(0.0)),
448 m_normalCached(false), m_attempts(0), m_nonfinite(0)
449 {
450 }
451
454 explicit bi_kappa_distribution(RealType kappa, RealType theta_perp= RealType(1.0),
455 RealType theta_par= RealType(1.0),
456 point_type ub= point_type({RealType(0.0), RealType(0.0),
457 RealType(1.0)}),
458 RealType max_normalized_velocity= RealType(20.0))
460 m_gen(std::random_device{}()), m_normalCache(RealType(0.0)), m_normalCached(false),
461 m_attempts(0), m_nonfinite(0)
462 {
464 }
465
468 explicit bi_kappa_distribution(const param_type &params)
469 : m_params(params), m_gen(std::random_device{}()), m_normalCache(RealType(0.0)),
470 m_normalCached(false), m_attempts(0), m_nonfinite(0)
471 {
472 define(params);
473 }
474
475 // ====================================================================
476 // Setters
477 // ====================================================================
478
481 void define(const param_type &params)
482 {
483 m_params= params;
484 reset(); // just to clear cache
485 }
486
524 void define(RealType kappa, RealType theta_perp= RealType(1.0),
525 RealType theta_par= RealType(1.0),
526 point_type ub= point_type({RealType(0.0), RealType(0.0), RealType(1.0)}),
527 RealType max_normalized_velocity= RealType(20.0))
528 {
530 }
531
533 void define(const param_type &params, int seed) { applySeed(m_gen, seed); define(params); }
534
537 void define(RealType kappa, RealType theta_perp, RealType theta_par,
539 {
540 applySeed(m_gen, seed);
542 }
543
544 // Individual parameter setters. Each calls define() with the other parameters
545 // unchanged, so it validates the full set and resets the counters.
546
548 void kappa(RealType value)
549 {
550 define(value, m_params.theta_perp(), m_params.theta_par(), m_params.ub(),
551 m_params.max_normalized_velocity());
552 }
553
555 void theta_perp(RealType value)
556 {
557 define(m_params.kappa(), value, m_params.theta_par(), m_params.ub(),
558 m_params.max_normalized_velocity());
559 }
560
562 void theta_par(RealType value)
563 {
564 define(m_params.kappa(), m_params.theta_perp(), value, m_params.ub(),
565 m_params.max_normalized_velocity());
566 }
567
569 void ub(const point_type &value)
570 {
571 define(m_params.kappa(), m_params.theta_perp(), m_params.theta_par(), value,
572 m_params.max_normalized_velocity());
573 }
574
582 void max_normalized_velocity(RealType value)
583 {
584 define(m_params.kappa(), m_params.theta_perp(), m_params.theta_par(), m_params.ub(),
585 value);
586 }
587
588 // ====================================================================
589 // Getters
590 // ====================================================================
591
593 param_type param() const { return m_params; }
594
595 RealType kappa() const { return m_params.kappa(); }
596 RealType theta_perp() const { return m_params.theta_perp(); }
597 RealType theta_par() const { return m_params.theta_par(); }
598 point_type ub() const { return m_params.ub(); }
600 RealType max_normalized_velocity() const { return m_params.max_normalized_velocity(); }
601
602 // ====================================================================
603 // Random engine control
604 // ====================================================================
608 void seed(int s)
609 {
610 applySeed(m_gen, s);
611 reset();
612 }
613
616 void reset()
617 {
618 m_normalCached= false;
619 m_normalCache= RealType(0.0);
620 m_attempts= 0;
621 m_nonfinite= 0;
622 }
623
624 // ====================================================================
625 // Observability
626 // ====================================================================
627
631 unsigned long long n_attempts() const { return m_attempts; }
632
649 unsigned long long n_nonfinite() const { return m_nonfinite; }
650
651 // ====================================================================
652 // Sampling
653 // ====================================================================
658 template <typename GeneratorType> result_type operator()(GeneratorType &gen)
659 {
660 return (*this)(gen, m_params);
661 }
662
666 {
667 return (*this)(m_gen);
668 }
669
673 template <typename GeneratorType>
674 result_type operator()(GeneratorType &gen, const param_type &params)
675 {
676 const RealType kHalf= RealType(0.5);
677 const RealType kOne= RealType(1.0);
678 const int kMaxCapRejectTries= 1000000;
679
680 RealType kappa= params.kappa();
681 RealType theta_perp= params.theta_perp();
682 RealType theta_par= params.theta_par();
683 point_type ub= params.ub();
684 RealType maxNormalizedVelocity= params.max_normalized_velocity();
685
686 const RealType a= kappa - kHalf;
687 const RealType sqrtKappa= std::sqrt(kappa);
688
689 // Untruncated mode runs the core mapping exactly once; capped mode redraws
690 // until the sample falls inside the box.
691 const bool capped= params.capped();
692 const int maxTries= capped ? kMaxCapRejectTries : 1;
693
694 const bool axisAligned= approximatelyEqual(ub[0], RealType(0.0)) &&
695 approximatelyEqual(ub[1], RealType(0.0)) &&
696 approximatelyEqual(ub[2], RealType(1.0));
697
698 // Four logarithms that only the capped branch reads, and so are only taken when
699 // there is a cap. Untruncated mode decides representability from the components
700 // themselves and needs no logarithm at all outside step 1; computing these anyway
701 // cost two `std::log` calls on every untruncated draw, which `-fmath-errno` (the
702 // default) forbids a compiler from removing.
703 //
704 // `logMax` is a screening quantity only: the cap branch uses it to decide whether a
705 // rejected draw is near enough to the type's limit to be worth materializing.
706 // Representability itself is never decided from a logarithm -- see
707 // bikappa_detail::materializeComponents.
708 //
709 // `logGBound` bounds the *velocity* from its radius alone:
710 // |g_j| <= |g| <= sqrt(kappa) max(theta_perp, theta_par) for every direction and
711 // every rotation, because a rotation preserves the norm. That is what the capped
712 // branch needs and what the normalized coordinate the cap test is written in cannot
713 // give it. It is finite because define() rejects a non-positive or non-finite
714 // theta, so the screen below is never comparing against a NaN.
715 const RealType logMax= capped ? std::log(std::numeric_limits<RealType>::max())
716 : RealType(0.0);
717 const RealType logCap= capped ? std::log(maxNormalizedVelocity) : RealType(0.0);
718 const RealType logSqrtKappa= capped ? std::log(sqrtKappa) : RealType(0.0);
719 const RealType logGBound=
720 capped ? logSqrtKappa + std::log(std::max(theta_perp, theta_par)) : RealType(0.0);
721
722 int tries= 0;
723 for (tries= 0; tries < maxTries; ++tries)
724 {
725 ++m_attempts;
726
727 // Step 1: the radius, carried as its logarithm.
728 //
729 // R = sqrt(X1)/sqrt(X2) with X1 ~ Gamma(3/2,1) and X2 ~ Gamma(a,1), a = kappa-1/2.
730 // As kappa -> 1/2 the shape a -> 0 and X2 underflows to exactly zero, which no
731 // rearrangement of sqrt(X1)/sqrt(X2) can survive. X2 is therefore never formed:
732 // log X2 comes from the shape-boosting identity and
733 //
734 // log R = (log X1 - log X2) / 2
735 //
736 // stays finite and accurate wherever the mathematical radius exists. X1 has
737 // shape 3/2 > 1, so it is drawn directly and its logarithm is well conditioned.
738 const RealType x1=
740 RealType(1.5), gen, m_normalCache, m_normalCached);
741 const RealType logX2=
743 m_normalCached);
744 const RealType logR= kHalf * (std::log(x1) - logX2);
745
746 // Step 2: a direction uniform on S^2, by the rejection method of Marsaglia
747 // (1972), Ann. Math. Statist. 43(2), 645-646. Draw a point uniformly in the
748 // unit disc and lift it; the lift is area-preserving, so the result is exactly
749 // uniform on the sphere.
750 //
751 // The textbook alternative -- cos(theta) uniform on (-1,1) and phi uniform on
752 // (0, 2pi) -- is equally correct as mathematics, and is what release 1.0.0
753 // used. It needs sin(phi) and cos(phi) of the same argument, and a
754 // compiler is free to fuse that pair into one combined routine. Clang does, on
755 // Darwin, into __sincos_stret, whose sine differs from the standalone sin by one
756 // unit in the last place for roughly one argument in a thousand; GCC calls the
757 // two separately. Two builds of this header then return different numbers for
758 // the same seed, and the difference belongs to the compiler rather than to the
759 // sampler. The rejection method uses only sqrt, which IEEE-754 requires to be
760 // correctly rounded, so the direction is identical under every compiler. It is
761 // also faster here, despite averaging 4/pi = 1.273 attempts per direction.
762 RealType d1, d2, dsq;
763 do
764 {
765 d1= RealType(2.0) *
767 d2= RealType(2.0) *
769 dsq= d1 * d1 + d2 * d2;
770 } while (dsq >= kOne);
771 // dsq == 0 is unreachable: openCanonical never returns exactly 1/2, so neither
772 // d1 nor d2 is ever exactly zero.
773 const RealType dscale= RealType(2.0) * std::sqrt(kOne - dsq);
774
775 const RealType nx= d1 * dscale;
776 const RealType ny= d2 * dscale;
777 const RealType nz= kOne - RealType(2.0) * dsq;
778
779 // Step 3: the cap, tested in the field-aligned frame before anything is
780 // exponentiated. This is the same predicate the linear form applies --
781 // |point_j| / theta_j = sqrt(kappa) R |n_j| <= lambda -- moved into the log
782 // domain so that an intended sample far outside the box is rejected rather
783 // than overflowed first and rejected afterwards. Only the largest component
784 // has to be examined, so this costs one logarithm rather than three.
785 if (capped)
786 {
787 const RealType maxAbsN=
788 std::max(std::abs(nx), std::max(std::abs(ny), std::abs(nz)));
789 const RealType logLargest= logR + logSqrtKappa + std::log(maxAbsN);
790 if (logLargest > logCap)
791 {
792 // An intended sample that is outside the box and also unrepresentable is
793 // still counted, so a caller can tell the two apart. Two things have to
794 // be right here.
795 //
796 // *What* is tested. Representability is a property of the velocity
797 // `R g_j`, not of the normalized coordinate `sqrt(kappa) R |n_j|` the cap
798 // test just used: the two differ by `theta` and by the rotation. The
799 // ratio is bounded by `sqrt(3) max(theta_perp, theta_par)/min(...)`,
800 // since `|w|/sqrt(3) <= max_j |w_j| <= |w|` -- at
801 // `theta_par/theta_perp = 2` that is 3.46. The rotation concentrates the
802 // largest component as readily as it spreads it, which is why the bound
803 // is not simply the theta ratio. The counter must answer the question
804 // n_nonfinite() documents, which is about the velocity.
805 //
806 // *How* it is tested. By materializing, for the same reason as step 5.
807 // The exponential is worth avoiding here -- in capped mode this is the
808 // hot branch -- so `logGBound` screens first. It is an upper bound on
809 // log|V_j| that holds for every direction and every rotation, so a draw a
810 // whole natural-log unit below the limit by that bound cannot overflow.
811 //
812 // The screen is sound, not merely generous. Its error is dominated by
813 // half an ulp of `logR + logGBound` at the limit, which is 88.72 * 2^-24
814 // = 5.3e-6 in `float` and 709.78 * 2^-53 = 7.9e-14 in `double`; with the
815 // libm and normalization terms the worst case is about 1.1e-5 and
816 // 1.0e-13. One natural-log unit exceeds those by 9.4e4 and 1.0e13.
817 //
818 // How often it fires is a property of the configuration, not a constant:
819 // about 7e-7 of attempts at double kappa = 0.51, but 17 % at float
820 // kappa = 0.51 and 87 % at double kappa = 0.5001, where most of the law
821 // genuinely lies outside the type. Where it fires often, it is doing
822 // the work it exists for.
823 if (logR + logGBound > logMax - kOne)
824 {
825 point_type gRej= fieldAlignedG(sqrtKappa, theta_perp, theta_par,
826 nx, ny, nz);
827 if (!axisAligned)
828 {
829 gRej= rotateFromFieldAlignedFrame(gRej, ub);
830 }
831 point_type scratch;
833 scratch))
834 {
835 ++m_nonfinite;
836 }
837 }
838 continue;
839 }
840 }
841
842 // Step 4: the order-unity vector g, with V = R g. Forming g first is what makes
843 // the representability test meaningful: an orthogonal rotation can spread one
844 // over-large local component across three representable global ones, so the test
845 // has to be applied to the components that are actually returned.
846 point_type g= fieldAlignedG(sqrtKappa, theta_perp, theta_par, nx, ny, nz);
847 if (!axisAligned)
848 {
850 }
851
852 // Step 5: materialize the components and decide representability from the
853 // components themselves, never from their logarithms. The whole of that
854 // decision lives in bikappa_detail::materializeComponents, which documents why
855 // a logarithmic test is wrong in both directions; the capped branch above calls
856 // the same routine, so the counter and the return can never disagree.
857 point_type point;
858 const bool anyOverflow=
860
861 if (anyOverflow)
862 {
863 // True overflow: the intended velocity has no representation in RealType.
864 // No formation can rescue it, so it is returned as a non-finite vector and
865 // counted, never silently redrawn. In capped mode this is unreachable for
866 // every cap a caller would write: an accepted draw has
867 // sqrt(kappa) R max_j|n_j| <= lambda, hence
868 // max_j |g_j| R <= sqrt(3) lambda max(theta_perp, theta_par), so reaching it
869 // would take lambda max(theta) above 1.97e38 in `float` or 1.04e308 in
870 // `double` -- a box larger than the type.
871 ++m_nonfinite;
872 }
873
874 return point;
875 }
876
877 throw std::runtime_error("failed to sample velocity under max_normalized_velocity cap: "
878 "rejection sampling exceeded internal attempt limit");
879 }
880
881 // ====================================================================
882 // Geometry helper
883 // ====================================================================
888 {
889 return rotateFromFieldAlignedFrame(local, ub);
890 }
891
895 {
896 const RealType kZero= RealType(0.0);
897 const RealType kOne= RealType(1.0);
898
899 // Normalize ub to get e3
900 RealType ubNorm2= ub[0] * ub[0] + ub[1] * ub[1] + ub[2] * ub[2];
901 if (approximatelyEqual(ubNorm2, kZero))
902 {
903 throw std::invalid_argument("ub must be a non-zero vector");
904 }
905
906 RealType ubNorm= std::sqrt(ubNorm2);
907
908 point_type e3;
909 e3[0]= ub[0] / ubNorm;
910 e3[1]= ub[1] / ubNorm;
911 e3[2]= ub[2] / ubNorm;
912
913 // Build e2 perpendicular to e3
914 point_type e2;
915 e2[0]= kOne;
916 e2[1]= kOne;
917 e2[2]= kOne;
918
919 int maxcomp= 0;
920 if (std::abs(e3[1]) > std::abs(e3[maxcomp]))
921 {
922 maxcomp= 1;
923 }
924 if (std::abs(e3[2]) > std::abs(e3[maxcomp]))
925 {
926 maxcomp= 2;
927 }
928
929 RealType sum= e3[0] + e3[1] + e3[2];
930 e2[maxcomp]= kOne - sum / e3[maxcomp];
931
932 RealType e2Norm2= e2[0] * e2[0] + e2[1] * e2[1] + e2[2] * e2[2];
933 RealType e2Norm= std::sqrt(e2Norm2);
934 e2[0]/= e2Norm;
935 e2[1]/= e2Norm;
936 e2[2]/= e2Norm;
937
938 // e1 = e2 x e3
939 point_type e1;
940 e1[0]= e2[1] * e3[2] - e2[2] * e3[1];
941 e1[1]= e2[2] * e3[0] - e2[0] * e3[2];
942 e1[2]= e2[0] * e3[1] - e2[1] * e3[0];
943
944 // Transform local coordinates to Cartesian coordinates
945 point_type point;
946 point[0]= local[0] * e1[0] + local[1] * e2[0] + local[2] * e3[0];
947 point[1]= local[0] * e1[1] + local[1] * e2[1] + local[2] * e3[1];
948 point[2]= local[0] * e1[2] + local[1] * e2[2] + local[2] * e3[2];
949
950 return point;
951 }
952
953 // ====================================================================
954 // Comparison
955 // ====================================================================
958 bool operator==(const bi_kappa_distribution &other) const { return m_params == other.m_params; }
959
961 bool operator!=(const bi_kappa_distribution &other) const { return !(*this == other); }
962
963 private:
964 // ====================================================================
965 // Internal helpers
966 // ====================================================================
967 static void applySeed(std::mt19937 &gen, int s)
968 {
969 if (s < 0)
970 gen.seed(std::random_device{}());
971 else
972 gen.seed(static_cast<unsigned int>(s));
973 }
974
979 static point_type fieldAlignedG(RealType sqrtKappa, RealType theta_perp, RealType theta_par,
980 RealType nx, RealType ny, RealType nz)
981 {
982 point_type g;
983 g[0]= sqrtKappa * theta_perp * nx;
984 g[1]= sqrtKappa * theta_perp * ny;
985 g[2]= sqrtKappa * theta_par * nz;
986 return g;
987 }
988
989 static bool approximatelyEqual(RealType a, RealType b)
990 {
991 RealType scale= std::max(std::max(RealType(1.0), std::abs(a)), std::abs(b));
992 return std::abs(a - b) <= std::numeric_limits<RealType>::epsilon() * scale;
993 }
994
995 param_type m_params;
996 std::mt19937 m_gen;
997 RealType m_normalCache;
998 bool m_normalCached;
999 unsigned long long m_attempts;
1000 unsigned long long m_nonfinite;
1001};
1002
1003#endif // _BI_KAPPA_DISTRIBUTION_H_
The parameters of a bi_kappa_distribution: kappa, theta_perp, theta_par, ub and the velocity cap.
bool operator==(const param_type &other) const
True if every parameter compares equal.
RealType theta_par() const
Parallel thermal speed.
bool capped() const
True when a finite component-wise cap is in force, that is, when the sampled distribution is the bi-K...
RealType theta_perp() const
Perpendicular thermal speed.
RealType kappa() const
Spectral index.
bi_kappa_distribution< RealType > distribution_type
The owning sampler.
RealType max_normalized_velocity() const
Velocity cap in thermal speeds; +infinity for no_cap().
bool operator!=(const param_type &other) const
Negation of operator==.
point_type ub() const
Field direction, as given.
param_type(RealType kappa=RealType(2.0), RealType theta_perp=RealType(1.0), RealType theta_par=RealType(1.0), point_type ub=point_type({RealType(0.0), RealType(0.0), RealType(1.0)}), RealType max_normalized_velocity=RealType(20.0))
Store and validate the parameters.
bool operator==(const bi_kappa_distribution &other) const
True if the two samplers have equal parameters.
bi_kappa_distribution(RealType kappa, RealType theta_perp=RealType(1.0), RealType theta_par=RealType(1.0), point_type ub=point_type({RealType(0.0), RealType(0.0), RealType(1.0)}), RealType max_normalized_velocity=RealType(20.0))
Construct and call define() with these arguments.
unsigned long long n_nonfinite() const
Attempts since the last reset(), define() or seed() whose intended velocity vector had no representat...
void define(RealType kappa, RealType theta_perp=RealType(1.0), RealType theta_par=RealType(1.0), point_type ub=point_type({RealType(0.0), RealType(0.0), RealType(1.0)}), RealType max_normalized_velocity=RealType(20.0))
Configure the sampler.
void define(const param_type &params)
Replace all parameters with params (already validated by its constructor), then call reset().
void reset()
Discard any variate cached inside the sampler and zero the observability counters.
param_type param() const
The current parameters, for example to test param().capped().
RealType theta_par() const
Parallel thermal speed.
bi_kappa_distribution(const param_type &params)
Construct from a parameter set.
result_type operator()(GeneratorType &gen)
Draw one velocity from the engine gen instead of the internal one.
result_type operator()()
Draw one velocity from the internal engine.
void ub(const point_type &value)
Set the field direction, keeping the other parameters; throws as define() does.
std::array< RealType, 3 > result_type
A velocity {vx, vy, vz}.
result_type operator()(GeneratorType &gen, const param_type &params)
Draw one velocity from gen with the parameters params instead of the stored ones.
void define(RealType kappa, RealType theta_perp, RealType theta_par, point_type ub, RealType max_normalized_velocity, int seed)
define() with all five parameters, after seeding the internal engine with seed as seed() does (seed >...
void kappa(RealType value)
Set kappa, keeping the other parameters; throws as define() does.
void max_normalized_velocity(RealType value)
Set the velocity cap, keeping the other parameters.
unsigned long long n_attempts() const
Core-mapping attempts made since the last reset(), define() or seed().
point_type rotate_from_fieldAligned_frame(const point_type &local, const point_type &ub) const
Rotate local = {v_perp1, v_perp2, v_par} from field-aligned components to the global frame,...
void theta_par(RealType value)
Set theta_par, keeping the other parameters; throws as define() does.
void theta_perp(RealType value)
Set theta_perp, keeping the other parameters; throws as define() does.
point_type ub() const
Field direction, as given.
static point_type rotateFromFieldAlignedFrame(const point_type &local, const point_type &ub)
The same rotation as rotate_from_fieldAligned_frame(), as a static function that needs no instance.
RealType max_normalized_velocity() const
Velocity cap in thermal speeds; +infinity for no_cap().
void define(const param_type &params, int seed)
define(params), after seeding the internal engine with seed as seed() does.
bool operator!=(const bi_kappa_distribution &other) const
Negation of operator==.
RealType theta_perp() const
Perpendicular thermal speed.
bi_kappa_distribution()
Construct with kappa = 2, theta_perp = theta_par = 1, ub = {0, 0, 1} and a cap of 20.
RealType kappa() const
Spectral index.
static constexpr RealType no_cap()
Value of the cap that selects the uncapped sampler: +infinity.
result_type point_type
Same as result_type.
Sampling primitives used to build the bi-Kappa radius.
RealType marsagliaTsangGamma(RealType shape, GeneratorType &gen, RealType &ncache, bool &ncached)
Gamma(shape, 1) for shape >= 1, by Marsaglia and Tsang (2000), ACM TOMS 26(3), 363-372.
RealType logGamma(RealType a, GeneratorType &gen, RealType &ncache, bool &ncached)
log X for X ~ Gamma(a, 1), for every a > 0, without ever forming X.
RealType openCanonical(GeneratorType &gen)
Uniform on the open interval (0,1), by an explicit mapping from engine bits.
int engineBits()
Whole bits of entropy the engine delivers per call (32 for std::mt19937).
RealType polarNormal(GeneratorType &gen, RealType &cache, bool &cached)
Standard normal by the Marsaglia polar method.
bool materializeComponents(RealType logR, const std::array< RealType, 3 > &g, std::array< RealType, 3 > &point)
Materialize V_j = R g_j from log R, and report whether any component overflowed.