band.py

Checks: FLATTEN: Read by rank, the failures sit in a band of depths rule; rule; property; pattern.

Cited on: FLATTEN.

To run it: save band.py, with bandend.py, flatten.py, prunerr.py beside it; needs mpmath.

"""band.py -- at a fixed rank, which depths of flattening make the
least-height polynomial beat every product of factors x^d - 1, and from
which depth one product, the champion, attains it.

QUESTION. flatten.py finds the chart's failing cells (h < ph) at ranks
r = M - J from 5 to 18 only. Is that range a fact about the rank, or
the chart's width M <= 40 crossing something that moves with the depth?
Read one rank at a time, every depth up to the one from which a
certificate takes over: where does the rank first fail, where does it
last fail, and from where does the champion attain h?

THE OBJECTS (flatten.py's senses). h(M, J) is the least height of a
nonzero multiple of (x - 1)^J of degree < M; ph(M, J) the least height
of a pure product prod (x^g - 1) of at least J parts and degree < M;
the cell FAILS when h < ph. A pure product of n parts is (x - 1)^n
prod_{d in E} [d]_x, [d]_x = 1 + x + ... + x^(d-1), E the multiset of
its parts of 2 or more, at most n of them, of degree n + w, w =
sum_{d in E} (d - 1). So at rank r and depth J the admissible ones
have n = J + t parts, t >= 0, and w <= r - 1 - t.
  THE CHAMPION. (1 + x)^(r-1) (x - 1)^J, the pure product
      (x^2 - 1)^(r-1) (x - 1)^(J-r+1) of exactly J parts, from
      J = r - 1 on.
  THE BAND at rank r: J_lo, the least failing depth, and J_hi, the
      greatest; J_ch, the least depth from which the champion attains
      h at every depth read.

THE ENGINE, exact at every cell: no floating-point search and no error
bound. The reduced basis b of the cell's lattice has a least height H.
A lattice vector of height below H has squared norm at most
(H - 1)^2 M, and prunerr.walk visits every lattice vector of that ball
in exact integers, from the rows' own Gram-Schmidt data
(prunerr.integral_gs): h is the least height it meets, or H if that
is lower or the ball holds only 0.
The rows generate the multiples of (x - 1)^J of width M, read a cell
(prunerr.spans). ph is a minimum over a table: pure_row(n, w) holds
the least height of a pure product of exactly n parts by its weight w,
built by multiplying (x - 1)^n by one [d]_x at a time, and ph(r, J)
is the least entry over n = J + t, w <= r - 1 - t. The champion's
height is computed apart, by r - 1 multiplications by 1 + x.

THE CELLS. Ranks 3..14 at every depth J = 2 .. J_c - 1, where J_c =
19, 26, 47, 57, 97, 108, 157, 170, 227, 241, 305, 319 is the depth
from which the champion is certified the only minimiser (bandend.JC:
a scope here, where each rank's scan may stop, and no claim of this
file): 1,749 cells. Ranks 15..22 from J = 2 to the first
failing depth, 60 at most: 175 cells. Ranks 1 and 2 are controls.

PREDICTIONS, frozen before this form's first run. An earlier form in
three files (a floating-point search, with a bound on its error; ph
by a list of cofactors) printed every figure of W1.
  W1 the failing depths at ranks 5..14, as runs:
        5: 18-30.  6: 22, 24-33.  7: 26-54, 56, 58.
        8: 19, 21-24, 26, 32-60.
        9: 12, 14, 21, 23, 25, 27, 29, 31, 36-86, 88.
       10: 24-104, 106.  11: 14, 23-122.  12: 15, 17, 30-152.
       13: 10, 12, 18, 20, 22, 29-156, 158, 160, 162, 164, 166, 168.
       14: 19, 21-24, 26, 29-189, 191, 193, 195.
     Ranks 3 and 4 never fail, the champion attaining h from 7 and
     13. At ranks 5..14 J_ch = J_hi + 1. Ranks 15..22 first fail at
     17, 23, 19, 20, 26, 23, 25, 30.
  W2 the rows span the lattice at every cell.
  W3 on the chart's corner M <= 30 the exact h is flatten.route's and
     the table's ph is flatten.ph_of's, at all 385 cells of ranks
     1..22.
  W4 the limit of n parts of 2 or more moves no ph of the scan.
  W5 at every cell a product of exactly J parts attains ph.
KILL (printed): a rank's record off its prediction; a cell whose rows
do not span; h above ph or ph above the champion's height.

CONTROLS, run before the scan; one failing stops the run.
  BY HAND. times_window: (x - 1)[3] = x^3 - 1; (1 + 2x + 3x^2)(1 + x)
     = 1 + 3x + 5x^2 + 3x^3; 1 times [3]. pure_row, heights and counts
     of multisets by weight: one part, weights 0..3: x - 1, x^2 - 1,
     x^3 - 1, x^4 - 1, heights 1, one multiset each ({2, 2}, {2, 3}
     and {2, 2, 2} have too many parts); two parts: (x - 1)^2 of
     height 2, then 1, 1, 1, with 1, 1, 2, 2 multisets; three parts,
     weights 0..2: 3, 2, 2; four parts: 6, 3, 3, where at weight 2
     {2, 2} gives x^6 - 2x^5 - x^4 + 4x^3 - x^2 - 2x + 1, height 4,
     and is met before {3}, x^6 - 3x^5 + 3x^4 - 2x^3 + 3x^2 - 3x + 1,
     height 3.
     ph on tables written by hand, rank 3, depth 2: rows 2: (5, 4,
     3), 3: (2, 9), 4: (7) give 2 over all and 3 at exactly two parts;
     rows 2: (5, 4, 3), 3: (6, 9, 1), 4: (7, 0, 0) give 3 and 3, the
     entries 1 and 0 being past the weights admissible. On a table it
     builds: rank 1, depth 4: 6; rank 2, depth 2: 1; depth 3: 2, the
     least of (x - 1)^3, (x - 1)^3 (1 + x) = x^4 - 2x^3 + 2x - 1 and
     (x - 1)^4.
     The champion: rank 1, depth 4: 6; rank 3, depths 2 and 3: (x^2 -
     1)^2, height 2, and x^5 - x^4 - 2x^3 + 2x^2 + x - 1, height 2;
     rank 4, depth 3: (x^2 - 1)^3, height 3.
     least_of on u = (2, ..., 2) and v = (3, 0, ..., 0) in width 9:
     H = 2, |a u + b v|^2 = (2a + 3b)^2 + 32 a^2, so the ball of
     squared radius 9 holds +-v alone, of height 3, and the least
     height is 2, not the least met.
     exact_height: (3, 2), the multiples of (1, -2, 1): 2; (4, 2),
     whose reduced rows hold (1, -1, -1, 1): 1; (17, 10), where the
     least height 23 lies below the reduced basis's 24 (prunerr.py's
     control prints both): the walk leaves its start. cell at depth
     2: (x - 1)(x^2 - 1) = x^3 - x^2 - x + 1 has two parts and height
     1, so h = ph = 1 at ranks 3 and 4; the champion is (x^2 - 1)^2,
     height 2, at rank 3, and at rank 4 it would need three parts.
     runs, depths and rank_record on rows written by hand: a rank with
     two failing depths, a clean depth between them where the champion
     attains h, a cell whose rows do not span and the champion's start
     at 6; and one with h above ph, ph above the champion's, and no
     start.
  RANKS 1 AND 2, depths 2..140, closed forms. At rank 1 the lattice
     is the multiples of (x - 1)^J: h = ph = C(J, floor(J/2)). At rank
     2 the least height is the champion's (a theorem, rank2.py), and
     the champion (1 + x)(x - 1)^J has coefficients +-(C(J, k) -
     C(J, k - 1)): h = ph = max_k |C(J, k) - C(J, k - 1)|.
  THE CHART'S CORNER. Every cell of ranks 1..22 with M <= 30 against
     flatten.py: the exact h against flatten.route's, the table's ph
     against flatten.ph_of's, agreements counted; and against the
     next width's, where they must part at some cells.

FINDINGS (copied from the printed output).
  (1) THE CONTROLS PASS. Every hand case; ranks 1 and 2 at their
      closed forms at all 139 depths each; on the chart's corner the
      exact h and the table's ph are flatten.py's at all 385 cells
      (W3), and at 164 and 167 of them against the next width's.
  (2) THE SCAN (W1 and W2 hold, the KILL misses). At all 1,924 cells
      the rows span the lattice and h <= ph, and ph <= the champion's
      height wherever the champion is a pure product of J parts.
      Ranks 3 and 4 never fail below J_c, the champion attaining h
      from 7 and 13. At ranks 5..14 the failing depths are W1's runs,
      to the depth, and the champion attains h at every depth from
      J_hi + 1 = 31, 34, 59, 61, 89, 107, 123, 153, 169, 196 through
      J_c - 1. Ranks 15..22 first fail at 17, 23, 19, 20, 26, 23, 25,
      30.
  (3) THE CHART'S RANKS. The ranks whose first failing depth is a cell
      of the chart, J_lo <= min(30, 40 - r), are 5..18: the chart's
      failing ranks are where its widths meet a band.
  (4) EXACTLY J PARTS (W5 holds). At every cell of the scan, and of
      ranks 1 and 2, a product of exactly J parts attains ph.

RUN RECORD. python band.py: 27 of 27 checks, 47.4 s, peak commit
16.9 MB.
Entered from this form's first print, no hand value behind them: the
corner's agreements at the next width, 164 and 167. W3 was frozen at
the chart's 560 cells of ranks 1..22 and narrowed to the corner before
the first run, flatten.py's table to degree 39 costing 9.4 s a run; W5
was added then.
Edits by hand, the FAIL lines named before each run. The limit of n
parts dropped from pure_row is red at its hand counts and nowhere
else: W4 holds, no ph of the scan or the corner moves, for a reason
not derived. The products of more than J parts dropped from ph are
red at the hand tables and nowhere else, as (4) says. Rank 3 read one
depth further is red at the depths' hand line and at its own; rank 4,
at its own alone.
One site changed at a time, at every site of every function but main
and those named check or section, the run read: 148 mutants, 142
failing a check, none past the clock, 6 passing, none of the 6 moving
a line of the print. One of the six was a gap, the least height's
clause for a ball whose least vector is above H, which no cell meets:
least_of and its hand lattice came of it, and the 8 sites of its two
functions were read again, 7 failing. The 5 that pass at this form: a
tie that returns H either way; a tie in pure_row that replaces a
height by its equal; pure_row built two weights wider than ph reads;
and two that W5 makes equal, the corner comparing ph at exactly J
parts and the scan's stop reading it. An earlier meter of 145 passed
two more, at the champion's edge J = r - 1, which no hand cell read:
cell's two hand cells came of them. The lines of ranks 3 and 4 no
mutant turned without failing a control first; the edits by hand
above read them.
"""
import os
import sys
import time
from itertools import accumulate
from math import comb

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import flatten  # noqa: E402
import prunerr  # noqa: E402
# the depth from which the champion is certified: where a rank's scan
# stops
from bandend import JC  # noqa: E402


