closure.py

Checks: BONACCI: The closing carry theorem; property; rule.

Cited on: BONACCI.

To run it: save closure.py; standard library only.

"""
closure.py -- the 0/1 representations of S's prefix values: S with the
e_1 excursions alone, at every d >= 4?

QUESTION. y = S^inf, S = 1 0^(d+1) 1^(d-3) 0 1 0 low digit first, P =
2d + 2, q_n = 2^n (n < d), q_n = q_(n-1) + ... + q_(n-d) (n >= d). A
0/1 string y' is carried to S^inf by an integer x (y - y' = Delta(F)x,
first window sum 0, legality dropped). Summing q_s (Delta(F)x)_s over s < N:

    v'_N = v_N + sum_(i<d) x_(N+i) R_(N,i),  R_(N,i) = q_(N+i-d) + ...
    + q_(N-1),

v_N, v'_N the values of the first N digits (x_n's coefficient is 0 at
d <= n < N and 1 at n < d, the first window sum 0). So a zero window
W_N makes y'[0, N) a 0/1 representation of the legal prefix value v_N.

BY HAND (before the script). (R) Every 0/1 string of value n reaches
the legal one by carries 1^d 0 -> 0^d 1 at its topmost 1^d (a 0 or the
top above it; the digit sum falls by d - 1; the legal string is
unique), so the representations of n are the closure of the legal one
under uncarries 0^d 1 -> 1^d 0 at j >= d. (S) A 1 at j >= d is
uncarried iff the d digits below it are 0. In a period of S the 1s sit
at 0, d + 2..2d - 2 and 2d: the 1 at 0 has the 1 at 2d two below, the
1 at m = d + 2 the zeros at 2..d + 1, each later 1 of the run a 1 one
below, and the 1 at 2d the 1 at 2d - 2 two below (d >= 4). After the
excursion at m the 1s of that period sit at 0, 2..d + 1, d + 3..2d - 2
and 2d: the 1 at 2 has the 1 at 0 two below, each of 3..d + 1 a 1 one
below, the 1 at d + 3 the 1 at d + 1 two below, each later 1 of the run
a 1 one below as before, and the 1 at 2d the 1 at 2d - 2 two below at
d >= 5 and the 1 at d + 1 three below at d = 4.
An excursion writes its own period's 2..d + 2 alone, and the 1 at 0 of
the next period reads no lower than d + 2, where the 1 at 2d stands
either way. So after excursions at any set of m no uncarry applies but
an excursion at another m, and the representations of v_N are S[0, N)
with the excursion at any subset of the m with m < N, 2^k of them, k =
#{m < N}. THEOREM: if the windows of (S^inf, y') vanish at infinitely
many N, y' is S^inf with the e_1 carry at some of its 0^(d+1) runs, at
every d >= 4.

FROZEN (before the run).
  PRINT, d = 4..7, every N up to 20 (2^20 strings): the count of 0/1
    strings of length N with value v_N, against 2^k, and the set
    against the excursion strings.
  KILL: a count or a set differing at some (d, N).
  CONTROL C1, read first: (R) itself, the brute-force representations
    of 40 seeded n < q_(N-1) at d = 4, N = 18, against the uncarry closure
    of n's legal string, set for set. C2, the comparator fires: at
    d = 3 (outside the theorem, the 1 at 2d - 2 = 4 missing from S's
    run 1^(d-3)), some N prints a count other than 2^k.

CHANGED FROM THE FROZEN (named). C2 at d = 3 fired by construction:
there m = d + 2 holds a 0 in S, so excursions() wrote strings of
another value (101110, value 25, against v = 1 at N = 6). It is
replaced by a plant through the KILL's own loop and comparator, read
before the kill: at d = 4 the largest excursion string dropped from
each set of two or more, which must fire (a first replacement, compared
outside that loop, passed by set identity and read nothing).

THE SECOND ENGINE. The first, the frozen block's, read a table of all
2^20 strings: two excursions side by side only at d = 4 from N = 17
and at d = 5 at N = 20, and one at d = 6, 7; its cost was its table.
The kill is kept as frozen and read without one. C1 is read at every
n at N <= 12, d = 2, 3, 4, where it was 40 seeded n at d = 4, N = 18;
C2's plant is cut, the hand rows where the comparator must say no in
its place.

ARMS. reps(q, v) lists every 0/1 string of length len(q) and value v by
descent from the top digit, a branch left only where the rest is
negative or above the sum of the weights still to come, where no
string completes it: so it loses none, and it uses neither (R) nor (S).
row(d, y), for any 0/1 string y, is (k, the strings of y's value, the
excursion strings of y, the strings in both), the excursion strings y
with ones written at m - d..m - 1 and a 0 at m over every set of the m
= d + 2 mod P below len(y), k their number. A row holds iff the three
counts are one number, the two sets then equal. sweep reads the row of
S[0, N) at every N = 1..3P.

CONTROLS, read first, a failure stopping the run. Every hand value was
fixed before the run that read it, those the second CHANGED block
names after the engine was written, the rest before.
  - The weights at d = 2, 3, 4 and the word at d = 4 and 6, digit by
    digit;
    v_20 = 1 + 56 + 208 + 773 + 39648 + 147312 = 187998 at d = 4.
  - reps against the table of all 2^N strings sorted by value, at
    every value 0..q_0 + ... + q_(N-1), each some string's (a value
    with none counts against), d = 2, 3, 4, N = 1..12: 8190
    strings a d (2 + 4 + ... + 4096); on (1, 2, 3, 5, 8) no string
    of value -1 or 20, one of 0 and one of 19.
  - d = 2, weights (1, 2, 3, 5, 8): 8 = 5 + 3 = 5 + 2 + 1, the strings
    00001, 00110, 11010, and the uncarry closure of 00001 the same
    three (at 4, then at 2; in 11010 the 1 at 3 sits on the 1 at 1).
  - (R) itself: reps against the uncarry closure of the legal string
    at every n < q_N, d = 2, 3, 4, N = 1..12: 984, 3734 and 5966
    values, the sums of q_1..q_12 (those at N <= d, where nothing
    uncarries, among them).
  - Rows by hand. d = 4, S[0, 7) = 1000001, value 57: with 56 the rest
    is 1, without it 59 loses 2 one way, so 1000001 and 1011110, the
    excursion at 6: (1, 2, 2, 2). d = 4, S[0, 20), ones at 0, 6, 8, 10,
    16, 18: the 1s at 6 and 16 alone have four zeros below, and after
    either excursion the 1 at 8 or 18 sits three above a new one, so
    by the closure four strings: (2, 4, 4, 4). d = 3, outside the
    theorem (S has no 1 at m =
    5): S[0, 6) = 100000 has value 1 and one string, and the excursion
    written over it, 101110, has value 25: (1, 1, 2, 1). S[0, 7) =
    1000001 has value 45 = 44 + 1 = 1 + 7 + 13 + 24, so 1000001 and
    1001110, an uncarry at 2d and no excursion, beside the written
    1011101: (1, 2, 2, 1). d = 4, y = 100000100001, no prefix of S,
    value 1547: its 1 at 11 has four zeros below, an uncarry no
    excursion is, so four strings, 100000100001, 101111000001,
    100000111110, 101111011110, the first two the excursion strings:
    (1, 4, 2, 2), a representation no excursion gives, the theorem's
    own failure. Of the five the first two hold; the third fails the
    excursion strings' clause alone, the fifth the representations'
    alone; their tally is 2 held of 5, four rows at k = 1 and one at
    2, 13 strings of the values and 12 excursion strings.
  - The sweep at d = 3, N = 1..24: from N = 6 on an excursion string
    has another value, so 5 rows of 24 hold, N = 1..5.

PREDICTIONS AND KILL (the second engine's, fixed before it was
written).
  PRINT: "held n of 858" over the rows d = 4..16, N = 1..6d + 6; the
    rows by k; the strings.
  KILL: n < 858.
  PINS, by hand: k is 0 at N <= d + 2, 1 to 3d + 4, 2 to 5d + 6 and 3
    to 6d + 6, so d + 2, 2d + 2, 2d + 2 and d rows at a d, and over d =
    4..16 (their sum 130) 156, 286, 286 and 130 rows, 858; the strings
    21d + 14 at a d, 2912.
  PREDICTED: held 858 of 858; 2912 strings of the values and 2912
    excursion strings.

CHANGED FROM THE FROZEN (the second engine's, named). The list of
breaks written before the first run called the upper cut's removal
harmless; it is not, the bottom of the descent reading the rest by the
same cut: it fails the 14 lines that read reps before the sweep at d =
3, which the uncut descent then ends at the memory cap. The row at N =
20 was frozen as the theorem's prediction; its derivation by the
closure was written at the draft's read, after the row had printed.
Added with the breaks: the word at d = 6. Added at the draft's read,
each hand value before its run: the five rows' tally, since the two
sums of strings were read only where they are one number; the line at
d = 3, N = 6; the line a d, in place of a count of the rows that the
kill's line reads. Added at the first run of the mutation meter, for a
survivor: a value with no string counts against reps in the table's
control.

FINDINGS (copied from the prints).
  - The controls hold, each hand value as written: reps is the table's
    set at 1580, 4443 and 6428 values at d = 2, 3, 4, 8190 strings
    each; the legal string's closure at 984, 3734 and 5966 n; the five
    hand rows (1, 2, 2, 2), (2, 4, 4, 4), (1, 1, 2, 1), (1, 2, 2, 1),
    (1, 4, 2, 2), the first two holding; the sweep at d = 3 at 5 of
    24.
  - The KILL misses: held 858 of 858, the 6d + 6 rows at each of the
    13 d, 156, 286, 286 and 130 rows at k = 0, 1, 2, 3, 2912 strings
    of the values and 2912 excursion strings. At d = 4..16 and every N
    = 1..6d + 6 the 0/1 strings of length N and value v_N are exactly
    the excursion strings, up to three excursions side by side. A
    finite check of (S); (R) and (S) are the proof, and with the
    prefix identity they prove the THEOREM at every d >= 4. Left open:
    a pair whose windows are nonzero from some N on, a carry that
    never closes.
  - The first engine read the same at d = 4..7, N = 1..20, up to 2
    excursions at d = 4, 5 and 1 at d = 6, 7: its C1 at 40 seeded n, 0
    differing, its C2 firing at 14 N, first (N, brute, plant) (7, 2,
    1), (8, 2, 1).

RUN RECORD: python closure.py 6/6, peak commit 342.1 MB, wall 0.7 s
(the memory guard's clock); with C2 through the KILL's loop 6/6,
342.0 MB, 0.6 s.
The second engine: python closure.py 25/25, 0.2 s, peak commit 9.4 MB
under a 512 MB cap; the draft's first run 23/23, 0.2 s. The mutation
meter, every one-token and structural change of its functions, 128,
each run: 125 red, 3 moving no line, each equivalent (a mask's 1 read
for its truth alone; the legal string's loop one index past the
bottom, the rest 0 there; one weight more than the lemma reads); the
line count's check failed by none. 33 breaks by hand, each one edit,
32 of them run twice, the second with the controls' stop lifted: 32
red, one by the memory cap as well, 1 green as predicted (the table's
control forgiving a value with no string, which these weights never
have).

USAGE. python closure.py
"""
import itertools
import sys
import time

