erring_widths.py

Checks: SIZE: Growing widths property; observation.

Cited on: SIZE.

To run it: save erring_widths.py, with erring_label.py beside it; standard library only.

"""
erring_widths.py -- does a width profile growing with position err
below rounding's 1/10, and what does a cut set's reading become as the
cut set is scaled?

QUESTION. Fill [0, c) with m intervals below the overflow label
(N = 2c - 1), the error as in erring_label.py, kappa_m the limsup over
c of the least such error over c^2. Rounding (equal widths, one wide top
[uc, c)) errs on a quarter of its fine pairs and tends to 1/10
(erring_label.py's K7). Does a profile w(t) = g c (t/c)^p, widths at
least 1, err below 1/10, and does its reading e/c^2 hold as c grows?

THE ARGUMENT (written before this script). A cell of widths n1, n2
sums over an interval of width n1 + n2 at x + y, where the label has
width W(x + y); it errs nowhere unless a cut lies inside. Rounding has
n1 = n2 = W, a block twice its label.

DESIGN. profile cuts [0, U) at t -> t + max(1, round(g c (t/c)^p)),
U = c or a top cut round(u c) with [U, c) one wide label. profile_at
bisects g, geometrically from [1e-9, 1e3], to the first g that gives m
intervals: a case (c, p, m, u) names the cut set this search returns,
one of several with m intervals. Four cases: p = 1 at m = 162 and 400
and p = 2 at m = 400, top 0.8, built at c = 4000; p = 2 at m = 1000,
top 0.9, built at c = 10000. Each is read two ways: the same cut set
scaled by k, and the profile re-tuned at c/2.

THE SCALING LAW (derived from the first run's integers). Scale a cut
set by k. Every count in a cell, its pairs summing below N and its
pairs landing in one label, is a signed sum of t(t + 1)/2 at
arguments k s or k s - 1 (four terms, or a difference of two such
sums), s an integer, and zero where s <= 0: a quadratic in k
with no constant term. A cell errs on its pairs less its largest
label's, so the error over k is a sum of lines less maxima of lines:
concave and piecewise linear in k >= 1, and one line once each cell's
most frequent label has settled, its slope c^2 times the continuum
error, each k^2 coefficient an area. Twice that last slope is an
integer, areas(): over the cells, 2 n1 n2 less the largest label's
share, each share twice an area, a signed sum of squares of integers,
no scale and no float. Errors at three or more scales, k = 1 among
them, on one a k^2 - b k put the error over k on the line a k - b to
the last scale; past it the slope can only fall, so a/c^2 is at least
the continuum
error, and equals it where 2a = areas: the slope on the scales run is
then the last and the least, and the cut set errs a k^2 - b k at every
integer k >= 1.

PREDICTIONS AND KILLS (written before the run).
  W1 at fixed m the profile's e/c^2 moves under 2% from c = 2000,
     re-tuned, to c = 4000.
  K-floor: the lean "1/10 is the limit" dies if a profile prints
     e/c^2 < 0.095 at c = 4000 and within 2% at c = 2000.
  W2 (written after W1's prints) at m = 1000, c = 10000, a profile
     prints below 0.0785 (the m = 400, p = 2 reading), holding within
     2% scaled x2. Dies (the fall stalls) if it is above 0.0785.

FINDINGS (from the printed run; the seven controls passed first).
  K-floor fired: m = 400, p = 1, top 0.8 prints 0.0852 at c = 4000 and,
     re-tuned at c = 2000, 0.0837, 1.77% lower. 1/10 is rounding's
     limit, not a floor; this cut set's limit below, 0.08572, says it
     without the re-tuning.
  W1 failed at two of its three cases: re-tuned at c = 2000 the
     profiles print 2.06, 1.77 and 9.51% lower (m = 400, p = 2: 0.0710
     against 0.0785); the m = 1000 case, which W1 did not name, prints
     7.87% lower at c = 5000. A re-tuned reading is that of the cut set
     the search returns at c/2, one of several with m intervals, and no
     other is read here. The reading kappa_m needs is the same cut set scaled.
  W2 held on the row run: m = 1000, c = 10000, p = 2, top 0.9 prints
     0.0723, scaled x2 0.0731 (+1.03%), x4 0.0734. The comparison over
     other p and tops at m = 1000 is not run.
  The scaling law holds from k = 1 at all four cut sets, its a/c^2 the
     continuum error: each errs (areas k^2 - 2 b k)/2 at every scale
     run (x1, x2, x4, x8, x16; x1, x2, x4 at m = 1000), so at every
     k >= 1, b = 239, 9030, 23923 and 148951. A reading rises with the
     scale, by b/(k c^2) short of its limit (0.0785, 0.0793, 0.0796, 0.0798,
     0.0799 at m = 400, p = 2), and the limits, areas/(2 c^2), print
     0.09054, 0.08572, 0.08000 and 0.07380. A row's b and re-tuned
     error have no hand value: their check holds them to this script's
     first printed run, and that one b fits every scale of a row is the
     finding.
  The widths are a companding quantizer's (steps 1/G'(t), p = 1 the
  logarithmic compressor of mu-law), and only the constants are the
  run's.

CONTROLS. fast_error equals erring_label.error on all 561 cut sets at
N = 12, s = 2..5 (11 + 55 + 165 + 330) and, below the overflow label,
on the twelve profiles at c = 200 (p = 1, 2; g = 0.1, 0.3; top None,
0.8, 0.9). By hand: the error below the overflow label at the cuts
(0, 4), which is 6 (of the 16 pairs of [0, 4) squared, 10 sum below 4),
and at (0, 1, 4), which is 3 ([1, 4) squared sums to 2, 3, 3 below 4
and six times at 4 to 6); profile at c = 16, p = 1,
g = 0.5, where the width is t/2 and ties round to even, (0, 1, 2, 3, 5,
7, 11, 16), with a top cut at 12, which joins it, and at 11, where a
step lands on it and it is one cut, and at p = 2, g = 1, (0, 1, 2, 3,
4, 5, 7, 10, 16); profile_at at c = 4, p = 1, where the first step is 1
at every g: m = 4 at the first g tried, m = 3 as (0, 1, 2, 4) and not
(0, 1, 3, 4), m = 2 as (0, 1, 4), m = 1 and m = 5 missed; and 1/4 as
50% below 8/16. areas by hand: 16 at (0, 4) (of the cell's 32, [0, 4)
holds 16); 7 at (0, 1, 4) (the cells err 1, 1, 1 and 4); 48 at (0, 3,
6, 7, 9), c = 9 (9, twice 9, twice 2, twice 4, and 9 at [3, 6)
squared). That cut set errs 21 = 3 + 2 (3) + 2 (1) + 2 (3) + 4, and
91 = 15 + 2 (15) + 2 (4) + 2 (10) + 18 at twice the scale, by hand, so
its first two scales fit 2a = 91 - 42 = 49, one above its areas:
[3, 6) squared holds 5 pairs in [7, 9) and 3 in the overflow, whose
areas are 8 and 9. The rows' 22 errors are 6 + 6 + 6 + 4.
"""

