parcount.py

Checks: COORDINATES: The parity variant's reach rule; pattern; observation.

Cited on: COORDINATES.

To run it: save parcount.py, with shiftpar.py, shiftsum.py beside it; needs numpy, sympy.

"""parcount.py — is the code reading's first miss structure, or a draw?

QUESTION. Under the parity variant's code reading C (shiftpar.py) the
first miss is a data pair with a residue flip, (e_i 2^i + e_j 2^j) 2^t
= e_l 2^l mod M, 0 <= i < j, 0 <= l < r. Its least j at the paper's
moduli (5, 94, 29546 at 125, 32749, 2^31 - 19) sits 2.8 and 5.0 times
above the scale guess sqrt(D/r). Structure of 2 mod M, or draws of a
model the guess got wrong?

THE REDUCTION (by hand, before this engine). l < r < t <= i + t, M odd:
dividing by 2^l, M | e_i 2^u + e_j 2^v - e_l, u = i + t - l < v = j +
t - l. A miss is a TRINOMIAL (u, v, s1, s2), M | 2^v + s1 2^u + s2,
and a trinomial gives misses at l = max(0, t - u) .. r - 1, i = u - t
+ l, j = v - t + l, nonempty iff u >= u0 = t - r + 1. So
    j_min = min over trinomials, u0 <= u < v, of v - min(t, u),
each trinomial a cluster of up to r misses.

THE MODELS. Tuple (the scale guess's): each normalized miss an
independent 1/M event, N_T(J) = 2r J(J+1)/M misses with j <= J.
Cluster: each trinomial an independent 1/M event, N_C(J) = 4[(r - 1)J
+ J(J+1)/2]/M. Z = N(j_min) at the midpoint (N(j_min - 1) +
N(j_min))/2 is Exp(1) under the true model.

THE FROZEN BLOCK, written before this engine and copied whole:
PREDICTIONS, frozen.
 P1 the reduction: j_min by trinomials = shiftpar.witness's least j at
    every prime of 12 bits (lmax 4·sqrt(M)) and at the three paper
    moduli (lmax 60, 400, 40000): 5, 94, 29546.
 P2 the exact tuple count with j ≤ J (summed over each cluster's l)
    = a direct enumeration of the congruence over (i, j, l, σ, τ) at
    the 12-bit primes of the family, J = 40.
 P3 Z under the cluster model reads Exp(1): mean in [0.9, 1.1] over
    the family; the tuple model's mean reads above 5.
 P4 the paper's moduli: P_C = exp(−N_C(j_min − 1)) in [0.05, 0.95] at
    each; "two draws" (three).

THE FAMILY, built, not drawn: for each r = 12..20 (t = r + 1, M an
r-bit prime), the spread arm, 300 primes at evenly spaced indices of
the r-bit primes, and the corner arm, the 30 largest r-bit primes
(the 2^r − δ of the paper's choice): 2970 primes.

KILL, as printed:
  "Z cluster mean over 2970 primes: X (sd ...)" — the cluster model
  dies (STRUCTURE) if X is outside [0.9, 1.1] (≥ 5 sd of the null);
  "Z cluster mean, corner arm: X" — the corner shows structure if
  outside [0.75, 1.25] (4 sd at 270);
  "count ratio exact/N_C at J* = 2 sqrt(M), primes with O > J* + t:
  X" — the cluster model's mean dies outside [0.95, 1.05].
  Survival on all three: the 94 and 29,546 are draws, the scale guess
  wrong by the cluster (sqrt(M/2) against sqrt(M/(2r))).

CONTROLS, read first.
 C1 the hand count at M = 31 (O = 5, r = 5, t = 6, u0 = 2; mod 31 the
    trinomials are u ≡ v ≡ 4 mod 5 (16 + 16 − 1), u ≡ 0 and v ≡ 1
    (2 − 1 − 1), u ≡ 1 and v ≡ 0 (1 − 2 + 1)): clusters with j ≤ J
    at J = 1..5 number 1, 1, 1, 2, 4 ((5,6) j 1; (6,10) j 4; (4,9) and
    (10,11) j 5); j_min = 1.
 C2 N_C's closed form = its pair count brute-summed, at r = 12..20, J
    ≤ 300.
 C3 the PLANT: the same engine and filter with 2^n mod M replaced by
    independent uniform residues (seeded), same family: Z cluster mean
    in [0.9, 1.1] and count ratio in [0.95, 1.05]; a filter that
    misreads a true model fails here first.

CHANGES TO WHAT WAS FROZEN. The spread arm's 300 are drawn from the
r-bit primes below the corner's 30, so the arms share no prime; at r
= 12 there are 255 r-bit primes, so the spread arm takes all 225 below
the corner and the family is 2895, not 2970. Three hand figures in the
derivation written before the block were wrong, the bands untouched: N_T at 32749 is 8.008, P 3.33e-4 at
its print; the medians solve 2J² + (4r − 2)J = M ln 2 (the block's J²
+ 28J and J² + 60J drop a J); and the integers' region (b), v ≤ r − 2,
where |2^v ± 2^u ± 1| < M holds no trinomial at any r-bit prime, holds
N_C 0.070 at 2053 and 0.035 at 4093, not below 0.02. C3 runs no order
filter, its residues having no order (its count line says so). At 125,
composite, the rate is 3/400, not 1/125 (a target must be a unit),
P4's 125 row read at it after the first run; the tuple model's N_T
stays at 1/M there. The KILL and P3's bar entered the exit status
after the first run.

FINDINGS (the run's lines, copied; C3's and P3's by-r lines cut, the
family count, the trinomial PASS lines (2895 of 2895, both runs) cut,
the band and P4 PASS lines folded into their prints).
  PASS  C1 M 31, r 5, t 6: clusters with j <= 1..5 [1, 1, 1, 2, 4],
  j_min 1 (hand: [1, 1, 1, 2, 4], 1)
  PASS  C2 N_C's closed form = the pair count at r 12..20, J 0..300
  step 7: 0 off
  C3 plant: Z cluster mean over 2895 primes: 1.0004 (sample sd 1.001,
  of the mean 0.0186); Z tuple mean: 13.540; spread arm (2625): 0.9999;
  corner arm (270): 1.0061; count ratio 25116 / 25072.3 = 1.0017
  PASS  P1 trinomial j_min = witness's least j at 255 of 255 12-bit primes
  PASS  P2 cluster-summed misses = direct count, j <= 40, at 255 of 255
  12-bit primes
  P3: Z cluster mean over 2895 primes: 1.0102 (sample sd 1.028, of the
  mean 0.0191); Z tuple mean: 13.778; spread arm (2625): 1.0192; corner
  arm (270): 0.9223; by r from 0.925 (13) to 1.123 (16)
  P3: count ratio exact/N_C at J* = 2 sqrt(M), 2856 of 2895 primes kept
  (O > J* + t; no filter on the plant): 24739 / 24715.8 = 1.0009
  KILL Z cluster mean over the family: 1.0102 (held, band [0.9, 1.1])
  KILL Z cluster mean, corner arm: 0.9223 (held, band [0.75, 1.25])
  KILL count ratio: 1.0009 (held, band [0.95, 1.05])
  P3 tuple model's Z mean 13.778 (frozen: above 5)
  PASS  KILL held at all three bands, the tuple mean above 5
  P4 M 125: j_min 5 (witness 5), rate 3/400, N_C(j-1) 1.0200, P_C
  0.361; N_T(j-1) 2.240, P_T 1.06e-01
  P4 M 32749: j_min 94 (witness 94), rate 1/M, N_C(j-1) 0.6929, P_C
  0.500; N_T(j-1) 8.008, P_T 3.33e-04
  P4 M 2147483629: j_min 29546 (witness 29546), rate 1/M, N_C(j-1)
  0.8146, P_C 0.443; N_T(j-1) 25.203, P_T 1.13e-11
  Read: two draws, three with 125. C's first miss is the least
  trinomial multiple of M, and the family reads as independent 1/M
  trinomials at its resolution (the mean's sd 0.019, about 0.06 per r
  and at the corner): the empty integers' region, N_C 0.035 to 0.070
  at 12 bits, sits under r = 12's 0.064, and the corner's 0.922 is
  1.2 sd low (sd 0.063 from the family's 1.028). The scale guess
  sqrt(D/r), D = (M - 1)/2 at 32749 and 2^31 - 19, is the tuple
  model's scale (its median about sqrt(ln 2 D/r)), which counts a
  cluster's up-to-r misses as independent: its Z mean is 13.8. The
  cluster median, the least J with N_C(J) >= ln 2, is the least
  integer past the root of 2J^2 + (4r - 2)J = M ln 2, near sqrt(M ln
  2 / 2) only where M >> r^2: 94 against 106.5 at 32749, 27251
  against 27281 at 2^31 - 19. The plant reads the filter at 1.0004,
  so a true model passes it. 39 of 2895 primes have ord_M(2) <= J* +
  t; they enter Z, not the count ratio. Toy scale: primes of 12 to 20
  bits, plus the paper's three moduli.

RUN RECORD. 11.9 s wall under a 2048 MB cap, peak commit 63.8 MB, one
process, exit 0; with the KILL in the exit status, 12.1 s, 63.8 MB,
exit 0, and a copy with the family band made [1.05, 1.1] exits 1;
with 125's rate, 12.9 s, 63.6 MB, exit 0.
"""

