93 From Particles to the Kinetic Equation

93.1 Particles from the chain

Every ingredient of the model is a link that the chain has already produced. A velocity component is one of three steps \(m,z,p\), read as \(-1,0,+1\); it is carried as the shifted number \(v+1\in \{0,1,2\}\), so that every conserved quantity below is a sum of natural numbers and no subtraction occurs. A velocity is a pair of components (the pair and diagonal of the first links), nine velocities in all, listed in the order \(\mathrm {idx}(v)=3(v_x+1)+(v_y+1)\). Space is the torus \((\mathbb Z/L)^2\), and one step along a component is

\[ x\mapsto \operatorname {rem}_L\bigl (x+(v+1)+(L-1)\bigr ), \]
the remainder map of the torus link. A configuration is a list of particles \((x,y,v)\), kept sorted by (cell, velocity) with the insertion sort of the ordering link (\(\operatorname {ins}\) and \(\operatorname {isort}\), choosing by \(\operatorname {sel}\circ \operatorname {sb}\)). Time is the iteration link: the state after \(n\) steps is \(\operatorname {iter}\,n\,\mathrm {step}\).

93.2 The collision, from two conserved quantities

Write \(N\), \(M_x=\sum (v_x+1)\), \(M_y=\sum (v_y+1)\) and \(E=\sum (v_x^2+v_y^2)\) for the number, the two shifted momenta and the energy of a list of velocities. In one dimension a pair \((a,b)\) and a pair \((c,e)\) with the same momentum and the same energy are equal up to order:

\[ c+e=a+b,\quad c^2+e^2=a^2+b^2 \;\Longrightarrow \; (c,e)=(a,b)\ \text {or}\ (c,e)=\operatorname {swp}(a,b) \]
(Lean: one_dim_id_or_swp). So in one dimension the two conserved quantities leave exactly the identity and the swap \(\sigma \) of the first links. In the plane the class of velocity multisets with given \((N,M_x,M_y,E)\) can be larger, and the collision is the cyclic successor inside that class: the velocities in one cell, as a sorted list \(M\), are replaced by the next multiset of the same size with the same \((N,M_x,M_y,E)\), in the fixed listing of all multisets (cellColl). Inside each class this is a cyclic shift, hence a bijection; with two elements in the class it is the swap again. For two particles the classes are small: a head-on pair turns through a right angle, \(\{(-1,0),(1,0)\}\mapsto \{(0,-1),(0,1)\}\), and a pair \((0,1),(1,0)\) becomes a rest particle and a diagonal mover (Lean: coll_examples). The right-angle turn is the collision of the HPP gas; here it is not assumed but appears as the two-element class \(\{(\pm 1,0)\}\leftrightarrow \{(0,\pm 1)\}\) of the successor rule, and the model of Hardy, Pomeau and de Pazzis [989] is the restriction of this rule to the four unit velocities with at most one particle per velocity. The successor rule changes \(20\) of the \(45\) two-particle multisets, \(120\) of the \(165\) three-particle ones and \(426\) of the \(495\) four-particle ones.

A step is: stream every particle, sort, collide every cell (step). The cell-wise grouping takes the run of equal cells at the head of the sorted list (runOf) and writes the collided velocities back into that cell (emit).

93.3 The one-particle distribution, by counting

Fix a cell \(c\) and an ensemble of worlds (a list of configurations). In each world, take the list of velocities in \(c\) after streaming. The one-particle distribution is a count,

