cell_exact.py

Checks: SIZE: The cell tent bound theorem; property; rule; observation.

Cited on: SIZE.

To run it: save cell_exact.py, with erring_cells.py, erring_label.py, erring_lower.py, erring_widths.py, erring_zones.py beside it; needs numpy.

"""
cell_exact.py -- LB_s >= G2(sort P) at m = 2 and m = 3, at every real
partition, by an exact case split: its cover and minimizer checked, its
engine set against the definition by an argument and a second evaluator.

QUESTION. P cuts [0, 1) into I_1, ..., I_m at 0 = c_0 < ... < c_m = 1,
overflow [1, 2) one label. e_a(y) is w_a less the longest piece of
I_a + y cut at the boundaries c_1, ..., c_m, U_ab its integral over y in
I_b, and LB_s = sum_a U_aa + 2 sum over pairs of U at (the wider row,
the narrower column), called LB_low where equal widths leave the wider
of a pair free. G2(sort P) is erring_cells.py's g2 on the widths
sorted increasing, ties c_(b-1) = c_j/2 in. Is LB_s >= G2(sort P) at
every P with m = 2 or 3? With LB_s <= LB3 <= E, a yes gives E >=
G2(sort P) there.

BY HAND (fixed before the engine was written). At m = 2, with s the
narrower width, L = 1 - s and M = 1 - 2s: narrow first, U_aa = T^Q_aa
and LB_s - G2 = 2U_21 = s^2 (s <= 1/3), 3s - 7s^2/2 - 1/2 (1/3 <= s
< 1/2); wide first, U_22 = 0 and LB_s - G2 = s/2 + s^2/2 (s <= 1/4),
5s/2 - 7s^2/2 - 1/4 (1/4 <= s < 1/2); equal widths, 3/16 = 3/16.
  Derived (later, before `definition` was written), the boundaries
c_1 and 1. Narrow first (c_1 = s): I_1 + y
holds s alone, pieces s - y and y, so U_11 = int_0^s min(y, s - y) =
s^2/4. I_2 + y = [s + y, 1 + y) holds 1 iff y < L, pieces L - y and y:
U_22 = int_s^L min(y, L - y), which is L^2/4 - s^2/2 (s <= 1/3, where
L/2 >= s) or M^2/2, and U_21 = int_0^s min(y, L - y), s^2/2 or Ls -
s^2/2 - L^2/4. The order is sorted: T_11 is the whole tent at s, s^2/4;
T_22 integrates the tent at 1, radius L/2, from 2s + L/2, which is s
past its left end and before its centre iff s <= 1/3, so T_22 = U_22;
S' = 0 below s = 1/2. So G2 = L^2/4 - s^2/4 or s^2/4 + M^2/2 and LB_s -
G2 = 2U_21. Wide first (c_1 = L): I_2 + y starts at 2L >= 1, U_22 = 0.
I_1 + y = [y, L + y) holds L, and 1 iff y > s: e = min(y, L - y) on (0,
s], min(y, M, 1 - y) on (s, L) (pieces L - y, s, y - s) and min(y - s,
1 - y) over I_2. U_12 = s^2/2 (s <= 1/3) or L^2/4 - M^2/2. U_11 = 1/4 -
s^2/2 (s <= 1/4, M >= 1/2), 2s - 9s^2/2 (1/4 < s <= 1/3, s <= M < 1/2 <
2s <= L), Ls - s^2/2 - L^2/4 + M^2 (s > 1/3, e = M on all of (s, L)).
U_11 + 2U_12 - G2 is s/2 + s^2/2, then 5s/2 - 7s^2/2 - 1/4 on both
later ranges. Equal widths: U_11 = U_12 = U_21 = T_11 = 1/16, U_22 =
T_22 = 0, S'_2 = 1/4 on the tie. Each form is >= 0 on its range, the
two concave ones 1/9 and 1/8, 5/32 and 1/8 at their ends.

DESIGN. Every quantity in U, T^Q and G2 is built from the cuts by
affine maps, comparisons of affine forms and products of two affine
forms. The engine carries each quantity as an affine form in the free
cuts (Fractions) and takes each comparison's branch at an interior
point of a face, recording the compared form. When no recorded form
changes strict sign over the face's vertices, every point of the open
face takes the same branches (an affine form >= 0 at the vertices and
> 0 at one is > 0 on the open face), so LB_s - G2 is one quadratic
there; else the face is split on that form's line. Faces: the open
polygons of 0 < c_1 < c_2 < 1 (m = 3), then every polygon edge as an
open segment, split alike, then every vertex, so G2's inclusive jumps
are read where they sit. A quadratic's least on a closed polygon is
exact: the vertices, each edge's critical point, and the interior
critical point when the Hessian is positive definite. U by segments
of y in I_b, cut at c_(b-1), c_b, beta - c_(a-1), beta - c_a; on each
the longest piece is max(p - y, q + y, r), cut at (p - q)/2, p - r,
r - q. T^Q_jj by h(t) = max(0, r - dist(t, B)), r = v_j/2, cut at beta
and beta +- r: on sorted widths t runs over [2C_(j-1) + r, 2C_(j-1) +
3r], the tent at C_(j-1) ends at or before it, and the boundaries from
C_j on are at least 2r apart, so no two tents overlap there. Both
integrals by the trapezoid rule, exact on linear pieces.

Where widths are equal the order of the equal ones is free, and LB_s
does not see it: if w_a = w_b, I_a + y over y in I_b and I_b + y over y
in I_a are the same intervals, so U_ab = U_ba. Every order is carried
all the same, for the rows D_a = U_aa + 2 sum_(b earlier in the order)
U_ab, which do depend on it.

THE SPLIT AS A PROOF owes three things: that a face's quadratic is the
definition's, a cover and a minimizer.
  engine     (A) U, T and evaluate hold the cuts as affine forms and
             never the point, which Ctx.sign alone reads: a run is a
             function of the signs it is answered. On a final face no
             recorded form is mixed over the vertices, so each keeps
             one sign on the open face (a constant form everywhere),
             and the run at any of its points asks the same forms, is
             answered alike and returns the centroid's quadratics.
             (B) At one point the run is the definition. U: between
             consecutive y where an end of I_a + y meets a boundary,
             the boundaries inside are fixed, B[lo] to B[hi], read at
             the midpoint; with none the piece is w and e = 0; else
             the pieces are p - y, q + y and the gaps between, r the
             largest, and max(p - y, q + y, r) is linear between its
             three crossings, where the trapezoid rule is exact. T: h
             is the definition's largest tent, linear between its
             points by the argument in DESIGN. evaluate: the widths
             sorted through sign; share j is T^Q_jj + (v_j^2/2) #{i >=
             j: C_i <= 2C_(j-1)}, the sum over j of S'_j taken by b; an
             order is kept iff no narrower interval ranks later, and
             LB charges U_ab where b ranks before a.
             (A) and (B) give the definition at every point of every
             face. (A) is the construction's; (B) is a reading of
             code, and `definition` reads it a second way, sharing
             nothing (each piece cut as defined, the midpoint rule on
             a superset of the kinks): X5 sets every face against it,
             a cell at six nodes that fix a quadratic, so a definition
             that is any one quadratic on a cell is the engine's.
  cover      the cells are convex and lie in the simplex, no two share
             an interior point (an edge line of one separates each
             pair) and their areas sum to its 1/2; every cell edge off
             the simplex's boundary lies under open segments and read
             vertices; at m = 2 the open segments and their cuts tile
             (0, 1).
  minimizer  poly_min, seg_min and least_over on one convex quadratic,
             2x^2 + xy + y^2 - 13x/10 - 6y/5 + 9/25, critical at (1/5,
             1/2) with value -7/100, on its negative, and on forms
             missing a term: a least inside, on an edge, at a vertex,
             on a segment's inside and end.

PREDICTIONS AND KILLS (fixed before the engine was written).
  X1 at m = 2 the engine's pieces equal the hand forms exactly.
  X2 the engine against erring_cells' shifts and sorted_g2 at every
     composition of 23 into 2 parts and of 17 into 3, and four of 4
     parts: |diff| < 1e-12; at
     (2, 4, 2, 5)/13, 169 LB_s = 169 G2 = 27 exactly.
  X3 break: the reverse charge (each pair to its narrower row) yields
     a certified negative face at m = 3 (a float probe read the
     reverse charge at 0.636 of G2 at widths (1, 1, 2)).
  X4 (added with the engine, not frozen) each final cell's and
     segment's G2 and LB at m = 3, every order, equal a point
     evaluation at two interior points off its centroid.
  X5 (fixed before `definition` was written) each face's U, G2 and LB,
     every order, equal `definition` at six nodes a cell, at 1/4, 1/2
     and 3/4 of a segment and at every read vertex: 630, 489 and 59
     points at m = 3, 15 and 4 at m = 2, none off; a kink dropped from
     U or a tent's end from T turns it red. `definition` is read first
     on the hand rows (D1), nodes, against and faces_off on hand cases
     (D2). Dropped from what was fixed: a count of the pairs of equal
     widths whose two charges differ, since X5 compares every U_ab.
  P  LB_low >= G2 on every face at m = 2 and 3; zeros only at ties,
     at m = 3 (1, 1, 1) and (1, 1, 2).
  K  a face whose exact least of LB_pi - G2 is below 0 kills it.

HAND ROWS, U in the unit named, the shares by sorted rank, D by
position at each order. Fixed before the checks that read them: H1 and
H3 whole, H2's U and shares, H4's U_22 and rank 1 share; the rest of
H2 and H4 derived by hand as the checks were written.
  H1 (1, 1, 2)/4, in 1/16: U = (1/4, 1/4, 1/4), (1/4, 0, 1/4), (1/2,
     1/2, 0); shares (1/4, 1/2, 2); LB_s = G2 = 11/4 and the reverse
     charge 7/4, so its gap is -1/16; D = (1/4, 1/2, 2) or (3/4, 0, 2).
  H2 (1, 1, 1)/3, in 1/9: U_ab = 1/4 where a + b <= 4, else 0; shares
     (1/4, 3/4, 1/2); LB_s = G2 = 3/2 at each of the six orders.
  H3 (2, 4, 2, 5)/13, in 1/169: U = (1, 1, 1, 1), (2, 6, 1/2, 7/2), (1,
     1/2, 1/2, 0), (2, 17/4, 0, 0); shares (1, 2, 23/2, 25/2); LB_s =
     G2 = 27; D = (1, 11, 5/2, 25/2) or (3, 11, 1/2, 25/2).
  H4 (2, 1)/3, in 1/9: U = (3/2, 1/2), (1/4, 0); shares (1/4, 1/2);
     LB_s = 5/2, G2 = 3/4, the gap 7/36 of the hand form.
  Predicted with them: five segments at m = 2, cut at the hand forms'
  seams 1/3, 1/2, 2/3, 3/4; the cover closing; the zero set of P.

FINDINGS (from the printed run; the controls first: X2 max |dU| 1.1e-16
and |dG2| 8.3e-17 at 147 widths, X2's and a fifth of 4 parts, (1, 1,
1, 1), where a share counts two boundaries; H1 to H4 equal to their
hand rows, 2, 6, 2 and 1 orders; D1 no field off, D2 the six nodes and
4 of 8 hand points off as by hand; M1 to M4 0 off, M5's nine counts of
holes 0, 1, 1, 0, 1, 0, 1, 1, 2, M6's zero set, M7's (4, 2, 1) and
M8's counts as by hand; X1 0 mismatches at 34 points; X4 0 off over
536; X3 the reverse charge's least -1/16 at (1/4, 1/4, 1/2)).
  X5 held: 0 off over 630, 489 and 59 points at m = 3 and over 15 and 4
     at m = 2. The two breaks, each in a copy: U's kink r - q dropped,
     3 and 406 points off (X1 and X2 turn too); T's beta + r dropped,
     18 and 1124 off (X1, X2, H4, D2 and K too). `definition` with its
     crossings dropped, or its ties out, fails D1.
  P held: LB_low - G2(sort P) is never below 0 at m = 2 or 3, its least
     0 at both, so, the engine's quadratics being the definition's
     by (A) and (B), E >= LB3 >= LB_low >= G2(sort P) at every P with
     m = 2 or 3. At
     m = 2, 5 segments cut at c_1 = 1/3, 1/2, 2/3, 3/4, the
     hand forms' seams, tile (0, 1) with 0 holes, and the one zero in
     the open range is c_1 = 1/2. At m = 3, 105 cells, 163 segments and
     59 open vertices: every cell convex, none with a vertex outside
     the simplex, 0 pairs overlapping, total area 1/2, and 0 holes on
     the 163 cell edges off the boundary. LB is the same at every order
     of equal widths on the 39 segments and vertices holding more than
     one; no cell holds more than one. The zeros are not the two
     predicted points but the
     whole closed segment between them, widths (t, t, 1 - 2t) for
     1/4 <= t <= 1/3 (w_1 = w_2, the sorted tie C_1 = C_2/2): every
     vertex on it is 0, no other vertex or segment point is, and no
     cell holds a zero inside.
  Run: 4.9 s, 27/27.
"""