import math
import os
import random
import sys

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
from shiftpar import witness  # noqa: E402

RS = range(12, 21)
N_SPREAD, N_CORNER = 300, 30


def sieve(n):
    s = bytearray([1]) * n
    s[0:2] = b"\x00\x00"
    for p in range(2, int(n ** 0.5) + 1):
        if s[p]:
            s[p * p::p] = bytearray(len(range(p * p, n, p)))
    return [i for i in range(n) if s[i]]


def family():
    """(r, arm, M) over r = 12..20."""
    ps = sieve(1 << 20)
    out = []
    for r in RS:
        rb = [p for p in ps if (1 << (r - 1)) < p < (1 << r)]
        corner, rest = rb[-N_CORNER:], rb[:-N_CORNER]
        n = len(rest)
        idx = sorted({round(k * (n - 1) / (N_SPREAD - 1))
                      for k in range(N_SPREAD)}) if n > N_SPREAD else range(n)
        assert len(idx) == min(n, N_SPREAD)
        out += [(r, "spread", rest[i]) for i in idx]
        out += [(r, "corner", M) for M in corner]
    return out


def n_c(J, r, M):
    return 4 * ((r - 1) * J + J * (J + 1) / 2) / M


def n_t(J, r, M):
    return 2 * r * J * (J + 1) / M