# --------------------------------------------------------- the pure products

def times_window(P, d):
    """P times [d]_x = 1 + x + ... + x^(d-1)."""
    S = list(accumulate(P + [0] * (d - 1)))
    return S[:d] + [S[k] - S[k - d] for k in range(d, len(S))]


def pure_row(n, wmax):
    """(best, count), each by weight w = 0..wmax: the least height of
    (x - 1)^n prod_{d in E} [d]_x over the multisets E of parts >= 2
    with sum (d - 1) = w and at most n parts, the pure products of
    exactly n parts and degree n + w, and how many multisets there
    are."""
    best = [None] * (wmax + 1)
    count = [0] * (wmax + 1)

    def walk(P, size, w, last):
        hgt = max(max(P), -min(P))
        count[w] += 1
        if best[w] is None or hgt < best[w]:
            best[w] = hgt
        if size < n:
            for d in range(last, wmax - w + 2):
                walk(times_window(P, d), size + 1, w + d - 1, d)

    walk(flatten.pow_xm1(n), 0, 0, 2)
    return best, count


def ph(table, r, J):
    """(the least height of a pure product admissible at rank r, depth
    J; the least among those of exactly J parts). table: pure_row's
    best by part count, filled as needed."""
    for t in range(r):
        if J + t not in table:
            table[J + t] = pure_row(J + t, r - 1)[0]
    return (min(table[J + t][w] for t in range(r) for w in range(r - t)),
            min(table[J][w] for w in range(r)))