DS = range(4, 17)
PERIODS = 3
SMALL = (2, 3, 4)
TOP = 12
RECORD = {
    "rows": 858,
    "by_k": {0: 156, 1: 286, 2: 286, 3: 130},
    "strings": 2912,
    "table": {2: 8190, 3: 8190, 4: 8190},
    "lemma": {2: 984, 3: 3734, 4: 5966},
}
LINES = 25
CHECKS = []


def weights(d, N):
    q = []
    for n in range(N):
        q.append(2 ** n if n < d else sum(q[n - d:n]))
    return q


def word(d):
    return [1] + [0] * (d + 1) + [1] * (d - 3) + [0, 1, 0]


def prefix(d, N):
    S = word(d)
    return tuple(S[n % len(S)] for n in range(N))


def value(z, q):
    return sum(w for bit, w in zip(z, q, strict=True) if bit)


def digits(text):
    return tuple(int(c) for c in text)


def reps(q, v):
    """Every 0/1 string, low digit first, of length len(q) and value v."""
    below = [0]
    for w in q:
        below.append(below[-1] + w)
    out, todo = set(), [(len(q), v, ())]
    while todo:
        j, rest, top = todo.pop()
        if not 0 <= rest <= below[j]:
            continue
        if j == 0:
            out.add(top)
            continue
        for bit in (0, 1):
            todo.append((j - 1, rest - bit * q[j - 1], (bit,) + top))
    return out