def n_c_brute(J, r, t):
    """The pair count under N_C: u0 <= u < v, v - min(t, u) <= J."""
    u0 = t - r + 1
    return sum(1 for u in range(u0, J + t) for v in range(u + 1, J + t + 1)
               if v - min(t, u) <= J)


def powers(M, V):
    res, x = [], 1
    for _ in range(V):
        res.append(x)
        x = 2 * x % M
    return res


def engine(M, r, t, res, jc, jt=None):
    """Trinomials x_v + s1 x_u + s2 = 0 mod M over u0 <= u < v, x_n =
    res[n]: (j_min, clusters with j <= jc, misses with j <= jt, the
    largest v read). Reads v until v - t exceeds both j_min and jc."""
    u0 = t - r + 1
    seen = {}
    jmin, ncl, ntu = None, 0, 0
    v = u0
    while v < len(res):
        if v - t > jc and jmin is not None and v - t > jmin:
            break
        if v - 1 >= u0:
            seen.setdefault(res[v - 1], []).append(v - 1)
        x = res[v]
        for y in ((-(x + 1)) % M, (x + 1) % M, (-(x - 1)) % M, (x - 1) % M):
            for u in seen.get(y, ()):
                j = v - min(t, u)
                if jmin is None or j < jmin:
                    jmin = j
                if j <= jc:
                    ncl += 1
                if jt is not None:
                    lo = max(0, t - u)
                    hi = min(r - 1, jt - v + t)
                    ntu += max(0, hi - lo + 1)
        v += 1
    return jmin, ncl, ntu, v


def direct_tuples(M, r, t, J):
    """Normalized misses (e_i = +1) with j <= J, by the congruence."""
    tgt = {}
    for l in range(r):
        for tau in (1, -1):
            k = tau * (1 << l) % M
            tgt[k] = tgt.get(k, 0) + 1
    st = pow(2, t, M)
    n = 0
    for j in range(1, J + 1):
        for i in range(j):
            for sg in (1, -1):
                n += tgt.get(((1 << i) + sg * (1 << j)) * st % M, 0)
    return n


