bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
general_position_generator.H
Go to the documentation of this file.
1#ifndef _GENERAL_POSITION_GENERATOR_H_
2#define _GENERAL_POSITION_GENERATOR_H_
3
4#include <cmath>
5#include <cstddef>
6#include <functional>
7#include <random>
8#include <stdexcept>
9#include <vector>
10
26template <typename RealType= double> class general_position_generator
27{
28 public:
29 using result_type= std::vector<RealType>;
32 using density_function= std::function<RealType(const point_type &)>;
33
37 : m_dimension(0), m_lowerBounds(), m_upperBounds(), m_rangeWidths(), m_densityFunction(),
38 m_maxRejectTries(200000), m_densityUpperBound(RealType(0.0)), m_isDefined(false),
39 m_gen(std::random_device{}()),
40 m_distAccept(RealType(0.0), RealType(1.0)), m_distUnit(RealType(0.0), RealType(1.0))
41 {
42 }
43
46 const point_type &upper_bounds, density_function density_function,
47 int probe_points= 4096, int max_reject_tries= 200000)
49 {
50 define(dimension, lower_bounds, upper_bounds, density_function, probe_points,
51 max_reject_tries);
52 }
53
84 void define(int dimension, const point_type &lower_bounds, const point_type &upper_bounds,
85 density_function density_function, int probe_points= 4096,
86 int max_reject_tries= 200000)
87 {
88 m_isDefined= false;
89
90 if (!(dimension >= 1 && dimension <= 3))
91 {
92 throw std::invalid_argument("dimension must be 1, 2, or 3");
93 }
95 {
96 throw std::invalid_argument("density_function callable must be provided");
97 }
98 if (lower_bounds.size() != static_cast<std::size_t>(dimension) ||
99 upper_bounds.size() != static_cast<std::size_t>(dimension))
100 {
101 throw std::invalid_argument("lower_bounds and upper_bounds sizes must match dimension");
102 }
103 if (probe_points <= 0)
104 {
105 throw std::invalid_argument("probe_points must be positive");
106 }
107 if (max_reject_tries <= 0)
108 {
109 throw std::invalid_argument("max_reject_tries must be positive");
110 }
111
112 point_type range_widths(static_cast<std::size_t>(dimension), RealType(0.0));
113
114 int d= 0;
115 for (d= 0; d < dimension; ++d)
116 {
117 std::size_t idx= static_cast<std::size_t>(d);
118 if (!(lower_bounds[idx] < upper_bounds[idx]))
119 {
120 throw std::invalid_argument("each lower bound must be strictly less than its upper "
121 "bound");
122 }
123 range_widths[idx]= upper_bounds[idx] - lower_bounds[idx];
124 }
125
126 m_dimension= dimension;
127 m_lowerBounds= lower_bounds;
128 m_upperBounds= upper_bounds;
129 m_rangeWidths= range_widths;
130 m_densityFunction= density_function;
131 m_maxRejectTries= max_reject_tries;
132 m_densityUpperBound= RealType(0.0);
133
134 m_distAccept.param(
135 typename std::uniform_real_distribution<RealType>::param_type(RealType(0.0),
136 RealType(1.0)));
137 m_distUnit.param(
138 typename std::uniform_real_distribution<RealType>::param_type(RealType(0.0),
139 RealType(1.0)));
140
141 m_densityUpperBound= estimateDensityUpperBound(probe_points);
142 if (m_densityUpperBound <= RealType(0.0))
143 {
144 throw std::invalid_argument("density_function must be positive somewhere inside the "
145 "domain");
146 }
147
148 m_distAccept.param(typename std::uniform_real_distribution<RealType>::param_type(
149 RealType(0.0), m_densityUpperBound));
150
151 reset();
152 m_isDefined= true;
153 }
154
157 void seed(int s)
158 {
159 applySeed(m_gen, s);
160 reset();
161 }
162
165 void reset()
166 {
167 m_distAccept.reset();
168 m_distUnit.reset();
169 }
170
171 int dimension() const { return m_dimension; }
172 const point_type &lowerBounds() const { return m_lowerBounds; }
173 const point_type &upperBounds() const { return m_upperBounds; }
176 RealType densityUpperBound() const { return m_densityUpperBound; }
177
181 template <typename GeneratorType> point_type operator()(GeneratorType &gen) const
182 {
183 if (!m_isDefined)
184 {
185 throw std::runtime_error(
186 "general_position_generator must be define(...)d before sampling");
187 }
188
189 int tries= 0;
190 for (tries= 0; tries < m_maxRejectTries; ++tries)
191 {
192 point_type point= sampleUniformPoint(gen);
193 RealType rho= evaluateDensity(point);
194 RealType y= m_distAccept(gen);
195 if (y <= rho)
196 {
197 return point;
198 }
199 }
200
201 throw std::runtime_error("failed to sample position from density_function: rejection "
202 "sampling exceeded max_reject_tries");
203 }
204
207 {
208 return (*this)(m_gen);
209 }
210
211 private:
212 static void applySeed(std::mt19937 &gen, int s)
213 {
214 if (s < 0)
215 gen.seed(std::random_device{}());
216 else
217 gen.seed(static_cast<unsigned int>(s));
218 }
219
220 RealType evaluateDensity(const point_type &point) const
221 {
222 RealType value= m_densityFunction(point);
223 if (!std::isfinite(value))
224 {
225 throw std::runtime_error("density_function returned a non-finite value");
226 }
227 if (value < RealType(0.0))
228 {
229 throw std::runtime_error("density_function returned a negative value; expected a "
230 "non-negative density");
231 }
232 return value;
233 }
234
235 template <typename GeneratorType> point_type sampleUniformPoint(GeneratorType &gen) const
236 {
237 point_type point(static_cast<std::size_t>(m_dimension), RealType(0.0));
238 int d= 0;
239 for (d= 0; d < m_dimension; ++d)
240 {
241 std::size_t idx= static_cast<std::size_t>(d);
242 point[idx]= m_lowerBounds[idx] + m_rangeWidths[idx] * m_distUnit(gen);
243 }
244 return point;
245 }
246
247 RealType estimateDensityUpperBound(int probe_points) const
248 {
249 std::mt19937 probeGen(1337u);
250 RealType max_value= RealType(0.0);
251
252 int i= 0;
253 for (i= 0; i < probe_points; ++i)
254 {
255 point_type point= sampleUniformPoint(probeGen);
256 RealType value= evaluateDensity(point);
257 if (value > max_value)
258 {
259 max_value= value;
260 }
261 }
262
263 // Add safety margin in case peak lies between probes.
264 return max_value * RealType(1.05);
265 }
266
267 int m_dimension;
268 point_type m_lowerBounds;
269 point_type m_upperBounds;
270 point_type m_rangeWidths;
271 density_function m_densityFunction;
272 int m_maxRejectTries;
273 RealType m_densityUpperBound;
274 bool m_isDefined;
275 mutable std::mt19937 m_gen;
276 mutable std::uniform_real_distribution<RealType> m_distAccept;
277 mutable std::uniform_real_distribution<RealType> m_distUnit;
278};
279
280#endif // _GENERAL_POSITION_GENERATOR_H_
const point_type & lowerBounds() const
Lower corner of the box.
general_position_generator()
Construct an undefined generator; call define() before drawing.
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.
point_type operator()(GeneratorType &gen) const
Draw one position from the engine gen instead of the internal one.
void reset()
Discard any state cached by the internal uniform distributions.
std::function< RealType(const point_type &)> density_function
The type of the density rho(x) passed to define().
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()() const
Draw one position from the internal engine; throws as operator()(gen) does.
int dimension() const
1, 2 or 3; 0 before define().
std::vector< RealType > result_type
A position, of length dimension().
RealType densityUpperBound() const
The rejection envelope: the largest probed value of rho times 1.05.
general_position_generator(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)
Construct and call define() with these arguments.
const point_type & upperBounds() const
Upper corner of the box.
result_type point_type
Same as result_type.