1#ifndef _BI_KAPPA_DISTRIBUTION_H_
2#define _BI_KAPPA_DISTRIBUTION_H_
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"
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 " \
58 unsigned long long range=
static_cast<unsigned long long>(GeneratorType::max()) -
59 static_cast<unsigned long long>(GeneratorType::min());
83template <
typename RealType,
typename GeneratorType> RealType
openCanonical(GeneratorType &gen)
85 const int bits= std::numeric_limits<RealType>::digits - 1;
87 unsigned long long k= 0;
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));
97 return (
static_cast<RealType
>(k) + RealType(0.5)) * std::ldexp(RealType(1.0), -bits);
103template <
typename RealType,
typename GeneratorType>
104RealType
polarNormal(GeneratorType &gen, RealType &cache,
bool &cached)
117 }
while (s >= RealType(1.0));
120 const RealType f= std::sqrt(RealType(-2.0) * std::log(s) / s);
129template <
typename RealType,
typename GeneratorType>
132 const RealType d= shape - RealType(1.0) / RealType(3.0);
133 const RealType c= RealType(1.0) / std::sqrt(RealType(9.0) * d);
140 v= RealType(1.0) + c * x;
141 }
while (v <= RealType(0.0));
144 const RealType xx= x * x;
145 if (u < RealType(1.0) - RealType(0.0331) * xx * xx)
149 if (std::log(u) < RealType(0.5) * xx + d * (RealType(1.0) - v + std::log(v)))
183template <
typename RealType,
typename GeneratorType>
184RealType
logGamma(RealType a, GeneratorType &gen, RealType &ncache,
bool &ncached)
189 return std::log(y) + std::log(u) / a;
230template <
typename RealType>
232 std::array<RealType, 3> &point)
234 const RealType maxFinite= std::numeric_limits<RealType>::max();
235 const RealType rTry= std::exp(logR);
237 const bool radiusRepresentable= (rTry <= maxFinite);
238 const RealType R= radiusRepresentable ? rTry : RealType(0.0);
240 bool anyOverflow=
false;
241 for (
int j= 0; j < 3; ++j)
243 if (g[j] == RealType(0.0))
245 point[j]= RealType(0.0);
248 const RealType absG= std::abs(g[j]);
252 const RealType mag= radiusRepresentable ? R * absG
253 : std::exp(logR + std::log(absG));
254 if (!(mag <= maxFinite))
257 point[j]= (g[j] < RealType(0.0)) ? -std::numeric_limits<RealType>::infinity()
258 : std::numeric_limits<RealType>::infinity();
261 point[j]= (g[j] < RealType(0.0)) ? -mag : mag;
344 if (!(m_kappa > RealType(0.5)))
346 throw std::invalid_argument(
"kappa must be > 0.5 for normalization");
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()))
352 throw std::invalid_argument(
353 "Temperature parameters must be positive and finite");
358 RealType n2= RealType(0.0);
359 for (
int j= 0; j < 3; ++j)
361 if (!(std::abs(m_ub[j]) <= std::numeric_limits<RealType>::max()))
363 throw std::invalid_argument(
"ub components must be finite");
365 n2+= m_ub[j] * m_ub[j];
367 if (!(n2 > RealType(0.0)))
369 throw std::invalid_argument(
"ub must be a non-zero vector");
375 if (!(m_maxNormalizedVelocity > RealType(0.0)))
377 throw std::invalid_argument(
378 "max_normalized_velocity must be positive, or no_cap() for the "
379 "untruncated distribution");
383 RealType
kappa()
const {
return m_kappa; }
393 bool capped()
const {
return std::isfinite(m_maxNormalizedVelocity); }
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;
408 RealType m_theta_perp;
409 RealType m_theta_par;
411 RealType m_maxNormalizedVelocity;
438 return std::numeric_limits<RealType>::infinity();
447 : m_params(), m_gen(std::random_device{}()), m_normalCache(RealType(0.0)),
448 m_normalCached(false), m_attempts(0), m_nonfinite(0)
460 m_gen(std::random_device{}()), m_normalCache(RealType(0.0)), m_normalCached(false),
461 m_attempts(0), m_nonfinite(0)
469 : m_params(params), m_gen(std::random_device{}()), m_normalCache(RealType(0.0)),
470 m_normalCached(false), m_attempts(0), m_nonfinite(0)
540 applySeed(m_gen,
seed);
550 define(value, m_params.theta_perp(), m_params.theta_par(), m_params.ub(),
551 m_params.max_normalized_velocity());
557 define(m_params.kappa(), value, m_params.theta_par(), m_params.ub(),
558 m_params.max_normalized_velocity());
564 define(m_params.kappa(), m_params.theta_perp(), value, m_params.ub(),
565 m_params.max_normalized_velocity());
571 define(m_params.kappa(), m_params.theta_perp(), m_params.theta_par(), value,
572 m_params.max_normalized_velocity());
584 define(m_params.kappa(), m_params.theta_perp(), m_params.theta_par(), m_params.ub(),
593 param_type
param()
const {
return m_params; }
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(); }
618 m_normalCached=
false;
619 m_normalCache= RealType(0.0);
660 return (*
this)(gen, m_params);
667 return (*
this)(m_gen);
673 template <
typename GeneratorType>
676 const RealType kHalf= RealType(0.5);
677 const RealType kOne= RealType(1.0);
678 const int kMaxCapRejectTries= 1000000;
680 RealType
kappa= params.kappa();
684 RealType maxNormalizedVelocity= params.max_normalized_velocity();
686 const RealType a=
kappa - kHalf;
687 const RealType sqrtKappa= std::sqrt(
kappa);
691 const bool capped= params.capped();
692 const int maxTries= capped ? kMaxCapRejectTries : 1;
694 const bool axisAligned= approximatelyEqual(
ub[0], RealType(0.0)) &&
695 approximatelyEqual(
ub[1], RealType(0.0)) &&
696 approximatelyEqual(
ub[2], RealType(1.0));
715 const RealType logMax= capped ? std::log(std::numeric_limits<RealType>::max())
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=
723 for (tries= 0; tries < maxTries; ++tries)
740 RealType(1.5), gen, m_normalCache, m_normalCached);
741 const RealType logX2=
744 const RealType logR= kHalf * (std::log(x1) - logX2);
762 RealType d1, d2, dsq;
769 dsq= d1 * d1 + d2 * d2;
770 }
while (dsq >= kOne);
773 const RealType dscale= RealType(2.0) * std::sqrt(kOne - dsq);
775 const RealType nx= d1 * dscale;
776 const RealType ny= d2 * dscale;
777 const RealType nz= kOne - RealType(2.0) * dsq;
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)
823 if (logR + logGBound > logMax - kOne)
858 const bool anyOverflow=
877 throw std::runtime_error(
"failed to sample velocity under max_normalized_velocity cap: "
878 "rejection sampling exceeded internal attempt limit");
896 const RealType kZero= RealType(0.0);
897 const RealType kOne= RealType(1.0);
900 RealType ubNorm2=
ub[0] *
ub[0] +
ub[1] *
ub[1] +
ub[2] *
ub[2];
901 if (approximatelyEqual(ubNorm2, kZero))
903 throw std::invalid_argument(
"ub must be a non-zero vector");
906 RealType ubNorm= std::sqrt(ubNorm2);
909 e3[0]=
ub[0] / ubNorm;
910 e3[1]=
ub[1] / ubNorm;
911 e3[2]=
ub[2] / ubNorm;
920 if (std::abs(e3[1]) > std::abs(e3[maxcomp]))
924 if (std::abs(e3[2]) > std::abs(e3[maxcomp]))
929 RealType sum= e3[0] + e3[1] + e3[2];
930 e2[maxcomp]= kOne - sum / e3[maxcomp];
932 RealType e2Norm2= e2[0] * e2[0] + e2[1] * e2[1] + e2[2] * e2[2];
933 RealType e2Norm= std::sqrt(e2Norm2);
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];
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];
967 static void applySeed(std::mt19937 &gen,
int s)
970 gen.seed(std::random_device{}());
972 gen.seed(
static_cast<unsigned int>(s));
980 RealType nx, RealType ny, RealType nz)
989 static bool approximatelyEqual(RealType a, RealType b)
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;
997 RealType m_normalCache;
999 unsigned long long m_attempts;
1000 unsigned long long m_nonfinite;
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 ¶ms)
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 ¶ms)
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 ¶ms)
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 ¶ms, 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.