def table(q):
    """value -> its strings, over all 2^len(q) strings."""
    out = {}
    for z in itertools.product((0, 1), repeat=len(q)):
        out.setdefault(value(z, q), set()).add(z)
    return out


def against_table(d, N):
    """(values where reps is the table's set, values, strings reps
    lists) over the values 0..sum(q), each some string's."""
    q = weights(d, N)
    t = table(q)
    agree = values = strings = 0
    for v in range(sum(q) + 1):
        got = reps(q, v)
        values += 1
        strings += len(got)
        agree += got == t.get(v)
    return agree, values, strings


def legal_of(n, q):
    z = [0] * len(q)
    for j in range(len(q) - 1, -1, -1):
        if q[j] <= n:
            z[j], n = 1, n - q[j]
    return tuple(z)


def closure(z, d):
    seen, todo = {z}, [z]
    while todo:
        s = todo.pop()
        for j in range(d, len(s)):
            if s[j] == 1 and not any(s[j - d:j]):
                t = s[:j - d] + (1,) * d + (0,) + s[j + 1:]
                if t not in seen:
                    seen.add(t)
                    todo.append(t)
    return seen


def lemma(d, N):
    """(R): (the n where reps is the uncarry closure of the legal
    string, the n) over n < q_N."""
    q = weights(d, N + 1)
    q, top = q[:N], q[N]
    agree = count = 0
    for n in range(top):
        count += 1
        agree += reps(q, n) == closure(legal_of(n, q), d)
    return agree, count


