Fold 6 of the openai/math Origami Epic (#19898, tranche B: #21958). The ANALYSE series confronts a research statement with what the repository can prove; here the statement is a counting problem.
Finding a perfect matching in a bipartite graph: polynomial (flow, Hungarian assignment — the assignment_lean lake exhibits it, cf. Duality.lean).
Counting perfect matchings: the #P class — and the matrix object that carries this count is the permanent, the sign-forgetting cousin of the determinant.
Tranche A (#21962) deposited into the lake the bridge card_eq_permanent: the permanent (native Mathlib organ) of the 0/1 adjacency matrix equals the number of perfect matchings. This notebook does three things:
it audits the foundation (the Mathlib organ Matrix.permanent, the file Counting.lean) and checks the signatures and axioms from the lake;
it cross-checks the bridge by brute-force enumeration in Python — every value Lean evaluates must come out identical from the enumeration;
it exercises the native negative controls (Matrix.permanent_zero, Matrix.permanent_one) as guarantees of meaning.
Overall epistemic status (doctrine #19898, detailed in §7): this repository proves the local bridge; #P-completeness (Valiant) and the FPRAS (Jerrum–Sinclair–Vigoda) are classical theorems cited; the lean/docs skeleton published by the openai/math authors (family 113) is reported, not verified here.
Execution environment: kernel python3 (the repository venv); the Lean cells compile probes via wsl + lake env lean against the assignment_lean lake (toolchain v4.33.0, Mathlib pin db584cd6d46c) — the convention of the -Lean-Python series (cf. ANALYSE-06). ## Navigation
1. The statement — counting perfect matchings (family 113)
A bipartite graph \(G = (U \cup V, E)\) with \(|U| = |V| = n\), represented by its boolean adjacency matrix \(B\) (\(B_{ij}\): the edge \(i \to j\) exists).
A perfect matching is a bijection \(\sigma : U \to V\) such that every edge \((i, \sigma(i))\) exists.
The permanent of a square \(n \times n\) matrix \(M\) is \(\mathrm{perm}(M) = \sum_{\sigma \in S_n} \prod_{i=1}^{n} M_{i,\sigma(i)}\) — the sum over all permutations, like the determinant without the signs.
On a 0/1 matrix every product equals \(1\) exactly when \(\sigma\) is a covered matching: \(\mathrm{perm}(B) = \#\{\text{perfect matchings}\}\). Counting already means evaluating the permanent.
The class jump: deciding whether a perfect matching exists is polynomial; counting the perfect matchings of a bipartite graph is #P-complete — the founding problem of the class (Valiant, 1979) — and yet it admits a randomised FPRAS (Jerrum–Sinclair–Vigoda, 2004). Both theorems are literature classics, cited here as such; the status of the formal skeleton published by the openai/math authors is treated in §7.
2. The proof chain — three links, only one of them ours
Link
Carrier
Status in this notebook
1. The organ Matrix.permanent exists (zero, one, transpose, diagonal…)
Mathlib at pin v4.33.0
verified (audit §3 + probes)
2. The bridge card_eq_permanent: permanent of the adjacency = number of matchings
the assignment_lean lake (tranche A, #21962)
verified (signatures + axioms + #eval cross-checked in §5)
3. #P-completeness of counting; FPRAS; SDP frontier (family 126)
classical literature / openai/math skeleton
cited / reported — never “proved by us”
The notebook’s method follows the series: never confuse what the repository proves (links 1-2, backed by #print axioms) with what it cites (link 3). The Python cross-check of §4-§5 does not prove the bridge — it verifies that the formalisation did not pick the wrong object: every Lean value must come out identical from the brute-force enumeration.
3. The Lean foundation — auditing the organ and the bridge
Two preliminary checks, made at the source: the organ Matrix.permanent is indeed in Mathlib at the lake’s pin (with its native controls permanent_zero, permanent_one), and the file Counting.lean of tranche A is present in the lake with the expected declarations.
toolchain du lac : leanprover/lean4:v4.33.0
organe Mathlib — Mathlib/LinearAlgebra/Matrix/Permanent.lean :
4370 octets
théorèmes natifs `permanent_*` (extraits) :
theorem permanent_diagonal {d : n → R} : permanent (diagonal d) = ∏ i, d i
theorem permanent_zero [Nonempty n] : permanent (0 : Matrix n n R) = 0
theorem permanent_one : permanent (1 : Matrix n n R) = 1
theorem permanent_isEmpty [IsEmpty n] {A : Matrix n n R} : permanent A = 1
theorem permanent_eq_one_of_card_eq_zero {A : Matrix n n R} (h : card n = 0) : permanent A = 1
theorem permanent_unique {n : Type*} [Unique n] [DecidableEq n] [Fintype n] (A : Matrix n n R) :
Reading the audit
The organ exists at the pin: Permanent.lean carries the definition and a family of native theorems, including the two controls used in §6 (permanent_zero, permanent_one) and the transpose used by the bridge proof (permanent_transpose). The lake runs under toolchain v4.33.0 — the pin under which tranche A was proved.
Organ-first (#13564): the lake redefines neither the permanent nor its lemmas — it invokes the Mathlib organ and proves the correspondence with matchings.
# Lecture du socle : Counting.lean (tranche A, #21962) — extraits numérotés.COUNTING_WIN = os.path.join(os.getcwd(), "..", "..", "..","GameTheory", "assignment_lean", "Assignment", "Counting.lean")lines =open(COUNTING_WIN, encoding="utf-8").read().splitlines()print("fichier :", os.path.relpath(COUNTING_WIN, os.getcwd()), f"({len(lines)} lignes)")print()for a, b in [(23, 32), (50, 57), (74, 80)]:print(f"--- lignes {a}-{b} ---")for k inrange(a -1, b):print(f"{k +1:3d} | {lines[k]}")print()
fichier : ..\..\..\GameTheory\assignment_lean\Assignment\Counting.lean (82 lignes)
--- lignes 23-32 ---
23 | /-- Matrice d'adjacence entiere d'un graphe biparti sur `Fin n × Fin n` :
24 | `1` si l'arete existe, `0` sinon. -/
25 | def adjMatrix (B : Matrix (Fin n) (Fin n) Bool) : Matrix (Fin n) (Fin n) ℕ :=
26 | B.map fun b => if b then 1 else 0
27 |
28 | /-- L'ensemble des couplages parfaits d'un graphe biparti : les permutations
29 | dont toutes les aretes ligne `i` vers colonne `σ i` sont presentes. -/
30 | def perfectMatchingSet (B : Matrix (Fin n) (Fin n) Bool) :
31 | Finset (Equiv.Perm (Fin n)) :=
32 | Finset.univ.filter fun σ => ∀ i, B i (σ i)
--- lignes 50-57 ---
50 | /-- **Le pont** : le permanent (Mathlib) de la matrice d'adjacence 0/1 egale
51 | le nombre de couplages parfaits du graphe biparti. C'est la formalisation
52 | locale du point d'entree des familles 113 (FPRAS pour compter) et 126
53 | (cloture SDP) d'openai/math, citees avec leur statut epistemique dans le
54 | carnet ANALYSE-12. -/
55 | theorem card_eq_permanent (B : Matrix (Fin n) (Fin n) Bool) :
56 | (perfectMatchingSet B).card = (adjMatrix B).permanent := by
57 | classical
--- lignes 74-80 ---
74 | /-- Corollaire du pont sur le graphe complet : le permanent de la matrice
75 | tout-un est le factoriel de n (temoin croise avec `Fintype.card_perm`). -/
76 | theorem permanent_complete_eq_factorial (B : Matrix (Fin n) (Fin n) Bool)
77 | (h : ∀ i j, B i j) :
78 | (adjMatrix B).permanent = Nat.factorial (Fintype.card (Fin n)) := by
79 | rw [← card_eq_permanent B, card_eq_factorial B h, Finset.card_univ,
80 | Fintype.card_perm]
Reading the foundation
Both local definitions bridge graphs and algebra: adjMatrix (0/1 <- Bool) and perfectMatchingSet (the covered permutations, as a Finset). The statement card_eq_permanent says exactly the announced equality; the corollary permanent_complete_eq_factorial confronts it with the factorial on the complete graph — a cross-witness with Fintype.card_perm. The proof (visible in the file) rewrites the cardinal filter as a sum of indicators and then recognises the definition of the permanent, relying on Matrix.permanent_transpose — no hidden computation.
The signatures are the expected ones: card_eq_permanent speaks about the cardinality of the Finset of covered permutations against the permanent of the adjacency (a ℕ matrix), and Mathlib’s two native controls are argument-free statements (permanent 0 = 0, permanent 1 = 1).
The axioms: card_eq_permanent depends only on Mathlib’s three standard axioms (propext, Classical.choice, Quot.sound) — no sorryAx (no hole), no Lean.ofReduceBool (no native decision without proof). That is the formal-integrity witness of link 2.
4. The permanent by brute-force enumeration — the Python cross-check
The Python path is deliberately naive and independent of the lake: permanent_def applies the definition (sum over itertools.permutations of products), count_matchings counts perfect matchings directly (boolean test of the edges). Two disjoint code paths that must return the same number — then an exhaustive confrontation over the whole space of 0/1 matrices for \(n \le 3\).
# Le permanent par définition, le comptage direct des couplages, et une galerie de témoins.from itertools import permutationsimport mathdef permanent_def(M): n =len(M)returnsum(math.prod(M[i][s[i]] for i inrange(n)) for s in permutations(range(n)))def count_matchings(M): n =len(M)returnsum(1for s in permutations(range(n)) ifall(M[i][s[i]] for i inrange(n)))def edges_to_matrix(n, edges): M = [[0] * n for _ inrange(n)]for i, j in edges: M[i][j] =1return MK33 = edges_to_matrix(3, [(i, j) for i inrange(3) for j inrange(3)])B3 = edges_to_matrix(3, [(0, 0), (0, 2), (1, 0), (1, 1), (2, 1), (2, 2)])BLOC4 = edges_to_matrix(4, [(0, 0), (0, 1), (1, 0), (1, 1), (2, 2), (2, 3), (3, 2), (3, 3)])CYC4 = edges_to_matrix(4, [(i, i) for i inrange(4)] + [(i, (i +1) %4) for i inrange(4)])VIDE3 = edges_to_matrix(3, [])ID3 = edges_to_matrix(3, [(i, i) for i inrange(3)])print(f"{'graphe témoin':<24}{'permanent_def':>14}{'count_matchings':>17}")print("-"*57)for nom, M in [("K3,3 (complet)", K33), ("B3 (6 arêtes)", B3), ("bloc K2,2 + K2,2", BLOC4), ("cycle C4", CYC4), ("vide (3x3)", VIDE3), ("identité I3", ID3)]: p, c = permanent_def(M), count_matchings(M)print(f"{nom:<24}{p:>14}{c:>17}{'accord'if p == c else'ÉCART'}")print()print("K3,3 =", math.factorial(3), "— le factoriel prédit par permanent_complete_eq_factorial (lignes 74-80 ci-dessus).")
The two Python paths agree on the whole gallery, and the values illustrate the theory: the complete graph returns \(3! = 6\) (the lake’s corollary), the empty graph returns \(0\) (no matching — the content of permanent_zero in §6), the identity returns \(1\) (permanent_one), and the block \(K_{2,2} \oplus K_{2,2}\) returns \(2 \times 2 = 4\): counting is multiplicative over disjoint unions — a property a polynomial “finder” does not need.
# Confrontation exhaustive : TOUTES les matrices 0/1 pour n <= 3, plus la symétrie# par transposée (pendant Python de Matrix.permanent_transpose).ecarts =0total =0for n in [1, 2, 3]:for bits inrange(2** (n * n)): M = [[(bits >> (i * n + j)) &1for j inrange(n)] for i inrange(n)] total +=1if permanent_def(M) != count_matchings(M): ecarts +=1if permanent_def(M) != permanent_def([list(r) for r inzip(*M)]): ecarts +=1print(f"{total} matrices balayées (espace 0/1 complet pour n <= 3, transposées incluses) : {ecarts} écart(s)")
530 matrices balayées (espace 0/1 complet pour n <= 3, transposées incluses) : 0 écart(s)
Reading the confrontation
Over the complete space of small instances (every 0/1 matrix up to \(n = 3\), i.e. exhaustive enumeration rather than a sample), the equality permanent = count never wavers, and the transpose symmetry holds — the computational counterpart of Matrix.permanent_transpose, which the bridge proof uses. This is not a proof of the bridge (that is the role of link 2), but it is object-error detection: the formalisation counts what we think it counts.
5. The bridge confronted — Lean #eval against Python enumeration
The decisive test: Lean evaluates (#eval) the cardinality of perfectMatchingSet and the permanent of the adjacency on the concrete witnesses, then Python reads those values back and compares them with its own enumeration. The two literal matrices (B3, BLOC4) are written once on the Lean side — the notebook requires them to describe the same graphs as the edge lists of §4.
The four quantities agree: the cardinality computed by the Lean kernel from the lake’s set-theoretic definition and the permanent computed by the Mathlib definition return exactly the numbers of the Python enumeration. The bridge is not a coincidence of statements — both sides compute the same thing on independent implementations (Lean kernel against Python interpreter).
6. The native negative controls — permanent_zero and permanent_one
Mathlib itself supplies the two guarantees of meaning for counting: a null matrix has a null permanent (no matching in an edgeless graph), and the identity matrix has a permanent equal to 1 (exactly one perfect matching: the identity permutation). These are theorems proved in the organ — the notebook re-declares them as example (proof: the native lemma, argument-free) and confronts them with the same graphs on the Python side.
The examples compile: both native statements apply as they are to the concrete sizes (no argument to supply — they are closed equalities). The #evals return 0 and 1 as expected, and the Python counter-check on the same graphs (VIDE3, ID3 from §4) gives the same numbers. The axioms of both native lemmas are the three standard ones — the counting controls rest on nothing stronger than the bridge itself.
7. Epistemic status per family — 113, 126, 104
Doctrine of Epic #19898: every statement inherited from openai/math carries its status, per family. Never “OpenAI proved X, therefore X”.
Family 113 — counting perfect matchings (FPRAS, #P)
Classical literature, cited: the #P-completeness of counting bipartite perfect matchings (Valiant, 1979) and the existence of a randomised FPRAS (Jerrum–Sinclair–Vigoda, 2004) are published, peer-reviewed theorems, cited here at the level of their statement — this repository does not re-prove them.
openai/math (reported): family 113 of the authors’ repository publishes a lean/docs skeleton for this counting thread. Status: reported — skeleton published by the authors, not verified by this repository.
What this repository proves: the local bridge card_eq_permanent (link 2, standard axioms, §3) — the formal entry point of counting, not the complexity bounds.
Family 126 — SDP closure of the matching polytope
Negative result (no compact semidefinite lift); same reading grid: statement cited from the literature, openai/math skeleton reported, nothing verified locally beyond the bridge that defines the counted object.
Family 104 — on watch
No treatment in this fold; mentioned for the memory of the landscape.
8. Friction and discovery path
Three real frictions met while writing this notebook, kept because they teach the method:
Signatures are probed, not guessed. The first draft of the example control applied an argument to Matrix.permanent_zero (permanent_zero _) — a #check probe revealed that the native statement is closed (permanent 0 = 0, no quantifier over the matrix). One probe cycle beats one failed notebook-execution cycle.
The lake’s entry cost is the Mathlib import. Every lake env lean probe pays the import (measured: ~5 min per probe through the WSL /mnt/d mount, seconds on a lake in a native filesystem) — so the probes are grouped into three files rather than scattered per cell, with a timeout sized for the cold import (850 s).
Two literals for one graph. The witnesses exist on the Lean side (!![...] literals) and on the Python side (edge lists); the notebook enforces the discipline of writing them side by side in the same cell so that de-synchronisation stays visible.
9. Exercises
Three exercises, from computation to meaning. Series convention: stubs without deliberate errors — the notebook runs end to end even when unfinished.
# Exercice 1 -- Ryser : le permanent par inclusion-exclusion (a completer)# But : evaluer le permanent SANS enumerer les n! permutations -- par la formule de# Ryser : perm(M) = (-1)^n * sum_{S sous-ensemble non vide des colonnes} (-1)^{|S|} * prod_i (sum_{j in S} M[i][j])# Etape 1 : implementer ryser(M) avec itertools.combinations (ou un balayage de bits).# Etape 2 : verifier que ryser coincide avec permanent_def sur TOUS les temoins du# paragraphe 4 (K33, B3, BLOC4, CYC4, VIDE3, ID3).# Indice : pour n <= 6, le balayage des 2^n - 1 sous-ensembles est immediat.def ryser(M):# TODO etudiantreturnNoneprint("Exercice a completer")
Exercice a completer
Exercise 2 — Union of two cycles: predict, then measure
A 2-regular bipartite graph is a union of even cycles; each cycle \(C_{2k}\) carries exactly two perfect matchings. Before measuring: how many perfect matchings for the union of two \(C_4\) (\(n = 8\))? Then build the matrix and check.
# Exercice 2 -- union de deux C4 (n=8) : PREDIRE le compte, puis MESURER (a completer)# Etape 1 : construire la matrice 8x8 de l'union de deux cycles C4 :# cycle 1 sur les sommets 0-3 (colonnes 0-3), cycle 2 sur les sommets 4-7 (colonnes 4-7),# chaque cycle reliant i a i et (i+1) mod 4 dans son bloc.# Etape 2 : noter la prediction ici (en commentaire), puis mesurer avec count_matchings# et permanent_def -- les trois valeurs doivent coherir.def union_deux_c4():# TODO etudiantreturnNoneprint("Exercice a completer")
Exercice a completer
Exercise 3 — The limit of the bridge: negative entries
The bridge card_eq_permanent lives on 0/1 adjacency matrices. What becomes of the counting interpretation when the permanent is evaluated on a matrix with arbitrary coefficients — for instance a \(-1\) entry? Measure, then explain why the bridge proof (products of indicators) does not extend.
# Exercice 3 -- une entree negative : le permanent compte-t-il encore ? (a completer)M_neg = [[1, 1], [-1, 1]]# Etape 1 : evaluer permanent_def(M_neg) et decrire le resultat (signe, valeur).# Etape 2 : en une phrase (en commentaire), expliquer pourquoi ce nombre n'est PLUS# un compte de couplages -- quel maillon de la preuve du pont (produits d'indicateurs 0/1)# casse avec une entree negative ?print("Exercice a completer")
Exercice a completer
10. Conclusion
What the repository now knows: the Mathlib permanent of the adjacency matrix equals the number of perfect matchings — a bridge proved (tranche A), verified here by signatures, axioms and #eval cross-checked against exhaustive Python enumeration on small instances.
What this notebook cites without proving: #P-completeness (Valiant), the FPRAS (JSV), the SDP frontier (family 126) — status per family in §7; the openai/math skeleton of family 113 remains reported.
What counting has over finding: the gallery of §4 shows it on one example — counting is multiplicative over disjoint unions, it distinguishes graphs that are equally “coverable”, and it is precisely that richness which places it in #P while existence remains polynomial.
The local link is closed; the complexity frontier remains a cited statement — and that is exactly the distinction the ANALYSE series exists to hold.