selfreport.py
Checks: RULER: With σ known, no self-report read off D̂ is unbiased at every distance theorem; property; observation.
Cited on: RULER.
To run it: save selfreport.py, with audit.py beside it; needs numpy, scipy.
"""selfreport.py -- what a deletion auditor can say about the stability
of their own answer without the truth, and the proof that no such
statement is right at every size.
QUESTION. The mixture-proportion audit of audit.py returns an estimate
on one side of one half, and a second audit of the same world on fresh
samples may land on the other. audit.py proved the side to be the sign
of D-hat (G-hat - B-hat) off a zone and the ties, D-hat the scalar
D-hat = s_u^2 - s_in^2/2 - s_out^2/2 - dhat^2/4,
so two replicates off the box with their vertices on one side of it
(there the vertex's side is the sign of G-hat - B-hat: above the box
G-hat > 2 B-hat, below it G-hat < 0 < B-hat) land on opposite sides of
1/2 exactly when their D-hats differ in sign, a replicate with D-hat
zero, at an estimate of exactly 1/2, on neither.
That event needs no truth: both replicates share the one unknown
direction. An auditor holding D-hat and a truth-free estimate of its
spread can therefore STATE an instability, the chance a fresh audit
lands on the other side, of the form Phi(-|D-hat| / (zeta sd-hat)) for a
scale zeta, or the pair form 2 p-hat (1 - p-hat). How good is any such
self-report, and can one be right in the mean at every size?
THE WORLDS. audit.py's depth cells W2 = (12, 3), kappa = 1/5, and
W3 = (2, 8), kappa = 4/5, imported with their samplers, their exact
moments and its reading of a replicate, never copied. Population D:
7857/254800 at W2, 1/25 at W3.
THE ARGUMENT.
(A) THE PAIR RATE. Write nu = D/sigma, signed, sigma the spread of
D-hat (D > 0 at both cells). In the normal reading
D-hat ~ N(D, sigma^2) two independent replicates differ in sign
with probability
g(nu) = 2 Phi(nu) Phi(-nu) = (1 - erf(nu/sqrt 2)^2)/2,
even in nu, 1/2 at nu = 0.
(B) THE LAWS ARE CLOSED. A statement s(|D-hat|/sigma) has mean
E s(|nu + Z|), Z standard normal: its FOLDED law, even in nu;
take nu >= 0. Owen's function T(h, a) is the mass a standard
normal pair (X, Y) puts on X >= h, 0 <= Y <= a X: what lies
beyond a line at distance h from the origin, seen from the
origin between the line's foot and the point a h along it. Its
derivative in a is int_h^inf phi(x) phi(a x) x dx, so
T(h, a) = (1/(2 pi)) int_0^a exp(-h^2 (1 + x^2)/2)/(1 + x^2) dx,
and T(h, inf) = Phi(-h)/2. Take two unit forms S_1, S_2 of a
standard normal pair, of correlation rho. The wedge S_1 < -h,
S_2 < h lies beyond the line S_1 = -h and on the origin's side
of S_2 = h, both at distance h, and its apex sits h c from each
foot, c = sqrt((1 + rho)/(1 - rho)): the first line's foot lies
on the wedge's edge, the second's behind the apex. Seen from the
origin the wedge is what lies beyond the first line from the
apex on, T(h, c) + T(h, inf), less what lies beyond the second
from the apex on, T(h, inf) - T(h, c): it is 2 T(h, c).
For W standard normal and independent, Phi(-|y|/zeta) =
P(zeta W + y < 0, zeta W - y < 0); at y = nu + Z the two forms
have variance 1 + zeta^2 and covariance zeta^2 - 1, so c = zeta
and h = nu/sqrt(1 + zeta^2). The pair forms 2 Phi(k y) Phi(-k y)
are wedges too (W_1 - k y and W_2 + k y, correlation
-k^2/(1 + k^2)). So
PHI at zeta 2 T(nu/sqrt(1 + zeta^2), zeta)
PAIR 4 T(nu/sqrt 2, 1/sqrt 3)
SHARP 4 T(2 nu/sqrt 5, 1/3)
the truth g 4 T(nu, 1),
and PHI at zeta = 1 is Phi(nu/sqrt 2) Phi(-nu/sqrt 2) =
g(nu/sqrt 2)/2. For h >= 1, T(h, a) e^(h^2/2) h lies between
(Phi(b) - 1/2)/(2 sqrt(2 pi)), b = min(a, 1), and
1/(2 sqrt(2 pi)): above, 1/(1 + x^2) <= 1 and the Gaussian
integral over all x >= 0; below, 1/(1 + x^2) >= 1/2 on [0, b]
and int_0^b e^(-h^2 x^2/2) dx >= (1/h) int_0^b e^(-u^2/2) du.
Every arm's first argument is nu scaled by s < 1 (the pair form
sharpened k times: k/sqrt(1 + k^2)), so from s nu = 1 on its
ratio to g is at least a constant times e^((1 - s^2) nu^2/2):
the noise in D-hat flattens the exponent nu^2/2 to
nu^2/(2(1 + zeta^2)), to nu^2/4 and to 2 nu^2/5, and each arm's
ratio to g diverges, both tending to 0.
At nu = 0, T(0, a) = arctan(a)/(2 pi): the laws are 1/4,
arctan(sqrt 2)/pi, 1/3 and 1/2 - arcsin(4/5)/pi against g = 1/2.
(C) NO UNBIASED SELF-REPORT (theorem, in the normal model).
Put X = D-hat/sigma ~ N(nu, 1), sigma known, nu any real. No
function f with a mean at every nu has E_nu f(X) = g(nu) for
every nu.
Proof. phi(x - nu) = phi(x) exp(nu x - nu^2/2), and
int |f| phi(x) e^(a x) dx = e^(a^2/2) E_a|f| is finite at every
real a, so G(nu) = int f(x) phi(x - nu) dx is entire in nu, with
|G(i t)| <= E_0|f| e^(t^2/2). g is entire because erf is, and
g(i t) = (1 + erfi(t/sqrt 2)^2)/2.
For x >= 1, int_0^x e^(s^2) ds >= (1/x) e^((x - 1/x)^2) >=
e^(x^2 - 2)/x, so erfi(x) >= (2/sqrt pi) e^(x^2 - 2)/x and
g(i t) >= (4/pi) e^(t^2 - 4)/t^2 for t >= sqrt 2.
If G = g on the real line the two entire functions agree
everywhere, and (4/pi) e^(t^2 - 4)/t^2 <= E_0|f| e^(t^2/2) fails
for large t. QED. For a statement valued in [0, 1] one number
ends it: g(2i) = 7.618 against e^2 = 7.389. So calibration in
the mean at every distance is not a form to be found: even an
auditor handed sigma exactly, whose whole evidence is D-hat, has
none. (Sufficiency makes D-hat the whole evidence in that model;
the finite-sample worlds are only near it.) The bound is the
right size: PHI at zeta = 1, with E_0|f| = 1/4, has the mean
(1 + erfi(t/2)^2)/4 at nu = i t, inside e^(t^2/2)/4 and of
order e^(t^2/2)/(pi t^2), where g is of order
e^(t^2)/(pi t^2).
(D) THE CONDITIONAL TRUTH HAS TWO VALUES. Given replicate 1, a fresh
replicate disagrees with probability p = Phi(-|nu|) if D-hat_1 has
D's sign and 1 - p if not. A statement reads |D-hat_1| (and its
sign, whose meaning needs D's), so binning on it mixes the two
values: a reliability diagram of any such statement slopes, and
the mixture weight is a function of nu, hence of the truth.
BY HAND.
nu D/sd(D-hat), the delta-method variance from the exact
moments: 0.645041/n - 0.239094 (n - 3)/(n(n - 1)) at W2 and
(92153/202500)/n - (153521/810000)(n - 3)/(n(n - 1)) at W3,
so 0.338, 0.682, 1.530 and 0.541, 1.094, 2.453 at n = 50,
200, 1000.
sd-hat squared, on two triples of four draws (three would kill the
squared-variance term). (in, out, audited) = ([0,0,0,4],
[1,1,3,7], [0,1,1,2]): variances 4, 8, 2/3, third moments 6
and 12, fourth 21, 72, 1/2, d = 2, and the five terms
19/216 + 47/48 + 19/6 + 3 + 3/2 = 3773/432. And (in, out,
audited) = ([1,1,3,7], [0,1,1,2], [0,0,0,4]): d = -2 and
47/12 + 19/6 + 19/864 + 13/6 + 3 = 10603/864.
arms at |D-hat|/sd-hat = 1: Phi(-1) = 0.15865525, Phi(-1/sqrt 2)
= 0.23975006, and with p = Phi(-1), q = Phi(-2) = 0.02275013,
2(p - p^2) = 0.26696753 and 2(q - q^2) = 0.04446513; at 0
each is 1/2.
floor (4/pi) e^(t^2 - 4)/t^2 is 1/pi at t = 2 and 2/(pi e^2) at
sqrt 2.
pairs nine, of replicates (A, G, B): a = (1.6875, 3, 1), estimate
3/4, D-hat 0.4375; b = (0.6875, 3, 1), 1/4, -0.5625;
c = (-1.3125, -1, 1), 3/4, -0.5625; e = (-0.3125, -1, 1), 1/4,
0.4375; f = (1, 1.5, 1), in the box, 3/4; l = (1.5, 2, 0), no
vertex, 3/4, 0.5; t = (1.25, 3, 1), 1/2, 0. Of (a, b), (a, a),
(a, c), (a, f), (l, a), (c, e), (t, a), (a, t), (f, f) five
are off the box on one side, (a, b), (a, a), (c, e), (t, a),
(a, t); two of those are tied, three are scored, three hit;
two of the nine are strictly opposite. Seven first replicates
have D-hat positive (f's is 0.5), one of those pairs
opposite; one negative, opposite; one zero. (a, c) is what
the one-side clause is for: one side of 1/2, D-hats of
opposite sign. No replicate misses the law, so two readings
no (A, G, B) gives are planted: opposite sides with D-hats of
one sign, and one side with D-hats of opposite sign, each
scored and a miss.
(C) erfi(sqrt 2) = (2/sqrt pi) e^2 F(sqrt 2), F Dawson's
function, 0.45254: 3.7731, so g(2i) = 7.618.
DESIGN. For each cell and n in {50, 200, 1000}, R = 1000 replicate
PAIRS (fresh member, non-member and audited samples of size n each),
one stream per (cell, n). Per replicate: audit.py's reading (the
estimate's side of 1/2 as a sign, D-hat, its ties), the side of the
box its vertex lies on, and the replicate's OWN delta-method spread
sd-hat(D-hat): audit.py's formula with the sample's central moments
(divisor n for the third and fourth) in place of the exact ones. The
pair event is the ESTIMATOR's: the two estimates strictly on opposite
sides of 1/2. Four truth-free arms from replicate 1:
PHI1 Phi(-|D-hat|/sd-hat) (zeta = 1)
PHI2 Phi(-|D-hat|/(sqrt2 sd-hat)) (zeta = sqrt 2)
PAIR 2 p (1 - p), p = Phi(-|D-hat|/sd-hat)
SHARP 2 p (1 - p), p = Phi(-2|D-hat|/sd-hat)
Each arm's law is (B)'s Owen form at the row's nu (exact sigma); the
controls read the forms against the fold by quadrature on the half
line, against their values at 0 and, for PHI1, against its product
form. Every count is a row's field, read against its population; the
seeded counts, means and distances are pinned as recorded. The pair
law and P3's bar are read again at five
further seeds in the bare run, and `--seeds FIRST COUNT` reads them at
any.
PREDICTIONS (fixed before the engine, when the laws were read by
quadrature; P0(i), W3's D = 1/25, is audit.py's own check, and (ii)
and (iii), then a gate, are read in the sweep, the hand rows being the
controls).
P0 CONTROLS, read first. (ii) On every pair whose two replicates both
have their own vertex off the box and on the same side of it,
"estimates on opposite sides of 1/2" equals "D-hats of opposite
sign": zero exceptions. (iii) At n in {200, 1000} the mean plug-in
sd-hat is within 5% of the exact delta sd, and the measured sd of
D-hat over replicates is within 5% of it.
P1 (C) The representation g(nu) = E h(U), U = (X1 + X2)/sqrt 2,
h(u) = 2 Phi(-|u|), matches 2 Phi(nu) Phi(-nu) to 1e-9 on nu in
[-4, 4]; g(i t) pi t^2 e^(-t^2) is within 0.05 of 1 at t = 8,
moving toward 1 from t = 2 to 8; and g(i t)/e^(t^2/2) exceeds
1000 at t = 8.
P2 (A) At n in {200, 1000} the realized pair rate is within 4
standard errors (at the law's value, R = 1000) of g(nu).
P3 (B) At n in {200, 1000} every arm's mean is within 0.025 of its
folded law; n = 50 printed and weighed.
P4 (B) For PHI1, PHI2 and PAIR the ratio of the arm's mean to g(nu)
is larger at the largest-nu row (W3, n = 1000) than at the
smallest (W2, n = 50), and above 2 there. SHARP's ratio is below
1 at every one of the six rows.
P5 (D) At n in {200, 1000}, among pairs whose first D-hat has D's
sign the realized rate is within 4 standard errors of Phi(-nu),
and among the rest of 1 - Phi(-nu), wherever a group holds at
least 30 pairs.
Frozen with the closed forms, before they ran: the hand values
above, but for the pair (a, t), the pair (f, f), the planted misses
and the vertex row with B-hat = 1e-16, each added on a reading of the
draft; at the recorded stream 4,819 pairs off the box on one side,
none tied, every scored pair a hit; the strictly opposite pairs at
n >= 200 unmoved at 373, 123, 241, 18 and at n = 50 at or a few below
465 and 394; at W3, n = 200, 861 first replicates on D's side with 117
pairs opposite and 139 off it with 124; the arms' means, the laws and
the crossings unmoved; at five further seeds every scored pair a hit,
the KILL a scored pair that misses at any seed.
KILL. A hand control off: nothing is read. P3 off at n >= 200: the
folded law is not the law of these statements.
FINDINGS. No kill fired, and every frozen count held; two hand values
were redone, the pair arms at 1, first multiplied out as 0.2669682 and
0.0444652. One frozen clause was wrong: P4 asked the sharpened pair
arm to stay below the pair rate across the sweep, which (B) forbids at
every scale. Its law meets g past nu = 2.18, and the largest-nu row,
nu = 2.45, measures 0.019 against g = 0.014 (law 0.017); the ratios of
the arms' means to g run 0.48 to 2.83, 0.60 to 5.43, 0.65 to 4.45 and
0.37 to 1.33 from the smallest nu to the largest, each a pinned mean
over g. P1 held and is cut: its representation and psi's kink were a
detour, g being closed on the imaginary axis, and the four values the
quadrature read there reprint from the closed form. P3 is read at its
frozen 0.025, at the recorded seed and at five further; P2's and P5's
distances are pinned, all inside their frozen 4 standard errors.
controls nu 0.338, 0.682, 1.530 and 0.541, 1.094, 2.453; the
plug-in spread squared 3773/432 and 10603/864 on the hand
triples; the four Owen forms equal their folds at 52 of 52
points to 1e-12, and Phi(nu/sqrt 2) Phi(-nu/sqrt 2) and g
equal 2 T(nu/sqrt 2, 1) and 4 T(nu, 1), T by its integral,
at 13 of 13; the nine hand pairs; the two planted pairs
miss.
theorem g(i t) and PHI1's law at i t equal their forms in erfi
by its integral at the 12 points, to 1e-10 as a share.
g(2i) = 7.6182 against e^2 = 7.3891; g(i t) over
e^(t^2/2) is 1.031, 69.38, 6.165e5, 4.057e11 at t = 2, 4,
6, 8 and over e^(t^2)/(pi t^2) 1.75342, 1.16983, 1.06193,
1.03311; PHI1's law over e^(t^2/2)/(pi t^2) is 1.58329,
1.45711, 1.14410, 1.07078: the bound's exponent is met and
g's is twice it. The floor lies under g at all 12 points,
and g passes e^(t^2/2) at the 11 from t = 2, not at
sqrt 2.
pair 4,819 pairs off the box with both vertices on one side
(558, 887, 1000 at W2 and 537, 838, 999 at W3), none tied,
4,819 hits; at five further seeds 24,189 of 24,189 of
30,000 pairs, none tied. Strictly opposite pairs of 1000
against g(nu): 464, 373, 123 against 0.465, 0.372, 0.118
and 394, 241, 18 against 0.415, 0.236, 0.014: +0.03, +0.47,
+0.34 and +1.06 of the law's standard errors at n >= 200.
spread the mean plug-in sd-hat 0.0860, 0.0441, 0.0201 and 0.0711,
0.0362, 0.0163 against the exact 0.0912, 0.0452, 0.0202
and 0.0739, 0.0366, 0.0163: below it by 2.49% and 0.10%,
0.92% and 0.27% at n >= 200. The spread of D-hat over
replicates is audit.py's to measure.
law the largest gap of an arm's mean from its law at
n >= 200 is 0.00998 (PAIR at W2, n = 200), and 0.01129
over the five further seeds; at n = 50 the arms sit
0.004 to 0.024 below it, D-hat's normal reading degrading
there. Each law is below g at 0 (by 1/4, 0.1959, 1/6,
0.2952) and changes sign against it once on the grid, past
1.51, 1.13, 1.07, 2.18: every arm under-warns below its
crossing and over-warns above it.
sides given replicate 1, the opposite pairs on D's side against
Phi(-nu) and off it against 1 - Phi(-nu): 178 of 724
against 0.247 and 195 of 276 against 0.753 at W2, n = 200;
117 of 861 against 0.137 and 124 of 139 against 0.863 at
W3, n = 200; the seven groups of 30 or more at n >= 200
within 1.78 standard errors (the eighth holds 11 pairs; no
group sits near 30).
A count of 1000 reads to about 0.016 at its largest; a pinned count,
mean or distance is the record of this seed on this generator, and the
laws, the hand rows and the further seeds do not depend on it.
RUN RECORD. python selfreport.py: 25 of 25 checks, about 4 s, peak
commit about 114 MB. The populations by row, the n = 50 counts, the
six-place means, the distances in standard errors and the five further
seeds' record were entered from a print of this file; every other pin
was derived or recorded before it.
Read by breaks: of 219 single edits inside the engine's functions (a
comparison negated or its boundary moved, a sign, a small constant, a
clause or a loop cut) 209 fail a check; ten pass and move no line:
nine are bounds never met with equality (the five tolerances of the
laws' and the axis forms' agreements, the vertex's tolerance, P3's bar
at a further seed, a group of exactly 30, and a product of D-hats of
exactly zero among scored pairs, which the ties have already taken),
one an absolute tolerance the quadrature of e^(s^2) never needs. The
pair law's check sits behind the controls: with their stop lifted, the
law negated fails it and its further seeds, and the law's clause cut
fails the planted pairs alone. The seed moved by one or by two fails
the six records and nothing else.
"""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import sys
import time
from fractions import Fraction as F
from math import asin, atan, exp, pi, sqrt
import numpy as np
from scipy.integrate import quad
from scipy.special import erf, erfi, ndtr, owens_t
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from audit import TOL, W2, W3, coefficients, side_read # noqa: E402
NS = (50, 200, 1000)
R = 1000
SEED = 20260929
ARMS = ("PHI1", "PHI2", "PAIR", "SHARP")
CHECKS = []
HAND_NU = {"W(12,3)": (0.338, 0.682, 1.530), "W(2,8)": (0.541, 1.094, 2.453)}
HAND_TRIPLES = (
(([0, 0, 0, 4], [1, 1, 3, 7], [0, 1, 1, 2]), F(3773, 432)),
(([1, 1, 3, 7], [0, 1, 1, 2], [0, 0, 0, 4]), F(10603, 864)),
)
HAND_ARMS = ((0.0, (0.5, 0.5, 0.5, 0.5)),
(1.0, (0.15865525, 0.23975006, 0.26696753, 0.04446513)))
HAND_AT_0 = (0.25, atan(sqrt(2)) / pi, 1 / 3, 0.5 - asin(0.8) / pi)
HAND_VERTEX = ((3, 1, 1), (-1, 1, -1), (0, 1, 0), (2, 1, 0), (2, 0, 0),
(-2, 0, 0), (0.3, 1e-16, 0))
_a, _b, _c, _e = ((1.6875, 3, 1), (0.6875, 3, 1), (-1.3125, -1, 1),
(-0.3125, -1, 1))
_f, _l, _t = (1, 1.5, 1), (1.5, 2, 0), (1.25, 3, 1)
HAND_PAIRS = ((_a, _b), (_a, _a), (_a, _c), (_a, _f), (_l, _a), (_c, _e),
(_t, _a), (_a, _t), (_f, _f))
# two pairs no replicate gives, as (side, D-hat) of the first and of
# the second reading: each scored, each a miss
PLANTED = (((1, 0.5), (-1, 0.3)), ((1, 0.5), (1, -0.3)))
# g(i t) pi t^2 e^(-t^2) at t = 2, 4, 6, 8: the record of a second
# route, a quadrature of e^(t^2) psi-hat(sqrt 2 t), psi(u) =
# 2 Phi(-|u|) phi(u), printed before the closed form was known
AXIS_PINS = (1.75342, 1.16983, 1.06193, 1.03311)
CROSS_PINS = ((1, 151, -0.25), (1, 113, atan(sqrt(2)) / pi - 0.5),
(1, 107, -1 / 6), (1, 218, -asin(0.8) / pi))
P_SD = (0.085996, 0.044061, 0.020139, 0.071065, 0.036233, 0.016262)
P_ARM = ((0.220928, 0.277530, 0.300587, 0.171393),
(0.221010, 0.278167, 0.303175, 0.172558),
(0.121840, 0.178125, 0.180729, 0.075008),
(0.222235, 0.278960, 0.303626, 0.171380),
(0.173883, 0.231163, 0.243238, 0.125177),
(0.039758, 0.076401, 0.062604, 0.018727))
# a seeded run's record, a (cell, n): pairs off the box on one side,
# tied; strictly opposite pairs; first replicates on D's side, the
# opposite among them; off it, the opposite among them; the mean
# plug-in spread; the four arms' means
PAIR_PINS = {
("W(12,3)", 50): (558, 0, 464, 606, 246, 394, 218, P_SD[0], P_ARM[0]),
("W(12,3)", 200): (887, 0, 373, 724, 178, 276, 195, P_SD[1], P_ARM[1]),
("W(12,3)", 1000): (1000, 0, 123, 939, 64, 61, 59, P_SD[2], P_ARM[2]),
("W(2,8)", 50): (537, 0, 394, 699, 191, 301, 203, P_SD[3], P_ARM[3]),
("W(2,8)", 200): (838, 0, 241, 861, 117, 139, 124, P_SD[4], P_ARM[4]),
("W(2,8)", 1000): (999, 0, 18, 989, 7, 11, 11, P_SD[5], P_ARM[5]),
}
# five further seeds: pairs, off the box on one side, tied, scored,
# and the largest gap of an arm's mean from its law at n >= 200
FAR_PINS = (30000, 24189, 0, 24189, 0.01129)
BAR = 0.025 # P3's, as frozen
# at n >= 200, in standard errors: the opposite pairs from g(nu); the
# groups' opposite pairs from Phi(-nu) and 1 - Phi(-nu)
PAIR_GAP_PINS = (0.03, 0.47, 0.34, 1.06)
GROUP_GAP_PINS = (-0.10, -1.77, 0.64, 0.97, -0.10, 1.00, -0.00)
def check(name, ok, detail=""):
CHECKS.append(bool(ok))
tag = "PASS" if ok else "FAIL"
print(f" {tag} {name}" + (f" ({detail})" if detail else ""))
def section(title):
print()
print(title)
# ------------------------------------------------------------ the laws
def g_of(z):
"""(A) the pair rate 2 Phi(z) Phi(-z), at a real or a complex z."""
return (1 - erf(z / sqrt(2)) ** 2) / 2
def g_axis(t):
"""(C) g(i t)."""
return (1 + erfi(t / sqrt(2)) ** 2) / 2
def g_floor(t):
"""(C) the hand bound under g(i t), t >= sqrt 2."""
return 4 / pi * exp(t * t - 4) / (t * t)
def phi1_axis(t):
"""(C) PHI1's law at nu = i t."""
return (1 + erfi(t / 2) ** 2) / 4
def arm_values(x):
"""The four statements at x = |D-hat|/sd-hat, in ARMS' order."""
return (ndtr(-x), ndtr(-x / sqrt(2)), 2 * ndtr(-x) * ndtr(x),
2 * ndtr(-2 * x) * ndtr(2 * x))
def laws(nu):
"""(B) the four folded laws at nu, in ARMS' order."""
return (2 * owens_t(nu / sqrt(2), 1.0),
2 * owens_t(nu / sqrt(3), sqrt(2)),
4 * owens_t(nu / sqrt(2), 1 / sqrt(3)),
4 * owens_t(2 * nu / sqrt(5), 1 / 3))
def fold(nu, k):
"""The definition of arm k's law, E arm_k(|nu + Z|), on the half
line."""
def f(y):
return float(arm_values(y)[k]) * (exp(-(y - nu) ** 2 / 2)
+ exp(-(y + nu) ** 2 / 2))
return quad(f, 0, 40, epsabs=1e-14, epsrel=1e-13,
limit=400)[0] / sqrt(2 * pi)
def owen_integral(h, a):
"""T(h, a) by its integral."""
return quad(lambda x: exp(-h * h * (1 + x * x) / 2) / (1 + x * x),
0, a, epsabs=1e-14, epsrel=1e-13)[0] / (2 * pi)
def erfi_integral(x):
"""erfi(x) = (2/sqrt pi) int_0^x e^(s^2) ds, by quadrature."""
return 2 / sqrt(pi) * quad(lambda u: exp(u * u), 0, x, epsabs=0,
epsrel=1e-13)[0]
def law_hits(grid):
"""Agreements to 1e-12 over the grid: each arm's Owen form with its
fold; the product Phi(nu/sqrt 2) Phi(-nu/sqrt 2) with
2 T(nu/sqrt 2, 1) and g with 4 T(nu, 1), T by its integral."""
folds = prod = truth = 0
for nu in grid:
L = laws(nu)
folds += sum(abs(L[k] - fold(nu, k)) <= TOL for k in range(4))
prod += abs(ndtr(nu / sqrt(2)) * ndtr(-nu / sqrt(2))
- 2 * owen_integral(nu / sqrt(2), 1.0)) <= TOL
truth += abs(g_of(nu) - 4 * owen_integral(nu, 1.0)) <= TOL
return int(folds), int(prod), int(truth)
def axis_hits(ts):
"""Agreements to 1e-10, as a share, of g(i t) and of PHI1's law at
i t with their forms in erfi by its integral."""
return (sum(abs((1 + erfi_integral(t / sqrt(2)) ** 2) / 2 - g_axis(t))
<= 1e-10 * g_axis(t) for t in ts),
sum(abs((1 + erfi_integral(t / 2) ** 2) / 4 - phi1_axis(t))
<= 1e-10 * phi1_axis(t) for t in ts))
def crossings(grid):
"""Per arm: the sign changes of its law less g along the grid, the
index before the first, and the gap at the grid's start."""
g = g_of(grid)
out = []
for L in laws(grid):
idx = np.nonzero(np.diff(np.sign(L - g)))[0]
out.append((len(idx), int(idx[0]), float(L[0] - g[0])))
return out
def nu_of(w, n):
return float(w.D) / w.sd_D(n)
def rate_gap(k, m, p):
"""k of m less the rate p, in p's standard errors over m."""
return (k / m - p) / sqrt(p * (1 - p) / m)
# ------------------------------------------------------- the replicates
def sd_hat(xm, xn, xu):
"""The replicate's own delta-method spread of D-hat: audit.py's
Depth.var_D with sample moments in place of the exact ones."""
n = xm.shape[-1]
def mom(x):
c = x - x.mean(-1, keepdims=True)
return (c * c).sum(-1) / (n - 1), (c ** 3).mean(-1), (c ** 4).mean(-1)
(vm, m3m, m4m), (vn, m3n, m4n), (vu, _, m4u) = mom(xm), mom(xn), mom(xu)
def v(m4, var):
return m4 / n - var * var * (n - 3) / (n * (n - 1))
d = xn.mean(-1) - xm.mean(-1)
tot = (v(m4u, vu) + v(m4m, vm) / 4 + v(m4n, vn) / 4
+ d * d / 4 * (vm + vn) / n + d / 2 * (m3n - m3m) / n)
return np.sqrt(tot)
def vertex_side(G, B):
"""1 or -1 where the vertex G/(2B) lies above the box or below it,
0 where it lies in the box or there is none (B zero to 1e-12, as
audit.py reads its ties)."""
G, B = np.asarray(G, dtype=float), np.asarray(B, dtype=float)
return np.where(B > TOL, (G > 2 * B).astype(int) - (G < 0), 0)
def reading(A, G, B):
"""A replicate as the pair read needs it: audit.py's side of 1/2,
tie and D-hat, and the vertex's side of the box."""
s = side_read(A, G, B)
return dict(side=s["side"], tie=s["tie"], D=s["D"], v=vertex_side(G, B))
def pair_read(a, b):
"""Counts over pairs of readings, a the first replicate: pairs off
the box with both vertices on one side (pop), those holding a tie,
the scored rest and its hits (strictly opposite sides of 1/2 iff
D-hats of opposite sign); the strictly opposite pairs of all; first
replicates with D-hat positive, the side of D at both cells, and
negative, and the opposite pairs among each."""
opp = a["side"] * b["side"] < 0
pop = (a["v"] != 0) & (a["v"] == b["v"])
tied = pop & (a["tie"] | b["tie"])
scored = pop & ~tied
hit = scored & (opp == (a["D"] * b["D"] < 0))
on, off = a["D"] > 0, a["D"] < 0
return dict(pop=int(pop.sum()), tied=int(tied.sum()),
scored=int(scored.sum()), hits=int(hit.sum()),
opp=int(opp.sum()), on=int(on.sum()),
opp_on=int((opp & on).sum()), off=int(off.sum()),
opp_off=int((opp & off).sum()))
def hand_pairs(pairs):
cols = [np.array([p[i][k] for p in pairs], dtype=float)
for i in range(2) for k in range(3)]
return pair_read(reading(*cols[:3]), reading(*cols[3:]))
def planted_pairs(pairs):
"""Readings built field by field, both vertices above the box and
no tie, through pair_read."""
a, b = (dict(side=np.array([p[i][0] for p in pairs]),
D=np.array([p[i][1] for p in pairs]),
tie=np.zeros(len(pairs), dtype=bool),
v=np.ones(len(pairs), dtype=int)) for i in range(2))
return pair_read(a, b)
def rng_for(ci, n, seed=SEED):
return np.random.default_rng([seed, ci, n])
def replicate(w, rng, n):
"""R replicates: the reading and the three samples."""
x = w.draw(rng, n, size=R)
return reading(*coefficients(*x)), x
def pair_row(w, ci, n, seed=SEED):
"""One (cell, n): R pairs through pair_read, the mean plug-in
spread and the mean of each arm on the first replicate."""
rng = rng_for(ci, n, seed)
(a, x), (b, _) = replicate(w, rng, n), replicate(w, rng, n)
rec = pair_read(a, b)
sd = sd_hat(*x)
rec["sdh"] = float(sd.mean())
rec["arms"] = tuple(float(v.mean())
for v in arm_values(np.abs(a["D"]) / sd))
return rec
def pair_sweep(cells, seed=SEED):
return {(w.name, n): pair_row(w, ci, n, seed)
for ci, w in enumerate(cells, start=1) for n in NS}
def far_sweep(cells, seeds):
"""Over further seeds: pairs, those off the box on one side, tied,
scored, and the scored that hit; the gaps of the arms' means from
their laws at n >= 200, those inside P3's bar, and the largest."""
t = dict(pairs=0, pop=0, tied=0, scored=0, hits=0, gaps=0, near=0,
gap=0.0)
for seed in seeds:
rec = pair_sweep(cells, seed)
for r in rec.values():
t["pairs"] += R
for k in ("pop", "tied", "scored", "hits"):
t[k] += r[k]
g = [abs(x) for x in arm_gaps(rec, cells)]
t["gaps"] += len(g)
t["near"] += sum(x < BAR for x in g)
t["gap"] = max([t["gap"]] + g)
return t
def spread_gaps(rec, cells):
"""At n >= 200: the mean plug-in spread over the exact one, less
1."""
return [rec[w.name, n]["sdh"] / w.sd_D(n) - 1
for w in cells for n in NS[1:]]
def arm_gaps(rec, cells):
"""At n >= 200: each arm's mean less its law."""
return [m - law for w in cells for n in NS[1:]
for m, law in zip(rec[w.name, n]["arms"], laws(nu_of(w, n)))]
def pair_gaps(rec, cells):
"""At n >= 200: the opposite pairs against g(nu), in standard
errors."""
return [rate_gap(rec[w.name, n]["opp"], R, float(g_of(nu_of(w, n))))
for w in cells for n in NS[1:]]
def group_gaps(rec, cells):
"""At n >= 200, each group of 30 pairs or more: its opposite pairs
against Phi(-nu) on D's side and 1 - Phi(-nu) off it, in standard
errors."""
out = []
for w in cells:
for n in NS[1:]:
r, p = rec[w.name, n], float(ndtr(-nu_of(w, n)))
for k, m, want in ((r["opp_on"], r["on"], p),
(r["opp_off"], r["off"], 1 - p)):
if m >= 30:
out.append(rate_gap(k, m, want))
return out
# ------------------------------------------------------------ sections
def section_controls():
section("CONTROLS")
for w in (W2, W3):
print(f" {w.name}: D = {w.D}, exact delta sd(D-hat) "
+ ", ".join(f"{w.sd_D(n):.4f}" for n in NS) + "; nu "
+ ", ".join(f"{nu_of(w, n):.4f}" for n in NS))
check("nu at the six rows as by hand",
sum(abs(nu_of(w, n) - x) < 0.0005 for w in (W2, W3)
for n, x in zip(NS, HAND_NU[w.name])) == 6)
sq = [float(sd_hat(*(np.array(x, dtype=float) for x in tr))) ** 2
for tr, _ in HAND_TRIPLES]
check("the plug-in spread's square on the two hand triples",
sum(abs(s - float(h)) <= TOL
for s, (_, h) in zip(sq, HAND_TRIPLES)) == 2,
f"{sq[0]:.6f}, {sq[1]:.6f}")
check("the four arms at 0 and at 1 as by hand",
sum(abs(float(v) - h) < 5e-8 for x, hand in HAND_ARMS
for v, h in zip(arm_values(x), hand)) == 8,
", ".join(f"{float(v):.8f}" for v in arm_values(1.0)))
check("the four laws at nu = 0 as by hand, and g = 1/2 there",
sum(abs(float(v) - h) <= TOL
for v, h in zip(laws(0.0), HAND_AT_0)) == 4
and g_of(0.0) == 0.5)
grid = np.linspace(0.0, 6.0, 13)
folds, prod, truth = law_hits(grid)
check("each arm's Owen form is its fold by quadrature; "
"Phi(nu/sqrt 2) Phi(-nu/sqrt 2) is 2 T(nu/sqrt 2, 1) and g is "
"4 T(nu, 1), T by its integral",
(folds, prod, truth) == (52, 13, 13),
f"{folds} of 52, {prod} and {truth} of 13")
check("the vertex's side on seven hand rows",
sum(int(vertex_side(G, B)) == v for G, B, v in HAND_VERTEX) == 7)
hp = hand_pairs(HAND_PAIRS)
check("the pair read on nine hand pairs: off the box on one side, "
"tied, scored, hits, opposite; on D's side and off it",
tuple(hp.values()) == (5, 2, 3, 3, 2, 7, 1, 1, 1),
", ".join(str(x) for x in hp.values()))
pl = planted_pairs(PLANTED)
check("two planted pairs no replicate gives are scored and miss",
(pl["pop"], pl["scored"], pl["hits"]) == (2, 2, 0),
f"{pl['hits']} hits of {pl['scored']} scored")
check("a rate's distance in standard errors on two hand rows",
abs(rate_gap(60, 100, 0.5) - 2) <= TOL
and abs(rate_gap(20, 400, 0.1) + 10 / 3) <= TOL)
return all(CHECKS)
def section_theorem():
section("THE THEOREM'S GROWTH, on the imaginary axis")
ts = [sqrt(2)] + list(range(2, 13))
for t, pin in zip((2, 4, 6, 8), AXIS_PINS):
print(f" t = {t}: g(it) = {g_axis(t):.5g} over e^(t^2/2) "
f"{g_axis(t) / exp(t * t / 2):.4g} over e^(t^2)/(pi t^2) "
f"{g_axis(t) * pi * t * t * exp(-t * t):.5f} PHI1's law "
f"over e^(t^2/2)/(pi t^2) "
f"{phi1_axis(t) * pi * t * t * exp(-t * t / 2):.5f}")
check("g and PHI1's law at i t against erfi by its integral, at 12 "
"points", axis_hits(ts) == (12, 12))
check("g(2i) is 7.618 as by hand, above e^2",
abs(g_axis(2) - 7.618) < 0.0005 and g_axis(2) > exp(2),
f"{g_axis(2):.4f}, {exp(2):.4f}")
check("the hand floor (4/pi) e^(t^2 - 4)/t^2 is 1/pi at 2 and "
"2/(pi e^2) at sqrt 2, and lies under g(i t) at each of the 12",
abs(g_floor(2) - 1 / pi) <= TOL
and abs(g_floor(sqrt(2)) - 2 / (pi * exp(2))) <= TOL
and sum(g_floor(t) <= g_axis(t) for t in ts) == 12)
check("g(i t) pi t^2 e^(-t^2) at t = 2, 4, 6, 8 as recorded",
sum(abs(g_axis(t) * pi * t * t * exp(-t * t) - x) < 0.000005
for t, x in zip((2, 4, 6, 8), AXIS_PINS)) == 4)
check("PHI1's law on the axis inside its bound e^(t^2/2)/4 at each "
"of the 12; g past e^(t^2/2) at the 11 from t = 2",
sum(phi1_axis(t) <= exp(t * t / 2) / 4 for t in ts) == 12
and [g_axis(t) > exp(t * t / 2) for t in ts]
== [False] + [True] * 11)
def section_statements():
section("THE SELF-REPORT: four truth-free arms against the pair event")
cells = (W2, W3)
rec = pair_sweep(cells)
print(" cell n nu g(nu) opposite on one side/tied/hits "
"sd-hat exact arm means (law)")
for w in cells:
for n in NS:
r, nu = rec[w.name, n], nu_of(w, n)
cols = " ".join(f"{a} {m:.6f} ({law:.6f})" for a, m, law
in zip(ARMS, r["arms"], laws(nu)))
print(f" {w.name:7s} {n:4d} {nu:.3f} {float(g_of(nu)):.3f}"
f" {r['opp']:4d} {r['pop']}/{r['tied']}/{r['hits']}"
f" {r['sdh']:.6f} {w.sd_D(n):.6f} "
+ cols)
p = float(ndtr(-nu))
print(f" conditional: D's side {r['opp_on']} of {r['on']} "
f"against {p:.3f}; off it {r['opp_off']} of {r['off']} "
f"against {1 - p:.3f}")
pop = sum(r["pop"] for r in rec.values())
check("PAIR off the box with both vertices on one side: opposite "
"sides of 1/2 iff D-hats of opposite sign, at every scored "
"pair of each row",
sum(r["hits"] == r["scored"] for r in rec.values()) == 6,
f"{sum(r['hits'] for r in rec.values())} of "
f"{sum(r['scored'] for r in rec.values())} scored of {pop}")
far = far_sweep(cells, range(SEED + 1, SEED + 6))
print(f" at five further seeds: {far['hits']} of {far['scored']} "
f"scored of {far['pop']} off the box on one side, "
f"{far['tied']} tied, of {far['pairs']} pairs; the largest "
f"gap of an arm's mean from its law {far['gap']:.5f}")
check("PAIR the same at five further seeds, every scored pair",
far["hits"] == far["scored"])
check("the five further seeds' pairs, population, ties, scored "
"and largest gap as recorded",
(far["pairs"], far["pop"], far["tied"], far["scored"])
== FAR_PINS[:4] and abs(far["gap"] - FAR_PINS[4]) < 5e-6)
check("PAIR the population, the ties, the opposite pairs and the "
"two groups as recorded",
sum((r["pop"], r["tied"], r["opp"], r["on"], r["opp_on"],
r["off"], r["opp_off"]) == PAIR_PINS[k][:7]
for k, r in rec.items()) == 6,
f"{pop} off the box on one side in all")
check("the mean plug-in spread as recorded",
sum(abs(r["sdh"] - PAIR_PINS[k][7]) < 5e-7
for k, r in rec.items()) == 6)
check("the 24 arm means as recorded",
sum(abs(m - x) < 5e-7 for k, r in rec.items()
for m, x in zip(r["arms"], PAIR_PINS[k][8])) == 24)
sdg = spread_gaps(rec, cells)
check("the mean plug-in spread within 5% of the exact one at each "
"row with n >= 200",
sum(abs(x) < 0.05 for x in sdg) == 4,
"as a share " + ", ".join(f"{x:+.4f}" for x in sdg))
gaps = arm_gaps(rec, cells)
check("each arm's mean within 0.025 of its law at each row with "
"n >= 200, at the recorded seed and at the five further",
sum(abs(x) < BAR for x in gaps) == 16
and (far["near"], far["gaps"]) == (80, 80),
f"largest {max(abs(x) for x in gaps):.5f} and {far['gap']:.5f}")
pg = pair_gaps(rec, cells)
check("the opposite pairs' distance from g(nu) in its standard "
"errors as recorded at each row with n >= 200",
sum(abs(x - y) <= 0.005 for x, y in zip(pg, PAIR_GAP_PINS)) == 4
and len(pg) == 4,
"in standard errors " + ", ".join(f"{x:+.2f}" for x in pg))
cg = group_gaps(rec, cells)
check("the two conditional rates' distances from Phi(-nu) and "
"1 - Phi(-nu) in standard errors as recorded, in each of the 7 "
"groups of 30 or more at n >= 200",
sum(abs(x - y) <= 0.005 for x, y in zip(cg, GROUP_GAP_PINS)) == 7
and len(cg) == 7,
"in standard errors " + ", ".join(f"{x:+.2f}" for x in cg))
grid = np.linspace(0.0, 6.0, 601)
cr = crossings(grid)
print(" law less g on [0, 6], its sign changes and the grid point "
"before the first: " + ", ".join(
f"{a} {c[0]} at {grid[c[1]]:.2f}" for a, c in zip(ARMS, cr)))
check("each arm's law less g changes sign once on the 601 grid "
"points of [0, 6], after the recorded one, from the hand gap "
"at 0",
sum(c[:2] == p[:2] and abs(c[2] - p[2]) <= TOL
for c, p in zip(cr, CROSS_PINS)) == 4 and len(cr) == 4)
def main():
t0 = time.time()
if not section_controls():
print("\nCONTROL FAILED: nothing below is read.")
sys.exit(1)
if sys.argv[1:2] == ["--seeds"]:
first, count = int(sys.argv[2]), int(sys.argv[3])
t = far_sweep((W2, W3), range(first, first + count))
print(f"seeds {first} to {first + count - 1}: {t['hits']} of "
f"{t['scored']} scored of {t['pop']} off the box on one "
f"side, {t['tied']} tied, of {t['pairs']} pairs; "
f"{t['near']} of {t['gaps']} gaps inside {BAR}, the "
f"largest {t['gap']:.5f}; "
f"{time.time() - t0:.1f} s")
sys.exit(0 if t["hits"] == t["scored"] else 1)
section_theorem()
section_statements()
print()
print(f"{sum(CHECKS)} of {len(CHECKS)} checks, "
f"{time.time() - t0:.1f} s")
sys.exit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
main()