diff --git a/research/lever-integer-twins/README.md b/research/lever-integer-twins/README.md new file mode 100644 index 0000000000..a19aaf15bd --- /dev/null +++ b/research/lever-integer-twins/README.md @@ -0,0 +1,217 @@ +# Integer twins of three ideal lever combinations + +**All three minimal reaching cells in PR3874 still clear its stated target after +integer rounding in the declared models.** This resolves its first open question +as an arithmetic screen. No physical realization, supplier or new kappa is +claimed. The selected conditional result remains 0.001672660197076918. + +The most restrictive row tested preserves one identical integer paid profile in +every call and pools idle mass across nine calls. For selected-centre/rank8/u2, +its root is strictly between **0.010351600977 and 0.010351600978**, giving a +balanced-transfer kappa cap between **0.010245543201980** and +**0.010245543202961** (outward rounded here). Thus integer rounding does not +remove this cell's planning margin. However its remaining allowance at the +target is only **16 additional rank-one children per nine-call pool**; 17 fail. +This is an additive recursive-work budget, not a scalar-ADD tariff or permission +to ignore restoration and other costs. + +## Exact question and source boundary + +This takes Nick Petalas's [PR3874](https://github.com/CrocSwap/integer-mult-bounds/pull/3874) +Open next question 1 at `fb86b078a53042974d88b9758fe36622571349d0`, following the +[handoff](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19028179). +The canonical claim/result lives in [Discussion2278](https://github.com/CrocSwap/integer-mult-bounds/discussions/2278#discussioncomment-19029577). +The original card is `complex-new-helper-inventory`, explicitly **changed** to +this requested pricing subproblem, not its physically-realizable-contract gate. + +Keep width 73, 896 live families per nine calls, rank guard 51 and the following +three parent cells. Shared centre products stay rank 8, just as in PR3874. + +| Cell | Variable paid mass per call | Variable rank cap | Fixed rank-8 children per call | Centre charge | Unpaid coordinates | +|---|---:|---:|---:|---:|---:| +| selected-r8-u2 | 5586 | 8 | 0 | 64 | 2 | +| shared-r32-u1 | 5522 | 32 | 4 | 32 | 1 | +| free-r16-u1 | 5522 | 16 | 0 | 0 | 1 | + +The declared target is **kappa = 1/99**, following PR3874's explicit table. +Since kappa = a/(1+a), the correct moment test is **a = 1/98**. +Testing a = 1/99 would instead test kappa = 1/100. This package does not change +the repository's separate kappa > .01 planning objective. + +For N calls, W = 896 N/9 and total rank mass is `(73-u)W + C N`. +Subtract the full paid mass to obtain idle mass. For u2 the per-call idle +average is `13918/9`; for the other two cells it is `1646`. Integral families +and the u2 mass require N divisible by nine. We test N=9 and N=144; neither is +asserted to be a legal physical pooling group for a future changed construction. + +The integer twin allows variable ranks **at most** the named cap, including a +remainder child. Requiring every child to have exactly that rank is a different +model and can fail divisibility. This is the rank-cap interpretation requested +by the predecessor's proposed integer DP. + +Two paid restrictions are kept separate: + +* **uniform:** partition the variable mass into integer children inside each + call, then repeat that exact profile N times; +* **pooled:** partition N times the variable mass with no call boundaries. + This is a further relaxation, not a repeated local word. + +Idle is independently pooled across all N calls in both models. Integrality is +imposed **before** dividing by W. In particular, nonintegral per-call averages +are not an aggregate impossibility. This follows the boundary correction in +PR3747 and the two-unpaid mass observations of PR3754/PR3757. + +## Results + +All rows have certified `moment(a_lo) < 1 < moment(a_hi)` with +`a_hi = a_lo + 10^-12`. Every target moment is strictly below one, checked by +both arithmetic engines. The kappa column is the lower endpoint of the +**model root's** transformed bracket, rounded for display; it is not an achieved +multiplication exponent. Exact fractions, full paid/idle histograms and target +moment intervals are in `RESULT.json`. + +| Cell / calls / paid restriction | a lower endpoint | kappa bracket lower (approx.) | Extra rank-one children: maximum passing integer | +|---|---:|---:|---:| +| selected-r8-u2/9/uniform | 0.010351600977 | 0.010245543202 | 16 | +| selected-r8-u2/9/pooled | 0.010353593558 | 0.010247495158 | 16 | +| selected-r8-u2/144/uniform | 0.010351914854 | 0.010245850680 | 268 | +| selected-r8-u2/144/pooled | 0.010354156699 | 0.010248046816 | 272 | +| shared-r32-u1/9/uniform | 0.012857118397 | 0.012693911277 | 120 | +| shared-r32-u1/9/pooled | 0.012881196799 | 0.012717381703 | 121 | +| shared-r32-u1/144/uniform | 0.012861767247 | 0.012698442831 | 1931 | +| shared-r32-u1/144/pooled | 0.012887413706 | 0.012723441452 | 1946 | +| free-r16-u1/9/uniform | 0.011000817562 | 0.010881116386 | 62 | +| free-r16-u1/9/pooled | 0.011005405074 | 0.010885604586 | 62 | +| free-r16-u1/144/uniform | 0.011003116946 | 0.010883365997 | 1003 | +| free-r16-u1/144/pooled | 0.011008280352 | 0.010888417598 | 1009 | + +The last column adds work to the complete base histogram with unchanged W and +**no compensating mass credit**. Both signs are certified at a=1/98: the listed +integer k passes and k+1 fails. Any combined realization charges must fit the +same moment slack; different-rank work must be priced at its own child cost. The surcharge is +aggregate and need not preserve the base paid word's per-call uniformity. If the +extra rank-one work must itself be identical in every call, the tight row allows +only one extra child per call (nine total); two per call exceed its limit. +These numbers do not price a complete producer, consumer, dirty restoration, +frame transport, precision or the bit supplier. + +For the tight nine-call uniform row, paid `{8:6282,2:9}` and idle +`{51:272,46:1}` have masses 50274 and 13918, totalling +`64192 = 71*896 + 64*9`. Independent integer powers give the strict bound + + moment(1/98) < 111970002856773289113 / 112000000000000000000 < 1. + +The other nine-call uniform paid profiles are +`{32:1548,18:9,8:36}` and `{16:3105,2:9}`. Both have idle +`{51:290,24:1}`. The pooled alternatives are printed in the exact receipt. +No all-24-cell integer lattice or antichain classification is claimed. + +## Why the histograms are optimal in these models + +Reuse the strict-concavity argument of +[PR1685's retained proof](../idle-packing-stability/README.md#proof-2-exact-integer-optimum), +credited to Penguin (OpenAI) for Maximus Putnam. For 0 0 + + +@lru_cache(maxsize=None, typed=True) +def child_cost(rank, width, saving, places=PLACES): + """Enclose (rank/width)^(1-saving) on a decimal grid, exactly. + + The search invariant is lo^q m^e <= r^e S^q < hi^q m^e. + Initially lo=0 and hi=S+1, since 0 < r/m <= 1. At termination + hi=lo+1; exact equality at lo collapses the enclosure to one point. + Exact rational endpoint cases avoid unnecessary rounding. + """ + require(positive_int(rank) and positive_int(width), "positive integer rank/width required") + require(rank <= width, "rank exceeds width") + require(type(saving) is Fraction and 0 <= saving <= 1, "saving must be a Fraction in [0, 1]") + require(positive_int(places), "positive integer decimal precision required") + if rank == width or saving == 1: + return Fraction(1), Fraction(1) + if saving == 0: + value = Fraction(rank, width) + return value, value + power = 1 - saving + exponent, root = power.numerator, power.denominator + scale = 10 ** places + factor = width ** exponent + right = rank ** exponent * scale ** root + lo, hi = 0, scale + 1 + while hi - lo > 1: + mid = (lo + hi) // 2 + if mid ** root * factor <= right: + lo = mid + else: + hi = mid + lower = Fraction(lo, scale) + upper = lower if lo ** root * factor == right else Fraction(hi, scale) + return lower, upper + + +def fraction_string(value, label): + require(type(value) is str, label + " must be a rational string") + try: + return Fraction(value) + except (ValueError, ZeroDivisionError) as error: + raise ValueError(label + " is not a rational number") from error + + +def check_document(document): + """Return independent target enclosures; reject any unproved passing row.""" + require(type(document) is dict, "result must be an object") + width = document.get("width") + require(type(width) is int and width == 73, "expected width 73") + require(fraction_string(document.get("target_a"), "target_a") == TARGET, + "expected exact target_a = 1/98, corresponding to kappa = 1/99") + rows = document.get("rows") + require(type(rows) is list and bool(rows), "nonempty rows required") + names = set() + checked = [] + for row in rows: + require(type(row) is dict, "row must be an object") + name = row.get("name") + require(type(name) is str and bool(name) and name not in names, "unique nonempty row name required") + names.add(name) + families = row.get("families") + require(positive_int(families), name + ": positive integer families required") + histogram = row.get("histogram") + require(type(histogram) is dict and bool(histogram), name + ": nonempty histogram required") + lower = upper = Fraction(0) + for key, count in histogram.items(): + require(type(key) is str and key.isascii() and key.isdigit(), name + ": rank key must be decimal") + rank = int(key) + require(str(rank) == key and positive_int(rank), name + ": rank key must be canonical and positive") + require(2 * rank * rank < width * width, name + ": rank violates the halving guard") + require(positive_int(count), name + ": count must be a positive integer") + lo, hi = child_cost(rank, width, TARGET) + lower += count * lo + upper += count * hi + lower /= families + upper /= families + reported_lo = fraction_string(row.get("target_moment_lo"), name + ": target_moment_lo") + reported_hi = fraction_string(row.get("target_moment_hi"), name + ": target_moment_hi") + require(lower <= reported_lo <= reported_hi <= upper, + name + ": primary interval is not contained in independent grid enclosure") + require(reported_hi < 1, name + ": primary interval does not prove target pass") + require(upper < 1, name + ": independent integer powers do not prove target pass") + extra = row.get("extra_rank1_children_at_target") + require(type(extra) is int and extra >= 0, name + ": nonnegative integer extra-child count required") + one_lo, one_hi = child_cost(1, width, TARGET) + extra_upper = upper + extra * one_hi / families + next_lower = lower + (extra + 1) * one_lo / families + require(extra_upper < 1, name + ": claimed extra-child budget does not pass") + require(next_lower > 1, name + ": extra-child budget is not proved maximal") + checked.append({"name": name, "moment_lo": str(lower), "moment_hi": str(upper), + "extra_rank1_children_at_target": extra, + "with_extra_moment_hi": str(extra_upper), + "with_one_more_moment_lo": str(next_lower)}) + return checked + + +def expect_rejection(callback, label): + try: + callback() + except ValueError: + return + raise ValueError("negative control accepted: " + label) + + +def self_test(): + """Exact calibrations plus malformed-input and false-passing controls.""" + require(child_cost(73, 73, TARGET) == (Fraction(1), Fraction(1)), "unit-ratio calibration") + require(child_cost(7, 73, Fraction(0)) == (Fraction(7, 73), Fraction(7, 73)), "zero-saving calibration") + require(child_cost(7, 73, Fraction(1)) == (Fraction(1), Fraction(1)), "unit-saving calibration") + require(child_cost(9, 25, Fraction(1, 2)) == (Fraction(3, 5), Fraction(3, 5)), "exact-square calibration") + lo, hi = child_cost(16, 81, Fraction(1, 2)) + require(lo < Fraction(4, 9) < hi and hi - lo == Fraction(1, 10 ** PLACES), "rounded rational-square calibration") + lo, hi = child_cost(2, 3, Fraction(1, 2)) + require(lo * lo < Fraction(2, 3) < hi * hi, "irrational-square calibration") + for rank, width, saving in [(0, 73, TARGET), (74, 73, TARGET), (1, 0, TARGET), + (True, 73, TARGET), (1, 73, Fraction(-1, 98)), + (1, 73, Fraction(99, 98)), (1, 73, 0.5)]: + expect_rejection(lambda: child_cost(rank, width, saving), "invalid child domain") + expect_rejection(lambda: child_cost(1, 73, TARGET, 0), "zero precision") + lo, hi = child_cost(1, 73, TARGET) + expect_rejection(lambda: child_cost(True, 73, TARGET), "bool rank after integer cache entry") + fixture = {"width": 73, "target_a": "1/98", "rows": [{ + "name": "positive", "histogram": {"1": 1}, "families": 1, + "extra_rank1_children_at_target": 68, + "target_moment_lo": str(lo), "target_moment_hi": str(hi)}]} + require(len(check_document(fixture)) == 1, "positive document fixture") + expect_rejection(lambda: check_document({**fixture, "target_a": "1/99"}), "kappa substituted for saving") + expect_rejection(lambda: check_document({**fixture, "rows": []}), "empty evidence") + row = fixture["rows"][0] + for changed in ({"histogram": {"1": -1}}, {"histogram": {"1": True}}, + {"histogram": {"01": 1}}, {"histogram": {"52": 1}}, + {"families": 0}, {"target_moment_hi": "2"}, + {"extra_rank1_children_at_target": -1}, + {"extra_rank1_children_at_target": True}, + {"extra_rank1_children_at_target": 67}, + {"extra_rank1_children_at_target": 69}): + expect_rejection(lambda: check_document({**fixture, "rows": [{**row, **changed}]}), "invalid row") + lo, hi = child_cost(51, 73, TARGET) + failing = {**row, "histogram": {"51": 2}, + "target_moment_lo": str(2 * lo), "target_moment_hi": str(2 * hi)} + expect_rejection(lambda: check_document({**fixture, "rows": [failing]}), "genuinely failing moment") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("result", nargs="?", type=Path, default=Path(__file__).with_name("RESULT.json")) + parser.add_argument("--self-test", action="store_true", help="run calibrations and negative controls only") + args = parser.parse_args() + self_test() + if args.self_test: + print("PASS_INDEPENDENT_INTEGER_POWER_CONTROLS") + return + result = json.loads(args.result.read_text(encoding="utf-8")) + checked = check_document(result) + for row in checked: + print(json.dumps(row, sort_keys=True)) + print("PASS_INDEPENDENT_INTEGER_POWER_TARGET rows=" + str(len(checked))) + + +if __name__ == "__main__": + main() diff --git a/research/lever-integer-twins/predecessor/grid.py b/research/lever-integer-twins/predecessor/grid.py new file mode 100644 index 0000000000..aee9cdd3bd --- /dev/null +++ b/research/lever-integer-twins/predecessor/grid.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Ideal combined-lever budget grid for the selected complex local word. + +Extends `research/complex-local-word-ceiling/levers.py` (seven one-at-a-time rows) +to the full grid of the three published lever families: + + * centre charge c in {64 selected, 32 shared-by-two-calls, 0 free}; + * local shape word (published profile), or all non-centre paid mass delivered + as (fractional) children of rank r in {8, 16, 32}; + * unpaid coords u in {1 coverage law, 2 what-if changed coverage law}; + +plus the two three-lever rows that combine u = 2 with centre-free/shared and rank 16. + +Every row keeps the parent premises: m = 73, 896 live families over nine stages +(w = 896/9 live families per call), outer halving guard R = 51, fractional idle +remainder at rank R, paid centre charge c in the coverage identity. The ceiling is +the exact rational bracket of the parent `ceiling()` at grid 1e-12; the reported +a_cap is the certified upper grid point, kappa_cap = a_cap / (1 + a_cap) under the +retained balanced reduction. + +These are ideal favorable relaxations for planning and screening, exactly like the +published lever rows: every row omits whatever cost realizing the lever would add +elsewhere, needs an actual word/contract on both suppliers and all-size admission, +and establishes no kappa, supplier or frontier change. + +Douglas Colkitt's ceiling model; grid built by Nick Petalas with AI assistance. +Apache-2.0. +""" +import json +import sys +from fractions import Fraction as Q +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'complex-local-word-ceiling')) +import ceiling as C # noqa: E402 + +M, FAM, ST = 73, 896, 9 +WORD = {1: 2412, 2: 418, 3: 432, 4: 142, 5: 82, 8: 8} +MASS = sum(r * n for r, n in WORD.items()) # 5586 +GRID = Q(1, 10 ** 12) +TARGET = Q(1, 99) # ambitious planning saving + +# centre variants: (tag, charge, rank-8 centre copies per call) +CENTRES = [('sel', 64, 8), ('shr', 32, 4), ('free', 0, 0)] +# local shapes: 'word' keeps the published non-centre profile; else rank r +SHAPES = ['word', 8, 16, 32] +UNPAID = [1, 2] + + +def profile(centre_tag, shape): + """Per-call paid profile (dict rank -> Fraction count) for one centre/shape cell. + + The sel rows reproduce the parent levers exactly: at centre charge 64 the whole + local mass (including the centre products) is delivered as rank-r children. When + centre copies are retained (shared) or removed (free), only the non-centre mass + 5522 is reshaped; retained shared copies stay rank-8 children. + """ + charge, copies = next((c, k) for t, c, k in CENTRES if t == centre_tag) + prof = {} + if shape == 'word': + for r, n in WORD.items(): + prof[r] = Q(copies if r == 8 else n) + elif centre_tag == 'sel': + prof[shape] = Q(MASS, shape) + else: + if copies: + prof[8] = Q(copies) + prof[shape] = prof.get(shape, Q(0)) + Q(MASS - 64, shape) + prof = {r: n for r, n in prof.items() if n > 0} + mass = sum(r * n for r, n in prof.items()) + assert mass == {64: MASS, 32: MASS - 32, 0: MASS - 64}[charge], (centre_tag, shape, mass) + return prof, charge + + +def row(centre_tag, shape, unpaid, grid=GRID): + prof, charge = profile(centre_tag, shape) + lo, hi = C.ceiling(prof, M, FAM, ST, charge, grid=grid, unpaid=unpaid) + return lo, hi + + +def compute_rows(): + rows = [] + for centre_tag, _, _ in CENTRES: + for shape in SHAPES: + for unpaid in UNPAID: + lo, hi = row(centre_tag, shape, unpaid) + rows.append(dict(centre=centre_tag, shape=str(shape), unpaid=unpaid, + a_lo=str(lo), a_hi=str(hi), + kappa_hi=str(hi / (1 + hi)))) + return rows + + +def main(): + rows = compute_rows() + base = next(Q(r['a_hi']) for r in rows + if (r['centre'], r['shape'], r['unpaid']) == ('sel', 'word', 1)) + for r in rows: + a = Q(r['a_hi']) + print(f"centre={r['centre']:>4s} shape={r['shape']:>4s} unpaid={r['unpaid']} " + f"a_cap={float(a):.9f} x{float(a / base):.3f} " + f"kappa_cap={float(Q(r['kappa_hi'])):.9f} " + f"target={float(TARGET):.6f} {'REACHES' if a / (1 + a) >= TARGET else 'no'}") + + +if __name__ == '__main__': + main() diff --git a/research/lever-integer-twins/verify.py b/research/lever-integer-twins/verify.py new file mode 100644 index 0000000000..371da98981 --- /dev/null +++ b/research/lever-integer-twins/verify.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Integer twins of three PR3874 cells; pricing only, no new kappa. + +ToikY with substantial OpenAI Codex assistance. Apache-2.0. +Exact log/exp engine is credited reuse of Colkitt/Claude's ceiling.py. +""" +import argparse +import ast +import hashlib +import importlib.util +import json +from collections import Counter +from fractions import Fraction as Q +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +GRID = Q(1, 10**12) +TARGET_KAPPA = Q(1, 99) +TARGET_A = TARGET_KAPPA / (1 - TARGET_KAPPA) +# cap, unpaid, centre charge, fixed rank-8 copies, reshapeable mass per call +CELLS = {'selected-r8-u2': (8,2,64,0,5586), + 'shared-r32-u1': (32,1,32,4,5522), + 'free-r16-u1': (16,1,0,0,5522)} + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def authenticate(): + sources = json.loads((HERE/'SOURCES.json').read_text()) + for row in sources['files']: + if row['usage'] == 'input': + require(hashlib.sha256((ROOT/row['path']).read_bytes()).hexdigest() + == row['sha256'], 'changed source: '+row['path']) + for row in sources['external_predecessors']: + require(hashlib.sha256((HERE/row['retained_path']).read_bytes()).hexdigest() + == row['sha256'], 'changed retained predecessor') + + +def constants(path): + values = {} + for node in ast.parse(path.read_text()).body: + if not isinstance(node, ast.Assign): + continue + t = node.targets[0] + if isinstance(t,ast.Tuple) and [v.id for v in t.elts] == ['M','FAM','ST']: + values.update(zip(['M','FAM','ST'],ast.literal_eval(node.value))) + elif isinstance(t,ast.Name) and t.id in ('WORD','CENTRES','SHAPES','UNPAID'): + values[t.id] = ast.literal_eval(node.value) + return values + + +def optimum(mass, cap): + require(type(mass) is int and mass >= 0, 'mass must be a nonnegative integer') + require(type(cap) is int and 0 < cap <= 51, 'invalid rank cap') + q, r = divmod(mass,cap) + return {rank:n for rank,n in ((cap,q),(r,1 if r else 0)) if n} + + +def validate_histogram(hist, mass, cap): + require(all(type(r) is int and 00 + for r,n in hist.items()), 'invalid rank/count') + require(sum(r*n for r,n in hist.items()) == mass, 'wrong mass') + + +def histograms(tag, calls, mode): + require(type(calls) is int and calls>0 and calls%9==0, 'pool must contain 9k calls') + require(mode in ('uniform','pooled'), 'unknown paid model') + cap, unpaid, centre, fixed, mass = CELLS[tag] + families = 896*calls//9 + paid = Counter({r:n*calls for r,n in optimum(mass,cap).items()} + if mode=='uniform' else optimum(mass*calls,cap)) + if fixed: + paid[8] += fixed*calls + pmass = (mass+8*fixed)*calls + imass = (73-unpaid)*families+centre*calls-pmass + idle = optimum(imass,51) + validate_histogram(dict(paid),pmass,cap) + validate_histogram(idle,imass,51) + return dict(paid),idle,families,pmass,imass + + +def moment(C, hist, families, a): + require(0<=a<=Q(1,20), 'saving outside search domain') + lo = hi = Q(0) + for r,n in hist.items(): + x,y = C.child_cost(r,73,a) + lo += n*x + hi += n*y + return lo/families,hi/families + + +def bracket(C, hist, families): + low,high = 0,int(Q(1,20)/GRID) + require(moment(C,hist,families,0)[1]<1, 'no positive saving') + require(moment(C,hist,families,high*GRID)[0]>1, 'root outside window') + while high-low>1: + mid = (low+high)//2 + lo,hi = moment(C,hist,families,mid*GRID) + if hi<1: + low=mid + elif lo>1: + high=mid + else: + raise ValueError('unresolved grid sign') + return low*GRID,high*GRID + + +def encode(hist): + return {str(r):n for r,n in sorted(hist.items())} + + +def compute(C): + rows=[] + for tag in CELLS: + for calls in (9,144): + for mode in ('uniform','pooled'): + paid,idle,families,pmass,imass=histograms(tag,calls,mode) + hist=dict(Counter(paid)+Counter(idle)) + lo,hi=bracket(C,hist,families) + tl,th=moment(C,hist,families,TARGET_A) + require(th<1 and lo>TARGET_A, 'integer cell misses target') + require(moment(C,hist,families,lo)[1]<1