def champion(r, J):
    """The height of (1 + x)^(r-1) (x - 1)^J."""
    P = flatten.pow_xm1(J)
    for _ in range(r - 1):
        P = times_window(P, 2)
    return flatten.height(P)


# ------------------------------------------------------------ the exact cell

def least_of(b, M):
    """(h, H): the least height of a nonzero vector of the lattice the
    rows b generate, with no float, and the rows' own least height H."""
    H = min(flatten.height(v) for v in b)
    low = prunerr.walk(b, *prunerr.integral_gs(b), M, H)[3]
    return (H if low is None or low > H else low), H


def exact_height(M, J):
    """(h, H, spans): h(M, J) with no float, the reduced basis's least
    height H, and whether its rows generate the cell's lattice."""
    b = flatten.lll(flatten.basis(M, J))[0]
    return least_of(b, M) + (prunerr.spans(b, J),)


def cell(table, r, J):
    """(J, h, ph, ph at exactly J parts, the champion's height or None
    where it is no pure product of J parts, spans)."""
    h, _, sp = exact_height(r + J, J)
    p, pj = ph(table, r, J)
    return J, h, p, pj, champion(r, J) if J >= r - 1 else None, sp


def depths(r):
    """The depths read at rank r, the last only if none fails first
    from rank 15 on."""
    return range(2, 141 if r <= 2 else JC[r] if r <= 14 else 61)