def excursions(d, y):
    """(y with the excursion written at every set of the m = d + 2 mod
    2d + 2 below len(y), the number of those m)."""
    ms = list(range(d + 2, len(y), 2 * d + 2))
    out = set()
    for some in itertools.product((0, 1), repeat=len(ms)):
        z = list(y)
        for on, m in zip(some, ms, strict=True):
            if on:
                z[m - d:m + 1] = [1] * d + [0]
        out.add(tuple(z))
    return out, len(ms)


def row(d, y):
    q = weights(d, len(y))
    got = reps(q, value(y, q))
    want, k = excursions(d, y)
    return k, len(got), len(want), len(got & want)


def holds(r):
    _, n_reps, n_exc, n_both = r
    return n_reps == n_both and n_exc == n_both


def sweep(ds, periods):
    return {(d, N): row(d, prefix(d, N))
            for d in ds for N in range(1, periods * (2 * d + 2) + 1)}


def tally(rec):
    """(rows that hold, rows, rows by k, strings of the values,
    excursion strings)."""
    held = n_reps = n_exc = 0
    by_k = {}
    for r in rec.values():
        held += holds(r)
        by_k[r[0]] = by_k.get(r[0], 0) + 1
        n_reps += r[1]
        n_exc += r[2]
    return held, len(rec), by_k, n_reps, n_exc


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