from bisect import bisect_left, bisect_right

from erring_label import below, cutsets, error

CHECKS = []

# profile's cuts at (c, p, g, u) and profile_at's at (c, p, m), by hand
# (CONTROLS); the error below the overflow label, and areas, at (cuts,
# c), by hand.
HAND_PROFILE = {(16, 1, 0.5, None): (0, 1, 2, 3, 5, 7, 11, 16),
                (16, 1, 0.5, 0.75): (0, 1, 2, 3, 5, 7, 11, 12, 16),
                (16, 1, 0.5, 0.6875): (0, 1, 2, 3, 5, 7, 11, 16),
                (16, 2, 1.0, None): (0, 1, 2, 3, 4, 5, 7, 10, 16)}
HAND_AT = {(4, 1, 4): (0, 1, 2, 3, 4), (4, 1, 3): (0, 1, 2, 4),
           (4, 1, 2): (0, 1, 4), (4, 1, 1): None, (4, 1, 5): None}
HAND_OVER = {((0, 4), 4): 6, ((0, 1, 4), 4): 3,
             ((0, 3, 6, 7, 9), 9): 21, ((0, 6, 12, 14, 18), 18): 91}
HAND_AREAS = {((0, 4), 4): 16, ((0, 1, 4), 4): 7, ((0, 3, 6, 7, 9), 9): 48}