import functools
import itertools
import os
import time
from fractions import Fraction as Fr

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
HALF = Fr(1, 2)
CHECKS = []


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


class Aff:
    """k[0] + sum k[i + 1] x_i, exact."""
    __slots__ = ("k",)

    def __init__(self, k):
        self.k = tuple(k)

    @staticmethod
    def const(c, d):
        return Aff((Fr(c),) + (Fr(0),) * d)

    @staticmethod
    def var(i, d):
        k = [Fr(0)] * (d + 1)
        k[i + 1] = Fr(1)
        return Aff(k)

    def __add__(self, o):
        return Aff(a + b for a, b in zip(self.k, o.k))

    def __sub__(self, o):
        return Aff(a - b for a, b in zip(self.k, o.k))

    def sc(self, c):
        return Aff(a * c for a in self.k)

    def at(self, p):
        return self.k[0] + sum(a * x for a, x in zip(self.k[1:], p))

    def mul(self, o):
        q = {}
        for i, a in enumerate(self.k):
            if a:
                for j, b in enumerate(o.k):
                    if b:
                        key = (min(i, j), max(i, j))
                        q[key] = q.get(key, 0) + a * b
        return Quad(q)


class Quad:
    """sum q[(i, j)] x_i x_j over x_0 = 1, x_1, ..., x_d."""
    __slots__ = ("q",)

    def __init__(self, q=None):
        self.q = {k: v for k, v in (q or {}).items() if v}

    def __add__(self, o):
        q = dict(self.q)
        for k, v in o.q.items():
            q[k] = q.get(k, 0) + v
        return Quad(q)

    def __sub__(self, o):
        return self + o.sc(-1)

    def sc(self, c):
        return Quad({k: v * c for k, v in self.q.items()})

    def at(self, p):
        x = (Fr(1),) + tuple(p)
        return sum(v * x[i] * x[j] for (i, j), v in self.q.items())

    def along(self, P0, D):
        """(al, be, ga): q(P0 + t D) = al t^2 + be t + ga."""
        x0 = (Fr(1),) + tuple(P0)
        dx = (Fr(0),) + tuple(D)
        al = be = ga = Fr(0)
        for (i, j), v in self.q.items():
            al += v * dx[i] * dx[j]
            be += v * (x0[i] * dx[j] + dx[i] * x0[j])
            ga += v * x0[i] * x0[j]
        return al, be, ga


def qsum(items, zero):
    tot = zero
    for x in items:
        tot = tot + x
    return tot