\[ F(c,v)=\sum _{\text {worlds}}\#\{v\ \text {in the cell}\}, \]
and \(f=F/(\text {number of worlds})\). The pair distribution is the count of worlds whose cell holds exactly the sorted pair \(P=(u,w)\) and nothing else:
\[ F_2(c;P)=\#\{\text {worlds}: \text {cell content}=P\}. \]
Both are sums of natural numbers (Lean: Fstr, F2). Streaming is exact transport, \(F^{\mathrm {str}}(c,v)=F(c-v,v)\), as in the cell balance of Section 93.12. All of the content is in the collision.

93.4 The exact hierarchy (Lean, general)

The collision of a cell with content \(M\) is \(\mathrm {cc}(M)\), the cell collision defined above, applied to the sorted list. Cells with \(0\) or \(1\) particle do not change (cc_nil, cc_single). Two equal velocities never collide, because their class has one element (same_velocity_no_coll). The two-particle cells are reached through the list of the \(45\) sorted pairs: every two-element cell sorts into exactly one of them, and the list has no repeats (pairs2_mem, pairs2_nodup). An indicator sum over the list then picks out that one pair (fiber, pair_world). Summing over worlds gives, for every ensemble and every velocity \(v\), the exact identity

\[ F'(v)+\mathrm {Loss}_2(v)+L_3(v)=F^{\mathrm {str}}(v)+\mathrm {Gain}_2(v)+G_3(v) \]
(hierarchy), where
\[ \mathrm {Gain}_2(v)=\sum _{P}F_2(P)\,\#\{v\ \text {in}\ \mathrm {coll}(P)\},\qquad \mathrm {Loss}_2(v)=\sum _{P}F_2(P)\,\#\{v\ \text {in}\ P\}, \]
and \(G_3,L_3\) are the same counts over the worlds whose cell holds three or more particles. So the one-step change of \(f\) is written exactly with the pair distribution, plus a remainder from cells with at least three particles. This remainder is there because the collision of the model acts on the whole cell, not on pairs. When no cell holds three or more particles the remainder vanishes, and
\[ F'(v)+\mathrm {Loss}_2(v)=F^{\mathrm {str}}(v)+\mathrm {Gain}_2(v) \]
holds exactly (hierarchy_dilute). This is the first equation of the hierarchy, and nothing in it is approximate.

93.5 Closure: where molecular chaos holds, and how close the gas comes

(a) Proved. If, at the moment of collision, the occupations of two velocities are independent over the ensemble (the worlds are all pairs \((a,b)\) from two lists), then

\[ \sum _a\sum _b a\,b=\Bigl (\sum _a a\Bigr )\Bigl (\sum _b b\Bigr ) \]
(chaos_product): the pair density is the product, \(f_2=f\,f\). The same factorisation was the \(\beta =0\) statement of the gauge section.

Also proved: one collision step does not keep this product form. Take the four worlds in which \((1,0)\) and \((-1,0)\) are each present or absent. Before the collision, \(f_2=\tfrac 14=f\,f\). After it, the turned velocities \((0,\pm 1)\) have \(f_2=\tfrac 14\) but \(f\,f=\tfrac 1{16}\) (chaos_not_kept). Chaos is restored by streaming the collision partners apart before they meet again, which is a statement about the limit.

(b) Measured. Starting from a product state with velocities \((\pm 1,0)\) and \((0,0)\), we measure the chaos defect \(\delta =\sum _{u<w}|\langle n_un_w\rangle -\langle n_u\rangle \langle n_w\rangle |/\sum _{u<w}\langle n_u\rangle \langle n_w\rangle \) in the cells just before collision. Two versions are measured. \(\delta _2\) uses \(p_2(u,w)\), the fraction of cells holding exactly \(\{u,w\}\); this is the object in the exact hierarchy. \(\kappa \) uses the full pair density \(\langle n_un_w\rangle \). Signed differences are averaged over \(30\) steps and all runs before absolute values are taken. The number of runs grows as \(\rho ^{-2}\), so that every row sees about the same number of two-particle cells. \(\varphi _3\) is the fraction of particles in cells with three or more particles: the weight of the remainder \(G_3,L_3\).

\(\rho \) \(L\) runs \(\delta _2\) \(\kappa \) \(\varphi _3\)
0.8 16 16 0.611 0.024 0.2320
0.8 32 4 0.608 0.029 0.2307
0.8 64 1 0.617 0.029 0.2318
0.4 16 64 0.376 0.040 0.0738
0.4 32 16 0.370 0.028 0.0732
0.4 64 4 0.378 0.029 0.0782
0.2 16 256 0.229 0.104 0.0193
0.2 32 64 0.204 0.030 0.0201
0.2 64 16 0.204 0.023 0.0204
0.1 16 1024 0.245 0.201 0.0049
0.1 32 256 0.142 0.091 0.0049
0.1 64 64 0.108 0.025 0.0052
Table 237: Closure defects before collision (E1).

At \(L=64\), \(\delta _2\) falls from \(0.62\) to \(0.11\) as \(\rho \) goes from \(0.8\) to \(0.1\), close to \(1-e^{-\rho }\) (\(0.55,0.33,0.18,0.10\)). Most of \(\delta _2\) is therefore the probability that a third particle is also present, which vanishes with the density. The genuine correlation \(\kappa \) is at most \(0.03\) at \(L=64\) for every density. It grows on small tori: averaged over \(\rho \) it is \(0.092\), \(0.045\), \(0.026\) for \(L=16,32,64\), consistent with partners meeting again round a small torus (the smallest torus at the lowest density also carries the largest statistical error). The remainder weight \(\varphi _3\) falls like \(\rho ^2\). So, within these measurements, \(f_2-f\,f\to 0\) as the density decreases and as the system grows. For the Kac version of the same collision, Section 93.19 proves the exact hierarchy at every \(N\), exact chaos at \(t=0\) and a bound \(t/(N-1)\) on direct encounters, and computes \(N|f_2-f\,f|\) exactly for \(N\le 24\).

93.6 The kinetic equation

Insert \(F_2(u,w)\approx f_uf_w\) for \(u\neq w\) into the dilute hierarchy and divide by the number of worlds:

\[ f_{t+1}(c,v)=g(c,v)+\sum _{u<w} g(c,u)\,g(c,w)\, \bigl [\#\{v\in \mathrm {coll}(u,w)\}-\#\{v\in \{u,w\}\}\bigr ], \]
where \(g(c,u)=f_t(c-u,u)\) is the streamed distribution. This is a discrete-velocity Boltzmann equation: free streaming plus a gain-minus-loss collision term that is quadratic in \(f\). Its kernel is the pair collision of the model, derived above from the two conserved quantities. Boltzmann’s equation [987] is reached here in this order: count, exact identity, then closure; the closure is measured above, and its Kac version is in Section 93.19.

Particles against the equation. For a spatially homogeneous product initial state (\(20000\) particles, velocities \((\pm 1,0),(0,0)\)) we run the particles and iterate the equation from the same \(f\). Error is \(\max _t\sum _v|f_{\mathrm {sim}}-f_{\mathrm {kin}}|\) divided by the total change of \(f\):

\(\rho \) \(L\) steps relative error
0.4 224 100 0.086
0.2 316 200 0.039
0.1 447 400 0.032
Table 238: Particles against the kinetic equation, homogeneous relaxation (E2).

The error decreases with the density. The step from \(0.2\) to \(0.1\) is small: at fixed particle number the sampling noise of \(f_{\mathrm {sim}}\) is fixed, while the total change of \(f\) shrinks. The entropies agree as well: at \(\rho =0.1\), \(H_{\mathrm {sim}}\) goes from \(-0.34012\) to \(-0.40362\) and \(H_{\mathrm {kin}}\) to \(-0.40363\).

93.7 The H theorem

Proved: semi-detailed balance. The pair collision is a permutation of the \(45\) pairs (pairs_perm), so for every function \(h\) of pairs with values in any commutative monoid, \(\sum _P h(\mathrm {coll}\,P)=\sum _P h(P)\) (sum_perm). Consequently, if the pair weight \(F(P)\) is the same on \(P\) and on \(\mathrm {coll}\,P\), as \(f_uf_w\) is when \(\ln f\) is a combination of the conserved quantities, then the closed gain of every velocity equals its closed loss (balance). The Maxwellians \(f_v\propto e^{a+b\cdot v-\beta e_v}\) are therefore stationary.

Monotonicity of \(H=\sum _v f_v\ln f_v\). For the continuous-time equation, \(dH/dt\le 0\) is derived in Section 93.19 from sum_perm and \(\ln y\le y-1\) [988], and the logarithm-free counting version is proved in Lean there: the exact ratio \(W'/W\), and balance as a local maximum of \(W\). For the discrete-time equation used here, the monotonicity is measured:

over \(200\) random homogeneous initial states (densities \(0.05\) to \(0.4\), \(300\) steps each), the largest one-step increase of \(H\) was \(2.2\times 10^{-16}\), which is rounding. Along the particle runs of E2, \(H\) computed from the measured \(f\) also decreases and ends within \(10^{-4}\) of the kinetic value.

93.8 From the kinetic equation back to the fluid

Proved: the collision terms carry no number, momentum or energy. For each of the four conserved weights \(w\), \(\sum _v w(v)\,\#\{v\in M\}=\sum _{u\in M}w(u)\) (moment_cell), and so \(\sum _v w(v)F'(v)=\sum _v w(v)F^{\mathrm {str}}(v)\) for the exact step (moments_exact). Likewise \(\sum _v w(v)\mathrm {Gain}_2(v)=\sum _v w(v)\mathrm {Loss}_2(v)\) for the closed term, for any pair weights (moments_closed). Taking these moments of the kinetic equation removes the collision term and leaves only the streaming. That is the cell balance \(A_c(t+1)+\mathrm {Out}_c=A_c(t)+\mathrm {In}_c\) of Section 93.12, for \(N,M_x,M_y,E\). The fluid equations are therefore the moment equations of the kinetic equation, with the fluxes \(\sum _v w(v)\,v\,f\).

Closing the fluxes at a Maxwellian gives the sound speed \(c^2=\sum f_0v_x^2e/(2\sum f_0v_x^2)\), the formula of Section 93.12 with the classical susceptibility \(f\) in place of \(f(1+f)\). This is derived from local equilibrium in Section 93.19. We run the kinetic equation itself, linearised about \(f_0\propto e^{-\beta e}\), and measure its modes:

\(L\) \(n\) \(k\) \(\Gamma _T/k^2\) \(\omega /k\)
32 1 0.1963 0.2746 0.9050
64 1 0.0982 0.2742 0.8914
64 2 0.1963 0.2746 0.9050
128 1 0.0491 0.2741 0.8851
Table 239: Linear modes of the kinetic equation, \(\rho =1\), \(\beta =1/2\) (E4).

Over these points the shear rate fits \(\Gamma _T\propto k^{2.001}\), a kinematic viscosity \(\nu _{\mathrm {kin}}=0.274\). The sound speed approaches the closure value \(0.8798\) as \(k\to 0\) (\(0.8851\) at the smallest \(k\), \(0.6\%\) above). Along every run \(N,M_x,M_y,E\) stay constant to \(3\times 10^{-14}\), as the Lean moment theorems require.

So the line is closed: particles (exact conservation and cell balance, Lean) \(\to \) exact hierarchy (Lean) \(\to \) closure (proved where the ensemble is a product, measured otherwise) \(\to \) kinetic equation (compared with the particles) \(\to \) moments (Lean) \(\to \) fluid equations (modes measured).

93.9 Status

Statement

Status

Where

exact hierarchy \(F'+\mathrm {Loss}_2+L_3=F+\mathrm {Gain}_2+G_3\)

Lean, general

hierarchy

dilute case: \(F'+\mathrm {Loss}_2=F+\mathrm {Gain}_2\)

Lean, general

hierarchy_dilute

product ensemble \(\Rightarrow f_2=ff\)

Lean, general

chaos_product

one step breaks \(f_2=ff\)

Lean, example

chaos_not_kept

pair collision is a permutation; semi-detailed balance

Lean

pairs_perm, balance

collision terms have zero \(N,M,E\) moments

Lean, general

moments_exact, moments_closed

\(f_2-ff\to 0\) as density decreases

measured; proof remaining

E1

kinetic equation matches particles at low density

measured

E2

\(H\) decreases along the closed equation, discrete time

measured; proof remaining

E3

\(dH/dt\le 0\), continuous time; \(W\) counting

derived / Lean

Section 93.19

Kac version: exact hierarchy, chaos at \(t=0\), encounter bound

Lean

Section 93.19

sound and shear modes of the kinetic equation

measured

E4

Comparison. For continuum hard spheres the passage from particles to the Boltzmann equation is Lanford’s theorem [990], extended to long times by Deng, Hani and Ma [991]; those proofs control the propagation of chaos.

93.10 Machine check

The Lean files of this section are FluidChain.lean (the model: velocities, the cell collision, streaming, sorting) and KineticChain.lean (counting, the exact hierarchy, chaos, balance, moments). In AXIOMS.txt they have \(46\) and \(54\) theorems, \(100\) in all, and every one of the \(100\) #print axioms lines reads “does not depend on any axioms”. They import FrobChain.lean and FTAChain.lean from the earlier links. The numbers come from numeric_kinetic.py, which imports the particle dynamics from numeric_fluid.py; its output is NUMERIC_KINETIC.txt. The fluid section (Section 93.12) uses FluidChain.lean and numeric_fluid.py as listed here.

Listing 366: FluidChain.lean: the lattice gas, conservation and cell balance

FluidChain.lean

/-
  FluidChain.lean
  From particles to a fluid: a lattice gas built from the chain (T15).

  Lean 4 core plus FTAChain (pairs, `swp`, `sel`/`sb`, `rem`, `pre`, `iter`,
  the laws of + and *) and FrobChain (`sumTo`). Proofs are hand-written terms,
  rewriting and case splits closed by `rfl`; no omega / simp / ring / decide /
  norm_num / linarith.

  The model (designed here):
  * a velocity component is one of three steps `m, z, p` (−1, 0, +1);
    a velocity is a pair of components (9 velocities in the plane);
  * space is the torus (Z/L)^2; a particle moves by `x ↦ rem L (x + (v+1) + (L-1))`;
  * the particles form a list, sorted by (cell, velocity) with insertion sort
    (`sel ∘ sb`, as `ins`/`isort` in FTAChain);
  * time is `iter n step`;
  * collision: the velocities in one cell form a sorted list (a multiset).
    It is replaced by the next multiset, in a fixed listing of all multisets
    of that size, with the same number, momentum and energy. Inside each such
    class this is a cyclic shift, so it is a bijection of the class.
    For two particles in one dimension the class is the pair and its swap,
    so the outcome is `id` or `swp` (`one_dim_id_or_swp`).
  Momentum components are carried shifted by one (`v + 1 ∈ {0,1,2}`), so every
  conserved quantity is a sum of natural numbers; the true momentum is the
  shifted one minus the particle number.

  Proved here (for every L, every configuration, every time):
    one_dim_id_or_swp              1D: same (P, E) ⇒ the pair or its swap
    cellColl_class, cons_*         the cell collision keeps N, Mx, My, E
    step_conserves, iter_conserves exact global conservation, all weights
    number/momentum_x/momentum_y/energy_conserved
    ind_balance                    the four cases of one particle
    stream_balance                 cell balance under streaming
    collideAll_cell, isort_cell    collisions and sorting keep every cell's sums
    cell_step                      one step:  A_c(t+1) + Out = A_c(t) + In
    cell_telescope                 T steps:   A_c(T) + Σ_t Out_t = A_c(0) + Σ_t In_t
    continuity, momentum_x, momentum_y, energy_cell   the four cell equations
-/
import FrobChain

namespace FluidChain
open FTAChain FrobChain

/-! ## Velocities -/

/-- One velocity component: −1, 0, +1. -/
inductive C3 where
  | m
  | z
  | p

/-- The component shifted by one: `v + 1`. -/
def sh : C3 → Nat
  | .m => 0
  | .z => 1
  | .p => 2

/-- The square of the component. -/
def sq : C3 → Nat
  | .m => 1
  | .z => 0
  | .p => 1

def c3Eq : C3 → C3 → Bool
  | .m, .m => true
  | .m, .z => false
  | .m, .p => false
  | .z, .m => false
  | .z, .z => true
  | .z, .p => false
  | .p, .m => false
  | .p, .z => false
  | .p, .p => true

/-- A velocity in the plane. -/
abbrev V := C3 × C3

def mass (_ : V) : Nat := 1
def mx (u : V) : Nat := sh u.1
def my (u : V) : Nat := sh u.2
def en (u : V) : Nat := sq u.1 + sq u.2

def idx (u : V) : Nat := 3 * sh u.1 + sh u.2

def vEq (u v : V) : Bool := c3Eq u.1 v.1 && c3Eq u.2 v.2

/-- The nine velocities, in `idx` order. -/
def allV : List V :=
  [(.m, .m), (.m, .z), (.m, .p), (.z, .m), (.z, .z), (.z, .p), (.p, .m), (.p, .z), (.p, .p)]

/-! ## Bool and Nat bookkeeping -/

theorem nat_beq_self : ∀ n : Nat, Nat.beq n n = true
  | 0 => rfl
  | n + 1 => nat_beq_self n

theorem ne_of_beq_false {a b : Nat} (h : Nat.beq a b = false) : a ≠ b := fun e =>
  Bool.noConfusion ((nat_beq_self b).symm.trans ((congrArg (fun t => Nat.beq t b) e).symm.trans h))

theorem and_true_l {a b : Bool} (h : (a && b) = true) : a = true := by
  cases a with
  | true => rfl
  | false => exact h

theorem and_true_r {a b : Bool} (h : (a && b) = true) : b = true := by
  cases a with
  | true => exact h
  | false => exact Bool.noConfusion h

/-! ## One dimension: two conserved quantities leave `id` or `swp` -/

/-- **1D collisions.** If `(c, e)` has the same momentum and energy as `(a, b)`,
    it is `(a, b)` or `swp (a, b)`. -/
theorem one_dim_id_or_swp (a b c e : C3)
    (hP : sh c + sh e = sh a + sh b) (hE : sq c + sq e = sq a + sq b) :
    (c, e) = (a, b) ∨ (c, e) = swp (a, b) := by
  cases a <;> cases b <;> cases c <;> cases e <;>
    first
    | exact Or.inl rfl
    | exact Or.inr rfl
    | exact absurd hP (ne_of_beq_false rfl)
    | exact absurd hE (ne_of_beq_false rfl)

/-! ## Multisets of velocities and the cell collision -/

def vsum (w : V → Nat) : List V → Nat
  | [] => 0
  | u :: us => w u + vsum w us

def rep (u : V) : Nat → List V
  | 0 => []
  | c + 1 => u :: rep u c

/-- All sorted lists of length `n` from the listed velocities (multisets). -/
def msets : List V → Nat → List (List V)
  | [], 0 => [[]]
  | [], _ + 1 => []
  | u :: us, n => (List.range (n + 1)).flatMap fun c => (msets us (n - c)).map fun M => rep u c ++ M

theorem msets_count : (msets allV 2).length = 45 ∧ (msets allV 3).length = 165 := ⟨rfl, rfl⟩

/-- Same number, momentum and energy. -/
def sameClass (M M' : List V) : Bool :=
  Nat.beq (vsum mass M) (vsum mass M') && Nat.beq (vsum mx M) (vsum mx M') &&
  Nat.beq (vsum my M) (vsum my M') && Nat.beq (vsum en M) (vsum en M')

def lEq : List V → List V → Bool
  | [], [] => true
  | [], _ :: _ => false
  | _ :: _, [] => false
  | u :: us, v :: vs => vEq u v && lEq us vs

def filt {A : Type} (p : A → Bool) : List A → List A
  | [] => []
  | a :: as => match p a with
    | true => a :: filt p as
    | false => filt p as

def headOr {A : Type} (d : A) : List A → A
  | [] => d
  | y :: _ => y

/-- The element after `x` in `cls`, wrapping round to the first. -/
def nextAfter (x : List V) (cls : List (List V)) : List (List V) → List V
  | [] => x
  | y :: ys => match lEq y x with
    | true => headOr (headOr x cls) ys
    | false => nextAfter x cls ys

/-- **The cell collision.** The next multiset of the same size with the same
    number, momentum and energy. -/
def cellColl (M : List V) : List V :=
  let cls := filt (sameClass M) (msets allV (vsum mass M))
  nextAfter M cls cls

/-- Every element satisfies `P`. -/
def AllP {A : Type} (P : A → Prop) : List A → Prop
  | [] => True
  | a :: as => P a ∧ AllP P as

theorem allP_filt {A : Type} (p : A → Bool) : ∀ l : List A, AllP (fun a => p a = true) (filt p l)
  | [] => trivial
  | a :: as => by
    show AllP (fun a => p a = true) (match p a with
      | true => a :: filt p as
      | false => filt p as)
    cases h : p a with
    | true => exact ⟨h, allP_filt p as⟩
    | false => exact allP_filt p as

theorem headOr_P {A : Type} (P : A → Prop) (d : A) (hd : P d) : ∀ l, AllP P l → P (headOr d l)
  | [], _ => hd
  | _ :: _, h => h.1

theorem nextAfter_P (P : List V → Prop) (x : List V) (cls : List (List V)) (hx : P x)
    (hc : AllP P cls) : ∀ l, AllP P l → P (nextAfter x cls l)
  | [], _ => hx
  | y :: ys, h => by
    show P (match lEq y x with
      | true => headOr (headOr x cls) ys
      | false => nextAfter x cls ys)
    cases lEq y x with
    | true => exact headOr_P P _ (headOr_P P x hx cls hc) ys h.2
    | false => exact nextAfter_P P x cls hx hc ys h.2

theorem sameClass_self (M : List V) : sameClass M M = true := by
  show (Nat.beq (vsum mass M) (vsum mass M) && Nat.beq (vsum mx M) (vsum mx M) &&
    Nat.beq (vsum my M) (vsum my M) && Nat.beq (vsum en M) (vsum en M)) = true
  rw [nat_beq_self, nat_beq_self, nat_beq_self, nat_beq_self]
  rfl

theorem cellColl_class (M : List V) : sameClass M (cellColl M) = true :=
  nextAfter_P (fun M' => sameClass M M' = true) M _ (sameClass_self M)
    (allP_filt _ _) _ (allP_filt _ _)

/-- A weight is kept by every cell collision. -/
def CellCons (w : V → Nat) : Prop := ∀ M, vsum w (cellColl M) = vsum w M

theorem cons_mass : CellCons mass := fun M =>
  (Nat.eq_of_beq_eq_true (and_true_l (and_true_l (and_true_l (cellColl_class M))))).symm

theorem cons_mx : CellCons mx := fun M =>
  (Nat.eq_of_beq_eq_true (and_true_r (and_true_l (and_true_l (cellColl_class M))))).symm

theorem cons_my : CellCons my := fun M =>
  (Nat.eq_of_beq_eq_true (and_true_r (and_true_l (cellColl_class M)))).symm

theorem cons_en : CellCons en := fun M =>
  (Nat.eq_of_beq_eq_true (and_true_r (cellColl_class M))).symm

/-- Head-on pairs turn by a right angle; a moving pair hands its motion to a
    rest particle; a head-on pair with a rest particle turns as a whole. -/
theorem coll_examples :
    (cellColl [(.m, .z), (.p, .z)]).map idx = [3, 5] ∧
    (cellColl [(.z, .p), (.p, .z)]).map idx = [4, 8] ∧
    (cellColl [(.m, .z), (.z, .z), (.p, .z)]).map idx = [3, 4, 5] := ⟨rfl, rfl, rfl⟩

/-! ## Particles, streaming, sorting, grouping -/

structure Pt where
  x : Nat
  y : Nat
  v : V

/-- One step along a component on the circle `Z/L`: `x + v` with `v + 1 = sh`. -/
def move (L : Nat) (x : Nat) (c : C3) : Nat := rem L (x + sh c + pre L)

def stream (L : Nat) (q : Pt) : Pt := ⟨move L q.x q.v.1, move L q.y q.v.2, q.v⟩

/-- Sort key: cell first, then velocity. -/
def key (L : Nat) (q : Pt) : Nat := (q.x * L + q.y) * 9 + idx q.v

/-- Insertion, as `ins` in FTAChain. -/
def insP (L : Nat) (q : Pt) : List Pt → List Pt
  | [] => [q]
  | r :: m => sel (sb (key L q) (key L r)) (q :: r :: m) (r :: insP L q m)

def isortP (L : Nat) : List Pt → List Pt
  | [] => []
  | q :: m => insP L q (isortP L m)

def sameCell (q r : Pt) : Bool := Nat.beq q.x r.x && Nat.beq q.y r.y

/-- The velocities of the leading run in `q`'s cell, and what follows. -/
def runOf (q : Pt) : List Pt → List V × List Pt
  | [] => ([], [])
  | r :: m => match sameCell q r with
    | true => ((r.v :: (runOf q m).1), (runOf q m).2)
    | false => ([], r :: m)

/-- Put velocities into `q`'s cell. -/
def emit (q : Pt) : List V → List Pt
  | [] => []
  | v :: vs => ⟨q.x, q.y, v⟩ :: emit q vs

/-- Collide every cell (fuel `f`: at most `f` cells). -/
def collideAll : Nat → List Pt → List Pt
  | 0, l => l
  | _ + 1, [] => []
  | f + 1, q :: m => emit q (cellColl (q.v :: (runOf q m).1)) ++ collideAll f (runOf q m).2

/-- **One time step**: stream, sort, collide every cell. -/
def step (L : Nat) (ps : List Pt) : List Pt :=
  collideAll ps.length (isortP L (ps.map (stream L)))

/-! ## Sums over particles -/

def lsum (f : Pt → Nat) : List Pt → Nat
  | [] => 0
  | q :: m => f q + lsum f m

theorem lsum_ext (f g : Pt → Nat) (h : ∀ q, f q = g q) : ∀ l, lsum f l = lsum g l
  | [] => rfl
  | q :: m => by
    show f q + lsum f m = g q + lsum g m
    rw [h q, lsum_ext f g h m]

theorem lsum_add (f g : Pt → Nat) : ∀ l, lsum (fun q => f q + g q) l = lsum f l + lsum g l
  | [] => rfl
  | q :: m => by
    show f q + g q + lsum (fun q => f q + g q) m = f q + lsum f m + (g q + lsum g m)
    rw [lsum_add f g m]
    exact mid4 _ _ _ _

theorem lsum_map (f : Pt → Nat) (g : Pt → Pt) : ∀ l, lsum f (l.map g) = lsum (fun q => f (g q)) l
  | [] => rfl
  | q :: m => by
    show f (g q) + lsum f (m.map g) = f (g q) + lsum (fun q => f (g q)) m
    rw [lsum_map f g m]

theorem lsum_append (f : Pt → Nat) : ∀ a b : List Pt, lsum f (a ++ b) = lsum f a + lsum f b
  | [], b => (nzero_add _).symm
  | q :: a, b => by
    show f q + lsum f (a ++ b) = f q + lsum f a + lsum f b
    rw [lsum_append f a b, nadd_assoc]

theorem lsum_ins (f : Pt → Nat) (L : Nat) (q : Pt) : ∀ l, lsum f (insP L q l) = f q + lsum f l
  | [] => rfl
  | r :: m => by
    show lsum f (sel (sb (key L q) (key L r)) (q :: r :: m) (r :: insP L q m)) = f q + (f r + lsum f m)
    cases sb (key L q) (key L r) with
    | zero => rfl
    | succ k =>
      show f r + lsum f (insP L q m) = f q + (f r + lsum f m)
      rw [lsum_ins f L q m]
      exact nadd_left_comm _ _ _

theorem lsum_isort (f : Pt → Nat) (L : Nat) : ∀ l, lsum f (isortP L l) = lsum f l
  | [] => rfl
  | q :: m => by
    show lsum f (insP L q (isortP L m)) = f q + lsum f m
    rw [lsum_ins, lsum_isort f L m]

/-! ## Cells -/

def ind : Bool → Nat
  | true => 1
  | false => 0

/-- The particle is in cell `(cx, cy)`. -/
def atC (cx cy : Nat) (q : Pt) : Bool := Nat.beq q.x cx && Nat.beq q.y cy

/-- The amount of weight `w` in cell `(cx, cy)`. -/
def cellSum (cx cy : Nat) (w : V → Nat) (l : List Pt) : Nat :=
  lsum (fun q => ind (atC cx cy q) * w q.v) l

/-- The weight carried by all particles: the whole torus. -/
def total (w : V → Nat) (l : List Pt) : Nat := lsum (fun q => w q.v) l

theorem atC_same (cx cy : Nat) (q r : Pt) (h : sameCell q r = true) : atC cx cy r = atC cx cy q := by
  have hx : q.x = r.x := Nat.eq_of_beq_eq_true (and_true_l h)
  have hy : q.y = r.y := Nat.eq_of_beq_eq_true (and_true_r h)
  show (Nat.beq r.x cx && Nat.beq r.y cy) = (Nat.beq q.x cx && Nat.beq q.y cy)
  rw [hx, hy]

/-- A weight on particles that, inside one cell, only sees the velocity:
    `F q = k * w q.v` with `k` the same for all particles in `q`'s cell. -/
theorem emit_sum (F : Pt → Nat) (w : V → Nat) (q : Pt) (k : Nat)
    (hF : ∀ v, F ⟨q.x, q.y, v⟩ = k * w v) : ∀ vs, lsum F (emit q vs) = k * vsum w vs
  | [] => (Nat.mul_zero k).symm
  | v :: vs => by
    show F ⟨q.x, q.y, v⟩ + lsum F (emit q vs) = k * (w v + vsum w vs)
    rw [hF v, emit_sum F w q k hF vs, nleft_distrib]

theorem run_sum (F : Pt → Nat) (w : V → Nat) (q : Pt) (k : Nat)
    (hF : ∀ r, sameCell q r = true → F r = k * w r.v) :
    ∀ m, lsum F m = k * vsum w (runOf q m).1 + lsum F (runOf q m).2
  | [] => rfl
  | r :: m => by
    show F r + lsum F m = k * vsum w (match sameCell q r with
        | true => ((r.v :: (runOf q m).1), (runOf q m).2)
        | false => ([], r :: m)).1
      + lsum F (match sameCell q r with
        | true => ((r.v :: (runOf q m).1), (runOf q m).2)
        | false => ([], r :: m)).2
    cases h : sameCell q r with
    | true =>
      show F r + lsum F m = k * (w r.v + vsum w (runOf q m).1) + lsum F (runOf q m).2
      rw [hF r h, run_sum F w q k hF m, nleft_distrib, nadd_assoc]
    | false =>
      show F r + lsum F m = k * 0 + (F r + lsum F m)
      rw [Nat.mul_zero, nzero_add]

/-- Collisions keep any weight of the form `k(cell) * w(velocity)` when `w` is
    kept by every cell collision. -/
theorem collideAll_sum (F : Pt → Nat) (w : V → Nat) (hw : CellCons w)
    (kc : Pt → Nat)
    (hF : ∀ q r, sameCell q r = true → F r = kc q * w r.v)
    (hE : ∀ q v, F ⟨q.x, q.y, v⟩ = kc q * w v) :
    ∀ f l, lsum F (collideAll f l) = lsum F l
  | 0, _ => rfl
  | _ + 1, [] => rfl
  | f + 1, q :: m => by
    show lsum F (emit q (cellColl (q.v :: (runOf q m).1)) ++ collideAll f (runOf q m).2) = F q + lsum F m
    rw [lsum_append, emit_sum F w q (kc q) (hE q), hw, collideAll_sum F w hw kc hF hE f,
      run_sum F w q (kc q) (hF q) m]
    show kc q * (w q.v + vsum w (runOf q m).1) + _ = F ⟨q.x, q.y, q.v⟩ + _
    rw [hE q q.v, nleft_distrib, nadd_assoc]

theorem sameCell_refl (q : Pt) : sameCell q q = true := by
  show (Nat.beq q.x q.x && Nat.beq q.y q.y) = true
  rw [nat_beq_self, nat_beq_self]
  rfl

/-! ## Exact global conservation -/

theorem collideAll_total (w : V → Nat) (hw : CellCons w) (f : Nat) (l : List Pt) :
    total w (collideAll f l) = total w l :=
  collideAll_sum (fun q => w q.v) w hw (fun _ => 1)
    (fun _ r _ => (Nat.one_mul (w r.v)).symm) (fun _ v => (Nat.one_mul (w v)).symm) f l

/-- **One step conserves every collision-kept weight**, for every L and every
    configuration. -/
theorem step_conserves (w : V → Nat) (hw : CellCons w) (L : Nat) (ps : List Pt) :
    total w (step L ps) = total w ps := by
  show total w (collideAll ps.length (isortP L (ps.map (stream L)))) = _
  rw [collideAll_total w hw]
  show lsum _ (isortP L (ps.map (stream L))) = _
  rw [lsum_isort, lsum_map]
  rfl

/-- **Exact conservation at every time** (`iter n`). -/
theorem iter_conserves (w : V → Nat) (hw : CellCons w) (L : Nat) (ps : List Pt) :
    ∀ n : Nat, total w (iter n (step L) ps) = total w ps
  | 0 => rfl
  | n + 1 => (step_conserves w hw L (iter n (step L) ps)).trans (iter_conserves w hw L ps n)

theorem number_conserved (L n : Nat) (ps : List Pt) :
    total mass (iter n (step L) ps) = total mass ps := iter_conserves mass cons_mass L ps n

theorem momentum_x_conserved (L n : Nat) (ps : List Pt) :
    total mx (iter n (step L) ps) = total mx ps := iter_conserves mx cons_mx L ps n

theorem momentum_y_conserved (L n : Nat) (ps : List Pt) :
    total my (iter n (step L) ps) = total my ps := iter_conserves my cons_my L ps n

theorem energy_conserved (L n : Nat) (ps : List Pt) :
    total en (iter n (step L) ps) = total en ps := iter_conserves en cons_en L ps n

/-! ## Cell balance -/

/-- Weight leaving the cell in the streaming of one step. -/
def outF (L cx cy : Nat) (w : V → Nat) (l : List Pt) : Nat :=
  lsum (fun q => ind (atC cx cy q && !(atC cx cy (stream L q))) * w q.v) l

/-- Weight entering the cell in the streaming of one step. -/
def inF (L cx cy : Nat) (w : V → Nat) (l : List Pt) : Nat :=
  lsum (fun q => ind (!(atC cx cy q) && atC cx cy (stream L q)) * w q.v) l

/-- One particle, four cases: `[after] + [leaves] = [before] + [enters]`. -/
theorem ind_balance (b1 b2 : Bool) : ind b2 + ind (b1 && !b2) = ind b1 + ind (!b1 && b2) := by
  cases b1 <;> cases b2 <;> rfl

theorem stream_balance (L cx cy : Nat) (w : V → Nat) (l : List Pt) :
    cellSum cx cy w (l.map (stream L)) + outF L cx cy w l = cellSum cx cy w l + inF L cx cy w l := by
  show lsum (fun q => ind (atC cx cy q) * w q.v) (l.map (stream L)) + outF L cx cy w l = _
  rw [lsum_map]
  show lsum (fun q => ind (atC cx cy (stream L q)) * w q.v) l
      + lsum (fun q => ind (atC cx cy q && !(atC cx cy (stream L q))) * w q.v) l
    = lsum (fun q => ind (atC cx cy q) * w q.v) l
      + lsum (fun q => ind (!(atC cx cy q) && atC cx cy (stream L q)) * w q.v) l
  rw [← lsum_add, ← lsum_add]
  apply lsum_ext
  intro q
  rw [← nright_distrib, ← nright_distrib, ind_balance]

/-- Collisions keep every cell's amount of every collision-kept weight. -/
theorem collideAll_cell (cx cy : Nat) (w : V → Nat) (hw : CellCons w) (f : Nat) (l : List Pt) :
    cellSum cx cy w (collideAll f l) = cellSum cx cy w l :=
  collideAll_sum (fun q => ind (atC cx cy q) * w q.v) w hw (fun q => ind (atC cx cy q))
    (fun q r h => by
      show ind (atC cx cy r) * w r.v = ind (atC cx cy q) * w r.v
      rw [atC_same cx cy q r h])
    (fun _ _ => rfl) f l

theorem isort_cell (cx cy : Nat) (w : V → Nat) (L : Nat) (l : List Pt) :
    cellSum cx cy w (isortP L l) = cellSum cx cy w l := lsum_isort _ L l

/-- **Cell balance for one step**: `A_c(t+1) + Out_c(t) = A_c(t) + In_c(t)`. -/
theorem cell_step (L cx cy : Nat) (w : V → Nat) (hw : CellCons w) (l : List Pt) :
    cellSum cx cy w (step L l) + outF L cx cy w l = cellSum cx cy w l + inF L cx cy w l := by
  show cellSum cx cy w (collideAll l.length (isortP L (l.map (stream L)))) + _ = _
  rw [collideAll_cell cx cy w hw, isort_cell]
  exact stream_balance L cx cy w l

/-- **Telescoping in time**:
    `A_c(T) + Σ_{t<T} Out_c(t) = A_c(0) + Σ_{t<T} In_c(t)`. -/
theorem cell_telescope (L cx cy : Nat) (w : V → Nat) (hw : CellCons w) (ps : List Pt) :
    ∀ T : Nat, cellSum cx cy w (iter T (step L) ps)
        + sumTo T (fun t => outF L cx cy w (iter t (step L) ps))
      = cellSum cx cy w ps + sumTo T (fun t => inF L cx cy w (iter t (step L) ps))
  | 0 => rfl
  | T + 1 => by
    have ih := cell_telescope L cx cy w hw ps T
    have hs := cell_step L cx cy w hw (iter T (step L) ps)
    show cellSum cx cy w (step L (iter T (step L) ps))
        + (sumTo T (fun t => outF L cx cy w (iter t (step L) ps)) + outF L cx cy w (iter T (step L) ps))
      = cellSum cx cy w ps
        + (sumTo T (fun t => inF L cx cy w (iter t (step L) ps)) + inF L cx cy w (iter T (step L) ps))
    rw [nadd_comm (sumTo T _) (outF L cx cy w (iter T (step L) ps)), ← nadd_assoc, hs,
      nadd_right_comm, ih, nadd_assoc]

/-- The cell continuity equation (mass weight). -/
theorem continuity (L cx cy : Nat) (ps : List Pt) (T : Nat) :
    cellSum cx cy mass (iter T (step L) ps)
        + sumTo T (fun t => outF L cx cy mass (iter t (step L) ps))
      = cellSum cx cy mass ps + sumTo T (fun t => inF L cx cy mass (iter t (step L) ps)) :=
  cell_telescope L cx cy mass cons_mass ps T

/-- The cell momentum equation, x component (shifted momentum weight). -/
theorem momentum_x (L cx cy : Nat) (ps : List Pt) (T : Nat) :
    cellSum cx cy mx (iter T (step L) ps)
        + sumTo T (fun t => outF L cx cy mx (iter t (step L) ps))
      = cellSum cx cy mx ps + sumTo T (fun t => inF L cx cy mx (iter t (step L) ps)) :=
  cell_telescope L cx cy mx cons_mx ps T

/-- The cell momentum equation, y component. -/
theorem momentum_y (L cx cy : Nat) (ps : List Pt) (T : Nat) :
    cellSum cx cy my (iter T (step L) ps)
        + sumTo T (fun t => outF L cx cy my (iter t (step L) ps))
      = cellSum cx cy my ps + sumTo T (fun t => inF L cx cy my (iter t (step L) ps)) :=
  cell_telescope L cx cy my cons_my ps T

/-- The cell energy equation. -/
theorem energy_cell (L cx cy : Nat) (ps : List Pt) (T : Nat) :
    cellSum cx cy en (iter T (step L) ps)
        + sumTo T (fun t => outF L cx cy en (iter t (step L) ps))
      = cellSum cx cy en ps + sumTo T (fun t => inF L cx cy en (iter t (step L) ps)) :=
  cell_telescope L cx cy en cons_en ps T

/-! ## A concrete run (the same run is repeated in numeric_fluid.py) -/

def demo : List Pt :=
  [⟨0, 0, (.p, .z)⟩, ⟨2, 0, (.m, .z)⟩, ⟨1, 3, (.z, .p)⟩, ⟨3, 1, (.p, .p)⟩, ⟨1, 1, (.z, .z)⟩]

def enc (q : Pt) : Nat × Nat × Nat := (q.x, q.y, idx q.v)

set_option maxRecDepth 100000 in
theorem demo_run :
    total mass (iter 6 (step 4) demo) = 5 ∧ total mx (iter 6 (step 4) demo) = 6 ∧
    total my (iter 6 (step 4) demo) = 7 ∧ total en (iter 6 (step 4) demo) = 5 :=
  ⟨rfl, rfl, rfl, rfl⟩

set_option maxRecDepth 100000 in
theorem demo_final : (iter 6 (step 4) demo).map enc = [(1, 1, 4), (1, 1, 5), (1, 1, 5), (1, 3, 5), (1, 3, 6)] := rfl

end FluidChain

#print axioms FluidChain.nat_beq_self
#print axioms FluidChain.ne_of_beq_false
#print axioms FluidChain.and_true_l
#print axioms FluidChain.and_true_r
#print axioms FluidChain.one_dim_id_or_swp
#print axioms FluidChain.msets_count
#print axioms FluidChain.allP_filt
#print axioms FluidChain.headOr_P
#print axioms FluidChain.nextAfter_P
#print axioms FluidChain.sameClass_self
#print axioms FluidChain.cellColl_class
#print axioms FluidChain.cons_mass
#print axioms FluidChain.cons_mx
#print axioms FluidChain.cons_my
#print axioms FluidChain.cons_en
#print axioms FluidChain.coll_examples
#print axioms FluidChain.lsum_ext
#print axioms FluidChain.lsum_add
#print axioms FluidChain.lsum_map
#print axioms FluidChain.lsum_append
#print axioms FluidChain.lsum_ins
#print axioms FluidChain.lsum_isort
#print axioms FluidChain.atC_same
#print axioms FluidChain.emit_sum
#print axioms FluidChain.run_sum
#print axioms FluidChain.collideAll_sum
#print axioms FluidChain.sameCell_refl
#print axioms FluidChain.collideAll_total
#print axioms FluidChain.step_conserves
#print axioms FluidChain.iter_conserves
#print axioms FluidChain.number_conserved
#print axioms FluidChain.momentum_x_conserved
#print axioms FluidChain.momentum_y_conserved
#print axioms FluidChain.energy_conserved
#print axioms FluidChain.ind_balance
#print axioms FluidChain.stream_balance
#print axioms FluidChain.collideAll_cell
#print axioms FluidChain.isort_cell
#print axioms FluidChain.cell_step
#print axioms FluidChain.cell_telescope
#print axioms FluidChain.continuity
#print axioms FluidChain.momentum_x
#print axioms FluidChain.momentum_y
#print axioms FluidChain.energy_cell
#print axioms FluidChain.demo_run
#print axioms FluidChain.demo_final

Listing 367: KineticChain.lean: counting, the exact hierarchy, chaos, semi-detailed balance, moments

KineticChain.lean

/-
  KineticChain.lean
  From particles to a kinetic equation, in the FluidChain model (T18).

  Lean 4 core plus FTAChain and FluidChain. Proofs are hand-written terms,
  rewriting and case splits closed by `rfl`; no omega / simp / ring / decide /
  norm_num / linarith.

  Counting. An ensemble is a list of worlds; for a fixed cell, a world is the
  list of velocities in that cell after streaming. The one-particle
  distribution is the count `F v E = Σ_worlds #(v in the cell)`, and the
  pair distribution is the count `F2 P E = #(worlds whose cell holds exactly
  the pair P)`. Dividing by the number of worlds gives f and f2.

  Proved here:
    c3Eq_sound, vEq_sound, lEq_sound, *_refl   Bool equality means equality
    fiber                      Σ_{P ∈ Ps} [k = P] g P = g k (k in Ps, no repeats)
    cnt_ins, cnt_sort          sorting keeps counts
    cc_nil, cc_single          empty and one-particle cells do not change
    pair_world                 a two-particle cell, through the pair list
    hierarchy                  exact: F' + Loss2 + L3 = F + Gain2 + G3
                               (the change of f is the pair term in F2 plus
                               the term of cells with ≥ 3 particles)
    hierarchy_dilute           if no cell holds ≥ 3 particles: F' + Loss2 = F + Gain2
    chaos_product              product ensembles: Σ_a Σ_b a b = (Σ a)(Σ b), so f2 = f f
    chaos_not_kept             one collision step destroys the product form (example)
    same_velocity_no_coll      a pair with equal velocities never collides
    pairs_perm, sum_perm       the pair collision is a permutation of the 45 pairs
    balance                    semi-detailed balance: class-constant weights make
                               the closed gain equal to the closed loss
    moment_cell, moments_exact, moments_closed
                               N, Mx, My, E moments of both collision terms vanish
-/
import FluidChain

namespace KineticChain
open FTAChain FluidChain

/-! ## Sums and gates -/

def sumL {A : Type} (f : A → Nat) : List A → Nat
  | [] => 0
  | a :: as => f a + sumL f as

def gate : Bool → Nat → Nat
  | true, x => x
  | false, _ => 0

theorem sumL_ext {A : Type} (f g : A → Nat) (h : ∀ a, f a = g a) : ∀ l, sumL f l = sumL g l
  | [] => rfl
  | a :: as => by
    show f a + sumL f as = g a + sumL g as
    rw [h a, sumL_ext f g h as]

theorem sumL_add {A : Type} (f g : A → Nat) : ∀ l, sumL (fun a => f a + g a) l = sumL f l + sumL g l
  | [] => rfl
  | a :: as => by
    show f a + g a + sumL (fun a => f a + g a) as = f a + sumL f as + (g a + sumL g as)
    rw [sumL_add f g as]
    exact mid4 _ _ _ _

theorem sumL_mul {A : Type} (f : A → Nat) (c : Nat) : ∀ l, sumL (fun a => f a * c) l = sumL f l * c
  | [] => (nzero_mul c).symm
  | a :: as => by
    show f a * c + sumL (fun a => f a * c) as = (f a + sumL f as) * c
    rw [sumL_mul f c as, nright_distrib]

theorem sumL_cmul {A : Type} (f : A → Nat) (c : Nat) : ∀ l, sumL (fun a => c * f a) l = c * sumL f l
  | [] => rfl
  | a :: as => by
    show c * f a + sumL (fun a => c * f a) as = c * (f a + sumL f as)
    rw [sumL_cmul f c as, nleft_distrib]

theorem sumL_swap {A B : Type} (g : A → B → Nat) (bs : List B) :
    ∀ as : List A, sumL (fun a => sumL (fun b => g a b) bs) as = sumL (fun b => sumL (fun a => g a b) as) bs
  | [] => by
    show 0 = sumL (fun b => 0) bs
    exact (zeros bs).symm
  | a :: as => by
    show sumL (fun b => g a b) bs + sumL (fun a => sumL (fun b => g a b) bs) as
      = sumL (fun b => g a b + sumL (fun a => g a b) as) bs
    rw [sumL_swap g bs as, sumL_add]
where
  zeros : ∀ l : List B, sumL (fun _ => 0) l = 0
    | [] => rfl
    | _ :: l => by
      show 0 + sumL (fun _ => 0) l = 0
      rw [zeros l]

theorem gate_mul (b : Bool) (x : Nat) : gate b x = gate b 1 * x := by
  cases b with
  | true => exact (Nat.one_mul x).symm
  | false => exact (nzero_mul x).symm

theorem gate_and_false (b : Bool) (x : Nat) : gate (false && b) x = 0 := rfl

/-! ## Bool equality is equality -/

theorem c3Eq_sound : ∀ a b : C3, c3Eq a b = true → a = b := by
  intro a b h
  cases a <;> cases b <;> first | rfl | exact Bool.noConfusion h

theorem c3Eq_refl : ∀ a : C3, c3Eq a a = true := by
  intro a
  cases a <;> rfl

theorem vEq_sound (u v : V) (h : vEq u v = true) : u = v := by
  have h1 := c3Eq_sound u.1 v.1 (and_true_l h)
  have h2 := c3Eq_sound u.2 v.2 (and_true_r h)
  cases u with
  | mk a b => cases v with
    | mk c d =>
      show (a, b) = (c, d)
      have e1 : a = c := h1
      have e2 : b = d := h2
      rw [e1, e2]

theorem vEq_refl (u : V) : vEq u u = true := by
  show (c3Eq u.1 u.1 && c3Eq u.2 u.2) = true
  rw [c3Eq_refl, c3Eq_refl]
  rfl

theorem lEq_sound : ∀ k P : List V, lEq k P = true → k = P
  | [], [], _ => rfl
  | [], _ :: _, h => Bool.noConfusion h
  | _ :: _, [], h => Bool.noConfusion h
  | u :: us, v :: vs, h => by
    rw [vEq_sound u v (and_true_l h), lEq_sound us vs (and_true_r h)]

theorem lEq_refl : ∀ k : List V, lEq k k = true
  | [] => rfl
  | u :: us => by
    show (vEq u u && lEq us us) = true
    rw [vEq_refl, lEq_refl us]
    rfl

def llEq : List (List V) → List (List V) → Bool
  | [], [] => true
  | [], _ :: _ => false
  | _ :: _, [] => false
  | P :: Ps, Q :: Qs => lEq P Q && llEq Ps Qs

theorem llEq_sound : ∀ A B : List (List V), llEq A B = true → A = B
  | [], [], _ => rfl
  | [], _ :: _, h => Bool.noConfusion h
  | _ :: _, [], h => Bool.noConfusion h
  | P :: Ps, Q :: Qs, h => by
    rw [lEq_sound P Q (and_true_l h), llEq_sound Ps Qs (and_true_r h)]

/-! ## Membership and the fiber lemma -/

def memB (k : List V) : List (List V) → Bool
  | [] => false
  | P :: Ps => lEq k P || memB k Ps

def nodupB : List (List V) → Bool
  | [] => true
  | P :: Ps => !(memB P Ps) && nodupB Ps

theorem or_false_l {a b : Bool} (h : (a || b) = true) (ha : a = false) : b = true := by
  rw [ha] at h
  exact h

theorem fiber_zero (k : List V) (g : List V → Nat) :
    ∀ Ps, memB k Ps = false → sumL (fun P => gate (lEq k P) (g P)) Ps = 0
  | [], _ => rfl
  | P :: Ps, h => by
    show gate (lEq k P) (g P) + sumL (fun P => gate (lEq k P) (g P)) Ps = 0
    cases e : lEq k P with
    | true =>
      have h' : (lEq k P || memB k Ps) = false := h
      rw [e] at h'
      exact Bool.noConfusion h'
    | false =>
      have h' : (lEq k P || memB k Ps) = false := h
      rw [e] at h'
      show 0 + _ = 0
      rw [fiber_zero k g Ps h']

/-- **Fiber lemma.** If `k` is in the list and the list has no repeats, the
    indicator sum picks out `g k`. -/
theorem fiber (k : List V) (g : List V → Nat) :
    ∀ Ps, memB k Ps = true → nodupB Ps = true → sumL (fun P => gate (lEq k P) (g P)) Ps = g k
  | [], h, _ => Bool.noConfusion h
  | P :: Ps, h, hn => by
    show gate (lEq k P) (g P) + sumL (fun P => gate (lEq k P) (g P)) Ps = g k
    have hn1 : memB P Ps = false := by
      cases e : memB P Ps with
      | false => rfl
      | true =>
        have hn' : (!(memB P Ps) && nodupB Ps) = true := hn
        rw [e] at hn'
        exact Bool.noConfusion hn'
    have hn2 : nodupB Ps = true := and_true_r hn
    cases e : lEq k P with
    | true =>
      have kP : k = P := lEq_sound k P e
      show g P + _ = g k
      rw [← kP] at hn1
      rw [fiber_zero k g Ps hn1, ← kP]
      rfl
    | false =>
      show 0 + _ = g k
      rw [nzero_add]
      exact fiber k g Ps (or_false_l h e) hn2

/-! ## Counting velocities, sorting -/

/-- Number of copies of `v` in a cell. -/
def cntV (v : V) : List V → Nat
  | [] => 0
  | u :: us => ind (vEq u v) + cntV v us

def insV (u : V) : List V → List V
  | [] => [u]
  | w :: ws => sel (sb (idx u) (idx w)) (u :: w :: ws) (w :: insV u ws)

def sortV : List V → List V
  | [] => []
  | u :: us => insV u (sortV us)

theorem cnt_ins (v u : V) : ∀ l, cntV v (insV u l) = ind (vEq u v) + cntV v l
  | [] => rfl
  | w :: ws => by
    show cntV v (sel (sb (idx u) (idx w)) (u :: w :: ws) (w :: insV u ws)) = _
    cases sb (idx u) (idx w) with
    | zero => rfl
    | succ k =>
      show ind (vEq w v) + cntV v (insV u ws) = ind (vEq u v) + (ind (vEq w v) + cntV v ws)
      rw [cnt_ins v u ws]
      exact nadd_left_comm _ _ _

theorem cnt_sort (v : V) : ∀ l, cntV v (sortV l) = cntV v l
  | [] => rfl
  | u :: us => by
    show cntV v (insV u (sortV us)) = ind (vEq u v) + cntV v us
    rw [cnt_ins, cnt_sort v us]

/-- The cell collision on any list of velocities: sort, then `cellColl`. -/
def cc (M : List V) : List V := cellColl (sortV M)

/-- The 45 sorted pairs. -/
def pairs2 : List (List V) := msets allV 2

theorem pairs2_nodup : nodupB pairs2 = true := rfl

theorem pairs2_mem (a b : V) : memB (sortV [a, b]) pairs2 = true := by
  cases a with
  | mk a1 a2 => cases b with
    | mk b1 b2 => cases a1 <;> cases a2 <;> cases b1 <;> cases b2 <;> rfl

theorem cc_nil : cc [] = [] := rfl

theorem cc_single (a : V) : cc [a] = [a] := by
  cases a with
  | mk a1 a2 => cases a1 <;> cases a2 <;> rfl

/-- **A pair of equal velocities never collides** (its class has one element). -/
theorem same_velocity_no_coll (a : V) : cc [a, a] = [a, a] := by
  cases a with
  | mk a1 a2 => cases a1 <;> cases a2 <;> rfl

/-! ## The exact hierarchy -/

/-- At most two particles. -/
def small : List V → Bool
  | [] => true
  | [_] => true
  | [_, _] => true
  | _ :: _ :: _ :: _ => false

/-- One-particle count after the step. -/
def Fnext (v : V) (E : List (List V)) : Nat := sumL (fun M => cntV v (cc M)) E

/-- One-particle count after streaming, before the collision. -/
def Fstr (v : V) (E : List (List V)) : Nat := sumL (fun M => cntV v M) E

/-- Pair count: worlds whose cell holds exactly the pair `P` (and nothing else). -/
def F2 (P : List V) (E : List (List V)) : Nat := sumL (fun M => gate (small M && lEq (sortV M) P) 1) E

/-- Gain and loss of `v` from two-particle cells, written with `F2`. -/
def Gain2 (v : V) (E : List (List V)) : Nat := sumL (fun P => F2 P E * cntV v (cellColl P)) pairs2
def Loss2 (v : V) (E : List (List V)) : Nat := sumL (fun P => F2 P E * cntV v P) pairs2

/-- The same from cells with three or more particles. -/
def G3 (v : V) (E : List (List V)) : Nat := sumL (fun M => gate (!(small M)) (cntV v (cc M))) E
def L3 (v : V) (E : List (List V)) : Nat := sumL (fun M => gate (!(small M)) (cntV v M)) E

/-- Per world: the two-particle indicator sum, through the pair list. -/
theorem pair_world (M : List V) (g : List V → Nat) :
    sumL (fun P => gate (small M && lEq (sortV M) P) (g P)) pairs2
      = gate (small M && memB (sortV M) pairs2) (g (sortV M)) := by
  cases hs : small M with
  | false => exact fiber_zero_all _
  | true =>
    show sumL (fun P => gate (lEq (sortV M) P) (g P)) pairs2 = gate (memB (sortV M) pairs2) (g (sortV M))
    cases hm : memB (sortV M) pairs2 with
    | true => exact fiber (sortV M) g pairs2 hm pairs2_nodup
    | false => exact fiber_zero (sortV M) g pairs2 hm
where
  fiber_zero_all : ∀ Ps : List (List V), sumL (fun P => gate (false && lEq (sortV M) P) (g P)) Ps = 0
    | [] => rfl
    | _ :: Ps => by
      show 0 + _ = 0
      rw [fiber_zero_all Ps]

theorem gate_true (x : Nat) : gate true x = x := rfl
theorem gate_false (x : Nat) : gate false x = 0 := rfl

theorem single_not_pair (a : V) : memB (sortV [a]) pairs2 = false := by
  cases a with
  | mk a1 a2 => cases a1 <;> cases a2 <;> rfl

/-- One world, all four shapes of cell. -/
theorem world_identity (v : V) (M : List V) :
    cntV v (cc M) + gate (small M && memB (sortV M) pairs2) (cntV v (sortV M))
        + gate (!(small M)) (cntV v M)
      = cntV v M + gate (small M && memB (sortV M) pairs2) (cntV v (cellColl (sortV M)))
        + gate (!(small M)) (cntV v (cc M)) := by
  match M with
  | [] => rfl
  | [a] =>
    have h1 : (small [a] && memB (sortV [a]) pairs2) = false := by
      rw [single_not_pair]
      rfl
    have h2 : (!(small [a])) = false := rfl
    rw [h1, h2, gate_false, gate_false, gate_false, gate_false, cc_single]
  | [a, b] =>
    have h1 : (small [a, b] && memB (sortV [a, b]) pairs2) = true := by
      rw [pairs2_mem]
      rfl
    have h2 : (!(small [a, b])) = false := rfl
    rw [h1, h2, gate_true, gate_true, gate_false, gate_false, Nat.add_zero, Nat.add_zero, cnt_sort]
    exact nadd_comm _ _
  | a :: b :: c :: rest =>
    have h1 : (small (a :: b :: c :: rest) && memB (sortV (a :: b :: c :: rest)) pairs2) = false := rfl
    have h2 : (!(small (a :: b :: c :: rest))) = true := rfl
    rw [h1, h2, gate_true, gate_true, gate_false, gate_false, Nat.add_zero, Nat.add_zero]
    exact nadd_comm _ _

theorem gain2_eq (v : V) (E : List (List V)) :
    Gain2 v E = sumL (fun M => gate (small M && memB (sortV M) pairs2) (cntV v (cellColl (sortV M)))) E := by
  show sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) 1) E * cntV v (cellColl P)) pairs2 = _
  have e1 : sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) 1) E * cntV v (cellColl P)) pairs2
      = sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) (cntV v (cellColl P))) E) pairs2 :=
    sumL_ext _ _ (fun P => by
      rw [← sumL_mul]
      exact sumL_ext _ _ (fun M => (gate_mul _ _).symm) E) pairs2
  rw [e1, ← sumL_swap]
  exact sumL_ext _ _ (fun M => pair_world M (fun P => cntV v (cellColl P))) E

theorem loss2_eq (v : V) (E : List (List V)) :
    Loss2 v E = sumL (fun M => gate (small M && memB (sortV M) pairs2) (cntV v (sortV M))) E := by
  show sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) 1) E * cntV v P) pairs2 = _
  have e1 : sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) 1) E * cntV v P) pairs2
      = sumL (fun P => sumL (fun M => gate (small M && lEq (sortV M) P) (cntV v P)) E) pairs2 :=
    sumL_ext _ _ (fun P => by
      rw [← sumL_mul]
      exact sumL_ext _ _ (fun M => (gate_mul _ _).symm) E) pairs2
  rw [e1, ← sumL_swap]
  exact sumL_ext _ _ (fun M => pair_world M (fun P => cntV v P)) E