# (c, p, m, u) -> (the scales k, then b: twice the error of the cut set
# scaled by k is areas k^2 - 2 b k at each; then the error of the
# profile re-tuned at c/2). The two integers of a row are the first
# printed run's.
ROWS = {(4000, 1, 162, 0.8): ((1, 2, 4, 8, 16), 239, 354610),
        (4000, 1, 400, 0.8): ((1, 2, 4, 8, 16), 9030, 334600),
        (4000, 2, 400, 0.8): ((1, 2, 4, 8, 16), 23923, 284176),
        (10000, 2, 1000, 0.9): ((1, 2, 4), 148951, 1665615)}


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


def fast_error(cuts, N):
    """error(cuts, N), reading only the labels each cell's sums meet."""
    s = len(cuts) - 1
    E = 0
    for a in range(s):
        u1, n1 = cuts[a], cuts[a + 1] - cuts[a]
        for b in range(s):
            u2, n2 = cuts[b], cuts[b + 1] - cuts[b]
            base = u1 + u2
            if base >= N:
                continue
            tot = below(n1, n2, N - base)
            top = min(base + n1 + n2 - 2, N - 1)
            lo = bisect_right(cuts, base) - 1
            hi = bisect_right(cuts, top) - 1
            if lo == hi:
                continue
            best = 0
            for L in range(lo, hi + 1):
                k = (below(n1, n2, min(cuts[L + 1], N) - base)
                     - below(n1, n2, cuts[L] - base))
                best = max(best, k)
            E += tot - best
    return E


def over(cuts, c):
    """The error of cuts on [0, c) below one overflow label [c, 2c - 1)."""
    return fast_error(cuts + (2 * c - 1,), 2 * c - 1)


def area2(a, b, t):
    """Twice the area of {(x, y) in [0, a) x [0, b) : x + y < t}."""
    return (max(t, 0) ** 2 - max(t - a, 0) ** 2 - max(t - b, 0) ** 2
            + max(t - a - b, 0) ** 2)


def areas(cuts, c):
    """2 c^2 times the continuum error of cuts / c, overflow [1, 2): over
    the cells, twice the area less the largest label's share."""
    lab = cuts + (2 * c,)
    s = len(cuts) - 1
    A = 0
    for i in range(s):
        n1 = cuts[i + 1] - cuts[i]
        for j in range(s):
            n2 = cuts[j + 1] - cuts[j]
            base = cuts[i] + cuts[j]
            lo = bisect_right(lab, base) - 1
            hi = bisect_left(lab, base + n1 + n2) - 1
            A += 2 * n1 * n2 - max(area2(n1, n2, lab[L + 1] - base)
                                   - area2(n1, n2, lab[L] - base)
                                   for L in range(lo, hi + 1))
    return A


def lower(E1, c1, E2, c2):
    """By what percent E2 / c2^2 is below E1 / c1^2."""
    return 100 * (1 - (E2 * c1 * c1) / (E1 * c2 * c2))


def profile(c, p, g, u=None):
    """Cuts of the profile t -> t + max(1, round(g c (t/c)^p)) on [0, U),
    U = c or the top cut u c, then [U, c) as one top label."""
    U = c if u is None else round(u * c)
    cuts = [0]
    t = 0
    while True:
        t = t + max(1, round(g * c * (t / c) ** p))
        if t >= U:
            break
        cuts.append(t)
    cuts.append(U)
    if U < c:
        cuts.append(c)
    return tuple(cuts)


def profile_at(c, p, m, u=None):
    """A profile with m intervals, g found by bisection (None if missed)."""
    lo, hi = 1e-9, 1e3
    for _ in range(200):
        g = (lo * hi) ** 0.5
        k = len(profile(c, p, g, u)) - 1
        if k == m:
            return profile(c, p, g, u)
        if k > m:
            lo = g
        else:
            hi = g
    return None