class Ctx:
    """Takes each comparison's branch at p, recording the compared form."""

    def __init__(self, p):
        self.p = tuple(p)
        self.forms = {}

    def sign(self, f):
        v = f.at(self.p)
        if any(f.k[1:]):
            lead = next(a for a in f.k[1:] if a)
            key = tuple(a / abs(lead) for a in f.k)
            self.forms[key] = f
        return (v > 0) - (v < 0)

    def mx(self, f, g):
        return f if self.sign(f - g) >= 0 else g

    def sort(self, xs):
        xs = sorted(xs, key=functools.cmp_to_key(lambda f, g:
                                                 self.sign(f - g)))
        out = [xs[0]]
        for x in xs[1:]:
            if self.sign(x - out[-1]) != 0:
                out.append(x)
        return out

    def inside(self, t, lo, hi):
        return self.sign(t - lo) > 0 and self.sign(hi - t) > 0


def trapezoid(pts, f, zero):
    return qsum(((f(u0) + f(u1)).sc(HALF).mul(u1 - u0)
                 for u0, u1 in zip(pts, pts[1:])), zero)


def U(ctx, C, a, b, zq):
    """U_ab: w_a less the longest piece of I_a + y, integrated over I_b."""
    B = C[1:]
    L0, R0 = C[a], C[a + 1]
    w = R0 - L0
    y0b, y1b = C[b], C[b + 1]
    cand = [t for beta in B for t in (beta - L0, beta - R0)
            if ctx.inside(t, y0b, y1b)]
    ys = ctx.sort([y0b, y1b] + cand)
    tot = zq
    for y0, y1 in zip(ys, ys[1:]):
        ym = (y0 + y1).sc(HALF)
        ins = [k for k, beta in enumerate(B)
               if ctx.inside(beta, L0 + ym, R0 + ym)]
        if not ins:
            continue
        lo, hi = ins[0], ins[-1]
        p, q = B[lo] - L0, R0 - B[hi]
        r = None
        for k in range(lo, hi):
            g = B[k + 1] - B[k]
            r = g if r is None else ctx.mx(r, g)
        brk = [(p - q).sc(HALF)] + ([p - r, r - q] if r is not None else [])
        pts = ctx.sort([y0, y1] + [t for t in brk if ctx.inside(t, y0, y1)])

        def f(y):
            v = ctx.mx(p - y, q + y)
            return v if r is None else ctx.mx(v, r)
        tot = tot + w.mul(y1 - y0) - trapezoid(pts, f, zq)
    return tot


def T(ctx, Cq, j, zq):
    """T^Q_jj: I_j's tent integrated over its own shifts, the widths
    nondecreasing."""
    B = Cq[1:]
    d = len(Cq[0].k) - 1
    zero = Aff.const(0, d)
    r = (Cq[j + 1] - Cq[j]).sc(HALF)
    t0, t1 = Cq[j] + r + Cq[j], Cq[j] + r + Cq[j + 1]
    cand = [x for beta in B for x in (beta - r, beta, beta + r)]
    pts = ctx.sort([t0, t1] + [x for x in cand if ctx.inside(x, t0, t1)])

    def h(t):
        best = zero
        for beta in B:
            best = ctx.mx(best, r - ctx.mx(t - beta, beta - t))
        return best
    return trapezoid(pts, h, zq)


def evaluate(ctx, C):
    """U, G2 and the sorted shares; LB, the reverse charge and the row
    shares D for every order of the widths consistent with them."""
    m = len(C) - 1
    d = len(C[0].k) - 1
    zq = Quad()
    Um = [[U(ctx, C, a, b, zq) for b in range(m)] for a in range(m)]
    w = [C[a + 1] - C[a] for a in range(m)]
    v = sorted(w, key=functools.cmp_to_key(lambda f, g: ctx.sign(f - g)))
    Cq = [Aff.const(0, d)]
    for x in v:
        Cq.append(Cq[-1] + x)
    Tq = [T(ctx, Cq, j, zq) for j in range(m)]
    share = []
    for j in range(m):
        n = sum(1 for i in range(j + 1, m + 1)
                if ctx.sign(Cq[j].sc(2) - Cq[i]) >= 0)
        share.append(Tq[j] + v[j].mul(v[j]).sc(Fr(n, 2)))
    g2 = qsum(share, zq)
    less = {(a, b): ctx.sign(w[a] - w[b]) < 0
            for a in range(m) for b in range(m)}
    diag = qsum((Um[a][a] for a in range(m)), zq)
    out = []
    for rank in itertools.permutations(range(m)):
        if any(less[a, b] and rank[a] > rank[b]
               for a in range(m) for b in range(m)):
            continue
        D = [Um[a][a] + qsum((Um[a][b] for b in range(m)
                              if rank[b] < rank[a]), zq).sc(2)
             for a in range(m)]
        rev = diag + qsum((Um[a][b] for a in range(m) for b in range(m)
                           if rank[a] < rank[b]), zq).sc(2)
        out.append({"rank": rank, "lb": qsum(D, zq), "rev": rev,
                    "D": D})
    return {"U": Um, "g2": g2, "share": share, "orders": out}


def cuts(m):
    d = m - 1
    return ([Aff.const(0, d)] + [Aff.var(i, d) for i in range(d)]
            + [Aff.const(1, d)])


def point_cuts(widths):
    tot = sum(Fr(x) for x in widths)
    C, c = [Aff.const(0, 0)], Fr(0)
    for x in widths:
        c += Fr(x) / tot
        C.append(Aff.const(c, 0))
    return C


def at_point(widths):
    return evaluate(Ctx(()), point_cuts(widths))


# --- the definition, a second time ---------------------------------------

def definition(widths):
    """U, G2 and LB at one point from their definitions, sharing nothing
    with the engine above: e_a(y) by cutting I_a + y at the boundaries
    strictly inside it; each integral by the midpoint rule between the
    consecutive points of a superset of its kinks (where an end meets a
    boundary, and every crossing of two of the lines a piece's length, a
    tent's side or its floor 0 can be), exact since the integrand is one
    line between them."""
    tot = sum(Fr(x) for x in widths)
    w = [Fr(x) / tot for x in widths]
    m = len(w)

    def ends(ws):
        c = [Fr(0)]
        for x in ws:
            c.append(c[-1] + x)
        return c

    def crossings(lines):
        return [(i2 - i1) / (s1 - s2) for s1, i1 in lines
                for s2, i2 in lines if s1 != s2]

    def integral(f, lo, hi, kinks):
        pts = sorted({lo, hi} | {x for x in kinks if lo < x < hi})
        return sum((v - u) * f((u + v) / 2) for u, v in zip(pts, pts[1:]))

    c = ends(w)

    def u(a, b):
        lo, hi = c[a], c[a + 1]

        def e(y):
            cut = ([lo + y] + [x for x in c[1:] if lo + y < x < hi + y]
                   + [hi + y])
            return w[a] - max(q - p for p, q in zip(cut, cut[1:]))
        lines = ([(-1, x - lo) for x in c[1:]] + [(1, hi - x) for x in c[1:]]
                 + [(0, x2 - x1) for x1 in c[1:] for x2 in c[1:] if x1 < x2])
        meets = [x - z for x in c[1:] for z in (lo, hi)]
        return integral(e, c[b], c[b + 1], meets + crossings(lines))

    Um = [[u(a, b) for b in range(m)] for a in range(m)]
    v = sorted(w)
    cq = ends(v)

    def t(j):
        r = v[j] / 2

        def h(x):
            return max([Fr(0)] + [r - abs(x - beta) for beta in cq[1:]])
        lines = ([(0, Fr(0))] + [(1, r - beta) for beta in cq[1:]]
                 + [(-1, r + beta) for beta in cq[1:]])
        return integral(h, 2 * cq[j] + r, cq[j] + cq[j + 1] + r,
                        crossings(lines))

    s1 = sum((v[b] ** 2 for j in range(1, m + 1) for b in range(j)
              if 2 * cq[b] >= cq[j]), Fr(0))
    lb = sum(Um[a][a] for a in range(m))
    for a in range(m):
        for b in range(a + 1, m):
            lb += 2 * (Um[a][b] if w[a] >= w[b] else Um[b][a])
    return {"U": Um, "g2": sum(t(j) for j in range(m)) + s1 / 2, "lb": lb}


