bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
general_velocity_generator.H
Go to the documentation of this file.
1#ifndef _GENERAL_VELOCITY_GENERATOR_H_
2#define _GENERAL_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
30template <typename RealType= double> class general_velocity_generator
31{
32 public:
33 using result_type= std::array<RealType, 3>;
36 using speed_sq_pdf_function= std::function<RealType(RealType)>;
37
41 : m_speedSqPdf(), m_speedSqMin(RealType(0.0)), m_speedSqMax(RealType(1.0)),
42 m_maxRejectTries(100000),
43 m_pdfUpperBound(RealType(0.0)), m_isDefined(false), m_gen(std::random_device{}()),
44 m_distSpeedSq(RealType(0.0), RealType(1.0)), m_distAccept(RealType(0.0), RealType(1.0)),
45 m_distCosTheta(RealType(-1.0), RealType(1.0)),
46 m_distPhi(RealType(0.0), RealType(2.0) * piValue())
47 {
48 }
49
51 general_velocity_generator(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min,
52 RealType speed_sq_max, int probe_points= 1024,
53 int max_reject_tries= 100000)
55 {
56 define(speed_sq_pdf, speed_sq_min, speed_sq_max, probe_points, max_reject_tries);
57 }
58
93 void define(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min, RealType speed_sq_max,
94 int probe_points= 1024, int max_reject_tries= 100000)
95 {
96 m_isDefined= false;
97
98 if (!speed_sq_pdf)
99 {
100 throw std::invalid_argument("speed_sq_pdf callable must be provided");
101 }
102 if (speed_sq_min < RealType(0.0))
103 {
104 throw std::invalid_argument("speed_sq_min must be non-negative (w = |v|^2 >= 0)");
105 }
106 if (!(speed_sq_min <= speed_sq_max))
107 {
108 throw std::invalid_argument("speed_sq_max must not be less than speed_sq_min");
109 }
110 if (probe_points < kMinProbePoints)
111 {
112 // An envelope estimated from a handful of probes can miss the peak of g and
113 // bias the samples silently. The floor also rejects a call written for the
114 // 1.0.0 interface define(f, E_min, E_max, mass) whose mass, landing here, is
115 // below 64.
116 throw std::invalid_argument("probe_points must be at least 64");
117 }
118 if (max_reject_tries <= 0)
119 {
120 throw std::invalid_argument("max_reject_tries must be positive");
121 }
122
123 m_speedSqPdf= speed_sq_pdf;
124 m_speedSqMin= speed_sq_min;
125 m_speedSqMax= speed_sq_max;
126 m_maxRejectTries= max_reject_tries;
127 m_pdfUpperBound= RealType(0.0);
128
129 m_distSpeedSq.param(typename std::uniform_real_distribution<RealType>::param_type(
130 m_speedSqMin, m_speedSqMax));
131 m_distAccept.param(
132 typename std::uniform_real_distribution<RealType>::param_type(RealType(0.0),
133 RealType(1.0)));
134 m_distCosTheta.param(typename std::uniform_real_distribution<RealType>::param_type(
135 RealType(-1.0), RealType(1.0)));
136 m_distPhi.param(typename std::uniform_real_distribution<RealType>::param_type(
137 RealType(0.0), RealType(2.0) * piValue()));
138
139 // A single-valued range needs no envelope: every sample has w = speed_sq_min.
140 if (speed_sq_min < speed_sq_max)
141 {
142 m_pdfUpperBound= estimatePdfUpperBound(probe_points);
143 if (m_pdfUpperBound <= RealType(0.0))
144 {
145 throw std::invalid_argument(
146 "speed_sq_pdf must be positive somewhere within [speed_sq_min, speed_sq_max]");
147 }
148
149 m_distAccept.param(typename std::uniform_real_distribution<RealType>::param_type(
150 RealType(0.0), m_pdfUpperBound));
151 }
152
153 reset();
154 m_isDefined= true;
155 }
156
159 void seed(int s)
160 {
161 applySeed(m_gen, s);
162 reset();
163 }
164
167 void reset()
168 {
169 m_distSpeedSq.reset();
170 m_distAccept.reset();
171 m_distCosTheta.reset();
172 m_distPhi.reset();
173 }
174
179 template <typename GeneratorType> point_type operator()(GeneratorType &gen)
180 {
181 if (!m_isDefined)
182 {
183 throw std::runtime_error(
184 "general_velocity_generator must be define(...)d before sampling");
185 }
186
187 const RealType kOne= RealType(1.0);
188
189 RealType speed= std::sqrt(sampleSpeedSq(gen)); // |V| = sqrt(w), w = |V|^2
190
191 RealType cosTheta= m_distCosTheta(gen);
192 RealType sinTheta= std::sqrt(std::max(RealType(0.0), kOne - cosTheta * cosTheta));
193 RealType phi= m_distPhi(gen);
194
195 RealType vx= speed * sinTheta * std::cos(phi);
196 RealType vy= speed * sinTheta * std::sin(phi);
197 RealType vz= speed * cosTheta;
198
199 point_type point;
200 point[0]= vx;
201 point[1]= vy;
202 point[2]= vz;
203 return point;
204 }
205
208 {
209 return (*this)(m_gen);
210 }
211
212 RealType speedSqMin() const { return m_speedSqMin; }
213 RealType speedSqMax() const { return m_speedSqMax; }
216 RealType pdfUpperBound() const { return m_pdfUpperBound; }
217
218 private:
219 RealType evaluateSpeedSqPdf(RealType speed_sq) const
220 {
221 RealType value= m_speedSqPdf(speed_sq);
222 if (!std::isfinite(value))
223 {
224 throw std::runtime_error("speed_sq_pdf returned a non-finite value");
225 }
226 if (value < RealType(0.0))
227 {
228 throw std::runtime_error(
229 "speed_sq_pdf returned a negative value; expected a non-negative PDF");
230 }
231 return value;
232 }
233
234 RealType estimatePdfUpperBound(int probe_points) const
235 {
236 RealType max_value= RealType(0.0);
237 int i= 0;
238 for (i= 0; i < probe_points; ++i)
239 {
240 RealType ratio= RealType(i) / RealType(probe_points - 1);
241 RealType speed_sq= m_speedSqMin + ratio * (m_speedSqMax - m_speedSqMin);
242 RealType value= evaluateSpeedSqPdf(speed_sq);
243 if (value > max_value)
244 {
245 max_value= value;
246 }
247 }
248
249 // Add safety margin in case peak lies between probes.
250 return max_value * RealType(1.05);
251 }
252
253 template <typename GeneratorType> RealType sampleSpeedSq(GeneratorType &gen)
254 {
255 if (!(m_speedSqMin < m_speedSqMax))
256 {
257 return m_speedSqMin;
258 }
259 int tries= 0;
260 for (tries= 0; tries < m_maxRejectTries; ++tries)
261 {
262 RealType speed_sq= m_distSpeedSq(gen);
263 RealType y= m_distAccept(gen);
264 RealType pdf_value= evaluateSpeedSqPdf(speed_sq);
265 if (y <= pdf_value)
266 {
267 return speed_sq;
268 }
269 }
270
271 throw std::runtime_error("failed to sample speed_sq from speed_sq_pdf: rejection sampling "
272 "exceeded max_reject_tries");
273 }
274
275 static void applySeed(std::mt19937 &gen, int s)
276 {
277 if (s < 0)
278 gen.seed(std::random_device{}());
279 else
280 gen.seed(static_cast<unsigned int>(s));
281 }
282
283 static RealType piValue() { return RealType(3.14159265358979323846264338327950288L); }
284
285 static const int kMinProbePoints= 64;
286
287 speed_sq_pdf_function m_speedSqPdf;
288 RealType m_speedSqMin;
289 RealType m_speedSqMax;
290 int m_maxRejectTries;
291 RealType m_pdfUpperBound;
292 bool m_isDefined;
293 std::mt19937 m_gen;
294 std::uniform_real_distribution<RealType> m_distSpeedSq;
295 std::uniform_real_distribution<RealType> m_distAccept;
296 std::uniform_real_distribution<RealType> m_distCosTheta;
297 std::uniform_real_distribution<RealType> m_distPhi;
298};
299
300#endif // _GENERAL_VELOCITY_GENERATOR_H_
point_type operator()(GeneratorType &gen)
Draw one velocity from the engine gen instead of the internal one.
point_type operator()()
Draw one velocity from the internal engine; throws as operator()(gen) does.
void seed(int s)
Reseed the internal engine and discard any variate cached from before, so that seed(s) followed by n ...
general_velocity_generator(speed_sq_pdf_function speed_sq_pdf, RealType speed_sq_min, RealType speed_sq_max, int probe_points=1024, int max_reject_tries=100000)
Construct and call define() with these arguments.
RealType pdfUpperBound() const
The rejection envelope: the largest probed value of g times 1.05, or 0 when speed_sq_min == speed_sq_...
void reset()
Discard any state cached by the internal distributions.
general_velocity_generator()
Construct an undefined generator; call define() before drawing.
std::function< RealType(RealType)> speed_sq_pdf_function
The type of the density g(w) passed to define().
result_type point_type
Same as result_type.
RealType speedSqMin() const
Lower end of the sampled w.
std::array< RealType, 3 > result_type
A velocity {vx, vy, vz}.
RealType speedSqMax() const
Upper end of the sampled w.
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.