def order_small(res, V):
    """ord_M(2) <= V, read off the residues (res[0] = 1)."""
    return any(res[n] == 1 for n in range(1, min(V + 1, len(res))))


def check(label, ok):
    print(("PASS  " if ok else "FAIL  ") + label)
    return bool(ok)


def zmid(nf, j, r, M):
    return (nf(j - 1, r, M) + nf(j, r, M)) / 2


def run_family(fam, plant, seed=7):
    rng = random.Random(seed)
    rows = []
    for r, arm, M in fam:
        t = r + 1
        js = int(2 * math.sqrt(M))
        V = int(12 * math.sqrt(M)) + t + 2
        if plant:
            res = [1] + [rng.randrange(1, M) for _ in range(V - 1)]
        else:
            res = powers(M, V)
        jmin, ncl, _, vread = engine(M, r, t, res, js)
        small = (not plant) and order_small(res, js + t)
        rows.append((r, arm, M, jmin, ncl, js, small))
    return rows


def summarize(rows, tag):
    good = True
    nonef = [row for row in rows if row[3] is None]
    good &= check(f"{tag}: every prime has a trinomial below 12 sqrt(M): "
                  f"{len(rows) - len(nonef)} of {len(rows)}", not nonef)
    zc = [zmid(n_c, j, r, M) for r, _, M, j, *_ in rows if j is not None]
    zt = [zmid(n_t, j, r, M) for r, _, M, j, *_ in rows if j is not None]
    mc, mt = sum(zc) / len(zc), sum(zt) / len(zt)
    sdc = math.sqrt(sum((z - mc) ** 2 for z in zc) / (len(zc) - 1))
    print(f"  {tag}: Z cluster mean over {len(zc)} primes: {mc:.4f} "
          f"(sample sd {sdc:.3f}, of the mean {sdc / math.sqrt(len(zc)):.4f})")
    print(f"  {tag}: Z tuple mean: {mt:.3f}")
    for arm in ("spread", "corner"):
        za = [zmid(n_c, j, r, M) for r, a, M, j, *_ in rows
              if a == arm and j is not None]
        print(f"  {tag}: Z cluster mean, {arm} arm ({len(za)}): "
              f"{sum(za) / len(za):.4f}")
    print(f"  {tag}: Z cluster mean by r: " + ", ".join(
        f"{r} {sum(zmid(n_c, j, rr, M) for rr, _, M, j, *_ in rows if rr == r) / sum(1 for row in rows if row[0] == r):.3f}"
        for r in RS))
    keep = [row for row in rows if not row[6]]
    ex = sum(row[4] for row in keep)
    mod = sum(n_c(row[5], row[0], row[2]) for row in keep)
    print(f"  {tag}: count ratio exact/N_C at J* = 2 sqrt(M), "
          f"{len(keep)} of {len(rows)} primes kept (O > J* + t; no filter "
          f"on the plant): "
          f"{ex} / {mod:.1f} = {ex / mod:.4f}")
    za = [zmid(n_c, j, r, M) for r, a, M, j, *_ in rows if a == "corner"]
    return good, mc, sum(za) / len(za), ex / mod, mt