def nodes(P):
    """The six nodes of the triangle on P's first three vertices, each
    pulled 1/8 toward the centroid: its corners and its sides' midpoints,
    inside the open P when P is convex. A quadratic 0 at the six is 0: it
    has three zeros on each side's line."""
    Cn = centroid(P)
    A, B, C = (tuple((7 * x + c) / 8 for x, c in zip(X, Cn)) for X in P[:3])
    return [A, B, C, centroid([A, B]), centroid([B, C]), centroid([C, A])]


def against(r, Y):
    """True iff the face record r, read at the point Y, is the
    definition's there: G2, LB at every order, and every U_ab."""
    d = definition(widths_of(Y))
    m = len(d["U"])
    return (r["g2"].at(Y) == d["g2"]
            and all(o["lb"].at(Y) == d["lb"] for o in r["orders"])
            and all(r["U"][a][b].at(Y) == d["U"][a][b]
                    for a in range(m) for b in range(m)))


def faces_off(run):
    """(counts, off): how many points of the run's cells, segments and
    read vertices were set against the definition (six nodes a cell, the
    quarter points of a segment, each vertex), and the points that
    differ, each with its kind."""
    pts = [("cell", r, Y) for P, r in run.cells for Y in nodes(P)]
    pts += [("segment", r, tuple(a + (b - a) * Fr(k, 4) for a, b in zip(A, B)))
            for (A, B), r in run.segs for k in (1, 2, 3)]
    pts += [("vertex", r, X) for X, r in run.verts.items() if r is not None]
    counts = tuple(sum(kind == k for kind, _, _ in pts)
                   for k in ("cell", "segment", "vertex"))
    return counts, [(kind, Y) for kind, r, Y in pts if not against(r, Y)]


# --- faces ---------------------------------------------------------------

def centroid(P):
    n = len(P)
    return tuple(sum(x[i] for x in P) / n for i in range(len(P[0])))


def mixed(f, P):
    s = [f.at(x) for x in P]
    return any(v > 0 for v in s) and any(v < 0 for v in s)


def split_poly(P, f):
    out = ([], [])
    n = len(P)
    for i in range(n):
        A, B = P[i], P[(i + 1) % n]
        fa, fb = f.at(A), f.at(B)
        if fa >= 0:
            out[0].append(A)
        if fa <= 0:
            out[1].append(A)
        if (fa > 0 and fb < 0) or (fa < 0 and fb > 0):
            t = fa / (fa - fb)
            X = tuple(a + t * (b - a) for a, b in zip(A, B))
            out[0].append(X)
            out[1].append(X)
    return out


def seg_min(q, A, B):
    """[(value, point, interior)]: the candidates for the least of q on
    [A, B], interior when off both ends."""
    D = tuple(b - a for a, b in zip(A, B))
    al, be, ga = q.along(A, D)
    c = [(ga, A, False), (al + be + ga, B, False)]
    if al > 0:
        t = -be / (2 * al)
        if 0 < t < 1:
            c.append((al * t * t + be * t + ga,
                      tuple(a + t * x for a, x in zip(A, D)), True))
    return c


def poly_min(q, P):
    c = []
    for i in range(len(P)):
        c += [(v, X, False) for v, X, _ in
              seg_min(q, P[i], P[(i + 1) % len(P)])]
    a, b, cc = q.q.get((1, 1), 0), q.q.get((1, 2), 0), q.q.get((2, 2), 0)
    det = 4 * a * cc - b * b
    if a > 0 and det > 0:
        dx, dy = q.q.get((0, 1), 0), q.q.get((0, 2), 0)
        X = (-2 * cc * dx + b * dy) / det
        Y = (b * dx - 2 * a * dy) / det
        if strictly_inside((X, Y), P):
            c.append((q.at((X, Y)), (X, Y), True))
    return c


def strictly_inside(X, P):
    n = len(P)
    s = []
    for i in range(n):
        A, B = P[i], P[(i + 1) % n]
        s.append((B[0] - A[0]) * (X[1] - A[1]) - (B[1] - A[1]) * (X[0] - A[0]))
    return all(v > 0 for v in s) or all(v < 0 for v in s)


def on_edge_of_domain(X, m):
    if m == 2:
        return X[0] in (0, 1)
    return X[0] == 0 or X[0] == X[1] or X[1] == 1


class Run:
    def __init__(self, m):
        self.m = m
        self.cells, self.segs, self.verts = [], [], {}

    def eval_at(self, p):
        ctx = Ctx(p)
        return ctx, evaluate(ctx, cuts(self.m))

    def cell(self, P0):
        stack = [P0]
        while stack:
            P = stack.pop()
            ctx, r = self.eval_at(centroid(P))
            f = next((f for f in ctx.forms.values() if mixed(f, P)), None)
            if f is None:
                self.cells.append((P, r))
            else:
                stack.extend(Q for Q in split_poly(P, f) if len(Q) >= 3)

    def seg(self, A0, B0):
        stack = [(A0, B0)]
        while stack:
            A, B = stack.pop()
            ctx, r = self.eval_at(centroid([A, B]))
            f = next((f for f in ctx.forms.values() if mixed(f, [A, B])),
                     None)
            if f is None:
                self.segs.append(((A, B), r))
                for X in (A, B):
                    self.verts.setdefault(X, None)
            else:
                fa, fb = f.at(A), f.at(B)
                t = fa / (fa - fb)
                X = tuple(a + t * (b - a) for a, b in zip(A, B))
                stack += [(A, X), (X, B)]

    def faces(self):
        m = self.m
        if m == 2:
            self.seg((Fr(0),), (Fr(1),))
        else:
            self.cell([(Fr(0), Fr(0)), (Fr(0), Fr(1)), (Fr(1), Fr(1))])
            edges = set()
            for P, _ in self.cells:
                for i in range(len(P)):
                    A, B = P[i], P[(i + 1) % len(P)]
                    if (on_edge_of_domain(A, m) and on_edge_of_domain(B, m)
                            and on_edge_of_domain(centroid([A, B]), m)):
                        continue
                    edges.add((min(A, B), max(A, B)))
                    self.verts.setdefault(A, None)
                    self.verts.setdefault(B, None)
            for A, B in sorted(edges):
                self.seg(A, B)
        for X in list(self.verts):
            if not on_edge_of_domain(X, m):
                self.verts[X] = self.eval_at(X)[1]


def least_over(run, terms):
    """{label: (least, point, ranks)} of each quadratic terms(r, o) names,
    over every cell, segment and vertex and every order read there."""
    best = {}

    def take(lab, c, rank):
        for v, X, _ in c:
            if lab not in best or v < best[lab][0]:
                best[lab] = (v, X, rank)
    for P, r in run.cells:
        for o in r["orders"]:
            for lab, q in terms(r, o).items():
                take(lab, poly_min(q, P), o["rank"])
    for (A, B), r in run.segs:
        for o in r["orders"]:
            for lab, q in terms(r, o).items():
                take(lab, seg_min(q, A, B), o["rank"])
    for X, r in run.verts.items():
        if r is not None:
            for o in r["orders"]:
                for lab, q in terms(r, o).items():
                    take(lab, [(q.at(X), X, True)], o["rank"])
    return best


