height_ceiling.py

Checks: GATES: The height floor theorem; rule.

Cited on: GATES.

To run it: save height_ceiling.py, with gates.py beside it; standard library only.

"""height_ceiling.py -- is the height of a graded constant of order log p from
above?

QUESTION. On F_p, p >= 5, the height h_p(c) is the fewest operations
(MUL, INV the meadow inverse, NOT x = 1 - x) in a one-leaf word tree
reading c at every unit x other than 1. A count bounds max_c h_p(c)
below by f_p, of order log p. Is it of order log p from above, and at
what constant?

BY HAND (before any engine code). Words are trees, so a subword used
twice is paid twice. w_1 = MUL(x, INV x) costs 2, w_0 = NOT w_1 3,
m = MUL(MUL(NOT(INV x), INV(NOT x)), x) = -1 costs 6, w_2 = NOT m 7.
On an integer y: y = 2z gives w_y = MUL(w_2, w_z), w_z's cost + 8;
y = 1 - 2z gives w_y = NOT(MUL(w_2, w_z)), + 9. Read y from the bottom: y
even, z = y/2; y odd, z = (1 - y)/2. Both give |z| <= (|y| + 1)/2, so
v = |y| - 1 has v' <= floor(v/2), and |y| <= 1 comes within
floor(log2 v_0) + 1 steps. With c's balanced representative,
|y| <= (p - 1)/2, v_0 <= (p - 3)/2: at most floor(log2(p - 3)) steps,
each at most 9, ending at -1 (6; a graded c never reaches 0 or 1), or
earlier at 2 (7, under the 10 that 2 -> 1 costs). So for p >= 5

    max_c h_p(c) <= 9 floor(log2(p - 3)) + 6,

against the 16 floor(log2 c) - 1, c >= 2, that doubling and adding
one at 8 operations each give.
The words are integer words, one word per integer y at every p.

PREDICTIONS. (a) word(c) reads c at every graded x, every graded c,
every prime 5 <= p <= 199 (strongly: a proof). (b) its op count is
under the ceiling at every one (strongly). (c) at p = 5 and 7 it is at
least the exact heights (it must be: they are least). (d) the largest
op count at a p over log2 p sits between 7 and 9 near p = 199, the
odd-step chain y -> 1 - 2y (-1, 3, -5, 11, -21, 43, -85) setting the
worst c (weakly).

KILL (frozen; what the script PRINTS): "H5 word(c): X misreads, Y over
the ceiling, p = 5..199"; it fires iff X > 0 or Y > 0.

CONTROLS (read first). POSITIVE: at p = 5 and 7, ops(word(c)) >= the
exact search's h_p(c) at every graded c, and word(-1) is m at 6
operations. PLANT: the builder with w_2's word replaced by a word
reading 3 must misread somewhere in the family (it enters every step,
so it is one break per step).

FINDINGS. The kill misses; every prediction held but (d)'s chain,
which sets the worst at some primes only.
  "H5 word(c): 0 misreads, 0 over the ceiling, p = 5..199". POSITIVE:
  built {2: 7, 3: 14, 4: 6} against exact {2: 7, 3: 7, 4: 6} at p = 5,
  {2: 7, 3: 15, 4: 16, 5: 14, 6: 6} against {2: 7, 3: 11, 4: 8, 5: 11,
  6: 6} at p = 7. PLANT: "541556 misreads". (d): "p = 197: worst
  c = 112 (y = -85), 60 ops, ceiling 69, ops/log2 p = 7.87", p = 199
  the same y at 7.86, -85 on the odd-step chain; "p = 131: worst
  c = 66 (y = -65), 56 ops, ceiling 69, ops/log2 p = 7.96"; over the
  family "ops/log2 p at p = 131..199: 7.86 (p = 199) to 8.15 (p =
  151)". "the worst ops reached on the chain [...] at 17 of 44 primes",
  11, 13, 23, 43, 47, 53, 89 to 103 and 173 to 199. "least slack under
  the ceiling: 1, at p = [5]"; "slack past p = 5: 3 (p = 17) to 13
  (p = 131), over 43 primes"; by hand, y = -8 at p = 17 costs
  3 * 8 + 6 = 30 in three steps, the bound's step count. 2/2 checks, 10.0 s,
  10.9 MB peak commit (the first run).
  ADDED after the run: the full-family prints above and a second
  plant, the ceiling lowered by one step (9), which the kill's "over"
  arm must catch: "13 over, at 11 of 44 primes"; and the kill as a
  check reaching the exit code. 4/4 checks, 13.2 s, 10.1 MB.

RUN: python height_ceiling.py.
"""
import os
import sys
import time
from math import log2

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
from gates import ev, heights  # noqa: E402

