bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
field_aligned_velocity_generator.H
Go to the documentation of this file.
1#ifndef _FIELD_ALIGNED_VELOCITY_GENERATOR_H_
2#define _FIELD_ALIGNED_VELOCITY_GENERATOR_H_
3
4#include <array>
5#include <algorithm>
6#include <cmath>
7#include <functional>
8#include <limits>
9#include <random>
10#include <stdexcept>
11
38template <typename RealType= double> class field_aligned_velocity_generator
39{
40 public:
41 using result_type= std::array<RealType, 3>;
44 using speed_sq_pdf_function= std::function<RealType(RealType)>;
45
49 : m_speedSqPdf(), m_speedSqMin(RealType(0.0)), m_speedSqMax(RealType(1.0)),
50 m_thetaPerp(RealType(1.0)),
51 m_ub(point_type({RealType(0.0), RealType(0.0), RealType(1.0)})),
52 m_parallelSign(RealType(1.0)), m_maxNormalizedVelocity(RealType(20.0)),
53 m_maxRejectTries(100000),
54 m_pdfUpperBound(RealType(0.0)), m_isDefined(false), m_gen(std::random_device{}()),
55 m_distSpeedSq(RealType(0.0), RealType(1.0)), m_distAccept(RealType(0.0), RealType(1.0)),
56 m_standardNormal(RealType(0.0), RealType(1.0))
57 {
58 }
59
61 field_aligned_velocity_generator(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min,
62 RealType speed_sq_max, RealType theta_perp, point_type ub,
63 int parallel_sign, int probe_points= 1024,
64 int max_reject_tries= 100000,
65 RealType max_normalized_velocity= RealType(20.0))
67 {
68 define(speed_sq_pdf, speed_sq_min, speed_sq_max, theta_perp, ub, parallel_sign,
69 probe_points, max_reject_tries, max_normalized_velocity);
70 }
71
73 static constexpr RealType no_cap() { return std::numeric_limits<RealType>::infinity(); }
74
118 void define(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min, RealType speed_sq_max,
119 RealType theta_perp, point_type ub, int parallel_sign,
120 int probe_points= 1024, int max_reject_tries= 100000,
121 RealType max_normalized_velocity= RealType(20.0))
122 {
123 m_isDefined= false;
124
125 if (!speed_sq_pdf)
126 {
127 throw std::invalid_argument("speed_sq_pdf callable must be provided");
128 }
129 if (speed_sq_min < RealType(0.0))
130 {
131 throw std::invalid_argument("speed_sq_min must be non-negative (w = v_par^2 >= 0)");
132 }
133 if (!(speed_sq_min <= speed_sq_max))
134 {
135 throw std::invalid_argument("speed_sq_max must not be less than speed_sq_min");
136 }
137 if (theta_perp <= RealType(0.0))
138 {
139 throw std::invalid_argument("theta_perp must be positive");
140 }
141 if (parallel_sign != 1 && parallel_sign != -1)
142 {
143 throw std::invalid_argument("parallel_sign must be exactly +1 or -1");
144 }
145 if (probe_points < kMinProbePoints)
146 {
147 // Too few probes can miss the peak of g and bias the samples silently.
148 throw std::invalid_argument("probe_points must be at least 64");
149 }
150 if (max_reject_tries <= 0)
151 {
152 throw std::invalid_argument("max_reject_tries must be positive");
153 }
154 if (!(max_normalized_velocity > RealType(0.0)))
155 {
156 throw std::invalid_argument(
157 "max_normalized_velocity must be positive, or no_cap() for no perpendicular cap");
158 }
159
160 RealType ubNorm2= ub[0] * ub[0] + ub[1] * ub[1] + ub[2] * ub[2];
161 if (approximatelyEqual(ubNorm2, RealType(0.0)))
162 {
163 throw std::invalid_argument("ub (magnetic field) must be a non-zero vector");
164 }
165
166 m_speedSqPdf= speed_sq_pdf;
167 m_speedSqMin= speed_sq_min;
168 m_speedSqMax= speed_sq_max;
169 m_thetaPerp= theta_perp;
170 m_ub= ub;
171 m_parallelSign= static_cast<RealType>(parallel_sign);
172 m_maxNormalizedVelocity= max_normalized_velocity;
173 m_maxRejectTries= max_reject_tries;
174 m_pdfUpperBound= RealType(0.0);
175
176 m_distSpeedSq.param(typename std::uniform_real_distribution<RealType>::param_type(
177 m_speedSqMin, m_speedSqMax));
178 m_distAccept.param(
179 typename std::uniform_real_distribution<RealType>::param_type(RealType(0.0),
180 RealType(1.0)));
181
182 // A single-valued range needs no envelope: every sample has w = speed_sq_min.
183 if (speed_sq_min < speed_sq_max)
184 {
185 m_pdfUpperBound= estimatePdfUpperBound(probe_points);
186 if (m_pdfUpperBound <= RealType(0.0))
187 {
188 throw std::invalid_argument(
189 "speed_sq_pdf must be positive somewhere within [speed_sq_min, speed_sq_max]");
190 }
191
192 m_distAccept.param(typename std::uniform_real_distribution<RealType>::param_type(
193 RealType(0.0), m_pdfUpperBound));
194 }
195
196 reset();
197 m_isDefined= true;
198 }
199
202 void seed(int s)
203 {
204 applySeed(m_gen, s);
205 reset();
206 }
207
210 void reset()
211 {
212 m_distSpeedSq.reset();
213 m_distAccept.reset();
214 m_standardNormal.reset();
215 }
216
221 template <typename GeneratorType> point_type operator()(GeneratorType &gen)
222 {
223 if (!m_isDefined)
224 {
225 throw std::runtime_error(
226 "field_aligned_velocity_generator must be define(...)d before sampling");
227 }
228
229 const RealType sigmaScale= RealType(1.0) / std::sqrt(RealType(2.0));
230
231 // Parallel: v_par^2 -> signed speed along B.
232 RealType vPar= m_parallelSign * std::sqrt(sampleSpeedSq(gen));
233
234 // Perpendicular: 2D Maxwellian, N(0, theta_perp^2/2) per component, with the
235 // pair redrawn while either component exceeds the cap.
236 RealType vPerp1= RealType(0.0), vPerp2= RealType(0.0);
237 const RealType perpMax= m_maxNormalizedVelocity * m_thetaPerp;
238 int tries= 0;
239 for (tries= 0; tries < m_maxRejectTries; ++tries)
240 {
241 vPerp1= m_thetaPerp * sigmaScale * m_standardNormal(gen);
242 vPerp2= m_thetaPerp * sigmaScale * m_standardNormal(gen);
243 if (std::abs(vPerp1) <= perpMax && std::abs(vPerp2) <= perpMax)
244 break;
245 }
246 if (tries == m_maxRejectTries)
247 {
248 throw std::runtime_error("failed to sample the perpendicular components under "
249 "max_normalized_velocity: exceeded max_reject_tries");
250 }
251
252 // Field-aligned frame: (perp1 -> e1, perp2 -> e2, par -> e3 = B/|B|).
253 point_type local;
254 local[0]= vPerp1;
255 local[1]= vPerp2;
256 local[2]= vPar;
257 return rotate_from_fieldAligned_frame(local, m_ub);
258 }
259
262 {
263 return (*this)(m_gen);
264 }
265
266 RealType parallelSpeedSqMin() const { return m_speedSqMin; }
267 RealType parallelSpeedSqMax() const { return m_speedSqMax; }
268 RealType thetaPerp() const { return m_thetaPerp; }
269 point_type ub() const { return m_ub; }
270 RealType parallelSign() const { return m_parallelSign; }
272 RealType max_normalized_velocity() const { return m_maxNormalizedVelocity; }
275 RealType pdfUpperBound() const { return m_pdfUpperBound; }
276
277 // ====================================================================
278 // Geometry helper
279 // ====================================================================
284 {
285 const RealType kZero= RealType(0.0);
286 const RealType kOne= RealType(1.0);
287
288 RealType ubNorm2= ub[0] * ub[0] + ub[1] * ub[1] + ub[2] * ub[2];
289 if (approximatelyEqual(ubNorm2, kZero))
290 {
291 throw std::invalid_argument("ub must be a non-zero vector");
292 }
293
294 RealType ubNorm= std::sqrt(ubNorm2);
295
296 point_type e3;
297 e3[0]= ub[0] / ubNorm;
298 e3[1]= ub[1] / ubNorm;
299 e3[2]= ub[2] / ubNorm;
300
301 point_type e2({kOne, kOne, kOne});
302
303 int maxcomp= 0;
304 if (std::abs(e3[1]) > std::abs(e3[maxcomp]))
305 {
306 maxcomp= 1;
307 }
308 if (std::abs(e3[2]) > std::abs(e3[maxcomp]))
309 {
310 maxcomp= 2;
311 }
312
313 RealType sum= e3[0] + e3[1] + e3[2];
314 e2[maxcomp]= kOne - sum / e3[maxcomp];
315
316 RealType e2Norm2= e2[0] * e2[0] + e2[1] * e2[1] + e2[2] * e2[2];
317 RealType e2Norm= std::sqrt(e2Norm2);
318 e2[0]/= e2Norm;
319 e2[1]/= e2Norm;
320 e2[2]/= e2Norm;
321
322 point_type e1;
323 e1[0]= e2[1] * e3[2] - e2[2] * e3[1];
324 e1[1]= e2[2] * e3[0] - e2[0] * e3[2];
325 e1[2]= e2[0] * e3[1] - e2[1] * e3[0];
326
327 point_type point;
328 point[0]= local[0] * e1[0] + local[1] * e2[0] + local[2] * e3[0];
329 point[1]= local[0] * e1[1] + local[1] * e2[1] + local[2] * e3[1];
330 point[2]= local[0] * e1[2] + local[1] * e2[2] + local[2] * e3[2];
331 return point;
332 }
333
334 private:
335 RealType evaluateSpeedSqPdf(RealType speed_sq) const
336 {
337 RealType value= m_speedSqPdf(speed_sq);
338 if (!std::isfinite(value))
339 {
340 throw std::runtime_error("speed_sq_pdf returned a non-finite value");
341 }
342 if (value < RealType(0.0))
343 {
344 throw std::runtime_error(
345 "speed_sq_pdf returned a negative value; expected a non-negative PDF");
346 }
347 return value;
348 }
349
350 RealType estimatePdfUpperBound(int probe_points) const
351 {
352 RealType max_value= RealType(0.0);
353 int i= 0;
354 for (i= 0; i < probe_points; ++i)
355 {
356 RealType ratio= RealType(i) / RealType(probe_points - 1);
357 RealType speed_sq= m_speedSqMin + ratio * (m_speedSqMax - m_speedSqMin);
358 RealType value= evaluateSpeedSqPdf(speed_sq);
359 if (value > max_value)
360 {
361 max_value= value;
362 }
363 }
364
365 // Add safety margin in case peak lies between probes.
366 return max_value * RealType(1.05);
367 }
368
369 template <typename GeneratorType> RealType sampleSpeedSq(GeneratorType &gen)
370 {
371 if (!(m_speedSqMin < m_speedSqMax))
372 {
373 return m_speedSqMin;
374 }
375 int tries= 0;
376 for (tries= 0; tries < m_maxRejectTries; ++tries)
377 {
378 RealType speed_sq= m_distSpeedSq(gen);
379 RealType y= m_distAccept(gen);
380 RealType pdf_value= evaluateSpeedSqPdf(speed_sq);
381 if (y <= pdf_value)
382 {
383 return speed_sq;
384 }
385 }
386
387 throw std::runtime_error("failed to sample speed_sq from speed_sq_pdf: rejection sampling "
388 "exceeded max_reject_tries");
389 }
390
391 static void applySeed(std::mt19937 &gen, int s)
392 {
393 if (s < 0)
394 gen.seed(std::random_device{}());
395 else
396 gen.seed(static_cast<unsigned int>(s));
397 }
398
399 static const int kMinProbePoints= 64;
400
401 static bool approximatelyEqual(RealType a, RealType b)
402 {
403 RealType scale= std::max({RealType(1.0), std::abs(a), std::abs(b)});
404 return std::abs(a - b) <= std::numeric_limits<RealType>::epsilon() * scale;
405 }
406
407 speed_sq_pdf_function m_speedSqPdf;
408 RealType m_speedSqMin;
409 RealType m_speedSqMax;
410 RealType m_thetaPerp;
411 point_type m_ub;
412 RealType m_parallelSign;
413 RealType m_maxNormalizedVelocity;
414 int m_maxRejectTries;
415 RealType m_pdfUpperBound;
416 bool m_isDefined;
417 std::mt19937 m_gen;
418 std::uniform_real_distribution<RealType> m_distSpeedSq;
419 std::uniform_real_distribution<RealType> m_distAccept;
420 std::normal_distribution<RealType> m_standardNormal;
421};
422
423#endif // _FIELD_ALIGNED_VELOCITY_GENERATOR_H_
static constexpr RealType no_cap()
Value of max_normalized_velocity that removes the perpendicular cap.
point_type operator()(GeneratorType &gen)
Draw one velocity from the engine gen instead of the internal one.
std::array< RealType, 3 > result_type
A velocity {vx, vy, vz}.
RealType parallelSpeedSqMin() const
Lower end of the sampled v_par^2.
RealType pdfUpperBound() const
The rejection envelope: the largest probed value of g times 1.05, or 0 when speed_sq_min == speed_sq_...
RealType parallelSpeedSqMax() const
Upper end of the sampled v_par^2.
std::function< RealType(RealType)> speed_sq_pdf_function
The type of the density g(w) passed to define().
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,...
RealType parallelSign() const
+1 or -1, as a RealType.
void seed(int s)
Reseed the internal engine and discard any variate cached from before, so that seed(s) followed by n ...
point_type operator()()
Draw one velocity from the internal engine; throws as operator()(gen) does.
RealType max_normalized_velocity() const
Cap on each perpendicular component, in units of theta_perp; +infinity for no_cap().
point_type ub() const
Field direction, as given.
field_aligned_velocity_generator(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))
Construct and call define() with these arguments.
field_aligned_velocity_generator()
Construct an undefined generator; call define() before drawing.
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.
void reset()
Discard any state cached by the internal distributions, including the second normal variate of std::n...
RealType thetaPerp() const
Perpendicular thermal speed.