def main():
    good = True
    # C1: the hand count at M = 31.
    M, r, t = 31, 5, 6
    res = powers(M, 200)
    cnt = [engine(M, r, t, res, J)[1] for J in range(1, 6)]
    jm = engine(M, r, t, res, 5)[0]
    good &= check(f"C1 M 31, r 5, t 6: clusters with j <= 1..5 {cnt}, "
                  f"j_min {jm} (hand: [1, 1, 1, 2, 4], 1)",
                  cnt == [1, 1, 1, 2, 4] and jm == 1)
    # C2: N_C's closed form against its pair count.
    off = [(r, J) for r in RS for J in range(0, 301, 7)
           if 4 * n_c_brute(J, r, r + 1) != round(n_c(J, r, 1))]
    good &= check(f"C2 N_C's closed form = the pair count at r 12..20, "
                  f"J 0..300 step 7: {len(off)} off", not off)
    fam = family()
    print(f"  family: {len(fam)} primes")
    # C3: the plant, read through the same filter first.
    g, mc, mcor, rat, _ = summarize(run_family(fam, plant=True), "C3 plant")
    good &= g
    good &= check(f"C3 plant: Z cluster mean {mc:.4f} in [0.9, 1.1], count "
                  f"ratio {rat:.4f} in [0.95, 1.05]",
                  0.9 <= mc <= 1.1 and 0.95 <= rat <= 1.05)
    if not good:
        print("controls failed: no verdict")
        return 1
    # P1: the reduction against shiftpar.witness at 12 bits.
    p12 = [(r, M) for r, _, M in fam if r == 12]
    off = []
    for r, M in p12:
        t = r + 1
        lmax = int(4 * math.sqrt(M))
        w = witness(M, t, r, lmax)
        wj = w[3] if isinstance(w, tuple) else w
        jm = engine(M, r, t, powers(M, lmax + t + 2), lmax)[0]
        if wj != jm:
            off.append((M, wj, jm))
    good &= check(f"P1 trinomial j_min = witness's least j at {len(p12) - len(off)}"
                  f" of {len(p12)} 12-bit primes", not off)
    # P2: tuple counts against the direct congruence.
    off = []
    for r, M in p12:
        t = r + 1
        ntu = engine(M, r, t, powers(M, 40 + t + 2), 40, jt=40)[2]
        if ntu != direct_tuples(M, r, t, 40):
            off.append(M)
    good &= check(f"P2 cluster-summed misses = direct count, j <= 40, at "
                  f"{len(p12) - len(off)} of {len(p12)} 12-bit primes", not off)
    # P3 and the kill.
    g, mc, mcor, rat, mt = summarize(run_family(fam, plant=False), "P3")
    good &= g
    print(f"KILL Z cluster mean over the family: {mc:.4f} "
          f"({'held' if 0.9 <= mc <= 1.1 else 'STRUCTURE'}, band [0.9, 1.1])")
    print(f"KILL Z cluster mean, corner arm: {mcor:.4f} "
          f"({'held' if 0.75 <= mcor <= 1.25 else 'STRUCTURE'}, band [0.75, 1.25])")
    print(f"KILL count ratio: {rat:.4f} "
          f"({'held' if 0.95 <= rat <= 1.05 else 'DEAD'}, band [0.95, 1.05])")
    print(f"P3 tuple model's Z mean {mt:.3f} (frozen: above 5)")
    good &= check("KILL held at all three bands, the tuple mean above 5",
                  0.9 <= mc <= 1.1 and 0.75 <= mcor <= 1.25
                  and 0.95 <= rat <= 1.05 and mt > 5)
    # P4: the paper's moduli. At 125 = 5^3, a primitive root's powers are
    # uniform on the 100 units; 2^(v-u) + s1 is a unit at 3 of its 4
    # classes mod 5 and must meet one unit: the rate is 3/400, not 1/M.
    for M, r, lmax, rate in ((125, 7, 60, (3, 400)), (32749, 15, 400, None),
                             (2147483629, 31, 40000, None)):
        t = r + 1
        jm = engine(M, r, t, powers(M, lmax + t + 2), lmax)[0]
        w = witness(M, t, r, lmax)
        wj = w[3] if isinstance(w, tuple) else w
        nc, nt = n_c(jm - 1, r, M), n_t(jm - 1, r, M)
        if rate:
            assert pow(2, 100, M) == 1 and all(pow(2, 100 // q, M) != 1
                                               for q in (2, 5))
            nc = nc * M * rate[0] / rate[1]
        print(f"P4 M {M}: j_min {jm} (witness {wj}), "
              f"rate {'%d/%d' % rate if rate else '1/M'}, N_C(j-1) {nc:.4f}, "
              f"P_C {math.exp(-nc):.3f}; N_T(j-1) {nt:.3f}, "
              f"P_T {math.exp(-nt):.2e}")
        good &= check(f"P4 M {M}: trinomial = witness, P_C in [0.05, 0.95]",
                      jm == wj and 0.05 <= math.exp(-nc) <= 0.95)
    return 0 if good else 1


if __name__ == "__main__":
    sys.exit(main())