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.
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.
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}")
257 raise ValueError(f
"kappa must exceed 1/2; got {kappa}")
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}")
264 if not 0.0 < alpha < 1.0:
265 raise ValueError(f
"alpha must lie strictly between 0 and 1; got {alpha}")
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}")
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})")
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),
300 report[
"inputs"][
"frame"] =
"assumed field-aligned (third column parallel)"
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",
311 scales = math.sqrt(kappa) * np.array([theta_perp, theta_perp, theta_par])
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]
324 raise ValueError(
"every draw is non-finite; nothing to test")
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",
346 with np.errstate(over=
"ignore", divide=
"ignore", under=
"ignore"):
349 W[small] = 1.0 / (1.0 + R[small] ** 2)
350 inv2 = (1.0 / R[~small]) ** 2
351 W[~small] = inv2 / (1.0 + inv2)
360 with np.errstate(divide=
"ignore"):
361 U = stats.beta.cdf(W, b, 1.5)
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())
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"),
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))
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),
394 p_bin = np.clip(np.floor((phi + np.pi) / (2.0 * np.pi) * N_PHI_BINS).astype(int),
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)
401 cells = stats.chisquare(table.sum(axis=0))
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"):
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())
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)
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"),
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")
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)"),
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"),
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])
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,
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"),
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"),
537 max_component = float(np.abs(u).max() * math.sqrt(kappa))
538 max_speed_norm = float((R * math.sqrt(kappa)).max())
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"),
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 "
560 report[
"tests"][
"bound"] = bound
566 "holm_adjusted_pvalue": adjusted[name],
567 "rejected_at_alpha": bool(adjusted[name] <= alpha)}
568 for name, p
in pvalues.items()
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())),
578 report[
"passed"] = bool(
579 report[
"family"][
"n_rejected"] == 0
580 and report[
"tests"][
"anisotropy"][
"passed"]
581 and report[
"tests"][
"finiteness"][
"passed"]