def on_seg(X, A, B):
    u = [x - a for x, a in zip(X, A)]
    v = [b - a for a, b in zip(A, B)]
    cross = u[0] * v[1] - u[1] * v[0] if len(X) == 2 else 0
    dot = sum(x * y for x, y in zip(u, v))
    return cross == 0 and 0 <= dot <= sum(y * y for y in v)


# --- the cover -----------------------------------------------------------

def area(P):
    n = len(P)
    return abs(sum(P[i][0] * P[(i + 1) % n][1] - P[(i + 1) % n][0] * P[i][1]
                   for i in range(n))) / 2


def outside(cells):
    """How many vertices of the cells lie off the closed simplex 0 <=
    c_1 <= c_2 <= 1."""
    return sum(not 0 <= X[0] <= X[1] <= 1 for P in cells for X in P)


def convex(P):
    """True iff every edge's line has every other vertex strictly on one
    side, the same side all round: P is convex in its cyclic order, no
    three vertices in a line."""
    n = len(P)
    s = [(B[0] - A[0]) * (X[1] - A[1]) - (B[1] - A[1]) * (X[0] - A[0])
         for A, B in zip(P, P[1:] + P[:1]) for X in P if X not in (A, B)]
    return n >= 3 and (all(v > 0 for v in s) or all(v < 0 for v in s))


def apart(P, Q):
    """True iff the line of an edge of P or of Q has every vertex of one
    on its closed side and every vertex of the other on the opposite
    closed side: the hulls then share no interior point, and two convex
    polygons sharing none have such an edge."""
    for F, G in ((P, Q), (Q, P)):
        n = len(F)
        for i in range(n):
            A, B = F[i], F[(i + 1) % n]
            nx, ny = B[1] - A[1], A[0] - B[0]
            f = [nx * (X[0] - A[0]) + ny * (X[1] - A[1]) for X in F]
            g = [nx * (X[0] - A[0]) + ny * (X[1] - A[1]) for X in G]
            if max(f) <= 0 <= min(g) or max(g) <= 0 <= min(f):
                return True
    return False


def holes(run, A, B):
    """How many stretches of the closed segment [A, B] the run does not
    read: the open intervals between consecutive ends of its open
    segments lying in [A, B] that none of them contains, and the ends
    (A and B with them) off the domain's boundary that lie in none and
    hold no vertex record."""
    v = [b - a for a, b in zip(A, B)]
    vv = sum(y * y for y in v)
    spans = []
    for (C, D), _ in run.segs:
        if on_seg(C, A, B) and on_seg(D, A, B):
            s, t = (sum((x - a) * y for x, a, y in zip(X, A, v)) / vv
                    for X in (C, D))
            spans.append((min(s, t), max(s, t)))
    pts = sorted({Fr(0), Fr(1)} | {x for sp in spans for x in sp})
    bad = 0
    for s, t in zip(pts, pts[1:]):
        bad += not any(lo < (s + t) / 2 < hi for lo, hi in spans)
    for t in pts:
        X = tuple(a + t * y for a, y in zip(A, v))
        bad += not (on_edge_of_domain(X, run.m)
                    or any(lo < t < hi for lo, hi in spans)
                    or run.verts.get(X) is not None)
    return bad


def tied(run):
    """(n, off, wide): the segments and vertices holding more than one
    order of equal widths, those among them where two orders' LB differ
    on the face, and the cells holding more than one order."""
    n = off = 0
    for (A, B), r in run.segs:
        o = r["orders"]
        if len(o) > 1:
            D = tuple(b - a for a, b in zip(A, B))
            n += 1
            off += any((x["lb"] - o[0]["lb"]).along(A, D) != (0, 0, 0)
                       for x in o)
    for X, r in run.verts.items():
        if r is not None and len(r["orders"]) > 1:
            n += 1
            off += any(x["lb"].at(X) != r["orders"][0]["lb"].at(X)
                       for x in r["orders"])
    return n, off, sum(len(r["orders"]) > 1 for _, r in run.cells)


def zero_set(run):
    """Where LB - G2 is 0 off the domain's boundary, read at each face's
    first order: (joined, breaks, zeros, inside). joined: the open
    segments on which it vanishes identically, joined end to end;
    breaks: the read vertices on a joined segment, its ends in, where it
    is not 0; zeros: every other zero at a vertex or at a segment's
    critical point; inside: the cells holding a zero in their interior.
    With LB - G2 >= 0 on a closed convex cell, a zero inside is a local
    least, so the form is positive definite about it (the one zero in
    the plane, the cell's interior critical point), or c l^2 for a line
    l through it, or 0 (the centroid with it). The line leaves the cell
    at two boundary points, each a vertex or an edge's critical point,
    and no other candidate is 0: the first zero candidate is an end of
    the chord, and the chord's midpoint is inside and 0."""
    def gap(r):
        return r["orders"][0]["lb"] - r["g2"]
    flat, zeros = [], []
    for (A, B), r in run.segs:
        D = tuple(b - a for a, b in zip(A, B))
        if gap(r).along(A, D) == (0, 0, 0):
            flat.append((A, B))
        else:
            zeros += [X for v, X, i in seg_min(gap(r), A, B) if v == 0 and i]
    joined = []
    for A, B in sorted(flat):
        if joined and joined[-1][1] == A and on_seg(A, joined[-1][0], B):
            joined[-1] = (joined[-1][0], B)
        else:
            joined.append((A, B))
    breaks = 0
    for X, r in run.verts.items():
        if r is not None:
            on = any(on_seg(X, A, B) for A, B in joined)
            if gap(r).at(X) != 0:
                breaks += on
            elif not on:
                zeros.append(X)
    inside = 0
    for P, r in run.cells:
        z = [X for v, X, _ in poly_min(gap(r), P) if v == 0]
        inside += any(strictly_inside(M, P) and gap(r).at(M) == 0
                      for M in [centroid(P)]
                      + [centroid([z[0], Y]) for Y in z])
    return joined, breaks, sorted(set(zeros)), inside


def widths_of(X):
    c = (Fr(0),) + tuple(X) + (Fr(1),)
    return tuple(c[i + 1] - c[i] for i in range(len(c) - 1))


def fmt(X):
    return "(" + ", ".join(str(x) for x in X) + ")"


def hand_m2(x):
    """The hand forms of BY HAND: (LB_s, G2) at widths (x, 1 - x)."""
    s = min(x, 1 - x)
    L, M = 1 - s, 1 - 2 * s
    if s == HALF:
        return Fr(3, 16), Fr(3, 16)
    g2 = L * L / 4 - s * s / 4 if s <= Fr(1, 3) else s * s / 4 + M * M / 2
    if x < HALF:
        gap = s * s if s <= Fr(1, 3) else 3 * s - Fr(7, 2) * s * s - HALF
    else:
        gap = (s / 2 + s * s / 2 if s <= Fr(1, 4)
               else Fr(5, 2) * s - Fr(7, 2) * s * s - Fr(1, 4))
    return g2 + gap, g2


# --- sections ------------------------------------------------------------

def control_row(widths, unit, U, shares, orders):
    """The fields of evaluate at the widths that differ from a hand row
    in units of 1/unit: U, the shares by rank, G2 as their sum, the
    orders, and at each order D by position, LB as its sum and the
    reverse charge."""
    r = at_point(widths)

    def val(q):
        return q.at(()) * unit
    off = []
    if [[val(x) for x in row] for row in r["U"]] != U:
        off.append("U")
    if [val(x) for x in r["share"]] != shares:
        off.append("shares")
    if val(r["g2"]) != sum(shares):
        off.append("G2")
    if sorted(o["rank"] for o in r["orders"]) != sorted(orders):
        off.append("orders")
    for o in r["orders"]:
        D, rev = orders.get(o["rank"], ([], None))
        if [val(x) for x in o["D"]] != D:
            off.append(f"D at {o['rank']}")
        if val(o["lb"]) != sum(D):
            off.append(f"LB at {o['rank']}")
        if val(o["rev"]) != rev:
            off.append(f"rev at {o['rank']}")
    return off


