diff --git a/research/p104-odd-unit-per-grading/NOTICE b/research/p104-odd-unit-per-grading/NOTICE new file mode 100644 index 0000000000..b858dcf2b4 --- /dev/null +++ b/research/p104-odd-unit-per-grading/NOTICE @@ -0,0 +1,21 @@ +Apache-2.0. DreamingOfClouds with Claude Opus 5.5 (Anthropic), via Claude Code. The outside-session lanes +DECZERO, COURIER, YYMIX, XBIRTH and WEBS are DreamingOfClouds'. Parts of the analysis (the Clone lemma, +the b-family, M45 as the B-port contract) were Fable-assisted and reproduced independently by our lanes. + +data/base-7546-word.json.gz is the #7546 word by ToikY (bytes of expected/role902-WORD.json.gz at #7546 head +99438c43df7aac1e5dbcc43c1578fcd886c119ec, SHA256 pinned in words.py); credit ToikY. The unpaid words in Part III +are our own edits of it, shipped as edit lists (data/edits-*.json.gz, data/window8-targets.json.gz). + +data/W6805.json.gz is CubeJerry's #6805 word, used as data only by cuts.py; credit CubeJerry. +No code from that PR is run. The feeder6805 edit list (data/edits-feeder6805.json.gz) is our own (an outside-session lane, Fable-assisted), and data/mix14-bprime-R.json is our own lane data. + +data/lines120.json (Gram and F2^9 labels of the 120 E8 lines, the first 104 being the P104 ports) is our derived +data, checked against the repository file research/complex-frame-pair-decoders/inputs/pr717/P104_HIT_flip_3a.txt +(PR968 decoder, pinned in SOURCES.json) through data/iso968.json, as in #7583; credit the PR968 authors. +data/half18_frames.json and data/ports_B.json are our own lane data. + +Credit Rohan Arun for the #7113 signed caller and its B pair, Clear1nsight, ToikY and the other contributors of the +P104 price and replay lineage for the conventions, and SYLforge, FanPUYen and aliromman for the frontier PRs +referenced in the README. + +All checkers in this package are our own code; no code is imported from the repository or any other package. diff --git a/research/p104-odd-unit-per-grading/PROOF.md b/research/p104-odd-unit-per-grading/PROOF.md new file mode 100644 index 0000000000..db57cd8187 --- /dev/null +++ b/research/p104-odd-unit-per-grading/PROOF.md @@ -0,0 +1,302 @@ +# Proofs + +Tags as in the README: **[P]** proved here; **[C]** exact computation re-run by a checker in this package; +**[C-lane]** exact computation by our lane code, reported with its number, not re-run in CI; +**[C-param]** priced by our invoice tool (control: it reproduces #7546's κ .003648411294790 and S = 1424); +**[S]** judgement. A statement tagged [P] uses only what its proof says plus the cited earlier lemmas. + +Common setting (the P104 relay family, as in #7555 and #7557): + +- Registers hold rational linear combinations of input **tokens**. A public register starts at its own token; an owned + register starts at 0 (INIT) and ends cleared. Frames are F2-subspaces of F2^9. ADD/COPY need both operands at the + same frame; public MOVEs strictly ascend; owned MOVEs are nested and are the only paid owned events ("moved rows"). +- **Ports.** Port t has an odd label q_t ∈ F2^9 (q_t·q_t = 1). x_t and y_t are its two inputs. Cell (t, s) is **odd** + when q_t·q_s = 1, **even** otherwise. On P104 the Gram G of the 104 lines has G² = 26G; a cell is odd iff G_ts is + even (diagonal 2, off-diagonal 0), and even iff G_ts = ±1 [C e8laws.py]. +- **Contracts.** The per-port t = −1 contract is X = x − y, Y = x; #7546 runs t = 0. A **grading** σ_p flips the + sign of the phase variable q of port p; for a matrix N of Laurent entries, R(N) = σ(N)N⁻¹ and o(N) = rank(R − I). + +--- + +## 1. The odd unit, per grading + +**Theorem I1 (o = rank of the odd part, any size) [P, C odd_unit.py].** For any invertible n×n N over a ring where σ is +an automorphism and 2 is invertible, o(N) = rank Odd(N), Odd(N) = (N − σN)/2. + +*Proof.* R − I = (σN − N)N⁻¹ = −2·Odd(N)·N⁻¹, and N⁻¹ is invertible. ∎ + +The identity is blind to block size, ring and coupling: bigger blocks, ring extensions and coupled port blocks have +the same bill as their odd parts. + +**Theorem I2 (Cayley form of the park) [P, C].** Write N = E + O with E σ-even and O σ-odd. Then +R = (E − O)(E + O)⁻¹ and ker(R + I) ≅ ker E. So R has eigenvalue −1 exactly when the σ-even part is singular. + +*Proof.* R + I = ((E − O) + (E + O))N⁻¹ = 2E·N⁻¹. ∎ + +**Corollary I3 (per port) [P, C].** For N = [[c, aq], [b/q, d]] with a, b, c, d σ-fixed and Δ = cd − ab ≠ 0: +R = Δ⁻¹[[cd + ab, −2acq], [−2bd/q, cd + ab]], det R = 1, tr R = 2(cd + ab)/Δ, det(R + I) = −4cd/(ab − cd). +A root stage with pairing t needs tr R = 2 + 4t, so the native's **effective t is t_eff = ab/(cd − ab)**, and +**t_eff = −1 ⇔ cd = 0**: X holds no x or Y holds no y. That is the park. + +**Lemma I4 (dressing) [P, C].** For σ-fixed A, B, R(ANB) = A·R(N)·A⁻¹. Free (σ-fixed) caller operations cannot change +tr R, hence cannot change t_eff. *Proof.* σ(ANB) = A σ(N) B. ∎ A q-odd dressing does change tr R (control, 165/200). + +**Proposition I5 (the ledger is per grading) [P, C].** +1. The 104 gradings σ_p are distinct (no two ports have parallel gates; quoted from our GAUGECYCLE lane), and a q-free + coupling P⁻¹TP of the per-port targets leaves each port's σ_a-multiplicity at m_a = 2 [C I6]. +2. A unit shared by two ports would have to be odd in both gradings. The monomial q_a q_b is (o_a = o_b = 1), but it is + two directional kernels, so two child calls (05-layers.tex, "exact recursive contract": one child per residual + dimension). The isotropic kernel a + b·q_a²q_b², the combination that would let Y's end frame contain X's birth + frame, is **even in both gradings** (o_a = o_b = 0) [C I5]. +3. A coupled block can make E_a singular while E_0 = I (singular pencil E_a = [[1, q_b], [q_b⁻¹, 1]]), but its + q_b-odd entries are o_b = 2 junk in ledger b [C I4]. The park moves ledgers; it does not disappear. +4. Two ports cannot share one grading inside a word: 05-layers.tex l.4–7 fixes one array with complete address set, + and eq. (phase-conjugation), l.86–91, makes P_M a permutation of the whole array for any M ∈ GL(m, F2). There is + no per-port relabel inside a word without a frame event. + +**Theorem I6 (the 56 decoder rows are the odd unit) [P].** On every plane, every odd cell and every diagonal cell +must be served in both directions: y_s → X_t (UP: gather at f ⊆ q_s^⊥, deposit at f ∋ q_t) and x_s → Y_t (DOWN: +gather at f ∋ q_s, deposit at f ⊆ q_t^⊥). The diagonal alone forces both, since q_t ∉ q_t^⊥ (q_t·q_t = 1). A +monotone chain is blind to the other direction's odd cells, and a register used in both directions pays the climb +of each (round trip). Hence C(t = −1) ≥ C_up + C_down = 2·C_min per plane. + +*Proof.* A gather of s needs f ⊆ q_s^⊥ and a deposit into t needs q_t ∈ f (row model of #7583). UP chains climb from +a frame inside q_s^⊥ to one containing q_t; DOWN chains do the reverse, so a single monotone chain covers odd cells +in one direction only. ∎ #7546 already runs UP 56 + DOWN 56 across its two planes, and the park family +(an ascending 56 plus the W6805 descending 56) has the identical MOVE histogram [C-lane HANDT1], so every decoder +saving applies to t = 0 at the same rate: **the decoder cannot move t = −1 above t = 0.** + +**Exact E8 structure [C e8laws.py].** G² = 26G on the 104 ports, so G/2 = 13·proj(range G). The transposed twin of +the E8 decoder is frame-legal with M_L = G/2 and WᵀU = 13·I. The full UP-then-DOWN composition of the two G/2 +decoders leaves exactly −12·I on the diagonal and odd cells (0 of 5,720 odd cells nonzero): composing two decoders +is a per-port park with no owned charge, but only in the full order; a partial order breaks 1,360 cells. + +**Proposition I7 (XDEC: the joint multi-call decoder has rank ≥ 8k) [P, C].** A port and its copy in another call +carry the same label, so their cell is odd (q·q = 1). An 8-set of pairwise-odd ports and its k copies form a +principal 8k × 8k block with nonzero diagonal and zero off-diagonal pattern forced by the odd cells; any decoder +restricted to it is invertible, so rank ≥ 8k. Duplicate labels also forbid rank 8: w_p is fixed up to scale by its +55 odd neighbours, so w_{p'} ∝ w_p, contradicting w_{p'}·u_{p'} = 1, w_p·u_{p'} = 0. ∎ + +--- + +## 2. The contract invariant and the b-family + +**Proposition C1 [P, C odd_unit.py].** For any 2×2 contract [[a, b], [c, d]], t = bc/det and 1 + t = ad/det are +invariant under both diagonal gauges; t = −1 iff ad = 0, i.e. a zero diagonal entry ("Y has no y"). + +**Proposition C2 (M45 is the B-port contract) [P, C].** The merged plane M45 = [[1, −q], [1/q, 1]] satisfies +M45 = U_q + L_q − I while H = L_q·U_q; o(M45) = 2, R² = −I, M45² = 2J_q, M45⁴ = −4I, det M45 = 2, and +diag(1, ½)·M45 = HOST(−1, ½), so t_eff(M45) = −½: it is #7113's B pair on a ρ = 2 caller, and the det-2 factor is +one free SCALE. H·M45⁻¹ = [[1, 0], [1/(2q), ½]] has o = 1: turning M45 into the t = −1 native H is one q-odd op per +J, i.e. the park in caller form. + +**Proposition C3 (b-family) [P for the algebra, C-lane for the words].** The merged window word reaches +X = x − y, Y = x + b·y exactly for every b ∉ {0, −1} by changing window scalars only (t = −1/(1 + b)); t = −1 is the +limit b → 0, where one window scalar (1 + b)/b has a simple pole. (Fable-assisted analysis, reproduced by our lanes: +exact on 8/8 window ports for b = 1, ½, −½, −2, 10⁻³, 10⁻⁶.) + +**Proposition C4 (ρ = 1 forces the park; scoped to root callers) [P].** In the root-caller family (stages are hosted +pairs, gates σ-fixed, odd ops only at the thin units), a native is callable at a stage only if t_eff equals the stage's +t; ρ = 1 forces t = −1 at every stage (quoted root path theorem). By I4, free ops cannot move t_eff(M45) = −½, so each +of the 17 J needs ≥ 1 extra q-odd op per A port: c ≥ 1 owned-equivalent unit per A port per call against the +break-even 0.214 [C-param] — no crossing. Non-root callers are not covered. + +--- + +## 3. No-cloning lemmas (why every t = −1 construction pays one owned unit per port) + +**Rank lemma [P; toy C walls.py].** Every event (MOVE, ADD, COPY, SCALE ≠ 0, INIT, CLEAR) acts linearly on the full +state (public rows plus live owned rows, as functions of the public tokens); INIT adds a zero row and CLEAR removes +one, so rank(state) never increases. If the endpoint map is invertible, rank(state) = n_pub at all times. Hence: +(1) with no owned row live, public contents are independent and zeroing a public register is a permanent loss; +(2) a zeroed direction must sit in a live owned row until an owned → public ADD returns it; +(3) a dirty CLEAR is lossless iff its content lies in the span of the rest of the state at that moment. + +*Proof.* Each event's new state rows are linear combinations of the old ones (ADD/COPY/MOVE/SCALE), or a zero row is +added (INIT), or a row is deleted (CLEAR). None raises the row-space dimension. The endpoint is invertible, so the +final rank is n_pub, which equals the initial rank; hence the rank is n_pub throughout. (3): deleting a row keeps the +rank iff the row is in the span of the others. ∎ + +**Lock Lemma [P].** Let V0 be the span of the tokens of registers that are ever at {0}. After a register leaves {0}, +the V0-part of every content anywhere (public, unmoved owned, and decoder rows that snapshot native registers) lies in +the span of the departure contents. Only an owned row snapshotted at {0} and **moved** adds a V0 direction. + +*Proof.* Operations act between registers at one shared frame; public MOVEs ascend, so no public register returns to +{0}; unmoved owned rows stay at their frame. So the only way new V0 content reaches a register above {0} is through a +register that left {0} (its departure content) or an owned row that gathered at {0} and moved. ∎ + +**Clone lemma [P] (Fable-assisted analysis, reproduced independently by our CLONEAUDIT lane).** With ascending public +MOVEs and invertible contents, the contents with which registers leave {0} form a basis of the {0}-born token space +(Rank lemma). After the merge, the Y main arrives at its end frame as m + u, where m is its own departure content and u +is built at X's birth frame before any Y-side content is present. Final Y = x needs m in the span of what else reaches +the Y-end frame, which the basis property excludes; an unmoved snapshot can zero m only by making the global map +singular (Rank lemma (3)). So **the park needs a clone of m, and only moved owned rows clone.** + +**Theorem W (separate twins wired before/after the native) [P].** Keep the hosted twins as separate public registers +and wire them to the #7546 native only before or after it. Then either ≥ 96 moved owned rows are needed per call +(order Y = x) or the V-span deficit is ≥ 1 per A port (the other order). +*Proof sketch.* (Y = x order) pick φ ∈ V0* vanishing on all non-Y departure contents; the functional +g = Σ_s φ(c_{Y_s})·coef_{x_s} − φ(V0-part) vanishes on every register at frames ⊆ q_t^⊥ after the native, and its +support stays at frames ∋ q_t; so g(Y_t) = 0 forces φ(c_{Y_t}) = 0 for every exact Y_t, a rank deficit of ≥ 96 that +only moved {0}-rows (Lock Lemma) can fill. (Other order) X arrives at V with x-coefficient 1 and the V targets have +none, so span(V-arrivals) ⊋ span(V targets). ∎ + +**Lemma NT (new tokens are useless unless debited to old rows) [P].** Add public registers that no old public or +owned register ever reads. Then span(arrivals at f) ∩ old-space = span(old arrivals) at every frame f: the gain is 0. +*Proof.* Only new registers hold new tokens, so their token block stays invertible; registers strictly below f meet +only each other and only leave, so span(arrivals at f) ⊕ span(rows strictly below f) is direct, and the new +arrivals' token parts are independent. ∎ + +**Lemma AS / VA [P].** At a frame f where every read is corrected, the span of everything held at f is the span of +the arrival contents at f (AS). At V, everything held is in span(public arrivals at V) + span(moved owned rows at V); +with #7557's Theorem M, D ≥ rank_K(merged classes of the V arrivals) − m_moved, and a token-free y_t arriving at V +has class e_t, adding a row it cannot cancel (VA). [C-lane: rank_K{e_t : t ∈ A} = 95; #7546's live X arrivals 88.] +So an unmoved owned row changes **when** registers exchange content, never **where** they meet. + +**Lift law [P].** Rows that gather only at frames ∋ q_t hold vectors in span(T_t contents), T_t = registers at +frames ∋ q_t, and that span never shrinks. A delivery of x_t into Y_t at q_t^⊥ that leaves no deficit needs a first +deposit into a T_t register with content reaching outside T_t: an **ascending owned MOVE**. Descending decoder rows +and unmoved rows cannot make it. [toy C walls.py: A3/A4, the PLN variants are top-solvable 0/216 and 0/360 (D = 1); positive controls +D = 0 with one.] + +**Freeze Lemma [P].** Under no imports into q_t^⊥, the span of everything ever held at q_t^⊥ equals the span of +its arrival contents. *Proof.* Park every register on arrival at V or at any q_u^⊥ and drop all ops there; below-ops +never read parked registers, so the frozen program replays every below-op, and the parked set's span equals its +arrival span at all times. ∎ Hence time differences at q_t^⊥ (or at V, or below) deliver nothing a single-time +delivery cannot, and ≥ 1 crossing owned MOVE per served port stays necessary. + +**Shared-lift theorem [P, C e8laws.py].** One crossing owned MOVE serves only a set of pairwise F2-orthogonal +ports; such labels (q·q = 1) are linearly independent, so at most 9, and the exact maximum on P104 is **8**. With m +MOVEs, no m + 1 pairwise non-orthogonal ports can all be served (the matrix f_v(κ_u) has rank ≤ m, nonzero diagonal +and zeros on non-orthogonal pairs). *Note:* this is not "≤ 8m": the E8 Gram satisfies every Y-side constraint for +all 104 ports with m = 8; that "Gram lift" was then closed by the V side (Theorem M: D ≥ 104 − m_o on E8, and an A3 +exact test D ≥ 6 [C-lane GRAMLIFT]). + +**Commutation Theorem [P; toy C walls.py].** Every frame-local operation acts on the field side of a register +(C_r ← Σ A_rs C_s, A_rs any linear map on the field); every lemma above is a token-side row-space or support +statement. The two commute, so all of them hold for **any** enlargement of the same-frame op set (operator or +diagonal coefficients, graded registers, half-field swaps, block maps, monomials, lazy CLEAR, time shifts). A +primitive that changes a content's label is a copy plus one transition of Fourier rank ≥ 1, i.e. ≥ P[1] per field +(the d-metric price), so ≥ 1 unit per port per call. + +**XRECALL lemma [P, C].** x_b is born only at ⟨q_b⟩, gained only by same-frame ADDs, and public MOVEs ascend, so +every frame holding x_b contains ⟨q_b⟩. Y_b's end frame lies in q_b^⊥ and q_b·q_b = 1, so ⟨q_b⟩ ⊄ q_b^⊥: no frame +inside Y_b's end frame ever holds x_b publicly (0 of 96 recall sites without moved owned rows). + +**Zone lemma [P; toy C walls.py].** For two non-chainable receivers r1, r2, the zone Ξ of frames inside +q_r1^⊥ ∩ q_r2^⊥ is a down-set; ops in Ξ act invertibly on the pair of process adjoints, so the source rows +{(B[r1, t], B[r2, t])} entering Ξ must not be one line with both coordinates nonzero. One sender gives rank 1 and +is impossible however many helpers relay; two independent senders escape (A4 toy exact with 0 owned). + +**Owned additivity (PARALLEL) [P].** Owned cost is paid per moved row and one row carries one vector. Departure +contents of different instances, siblings or calls are independent tokens, and the Clone lemma's basis holds for +their union, so the delivered rank needed is the **sum** over instances: M(A + B) ≥ M(A) + M(B). A coded row +m_A + m_B needs m_B as side information at A's Y end, and only B's own Y main holds it (Rank lemma). So c ≥ 96/104 += 0.92 owned units per port per call under any sharing, against the break-even 0.214 [C-param]. + +**Wiring lemma (FUSET1) [P].** Twins kept as public helpers with tokens a, b and wired only before/after the native: +Y's final row restricted to (y, b) is u·E2 with E2 invertible, so Y cannot lose y; with a free owned park at {0}, +b and y move together and every vector in span{X, X2, Y2} at V has equal b and y coefficients. One extra +independent vector per A port is needed at V. + +**Cut Lemma (WEBS; outside-session lane, DreamingOfClouds') [P, C cuts.py].** Model: public registers with their own +token, ascending moves, ADD/COPY only at a shared frame; any number of helpers with any chains, tokens cancelled +anywhere, each ending at its own token; owned registers token-free, INIT empty, free while unmoved, dirty CLEAR +free, a MOVE a → b costs |dim b − dim a|; time is real time. Let 𝒢 be an up-set of frames, Π the public vectors +entering 𝒢 (tokens of registers born in 𝒢 and public contents at moves from outside into 𝒢), O the owned contents at +moves from outside into 𝒢, and F the finals of public registers ending in 𝒢. Then F ⊆ span(Π + O) and |Π| = dim F, +hence **rank(O mod Π) ≥ def(𝒢) := dim(F + Π) − dim F.** +*Proof.* By induction over the real event order, every content ever held at a frame of 𝒢 (public, owned, or owned +snapshot) lies in span(Π + O): public registers never leave 𝒢, and owned registers are INIT'd empty in 𝒢, carried +their content across the cut (O), or read it inside 𝒢. Each public register ending in 𝒢 contributed exactly one Π +vector (born in 𝒢 or crossed once), and the finals are independent because the word is exact. So +dim span(Π + O) ≥ dim(F + Π) and dim Π ≤ |Π| = dim F. ∎ Nothing about helpers is used: webs, token cancellation, +snapshots and zeroing are inside the induction. +Corollaries [P]: **C1** at t = −1, def(𝒢_s) ≥ 1 for 𝒢_s = {frames ∋ q_s} (x_s is born in 𝒢_s and is in F only +through Y_s's final, which ends in q_s^⊥ ∌ q_s), so some owned MOVE enters 𝒢_s; refining 𝒢_s by the up-sets of +owned ascents whose source is not inside q_s^⊥ shows that some owned ascent leaves q_s^⊥ upward. **C2** if every +owned move except line feeders {0} → ⟨q_t⟩ descends, only s's feeder crosses into 𝒢_s, so M ≥ 104 (S ≤ 712 +[C-param]) for any web and schedule. **C3** with no owned crossing into {≥ f}, every content at f lies in +span{x − y, x_r with f ⊆ q_r^⊥, tokens of helpers ending above f}, so X_s is U-complete there. **C4** with line +feeders F, unfed ports R and extra ascents E on a descending decoder, any pairwise-odd I ⊆ R gives an up-set with +def ≥ |I| that a line feeder enters only through an E-move starting on its line, so |E| ≥ |I| and +M ≥ |F| + α(R); α(P104) = 8 [C]. *Not proved:* that ascents cannot be shared between ports (cuts alone allow +climb 3 for n = 4 on F2³); the conjecture M ≥ n is [S]. + +**UFLOOR duality is type-preserving [P].** The dual of a U job (transfer [[I, Z], [0, I]], X ← y) has transfer +the transpose, whose receivers have X geometry: U ↦ U, L ↦ L; a MOVE A → B dualises to B^⊥ → A^⊥, so ascents stay +ascents. (This corrects internal notes that dualised U builds into L builds; none of those claims is in a public PR.) + +--- + +## 4. Decoder-wall pieces since #7583 + +Model and notation as in #7583 (row model; certificates Z on odd cells and the diagonal with nonzero diagonal). + +**Lemma A(acyc) [P].** Let M = Σ_k w_k u_kᵀ and T a port set with M_pp ≠ 0 on T and the nonzero odd off-diagonal +cells of M on T × T forming an **acyclic** digraph. Then every valid certificate Z has +|T| ≤ Σ_k rank Z[D_k ∩ T, S_k ∩ T]. *Proof.* In a topological order (Z∘M)[T, T] is triangular with diagonal +Z_pp·M_pp ≠ 0; Hadamard linearity and rank subadditivity give the bound. ∎ So rank certificates cannot tell an exact +decoder from one with arbitrary "upper" junk: proving C ≥ 52 on P104 this way requires that no acyclic decoder of +cost ≤ 51 exists. + +**Lemma B (mod-4 certificates, half-integer decoders) [P].** For rows with w 2-adically integral and 2u integral, and +any integer Z with odd diagonal and zero on even cells: n ≤ Σ_k s2(Z[D_k, S_k]), s2 = number of 2-adic invariant +factors of valuation ≤ 1. *Proof.* 2Δ = Σ diag(w) Z_k diag(2u); Smith-lift Z_k mod 4; the result is 2(Δ − 2X), +which is nonsingular. ∎ s2 is monotone under row and column deletion, so closures and mixtures go through. +[C-lane: sampled-closure LP with s2 gives λ ≥ 2.768 on 2,509 closures, against the 2.039 needed for C ≥ 52.] + +**Proposition H (HALF18 correction) [C e8laws.py].** The minimum rank of a full-flag certificate is far below the +"≈ 18 = 2h" stated in the HALFWALL notes behind #7583: on the 120 E8 lines a certificate of rank **15** exists +(15 pairwise-orthogonal 8-frames, Z = sum of the frame block-J's), and on the 104 P104 ports one of rank **13** +(13 frames); a pairwise-even 8-set gives the exact lower bound 8 (a diagonal block of Z), so the P104 minimum lies +in [8, 13]. The full flag therefore has slack; the binding constraints are on intermediate flags (sampled-flag LP +λ ≥ 2.62 [C-lane] against < 2.039 needed), so C ≥ 52 stays unproved. + +**Proposition E (early-set cap, EARLYCAP part A) [P].** Partition the 4,992 partner cells into early E and late F. +With C_all = G − 2I and GK = 0 (K = ker G), C_E K = −(2I + C_F)K. Put N = 2I + C_F (diagonal 2, ±1 on F); then the +contamination rank is d = rank(NK), so rank N ≤ d + 8, and rank N ≥ tr(N)²/‖N‖_F² = 208²/(416 + |F|). With +|F| = 4,992 − |E|: **|E| ≤ 5,408 − 43,264/(d + 8)**, i.e. ≤ 540.8 cells per contamination rank at d = 2 and +decreasing, below the 577 needed to tie the park family [C-param]. d = 0 forces E = ∅ (TMLEVER). The d = 1 window +577–600 is open. + +**Proposition T (T1CANCEL refutes EARLYCAP part B) [C-lane, P for the identification].** A diagonal canceller −x_t +added into the σ relay after the restore does make each merged class lie in range G (D = 0 in exact A3/A4/D4 +simulations and res = 0 mod p on E8). But the canceller reads Y_t's final at V: it is the owned L row copied into +the σ relay, and the free input is the zero-Y park P_t, so every "early" cell is a post-park cell and the design is +the park family plus 104 useless ADDs (0.8681× at the built U layer, 1.3093× at the LP floor [C-param]). + +--- + +## 5. Local re-solve on a fixed schedule + +Setting (NETCOMPILE frame window): wires 1..n, gates E = I + q·e_A e_Bᵀ or SCALE, product C = E_N ⋯ E_1. A gate at +frame F, time t is legal iff both wires are at F at time t. Dropping one interior stay removes its gates (circuit G2, +product C2); D := C2⁻¹T, P_t := product of G2 gates before t, N_t := P_t(D − I)P_t⁻¹. + +**Theorem F (the "one-rank law" is the Fredholm alternative) [P, C onerank.py].** A repair decided by comparing +rank A with rank [A | b] for one column b always has rank [A | b] − rank A ∈ {0, 1}. Every engine we used to test +drops (NETCOMPILE, SEEDBUILD, TOKDEBT, OWNRETIME) has one right-hand side, so the reported "every drop misses by +exactly one rank" (161/161, 162/162, 168 cases) means only "infeasible". **Correction:** our earlier +"contact-minimality conjecture" read structure into this count; it carries none. + +**Lemma LIN [P].** Insert corrections a_i += k_i·b_i at positions p_i into G2. If no source slot (b_j, p_j) is +reachable in G2's dependency DAG from a target slot (a_i, p_i) with p_i ≤ p_j, then +final = C2 + Σ k_i·S_{p_i}[:, a_i] ⊗ R_{p_i}[b_i, :] exactly. A relay through a drop-dirty wire is linear; only +wires already made dirty by a correction give bilinear terms. + +**Lemma TR (one-block re-solve) [P].** Replacing every gate at F during a maximal interval (t, F, Π) by some +X ∈ GL(Π) realises T iff N_t is supported on Π × Π. *Proof.* Gates elsewhere commute with X; C2 = S·X_o·P_t and +T = C2·D give X = X_o(I + N_t), which lies in GL(Π) iff I + N_t does. ∎ + +**Lemma 2B (two blocks) [P].** For time-disjoint intervals I1 < I2 with M = P2·P1⁻¹ and g = B1⁻¹ = I + E·Y·Eᵀ, +blocks exist iff N2 + (I + N2)·M[:, Π1]·Y·M⁻¹[Π1, :] = 0 off Π2 × Π2 (linear in Y) and det(I + Y) ≠ 0; then +B2 = (I + N2)·M·g·M⁻¹ is forced. + +**Descent Lemma [P, C onerank.py].** For any repair family decided by one linear system with one right-hand side, +greedy single drops terminate at a configuration where every single drop is infeasible, and by Theorem F every stay +then "misses by one". So the law holds at every local minimum and gives no lower bound: in the toy W·W⁻¹ (target I, +optimum 0 stays) descent can stop at 4 rigid stays, and m disjoint copies give 4m against 0. + +**Lemma RT (BREAKER8) [P, C words.py].** A main's route costs exactly what a helper doing the same route costs: +swapping the route onto a new helper plus one main jump leaves κ unchanged. So "mains are fixed" carries no price. diff --git a/research/p104-odd-unit-per-grading/README.md b/research/p104-odd-unit-per-grading/README.md new file mode 100644 index 0000000000..a35ac7cafa --- /dev/null +++ b/research/p104-odd-unit-per-grading/README.md @@ -0,0 +1,347 @@ +# P104: the odd unit, paid per grading (no κ) + +This package collects one day of P104 research (Nov 14) on two questions: + +- **The decoder wall.** Can the 56 owned decoder units per plane be reduced? +- **The t = −1 park.** Can a one-plane t = −1 native (X = x − y, Y = x) beat #7546's t = 0 word? + +It has three parts: + +- **Part I.** The lemmas and theorems we proved. +- **Part II.** Every route we closed, each as a scoped negative result with the reason it fails. +- **Part III.** The words we built that did not pay, with exact replays. + +It makes **no κ claim** and ships no new frontier word. The base word is ToikY's #7546 (κ 0.003648411294790). +At the time of writing the frontier is aliromman's #7605 (κ 0.0036504442446), stacked on #7604 (FanPUYen), +#7603 (SYLforge) and our #7601. None of the results below depends on those edits. + +**One cost behind both walls.** The bill for t = −1 and the bill for the decoder are the same object: the **odd +unit**, paid separately in each port's own grading σ_p. + +- o(N) = rank of N's σ-odd part, for any block, any ring and any port coupling (I1). +- t = −1 holds exactly when the σ-even part is singular (I2, the Cayley form of the park). +- No contract can share that unit between ports. Two ports never share a grading inside a word, and the isotropic + combination q_a + q_b is even in both gradings (I5). +- On the decoder side, the odd diagonal (q·q = 1) forces both an UP and a DOWN decoder in every plane. The 56 owned + rows are the price of that diagonal (I6). +- Every construction that tries to move the park elsewhere meets one fact. Content is never cloned without a + **moved owned row** (the Rank, Lock and Clone lemmas, Theorem W, NT, AS/VA, the lift law, Freeze, the Cut + Lemma, Commutation). That costs about 1 owned unit per port per call, against a break-even of 0.214. + +Tags: + +- **[P]** proved in [PROOF.md](PROOF.md). +- **[C]** exact computation, re-run by a checker in this package. +- **[C-lane]** exact computation by our lane code. Its number is reported, but CI does not re-run it. +- **[C-param]** priced by our invoice tool. Its control reproduces #7546's κ 0.003648411294790 and S = 1424. +- **[S]** judgement. +- **[open]** open question. + +Nothing tagged [S] or [open] is claimed as a result. + +A network-compiler effort (recompiling the helper layer from requirements) is ongoing. **Nothing from it is +claimed here.** + +## How to verify + +``` +python3 -I -B research/p104-odd-unit-per-grading/odd_unit.py # Part I.1–I.2 contract identities PASS_ODD_UNIT_PER_GRADING +python3 -I -B research/p104-odd-unit-per-grading/e8laws.py # E8/P104 exact structure PASS_E8_LAWS +python3 -I -B research/p104-odd-unit-per-grading/walls.py # register-machine toys for the walls PASS_WALL_TOYS +python3 -I -B research/p104-odd-unit-per-grading/onerank.py # Theorem F, descent toy PASS_ONERANK +python3 -I -B research/p104-odd-unit-per-grading/cuts.py # Cut Lemma on two real words PASS_CUT_LEMMA +python3 -I -B research/p104-odd-unit-per-grading/words.py # Part III exact replays PASS_UNPAID_WORDS +python3 scripts/research_package.py --package research/p104-odd-unit-per-grading +``` + +- All checkers use the standard library only and run in minutes. +- [VERIFY.json](VERIFY.json) lists what each one checks, including its positive and negative controls. + +--- + +## Part I. Theorems and lemmas + +### I.1 The odd unit, per grading (`odd_unit.py`) + +| # | statement | tag | +|---|---|---| +| I1 | o(N) = rank(σN·N⁻¹ − I) = rank Odd(N), for any size, ring or coupling (40/40 random coupled 2–4×4, both gradings) | [P, C] | +| I2 | Cayley form: ker(R + I) ≅ ker E. So t = −1 ⇔ the σ-even part E is singular (40/40, 17 of them with singular E) | [P, C] | +| I3 | Per port, N = [[c, aq], [b/q, d]]: det(R + I) = −4cd/(ab − cd) and t_eff = ab/(cd − ab). So t_eff = −1 ⇔ cd = 0 (the park) | [P, C] | +| I4 | Dressing: R(ANB) = A·R(N)·A⁻¹ for σ-fixed A, B. Free caller ops cannot change t_eff. Control: a q-odd dressing changes tr R on 165/200 | [P, C] | +| I5 | The ledger is per grading. A q-free coupling keeps m_a = 2. A singular pencil moves the park into ledger b as o_b = 2 junk. The isotropic kernel a + b·q_a²q_b² is even in both gradings, while q_a·q_b is odd in both but is two child calls. 05-layers.tex l.4–7 and l.86–91 allow no per-port relabel inside a word | [P, C] | +| I6 | t = −1 needs UP and DOWN decoders in each plane, because the diagonal is odd: C(t = −1) ≥ 2·C_min. #7546 already runs UP 56 + DOWN 56 across its two planes, so every decoder saving also applies at t = 0 | [P; C-lane histograms] | +| I7 | A joint decoder over k calls has rank ≥ 8k: a port and its copy form an odd cell | [P, C] | + +**Exact E8 structure** (`e8laws.py`) [C]: + +- G² = 26G, so G/2 = 13·proj(range G). +- The transposed-twin decoder is frame-legal, with M_L = G/2 and WᵀU = 13·I. +- Composing the full UP decoder with the full DOWN decoder leaves exactly **−12·I** on the diagonal and odd cells + (0 of 5,720 odd cells nonzero). In the full order the composition is a per-port park with no owned charge. A + partial order breaks 1,360 cells. +- One shared crossing serves at most **8** pairwise-orthogonal ports, and the maximum pairwise-odd set α(P104) is 8. + +### I.2 The contract invariant (`odd_unit.py`) + +- **C1 [P, C].** For a 2×2 contract, t = bc/det and 1 + t = ad/det are invariant under both diagonal gauges. + t = −1 exactly when a diagonal entry is zero. +- **C2 [P, C].** M45 = [[1, −q], [1/q, 1]] is the B-port contract. + - The factorisation is M45 = U_q + L_q − I, while H = L_q·U_q. + - Its invariants are o = 2, R² = −I and det = 2. + - diag(1, ½)·M45 = HOST(−1, ½), so t = −½ on a ρ = 2 caller. The factor 2 costs one free SCALE. + - H·M45⁻¹ has o = 1: turning M45 into t = −1 costs the park, as a caller op. +- **C3 (b-family) [P algebra, C-lane words].** The merged window word reaches X = x − y, Y = x + b·y exactly for + every b ∉ {0, −1}, using window scalars only (t = −1/(1 + b)). t = −1 is the limit b → 0, where one scalar + (1 + b)/b has a simple pole. This is Fable-assisted analysis, reproduced by our lanes. +- **C4 [P, root callers].** ρ = 1 forces t = −1 at every stage. M45 therefore needs ≥ 1 q-odd op per A port per + call, i.e. c ≥ 1 against the break-even 0.214 [C-param]. Non-root callers are not covered. + +### I.3 No-cloning lemmas (`walls.py`, `cuts.py`) + +| lemma | content | tag | +|---|---|---| +| Rank lemma | No event raises the full-state rank (public + live owned rows). An invertible endpoint therefore keeps the rank at n_pub throughout. A dirty CLEAR is lossless iff its content is in the span of the rest | [P, C toy] | +| Lock Lemma | After leaving {0}, every content's {0}-part lies in the span of the departure contents. Only a moved owned row snapshotted at {0} adds a direction | [P] | +| Clone lemma | The park needs a clone of the Y main's own departure content m, and only moved owned rows clone. Fable-assisted analysis, which our CLONEAUDIT lane reproduced and strengthened to the premise-free Rank lemma | [P, C toy] | +| Theorem W | Separate twins wired before/after the native need ≥ 96 moved owned rows (Y = x order), or leave a deficit ≥ 1 per A port (other order) | [P, C toy] | +| Lemma NT | New public carriers that old rows never read add 0 usable rank at every frame | [P] | +| Lemma AS / VA | At a corrected frame, everything held is in the span of the arrivals. Unmoved owned rows change *when* registers exchange, never *where* they meet | [P] | +| Lift law | An exact top delivery of x_t needs an **ascending** owned MOVE. Descending decoder rows and unmoved rows cannot make it | [P, C toy] | +| Freeze Lemma | Under no imports, the span at q_t^⊥ equals its arrival span, so time differences deliver nothing | [P] | +| Shared-lift theorem | One crossing MOVE serves only pairwise-orthogonal ports (≤ 8 on P104). m MOVEs cannot serve m + 1 pairwise non-orthogonal ports | [P, C] | +| Commutation Theorem | Same-frame ops act on the field side, and all walls above are token-side. Every wall therefore holds for any enlarged same-frame op set, and label-changing primitives cost ≥ 1 unit per port per call | [P, C toy] | +| XRECALL lemma | Every frame holding x_b contains ⟨q_b⟩, and ⟨q_b⟩ ⊄ q_b^⊥ because q·q = 1 | [P, C] | +| Zone lemma | Two non-chainable receivers cannot be served from a single sender's rank-1 rows, however many helpers relay | [P, C toy] | +| Owned additivity | Owned delivered rank adds across instances, siblings and calls: c ≥ 0.92 per port per call under any sharing | [P] | +| Wiring lemma | Separately wired twins need one extra independent vector per A port at V | [P] | +| **Cut Lemma** (WEBS) | For any up-set G of frames: rank(O mod Π) ≥ def(G) = dim(F + Π) − dim F, for **any helper web**. Here Π is the public vectors entering G, O the owned contents crossing into G, and F the finals in G | [P, C] | + +**Cut Lemma validation [C `cuts.py`].** + +- **W6805 (t = 0).** This is CubeJerry's #6805 word: def(G_s) = 0 on 104/104 ports, 0 owned crossings, and the + lemma holds on 104/104. +- **feeder6805 (t = −1, exact).** def = 1 on 104/104, exactly one owned crossing (its feeder) into each G_s, and + the lemma holds on 104/104. + +**Cut Lemma corollaries [P].** + +- **C1.** Every t = −1 port needs an owned ascent that leaves its Y-end hyperplane upward. +- **C2.** If all owned rows descend apart from line feeders {0} → ⟨q_t⟩, then M ≥ 104 and S ≤ 712, for any web and + any schedule. +- **C3 (dual law).** With no owned crossing into {≥ f}, X_s is U-complete at f. +- **C4.** M ≥ |F| + α(R), where F is the set of line feeders, R the unfed ports and α the maximum pairwise-odd + subset; α(P104) = 8. + +**Status of the WEBS sharing question.** + +- **Not proved.** Whether one owned ascent can be shared between ports is open. The conjecture M ≥ n at t = −1 is + [S]. +- **What the cuts allow.** Up-set cuts alone allow climb 3 for n = 4 on F2³ (13 sets). +- **What the search found.** None of those sets was realised in the numeric search, while its controls were exact + [N]. +- **In progress.** A lane (TOY4) is deciding the F2³ case exactly. Nothing from it is claimed here. + +### I.4 Decoder-wall pieces since #7583 + +| statement | tag | +|---|---| +| **Lemma A(acyc).** If a decoder's nonzero odd cells on T form an acyclic digraph, every rank certificate gives \|T\| ≤ Σ rank Z[D_k ∩ T, S_k ∩ T]. Certificates are therefore blind to "upper" junk, and C ≥ 52 by certificates needs "no acyclic decoder ≤ 51" | [P] | +| **Lemma B (mod-4 certificates).** For half-integer rows, n ≤ Σ s2(Z[D_k, S_k]) for any integer Z with odd diagonal. The sampled-closure LP gives λ ≥ 2.768, against the 2.039 needed | [P; C-lane] | +| **HALF18 (correction, see below).** Exact certificates of rank **15** on the 120 E8 lines (15 orthogonal 8-frames) and **13** on the 104 P104 ports. The full flag has slack, and intermediate flags bind (sampled LP λ ≥ 2.62) | [C] | +| **Early-set cap (EARLYCAP A).** \|E\| ≤ 5,408 − 43,264/(d + 8). That is ≤ 540.8 cells per contamination rank at d = 2, below the 577 needed. d = 1 (577–600) is open | [P, C arithmetic] | +| **UFLOOR duality.** Duality preserves job type (U ↦ U, L ↦ L, ascents ↦ ascents). The crossing U* = 7,126.97 D0/call is where the park family ties #7546 | [P; C-param] | +| **ACYCDEC.** Cleaning acyclic junk with extra rows turns decoder + cleaner into an exact decoder, so the saving is never positive. Small frames and subsets of 6–14 ports cost exactly n both ways | [P scoped; C-lane] | +| **Pure E8-world rows cost ≥ 56** even when acyclic (frame-partition Z of rank 13 + #7583's rigidity) | [P] | + +### I.5 Local re-solve on a fixed schedule (`onerank.py`) + +| statement | tag | +|---|---| +| **Theorem F.** With one right-hand side, rank[A \| b] − rank A ∈ {0, 1}. So "every drop misses by exactly one rank" means only "infeasible" (**correction**, see below) | [P, C] | +| **Lemma LIN.** Corrections through drop-dirty wires are exactly linear | [P] | +| **Lemma TR.** A one-block re-solve on interval (t, F, Π) works iff N_t is supported on Π × Π | [P] | +| **Lemma 2B.** A two-block re-solve is linear after eliminating one block, plus an invertibility condition | [P] | +| **Descent Lemma.** The law holds at every local minimum and gives no lower bound. Toy: 4 rigid stays against an optimum of 0, unbounded with copies | [P, C] | +| **Rigidity is schedule-driven.** Random coefficients on the same schedule repair 0/161 drops | [C-lane] | +| **Lemma RT.** A main's route costs exactly what a helper doing it costs (κ identical), so "mains fixed" carries no price | [P, C words.py] | + +--- + +## Part II. Negative results by route + +Each row gives what was tried, its exact scope, the reason it fails and the numbers. + +- "Built" prices use the measured U layer of today's words, 10,730 D0/call. +- Break-even for one-plane t = −1 is c* = 0.214 owned units per A port per call, or 0.075 for the all-B + variant [C-param]. + +### II.1 t = −1 native constructions + +| route | scope | why it fails | numbers | tag | +|---|---|---|---|---| +| YCHAN: twin y-channel | twins separate, wired before/after #7546's native, any helpers, free unmoved owned rows | Theorem W (token lock) | 1 moved owned row/A port → S = −112, no crossing. A free channel would give 1.1810× | [P, C toy, C-param] | +| FUSET1: fuse U and L jobs in one plane | twin identification preserving per-register op order/frames | Y side: 0/96 ports admit U reads below a zero-change park point. X side: 0/96 admit L/U order. Wiring lemma | ceiling 1.1810× needs a token-free y-channel ≤ 39 D0/A port | [P, C-lane] | +| BYPASS: merged twins + time-difference corrections | corrections from frame memory at each read | Lemma AS: a read is correctable iff its state is in the span of the arrivals. Full merge 1,806/2,260 uncorrectable (96/96 ports). Controls: unmerged #7546 2,260/2,260 pass | it would price 1.3014× if it worked | [P, C-lane] | +| MERGEBUILD: inserted-stop carriers | carriers that leave #7546's contents fixed | 931/933 missing directions not coverable. Lemma NT: new carriers add 0 | floor 933 dirs = 1,293 D0/call (< 5,652 slack), but no carrier class | [P, C-lane] | +| INNERWIRE / TOPL / TOPL2 / TOPLBUILD: merge Y2 into live Y_t, rebuilt top-L layer | PLN rules (X unwritten until donation) | Lift law: D ≥ 1 per merged port unless an ascending owned row is used. One lift/port → S = −160 | TOPL2 estimated ≈ 8.0k D0 against an 11.0k gate before the lift law closed it | [P, C toy] | +| LIFTTD: shared or unmoved lifts | no imports into q_t^⊥ | Freeze Lemma. Shared-lift theorem (≤ 8 ports per lift). 12 one-unit MOVEs → 0.9837× | | [P, C] | +| GRAMLIFT: E8 Gram lift with 8 MOVEs | Y-side algebra exact | No frame-legal design on A3. V side: Theorem M rank Ψ = 6 → D ≥ 6 on A3, D ≥ 104 − m_o on E8 | | [P, C-lane] | +| YEND: {0}-born helper carrying y to the Y end | merged window | No register visits both X-birth and Y-end (8/8). Y = x needs a dependence inside the invertible {0} basis | D_V = 1/port | [P, C-lane] | +| XRECALL: recall x_b from other ports' registers | public moves | XRECALL lemma: 0/96 sites without moved owned rows | | [P, C] | +| COURIER (outside-session lane, DreamingOfClouds'): Y couriers zeroed after delivery | real P104 frames | Only isolated 2-cycles. Induced matching ≤ 4 pairs → ≤ 8 couriers, each forcing an owned ascent. 0 with W6805's rows | S ≤ 848 with a free decoder; WEBS C4: M ≥ 100, S ≤ 780 | [P, C-lane] | +| YYMIX (outside-session lane, DreamingOfClouds') k = 2 staged Y–Y mixing → K2REAL with real carriers | cell model → real tokenized carriers | Carrier preloads must happen at {0}. 14 Y mains lose their preload carrier, and X_39 needs ≥ 7 owned rows | M_real ≥ 97, S ≤ 831, ≤ 0.914× (break-even M ≤ 92) | [P, C-lane, C-param] | +| YYMIX singular snapshot route (M = 0 in the cell model) | real tokens | CLONEAUDIT: the cell model's token-free carriers are 12 moved owned rows in disguise. A4 toy: snapshot CLEARs drop rank 20 → 16, and all Y wrong | artefact | [P, C toy] | +| MULTIHELP: multi-sender token-cancelling networks | 85/85 shared-sender pairs rank 2 | Zone lemma. 27 stuck antichains | M_real ≥ 91 (lower bound) against break-even 92 | [P, C-lane] | +| MULTIMIX: C = 0 range-sector fix for k = 2 | family E, W6805 L layer kept | The Y error has rank 8 and never vanishes for nonempty R. The fix needs ≥ 8 paid units | M ≥ 99 → ≤ 0.8955× | [P, C-lane] | +| WEBS: any helper web on MIX14 / COURIER / feeder designs | exact model | Cut Lemma corollaries C1, C2, C4 | W6805 family M ≥ 104 (S ≤ 712). MIX14 + any ascents M ≥ 96 (S ≤ 848). COURIER M ≥ 100 (S ≤ 780) | [P, C] | +| NEWMOVE: new primitives (priced descent, public clone, swaps, block transits, chart rotation mid-word) | linear, label-local up to rank-0 adapters | Commutation Theorem + transit floor (≥ P[1] per field) | ≥ 1 unit/port/call; global rotation is a no-op | [P, C toy] | +| BORDERCL: border/precision route (b → 0) | the repository's specification | The spec requires exact local maps. Its only approximation clause is analytic (06-transforms.tex l.214–224: error < √2·ℓ·2^−p, cost linear in p). Pole order 1 gives λ ≥ 2 on bad slots | cannot cost < 2,660 D0/call | [P from quoted text] | + +### II.2 Decoder (owned 56 per plane) + +| route | why it fails | tag | +|---|---|---| +| HANDT1: hand-built t = −1 decoder | UP + DOWN forced (I6). Late-L gathers at V cost +8/call (0.7933× built). The twin is the park family | [P, C] | +| DECZERO (outside-session lane, DreamingOfClouds'): zeroing / frame memory / mixing | Each alone is a relabel of the decoder. Zeroing + memory "free lifts" are new freedom (rank 2 per owned register) but cost ≥ 56 for rank-8 networks. Rank ≥ 9 is open | [P] | +| TWINDEC: shared decoder rows across planes | Live (DOWN) and hosted (UP) run opposite ways: C_joint = 112. Round-trip lemma | [P] | +| FACTORSWAP: alternative rank-8 factorisations | Exactly 10 decompositions on F0 ∪ F1 (8 at C = 56, 2 at 64). The C = 56 ones form one Aut orbit (order 384). The native mirror already maximises shared endpoint frames | [C-lane, S] | +| STAIRJUNK → STAIRBUILD → ASSEMBLYLB: staircase deposits | 0/96 interior flag frames exist in #7546. Staircases leave the write vectors per target unchanged (0/864 differ), so the assembly floor moves ≤ 43–146 D0 | [P, C-lane] | +| ACYCDEC / H9CERT: acyclic decoders below n | Sub-n acyclic hits are border-rank artefacts. Exact Gram decoders beat n only on large blocks (48–49 at n = 55) | [P scoped, C-lane] | +| XDEC: joint multi-call decoder | Rank ≥ 8k; joint ≥ 112 for k = 2 | [P, C] | +| ≥ 6 replacement rows (SIXROW), h = 9 wall | Still **open**. The missing union-rigidity lemma and the certificate obstruction (Lemma A, HALF18) are stated above | [open] | + +### II.3 Contract + +| route | why it fails | tag | +|---|---|---| +| CONTRACTX: bigger blocks, ring extensions | I1: the bill is rank Odd(M) for any size or ring | [P, C] | +| coupled ports, isotropic q_a + q_b | I5: the ledger is per grading; the isotropic kernel is even in both | [P, C] | +| SHAREDGRADING: two ports, one grading | 05-layers.tex l.4–7 and l.86–91: P_M permutes the whole array | [P from quoted text] | +| caller park Y_p += q·X_p | o = 1 per J → 17 odd units/port/word → S = −112 | [P, C-param] | +| DECZERO's mixed target T | o = 0 → the caller buys 34 odd units/port/word (≈ −3,264 S against ≈ 952 saved) | [P, C-param] | +| CALLER45: M45 at ρ = 1 | C4 (root callers) | [P] | + +### II.4 Parallel and multi-call + +| route | why it fails | tag | +|---|---|---| +| PARALLEL: amortised or batched parks, sibling sharing, direct sums | Owned additivity: c ≥ 0.92/port/call | [P] | +| KSLOT: k-slot coded multicast (a spec change) | On #7546: 2,727 of 3,427 interior stops are pure unicast, 251 merge-only, 449 branching (1,067 D0). Gain ≤ ~48 D0/call (~0.2%) at the toy gap 4.5%; passing needs ≥ 28% | [C-lane] | +| XDEC | Rank ≥ 8k | [P, C] | + +### II.5 Early-set and park family + +| route | why it fails | numbers | tag | +|---|---|---|---| +| TMLEVER: Theorem-M lever via co-read cancellation | needs ≥ 577–590 early cells per contamination rank to tie the park family; best E8 design 329 | ceiling 0.9301× at built U | [P, C-param] | +| EARLYCAP A | the cap above, for d ≥ 2 | | [P] | +| EARLYCAP B → T1CANCEL | the canceller is the owned L row copied into the σ relay, so it is the park family + 104 useless ADDs | 0.8681× built U, 1.3093× LP U | [C-lane, C-param] | +| UFLOOR | a U-only floor cannot close t = −1. The binding lever is the U-junk layer: built 10,730 against the crossing 7,127 | | [P, C-param] | + +### II.6 Merged twins and t = −½ + +| route | why it fails | numbers | tag | +|---|---|---|---| +| WINDOW8: merged 8-port window (shipped in Part III) | exact X = x − y, Y = x + y, but the park Y = x is impossible with shadows + token-only relays (x's birth frame is never inside the Y-end frame, 0/96) | 201.12 D0/call for the window route; owned fix ≈ 2,400 D0-eq against a gate of 471 | [P, C] | +| all-B single plane (t = −½, ρ = 2) | built 0.9773× (shadows 1,915 + relays 602 D0/call). Break-even shadows ≤ 14.41 D0/port | twins deleted 1.0950× | [C-param] | +| SHADOWCORE: cheaper shadows by editing | forced core 18.86 D0/port (min 15.79 > 14.4); no interior stop removable | | [C-lane] | +| MERGESCAN: per-port merge with cheaper relays | relays 6.279/port everywhere; best port 20.75 against break-even 20.69; A-type relay forced | 0 ports pass | [C-lane, P] | +| other ρ = 2 roots (t = −2, +1) | the invoice is t-invariant | | [C-lane] | + +### II.7 Local edits of #7546 (fixed operation graph) + +| route | result | tag | +|---|---|---| +| NETCOMPILE-W1 / REROUTE / ZEROSTOP / OWNRETIME: drop one stop or op and repair | 0/161, 0/332, 0/512, 0/101, 0/165 singles, 0/200 groups, 0 of 7,877 two-relay solves. By Theorem F these are plain infeasibility results | [C-lane] | +| ONERANK one- and two-block re-solves; MULTIBLOCK three-block | 0/161 invertible (2,815 corank-1 pairs only singular); 0 invertible in 13,540 triples | [P, C-lane] | +| MAINFUSE2: 2–4-op stop fusion and owned temporaries | 33 first-pass candidates all fail replay. One owned MOVE loses 1–7% | [C-lane] | +| SEEDBUILD: shared decoder partial sums S1–S6 | S1 built exactly; it costs +21.34 D0/call (κ ×0.99907); no stop removable (shipped in Part III) | [C] | +| OWNSCHED: re-schedule owned writes | write placement forced (Lemma F); best-case saving ≤ 380 D0/call against a 500 gate | [P, C-lane] | +| GEOFLOOR: d-geodesic helper paths | all 1,101 helpers have S ⊊ T, so every zero-loss path climbs; 0/332 meetings relocatable lower | [P, C-lane] | +| BREAKER8: joint meeting relocation including mains | 0/1,098 gains (loss concave in frame dimension). Lemma RT | [P, C] | +| TOKDEBT gate: is the one-rank miss token debt? | < 25% repaired (11.0% / 1.8% / 3.7%), so it is not. The rank-0 token-settled drops it found were shipped as #7601 | [C-lane] | +| CONTACTLB / JUNKLB: network floors | contact floor 145.6 D0, junk floor 313 forced stops = 433.9 D0/call (exact rational dual). Both ≈ 3% of the 13,974 D0/call network cost, so no plateau theorem | [C-lane] | + +--- + +## Part III. Words that did not pay (`words.py`, `data/`) + +- **Format.** Every word is shipped as an edit list against the vendored #7546 word, with a pinned canonical + SHA256 of the rebuilt word. +- **Replay.** Each is replayed exactly over the rationals, with legality checks. +- **Rows.** Its rows are compared with the stated targets. +- **Price.** It is priced by the 17-call invoice wherever κ is defined. + +| word | what it is | replay | price | +|---|---|---|---| +| #7546 (control) | ToikY's base word | legal, exact | S = 1424, κ 0.003648411294790845… (reproduced) | +| SEEDBUILD S1 | one decoder partial sum at a dim-2 join, serving 25–27 Y ports | legal; all 1,503 rows = #7546 (new helpers end at identity) | +21.3448 D0/call, κ 0.003645014837609… (×0.999069) | +| BREAKER8 relocation control | one 12-register meeting moved from dim 4 to dim 7 | legal; rows = #7546 | +16.8184 D0/call, κ 0.003645741005801… (×0.999268) | +| BREAKER8 Lemma RT swap | a main's route moved onto a new helper plus one main jump | legal; rows = #7546 | κ identical to #7546 | +| WINDOW8 w4_w00 | merged twins on the HALF18 8-frame window {20, 28, 69, 31, 38, 40, 48, 46}, shadow carriers + 2 token-only relays per port | legal; all 1,517 finals exact; X = x − y, Y = x + y on 8/8 ports; only 16 rows differ from #7546 | lane cost model: shadows 150.8892 + relays 16 × 3.1395 = 201.1210 D0/call. No κ (merged plane) | + +**Note on the WINDOW8 cost.** + +- **What 201.12 is.** It is the lane's route loss, against a design whose twins are deleted. +- **The census delta is smaller.** A plain census delta against #7546, with twins counted as mains, is 50.23 D0/call. +- **They are different questions.** The README quotes 201.12 only for the route comparison of II.6. + +**Cut Lemma words (`cuts.py`).** + +- W6805 is CubeJerry's #6805 word, vendored as data. +- feeder6805 is a t = −1 feeder word built by an outside-session lane (Fable-assisted, DreamingOfClouds'). It is shipped as an + edit list against W6805. + +**Not included, because the design was not replayed exactly as a word:** + +- the YYMIX/K2REAL k = 2 cell-model designs (cell model only); +- the COURIER designs; +- the HANDT1 twin decoder (its algebra is checked in `e8laws.py`); +- the TOKDEBT tier-A attempts (none built: no repair, or strict settlement ranks 1/1/54); +- the b-family variants of WINDOW8 (exact in our lane, not re-shipped); +- the MERGESCAN singleton merges. + +--- + +## Corrections of our own earlier statements + +1. **The "one-rank law" is a tautology.** Our NETCOMPILE, SEEDBUILD, TOKDEBT and OWNRETIME notes reported that + every drop "misses by exactly one rank". We read structure into it (the "contact-minimality conjecture"). By + Theorem F the count is only infeasibility. The underlying rigidity is schedule-driven and has no lower bound + (Descent Lemma). +2. **HALF18 (already posted as a comment on #7583).** The HALFWALL notes behind #7583 said a full-flag certificate + on E8 has minimum rank ≈ 18 = 2h. That numerical search failed its positive control. Exact frame certificates of rank + 15 (E8-120) and 13 (P104) exist (`e8laws.py`); the exact lower bound we check is 8, so the P104 minimum lies in + [8, 13]. The open question C ≥ 52 is unchanged in status; #7583's proved bounds are + unaffected. +3. **Duality.** Internal notes treated U builds as duals of L builds ("asc56 = dual of desc56"). Duality preserves + job type (UFLOOR). No public PR used this. +4. **EARLYCAP part B** ("a diagonal canceller makes early sets free") is refuted by T1CANCEL. It was never public. +5. **BYPASS relaxed screens** (0 failures, then 867) were optimistic. Only the non-descendant test (1,806/2,260 + failures) is sound. +6. **BREAKER8 control word.** The saved control `ctrl_up` is a costly relocation (×0.999268), not the Lemma RT + swap. The RT swap words are shipped separately. + +## Credits + +- **Authors.** DreamingOfClouds with Claude Opus 5.5 (Anthropic), via Claude Code. This includes the + outside-session lanes DECZERO, COURIER, YYMIX, XBIRTH and WEBS, which are DreamingOfClouds'. +- **Fable-assisted analysis.** The Clone lemma, the b-family and the identification of M45 as the B-port + contract. We reproduced each independently (CLONEAUDIT, CALLER45, MERGESCAN). +- **ToikY.** The #7546 base word. +- **CubeJerry.** The #6805 word, used as data in `cuts.py`. +- **SYLforge (#7603), FanPUYen (#7604) and aliromman (#7605).** The current frontier, referenced only. +- **Rohan Arun.** The #7113 signed caller and its B pair. +- **PR968 authors.** The P104 decoder file. +- **Conventions.** Clear1nsight and the P104 price and replay lineage. + +## Open next questions + +1. Can one owned ascent be shared between t = −1 ports (WEBS)? The cuts allow it, and no realisation is known. An + exact F2³ decision is in progress. +2. The d = 1 early-set window (577–600 cells per contamination rank at the LP-perfect U layer). +3. ≥ 6 replacement rows and the h = 9 wall (C ≥ 52): either an acyclic decoder ≤ 51 or a certificate that uses + intermediate flags. +4. A rank ≥ 9 "free-lift" decoder network below 56 (DECZERO). +5. Whether a non-root caller with ρ = 1 can consume M45 with three odd ops in total. diff --git a/research/p104-odd-unit-per-grading/SOURCES.json b/research/p104-odd-unit-per-grading/SOURCES.json new file mode 100644 index 0000000000..6a4fed7b67 --- /dev/null +++ b/research/p104-odd-unit-per-grading/SOURCES.json @@ -0,0 +1,30 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/complex-frame-pair-decoders/inputs/pr717/P104_HIT_flip_3a.txt", + "usage": "input", + "git_blob": "458ddb13dcf73ed031ffb96d9df149c994c7e4ee", + "sha256": "8e0178db02c14e1b29058cdbdbd50aac22f2b55a1ba21dc82f417610c9932526" + }, + { + "path": "upstream/build/sections/05-layers.tex", + "usage": "provenance", + "git_blob": "5ce8b3c83c455f221bb84858a97230b0285644aa", + "sha256": "20cfc8d12099d4e4ed9e3e7eeb6162edd9b6e0e076f24693364cd24377252594" + }, + { + "path": "upstream/build/sections/06-transforms.tex", + "usage": "provenance", + "git_blob": "de073e9292d58573f7065a3cd4f214e0d05f3444", + "sha256": "924316e4bc905066281d8f9e8746a49d8829aeb393688608deb1e61c3c87853c" + } + ] +} diff --git a/research/p104-odd-unit-per-grading/TASK.json b/research/p104-odd-unit-per-grading/TASK.json new file mode 100644 index 0000000000..aeb046e348 --- /dev/null +++ b/research/p104-odd-unit-per-grading/TASK.json @@ -0,0 +1,135 @@ +{ + "schema_version": 1, + "task_id": "p104-side-correction", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "p104-side-correction", + "question": "Can joint helper bases and a legal causal split improve the complete P104 productive/paid invoice?", + "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", + "research/p104-helper-subspace-splits/README.md", + "research/dyadic-helper-channel-capacity/README.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": "An exact arbitrary-input identity, source/target frame availability and restoration at the chosen cut, plus the complete channel+correction+idle/hosting bill or an explicit favorable bound. The native channel alone is not a supplier. A scoped local result may be retained without a complete supplier. Expanding it into further construction rounds requires the family-level budget and obligation gate in research-family-status.md; an optimistic passing relaxation alone is not acceptance.", + "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": "Start with the selected #5599 emitted word and review pending #5718 distinct input/output bases plus #5717/#5719 coverage before claiming work. Pick one uncovered source word, helper group and cut region. Prove the arbitrary-input relation and legal entry/exit corrections, then compare full target and paid profiles. Reject if completion, owned lifetimes or consumer costs repay the gain. A static pairing rank alone is not a physical split.", + "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": [ + "P104", + "helper basis", + "helper split", + "5718", + "dyadic capacity" + ], + "existing_checks": [ + { + "scope": "PR #4133: literal-slot defect", + "evidence": "research/p104-literal-slot-defect/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "88666f1dee93fbd85b31fd5d6f91a219e111b5f4", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4136: uniform commutation gap", + "evidence": "research/p104-uniform-commutation-gap/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "281ce601a8be9db470de630759179c23e1dfaa88", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4140: uniform encoding gap", + "evidence": "research/p104-uniform-encoding-gap/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "de25c6525aa866962309df5d107b32d55e6e5628", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4153: source-chart shortcut exhausts its optimistic allowance", + "evidence": "research/p104-source-chart-shortcut/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "9123241fea53df77e51ffe30d9aca1625d4bf3a8", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4154: fiber-tag seam mismatch", + "evidence": "research/p104-fiber-tag-seam/README.md", + "remaining": "Independently validate the stated scope or change its producer/consumer premise and pay the complete boundary.", + "status": "author-checked", + "source_commit": "4ffcdaee5d6255a9cea1fe53a5424435068089d0", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "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": "One day of P104 research (Nov 14) on the decoder wall and the t = -1 park, organised around one cost, the odd unit paid per grading sigma_p: (I) proved lemmas with exact checks - o(N) = rank Odd(N) for any block/ring/coupling, the Cayley form (t = -1 iff the sigma-even part is singular), per-grading ledgers, t_eff = ab/(cd-ab) and M45 as the t = -1/2 B-port contract, the no-cloning family (Rank, Lock, Clone, Theorem W, NT, AS/VA, lift law, Freeze, shared lift <= 8, Commutation, XRECALL, Zone, owned additivity, wiring, the web-general Cut Lemma), decoder structure (UP+DOWN forced, G/2 = 13 proj, -12 I composition, joint rank >= 8k), decoder-wall pieces since #7583 (Lemma A(acyc), Lemma B mod-4, HALF18 rank-15/13 certificates, early-set cap), and local re-solve laws (Theorem F, LIN, TR, 2B, Descent, RT); (II) every route closed that day as a scoped negative result with its reason and numbers; (III) the words built that did not pay, replayed exactly against #7546 with their prices.", + "scope_change_reason": "The card asks for a constructive helper-basis or causal-split improvement. This package instead records lower bounds, scoped negative results and unpaid words on P104 so that others can see which decoder, t = -1, contract, multi-call and local-edit routes are closed and why; it makes no kappa claim and ships no new frontier word.", + "bottleneck_link": "The P104 invoice's owned decoder mass (56 per plane) and the t = -1 park are the two fixed costs every proposed redesign has hit; this package shows they are one cost (the odd unit per grading) and that every construction tested pays about one owned unit per port per call, against a break-even near 0.214.", + "budget_minutes": 240, + "stop_rule": "Every proved claim has a proof in PROOF.md; every finite fact quoted as [C] is re-run by a standard-library checker with positive and negative controls; lane-only numbers are tagged [C-lane] or [C-param]; open items stated as open; validator PASS.", + "outcome": "negative-result", + "evidence": "README.md, PROOF.md, odd_unit.py, e8laws.py, walls.py, onerank.py, cuts.py, words.py, data/, VERIFY.json.", + "author": "DreamingOfClouds", + "ai_assistance": "Claude Opus 5.5 (Anthropic), via Claude Code; some analysis Fable-assisted, reproduced independently (see README credits).", + "open_questions": [ + { + "question": "Can one owned ascent serve several t = -1 ports (is M >= n at t = -1)?", + "why_it_matters": "Up-set cuts allow sharing; if sharing is impossible every one-plane t = -1 design on P104 has M >= 104 (S <= 712) and the t = -1 route is closed in the exact model.", + "first_step": "Decide the F2^3, n = 4 case (labels 1, 2, 4, 7) exactly for the 13 cut-feasible climb-3 owned sets.", + "blocked_by": "Nothing." + }, + { + "question": "Is there an early set with contamination rank d = 1 and 577-600 cells?", + "why_it_matters": "It is the only window the early-set cap leaves open for the Theorem-M lever at the LP-perfect U layer.", + "first_step": "Use the proportional-class structure forced at d = 1 (bicliques T x S) to bound |E| below 577.", + "blocked_by": "Nothing." + }, + { + "question": "Is C >= 52 on P104 (the h = 9 wall), and do >= 6 replacement rows always cost >= 28?", + "why_it_matters": "These are the remaining decoder-side savings (at most 4 owned units per plane).", + "first_step": "Either build an acyclic decoder of cost <= 51 (Lemma A) or find a certificate that uses intermediate flags; for six rows prove the union-rigidity lemma of #7583.", + "blocked_by": "Nothing." + }, + { + "question": "Can a rank >= 9 free-lift decoder network (zeroing + frame memory) cost below 56?", + "why_it_matters": "It is the only decoder freedom found that is not a relabel of the row model.", + "first_step": "Search rank-9 lift networks on E7/E6 toys with exact pricing.", + "blocked_by": "Nothing." + } + ] +} diff --git a/research/p104-odd-unit-per-grading/VERIFY.json b/research/p104-odd-unit-per-grading/VERIFY.json new file mode 100644 index 0000000000..9330561aae --- /dev/null +++ b/research/p104-odd-unit-per-grading/VERIFY.json @@ -0,0 +1,71 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/complex-frame-pair-decoders/inputs/pr717/P104_HIT_flip_3a.txt" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/odd_unit.py" + ], + "timeout_seconds": 60, + "checks": "Part I.1-I.2, exact over Q at generic rational points: I1 o(N) = rank Odd(N) on 40/40 random coupled 2-4x4 matrices in both gradings; I2 dim ker(R+I) = dim ker E on 40/40 (17 with singular E) plus the three park cases; I3 per-port det R = 1, det(R+I) = -4cd/(ab-cd), t_eff = ab/(cd-ab), t_eff = -1 iff cd = 0 on 300 points, HOST t_eff = alpha*beta; I4 coupled singular pencil (det E_a = 0, det E_0 = 1, o_a = o_b = 2); I5 isotropic kernel o_a = o_b = 0, monomial q_a q_b o = 1,1; I6 q-free coupling keeps m_a = 2; I7 M45 = U+L-I, H = LU, o = 2, R^2 = -I, M^2 = 2J, M^4 = -4I, det 2, diag(1,1/2)M45 = HOST(-1,1/2), t_eff = -1/2, o(H M45^-1) = 1; I8 dressing invariance on 200 cases, control q-odd dressing changes tr R on 165/200; I9 b-family t = -1/(1+b), gauge invariance, window-scalar pole. Prints PASS_ODD_UNIT_PER_GRADING." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/e8laws.py" + ], + "timeout_seconds": 120, + "checks": "Exact (Bareiss over Z, stdlib). Data hashes; 120-line E8 Gram (rank 8, G^2 = 30G) and the 104-port block equal to the pinned PR968 Gram on all 104^2 entries. HANDT1: diagonal odd, 5,720 odd cells all G = 0, 4,992 even cells G = +-1, G104^2 = 26 G104 (control 30G fails), G/26 idempotent of trace 8, transposed-twin L rows frame-legal (swapped frames illegal), M_L = G/2, W^T U = 13 I, composition residue -12 on the diagonal and 0 on all 5,720 odd cells, 1,360 cells hit by a single same-index term; XRECALL q.q = 1 (control: even vector inside its perp); max pairwise-orthogonal set and non-orthogonal clique number 8 on 104 and on the 96 A ports; XDEC copies give identity blocks of rank 16 and 24; HALF18 frame certificates rank 15 on E8-120 and 13 on P104 (partitions, zero on even cells, nonzero diagonal), lower bound 8; EARLYCAP rank(2I+C_F) <= d+8 and the |E| cap table, T1CANCEL res = 0 on two E8 matchings; BYPASS rank_K{e_t : t in A} = 95; FACTORSWAP 10 decompositions (8 at 56, 2 at 64); Lemma A sums (104 for the frame Z, control with invalid Z). Prints PASS_E8_LAWS." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/walls.py" + ], + "timeout_seconds": 300, + "checks": "Exact toys: Rank lemma (A4 real-token snapshot CLEARs drop rank 20 -> 16, final map singular 16/20; token-free owned carriers invertible; undelivered-carrier, held-copy CLEAR and public-swap controls; 250 random legal programs, 0 rank increases, dirty-CLEAR lossless-iff-in-span 0 violations); Lock/Theorem W (free wiring min D = n at n = 1, 2 in both orders, D = 0 with n owned ascents); Commutation Theorem (0/300 Lock violations with arbitrary local maps, cross-label control 47/300; chart rotation 59/59, 944/944); lift law (PLN variants top-solvable 0/216 A3, 0/360 A4 with D = 1; controls D = 0 exact); Zone lemma (two senders exact with 0 owned, one sender fails, proportional weights singular); Gram lift rank Psi = 6 on A3. Prints PASS_WALL_TOYS." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/onerank.py" + ], + "timeout_seconds": 60, + "checks": "Exact: Theorem F (rank[A|b] - rank A in {0,1} on 3,000 random matrices, solution or left witness in each case; two-column control misses by 2); Lemma LIN (formula exact on 947/947 circuits meeting the hypothesis, fails on 528/553 that do not); Lemma TR criterion matches on 400/400; T = I network with meetings M then M^-1 rigid at 4m single-stay drops for m = 1..4 against optimum 0, all repaired by Lemma TR, redundant-stay controls repairable. Prints PASS_ONERANK." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/cuts.py" + ], + "timeout_seconds": 240, + "checks": "Vendored W6805 bytes (CubeJerry #6805 word, sha256 pinned, data only); feeder6805 rebuilt from W6805 + edit list (pinned sha256); exact replay of both; Cut Lemma with exact ranks mod 1000000007 and 998244353 (must agree) on all 104 ports: W6805 def(G_s) = 0 on 104/104 with 0 owned crossings (24 owned moves all descend), feeder6805 def(G_s) = 1 on 104/104 with exactly one owned crossing each, lemma holds 104/104; control: feeder with crossings dropped flagged on 104/104, W6805 not flagged; alpha(P104) = 8 and alpha(MIX14 (b') R) = 6 by exhaustive branch and bound. Prints PASS_CUT_LEMMA." + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/words.py" + ], + "timeout_seconds": 400, + "checks": "Vendored #7546 word bytes (sha256 pinned); unpaid words rebuilt from #7546 + edit lists with pinned canonical sha256 (SEEDBUILD S1, BREAKER8 costly-relocation control ctrl_up, BREAKER8 Lemma RT swap words for mains 6 and 886, WINDOW8 w4_w00); exact Fraction replay and legality of each; S1 and ctrl_up rows equal #7546, 17-call invoice, kappa 0.003645014837609... (S1, x0.99907, +21.3448 D0/call) and 0.003645741005801... (ctrl_up, x0.99927, +16.8184 D0/call), both below #7546's reproduced 0.003648411294790845...; both Lemma RT words: all rows equal #7546, S, D0 and kappa equal #7546's in every digit, no-swap-back control rejected; WINDOW8 all 1517 finals equal T, X = x-y, Y = x+y on 8 ports, T differs from #7546 on 16 rows only, cost model 150.8892 + 16 x 3.1395 = 201.1210 D0/call, no kappa (merged plane); controls (corrupted ADDs, tampered edit list, tampered targets, tampered invoice) rejected. Prints PASS_UNPAID_WORDS." + } + ] +} diff --git a/research/p104-odd-unit-per-grading/cuts.py b/research/p104-odd-unit-per-grading/cuts.py new file mode 100644 index 0000000000..d45b8e9986 --- /dev/null +++ b/research/p104-odd-unit-per-grading/cuts.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Cut Lemma check on two exact P104 words, plus the partner-graph numbers alpha(P104) = 8 and alpha(R) = 6. + +Standard library only, one file; run it as python3 -I -B cuts.py. + +Cut Lemma. Let G be an up-set of frames. PI = public vectors entering G (tokens of public registers born in G +and contents of public registers at their moves from outside G into G), O = contents of owned registers at their +moves from outside G into G, F = finals of the public registers that end in G. Then F <= span(PI + O) and +|PI| = |F|, hence rank(O mod PI) >= def(G) := rank(F + PI) - rank(F). +Here G_s = {frames containing the port label q_s}. Ranks are exact over Q, computed modulo the two primes +1000000007 and 998244353 (the two must agree). + +Words (data only, replayed here with the legality rules of words.py): + W6805 CubeJerry's #6805 word (data/W6805.json.gz, SHA256 of the file pinned below). Expected: def(G_s) = 0 on + 104/104 ports, no owned crossing (its 24 owned moves all descend), lemma holds 104/104. + feeder6805 our feeder variant, data/edits-feeder6805.json.gz applied to W6805 (520 inserted events, one more owned + field). Expected: def(G_s) = 1 on 104/104, exactly one owned crossing into each G_s, lemma holds 104/104. +Control: the feeder word with its owned crossings removed from O must be flagged on every port (rank(O mod PI) = 0 < def). +alpha(G) = largest set of ports whose labels are pairwise odd (q_s . q_t = 1 over F2); exhaustive branch and bound +with a greedy-colouring bound (the search is a proof of maximality), for all 104 labels and for MIX14 (b') R. +""" +import collections +import copy +import gzip +import hashlib +import json +import sys +import time +from fractions import Fraction as Q +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DATA = HERE / 'data' +W6805_SHA256 = '2b70b1c76f5bacc32c1dc8bf5b74db3b7b6496e2a5682092124ead9d4b90bbdc' +FEEDER_CANON_SHA256 = '8e426c532be89d569721854f213f75b3c598eb5262e8299609bf17d3e2ca8157' +PRIMES = (1000000007, 998244353) + + +def require(cond, label): + if not cond: + raise AssertionError(label) + + +# --------------------------------------------------------------------------------------------- word handling +def span(vectors): + s = {0} + for v in vectors: + require(type(v) is int and 0 < v < 512 and v not in s, 'frame vectors independent in F2^9') + s |= {x ^ v for x in s} + return frozenset(s) + + +def apply_edits(A, E): + require(len(A['program']) == E['base_events'], 'edit list base length') + out, pos = [], 0 + for i1, i2, evs in E['replace']: + require(pos <= i1 <= i2 <= len(A['program']), 'edit ranges ordered') + out.extend(A['program'][pos:i1]) + out.extend(evs) + pos = i2 + out.extend(A['program'][pos:]) + W = copy.deepcopy(A) + for key, h in E['header'].items(): + W[key] = h['value'] + W['program'] = out + return W + + +def replay(W): + """Exact replay with legality; returns rows of the public registers, the public and the owned MOVE records + (register, from chart, to chart, content at the move), and the frame spans.""" + n, N = W['public'], W['public'] + W['owned_fields'] + sp = [span(f) for f in W['frames']] + rows = [{r: Q(1)} if r < n else {} for r in range(N)] + cur = list(W['initial']) + [None] * W['owned_fields'] + alive = set() + pub_moves, own_moves = [], [] + for i, e in enumerate(W['program']): + op, r = e[0], e[1] + require(type(r) is int and 0 <= r < N, '%d register index' % i) + if op == 'MOVE': + a, b, flag = e[2], e[3], e[4] + require(type(flag) is bool and flag == (r >= n) and cur[r] == a, '%d MOVE flag / current chart' % i) + if r >= n: + require(r in alive and (sp[a] < sp[b] or sp[b] < sp[a]), '%d owned MOVE live and nested' % i) + own_moves.append((r, a, b, dict(rows[r]))) + else: + require(sp[a] < sp[b], '%d public MOVE strictly ascends' % i) + pub_moves.append((r, a, b, dict(rows[r]))) + cur[r] = b + elif op == 'INIT': + require(r >= n and r not in alive and len(e) == 3, '%d INIT of a dead owned field' % i) + alive.add(r); rows[r] = {}; cur[r] = e[2] + elif op == 'CLEAR': + require(r >= n and r in alive and (len(e) == 2 or cur[r] == e[2]), '%d CLEAR (a dirty CLEAR carries no chart)' % i) + alive.discard(r); rows[r] = {}; cur[r] = None + elif op == 'SCALE': + q = Q(e[2]) + require(q != 0 and cur[r] == e[3] and (r < n or r in alive), '%d SCALE' % i) + rows[r] = {k: v * q for k, v in rows[r].items()} + elif op in ('ADD', 'COPY'): + s, q, f = e[2], Q(e[3]), e[4] + require(type(s) is int and 0 <= s < N and s != r and q != 0, '%d operand' % i) + require(cur[r] == f and cur[s] == f, '%d ADD/COPY operands at chart %d' % (i, f)) + require(all(x < n or x in alive for x in (r, s)), '%d owned field live' % i) + if op == 'COPY': + require(not rows[r], '%d COPY into a zero field' % i) + R = rows[r] + for k, v in rows[s].items(): + nv = R.get(k, 0) + q * v + if nv: + R[k] = nv + else: + R.pop(k, None) + else: + raise AssertionError('%d unknown op %r' % (i, op)) + require(not alive, 'every owned field cleared') + require(cur[:n] == list(W['final']), 'public fields end at final charts') + return rows[:n], pub_moves, own_moves, sp + + +# --------------------------------------------------------------------------------------------- exact ranks mod p +class Basis: + """Incremental row-echelon basis over GF(p) of sparse vectors {column: Fraction}.""" + + def __init__(self, p): + self.p, self.piv = p, {} + + def reduce(self, v): + p = self.p + v = {k: (x.numerator % p) * pow(x.denominator % p, p - 2, p) % p for k, x in v.items()} + v = {k: x for k, x in v.items() if x} + while v: + k = min(v) + b = self.piv.get(k) + if b is None: + return k, v + c = v[k] + for j, y in b.items(): + nv = (v.get(j, 0) - c * y) % p + if nv: + v[j] = nv + else: + v.pop(j, None) + return None, None + + def add(self, v): + k, r = self.reduce(v) + if k is None: + return False + inv = pow(r[k], self.p - 2, self.p) + self.piv[k] = {j: x * inv % self.p for j, x in r.items()} + return True + + def copy(self): + b = Basis(self.p); b.piv = dict(self.piv) + return b + + def rank(self): + return len(self.piv) + + +def ranks(F, PI, O): + """(rank PI, rank F, rank F+PI, rank PI+O, rank F+PI+O), identical modulo both primes. + Vectors are fed shortest first, which keeps the elimination sparse.""" + seen = set() + key = lambda v: len(v) + F, PI, O = sorted(F, key=key), sorted(PI, key=key), sorted(O, key=key) + for p in PRIMES: + bF, bPI = Basis(p), Basis(p) + for v in F: + bF.add(v) + for v in PI: + bPI.add(v) + bFPI = bPI.copy() + for v in F: + bFPI.add(v) + bPO = bPI.copy() + for v in O: + bPO.add(v) + bAll = bFPI.copy() + for v in O: + bAll.add(v) + seen.add((bPI.rank(), bF.rank(), bFPI.rank(), bPO.rank(), bAll.rank())) + require(len(seen) == 1, 'ranks agree modulo both primes: %s' % sorted(seen)) + return seen.pop() + + +def cut_check(W): + """Run the Cut Lemma on every port. Returns per-port records (def, #owned crossings, rank PI, rank F, rank F+PI, + rank PI+O, rank F+PI+O), the number of non-ascending public moves (0, replay enforces it) and the owned + move directions.""" + n = W['public'] + fin, pub_moves, own_moves, sp = replay(W) + odir = collections.Counter('asc' if sp[a] < sp[b] else 'desc' for r, a, b, c in own_moves) + recs = [] + for q in W['ports']: + G = [q in s for s in sp] + PI = [{r: Q(1)} for r in range(n) if G[W['initial'][r]]] + PI += [c for r, a, b, c in pub_moves if not G[a] and G[b]] + O = [c for r, a, b, c in own_moves if not G[a] and G[b]] + F = [fin[r] for r in range(n) if G[W['final'][r]]] + require(len(PI) == len(F), '|PI| = |F| for port %d' % q) + rPI, rF, rFPI, rPO, rAll = ranks(F, PI, O) + recs.append((rFPI - rF, len(O), rPI, rF, rFPI, rPO, rAll)) + return recs, odir + + +def evaluate(recs, drop_owned=False): + """Lemma check per port: F <= span(PI + O) and rank(O mod PI) >= def. With drop_owned the owned crossings are + removed from O (control). Returns (violations, histogram (def, crossings, rank(O mod PI))).""" + bad, hist = 0, collections.Counter() + for dfc, nO, rPI, rF, rFPI, rPO, rAll in recs: + if drop_owned: + rPO, rAll, nO = rPI, rFPI, 0 + bad += not (rAll == rPO and rPO - rPI >= dfc) + hist[(dfc, nO, rPO - rPI)] += 1 + return bad, hist + + +# --------------------------------------------------------------------------------------------- alpha +def alpha(labels, subset=None): + """Largest set of indices (within `subset`) with pairwise odd labels (dot product 1 over F2), exhaustive + branch and bound (greedy-colouring bound); returns (size, example).""" + dot = lambda a, b: bin(a & b).count('1') & 1 + idx = list(range(len(labels))) if subset is None else list(subset) + adj = {s: {t for t in idx if t != s and dot(labels[s], labels[t])} for s in idx} + best = [0, []] + + def colour_bound(cand): + order, bound, left = [], {}, list(cand) + k = 0 + while left: + k += 1 + cls, rest = [], [] + for v in left: + if all(v not in adj[u] for u in cls): + cls.append(v) + else: + rest.append(v) + for v in cls: + order.append(v); bound[v] = k + left = rest + return order, bound + + def expand(cur, cand): + order, bound = colour_bound(cand) + for v in reversed(order): + if len(cur) + bound[v] <= best[0]: + return + nc = [u for u in cand if u in adj[v]] + if nc: + expand(cur + [v], nc) + elif len(cur) + 1 > best[0]: + best[0], best[1] = len(cur) + 1, cur + [v] + cand = [u for u in cand if u != v] + expand([], idx) + ex = best[1] + require(all(dot(labels[a], labels[b]) for a in ex for b in ex if a != b), 'example set pairwise odd') + return best[0], sorted(ex) + + +# --------------------------------------------------------------------------------------------- main +def main(): + t0 = time.time() + raw = (DATA / 'W6805.json.gz').read_bytes() + require(hashlib.sha256(raw).hexdigest() == W6805_SHA256, 'vendored W6805 bytes') + A = json.loads(gzip.decompress(raw)) + E = json.loads(gzip.decompress((DATA / 'edits-feeder6805.json.gz').read_bytes())) + Fd = apply_edits(A, E) + cs = hashlib.sha256(json.dumps(Fd, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + require(cs == FEEDER_CANON_SHA256, 'feeder6805 rebuilt sha256 ' + cs) + print('PASS feeder6805 = W6805 + %d replacement(s) (%d events -> %d, owned fields %d -> %d), sha256 %s...' + % (len(E['replace']), len(A['program']), len(Fd['program']), A['owned_fields'], Fd['owned_fields'], cs[:12])) + require(len(A['ports']) == 104 and A['ports'] == Fd['ports'], '104 port labels') + + for W, name, want in ((A, 'W6805', {(0, 0, 0): 104}), (Fd, 'feeder6805', {(1, 1, 1): 104})): + recs, odir = cut_check(W) + bad, hist = evaluate(recs) + require(bad == 0, '%s: lemma violations %d' % (name, bad)) + require(dict(hist) == want, '%s: (def, crossings, rank(O mod PI)) histogram %s' % (name, dict(hist))) + print('PASS %s: exact replay legal; owned moves %s; ports 104; lemma violations 0; histogram ' + '(def(G_s), owned crossings into G_s, rank(O mod PI)) = %s' % (name, dict(odir), dict(hist))) + if name == 'W6805': + require(dict(odir) == {'desc': 24}, 'W6805: 24 owned moves, all descending') + else: + bad, hist = evaluate(recs, drop_owned=True) + require(bad == 104, 'control: every port flagged') + print('PASS control: feeder6805 with the owned crossings dropped is flagged on %d/104 ports ' + '(def 1 not covered by rank(O mod PI) = 0): %s' % (bad, dict(hist))) + if name == 'W6805': + bad, hist = evaluate(recs, drop_owned=True) + require(bad == 0, 'control: W6805 has def 0 and no crossings, so the same drop flags nothing') + print('PASS control: W6805 (def 0, no owned crossings) is not flagged by the same drop') + + labels = A['ports'] + a_all, ex = alpha(labels) + require(a_all == 8, 'alpha(P104) = 8') + print('PASS alpha(P104) = %d (exhaustive branch and bound over the 104 labels); example port indices %s' + % (a_all, ex)) + M = json.loads((DATA / 'mix14-bprime-R.json').read_text()) + require(sorted(M['L']) == sorted(labels), 'MIX14 labels = word labels as a set') + a_R, exR = alpha(M['L'], M['R']) + require(a_R == 6, 'alpha(R) = 6') + print('PASS alpha(R) = %d for MIX14 (b\') R of %d ports (indices into the MIX14 label list); example %s' + % (a_R, len(M['R']), exR)) + print('runtime %.0f s' % (time.time() - t0)) + print('PASS_CUT_LEMMA') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/research/p104-odd-unit-per-grading/data/W6805.json.gz b/research/p104-odd-unit-per-grading/data/W6805.json.gz new file mode 100644 index 0000000000..aab930c07e Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/W6805.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/base-7546-word.json.gz b/research/p104-odd-unit-per-grading/data/base-7546-word.json.gz new file mode 100644 index 0000000000..d63f6b195e Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/base-7546-word.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-ctrl.json.gz b/research/p104-odd-unit-per-grading/data/edits-ctrl.json.gz new file mode 100644 index 0000000000..88a1df4783 Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-ctrl.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-feeder6805.json.gz b/research/p104-odd-unit-per-grading/data/edits-feeder6805.json.gz new file mode 100644 index 0000000000..681fe09800 Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-feeder6805.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-rt6.json.gz b/research/p104-odd-unit-per-grading/data/edits-rt6.json.gz new file mode 100644 index 0000000000..487c0a8072 Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-rt6.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-rt886.json.gz b/research/p104-odd-unit-per-grading/data/edits-rt886.json.gz new file mode 100644 index 0000000000..588b338d9a Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-rt886.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-s1.json.gz b/research/p104-odd-unit-per-grading/data/edits-s1.json.gz new file mode 100644 index 0000000000..0a5e87029a Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-s1.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/edits-win.json.gz b/research/p104-odd-unit-per-grading/data/edits-win.json.gz new file mode 100644 index 0000000000..d7ee525c4f Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/edits-win.json.gz differ diff --git a/research/p104-odd-unit-per-grading/data/half18_frames.json b/research/p104-odd-unit-per-grading/data/half18_frames.json new file mode 100644 index 0000000000..066b30fdbe --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/half18_frames.json @@ -0,0 +1 @@ +{"note":"HALF18 exact frame partitions (indices into lines120.json; first 104 = P104)","E8_120":[[0,16,29,45,52,79,101,103],[1,5,17,24,26,37,47,93],[2,10,23,30,60,85,96,118],[3,6,22,42,54,86,113,115],[4,8,20,31,44,51,87,107],[9,11,18,40,50,61,72,100],[12,34,48,67,76,92,105,119],[13,36,46,69,73,80,88,104],[14,25,39,56,66,71,81,94],[27,49,65,97,98,99,110,112],[35,38,43,62,83,89,95,108],[19,32,41,68,74,78,82,102],[21,53,58,64,70,91,106,117],[7,55,63,75,84,90,111,114],[15,28,33,57,59,77,109,116]],"P104":[[0,18,9,87,33,50,100,23],[1,8,13,92,34,57,26,99],[2,60,62,95,35,89,77,54],[3,10,32,42,96,58,83,21],[4,5,16,88,44,49,27,22],[11,55,64,90,97,80,98,74],[12,7,37,45,36,59,76,15],[20,28,69,31,38,40,48,46],[25,71,39,81,66,56,94,14],[41,30,68,51,72,19,84,78],[43,65,73,85,101,52,103,79],[53,29,75,91,102,86,6,63],[61,47,82,93,67,24,17,70]]} \ No newline at end of file diff --git a/research/p104-odd-unit-per-grading/data/invoice-7546.json b/research/p104-odd-unit-per-grading/data/invoice-7546.json new file mode 100644 index 0000000000..f496503472 --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/invoice-7546.json @@ -0,0 +1 @@ +{"schema": "integer-mult-recursive-invoice/v1", "contract": {"model": "mixed-target-unnormalized-power-v1", "rank_semantics": "H_r costs r^(1-C); debit surrendered productive fields", "ambient_rank": 145, "boundary": "complete signed #7113 caller application with 17 native calls"}, "paid": {"1": 68367, "2": 14484, "3": 14059, "4": 3791, "5": 5831, "6": 272, "7": 187, "8": 741, "9": 32, "16": 416, "24": 416, "32": 416, "40": 416, "48": 416, "56": 416, "64": 208}, "targets": {"1": 306, "2": 357, "3": 799, "4": 3825, "5": 1360, "6": 731, "7": 323, "8": 544, "9": 10888, "17": 416, "25": 416, "33": 416, "41": 416, "49": 416, "57": 416, "65": 416, "73": 208, "137": 208}} \ No newline at end of file diff --git a/research/p104-odd-unit-per-grading/data/iso968.json b/research/p104-odd-unit-per-grading/data/iso968.json new file mode 100644 index 0000000000..4d1ce7948a --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/iso968.json @@ -0,0 +1 @@ +{"eps":[1,1,-1,-1,1,1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,1],"perm":[2,8,58,64,102,68,69,47,7,65,52,74,78,20,24,59,60,99,79,73,53,21,42,43,103,91,70,37,28,101,85,86,15,35,26,82,19,98,31,89,13,32,41,90,57,76,22,72,0,56,75,51,3,46,71,67,1,50,4,81,55,23,5,61,80,54,9,49,77,45,6,66,10,48,93,39,87,97,11,44,92,38,16,100,83,34,14,63,36,30,95,40,88,33,12,29,94,17,25,84,62,96,27,18]} diff --git a/research/p104-odd-unit-per-grading/data/lines120.json b/research/p104-odd-unit-per-grading/data/lines120.json new file mode 100644 index 0000000000..5f455d1458 --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/lines120.json @@ -0,0 +1 @@ +{"labels":[11,19,35,131,259,13,21,37,69,133,261,41,73,265,49,145,161,193,321,385,14,22,38,70,134,26,74,138,50,146,274,194,322,386,28,44,140,84,148,276,100,292,196,324,388,56,88,152,168,296,200,328,392,112,176,304,208,336,400,224,352,416,508,506,502,494,478,446,382,254,505,501,493,477,445,381,253,499,475,443,379,251,487,471,439,375,247,463,431,367,239,415,351,223,319,191,81,98,164,262,268,273,280,290,42,266,25,137,7,67,448,104,76,82,162,97,289,127,52,491],"gram":[[2,-1,-1,1,1,-1,0,0,0,0,0,1,-1,-1,0,0,0,0,0,0,-1,0,0,0,0,-1,1,1,0,0,0,0,0,0,0,0,0,-1,-1,-1,1,1,1,-1,1,0,0,0,0,0,0,0,0,-1,1,1,1,1,1,1,1,-1,0,1,0,1,1,1,-1,1,1,0,-1,-1,-1,-1,1,1,0,0,0,0,1,1,-1,1,-1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,-1,-1,1,1,-1,1,1,0,0,0,0,0,0,0,1,0],[-1,2,1,-1,-1,0,1,0,0,0,0,0,0,0,-1,1,0,0,0,0,0,-1,0,0,0,1,0,0,-1,1,-1,0,0,0,0,1,-1,0,0,0,-1,-1,-1,1,-1,0,0,0,-1,-1,1,1,1,0,0,0,0,0,0,-1,-1,1,0,-1,-1,0,-1,-1,1,-1,-1,1,0,1,1,1,-1,0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1,0,0,0,0,1,0,-1,0,0,0,0,1,0,1,0,0,0,0,1,-1,1,-1,1,-1,0,0,0,0,-1,-1,-1,-1,0,0,0,0,0,-1,0,1,-1,-1,-1,1,0,0,0,1,0,1,0,0,0,1,-1,0,0,0,0,0,2]]} \ No newline at end of file diff --git a/research/p104-odd-unit-per-grading/data/mix14-bprime-R.json b/research/p104-odd-unit-per-grading/data/mix14-bprime-R.json new file mode 100644 index 0000000000..37969c1f7d --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/mix14-bprime-R.json @@ -0,0 +1 @@ +{"R": [1, 5, 14, 17, 34, 56, 65, 73, 76, 77, 93, 94, 101, 103], "L": [11, 19, 35, 131, 259, 13, 21, 37, 69, 133, 261, 41, 73, 265, 49, 145, 161, 193, 321, 385, 14, 22, 38, 70, 134, 26, 74, 138, 50, 146, 274, 194, 322, 386, 28, 44, 140, 84, 148, 276, 100, 292, 196, 324, 388, 56, 88, 152, 168, 296, 200, 328, 392, 112, 176, 304, 208, 336, 400, 224, 352, 416, 508, 506, 502, 494, 478, 446, 382, 254, 505, 501, 493, 477, 445, 381, 253, 499, 475, 443, 379, 251, 487, 471, 439, 375, 247, 463, 431, 367, 239, 415, 351, 223, 319, 191, 81, 98, 164, 262, 268, 273, 280, 290], "source": "MIX14/design_bprime.json R (indices into L); MIX14/L.json labels"} \ No newline at end of file diff --git a/research/p104-odd-unit-per-grading/data/ports_B.json b/research/p104-odd-unit-per-grading/data/ports_B.json new file mode 100644 index 0000000000..eb102ab5e6 --- /dev/null +++ b/research/p104-odd-unit-per-grading/data/ports_B.json @@ -0,0 +1 @@ +{"note":"labels (F2^9, same as lines120.json labels[:104]) of the 8 non-D ports of the #7546 hosted word (MAINFUSE/w7546.json.gz hosted.Dports excludes them); the other 96 are the A (D) ports","B_labels":[81,273,262,98,290,268,164,280]} \ No newline at end of file diff --git a/research/p104-odd-unit-per-grading/data/window8-targets.json.gz b/research/p104-odd-unit-per-grading/data/window8-targets.json.gz new file mode 100644 index 0000000000..fd571bab16 Binary files /dev/null and b/research/p104-odd-unit-per-grading/data/window8-targets.json.gz differ diff --git a/research/p104-odd-unit-per-grading/e8laws.py b/research/p104-odd-unit-per-grading/e8laws.py new file mode 100644 index 0000000000..c91689ab2a --- /dev/null +++ b/research/p104-odd-unit-per-grading/e8laws.py @@ -0,0 +1,549 @@ +"""E8/P104 structural laws, exact checker. Standard library only; run as `python3 -I -B e8laws.py` from any cwd. + +Data: data/lines120.json (120 E8 lines, first 104 = P104 ports; F2^9 labels + integer Gram), data/iso968.json (PR968 +isomorphism), data/ports_B.json (the 8 non-D ports of the #7546 hosted word, as labels), data/half18_frames.json (HALF18 +frame partitions). Label convention: odd cell (t,s) <=> dot(q_t,q_s)=1 <=> G_ts even (so every diagonal cell is odd, +q.q = 1; G_ts = +-1 <=> dot = 0 off the diagonal). +All arithmetic is exact (ints, Fractions, Bareiss ranks over Z). Sections: + 0 data + PR968 isomorphism 5 HALF18 frame partitions (E8 rank 15, P104 rank 13) + 1 HANDT1 G^2=26G, twin, -12 I 6 EARLYCAP rank/Frobenius cap, T1CANCEL res=0 + 2 XRECALL/XBIRTH geometry 7 BYPASS rank_K{e_t} = 95 + 3 LIFTTD orthogonal sets/cliques 8 FACTORSWAP exactly 10 rank-8 decompositions + 4 XDEC joint-decoder rank 8k 9 H9CERT Lemma A (acyclic) toy +Prints PASS_E8_LAWS.""" +import hashlib, json, random, itertools, time +from pathlib import Path +from fractions import Fraction as Fr + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +PR968 = 'research/complex-frame-pair-decoders/inputs/pr717/P104_HIT_flip_3a.txt' +PR968_SHA256 = '8e0178db02c14e1b29058cdbdbd50aac22f2b55a1ba21dc82f417610c9932526' +SHA = { + 'lines120.json': '4a91033b56fe23feb897b90e6259b33dfbe428ff07ad7ce511a73835074f2708', + 'iso968.json': 'fd3fb6b90918d6802c7b22b7fe2efdf3a3979e4bc50bb610437957a84b702e1f', + 'ports_B.json': '96daa0f02363e2fc1fd1ab5c9098db66eab448d1a588660781dfbcc4b0e1b5f7', + 'half18_frames.json': 'e62a80221d167f59c208fb3ae8b18f5aff739bffa4093e03fe061c08a506a00a', +} +PAIRS = [(117, 107), (114, 106), (111, 108), (104, 110), (115, 109), (112, 119), (105, 118), (116, 113)] # (d_j, d'_j) +N = 104 +P = list(range(N)) +T0 = time.time() + + +def say(s): + print(s, flush=True) + + +def expect(name, got, want): + if got != want: + raise SystemExit('FAIL %s: got %r want %r' % (name, got, want)) + say('ok %s: %r' % (name, got)) + + +def dot(a, b): + return bin(a & b).count('1') & 1 + + +def rank2(vs): + basis = [] + for v in vs: + for b in basis: + v = min(v, v ^ b) + if v: + basis.append(v) + return len(basis) + + +def span(vs): + s = {0} + for v in vs: + if v not in s: + s |= {x ^ v for x in s} + return s + + +def pairing_rank(Dl, Sl): + Sl = sorted(set(Sl)) + return rank2([sum(dot(t, s) << i for i, s in enumerate(Sl)) for t in set(Dl)]) + + +def irank(M): + """exact rank over Q of an integer matrix: fraction-free (Bareiss) elimination with column skipping.""" + A = [[int(x) for x in r] for r in M] + m = len(A) + if m == 0: + return 0 + n = len(A[0]) + r = 0 + prev = 1 + for c in range(n): + p = next((i for i in range(r, m) if A[i][c]), None) + if p is None: + continue + A[r], A[p] = A[p], A[r] + piv = A[r][c] + for i in range(r + 1, m): + ai = A[i] + f = ai[c] + ar = A[r] + for j in range(c + 1, n): + ai[j] = (piv * ai[j] - f * ar[j]) // prev + ai[c] = 0 + prev = piv + r += 1 + if r == m: + break + return r + + +def qrank(M): + A = [[Fr(x) for x in r] for r in M] + r = 0 + for c in range(len(A[0]) if A else 0): + p = next((i for i in range(r, len(A)) if A[i][c] != 0), None) + if p is None: + continue + A[r], A[p] = A[p], A[r] + for i in range(len(A)): + if i != r and A[i][c] != 0: + f = A[i][c] / A[r][c] + A[i] = [x - f * y for x, y in zip(A[i], A[r])] + r += 1 + return r + + +def nullspace(M): + A = [[Fr(x) for x in r] for r in M] + m = len(A[0]) + piv = [] + r = 0 + for c in range(m): + p = next((i for i in range(r, len(A)) if A[i][c] != 0), None) + if p is None: + continue + A[r], A[p] = A[p], A[r] + A[r] = [x / A[r][c] for x in A[r]] + for i in range(len(A)): + if i != r and A[i][c] != 0: + f = A[i][c] + A[i] = [x - f * y for x, y in zip(A[i], A[r])] + piv.append(c) + r += 1 + out = [] + for fc in (c for c in range(m) if c not in piv): + v = [Fr(0)] * m + v[fc] = Fr(1) + for i, pc in enumerate(piv): + v[pc] = -A[i][fc] + out.append(v) + return out + + +def maxclique(adj): + """exact maximum clique (branch and bound with greedy colouring) on bitmask adjacency; returns (size, members).""" + n = len(adj) + best = [0, []] + + def colour(Pm): + order, col = [], [] + c = 0 + Um = Pm + while Um: + c += 1 + Qm = Um + while Qm: + v = (Qm & -Qm).bit_length() - 1 + Qm &= ~(1 << v) + Qm &= ~adj[v] + Um &= ~(1 << v) + order.append(v) + col.append(c) + return order, col + + def expand(R, Pm): + order, col = colour(Pm) + for i in range(len(order) - 1, -1, -1): + if len(R) + col[i] <= best[0]: + return + v = order[i] + R.append(v) + NP = Pm & adj[v] + if NP: + expand(R, NP) + elif len(R) > best[0]: + best[0], best[1] = len(R), R[:] + R.pop() + Pm &= ~(1 << v) + + expand([], (1 << n) - 1) + return best[0], best[1] + + +def graph(labels, want, idx=None): + """bitmask graph on `idx` positions (default all): edge i~j (i!=j) iff dot(labels_i,labels_j)==want.""" + idx = list(range(len(labels))) if idx is None else list(idx) + return [sum(1 << b for b, j in enumerate(idx) if j != i and dot(labels[i], labels[j]) == want) for i in idx] + + +def selftest(): + rnd = random.Random(1) + for _ in range(30): + m, n = rnd.randint(1, 7), rnd.randint(1, 7) + M = [[rnd.choice((0, 0, 1, -1, 2, 3)) for _ in range(n)] for _ in range(m)] + assert irank(M) == qrank(M) + for _ in range(30): + n = rnd.randint(2, 12) + E = {(i, j) for i in range(n) for j in range(i + 1, n) if rnd.random() < 0.5} + adj = [sum(1 << j for j in range(n) if (min(i, j), max(i, j)) in E) for i in range(n)] + bf = max((len(c) for k in range(1, n + 1) for c in itertools.combinations(range(n), k) + if all((a, b) in E for a, b in itertools.combinations(c, 2))), default=0) + assert maxclique(adj)[0] == bf + say('ok self-tests: Bareiss rank == Fraction rank, branch-and-bound clique == brute force (60 random cases)') + + +def main(): + selftest() + raws = {f: (HERE / 'data' / f).read_bytes() for f in SHA} + for f in SHA: + expect('SHA256 data/' + f, hashlib.sha256(raws[f]).hexdigest(), SHA[f]) + d = json.loads(raws['lines120.json']) + U, G = d['labels'], d['gram'] + G4 = [r[:N] for r in G[:N]] + Ul = U[:N] + odd_off = [(t, s) for t in P for s in P if t != s and dot(U[t], U[s])] + even_off = [(t, s) for t in P for s in P if t != s and not dot(U[t], U[s])] + + # ------------------------------------------------------------------ 0 + say('== 0. data and PR968 isomorphism') + expect('120 lines: odd distinct labels, dot = G+1 mod 2 on all 120^2 pairs, G_ts in {0,+-1}, rank 8, G^2=30G', + (len(set(U)), all(dot(U[i], U[i]) for i in range(120)), + all(dot(U[i], U[j]) == (G[i][j] + 1) % 2 for i in range(120) for j in range(120)), + all(G[i][j] in (0, 1, -1) for i in range(120) for j in range(120) if i != j), + irank(G), + all(sum(G[i][k] * G[k][j] for k in range(120)) == 30 * G[i][j] for i in range(120) for j in range(120))), + (120, True, True, True, 8, True)) + raw = (ROOT / PR968).read_bytes() + expect('SHA256 of PR968 decoder file', hashlib.sha256(raw).hexdigest(), PR968_SHA256) + ls = raw.decode().split('\n') + Dr = [[int(x) for x in l[3:].split()] for l in ls if l.startswith(' d:')] + Tr = [[int(x) for x in l[3:].split()] for l in ls if l.startswith(' t:')] + GP = [[sum(Dr[k][i] * Tr[k][j] for k in range(8)) // 2 for j in P] for i in P] + iso = json.loads(raws['iso968.json']) + perm, eps = iso['perm'], iso['eps'] + expect('PR968 Gram = eps eps G104(perm) on all 104^2 entries', + all(GP[u][v] == eps[u] * eps[v] * G[perm[u]][perm[v]] for u in P for v in P), True) + + # ------------------------------------------------------------------ 1 HANDT1 + say('== 1. HANDT1: odd cells, G^2 = 26 G, twin decoder, composition residue -12 I') + expect('q_t.q_t = 1 for all 104 (diagonal odd)', all(dot(U[t], U[t]) == 1 for t in P), True) + expect('odd off-diagonal cells of P104, all with G=0', (len(odd_off), all(G[t][s] == 0 for t, s in odd_off)), (5720, True)) + expect('even off-diagonal cells, all with G != 0 (G=+-1)', + (len(even_off), all(G[t][s] in (1, -1) for t, s in even_off)), (4992, True)) + G2 = [[sum(G4[t][k] * G4[k][s] for k in P) for s in P] for t in P] + expect('G104^2 = 26 G104 exactly', all(G2[t][s] == 26 * G4[t][s] for t in P for s in P), True) + expect('control: G104^2 != 30 G104 (the 120-line constant), and rank G104 = 8', + (all(G2[t][s] == 30 * G4[t][s] for t in P for s in P), irank(G4)), (False, 8)) + # G/26 idempotent of trace 8 => G/2 = 13 * proj(range G) + Pj = [[Fr(G4[t][s], 26) for s in P] for t in P] + expect('proj = G/26 symmetric, idempotent, trace 8 (so G/2 = 13 proj)', + (all(sum(Pj[t][k] * Pj[k][s] for k in P) == Pj[t][s] for t in P for s in P), sum(Pj[t][t] for t in P)), (True, 8)) + rows = [] + for dd, dp in PAIRS: + c = G[dd][dp] + assert dd >= N and dp >= N and c in (1, -1) + rows.append(([G[p][dd] for p in P], [c * G[s][dp] for s in P], dd, dp)) # w, u2 = 2u (u = G/(2c)) + expect('UP decoder: sum_k w_k u_k^T = G/2 on all 104^2 cells', + all(sum(w[t] * u2[s] for w, u2, _, _ in rows) == G4[t][s] for t in P for s in P), True) + expect('transposed twin L (deposit u_k, gather w_k): M_L = sum u_k w_k^T = G/2 on all 104^2 cells', + all(sum(u2[t] * w[s] for w, u2, _, _ in rows) == G4[t][s] for t in P for s in P), True) + leg = all(all(dot(U[t], U[dp]) == 0 for t in P if u2[t]) and all(dot(U[s], U[dd]) == 0 for s in P if w[s]) + for w, u2, dd, dp in rows) + tight = all({t for t in P if u2[t]} == {t for t in P if dot(U[t], U[dp]) == 0} and + {s for s in P if w[s]} == {s for s in P if dot(U[s], U[dd]) == 0} for w, u2, dd, dp in rows) + swapped = sum(1 for w, u2, dd, dp in rows if any(dot(U[s], U[dp]) for s in P if w[s])) + expect('L rows frame-legal (deposit labels in z^perp for = U[d\'], gather labels in U[d]^perp), supports exactly the perps', + (leg, tight), (True, True)) + expect('control: gather/deposit frames swapped is illegal on all 8 rows', swapped, 8) + ip = lambda a, b: sum(x * y for x, y in zip(a, b)) + WU = [[Fr(ip(rows[k][0], rows[j][1]), 2) for j in range(8)] for k in range(8)] + expect('W^T U = 13 I (8x8)', WU, [[Fr(13) if k == j else Fr(0) for j in range(8)] for k in range(8)]) + UUm = [[Fr(ip(rows[k][1], rows[j][1]), 4) for j in range(8)] for k in range(8)] + WWm = [[ip(rows[k][0], rows[j][0]) for j in range(8)] for k in range(8)] + offd = lambda M: any(M[k][j] != 0 for k in range(8) for j in range(8) if k != j) + expect('U^T U (diag 13) and W^T W (diag 52) are NOT diagonal', + (offd(UUm), offd(WWm), {UUm[k][k] for k in range(8)}, {WWm[k][k] for k in range(8)}), (True, True, {Fr(13)}, {52})) + # full composition M_L M_U and M_U M_L (each M = G/2 so 4 M_L M_U = sum_kj u2_k (w_k.w_j) u2_j^T) + y = [[sum(WWm[k][j] * rows[j][1][s] for j in range(8)) for s in P] for k in range(8)] + X = [[sum(rows[k][1][t] * y[k][s] for k in range(8)) for s in P] for t in P] # = 4 M_L M_U + z = [[sum(UUm[j][k] * 4 * rows[k][0][s] for k in range(8)) for s in P] for j in range(8)] + X2 = [[sum(rows[j][0][t] * z[j][s] for j in range(8)) for s in P] for t in P] # = 4 M_U M_L + for nm, XX in (('M_L after M_U', X), ('M_U after M_L', X2)): + res_diag = {Fr(1) - Fr(XX[t][t], 4) for t in P} + odd_nz = sum(1 for t, s in odd_off if XX[t][s] != 0) + expect('full composition %s: C-cell residue I - M_L M_U = -12 on the diagonal, odd cells nonzero' % nm, + (res_diag, odd_nz), ({Fr(-12)}, 0)) + expect(' and 4 M_L M_U = G^2 = 26 G, i.e. the composition is 13 G/2 on all 104^2 cells', all(XX[t][s] == 26 * G4[t][s] for t in P for s in P), True) + cnts = set() + for w, u2, _, _ in rows: + cnts.add(sum(1 for t in P for s in P if w[t] * w[s] != 0 and (t == s or dot(U[t], U[s])))) + expect('partial order: one same-index pair term w_k w_k^T touches this many diag+odd cells (each of the 8 rows)', cnts, {1360}) + expect('control: a full-support term would touch 104+5720 C-cells; 1360 < 5824', (1360 < 104 + 5720,), (True,)) + + # ------------------------------------------------------------------ 2 XRECALL / XBIRTH + say('== 2. XRECALL/XBIRTH geometry: not inside q_b^perp') + expect(' not inside q_b^perp for all 104 (q_b.q_b = 1)', all(dot(q, q) == 1 for q in Ul), True) + ev = [Ul[i] ^ Ul[j] for i in range(5) for j in range(i + 1, 5)] + expect('control: an even vector (q_i+q_j, norm 0) IS inside its own perp', all(dot(v, v) == 0 for v in ev), True) + part_ok = all(span([Ul[s] for s in P if s != t and G4[t][s]]) == {x for x in range(512) if not dot(x, Ul[t])} for t in P) + expect('T1CANCEL frame fact: the 48 partner labels of t span t^perp (dim 8 of 9) for all 104 t, and q_t not in t^perp', + (part_ok, all(dot(Ul[t], Ul[t]) for t in P)), (True, True)) + expect('for a != b: inside q_a^perp iff q_a.q_b = 0 (so q_a in q_b^perp is irrelevant to x_b)', + all((dot(Ul[a], Ul[b]) == 0) == (G4[a][b] != 0) for a in P for b in P if a != b), True) + + # ------------------------------------------------------------------ 3 LIFTTD + say('== 3. LIFTTD: orthogonal port sets and the non-orthogonal clique number') + B_labels = json.loads(raws['ports_B.json'])['B_labels'] + Bidx = sorted(Ul.index(x) for x in B_labels) + Aidx = [i for i in P if i not in Bidx] + expect('8 non-D ports found among the 104 labels; 96 A ports', (len(Bidx), len(Aidx)), (8, 96)) + w0, c0 = maxclique(graph(Ul, 0)) + expect('max pairwise F2-orthogonal (dot 0) port set on P104', w0, 8) + expect(' example set is pairwise orthogonal with q.q=1, so its Gram over F2 is I: F2 rank', rank2([Ul[i] for i in c0]), 8) + expect(' independence argument: n orthogonal odd labels are independent (<=9 in F2^9); exact max is 8, no 9-set', (w0 <= 9, w0), (True, 8)) + w0A, _ = maxclique(graph(Ul, 0, Aidx)) + expect('max pairwise-orthogonal set on the 96 A ports', w0A, 8) + w1, c1 = maxclique(graph(Ul, 1)) + expect('clique number of the non-orthogonal (dot 1, i.e. odd-cell) graph on all 104', w1, 8) + w1A, _ = maxclique(graph(Ul, 1, Aidx)) + expect('clique number of the non-orthogonal graph on the 96 A ports', w1A, 8) + adjA = graph(Ul, 1, Aidx) + degs = [bin(a).count('1') for a in adjA] + expect('non-orth degree min/max on the 96', (min(degs), max(degs)), (48, 54)) + pl = [sum(1 << j for j in range(12) if j != i and (i < 8) == (j < 8) and (i < 8 or (i + j) % 2 == 1)) for i in range(12)] + expect('control: clique search on a planted graph (K8 plus a 4-vertex bipartite part) finds 8', maxclique(pl)[0], 8) + + # ------------------------------------------------------------------ 4 XDEC + say('== 4. XDEC: joint (cross-call) decoder rank >= 8k') + cl = c1 + expect('a port and its copy form an odd cell (same label)', all(dot(Ul[t], Ul[t]) == 1 for t in P), True) + for k in (2, 3): + pts = [(i, a) for i in cl for a in range(k)] + Tg = [[1 if p == q else 0 for q in pts] for p in pts] # target: diagonal 1, every (odd) cell 0 + allodd = all(dot(Ul[p[0]], Ul[q[0]]) == 1 for p in pts for q in pts) + expect('k=%d: 8-clique x %d copies is pairwise odd (%d points), target block = identity; exact rank' % (k, k, 8 * k), + (allodd, len(pts), irank(Tg)), (True, 8 * k, 8 * k)) + # clique number of the k-copy multiset graph: projection argument gives <= k*omega = 8k; constructive 8k above + rnd = random.Random(7) + L = list(Ul) + pos = [v for v in range(1, 512) if bin(v).count('1') % 2 == 0] + perm9 = list(range(9)) + rnd.shuffle(perm9) + trans = [rnd.choice(pos) for _ in range(12)] + + def iso9(x): + yv = 0 + for i in range(9): + if x >> i & 1: + yv |= 1 << perm9[i] + for v in trans: + if dot(yv, v): + yv ^= v + return yv + L2 = [iso9(x) for x in L] + assert all(dot(L2[i], L2[j]) == dot(L[i], L[j]) for i in range(0, N, 3) for j in range(N)) + ov = len(set(L) & set(L2)) + allL = L + L2 + wj, _ = maxclique(graph(allL, 1)) + expect('relabelled second call (random O(9,2) isometry, overlap %d labels): clique of L u sigma(L) in the odd graph' % ov, wj, 16) + wm, _ = maxclique(graph(L + L, 1)) + expect('identical second call: clique of L u L (multiset, 208 vertices)', wm, 16) + expect('control: a single call has clique 8 < 16 = 8k', w1, 8) + + # ------------------------------------------------------------------ 5 HALF18 + say('== 5. HALF18: exact rank certificates (CORRECTS the earlier "min rank ~ 18 = 2h" claim)') + fr = json.loads(raws['half18_frames.json']) + + def frame_cert(name, blocks, m): + ok_part = sorted(x for b in blocks for x in b) == list(range(m)) + Z = [[0] * m for _ in range(m)] + for b in blocks: + for a in b: + for c in b: + Z[a][c] += 1 + ev_zero = all(Z[a][c] == 0 for a in range(m) for c in range(m) if a != c and dot(U[a], U[c]) == 0) + dnz = all(Z[a][a] != 0 for a in range(m)) + pw = all(dot(U[a], U[c]) == 1 for b in blocks for a in b for c in b) + return ok_part, pw, ev_zero, dnz, irank(Z), Z + ok_part, pw, ev0, dnz, rk, Z120 = frame_cert('E8', fr['E8_120'], 120) + expect('E8-120: 15 frames partition the 120 lines, each pairwise odd(dot 1, G=0), Z=0 on even cells, diag nonzero, exact rank', + (len(fr['E8_120']), [len(b) for b in fr['E8_120']] == [8] * 15, ok_part, pw, ev0, dnz, rk), (15, True, True, True, True, True, 15)) + ok_part, pw, ev0, dnz, rk, Z104 = frame_cert('P104', fr['P104'], 104) + expect('P104: 13 frames partition the 104 ports, same properties, exact rank', + (len(fr['P104']), ok_part, pw, ev0, dnz, rk), (13, True, True, True, True, 13)) + w120, _ = maxclique(graph(U, 1)) + a120, _ = maxclique(graph(U, 0)) + expect('omega(odd graph): E8-120 and P104 (frames have <= 8 lines so >= 15 resp. 13 frames; both certificates meet it)', + (w120, w1, -(-120 // w120), -(-104 // w1)), (8, 8, 15, 13)) + expect('alpha = max pairwise-even (dot 0) set: E8-120 and P104 (8 even labels give a nonsingular diagonal block, so rank >= 8)', + (a120, w0), (8, 8)) + c0e = maxclique(graph(Ul, 0))[1] + Zs = [[Z104[a][c] for c in c0e] for a in c0e] + expect('lower bound 8: the Z block on the 8 pairwise-even ports is diagonal, nonzero, rank', (irank(Zs), all(Zs[i][j] == 0 for i in range(8) for j in range(8) if i != j)), (8, True)) + badZ = [r[:] for r in Z104] + bad = next((a, c) for a in P for c in P if a != c and dot(U[a], U[c]) == 0) + badZ[bad[0]][bad[1]] = 1 + expect('control: Z with one extra nonzero on an even cell is detected', all(badZ[a][c] == 0 for a in P for c in P if a != c and dot(U[a], U[c]) == 0), False) + say(' range for min rank of Z (nonzero diag, zero on even cells) on P104: [8, 13]; exact infeasibility of <=12 NOT claimed') + + # ------------------------------------------------------------------ 6 EARLYCAP / T1CANCEL + say('== 6. EARLYCAP: rank(2I + C_F) <= d + 8 and |E| <= 5408 - 43264/(d+8); T1CANCEL res = 0') + part_cells = [(t, s) for t in P for s in P if t != s and G4[t][s]] + pairs_u = [(t, s) for t, s in part_cells if t < s] + expect('partner cells: 4992 ordered (2496 pairs), entries +-1', (len(part_cells), len(pairs_u)), (4992, 2496)) + rnd = random.Random(11) + + def case(name, Eset): + E = set() + for t, s in Eset: + E.add((t, s)) + E.add((s, t)) + CE = [[G4[t][s] if (t, s) in E else 0 for s in P] for t in P] + Nm = [[(2 if t == s else 0) + (G4[t][s] if (t != s and G4[t][s] and (t, s) not in E) else 0) for s in P] for t in P] + d = irank(CE + G4) - 8 # rank(C_E K), K = ker G (dim 96), via rank [C_E; G] = 8 + rank(C_E K) + rN = irank(Nm) + nE = len(E) + nF = 4992 - nE + cs_ok = rN * (416 + nF) >= 208 * 208 + cap_ok = Fr(nE) <= 5408 - Fr(43264, d + 8) + say(' %-22s |E|=%4d d=%2d rank N=%3d rank<=d+8: %s Cauchy-Schwarz rankN>=208^2/(416+|F|): %s |E|<=cap: %s' % + (name, nE, d, rN, rN <= d + 8, cs_ok, cap_ok)) + assert rN <= d + 8 and cs_ok and cap_ok, name + return nE, d, rN + r_empty = case('E empty', []) + r_all = case('E all (control d=96)', pairs_u) + expect('E empty: rank N = rank G = 8, d = 0; E all: N = 2I rank 104, d = 96', (r_empty[1:], r_all[1:]), ((0, 8), (96, 104))) + rnd2 = random.Random(5) + half = [pc for pc in pairs_u if rnd2.random() < 0.5] + r_half = case('random half', half) + expect('control: a random half-early set has rank(C_E K) = d = 96 (no cap violation)', r_half[1], 96) + case('random 5%', [pc for pc in pairs_u if rnd2.random() < 0.05]) + tab = [] + for dd in range(1, 9): + cap = 5408 - Fr(43264, dd + 8) + tab.append((dd, float(cap), float(cap / dd))) + say(' d, cap on |E|, cells per rank: ' + '; '.join('%d: %.1f, %.1f' % t for t in tab)) + expect('cells per rank at d=2,3,4,8 (the 577 gate)', + [round(float((5408 - Fr(43264, dd + 8)) / dd), 1) for dd in (2, 3, 4, 8)], [540.8, 491.6, 450.7, 338.0]) + expect('cells per rank < 577 for all d >= 2 (up to 96) and strictly decreasing from d=1; d=1 cap |E| <= floor 600.9', + (all(((5408 - Fr(43264, dd + 8)) / dd) < 577 for dd in range(2, 97)), + all(((5408 - Fr(43264, dd + 8)) / dd) > ((5408 - Fr(43264, dd + 9)) / (dd + 1)) for dd in range(1, 96)), + int(5408 - Fr(43264, 9))), (True, True, 600)) + # T1CANCEL: exact res and rank N0 on random sigma matchings (E8) + part = {t: [s for s in P if s != t and G4[t][s]] for t in P} + rng = random.Random(2) + + def rand_matching(): + match, rowof = {}, {} + + def aug(t, seen): + c = part[t][:] + rng.shuffle(c) + for q in c: + if q in seen: + continue + seen.add(q) + if q not in rowof or aug(rowof[q], seen): + match[t] = q + rowof[q] = t + return True + return False + for t in rng.sample(P, N): + assert aug(t, set()) + return match + idx = [] + for i in P: + if irank([G4[j] for j in idx + [i]]) > len(idx): + idx.append(i) + if len(idx) == 8: + break + Rg = [G4[i] for i in idx] + for trial in range(2): + sig = rand_matching() + M0 = [[G4[sig[t]][t] * G4[sig[t]][j] - (1 if j == t else 0) for j in P] for t in P] + A2 = [[G4[t][j] - 2 * M0[t][j] for j in P] for t in P] + cond = [[sum(A2[i][j] * Rg[k][i] for i in P) for k in range(8)] for j in P] + res = 8 - irank(cond) + N0 = [[Fr(G4[p][t], 2) - (Fr(G4[p][t], 2) if sig[t] == p else 0) for t in P] for p in P] + rN0 = irank([[int(2 * x) for x in r] for r in N0]) + expect('T1CANCEL E8 sigma %d (perfect partner matching): exact res(C_eff=G/2) and rank N0' % trial, (res, rN0), (0, 104)) + say(' (T1CANCEL A3/A4 toy part not ported: needs the lane simulators)') + + # ------------------------------------------------------------------ 7 BYPASS + say('== 7. BYPASS: rank_K{e_t}') + K = nullspace(G4) + expect('dim K = dim ker G104', len(K), 96) + rA = irank([[int(k[t] * 1) if k[t].denominator == 1 else 0 for t in Aidx] for k in K]) if all(k[t].denominator == 1 for k in K for t in Aidx) else None + if rA is None: + rA = qrank([[k[t] for t in Aidx] for k in K]) + rB = qrank([[k[t] for t in Bidx] for k in K]) + expect('rank_K{e_t : t in A (96 ports)} = rank of the kernel basis restricted to A', rA, 95) + expect('formula cross-check: 96 - (|B| - rank G[:,B]) = rank_K A; rank G[:,B]', (96 - (8 - irank([[G4[t][b] for b in Bidx] for t in P])), irank([[G4[t][b] for b in Bidx] for t in P])), (95, 7)) + expect('rank_K{e_t : t in B (8 ports)}', rB, 8) + expect('control: all 104 ports give rank_K = 96 = dim K', qrank([[k[t] for t in P] for k in K]), 96) + + # ------------------------------------------------------------------ 8 FACTORSWAP + say('== 8. FACTORSWAP: rank-8 decompositions G/2 = sum_j c_j v_dj v_ej^T on the 16 lines F0 u F1') + S16 = sorted(d for pr in PAIRS for d in pr) + expect('S16 = the 16 non-port lines 104..119', S16, list(range(104, 120))) + price = {} + for dl in S16: + for el in S16: + price[(dl, el)] = pairing_rank([U[t] for t in P if G[t][dl]], [U[s] for s in P if G[s][el]]) + from collections import Counter + expect('row price histogram over all 16x16 (deposit line, gather line)', dict(Counter(price.values())), {7: 64, 8: 192}) + Gs = [[G[a][b] for b in S16] for a in S16] + found = [] + for sub in itertools.combinations(range(16), 8): + if irank([[Gs[a][b] for b in sub] for a in sub]) < 8: + continue + ok = [] + for j in range(8): + m = [e for e in range(16) if Gs[e][sub[j]] != 0 and all(Gs[e][sub[k]] == 0 for k in range(8) if k != j)] + if not m: + break + ok.append(m) + else: + found.append((sub, ok)) + tot = Counter(sum(price[(S16[i], S16[o[0]])] for i, o in zip(sub, ok)) for sub, ok in found) + expect('independent 8-subsets of S16 with a dual-basis row on an S16 line for every j', len(found), 10) + expect('total price histogram (8 decompositions at C=56, 2 at 64)', dict(tot), {56: 8, 64: 2}) + expect('gather choices per row are unique (multiplicity)', Counter(len(o) for s, ok in found for o in ok), Counter({1: 80})) + rs = list(PAIRS) + expect('control: the native pairing (d_j, d\'_j) rows each price 7 (total 56)', (sum(price[p] for p in rs), sorted({price[p] for p in rs})), (56, [7])) + + # ------------------------------------------------------------------ 9 H9CERT + say('== 9. H9CERT Lemma A (acyclic): n <= sum_k rank Z[D_k, S_k] for every valid Z (exact decoder: odd cells of M are 0)') + Dk = [[t for t in P if w[t]] for w, _, _, _ in rows] + Sk = [[s for s in P if u2[s]] for _, u2, _, _ in rows] + Mx = [[Fr(G4[t][s], 2) for s in P] for t in P] + Zq = [[dot(Ul[a], Ul[b]) for b in P] for a in P] + Zi = [[1 if a == b else 0 for b in P] for a in P] + for nm, Zm in (('frame-partition Z (rank 13)', Z104), ('Z = I', Zi), ('Z = Q (dot matrix)', Zq)): + valid = all(Zm[a][a] != 0 for a in P) and all(Zm[a][b] == 0 for a in P for b in P if a != b and dot(Ul[a], Ul[b]) == 0) + had = all(Zm[t][s] * Mx[t][s] == (Zm[t][t] if t == s else 0) for t in P for s in P) + ranks = [irank([[Zm[t][s] for s in Sk[k]] for t in Dk[k]]) for k in range(8)] + say(' %s: valid %s, Z o M = diag(Z_pp) %s, block ranks %s sum %d >= 104: %s' % (nm, valid, had, ranks, sum(ranks), sum(ranks) >= 104)) + assert valid and had and sum(ranks) >= 104 + zinv = [r[:] for r in Z104] + zinv[0][0] = 0 + ranks = [irank([[zinv[t][s] for s in Sk[k]] for t in Dk[k]]) for k in range(8)] + say(' control (invalid Z, port 0 diagonal zeroed): Z o M diagonal singular, block rank sum %d (bound no longer required)' % sum(ranks)) + say(' (ACYCDEC lb.py not ported)') + + say('elapsed %.1fs' % (time.time() - T0)) + say('PASS_E8_LAWS') + + +if __name__ == '__main__': + main() diff --git a/research/p104-odd-unit-per-grading/odd_unit.py b/research/p104-odd-unit-per-grading/odd_unit.py new file mode 100644 index 0000000000..200f9595a5 --- /dev/null +++ b/research/p104-odd-unit-per-grading/odd_unit.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Part I, the odd unit paid per grading: exact checks of the contract identities. Standard library only. + +A grading sigma_p flips the sign of one port variable q_p (q -> -q). For a matrix N(q) of Laurent entries, +R(N) = sigma(N) N^-1 is its sigma-factor and o(N) = rank(R - I) its odd-unit count. Matrices are evaluated +exactly over Q at two generic rational points; sigma is evaluation at -q. Checked: + + I1 o(N) = rank Odd(N), Odd(N) = (N - sigma N)/2, for random 2x2..4x4 coupled matrices in two port variables, + in both gradings (any size, any coupling). + I2 Cayley form: with E, O the sigma-even/odd parts, dim ker(R + I) = dim ker E (t = -1 <=> E singular). + I3 per port N = [[c, a q], [b/q, d]]: det R = 1, tr R = 2(cd+ab)/(cd-ab), det(R + I) = -4cd/(ab - cd), so + t_eff = ab/(cd - ab) and t_eff = -1 <=> cd = 0 (the park); HOST(alpha, beta) has t_eff = alpha*beta. + I4 coupled singular pencil: E_a singular while E_0 = I, and the q_b-odd entries are o_b = 2 junk in ledger b. + I5 the isotropic kernel a + b q_a^2 q_b^2 is even in both gradings (o_a = o_b = 0); the monomial q_a q_b is odd in + both (o_a = o_b = 1). + I6 a q-free coupling P^-1 T P of the per-port target T = diag(1/q_a, 1/q_a, 1/q_b, 1/q_b) leaves m_a = 2. + I7 the merged plane M45 = [[1,-q],[1/q,1]]: M45 = U_q + L_q - I, H = L_q U_q, o(M45) = 2, R^2 = -I, + M45^2 = 2 J_q, M45^4 = -4I, det 2, diag(1,1/2) M45 = HOST(-1, 1/2) (t = -1/2), H M45^-1 = [[1,0],[1/(2q),1/2]] + has o = 1 (the park as a caller op). + I8 dressing invariance: R(A N B) = A R(N) A^-1 for sigma-fixed A, B (tr R invariant), 200 random cases; + control: a q-odd A changes tr R. + I9 the b-family X = x - y, Y = x + b y: t = bc/det = -1/(1+b) for b not in {0,-1}; t = -1 only at b = 0, where + the window scalar (1+b)/b has a simple pole; t is invariant under both diagonal gauges. +Prints PASS_ODD_UNIT_PER_GRADING.""" +import random +from fractions import Fraction as Fr + +PTS = [(Fr(7, 3), Fr(-5, 11)), (Fr(13, 2), Fr(3, 17))] + + +def say(s): + print(s, flush=True) + + +def expect(name, got, want): + if got != want: + raise SystemExit('FAIL %s: got %r want %r' % (name, got, want)) + say('ok %s: %r' % (name, got)) + + +def rank(M): + A = [list(r) for r in M] + r = 0 + cols = len(A[0]) if A else 0 + for c in range(cols): + p = next((i for i in range(r, len(A)) if A[i][c] != 0), None) + if p is None: + continue + A[r], A[p] = A[p], A[r] + for i in range(len(A)): + if i != r and A[i][c] != 0: + f = A[i][c] / A[r][c] + A[i] = [x - f * y for x, y in zip(A[i], A[r])] + r += 1 + return r + + +def mul(A, B): + return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))] + + +def inv(A): + n = len(A) + M = [list(A[i]) + [Fr(int(i == j)) for j in range(n)] for i in range(n)] + for c in range(n): + p = next(i for i in range(c, n) if M[i][c] != 0) + M[c], M[p] = M[p], M[c] + piv = M[c][c] + M[c] = [x / piv for x in M[c]] + for i in range(n): + if i != c and M[i][c] != 0: + f = M[i][c] + M[i] = [x - f * y for x, y in zip(M[i], M[c])] + return [r[n:] for r in M] + + +def det(A): + A = [list(r) for r in A] + n, d = len(A), Fr(1) + for c in range(n): + p = next((i for i in range(c, n) if A[i][c] != 0), None) + if p is None: + return Fr(0) + if p != c: + A[c], A[p] = A[p], A[c] + d = -d + d *= A[c][c] + for i in range(c + 1, n): + f = A[i][c] / A[c][c] + A[i] = [x - f * y for x, y in zip(A[i], A[c])] + return d + + +def eye(n): + return [[Fr(int(i == j)) for j in range(n)] for i in range(n)] + + +def add(A, B, s=1): + return [[x + s * y for x, y in zip(r, t)] for r, t in zip(A, B)] + + +def ev(M, qa, qb): + return [[Fr(f(qa, qb)) for f in r] for r in M] + + +SIG = {'a': lambda qa, qb: (-qa, qb), 'b': lambda qa, qb: (qa, -qb)} + + +def o(M, g): + best = 0 + for qa, qb in PTS: + N = ev(M, qa, qb) + S = ev(M, *SIG[g](qa, qb)) + best = max(best, rank(add(mul(S, inv(N)), eye(len(N)), -1))) + return best + + +def r_odd(M, g): + best = 0 + for qa, qb in PTS: + N = ev(M, qa, qb) + S = ev(M, *SIG[g](qa, qb)) + best = max(best, rank([[(x - y) / 2 for x, y in zip(r, t)] for r, t in zip(S, N)])) + return best + + +MON = [lambda a, b: 1, lambda a, b: -1, lambda a, b: 2, lambda a, b: a, lambda a, b: -a, lambda a, b: 1 / a, + lambda a, b: a * b, lambda a, b: b, lambda a, b: 1 / b, lambda a, b: 0] + + +def random_matrix(rng): + d = rng.choice([2, 3, 4]) + M = [[rng.choice(MON) for _ in range(d)] for _ in range(d)] + if any(det(ev(M, qa, qb)) == 0 for qa, qb in PTS): + return None + return M + + +def main(): + rng = random.Random(1) + # I1 + ok = n = 0 + while n < 40: + M = random_matrix(rng) + if M is None: + continue + n += 1 + ok += (o(M, 'a') == r_odd(M, 'a')) and (o(M, 'b') == r_odd(M, 'b')) + expect('I1 o(N) = rank Odd(N), random coupled 2-4x4, both gradings', (ok, n), (40, 40)) + # I2 (include matrices with a singular even part by construction) + ok = n = sing = 0 + while n < 40: + M = random_matrix(rng) + if M is None: + continue + qa, qb = PTS[0] + N = ev(M, qa, qb) + S = ev(M, -qa, qb) + E = [[(x + y) / 2 for x, y in zip(r, t)] for r, t in zip(N, S)] + R = mul(S, inv(N)) + a = len(N) - rank(add(R, eye(len(N)))) + b = len(N) - rank(E) + n += 1 + ok += a == b + sing += b > 0 + expect('I2 Cayley dim ker(R+I) = dim ker E (random)', (ok, n), (40, 40)) + say(' (of which with singular E: %d)' % sing) + for c_, d_ in [(0, 1), (1, 0), (0, 0)]: + # park examples: per-port N with cd = 0 must have a -1 eigenvalue + M = [[lambda qa, qb, c_=c_: c_, lambda qa, qb: qa], [lambda qa, qb: 1 / qa, lambda qa, qb, d_=d_: d_]] + qa, qb = PTS[0] + N, S = ev(M, qa, qb), ev(M, -qa, qb) + if det(N) == 0: + continue + expect('I2 park c=%d d=%d: dim ker(R+I) = dim ker E' % (c_, d_), + 2 - rank(add(mul(S, inv(N)), eye(2))), 2 - rank([[(x + y) / 2 for x, y in zip(r, t)] for r, t in zip(N, S)])) + # I3 per-port law, exact at random rational points + bad = 0 + for _ in range(300): + a, b, c, d, q = (Fr(rng.randint(-9, 9), rng.randint(1, 7)) for _ in range(5)) + if q == 0 or c * d - a * b == 0 or a * b - c * d == 0: + continue + N = [[c, a * q], [b / q, d]] + S = [[c, -a * q], [-b / q, d]] + R = mul(S, inv(N)) + D = c * d - a * b + bad += det(R) != 1 + bad += R[0][0] + R[1][1] != 2 * (c * d + a * b) / D + bad += det(add(R, eye(2))) != -4 * c * d / (a * b - c * d) + # t_eff from tr R = tr W = 2 + 4t + t = ((R[0][0] + R[1][1]) - 2) / 4 + bad += t != a * b / (c * d - a * b) + bad += (t == -1) != (c * d == 0) + expect('I3 per-port R, det R = 1, det(R+I) = -4cd/(ab-cd), t_eff = ab/(cd-ab), t_eff=-1 <=> cd=0 (300 points)', bad, 0) + bad = 0 + for _ in range(100): + al, be = Fr(rng.randint(-9, 9), rng.randint(1, 5)), Fr(rng.randint(-9, 9), rng.randint(1, 5)) + a, b, c, d = al, be, Fr(1), 1 + al * be + if c * d - a * b == 0: + continue + bad += a * b / (c * d - a * b) != al * be + expect('I3 HOST(alpha,beta) = [[1, alpha q],[beta/q, 1+alpha beta]] has t_eff = alpha*beta', bad, 0) + # I4 coupled singular pencil + Na = [[lambda qa, qb: 1, lambda qa, qb: qb + qa], [lambda qa, qb: 1 / qb - 1 / qa, lambda qa, qb: 1]] + qa, qb = PTS[0] + N = ev(Na, qa, qb) + Sa = ev(Na, -qa, qb) + Sb = ev(Na, qa, -qb) + Sab = ev(Na, -qa, -qb) + Ea = [[(w + x) / 2 for w, x in zip(r, s)] for r, s in zip(N, Sa)] + E0 = [[(w + x + y + z) / 4 for w, x, y, z in zip(r, s, t, u)] for r, s, t, u in zip(N, Sa, Sb, Sab)] + expect('I4 coupled block: det E_a, det E_0, o_a, o_b', (det(Ea), det(E0), o(Na, 'a'), o(Na, 'b')), (0, 1, 2, 2)) + # I5 isotropic kernel + A, B = Fr(1, 2), Fr(1, 3) + Cw = [[lambda qa, qb: A + B * qa ** 2 * qb ** 2]] + Mono = [[lambda qa, qb: qa * qb]] + expect('I5 C_{qa+qb} = a + b qa^2 qb^2: (o_a, o_b); monomial qa qb: (o_a, o_b)', + (o(Cw, 'a'), o(Cw, 'b'), o(Mono, 'a'), o(Mono, 'b')), (0, 0, 1, 1)) + # I6 q-free coupling keeps m_a = 2 + P = [[1, 2, 0, 1], [0, 1, 1, 0], [3, 0, 1, 0], [0, 0, 1, 1]] + P = [[Fr(x) for x in r] for r in P] + Pi = inv(P) + qa, qb = PTS[0] + + def W(qa, qb): + T = [[Fr(0)] * 4 for _ in range(4)] + T[0][0] = T[1][1] = 1 / qa + T[2][2] = T[3][3] = 1 / qb + return mul(mul(Pi, T), P) + Wn, Ws = W(qa, qb), W(-qa, qb) + R = mul(Ws, inv(Wn)) + expect('I6 coupled target: dim ker(R_a + I), rank(R_a - I)', (4 - rank(add(R, eye(4))), rank(add(R, eye(4), -1))), (2, 2)) + # I7 the merged plane M45 + bad = 0 + for q in [Fr(7, 3), Fr(-5, 2), Fr(11, 13)]: + M45 = [[Fr(1), -q], [1 / q, Fr(1)]] + Uq = [[Fr(1), -q], [Fr(0), Fr(1)]] + Lq = [[Fr(1), Fr(0)], [1 / q, Fr(1)]] + H = [[Fr(1), -q], [1 / q, Fr(0)]] + Jq = [[Fr(0), -q], [1 / q, Fr(0)]] + bad += add(add(Uq, Lq), eye(2), -1) != M45 + bad += mul(Lq, Uq) != H + S = [[Fr(1), q], [-1 / q, Fr(1)]] + R = mul(S, inv(M45)) + bad += rank(add(R, eye(2), -1)) != 2 + bad += mul(R, R) != [[-1, 0], [0, -1]] + M2 = mul(M45, M45) + bad += M2 != [[2 * x for x in r] for r in Jq] + bad += mul(M2, M2) != [[-4, 0], [0, -4]] + bad += det(M45) != 2 + bad += mul([[Fr(1), Fr(0)], [Fr(0), Fr(1, 2)]], M45) != [[Fr(1), -q], [1 / (2 * q), Fr(1, 2)]] + HM = mul(H, inv(M45)) + bad += HM != [[1, 0], [1 / (2 * q), Fr(1, 2)]] + SHM = [[Fr(1), Fr(0)], [-1 / (2 * q), Fr(1, 2)]] + bad += rank(add(mul(SHM, inv(HM)), eye(2), -1)) != 1 + expect('I7 M45 = U+L-I, H = L U, o = 2, R^2 = -I, M^2 = 2J, M^4 = -4I, det 2, diag(1,1/2)M = HOST(-1,1/2), o(H M^-1) = 1', bad, 0) + # HOST(-1, 1/2) has t = -1/2 + expect('I7 t_eff(M45) via I3 (a=-1,b=1,c=d=1)', Fr(-1) * 1 / (1 * 1 - Fr(-1) * 1), Fr(-1, 2)) + # I8 dressing invariance + bad = ctrl = 0 + for _ in range(200): + q = Fr(rng.randint(1, 9), rng.randint(1, 9)) * rng.choice([1, -1]) + rnd = lambda: Fr(rng.randint(-5, 5), rng.randint(1, 4)) + while True: + A = [[rnd(), rnd()], [rnd(), rnd()]] + B = [[rnd(), rnd()], [rnd(), rnd()]] + c, d, a, b = rnd(), rnd(), rnd(), rnd() + if det(A) and det(B) and c * d - a * b: + break + N = [[c, a * q], [b / q, d]] + S = [[c, -a * q], [-b / q, d]] + R = mul(S, inv(N)) + ANB, sANB = mul(mul(A, N), B), mul(mul(A, S), B) + R2 = mul(sANB, inv(ANB)) + bad += R2 != mul(mul(A, R), inv(A)) + # control: q-odd dressing A' = [[1, q],[0,1]] (sigma(A') != A') + Ao, sAo = [[Fr(1), q], [Fr(0), Fr(1)]], [[Fr(1), -q], [Fr(0), Fr(1)]] + R3 = mul(mul(sAo, S), inv(mul(Ao, N))) + ctrl += (R3[0][0] + R3[1][1]) != (R[0][0] + R[1][1]) + expect('I8 R(ANB) = A R(N) A^-1 for sigma-fixed A,B (200)', bad, 0) + say('ok I8 control: q-odd dressing changes tr R on %d/200' % ctrl) + if ctrl < 100: + raise SystemExit('FAIL I8 control too weak') + # I9 b-family + bad = 0 + for b in [Fr(1), Fr(1, 2), Fr(-1, 2), Fr(-2), Fr(1, 1000), Fr(1, 10 ** 6), Fr(-2, 3)]: + C = [[Fr(1), Fr(-1)], [Fr(1), b]] + t = C[0][1] * C[1][0] / det(C) + bad += t != -1 / (1 + b) + for g1, g2 in [(Fr(2), Fr(3)), (Fr(-1, 5), Fr(7))]: + for Cg in (mul([[g1, 0], [0, g2]], C), mul(C, [[g1, 0], [0, g2]])): + bad += Cg[0][1] * Cg[1][0] / det(Cg) != t + bad += Cg[0][0] * Cg[1][1] / det(Cg) != 1 + t + expect('I9 b-family t = -1/(1+b), gauge-invariant t and 1+t (7 b values x 4 gauges)', bad, 0) + expect('I9 table t at b = 1, 1/2, -1/2, -2', [str(-1 / (1 + b)) for b in [Fr(1), Fr(1, 2), Fr(-1, 2), Fr(-2)]], + ['-1/2', '-2/3', '-2', '1']) + C0 = [[Fr(1), Fr(-1)], [Fr(1), Fr(0)]] + expect('I9 b = 0 (t = -1): t, zero diagonal entry', (C0[0][1] * C0[1][0] / det(C0), C0[1][1]), (-1, 0)) + expect('I9 window scalar |(1+b)/b| at b = 1, 1/2, -1/2, -2, 1e-3, 1e-6 (simple pole at b = 0)', + [str(abs((1 + b) / b)) for b in [Fr(1), Fr(1, 2), Fr(-1, 2), Fr(-2), Fr(1, 1000), Fr(1, 10 ** 6)]], + ['2', '3', '1', '1/2', '1001', '1000001']) + say('PASS_ODD_UNIT_PER_GRADING') + + +if __name__ == '__main__': + main() diff --git a/research/p104-odd-unit-per-grading/onerank.py b/research/p104-odd-unit-per-grading/onerank.py new file mode 100644 index 0000000000..62d1a03c5f --- /dev/null +++ b/research/p104-odd-unit-per-grading/onerank.py @@ -0,0 +1,321 @@ +"""onerank.py -- exact checks behind the ONERANK lane (cards/WILD/ONERANK): the 'exact one-rank law' is a Fredholm tautology, +Lemma LIN (corrections through a drop-dirty wire are linear), Lemma TR (one-block re-solve criterion), and the 'no lower bound' +toy (T = I network that stops rigid at 4 stays; disjoint copies give an unbounded gap). +Standard library only; `python3 -I -B onerank.py` from any cwd; exact arithmetic (Fractions / ints mod 2^31-1); seeded. +The lane toy.py / toy2.py themselves need numpy + the NETCOMPILE-frame engine lin2.py; they are NOT ported. What is ported here +are the lemma-level checks (self-contained constructions with the same mathematical content), so the 'rigid toy' below is an +independent re-derivation of the toy2 witness (2 wires, meetings carrying M then M^-1), not a replay of lin2.analyse.""" +import itertools, random, time, collections +from fractions import Fraction as Fr +T0 = time.time() +P = 2 ** 31 - 1 +def ok(msg): print('ok', msg, flush=True) +def check(c, msg): + if not c: raise AssertionError(msg) + +# ---------------------------------------------------------------------------------------------------------------- linear algebra +def rref(M): + A = [[Fr(x) for x in r] for r in M]; piv = []; r = 0 + nc = len(A[0]) if A else 0 + for c in range(nc): + p = next((i for i in range(r, len(A)) if A[i][c] != 0), None) + if p is None: continue + A[r], A[p] = A[p], A[r]; iv = 1 / A[r][c]; A[r] = [x * iv for x in A[r]] + for i in range(len(A)): + if i != r and A[i][c] != 0: + f = A[i][c]; A[i] = [a - f * b for a, b in zip(A[i], A[r])] + piv.append(c); r += 1 + if r == len(A): break + return A[:r], piv +def rank(M): return len(rref(M)[1]) if M and M[0] else 0 +def hcat(A, cols): return [list(r) + [c[i] for c in cols] for i, r in enumerate(A)] +def solve(A, b): + """exact: x with A x = b, or None.""" + R, piv = rref(hcat(A, [b])) + n = len(A[0]) + if n in piv: return None + x = [Fr(0)] * n + for i, c in enumerate(piv): x[c] = R[i][n] + return x +def left_witness(A, b): + """y with y A = 0 and y.b != 0 (Fredholm certificate of infeasibility) or None.""" + At = [list(c) for c in zip(*A)] + R, piv = rref(At); m = len(A); free = [c for c in range(m) if c not in piv] + for f in free: + y = [Fr(0)] * m; y[f] = Fr(1) + for i, c in enumerate(piv): y[c] = -R[i][f] + if sum(a * c for a, c in zip(y, b)) != 0: return y + return None +def lnull(A): + At = [list(c) for c in zip(*A)] + R, piv = rref(At); m = len(A); out = [] + for f in [c for c in range(m) if c not in piv]: + y = [Fr(0)] * m; y[f] = Fr(1) + for i, c in enumerate(piv): y[c] = -R[i][f] + out.append(y) + return out +def matmul(A, B): + Bt = list(zip(*B)); return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A] +def eye(n): return [[Fr(int(i == j)) for j in range(n)] for i in range(n)] +def inv(M): + n = len(M); R, piv = rref([list(map(Fr, r)) + list(eye(n)[i]) for i, r in enumerate(M)]) + assert piv[:n] == list(range(n)), 'singular'; return [r[n:] for r in R] + +# ==================================================================================================================== +# 7a. Theorem F (Fredholm): one appended column -> rank rises by 0 or 1, 'misses by exactly one rank' == 'infeasible' +# ==================================================================================================================== +def rand_matrix(rng, m, n): + kind = rng.choice(['dense', 'sparse', 'lowrank']) + if kind == 'dense': A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(m)] + elif kind == 'sparse': A = [[rng.choice([0, 0, 0, 1, -1, 2]) for _ in range(n)] for _ in range(m)] + else: + k = rng.randint(1, max(1, min(m, n) - 1)); U = [[rng.randint(-2, 2) for _ in range(k)] for _ in range(m)] + W = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(k)] + A = [[sum(U[i][t] * W[t][j] for t in range(k)) for j in range(n)] for i in range(m)] + return [[Fr(x) for x in r] for r in A], kind + +def section_theorem_f(seed=11, trials=3000): + t = time.time(); rng = random.Random(seed) + cnt = collections.Counter(); sup_differs = 0; two_col = collections.Counter() + for _ in range(trials): + m = rng.randint(2, 7); n = rng.randint(1, 7) + A, kind = rand_matrix(rng, m, n) + if rng.random() < 0.5: b = [Fr(rng.randint(-3, 3)) for _ in range(m)] + else: + x = [Fr(rng.randint(-2, 2)) for _ in range(n)]; b = [sum(a * c for a, c in zip(r, x)) for r in A] + if rng.random() < 0.3: b[rng.randrange(m)] += 1 # perturb: usually infeasible + r1 = rank(A); r2 = rank(hcat(A, [b])); d = r2 - r1 + check(d in (0, 1), 'Theorem F violated: rank rose by %d' % d) + x = solve(A, b); y = left_witness(A, b) + if d == 0: + check(x is not None and all(sum(a * c for a, c in zip(r, x)) == bi for r, bi in zip(A, b)), 'feasible but no solution') + check(y is None, 'feasible but has a Fredholm witness') + else: + check(x is None, 'rank jumped but solvable') + check(y is not None and all(sum(y[i] * A[i][j] for i in range(m)) == 0 for j in range(n)) and sum(a * c for a, c in zip(y, b)) != 0, 'no Fredholm witness') + # phi is not canonical: another witness with different support (when the left kernel has dim >= 2) + Ln = lnull(A) + if len(Ln) >= 2: + y2 = [a + c * (1 + rng.randint(1, 3)) for a, c in zip(y, Ln[0] if Ln[0] != y else Ln[1])] + if sum(a * c for a, c in zip(y2, b)) != 0 and all(sum(y2[i] * A[i][j] for i in range(m)) == 0 for j in range(n)): + sup_differs += (tuple(v != 0 for v in y2) != tuple(v != 0 for v in y)) + cnt['d=%d' % d] += 1; cnt[kind] += 1 + # two appended columns (control): rank can rise by 2 (and never by more than 2) + b2 = [Fr(rng.randint(-3, 3)) for _ in range(m)] + d2 = rank(hcat(A, [b, b2])) - r1 + check(0 <= d2 <= 2, 'two columns raised rank by %d' % d2); two_col[d2] += 1 + check(cnt['d=0'] > 100 and cnt['d=1'] > 100, 'both outcomes must occur') + check(two_col[2] > 100, 'control: two appended columns must be able to miss by 2') + A = [[Fr(1)], [Fr(0)], [Fr(0)]]; b1 = [Fr(0), Fr(1), Fr(0)]; b2 = [Fr(0), Fr(0), Fr(1)] + check(rank(hcat(A, [b1, b2])) - rank(A) == 2, 'explicit 2-miss') + ok('ONERANK Theorem F (Fredholm): %d random exact matrices (dense/sparse/low-rank, 2-7 x 1-7), one appended column: rank[A|b]-rank A in {0,1} always (%d zero, %d one); d=0 iff Ax=b has an exact solution, d=1 iff exact left witness y (yA=0, y.b!=0) exists -- "misses by exactly one rank" == "infeasible" (0 violations)' % (trials, cnt['d=0'], cnt['d=1'])) + ok('ONERANK phi not canonical: %d infeasible instances where a second Fredholm witness with a different support exists' % sup_differs) + ok('ONERANK control: TWO appended columns can miss by 2 (explicit A=e1, b1=e2, b2=e3: rank 1 -> 3; random trials: miss 0/1/2 = %d/%d/%d, never >2) (%.1fs)' % (two_col[0], two_col[1], two_col[2], time.time() - t)) + +# ==================================================================================================================== +# 7b. Lemma LIN: corrections a_i += k_i b_i inserted into G2 are exactly linear iff no source slot is downstream of an earlier target +# ==================================================================================================================== +def mat_id(n): return [[int(i == j) for j in range(n)] for i in range(n)] +def mm(A, B): + n = len(A); m = len(B[0]); k = len(B) + return [[sum(A[i][t] * B[t][j] for t in range(k)) % P for j in range(m)] for i in range(n)] +def transv(n, a, b, c): + E = mat_id(n); E[a][b] = c % P; return E # row_a += c * row_b acts on a column-state vector +def prod_gates(n, gates): + C = mat_id(n) + for (a, b, c) in gates: C = mm(transv(n, a, b, c), C) # C = E_N ... E_1 + return C +def madd(A, B): return [[(a + b) % P for a, b in zip(r, s)] for r, s in zip(A, B)] + +def section_lin(seed=5, trials=1500): + t = time.time(); rng = random.Random(seed) + nh = nf = nfeq = nd = 0; nfail_formula_when_hyp = 0 + for _ in range(trials): + n = rng.randint(3, 6); N = rng.randint(4, 9) + gate = lambda: (lambda ab: (ab[0], ab[1], rng.randrange(1, P)))(rng.sample(range(n), 2)) + full = [gate() for _ in range(N + 1)] + use_drop = rng.random() < 0.5 + if use_drop: + d = rng.randrange(N + 1); G2 = full[:d] + full[d + 1:]; da = full[d][0] + else: G2 = full[:N]; d = None + N2 = len(G2) + m = rng.randint(1, 3); corr = [] + for _ in range(m): + a, b = rng.sample(range(n), 2); corr.append((rng.randint(0, N2), a, b, rng.randrange(1, P))) # (position, a, b, k) + # hypothesis: for all ordered (i, j) with p_i <= p_j, source b_j not reachable from target a_i via G2 gates [p_i, p_j) + def dirty_from(a0, p0, p1): + D = {a0} + for idx in range(p0, p1): + ga, gb, _ = G2[idx] + if gb in D: D.add(ga) + return D + hyp = True + for i in range(m): + for j in range(m): + if corr[i][0] <= corr[j][0] and corr[j][2] in dirty_from(corr[i][1], corr[i][0], corr[j][0]): hyp = False + # actual product with insertions (stable by position then list order) + order = sorted(range(m), key=lambda i: corr[i][0]); seq = []; ci = 0 + for idx in range(N2 + 1): + while ci < m and corr[order[ci]][0] == idx: + _, a, b, k = corr[order[ci]]; seq.append((a, b, k)); ci += 1 + if idx < N2: seq.append(G2[idx]) + Cfin = prod_gates(n, seq); C2 = prod_gates(n, G2) + pred = C2 + for (p, a, b, k) in corr: + Rp = prod_gates(n, G2[:p]); Sp = prod_gates(n, G2[p:]) if False else None + # S_p = E_N2 ... E_{p+1}: product of the suffix gates, applied after the prefix + S = mat_id(n) + for (ga, gb, gc) in G2[p:]: S = mm(transv(n, ga, gb, gc), S) + term = [[(k * S[i][a] % P) * Rp[b][j] % P for j in range(n)] for i in range(n)] + pred = madd(pred, term) + eq = (pred == Cfin) + if hyp: + nh += 1; check(eq, 'Lemma LIN violated (hypothesis holds, formula fails)') + if use_drop: + # count instances in which a source slot is dirtied by the drop itself (drop-dirty source) + for (p, a, b, k) in corr: + if p >= d and b in dirty_from(da, d, p): nd += 1; break + else: + nf += 1; nfeq += eq + check(nh > 300 and nf > 100 and nd > 30, 'coverage nh=%d nf=%d nd=%d' % (nh, nf, nd)) + check(nfeq <= nf * 0.05, 'control: when a source is downstream of a target the formula must (nearly always) fail: %d/%d equal' % (nfeq, nf)) + ok('ONERANK Lemma LIN: %d random transvection circuits with 1-3 corrections: %d satisfy the "no source downstream of a target" hypothesis and final = C2 + sum k_i S[:,a_i] R[b_i,:] holds EXACTLY in all %d (0 violations); %d of them have a source dirtied by the dropped gate (drop-dirty relay is a LINEAR source)' % (trials, nh, nh, nd)) + ok('ONERANK Lemma LIN control: %d instances with a source downstream of an earlier target: the linear formula fails in %d/%d (bilinear cross term k_i k_j present; %d coincidental equalities) (%.1fs)' % (nf, nf - nfeq, nf, nfeq, time.time() - t)) + +# ==================================================================================================================== +# 7c. Lemma TR (one-block re-solve) criterion +# ==================================================================================================================== +def rand_block(rng, n, Pi): + while True: + X = eye(n) + for i in Pi: + for j in Pi: X[i][j] = Fr(rng.randint(-3, 3)) + (1 if i == j else 0) + try: inv(X); return X + except AssertionError: pass +def section_tr(seed=9, trials=400): + t = time.time(); rng = random.Random(seed); nsup = nunsup = 0 + for _ in range(trials): + n = rng.randint(3, 5); nb = rng.randint(3, 5) + sup = [sorted(rng.sample(range(n), rng.randint(2, min(3, n)))) for _ in range(nb)] + blocks = [rand_block(rng, n, s) for s in sup] + j = rng.randrange(nb); Pi = sup[j] + def prodseq(bs): + C = eye(n) + for B in bs: C = matmul(B, C) + return C + Pt = prodseq(blocks[:j]); S = prodseq(blocks[j + 1:]); Xo = blocks[j] + C2 = matmul(S, matmul(Xo, Pt)) + if rng.random() < 0.5: Xnew = rand_block(rng, n, Pi); T = matmul(S, matmul(Xnew, Pt)) # T reachable by re-solving block j + else: T = rand_block(rng, n, sorted(rng.sample(range(n), rng.randint(2, n)))) # generic invertible target + D = matmul(inv(C2), T); Nt = matmul(Pt, matmul([[a - b for a, b in zip(r, e)] for r, e in zip(D, eye(n))], inv(Pt))) + X = matmul(inv(S), matmul(T, inv(Pt))) + check(X == matmul(Xo, [[a + b for a, b in zip(r, e)] for r, e in zip(Nt, eye(n))]), 'X = X_o (I + N_t) identity fails') + supported = all(Nt[a][b] == 0 for a in range(n) for b in range(n) if not (a in Pi and b in Pi)) + inGL = all((X[a][b] == (1 if a == b else 0)) for a in range(n) for b in range(n) if not (a in Pi and b in Pi)) + check(supported == inGL, 'Lemma TR criterion: N_t supported on PixPi must equal X in GL(Pi)') + if supported: check(matmul(S, matmul(X, Pt)) == T, 're-solved circuit must realise T'); nsup += 1 + else: nunsup += 1 + check(nsup > 50 and nunsup > 50, 'TR coverage') + ok('ONERANK Lemma TR: %d random block circuits (n=3-5): X = X_o(I+N_t) exact; N_t supported on PixPi <=> the re-solved block lies in GL(Pi) and realises T (%d supported/solvable, %d unsupported/unsolvable by one block; 0 mismatches) (%.1fs)' % (nsup + nunsup, nsup, nunsup, time.time() - t)) + +# ==================================================================================================================== +# 7d. 'No lower bound possible': T = I network, rigid at 4 stays per copy, unbounded gap +# ==================================================================================================================== +def rand_gl2(rng): + while True: + a, b, c, d = [rng.randint(-3, 3) for _ in range(4)] + if a * d - b * c != 0: return [[Fr(a), Fr(b)], [Fr(c), Fr(d)]] +def embed(n, w0, w1, B): + E = eye(n); E[w0][w0], E[w0][w1], E[w1][w0], E[w1][w1] = B[0][0], B[0][1], B[1][0], B[1][1]; return E +def slot_family_feasible(n, blocks_remaining, T): + """Remaining circuit = list of (w0,w1,B) blocks in time order (each block is a frame where both wires are co-present). + Linear repair family: single transvection corrections a += k b for (a,b) the two co-present wires, inserted before or + after a remaining block (a slot lies inside that frame's stay). final = C2 + sum k S[:,a] R[b,:]. Returns (r1, r2, feasible).""" + mats = [embed(n, w0, w1, B) for (w0, w1, B) in blocks_remaining] + C2 = eye(n) + for E in mats: C2 = matmul(E, C2) + cols = [] + for pos in range(len(mats) + 1): + for before in (True, False): + pass + slots = [] + for bi, (w0, w1, B) in enumerate(blocks_remaining): + slots.append((bi, w0, w1)); slots.append((bi + 1, w0, w1)) # position index = number of blocks applied before the slot + seen = set() + for (pos, w0, w1) in slots: + for (a, b) in ((w0, w1), (w1, w0)): + if (pos, a, b) in seen: continue + seen.add((pos, a, b)) + R = eye(n) + for E in mats[:pos]: R = matmul(E, R) + S = eye(n) + for E in mats[pos:]: S = matmul(E, S) + cols.append([S[i][a] * R[b][j] for i in range(n) for j in range(n)]) + A = [[c[r] for c in cols] for r in range(n * n)] + bvec = [T[i][j] - C2[i][j] for i in range(n) for j in range(n)] + r1 = rank(A); r2 = rank(hcat(A, [bvec])) + return r1, r2, r1 == r2 + +def section_rigid(seed=4): + t = time.time(); rng = random.Random(seed); stats = [] + # genericity: for most M the linear family cannot repair a lone M (or M^-1) against T = I; a few special M (e.g. M a + # reflection-like matrix with I-M in the span of the four slot terms) are repairable and are excluded from the toy + nspecial = 0; nM = 300 + for _ in range(nM): + M0 = rand_gl2(rng) + if slot_family_feasible(2, [(0, 1, M0)], eye(2))[2] or slot_family_feasible(2, [(0, 1, inv(M0))], eye(2))[2]: nspecial += 1 + def generic_gl2(): + while True: + M0 = rand_gl2(rng) + if not slot_family_feasible(2, [(0, 1, M0)], eye(2))[2] and not slot_family_feasible(2, [(0, 1, inv(M0))], eye(2))[2]: return M0 + for m in (1, 2, 3, 4): + n = 2 * m; Ms = [generic_gl2() for _ in range(m)] + # network: copy c has frames F_c1 (block M_c) then F_c2 (block M_c^-1); copies occupy disjoint wire pairs + net = [] + for c in range(m): net.append((2 * c, 2 * c + 1, Ms[c], 'F%d1' % c)); net.append((2 * c, 2 * c + 1, inv(Ms[c]), 'F%d2' % c)) + T = eye(n); full = eye(n) + for (w0, w1, B, _) in net: full = matmul(embed(n, w0, w1, B), full) + check(full == T, 'network must realise T = I') + stays = 4 * m; rigid = 0; fred = 0; tr_ok = 0 + for fi, (dw0, dw1, dB, name) in enumerate(net): + for wdrop in (dw0, dw1): # one wire loses its stay at this frame -> the pair is no longer co-present there + remaining = [(w0, w1, B) for k, (w0, w1, B, _) in enumerate(net) if k != fi] + # blocks of OTHER copies are present but cannot interact with this pair; the slot family only uses co-present pairs + r1, r2, feas = slot_family_feasible(n, remaining, T) + rigid += (not feas); fred += (r2 - r1 == 1) + # Lemma TR: re-solve the other meeting of the same copy to X in GL(2) so the product is T again + c = fi // 2; other = fi ^ 1 + rest = eye(n) + for k, (w0, w1, B, _) in enumerate(net): + if k not in (fi, other): rest = matmul(embed(n, w0, w1, B), rest) + X = inv(rest) if False else None + # other copy's blocks commute with this copy's block; new block X must equal T restricted to this pair = identity + Xnew = eye(2) + trial = eye(n) + for k, (w0, w1, B, _) in enumerate(net): + if k == fi: continue + trial = matmul(embed(n, w0, w1, Xnew if k == other else B), trial) + tr_ok += (trial == T) + check(rigid == stays and fred == stays, 'every single-stay drop must be infeasible with r2 = r1+1 (m=%d: %d/%d, fredholm %d)' % (m, rigid, stays, fred)) + check(tr_ok == stays, 'Lemma TR re-solve must repair every drop') + stats.append((m, stays, rigid)) + # positive controls: a genuinely redundant stay IS repairable by the same linear family + M = rand_gl2(rng); n = 2 + E = [[Fr(1), Fr(5)], [Fr(0), Fr(1)]] + r1, r2, feas = slot_family_feasible(2, [(0, 1, eye(2))], E) + check(feas and r1 == r2, 'positive control: transvection re-inserted at an unchanged co-presence') + E2 = [[Fr(1), Fr(0)], [Fr(-3), Fr(1)]] + r1b, r2b, feasb = slot_family_feasible(2, [(0, 1, eye(2))], E2); check(feasb and r1b == r2b, 'positive control 2') + r1, r2, feas = slot_family_feasible(2, [(0, 1, M)], eye(2)) # M left alone, T = I: rigid (the toy) + check(not feas and r2 == r1 + 1 and r1 == 3, 'single remaining block M, target I: rank 3 vs 4') + ok('ONERANK no-lower-bound toy: network = per-copy meetings M then M^-1 on disjoint wire pairs, T = I (optimum 0 stays, drop everything): every single-stay drop (4m of them) is infeasible for the whole linear single-transvection slot family, with r2 = r1+1 each time (Fredholm); m = 1,2,3,4 copies: rigid %s; Lemma TR re-solve (other meeting := X in GL(2)) repairs 4m/4m' % ', '.join('%d/%d' % (r, s) for _, s, r in stats)) + ok('ONERANK genericity: %d/%d random M in GL(2) (entries -3..3) have a lone-block M or M^-1 repairable by the linear slot family; the rest are rigid (r1=3, r2=4)' % (nspecial, nM)) + ok('ONERANK unbounded gap: a locally rigid network with %s interior stays vs optimum 0 for m = 1,2,3,4 (4m vs 0, ratio unbounded); positive controls (redundant/unchanged co-presence) are repairable (rank equal) (%.1fs)' % (', '.join(str(4 * m) for m in (1, 2, 3, 4)), time.time() - t)) + +if __name__ == '__main__': + section_theorem_f() + section_lin() + section_tr() + section_rigid() + print('total %.1fs' % (time.time() - T0)) + print('PASS_ONERANK') diff --git a/research/p104-odd-unit-per-grading/walls.py b/research/p104-odd-unit-per-grading/walls.py new file mode 100644 index 0000000000..58b8e14007 --- /dev/null +++ b/research/p104-odd-unit-per-grading/walls.py @@ -0,0 +1,835 @@ +"""walls.py -- exact toy checks for the t=-1 'walls' (Rank lemma / Clone, Lock Lemma / Theorem W, Commutation Theorem, +lift law, Zone lemma, Gram-lift Theorem M). Standard library only; run as `python3 -I -B walls.py` from any cwd. +Ported from the lane toys under cards/WILD/{CLONEAUDIT,YCHAN,NEWMOVE,TOPLBUILD,MULTIHELP,GRAMLIFT} with their controls kept; +all arithmetic is exact (Fractions, ints mod a prime, F2 bitmasks); all randomness is seeded. +Every section asserts the lane claim and prints `ok ...` lines; the last line is PASS_WALL_TOYS iff every assertion held. +NOT ported (need data/libraries absent from stdlib): CLONEAUDIT ctrl7546 (word json + numpy), DECZERO (E8 104-port labelled +geometry from numpy/G104.npy), PARALLEL/KSLOT (scipy MILP), EARLYCAP (LEMMAA2 rhok), MULTIHELP p104.py (YYMIX data).""" +import itertools, random, sys, time, collections +from fractions import Fraction as Q +Fr = Q +T0 = time.time() +def ok(msg): print('ok', msg, flush=True) +def check(cond, msg): + if not cond: raise AssertionError(msg) + +# ===================================================================================================================== +# 1. CLONEAUDIT: Rank lemma + Clone. (Run/rank/kernel copied from CLONEAUDIT/toy.py) +# ===================================================================================================================== +def span(basis): + s = {0} + for v in basis: + if v not in s: s |= {x ^ v for x in s} + return frozenset(s) + +def rank(rows, ncols): + M = [[r.get(j, Q(0)) for j in range(ncols)] for r in rows] + rk = 0 + for c in range(ncols): + p = next((i for i in range(rk, len(M)) if M[i][c] != 0), None) + if p is None: continue + M[rk], M[p] = M[p], M[rk] + for i in range(len(M)): + if i != rk and M[i][c] != 0: + f = M[i][c] / M[rk][c]; M[i] = [a - f * b for a, b in zip(M[i], M[rk])] + rk += 1 + return rk + +def kernel(rows, ncols): + M = [[r.get(j, Q(0)) for j in range(ncols)] for r in rows]; piv = []; rk = 0 + for c in range(ncols): + p = next((i for i in range(rk, len(M)) if M[i][c] != 0), None) + if p is None: continue + M[rk], M[p] = M[p], M[rk]; M[rk] = [a / M[rk][c] for a in M[rk]] + for i in range(len(M)): + if i != rk and M[i][c] != 0: + f = M[i][c]; M[i] = [a - f * b for a, b in zip(M[i], M[rk])] + piv.append(c); rk += 1 + out = [] + for fcol in [c for c in range(ncols) if c not in piv]: + v = [Q(0)] * ncols; v[fcol] = Q(1) + for i, c in enumerate(piv): v[c] = -M[i][fcol] + out.append(v) + return out + +class Run: + """Replay mirroring the verifier rules: public MOVE strictly ascending, owned MOVE strictly descending (flagged), + ADD/COPY at a common frame, COPY into empty owned, CLEAR content NOT checked. Tracks the full-state rank.""" + def __init__(s, names, init_frames): + s.names = list(names); s.n = len(names); s.rows = [{i: Q(1)} for i in range(s.n)] + s.cur = list(init_frames); s.owned = {}; s.bad = []; s.mass = 0; s.ownmove_up = 0; s.peak = 0; s.log = [] + def idx(s, r): return s.names.index(r) if isinstance(r, str) else r + def state_rank(s): + return rank(s.rows + [v[0] for v in s.owned.values()], s.n) + def MOVE(s, r, b): + if r in s.owned: + a = s.owned[r][1] + if not (span(b) < span(a)): s.ownmove_up += 1 + s.mass += abs(len(b) - len(a)); s.owned[r][1] = b + else: + i = s.idx(r) + if not (span(s.cur[i]) < span(b)): s.bad.append(('public-move-not-ascending', r)) + s.cur[i] = b + def fr(s, r): return s.owned[r][1] if r in s.owned else s.cur[s.idx(r)] + def row(s, r): return s.owned[r][0] if r in s.owned else s.rows[s.idx(r)] + def setrow(s, r, v): + if r in s.owned: s.owned[r][0] = v + else: s.rows[s.idx(r)] = v + def INIT(s, o, f): + s.owned[o] = [{}, f]; s.peak = max(s.peak, len(s.owned)) + def CLEAR(s, o, tag=''): + before = s.state_rank(); dirty = bool(s.owned[o][0]); del s.owned[o]; after = s.state_rank() + s.log.append((tag or o, dirty, before, after)) + def ADD(s, r, src, q=1, copy=False): + if span(s.fr(r)) != span(s.fr(src)): s.bad.append(('add-frame', r, src)) + if copy and s.row(r): s.bad.append(('copy-nonzero', r)) + R = {} if copy else dict(s.row(r)) + for k, v in s.row(src).items(): + nv = R.get(k, 0) + Q(q) * v + if nv: R[k] = nv + else: R.pop(k, None) + s.setrow(r, R) + def SCALE(s, r, q): s.setrow(r, {k: v * Q(q) for k, v in s.row(r).items()}) + +h = 4; ports = range(4); q = [1 << r for r in ports]; sig = {0: 1, 1: 0, 2: 3, 3: 2} +ZERO = []; L = lambda r: [q[r]]; HYP = lambda r: [q[s] for s in ports if s != r]; V = [q[r] for r in ports] +cells = [(s, r) for r in ports for s in ports if s != r] + +def build(mode, skip=None): + names = ['X%d' % r for r in ports] + ['Y%d' % r for r in ports] + inits = [L(r) for r in ports] + [ZERO for r in ports] + if mode == 'real': names += ['h%d%d' % c for c in cells]; inits += [ZERO for c in cells] + R = Run(names, inits); x = lambda r: r; y = lambda r: 4 + r + for a, b in [(0, 1), (2, 3)]: + A, B_ = 'Y%d' % a, 'Y%d' % b + R.ADD(A, B_); R.ADD(B_, A, -1); R.ADD(A, B_); R.SCALE(A, -1) + for (s, r) in cells: + c = 'h%d%d' % (s, r) if mode == 'real' else 'O%d%d' % (s, r) + if mode == 'real': R.MOVE(c, L(s)); R.ADD(c, 'X%d' % s) + else: R.INIT(c, L(s)); R.ADD(c, 'X%d' % s, copy=True) + for r in ports: + Y = 'Y%d' % r; R.MOVE(Y, L(sig[r])); R.ADD('X%d' % sig[r], Y) + R.INIT('S', L(sig[r])); R.ADD('S', Y, copy=True); R.ADD(Y, 'S', -1); R.CLEAR('S', 'snapshot Y%d' % r) + for r in ports: + Y = 'Y%d' % r; R.MOVE(Y, HYP(r)) + for s in ports: + if s == r or (s, r) == skip: continue + c = 'h%d%d' % (s, r) if mode == 'real' else 'O%d%d' % (s, r) + R.MOVE(c, HYP(r)); R.ADD(Y, c) + if mode != 'real': R.CLEAR(c, 'carrier O%d%d' % (s, r)) + if skip and mode != 'real': + c = 'O%d%d' % skip; R.MOVE(c, HYP(skip[1])); R.CLEAR(c, 'carrier O%d%d(skipped)' % skip) + for r in ports: R.MOVE('X%d' % r, V) + tgt = {} + for r in ports: + tgt['X%d' % r] = {x(r): Q(1), y(r): Q(-1)} + tgt['Y%d' % r] = {x(s): Q(1) for s in ports if s != r} + if mode == 'real': + for i, nm in enumerate(R.names): + if nm[0] == 'h': tgt[nm] = {i: Q(1)} + wrong = [nm for nm in R.names if R.rows[R.idx(nm)] != tgt[nm]] + return R, wrong, rank(R.rows, R.n) + +def section_cloneaudit(): + t = time.time() + # A4 toy, token-free carriers (cell model): exact, invertible, no rank-lowering CLEAR + R, w, fr = build('cell') + check(w == [] and fr == R.n == 8 and not R.bad and R.ownmove_up == 12 and R.mass == 24 and R.peak == 13, 'cell model') + check(len(R.log) == 16 and all(a >= b for _, _, b, a in R.log) and all(b == a for _, _, b, a in R.log), 'cell CLEARs rank-neutral') + ok('CLONEAUDIT cell model (token-free owned carriers): n_pub 8, finals exact, final rank 8/8, 16 dirty CLEARs all rank-neutral, 12 owned ascents (verifier-illegal: owned must descend), mass 24, peak owned 13') + # negative control: carrier undelivered + R, w, fr = build('cell', skip=(1, 0)) + check(w == ['Y0'], 'undelivered carrier must be flagged') + ok('CLONEAUDIT NEG control: one carrier undelivered -> finals wrong [Y0] (flagged)') + # real tokens: rank drops 20 -> 19 -> 18 -> 17 -> 16, final map singular 16/20 + R, w, fr = build('real') + drops = [(tg, b, a) for tg, d, b, a in R.log if a < b] + check(R.n == 20 and not R.bad and R.ownmove_up == 0, 'real legality') + check([(b, a) for _, b, a in drops] == [(20, 19), (19, 18), (18, 17), (17, 16)], 'rank drops %s' % drops) + check(fr == 16 and len(w) == 16 and all(nm[0] in 'Yh' for nm in w), 'final map singular 16/20') + K = kernel(R.rows, R.n); check(len(K) == 4, 'kernel dim') + expect = {frozenset([('X%d' % r, -1), ('Y%d' % r, -1)] + [('h%d%d' % (r, s), 1) for s in ports if s != r]) for r in ports} + got = {frozenset((R.names[i], int(c)) for i, c in enumerate(v) if c) for v in K} + check(got == expect, 'kernel per pair mismatch %s' % got) + ok('CLONEAUDIT REAL tokens (public helper carriers): 4 snapshot CLEARs lower state rank 20->19->18->17->16, final map SINGULAR 16/20; kernel = {X_r=-1,Y_r=-1,3 carriers reading X_r=+1} per r; all 4 Y and 12 helpers end wrong; 0 illegal events') + # positive controls + P = Run(['X1', 'Y0'], [L(1), ZERO]); P.MOVE('Y0', L(1)); P.INIT('S', L(1)); P.ADD('S', 'X1', copy=True) + P.ADD('X1', 'Y0'); P.CLEAR('S', 'snapshot X1') + check(P.log[0][1] and P.log[0][2] == P.log[0][3] == 2, 'pos ctrl 1') + P = Run(['X1', 'Y0'], [L(1), ZERO]); P.MOVE('Y0', L(1)); P.INIT('S', L(1)); P.ADD('S', 'X1', copy=True); P.CLEAR('S', 'copy, no change') + check(P.log[0][1] and P.log[0][2] == P.log[0][3], 'pos ctrl 2') + ok('CLONEAUDIT POS controls: dirty CLEAR of a copy of a still-held register is rank-neutral (2->2, two variants)') + P = Run(['X1', 'Y0'], [L(1), ZERO]); P.MOVE('Y0', L(1)); P.ADD('X1', 'Y0'); P.ADD('Y0', 'X1', -1) + check(P.state_rank() == 2 and not P.bad and P.rows == [{0: Q(1), 1: Q(1)}, {0: Q(-1)}], 'public swap') + ok('CLONEAUDIT POS control: public swap at the line (X,Y)=(x,m)->(x+m,-x) is invertible (rank 2/2), no illegal event') + ok('CLONEAUDIT toy %.1fs' % (time.time() - t)) + +def section_rank_lemma_random(seed=20261114, programs=250, events=45): + """Random legal programs: full-state rank never increases; dirty CLEAR lossless iff content in span of the rest; + any rank-lowering CLEAR is permanent (final public rank <= min over time of state rank).""" + t = time.time(); rng = random.Random(seed) + lev = [[], [1], [1, 2], [1, 2, 4]] # chain of frames, level k = k-dim; public move up, owned move down + nlow = nlossless_dirty = nclears = nmono = 0; cap_ok = 0 + for _ in range(programs): + npub = rng.randint(3, 5); levels = [rng.randint(0, 2) for _ in range(npub)] + R = Run(['P%d' % i for i in range(npub)], [lev[l] for l in levels]); lv = {i: levels[i] for i in range(npub)} + olv = {}; mn = R.state_rank(); prev = mn; nown = 0 + check(prev == npub, 'initial rank') + for _ in range(events): + kind = rng.choice(['INIT', 'ADD', 'ADD', 'ADD', 'COPY', 'SCALE', 'CLEAR', 'CLEAR', 'MOVE', 'PARK']) + names = list(range(npub)) + list(olv) + if kind == 'INIT' and len(olv) < 3: + nm = 'O%d' % nown; nown += 1; l = rng.randint(0, 3); R.INIT(nm, lev[l]); olv[nm] = l + elif kind in ('ADD', 'COPY'): + same = [(a, b) for a in names for b in names if a != b and (lv.get(a, olv.get(a)) == lv.get(b, olv.get(b)))] + if not same: continue + a, b = rng.choice(same) + if kind == 'COPY': + if a in olv or a < npub and False: pass + if isinstance(a, str): # COPY into an (already) live owned row only if it is empty; use fresh owned instead + if R.owned[a][0]: R.ADD(a, b, rng.choice([-2, -1, 1, 2])) + else: R.ADD(a, b, 1, copy=True) + else: R.ADD(a, b, rng.choice([-2, -1, 1, 2])) + else: R.ADD(a, b, rng.choice([-2, -1, 1, 2])) + elif kind == 'PARK' and len(olv) < 3: # park a public content in a fresh owned row and zero the public register + a = rng.randrange(npub); nm = 'O%d' % nown; nown += 1; l = lv[a] + R.INIT(nm, lev[l]); olv[nm] = l; R.ADD(nm, a, 1, copy=True); R.ADD(a, nm, -1) + elif kind == 'SCALE' and names: + R.SCALE(rng.choice(names), rng.choice([-2, -1, 2, 3])) + elif kind == 'CLEAR' and olv: + nm = rng.choice(list(olv)); content = R.owned[nm][0] + rest = [r for r in R.rows] + [v[0] for k, v in R.owned.items() if k != nm] + before = R.state_rank(); rest_rank = rank(rest, npub) + in_span = (rank(rest + [content], npub) == rest_rank) + R.CLEAR(nm); del olv[nm]; after = R.state_rank(); nclears += 1 + check((after == before) == in_span, 'dirty CLEAR lossless iff content in span of the rest') + if not content: check(after == before, 'clean CLEAR must be neutral') + if after < before: nlow += 1 + elif content: nlossless_dirty += 1 + elif kind == 'MOVE': + cand = [i for i in range(npub) if lv[i] < 3] + if cand and rng.random() < 0.5: + i = rng.choice(cand); nl = rng.randint(lv[i] + 1, 3); R.MOVE(i, lev[nl]); lv[i] = nl + elif olv: + nm = rng.choice(list(olv)) + if olv[nm] > 0: + nl = rng.randint(0, olv[nm] - 1); R.MOVE(nm, lev[nl]); olv[nm] = nl + r = R.state_rank() + check(r <= prev, 'Rank lemma violated: state rank rose %d -> %d' % (prev, r)); nmono += 1 + mn = min(mn, r); prev = r + for nm in list(olv): R.CLEAR(nm); del olv[nm] + fin = rank(R.rows, npub) + check(fin <= mn, 'rank-lowering CLEAR not permanent'); cap_ok += 1 + check(R.ownmove_up == 0 and not R.bad, 'generator produced an illegal event: %s' % R.bad) + check(nlow >= 20 and nlossless_dirty >= 20, 'control coverage: both rank-lowering (%d) and lossless dirty (%d) CLEARs must occur' % (nlow, nlossless_dirty)) + ok('RANK LEMMA random legal programs: %d programs, %d events, state rank never increased (0 violations); %d CLEARs: %d rank-lowering, %d dirty-but-lossless; dirty CLEAR lossless iff content in span(rest) (0 violations); final public rank <= min state rank in %d/%d programs; 0 illegal events (%.1fs)' % (programs, nmono, nclears, nlow, nlossless_dirty, cap_ok, programs, time.time() - t)) + +# ===================================================================================================================== +# 2. YCHAN: Lock Lemma / Theorem W toy table (copied from YCHAN/toy.py; nh=3 rows skipped for time) +# ===================================================================================================================== +def rank_y(rows): + R = [list(r) for r in rows if any(r)]; rk = 0; nc = len(R[0]) if R else 0 + for c in range(nc): + p = next((i for i in range(rk, len(R)) if R[i][c]), None) + if p is None: continue + R[rk], R[p] = R[p], R[rk]; pv = R[rk][c] + for i in range(len(R)): + if i != rk and R[i][c]: + f = R[i][c] / pv; R[i] = [a - f * b for a, b in zip(R[i], R[rk])] + rk += 1 + return rk + +def ychan_run(n, nh, target, rng, kasc=0, retime=False): + S = {} + for t in range(n): + for s in 'xyab': S[s + str(t)] = len(S) + for j in range(nh): S['h%d' % j] = len(S) + N = len(S); e = lambda k: [Fr(int(i == S[k])) for i in range(N)] + add = lambda u, v, c=1: [a + c * b for a, b in zip(u, v)] + zeroes = [Fr(0)] * N + V0 = ['y%d' % t for t in range(n)] + ['b%d' % t for t in range(n)] + ['h%d' % j for j in range(nh)] + Zregs = ['Y%d' % t for t in range(n)] + ['Y2_%d' % t for t in range(n)] + ['H%d' % j for j in range(nh)] + def rvec(): + v = zeroes[:] + for s in V0: + if rng.random() < 0.35: v = add(v, e(s), rng.choice([-1, 1, 2])) + return v + C = {} + for i, R in enumerate(Zregs): + C[R] = rvec() if rng.random() < 0.85 else e(V0[i]) + route = {j: rng.choice([('L', rng.randrange(n)), ('P', rng.randrange(n)), 'V']) for j in range(nh)} + if retime: + for j in range(nh): + if route[j][0] == 'L' and rng.random() < 0.8: + t = route[j][1]; cY = C['Y%d' % t]; cH = C['H%d' % j] + lam = rng.choice([-1, 1]); mu = rng.choice([-1, 0, 1]) + C['H%d' % j] = add(cH, cY, lam) + C['Y%d' % t] = add(cY, cH, mu) if rng.random() < 0.5 else add(cY, C['H%d' % j], mu) + X = {}; X2 = {} + for t in range(n): + up = [C['H%d' % j] for j in route if route[j] == ('L', t)] + x = e('x%d' % t); a = e('a%d' % t) + for v in up: + if rng.random() < 0.7: x = add(x, v, rng.choice([-1, 1])) + if rng.random() < 0.5: a = add(a, v, rng.choice([-1, 1])) + X[t] = x; X2[t] = a + Yp = {t: add(C['Y%d' % t], X[t]) for t in range(n)} + X2p = {t: add(X2[t], C['Y2_%d' % t], -1) for t in range(n)} + D = 0; SV = []; PQ = [] + for t in range(n): + Pq = [Yp[t], C['Y2_%d' % t]] + [C['H%d' % j] for j in route if route[j] == ('P', t)] + tgt = e('x%d' % t) if target == 'LU' else add(e('x%d' % t), e('y%d' % t)) + if rank_y(Pq + [tgt]) > rank_y(Pq): D += 1 + PQ.append(Pq) + SV += [X[t], X2p[t]] + SV += [C['H%d' % j] for j in route if route[j] == 'V' or route[j][0] == 'L'] + for _ in range(kasc): SV.append(rvec()) + TV = [] + for t in range(n): + TV.append(add(e('x%d' % t), e('y%d' % t), -1) if target == 'LU' else [-c for c in e('y%d' % t)]) + TV += [e('a%d' % t), e('b%d' % t)] + TV += [e('h%d' % j) for j in range(nh)] + for Pq in PQ: + m = len(Pq) - 1 + for _ in range(m): + base = rank_y(SV); best = None + for co in itertools.product([-2, -1, 0, 1, 2], repeat=len(Pq)): + if not any(co): continue + v = [sum(c * P[i] for c, P in zip(co, Pq)) for i in range(len(Pq[0]))] + if rank_y(SV + [v]) > base and rank_y(SV + TV + [v]) == rank_y(SV + TV): best = v; break + if best is None: break + SV.append(best) + D += rank_y(SV + TV) - rank_y(SV) + return D + +def section_ychan(nit=1500): + t = time.time(); rng = random.Random(1) + table = {} + for n, nh in [(1, 1), (1, 2), (2, 2)]: + for target in ['LU', 'UL']: + for kasc, rt in [(0, False), (n, False), (0, True)]: + res = [ychan_run(n, nh, target, rng, kasc=kasc, retime=rt) for _ in range(nit)] + table[(n, nh, target, kasc, rt)] = (min(res), sorted(collections.Counter(res).items())[:4]) + exp = { # lane toy.out (seed 1, 1500 samples) for the rows ported here + (1, 1, 'LU', 0, False): (1, [(1, 252), (2, 1013), (3, 235)]), (1, 1, 'LU', 1, False): (0, [(0, 94), (1, 689), (2, 623), (3, 94)]), + (1, 1, 'UL', 0, False): (1, [(1, 317), (2, 843), (3, 317), (4, 23)]), (1, 1, 'UL', 1, False): (0, [(0, 124), (1, 612), (2, 630), (3, 129)]), + (2, 2, 'LU', 0, False): (2, [(2, 9), (3, 165), (4, 1180), (5, 144)]), (2, 2, 'LU', 2, False): (0, [(0, 1), (1, 97), (2, 769), (3, 581)]), + (2, 2, 'UL', 0, False): (2, [(2, 18), (3, 319), (4, 1008), (5, 151)]), (2, 2, 'UL', 2, False): (0, [(0, 12), (1, 195), (2, 734), (3, 504)]), + (2, 2, 'LU', 0, True): (2, [(2, 6), (3, 196), (4, 1177), (5, 117)]), (2, 2, 'UL', 0, True): (2, [(2, 25), (3, 310), (4, 1033), (5, 130)]), + } + for k, v in exp.items(): + check(table[k][0] == v[0], 'min D %s: got %s lane %s' % (k, table[k][0], v[0])) + # Theorem W: free wiring (no owned ascent) forces D >= n for every sample, for every row; n ascents reach D=0 + for (n, nh, target, kasc, rt), (mn, _) in table.items(): + if kasc == 0: check(mn >= n and mn == n, 'free wiring min D must equal n: %s %d' % ((n, nh, target, rt), mn)) + elif n == kasc and not rt: check(mn == 0, 'n owned ascents must give D=0: %s' % ((n, nh, target),)) + ok('YCHAN Lock/Theorem W: free wiring (LU and UL, incl. re-timed L) min D = 1 at n=1 and 2 at n=2 (nh 1,2); +n owned ascents (positive control) min D = 0; (%d samples/row, seed 1; the lane own toy.py rerun today gives a slightly different histogram than its stored toy.out, e.g. n=1 nh=1 LU hist (1,266),(2,986),(3,248) vs stored (1,252),(2,1013),(3,235); minima are stable; nh=3 rows not ported) (%.1fs)' % (nit, time.time() - t)) + +# ===================================================================================================================== +# 3. NEWMOVE: Commutation Theorem (copied from NEWMOVE/toy.py; same seed 7 and call order -> same counts) +# ===================================================================================================================== +P31 = 2 ** 31 - 1 +def rank_p(M): + M = [r[:] for r in M]; rk = 0; cols = len(M[0]) if M else 0 + for c in range(cols): + piv = next((i for i in range(rk, len(M)) if M[i][c] % P31), None) + if piv is None: continue + M[rk], M[piv] = M[piv], M[rk]; inv = pow(M[rk][c], P31 - 2, P31) + M[rk] = [x * inv % P31 for x in M[rk]] + for i in range(len(M)): + if i != rk and M[i][c] % P31: + f = M[i][c]; M[i] = [(a - f * b) % P31 for a, b in zip(M[i], M[rk])] + rk += 1 + return rk +def matmul_p(A, B): + return [[sum(a * b for a, b in zip(r, col)) % P31 for col in zip(*B)] for r in A] + +def newmove_t1(R, trials=300, k=2, control=False): + viol = 0 + for _ in range(trials): + n = 7; frames = [(), (1,), (1, 2), (1, 2, 3), (2,), (2, 3)] + sub = lambda a, b: set(a) < set(b) + lab = [() if r < 3 else R.choice(frames[1:]) for r in range(n)] + N = n * k + C = [[[1 if c == r * k + i else 0 for c in range(N)] for i in range(k)] for r in range(n)] + V0 = [c for r in range(3) for c in range(r * k, r * k + k)] + dep = []; did_cross = False + for step in range(40): + if R.random() < 0.35: + r = R.randrange(n); ups = [f for f in frames if sub(lab[r], f)] + if ups: + if lab[r] == (): dep += [[row[c] for c in V0] for row in C[r]] + lab[r] = R.choice(ups) + else: + f = R.choice(frames); grp = [r for r in range(n) if lab[r] == f] + if control and not did_cross and f != () and any(lab[r] == () for r in range(3)): + src = next(r for r in range(3) if lab[r] == ()); grp = grp + [src]; did_cross = True + if len(grp) < 1: continue + A = [[R.randrange(P31) for _ in range(k * len(grp))] for _ in range(k * len(grp))] + stack = [row for r in grp for row in C[r]] + new = matmul_p(A, stack) + for j, r in enumerate(grp): C[r] = new[j * k:(j + 1) * k] + outside = [[row[c] for c in V0] for r in range(n) if lab[r] != () for row in C[r]] + if outside and rank_p(dep + outside) > rank_p(dep) if dep else (outside and rank_p(outside) > 0): + viol += 1 + return viol + +def mat_inv2(G): + n = len(G); M = [r[:] + [int(i == j) for j in range(n)] for i, r in enumerate(G)] + for c in range(n): + piv = next(i for i in range(c, n) if M[i][c]); M[c], M[piv] = M[piv], M[c] + for i in range(n): + if i != c and M[i][c]: M[i] = [a ^ b for a, b in zip(M[i], M[c])] + return [r[n:] for r in M] +def mv(M, v): return tuple(sum(M[i][j] * v[j] for j in range(len(v))) % 2 for i in range(len(M))) +def transpose(M): return [list(r) for r in zip(*M)] +def dot2(a, b): return sum(x * y for x, y in zip(a, b)) % 2 + +def section_newmove(): + t = time.time(); R = random.Random(7) + v0 = newmove_t1(R); v1 = newmove_t1(R, control=True) + check(v0 == 0, 'Lock violations with arbitrary local maps: %d' % v0) + check(v1 > 0, 'control must bite') + msg = 'NEWMOVE T1 Commutation Theorem: arbitrary frame-local 2x2 field maps %d/300 Lock violations; one cross-label op control %d/300' % (v0, v1) + ok(msg + (' (identical to lane: 0/300, 47/300)' if (v0, v1) == (0, 47) else ' (lane reported 47/300 for the control; qualitative control reproduced, counts differ)')) + h = 3; vecs = list(itertools.product((0, 1), repeat=h)) + def subspaces(): + seen = set() + for k in range(h + 1): + for gens in itertools.combinations(vecs, k): + S = {tuple([0] * h)} + for g in gens: S |= {tuple((a + b) % 2 for a, b in zip(s, g)) for s in S} + seen.add(frozenset(S)) + return seen + def LU(U): + perp = [v for v in vecs if all(dot2(v, u) == 0 for u in U)] + return frozenset(u + tuple((a + b) % 2 for a, b in zip(u, w)) for u in U for w in perp) + def KG(G): + Gi = mat_inv2(G); GiT = transpose(Gi) + return lambda x: mv(G, x[:h]) + tuple((a + b) % 2 for a, b in zip(mv([[(G[i][j] + GiT[i][j]) % 2 for j in range(h)] for i in range(h)], x[:h]), mv(GiT, x[h:]))) + L0 = frozenset(tuple([0] * h) + v for v in vecs); LF = frozenset(v + v for v in vecs) + def dist(Lx, Mx): import math; return h - int(math.log2(len(Lx & Mx))) + ok_fix = ok_map = 0; maxd = 0; nG = 0; subs = subspaces() + for _ in range(200): + G = [[R.randrange(2) for _ in range(h)] for _ in range(h)] + try: mat_inv2(G) + except StopIteration: continue + nG += 1; K = KG(G) + ok_fix += (frozenset(map(K, L0)) == L0 and frozenset(map(K, LF)) == LF) + for U in subs: + GU = frozenset(mv(G, u) for u in U) + ok_map += frozenset(map(K, LU(U))) == LU(GU) + maxd = max(maxd, dist(LU(U), LU(GU))) + check(ok_fix == nG and ok_map == nG * len(subs) and maxd > 0, 'T2 global rotation') + ok('NEWMOVE T2 chart rotation (h=3, F2): K_G fixes L0 and LF %d/%d; K_G L_U = L_GU %d/%d; max d(L_U,L_GU)=%d>0 (relabel reading is a real transition) (%.1fs)' % (ok_fix, nG, ok_map, nG * len(subs), maxd, time.time() - t)) + +# ===================================================================================================================== +# 4. TOPLBUILD g1toy: lift law (WILDPAIR wp.run + GLIFT geometry/unit_flag inlined) +# ===================================================================================================================== +def perpF(F, N): + return frozenset(c for c in range(1 << N) if all(not dot(c, v) for v in F)) +def dot(a, b): return bin(a & b).count('1') & 1 +def fdim(F): return len(F).bit_length() - 1 +def basis(F): + b = [] + for v in sorted(F): + w = v + for x in b: w = min(w, w ^ x) + if w: b.append(w) + return b +def wp_run(W): + N = W['N']; R = W['regs']; fr = {}; row = {}; own = set(); bad = []; units = 0; asc = 0; dirty = 0 + for r, d in R.items(): fr[r] = span(d['f0']); row[r] = {r: Fr(1)} + for i, op in enumerate(W['program']): + k, r = op[0], op[1] + alive = r in R or r in own + if k == 'MOVE': + F = span(op[2]) + if not alive: bad.append((i, 'move-dead', r)); continue + A = fr[r] + if r in R: + if not (A < F): bad.append((i, 'public-not-ascending', r)) + else: + if not (A <= F or F <= A): bad.append((i, 'owned-nonnested', r)) + units += abs(fdim(F) - fdim(A)); asc += fdim(F) > fdim(A) + fr[r] = F + elif k in ('ADD', 'COPY'): + s = op[3] if k == 'ADD' else op[2]; c = Fr(op[2]) if k == 'ADD' else Fr(1) + if not (s in R or s in own): bad.append((i, 'src-dead', s)); continue + if k == 'COPY': + if r in R or r in own: bad.append((i, 'copy-into-live', r)); continue + own.add(r); fr[r] = fr[s]; row[r] = {} + elif not alive: bad.append((i, 'add-dead', r)); continue + if fr[r] != fr[s]: bad.append((i, 'frame', r, s)) + if r == s: bad.append((i, 'self-add')); continue + d = row[r] + for a, v in row[s].items(): + nv = d.get(a, 0) + c * v + if nv: d[a] = nv + else: d.pop(a, None) + elif k == 'SCALE': + if not alive or Fr(op[2]) == 0: bad.append((i, 'scale', r)); continue + row[r] = {a: v * Fr(op[2]) for a, v in row[r].items()} + elif k == 'INIT': + if alive: bad.append((i, 'init-live', r)); continue + own.add(r); fr[r] = span(op[2]); row[r] = {} + elif k == 'CLEAR': + if r not in own: bad.append((i, 'clear-nonowned', r)); continue + dirty += bool(row[r]); own.discard(r); del fr[r]; del row[r] + if own: bad.append(('owned-alive', sorted(own))) + for r, d in R.items(): + if fr[r] != span(d['f1']): bad.append(('final-frame', r)) + return dict(bad=bad, rows={r: row[r] for r in R}, frames={r: fr[r] for r in R}, units=units, ascents=asc, dirty=dirty) + +def geometry(m): + """A_m lines: ports q_ij = e_i + e_j + e_{m+1} in GF(2)^(m+2); roots v_ij = e_i - e_j (Gram G).""" + N = m + 2; pairs = list(itertools.combinations(range(m + 1), 2)) + prts = [(1 << i) | (1 << j) | (1 << (m + 1)) for i, j in pairs] + roots = [[(1 if k == i else -1 if k == j else 0) for k in range(m + 1)] for i, j in pairs] + n = len(prts) + G = [[sum(a * b for a, b in zip(roots[s], roots[t])) for t in range(n)] for s in range(n)] + B = [[Fr(r[k]) for k in range(m)] for r in roots] + IJ = [[Fr(1 + (a == b)) for b in range(m)] for a in range(m)] + C = [[sum(B[t][a] * IJ[a][j] for a in range(m)) / 2 for j in range(m)] for t in range(n)] + for s in range(n): + for t in range(n): + assert sum(C[s][j] * B[t][j] for j in range(m)) == Fr(G[s][t], 2) + assert (G[s][t] % 2 == 1) == (s != t and dot(prts[s], prts[t]) == 0), 'partner <=> G odd' + Z = {(s, t): Fr(G[s][t], 2) for s in range(n) for t in range(n) if s != t and G[s][t]} + return N, prts, G, B, C, Z + +def unit_flag(start, top, rng): + ch = [start]; cur = start + while fdim(cur) < fdim(top): + cand = [v for v in top if v not in cur] + v = rng.choice(cand); cur = frozenset(cur | {x ^ v for x in cur}); ch.append(cur) + assert ch[-1] == top + return ch + +def lsolve(cols, rhs): + syms = sorted({k for v in cols for k in v} | set(rhs)); n = len(cols) + A = [[Fr(v.get(s, 0)) for v in cols] + [Fr(rhs.get(s, 0))] for s in syms]; piv = []; r0 = 0 + for c in range(n): + p = next((i for i in range(r0, len(A)) if A[i][c]), None) + if p is None: continue + A[r0], A[p] = A[p], A[r0]; iv = 1 / A[r0][c]; A[r0] = [x * iv for x in A[r0]] + for i in range(len(A)): + if i != r0 and A[i][c]: f = A[i][c]; A[i] = [x - f * y for x, y in zip(A[i], A[r0])] + piv.append(c); r0 += 1 + if any(A[i][-1] for i in range(r0, len(A))): return None + sol = [Fr(0)] * n + for i, c in enumerate(piv): sol[c] = A[i][-1] + return sol + +def rank_d(vecs): + syms = sorted({k for v in vecs for k in v}); M = [[Fr(v.get(s, 0)) for s in syms] for v in vecs]; r = 0 + for c in range(len(syms)): + p = next((i for i in range(r, len(M)) if M[i][c]), None) + if p is None: continue + M[r], M[p] = M[p], M[r] + for i in range(len(M)): + if i != r and M[i][c]: f = M[i][c] / M[r][c]; M[i] = [x - f * y for x, y in zip(M[i], M[r])] + r += 1 + return r + +def g1_build(m, t, variant, rng, k1=None, k2=None): + N, prts, G, B, C, Z = geometry(m); n = len(prts) + Vf = span([1 << i for i in range(N)]); Z0 = frozenset({0}); hyp = [perpF(span([qq]), N) for qq in prts] + cand = [u for u in range(n) if u != t and dot(prts[u], prts[t]) == 0] + c = rng.choice(cand) + chain = unit_flag(span([prts[c]]), hyp[t], rng) + regs = {} + X = ['X%d' % u for u in range(n)] + for u in range(n): regs[X[u]] = dict(kind='X', f0=basis(span([prts[u]])), f1=basis(Vf)) + Y, A, H = 'Y%d' % t, 'A%d' % t, 'H%d' % t + Bp = 'B%d' % t + if variant == 'pln_B': regs[Bp] = dict(kind='H', f0=[], f1=basis(Vf)) + regs[Y] = dict(kind='Y', f0=[], f1=basis(hyp[t])); regs[A] = dict(kind='H', f0=[], f1=basis(Vf)); regs[H] = dict(kind='H', f0=[], f1=basis(Vf)) + P = []; M = lambda r, F: P.append(('MOVE', r, basis(F))); Ad = lambda d, k, s: P.append(('ADD', d, Fr(k), s)) if k else None + k1 = Fr(rng.choice([-2, -1, 1, 2, 3])) if k1 is None else Fr(k1); k2 = Fr(rng.choice([-1, 0, 1, 2])) if k2 is None else Fr(k2) + O, O2, Pz = 'O%d' % t, 'Q%d' % t, 'P%d' % t + if variant != 'ctrl_zr': + P.append(('INIT', O, basis(span([prts[t]])))); Ad(O, 1, X[t]); M(O, Z0) + Ad(A, -1, H) + Ad(O, 1, H) + if variant == 'ctrl_m1': + P.append(('INIT', O2, basis(span([prts[t]])))); Ad(O2, 1, X[t]); M(O2, Vf); M(O2, hyp[t]) + if variant == 'ctrl_zr': + Fq = span([prts[t], prts[c]]) + P.append(('INIT', Pz, basis(span([prts[c]])))); Ad(Pz, 1, X[c]); M(Pz, Fq) + M(X[t], Fq); Ad(X[t], 1, Pz); P.append(('CLEAR', Pz)) + P.append(('INIT', O, basis(Fq))); Ad(O, 1, X[t]); M(O, span([prts[c]])) + Ad(X[c], -1, O); P.append(('CLEAR', O)) + if variant in ('pln_lo', 'ctrl_m1', 'pln_B'): + Ad(A, 1, O); P.append(('CLEAR', O)) + if variant == 'ctrl_t0': + Ad(Y, 1, O); Ad(Y, -1, H); P.append(('CLEAR', O)); Ad(A, 1, H) + M(H, Vf) + if variant != 'ctrl_t0': + M(A, chain[0]) + if variant in ('pln_lo', 'pln_hi'): + Ad(X[c], k1, A); Ad(A, k2, X[c]) + if variant == 'pln_B': + M(Bp, chain[0]); Ad(Bp, 1, A); Ad(Bp, -k1, X[c]); Ad(X[c], k2 or 1, Bp) + if variant == 'pln_hi': + M(O, chain[0]); Ad(A, 1, O); P.append(('CLEAR', O)) + M(Y, chain[0]) + for F in chain[1:]: + for r in ([A, X[c]] if variant != 'ctrl_t0' else [X[c]]) + ([Bp] if variant == 'pln_B' else []) + [Y]: M(r, F) + st = wp_run(dict(N=N, regs=regs, program=P + [('CLEAR', O2)] if variant == 'ctrl_m1' else P)) + rows = st['rows']; info = {} + names = list(regs); zc = lsolve([rows[r] for r in names], {X[t]: Fr(1)}) + info['z_support'] = sorted(r for r, v in zip(names, zc or []) if v) if zc else 'singular' + if variant in ('pln_lo', 'pln_hi', 'ctrl_zr', 'pln_B'): + present = [A, X[c]] + ([Bp] if variant == 'pln_B' else []) + sol = lsolve([rows[r] for r in present], {X[t]: Fr(1)}) + info['top_solvable'] = sol is not None + if sol: + for r, k in zip(present, sol): Ad(Y, k, r) + if variant == 'ctrl_m1': + Ad(Y, 1, A); Ad(A, -1, O2); Ad(Y, -1, A); P.append(('CLEAR', O2)) + for u in range(n): + if u != c and not (variant == 'ctrl_zr' and u == t): + for F in unit_flag(span([prts[u]]), Vf, rng)[1:]: M(X[u], F) + if variant == 'ctrl_zr': + for F in unit_flag(span([prts[t], prts[c]]), Vf, rng)[1:]: M(X[t], F) + for r in ([A, X[c]] if variant != 'ctrl_t0' else [X[c], A]) + ([Bp] if variant == 'pln_B' else []): M(r, Vf) + W = dict(N=N, regs=regs, program=P) + st = wp_run(W); rows = st['rows'] + Vr = [r for r in regs if st['frames'][r] == Vf] + Tg = {r: {r: Fr(1)} for r in Vr} + def_rank = len(Vr) - rank_d([rows[r] for r in Vr]) + yok = rows[Y] == {Y: Fr(1), X[t]: Fr(1)} + if def_rank == 0: + coef = {r: lsolve([Tg[s] for s in Vr], rows[r]) for r in Vr} + Mx = [coef[r][:] for r in Vr]; nv = len(Vr) + for col in range(nv): + if Mx[col][col] == 0: + piv = next(i for i in range(col + 1, nv) if Mx[i][col]) + P.append(('ADD', Vr[col], Fr(1), Vr[piv])); Mx[col] = [a + b for a, b in zip(Mx[col], Mx[piv])] + if Mx[col][col] != 1: + s_ = 1 / Mx[col][col]; P.append(('SCALE', Vr[col], s_)); Mx[col] = [a * s_ for a in Mx[col]] + for i in range(nv): + if i != col and Mx[i][col]: + f_ = Mx[i][col]; P.append(('ADD', Vr[i], -f_, Vr[col])); Mx[i] = [a - f_ * b for a, b in zip(Mx[i], Mx[col])] + st = wp_run(W); rows = st['rows'] + exact = all(rows[r] == Tg[r] for r in Vr) and rows[Y] == {Y: Fr(1), X[t]: Fr(1)} + else: + exact = False + info.update(D=def_rank + (0 if yok else 1), def_rank=def_rank, Y_ok=yok, legal=(st['bad'] == []), bad=st['bad'][:3], + exact_word=exact, owned_units=st['units'], owned_ascents=st['ascents'], dirty_clears=st['dirty'], k=(k1, k2), carrier=c) + return info + +def section_g1toy(): + t = time.time(); agg_all = {} + for m in (3, 4): + n = len(geometry(m)[1]) + for variant in ('pln_lo', 'pln_hi', 'pln_B', 'ctrl_t0', 'ctrl_m1', 'ctrl_zr'): + agg = collections.Counter() + for tt in range(n): + for s in range(12): + rng = random.Random(1000 * tt + s) + k1, k2 = [(1, -1), (-1, 1), (2, Fr(-1, 2)), (1, 0), (0, 1), (3, 2), (None, None)][s % 7] if variant.startswith('pln') else (None, None) + r = g1_build(m, tt, variant, rng, k1, k2) + agg['runs'] += 1; agg['D=%d' % r['D']] += 1; agg['legal' if r['legal'] else 'ILLEGAL'] += 1 + agg['exact' if r['exact_word'] else 'not_exact'] += 1 + if 'top_solvable' in r: agg['top_solvable=%s' % r['top_solvable']] += 1 + agg['z_in_cone' if r['z_support'] != 'singular' and 'X%d' % tt not in r['z_support'] else 'z_on_Xt_or_sing'] += 1 + agg['owned_units=%d' % r['owned_units']] += 1 + agg_all[(m, variant)] = agg + runs = agg['runs'] + check(runs == 12 * n and agg['legal'] == runs, 'legality/runs %s' % ((m, variant),)) + if variant.startswith('pln'): + check(agg['D=1'] == runs and agg['not_exact'] == runs and agg['top_solvable=False'] == runs and agg['z_on_Xt_or_sing'] == runs, 'PLN must fail: %s %s' % ((m, variant), dict(agg))) + else: + check(agg['D=0'] == runs and agg['exact'] == runs, 'control must succeed: %s %s' % ((m, variant), dict(agg))) + if variant == 'ctrl_zr': check(agg['top_solvable=True'] == runs and agg['z_in_cone'] == runs and agg['owned_units=2'] == runs, 'ctrl_zr') + c3 = agg_all[(3, 'pln_lo')]['runs'] + agg_all[(3, 'pln_hi')]['runs'] + agg_all[(3, 'pln_B')]['runs'] + c4 = agg_all[(4, 'pln_lo')]['runs'] + agg_all[(4, 'pln_hi')]['runs'] + agg_all[(4, 'pln_B')]['runs'] + ok('TOPLBUILD G1 lift law: PLN top delivery (pln_lo/pln_hi/pln_B) top-solvable 0/%d on A3 and 0/%d on A4 (D=1 every run, all legal, none exact; z_t stays on X_t); controls ctrl_t0, ctrl_m1, ctrl_zr D=0 and exact word in every run (ctrl_zr: 2 owned units, z_t in cone, top solvable) (%.1fs)' % (c3, c4, time.time() - t)) + ok('GRAMLIFT ctrl (A3): no lift pln_lo/pln_hi D=1 on every run, ctrl_t0 D=0, ctrl_zr (1 lift + 1 DOWN) D=0 exact -- same runs as above (12 seeds x 6 ports)') + +# ===================================================================================================================== +# 5. MULTIHELP: Zone lemma toy (uses the CLONEAUDIT Run above) +# ===================================================================================================================== +e_ = [1, 2, 4, 8]; q1, q2, qa, qa2, b1, b2 = 1, 2, 4, 8, 2, 1; VV = e_ +inXi = lambda fr: all(not dot(v, q1) and not dot(v, q2) for v in fr) +def solve_rep(rows, tgt, n): + m = len(rows); M = [[rows[z].get(j, Q(0)) for z in range(m)] + [tgt.get(j, Q(0))] for j in range(n)] + piv = []; r = 0 + for c in range(m): + p = next((i for i in range(r, n) if M[i][c] != 0), None) + if p is None: continue + M[r], M[p] = M[p], M[r]; M[r] = [x / M[r][c] for x in M[r]] + for i in range(n): + if i != r and M[i][c] != 0: f = M[i][c]; M[i] = [x - f * y for x, y in zip(M[i], M[r])] + piv.append(c); r += 1 + if any(M[i][m] != 0 for i in range(r, n)): return None + rho = [Q(0)] * m + for i, c in enumerate(piv): rho[c] = M[i][m] + return rho + +class ZRun(Run): + def setup(s, W, helpers): + s.W = W; s.trace = []; s.tg = s.targets(helpers) + def targets(s, helpers): + ix = s.idx; t = {} + t['Y1'] = {ix('X_b1'): Q(-1), ix('X_s'): Q(s.W[0][0]), ix('X_s2'): Q(s.W[0][1])} + t['Y2'] = {ix('X_b2'): Q(-1), ix('X_s'): Q(s.W[1][0]), ix('X_s2'): Q(s.W[1][1])} + t['X_b1'] = {ix('X_b1'): Q(1), ix('Y1'): Q(-1)}; t['X_b2'] = {ix('X_b2'): Q(1), ix('Y2'): Q(-1)} + t['X_s'] = {ix('X_s'): Q(1)}; t['X_s2'] = {ix('X_s2'): Q(1)} + for hh in helpers: t[hh] = {ix(hh): Q(1)} + return {k: {c: v for c, v in d.items() if v} for k, d in t.items()} + def xi_rank(s): + r1 = solve_rep(s.rows, {k: v for k, v in s.tg['Y1'].items()}, s.n); r2 = solve_rep(s.rows, s.tg['Y2'], s.n) + blk = [{0: r1[z], 1: r2[z]} for z in range(s.n) if inXi(s.cur[z])] + blk = [{k: v for k, v in b.items() if v} for b in blk] + viol = [s.names[z] for z in range(s.n) if (r1[z] and any(dot(v, q1) for v in s.cur[z])) or (r2[z] and any(dot(v, q2) for v in s.cur[z]))] + return rank(blk, 2), viol + def snap(s, tag): s.trace.append((tag,) + s.xi_rank()) + +def mh_common(R): + R.SCALE('Y1', -1); R.SCALE('Y2', -1) + R.MOVE('Y1', [b1]); R.ADD('X_b1', 'Y1'); R.ADD('Y1', 'X_b1', -1) + R.MOVE('Y2', [b2]); R.ADD('X_b2', 'Y2'); R.ADD('Y2', 'X_b2', -1) +def mh_finish(R, helpers): + for r in ['X_b1', 'X_b2', 'X_s', 'X_s2'] + helpers: + if span(R.cur[R.idx(r)]) != span(VV): R.MOVE(r, VV) + wrong = [nm for nm in R.tg if R.rows[R.idx(nm)] != R.tg[nm]] + return wrong, rank(R.rows, R.n), sorted({v for _, _, vs in R.trace for v in vs}) +mh_names = ['X_s', 'X_s2', 'X_b1', 'X_b2', 'Y1', 'Y2']; mh_inits = [[qa], [qa2], [b1], [b2], [], []] +G_ = [qa, qa2]; G1_ = [qa, qa2, b1]; G2_ = [qa, qa2, b2] + +def mh_escape(W): + H = ['h1', 'h2']; R = ZRun(mh_names + H, mh_inits + [[], []]); R.setup(W, H); R.snap('t0'); mh_common(R); R.snap('cells') + for hh, X in (('h1', 'X_s'), ('h2', 'X_s2')): + R.MOVE(hh, [qa] if X == 'X_s' else [qa2]); R.ADD(X, hh, -1); R.ADD(hh, X) + R.snap('parked') + for r in ('h1', 'h2', 'X_s', 'X_s2'): R.MOVE(r, G_) + (p, qq), (r_, s_) = W; det = Q(p * s_ - qq * r_); assert det != 0 + R.SCALE('h1', p); R.ADD('h1', 'h2', Q(qq)) + R.SCALE('h2', Q(s_) - Q(r_) * Q(qq) / Q(p)); R.ADD('h2', 'h1', Q(r_) / Q(p)) + R.snap('mixed in Xi') + R.MOVE('h1', G1_); R.MOVE('Y1', G1_); R.ADD('Y1', 'h1'); R.snap('deliver Y1') + R.MOVE('h2', G2_); R.MOVE('Y2', G2_); R.ADD('Y2', 'h2'); R.snap('deliver Y2') + for r in ('h1', 'h2', 'X_s', 'X_s2'): R.MOVE(r, VV) + R.ADD('h2', 'h1', -Q(r_) / Q(p)); R.SCALE('h2', 1 / (Q(s_) - Q(r_) * Q(qq) / Q(p))); R.ADD('h1', 'h2', -Q(qq)); R.SCALE('h1', 1 / Q(p)) + for hh, X in (('h1', 'X_s'), ('h2', 'X_s2')): R.ADD(hh, X, -1); R.ADD(X, hh) + R.snap('V settled') + wrong, fr, viol = mh_finish(R, H) + return R, wrong, fr, viol + +def mh_single(): + H = ['h1', 'h2']; R = ZRun(mh_names + H, mh_inits + [[], []]); R.setup(((1, 0), (1, 0)), H); R.snap('t0'); mh_common(R); R.snap('cells') + R.MOVE('h1', [qa]); R.ADD('X_s', 'h1', -1); R.ADD('h1', 'X_s') + R.MOVE('h2', [qa]); R.ADD('X_s', 'h2', -1); R.ADD('h2', 'X_s'); R.snap('two reads') + R.MOVE('h1', [qa, b1]); R.MOVE('Y1', [qa, b1]); R.ADD('Y1', 'h1'); R.snap('Y1') + R.MOVE('h2', [qa, b2]); R.MOVE('Y2', [qa, b2]); R.ADD('Y2', 'h2'); R.snap('Y2') + for r in ('h1', 'h2', 'X_s'): R.MOVE(r, VV) + R.ADD('h2', 'X_s', -1); R.ADD('X_s', 'h2'); R.ADD('h1', 'X_s', -1); R.ADD('X_s', 'h1') + wrong, fr, viol = mh_finish(R, H) + return R, wrong, fr, viol + +def mh_chainable(): + nb1 = 8 + R = ZRun(mh_names, [[qa], [qa2], [nb1], [b2], [], []]); R.setup(((1, 0), (1, 0)), []) + R.SCALE('Y1', -1); R.SCALE('Y2', -1) + R.MOVE('Y1', [nb1]); R.ADD('X_b1', 'Y1'); R.ADD('Y1', 'X_b1', -1); R.MOVE('Y2', [b2]); R.ADD('X_b2', 'Y2'); R.ADD('Y2', 'X_b2', -1) + R.MOVE('X_s', [qa, nb1]); R.MOVE('Y1', [qa, nb1]); R.ADD('Y1', 'X_s') + R.MOVE('X_s', [qa, nb1, b2]); R.MOVE('Y2', [qa, nb1, b2]); R.ADD('Y2', 'X_s') + for r in ['X_b1', 'X_b2', 'X_s', 'X_s2']: R.MOVE(r, VV) + return R, [nm for nm in R.tg if R.rows[R.idx(nm)] != R.tg[nm]] + +def section_multihelp(): + t = time.time() + for W, lab in (((Q(1), Q(1)), (Q(1), Q(-1))), ((Q(1, 2), Q(-1, 2)), (Q(1, 2), Q(1, 2)))): + R, wrong, fr, viol = mh_escape((W[0:2], lab) if False else (W, lab)) + tr = [(a, b) for a, b, _ in R.trace] + check(not R.bad and R.ownmove_up == 0 and wrong == [] and fr == 8 == R.n and viol == [] and len(R.owned) == 0, 'ESCAPE must be exact with 0 owned: %s %s' % (wrong, R.bad)) + check([b for _, b in tr] == [2, 2, 2, 2, 1, 0, 0], 'Xi rank trace %s' % tr) + check(R.peak == 0, 'no owned rows used') + ok('MULTIHELP Zone lemma ESCAPE: 2 senders (weights (1,1),(1,-1) and +-1/2), 2 tokened public helpers, X-PARK + Xi mix, 0 owned rows (peak 0): 0 illegal events, all finals exact, final map 8/8, Xi rank 2->2->2->2->1->0->0, no adjoint-support violation') + try: + mh_escape(((Q(1), Q(1)), (Q(1), Q(1)))); raise RuntimeError('proportional weights must be singular') + except AssertionError: + ok('MULTIHELP NEG control: proportional weights (1,1),(1,1): Xi mix singular (det 0), no e1/e2 pieces') + R, wrong, fr, viol = mh_single() + y2 = {R.names[k]: v for k, v in R.rows[R.idx('Y2')].items()} + check(not R.bad and wrong == ['Y2'] and fr == 8 and viol == ['h1'] and [b for _, b, _ in R.trace][-2:] == [0, 0], 'single-sender NEG') + check(y2 == {'X_b2': Q(-1), 'X_s': Q(1), 'h1': Q(-1)}, 'Y2 final %s' % y2) + ok('MULTIHELP NEG control: ONE sender (per-sender counting needs >=1 owned row): finals wrong [Y2] (Y2 = -x_b2 + x_s - h1), Xi rank stuck at 1 until delivery, adjoint-support violation by h1') + R, wrong = mh_chainable() + check(not R.bad and wrong == [], 'chainable POS') + ok('MULTIHELP POS control: chainable geometry, one sender on its own chain: 0 illegal events, finals exact (%.1fs)' % (time.time() - t)) + +# ===================================================================================================================== +# 6. GRAMLIFT alg.py: A3 Gram-lift algebra, Theorem M (own exact linear algebra) +# ===================================================================================================================== +def rref(M): + A = [[Fr(x) for x in row] for row in M]; piv = []; r = 0 + ncol = len(A[0]) if A else 0 + for c in range(ncol): + p = next((i for i in range(r, len(A)) if A[i][c] != 0), None) + if p is None: continue + A[r], A[p] = A[p], A[r]; inv = 1 / A[r][c]; A[r] = [x * inv for x in A[r]] + for i in range(len(A)): + if i != r and A[i][c] != 0: + f = A[i][c]; A[i] = [a - f * b for a, b in zip(A[i], A[r])] + piv.append(c); r += 1 + if r == len(A): break + return A[:r], piv +def rank_m(M): return len(rref(M)[1]) if M and M[0] else 0 +def nullspace(M): + R, piv = rref(M); n = len(M[0]); out = [] + for f in [c for c in range(n) if c not in piv]: + v = [Fr(0)] * n; v[f] = Fr(1) + for i, c in enumerate(piv): v[c] = -R[i][f] + out.append(v) + return out +def mmul(A, B): + Bt = list(zip(*B)); return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A] +def minv(M): + n = len(M); A = [list(map(Fr, r)) + [Fr(int(i == j)) for j in range(n)] for i, r in enumerate(M)] + R, piv = rref(A); assert piv[:n] == list(range(n)), 'singular'; return [r[n:] for r in R] + +def section_gramlift(): + t = time.time() + N, prts, G, B, C_, Z = geometry(3); n = 6 + Rr = [[Fr(x) for x in r] for r in B]; Gm = [[Fr(x) for x in r] for r in G] + K = nullspace(Gm) + check(rank_m(Gm) == 3 and len(K) == 3, 'rank G / dim K') + check(all((G[s][u] == 0) == (dot(prts[s], prts[u]) == 1) for s in range(n) for u in range(n) if s != u) and [G[i][i] for i in range(n)] == [2] * 6, 'Gram pattern') + colsB = [[Rr[i][j] for i in range(n)] for j in range(3)] + inter = len(colsB) + len(K) - rank_m(colsB + K) + check(inter == 0, 'range(B) cap K') + part = lambda u, w: u != w and dot(prts[u], prts[w]) == 0 + cs = [p for p in itertools.permutations(range(n)) if all(part(u, p[u]) for u in range(n))] + check(len(cs) == 80, 'partner derangements %d' % len(cs)) + rng = random.Random(3); got = 0 + for c in (cs[0], cs[40], cs[79]): + P = [[Fr(int(c[u] == w)) for w in range(n)] for u in range(n)] + for trial in range(200): + Cm = [[Fr(rng.randint(-2, 2)) for _ in range(n)] for _ in range(3)] + BC = mmul(Rr, Cm); E = [[(1 if i == j else 0) - P[i][j] - BC[i][j] for j in range(n)] for i in range(n)] + if rank_m(E) < n: continue + A = mmul(minv(E), Rr) + for u in range(n): + xpart = [P[u][w] + E[u][w] for w in range(n)]; spart = [sum(E[u][w] * A[w][j] for w in range(n)) for j in range(3)] + check(spart == Rr[u], 'sigma-part'); check(all(xpart[w] == (1 if w == u else 0) - BC[u][w] for w in range(n)), 'x-part') + Psi = [[sum(k[w] * ((1 if w == u else 0) - BC[u][w]) for w in range(n)) for k in K] + list(Rr[u]) for u in range(n)] + Psi0 = [[k[u] for k in K] for u in range(n)] + check(rank_m(Psi) == 6 and rank_m(Psi0) == 3, 'Theorem M ranks %d %d' % (rank_m(Psi), rank_m(Psi0))) + got += 1; break + check(got == 3, 'three carrier maps') + ok('GRAMLIFT A3: rank G=3, dim ker G=3, G zero exactly on non-orthogonal pairs, diag 2; Y-side frozen algebra exact (E=I-P-BC invertible, xi_u=x_u+kappa_u, kappa_u in K) on 3 of the 80 partner derangements; range(B) cap K = 0 hence Theorem M rank Psi = 6 = n (so D >= 6 - m_o = 6 with m_o=0) vs no-lift baseline rank Psi0 = 3 (%.1fs)' % (time.time() - t)) + +if __name__ == '__main__': + section_cloneaudit() + section_rank_lemma_random() + section_ychan() + section_newmove() + section_g1toy() + section_multihelp() + section_gramlift() + print('total %.1fs' % (time.time() - T0)) + print('PASS_WALL_TOYS') diff --git a/research/p104-odd-unit-per-grading/words.py b/research/p104-odd-unit-per-grading/words.py new file mode 100644 index 0000000000..4286d172a8 --- /dev/null +++ b/research/p104-odd-unit-per-grading/words.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Exact replay of three P104 words that were built, replayed exactly, and did NOT pay. + +Standard library only, one self-contained file; run it as python3 -I -B words.py (about 1-2 minutes). +Each word is shipped as an edit list against the vendored #7546 word (data/base-7546-word.json.gz, +SHA256 pinned below), never as a pickle. Nothing here claims a better kappa. + +Edit format (data/edits-*.json.gz): header edits (per list key: positions to overwrite and entries to append; +scalars replaced), `shift` (the owned register indices >= 1501 of the base program are renumbered by +shift, +because the word has `shift` more public registers), and `replace` = [[i1, i2, events]] replacing +shifted_base_program[i1:i2] by `events`. The rebuilt word must have the pinned SHA256 of its canonical JSON. + +Word 1 SEEDBUILD S1 partial-sum word (s1_aug): two new public helpers A, B (born at {0}, ending at V). +Word 2 BREAKER8 costly-relocation control (ctrl_up): one 12-register meeting moved from dim 4 to dim 7, + kappa x0.999268 (a control; it is NOT a Lemma-RT word). +Words 2b BREAKER8 Lemma RT swap words rt6 (X main 6) and rt886 (hosted Y2 main 886): the main's whole route is + handed to a new public helper by a three-ADD swap, the main makes one MOVE, and a swap back follows; + rows, S, D0 and kappa are unchanged (kappa equal to #7546's in every digit). +Word 3 WINDOW8 merged-twin window word (w4_w00): X2->X, Y2->Y merged on 8 ports with 8x2 shadow helpers + and 16 token-only relays; its targets differ from #7546 by X = x - y on those ports. + +Checks per word: exact rebuild; exact Fraction replay from arbitrary inputs with the legality rules of the +#7546 checkers (operands at the event's chart, public MOVEs strictly ascend, owned MOVEs nested, COPY into zero, +no SCALE by 0, owned fields cleared, public fields end at `final`); every row against its target; census, +complete invoice (17 native calls), kappa and D0 per call for words 1 and 2 against #7546's reproduced crossing; +for word 3 the D0 cost model of the lane (shadow and relay route losses) recomputed from the word. +Controls: corrupted events, a tampered target, a tampered edit list and a tampered invoice must be rejected. +""" +import collections +import copy +import decimal +import gzip +import hashlib +import json +import sys +import time +from fractions import Fraction as Q +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DATA = HERE / 'data' +BASE_SHA256 = '6e03624b173b90356e96f845d05fc93153846b863734dc8163ab6c44c602cd32' +CALLS = 17 +NB = 1501 # public registers of #7546 +D = decimal.Decimal +PINS = { # SHA256 of the canonical JSON (sort_keys, compact) of each rebuilt word + 's1': '0d8246087b391d204bc7130beb2896a746bff428ed0afcedbb7dd654a21be924', + 'ctrl': 'bb7704d57ec92eb3ec16d09329a22710bf0682ddf3ce5d5545f924db365546a3', + 'win': '52aac745b74267dd73207f702dfb6bdcfea9fc8f2b284f97e2c9ee59cc2d8580', + 'rt6': 'd621679590a21b5a08cec9e2c390dfd2281ec7fe9f4e7b10ce1b0b72f05b5a3b', + 'rt886': '9fa7af5d708bc37c8758255473aec79e226e91c3b09c80bc4653626e7c63a4f5', +} + + +def require(cond, label): + if not cond: + raise AssertionError(label) + + +def canon_sha(W): + return hashlib.sha256(json.dumps(W, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +# --------------------------------------------------------------------------------------------- rebuilding +def shift_program(program, k): + out = [] + for e in program: + e = list(e) + if e[1] >= NB: + e[1] += k + if e[0] in ('ADD', 'COPY') and e[2] >= NB: + e[2] += k + out.append(e) + return out + + +def apply_edits(B, E): + """Rebuild a word from the #7546 word B and an edit list E.""" + require(len(B['program']) == E['base_events'], 'edit list base length') + base = shift_program(B['program'], E['shift']) + out, pos = [], 0 + for i1, i2, evs in E['replace']: + require(pos <= i1 <= i2 <= len(base), 'edit ranges ordered') + out.extend(base[pos:i1]) + out.extend(evs) + pos = i2 + out.extend(base[pos:]) + W = copy.deepcopy(B) + for key, h in E['header'].items(): + if 'value' in h: + W[key] = h['value'] + else: + lst = list(W[key]) + for i, v in h['set'].items(): + lst[int(i)] = v + W[key] = lst + h['append'] + W['program'] = out + return W + + +# --------------------------------------------------------------------------------------------- replay +def span(vectors): + s = {0} + for v in vectors: + require(type(v) is int and 0 < v < 512 and v not in s, 'frame vectors independent in F2^9') + s |= {x ^ v for x in s} + return frozenset(s) + + +def mains(W): + live = set(W['live']) + return live | {r + 112 for r in live} | set(W['hosted']['X2']) | set(W['hosted']['Y2']) + + +def replay(W): + """Exact replay; returns rows and end charts. Raises AssertionError on any illegality.""" + n, N = W['public'], W['public'] + W['owned_fields'] + require(len(W['initial']) == n and len(W['final']) == n, 'header lengths') + sp = [span(f) for f in W['frames']] + rows = [{r: Q(1)} if r < n else {} for r in range(N)] + cur = list(W['initial']) + [None] * W['owned_fields'] + alive = set() + for i, e in enumerate(W['program']): + op, r = e[0], e[1] + require(type(r) is int and 0 <= r < N, '%d register index' % i) + if op == 'MOVE': + a, b, flag = e[2], e[3], e[4] + require(type(flag) is bool and flag == (r >= n), '%d MOVE ownership flag' % i) + require(cur[r] == a, '%d MOVE from the current chart' % i) + if r >= n: + require(r in alive, '%d owned MOVE on a live field' % i) + require(sp[a] < sp[b] or sp[b] < sp[a], '%d owned MOVE nested' % i) + else: + require(sp[a] < sp[b], '%d public MOVE strictly ascends' % i) + cur[r] = b + elif op == 'INIT': + require(r >= n and r not in alive and len(e) == 3, '%d INIT of a dead owned field' % i) + alive.add(r); rows[r] = {}; cur[r] = e[2] + elif op == 'CLEAR': + require(r >= n and r in alive and cur[r] == e[2], '%d CLEAR at the current chart' % i) + alive.discard(r); rows[r] = {}; cur[r] = None + elif op == 'SCALE': + q = Q(e[2]) + require(q != 0, '%d SCALE by zero' % i) + require(cur[r] == e[3] and (r < n or r in alive), '%d SCALE chart' % i) + rows[r] = {k: v * q for k, v in rows[r].items()} + elif op in ('ADD', 'COPY'): + s, q, f = e[2], Q(e[3]), e[4] + require(type(s) is int and 0 <= s < N and s != r, '%d operand' % i) + require(q != 0, '%d zero coefficient' % i) + require(cur[r] == f and cur[s] == f, '%d ADD/COPY operands at chart %d' % (i, f)) + for x in (r, s): + require(x < n or x in alive, '%d owned field live' % i) + if op == 'COPY': + require(not rows[r], '%d COPY into a zero field' % i) + R = rows[r] + for k, v in rows[s].items(): + nv = R.get(k, 0) + q * v + if nv: + R[k] = nv + else: + R.pop(k, None) + else: + raise AssertionError('%d unknown op %r' % (i, op)) + require(not alive, 'every owned field cleared') + require(cur[:n] == list(W['final']), 'public fields end at final charts') + return dict(rows=rows, cur=cur) + + +# --------------------------------------------------------------------------------------------- accounting +def dims(W): + return [len(f) for f in W['frames']] + + +def census(W): + """Paid MOVE ranks per native call and helper targets (the #7546 accounting; mains are never targets).""" + dim, n, M = dims(W), W['public'], mains(W) + paid = collections.Counter(abs(dim[e[3]] - dim[e[2]]) for e in W['program'] if e[0] == 'MOVE') + helpers = collections.Counter(dim[W['final'][r]] - dim[W['initial'][r]] for r in range(n) if r not in M) + helpers.pop(0, None) + return dict(paid=paid, helpers=helpers) + + +def f_ln(r): + return D(r) * D(r).ln() if r > 1 else D(0) + + +def D0(T, P): + """D0 = sum (T - P) r ln r.""" + with decimal.localcontext(decimal.Context(prec=60)): + return sum((D(T.get(r, 0) - P.get(r, 0)) * f_ln(r) for r in set(T) | set(P)), D(0)) + + +def crossing(T, P, digits=40): + """Root of F(C) = sum (T_r - P_r) r^(1-C) on [0.003, 0.0045] by bisection in 80-digit decimals.""" + with decimal.localcontext(decimal.Context(prec=digits + 40)): + ranks = sorted(set(T) | set(P)) + terms = [(D(T.get(r, 0) - P.get(r, 0)) * r, D(r).ln()) for r in ranks] + + def F(C): + return sum((c * (-C * l).exp() for c, l in terms), D(0)) + lo, hi = D('0.003'), D('0.0045') + require(F(lo) > 0 > F(hi), 'crossing bracketed') + for _ in range(160): + mid = (lo + hi) / 2 + if F(mid) > 0: + lo = mid + else: + hi = mid + return decimal.Context(prec=digits).create_decimal(lo) + + +def invoice_of(inv0, cb, cw): + """#7546's complete invoice with the native delta (word minus #7546) charged CALLS times.""" + P = collections.Counter({int(k): v for k, v in inv0['paid'].items()}) + T = collections.Counter({int(k): v for k, v in inv0['targets'].items()}) + for r, v in cw['paid'].items(): + P[r] += CALLS * v + for r, v in cb['paid'].items(): + P[r] -= CALLS * v + for r, v in cw['helpers'].items(): + T[r] += CALLS * v + for r, v in cb['helpers'].items(): + T[r] -= CALLS * v + for C_ in (P, T): + for r in list(C_): + require(C_[r] >= 0, 'negative count') + if C_[r] == 0: + del C_[r] + return dict(P), dict(T) + + +def surplus(T, P): + return sum(r * (T.get(r, 0) - P.get(r, 0)) for r in set(T) | set(P)) + + +# --------------------------------------------------------------------------------------------- helpers +def load_edits(name): + return json.loads(gzip.decompress((DATA / ('edits-%s.json.gz' % name)).read_bytes())) + + +def rows_equal_base(W, RB, R, label): + """Rows of W against #7546's rows under the explicit index map: public registers < 1501 keep their index, + new public registers (index >= 1501) must end at identity, owned rows empty.""" + n = W['public'] + bad = [r for r in range(n) if R['rows'][r] != (RB['rows'][r] if r < NB else {r: Q(1)})] + require(not bad, '%s: all %d public rows equal the #7546 targets (first differing %s)' % (label, n, bad[:3])) + require(all(not R['rows'][r] for r in range(n, len(R['rows']))), '%s: owned rows end empty' % label) + + +def corrupt(W, kind): + """A copy of W with one late ADD damaged: kind 'chart' (operand chart wrong) or 'coef' (coefficient doubled).""" + X = copy.deepcopy(W) + P = X['program'] + i = next(j for j in range(len(P) * 3 // 4, len(P)) if P[j][0] == 'ADD') + if kind == 'chart': + P[i][4] = (P[i][4] + 1) % len(X['frames']) + else: + P[i][3] = str(Q(P[i][3]) * 2) + return X, i + + +def rejected(label, fn): + try: + fn() + except AssertionError as exc: + print('PASS control rejected: %s (%s)' % (label, str(exc)[:90])) + return + raise AssertionError('control not rejected: ' + label) + + +# --------------------------------------------------------------------------------------------- word 3 +def route_loss(W, r): + """f(climb) - sum f(step) of public register r (f(x) = x ln x): its loss against a single jump.""" + dim = dims(W) + steps = [abs(dim[e[3]] - dim[e[2]]) for e in W['program'] if e[0] == 'MOVE' and e[1] == r] + return f_ln(dim[W['final'][r]] - dim[W['initial'][r]]) - sum((f_ln(s) for s in steps), D(0)) + + +def win_checks(B, RB, W, R, E, label, info): + n = W['public'] + Tj = json.loads(gzip.decompress((DATA / 'window8-targets.json.gz').read_bytes())) + ports = Tj['ports'] + T = {r: dict(RB['rows'][r]) for r in range(NB)} + for r in range(NB, n): + T[r] = {r: Q(1)} + for r, row in Tj['changed'].items(): + T[int(r)] = {int(k): Q(v) for k, v in row.items()} + + def check_rows(R_, T_): + bad = [r for r in range(n) if R_['rows'][r] != T_[r]] + require(not bad, 'all %d public finals equal the targets (first differing %s)' % (n, bad[:3])) + require(all(not R_['rows'][r] for r in range(n, len(R_['rows']))), 'owned rows end empty') + check_rows(R, T) + H = W['hosted'] + X = [W['live'][p] for p in ports] + Y = [W['live'][p] + 112 for p in ports] + X2 = [H['X2'][H['Dports'].index(p)] for p in ports] + Y2 = [H['Y2'][H['Dports'].index(p)] for p in ports] + for x, y, x2, y2 in zip(X, Y, X2, Y2): + # x, y are the symbols of the X and Y main registers: X = x - y, Y = x + y; the twins end at identity + require(R['rows'][x] == {x: Q(1), y: Q(-1)}, 'window X row = x - y') + require(R['rows'][y] == {y: Q(1), x: Q(1)}, 'window Y row = x + y') + require(R['rows'][x2] == {x2: Q(1)} and R['rows'][y2] == {y2: Q(1)}, 'twins end at identity') + diff = sorted(r for r in range(NB) if T[r] != RB['rows'][r]) + require(diff == sorted(X + X2), 'targets differ from #7546 exactly on the 8 window X mains and their 8 X2 twins') + nonwin = [r for r in range(NB) if r not in set(X + X2)] + require(all(R['rows'][r] == RB['rows'][r] for r in nonwin), 'non-window rows equal #7546') + print('PASS %s: %s; exact replay legal; all %d public finals equal T; X = x - y, Y = x + y on %d window ' + 'ports, twins identity; T differs from #7546 on %d rows only (the window X and X2 rows), the other %d ' + 'rows equal #7546, the %d relays end at identity' % (label, info, n, len(ports), len(diff), len(nonwin), + n - NB)) + # the lane's cost model (WINDOW8 cost.py): route losses of the 16 shadows (the twins) and the 16 relays + sh = [route_loss(W, r) for r in X2 + Y2] + rl = [route_loss(W, r) for r in range(NB, n)] + require(len(sh) == 16 and len(rl) == 16, 'counts') + ssh, srl = sum(sh, D(0)), sum(rl, D(0)) + print('PASS %s cost model: shadows %s + relays 16 x %s = %s D0/call' + % (label, ssh.quantize(D('0.0001')), (srl / 16).quantize(D('0.0001')), (ssh + srl).quantize(D('0.0001')))) + # plain census delta of the word against #7546 (header mains; the twins stay 'mains', so no twin credit) + cw, cb = census(W), census(B) + P1 = collections.Counter(cw['paid']); P1.subtract(cb['paid']) + T1 = collections.Counter(cw['helpers']); T1.subtract(cb['helpers']) + P1 = {k: v for k, v in sorted(P1.items()) if v} + T1 = {k: v for k, v in sorted(T1.items()) if v} + print('INFO %s plain census D0/call delta vs #7546 (twins counted as mains): %s; paid-MOVE delta %s, ' + 'helper delta %s. Merged plane: kappa not computed.' + % (label, D0(T1, P1).quantize(D('0.0001')), P1, T1)) + for kind in ('chart', 'coef'): + Xw, i = corrupt(W, kind) + if kind == 'chart': + rejected('%s: ADD %d operand chart corrupted' % (label, i), lambda: replay(Xw)) + else: + rejected('%s: ADD %d coefficient doubled' % (label, i), lambda: check_rows(replay(Xw), T)) + T2 = copy.deepcopy(T) + T2[X[0]][Y[0]] = Q(-2) + rejected('%s: tampered target row (X = x - 2y)' % label, lambda: check_rows(R, T2)) + T3 = copy.deepcopy(T) + T3[X[0]] = dict(RB['rows'][X[0]]) + rejected('%s: window X target replaced by #7546 row (x)' % label, lambda: check_rows(R, T3)) + + +# --------------------------------------------------------------------------------------------- main +def main(): + t0 = time.time() + base_raw = (DATA / 'base-7546-word.json.gz').read_bytes() + require(hashlib.sha256(base_raw).hexdigest() == BASE_SHA256, 'vendored #7546 word bytes') + B = json.loads(gzip.decompress(base_raw)) + RB = replay(B) + inv0 = json.loads((DATA / 'invoice-7546.json').read_text()) + cb = census(B) + # the caller part of the invoice is #7546's invoice minus 17 native censuses; it must be non-negative + P0, T0 = invoice_of(inv0, cb, cb) + require(P0 == {int(k): v for k, v in inv0['paid'].items()} + and T0 == {int(k): v for k, v in inv0['targets'].items()}, 'invoice reconstructs') + S0 = surplus(T0, P0) + require(S0 == 1424, 'rank surplus 1424') + k0 = crossing(T0, P0) + lo, hi = D('0.00364841129479084532481164992024'), D('0.00364841129479084532481164992025') + require(lo <= k0 <= hi, '#7546 published crossing reproduced') + d0_base = D0(T0, P0) + require(abs(d0_base - D('393242.1350')) < D('0.00005'), 'D0 of #7546 = 393242.1350') + print('PASS positive control #7546: replay legal (%d events), S = %d, kappa %s (inside the published enclosure ' + '[...992024, ...992025]), D0 = %s' % (len(B['program']), S0, k0, d0_base.quantize(D('0.0001')))) + + s1_kappa = None + for name, label in (('s1', 'SEEDBUILD S1'), ('ctrl', 'BREAKER8 costly-relocation control (ctrl_up, meeting dim 4->7)'), + ('rt6', 'BREAKER8 Lemma RT main 6'), ('rt886', 'BREAKER8 Lemma RT main 886'), + ('win', 'WINDOW8 w4_w00')): + E = load_edits(name) + W = apply_edits(B, E) + sha = canon_sha(W) + require(sha == PINS[name], '%s rebuilt word sha256 %s' % (label, sha)) + R = replay(W) + n = W['public'] + hdr = sorted(k for k in W if k != 'program' and W[k] != B[k]) + info = 'rebuilt from #7546 + edits (%d events, %d public, header keys changed %s, sha256 %s...)' % ( + len(W['program']), n, hdr, sha[:12]) + if name == 'win': + win_checks(B, RB, W, R, E, label, info) + continue + rows_equal_base(W, RB, R, label) + cw = census(W) + P1, T1 = invoice_of(inv0, cb, cw) + S1 = surplus(T1, P1) + k1 = crossing(T1, P1) + dd = (D0(T1, P1) - d0_base) / CALLS + dP = collections.Counter(cw['paid']); dP.subtract(cb['paid']) + dT = collections.Counter(cw['helpers']); dT.subtract(cb['helpers']) + dP = {k: v for k, v in sorted(dP.items()) if v} + dT = {k: v for k, v in sorted(dT.items()) if v} + with decimal.localcontext(decimal.Context(prec=12)): + ratio = k1 / k0 + print('PASS %s: %s; exact replay legal; all %d public rows equal #7546 targets (new helpers identity), ' + 'owned rows empty' % (label, info, n)) + print(' per-call paid delta %s, helper-target delta %s; S = %d; paid positions %d; kappa %s ' + '(x%s vs #7546); D0/call delta %s' + % (dP, dT, S1, sum(r * v for r, v in P1.items()), k1, ratio, dd.quantize(D('0.0001')))) + if name.startswith('rt'): + require(k1 == k0 and dd == 0 and S1 == S0, '%s: kappa, D0 and S equal #7546 exactly' % label) + print('PASS %s: kappa identical to #7546 in every digit (%s), D0/call delta exactly 0' % (label, k1)) + if name == 'rt6': + Xs = copy.deepcopy(W); Xs['program'] = Xs['program'][:-3] + rejected('%s: no swap-back' % label, lambda: rows_equal_base(Xs, RB, replay(Xs), label)) + if name == 's1': + s1_kappa, s1_inv = k1, (P1, T1) + for kind in ('chart', 'coef'): + X, i = corrupt(W, kind) + if kind == 'chart': + rejected('%s: ADD %d operand chart corrupted' % (label, i), lambda: replay(X)) + else: + rejected('%s: ADD %d coefficient doubled' % (label, i), + lambda: rows_equal_base(X, RB, replay(X), label)) + E2 = copy.deepcopy(E) + E2['replace'][0][2] = E2['replace'][0][2] + [['SCALE', 0, '3', 0]] + rejected('%s: tampered edit list' % label, + lambda: require(canon_sha(apply_edits(B, E2)) == PINS[name], 'rebuilt sha256 differs from the pin')) + P1, T1 = s1_inv + bad = dict(P1); bad[3] -= 1 + require(crossing(T1, bad) != s1_kappa, 'tampered invoice changes the crossing') + print('PASS control rejected: S1 invoice with one rank-3 job removed gives a different kappa') + print('runtime %.0f s' % (time.time() - t0)) + print('PASS_UNPAID_WORDS') + + +if __name__ == '__main__': + sys.exit(main())