/-- **The exact hierarchy.** For every ensemble and every velocity:
    `F'(v) + Loss2(v) + L3(v) = F(v) + Gain2(v) + G3(v)`.
    The change of the one-particle count is the two-particle collision term,
    written with the pair count `F2`, plus the term of cells with ≥ 3 particles. -/
theorem hierarchy (v : V) (E : List (List V)) :
    Fnext v E + Loss2 v E + L3 v E = Fstr v E + Gain2 v E + G3 v E := by
  rw [gain2_eq, loss2_eq]
  show sumL _ E + sumL _ E + sumL _ E = sumL _ E + sumL _ E + sumL _ E
  rw [← sumL_add, ← sumL_add, ← sumL_add, ← sumL_add]
  exact sumL_ext _ _ (world_identity v) E

/-- Every world has at most two particles in the cell. -/
def AllSmall : List (List V) → Prop
  | [] => True
  | M :: Ms => small M = true ∧ AllSmall Ms

theorem g3_zero (v : V) : ∀ E, AllSmall E → G3 v E = 0
  | [], _ => rfl
  | M :: Ms, h => by
    show gate (!(small M)) (cntV v (cc M)) + G3 v Ms = 0
    rw [h.1, g3_zero v Ms h.2]
    rfl

theorem l3_zero (v : V) : ∀ E, AllSmall E → L3 v E = 0
  | [], _ => rfl
  | M :: Ms, h => by
    show gate (!(small M)) (cntV v M) + L3 v Ms = 0
    rw [h.1, l3_zero v Ms h.2]
    rfl

/-- **Dilute case.** If no cell holds three or more particles, the change of
    `F` is exactly the pair collision term in `F2`:
    `F'(v) + Loss2(v) = F(v) + Gain2(v)`. -/
theorem hierarchy_dilute (v : V) (E : List (List V)) (h : AllSmall E) :
    Fnext v E + Loss2 v E = Fstr v E + Gain2 v E := by
  have e := hierarchy v E
  rw [g3_zero v E h, l3_zero v E h, Nat.add_zero, Nat.add_zero] at e
  exact e

/-! ## Molecular chaos: when it holds, and that one step breaks it -/

/-- **Product ensembles factorise.** If the occupations of two velocities are
    chosen independently (all pairs `(a, b)` from `A × B`), then
    `Σ_a Σ_b a b = (Σ a)(Σ b)`: the pair density is the product of the
    one-particle densities, `f2 = f f`. -/