def scan(r):
    """The cells of rank r by depth; from rank 15 on, to the first
    failing one."""
    table, rows = {}, []
    for J in depths(r):
        rows.append(cell(table, r, J))
        if r >= 15 and rows[-1][1] < rows[-1][2]:
            break
    return rows


def runs(ints):
    """Increasing integers as maximal runs (first, last)."""
    out = []
    for J in ints:
        if out and J == out[-1][1] + 1:
            out[-1] = (out[-1][0], J)
        else:
            out.append((J, J))
    return tuple(out)


def rank_record(rows):
    """(cells; cells whose rows span; cells with h <= ph <= the
    champion's height; cells where exactly J parts attain ph; the
    failing depths, h < ph, as runs; J_ch, the least depth from which
    the champion attains h at every depth read, or None)."""
    start = None
    for J, h, p, pj, c, sp in reversed(rows):
        if c != h:
            break
        start = J
    return (len(rows),
            sum(1 for row in rows if row[5]),
            sum(1 for J, h, p, pj, c, sp in rows
                if h <= p and (c is None or p <= c)),
            sum(1 for row in rows if row[2] == row[3]),
            runs([row[0] for row in rows if row[1] < row[2]]),
            start)


def on_chart(records):
    """The ranks whose first failing depth is a cell of flatten.py's
    chart: J_lo <= min(30, 40 - r)."""
    return [r for r in sorted(records)
            if records[r][4] and records[r][4][0][0] <= min(30, 40 - r)]


def corner(shift):
    """(cells, cells where the exact h is flatten.route's, cells where
    the table's ph is flatten.ph_of's) over ranks 1..22, M = r + J <=
    30, flatten.py read at width M + shift."""
    pure = flatten.pure_table(29 + shift)
    n = same_h = same_p = 0
    for r in range(1, 23):
        table = {}
        for J in range(2, 31 - r):
            n += 1
            same_h += (exact_height(r + J, J)[0]
                       == flatten.route(r + J + shift, J)[0])
            same_p += (ph(table, r, J)[0]
                       == flatten.ph_of(pure, r + J + shift, J)[0])
    return n, same_h, same_p