def section_controls():
    print("controls")
    ok = n = 0
    for s in range(2, 6):
        for cu in cutsets(12, s):
            n += 1
            ok += fast_error(cu, 12) == error(cu, 12)
    check("control: fast error equals error() on every cut set at N = 12, "
          "s = 2..5", ok == n == 561, f"{ok} of {n} cut sets")
    ok = n = 0
    for p in (1, 2):
        for g in (0.1, 0.3):
            for u in (None, 0.8, 0.9):
                cu = profile(200, p, g, u)
                n += 1
                ok += over(cu, 200) == error(cu + (399,), 399)
    check("control: below the overflow label, fast error equals error() "
          "on profiles at c = 200", ok == n == 12, f"{ok} of {n} cut sets")
    ok = sum(over(cu, c) == e for (cu, c), e in HAND_OVER.items())
    check("control: the error below the overflow label by hand",
          ok == len(HAND_OVER) == 4, f"{ok} of {len(HAND_OVER)} cut sets")
    ok = sum(areas(cu, c) == v for (cu, c), v in HAND_AREAS.items())
    cu, c = (0, 3, 6, 7, 9), 9
    fit = over(tuple(2 * x for x in cu), 2 * c) - 2 * over(cu, c)
    check("control: areas by hand, and at c = 9 the first two scales fit "
          "one above them", ok == len(HAND_AREAS) == 3
          and fit == areas(cu, c) + 1 == 49,
          f"{ok} of {len(HAND_AREAS)} cut sets, fit {fit}")
    ok = sum(profile(*k) == v for k, v in HAND_PROFILE.items())
    check("control: profile's cuts by hand", ok == len(HAND_PROFILE) == 4,
          f"{ok} of {len(HAND_PROFILE)} rows")
    ok = sum(profile_at(*k) == v for k, v in HAND_AT.items())
    check("control: profile_at's cuts and misses by hand",
          ok == len(HAND_AT) == 5, f"{ok} of {len(HAND_AT)} rows")
    x = lower(8, 4, 1, 2)
    check("control: 1/4 is 50 percent below 8/16", x == 50, f"{x}")


def section_scale():
    """W1, K-floor, W2 and the scaling law: each cut set scaled, and its
    profile re-tuned at c/2."""
    print("fixed m: each cut set scaled, and its profile re-tuned at c/2")
    rec, pct = {}, {}
    ok = n = 0
    for (c, p, m, u), (ks, b, e2) in ROWS.items():
        cu = profile_at(c, p, m, u)
        A = areas(cu, c)
        E = [over(tuple(k * x for x in cu), k * c) for k in ks]
        rec[c, p, m, u] = E
        re = over(profile_at(c // 2, p, m, u), c // 2)
        pct[c, p, m, u] = lower(E[0], c, re, c // 2)
        n += len(ks) + 1
        ok += sum(2 * e == A * k * k - 2 * b * k for k, e in zip(ks, E))
        ok += re == e2
        print(f"    m = {m} p = {p} top {u} c = {c}: scaled "
              + ", ".join(f"x{k}" for k in ks) + " "
              + ", ".join(f"{e / (k * c) ** 2:.4f}" for k, e in zip(ks, E))
              + f", limit {A / 2 / c / c:.5f}, b {b}; re-tuned c = {c // 2} "
              f"{re / (c // 2) ** 2:.4f}, {pct[c, p, m, u]:.2f}% lower")
    check("the rows: twice each scaled error is areas k^2 - 2 b k, each "
          "re-tuned error as first printed", ok == n == 22,
          f"{ok} of {n} errors")
    w1 = [x for (c, _, _, _), x in pct.items() if c == 4000]
    ok = sum(abs(x) < 2 for x in w1)
    check("W1 fails at two of its three cases: re-tuned at c = 2000 one "
          "reading moves under 2%", ok == 1 and len(w1) == 3,
          f"{ok} of {len(w1)} cases")
    key = (4000, 1, 400, 0.8)
    r = rec[key][0] / 4000 ** 2
    check("K-floor fires: m = 400, p = 1 below 0.095 at c = 4000 and "
          "within 2% at c = 2000", r < 0.095 and abs(pct[key]) < 2,
          f"{r:.4f}, {pct[key]:.2f}%")
    E = rec[10000, 2, 1000, 0.9]
    r, x2 = E[0] / 10000 ** 2, -lower(E[0], 10000, E[1], 20000)
    check("W2: m = 1000, p = 2 below 0.0785 and within 2% scaled x2",
          r < 0.0785 and abs(x2) < 2, f"{r:.4f}, {x2:+.2f}%")


def main():
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    section_scale()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed")
    raise SystemExit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()