def section_controls():
    print("CONTROLS")
    import numpy as np
    from erring_cells import shifts, sorted_g2
    from erring_lower import cuts_of
    pts = ([(k, 23 - k) for k in range(1, 23)]
           + [(a, b, 17 - a - b) for a in range(1, 16)
              for b in range(1, 17 - a)]
           + [(3, 1, 4, 1), (5, 9, 2, 6), (2, 7, 1, 8), (1, 1, 2, 3),
              (1, 1, 1, 1)])
    du = dg = 0.0
    for wt in pts:
        r = at_point(wt)
        Uf = np.array([[float(x.at(())) for x in row] for row in r["U"]])
        du = max(du, float(np.abs(Uf - shifts(cuts_of(wt))).max()))
        dg = max(dg, abs(float(r["g2"].at(())) - sorted_g2(wt)))
    check("X2 U and G2 against erring_cells at 147 widths", du < 1e-12
          and dg < 1e-12 and len(pts) == 147,
          f"({len(pts)} widths: max |dU| {du:.1e}, |dG2| {dg:.1e})")
    q, h = Fr(1, 4), HALF
    rows = (
        ("H1 (1, 1, 2)/4", (1, 1, 2), 16,
         [[q, q, q], [q, 0, q], [h, h, 0]], [q, h, 2],
         {(0, 1, 2): ([q, h, 2], 7 * q), (1, 0, 2): ([3 * q, 0, 2], 7 * q)}),
        ("H2 (1, 1, 1)/3", (1, 1, 1), 9,
         [[q, q, q], [q, q, 0], [q, 0, 0]], [q, 3 * q, h],
         {(0, 1, 2): ([q, 3 * q, h], 3 * h),
          (0, 2, 1): ([q, 3 * q, h], 3 * h),
          (1, 0, 2): ([3 * q, q, h], 3 * h),
          (1, 2, 0): ([3 * q, 3 * q, 0], 3 * h),
          (2, 0, 1): ([5 * q, q, 0], 3 * h),
          (2, 1, 0): ([5 * q, q, 0], 3 * h)}),
        ("H3 (2, 4, 2, 5)/13", (2, 4, 2, 5), 169,
         [[1, 1, 1, 1], [2, 6, h, 7 * h], [1, h, h, 0], [2, 17 * q, 0, 0]],
         [1, 2, 23 * h, 25 * h],
         {(0, 2, 1, 3): ([1, 11, 5 * h, 25 * h], 43 * h),
          (1, 2, 0, 3): ([3, 11, h, 25 * h], 43 * h)}),
        ("H4 (2, 1)/3", (2, 1), 9,
         [[3 * h, h], [q, 0]], [q, h], {(1, 0): ([5 * h, 0], 2)}))
    for name, w, unit, U, shares, orders in rows:
        off = control_row(w, unit, U, shares, orders)
        check(f"{name} equals its hand row", not off,
              f"(fields off: {', '.join(off) or 'none'}; "
              f"{len(orders)} orders)")
    section_definition(rows)
    section_minimizer()


def section_definition(rows):
    """The second evaluator on the hand rows, then nodes, against and
    faces_off on hand cases."""
    F = Fr
    off = []
    for name, w, unit, U, shares, orders in rows:
        d = definition(w)
        if [[x * unit for x in row] for row in d["U"]] != U:
            off.append(name[:2] + " U")
        if d["g2"] * unit != sum(shares):
            off.append(name[:2] + " G2")
        if {d["lb"] * unit} != {sum(D) for D, _ in orders.values()}:
            off.append(name[:2] + " LB")
    check("D1 the definition's U, G2 and LB equal the four hand rows",
          not off, f"(fields off: {', '.join(off) or 'none'})")
    tri = [(F(0), F(0)), (F(0), F(1)), (F(1), F(1))]
    six = [(F(1, 24), F(1, 12)), (F(1, 24), F(23, 24)),
           (F(11, 12), F(23, 24)), (F(1, 24), F(25, 48)),
           (F(23, 48), F(23, 24)), (F(23, 48), F(25, 48))]
    X = (F(1, 4), HALF)
    r = Run(3).eval_at(X)[1]
    one = Aff.const(1, 2).mul(Aff.const(1, 2))
    o = r["orders"]
    wrong = (r, dict(r, g2=r["g2"] + one),
             dict(r, orders=[o[0], dict(o[1], lb=o[1]["lb"] + one)]),
             dict(r, U=r["U"][:2] + [r["U"][2][:2] + [r["U"][2][2] + one]]))
    got = [against(x, X) for x in wrong]
    run = Run(2)
    r1, r3 = run.eval_at((F(1, 6),))[1], run.eval_at((F(1, 3),))[1]
    run.segs = [(((F(0),), (F(1, 3),)), r1), (((F(1, 3),), (HALF,)), r1)]
    run.verts = {(F(0),): None, (F(1, 3),): r3, (HALF,): r1}
    far = faces_off(run)
    check("D2 nodes, against and faces_off on hand cases",
          nodes(tri) == six and got == [True, False, False, False]
          and far == ((0, 6, 2), [("segment", (F(3, 8),)),
                                  ("segment", (F(5, 12),)),
                                  ("segment", (F(11, 24),)),
                                  ("vertex", (HALF,))]),
          f"(six nodes of the simplex; at (1, 1, 2)/4 the record, then G2, "
          f"the second order's LB and U_33 each moved: {got}; at m = 2 the "
          f"first segment's record on the second and on the cut 1/2: "
          f"{far[0]} points, {len(far[1])} off)")