CHECKS = []
TOP = 199
X = "x"
W1 = ("MUL", X, ("INV", X))
W0 = ("NOT", W1)
M = ("MUL", ("MUL", ("NOT", ("INV", X)), ("INV", ("NOT", X))), X)
W2 = ("NOT", M)
W3 = ("NOT", ("MUL", W2, M))          # 1 - 2(-1) = 3: the plant's word


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    tail = f"  ({detail})" if detail else ""
    print(f"  {'PASS' if ok else 'FAIL'}  {name}{tail}", flush=True)


def ops(w):
    return 0 if w == X else 1 + sum(ops(a) for a in w[1:])


def word(y, two=W2):
    """The integer word for y: doubling and 1 - 2z from the bottom bit."""
    if y == 1:
        return W1
    if y == 0:
        return W0
    if y == -1:
        return M
    if y == 2 and two is W2:
        return W2
    if y % 2 == 0:
        return ("MUL", two, word(y // 2, two))
    return ("NOT", ("MUL", two, word((1 - y) // 2, two)))


def balanced(c, p):
    return c if 2 * c < p else c - p


def primes(lo, hi):
    return [q for q in range(lo, hi + 1)
            if q > 1 and all(q % d for d in range(2, int(q ** 0.5) + 1))]


def ceiling(p):
    return 9 * ((p - 3).bit_length() - 1) + 6


def family(two=W2, shift=0):
    """(misreads, over, rows): rows (p, worst c, its ops, ceiling, every
    y at the worst ops); shift moves the ceiling (the plant's arm)."""
    mis = over = 0
    rows = []
    for p in primes(5, TOP):
        worst = (0, None)
        cost = {}
        for c in range(2, p):
            w = word(balanced(c, p), two)
            n = ops(w)
            cost[balanced(c, p)] = n
            mis += sum(ev(w, x, p) != c for x in range(2, p))
            over += n > ceiling(p) + shift
            worst = max(worst, (n, c))
        tied = sorted(y for y, n in cost.items() if n == worst[0])
        rows.append((p, worst[1], worst[0], ceiling(p), tied))
    return mis, over, rows


if __name__ == "__main__":
    t0 = time.time()
    print("CONTROLS")
    ok = True
    for p in (5, 7):
        h = heights(p)
        built = {c: ops(word(balanced(c, p))) for c in range(2, p)}
        ok &= all(built[c] >= h[c] for c in h)
        print(f"  p = {p}: exact {dict(sorted(h.items()))}, built "
              f"{dict(sorted(built.items()))}")
    check("POSITIVE: built >= exact at p = 5, 7; word(-1) is m at 6",
          ok and word(-1) is M and ops(M) == 6)
    pm, _, _ = family(two=W3)
    check("PLANT: w_2 replaced by a word reading 3 misreads",
          pm > 0, f"{pm} misreads")
    _, po, rp = family(shift=-9)
    hit = [p for p, _, n, cap, _ in rp if n > cap - 9]
    check("PLANT: the ceiling lowered by one step is passed", po > 0,
          f"{po} over, at {len(hit)} of {len(rp)} primes")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    mis, over, rows = family()
    for p, c, n, cap, _ in rows:
        if p in (5, 7, 11, 13, 31, 61, 127, 131, 197, 199):
            print(f"  p = {p}: worst c = {c} (y = {balanced(c, p)}), "
                  f"{n} ops, ceiling {cap}, ops/log2 p = {n / log2(p):.2f}")
    slack = min(cap - n for _, _, n, cap, _ in rows)
    tight = [p for p, _, n, cap, _ in rows if cap - n == slack]
    print(f"  least slack under the ceiling: {slack}, at p = {tight}")
    past = sorted((cap - n, p) for p, _, n, cap, _ in rows if p > 5)
    print(f"  slack past p = 5: {past[0][0]} (p = {past[0][1]}) to "
          f"{past[-1][0]} (p = {past[-1][1]}), over {len(past)} primes")
    hi = [(n / log2(p), p) for p, _, n, _, _ in rows if p >= 131]
    print(f"  ops/log2 p at p = 131..{TOP}: {min(hi)[0]:.2f} (p = "
          f"{min(hi)[1]}) to {max(hi)[0]:.2f} (p = {max(hi)[1]})")
    chain = {-1, 3, -5, 11, -21, 43, -85}
    on = [p for p, _, _, _, t in rows if chain & set(t)]
    print(f"  the worst ops reached on the chain {sorted(chain)} at "
          f"{len(on)} of {len(rows)} primes: {on}")
    print(f"H5 word(c): {mis} misreads, {over} over the ceiling, "
          f"p = 5..{TOP}")
    print(f"KILL fires: {mis > 0 or over > 0}")
    check("H5 KILL: every word reads its c, none over the ceiling",
          mis == 0 and over == 0)
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)