From f1a1779008ef19aee899d48572ac2235ed5344f2 Mon Sep 17 00:00:00 2001 From: Nick Petalas Date: Fri, 13 Nov 2026 22:48:37 +0000 Subject: [PATCH] feat(research): prove global integer gauge optimization is NP-complete --- research/integer-gauge-maxcut/PROOF.md | 215 ++++++++++++++++++ research/integer-gauge-maxcut/README.md | 146 +++++++++++++ research/integer-gauge-maxcut/SOURCES.json | 24 ++ research/integer-gauge-maxcut/TASK.json | 74 +++++++ research/integer-gauge-maxcut/VERIFY.json | 36 +++ research/integer-gauge-maxcut/verify.py | 242 +++++++++++++++++++++ 6 files changed, 737 insertions(+) create mode 100644 research/integer-gauge-maxcut/PROOF.md create mode 100644 research/integer-gauge-maxcut/README.md create mode 100644 research/integer-gauge-maxcut/SOURCES.json create mode 100644 research/integer-gauge-maxcut/TASK.json create mode 100644 research/integer-gauge-maxcut/VERIFY.json create mode 100644 research/integer-gauge-maxcut/verify.py diff --git a/research/integer-gauge-maxcut/PROOF.md b/research/integer-gauge-maxcut/PROOF.md new file mode 100644 index 0000000000..fde36a40b7 --- /dev/null +++ b/research/integer-gauge-maxcut/PROOF.md @@ -0,0 +1,215 @@ +# An exact Max Cut reduction for constant integer gauges + +This contribution was produced by Nick Petalas. Apache-2.0. + +## Priced problem + +Fix a finite chronological scalar word on rational registers. Its only +instructions are `v_t += 2^e v_s`, with t distinct from s and +`e in {-1,0,1}`. One reference register r has fixed exponent zero. +Each other register i may choose any integer exponent k_i. Apply the entry +scale `v_i *= 2^k_i`, replace each coefficient by +`2^(e+k_t-k_s)`, and apply the exit scale `v_i *= 2^(-k_i)`. +The instruction order and identities of all registers remain fixed. + +The tariff is the real-component copy-init tariff declared in Philipp / +mightyOil's [PR1310](https://github.com/CrocSwap/integer-mult-bounds/pull/1310), +README section "Why the finite pair census covers all integer exponents". +For a positive power of two it is + +```text +ADD(2^z) costs 3 + |z| - [z=0]. +SCALE(2^z) costs |z|. +``` + +Every ADD includes its coefficient-work cleanup. A unit ADD is a direct +ADD followed by CLEAR of that work register, costing two. A nonunit ADD +copies its source to the work register, applies |z| doubles or halves, +adds it to the target, and clears work, costing 3+|z|. The work register +can start arbitrary and ends zero. Its entry value is disposable under +this owned-work contract. It is not an extra restored donor. All data +registers, including the reference, start arbitrary. + +This is an optimization over representations of a fixed word. Combining +repeated ADDs, changing the algorithm, replacing the lowerer, removing +CLEARs, free renaming, free scales and changing the reference gauge are +outside the problem. + +Let `f(z)=|z|-[z=0]`. For N instructions the complete scalar bill is + +```text +B(k) = 3N + 2 sum_i |k_i| + sum_(t,s,e) f(e+k_t-k_s). (1) +``` + +The 2|k_i| term pays both boundaries. No boundary cost is omitted. +The source's tariff and scalar conjugation interface are premises here; +its historical k8 word, counts and stationarity proofs are not replayed. + +## The construction and exact optimum + +Let G be any nonempty finite simple graph with n vertices, m edges and +maximum degree Delta. Isolated vertices are permitted. Put +`A=2 Delta+1`. Use one data register for each vertex and one reference r. +First, in vertex order, emit for every i + +```text +A copies of v_i += v_r, +A+1 copies of v_i += (1/2) v_r. +``` + +Then, in lexicographic edge order, emit for every edge i=2 and x<=-1, respectively, direct substitution gives + +```text +U_A(x)-1 = (2A+3)(x-1) + A+1, x>=2, +U_A(x)-1 = (2A+3)(-x) + A, x<=-1. +``` + +Consequently, for every integer x, + +```text +U_A(x)-U_A(c(x)) >= (2A+3)|x-c(x)|. (3) +``` + +The two directed instructions of an edge together contribute + +```text +H(d) = f(1+d)+f(1-d) + = 2 if d=0, + 1 if |d|=1, + 2|d| if |d|>=2. +``` + +Its consecutive differences have absolute value at most three. By a +finite telescoping sum, `|H(u)-H(v)|<=3|u-v|` for all integers u,v. +This estimate includes the unit-coefficient discount at d=+1 and d=-1. + +### Clipping proves the unrestricted integer result + +Write `F=B-3N`. Clip one coordinate k_i to c(k_i), leaving every other +coordinate fixed, even if the other coordinates are unbounded integers. +The unary part decreases by at least `(2A+3)|k_i-c(k_i)|`. The incident +edge terms together can increase by at most +`3 degree(i)|k_i-c(k_i)|`. Thus the total decrease is at least + +```text +(2A+3-3 degree(i)) |k_i-c(k_i)| + >= (Delta+5) |k_i-c(k_i)|. (4) +``` + +This is positive for every nonbinary k_i. Clipping each coordinate once +therefore gives the quantitative inequality + +```text +B(k) >= B(c(k)) + (Delta+5) sum_i |k_i-c(k_i)|. (5) +``` + +No finite search box is assumed. A minimum exists because the finite +binary domain contains a point at least as good as every integer point. +Every minimizer is binary by the strict part of (5). + +For binary k, each unary term is one. Each edge contributes two when +uncut and one when cut. Hence + +```text +F(k)=n+2m-cut_G(k), +B(k)=3[n(2A+1)+2m]+n+2m-cut_G(k). +``` + +This proves (2) and the optimizer characterization. In particular, the +ungauged bill B(0) is `n(12 Delta+10)+8m`, so the maximum obtainable saving +is exactly MaxCut(G). + +## Complexity consequence + +The decision problem for the declared fixed-word gauge tariff is +NP-complete, even when every original coefficient belongs to {1/2,1,2}, +there is just one fixed reference, and both boundary scales are charged. + +For hardness, use the classical Simple Max Cut decision problem. Given +G and integer q, construct the word above and set +`K=n(12 Delta+10)+8m-q`. Equation (2) gives + +```text +MaxCut(G)>=q if and only if some integer gauge has B(k)<=K. +``` + +The word has O(n Delta+m) instructions, hence polynomial size. Repeated +instructions are explicitly present in this count. All original scalar +coefficients have constant bit length, and the threshold has polynomial +bit length. This is a many-one reduction. + +For membership in NP of the full declared problem, each ADD costs at +least two and every other charge is nonnegative. A witness with bill at +most nonnegative K must satisfy `2 sum_i |k_i|<=K`. Therefore every +exponent has O(log(K+1)) bits. Evaluating (1) requires only integer +arithmetic polynomial in the word length and these bit lengths. Negative +K is immediately infeasible. Thus a polynomial-size exponent witness +exists for every yes-instance. The same conclusion holds for the +constructed subfamily, whose witnesses can be chosen binary. + +Classical hardness is cited from Garey, Johnson and Stockmeyer, +[Some simplified NP-complete graph problems, Theoretical Computer Science +1 (1976), 237-267](https://doi.org/10.1016/0304-3975(76)90059-1), +Section 1's Simple Max Cut theorem. Their theorem is a premise, not a new +complexity result here. The new result is its exact realization in (1). +No literature-priority claim is made for graph reductions or nonconvex +integer-potential optimization in general. + +## Complete endpoint and limits + +After entry scaling maintain the invariant that represented register i +is `2^k_i` times its original-word value at the same cut. A transformed +ADD preserves this invariant because + +```text +2^k_t v_t + 2^(e+k_t-k_s) 2^k_s v_s + = 2^k_t (v_t+2^e v_s). +``` + +The reference has k_r=0. The exit scales remove every remaining factor. +This proves equality of the whole linear endpoint for arbitrary rational +data, with arbitrary initial coefficient-work contents cleared as charged. +It restores the intended original-word outputs, not the initial data +registers individually. The finite checker executes the literal primitive +words on all basis columns of its endpoint fixtures, including the work +column, and on signed rational dirty states. + +The theorem is about worst-case constructed words. It proves neither +hardness of the actual 237-helper instance nor a new bound on that word's +minimum. It does not supply a faster multiplication algorithm, native +admission, a changed productive or paid rank profile, rounded precision, +physical hosting, stock, tape costs, compiler closure or a new kappa. +The five selected framework assumptions remain. A different tariff or +unrestricted circuit resynthesis can escape this obstruction. diff --git a/research/integer-gauge-maxcut/README.md b/research/integer-gauge-maxcut/README.md new file mode 100644 index 0000000000..7183a84906 --- /dev/null +++ b/research/integer-gauge-maxcut/README.md @@ -0,0 +1,146 @@ +# Global integer dyadic-gauge optimization encodes Max Cut exactly + +This contribution was produced by Nick Petalas. Apache-2.0. + +Claim type: scoped written proof with exact finite corroboration. Global +constant integer dyadic-gauge optimization under the boundary-inclusive +copy-init scalar tariff is NP-complete. This already holds for fixed +words with original coefficients only 1/2, 1 and 2, one fixed reference +register, arbitrary dirty data, and both entry and exit scales paid. + +For every simple graph G with n>=1 vertices, m edges and maximum degree +Delta, an explicit word has exact minimum real-component scalar bill + +```text +min B = n(12 Delta+10) + 8m - MaxCut(G). +``` + +Its ungauged bill is the same expression without the MaxCut subtraction. +Every integer optimum is binary and corresponds to a maximum cut. A +quantitative clipping inequality covers every integer gauge, including +ones outside any finite search box. [PROOF.md](PROOF.md) gives the word, +full bill, clipping argument, complexity reduction and dirty endpoint proof. +For complex arithmetic the inherited separate real/imaginary lowering +simply doubles the real bill; it does not alter the optimizing gauges. + +Philipp / mightyOil's [PR1310](https://github.com/CrocSwap/integer-mult-bounds/pull/1310) +provides the exact scalar objective and explicitly separates pair +stationarity from a global optimum. This new result explains a worst-case +obstruction to a general efficient global optimizer. It does not audit, +replay or decide that predecessor's historical 237-helper instance. +Classical Simple Max Cut hardness is due to Garey, Johnson and Stockmeyer; +the [primary paper](https://doi.org/10.1016/0304-3975(76)90059-1) is cited +with its locator in the proof. No general literature-priority claim is made. + +## Evidence and reproduction + +From the repository root, using CPython 3.12 and its standard library: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -B research/integer-gauge-maxcut/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -W error -O -B research/integer-gauge-maxcut/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/integer-gauge-maxcut +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/integer-gauge-maxcut --check-source-history +``` + +Another Python 3.12 path can replace the absolute interpreter path. Direct +replay prints `PASS_INTEGER_GAUGE_MAXCUT` in a generated JSON receipt bound +to every package file and the pinned predecessor README. It writes only +standard output. The registered manifest repeats the direct verifier +normally and with optimization, with a 120-second limit per command. + +The checker enumerates every simple labeled graph through four vertices. +For every graph it compares the literal event tariff with the reduced +objective on every gauge in {-2,-1,0,1,2,3}^n, verifies quantitative clipping, +and independently enumerates every binary cut and decision threshold. +The universal theorem rests on the written proof, not this finite box. +The generated counts are 75 graphs, 1,098 binary assignments, 84,750 +integer assignments and 430 threshold comparisons. The complete-graph +minimum bills at n=1,2,3,4 are 10, 51, 124 and 228. + +Separately, every graph through three vertices and every gauge in +{-1,0,1,2}^n is lowered to literal COPY, ADD, CLEAR, DOUBLE and HALVE +instructions. Their lengths must equal the charged bill. All basis +columns, including independent coefficient-work dirt, and two signed +rational states must match the direct ungauged linear endpoint. No +predecessor executable is imported. Controls exercise the coefficient +ratio, missing exit, truncated word, boundary price, unit discount, +frustrated triangle and invalid graph boundaries. +The literal checks cover 548 gauge words, 3,796 dirty endpoints and +419,653 executed primitives. There are 1,799 local-lemma substitutions, +six semantic controls and eight invalid-graph rejections. + +## Scope and provenance + +The card `complex-new-helper-inventory` is marked changed in TASK.json. +This is a scalar-search side result. It does not satisfy that card's +physical productive-inventory acceptance gate. The orientation baseline +passed source bindings only. Canonical base is +`e54523517d0f03e58352e647c403a5af3e525a57`, priority revision 8. The selected +record is #7000 at kappa 0.00363005817; the priority headline describes an +older checkpoint. Source manifests pin the original card, selection and +predecessor text. The sole live external input is that text, authenticated +before mathematical execution and included in the replay/export inventory. + +The [advance claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19601582) +reserves this exact global-integer problem. Main-tree, merged-PR, open-PR +and live Discussion checks found related coframe hardness and local gauge +results, but no matching integer-gauge construction within that bounded +coverage. The overlap cache covered 846 open PRs, 7,483 Discussion records +and 10,178 HEAD notes. This is not a proof of novelty or an exhaustive +literature search. + +This fixes the chronological word and the declared lowerer. Repeated +instructions may be resynthesized under a different problem. Work CLEARs +are charged and retain their owned-work semantics. No claim is made about +physical tape cost, rounded precision, stock, native operators, supplier +admission, a changed recursive moment, the selected frontier or complete +multiplication. No predecessor scientific replay, selected cold replay, +Lean or Docker ran. Independent human and formal proof-kernel review are +unclaimed. + +## Open next questions + +Can a useful structural restriction on the actual scalar interaction +graph yield an exact global optimizer despite this worst-case reduction? +First measure one pinned graph's treewidth or a small deletion set that +removes its frustrated edge potentials, then derive a complete-state +algorithm with both boundary scales and unit discounts retained. This +matters because the theorem leaves structured supplier instances open. +No width bound or such algorithm is supplied here. + +## Credit + +Credit Philipp / mightyOil #1310 for the explicit objective and global +optimality distinction, Hanson Sun / bbMisk #1214 for the earlier exact +pair method, woklerx #1161 for scalar gauge conjugation, and Sagar Thakrar +#696 for the retained copy-init lowerer, with Jeremy Kothe, Hao Yan / +icekylinx, Douglas Colkitt and the retained supplier lineage. Their files +and credit lines remain unchanged. Classical Max Cut hardness and the +standard diagonal conjugation identity keep their established credit. +The new contribution is the graph word, exact full-tariff identity, +all-integer clipping proof and its finite corroboration. + +Nick Petalas #6225 is an older local exclusion on a fixed historical +instance. Nick Petalas #5888 is an older transported-coframe rank-cost +hardness result. Neither supplies this construction, objective reduction, +proof or executable. They are related background, not main predecessors. + +## Checker bounds + +Every loop is bounded by the fixed census domains: at most four vertices, +six edges, 72 source ADDs, 1,024 primitive instructions, 1,296 integer +gauges per graph, 16 binary gauges and seven endpoint fixtures per word. +Each function is below 60 physical lines. Exceptions keep checks active +under optimization. There is no recursion, network use, dynamic code, +subprocess or file writing in the scientific verifier. + +Power of Ten rule 3 has a managed-runtime deviation. Python allocates +integers, tuples, lists and Fractions during execution. The bounds above +limit live mathematical data, while fixed file inventories limit source +reads. The largest integer gauge tested in the census is three in +absolute value, and literal endpoints use exponents from -1 through two. +No heap profile or fixed-allocation native implementation is claimed. +Rule 10 uses warning-strict normal/optimized execution and AST inspection; +a separate static analyzer is unavailable in the declared environment. +Extending these domains requires revisiting their memory and loop bounds. diff --git a/research/integer-gauge-maxcut/SOURCES.json b/research/integer-gauge-maxcut/SOURCES.json new file mode 100644 index 0000000000..84cb966157 --- /dev/null +++ b/research/integer-gauge-maxcut/SOURCES.json @@ -0,0 +1,24 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/k8-coupled-gauge-stationarity/README.md", + "usage": "input", + "git_blob": "7a8f7b81fc6f512f0b2310f6fdca6dcda97bf23d", + "sha256": "c7c4cd089c0e0198784d16d8ec7c615d9f24fcc2c0d453a4f573f08c88dcdacf" + } + ] +} diff --git a/research/integer-gauge-maxcut/TASK.json b/research/integer-gauge-maxcut/TASK.json new file mode 100644 index 0000000000..ab9f8e70da --- /dev/null +++ b/research/integer-gauge-maxcut/TASK.json @@ -0,0 +1,74 @@ +{ + "schema_version": 1, + "task_id": "complex-new-helper-inventory", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "complex-new-helper-inventory", + "question": "Can a changed helper inventory earn productive credit that survives completion, compilation and the actual caller?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "A source-bound arbitrary-input identity and legal producer/consumer boundary with the complete paid and productive target invoice, including restoration, ownership, native alignment and extra charges. Price under the actual current model; historical ceiling.py assumptions must be established before use. A favorable optimistic relaxation keeps a route open but is not a completed supplier. A scoped local result remains useful; expansion requires the family-level budget gate.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Specify all arbitrary inputs, owned fields, restored outputs and a physically legal consumer. Compare complete P and T, including target debits and precision/stock costs. #5599 is a positive control for target refinement, not permission to split every helper for free. #5614 is a hypothetical compiler budget, not an emitted 145-split word. Stop at the first unpaid boundary or a failing optimistic full bill.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "productive helper", + "target refinement", + "5599", + "5614" + ], + "existing_checks": [ + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Construct a graph-indexed fixed scalar word whose boundary-inclusive integer-gauge optimum is n(12 Delta+10)+8m-MaxCut(G), and prove NP-completeness under the retained copy-init tariff.", + "scope_change_reason": "This is a new worst-case scalar-search obstruction, not a changed productive inventory or a physical supplier. The card acceptance gate remains unmet.", + "bottleneck_link": "Global coupled scalar optimization need not inherit a polynomial exact solver from local stationarity. Structured actual supplier instances remain open; no paid moment changes.", + "budget_minutes": 60, + "stop_rule": "Stop at the first verified exact reduction, then package it. No larger search or actual-instance optimum is attempted.", + "outcome": "completed", + "evidence": "PROOF.md gives the all-integer theorem; verify.py enumerates graph/gauge tariffs and literal dirty endpoints and emits generated hash-bound receipts.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Which structural restriction on an actual scalar interaction graph permits exact global optimization?", + "why_it_matters": "Worst-case hardness does not settle structured supplier words.", + "first_step": "Pin one graph, measure its treewidth or a deletion set removing frustrated potentials, then derive an exact complete-state method.", + "blocked_by": "No structural bound or algorithm is established here." + } + ] +} diff --git a/research/integer-gauge-maxcut/VERIFY.json b/research/integer-gauge-maxcut/VERIFY.json new file mode 100644 index 0000000000..aa8fc02e48 --- /dev/null +++ b/research/integer-gauge-maxcut/VERIFY.json @@ -0,0 +1,36 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/k8-coupled-gauge-stationarity/README.md" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Exact integer-gauge clipping, cut/tariff identities, literal dirty endpoints and rejecting controls" + }, + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "The same finite corroboration with assertions disabled" + } + ] +} diff --git a/research/integer-gauge-maxcut/verify.py b/research/integer-gauge-maxcut/verify.py new file mode 100644 index 0000000000..3c422ac486 --- /dev/null +++ b/research/integer-gauge-maxcut/verify.py @@ -0,0 +1,242 @@ +"""Exact new gauge/Max Cut reduction. Produced by Nick Petalas; Apache-2.0.""" + +from fractions import Fraction +from hashlib import sha256 +from itertools import combinations, product +import json +from pathlib import Path + +HERE = Path(__file__).resolve().parent +FILES = ("README.md", "PROOF.md", "TASK.json", "SOURCES.json", "VERIFY.json", "verify.py") + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def graph(n, edges): + need(type(n) is int and 1 <= n <= 4, "vertex bound") + need(type(edges) is tuple and len(edges) <= 6, "edge bound") + for edge in edges: + need(type(edge) is tuple and len(edge) == 2, "edge shape") + i, j = edge + need(type(i) is int and type(j) is int and 0 <= i < j < n, "edge endpoints") + need(tuple(sorted(set(edges))) == edges, "simple ordered edges") + delta = max(sum(i in edge for edge in edges) for i in range(n)) + return 2 * delta + 1, delta + + +def gauges(n, k): + need(type(k) is tuple and len(k) == n, "gauge shape") + need(all(type(x) is int and abs(x) <= 1024 for x in k), "gauge bound") + + +def f(z): + return abs(z) - int(z == 0) + + +def unary(a, x): + return 2 * abs(x) + a * f(x) + (a + 1) * f(x - 1) + + +def pair(d): + return f(1 + d) + f(1 - d) + + +def objective(n, edges, k): + a, _ = graph(n, edges) + gauges(n, k) + return sum(unary(a, x) for x in k) + sum(pair(k[i] - k[j]) for i, j in edges) + + +def word(n, edges): + a, _ = graph(n, edges) + result = [] + for i in range(n): + result.extend([(i, n, 0)] * a) + result.extend([(i, n, -1)] * (a + 1)) + for i, j in edges: + result.extend(((i, j, 1), (j, i, 1))) + need(len(result) <= 72, "word capacity") + return tuple(result) + + +def invoice(events, k): + g = k + (0,) + return 2 * sum(abs(x) for x in k) + sum(3 + f(e + g[t] - g[s]) for t, s, e in events) + + +def primitives(events, k, wrong_ratio=False, omit_exit=False): + g = k + (0,) + work = len(g) + result = [] + for i, x in enumerate(k): + result.extend([("double" if x > 0 else "halve", i)] * abs(x)) + for t, s, e in events: + z = e + (g[s] - g[t] if wrong_ratio else g[t] - g[s]) + if z: + result.append(("copy", work, s)) + result.extend([("double" if z > 0 else "halve", work)] * abs(z)) + result.append(("add", t, work)) + else: + result.append(("add", t, s)) + result.append(("clear", work)) + if not omit_exit: + for i, x in enumerate(k): + result.extend([("halve" if x > 0 else "double", i)] * abs(x)) + need(len(result) <= 1024, "primitive capacity") + return tuple(result) + + +def execute(ops, initial): + state = list(map(Fraction, initial)) + for op in ops: + tag, t = op[:2] + if tag == "copy": + state[t] = state[op[2]] + elif tag == "clear": + state[t] = Fraction(0) + elif tag == "add": + state[t] += state[op[2]] + elif tag == "double": + state[t] *= 2 + elif tag == "halve": + state[t] /= 2 + else: + raise ValueError("unknown primitive") + return tuple(state) + + +def exact_endpoint(events, initial): + state = list(map(Fraction, initial)) + for t, s, e in events: + state[t] += Fraction(2) ** e * state[s] + state[-1] = Fraction(0) + return tuple(state) + + +def graph_cases(max_n): + need(1 <= max_n <= 4, "census bound") + for n in range(1, max_n + 1): + possible = tuple(combinations(range(n), 2)) + for mask in range(1 << len(possible)): + yield n, tuple(e for j, e in enumerate(possible) if (mask >> j) & 1) + + +def algebra_checks(): + counts = {"graphs": 0, "binary_assignments": 0, "integer_assignments": 0, "thresholds": 0} + complete_minima = {} + for n, edges in graph_cases(4): + counts["graphs"] += 1 + a, delta = graph(n, edges) + events = word(n, edges) + base = n * (6 * a + 4) + 8 * len(edges) + cuts = [sum(k[i] != k[j] for i, j in edges) for k in product(range(2), repeat=n)] + best = max(cuts) + binary_min = min(invoice(events, k) for k in product(range(2), repeat=n)) + need(binary_min == base - best, "exact Max Cut minimum") + for k, cut in zip(product(range(2), repeat=n), cuts): + need(invoice(events, k) == base - cut, "literal binary tariff") + counts["binary_assignments"] += 1 + for k in product(range(-2, 4), repeat=n): + clipped = tuple(min(1, max(0, x)) for x in k) + distance = sum(abs(x - y) for x, y in zip(k, clipped)) + value = objective(n, edges, k) + need(invoice(events, k) == 3 * len(events) + value, "full invoice decomposition") + need(value >= objective(n, edges, clipped) + (delta + 5) * distance, "quantitative clipping") + need(invoice(events, k) >= binary_min, "integer optimum floor") + counts["integer_assignments"] += 1 + for threshold in range(-1, len(edges) + 2): + need((best >= threshold) == (binary_min <= base - threshold), "decision equivalence") + counts["thresholds"] += 1 + if len(edges) == n * (n - 1) // 2: + complete_minima[str(n)] = binary_min + counts["complete_graph_minima"] = complete_minima + return counts + + +def endpoint_checks(): + counts = {"gauge_words": 0, "dirty_endpoints": 0, "executed_primitives": 0} + for n, edges in graph_cases(3): + events = word(n, edges) + for k in product(range(-1, 3), repeat=n): + ops = primitives(events, k) + need(len(ops) == invoice(events, k), "literal macro bill") + counts["gauge_words"] += 1 + fixtures = [tuple(int(j == i) for j in range(n + 2)) for i in range(n + 2)] + fixtures.extend(tuple(Fraction((i + 1) * sign, i + 2) for i in range(n + 2)) for sign in (-1, 1)) + for initial in fixtures: + need(execute(ops, initial) == exact_endpoint(events, initial), "complete dirty endpoint") + counts["dirty_endpoints"] += 1 + counts["executed_primitives"] += len(ops) + return counts + + +def control_checks(): + events = word(2, ((0, 1),)) + k = (1, 0) + initial = (Fraction(2), Fraction(-3), Fraction(5), Fraction(7)) + expected = exact_endpoint(events, initial) + need(execute(primitives(events, k, wrong_ratio=True), initial) != expected, "wrong-ratio control") + need(execute(primitives(events, k, omit_exit=True), initial) != expected, "missing-exit control") + need(execute(primitives(events, k)[:-1], initial) != expected, "truncated-word control") + need(invoice(events, k) - 2 * sum(map(abs, k)) != invoice(events, k), "boundary-price control") + need(sum(3 + abs(e) for _, _, e in events) != invoice(events, (0, 0)), "unit-discount control") + triangle = ((0, 1), (0, 2), (1, 2)) + need(max(sum(x[i] != x[j] for i, j in triangle) for x in product(range(2), repeat=3)) == 2, "frustrated triangle") + rejections = 0 + for n, edges in ((0, ()), (5, ()), (2, ((0, 0),)), (2, ((1, 0),)), (2, ((0, 2),)), (2, ((0, 1), (0, 1))), (2, [[0, 1]]), (True, ())): + try: + graph(n, edges) + except ValueError: + rejections += 1 + else: + raise ValueError("invalid graph accepted") + need(rejections == 8, "all invalid controls rejected") + return {"semantic_controls": 6, "invalid_graph_rejections": rejections} + + +def local_lemmas(): + count = 0 + for d in range(-128, 129): + need(pair(d) == (2 if d == 0 else 1 if abs(d) == 1 else 2 * abs(d)), "pair formula") + need(abs(pair(d + 1) - pair(d)) <= 3, "pair Lipschitz") + for a in range(1, 8): + clipped = min(1, max(0, d)) + need(unary(a, clipped) == 1, "binary unary value") + need(unary(a, d) - 1 >= (2 * a + 3) * abs(d - clipped), "unary clipping") + count += 1 + return count + + +def source_hashes(): + pins = json.loads((HERE / "SOURCES.json").read_text()) + hashes = {} + for pin in pins["files"]: + if pin["usage"] == "input": + path = HERE.parents[1] / pin["path"] + raw = path.read_bytes() + need(len(raw) <= 32768, "source capacity") + digest = sha256(raw).hexdigest() + need(digest == pin["sha256"], "source authentication") + hashes[pin["path"]] = digest + for name in FILES: + raw = (HERE / name).read_bytes() + need(len(raw) <= 65536, "package file capacity") + hashes[name] = sha256(raw).hexdigest() + return hashes + + +def main(): + hashes = source_hashes() + result = {"status": "PASS_INTEGER_GAUGE_MAXCUT", "files_sha256": hashes} + result["local_lemma_cases"] = local_lemmas() + result["algebra"] = algebra_checks() + result["endpoints"] = endpoint_checks() + result["controls"] = control_checks() + print(json.dumps(result, sort_keys=True)) + + +if __name__ == "__main__": + main()