theorem chaos_product (A B : List Nat) :
    sumL (fun a => sumL (fun b => a * b) B) A = sumL (fun a => a) A * sumL (fun b => b) B := by
  have e : sumL (fun a => sumL (fun b => a * b) B) A = sumL (fun a => a * sumL (fun b => b) B) A :=
    sumL_ext _ _ (fun a => sumL_cmul (fun b => b) a B) A
  rw [e, sumL_mul]

/-- Two velocities `(1,0)` and `(-1,0)`, each present or absent independently:
    four worlds, a product ensemble. -/
def chaosEns : List (List V) := [[], [(.p, .z)], [(.m, .z)], [(.m, .z), (.p, .z)]]

/-- **Chaos is not kept by a step.** Before the collision,
    `4 · Σ n₊ n₋ = (Σ n₊)(Σ n₋)`: with four worlds, `f2 = 1/4 = (1/2)(1/2) = f f`.
    After one collision the turned velocities `(0,1)` and `(0,-1)` have
    `4 · Σ n_↑ n_↓ = 4` but `(Σ n_↑)(Σ n_↓) = 1`: `f2 = 1/4 ≠ 1/16 = f f`. -/
theorem chaos_not_kept :
    4 * sumL (fun M => cntV (.p, .z) M * cntV (.m, .z) M) chaosEns
        = sumL (fun M => cntV (.p, .z) M) chaosEns * sumL (fun M => cntV (.m, .z) M) chaosEns ∧
    4 * sumL (fun M => cntV (.z, .p) (cc M) * cntV (.z, .m) (cc M)) chaosEns = 4 ∧
    sumL (fun M => cntV (.z, .p) (cc M)) chaosEns * sumL (fun M => cntV (.z, .m) (cc M)) chaosEns = 1 :=
  ⟨rfl, rfl, rfl⟩

/-! ## Semi-detailed balance -/

/-- A commutative monoid, given by its operations and laws. -/
structure ACM (R : Type) where
  add : R → R → R
  zero : R
  add_assoc : ∀ a b c, add (add a b) c = add a (add b c)
  add_comm : ∀ a b, add a b = add b a
  zero_add : ∀ a, add zero a = a

section Monoid
variable {R : Type} (K : ACM R)

def sumR {A : Type} (f : A → R) : List A → R
  | [] => K.zero
  | a :: as => K.add (f a) (sumR f as)

/-- `n • x`. -/
def nsm (x : R) : Nat → R
  | 0 => K.zero
  | n + 1 => K.add x (nsm x n)

def keyP (P : List V) : Nat := sumL (fun u => idx u) P + 9 * idx (headOr (.z, .z) P)

def insL (P : List V) : List (List V) → List (List V)
  | [] => [P]
  | Q :: Qs => sel (sb (keyP P) (keyP Q)) (P :: Q :: Qs) (Q :: insL P Qs)

def sortL : List (List V) → List (List V)
  | [] => []
  | P :: Ps => insL P (sortL Ps)

theorem sumR_ins (f : List V → R) (P : List V) :
    ∀ l, sumR K f (insL P l) = K.add (f P) (sumR K f l)
  | [] => rfl
  | Q :: Qs => by
    show sumR K f (sel (sb (keyP P) (keyP Q)) (P :: Q :: Qs) (Q :: insL P Qs)) = _
    cases sb (keyP P) (keyP Q) with
    | zero => rfl
    | succ k =>
      show K.add (f Q) (sumR K f (insL P Qs)) = K.add (f P) (K.add (f Q) (sumR K f Qs))
      rw [sumR_ins f P Qs, ← K.add_assoc, K.add_comm (f Q) (f P), K.add_assoc]

theorem sumR_sort (f : List V → R) : ∀ l, sumR K f (sortL l) = sumR K f l
  | [] => rfl
  | P :: Ps => by
    show sumR K f (insL P (sortL Ps)) = K.add (f P) (sumR K f Ps)
    rw [sumR_ins, sumR_sort f Ps]

theorem sumR_map (f : List V → R) (g : List V → List V) :
    ∀ l, sumR K f (l.map g) = sumR K (fun P => f (g P)) l
  | [] => rfl
  | P :: Ps => by
    show K.add (f (g P)) (sumR K f (Ps.map g)) = K.add (f (g P)) (sumR K (fun P => f (g P)) Ps)
    rw [sumR_map f g Ps]

theorem sumR_ext {A : Type} (f g : A → R) (h : ∀ a, f a = g a) : ∀ l, sumR K f l = sumR K g l
  | [] => rfl
  | a :: as => by
    show K.add (f a) (sumR K f as) = K.add (g a) (sumR K g as)
    rw [h a, sumR_ext f g h as]

/-- The 45 pairs, written out. -/
def pairsLit : List (List V) :=
    [[(.p, .p), (.p, .p)], [(.p, .z), (.p, .p)], [(.p, .z), (.p, .z)], [(.p, .m), (.p, .p)], [(.p,
    .m), (.p, .z)], [(.p, .m), (.p, .m)], [(.z, .p), (.p, .p)], [(.z, .p), (.p, .z)], [(.z, .p),
    (.p, .m)], [(.z, .p), (.z, .p)], [(.z, .z), (.p, .p)], [(.z, .z), (.p, .z)], [(.z, .z), (.p,
    .m)], [(.z, .z), (.z, .p)], [(.z, .z), (.z, .z)], [(.z, .m), (.p, .p)], [(.z, .m), (.p, .z)],
    [(.z, .m), (.p, .m)], [(.z, .m), (.z, .p)], [(.z, .m), (.z, .z)], [(.z, .m), (.z, .m)], [(.m,
    .p), (.p, .p)], [(.m, .p), (.p, .z)], [(.m, .p), (.p, .m)], [(.m, .p), (.z, .p)], [(.m, .p),
    (.z, .z)], [(.m, .p), (.z, .m)], [(.m, .p), (.m, .p)], [(.m, .z), (.p, .p)], [(.m, .z), (.p,
    .z)], [(.m, .z), (.p, .m)], [(.m, .z), (.z, .p)], [(.m, .z), (.z, .z)], [(.m, .z), (.z, .m)],
    [(.m, .z), (.m, .p)], [(.m, .z), (.m, .z)], [(.m, .m), (.p, .p)], [(.m, .m), (.p, .z)], [(.m,
    .m), (.p, .m)], [(.m, .m), (.z, .p)], [(.m, .m), (.z, .z)], [(.m, .m), (.z, .m)], [(.m, .m),
    (.m, .p)], [(.m, .m), (.m, .z)], [(.m, .m), (.m, .m)]]

/-- Their images under the collision, written out. -/
def collLit : List (List V) :=
    [[(.p, .p), (.p, .p)], [(.p, .z), (.p, .p)], [(.p, .z), (.p, .z)], [(.p, .m), (.p, .p)], [(.p,
    .m), (.p, .z)], [(.p, .m), (.p, .m)], [(.z, .p), (.p, .p)], [(.z, .z), (.p, .p)], [(.z, .m),
    (.p, .p)], [(.z, .p), (.z, .p)], [(.z, .p), (.p, .z)], [(.z, .z), (.p, .z)], [(.z, .m), (.p,
    .z)], [(.z, .z), (.z, .p)], [(.z, .z), (.z, .z)], [(.z, .p), (.p, .m)], [(.z, .z), (.p, .m)],
    [(.z, .m), (.p, .m)], [(.m, .z), (.p, .z)], [(.z, .m), (.z, .z)], [(.z, .m), (.z, .m)], [(.m,
    .p), (.p, .p)], [(.m, .z), (.p, .p)], [(.m, .m), (.p, .p)], [(.m, .p), (.z, .p)], [(.m, .z),
    (.z, .p)], [(.m, .m), (.z, .p)], [(.m, .p), (.m, .p)], [(.m, .p), (.p, .z)], [(.z, .m), (.z,
    .p)], [(.m, .m), (.p, .z)], [(.m, .p), (.z, .z)], [(.m, .z), (.z, .z)], [(.m, .m), (.z, .z)],
    [(.m, .z), (.m, .p)], [(.m, .z), (.m, .z)], [(.m, .p), (.p, .m)], [(.m, .z), (.p, .m)], [(.m,
    .m), (.p, .m)], [(.m, .p), (.z, .m)], [(.m, .z), (.z, .m)], [(.m, .m), (.z, .m)], [(.m, .m),
    (.m, .p)], [(.m, .m), (.m, .z)], [(.m, .m), (.m, .m)]]

set_option maxRecDepth 100000 in
theorem pairs2_lit : pairs2 = pairsLit := llEq_sound _ _ (by rfl)

set_option maxHeartbeats 1000000 in
set_option maxRecDepth 100000 in
theorem map_lit : pairs2.map cellColl = collLit := llEq_sound _ _ (by rfl)

set_option maxHeartbeats 1000000 in
set_option maxRecDepth 100000 in
/-- **The pair collision permutes the 45 pairs**: sorting the images gives the
    sorted pairs. -/
theorem pairs_perm : sortL collLit = sortL pairsLit := llEq_sound _ _ (by rfl)

/-- Summing over the collided pairs is summing over the pairs. -/
theorem sum_perm (f : List V → R) :
    sumR K (fun P => f (cellColl P)) pairs2 = sumR K f pairs2 :=
  calc sumR K (fun P => f (cellColl P)) pairs2 = sumR K f (pairs2.map cellColl) := (sumR_map K f cellColl pairs2).symm
    _ = sumR K f collLit := by rw [map_lit]
    _ = sumR K f (sortL collLit) := (sumR_sort K f collLit).symm
    _ = sumR K f (sortL pairsLit) := by rw [pairs_perm]
    _ = sumR K f pairsLit := sumR_sort K f pairsLit
    _ = sumR K f pairs2 := by rw [pairs2_lit]

/-- **Semi-detailed balance.** If the pair weight `F` (for example
    `f_u f_w` with `f` a function of the conserved quantities) is the same on
    a pair and on its collided pair, the closed gain of every velocity equals
    its closed loss. -/
theorem balance (F : List V → R) (hF : ∀ P, F (cellColl P) = F P) (v : V) :
    sumR K (fun P => nsm K (F P) (cntV v (cellColl P))) pairs2
      = sumR K (fun P => nsm K (F P) (cntV v P)) pairs2 := by
  have e : sumR K (fun P => nsm K (F P) (cntV v (cellColl P))) pairs2
      = sumR K (fun P => nsm K (F (cellColl P)) (cntV v (cellColl P))) pairs2 :=
    sumR_ext K _ _ (fun P => by rw [hF P]) pairs2
  rw [e]
  exact sum_perm K (fun P => nsm K (F P) (cntV v P))

end Monoid

/-! ## Moments: the collision terms carry no number, momentum or energy -/

def memV (k : V) : List V → Bool
  | [] => false
  | u :: us => vEq k u || memV k us

def nodupV : List V → Bool
  | [] => true
  | u :: us => !(memV u us) && nodupV us

theorem memV_all (u : V) : memV u allV = true := by
  cases u with
  | mk a b => cases a <;> cases b <;> rfl

theorem fiber_zeroV (k : V) (g : V → Nat) :
    ∀ us, memV k us = false → sumL (fun u => gate (vEq k u) (g u)) us = 0
  | [], _ => rfl
  | u :: us, h => by
    show gate (vEq k u) (g u) + sumL (fun u => gate (vEq k u) (g u)) us = 0
    cases e : vEq k u with
    | true =>
      have h' : (vEq k u || memV k us) = false := h
      rw [e] at h'
      exact Bool.noConfusion h'
    | false =>
      have h' : (vEq k u || memV k us) = false := h
      rw [e] at h'
      show 0 + _ = 0
      rw [fiber_zeroV k g us h']

theorem fiberV2 (k : V) (g : V → Nat) :
    ∀ us, memV k us = true → nodupV us = true → sumL (fun u => gate (vEq k u) (g u)) us = g k
  | [], h, _ => Bool.noConfusion h
  | u :: us, h, hn => by
    show gate (vEq k u) (g u) + sumL (fun u => gate (vEq k u) (g u)) us = g k
    have hn1 : memV u us = false := by
      cases e : memV u us with
      | false => rfl
      | true =>
        have hn' : (!(memV u us) && nodupV us) = true := hn
        rw [e] at hn'
        exact Bool.noConfusion hn'
    have hn2 : nodupV us = true := and_true_r hn
    cases e : vEq k u with
    | true =>
      have ku : k = u := vEq_sound k u e
      show g u + _ = g k
      rw [← ku] at hn1
      rw [fiber_zeroV k g us hn1, ← ku]
      rfl
    | false =>
      show 0 + _ = g k
      rw [nzero_add]
      exact fiberV2 k g us (or_false_l h e) hn2

theorem gate_ind (b : Bool) (x : Nat) : x * ind b = gate b x := by
  cases b with
  | true => exact Nat.mul_one x
  | false => rfl

/-- `Σ_v w(v) [u = v] = w(u)`. -/
theorem pick (w : V → Nat) (u : V) : sumL (fun v => w v * ind (vEq u v)) allV = w u := by
  have e : sumL (fun v => w v * ind (vEq u v)) allV = sumL (fun v => gate (vEq u v) (w v)) allV :=
    sumL_ext _ _ (fun v => gate_ind _ _) allV
  rw [e]
  exact fiberV u w
where
  fiberV (u : V) (w : V → Nat) : sumL (fun v => gate (vEq u v) (w v)) allV = w u :=
    fiberV2 u w allV (memV_all u) rfl

/-- `Σ_v w(v) · #(v in M) = Σ_{u ∈ M} w(u)`. -/
theorem moment_cell (w : V → Nat) : ∀ M, sumL (fun v => w v * cntV v M) allV = vsum w M
  | [] => sumL_zero
  | u :: us => by
    show sumL (fun v => w v * (ind (vEq u v) + cntV v us)) allV = w u + vsum w us
    have e : sumL (fun v => w v * (ind (vEq u v) + cntV v us)) allV
        = sumL (fun v => w v * ind (vEq u v) + w v * cntV v us) allV :=
      sumL_ext _ _ (fun v => nleft_distrib _ _ _) allV
    rw [e, sumL_add, pick, moment_cell w us]
where
  sumL_zero : sumL (fun v => w v * cntV v []) allV = vsum w [] := rfl

/-- **The exact collision term has no moments**: for `w` one of the four
    conserved weights, `Σ_v w(v) F'(v) = Σ_v w(v) F(v)` in every cell. -/
theorem moments_exact (w : V → Nat) (hw : CellCons w) (E : List (List V)) :
    sumL (fun v => w v * Fnext v E) allV = sumL (fun v => w v * Fstr v E) allV := by
  show sumL (fun v => w v * sumL (fun M => cntV v (cc M)) E) allV
    = sumL (fun v => w v * sumL (fun M => cntV v M) E) allV
  have e1 : ∀ (g : V → List V → Nat),
      sumL (fun v => w v * sumL (fun M => g v M) E) allV
        = sumL (fun M => sumL (fun v => w v * g v M) allV) E := fun g =>
    (sumL_ext _ _ (fun v => (sumL_cmul (fun M => g v M) (w v) E).symm) allV).trans
      (sumL_swap (fun v M => w v * g v M) E allV)
  rw [e1 (fun v M => cntV v (cc M)), e1 (fun v M => cntV v M)]
  exact sumL_ext _ _ (fun M => by
    rw [moment_cell, moment_cell]
    exact hw (sortV M) |>.trans (vsum_sort w M)) E
where
  vsum_sort (w : V → Nat) (M : List V) : vsum w (sortV M) = vsum w M := by
    rw [← moment_cell w (sortV M), ← moment_cell w M]
    exact sumL_ext _ _ (fun v => by rw [cnt_sort]) allV

/-- **The closed (two-particle) collision term has no moments either**, for
    any pair weights `F2`: `Σ_v w(v) Gain2(v) = Σ_v w(v) Loss2(v)`. -/
theorem moments_closed (w : V → Nat) (hw : CellCons w) (G : List V → Nat) :
    sumL (fun v => w v * sumL (fun P => G P * cntV v (cellColl P)) pairs2) allV
      = sumL (fun v => w v * sumL (fun P => G P * cntV v P) pairs2) allV := by
  have e1 : ∀ (g : V → List V → Nat),
      sumL (fun v => w v * sumL (fun P => G P * g v P) pairs2) allV
        = sumL (fun P => G P * sumL (fun v => w v * g v P) allV) pairs2 := fun g =>
    ((sumL_ext _ _ (fun v => (sumL_cmul (fun P => G P * g v P) (w v) pairs2).symm) allV).trans
      (sumL_swap (fun v P => w v * (G P * g v P)) pairs2 allV)).trans
      (sumL_ext _ _ (fun P => (sumL_ext _ _ (fun v => by
          rw [← nmul_assoc, nmul_comm (w v) (G P), nmul_assoc]) allV).trans
        (sumL_cmul (fun v => w v * g v P) (G P) allV)) pairs2)
  rw [e1 (fun v P => cntV v (cellColl P)), e1 (fun v P => cntV v P)]
  refine sumL_ext _ _ (fun P => ?_) pairs2
  rw [moment_cell, moment_cell, hw P]

end KineticChain

#print axioms KineticChain.sumL_ext
#print axioms KineticChain.sumL_add
#print axioms KineticChain.sumL_mul
#print axioms KineticChain.sumL_cmul
#print axioms KineticChain.sumL_swap
#print axioms KineticChain.gate_mul
#print axioms KineticChain.gate_and_false
#print axioms KineticChain.c3Eq_sound
#print axioms KineticChain.c3Eq_refl
#print axioms KineticChain.vEq_sound
#print axioms KineticChain.vEq_refl
#print axioms KineticChain.lEq_sound
#print axioms KineticChain.lEq_refl
#print axioms KineticChain.llEq_sound
#print axioms KineticChain.or_false_l
#print axioms KineticChain.fiber_zero
#print axioms KineticChain.fiber
#print axioms KineticChain.cnt_ins
#print axioms KineticChain.cnt_sort
#print axioms KineticChain.pairs2_nodup
#print axioms KineticChain.pairs2_mem
#print axioms KineticChain.cc_nil
#print axioms KineticChain.cc_single
#print axioms KineticChain.same_velocity_no_coll
#print axioms KineticChain.pair_world
#print axioms KineticChain.gate_true
#print axioms KineticChain.gate_false
#print axioms KineticChain.single_not_pair
#print axioms KineticChain.world_identity
#print axioms KineticChain.gain2_eq
#print axioms KineticChain.loss2_eq
#print axioms KineticChain.hierarchy
#print axioms KineticChain.g3_zero
#print axioms KineticChain.l3_zero
#print axioms KineticChain.hierarchy_dilute
#print axioms KineticChain.chaos_product
#print axioms KineticChain.chaos_not_kept
#print axioms KineticChain.sumR_ins
#print axioms KineticChain.sumR_sort
#print axioms KineticChain.sumR_map
#print axioms KineticChain.sumR_ext
#print axioms KineticChain.pairs2_lit
#print axioms KineticChain.map_lit
#print axioms KineticChain.pairs_perm
#print axioms KineticChain.sum_perm
#print axioms KineticChain.balance
#print axioms KineticChain.memV_all
#print axioms KineticChain.fiber_zeroV
#print axioms KineticChain.fiberV2
#print axioms KineticChain.gate_ind
#print axioms KineticChain.pick
#print axioms KineticChain.moment_cell
#print axioms KineticChain.moments_exact
#print axioms KineticChain.moments_closed

Listing 368: numeric_fluid.py: the particle dynamics and the fluid modes

numeric_fluid.py

#!/usr/bin/env python3
"""T15 numerics: the FluidChain lattice gas, its hydrodynamic modes.

Python standard library only, fixed seeds. The model is the one defined in
work/FluidChain.lean (same velocity listing, same collision table, same
stable sort by cell, same pairing of neighbours in the sorted list).

Writes work/NUMERIC_FLUID.txt next to this script.
"""
import cmath
import math
import os
import random

# ---------------------------------------------------------------- the model
# components m, z, p  <->  -1, 0, +1 ; sh = v + 1 ; sq = v^2
COMP = [-1, 0, 1]
ALLV = [(a, b) for a in COMP for b in COMP]          # same order as allV in Lean
IDX = {v: 3 * (v[0] + 1) + (v[1] + 1) for v in ALLV}  # idx in Lean


def mx(v): return v[0] + 1
def my(v): return v[1] + 1
def en(v): return v[0] * v[0] + v[1] * v[1]


_MS = {}


def msets(start, n):
    """Sorted velocity lists of length n from ALLV[start:], in the order of `msets` in Lean."""
    k = (start, n)
    if k in _MS:
        return _MS[k]
    if start == len(ALLV):
        r = [()] if n == 0 else []
    else:
        u = ALLV[start]
        r = [(u,) * c + M for c in range(n + 1) for M in msets(start + 1, n - c)]
    _MS[k] = r
    return r


def cls_key(M):
    return (len(M), sum(mx(v) for v in M), sum(my(v) for v in M), sum(en(v) for v in M))


_CLS = {}
_CC = {}


def cell_coll(M):
    """The next multiset with the same (N, Mx, My, E), cyclically (cellColl in Lean)."""
    if M in _CC:
        return _CC[M]
    n = len(M)
    if n not in _CLS:
        groups = {}
        for Q in msets(0, n):
            groups.setdefault(cls_key(Q), []).append(Q)
        _CLS[n] = groups
    cls = _CLS[n][cls_key(M)]
    i = cls.index(M)
    r = cls[i + 1] if i + 1 < len(cls) else cls[0]
    _CC[M] = r
    return r


def step(L, ps):
    """ps: list of (x, y, v). Stream, stable sort by (cell, idx), collide each cell."""
    moved = [((x + v[0]) % L, (y + v[1]) % L, v) for (x, y, v) in ps]
    moved.sort(key=lambda q: (q[0] * L + q[1]) * 9 + IDX[q[2]])   # stable, as insP/isortP
    out = []
    i, n = 0, len(moved)
    while i < n:
        j = i + 1
        while j < n and moved[j][0] == moved[i][0] and moved[j][1] == moved[i][1]:
            j += 1
        M = tuple(q[2] for q in moved[i:j])
        x, y = moved[i][0], moved[i][1]
        out += [(x, y, v) for v in cell_coll(M)]
        i = j
    return out


def totals(ps):
    return (len(ps), sum(mx(v) for _, _, v in ps), sum(my(v) for _, _, v in ps),
            sum(en(v) for _, _, v in ps))


# ---------------------------------------------------------- equilibrium
def occupations(rho, beta):
    """Invariant measure: occupation n of each (cell, velocity) geometric with z_v = e^{lam - beta e_v}.
    Mean f_v = z_v / (1 - z_v). lam fixed by sum_v f_v = rho."""
    def f(lam):
        return [math.exp(lam - beta * en(v)) / (1 - math.exp(lam - beta * en(v))) for v in ALLV]
    lo, hi = -50.0, -1e-12
    for _ in range(200):
        mid = (lo + hi) / 2
        if sum(f(mid)) < rho:
            lo = mid
        else:
            hi = mid
    lam = (lo + hi) / 2
    return lam, f(lam)


def sound_speed_pred(rho, beta):
    """c^2 = sum chi vx^2 e / (2 sum chi vx^2), chi = f (1 + f): cell balance closed at local equilibrium."""
    _, fs = occupations(rho, beta)
    chi = [x * (1 + x) for x in fs]
    vx2 = sum(c * v[0] ** 2 for c, v in zip(chi, ALLV))
    vx2e = sum(c * v[0] ** 2 * en(v) for c, v in zip(chi, ALLV))
    return math.sqrt(vx2e / (2 * vx2))


def init(L, rho, beta, rng):
    lam, _ = occupations(rho, beta)
    ps = []
    for x in range(L):
        for y in range(L):
            for v in ALLV:
                z = math.exp(lam - beta * en(v))
                n = 0
                while rng.random() < z:
                    n += 1
                ps += [(x, y, v)] * n
    return ps


# --------------------------------------------------------- measurements
def modes(L, ps, ns):
    """Fourier modes along x: rho_k, j^x_k (longitudinal), j^y_k (transverse)."""
    out = []
    for n in ns:
        tab = [cmath.exp(-2j * math.pi * n * x / L) for x in range(L)]
        r = jx = jy = 0j
        for x, _, v in ps:
            e = tab[x]
            r += e
            jx += v[0] * e
            jy += v[1] * e
        out.append((r, jx, jy))
    return out


def autocorr(series, tmax):
    T = len(series)
    c0 = sum(abs(z) ** 2 for z in series) / T
    return [sum((series[s + t] * series[s].conjugate()).real for s in range(T - t)) / (T - t) / c0
            for t in range(tmax + 1)]


def fit_decay(c):
    """Γ from ln C(t) = -Γ t over the range where C > 0.25."""
    ts, ys = [], []
    for t, v in enumerate(c):
        if t == 0:
            continue
        if v <= 0.25:
            break
        ts.append(t)
        ys.append(math.log(v))
    if len(ts) < 2:
        return float('nan')
    tm = sum(ts) / len(ts)
    ym = sum(ys) / len(ys)
    return -sum((t - tm) * (y - ym) for t, y in zip(ts, ys)) / sum((t - tm) ** 2 for t in ts)


def fit_sound(c, tfit):
    """Least squares of e^{-Γ t} cos(ω t) on 0..tfit, by grid then refinement."""
    def err(om, ga):
        return sum((c[t] - math.exp(-ga * t) * math.cos(om * t)) ** 2 for t in range(tfit + 1))
    best = (1e9, 0, 0)
    for i in range(1, 200):
        om = i * 0.005
        for j in range(0, 100):
            ga = j * 0.001
            e = err(om, ga)
            if e < best[0]:
                best = (e, om, ga)
    _, om, ga = best
    h1, h2 = 0.005, 0.001
    for _ in range(40):
        cand = [(err(om + a * h1, ga + b * h2), om + a * h1, ga + b * h2)
                for a in (-1, 0, 1) for b in (-1, 0, 1)]
        e, om, ga = min(cand)
        h1 *= 0.7
        h2 *= 0.7
    return om, ga


def run(L, rho, beta, steps, burn, ns, tmax, seeds):
    """Average the normalised autocorrelations over independent runs (one per seed)."""
    cTs = [[0.0] * (tmax + 1) for _ in ns]
    cLs = [[0.0] * (tmax + 1) for _ in ns]
    cons = []
    for seed in seeds:
        rng = random.Random(seed)
        ps = init(L, rho, beta, rng)
        t0 = totals(ps)
        for _ in range(burn):
            ps = step(L, ps)
        series = [[] for _ in ns]
        for _ in range(steps):
            ps = step(L, ps)
            for i, m in enumerate(modes(L, ps, ns)):
                series[i].append(m)
        cons.append((t0, totals(ps)))
        for i in range(len(ns)):
            cT = autocorr([m[2] for m in series[i]], tmax)
            cL = autocorr([m[1] for m in series[i]], tmax)
            cTs[i] = [a + b / len(seeds) for a, b in zip(cTs[i], cT)]
            cLs[i] = [a + b / len(seeds) for a, b in zip(cLs[i], cL)]
    res = []
    for i, n in enumerate(ns):
        k = 2 * math.pi * n / L
        gT = fit_decay(cTs[i])
        om, gS = fit_sound(cLs[i], min(tmax, int(3 * math.pi / (k * 0.7))))
        res.append(dict(L=L, n=n, k=k, gT=gT, om=om, gS=gS))
    return cons, res


def slope(xs, ys):
    xm = sum(xs) / len(xs)
    ym = sum(ys) / len(ys)
    return sum((x - xm) * (y - ym) for x, y in zip(xs, ys)) / sum((x - xm) ** 2 for x in xs)


def lean_demo():
    """The configuration `demo` of FluidChain.lean after 6 steps on L = 4."""
    m, z, p = -1, 0, 1
    ps = [(0, 0, (p, z)), (2, 0, (m, z)), (1, 3, (z, p)), (3, 1, (p, p)), (1, 1, (z, z))]
    for _ in range(6):
        ps = step(4, ps)
    return [(x, y, IDX[v]) for x, y, v in ps], totals(ps)


LEAN_DEMO_FINAL = [(1, 1, 4), (1, 1, 5), (1, 1, 5), (1, 3, 5), (1, 3, 6)]


def main():
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    out.append("FluidChain lattice gas: 9 velocities, cell collision = next multiset with same (N, Mx, My, E)")
    for n in (2, 3, 4):
        ch = sum(1 for M in msets(0, n) if cell_coll(M) != M)
        out.append(f"  cells with {n} particles: {ch} of {len(msets(0, n))} multisets change in a collision")
    demo, dt = lean_demo()
    out.append(f"  Lean demo after 6 steps (x, y, idx): {demo}")
    out.append(f"  Lean demo totals (N, Mx, My, E) = {dt}")
    check("demo totals = (5, 6, 7, 5) as in FluidChain.demo_run", dt == (5, 6, 7, 5))
    check("demo configuration = FluidChain.demo_final", demo == LEAN_DEMO_FINAL)

    beta, rho = 0.5, 2.0
    c_pred = sound_speed_pred(rho, beta)
    lam, fs = occupations(rho, beta)
    out.append(f"Equilibrium: density {rho} per cell, occupations geometric, z_v = exp(lam - beta e_v), beta = {beta}")
    out.append(f"  lam = {lam:.6f}; mean occupations f_v = " + ", ".join(f"{x:.4f}" for x in fs))
    out.append(f"  closure prediction c = sqrt(Σ χ vx^2 e / (2 Σ χ vx^2)), χ = f(1+f): {c_pred:.6f}")

    rows = []
    for L, seeds, steps in ((32, (1, 2), 8000), (64, (3, 4), 8000)):
        cons, res = run(L, rho, beta, steps=steps, burn=300, ns=(1, 2, 3), tmax=120, seeds=seeds)
        for t0, t1 in cons:
            check(f"L = {L}: (N, Mx, My, E) exactly conserved {t0} -> {t1}", t0 == t1)
        rows += res

    out.append("")
    out.append(" L   n    k       Γ_T      Γ_T/k^2   ω        c=ω/k    Γ_s      Γ_s/k^2")
    for r in rows:
        k2 = r['k'] ** 2
        out.append(f" {r['L']:<3} {r['n']:<3} {r['k']:.4f}  {r['gT']:.5f}  {r['gT'] / k2:.4f}    "
                   f"{r['om']:.5f}  {r['om'] / r['k']:.4f}   {r['gS']:.5f}  {r['gS'] / k2:.4f}")
    small = [r for r in rows if r['k'] < 0.4]
    aT = slope([math.log(r['k']) for r in small], [math.log(r['gT']) for r in small])
    aS = slope([math.log(r['k']) for r in small], [math.log(r['gS']) for r in small])
    aW = slope([math.log(r['k']) for r in small], [math.log(r['om']) for r in small])
    nus = [r['gT'] / r['k'] ** 2 for r in small]
    cs = [r['om'] / r['k'] for r in small]
    nu_mean = sum(nus) / len(nus)
    c_mean = sum(cs) / len(cs)
    gs_mean = sum(r['gS'] / r['k'] ** 2 for r in small) / len(small)
    out.append("")
    out.append(f"  fits over k < 0.4 ({len(small)} points):  Γ_T ∝ k^{aT:.3f},  ω ∝ k^{aW:.3f},  Γ_s ∝ k^{aS:.3f}")
    out.append(f"  ν = <Γ_T/k^2> = {nu_mean:.4f},  Γ_s/k^2 = {gs_mean:.4f},  c = <ω/k> = {c_mean:.4f}")
    out.append(f"  c prediction {c_pred:.4f}, relative difference {abs(c_mean - c_pred) / c_pred:.3f}")
    check("transverse momentum diffuses: exponent of Γ_T in k within 2 ± 0.35", abs(aT - 2) < 0.35)
    check("sound propagates: exponent of ω in k within 1 ± 0.1", abs(aW - 1) < 0.1)
    check("sound speed within 5% of the closure prediction", abs(c_mean - c_pred) / c_pred < 0.05)
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")

    text = "\n".join(out) + "\n"
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "NUMERIC_FLUID.txt")
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(text)
    print(text, end="")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())