# ---------------------------------------------------------------- the checks

RECORD = {
    3: (17, 17, 17, 17, (), 7),
    4: (24, 24, 24, 24, (), 13),
    5: (45, 45, 45, 45, ((18, 30),), 31),
    6: (55, 55, 55, 55, ((22, 22), (24, 33)), 34),
    7: (95, 95, 95, 95, ((26, 54), (56, 56), (58, 58)), 59),
    8: (106, 106, 106, 106,
        ((19, 19), (21, 24), (26, 26), (32, 60)), 61),
    9: (155, 155, 155, 155,
        ((12, 12), (14, 14), (21, 21), (23, 23), (25, 25), (27, 27),
         (29, 29), (31, 31), (36, 86), (88, 88)), 89),
    10: (168, 168, 168, 168, ((24, 104), (106, 106)), 107),
    11: (225, 225, 225, 225, ((14, 14), (23, 122)), 123),
    12: (239, 239, 239, 239, ((15, 15), (17, 17), (30, 152)), 153),
    13: (303, 303, 303, 303,
         ((10, 10), (12, 12), (18, 18), (20, 20), (22, 22), (29, 156),
          (158, 158), (160, 160), (162, 162), (164, 164), (166, 166),
          (168, 168)), 169),
    14: (317, 317, 317, 317,
         ((19, 19), (21, 24), (26, 26), (29, 189), (191, 191),
          (193, 193), (195, 195)), 196),
    15: (16, 16, 16, 16, ((17, 17),), None),
    16: (22, 22, 22, 22, ((23, 23),), None),
    17: (18, 18, 18, 18, ((19, 19),), None),
    18: (19, 19, 19, 19, ((20, 20),), None),
    19: (25, 25, 25, 25, ((26, 26),), None),
    20: (22, 22, 22, 22, ((23, 23),), None),
    21: (24, 24, 24, 24, ((25, 25),), None),
    22: (29, 29, 29, 29, ((30, 30),), None),
}
FIELDS = ("cells, cells whose rows span, with h <= ph <= the champion's, "
          "where exactly J parts attain ph; the failing depths; the "
          "champion's start")

CHECKS = []


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


def check_hand(name, pairs):
    hits = sum(1 for got, want in pairs if got == want)
    check(name, hits == len(pairs), f"{hits} of {len(pairs)} cases")


def section(title):
    print()
    print(title)
    print("-" * len(title))


