diff --git a/research/negative-slope-partition-optimizer/PROOF.md b/research/negative-slope-partition-optimizer/PROOF.md new file mode 100644 index 0000000000..14ab2c3059 --- /dev/null +++ b/research/negative-slope-partition-optimizer/PROOF.md @@ -0,0 +1,178 @@ +# Exact maximization for a negative Reading B slope + +This scoped proof was produced by Nick Petalas. Apache-2.0. + +## Contract and credit + +Let R be a positive integer. Let phi be a real-valued function on +{0,...,R}, with phi(0)=0 and differences + +```text +delta(j) = phi(j) - phi(j-1), +delta(1) >= ... >= delta(R) >= 0. +``` + +Fix d<0 and c>=0. For a positive integer partition of R, choose one free +piece and charge c+d phi(r) to each remaining piece. Its credit relative +to the unsplit target is + +```text +Delta = phi(free) + sum_charged [phi(r) - c - d phi(r)] - phi(R). +``` + +Unpaidmoon's [#7299](https://github.com/CrocSwap/integer-mult-bounds/pull/7299) +states this Reading B formula. Its +[#7449](https://github.com/CrocSwap/integer-mult-bounds/pull/7449), head +`180fac9c9797fee6ec44df8d9540f71612d07e1a`, proves an existence test +and explicitly leaves the maximizing partition open. These results are +cited premises, not audit targets. The argument below uses the displayed +definition and elementary discrete concavity. It does not use either +predecessor's existence proof or executable. + +## Theorem + +For each piece count 2<=k<=R put m=k-1 and n=floor(R/k). For every +1<=s<=n write + +```text +R-s = m q + r, 0<=r1. For a fixed multiset of pieces, the credit is + +```text +A sum_i phi(r_i) + d phi(free) - (k-1)c - phi(R). +``` + +Since d<0, choose a piece of minimum phi-value as the free piece. +Monotonicity of phi lets us choose a shortest piece s, including when +several distinct ranks have the same tariff. Positivity and the sum R +give 1<=s<=floor(R/k), and every charged piece is at least s. + +Fix k and s. If two charged ranks a,b obey b>=a+2, replace them by +a+1,b-1. They stay positive and at least s. The tariff sum changes by + +```text +phi(a+1)+phi(b-1)-phi(a)-phi(b) = delta(a+1)-delta(b) >= 0. +``` + +Multiplication by A preserves the inequality. Repeating the exchange +terminates: the nonnegative integer sum of squares of the charged ranks +strictly decreases at each exchange. At termination those ranks differ +by at most one, hence are exactly q and q+1 with the multiplicities in +the theorem. Conversely this vector is feasible because +`R-s >= (k-1)s`, so q>=s. It has credit F_k(s)-m c. This proves part 1 +without asserting uniqueness; a linear tariff can have many other optima. + +Let B_m(t) denote the maximum tariff sum of m positive integers totaling +t. The same exchange argument gives its balanced formula. Removing one +unit from a largest balanced piece gives + +```text +B_m(t) - B_m(t-1) = delta(ceil(t/m)), t>=m+1. +``` + +For completeness, if t=mq+r with r>0, the removed unit changes one +q+1 to q, giving delta(q+1). If r=0, it changes one q to q-1, +giving delta(q). These are exactly the two ceiling cases. + +For s=m+1, so subtracting adjacent F-values gives + +```text +F_k(s+1)-F_k(s) = delta(s+1) - A delta(ceil((R-s)/m)). +``` + +As s increases, delta(s+1) does not increase. The ceiling index does +not increase, so its delta-value does not decrease. Therefore D_k(s) +does not increase. This proves part 2. + +A sequence with nonincreasing forward differences increases strictly +until its first nonpositive difference, then never exceeds that value. +The first such index is the first maximizing index, even if several +zero differences follow it. If no such index exists, every step is +positive and n is the first maximum. This proves the index rule in +part 3. The search maintains an interval [low,high], initially [1,n]. +At a midpoint h0 discards indices <=h; otherwise it +discards indices >h. The remaining interval has at most the ceiling +of half the previous length. Thus ceil(log2 n) comparisons suffice. + +Every positive partition has some k between 1 and R. The case k=1 +has credit zero. Part 1 covers every other k. Each F-value uses a +constant number of tariff lookups and arithmetic operations, and each +sign test does too. Performing the bounded search for every k and +comparing the values proves part 4. The flat fee affects the choice +of k but cannot change the best s at a fixed k. + +## The zero-fee first example + +At c=0, the all-singleton partition always attains the global maximum. +Subadditivity, obtained by summing decreasing first differences, gives +`phi(r)<=r phi(1)`. Since the free rank s>=1 also gives phi(s)>=phi(1), + +```text +Delta = A sum_i phi(r_i) + d phi(s) - phi(R) + <= [A R + d] phi(1) - phi(R). +``` + +All R singleton pieces attain the right-hand side. For the strictly +concave harmonic tariff any piece larger than one makes its subadditive +bound strict, so this is the unique maximizing multiset when R>=2. +This settles the zero-fee harmonic first example asked for in #7449 +at every rank. The binary-search theorem also handles nonzero fees. + +At R=12, d=-1 and c=0, the first fixed-length optima include + +```text +k=2: (4,8), credit 122407/27720; +k=3: (2,5,5), credit 41747/5544. +``` + +The three-piece optimum strictly beats both (4,4,4) and (1,1,10). +The global optimum is twelve ones with credit 23-H_12. These rational +values and strict comparisons are computed by the verifier. + +## Boundary of the argument + +Concavity is essential to the charged-piece exchange. With the +nondecreasing table phi=(0,0,1,1,4,4,4), R=6, d=-1 and c=0, +the partition (1,1,4) has credit 4, whereas balancing its charged +pieces to (1,2,3) gives credit 0. The verifier computes both. + +The sign restriction d<0 chooses a shortest free piece; a positive +slope chooses a largest-tariff piece instead. The supplied optimizer +rejects nonnegative slopes rather than silently using the wrong rule. + +This is an accounting theorem under a declared rank-dependent fee. +It supplies no physical adapter, legal split, dirty-state restoration, +native operation, uniform compiler, selected-ledger improvement, new +kappa, or complete multiplication theorem. All five selected framework +assumptions remain. Independent human and formal proof-kernel review +are unclaimed. diff --git a/research/negative-slope-partition-optimizer/README.md b/research/negative-slope-partition-optimizer/README.md new file mode 100644 index 0000000000..28093a88df --- /dev/null +++ b/research/negative-slope-partition-optimizer/README.md @@ -0,0 +1,177 @@ +# Exact negative-slope partition optimizer + +This contribution was produced by Nick Petalas. Apache-2.0. + +For the negative-slope Reading B contract of unpaidmoon's +[#7449](https://github.com/CrocSwap/integer-mult-bounds/pull/7449), this package +finds a maximizing partition, answering its Open next question 1. The claim is +a **scoped written proof with exhaustive finite corroboration**. No new kappa +or selected-frontier change is claimed. + +At fixed piece count k, choose the shortest free rank s. The charged pieces +can be balanced. If R-s=(k-1)q+r, their multiplicities are k-1-r at q and r +at q+1. The resulting objective F_k is discretely concave in s, with + +```text +F_k(s+1)-F_k(s) + = delta(s+1) - (1-d) delta(ceil((R-s)/(k-1))). +``` + +The first nonpositive difference locates the first maximizing s. Comparing +these values over k and the unsplit target gives an exact optimizer in +O(R log R) arithmetic operations and comparisons. This is an oracle-model +bound, not a bit-complexity or tape-runtime claim. The proof covers all ranks +and real nondecreasing discretely concave tariffs with phi(0)=0, d<0, c>=0. +The supplied rational implementation accepts ranks 1 through 4096. + +At zero fee every tariff has an all-singleton optimum. For the strictly +concave harmonic tariff that maximizing multiset is unique, settling #7449's +proposed zero-fee first example at every rank. Nonzero fees use the same +optimizer. For the harmonic tariff at R=12, d=-1, c=0, the first fixed-length +optima include (4,8), scoring 122407/27720, and (2,5,5), scoring 41747/5544. +The latter strictly beats both the balanced and extreme three-piece splits. + +[PROOF.md](PROOF.md) contains the theorem, proof and scope counterexample. +[verify.py](verify.py) contains the optimizer and a separate literal partition +census that enumerates every possible free-piece choice. + +## Verification + +The exact finite checks cover: + +- All 1,000 tariff tables at ranks 1 through 10 whose nonincreasing first + differences lie in {0,1,2,3}, at slopes -3, -1, -1/3. +- Harmonic tariffs at ranks 1 through 20, at those slopes and -1/20. +- Every positive integer partition in each domain and every free-piece + choice at zero fee. For fees 0, 1/3, 1, 3, 7, subtract the exact length fee + from these exhaustive fixed-length maxima before comparing the global + optimizer. Counts include repeated partitions across tariff and slope cases. +- The first-difference identity, the first maximizing free-rank tie rule, + the binary comparison bound, global maximum, and an attaining partition. +- Explicit interior-free-rank examples, flat and linear tariffs, invalid + input rejection, and a nonconcave example where balancing charged pieces + strictly loses credit. + +A full run reports zero errors, 3,080 tariff/slope cases, 87,703 partition +scores, 396,388 free-piece choices, 21,784 fixed-length comparisons, +16,208 difference identities, 15,400 global comparisons, six witness checks +and thirteen failure controls. These are exact counts, not runtime estimates. +The finite census corroborates the written theorem; it is not an all-rank +exhaustive certificate. + +## Reproduce + +From the repository root, using CPython 3.12.15 and the standard library: + +```sh +IMB_PYTHON=/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 +"$IMB_PYTHON" -I -W error -B research/negative-slope-partition-optimizer/verify.py +"$IMB_PYTHON" -I -O -W error -B research/negative-slope-partition-optimizer/verify.py +"$IMB_PYTHON" -B scripts/research_package.py --package research/negative-slope-partition-optimizer +"$IMB_PYTHON" -B scripts/check_research_commit.py --package research/negative-slope-partition-optimizer --check-source-history --check-modes +``` + +The direct marker is `PASS_NEGATIVE_SLOPE_PARTITION_OPTIMIZER`; the registered +runner also prints `PASS_REGISTERED_RESEARCH_PACKAGE`. The commit check must +run after committing. Both registered commands have a 240-second limit. +Local warning-strict normal and optimized executions took 2.56 and 2.43 +seconds, respectively. These are single-run wall times for the timeout check, +not performance benchmarks. The registered two-command replay took 5.22 seconds. +For an optional generated receipt, append `--receipt /absolute/scratch/receipt.json` +to a direct command. The receipt records the actual interpreter, counts and +SHA256 of every package file. No receipt is hand-written or committed. + +## Scope, sources and overlap + +Card `coverage-law-change`, priority revision 8, base +`e54523517d0f03e58352e647c403a5af3e525a57`. Scope status is changed from a +completed physical call to this explicit accounting optimization. The selected +record is #7000 with kappa 363005817/100000000000. The catalogue's #5599 +assessment is historical. The source-binding orientation passed; no selected +scientific replay was run. Source pins for the catalogue and selected record +are provenance only, and there are no imported scientific inputs. + +Question source and direct predecessor: unpaidmoon #7449 at +`180fac9c9797fee6ec44df8d9540f71612d07e1a`. Its existence theorem is cited, +not replayed. Unpaidmoon #7299 at `bfcb85c0b7298392607092f751df4a7b1afb60c6` +supplies the Reading B definition and earlier fee analysis. The proof restates +the definition and is self-contained. These unmerged heads are citations, +not Git-history dependencies. No predecessor program is imported or executed. + +Live open-PR and Discussion intake was checked on November 12, 2026, including +#1166 and active threads. The overlap helper covered 768 open PRs and 7,360 +Discussion records. Its local sparse inventory omitted 9,973 historical note +paths; direct `git grep origin/main` searches covered the complete committed +README inventory for Reading B, negative slope, shortest/free pieces and +weighted balancing. Merged-PR searches also included rank-dependent fees and +the general partition model. The account-filtered #7449 reference search found +no recent source reuse among open PRs, but its closed-PR scan timed out; the +separate live all-state own-PR list and merged searches supply additional +coverage. None of these searches proves novelty. + +Related open work: + +- [#7449](https://github.com/CrocSwap/integer-mult-bounds/pull/7449) decides + existence for the same negative-slope fee. This package determines a + maximizing partition and does not replay its existence proof. +- [#7299](https://github.com/CrocSwap/integer-mult-bounds/pull/7299) studies + both fee readings, proves Reading A optima and nonnegative Reading B + existence, and leaves negative Reading B existence open. The present + optimizer concerns the negative Reading B maximum. +- [#7445](https://github.com/CrocSwap/integer-mult-bounds/pull/7445) identifies + a physical helper adapter and distinguishes it from the abstract fee + readings. This package makes no claim that its fee is physically realized. +- [#7303](https://github.com/CrocSwap/integer-mult-bounds/pull/7303) bounds + actual fixed-word singleton splits and a charged two-way moment. This + package optimizes the declared abstract fee without asserting physical + feasibility or comparing those different quantities. + +## Limitations and unrun obligations + +A profitable accounting partition does not provide a legal physical split or +adapter. Native implementation, chronological delivery, arbitrary dirty-state +restoration, complete paid and productive invoices, and supplier admission +remain unproved here. The five selected framework assumptions remain. No +complete multiplication theorem, independent human review or formal proof-kernel +acceptance is claimed. Lean, Docker, selected cold replays and predecessor +scientific suites were not run. Hosted CI is separate from the local evidence. + +## Open next questions + +1. Can one find the best piece count without comparing every k? The current + theorem searches the free rank efficiently at each k. First study the + discrete curvature of the optimized fixed-length values on exact tariff + tables. Maximization over s does not itself preserve concavity in k. +2. Does a real helper adapter have this negative-slope fee with independent + delivery? First name one producer, consumer, per-piece charge and complete + restoration contract. No such adapter is supplied here, and accounting + gains alone do not justify construction expansion. + +## Implementation bounds + +The optimizer validates rational input, rank 1 through 4096, negative slope, +nonnegative fee and the tariff hypotheses. Its binary search has an explicit +bit-length iteration cap. Census ranks are capped at 20; the larger integer +family stops at 10 and enumerates bounded combinations of four increments. +All functions are under 60 lines, and the code uses no recursion or dynamic +code loading. Contract rejection and all mathematical acceptance checks remain +active under optimized Python; assertions only check internal invariants. + +Python allocates integers, fractions and collections during execution. This is +a managed-runtime deviation from fixed post-initialization allocation. Live +storage is bounded by the supplied tariff and the fixed census domains; +arithmetic storage depends on input numerator and denominator lengths. The +census retains only one rank's partitions and one tariff case at a time. +A packed fixed-capacity implementation would require a separate numeric-range +contract before use in a constrained runtime. Warning-strict normal and +optimized commands are registered for every package replay. + +## Credit + +The new normal form, difference test, optimizer, zero-fee consequence and +corroborating verifier were produced by Nick Petalas. Unpaidmoon #7449 supplies +the maximizing-partition question and #7299 the fee definition. Retain their +Ali Romman #5769 fee-contract lineage and Nick Petalas #6651 uniform-fee +background; #5909 supplies earlier unit-fee context. Those optimization and +existence theorems are not steps in this proof. Balancing by discrete concavity +and monotone binary search are classical; no literature-priority claim is made. diff --git a/research/negative-slope-partition-optimizer/SOURCES.json b/research/negative-slope-partition-optimizer/SOURCES.json new file mode 100644 index 0000000000..5335fa97d9 --- /dev/null +++ b/research/negative-slope-partition-optimizer/SOURCES.json @@ -0,0 +1,18 @@ +{ + "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" + } + ] +} diff --git a/research/negative-slope-partition-optimizer/TASK.json b/research/negative-slope-partition-optimizer/TASK.json new file mode 100644 index 0000000000..91a4dbc6e3 --- /dev/null +++ b/research/negative-slope-partition-optimizer/TASK.json @@ -0,0 +1,90 @@ +{ + "schema_version": 1, + "task_id": "coverage-law-change", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "coverage-law-change", + "question": "Can a completed call earn more independent productive target credit without an offsetting paid bill?", + "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": "Use #5599 as a completed positive control, then choose one uncovered cut/module beyond an applicable frozen exclusion. Derive independence, saturation and chronological availability rather than counting rational rank alone. Price target credits and all new jobs together, then check compiler and actual caller compatibility. Stop on a nonphysical credit or an unfavorable complete relaxation.", + "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": [ + "target credit", + "helper split", + "coverage law" + ], + "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": "Exact maximizing positive partition for the negative-slope Reading B credit under a nondecreasing discretely concave tariff, with one shortest free piece and balanced charged pieces.", + "scope_change_reason": "The catalogue asks for a physically completed call. This package answers the explicitly open maximizing-partition accounting question in unpaidmoon #7449, without claiming an implemented adapter or supplier.", + "bottleneck_link": "This is a side result for pricing independent-target refinement with rank-dependent per-piece fees. It determines the best accounting credit before physical split legality and the complete caller invoice are addressed.", + "budget_minutes": 60, + "stop_rule": "Stop after the first verified normal-form and exact optimizer theorem, the zero-fee consequence and finite rational corroboration. Do not expand to physical adapters or other fee readings.", + "outcome": "completed", + "evidence": "PROOF.md supplies the all-rank argument; verify.py compares the optimizer against literal enumeration of all free-piece choices and all integer partitions in its declared finite boxes.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can the best piece count be found without comparing every k for this negative-slope contract?", + "why_it_matters": "The present theorem locates the best free rank at each k but still compares all k.", + "first_step": "Study the discrete curvature of the optimized fixed-length values using exact tariff tables.", + "blocked_by": "Maximizing over the free rank does not by itself preserve concavity in the piece count." + }, + { + "question": "Does any actual helper adapter obey this negative-slope fee with independent target delivery?", + "why_it_matters": "An accounting optimum can improve the recursive bill only when its fee and split can be implemented legally.", + "first_step": "Specify one helper, the producer and consumer, the physical per-piece charge and every restoration obligation.", + "blocked_by": "This package provides no physical adapter or selected-invoice binding." + } + ], + "question_source": { + "pr": 7449, + "author": "unpaidmoon", + "head": "180fac9c9797fee6ec44df8d9540f71612d07e1a", + "usage": "Question and self-contained fee definition only; no predecessor theorem is replayed or needed in the proof." + }, + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19572850", + "environment": { + "python": "3.12.15", + "dependencies": "standard library only" + } +} diff --git a/research/negative-slope-partition-optimizer/VERIFY.json b/research/negative-slope-partition-optimizer/VERIFY.json new file mode 100644 index 0000000000..a0e67d29a2 --- /dev/null +++ b/research/negative-slope-partition-optimizer/VERIFY.json @@ -0,0 +1,34 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 240, + "checks": "Exact optimizer against every integer partition and free-piece choice over all rank-at-most-10 concave integer tariffs with first differences in 0..3, plus harmonic tariffs through rank 20; first-difference, tie, witness and failure controls." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 240, + "checks": "Repeat the full exact coverage with Python assertions disabled; require-based acceptance checks remain active." + } + ] +} diff --git a/research/negative-slope-partition-optimizer/verify.py b/research/negative-slope-partition-optimizer/verify.py new file mode 100644 index 0000000000..43ccd15625 --- /dev/null +++ b/research/negative-slope-partition-optimizer/verify.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Exact negative-slope partition optimizer and exhaustive corroboration. + +Produced by Nick Petalas. Apache-2.0. See PROOF.md for the all-rank theorem. +No predecessor executable or selected scientific replay is used. +""" + +import argparse +from fractions import Fraction as Q +import hashlib +from itertools import combinations_with_replacement +import json +from pathlib import Path +import platform + + +MAX_RANK = 4096 +GRID_RANK = 10 +HARMONIC_RANK = 20 +SLOPES = (Q(-3), Q(-1), Q(-1, 3)) +FEES = (Q(0), Q(1, 3), Q(1), Q(3), Q(7)) + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def validate(phi, slope, fee): + require(2 <= len(phi) <= MAX_RANK + 1, "tariff rank outside 1..4096") + require(all(isinstance(x, (int, Q)) for x in phi), "tariff must be rational") + require(isinstance(slope, (int, Q)) and slope < 0, "slope must be negative") + require(isinstance(fee, (int, Q)) and fee >= 0, "fee must be nonnegative") + require(phi[0] == 0, "tariff must vanish at zero") + steps = tuple(phi[j] - phi[j - 1] for j in range(1, len(phi))) + require(steps[-1] >= 0, "tariff must be nondecreasing") + require(all(a >= b for a, b in zip(steps, steps[1:])), "tariff must be concave") + + +def balanced_score(phi, rank, pieces, free, slope): + """The c-free objective at a fixed shortest piece; caller supplies legal bounds.""" + charged = pieces - 1 + quotient, remainder = divmod(rank - free, charged) + assert 1 <= free <= quotient + total = (charged - remainder) * phi[quotient] + remainder * phi[quotient + 1] + return phi[free] + (1 - slope) * total - phi[rank] + + +def first_difference(phi, rank, pieces, free, slope): + charged = pieces - 1 + last = (rank - free + charged - 1) // charged + return phi[free + 1] - phi[free] - (1 - slope) * (phi[last] - phi[last - 1]) + + +def fixed_length(phi, rank, pieces, slope): + """Return the first maximizing free rank, c-free score and comparison count.""" + assert 2 <= pieces <= rank < len(phi) + low, high = 1, rank // pieces + comparisons = 0 + for _ in range((rank // pieces).bit_length()): + if low == high: + break + middle = (low + high) // 2 + if first_difference(phi, rank, pieces, middle, slope) > 0: + low = middle + 1 + else: + high = middle + comparisons += 1 + require(low == high, "binary search exhausted its explicit bound") + assert low == 1 or first_difference(phi, rank, pieces, low - 1, slope) > 0 + assert low == rank // pieces or first_difference(phi, rank, pieces, low, slope) <= 0 + return low, balanced_score(phi, rank, pieces, low, slope), comparisons + + +def optimize(phi, slope, fee): + """Maximize credit, breaking global ties by the least piece count.""" + validate(phi, slope, fee) + rank = len(phi) - 1 + best_value, best_pieces, best_free = Q(0), 1, rank + comparisons = 0 + for pieces in range(2, rank + 1): + free, before_fee, used = fixed_length(phi, rank, pieces, slope) + value = before_fee - (pieces - 1) * fee + comparisons += used + if value > best_value: + best_value, best_pieces, best_free = value, pieces, free + if best_pieces == 1: + return best_value, (rank,), comparisons + q, r = divmod(rank - best_free, best_pieces - 1) + parts = (best_free,) + (q,) * (best_pieces - 1 - r) + (q + 1,) * r + assert sum(parts) == rank and min(parts) == best_free + return best_value, parts, comparisons + + +def all_partitions(rank): + """Independent bounded dynamic enumeration, without the normal-form theorem.""" + require(1 <= rank <= HARMONIC_RANK, "partition census rank outside 1..20") + rows = [[] for _ in range(rank + 1)] + rows[0] = [()] + for part in range(1, rank + 1): + for total in range(part, rank + 1): + # The source row is strictly earlier, so it cannot grow during this loop. + rows[total].extend(p + (part,) for p in rows[total - part]) + return rows[rank] + + +def literal_credit(phi, parts, slope, fee): + """Enumerate every choice of the uncharged part using the fee contract.""" + values = [] + for free_index, free in enumerate(parts): + value = phi[free] - phi[sum(parts)] + for index, part in enumerate(parts): + if index != free_index: + value += phi[part] - (fee + slope * phi[part]) + values.append(value) + return max(values) + + +def brute_fixed(phi, rows, slope): + best = {} + for parts in rows: + pieces = len(parts) + candidate = (literal_credit(phi, parts, slope, Q(0)), -min(parts)) + if pieces not in best or candidate > best[pieces]: + best[pieces] = candidate + return best + + +def compare_case(phi, rows, slope, counts): + rank = len(phi) - 1 + exact = brute_fixed(phi, rows, slope) + counts["partitions_scored"] += len(rows) + counts["free_choices_scored"] += sum(map(len, rows)) + for pieces in range(2, rank + 1): + free, score, used = fixed_length(phi, rank, pieces, slope) + require((score, -free) == exact[pieces], "fixed-length optimizer disagrees") + bound = (rank // pieces - 1).bit_length() + require(used <= bound, "binary comparison bound exceeded") + counts["fixed_length_comparisons"] += 1 + for s in range(1, rank // pieces): + actual = balanced_score(phi, rank, pieces, s + 1, slope) + actual -= balanced_score(phi, rank, pieces, s, slope) + require(actual == first_difference(phi, rank, pieces, s, slope), "difference formula") + counts["difference_identities"] += 1 + for fee in FEES: + expected = max((v[0] - (k - 1) * fee, -k) for k, v in exact.items()) + value, parts, _ = optimize(phi, slope, fee) + require((value, -len(parts)) == expected, "global optimizer disagrees") + require(literal_credit(phi, parts, slope, fee) == value, "witness does not attain") + counts["global_comparisons"] += 1 + counts["tariff_slope_cases"] += 1 + + +def exhaustive_grid(counts): + for rank in range(1, GRID_RANK + 1): + rows = all_partitions(rank) + for increasing in combinations_with_replacement(range(4), rank): + phi = [Q(0)] + for step in reversed(increasing): + phi.append(phi[-1] + step) + for slope in SLOPES: + compare_case(phi, rows, slope, counts) + counts["integer_tariffs"] += 1 + + +def harmonic_grid(counts): + phi = [Q(0)] + for rank in range(1, HARMONIC_RANK + 1): + phi.append(phi[-1] + Q(1, rank)) + rows = all_partitions(rank) + for slope in (*SLOPES, Q(-1, 20)): + compare_case(phi, rows, slope, counts) + + +def witnesses(): + phi = [Q(0)] + for rank in range(1, 13): + phi.append(phi[-1] + Q(1, rank)) + expected = ((2, 4, Q(122407, 27720)), (3, 2, Q(41747, 5544))) + for pieces, free, score in expected: + actual_free, actual_score, _ = fixed_length(phi, 12, pieces, Q(-1)) + require((actual_free, actual_score) == (free, score), "interior-free witness") + value, parts, _ = optimize(phi, Q(-1), Q(0)) + require(parts == (1,) * 12, "zero-fee singleton optimum") + require(value == 23 - phi[12], "zero-fee value") + # This is neither the balanced nor the extreme three-part partition. + winner = literal_credit(phi, (2, 5, 5), Q(-1), Q(0)) + require(winner > literal_credit(phi, (4, 4, 4), Q(-1), Q(0)), "balanced control") + require(winner > literal_credit(phi, (1, 1, 10), Q(-1), Q(0)), "extreme control") + return 6 + + +def failure_controls(): + cases = ( + ((0, 1, 3), -1, 0), + ((0, 2, 1), -1, 0), + ((1, 2, 3), -1, 0), + ((0, 1, 2), 0, 0), + ((0, 1, 2), 1, 0), + ((0, 1, 2), -1, -1), + ((0, 1.0, 2), -1, 0), + ((0,), -1, 0), + ((0,) * (MAX_RANK + 2), -1, 0), + ) + for phi, slope, fee in cases: + rejected = False + try: + optimize(phi, slope, fee) + except ValueError: + rejected = True + require(rejected, "invalid contract accepted") + # Without concavity even balancing the charged pieces can lower the credit. + bad = tuple(map(Q, (0, 0, 1, 1, 4, 4, 4))) + require(literal_credit(bad, (1, 1, 4), Q(-1), Q(0)) == 4, "nonconcave witness") + require(literal_credit(bad, (1, 2, 3), Q(-1), Q(0)) == 0, "nonconcave balance") + # Choosing a balanced whole partition is a genuinely failing candidate. + linear = tuple(map(Q, range(7))) + require(literal_credit(linear, (2, 2, 2), Q(-1), Q(0)) == 4, "linear balanced") + require(literal_credit(linear, (1, 2, 3), Q(-1), Q(0)) == 5, "linear unbalanced") + return len(cases) + 4 + + +def write_receipt(path, counts): + package = Path(__file__).resolve().parent + destination = Path(path).resolve() + require(not destination.is_relative_to(package), "receipt must be outside the package") + files = sorted(p for p in package.iterdir() if p.is_file()) + receipt = { + "schema": "negative-slope-partition-verification/v1", + "status": "passed", + "python": platform.python_version(), + "counts": counts, + "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in files}, + } + written = destination.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n") + require(written > 0, "empty receipt") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--receipt", help="optional hash-bound JSON output outside the package") + args = parser.parse_args() + counts = dict.fromkeys(("integer_tariffs", "tariff_slope_cases", "partitions_scored", + "free_choices_scored", "fixed_length_comparisons", + "difference_identities", "global_comparisons"), 0) + exhaustive_grid(counts) + harmonic_grid(counts) + counts["witness_checks"] = witnesses() + counts["failure_controls"] = failure_controls() + counts["errors"] = 0 + if args.receipt: + write_receipt(args.receipt, counts) + print("PASS_NEGATIVE_SLOPE_PARTITION_OPTIMIZER " + json.dumps(counts, sort_keys=True)) + + +if __name__ == "__main__": + main()