def section_hand():
    print("CONTROLS: the weights and the word, by hand", flush=True)
    q4 = [1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536,
          10671, 20569, 39648, 76424, 147312, 283953]
    check("the weights at d = 4 to q_19, at d = 3 to q_6, at d = 2 to q_4",
          (weights(4, 20), weights(3, 7), weights(2, 5))
          == (q4, [1, 2, 4, 7, 13, 24, 44], [1, 2, 3, 5, 8]),
          f"q_19 = {weights(4, 20)[-1]} at d = 4")
    y20 = prefix(4, 20)
    check("S = 1000001010 at d = 4 and 10000000111010 at d = 6, and "
          "S[0, 20) twice the first",
          (tuple(word(4)), tuple(word(6)), y20)
          == (digits("1000001010"), digits("10000000111010"),
              digits("10000010101000001010")),
          "".join(map(str, y20)))
    check("v_20 = 187998 at d = 4", value(y20, q4) == 187998,
          f"{value(y20, q4)}")

    print("CONTROLS: reps against the table of all 2^N strings", flush=True)
    for d in SMALL:
        got = [against_table(d, N) for N in range(1, TOP + 1)]
        agree, values, strings = (sum(g[i] for g in got) for i in range(3))
        check(f"d = {d}: reps is the table's set at every value, N = 1..12",
              agree == values and strings == RECORD["table"][d],
              f"{agree} of {values} values, {strings} strings")
    q2 = [1, 2, 3, 5, 8]
    check("no string of value -1 or 20 on (1, 2, 3, 5, 8), one of 0 and 19",
          [len(reps(q2, v)) for v in (-1, 20, 0, 19)] == [0, 0, 1, 1],
          f"{[len(reps(q2, v)) for v in (-1, 20, 0, 19)]}")

    print("CONTROLS: (R), the uncarry closure", flush=True)
    three = {digits("00001"), digits("00110"), digits("11010")}
    check("d = 2: 8 is 00001, 00110, 11010", reps(q2, 8) == three,
          f"{sorted(''.join(map(str, z)) for z in reps(q2, 8))}")
    check("d = 2: the legal string of 8 is 00001, its closure the three",
          legal_of(8, q2) == digits("00001")
          and closure(digits("00001"), 2) == three,
          f"{len(closure(digits('00001'), 2))} strings")
    for d in SMALL:
        got = [lemma(d, N) for N in range(1, TOP + 1)]
        agree, count = (sum(g[i] for g in got) for i in range(2))
        check(f"d = {d}: reps is the legal string's closure at every "
              f"n < q_N, N = 1..12",
              agree == count == RECORD["lemma"][d], f"{agree} of {count}")

    print("CONTROLS: rows by hand", flush=True)
    q7 = weights(4, 7)
    two = {digits("1000001"), digits("1011110")}
    check("d = 4, S[0, 7): value 57, its strings 1000001 and 1011110, "
          "the excursion strings too",
          (value(prefix(4, 7), q7), reps(q7, 57), excursions(4, prefix(4, 7)))
          == (57, two, (two, 1)), f"row {row(4, prefix(4, 7))}")
    odd = digits("100000100001")
    four = {odd, digits("101111000001"), digits("100000111110"),
            digits("101111011110")}
    check("d = 4, 100000100001: value 1547, four strings by hand, the "
          "first two the excursion strings",
          (value(odd, weights(4, 12)), reps(weights(4, 12), 1547),
           excursions(4, odd)[0])
          == (1547, four, {odd, digits("101111000001")}),
          f"row {row(4, odd)}")
    q3 = weights(3, 7)
    check("d = 3, S[0, 6): value 1, the written 101110 of value 25",
          (value(prefix(3, 6), q3[:6]), excursions(3, prefix(3, 6))[0],
           value(digits("101110"), q3[:6]))
          == (1, {digits("100000"), digits("101110")}, 25),
          f"row {row(3, prefix(3, 6))}")
    check("d = 3, S[0, 7): value 45, its strings 1000001 and 1001110, "
          "the written ones 1000001 and 1011101",
          (value(prefix(3, 7), q3), reps(q3, 45),
           excursions(3, prefix(3, 7))[0])
          == (45, {digits("1000001"), digits("1001110")},
              {digits("1000001"), digits("1011101")}),
          f"row {row(3, prefix(3, 7))}")
    hand = [(4, prefix(4, 7), (1, 2, 2, 2)), (4, y20, (2, 4, 4, 4)),
            (3, prefix(3, 6), (1, 1, 2, 1)), (3, prefix(3, 7), (1, 2, 2, 1)),
            (4, odd, (1, 4, 2, 2))]
    rows = [row(d, y) for d, y, _ in hand]
    check("the five hand rows", rows == [r for _, _, r in hand], f"{rows}")
    check("of the five the first two hold",
          [holds(r) for r in rows] == [True, True, False, False, False],
          f"{[holds(r) for r in rows]}")
    five = tally(dict(enumerate(rows)))
    check("the five's tally: 2 held of 5, k = 1 four times and 2 once, "
          "13 strings and 12",
          five == (2, 5, {1: 4, 2: 1}, 13, 12), f"{five}")
    rec3 = sweep([3], PERIODS)
    held, n, _, _, _ = tally(rec3)
    check("d = 3: the sweep holds at N = 1..5 alone, of 24",
          (held, n) == (5, 24)
          and [N for (_, N), r in rec3.items() if holds(r)] == [1, 2, 3, 4, 5],
          f"{held} of {n}")


def section_sweep(rec):
    held, n, by_k, n_reps, n_exc = tally(rec)
    print("\nTHE SWEEP: the strings of v_N against the excursion strings, "
          f"d = {DS[0]}..{DS[-1]}, N = 1..6d + 6", flush=True)
    good = 0
    for d in DS:
        mine = {key: r for key, r in rec.items() if key[0] == d}
        h, m, _, a, b = tally(mine)
        good += (h, m, a, b) == (6 * d + 6, 6 * d + 6, 21 * d + 14,
                                 21 * d + 14)
        print(f"    d = {d:2d}: held {h} of {m}, {a} strings", flush=True)
    check("at each d the 6d + 6 rows hold, 21d + 14 strings of the "
          "values and as many excursion strings", good == len(DS),
          f"{good} of {len(DS)} d")
    check("the rows by k are 156, 286, 286, 130", by_k == RECORD["by_k"],
          f"{sorted(by_k.items())}")
    check("2912 strings of the values, 2912 excursion strings",
          n_reps == n_exc == RECORD["strings"], f"{n_reps} and {n_exc}")
    check("KILL misses: every row holds", held == n == RECORD["rows"],
          f"held {held} of {n}")


def main():
    t_all = time.time()
    section_hand()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    section_sweep(sweep(DS, PERIODS))
    ran = len(CHECKS)
    check("every check line of the run printed, this one aside",
          ran == LINES - 1, f"{ran} of {LINES - 1}")
    print()
    print("%d of %d checks, %.1f s"
          % (sum(CHECKS), len(CHECKS), time.time() - t_all))
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()