Short examples for the five samplers.
They use Real = double; Single precision shows the float instantiation. Every sampler is used the same way: construct, call define(...), then call operator() once per sample. An oblique magnetic field and Loading particles in a simulation are complete programs.
Building the tests and the demo
The headers need only a C++11 compiler. To build and run the code in cpp/:
make -C cpp test # regression suite; exit status 0 if every check passes
cd cpp && make && ./main.exe # short worked examples of all five samplers
make -C cpp CXX=clang++ test # use a different compiler
Bi-Kappa velocities
#include <fstream>
BK biKappa;
biKappa.
define(2.0, 1.0, 2.0, {0, 0, 1}, BK::no_cap(), 20030410);
std::ofstream out("samples_bikappa.txt");
for (int i = 0; i < 100000; ++i) {
BK::point_type v = biKappa();
out << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
}
Bi-Kappa distribution class for sampling 3D velocity vectors.
void define(const param_type ¶ms)
Replace all parameters with params (already validated by its constructor), then call reset().
The seed is the sixth argument, so the cap has to be given when a seed is passed to define(...). Alternatively, call biKappa.seed(20030410) after define(...).
The velocity cap
The fifth argument, max_normalized_velocity, is a cap in thermal speeds. It defaults to 20.
BK dist;
dist.define(2.0, 1.0, 2.0, {0, 0, 1});
dist.define(2.0, 1.0, 2.0, {0, 0, 1}, BK::no_cap());
dist.define(2.0, 1.0, 2.0, {0, 0, 1}, 50.0);
bool c = dist.param().capped();
dist.max_normalized_velocity(BK::no_cap());
dist.max_normalized_velocity(0.0);
With a finite cap, a draw is redrawn if |v_i| / theta_i > cap for any component in field-aligned coordinates. The samples then follow the bi-Kappa distribution conditioned on that box, not the bi-Kappa distribution itself. For kappa <= 3/2 a cap of 20 removes an appreciable part of the high-energy tail; the paper's section on finite velocity bounds quantifies this. Use no_cap() when the tail matters.
The box is aligned with the field-aligned axes and rotates with ub. Global-frame components are bounded individually only when ub = {0, 0, 1}; the speed is always bounded by cap * sqrt(2 theta_perp^2 + theta_par^2). See The velocity cap for details.
Bi-Maxwellian velocities
The same interface without kappa. The cap works as for bi_kappa_distribution, with the same default of 20; for a Maxwellian it has no practical effect.
BM biMaxwell;
biMaxwell.
define(1.0, 2.0, {0, 0, 1});
biMaxwell.define(1.0, 2.0, {0, 0, 1}, BM::no_cap(), 20030410);
BM::point_type v = biMaxwell();
Bi-Maxwellian distribution for 3D velocity sampling.
void define(const param_type ¶ms)
Replace all parameters with params, then call reset().
Seeding
BK dist;
dist.define(2.0, 1.0, 2.0);
dist.seed(55555);
dist.seed(-1);
Without a seed, runs are not reproducible. On every sampler seed(s) also calls reset(), which discards any variate cached from earlier draws, so reseeding restarts the stream exactly. For bi_kappa_distribution a given seed gives the same values under libc++ and libstdc++ on the same architecture; the values are not bitwise identical across architectures. The other four samplers use std::normal_distribution or std::uniform_real_distribution, whose values can depend on the standard library. CHANGELOG.md lists the versions in which the values for a given seed changed.
Sharing one engine
Pass your own engine to operator() to draw several samplers from one stream. For bi_kappa_distribution the engine must produce a power-of-two number of distinct values, as std::mt19937 and std::mt19937_64 do. This is not checked at compile time: std::minstd_rand compiles without a warning but does not meet the requirement.
#include <random>
std::mt19937 gen(42u);
BK core, halo;
core.define(5.0, 1.0, 1.0);
halo.define(2.0, 3.0, 3.0);
BK::point_type a = core(gen);
BK::point_type b = halo(gen);
An oblique magnetic field
ub can point in any direction and need not have unit length. theta_par applies along ub and theta_perp across it. The sampler returns velocities in the global frame, so to recover field-aligned components, project onto the unit vector b = ub / |ub|: v_par = v . b and v_perp^2 = |v|^2 - v_par^2. This program checks the result against the variances of Thermal speeds: theta_perp, theta_par, which exist for kappa > 3/2.
#include <cmath>
#include <cstdio>
{
const BK::point_type ub = {1.0, 2.0, 3.0};
BK dist;
dist.
define(4.0, 1.0, 2.0, ub, BK::no_cap(), 12345);
const double norm = std::sqrt(ub[0] * ub[0] + ub[1] * ub[1] + ub[2] * ub[2]);
const double b[3] = {ub[0] / norm, ub[1] / norm, ub[2] / norm};
const int n = 1000000;
double sum_par2 = 0.0, sum_perp2 = 0.0;
for (int i = 0; i < n; ++i) {
const BK::point_type v = dist();
const double v_par = v[0] * b[0] + v[1] * b[1] + v[2] * b[2];
const double v2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
sum_par2 += v_par * v_par;
sum_perp2 += v2 - v_par * v_par;
}
std::printf("<v_par^2> = %.3f <v_perp^2> = %.3f\n", sum_par2 / n, sum_perp2 / n);
return 0;
}
The two perpendicular axes the sampler uses internally matter only for a finite cap, whose box is aligned with them; see The velocity cap.
Single precision
BKf distf;
distf.
define(3.0f, 1.0f, 2.0f, {0.0f, 0.0f, 1.0f}, BKf::no_cap(), 12345);
BKf::point_type vf = distf();
bi_kappa_distribution<float> does all of its arithmetic in float, so for the same seed it returns different numbers from the double instantiation. It is suitable when kappa is not close to 1/2 and about seven significant digits per component are enough. Near kappa = 1/2 a noticeable fraction of float draws exceeds the largest float (about 1.4e-4 of draws at kappa = 0.55); see Finite precision near kappa = 1/2 and use double there.
Loading particles in a simulation
This program fills arrays for N particles with a drifting bi-Kappa population, as a particle-in-cell code would at initialization. It converts kinetic temperatures to thermal speeds with the relation of Thermal speeds: theta_perp, theta_par, which holds for kappa > 3/2; for smaller kappa, specify theta directly. Each thread or MPI rank has its own sampler, and so its own engine, with its own seed. The ranks are simulated here by a loop.
#include <cmath>
#include <cstdio>
#include <vector>
{
const double k_B = 1.380649e-23;
const double m = 1.67262192e-27;
const double kappa = 3.0;
const double T_perp = 1.0e5, T_par = 2.0e5;
const BK::point_type b = {0.0, 0.6, 0.8};
const double drift[3] = {4.0e5, 0.0, 0.0};
const double theta_perp = std::sqrt((2.0 - 3.0 / kappa) * k_B * T_perp / m);
const double theta_par = std::sqrt((2.0 - 3.0 / kappa) * k_B * T_par / m);
const int n_ranks = 4;
const int n_per_rank = 250000;
const int base_seed = 1000;
const int n = n_ranks * n_per_rank;
std::vector<double> vx(n), vy(n), vz(n);
for (int rank = 0; rank < n_ranks; ++rank) {
BK dist;
dist.define(kappa, theta_perp, theta_par, b, BK::no_cap(), base_seed + rank);
for (int i = rank * n_per_rank; i < (rank + 1) * n_per_rank; ++i) {
const BK::point_type v = dist();
vx[i] = v[0] + drift[0];
vy[i] = v[1] + drift[1];
vz[i] = v[2] + drift[2];
}
}
double sum = 0.0;
for (int i = 0; i < n; ++i) {
const double v_par = (vx[i] - drift[0]) * b[0] + (vy[i] - drift[1]) * b[1] +
(vz[i] - drift[2]) * b[2];
sum += v_par * v_par;
}
std::printf("T_par from the sample: %.4g K (target %.4g K)\n", m * sum / n / k_B, T_par);
return 0;
}
Changing parameters
define(...) replaces the whole configuration. Each single-parameter setter re-validates the full set.
BK dist;
dist.define(2.0, 1.0, 1.0);
dist.kappa(5.0);
dist.theta_par(2.5);
dist.ub({1, 2, 3});
dist.max_normalized_velocity(BK::no_cap());
Overflow near kappa = 1/2
Close to kappa = 1/2, some bi-Kappa draws exceed the largest representable floating-point number. Without a cap they are returned with infinite components; with a cap they are redrawn. n_nonfinite() counts such draws and n_attempts() counts all attempts since the last define(), seed() or reset().
BK dist;
dist.define(0.505, 1.0, 1.0, {0, 0, 1}, BK::no_cap());
for (int i = 0; i < 1000000; ++i) {
BK::point_type v = dist();
if (!std::isfinite(v[0]) || !std::isfinite(v[1]) || !std::isfinite(v[2])) {
}
}
unsigned long long lost = dist.n_nonfinite();
Under -ffast-math the compiler may assume that no infinity occurs, so no_cap() and the counters are unreliable. bi_kappa_distribution.H then prints a compile-time note; define BI_KAPPA_ALLOW_FAST_MATH to silence it. See Finite precision near kappa = 1/2 for typical rates.
Isotropic velocities from your own density
general_velocity_generator draws w = |v|^2 from a density g(w) you supply, by rejection sampling, and gives the velocity an isotropic direction with speed sqrt(w). There is no mass argument: for a distribution written in energy, use w = 2E/m.
#include <cmath>
auto gW = [](
Real w) ->
Real {
return std::sqrt(w) * std::exp(-w); };
Samples velocities from a user-defined speed-squared distribution g(w).
void seed(int s)
Reseed the internal engine and discard any variate cached from before, so that seed(s) followed by n ...
result_type point_type
Same as result_type.
void define(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min, RealType speed_sq_max, int probe_points=1024, int max_reject_tries=100000)
Configure the sampler.
If w_min == w_max, every sample has speed sqrt(w_min). probe_points (fourth argument, default 1024) must be at least 64.
Field-aligned velocities
field_aligned_velocity_generator draws w = v_par^2 from your density g(w) and puts the parallel component along ub (sign = +1) or opposite to it (sign = -1). The two perpendicular components are Maxwellian with thermal speed theta_perp, each N(0, theta_perp^2 / 2), and each is capped at 20 * theta_perp by default. The result is returned in the global frame.
#include <cmath>
auto gW = [](
Real w) ->
Real {
return std::exp(-0.5 * w); };
FA faGen;
faGen.define(gW, 0.0, 40.0, 1.0, {0, 0, 1}, +1);
faGen.seed(20030410);
FA::point_type v = faGen();
faGen.define(gW, 0.0, 40.0, 1.0, {0, 0, 1}, +1, 1024, 100000, FA::no_cap());
Samples field-aligned velocities: an arbitrary parallel speed-squared distribution along B,...
Positions from your own density
general_position_generator draws positions in one to three dimensions from a density rho(x) in an axis-aligned box, by rejection sampling. The point is a std::vector<Real> of length dimension.
#include <cmath>
auto rho = [](
const pos_t& x) ->
Real {
return 1.0 + std::sin(x[0]) * std::sin(x[1]); };
const Real pi = 3.14159265358979;
posGen.
define(2, {-pi, -pi}, {pi, pi}, rho);
pos_t x = posGen();
Samples positions in 1D/2D/3D from a user density rho(x), rho(x,y), or rho(x,y,z).
void define(int dimension, const point_type &lower_bounds, const point_type &upper_bounds, density_function density_function, int probe_points=4096, int max_reject_tries=200000)
Configure the sampler.
void seed(int s)
Reseed the internal engine and discard any variate cached from before, so that seed(s) followed by n ...
result_type point_type
Same as result_type.
Errors
- define(...) and the setters throw std::invalid_argument for a value outside its valid range (see Parameter reference).
- The general, field-aligned and position generators throw std::runtime_error if called before define(...), if max_reject_tries is exhausted, or if your function returns a negative or non-finite value.
- bi_kappa_distribution and bi_maxwellian_distribution throw std::runtime_error after 10^6 consecutive rejections by the cap.
try {
} catch (const std::runtime_error& e) {
}
Demo program
cpp/main.cpp runs a short example of each sampler:
#include <random>
#include <cmath>
#include <iostream>
#include <fstream>
{
const Real theta_perp = 1.0;
const Real theta_par = 2.0;
const int n_particle = 50000;
std::cout << "=== Example 1: BiKappaDistribution ===" << std::endl;
biKappa.
define(kappa, theta_perp, theta_par, {0,0,1},
{
std::ofstream out("samples_bikappa.txt");
for (int i = 0; i < n_particle; ++i) {
out << v[0] << " " << v[1] << " " << v[2] << "\n";
}
std::cout << "wrote " << n_particle << " samples to samples_bikappa.txt" << std::endl;
}
std::cout << "\n=== Example 2: BiMaxwellianDistribution ===" << std::endl;
biMaxwell.
define(theta_perp, theta_par, {0,0,1},
{
std::ofstream out("samples_bimaxwellian.txt");
for (int i = 0; i < n_particle; ++i) {
out << v[0] << " " << v[1] << " " << v[2] << "\n";
}
std::cout << "wrote " << n_particle << " samples to samples_bimaxwellian.txt" << std::endl;
}
std::cout << "\n=== Example 3: general_velocity_generator (isotropic Maxwellian via w=|v|^2) ==="
<< std::endl;
const Real theta_iso = theta_perp;
auto speedSqPdf = [theta_iso](
Real w) ->
Real {
return std::sqrt(w) * std::exp(-w / (theta_iso * theta_iso));
};
velocityGen.
define(speedSqPdf,
static_cast<Real>(25.0));
velocityGen.
seed(20030410);
{
std::ofstream out("samples_general_velocity.txt");
for (int i = 0; i < n_particle; ++i) {
out << v[0] << " " << v[1] << " " << v[2] << "\n";
}
std::cout << "wrote " << n_particle << " samples to samples_general_velocity.txt"
<< std::endl;
}
std::cout << "\n=== Example 4: general_position_generator (rho=1+sin(x)sin(y)) ===" << std::endl;
auto rho = [](
const position_point_type &x) ->
Real {
return 1 + std::sin(x[0]) * std::sin(x[1]);
};
static double pi = 3.14159;
positionGen.
define(2, {-pi, -pi}, {pi, pi}, rho);
positionGen.
seed(20030410);
{
std::ofstream out("samples_general_position.txt");
for (int i = 0; i < n_particle; ++i) {
const position_point_type x = positionGen();
out << x[0] << " " << x[1] << "\n";
}
std::cout << "wrote " << n_particle << " samples to samples_general_position.txt"
<< std::endl;
}
std::cout << "\n=== Example 5: field_aligned_velocity_generator (uniform w_par, B=(1,1,1)) ==="
<< std::endl;
const Real w_max_par = 4.0;
auto parallelSpeedSqPdf = [](
Real) ->
Real {
return Real(1.0); };
fieldAlignedGen.
define(parallelSpeedSqPdf,
w_max_par,
theta_perp,
{1, 1, 1},
+1);
fieldAlignedGen.
seed(20030410);
{
std::ofstream out("samples_field_aligned.txt");
for (int i = 0; i < n_particle; ++i) {
out << v[0] << " " << v[1] << " " << v[2] << "\n";
}
std::cout << "wrote " << n_particle << " samples to samples_field_aligned.txt"
<< std::endl;
}
return 0;
}
static constexpr RealType no_cap()
Value of the cap that selects the uncapped sampler: +infinity.
result_type point_type
Same as result_type.
result_type point_type
Same as result_type.
static constexpr RealType no_cap()
Value of the cap that selects the uncapped sampler: +infinity.
void seed(int s)
Reseed the internal engine and discard any variate cached from before, so that seed(s) followed by n ...
void define(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min, RealType speed_sq_max, RealType theta_perp, point_type ub, int parallel_sign, int probe_points=1024, int max_reject_tries=100000, RealType max_normalized_velocity=RealType(20.0))
Configure the sampler: user-supplied law along the field, Maxwellian across it.
result_type point_type
Same as result_type.