Listing 369: numeric_kinetic.py: closure defect, particles against the kinetic equation, H, kinetic modes

numeric_kinetic.py

#!/usr/bin/env python3
"""T18 numerics: particles -> kinetic (Boltzmann form) equation -> fluid, in the FluidChain model.

Python standard library only, fixed seeds. The particle dynamics is the one of
work/FluidChain.lean, imported from numeric_fluid.py (same collision table).

Writes work/NUMERIC_KINETIC.txt next to this script.
"""
import importlib.util
import math
import os
import random

HERE = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("numeric_fluid", os.path.join(HERE, "numeric_fluid.py"))
nf = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(nf)

ALLV, IDX, step, cell_coll, msets = nf.ALLV, nf.IDX, nf.step, nf.cell_coll, nf.msets
mx, my, en = nf.mx, nf.my, nf.en
NV = len(ALLV)

# Pair collision kernel: for each sorted pair P = (u, w), u != w, the change of
# the count of each velocity: K[P][v] = #(v in coll P) - #(v in P).
PAIRS = [P for P in msets(0, 2) if P[0] != P[1]]
KER = []
for P in PAIRS:
    Q = cell_coll(P)
    d = [0] * NV
    for v in Q:
        d[IDX[v]] += 1
    for v in P:
        d[IDX[v]] -= 1
    KER.append((IDX[P[0]], IDX[P[1]], d))
ACTIVE = [k for k in KER if any(k[2])]


def boltz_coll(g):
    """Closed collision: Δf_v = Σ_{pairs u<w} g_u g_w K_v(u,w)."""
    out = list(g)
    for a, b, d in ACTIVE:
        p = g[a] * g[b]
        if p:
            for v in range(NV):
                if d[v]:
                    out[v] += p * d[v]
    return out


def H(f):
    return sum(x * math.log(x) for x in f if x > 0)


# ------------------------------------------------------------- sampling
def sample(L, rho, probs, rng):
    """N = rho L^2 particles, independent uniform cells, velocities from probs (product state)."""
    N = int(round(rho * L * L))
    return [(rng.randrange(L), rng.randrange(L), rng.choices(ALLV, probs)[0]) for _ in range(N)]


def streamed_cells(L, ps):
    """Occupation vectors of all cells after streaming (before collision)."""
    occ = {}
    for x, y, v in ps:
        c = ((x + v[0]) % L, (y + v[1]) % L)
        o = occ.get(c)
        if o is None:
            o = occ[c] = [0] * NV
        o[IDX[v]] += 1
    return occ


# --------------------------------------------- E1: molecular chaos defect
INIT = [0.0] * NV
for v in ((1, 0), (-1, 0), (0, 0)):
    INIT[IDX[v]] = 1 / 3


def pair_stats(occ, ncell):
    """Pre-collision cell statistics: g_v = <n_v>, p2[u,w] = fraction of cells holding exactly {u,w},
    c2[u,w] = <n_u n_w> (u < w), and the fraction of particles in cells with >= 3 particles."""
    g = [0.0] * NV
    p2 = {}
    c2 = {}
    n3 = 0
    ntot = 0
    for o in occ.values():
        nz = [(i, x) for i, x in enumerate(o) if x]
        tot = sum(x for _, x in nz)
        ntot += tot
        if tot >= 3:
            n3 += tot
        for i, x in nz:
            g[i] += x
        for a in range(len(nz)):
            for b in range(a + 1, len(nz)):
                (i, x), (j, y) = nz[a], nz[b]
                c2[(i, j)] = c2.get((i, j), 0) + x * y
        if tot == 2 and len(nz) == 2:
            key = (nz[0][0], nz[1][0])
            p2[key] = p2.get(key, 0) + 1
    g = [x / ncell for x in g]
    return g, {k: v / ncell for k, v in p2.items()}, {k: v / ncell for k, v in c2.items()}, n3 / max(ntot, 1)


def chaos_run(L, rho, steps, reps, seed):
    """Signed differences averaged over time and runs before taking absolute values:
    δ2 = Σ_{u<w} |<p2 - g_u g_w>| / Σ <g_u g_w>  (exact-pair distribution vs product)
    κ  = Σ_{u<w} |<c2 - g_u g_w>| / Σ <g_u g_w>  (full pair correlation)."""
    rng = random.Random(seed)
    keys = [(i, j) for i in range(NV) for j in range(i + 1, NV)]
    d2 = {k: 0.0 for k in keys}
    dk = {k: 0.0 for k in keys}
    gg = {k: 0.0 for k in keys}
    f3 = 0.0
    cnt = 0
    for _ in range(reps):
        ps = sample(L, rho, INIT, rng)
        for _ in range(steps):
            ps = step(L, ps)
            g, p2, c2, n3 = pair_stats(streamed_cells(L, ps), L * L)
            for k in keys:
                prod = g[k[0]] * g[k[1]]
                d2[k] += p2.get(k, 0.0) - prod
                dk[k] += c2.get(k, 0.0) - prod
                gg[k] += prod
            f3 += n3
            cnt += 1
    den = sum(gg.values())
    return (sum(abs(x) for x in d2.values()) / den, sum(abs(x) for x in dk.values()) / den, f3 / cnt)


# ------------------------------------- E2: relaxation, particles vs kinetic
def fvec(ps, L):
    f = [0.0] * NV
    for _, _, v in ps:
        f[IDX[v]] += 1
    return [x / (L * L) for x in f]


def relax_compare(rho, N, T, seed):
    L = int(round(math.sqrt(N / rho)))
    rng = random.Random(seed)
    ps = sample(L, rho, INIT, rng)
    fs = [fvec(ps, L)]
    for _ in range(T):
        ps = step(L, ps)
        fs.append(fvec(ps, L))
    g = list(fs[0])
    fb = [g]
    for _ in range(T):
        g = boltz_coll(g)       # homogeneous: streaming does nothing
        fb.append(g)
    change = sum(abs(a - b) for a, b in zip(fs[0], fs[-1]))
    err = max(sum(abs(a - b) for a, b in zip(x, y)) for x, y in zip(fs, fb))
    tot0 = sum(fs[0])
    return L, err / change, fs, fb, tot0


# ------------------------------------------------- E4: kinetic -> fluid
def maxwell(rho, beta):
    w = [math.exp(-beta * en(v)) for v in ALLV]
    z = sum(w)
    return [rho * x / z for x in w]


def kinetic_modes(L, rho, beta, n, T, eps=1e-4):
    """1D periodic kinetic equation along x. Returns time series of j_y(k) (transverse)
    and j_x(k) (longitudinal), from a shear and from a density perturbation."""
    f0 = maxwell(rho, beta)
    k = 2 * math.pi * n / L
    res = {}
    for kind in ("shear", "sound"):
        f = []
        for x in range(L):
            c = math.cos(k * x)
            if kind == "shear":
                f.append([f0[i] * (1 + eps * v[1] * c) for i, v in enumerate(ALLV)])
            else:
                f.append([f0[i] * (1 + eps * v[0] * c) for i, v in enumerate(ALLV)])
        series = []
        tot = None
        for t in range(T + 1):
            jx = sum(f[x][i] * v[0] * math.cos(k * x) for x in range(L) for i, v in enumerate(ALLV))
            jy = sum(f[x][i] * v[1] * math.cos(k * x) for x in range(L) for i, v in enumerate(ALLV))
            series.append(jy if kind == "shear" else jx)
            if t == T:
                break
            # stream along x (y homogeneous), then collide every cell
            g = [[f[(x - v[0]) % L][i] for i, v in enumerate(ALLV)] for x in range(L)]
            f = [boltz_coll(c) for c in g]
            if tot is None:
                tot = [sum(sum(c[i] * w(v) for i, v in enumerate(ALLV)) for c in f) for w in (lambda v: 1, mx, my, en)]
        tot_end = [sum(sum(c[i] * w(v) for i, v in enumerate(ALLV)) for c in f) for w in (lambda v: 1, mx, my, en)]
        res[kind] = (series, max(abs(a - b) for a, b in zip(tot, tot_end)))
    return k, res


def fit_exp(s):
    ts = [t for t in range(1, len(s)) if s[t] / s[0] > 0.3]
    ys = [math.log(s[t] / s[0]) for t in ts]
    tm = sum(ts) / len(ts)
    ym = sum(ys) / len(ys)
    return -sum((t - tm) * (y - ym) for t, y in zip(ts, ys)) / sum((t - tm) ** 2 for t in ts)


def first_zero(s):
    for t in range(1, len(s)):
        if s[t - 1] > 0 >= s[t] or s[t - 1] < 0 <= s[t]:
            return t - 1 + s[t - 1] / (s[t - 1] - s[t])
    return float('nan')


def kinetic_sound_pred(rho, beta):
    f0 = maxwell(rho, beta)
    a = sum(f * v[0] ** 2 * en(v) for f, v in zip(f0, ALLV))
    b = sum(f * v[0] ** 2 for f, v in zip(f0, ALLV))
    return math.sqrt(a / (2 * b))


def slope(xs, ys):
    xm = sum(xs) / len(xs)
    ym = sum(ys) / len(ys)
    return sum((x - xm) * (y - ym) for x, y in zip(xs, ys)) / sum((x - xm) ** 2 for x in xs)


