bi-kappa 3.0.0
Monte Carlo particle samplers for plasma velocity and position distributions
Loading...
Searching...
No Matches
bikappa_validate.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Distributional validation of a bi-Kappa velocity sample.
3
4This module tests a *sample*, not a sampler. Nothing in it assumes the
5Gamma-ratio construction, so it applies to velocities produced by any bi-Kappa
6loader -- inverse transform, acceptance-rejection, or scale mixture.
7
8Input contract
9--------------
10``v`` (N, 3) array of velocities, in the simulation's global frame,
11 with N >= MIN_SAMPLES (1000).
12``kappa`` shape index, > 1/2.
13``theta_perp`` perpendicular thermal speed, > 0, in the units of ``v``.
14``theta_par`` parallel thermal speed, > 0, in the units of ``v``.
15``bhat`` magnetic-field direction, or ``None`` if the sample is already
16 field-aligned (i.e. the third column is the parallel one).
17``n_attempts`` total draws attempted, if the loader enforced a velocity bound
18 by discarding and redrawing. Supplying it lets the report
19 quote the rejected fraction, which for a hard bound equals the
20 total-variation distance from the uncapped distribution.
21``alpha`` family-wise significance level, 0 < alpha < 1.
22
23The thermal speeds follow the convention of Eq. (2) of the accompanying paper,
24
25 f(v) ~ [1 + v_perp^2/(kappa theta_perp^2) + v_par^2/(kappa theta_par^2)]^-(kappa+1),
26
27normalizable for every kappa > 1/2. A thermal speed is a speed, not a
28temperature. A temperature-linked convention such as
29theta^2 = 2[(kappa-3/2)/kappa](k_B T/m) is defined only for kappa > 3/2 and is
30*not* interchangeable with this one; convert before calling.
31
32The target is the uncapped distribution above. A sample from a loader that
33rejects draws outside a velocity bound follows a different, capped distribution;
34the tests then measure the effect of the bound.
35
36What the tests establish, and what they do not
37----------------------------------------------
38The cell-count test of the accompanying paper (Sec. VI B) and the radial,
39directional and independence tests below together pin down the
40three-dimensional distribution, because a spherically symmetric density is
41determined by its radial distribution plus a uniform, radius-independent
42direction. They are distribution-free and use no moments, so they remain valid
43on 1/2 < kappa <= 3/2 where the second moment does not exist. A pass is
44evidence that the sample is consistent with the target at the given size; it is
45not a proof of correctness, and it says nothing about a bound the loader may
46have applied -- for that, supply ``n_attempts`` and read the tail quantiles.
47
48Verdicts
49--------
50The nine distributional tests (seven when the sample is too small for the
51cell-count test) form one family. Each has a p-value, and the family is
52corrected with the Holm-Bonferroni step-down procedure: a test fails when its
53Holm-adjusted p-value is at most ``alpha``, which keeps the probability that a
54correct sample fails any of them at or below ``alpha`` (to the accuracy of the
55asymptotic p-values). Two further tests have
56their own criteria: the anisotropy ratio fails when it is more than four
57standard errors from its expected value, and the finiteness test fails on any
58non-finite draw. The tail quantiles and the largest normalized speeds are
59diagnostics and carry no verdict.
60
61Usage
62-----
63 from bikappa_validate import validate_sample, format_report
64 report = validate_sample(v, kappa=2.0, theta_perp=1.0, theta_par=2.0)
65 print(format_report(report))
66
67or from the command line (``--help`` lists the options and input formats):
68
69 python bikappa_validate.py sample.npy --kappa 2 --theta-perp 1 --theta-par 2
70
71Exit status is 0 if every test passes, 1 if at least one test fails, and 2 if
72the input or the options are invalid.
73"""
74
75from __future__ import annotations
76
77import argparse
78import json
79import math
80import os
81import sys
82import warnings
83
84import numpy as np
85from scipy import special, stats
86
87__all__ = ["validate_sample", "format_report", "load_sample", "field_basis",
88 "log_radius_quantile", "MIN_SAMPLES"]
89
90# Smallest sample the tests accept.
91MIN_SAMPLES = 1000
92
93# Quantile probes for the radial tail. The two extreme ones are where a radial
94# error shows up first and where Cartesian marginals are least sensitive.
95QUANTILE_PROBES = (0.5, 0.9, 0.99, 0.999)
96
97# Direction cells for the joint-direction and independence tests. The solid-angle
98# element is d(cos Theta) d(Phi), so equal intervals of cos(Theta) crossed with
99# equal intervals of Phi give cells of equal solid angle. Binning both angles is
100# what makes the independence test cover the whole direction: with cos(Theta)
101# alone, a dependence between radius and azimuth would pass unseen.
102N_RADIAL_BINS = 4
103N_COS_BINS = 5
104N_PHI_BINS = 8
105
106# The accompanying paper's test (Sec. VI B): Pearson's chi^2 over cells of equal
107# probability under the target -- N_SHELLS radius shells bounded by the exact
108# deciles of R, crossed with the equal-solid-angle direction cells above. Every
109# one of the N_SHELLS * 40 cells then has probability 1/400.
110N_SHELLS = 10
111MIN_EXPECTED_PER_CELL = 5.0
112
113# The test of the radius alone divides the outermost decile shell, R > r_9, further
114# at the radii that R exceeds with these probabilities (its 99th ... 99.999th
115# percentiles), so that the fastest 10% of draws are resolved in radius rather than
116# counted in one shell. An edge is used only if the shell beyond it expects at least
117# MIN_EXPECTED_PER_CELL draws; at the paper's 5 x 10^7 draws all four are used.
118TAIL_EXCEEDANCE = (1e-2, 1e-3, 1e-4, 1e-5)
119
120
121def log_radius_quantile(kappa: float, exceed) -> np.ndarray:
122 """log of the radius r with P(R > r) = exceed under the target, elementwise.
123
124 P(R > r) = P(W < w) with W = 1/(1+R^2) ~ Beta(kappa-1/2, 3/2), and R^2 = (1-w)/w.
125 Near kappa = 1/2 the edge w lies below the smallest double -- w ~ 10^-500 for
126 the 10^-5 edge at kappa = 0.51, and even the deciles underflow once
127 kappa - 1/2 < 3e-3 -- so Beta.ppf returns 0 there. For such w the leading term
128 of I_w(a, b) = w^a / (a B(a, b)) (1 + O(w)) is exact to double precision and
129 gives log w directly. Comparing log R with these edges then needs no bounded
130 transform of either, so nothing underflows however large R is.
131 """
132 a = kappa - 0.5
133 exceed = np.atleast_1d(np.asarray(exceed, dtype=float))
134 with np.errstate(divide="ignore"):
135 log_w = np.log(stats.beta.ppf(exceed, a, 1.5))
136 tiny = ~(log_w > math.log(1e-280))
137 log_w[tiny] = (np.log(exceed[tiny]) + math.log(a) + special.betaln(a, 1.5)) / a
138 return 0.5 * (np.log1p(-np.exp(log_w)) - log_w)
139
140
141def log_shell_edges(kappa: float) -> np.ndarray:
142 """log of the radii splitting R into N_SHELLS shells of equal probability."""
143 return log_radius_quantile(kappa, 1.0 - np.arange(1, N_SHELLS) / N_SHELLS)
144
145
146def radius_shells(kappa: float, n: int) -> tuple[np.ndarray, np.ndarray]:
147 """log edges and probabilities of the shells for the test of the radius alone.
148
149 The N_SHELLS decile shells, with the outermost divided at those TAIL_EXCEEDANCE
150 edges beyond which n draws expect at least MIN_EXPECTED_PER_CELL.
151 """
152 tail = [t for t in TAIL_EXCEEDANCE if n * t >= MIN_EXPECTED_PER_CELL]
153 edges = np.concatenate([log_shell_edges(kappa), log_radius_quantile(kappa, tail)])
154 exceed = np.concatenate([1.0 - np.arange(N_SHELLS) / N_SHELLS, tail, [0.0]])
155 return edges, exceed[:-1] - exceed[1:]
156
157
158# ----------------------------------------------------------------------------
159# frame handling
160# ----------------------------------------------------------------------------
161
162def field_basis(bhat: np.ndarray) -> np.ndarray:
163 """Orthonormal basis (e1, e2, e3) with e3 = bhat, as columns.
164
165 Built the same way as the released C++ loader: start from (1,1,1), replace
166 the component of largest |b_k| so the result is orthogonal to bhat. Picking
167 the largest component keeps the division safe -- for a unit vector
168 |b_k| >= 1/sqrt(3) -- including the axis-aligned cases.
169
170 Any orthonormal basis with e3 = bhat serves for the tests below, since they
171 depend on the perpendicular directions only through rotationally invariant
172 statistics.
173 """
174 b = np.asarray(bhat, dtype=float)
175 norm = np.linalg.norm(b)
176 if not np.isfinite(norm) or norm == 0.0:
177 raise ValueError("bhat must be a nonzero finite vector")
178 e3 = b / norm
179
180 e2 = np.ones(3)
181 k = int(np.argmax(np.abs(e3)))
182 e2[k] = 1.0 - e3.sum() / e3[k]
183 e2 /= np.linalg.norm(e2)
184
185 e1 = np.cross(e2, e3)
186 return np.column_stack([e1, e2, e3])
187
188
189# ----------------------------------------------------------------------------
190# the tests
191# ----------------------------------------------------------------------------
192
193def mad_relative_sigma(kappa: float, n: int) -> float:
194 """Asymptotic relative standard error of a sample MAD, per component.
195
196 Each Cartesian marginal of Eq. (2) is a scaled Student-t distribution with
197 nu = 2 kappa - 1 degrees of freedom, so in units of its own scale the MAD is
198 t0 = ppf(3/4, nu). For a symmetric distribution the MAD is the median of |X|, whose
199 density at t0 is 2 f(t0), giving
200
201 sqrt(n) (MAD_n - t0) -> N(0, 1 / (16 f(t0)^2)).
202
203 The relative error therefore scales as 1/(4 sqrt(n) t0 f(t0)), which blows up
204 as kappa -> 1/2 because the marginal flattens: a fixed percentage tolerance
205 would be far too tight there and far too loose at large kappa.
206 """
207 nu = 2.0 * kappa - 1.0
208 t0 = float(stats.t.ppf(0.75, nu))
209 f0 = float(stats.t.pdf(t0, nu))
210 return 1.0 / (4.0 * math.sqrt(n) * t0 * f0)
211
212
213def _holm_adjusted(pvalues: dict) -> dict:
214 """Holm-Bonferroni adjusted p-values over a family of p-values.
215
216 With the m p-values sorted as p_(1) <= ... <= p_(m), the adjusted value of
217 p_(i) is max_{j <= i} min(1, (m - j + 1) p_(j)). Rejecting every test whose
218 adjusted p-value is at most alpha is the Holm step-down procedure at
219 family-wise level alpha.
220 """
221 items = sorted(pvalues.items(), key=lambda kv: kv[1])
222 m = len(items)
223 adjusted, running = {}, 0.0
224 for i, (name, p) in enumerate(items):
225 running = max(running, min(1.0, (m - i) * p))
226 adjusted[name] = running
227 return adjusted
228
229
230def _finite_number(name: str, x) -> float:
231 try:
232 x = float(x)
233 except (TypeError, ValueError):
234 raise ValueError(f"{name} must be a number; got {x!r}") from None
235 if not math.isfinite(x):
236 raise ValueError(f"{name} must be finite; got {x}")
237 return x
238
239
241 kappa: float,
242 theta_perp: float,
243 theta_par: float,
244 bhat=None,
245 n_attempts: int | None = None,
246 alpha: float = 0.01) -> dict:
247 """Run the tests on an (N, 3) velocity sample. See the module docstring.
248
249 Returns a nested dict of per-test statistics and verdicts, plus a top-level
250 ``passed`` flag. Raises ``ValueError`` on a malformed input contract.
251 """
252 v = np.asarray(v, dtype=float)
253 if v.ndim != 2 or v.shape[1] != 3:
254 raise ValueError(f"the sample must have shape (N, 3); got {v.shape}")
255 kappa = _finite_number("kappa", kappa)
256 if not kappa > 0.5:
257 raise ValueError(f"kappa must exceed 1/2; got {kappa}")
258 theta_perp = _finite_number("theta_perp", theta_perp)
259 theta_par = _finite_number("theta_par", theta_par)
260 if not (theta_perp > 0.0 and theta_par > 0.0):
261 raise ValueError(f"the thermal speeds must be positive; got theta_perp = "
262 f"{theta_perp}, theta_par = {theta_par}")
263 alpha = _finite_number("alpha", alpha)
264 if not 0.0 < alpha < 1.0:
265 raise ValueError(f"alpha must lie strictly between 0 and 1; got {alpha}")
266 if bhat is not None:
267 bhat = np.asarray(bhat, dtype=float)
268 if bhat.shape != (3,):
269 raise ValueError(f"bhat must have three components; got shape {bhat.shape}")
270 field_basis(bhat) # raises on a zero or non-finite vector
271
272 n_total = v.shape[0]
273 if n_total < MIN_SAMPLES:
274 raise ValueError(f"the tests need at least {MIN_SAMPLES} draws; got {n_total}")
275 if n_attempts is not None:
276 if isinstance(n_attempts, bool) or int(n_attempts) != n_attempts:
277 raise ValueError(f"n_attempts must be an integer; got {n_attempts!r}")
278 n_attempts = int(n_attempts)
279 if n_attempts < n_total:
280 raise ValueError(f"the number of attempts ({n_attempts}) cannot be smaller "
281 f"than the number of draws in the sample ({n_total})")
282
283 report: dict = {
284 "inputs": {
285 "n_samples": n_total,
286 "kappa": float(kappa),
287 "theta_perp": float(theta_perp),
288 "theta_par": float(theta_par),
289 "bhat": None if bhat is None else [float(x) for x in np.asarray(bhat, float)],
290 "n_attempts": None if n_attempts is None else int(n_attempts),
291 "alpha": float(alpha),
292 },
293 "tests": {},
294 "notes": [],
295 }
296
297 # --- rotate into the field-aligned frame -------------------------------
298 if bhat is None:
299 local = v
300 report["inputs"]["frame"] = "assumed field-aligned (third column parallel)"
301 else:
302 M = field_basis(bhat)
303 local = v @ M # local = M^T v
304 report["inputs"]["frame"] = "rotated into the field-aligned frame using bhat"
305 report["tests"]["frame_basis"] = {
306 "orthonormality_error": float(np.abs(M.T @ M - np.eye(3)).max()),
307 "description": "max |M^T M - I| for the reconstructed basis",
308 }
309
310 # --- normalized coordinates: the isotropic core ------------------------
311 scales = math.sqrt(kappa) * np.array([theta_perp, theta_perp, theta_par])
312 u = local / scales
313
314 # Never form T = R^2: it overflows for R > 1.3e154 while R itself is
315 # representable, which would silently drop exactly the heavy-tail draws the
316 # radial test exists to examine. np.linalg.norm squares internally; hypot
317 # does not.
318 R = np.hypot(np.hypot(u[:, 0], u[:, 1]), u[:, 2])
319 finite = np.isfinite(R) & np.isfinite(local).all(axis=1)
320 n_nonfinite = int((~finite).sum())
321 u, R, local_f = u[finite], R[finite], local[finite]
322 n = int(R.size)
323 if n == 0:
324 raise ValueError("every draw is non-finite; nothing to test")
325
326 report["tests"]["finiteness"] = {
327 "n_nonfinite": n_nonfinite,
328 "fraction": n_nonfinite / n_total,
329 "passed": n_nonfinite == 0,
330 "description": "non-finite draws, which indicate the loader's precision limit rather than a distributional error",
331 }
332
333 b = kappa - 0.5
334 pvalues: dict = {}
335
336 # --- 1. radial law -----------------------------------------------------
337 # W = 1/(1+T) ~ Beta(kappa-1/2, 3/2), formed without materializing T. The
338 # complementary variable Y = T/(1+T) carries identical information in exact
339 # arithmetic but piles its mass against 1.0, where doubles have no relative
340 # resolution left; at kappa = 0.55 that alone makes a KS test fail on a
341 # perfectly good sample. The orientation is not cosmetic.
342 #
343 # For R > 1 the form (1/R)^2 / (1 + (1/R)^2) keeps W resolvable down to the
344 # subnormal range, R up to about 6e161, whereas 1/(1 + R^2) or
345 # 1/(1 + exp(2 log R)) returns W = 0 already for R > 1.3e154.
346 with np.errstate(over="ignore", divide="ignore", under="ignore"):
347 small = R <= 1.0
348 W = np.empty_like(R)
349 W[small] = 1.0 / (1.0 + R[small] ** 2)
350 inv2 = (1.0 / R[~small]) ** 2
351 W[~small] = inv2 / (1.0 + inv2)
352
353 # The radial tests run on the probability integral transform F_W(W), which
354 # is U(0,1) under the target. Where W underflows to 0 its CDF is still
355 # resolvable: for W -> 0, F_W(W) = W^b / (b B(b, 3/2)) (1 + O(W)), and
356 # log W = -2 log R to within a relative 1/R^2. Near kappa = 1/2 these draws
357 # carry a measurable share of the probability (about 6e-4 at kappa = 0.51),
358 # so mapping them all to F = 0 displaces them and fails an exact sample of a
359 # few million draws.
360 with np.errstate(divide="ignore"):
361 U = stats.beta.cdf(W, b, 1.5)
362 under = W <= 0.0
363 U[under] = np.exp(-2.0 * b * np.log(R[under])
364 - np.log(b) - special.betaln(b, 1.5))
365 n_w_underflow = int(under.sum())
366
367 ks_radial = stats.kstest(U, "uniform")
368 cvm_radial = stats.cramervonmises(U, "uniform")
369 pvalues["radial_ks"] = float(ks_radial.pvalue)
370 pvalues["radial_cvm"] = float(cvm_radial.pvalue)
371 report["tests"]["radial_law"] = {
372 "statistic_sqrtn_D": float(ks_radial.statistic * math.sqrt(n)),
373 "ks_pvalue": float(ks_radial.pvalue),
374 "cvm_statistic": float(cvm_radial.statistic),
375 "cvm_pvalue": float(cvm_radial.pvalue),
376 "n_w_underflow": n_w_underflow,
377 "description": ("scaled radius R = |v| in normalized coordinates against "
378 "T = R^2 ~ BetaPrime(3/2, kappa-1/2), tested through the "
379 "CDF of W = 1/(1+T) ~ Beta(kappa-1/2, 3/2); draws whose W "
380 "underflows use the small-W expansion of that CDF"),
381 }
382
383 # --- 2. directional uniformity ----------------------------------------
384 cos_theta = u[:, 2] / R
385 phi = np.arctan2(u[:, 1], u[:, 0])
386 ks_cos = stats.kstest(cos_theta, "uniform", args=(-1.0, 2.0))
387 ks_phi = stats.kstest(phi, "uniform", args=(-np.pi, 2.0 * np.pi))
388
389 # Equal-solid-angle direction cells, shared with the independence test.
390 r_edges = np.quantile(R, np.linspace(0.0, 1.0, N_RADIAL_BINS + 1))
391 r_bin = np.clip(np.searchsorted(r_edges[1:-1], R, side="right"), 0, N_RADIAL_BINS - 1)
392 c_bin = np.clip(np.floor((cos_theta + 1.0) / 2.0 * N_COS_BINS).astype(int),
393 0, N_COS_BINS - 1)
394 p_bin = np.clip(np.floor((phi + np.pi) / (2.0 * np.pi) * N_PHI_BINS).astype(int),
395 0, N_PHI_BINS - 1)
396 table = np.zeros((N_RADIAL_BINS, N_COS_BINS * N_PHI_BINS))
397 np.add.at(table, (r_bin, c_bin * N_PHI_BINS + p_bin), 1.0)
398 # The two KS tests check each angle on its own; uniform marginals make the
399 # direction uniform on the sphere only if the angles are also independent.
400 # Equal occupancy of the cells, summed over radius, tests the joint distribution.
401 cells = stats.chisquare(table.sum(axis=0))
402
403 # The paper's cell-count test: radius shells x direction cells, and the radius
404 # alone on the decile shells with the outermost divided into the tail. Skipped,
405 # with a note, when a cell would expect fewer than MIN_EXPECTED_PER_CELL draws,
406 # where the chi^2 approximation is poor. Non-finite draws were removed above
407 # and are reported by the finiteness test: a validator cannot tell a component
408 # that overflowed at the end of the calculation from one that went infinite
409 # through an intermediate underflow, so it does not assign them a radius.
410 n_cells = N_SHELLS * N_COS_BINS * N_PHI_BINS
411 if n / n_cells >= MIN_EXPECTED_PER_CELL:
412 with np.errstate(divide="ignore"):
413 log_R = np.log(R)
414 shell = np.searchsorted(log_shell_edges(kappa), log_R, side="right")
415 cell_counts = np.zeros((N_SHELLS, N_COS_BINS * N_PHI_BINS))
416 np.add.at(cell_counts, (shell, c_bin * N_PHI_BINS + p_bin), 1.0)
417 cells_all = stats.chisquare(cell_counts.ravel())
418 r_log_edges, r_probs = radius_shells(kappa, n)
419 r_counts = np.bincount(np.searchsorted(r_log_edges, log_R, side="right"),
420 minlength=r_probs.size)
421 cells_radius = stats.chisquare(r_counts, n * r_probs)
422 # Pearson's chi^2 against fully specified cell probabilities: k - 1 dof.
423 pvalues["cells_radius"] = float(cells_radius.pvalue)
424 pvalues["cells_all"] = float(cells_all.pvalue)
425 report["tests"]["cells"] = {
426 "radius_pvalue": float(cells_radius.pvalue),
427 "radius_statistic": float(cells_radius.statistic),
428 "radius_dof": int(r_probs.size - 1),
429 "radius_shells": int(r_probs.size),
430 "radius_outermost_percentile": float(100.0 * (1.0 - r_probs[-1])),
431 "radius_expected_outermost": float(n * r_probs[-1]),
432 "all_pvalue": float(cells_all.pvalue),
433 "all_statistic": float(cells_all.statistic),
434 "all_dof": int(n_cells - 1),
435 "expected_per_cell": n / n_cells,
436 "min_count": int(cell_counts.min()),
437 "description": (f"Pearson chi^2 against equal occupancy of {N_SHELLS} "
438 "equal-probability radius shells x "
439 f"{N_COS_BINS * N_PHI_BINS} equal-solid-angle direction "
440 "cells; 'radius' uses the radius shells alone, the "
441 "outermost divided at the 99th to 99.999th percentiles "
442 "of R as far as the sample size allows"),
443 }
444 else:
445 report["notes"].append(
446 f"cell-count test skipped: {n} draws give fewer than "
447 f"{MIN_EXPECTED_PER_CELL:g} expected per cell over {n_cells} cells")
448
449 pvalues["cos_theta"] = float(ks_cos.pvalue)
450 pvalues["phi"] = float(ks_phi.pvalue)
451 pvalues["direction_cells"] = float(cells.pvalue)
452 report["tests"]["direction"] = {
453 "cos_theta_sqrtn_D": float(ks_cos.statistic * math.sqrt(n)),
454 "cos_theta_pvalue": float(ks_cos.pvalue),
455 "phi_sqrtn_D": float(ks_phi.statistic * math.sqrt(n)),
456 "phi_pvalue": float(ks_phi.pvalue),
457 "cells_chi2_statistic": float(cells.statistic),
458 "cells_chi2_dof": int(N_COS_BINS * N_PHI_BINS - 1),
459 "cells_chi2_pvalue": float(cells.pvalue),
460 "description": ("cos(Theta) ~ U(-1,1) and Phi ~ U(-pi,pi) about bhat, and "
461 f"equal occupancy of {N_COS_BINS * N_PHI_BINS} equal-solid-angle "
462 f"cells ({N_COS_BINS} cos(Theta) x {N_PHI_BINS} Phi intervals)"),
463 }
464
465 # --- 3. radius-direction independence ----------------------------------
466 # A direction cell that no draw reaches has no expected count and would stop
467 # chi2_contingency; drop it here. An empty cell already fails the
468 # equal-occupancy test above, so nothing is hidden.
469 occupied = table.sum(axis=0) > 0
470 chi2 = stats.chi2_contingency(table[:, occupied])
471 inner = cos_theta[R <= r_edges[1]]
472 outer = cos_theta[R > r_edges[-2]]
473 ks_io = stats.ks_2samp(inner, outer)
474 pvalues["independence_chi2"] = float(chi2.pvalue)
475 pvalues["independence_inner_outer"] = float(ks_io.pvalue)
476 report["tests"]["independence"] = {
477 "chi2_statistic": float(chi2.statistic),
478 "chi2_pvalue": float(chi2.pvalue),
479 "chi2_dof": int(chi2.dof),
480 "min_cell_count": int(table.min()),
481 "inner_outer_ks_D": float(ks_io.statistic),
482 "inner_outer_ks_pvalue": float(ks_io.pvalue),
483 "description": ("chi^2 contingency over radial quartiles x the equal-solid-"
484 "angle direction cells, plus a two-sample KS of cos(Theta) "
485 "between the innermost and outermost radial quartiles"),
486 }
487
488 # --- 4. moment-free anisotropy ratio -----------------------------------
489 # MAD needs no moments, so this is the anisotropy check that survives
490 # 1/2 < kappa <= 3/2 where the variance does not exist.
491 mad = stats.median_abs_deviation(local_f, axis=0)
492 ratio = float(mad[2] / mad[0])
493 expected = float(theta_par / theta_perp)
494 perp_ratio = float(mad[1] / mad[0])
495 # A ratio of two MADs, each carrying the relative error above; the tolerance
496 # is four of those combined standard errors, chosen so that this test does
497 # not dominate the false-alarm rate of the family it sits in. The sqrt(2)
498 # treats the two MADs as independent, which they are not: both are driven by
499 # the same radial variate, and the correlation grows as the tail heavies.
500 # The tolerance is therefore conservative, and increasingly so as
501 # kappa -> 1/2 -- at kappa = 0.55 it is about twice the spread actually
502 # observed over replicates, and at kappa = 0.51 about ten times it. This
503 # test will not raise a false alarm at small kappa; it will also not catch
504 # much there.
505 sigma = math.sqrt(2.0) * mad_relative_sigma(kappa, n)
506 tol = 4.0 * sigma
507 report["tests"]["anisotropy"] = {
508 "mad_ratio_par_perp": ratio,
509 "expected": expected,
510 "relative_error": ratio / expected - 1.0,
511 "mad_ratio_perp_perp": perp_ratio,
512 "relative_sigma": sigma,
513 "tolerance": tol,
514 "passed": bool(abs(ratio / expected - 1.0) <= tol and abs(perp_ratio - 1.0) <= tol),
515 "description": ("MAD(v_par)/MAD(v_x) against theta_par/theta_perp, and "
516 "MAD(v_y)/MAD(v_x) against 1; the tolerance is four "
517 "asymptotic standard errors and widens as kappa -> 1/2"),
518 }
519
520 # --- 5. tail quantiles --------------------------------------------------
521 # Compared in log R: with kappa - 1/2 < 1 the upper quantiles span hundreds
522 # of decades, so a relative error on R is dominated by tail sampling noise.
523 with np.errstate(divide="ignore"):
524 theory = 0.5 * np.log(stats.betaprime.ppf(QUANTILE_PROBES, 1.5, b))
525 empirical = np.log(np.quantile(R, QUANTILE_PROBES))
526 log_err = np.where(np.isfinite(theory), empirical - theory, np.nan)
527 report["tests"]["tail_quantiles"] = {
528 "probes": list(QUANTILE_PROBES),
529 "log_error": [float(x) for x in log_err],
530 "ratio": [float(math.exp(x)) if np.isfinite(x) else None for x in log_err],
531 "description": ("diagnostic without a verdict: empirical minus exact "
532 "quantiles of log R; ratio is the empirical quantile of R "
533 "divided by the exact one, so 1 means an undistorted tail"),
534 }
535
536 # --- 6. an applied velocity bound ---------------------------------------
537 max_component = float(np.abs(u).max() * math.sqrt(kappa))
538 max_speed_norm = float((R * math.sqrt(kappa)).max())
539 bound: dict = {
540 "max_normalized_component": max_component,
541 "max_normalized_radius": max_speed_norm,
542 "description": ("diagnostic without a verdict: largest |v_i|/theta_i and "
543 "largest sqrt(sum (v_i/theta_i)^2) in the sample; a bound "
544 "applied by the loader shows up as a hard edge in whichever "
545 "of these the bounding region uses"),
546 }
547 if n_attempts is not None:
548 rejected = 1.0 - n_total / n_attempts
549 bound["rejected_fraction"] = rejected
550 bound["total_variation_from_unbounded"] = rejected
551 bound["note"] = ("for a bound enforced by discarding and redrawing, the rejected "
552 "fraction equals the total-variation distance from the uncapped "
553 "bi-Kappa distribution exactly; it bounds how far any probability "
554 "can move and does not bound a tail quantile")
555 report["notes"].append(
556 "A bound was declared. The tests compare the sample with the uncapped "
557 "distribution, so the radial tests and the tail quantiles show the effect "
558 "of the bound; a failure there measures the bound, not a defect of the "
559 "loader.")
560 report["tests"]["bound"] = bound
561
562 # --- overall verdict ----------------------------------------------------
563 adjusted = _holm_adjusted(pvalues)
564 family_tests = {
565 name: {"pvalue": p,
566 "holm_adjusted_pvalue": adjusted[name],
567 "rejected_at_alpha": bool(adjusted[name] <= alpha)}
568 for name, p in pvalues.items()
569 }
570 report["family"] = {
571 "alpha": alpha,
572 "correction": ("Holm-Bonferroni over the distributional tests; a test is "
573 "rejected when its Holm-adjusted p-value is at most alpha"),
574 "n_tests": len(family_tests),
575 "tests": family_tests,
576 "n_rejected": int(sum(d["rejected_at_alpha"] for d in family_tests.values())),
577 }
578 report["passed"] = bool(
579 report["family"]["n_rejected"] == 0
580 and report["tests"]["anisotropy"]["passed"]
581 and report["tests"]["finiteness"]["passed"]
582 )
583 return report
584
585
586# ----------------------------------------------------------------------------
587# reporting and I/O
588# ----------------------------------------------------------------------------
589
590def format_report(report: dict) -> str:
591 """Render a report as a short human-readable table.
592
593 The distributional tests are listed with their statistic, raw p-value and
594 Holm-adjusted p-value; each verdict is FAIL exactly when the adjusted
595 p-value is at most alpha. The tests with their own criteria and the
596 diagnostics without a verdict follow.
597 """
598 i = report["inputs"]
599 t = report["tests"]
600 fam = report["family"]
601 alpha = fam["alpha"]
602 out = [
603 "bi-Kappa sample validation",
604 f" N = {i['n_samples']}, kappa = {i['kappa']:g}, "
605 f"theta_perp = {i['theta_perp']:g}, theta_par = {i['theta_par']:g}",
606 f" frame: {i['frame']}",
607 "",
608 f" Distributional tests: {fam['n_tests']} tests, Holm-Bonferroni correction at "
609 f"family-wise alpha = {alpha:g}.",
610 " A test fails when its Holm-adjusted p-value is at most alpha.",
611 "",
612 f" {'test':36s} {'statistic':>22s} {'p-value':>9s} {'Holm p':>9s} verdict",
613 " " + "-" * 88,
614 ]
615
616 def pfmt(p):
617 return f"{p:.3f}" if p >= 1e-3 else f"{p:.1e}"
618
619 def row(name, key, stat):
620 d = fam["tests"][key]
621 out.append(f" {name:36s} {stat:>22s} {pfmt(d['pvalue']):>9s} "
622 f"{pfmt(d['holm_adjusted_pvalue']):>9s} "
623 f"{'FAIL' if d['rejected_at_alpha'] else 'PASS'}")
624
625 if "cells" in t:
626 c = t["cells"]
627 row(f"cell counts: radius, {c['radius_shells']} shells", "cells_radius",
628 f"chi2 = {c['radius_statistic']:.1f} ({c['radius_dof']} dof)")
629 row("cell counts: radius x direction", "cells_all",
630 f"chi2 = {c['all_statistic']:.1f} ({c['all_dof']} dof)")
631 rl = t["radial_law"]
632 row("radius, Kolmogorov-Smirnov", "radial_ks",
633 f"sqrt(n) D = {rl['statistic_sqrtn_D']:.3f}")
634 row("radius, Cramer-von Mises", "radial_cvm", f"T = {rl['cvm_statistic']:.4f}")
635 d = t["direction"]
636 row("direction: cos(Theta), KS", "cos_theta", f"sqrt(n) D = {d['cos_theta_sqrtn_D']:.3f}")
637 row("direction: Phi, KS", "phi", f"sqrt(n) D = {d['phi_sqrtn_D']:.3f}")
638 row("direction: equal-solid-angle cells", "direction_cells",
639 f"chi2 = {d['cells_chi2_statistic']:.1f} ({d['cells_chi2_dof']} dof)")
640 ind = t["independence"]
641 row("radius-direction independence", "independence_chi2",
642 f"chi2 = {ind['chi2_statistic']:.1f} ({ind['chi2_dof']} dof)")
643 row("cos(Theta), inner vs outer quartile", "independence_inner_outer",
644 f"D = {ind['inner_outer_ks_D']:.4f}")
645
646 an, fin = t["anisotropy"], t["finiteness"]
647 out += [
648 "",
649 " Tests with their own criteria:",
650 f" {'anisotropy':36s} {'':>42s} {'PASS' if an['passed'] else 'FAIL'}",
651 f" MAD(v_par)/MAD(v_perp1) = {an['mad_ratio_par_perp']:.4f}, expected "
652 f"{an['expected']:.4f} (error {100 * an['relative_error']:+.2f}%)",
653 f" MAD(v_perp2)/MAD(v_perp1) = {an['mad_ratio_perp_perp']:.4f}, expected 1",
654 f" each must lie within {100 * an['tolerance']:.2f}% of its expected value "
655 "(four standard errors)",
656 f" {'finite draws':36s} {'':>42s} {'PASS' if fin['passed'] else 'FAIL'}",
657 f" {fin['n_nonfinite']} of {i['n_samples']} draws are non-finite; any is a failure",
658 "",
659 " Diagnostics without a verdict:",
660 " tail quantiles of the radius, empirical / exact:",
661 ]
662 for p, r in zip(t["tail_quantiles"]["probes"], t["tail_quantiles"]["ratio"]):
663 out.append(f" p = {p:<6} {r:.4f}" if r is not None else f" p = {p:<6} n/a")
664 bd = t["bound"]
665 out.append(f" largest |v_i|/theta_i: {bd['max_normalized_component']:.4g}; "
666 f"largest normalized speed: {bd['max_normalized_radius']:.4g}")
667 if "frame_basis" in t:
668 out.append(f" basis orthonormality error: {t['frame_basis']['orthonormality_error']:.2e}")
669 if "rejected_fraction" in bd:
670 out.append(f" declared bound: rejected fraction {bd['rejected_fraction']:.3e}, "
671 "which is the total-variation distance from the uncapped distribution")
672 out.append("")
673 for note in report["notes"]:
674 out.append(f" note: {note}")
675 out.append(f" overall: {'PASS' if report['passed'] else 'FAIL'}")
676 return "\n".join(out)
677
678
679RAW_EXTENSIONS = (".bin", ".f64")
680
681
682def _read_text(path: str, delimiter) -> tuple[np.ndarray, str | None]:
683 """Read a text table, skipping one non-numeric header line if there is one.
684
685 Blank lines and lines starting with '#' are ignored. If the first other line
686 does not parse as numbers it is taken as a column header and skipped; any
687 later non-numeric line is an error.
688 """
689 header, skip = None, 0
690 with open(path, "r") as fh:
691 for lineno, raw in enumerate(fh, start=1):
692 line = raw.strip()
693 if not line or line.startswith("#"):
694 continue
695 try:
696 [float(tok) for tok in line.split(delimiter)]
697 except ValueError:
698 header, skip = line, lineno
699 break
700 with warnings.catch_warnings():
701 warnings.simplefilter("ignore", UserWarning) # "input contained no data"
702 try:
703 v = np.loadtxt(path, delimiter=delimiter, skiprows=skip, ndmin=2)
704 except ValueError as exc:
705 # NumPy's message may end with advice on its own keyword arguments.
706 raise ValueError(f"{path}: {str(exc).split('; use')[0]}") from None
707 return v, header
708
709
710def _load(path: str, binary: bool) -> tuple[np.ndarray, str | None]:
711 ext = os.path.splitext(path)[1].lower()
712 header = None
713 if binary or ext in RAW_EXTENSIONS:
714 v = np.fromfile(path, dtype=np.float64)
715 if v.size % 3:
716 raise ValueError(f"{path}: raw float64 input holds {v.size} values, "
717 "which is not a multiple of 3")
718 v = v.reshape(-1, 3)
719 elif ext == ".npy":
720 v = np.load(path, allow_pickle=False)
721 else:
722 v, header = _read_text(path, "," if ext == ".csv" else None)
723 v = np.asarray(v, dtype=float)
724 if v.size == 0:
725 raise ValueError(f"{path}: the file holds no data")
726 if v.ndim != 2 or v.shape[1] != 3:
727 raise ValueError(f"{path}: expected three columns (vx vy vz), got an array "
728 f"of shape {v.shape}")
729 return v, header
730
731
732def load_sample(path: str, binary: bool = False) -> np.ndarray:
733 """Read an (N, 3) velocity sample from a file.
734
735 The format follows the extension: ``.bin`` and ``.f64`` are raw float64
736 values in the machine's byte order, three per draw (``binary=True`` forces this for any
737 extension); ``.npy`` is a NumPy array of shape (N, 3); anything else is text
738 with three columns, separated by whitespace, or by commas for ``.csv``. In
739 text, blank lines and lines starting with '#' are ignored, and a first line
740 that is not numeric (a header such as ``vx vy vz``) is skipped.
741
742 Raises ``ValueError`` if the file does not hold an (N, 3) array of numbers,
743 and ``OSError`` if it cannot be read.
744 """
745 return _load(path, binary)[0]
746
747
748EPILOG = """\
749input formats:
750 .bin, .f64 raw float64 values, three per draw (vx vy vz); --binary forces
751 this for any extension
752 .npy NumPy array of shape (N, 3)
753 other text, three columns per line, separated by whitespace (by
754 commas for .csv); blank lines and lines starting with '#' are
755 ignored, and a non-numeric first line such as 'vx vy vz' is
756 skipped as a header
757
758The target is the uncapped bi-Kappa distribution of Eq. (2) of the paper,
759 f(v) ~ [1 + v_perp^2/(kappa theta_perp^2) + v_par^2/(kappa theta_par^2)]^-(kappa+1).
760A sample from a sampler that rejects draws outside a velocity bound follows a
761different, capped distribution; pass --attempts to have the rejected fraction
762reported.
763
764The distributional tests are corrected for multiple testing with the
765Holm-Bonferroni procedure at family-wise level --alpha: a test fails when its
766Holm-adjusted p-value is at most alpha. The anisotropy test fails beyond four
767standard errors, and any non-finite draw is a failure. Tail quantiles are
768reported without a verdict.
769
770exit status:
771 0 every test passes
772 1 at least one test fails
773 2 invalid input or options (message on stderr)
774
775example:
776 python bikappa_validate.py samples_bikappa.txt --kappa 2 --theta-perp 1 --theta-par 2
777"""
778
779
780def _parser() -> argparse.ArgumentParser:
781 ap = argparse.ArgumentParser(
782 prog="bikappa_validate.py",
783 description=("Test an (N, 3) velocity sample from any bi-Kappa loader against\n"
784 f"the bi-Kappa distribution. N must be at least {MIN_SAMPLES}."),
785 epilog=EPILOG,
786 formatter_class=argparse.RawDescriptionHelpFormatter)
787 ap.add_argument("sample", help="file holding the sample; see 'input formats' below")
788 ap.add_argument("--kappa", type=float, required=True,
789 help="spectral index kappa of the target distribution, > 1/2")
790 ap.add_argument("--theta-perp", type=float, required=True, metavar="THETA",
791 help=("perpendicular thermal speed, > 0: a speed in the units of the "
792 "sample, not a temperature (the convention of Eq. (2) of the "
793 "paper and of the C++ class)"))
794 ap.add_argument("--theta-par", type=float, required=True, metavar="THETA",
795 help="parallel thermal speed, > 0, in the same convention and units")
796 ap.add_argument("--bhat", type=float, nargs=3, default=None, metavar=("BX", "BY", "BZ"),
797 help=("magnetic-field direction in the frame of the sample, need not "
798 "be normalized; omit if the third column is already the "
799 "parallel component"))
800 ap.add_argument("--attempts", type=int, default=None, metavar="N",
801 help=("total draws attempted, for a sampler that rejects draws "
802 "outside a velocity bound and redraws them; must be at least "
803 "the number of draws in the sample"))
804 ap.add_argument("--alpha", type=float, default=0.01,
805 help="family-wise significance level, 0 < alpha < 1 (default 0.01)")
806 ap.add_argument("--binary", action="store_true",
807 help="read the file as raw float64 whatever its extension")
808 ap.add_argument("--json", action="store_true", help="print the full report as JSON")
809 return ap
810
811
812def main(argv=None) -> int:
813 args = _parser().parse_args(argv)
814 prog = "bikappa_validate.py"
815 try:
816 v, header = _load(args.sample, args.binary)
817 if header is not None:
818 print(f"{prog}: note: skipped the header line {header!r}", file=sys.stderr)
819 report = validate_sample(v, args.kappa, args.theta_perp, args.theta_par,
820 bhat=args.bhat, n_attempts=args.attempts, alpha=args.alpha)
821 except (ValueError, OSError) as exc:
822 msg = " ".join(str(exc).split()) or type(exc).__name__
823 print(f"{prog}: error: {msg}", file=sys.stderr)
824 return 2
825 print(json.dumps(report, indent=2) if args.json else format_report(report))
826 return 0 if report["passed"] else 1
827
828
829if __name__ == "__main__":
830 sys.exit(main())
int main()
Definition main.cpp:15
dict validate_sample(v, float kappa, float theta_perp, float theta_par, bhat=None, int|None n_attempts=None, float alpha=0.01)
tuple[np.ndarray, str|None] _load(str path, bool binary)
np.ndarray log_shell_edges(float kappa)
dict _holm_adjusted(dict pvalues)
np.ndarray log_radius_quantile(float kappa, exceed)
np.ndarray field_basis(np.ndarray bhat)
str format_report(dict report)
float mad_relative_sigma(float kappa, int n)
argparse.ArgumentParser _parser()
np.ndarray load_sample(str path, bool binary=False)
float _finite_number(str name, x)
tuple[np.ndarray, str|None] _read_text(str path, delimiter)
tuple[np.ndarray, np.ndarray] radius_shells(float kappa, int n)