bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
general_generators.py
Go to the documentation of this file.
1"""NumPy versions of the general velocity and position generators.
2
3GeneralVelocityGenerator, FieldAlignedVelocityGenerator and
4GeneralPositionGenerator are small NumPy ports of the C++ classes
5general_velocity_generator, field_aligned_velocity_generator and
6general_position_generator in cpp/, meant for prototyping a density in
7Python. They take the same parameters and use the same rejection envelope (the
8largest density found at a set of probe points, times 1.05). They are not a
9validated equivalent of the C++ classes: the C++ regression suite does not
10cover them, they check fewer invalid inputs, and they do not reproduce the C++
11random streams.
12
13Each generator is called with a numpy.random.Generator and returns one draw:
14``v = gen(rng)``. Running this file writes three example sample files to the
15current directory.
16"""
17
18import math
19from typing import Callable, List
20
21import numpy as np
22
23# Fewer probes can miss the peak of g and bias the samples silently (as in the C++ headers).
24MIN_PROBE_POINTS = 64
25
26
28 """Samples velocities from a user-defined speed-squared distribution g(w), w = |v|^2.
29
30 The speed is |v| = sqrt(w); the direction is isotropic in 3D. (For a
31 distribution originally posed in energy, w = |v|^2 = 2E/m, so the mass drops
32 out of this generator entirely.) If speed_sq_min == speed_sq_max, every sample has
33 the single speed sqrt(speed_sq_min)."""
34
35 def __init__(self, speed_sq_pdf: Callable, speed_sq_min: float, speed_sq_max: float,
36 probe_points: int = 1024, max_reject_tries: int = 100000):
37 if speed_sq_min < 0.0:
38 raise ValueError("speed_sq_min must be non-negative (w = |v|^2 >= 0)")
39 if not (speed_sq_min <= speed_sq_max):
40 raise ValueError("speed_sq_max must not be less than speed_sq_min")
41 if probe_points < MIN_PROBE_POINTS:
42 raise ValueError("probe_points must be at least 64")
43 self.speed_sq_pdf = speed_sq_pdf
44 self.speed_sq_min = speed_sq_min
45 self.speed_sq_max = speed_sq_max
46 self.max_reject_tries = max_reject_tries
47
48 # Estimate upper bound of the PDF (not needed for a single-valued range).
49 self.pdf_upper_bound = (self._estimate_pdf_upper_bound(probe_points)
50 if speed_sq_min < speed_sq_max else 0.0)
51
52 def _estimate_pdf_upper_bound(self, probe_points: int) -> float:
53 """Estimate the maximum value of the speed-squared PDF, with a 5% margin."""
54 grid = np.linspace(self.speed_sq_min, self.speed_sq_max, probe_points)
55 pdf_values = np.array([self.speed_sq_pdf(w) for w in grid])
56 return np.max(pdf_values) * 1.05
57
58 def sample_speed_sq(self, rng: np.random.Generator) -> float:
59 """Sample w = |v|^2 using rejection sampling."""
60 if not self.speed_sq_min < self.speed_sq_max:
61 return self.speed_sq_min
62 for _ in range(self.max_reject_tries):
63 w = rng.uniform(self.speed_sq_min, self.speed_sq_max)
64 u = rng.uniform(0, self.pdf_upper_bound)
65 if u <= self.speed_sq_pdf(w):
66 return w
67 raise RuntimeError("Failed to sample speed_sq after max_reject_tries attempts")
68
69 def __call__(self, rng: np.random.Generator) -> np.ndarray:
70 """Generate a random 3D velocity vector."""
71 speed = np.sqrt(self.sample_speed_sq(rng))
72
73 # Isotropic direction on sphere
74 cos_theta = rng.uniform(-1.0, 1.0)
75 sin_theta = np.sqrt(max(0.0, 1.0 - cos_theta**2))
76 phi = rng.uniform(0.0, 2.0 * np.pi)
77
78 vx = speed * sin_theta * np.cos(phi)
79 vy = speed * sin_theta * np.sin(phi)
80 vz = speed * cos_theta
81
82 return np.array([vx, vy, vz])
83
84
86 """Samples positions in 1D/2D/3D from a user density rho(x) by rejection sampling.
87
88 The domain is the axis-aligned box lower_bounds <= x <= upper_bounds, a hard
89 support. density_function takes a list of length ``dimension`` and returns
90 a finite, non-negative value, positive somewhere in the box; it need not be
91 normalized. The rejection envelope is the largest density found at
92 probe_points uniform points, drawn from a fixed seed so that two identical
93 constructions give the same envelope, times a 5% margin. A peak narrow
94 enough to fall between the probes is undersampled without warning. Each
95 call returns an array of length ``dimension``.
96 """
97
98 PROBE_SEED = 1337 # fixed, as in the C++ class, so the envelope is reproducible
99
100 def __init__(self, dimension: int, lower_bounds: List[float], upper_bounds: List[float],
101 density_function: Callable, probe_points: int = 4096, max_reject_tries: int = 200000):
102 if isinstance(dimension, bool) or dimension not in (1, 2, 3):
103 raise ValueError("dimension must be 1, 2, or 3")
104 if not callable(density_function):
105 raise ValueError("density_function must be callable")
106 lower = np.asarray(lower_bounds, dtype=float)
107 upper = np.asarray(upper_bounds, dtype=float)
108 if lower.shape != (dimension,) or upper.shape != (dimension,):
109 raise ValueError("lower_bounds and upper_bounds must each have `dimension` entries")
110 if not (np.isfinite(lower).all() and np.isfinite(upper).all()):
111 raise ValueError("the bounds must be finite")
112 if not (lower < upper).all():
113 raise ValueError("each lower bound must be strictly less than its upper bound")
114 if probe_points <= 0:
115 raise ValueError("probe_points must be positive")
116 if max_reject_tries <= 0:
117 raise ValueError("max_reject_tries must be positive")
118
119 self.dimension = dimension
120 self.lower_bounds = lower
121 self.upper_bounds = upper
122 self.density_function = density_function
123 self.max_reject_tries = max_reject_tries
124
126 if not self.density_upper_bound > 0.0:
127 raise ValueError("density_function must be positive somewhere inside the domain")
128
129 def _density(self, x: np.ndarray) -> float:
130 rho = float(self.density_function(x.tolist()))
131 if not math.isfinite(rho):
132 raise ValueError("density_function returned a non-finite value")
133 if rho < 0.0:
134 raise ValueError("density_function returned a negative value; expected a "
135 "non-negative density")
136 return rho
137
138 def _estimate_density_upper_bound(self, probe_points: int) -> float:
139 """Largest density at probe_points uniform points in the box, with a 5% margin."""
140 probe_rng = np.random.default_rng(self.PROBE_SEED)
141 width = self.upper_bounds - self.lower_bounds
142 max_density = 0.0
143 for _ in range(probe_points):
144 x = self.lower_bounds + probe_rng.uniform(0.0, 1.0, self.dimension) * width
145 max_density = max(max_density, self._density(x))
146 return max_density * 1.05
147
148 def __call__(self, rng: np.random.Generator) -> np.ndarray:
149 """Generate one position, an array of length ``dimension``."""
150 width = self.upper_bounds - self.lower_bounds
151 for _ in range(self.max_reject_tries):
152 x = self.lower_bounds + rng.uniform(0.0, 1.0, self.dimension) * width
153 u = rng.uniform(0.0, self.density_upper_bound)
154 if u <= self._density(x):
155 return x
156
157 raise RuntimeError("Failed to sample position after max_reject_tries attempts")
158
159
161 """Samples field-aligned velocities: an arbitrary parallel speed-squared
162 distribution g(w_par), w_par = v_par^2, along B, with a Maxwellian
163 perpendicular spread (thermal speed theta_perp). (For a distribution
164 originally posed in energy, w_par = v_par^2 = 2E_par/m, so the mass drops
165 out.) If speed_sq_min == speed_sq_max, every sample has the single parallel speed
166 sqrt(speed_sq_min). Each perpendicular component is capped at
167 max_normalized_velocity * theta_perp (default 20, as in the C++ header); pass
168 math.inf for no cap."""
169
170 def __init__(self, speed_sq_pdf: Callable, speed_sq_min: float, speed_sq_max: float,
171 theta_perp: float, ub: List[float], parallel_sign: int,
172 probe_points: int = 1024, max_reject_tries: int = 100000,
173 max_normalized_velocity: float = 20.0):
174 if speed_sq_min < 0.0:
175 raise ValueError("speed_sq_min must be non-negative (w = v_par^2 >= 0)")
176 if not (speed_sq_min <= speed_sq_max):
177 raise ValueError("speed_sq_max must not be less than speed_sq_min")
178 if probe_points < MIN_PROBE_POINTS:
179 raise ValueError("probe_points must be at least 64")
180 if not max_normalized_velocity > 0.0:
181 raise ValueError("max_normalized_velocity must be positive, or math.inf for no cap")
182 if theta_perp <= 0.0:
183 raise ValueError("theta_perp must be positive")
184 if parallel_sign not in (1, -1):
185 raise ValueError("parallel_sign must be exactly +1 or -1")
186 ub = np.asarray(ub, dtype=float)
187 if np.dot(ub, ub) == 0.0:
188 raise ValueError("ub (magnetic field) must be a non-zero vector")
189
190 self.speed_sq_pdf = speed_sq_pdf
191 self.speed_sq_min = speed_sq_min
192 self.speed_sq_max = speed_sq_max
193 self.theta_perp = theta_perp
194 self.parallel_sign = float(parallel_sign)
195 self.max_normalized_velocity = max_normalized_velocity
196 self.max_reject_tries = max_reject_tries
197
198 # Field-aligned orthonormal frame (e1, e2 perpendicular; e3 = B/|B|).
199 self.e1, self.e2, self.e3 = self._build_frame(ub)
200
201 # Estimate upper bound of the parallel speed-squared PDF.
203 if speed_sq_min < speed_sq_max else 0.0)
204
205 @staticmethod
206 def _build_frame(ub: np.ndarray):
207 """Right-handed orthonormal frame with e3 aligned to ub."""
208 e3 = ub / np.linalg.norm(ub)
209 # Pick a seed vector least aligned with e3 to stay well-conditioned.
210 seed = np.zeros(3)
211 seed[np.argmin(np.abs(e3))] = 1.0
212 e1 = np.cross(e3, seed)
213 e1 /= np.linalg.norm(e1)
214 e2 = np.cross(e3, e1)
215 return e1, e2, e3
216
217 def _estimate_pdf_upper_bound(self, probe_points: int) -> float:
218 grid = np.linspace(self.speed_sq_min, self.speed_sq_max, probe_points)
219 pdf_values = np.array([self.speed_sq_pdf(w) for w in grid])
220 return np.max(pdf_values) * 1.05
221
222 def sample_speed_sq(self, rng: np.random.Generator) -> float:
223 """Sample w_par = v_par^2 using rejection sampling."""
224 if not self.speed_sq_min < self.speed_sq_max:
225 return self.speed_sq_min
226 for _ in range(self.max_reject_tries):
227 w = rng.uniform(self.speed_sq_min, self.speed_sq_max)
228 u = rng.uniform(0, self.pdf_upper_bound)
229 if u <= self.speed_sq_pdf(w):
230 return w
231 raise RuntimeError("Failed to sample speed_sq after max_reject_tries attempts")
232
233 def __call__(self, rng: np.random.Generator) -> np.ndarray:
234 """Generate a random 3D velocity vector in the global frame."""
235 v_par = self.parallel_sign * np.sqrt(self.sample_speed_sq(rng))
236
237 # Perpendicular 2D Maxwellian: N(0, theta_perp^2/2) per component, with the pair
238 # redrawn while either component exceeds the cap.
239 sigma_perp = self.theta_perp / np.sqrt(2.0)
240 perp_max = self.max_normalized_velocity * self.theta_perp
241 for _ in range(self.max_reject_tries):
242 v_perp1 = sigma_perp * rng.standard_normal()
243 v_perp2 = sigma_perp * rng.standard_normal()
244 if abs(v_perp1) <= perp_max and abs(v_perp2) <= perp_max:
245 break
246 else:
247 raise RuntimeError("Failed to sample the perpendicular components under "
248 "max_normalized_velocity after max_reject_tries attempts")
249
250 return v_perp1 * self.e1 + v_perp2 * self.e2 + v_par * self.e3
251
252
253def main():
254 """Write example samples from the three generators to text files."""
255 n_particle = 200000
256 rng = np.random.default_rng(20030410)
257
258 theta_perp = 1.0
259
260 # g(w) = sqrt(w) exp(-w/theta^2) with w = |v|^2 is the speed-squared density of an
261 # isotropic Maxwellian of thermal speed theta: dw = 2|v| d|v| turns the sqrt(w) into
262 # the |v|^2 of the Maxwell speed pdf, so each Cartesian component is N(0, theta^2/2).
263 print("=== Example 1: GeneralVelocityGenerator g(w)=sqrt(w)exp(-w/theta^2), w=|v|^2 ===")
264 theta_iso = theta_perp
265 speed_sq_pdf = lambda w: np.sqrt(w) * np.exp(-w / theta_iso**2)
266 vel_gen = GeneralVelocityGenerator(speed_sq_pdf, 0.0, 25.0)
267
268 samples_velocity = []
269 for i in range(n_particle):
270 v = vel_gen(rng)
271 samples_velocity.append(v)
272 if (i + 1) % 100000 == 0:
273 print(f" generated {i + 1} samples")
274
275 # Write to file
276 with open("samples_general_velocity.txt", "w") as f:
277 for v in samples_velocity:
278 f.write(f"{v[0]} {v[1]} {v[2]}\n")
279 print(f"Wrote {n_particle} samples to samples_general_velocity.txt\n")
280
281 print("=== Example 2: GeneralPositionGenerator rho=1+sin(x)sin(y) ===")
282 rho = lambda x: 1.0 + np.sin(x[0]) * np.sin(x[1])
283
284 # 2D domain [-pi, pi]^2
285 pos_gen = GeneralPositionGenerator(2, [-np.pi, -np.pi], [np.pi, np.pi], rho)
286
287 samples_position = []
288 for i in range(n_particle):
289 x = pos_gen(rng)
290 samples_position.append(x)
291 if (i + 1) % 100000 == 0:
292 print(f" generated {i + 1} samples")
293
294 # Write to file
295 with open("samples_general_position.txt", "w") as f:
296 for x in samples_position:
297 f.write(f"{x[0]} {x[1]}\n")
298 print(f"Wrote {n_particle} samples to samples_general_position.txt\n")
299
300 # The simplest possible input: g(w) = 1 makes w = v_par^2 uniform on [0, w_max],
301 # and dw = 2 v_par d(v_par) turns that into the linear ramp
302 # p(v_par) = 2 v_par / w_max on [0, sqrt(w_max)]; B is tilted off the axes to
303 # exercise the rotation.
304 print("=== Example 3: FieldAlignedVelocityGenerator g(w)=1, B=(1,1,1), + ===")
305 w_max_par = 4.0 # v_par spans [0, 2]
306 parallel_speed_sq_pdf = lambda _w: 1.0
307 fa_gen = FieldAlignedVelocityGenerator(parallel_speed_sq_pdf, 0.0, w_max_par,
308 theta_perp=theta_perp, ub=[1.0, 1.0, 1.0],
309 parallel_sign=+1)
310
311 samples_field_aligned = []
312 for i in range(n_particle):
313 v = fa_gen(rng)
314 samples_field_aligned.append(v)
315 if (i + 1) % 100000 == 0:
316 print(f" generated {i + 1} samples")
317
318 # Write to file
319 with open("samples_field_aligned.txt", "w") as f:
320 for v in samples_field_aligned:
321 f.write(f"{v[0]} {v[1]} {v[2]}\n")
322 print(f"Wrote {n_particle} samples to samples_field_aligned.txt")
323
324
325if __name__ == "__main__":
326 main()
float _estimate_pdf_upper_bound(self, int probe_points)
float sample_speed_sq(self, np.random.Generator rng)
__init__(self, Callable speed_sq_pdf, float speed_sq_min, float speed_sq_max, float theta_perp, List[float] ub, int parallel_sign, int probe_points=1024, int max_reject_tries=100000, float max_normalized_velocity=20.0)
np.ndarray __call__(self, np.random.Generator rng)
np.ndarray __call__(self, np.random.Generator rng)
float _estimate_density_upper_bound(self, int probe_points)
__init__(self, int dimension, List[float] lower_bounds, List[float] upper_bounds, Callable density_function, int probe_points=4096, int max_reject_tries=200000)
__init__(self, Callable speed_sq_pdf, float speed_sq_min, float speed_sq_max, int probe_points=1024, int max_reject_tries=100000)
np.ndarray __call__(self, np.random.Generator rng)
float sample_speed_sq(self, np.random.Generator rng)
float _estimate_pdf_upper_bound(self, int probe_points)