def main():
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    out.append(f"Pair kernel: {len(PAIRS)} pairs with u != w, {len(ACTIVE)} of them change in a collision")

    # E1
    out.append("")
    out.append("E1. Closure defect before collision, from a product state with velocities (±1,0),(0,0),")
    out.append("    signed differences averaged over 30 steps and all runs, then |.| summed over pairs u < w:")
    out.append("    δ2 = Σ|<p2(u,w) - f_u f_w>| / Σ<f_u f_w>   (p2: cells holding exactly {u,w}; enters the hierarchy)")
    out.append("    κ  = Σ|<n_u n_w> - f_u f_w|  / Σ<f_u f_w>   (full pair correlation)")
    out.append("    φ3 = fraction of particles in cells with >= 3 particles (the remainder G3, L3)")
    out.append("    runs scale as (0.8/rho)^2 so that every row sees about the same number of two-particle cells")
    out.append("    rho     L    runs   δ2       κ        φ3")
    res = {}
    for rho in (0.8, 0.4, 0.2, 0.1):
        for L, base in ((16, 16), (32, 4), (64, 1)):
            reps = int(round(base * (0.8 / rho) ** 2))
            d2, kap, f3 = chaos_run(L, rho, 30, reps, seed=int(1000 * rho) + L)
            res[(rho, L)] = (d2, kap, f3)
            out.append(f"    {rho:<6}  {L:<4} {reps:<5}  {d2:.4f}   {kap:.4f}   {f3:.4f}")
    d_rho = [res[(r, 64)][0] for r in (0.8, 0.4, 0.2, 0.1)]
    k_L = [sum(res[(r, L)][1] for r in (0.8, 0.4, 0.2, 0.1)) / 4 for L in (16, 32, 64)]
    out.append("    δ2 at L = 64 by rho (0.8, 0.4, 0.2, 0.1): " + ", ".join(f"{x:.4f}" for x in d_rho))
    out.append("    κ averaged over rho, by L (16, 32, 64):   " + ", ".join(f"{x:.4f}" for x in k_L))
    check("δ2 decreases as the density decreases (L = 64)", all(d_rho[i] > d_rho[i + 1] for i in range(3)))
    check("κ decreases as L grows (averaged over rho)", k_L[0] > k_L[1] > k_L[2])
    check("φ3 decreases as the density decreases (L = 64)",
          all(res[(r1, 64)][2] > res[(r2, 64)][2] for r1, r2 in ((0.8, 0.4), (0.4, 0.2), (0.2, 0.1))))

    # E2
    out.append("")
    out.append("E2. Homogeneous relaxation: particles vs the closed kinetic equation")
    out.append("    f_v(t+1) = f_v(t) + Σ_{u<w} f_u f_w [#(v in coll(u,w)) - #(v in {u,w})]")
    out.append("    error = max_t Σ_v |f_sim - f_kin| / Σ_v |f_sim(0) - f_sim(T)|")
    errs = []
    for rho, T in ((0.4, 100), (0.2, 200), (0.1, 400)):
        L, e, fs, fb, tot0 = relax_compare(rho, 20000, T, seed=int(rho * 100))
        errs.append(e)
        out.append(f"    rho = {rho:<4} L = {L:<4} T = {T:<4} relative error = {e:.4f}")
        hs = [H(f) for f in fs]
        hb = [H(f) for f in fb]
        out.append(f"      H_sim: {hs[0]:.5f} -> {hs[-1]:.5f};  H_kin: {hb[0]:.5f} -> {hb[-1]:.5f}")
    check("the kinetic equation describes the particles better at lower density", errs[0] > errs[1] > errs[2])
    check("relative error below 10% at rho = 0.1", errs[2] < 0.10)

    # E3
    out.append("")
    out.append("E3. H theorem for the closed kinetic equation, 50 random homogeneous initial states")
    rng = random.Random(77)
    worst = -1.0
    for rho in (0.05, 0.1, 0.2, 0.4):
        for _ in range(50):
            w = [rng.random() ** 3 for _ in range(NV)]
            s = sum(w)
            f = [rho * x / s for x in w]
            h = H(f)
            for _ in range(300):
                f = boltz_coll(f)
                h2 = H(f)
                worst = max(worst, h2 - h)
                h = h2
    out.append(f"    largest one-step increase of H = Σ f ln f over all runs: {worst:.3e}")
    check("H never increases (up to 1e-12) along the closed equation", worst < 1e-12)

    # E4
    out.append("")
    beta, rho = 0.5, 1.0
    cpred = kinetic_sound_pred(rho, beta)
    out.append(f"E4. Kinetic -> fluid: linear modes of the kinetic equation about the Maxwellian")
    out.append(f"    f0_v ∝ exp(-beta e_v), rho = {rho}, beta = {beta}; closure c = sqrt(Σ f0 vx^2 e / (2 Σ f0 vx^2)) = {cpred:.5f}")
    out.append("    L    n   k        Γ_T        Γ_T/k^2   c = ω/k    max |Δ(N,Mx,My,E)|")
    rows = []
    for L, n in ((32, 1), (64, 1), (64, 2), (128, 1)):
        T = int(3 * L / cpred)
        k, res = kinetic_modes(L, rho, beta, n, T)
        gT = fit_exp(res["shear"][0])
        z = first_zero(res["sound"][0])
        om = (math.pi / 2) / z
        cons = max(res["shear"][1], res["sound"][1])
        rows.append((k, gT, om))
        out.append(f"    {L:<4} {n:<3} {k:.5f}  {gT:.6f}  {gT / k ** 2:.4f}    {om / k:.5f}    {cons:.1e}")
        check(f"L = {L}, n = {n}: N, Mx, My, E conserved to 1e-12 by the kinetic equation", cons < 1e-12)
    aT = slope([math.log(r[0]) for r in rows], [math.log(r[1]) for r in rows])
    cs = [r[2] / r[0] for r in rows]
    out.append(f"    Γ_T ∝ k^{aT:.3f};  c at the smallest k = {cs[-1]:.5f} vs closure {cpred:.5f}")
    check("shear diffuses in the kinetic equation: exponent within 2 ± 0.15", abs(aT - 2) < 0.15)
    check("sound speed of the kinetic equation within 2% of the closure", abs(cs[-1] - cpred) / cpred < 0.02)

    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_KINETIC.txt"), "w", encoding="utf-8") as fh:
        fh.write(text)
    print(text, end="")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())

Listing 370: NUMERIC_KINETIC.txt

NUMERIC_KINETIC.txt

Pair kernel: 36 pairs with u != w, 20 of them change in a collision

E1. Closure defect before collision, from a product state with velocities (±1,0),(0,0),
    signed differences averaged over 30 steps and all runs, then |.| summed over pairs u < w:
    δ2 = Σ|<p2(u,w) - f_u f_w>| / Σ<f_u f_w>   (p2: cells holding exactly {u,w}; enters the hierarchy)
    κ  = Σ|<n_u n_w> - f_u f_w|  / Σ<f_u f_w>   (full pair correlation)
    φ3 = fraction of particles in cells with >= 3 particles (the remainder G3, L3)
    runs scale as (0.8/rho)^2 so that every row sees about the same number of two-particle cells
    rho     L    runs   δ2       κ        φ3
    0.8     16   16     0.6111   0.0237   0.2320
    0.8     32   4      0.6079   0.0290   0.2307
    0.8     64   1      0.6173   0.0291   0.2318
    0.4     16   64     0.3757   0.0401   0.0738
    0.4     32   16     0.3702   0.0283   0.0732
    0.4     64   4      0.3777   0.0287   0.0782
    0.2     16   256    0.2285   0.1045   0.0193
    0.2     32   64     0.2042   0.0298   0.0201
    0.2     64   16     0.2043   0.0228   0.0204
    0.1     16   1024   0.2450   0.2011   0.0049
    0.1     32   256    0.1417   0.0913   0.0049
    0.1     64   64     0.1077   0.0247   0.0052
    δ2 at L = 64 by rho (0.8, 0.4, 0.2, 0.1): 0.6173, 0.3777, 0.2043, 0.1077
    κ averaged over rho, by L (16, 32, 64):   0.0923, 0.0446, 0.0263
  [PASS] δ2 decreases as the density decreases (L = 64)
  [PASS] κ decreases as L grows (averaged over rho)
  [PASS] φ3 decreases as the density decreases (L = 64)

