"""One-parameter families of the three-move game T(a,b): a fixed, b = L*m + e, all m >= MMIN. Candidate value function in base-b digits, verified by Z3 in linear integer arithmetic with m free. Generalizes scripts/a1_uniform.py. Statements proved for the family (via the Lean theorem ThreeMove.certifiedQ, with X0 = p): (A_D) G(x+p, y+r) = G(x, y) for y >= x + D (B_D) G(x+q, y+q) = G(x, y) for p <= x <= y < x + W + D with (p, r, D) as in experiments/open_cases.params (near ranges: D = 0; far ranges: D = a((2m'+1)a - b)). Candidate F on the window [0,X) x [0,Y): walls (x < p) and band (x >= p, y-x < W+D): decision trees in the digits of x, y in base b, of x in base b+a, of y-x in base b-a; above the band: F(x,y) = F(x-p, y-r); below the diagonal: F(y,x). python scripts/fam_uniform.py NAME forms | fit | numeric B1,B2,.. | conv | mex_walls | mex_rest | h1 | h2 | h3 Families: see FAMILIES below. """ import sys, json, math, time, itertools import numpy as np sys.path.insert(0, 'experiments'); sys.path.insert(0, 'scripts') from a1_uniform import tree_names, tree_np from open_cases import params FAMILIES = { # name: (a, L, e, mmin) b = L*m + e 'a1_even': (1, 2, 0, 4), 'a1_odd': (1, 2, -1, 5), 'a2_near': (2, 4, -1, 4), 'a2_far': (2, 4, 1, 6), 'a4_near1': (4, 8, -3, 4), 'a4_near2': (4, 8, -1, 4), 'a3_near1': (3, 6, -2, 4), 'a3_near2': (3, 6, -1, 4), 'a3_far1': (3, 6, 1, 3), 'a3_far2': (3, 6, 2, 3), } BASE = ['kx', 'hx', 'ky', 'hy', 'kxp', 'hxp', 'kd', 'hd'] # h* = (low digit) // a ; e* = (low digit) % a EXTRA = ['ex', 'ey', 'exp', 'ed'] SH1 = (-8, -6, -4, -3, -2, -1, 1, 2, 3, 4, 6, 8); SH3 = (-4, -2, 2, 4) def sh(t): return f'{t:+d}m' def build(B, m, only=None): """features: the digits, their residues, parities, and sums/differences of up to three digits shifted by multiples of m. Works on numpy arrays and on Z3 terms. B has the keys of BASE and EXTRA.""" F = {} def put(name, f): if only is None or name in only: F[name] = f() for n in EXTRA: put(n, lambda: B[n]) for n in BASE: put(n, lambda: B[n]); put(n + '%2', lambda: B[n] % 2) for t in SH1: put(n + sh(t), lambda: B[n] + t * m) for i, j in itertools.combinations(range(8), 2): u, w = B[BASE[i]], B[BASE[j]] put(f'({BASE[i]}+{BASE[j]})%2', lambda: (u + w) % 2) for sg, nm in ((-1, f'{BASE[i]}-{BASE[j]}'), (1, f'{BASE[i]}+{BASE[j]}')): put(nm, lambda: u + sg * w) for t in SH1: put(nm + sh(t), lambda: u + sg * w + t * m) for i, j, l in itertools.combinations(range(8), 3): u, w, z = B[BASE[i]], B[BASE[j]], B[BASE[l]] for su, sw in ((1, 1), (1, -1), (-1, 1), (-1, -1)): nm = f'{BASE[l]}{"+" if su>0 else "-"}{BASE[i]}{"+" if sw>0 else "-"}{BASE[j]}' put(nm, lambda: z + su * u + sw * w) for t in SH3: put(nm + sh(t), lambda: z + su * u + sw * w + t * m) return F class Fam: def __init__(self, name): self.name = name; self.a, self.L, self.e, self.mmin = FAMILIES[name] def b(self, m): return self.L * m + self.e def mof(self, b): assert (b - self.e) % self.L == 0; return (b - self.e) // self.L def raw(self, b): a = self.a; kind, mm, p, r, D, _ = params(a, b); X0 = p; c = b - a; W = r - p; q = p + r Y1 = max(a + b + D, max(b * ((x + p) // a) - r for x in range(a + b)), max(b * (x // a) for x in range(a + b))) X = X0 + p + q + (a + b); Y = max(Y1 + r + 1, X0 + q + (a + b) + D + c + r, X0 + p + b + W + D + q) ok = (a + b <= p) and (p + 2 * c <= r) and all(b * (x // a) <= Y1 and b * ((x + p) // a) <= Y1 + r for x in range(a + b)) and a + b + D <= Y1 return dict(kind=kind, p=p, r=r, q=q, X=X, Y=Y, ab=a + b, H2=X0 + q + a + b, H3=X0 + p + b, Y1p=Y1 + 1, D=D, WD=W + D, side_ok=ok) def forms(self, check_to=160): """every quantity Q as K*base + c with K = k1*m + k0 and c constant (base b, or b-a for WD); verified for many m""" out = {} ms = list(range(self.mmin, self.mmin + check_to)) R = [self.raw(self.b(m)) for m in ms] assert all(t['side_ok'] for t in R), 'side conditions / saturation bounds fail' assert len({t['D'] for t in R}) == 1 and len({t['kind'] for t in R}) == 1 for key in ('p', 'r', 'q', 'X', 'Y', 'ab', 'H2', 'H3', 'Y1p', 'WD'): base = [self.b(m) - (self.a if key == 'WD' else 0) for m in ms] c = [(t[key] + 6) % bb - 6 for t, bb in zip(R, base)] # constant offset, allowed to be slightly negative K = [(t[key] - ci) // bb for t, ci, bb in zip(R, c, base)] k1 = K[1] - K[0]; k0 = K[0] - k1 * ms[0] if not (len(set(c)) == 1 and all(Ki == k1 * m + k0 for Ki, m in zip(K, ms))): raise SystemExit(f'{self.name}: no digit form for {key}: K={K[:6]} c={c[:6]}') out[key] = (k1, k0, c[0]) out['D'] = R[0]['D']; out['kind'] = R[0]['kind'] return out def digits(a, b, xs, ys): d = ys - xs; jx, jy, jxp, jd = xs % b, ys % b, xs % (b + a), d % (b - a) return {'kx': xs // b, 'hx': jx // a, 'ex': jx % a, 'ky': ys // b, 'hy': jy // a, 'ey': jy % a, 'kxp': xs // (b + a), 'hxp': jxp // a, 'exp': jxp % a, 'kd': d // (b - a), 'hd': jd // a, 'ed': jd % a} def load(fam, which): return json.load(open(f'data/fam_{fam.name}_tree_{which}.json'))['tree'] def table(fam, b): from three_fast import sg_fast t = fam.raw(b); a = fam.a return t, sg_fast([(a, b), (b, a), (a + b, a + b)], t['X'], t['Y']) def F_np(fam, b, xs, ys, trees): t = fam.raw(b); a = fam.a; p, r = t['p'], t['r'] xs = xs.copy(); ys = ys.copy(); sw = ys < xs; xs[sw], ys[sw] = ys[sw], xs[sw] for _ in range(3): ab = (xs >= p) & (ys - xs >= t['WD']); xs[ab] -= p; ys[ab] -= r out = np.empty(len(xs), dtype=np.int64); w = xs < p for which, z in (('walls', w), ('band', ~w)): if z.any(): Fd = build(digits(a, b, xs[z], ys[z]), fam.mof(b), tree_names(trees[which])); out[z] = tree_np(trees[which], Fd, int(z.sum())) return out def fit(fam, btrain_max=41, ntest=3, cap=150000, only=None): from sklearn.tree import DecisionTreeClassifier ms = [m for m in range(fam.mmin, 400) if fam.b(m) <= btrain_max]; train = [fam.b(m) for m in ms] test = [fam.b(ms[-1] + k) for k in (1, 2, 4)][:ntest] def data(b, which, cap=None): t, G = table(fam, b); X, Y = t['X'], t['Y'] xs, ys = np.meshgrid(np.arange(X), np.arange(Y), indexing='ij'); k = ys >= xs; xs, ys = xs[k], ys[k] z = (xs < t['p']) if which == 'walls' else ((xs >= t['p']) & (ys - xs < t['WD'])); xs, ys = xs[z], ys[z] if cap and len(xs) > cap: idx = np.random.default_rng(b).choice(len(xs), cap, replace=False); xs, ys = xs[idx], ys[idx] Fd = build(digits(fam.a, b, xs, ys), fam.mof(b)); cols = list(Fd) return np.stack([Fd[c] for c in cols], 1).astype(np.int16), G[xs, ys], cols for which in (only,) if only else ('walls', 'band'): D = [data(b, which, cap) for b in train]; A = np.concatenate([t[0] for t in D]); v = np.concatenate([t[1] for t in D]); cols = D[0][2] T = DecisionTreeClassifier(random_state=0).fit(A, v); t = T.tree_ def rec(i): if t.children_left[i] == -1: return int(T.classes_[t.value[i][0].argmax()]) return [cols[t.feature[i]], math.floor(t.threshold[i]), rec(t.children_left[i]), rec(t.children_right[i])] json.dump(dict(family=fam.name, a=fam.a, b=f'{fam.L}*m{fam.e:+d}', region=which, fitted_on=train, node='[feature, c, subtree if feature <= c, subtree otherwise]; a leaf is the value', tree=rec(0)), open(f'data/fam_{fam.name}_tree_{which}.json', 'w')) msg = f'{fam.name} {which}: fitted on b = {train} ({len(v)} squares): {T.get_n_leaves()} leaves, depth {T.get_depth()}' for b in test: At, vt, _ = data(b, which); msg += f' | b={b}: {int((T.predict(At) != vt).sum())} wrong of {len(vt)}' print(msg, flush=True) def refine(fam, which, btrain_max, extra_b, rounds=8, cap=150000): """fit, then repeatedly add every square of the WHOLE region (for the training b and for extra_b) that the tree gets wrong, and refit, until none is left. The result is still only a candidate; Z3 decides.""" from sklearn.tree import DecisionTreeClassifier ms = [m for m in range(fam.mmin, 400) if fam.b(m) <= btrain_max]; train = [fam.b(m) for m in ms]; pool = train + list(extra_b) def region(b): t, G = table(fam, b); X, Y = t['X'], t['Y'] xs, ys = np.meshgrid(np.arange(X), np.arange(Y), indexing='ij'); k = ys >= xs; xs, ys = xs[k], ys[k] z = (xs < t['p']) if which == 'walls' else ((xs >= t['p']) & (ys - xs < t['WD'])) return xs[z], ys[z], G[xs[z], ys[z]] cols = None; As = []; vs = [] for b in train: xs, ys, g = region(b) if len(xs) > cap: idx = np.random.default_rng(b).choice(len(xs), cap, replace=False); xs, ys, g = xs[idx], ys[idx], g[idx] Fd = build(digits(fam.a, b, xs, ys), fam.mof(b)); cols = list(Fd); As.append(np.stack([Fd[c] for c in cols], 1).astype(np.int16)); vs.append(g) A = np.concatenate(As); v = np.concatenate(vs) for rnd in range(rounds): T = DecisionTreeClassifier(random_state=0).fit(A, v); t = T.tree_ def rec(i): if t.children_left[i] == -1: return int(T.classes_[t.value[i][0].argmax()]) return [cols[t.feature[i]], math.floor(t.threshold[i]), rec(t.children_left[i]), rec(t.children_right[i])] tree = rec(0); names = tree_names(tree) json.dump(dict(family=fam.name, a=fam.a, b=f'{fam.L}*m{fam.e:+d}', region=which, fitted_on=train, refined_on=list(extra_b), node='[feature, c, subtree if feature <= c, subtree otherwise]; a leaf is the value', tree=tree), open(f'data/fam_{fam.name}_tree_{which}.json', 'w')) wrong = {}; addA = []; addv = [] for b in pool: xs, ys, g = region(b); bad = np.zeros(len(xs), dtype=bool) for i0 in range(0, len(xs), 2000000): sl = slice(i0, i0 + 2000000) Fd = build(digits(fam.a, b, xs[sl], ys[sl]), fam.mof(b), names); bad[sl] = tree_np(tree, Fd, len(xs[sl])) != g[sl] wrong[b] = int(bad.sum()) if bad.any(): idx = np.nonzero(bad)[0][:60000] Fd = build(digits(fam.a, b, xs[idx], ys[idx]), fam.mof(b)); addA.append(np.stack([Fd[c] for c in cols], 1).astype(np.int16)); addv.append(g[idx]) print(f'{fam.name} {which} round {rnd}: {T.get_n_leaves()} leaves, depth {T.get_depth()}; wrong squares on whole regions: {wrong}', flush=True) if not addA: break A = np.concatenate([A] + addA); v = np.concatenate([v] + addv) def numeric(fam, bs): trees = {w: load(fam, w) for w in ('walls', 'band')} for b in bs: t, G = table(fam, b); X, Y = t['X'], t['Y']; bad = tot = 0 for x0 in range(0, X, 200): xs, ys = np.meshgrid(np.arange(x0, min(X, x0 + 200)), np.arange(Y), indexing='ij'); xs, ys = xs.ravel(), ys.ravel() bad += int((F_np(fam, b, xs, ys, trees) != G[xs, ys]).sum()); tot += len(xs) print(f'{fam.name} b={b}: window {X} x {Y} = {tot} squares; candidate differs from the true table on {bad}', flush=True) def z3_part(fam, what): from z3 import Int, Ints, IntVal, BoolVal, Solver, If, Or, And, Not, Implies, sat a = fam.a; fm = fam.forms(); D = fm['D'] import os trees = {w: (load(fam, w) if os.path.exists(f'data/fam_{fam.name}_tree_{w}.json') else 0) for w in ('walls', 'band')} if os.environ.get('FAM_CORRUPT'): # sanity test: FAM_CORRUPT=walls,7 changes leaf number 7 of the walls tree in memory only cw, cn = os.environ['FAM_CORRUPT'].split(','); cnt = [int(cn)] def flip(t): if not isinstance(t, list): cnt[0] -= 1; return (t + 1) % 4 if cnt[0] == -1 else t return [t[0], t[1], flip(t[2]), flip(t[3])] trees[cw] = flip(trees[cw]); assert cnt[0] < 0, 'no such leaf' if trees['band'] == 0: assert what == 'mex_walls', 'band tree missing' # wall positions only have wall options need = {w: tree_names(trees[w]) for w in trees} def tz(t, F): return IntVal(t) if not isinstance(t, list) else If(F[t[0]] <= t[1], tz(t[2], F), tz(t[3], F)) def lt(k, j, Kc): K, c = Kc; return Or(k < K, And(k == K, j < c)) def add(k, j, Kc, b): K, c = Kc; return If(j + c >= b, k + K + 1, k + K), If(j + c >= b, j + c - b, j + c) def sub(k, j, Kc, b): K, c = Kc; return If(j - c < 0, k - K - 1, k - K), If(j - c < 0, j - c + b, j - c) class Ctx: def __init__(self): self.s = Solver(); self.n = 0; self.aux = [] self.m = Int('m'); self.b = Int('b'); self.s.add(self.b == fam.L * self.m + fam.e, self.m >= fam.mmin) def q(self, key): k1, k0, c = fm[key]; base = self.b - a if key == 'WD' else self.b return (k1 * self.m + k0, c) if c >= 0 else (k1 * self.m + k0 - 1, c + base) # second digit kept in [0, base) def fresh(self, name): self.n += 1; return Int(f'{name}_{self.n}') def upper(self, P): kx, jx, ky, jy = P; return Or(ky > kx, And(ky == kx, jy >= jx)) def Fup(self, P, guard, depth=0): kx, jx, ky, jy = P; b = self.b kxp, jxp, kd, jd = self.fresh('kxp'), self.fresh('jxp'), self.fresh('kd'), self.fresh('jd') conv_x = Or([And(kxp == kx - c, jxp == jx - a * kx + c * (b + a)) for c in range(0, 2 * a + 3)]) e = a * (ky - kx) + (jy - jx) conv_d = Or([And(kd == ky - kx + c, jd == e - c * (b - a)) for c in range(-1, 4 * a + 6)]) self.s.add(Implies(guard, And(conv_x, 0 <= jxp, jxp <= b + a - 1, conv_d, 0 <= jd, jd <= b - a - 1))) B = dict(kxp=kxp, kd=kd, kx=kx, ky=ky, jd=jd) for low, h, e in ((jx, 'hx', 'ex'), (jy, 'hy', 'ey'), (jxp, 'hxp', 'exp'), (jd, 'hd', 'ed')): hv, ev = self.fresh(h), self.fresh(e); B[h], B[e] = hv, ev self.s.add(Implies(guard, And(low == a * hv + ev, 0 <= ev, ev < a))) self.aux.append(B) tw = tz(trees['walls'], build(B, self.m, need['walls'])); tb = tz(trees['band'], build(B, self.m, need['band'])) wall = lt(kx, jx, self.q('p')) if depth == 3: return If(wall, tw, tb) band = lt(kd, jd, self.q('WD')) qx = sub(kx, jx, self.q('p'), b); qy = sub(ky, jy, self.q('r'), b) return If(wall, tw, If(band, tb, self.Fup((qx[0], qx[1], qy[0], qy[1]), And(guard, Not(wall), Not(band)), depth + 1))) def F(self, P, exists): up = self.upper(P); kx, jx, ky, jy = P return If(up, self.Fup(P, And(exists, up)), self.Fup((ky, jy, kx, jx), And(exists, Not(up)))) def point(C): kx, jx, ky, jy = Ints('kx jx ky jy'); b = C.b; P = (kx, jx, ky, jy) C.s.add(kx >= 0, ky >= 0, 0 <= jx, jx < b, 0 <= jy, jy < b, C.upper(P)); return P def report(C, r, label, t0, ex=None): print(f'{fam.name}: {label}, all m >= {fam.mmin}: {r} ({time.time()-t0:.1f}s)', flush=True) if r == sat and ex: ex(C.s.model()) if what == 'conv': for body in ('x', 'd'): C = Ctx(); kx, jx, ky, jy = point(C); b = C.b C.s.add(lt(kx, jx, (C.q('X')[0] + 2, 0)), lt(ky, jy, (C.q('Y')[0] + 2, 0))) if body == 'x': C.s.add(Not(Or([And(0 <= jx - a * kx + c * (b + a), jx - a * kx + c * (b + a) <= b + a - 1) for c in range(0, 2 * a + 3)]))) else: e = a * (ky - kx) + (jy - jx); C.s.add(Not(Or([And(0 <= e - c * (b - a), e - c * (b - a) <= b - a - 1) for c in range(-1, 4 * a + 6)]))) t0 = time.time(); report(C, C.s.check(), f'{body}-conversion has no solution somewhere (unsat = it always has one)', t0) return C = Ctx(); P = point(C); kx, jx, ky, jy = P; b = C.b def ex(M): g = lambda v: M.eval(v, model_completion=True).as_long(); bb = g(b) print(' counterexample: b =', bb, 'x =', g(kx) * bb + g(jx), 'y =', g(ky) * bb + g(jy)) if what in ('mex_walls', 'mex_rest'): C.s.add(lt(kx, jx, C.q('X')), lt(ky, jy, C.q('Y'))) val = C.Fup(P, BoolVal(True)); wall = lt(kx, jx, C.q('p')); C.s.add(wall if what == 'mex_walls' else Not(wall)) part = '' if len(sys.argv) > 3 and '/' in sys.argv[3]: # split the query into 32 disjoint cases: python ... mex_rest i/32 i = int(sys.argv[3].split('/')[0]); assert sys.argv[3].endswith('/32') and 0 <= i < 32 A0 = C.aux[0]; inband = lt(A0['kd'], A0['jd'], C.q('WD')) C.s.add(kx % 2 == i % 2, ky % 2 == (i // 2) % 2, A0['hx'] % 2 == (i // 4) % 2, A0['hy'] % 2 == (i // 8) % 2, inband if (i // 16) % 2 == 0 else Not(inband)) part = f' [case {i} of 32]' xa = sub(kx, jx, (0, a), b); ya = sub(ky, jy, (0, a), b) ge = lambda k, j, K, c: Not(lt(k, j, (K, c))) opts = [(And(ge(kx, jx, 0, a), ky >= 1), (xa[0], xa[1], ky - 1, jy)), (And(kx >= 1, ge(ky, jy, 0, a)), (kx - 1, jx, ya[0], ya[1])), (And(ge(kx, jx, 1, a), ge(ky, jy, 1, a)), (xa[0] - 1, xa[1], ya[0] - 1, ya[1]))] vs = [C.F(Q, e) for e, Q in opts] has = lambda k: Or([And(e, v == k) for (e, _), v in zip(opts, vs)]) mex = If(Not(has(0)), 0, If(Not(has(1)), 1, If(Not(has(2)), 2, 3))) C.s.add(val != mex); t0 = time.time(); r = C.s.check() return report(C, r, f'mex rule violated in the window, {"walls" if what=="mex_walls" else "band and above"}{part} (unsat = never)', t0, ex) v0 = C.Fup(P, BoolVal(True)); kd, jd = C.aux[0]['kd'], C.aux[0]['jd'] if what == 'h1': # x < a+b, x + D <= y < Y1+1 C.s.add(lt(kx, jx, C.q('ab')), Or(kd >= 1, jd >= D), lt(ky, jy, C.q('Y1p'))); sx, sy = C.q('p'), C.q('r') elif what == 'h2': # a+b <= x < X0+q+a+b, D <= y-x < D + (b-a) C.s.add(Not(lt(kx, jx, C.q('ab'))), lt(kx, jx, C.q('H2')), Or(And(kd == 0, jd >= D), And(kd == 1, jd < D))); sx, sy = C.q('p'), C.q('r') else: # X0 <= x < X0+p+b, 0 <= y-x < W+D C.s.add(Not(lt(kx, jx, C.q('p'))), lt(kx, jx, C.q('H3')), lt(kd, jd, C.q('WD'))); sx = sy = C.q('q') qx = add(kx, jx, sx, b); qy = add(ky, jy, sy, b) v1 = C.Fup((qx[0], qx[1], qy[0], qy[1]), BoolVal(True)) C.s.add(v0 != v1); t0 = time.time(); r = C.s.check() report(C, r, f'{what.upper()} violated (unsat = never)', t0, ex) if __name__ == '__main__': fam = Fam(sys.argv[1]); what = sys.argv[2] if what == 'forms': fm = fam.forms(); t = fam.raw(fam.b(fam.mmin)) print(fam.name, f'a={fam.a}, b={fam.L}m{fam.e:+d}, m>={fam.mmin}: kind {fm["kind"]}, D={fm["D"]}; digit forms (k1, k0, c) meaning (k1*m+k0)*base + c:') for k, v in fm.items(): if isinstance(v, tuple): print(f' {k:4s} = ({v[0]}*m{v[1]:+d})*{"(b-a)" if k=="WD" else "b"} + {v[2]}') elif what == 'fit': fit(fam, int(sys.argv[3]) if len(sys.argv) > 3 else 41, only=sys.argv[4] if len(sys.argv) > 4 else None) elif what == 'refine': refine(fam, sys.argv[3], int(sys.argv[4]), [int(t) for t in sys.argv[5].split(',')]) elif what == 'numeric': numeric(fam, [int(t) for t in sys.argv[3].split(',')]) else: z3_part(fam, what)