def section_controls():
    section("CONTROLS: the pure products, the exact cell and the record "
            "by hand; ranks 1 and 2; the chart's corner")
    check_hand("times_window at three products; pure_row's heights and "
               "counts at one, two, three and four parts", [
                   (times_window([-1, 1], 3), [-1, 0, 0, 1]),
                   (times_window([1, 2, 3], 2), [1, 3, 5, 3]),
                   (times_window([1], 3), [1, 1, 1]),
                   (pure_row(1, 3), ([1, 1, 1, 1], [1, 1, 1, 1])),
                   (pure_row(2, 3), ([2, 1, 1, 1], [1, 1, 2, 2])),
                   (pure_row(3, 2), ([3, 2, 2], [1, 1, 2])),
                   (pure_row(4, 2), ([6, 3, 3], [1, 1, 2]))])
    check_hand("ph on two tables written by hand and at three cells; the "
               "champion at four", [
                   (ph({2: [5, 4, 3], 3: [2, 9], 4: [7]}, 3, 2), (2, 3)),
                   (ph({2: [5, 4, 3], 3: [6, 9, 1], 4: [7, 0, 0]}, 3, 2),
                    (3, 3)),
                   (ph({}, 1, 4), (6, 6)),
                   (ph({}, 2, 2), (1, 1)),
                   (ph({}, 2, 3), (2, 2)),
                   (champion(1, 4), 6),
                   (champion(3, 2), 2),
                   (champion(3, 3), 2),
                   (champion(4, 3), 3)])
    check_hand("least_of where the ball holds only a vector above H; "
               "exact_height at (3, 2), (4, 2) and (17, 10), where the "
               "least height is below the reduced basis's; cell at depth "
               "2, rank 3, where the champion has J parts, and rank 4, "
               "where it has not", [
                   (least_of([[2] * 9, [3] + [0] * 8], 9), (2, 2)),
                   (exact_height(3, 2), (2, 2, True)),
                   (exact_height(4, 2), (1, 1, True)),
                   (exact_height(17, 10), (23, 24, True)),
                   (cell({}, 3, 2), (2, 1, 1, 1, 2, True)),
                   (cell({}, 4, 2), (2, 1, 1, 1, None, True))])
    band = [(2, 5, 5, 5, None, True), (3, 4, 6, 6, 7, True),
            (4, 6, 6, 7, 6, False), (5, 3, 5, 5, 5, True),
            (6, 8, 8, 8, 8, True), (7, 9, 9, 9, 9, True)]
    odd = [(2, 3, 2, 2, None, True), (3, 3, 4, 5, 3, True),
           (4, 5, 5, 5, 6, True)]
    check_hand("runs at three lists; the depths read at seven ranks; "
               "rank_record on two ranks written by hand; on_chart", [
                   (runs([]), ()),
                   (runs([3]), ((3, 3),)),
                   (runs([3, 4, 5, 7, 9, 10]), ((3, 5), (7, 7), (9, 10))),
                   ([(d[0], d[-1]) for d in map(depths,
                                                (1, 2, 3, 14, 15, 22))],
                    [(2, 140), (2, 140), (2, 18), (2, 318), (2, 60),
                     (2, 60)]),
                   (len(depths(9)), 155),
                   (rank_record(band), (6, 5, 6, 5, ((3, 3), (5, 5)), 6)),
                   (rank_record(odd), (3, 3, 1, 2, ((3, 3),), None)),
                   (on_chart({9: (1, 1, 1, 1, ((30, 31),), None),
                              10: (1, 1, 1, 1, ((31, 31),), None),
                              11: (1, 1, 1, 1, ((29, 29), (40, 40)), None),
                              12: (1, 1, 1, 1, ((29, 29),), None),
                              13: (1, 1, 1, 1, (), 5)}), [9, 11])])
    low = [scan(r) for r in (1, 2)]
    check_hand("ranks 1 and 2 at depths 2..140: h and ph the closed forms, "
               "depths counted; their records", [
                   (sum(1 for J, h, p, pj, c, sp in low[0]
                        if h == p == comb(J, J // 2)), 139),
                   (sum(1 for J, h, p, pj, c, sp in low[1]
                        if h == p == max(abs(comb(J, k) - comb(J, k - 1))
                                         for k in range(1, J + 1))), 139),
                   (rank_record(low[0]), (139, 139, 139, 139, (), 2)),
                   (rank_record(low[1]), (139, 139, 139, 139, (), 2))])
    got = corner(0), corner(1)
    check("the chart's corner, M <= 30: the exact h and the table's ph "
          "against flatten.py's at every cell, and against the next "
          "width's, where they part",
          got == ((385, 385, 385), CORNER_NEXT), f"{got}")


CORNER_NEXT = (385, 164, 167)


def main():
    t_all = time.time()
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    section("THE SCAN: ranks 3..14 to J_c - 1, ranks 15..22 to the first "
            "failing depth")
    print("  " + FIELDS)
    records = {}
    for r in sorted(RECORD):
        t0 = time.time()
        records[r] = rank_record(scan(r))
        ok = records[r] == RECORD[r]
        check(f"rank {r}", ok, f"{records[r]}"
              + ("" if ok else f", recorded {RECORD[r]}")
              + "  (%.1f s)" % (time.time() - t0))
    check("the ranks whose first failing depth is a cell of the chart, "
          "J_lo <= min(30, 40 - r), are 5..18",
          on_chart(records) == list(range(5, 19)), f"{on_chart(records)}")
    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()