E2. Homogeneous relaxation: particles vs the closed kinetic equation
    f_v(t+1) = f_v(t) + Σ_{u<w} f_u f_w [#(v in coll(u,w)) - #(v in {u,w})]
    error = max_t Σ_v |f_sim - f_kin| / Σ_v |f_sim(0) - f_sim(T)|
    rho = 0.4  L = 224  T = 100  relative error = 0.0857
      H_sim: -0.80593 -> -1.06153;  H_kin: -0.80593 -> -1.06157
    rho = 0.2  L = 316  T = 200  relative error = 0.0386
      H_sim: -0.54160 -> -0.66842;  H_kin: -0.54160 -> -0.66846
    rho = 0.1  L = 447  T = 400  relative error = 0.0315
      H_sim: -0.34012 -> -0.40362;  H_kin: -0.34012 -> -0.40363
  [PASS] the kinetic equation describes the particles better at lower density
  [PASS] relative error below 10% at rho = 0.1

E3. H theorem for the closed kinetic equation, 50 random homogeneous initial states
    largest one-step increase of H = Σ f ln f over all runs: 2.220e-16
  [PASS] H never increases (up to 1e-12) along the closed equation

E4. Kinetic -> fluid: linear modes of the kinetic equation about the Maxwellian
    f0_v ∝ exp(-beta e_v), rho = 1.0, beta = 0.5; closure c = sqrt(Σ f0 vx^2 e / (2 Σ f0 vx^2)) = 0.87981
    L    n   k        Γ_T        Γ_T/k^2   c = ω/k    max |Δ(N,Mx,My,E)|
    32   1   0.19635  0.010588  0.2746    0.90497    7.1e-15
  [PASS] L = 32, n = 1: N, Mx, My, E conserved to 1e-12 by the kinetic equation
    64   1   0.09817  0.002643  0.2742    0.89139    1.4e-14
  [PASS] L = 64, n = 1: N, Mx, My, E conserved to 1e-12 by the kinetic equation
    64   2   0.19635  0.010588  0.2746    0.90497    2.8e-14
  [PASS] L = 64, n = 2: N, Mx, My, E conserved to 1e-12 by the kinetic equation
    128  1   0.04909  0.000660  0.2741    0.88514    2.8e-14
  [PASS] L = 128, n = 1: N, Mx, My, E conserved to 1e-12 by the kinetic equation
    Γ_T ∝ k^2.001;  c at the smallest k = 0.88514 vs closure 0.87981
  [PASS] shear diffuses in the kinetic equation: exponent within 2 ± 0.15
  [PASS] sound speed of the kinetic equation within 2% of the closure
ALL PASS

93.11 From Particles to Fluids

93.12 Exact conservation (Lean, general)

The equations of this section are the moments of the kinetic equation derived in Section 93.1. The particles, the space, the time and the collision are the model of Section 93.1, with the same notation \(N,M_x,M_y,E\).

For each of the four weights \(w\in \{1,\,v_x+1,\,v_y+1,\,v_x^2+v_y^2\}\) the collision keeps \(\sum w\) in every cell, because the result is an element of the filtered class (cellColl_class, cons_mass, cons_mx, cons_my, cons_en). Streaming does not change velocities, sorting is a permutation (lsum_isort), and the grouping only regroups (run_sum, emit_sum). Hence, for every \(L\), every configuration and every number of steps \(n\),

\[ \sum _{q\in \operatorname {iter} n\,\mathrm {step}\,(\mathrm {ps})} w(v_q) \;=\;\sum _{q\in \mathrm {ps}} w(v_q) \]
(iter_conserves; the four instances are number_conserved, momentum_x_conserved, momentum_y_conserved, energy_conserved). The true momentum is \(\sum v_x=M_x-N\), conserved because both terms are.

93.13 Cell balance and the continuity and momentum equations (Lean, general)

Fix a cell \(c\). For one particle let \(b_1=[x\in c]\) before streaming and \(b_2=[x'\in c]\) after. The four cases give

\[ [b_2]+[b_1\wedge \neg b_2]=[b_1]+[\neg b_1\wedge b_2] \]
(ind_balance). Multiplying by \(w(v)\) and summing over the list gives the streaming balance (stream_balance); the collision keeps the amount of every conserved weight inside every cell (collideAll_cell) and sorting keeps every sum (isort_cell). With \(A_c(t)\) the amount of \(w\) in \(c\) at time \(t\) and \(\mathrm {Out}_c(t)\), \(\mathrm {In}_c(t)\) the amounts carried out of and into \(c\) by the streaming of step \(t\):
\[ A_c(t+1)+\mathrm {Out}_c(t)=A_c(t)+\mathrm {In}_c(t) \]
(cell_step), and telescoping in time,
\[ A_c(T)+\sum _{t<T}\mathrm {Out}_c(t)=A_c(0)+\sum _{t<T}\mathrm {In}_c(t) \]
for every \(T\) (cell_telescope). For \(w=1\) this is the cell continuity equation (continuity); for \(w=v_x+1\) and \(w=v_y+1\) it is the cell momentum equation in shifted form (momentum_x, momentum_y), and subtracting the continuity equation gives it for the true momentum; for \(w=v_x^2+v_y^2\) it is the cell energy equation (energy_cell). All are exact identities of natural numbers, with no limit taken.

93.14 Equilibrium and the closure (derived, then checked numerically)

The step is a bijection of occupation configurations: streaming moves whole occupation layers, and the collision is a bijection of each class. Counting measure on occupation numbers \(n_{c,v}\in \mathbb N\) is therefore invariant, and so is every measure that is a function of the conserved totals. Taking \(\exp (\lambda N-\beta E)\) makes each \(n_{c,v}\) independent and geometric with \(z_v=e^{\lambda -\beta e_v}\), mean \(f_v=z_v/(1-z_v)\) and variance \(\chi _v=f_v(1+f_v)\). To close the cell equations at long wavelength, insert local equilibrium \(\delta f_v=\chi _v(\delta \lambda -\delta \beta \,e_v+u\,v_x)\) into the fluxes. The \(x\leftrightarrow y\) symmetry gives \(\Pi _{xx}=\sum v_x^2\,\delta f=\tfrac 12\,\delta E\), while \(j_x=u\sum \chi v_x^2\) and the energy flux is \(u\sum \chi v_x^2 e\). The momentum and energy equations then form a wave equation with speed

\[ c^2=\frac {\sum _v \chi _v\,v_x^2\,e_v}{2\sum _v\chi _v\,v_x^2}. \]
At density \(2\) per cell and \(\beta =1/2\) this gives \(c=0.867\). The transverse momentum has no pressure term, so to this order it can only diffuse. Given local equilibrium, this formula is derived in Section 93.19. There \(\Pi _{xx}=\tfrac 12\delta E\) and the energy-flux identity are a Lean theorem (pressure_half), and the wave equation follows by linear algebra. The particle system is compared with local equilibrium below.

93.15 The macroscopic limit (Python)

The gas is started in the invariant measure above (fixed seeds) on \(L=32\) and \(L=64\), two independent runs each, \(8000\) steps after \(300\) steps of burn-in. In every run \((N,M_x,M_y,E)\) is the same at the end as at the start, as the Lean theorems require. For \(k=2\pi n/L\) along \(x\) we record the normalised time autocorrelations of the transverse current \(j^y_k\) and of the longitudinal current \(j^x_k\). The transverse one is fitted by \(e^{-\Gamma _T t}\), the longitudinal one by \(e^{-\Gamma _s t}\cos \omega t\).

\(L\) \(n\) \(k\) \(\Gamma _T/k^2\) \(\omega \) \(\omega /k\) \(\Gamma _s/k^2\)
32 1 0.1963 0.578 0.1733 0.8826 0.192
32 2 0.3927 0.559 0.3596 0.9156 0.157
32 3 0.5890 0.489 0.5544 0.9412 0.104
64 1 0.0982 0.638 0.0864 0.8800 0.225
64 2 0.1963 0.527 0.1740 0.8863 0.208
64 3 0.2945 0.545 0.2653 0.9008 0.166
Table 240: Hydrodynamic modes of the FluidChain gas (density 2, \(\beta =1/2\)).

Over the points with \(k<0.4\) the fits give \(\Gamma _T\propto k^{1.90}\), \(\omega \propto k^{1.03}\) and \(\Gamma _s\propto k^{1.73}\). The measured sound speed is \(c=0.893\), against \(0.867\) from the closure (relative difference \(0.03\)). The ratio \(\omega /k\) falls towards the prediction as \(k\) decreases (\(0.880\) at the smallest \(k\)), so part of the \(3\%\) is dispersion at finite \(k\). The sound damping exponent \(1.73\) is further from \(2\) than the transverse one, so the diffusive form of the sound damping is the least certain of these measurements. So the coarse-grained density and momentum follow, within these errors, the linearised equations

\[ \partial _t\rho +\partial _x j_x=0,\qquad \partial _t j_x+\tfrac 12\,\partial _x e=\Gamma _s'\,\partial _x^2 j_x,\qquad \partial _t j_y=\nu \,\partial _x^2 j_y, \]
with \(\nu \approx 0.57\). These are the cell equations of the Lean section, with fluxes replaced by their local-equilibrium values plus a diffusive correction. The first equation is exact at every scale (continuity); the second and third, with \(c\) and \(\nu \), are the measured form.

93.16 Status

Statement

Status

Where

1D: same \((P,E)\) gives \(\mathrm {id}\) or \(\sigma \)

Lean, general

one_dim_id_or_swp

collision keeps \(N,M_x,M_y,E\) in each cell

Lean, general

cons_*

global conservation, all \(L\), all times

Lean, general

iter_conserves

cell balance for one step

Lean, general

cell_step

continuity, momentum, energy equations (telescoped)

Lean, general

cell_telescope

invariant measure is geometric in each occupation

text argument

this section

closure \(c^2=\sum \chi v_x^2 e/(2\sum \chi v_x^2)\)

derived from local equilibrium

Section 93.19

particles reach local equilibrium

measured; proof remaining

this section

\(\Gamma _T\propto k^2\), \(\omega \propto k\), value of \(c\)

measured

numeric_fluid.py

Comparison. The rigorous passage from particles to kinetic and fluid equations for continuum hard spheres is the work of Lanford [990] and, recently, Deng, Hani and Ma [991]. Here the kinetic equation of this model comes from the particles in Section 93.1, through the exact hierarchy proved in Lean, and the molecular-chaos closure and the H theorem are in Section 93.19.

93.17 Machine check

The Lean file of this section is FluidChain.lean (Listing 366). In AXIOMS.txt it has \(46\) theorems, and all \(46\) #print axioms lines read “does not depend on any axioms”. The numbers come from numeric_fluid.py (Listing 368); its output is NUMERIC_FLUID.txt.

Listing 371: NUMERIC_FLUID.txt

NUMERIC_FLUID.txt

FluidChain lattice gas: 9 velocities, cell collision = next multiset with same (N, Mx, My, E)
  cells with 2 particles: 20 of 45 multisets change in a collision
  cells with 3 particles: 120 of 165 multisets change in a collision
  cells with 4 particles: 426 of 495 multisets change in a collision
  Lean demo after 6 steps (x, y, idx): [(1, 1, 4), (1, 1, 5), (1, 1, 5), (1, 3, 5), (1, 3, 6)]
  Lean demo totals (N, Mx, My, E) = (5, 6, 7, 5)
  [PASS] demo totals = (5, 6, 7, 5) as in FluidChain.demo_run
  [PASS] demo configuration = FluidChain.demo_final
Equilibrium: density 2.0 per cell, occupations geometric, z_v = exp(lam - beta e_v), beta = 0.5
  lam = -1.126578; mean occupations f_v = 0.1354, 0.2447, 0.1354, 0.2447, 0.4796, 0.2447, 0.1354, 0.2447, 0.1354
  closure prediction c = sqrt(Σ χ vx^2 e / (2 Σ χ vx^2)), χ = f(1+f): 0.866696
  [PASS] L = 32: (N, Mx, My, E) exactly conserved (2108, 2155, 2128, 2183) -> (2108, 2155, 2128, 2183)
  [PASS] L = 32: (N, Mx, My, E) exactly conserved (2058, 2050, 2027, 2157) -> (2058, 2050, 2027, 2157)
  [PASS] L = 64: (N, Mx, My, E) exactly conserved (8077, 8089, 8124, 8369) -> (8077, 8089, 8124, 8369)
  [PASS] L = 64: (N, Mx, My, E) exactly conserved (8083, 8132, 8194, 8416) -> (8083, 8132, 8194, 8416)

 L   n    k       Γ_T      Γ_T/k^2   ω        c=ω/k    Γ_s      Γ_s/k^2
 32  1   0.1963  0.02228  0.5780    0.17330  0.8826   0.00741  0.1922
 32  2   0.3927  0.08622  0.5591    0.35956  0.9156   0.02424  0.1572
 32  3   0.5890  0.16953  0.4886    0.55440  0.9412   0.03620  0.1043
 64  1   0.0982  0.00615  0.6377    0.08640  0.8800   0.00217  0.2254
 64  2   0.1963  0.02034  0.5275    0.17402  0.8863   0.00802  0.2081
 64  3   0.2945  0.04732  0.5455    0.26530  0.9008   0.01442  0.1663

  fits over k < 0.4 (5 points):  Γ_T ∝ k^1.901,  ω ∝ k^1.028,  Γ_s ∝ k^1.725
  ν = <Γ_T/k^2> = 0.5696,  Γ_s/k^2 = 0.1898,  c = <ω/k> = 0.8931
  c prediction 0.8667, relative difference 0.030
  [PASS] transverse momentum diffuses: exponent of Γ_T in k within 2 ± 0.35
  [PASS] sound propagates: exponent of ω in k within 1 ± 0.1
  [PASS] sound speed within 5% of the closure prediction
ALL PASS

93.18 Closure, the H-Theorem and Local Equilibrium

93.19 The Kac version, by counting

We keep the velocities and the pair collision of Section 93.1 and drop space. \(N\) particles carry velocities \(v_1,\dots ,v_N\). At each step one ordered pair \((i,j)\) of distinct particles is chosen, every one of the \(N(N-1)\) pairs counted once, and the pair collision is applied to \((v_i,v_j)\). Time is \(t=k/N\) after \(k\) steps. The probability law is the counting measure on pair choices. Every statement below is a statement about counts, and the probabilities are those counts divided by \(N(N-1)\) or by \((N(N-1))^k\). This is the random-pair model of Kac [1755]; here it appears as the counting version of the collision of the chain.

93.20 The exact hierarchy at finite \(N\) (Lean, general)

Let \(n_a\) be the number of particles with velocity \(a\). Summing any \(G\) over ordered pairs of positions gives

\[ \sum _{i\neq j}G(v_i,v_j)+\sum _iG(v_i,v_i)=\sum _{a,b}n_an_b\,G(a,b) \]
(offDiag_full, pair_counting). Equal velocities never collide, so gain and loss agree on the diagonal (diag_gain_loss). Hence, for every \(N\), every configuration and every velocity \(v\),
\[ \sum _{i\neq j}\mathrm {gain}_v(v_i,v_j)+\sum _{a,b}n_an_b\,\mathrm {loss}_v(a,b) =\sum _{i\neq j}\mathrm {loss}_v(v_i,v_j)+\sum _{a,b}n_an_b\,\mathrm {gain}_v(a,b) \]
(kac_hierarchy). Divided by \(N(N-1)\), this says that the expected one-step change of \(n_v\) is \(\sum _{a,b}n_an_b\,(\mathrm {gain}-\mathrm {loss})/(N(N-1))\). Averaged over the ensemble it is written exactly with the pair distribution \(f_2(a,b)=E[n_an_b-\delta _{ab}n_a]/(N(N-1))\):
\[ E[n_v(k+1)]-E[n_v(k)]=\sum _{a,b}f_2(a,b)\,\bigl (\mathrm {gain}_v-\mathrm {loss}_v\bigr )(a,b). \]
The only error in closing it is \(f_2-f\otimes f\).

93.21 Propagation of chaos

Proved.

Correlation also travels along chains: \(1\) meets \(3\), then \(3\) meets \(2\). Counting those chains, together with the step from “not connected by a chain” to “independent”, is the combinatorial core of Kac’s and McKean’s arguments [1755, 1756].

Exact computation. For \(N\le 24\) the full law of the occupation vector evolves exactly, with no sampling. Start from independent velocities with \(P((1,0))=\tfrac 12\) and \(P((-1,0))=P((0,0))=\tfrac 14\), and let \(D(t)=\max _{a,b}|f_2(a,b)-f(a)f(b)|\).

\(N\) states \(N D(0.5)\) \(N D(1)\) \(N D(1.5)\) \(N D(2)\)
4 38 0.1397 0.1939 0.2128 0.2202
6 136 0.1189 0.1677 0.1813 0.1858
8 406 0.1095 0.1540 0.1661 0.1700
12 2352 0.1004 0.1409 0.1511 0.1530
16 9509 0.0960 0.1345 0.1434 0.1440
24 82036 0.0918 0.1281 0.1356 0.1346
Table 241: Exact chaos defect of the Kac chain, multiplied by \(N\).

\(D(0)=0\) exactly. \(N\,D(t)\) is bounded and decreases slowly with \(N\), so the data are consistent with \(|f_2-f\otimes f|\le C(t)/N\) with \(C(2)\approx 0.13\) for large \(N\).

93.22 The H theorem without logarithms (Lean, general)

Count microstates: \(W=N!/\prod _v n_v!\). A collision \((a,b)\to (c,d)\) moves the occupations \((n_a,n_b,n_c,n_d)=(x+1,y+1,z,w)\) to \((x,y,z+1,w+1)\). Then

\[ x!\,y!\,(z+1)!\,(w+1)!\cdot (x+1)(y+1)=(x+1)!\,(y+1)!\,z!\,w!\cdot (z+1)(w+1) \]
(W_ratio), that is,
\[ \frac {W'}{W}=\frac {n_a\,n_b}{(n_c+1)(n_d+1)}, \]
an exact rational number; the factorials of the other velocities cancel. If \(n_an_b<(n_c+1)(n_d+1)\) then \(W'<W\) (W_compare). At a balanced point, \(n_an_b=n_cn_d\), we have \(n_an_b<(n_c+1)(n_d+1)\), and likewise for the reverse collision. So every single collision from a balanced point, in either direction, strictly lowers \(W\) (no_increase_at_balance): the points where gain equals loss are exactly where \(W\) cannot be raised by one collision. This is Boltzmann’s counting of complexions [790], here as an identity of natural numbers.

93.23 The H theorem with logarithms (derived; partly in Lean)

For the continuous-time closed equation \(\dot f_v=\sum _{P}F(P)\,(\#\{v\in \mathrm {coll}\,P\}-\#\{v\in P\})\), with \(F(P)=f_af_b\) for \(P=(a,b)\), mass conservation gives

\[ \frac {dH}{dt}=\sum _v\ln f_v\,\dot f_v=\sum _PF(P)\,\ln \frac {F(\mathrm {coll}\,P)}{F(P)} \le \sum _P\bigl (F(\mathrm {coll}\,P)-F(P)\bigr )=0 . \]
The inequality is \(\ln y\le y-1\). The last equality holds because the pair collision permutes the pairs (pairs_perm, sum_perm of Section 93.1, Lean). Equality holds exactly when \(F(\mathrm {coll}\,P)=F(P)\) for every \(P\), that is, at the balanced points. The permutation step is a Lean theorem, and \(\ln y\le y-1\) is elementary calculus. This is the semi-detailed-balance form of the H theorem [988]. Numerically, the largest value of \(dH/dt\) over \(20000\) random \(f\) was \(-1.98\times 10^{-3}\), and at a Maxwellian it was \(2\times 10^{-32}\).

93.24 Local equilibrium

At a balanced point \(f_af_b=f_cf_d\) for every collision, so \(\ln f\) is a collision invariant. The invariants of the pair collision are exactly the span of \(1,v_x,v_y,e\). That \(1,v_x,v_y,e\) are invariants is a Lean theorem (cons_* of Section 93.1). That there are no others is an exact rational elimination, dimension \(4\), done in Python. Hence

\[ f_v=\exp (\alpha +\beta _xv_x+\beta _yv_y-\gamma \,e_v), \]
a Maxwellian. As a check at finite \(N\), climbing \(W\) by single collisions until no collision raises it, from \((n_{(1,0)},n_{(-1,0)},n_{(0,0)})=(N/2,N/4,N/4)\), ends at occupations whose logarithms fit a Maxwellian to within the integer resolution. The maximal residuals are \(1.4\times 10^{-2}\), \(5.5\times 10^{-4}\), \(1.1\times 10^{-5}\) and \(1.9\times 10^{-5}\) for \(N=10^3,10^4,10^5,10^6\), and residual times \(\min _vn_v\) stays below \(0.3\).

Pressure and sound speed. For every weight \(\chi \) that is symmetric under \(v_x\leftrightarrow v_y\) and every function \(h\) of the energy,

\[ 2\sum _v\chi _v\,v_x^2\,h(e_v)=\sum _v\chi _v\,e_v\,h(e_v) \]
(pressure_half). Take a perturbation of a local equilibrium at rest, \(\delta f_v=\chi _v(\delta \lambda -\delta \gamma \,e_v+u\,v_x)\), where \(\chi \) is the susceptibility of the equilibrium: \(\chi =f\) for the Maxwellian of the kinetic equation, \(\chi =f(1+f)\) for the geometric occupations of the lattice gas. With \(h=1\), the momentum flux is \(\Pi _{xx}=\tfrac 12\delta E\). The current is \(j_x=u\sum \chi v_x^2\), and the energy flux is \(u\sum \chi v_x^2e\). The cell equations for momentum and energy then give \(\partial _t^2j_x=\tfrac 12\partial _x^2(\sum \chi v_x^2e/\sum \chi v_x^2)\,j_x\), so
\[ c^2=\frac {\sum _v\chi _v\,v_x^2\,e_v}{2\sum _v\chi _v\,v_x^2}. \]
This is the formula used in Section 93.12, now derived from local equilibrium. The identity it rests on is proved in Lean, and the remaining steps are linear algebra in the text. With \(\chi =f\) at \(\rho =1\), \(\beta =\tfrac 12\) it gives \(c=0.8798\); the kinetic equation was measured at \(0.8851\) at its smallest \(k\). With \(\chi =f(1+f)\) at \(\rho =2\), \(\beta =\tfrac 12\) it gives \(c=0.8667\); the particles were measured at \(0.893\).

93.25 Status

Statement

Status

Where

exact Kac hierarchy at every \(N\)

Lean, general

kac_hierarchy

\(f_2=f\otimes f\) at \(t=0\) (product start)

Lean, general

tagged_product

direct encounter by time \(t\): probability \(\le t/(N-1)\)

Lean, general

enc_bound

\(|f_2-f\otimes f|\le C(t)/N\)

exact computation for \(N\le 24\); general \(N\) remaining

N1

\(W'/W=n_an_b/((n_c+1)(n_d+1))\)

Lean, general

W_ratio

balance is a local maximum of \(W\)

Lean, general

no_increase_at_balance

\(dH/dt\le 0\), continuous time

derived; permutation in Lean, \(\ln y\le y-1\) outside

this section, N2

invariants \(=\mathrm {span}\{1,v_x,v_y,e\}\)

Lean (\(\supseteq \)), exact rational (\(\subseteq \))

cons_*, N3

local equilibrium is Maxwellian

follows from the two rows above

this section, N4

\(\Pi _{xx}=E/2\) for symmetric \(\chi \)

Lean, general

pressure_half

sound speed formula from local equilibrium

derived (text + Lean identity)

this section

particles reach local equilibrium

measured; proof remaining

Sections 93.1, 93.12

93.26 Machine check

The Lean file of this section is ClosureChain.lean. In AXIOMS.txt it has \(22\) theorems, and all \(22\) #print axioms lines read “does not depend on any axioms”. It imports KineticChain.lean (Listing 367), whose pairs_perm, sum_perm and cons_* are used here. The numbers come from numeric_closure.py, which imports the collision of numeric_fluid.py (Listing 368); its output is NUMERIC_CLOSURE.txt.

Listing 372: ClosureChain.lean: the Kac hierarchy, encounter bound, microstate counts, isotropy

ClosureChain.lean

/-
  ClosureChain.lean
  Molecular chaos, the H theorem without logarithms, and local equilibrium (T20).

  Lean 4 core plus FTAChain, FluidChain and KineticChain. Proofs are
  hand-written terms and rewriting; no omega / simp / ring / decide /
  norm_num / linarith.

  The Kac version of the model: N particles carry velocities; at each step one
  ordered pair of distinct particles is chosen, every pair with the same
  weight (counting), and the pair collision `cc` is applied to it.

  Proved here:
    vsum_add, offDiag_full        sums over ordered pairs i ≠ j
    pair_counting                 Σ_{i≠j} G(v_i,v_j) + Σ_i G(v_i,v_i) = Σ_{a,b} n_a n_b G(a,b)
    diag_gain_loss                equal velocities: gain = loss
    kac_hierarchy                 exact, every N: the summed one-step gain and loss
                                  over all ordered pairs are the quadratic forms
                                  Σ n_a n_b gain, Σ n_a n_b loss
    tagged_product                product initial data: two tagged particles have
                                  f2(a,b) = f(a) f(b) exactly
    enc_complement, enc_bound     among (Q+1)^k step sequences, those that choose a
                                  fixed pair at least once number ≤ k (Q+1)^(k-1):
                                  a direct encounter has probability ≤ k/(Q+1)
    fact, W_ratio                 Π n'! · n_a n_b = Π n! · (n_c+1)(n_d+1): the ratio
                                  W'/W = n_a n_b / ((n_c+1)(n_d+1)) of microstate counts
    W_compare                     W' < W, W' = W, W' > W according to n_a n_b vs (n_c+1)(n_d+1)
    no_increase_at_balance        if n_a n_b = n_c n_d, a collision in either direction
                                  strictly lowers W: balance is a local maximum of W
    pressure_half                 for every distribution symmetric in (v_x, v_y):
                                  2 Σ χ v_x² h(e) = Σ χ e h(e)  (so Π_xx = E/2)
-/
import KineticChain

namespace ClosureChain
open FTAChain FluidChain KineticChain

/-! ## Sums over ordered pairs of particles -/

theorem vsum_add (f g : V → Nat) : ∀ M, vsum (fun u => f u + g u) M = vsum f M + vsum g M
  | [] => rfl
  | u :: us => by
    show f u + g u + vsum (fun u => f u + g u) us = f u + vsum f us + (g u + vsum g us)
    rw [vsum_add f g us]
    exact mid4 _ _ _ _

theorem vsum_ext (f g : V → Nat) (h : ∀ u, f u = g u) : ∀ M, vsum f M = vsum g M
  | [] => rfl
  | u :: us => by
    show f u + vsum f us = g u + vsum g us
    rw [h u, vsum_ext f g h us]

/-- `Σ_{i ≠ j} G(v_i, v_j)` over ordered pairs of positions in the list. -/
def offDiag (G : V → V → Nat) : List V → Nat
  | [] => 0
  | u :: us => vsum (fun w => G u w + G w u) us + offDiag G us

theorem regroup5 (A B C D E : Nat) : A + B + C + (D + E) = D + A + (B + (C + E)) := by
  rw [nadd_assoc A B C, nadd_assoc A (B + C), nadd_comm D A, nadd_assoc A D, ← nadd_assoc B C E,
    nadd_left_comm (B + C) D E]

theorem offDiag_full (G : V → V → Nat) :
    ∀ M, offDiag G M + vsum (fun u => G u u) M = vsum (fun u => vsum (G u) M) M
  | [] => rfl
  | u :: us => by
    show vsum (fun w => G u w + G w u) us + offDiag G us + (G u u + vsum (fun u => G u u) us)
      = (G u u + vsum (G u) us) + vsum (fun x => G x u + vsum (G x) us) us
    rw [vsum_add, vsum_add (fun x => G x u) (fun x => vsum (G x) us), ← offDiag_full G us]
    exact regroup5 _ _ _ _ _

/-- `Σ_{u ∈ M} h(u) = Σ_a h(a) n_a`. -/
theorem vsum_counts (h : V → Nat) (M : List V) : vsum h M = sumL (fun a => h a * cntV a M) allV :=
  (moment_cell h M).symm

/-- **Pair counting.** `Σ_{i≠j} G(v_i,v_j) + Σ_i G(v_i,v_i) = Σ_{a,b} n_a n_b G(a,b)`. -/
theorem pair_counting (G : V → V → Nat) (M : List V) :
    offDiag G M + vsum (fun u => G u u) M
      = sumL (fun a => sumL (fun b => G a b * cntV b M) allV * cntV a M) allV := by
  rw [offDiag_full, vsum_counts]
  exact sumL_ext _ _ (fun a => by rw [vsum_counts]) allV

/-- Gain and loss of velocity `v` when the pair `(a, b)` collides. -/
def gain (v a b : V) : Nat := cntV v (cc [a, b])
def loss (v a b : V) : Nat := cntV v [a, b]

theorem diag_gain_loss (v a : V) : gain v a a = loss v a a := by
  show cntV v (cc [a, a]) = cntV v [a, a]
  rw [same_velocity_no_coll]

/-- The quadratic form `Σ_{a,b} n_a n_b G(a,b)`. -/
def Q2 (G : V → V → Nat) (M : List V) : Nat :=
  sumL (fun a => sumL (fun b => G a b * cntV b M) allV * cntV a M) allV

/-- **The exact Kac hierarchy, every N.** Summed over all ordered pairs of
    distinct particles, `gain - loss` of every velocity equals the quadratic form
    in the occupation numbers:
    `Σ_{i≠j} gain + Q2(loss) = Σ_{i≠j} loss + Q2(gain)`.
    Divided by `N(N-1)`: the expected one-step change of `n_v` is
    `Σ_{a,b} n_a n_b (gain - loss) / (N(N-1))`, and its ensemble mean is written
    exactly with the pair distribution `f2(a,b) = E[n_a n_b] / (N(N-1))`. -/
theorem kac_hierarchy (v : V) (M : List V) :
    offDiag (gain v) M + Q2 (loss v) M = offDiag (loss v) M + Q2 (gain v) M := by
  have hg := pair_counting (gain v) M
  have hl := pair_counting (loss v) M
  have hd : vsum (fun u => gain v u u) M = vsum (fun u => loss v u u) M :=
    vsum_ext _ _ (fun u => diag_gain_loss v u) M
  show offDiag (gain v) M + Q2 (loss v) M = offDiag (loss v) M + Q2 (gain v) M
  rw [← show offDiag (gain v) M + vsum (fun u => gain v u u) M = Q2 (gain v) M from hg,
    ← show offDiag (loss v) M + vsum (fun u => loss v u u) M = Q2 (loss v) M from hl, hd,
    ← nadd_assoc, ← nadd_assoc, nadd_comm (offDiag (gain v) M) (offDiag (loss v) M)]

/-! ## Product initial data -/

theorem mul_right_comm'' (a b c : Nat) : a * b * c = a * c * b := by
  rw [nmul_assoc, nmul_comm b c, ← nmul_assoc]

theorem rearr4 (p q r t : Nat) : p * q * r * t = q * t * (p * r) := by
  rw [mul_right_comm'' p q r, nmul_assoc (p * r) q t, nmul_comm (p * r) (q * t)]

/-- **Two tagged particles of a product ensemble are independent.** With
    weights `w` for the first and second particle, the weight of
    `(v₁, v₂) = (a, b)` is `w a * w b`: `f2(a, b) = f(a) f(b)` exactly. -/
theorem tagged_product (w : V → Nat) (a b : V) :
    sumL (fun u => sumL (fun u' => w u * w u' * ind (vEq a u) * ind (vEq b u')) allV) allV
      = w a * w b := by
  have e1 : ∀ u, sumL (fun u' => w u * w u' * ind (vEq a u) * ind (vEq b u')) allV
      = w u * ind (vEq a u) * w b := fun u => by
    have e2 : sumL (fun u' => w u * w u' * ind (vEq a u) * ind (vEq b u')) allV
        = sumL (fun u' => w u' * ind (vEq b u') * (w u * ind (vEq a u))) allV :=
      sumL_ext _ _ (fun u' => rearr4 _ _ _ _) allV
    rw [e2, sumL_mul, pick, nmul_comm (w b)]
  rw [sumL_ext _ _ e1 allV, sumL_mul, pick]

/-! ## Direct encounters: a counting bound -/

/-- Number of sequences of `k` choices among `Q + 1` pairs that choose a fixed
    pair at least once. -/
def enc (Q : Nat) : Nat → Nat
  | 0 => 0
  | k + 1 => (Q + 1) ^ k + Q * enc Q k

/-- The complement: `enc + Q^k = (Q+1)^k` (sequences that never choose it number `Q^k`). -/
theorem enc_complement (Q : Nat) : ∀ k, enc Q k + Q ^ k = (Q + 1) ^ k
  | 0 => rfl
  | k + 1 => by
    show (Q + 1) ^ k + Q * enc Q k + Q ^ k * Q = (Q + 1) ^ k * (Q + 1)
    rw [nmul_comm (Q ^ k) Q, nadd_assoc, ← nleft_distrib, enc_complement Q k, nleft_distrib,
      nmul_one, nadd_comm ((Q + 1) ^ k), nmul_comm]

/-- **Direct-encounter bound.** `enc(k) · (Q+1) ≤ k · (Q+1)^k`: the probability
    that a fixed pair is chosen at least once in `k` steps is at most `k/(Q+1)`.
    With `Q + 1 = N(N-1)` ordered pairs and `k = tN` steps this is `≤ t/(N-1)`. -/
theorem enc_bound (Q : Nat) : ∀ k, enc Q k * (Q + 1) ≤ k * (Q + 1) ^ k
  | 0 => by
    show 0 * (Q + 1) ≤ 0 * 1
    rw [nzero_mul, nzero_mul]
    exact Nat.le_refl 0
  | k + 1 => by
    show ((Q + 1) ^ k + Q * enc Q k) * (Q + 1) ≤ (k + 1) * ((Q + 1) ^ k * (Q + 1))
    rw [nright_distrib, nmul_assoc Q, nsucc_mul]
    have h1 : Q * (enc Q k * (Q + 1)) ≤ Q * (k * (Q + 1) ^ k) := Nat.mul_le_mul_left Q (enc_bound Q k)
    have h2 : Q * (k * (Q + 1) ^ k) ≤ k * ((Q + 1) ^ k * (Q + 1)) := by
      rw [← nmul_assoc, nmul_comm Q k, nmul_assoc, nmul_comm ((Q + 1) ^ k) (Q + 1)]
      exact Nat.mul_le_mul_left k (Nat.mul_le_mul_right _ (Nat.le_succ Q))
    rw [nadd_comm]
    exact Nat.add_le_add (Nat.le_trans h1 h2) (Nat.le_refl _)

/-! ## Microstate counts without logarithms -/

def fact : Nat → Nat
  | 0 => 1
  | n + 1 => (n + 1) * fact n

theorem mul_right_comm' (a b c : Nat) : a * b * c = a * c * b := by
  rw [nmul_assoc, nmul_comm b c, ← nmul_assoc]

/-- **The ratio of microstate counts.** A collision `(a,b) → (c,d)` takes the
    occupations `(x+1, y+1, z, w)` to `(x, y, z+1, w+1)`. With `W = N!/Π n!`,
    `Π n'! · (x+1)(y+1) = Π n! · (z+1)(w+1)`, i.e.
    `W'/W = n_a n_b / ((n_c+1)(n_d+1))`, an exact rational number. -/
theorem W_ratio (x y z w : Nat) :
    fact x * fact y * fact (z + 1) * fact (w + 1) * ((x + 1) * (y + 1))
      = fact (x + 1) * fact (y + 1) * fact z * fact w * ((z + 1) * (w + 1)) := by
  show fact x * fact y * ((z + 1) * fact z) * ((w + 1) * fact w) * ((x + 1) * (y + 1))
      = (x + 1) * fact x * ((y + 1) * fact y) * fact z * fact w * ((z + 1) * (w + 1))
  rw [nmul_assoc (fact x * fact y), mul_right_comm' (fact x * fact y), mmid4 (fact x) (fact y),
    nmul_comm (fact x) (x + 1), nmul_comm (fact y) (y + 1),
    nmul_assoc ((x + 1) * fact x * ((y + 1) * fact y)) (fact z) (fact w),
    nmul_assoc ((x + 1) * fact x * ((y + 1) * fact y)) (fact z * fact w),
    mmid4 (fact z) (fact w) (z + 1) (w + 1), nmul_comm (fact z) (z + 1), nmul_comm (fact w) (w + 1)]

theorem lt_irrefl' (n : Nat) : ¬ n < n := Nat.lt_irrefl n

/-- **Comparing W.** If `D' X = D Y` with `D = Π n!`, `D' = Π n'!` and `D > 0`,
    then `X < Y` forces `D < D'` (so `W' < W`). -/
theorem W_compare (D D' X Y : Nat) (hD : 0 < D) (h : D' * X = D * Y) (hXY : X < Y) : D < D' := by
  cases Nat.lt_or_ge D D' with
  | inl hlt => exact hlt
  | inr hge =>
    have h1 : D' * X ≤ D * X := Nat.mul_le_mul_right X hge
    have h2 : D * X < D * Y := Nat.mul_lt_mul_of_pos_left hXY hD
    exact absurd (h ▸ Nat.lt_of_le_of_lt h1 h2) (lt_irrefl' _)

theorem lt_succ_prod (z w : Nat) : z * w < (z + 1) * (w + 1) := by
  rw [nsucc_mul, nleft_distrib, nmul_one]
  exact Nat.lt_succ_of_le (Nat.le_trans (Nat.le_add_right (z * w) z) (Nat.le_add_right _ w))

theorem pos_mul {a b : Nat} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := Nat.mul_le_mul ha hb

theorem fact_pos : ∀ n, 0 < fact n
  | 0 => Nat.zero_lt_succ 0
  | n + 1 => pos_mul (Nat.zero_lt_succ n) (fact_pos n)

/-- **Balance is a local maximum of W.** Let the occupations of `a, b, c, d` be
    `x+1, y+1, z+1, w+1` with `n_a n_b = n_c n_d`. The collision
    `(a,b) → (c,d)` makes the product of factorials strictly larger, i.e. W
    strictly smaller; so does the reverse collision `(c,d) → (a,b)`.
    (The factorials of the other velocities are a common factor.) -/
theorem no_increase_at_balance (x y z w : Nat)
    (hbal : (x + 1) * (y + 1) = (z + 1) * (w + 1)) :
    fact (x + 1) * fact (y + 1) * fact (z + 1) * fact (w + 1)
        < fact x * fact y * fact (z + 1 + 1) * fact (w + 1 + 1) ∧
    fact (z + 1) * fact (w + 1) * fact (x + 1) * fact (y + 1)
        < fact z * fact w * fact (x + 1 + 1) * fact (y + 1 + 1) := by
  constructor
  · apply W_compare _ _ ((x + 1) * (y + 1)) ((z + 1 + 1) * (w + 1 + 1))
      (pos_mul (pos_mul (pos_mul (fact_pos _) (fact_pos _)) (fact_pos _)) (fact_pos _))
      (W_ratio x y (z + 1) (w + 1))
    rw [hbal]
    exact lt_succ_prod (z + 1) (w + 1)
  · apply W_compare _ _ ((z + 1) * (w + 1)) ((x + 1 + 1) * (y + 1 + 1))
      (pos_mul (pos_mul (pos_mul (fact_pos _) (fact_pos _)) (fact_pos _)) (fact_pos _))
      (W_ratio z w (x + 1) (y + 1))
    rw [← hbal]
    exact lt_succ_prod (x + 1) (y + 1)

/-! ## Local equilibrium: the pressure is half the energy -/

def allC : List C3 := [.m, .z, .p]

/-- **Isotropy.** For every weight `χ` symmetric in the two components and every
    function `h` of the energy:
    `2 Σ_{a,b} χ(a,b) a² h(a²+b²) = Σ_{a,b} χ(a,b) (a²+b²) h(a²+b²)`.
    With `h = 1` and `χ = δf` this is `Π_xx = E/2`; with `h(e) = e` it gives the
    energy flux used in the sound speed. -/
theorem pressure_half (χ : C3 → C3 → Nat) (hs : ∀ a b, χ a b = χ b a) (h : Nat → Nat) :
    2 * sumL (fun a => sumL (fun b => χ a b * sq a * h (sq a + sq b)) allC) allC
      = sumL (fun a => sumL (fun b => χ a b * (sq a + sq b) * h (sq a + sq b)) allC) allC := by
  have split : sumL (fun a => sumL (fun b => χ a b * (sq a + sq b) * h (sq a + sq b)) allC) allC
      = sumL (fun a => sumL (fun b => χ a b * sq a * h (sq a + sq b)) allC) allC
        + sumL (fun a => sumL (fun b => χ a b * sq b * h (sq a + sq b)) allC) allC := by
    rw [← sumL_add]
    refine sumL_ext _ _ (fun a => ?_) allC
    rw [← sumL_add]
    refine sumL_ext _ _ (fun b => ?_) allC
    rw [nleft_distrib, nright_distrib]
  have swap : sumL (fun a => sumL (fun b => χ a b * sq b * h (sq a + sq b)) allC) allC
      = sumL (fun a => sumL (fun b => χ a b * sq a * h (sq a + sq b)) allC) allC := by
    rw [sumL_swap]
    refine sumL_ext _ _ (fun b => sumL_ext _ _ (fun a => ?_) allC) allC
    rw [hs a b, nadd_comm (sq a) (sq b)]
  rw [split, swap, Nat.two_mul]

end ClosureChain

#print axioms ClosureChain.vsum_add
#print axioms ClosureChain.vsum_ext
#print axioms ClosureChain.regroup5
#print axioms ClosureChain.offDiag_full
#print axioms ClosureChain.vsum_counts
#print axioms ClosureChain.pair_counting
#print axioms ClosureChain.diag_gain_loss
#print axioms ClosureChain.kac_hierarchy
#print axioms ClosureChain.mul_right_comm''
#print axioms ClosureChain.rearr4
#print axioms ClosureChain.tagged_product
#print axioms ClosureChain.enc_complement
#print axioms ClosureChain.enc_bound
#print axioms ClosureChain.mul_right_comm'
#print axioms ClosureChain.W_ratio
#print axioms ClosureChain.lt_irrefl'
#print axioms ClosureChain.W_compare
#print axioms ClosureChain.lt_succ_prod
#print axioms ClosureChain.pos_mul
#print axioms ClosureChain.fact_pos
#print axioms ClosureChain.no_increase_at_balance
#print axioms ClosureChain.pressure_half

Listing 373: numeric_closure.py: exact Kac chain, dH/dt, invariants, the W maximum, sound speed

numeric_closure.py

#!/usr/bin/env python3
"""T20 numerics: Kac version of the FluidChain model; chaos, H, local equilibrium.

Python standard library only, fixed seeds where randomness is used. The pair
collision is the one of work/FluidChain.lean (imported from numeric_fluid.py).

Writes work/NUMERIC_CLOSURE.txt next to this script.
"""
import importlib.util
import math
import os
import random
from fractions import Fraction

HERE = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("numeric_fluid", os.path.join(HERE, "numeric_fluid.py"))
nf = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(nf)

ALLV, IDX, cell_coll = nf.ALLV, nf.IDX, nf.cell_coll
NV = 9
EN = [nf.en(v) for v in ALLV]
VX = [v[0] for v in ALLV]
VY = [v[1] for v in ALLV]

# pair collision on velocity indices: (a, b) -> (c, d), a <= b
COLL = {}
for a in range(NV):
    for b in range(a, NV):
        Q = cell_coll((ALLV[a], ALLV[b]))
        COLL[(a, b)] = (IDX[Q[0]], IDX[Q[1]])
ACTIVE = {k: v for k, v in COLL.items() if tuple(sorted(v)) != k}


# ------------------------------------------------- N1: exact Kac chain
def multinomial_states(N, p):
    """Exact multinomial law of the occupation vector for N i.i.d. velocities with law p."""
    support = [i for i in range(NV) if p[i] > 0]
    out = {}

    def rec(i, left, n, prob):
        if i == len(support) - 1:
            n2 = list(n)
            n2[support[i]] = left
            pr = prob * Fraction(p[support[i]]) ** left / math.factorial(left)
            out[tuple(n2)] = out.get(tuple(n2), 0) + pr
            return
        for k in range(left + 1):
            n2 = list(n)
            n2[support[i]] = k
            rec(i + 1, left - k, n2, prob * Fraction(p[support[i]]) ** k / math.factorial(k))
    rec(0, N, [0] * NV, Fraction(math.factorial(N)))
    return {k: float(v) for k, v in out.items()}


def kac_step(dist, N):
    """One step: an ordered pair of distinct particles, uniformly; apply the pair collision."""
    tot = N * (N - 1)
    new = {}
    for n, pr in dist.items():
        stay = 1.0
        for (a, b), (c, d) in ACTIVE.items():
            if a == b:
                continue            # equal velocities never collide (Lean: same_velocity_no_coll)
            w = 2 * n[a] * n[b] / tot          # ordered pairs (i,j) and (j,i)
            if w == 0:
                continue
            m = list(n)
            m[a] -= 1
            m[b] -= 1
            m[c] += 1
            m[d] += 1
            m = tuple(m)
            new[m] = new.get(m, 0.0) + pr * w
            stay -= w
        new[n] = new.get(n, 0.0) + pr * stay
    return new


def chaos_defect(dist, N):
    f = [0.0] * NV
    f2 = [[0.0] * NV for _ in range(NV)]
    for n, pr in dist.items():
        for a in range(NV):
            if n[a]:
                f[a] += pr * n[a]
                for b in range(NV):
                    if n[b]:
                        f2[a][b] += pr * (n[a] * n[b] - (n[a] if a == b else 0))
    f = [x / N for x in f]
    D = max(abs(f2[a][b] / (N * (N - 1)) - f[a] * f[b]) for a in range(NV) for b in range(NV))
    return D, f


P0 = [0.0] * NV
for v, w in (((1, 0), 0.5), ((-1, 0), 0.25), ((0, 0), 0.25)):
    P0[IDX[v]] = w


# --------------------------------------------- N2: dH/dt for the closed equation
def dHdt(f):
    """Continuous-time closed equation: df_v/dt = Σ_{pairs a<b} f_a f_b K_v(a,b)."""
    s = 0.0
    for (a, b), (c, d) in ACTIVE.items():
        if a == b:
            continue
        F = f[a] * f[b]
        s += F * (math.log(f[c] * f[d]) - math.log(F))
    return s


# --------------------------------------------- N3: collision invariants (exact)
def invariant_dimension():
    rows = []
    for (a, b), (c, d) in ACTIVE.items():
        r = [Fraction(0)] * NV
        r[a] += 1
        r[b] += 1
        r[c] -= 1
        r[d] -= 1
        rows.append(r)
    M = [r[:] for r in rows]
    rank = 0
    for col in range(NV):
        piv = next((i for i in range(rank, len(M)) if M[i][col] != 0), None)
        if piv is None:
            continue
        M[rank], M[piv] = M[piv], M[rank]
        for i in range(len(M)):
            if i != rank and M[i][col] != 0:
                fac = M[i][col] / M[rank][col]
                M[i] = [x - fac * y for x, y in zip(M[i], M[rank])]
        rank += 1
    basis = [[1] * NV, VX, VY, EN]
    ok = all(sum(r[i] * phi[i] for i in range(NV)) == 0 for r in rows for phi in basis)
    # the four basis vectors are independent
    B = [[Fraction(x) for x in phi] for phi in basis]
    rb = 0
    for col in range(NV):
        piv = next((i for i in range(rb, 4) if B[i][col] != 0), None)
        if piv is None:
            continue
        B[rb], B[piv] = B[piv], B[rb]
        for i in range(4):
            if i != rb and B[i][col] != 0:
                fac = B[i][col] / B[rb][col]
                B[i] = [x - fac * y for x, y in zip(B[i], B[rb])]
        rb += 1
    return NV - rank, ok, rb


# --------------------------------------------- N4: the W maximum at large N
def w_climb(N):
    """Start with velocities (±1,0),(0,0); apply collisions while W = N!/Π n! increases,
    i.e. while n_a n_b > (n_c+1)(n_d+1). Stop at a point where no collision raises W."""
    n = [0] * NV
    n[IDX[(1, 0)]] = N // 2
    n[IDX[(-1, 0)]] = N // 4
    n[IDX[(0, 0)]] = N - N // 2 - N // 4
    moves = list(ACTIVE.items())
    changed = True
    sweeps = 0
    while changed:
        changed = False
        sweeps += 1
        for (a, b), (c, d) in moves + [((min(c, d), max(c, d)), (a, b)) for (a, b), (c, d) in moves]:
            if a == b:
                continue
            while n[a] > 0 and n[b] > 0 and n[a] * n[b] > (n[c] + 1) * (n[d] + 1):
                n[a] -= 1
                n[b] -= 1
                n[c] += 1
                n[d] += 1
                changed = True
    return n


def maxwell_fit(n):
    """Least squares of ln n_v on (1, vx, vy, e); return max residual."""
    X = [[1.0, VX[i], VY[i], EN[i]] for i in range(NV)]
    y = [math.log(n[i]) for i in range(NV)]
    # normal equations 4x4
    A = [[sum(X[k][i] * X[k][j] for k in range(NV)) for j in range(4)] for i in range(4)]
    bb = [sum(X[k][i] * y[k] for k in range(NV)) for i in range(4)]
    for i in range(4):
        p = max(range(i, 4), key=lambda r: abs(A[r][i]))
        A[i], A[p] = A[p], A[i]
        bb[i], bb[p] = bb[p], bb[i]
        for r in range(4):
            if r != i:
                fac = A[r][i] / A[i][i]
                A[r] = [x - fac * z for x, z in zip(A[r], A[i])]
                bb[r] -= fac * bb[i]
    coef = [bb[i] / A[i][i] for i in range(4)]
    res = max(abs(sum(X[k][j] * coef[j] for j in range(4)) - y[k]) for k in range(NV))
    return coef, res


def sound_speed(chi):
    a = sum(chi[i] * VX[i] ** 2 * EN[i] for i in range(NV))
    b = sum(chi[i] * VX[i] ** 2 for i in range(NV))
    return math.sqrt(a / (2 * b))


def main():
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    # N1
    out.append("N1. Exact Kac chain (full law of the occupation vector, no sampling).")
    out.append("    Start: N i.i.d. velocities, P((1,0)) = 1/2, P((-1,0)) = P((0,0)) = 1/4.")
    out.append("    D(t) = max_{a,b} |f2(a,b) - f(a) f(b)|, t = steps / N; Lean direct-encounter bound t/(N-1) for reference")
    ts = (0.5, 1.0, 1.5, 2.0)
    out.append("    N    states   " + "   ".join(f"N·D(t={t})" for t in ts))
    table = {}
    d0s = []
    for N in (4, 6, 8, 12, 16, 24):
        dist = multinomial_states(N, P0)
        D0, _ = chaos_defect(dist, N)
        d0s.append(D0)
        row = []
        step = 0
        for t in ts:
            while step < round(t * N):
                dist = kac_step(dist, N)
                step += 1
            D, _ = chaos_defect(dist, N)
            row.append(N * D)
        table[N] = row
        out.append(f"    {N:<4} {len(dist):<8} " + "   ".join(f"{x:9.5f}" for x in row) + f"    (D(0) = {D0:.1e})")
    check("D(0) < 1e-12 for the product start (exact f2 = f f)", max(d0s) < 1e-12)
    ratios = [table[24][i] / table[6][i] for i in range(len(ts))]
    out.append("    N·D(t) at N = 24 divided by N·D(t) at N = 6: " + ", ".join(f"{r:.3f}" for r in ratios))
    check("N·D(t) stays bounded as N grows (ratio N=24 / N=6 within [0.5, 2] for every t)",
          all(0.5 <= r <= 2 for r in ratios))

    # N2
    out.append("")
    out.append("N2. Continuous-time closed equation: dH/dt = Σ_pairs f_a f_b ln(f_c f_d / (f_a f_b)).")
    rng = random.Random(20)
    worst = -1e9
    for _ in range(20000):
        w = [rng.random() ** 3 + 1e-9 for _ in range(NV)]
        s = sum(w)
        f = [x / s for x in w]
        worst = max(worst, dHdt(f))
    out.append(f"    largest dH/dt over 20000 random f: {worst:.3e}")
    check("dH/dt <= 1e-15 for all samples", worst <= 1e-15)
    beta = 0.7
    fm = [math.exp(-beta * e + 0.3 * vx - 0.2 * vy) for e, vx, vy in zip(EN, VX, VY)]
    out.append(f"    dH/dt at a Maxwellian exp(-0.7 e + 0.3 vx - 0.2 vy): {dHdt(fm):.2e}")
    check("dH/dt = 0 at a Maxwellian (|.| < 1e-14)", abs(dHdt(fm)) < 1e-14)

    # N3
    out.append("")
    dim, ok_b, rb = invariant_dimension()
    out.append(f"N3. Collision invariants of the pair collision (exact rational elimination): dimension {dim}")
    out.append(f"    1, vx, vy, e are invariants: {ok_b}; they are independent: rank {rb}")
    check("the invariants are exactly span{1, vx, vy, e}", dim == 4 and ok_b and rb == 4)

    # N4
    out.append("")
    out.append("N4. Climbing W = N!/Π n! by single collisions until none raises it, then fitting")
    out.append("    ln n_v = α + β_x vx + β_y vy - γ e (a Maxwellian); max residual of the fit:")
    res = []
    mins = []
    for N in (10 ** 3, 10 ** 4, 10 ** 5, 10 ** 6):
        n = w_climb(N)
        if min(n) == 0:
            out.append(f"    N = {N:<8} some occupation is 0: {n}")
            res.append(float('inf'))
            continue
        coef, r = maxwell_fit(n)
        res.append(r)
        mins.append(min(n))
        out.append(f"    N = {N:<8} n = {n}")
        out.append(f"               fit (α, βx, βy, -γ) = ({coef[0]:.4f}, {coef[1]:.4f}, {coef[2]:.4f}, {coef[3]:.4f}), "
                   f"max residual {r:.2e}")
    out.append("    integer resolution: residual · min_v n_v = " + ", ".join(f"{r * m:.3f}" for r, m in zip(res, mins)))
    check("the W maximum is a Maxwellian up to integer rounding: residual · min n < 1 for every N",
          all(r * m < 1 for r, m in zip(res, mins)))
    check("residual below 1e-3 for N >= 10^4", all(r < 1e-3 for r in res[1:]))

    # N5
    out.append("")
    out.append("N5. Sound speed from the local-equilibrium formula c^2 = Σχ vx^2 e / (2 Σχ vx^2):")
    rho, beta = 1.0, 0.5
    w = [math.exp(-beta * e) for e in EN]
    z = sum(w)
    fcl = [rho * x / z for x in w]
    c_cl = sound_speed(fcl)
    out.append(f"    classical (Kac / kinetic fixed point), rho = 1, beta = 1/2: c = {c_cl:.5f}"
               f"  (kinetic equation measured 0.88514 at the smallest k, NUMERIC_KINETIC E4)")
    lam_lo, lam_hi = -50.0, -1e-12
    for _ in range(200):
        lam = (lam_lo + lam_hi) / 2
        fb = [math.exp(lam - 0.5 * e) / (1 - math.exp(lam - 0.5 * e)) for e in EN]
        if sum(fb) < 2.0:
            lam_lo = lam
        else:
            lam_hi = lam
    c_bose = sound_speed([x * (1 + x) for x in fb])
    out.append(f"    geometric occupations (particle model, rho = 2, beta = 1/2), χ = f(1+f): c = {c_bose:.5f}"
               f"  (particles measured 0.893, NUMERIC_FLUID)")
    check("classical value matches the kinetic-equation measurement within 1%", abs(c_cl - 0.88514) / c_cl < 0.01)
    check("geometric value matches the particle measurement within 5%", abs(c_bose - 0.8931) / c_bose < 0.05)

    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_CLOSURE.txt"), "w", encoding="utf-8") as fh:
        fh.write(text)
    print(text, end="")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())

Listing 374: NUMERIC_CLOSURE.txt

NUMERIC_CLOSURE.txt

N1. Exact Kac chain (full law of the occupation vector, no sampling).
    Start: N i.i.d. velocities, P((1,0)) = 1/2, P((-1,0)) = P((0,0)) = 1/4.
    D(t) = max_{a,b} |f2(a,b) - f(a) f(b)|, t = steps / N; Lean direct-encounter bound t/(N-1) for reference
    N    states   N·D(t=0.5)   N·D(t=1.0)   N·D(t=1.5)   N·D(t=2.0)
    4    38         0.13965     0.19387     0.21276     0.22021    (D(0) = 0.0e+00)
    6    136        0.11892     0.16772     0.18130     0.18579    (D(0) = 0.0e+00)
    8    406        0.10947     0.15398     0.16610     0.16998    (D(0) = 0.0e+00)
    12   2352       0.10036     0.14087     0.15108     0.15304    (D(0) = 0.0e+00)
    16   9509       0.09599     0.13446     0.14337     0.14397    (D(0) = 0.0e+00)
    24   82036      0.09177     0.12812     0.13557     0.13461    (D(0) = 0.0e+00)
  [PASS] D(0) < 1e-12 for the product start (exact f2 = f f)
    N·D(t) at N = 24 divided by N·D(t) at N = 6: 0.772, 0.764, 0.748, 0.725
  [PASS] N·D(t) stays bounded as N grows (ratio N=24 / N=6 within [0.5, 2] for every t)

N2. Continuous-time closed equation: dH/dt = Σ_pairs f_a f_b ln(f_c f_d / (f_a f_b)).
    largest dH/dt over 20000 random f: -1.977e-03
  [PASS] dH/dt <= 1e-15 for all samples
    dH/dt at a Maxwellian exp(-0.7 e + 0.3 vx - 0.2 vy): -2.47e-32
  [PASS] dH/dt = 0 at a Maxwellian (|.| < 1e-14)

N3. Collision invariants of the pair collision (exact rational elimination): dimension 4
    1, vx, vy, e are invariants: True; they are independent: rank 4
  [PASS] the invariants are exactly span{1, vx, vy, e}

N4. Climbing W = N!/Π n! by single collisions until none raises it, then fitting
    ln n_v = α + β_x vx + β_y vy - γ e (a Maxwellian); max residual of the fit:
    N = 1000     n = [13, 50, 13, 104, 390, 104, 57, 212, 57]
               fit (α, βx, βy, -γ) = (5.9699, 0.7335, 0.0000, -1.3325), max residual 1.43e-02
    N = 10000    n = [133, 501, 133, 1034, 3898, 1034, 566, 2135, 566]
               fit (α, βx, βy, -γ) = (8.2682, 0.7244, 0.0000, -1.3269), max residual 5.50e-04
    N = 100000   n = [1329, 5010, 1329, 10341, 38982, 10341, 5662, 21344, 5662]
               fit (α, βx, βy, -γ) = (10.5709, 0.7247, 0.0000, -1.3270), max residual 1.06e-05
    N = 1000000  n = [13290, 50101, 13290, 103409, 389820, 103409, 56620, 213441, 56620]
               fit (α, βx, βy, -γ) = (12.8734, 0.7247, 0.0000, -1.3270), max residual 1.92e-05
    integer resolution: residual · min_v n_v = 0.186, 0.073, 0.014, 0.256
  [PASS] the W maximum is a Maxwellian up to integer rounding: residual · min n < 1 for every N
  [PASS] residual below 1e-3 for N >= 10^4

N5. Sound speed from the local-equilibrium formula c^2 = Σχ vx^2 e / (2 Σχ vx^2):
    classical (Kac / kinetic fixed point), rho = 1, beta = 1/2: c = 0.87981  (kinetic equation measured 0.88514 at the smallest k, NUMERIC_KINETIC E4)
    geometric occupations (particle model, rho = 2, beta = 1/2), χ = f(1+f): c = 0.86670  (particles measured 0.893, NUMERIC_FLUID)
  [PASS] classical value matches the kinetic-equation measurement within 1%
  [PASS] geometric value matches the particle measurement within 5%
ALL PASS