def section_minimizer():
    """poly_min, seg_min and least_over on one convex quadratic, critical
    at (1/5, 1/2) with value -7/100, and on its negative."""
    q = (Aff((0, 2, 1)).mul(Aff.var(0, 2)) + Aff((0, 0, 1)).mul(Aff.var(1, 2))
         + Aff((Fr(9, 25), Fr(-13, 10), Fr(-6, 5))).mul(Aff.const(1, 2)))
    neg = q.sc(-1)
    one = Aff.const(1, 2).mul(Aff.const(1, 2))
    up = q + one
    F = Fr
    tri = [(F(0), F(0)), (F(0), F(1)), (F(1), F(1))]
    box = [(F(3, 10), F(0)), (F(1), F(0)), (F(1), F(1)), (F(3, 10), F(1))]
    far = [(HALF, HALF), (HALF, F(1)), (F(1), F(1))]
    sq = [(F(0), F(0)), (F(1), F(0)), (F(1), F(1)), (F(0), F(1))]
    wide = [(F(-1), F(0)), (F(1), F(0)), (F(1), F(1)), (F(-1), F(1))]
    top = (F(1, 5), HALF)
    x, y, c1 = Aff.var(0, 2), Aff.var(1, 2), Aff.const(1, 2)
    tall = [(F(0), F(-1)), (F(1), F(-1)), (F(1), F(1)), (F(0), F(1))]
    bowl = x.mul(x) + y.mul(y) + Aff((F(-1, 12), 0, -1)).mul(c1)
    bowl2 = x.mul(x) + y.mul(y) + Aff((F(-1, 12), -1, 0)).mul(c1)
    troughs = ((y.mul(y) + Aff((0, 0, -1)).mul(c1), wide),
               (x.mul(x) + Aff((0, -1, 0)).mul(c1), tall))
    polys = ((q, tri, F(-7, 100), top, True),
             (q, sq, F(-7, 100), top, True),
             (q.sc(F(1, 4)), tri, F(-7, 400), top, True),
             (bowl, wide, F(-1, 3), (F(0), HALF), True),
             (bowl2, tall, F(-1, 3), (HALF, F(0)), True),
             (q, box, F(-21, 400), (F(3, 10), F(9, 20)), False),
             (q, far, F(11, 100), (HALF, HALF), False),
             (neg, tri, F(-93, 50), (F(1), F(1)), False))
    off = sum(min(poly_min(p, P), key=lambda c: c[0]) != (v, X, i)
              for p, P, v, X, i in polys)
    flat = sum(i for p, P in troughs for _, _, i in poly_min(p, P))
    check("M1 poly_min on eight hand polygons and two troughs",
          off == 0 and flat == 0,
          f"({off} off: five interior leasts, an edge's, a vertex's, a "
          f"concave form's; {flat} interior points on y^2 - y, x^2 - x)")
    a, b = (F(3, 10), F(0)), (F(3, 10), F(1))
    segs = ((q, a, b, F(-21, 400), (F(3, 10), F(9, 20)), True),
            (q, (F(3, 10), HALF), b, F(-1, 20), (F(3, 10), HALF), False),
            (q, tri[0], tri[2], F(-49, 1600), (F(5, 16), F(5, 16)), True),
            (q, tri[1], (F(1), F(0)), F(7, 800), (F(11, 40), F(29, 40)),
             True),
            (neg, a, b, F(-1, 4), b, False))
    off = sum(min(seg_min(p, A, B), key=lambda c: c[0]) != (v, X, i)
              for p, A, B, v, X, i in segs)
    check("M2 seg_min on five hand segments", off == 0, f"({off} off)")
    diag = (tri[0], tri[2])
    low = (F(3, 10), HALF)

    def rec(*qs):
        return {"orders": [{"rank": (k,), "q": p} for k, p in enumerate(qs)]}
    runs = (([(far, rec(q)), (tri, rec(up, q))],
             [((a, b), rec(q)), (diag, rec(q))], (low, rec(q)),
             (F(-7, 100), top, (1,))),
            ([(far, rec(q)), (far, rec(up))],
             [(diag, rec(q)), ((a, b), rec(up, q))], (low, rec(q)),
             (F(-21, 400), (F(3, 10), F(9, 20)), (1,))),
            ([(far, rec(q)), (box, rec(q))],
             [(diag, rec(q)), ((a, b), rec(q))], (top, rec(up, q)),
             (F(-7, 100), top, (1,))))
    off = 0
    for cells, segs, vert, want in runs:
        run = Run(3)
        run.cells, run.segs = cells, segs
        run.verts = {far[0]: rec(q), tri[1]: None, vert[0]: vert[1]}
        best = least_over(run, lambda r, o: {"high": o["q"] + one,
                                             "low": o["q"]})
        off += best["low"] != want or best["high"][0] != want[0] + 1
    check("M3 least_over on three hand runs", off == 0,
          f"({off} off: the least in the second cell, in the second "
          "segment, at the last vertex, each at its second order and "
          "under its second label)")

    def shift(P, dx, dy):
        return [(x + dx, y + dy) for x, y in P]
    pairs = ((sq, shift(sq, 1, 0), True), (sq, shift(sq, HALF, HALF), False),
             (sq, [(F(1, 4), F(1, 4)), (F(1, 4), HALF), (HALF, HALF)],
              False), (tri, shift(tri, 0, 1), True),
             (tri, [(F(0), F(0)), (F(1), F(1)), (F(1), F(0))], True),
             (sq, shift(sq, 1, 1), True),
             (sq, [(HALF, F(2)), (F(2), HALF), (F(2), F(2))], True))
    off = sum(apart(P, Q) != want or apart(Q, P) != want
              for P, Q, want in pairs)
    check("M4 apart on seven hand pairs, both ways", off == 0 and
          [area(sq), area(tri), area(box)] == [1, HALF, F(7, 10)],
          f"({off} off: squares sharing an edge, overlapping, a triangle "
          "inside, two sharing a corner or a diagonal, a triangle past a "
          "corner that no edge of the square separates; three areas)")
    up1 = shift(tri, 0, 1)
    left = [(F(-1), F(1)), (F(0), F(0)), (F(0), F(1))]
    dart = [(F(0), F(0)), (F(1), F(0)), (F(1, 4), F(1, 4)), (F(0), F(1))]
    line = [(F(0), F(0)), (HALF, F(0)), (F(1), F(0)), (F(0), F(1))]
    bow = [(F(0), F(0)), (F(1), F(1)), (F(1), F(0)), (F(0), F(1))]
    got = ([outside([P]) for P in (tri, sq, wide, up1, left)]
           + [outside([sq, wide, up1])],
           [convex(P) for P in (tri, tri[::-1], sq, box, dart, line,
                                line[::-1], bow, tri[:2])])
    check("M8 outside and convex on hand polygons",
          got == ([0, 1, 3, 2, 1, 6],
                  [True, True, True, True] + [False] * 5),
          f"({got[0]} vertices off the simplex: none, c_1 > c_2, three of "
          f"a wide box, c_2 > 1 twice, c_1 < 0, three cells together; "
          f"convex {got[1]}: the simplex both ways round, two boxes, a "
          "dart, three vertices in a line both ways round, a bowtie, two "
          "points)")
    A, M, B = (F(1, 4), HALF), (F(1, 4), F(3, 4)), (F(1, 4), F(1))
    N = (F(1, 4), F(5, 8))
    got = []
    for segs, verts in (([(A, M), (M, B)], {A: 1, M: 1}),
                        ([(A, M)], {A: 1, M: 1}),
                        ([(A, M), (M, B)], {A: 1, M: None}),
                        ([(A, M), (M, B), (A, B)], {A: 1, M: None}),
                        ([(A, M), (M, B)], {M: 1}),
                        ([(M, A), (B, M)], {A: 1, M: 1}),
                        ([(M, B)], {A: 1, M: 1}),
                        ([(A, N), (N, M), (M, B)], {A: 1, N: 1, M: None}),
                        ([(A, N), (M, B)], {A: 1, M: 1})):
        run = Run(3)
        run.segs, run.verts = [(s, None) for s in segs], verts
        got.append(holes(run, A, B))
    check("M5 holes on nine hand runs", got == [0, 1, 1, 0, 1, 0, 1, 1, 2],
          f"({got}: whole, a segment gone, a vertex unread, the same "
          "under a longer segment, an end unread, the segments reversed, "
          "the first segment gone, a later vertex unread, a gap with an "
          "unread end)")

    def gaps(*lbs):
        return {"orders": [{"lb": p} for p in lbs], "g2": Quad()}
    line = Aff((F(-1, 4), -1, 1))
    zq = line.mul(line)
    Z0, Z1, Z2 = (F(1, 4), HALF), (HALF, F(3, 4)), (F(5, 8), F(7, 8))
    off0, off1 = (F(1, 16), F(5, 16)), (F(1, 8), F(3, 8))
    W, Z3, Z4 = (F(5, 8), F(15, 16)), (F(11, 16), F(15, 16)), (F(23, 32),
                                                               F(31, 32))
    run = Run(3)
    run.cells = [(far, gaps(up)), (tri, gaps(zq)),
                 (sq, gaps(x.mul(Aff((1, 0, -1))))), (sq, gaps(zq)),
                 (tri, gaps(Quad())), (tri, gaps(q + one.sc(F(7, 100))))]
    run.segs = [((Z0, Z1), gaps(zq)), ((Z1, Z2), gaps(zq)),
                ((Z2, W), gaps(Quad())), ((Z3, Z4), gaps(zq)),
                (((F(1, 8), F(1, 4)), (F(1, 8), HALF)), gaps(zq))]
    run.verts = {Z0: gaps(zq), Z1: gaps(up), off0: gaps(zq), tri[1]: None,
                 Z4: gaps(up)}
    got = zero_set(run)
    check("M6 zero_set on a hand run with the zero line y = x + 1/4",
          got == ([(Z0, Z2), (Z2, W), (Z3, Z4)], 2, [off0, off1], 4),
          f"({len(got[0])} zero segments (two joined, one turning off the "
          f"line, one past a gap), {got[1]} vertices on them not 0, "
          f"{len(got[2])} other zeros, {got[3]} cells of six with a zero "
          "inside: the line crosses two from boundary to boundary, one "
          "form is 0 on its whole triangle, one at its critical point "
          "alone, and x(1 - y) on the square is 0 at two corners with 1/4 "
          "between)")
    skew = q + Aff((F(-3, 10), 1, 0)).mul(y)
    run = Run(3)
    run.cells = [(tri, gaps(q)), (far, gaps(q, q))]
    run.segs = [((a, b), gaps(q)), ((a, b), gaps(q, skew)),
                (diag, gaps(q, skew))]
    run.verts = {tri[1]: None, top: gaps(q), a: gaps(q, skew),
                 far[0]: gaps(q, up)}
    got = tied(run)
    check("M7 tied on a hand run", got == (4, 2, 1),
          f"({got}: four faces with two orders, two differing on the "
          "face, one equal on its segment and not off it, one cell)")


def section_m2():
    print("m = 2")
    run = Run(2)
    run.faces()
    bad = n = 0
    for (A, B), r in run.segs:
        o = r["orders"]
        for k in range(1, 7):
            x = A[0] + (B[0] - A[0]) * k / 7
            lb, g2 = hand_m2(x)
            n += 1
            bad += (len(o) != 1 or o[0]["lb"].at((x,)) != lb
                    or r["g2"].at((x,)) != g2)
    for X, r in run.verts.items():
        if r is not None:
            lb, g2 = hand_m2(X[0])
            n += 1
            bad += (min(o["lb"].at(X) for o in r["orders"]) != lb
                    or r["g2"].at(X) != g2)
    check("X1 the engine equals the hand forms at 34 points", bad == 0
          and n == 34, f"({bad} mismatches at {n} points: six a segment "
          "and every cut)")
    cut = [X[0] for X in sorted(run.verts)]
    gaps = holes(run, (Fr(0),), (Fr(1),))
    check("V1 five open segments and their four cuts cover (0, 1)",
          gaps == 0 and len(run.segs) == 5
          and cut == [0, Fr(1, 3), HALF, Fr(2, 3), Fr(3, 4), 1],
          f"({gaps} holes; {len(run.segs)} segments, cut at "
          f"{', '.join(str(x) for x in cut)})")
    counts, far = faces_off(run)
    check("X5 the definition at three points a segment and every cut",
          not far and counts == (0, 15, 4),
          f"({len(far)} off over {counts}: "
          f"{[(k, fmt(widths_of(Y))) for k, Y in far[:3]]})")
    return run


def section_m3():
    print("m = 3")
    t0 = time.time()
    run = Run(3)
    run.faces()
    nv = sum(r is not None for r in run.verts.values())
    print(f"  {len(run.cells)} cells, {len(run.segs)} segments, {nv} open "
          f"vertices, {time.time() - t0:.1f} s")
    cells = [P for P, _ in run.cells]
    tot = sum(area(P) for P in cells)
    out, bent = outside(cells), sum(not convex(P) for P in cells)
    over = sum(not apart(P, Q) for P, Q in itertools.combinations(cells, 2))
    check("V2 105 convex cells inside the simplex, none overlapping, of "
          "area 1/2", len(cells) == 105 and bent == 0 and out == 0
          and over == 0 and tot == HALF,
          f"({len(cells)} cells, {bent} not convex, {out} vertices outside, "
          f"{over} pairs overlapping, total area {tot})")
    sides = (lambda X: X[0] == 0, lambda X: X[0] == X[1],
             lambda X: X[1] == 1)
    edges = sorted({(min(A, B), max(A, B)) for P in cells
                    for A, B in zip(P, P[1:] + P[:1])
                    if not any(f(A) and f(B) for f in sides)})
    gaps = sum(holes(run, A, B) for A, B in edges)
    check("V3 every cell edge off the boundary read by 163 open segments "
          "and 59 vertices", gaps == 0 and len(edges) == 163
          and len(run.segs) == 163 and nv == 59,
          f"({gaps} holes on {len(edges)} edges; {len(run.segs)} segments, "
          f"{nv} vertices)")
    off = n = 0
    faces = [(P, r) for P, r in run.cells] + [((A, B), r)
                                              for (A, B), r in run.segs]
    for P, r in faces:
        Cn = centroid(P)
        for X in (P[0], P[1]):
            Y = tuple((3 * c + x) / 4 for c, x in zip(Cn, X))
            q = at_point(widths_of(Y))
            n += 1
            off += (q["g2"].at(()) != r["g2"].at(Y)
                    or sorted(o["lb"].at(()) for o in q["orders"])
                    != sorted(o["lb"].at(Y) for o in r["orders"]))
    check("X4 each face's quadratics against two point evaluations",
          off == 0 and n == 2 * (105 + 163),
          f"({off} off over {n}, cells and segments, every order)")
    counts, far = faces_off(run)
    check("X5 the definition at six nodes a cell, three points a segment "
          "and every vertex", not far and counts == (630, 489, 59),
          f"({len(far)} off over {counts}: "
          f"{[(k, fmt(widths_of(Y))) for k, Y in far[:3]]})")
    least, at, _ = least_over(run, lambda r, o: {0: o["rev"] - r["g2"]})[0]
    check("X3 break: the reverse charge's least is -1/16 at (1, 1, 2)/4",
          least == Fr(-1, 16) and at == (Fr(1, 4), HALF),
          f"(least {least} at widths {fmt(widths_of(at))})")
    return run


def section_zeros(r2, r3):
    print("ORDERS AND ZEROS")
    t2, t3 = tied(r2), tied(r3)
    check("O LB the same at every order of equal widths",
          t2 == (1, 0, 0) and t3 == (39, 0, 0),
          f"(m = 2: {t2[0]} face with two orders, {t2[1]} differing; "
          f"m = 3: {t3[0]} segments and vertices with more than one, "
          f"{t3[1]} differing, {t3[2]} cells with more than one)")
    z2, z3 = zero_set(r2), zero_set(r3)
    check("Z2 m = 2: LB_low - G2 is 0 at c_1 = 1/2 alone",
          z2 == ([], 0, [(HALF,)], 0),
          f"({len(z2[0])} zero segments, {z2[1]} vertices on them not 0, "
          f"zeros at {[fmt(X) for X in z2[2]]}, {z2[3]} cells)")
    tie = [((Fr(1, 4), HALF), (Fr(1, 3), Fr(2, 3)))]
    check("Z3 m = 3: 0 on the widths (t, t, 1 - 2t), 1/4 <= t <= 1/3, alone",
          z3 == (tie, 0, [], 0),
          "(zero segments "
          + "; ".join(f"{fmt(widths_of(A))} to {fmt(widths_of(B))}"
                      for A, B in z3[0])
          + f"; {z3[1]} vertices on them not 0; other zeros "
          f"{[fmt(widths_of(X)) for X in z3[2]]}; {z3[3]} cells with a "
          "zero inside)")


def main():
    t0 = time.time()
    section_controls()
    if not all(ok for _, ok in CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        raise SystemExit(1)
    r2 = section_m2()
    r3 = section_m3()
    section_zeros(r2, r3)
    print("KILL")
    least = [least_over(r, lambda r, o: {0: o["lb"] - r["g2"]})[0][0]
             for r in (r2, r3)]
    check("K least LB_low - G2 is 0 at m = 2 and at m = 3, never below",
          least == [0, 0], f"(m = 2 {least[0]}, m = 3 {least[1]})")
    print(f"{sum(ok for _, ok in CHECKS)}/{len(CHECKS)} checks passed, "
          f"{time.time() - t0:.1f} s")
    raise SystemExit(0 if all(ok for _, ok in CHECKS) else 1)


if __name__ == "__main__":
    main()