diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ListSubtractProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ListSubtractProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c264cbabf0be3926bc9574aba217f3b0b2c03d3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ListSubtractProgram.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedCellShift +import OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram + +namespace OAI + +/-! # Binary subtraction at one list coordinate + +The scan depends on the stored list length. The subtracted amount remains +binary throughout and never controls a loop. +-/ + +namespace ContingencyTables.ListSubtractProgram + +open MatchingFPRAS.TreeTyped Polynomial + +abbrev Input := (List ℕ×ℕ)×ℕ +abbrev Cell := Input×ℕ + +def entry (z : Cell) : ℕ := + z.1.1.1.getD z.2 0-if z.2=z.1.1.2 then z.1.2 else 0 + +def entryRealizer : Realizer entry := by + let read : Realizer (fun z : Cell=>z.1.1.1.getD z.2 0) := + composition (pair (composition (composition first first) first) second) (getDFast 0) + let amount : Realizer (fun z : Cell=>if z.2=z.1.1.2 then z.1.2 else 0) := + (choose (composition (pair second (composition (composition first first) second)) natEqual) + (composition first second) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq]) + exact composition (pair read amount) subtract + +lemma polynomial_entry : PolynomialTime entryRealizer := by + unfold entryRealizer + apply polynomial_composition + · apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) (polynomial_getDFast 0) + · exact polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_natEqual) + (polynomial_composition polynomial_first polynomial_second) (polynomial_constant 0)) + · exact polynomial_subtract + +def indices (z : Input) : List ℕ := List.range z.1.1.length + +def indicesRealizer : Realizer indices := + composition (composition (composition first first) listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def subtractAt (z : Input) : List ℕ := + (indices z).map (fun i=>entry (z,i)) + +def subtractAtRealizer : Realizer subtractAt := + composition (pair identity indicesRealizer) (mapWith entryRealizer) + +lemma polynomial_subtractAt : PolynomialTime subtractAtRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_entry) + +lemma subtractAt_length (xs : List ℕ) (i t : ℕ) : + (subtractAt ((xs,i),t)).length=xs.length := by + simp [subtractAt,indices] + +lemma subtractAt_ofFn {m : ℕ} (x : Fin m→ℕ) (i : Fin m) (t : ℕ) : + subtractAt ((List.ofFn x,i.val),t)=List.ofFn (BoundedCellShift.margin x i t) := by + simp only [subtractAt,indices,List.length_ofFn,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map, + List.map_ofFn] + apply congrArg List.ofFn + funext j + simp only [entry,List.getD_eq_getElem?_getD,List.getElem?_ofFn,BoundedCellShift.margin] + by_cases h : j=i + · subst j + simp + · have hn : j.val≠i.val := fun he=>h (Fin.ext he) + simp [h,hn] + +end ContingencyTables.ListSubtractProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ListWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ListWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a894bc1e0464f545215aa32acd0313441f7ecfc9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ListWordProgram.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListBitProposal +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +import OAI.Combinatorics.MatchingCount.Machines.TreeSum + +namespace OAI + +/-! # Binary execution of the finite-list proposal + +The list is scanned only up to its own length. A binary index beyond the +end produces `none`; its numerical magnitude never determines a loop bound. +-/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators + +variable {A : Type} [Codec A] [Inhabited A] + +def getOptionFast : Realizer (fun x : List A×ℕ => x.1[x.2]?) := + (choose (composition (pair second (composition first listLength)) less) + (composition (getDFast default) TreeTyped.some) (constant none)).congr (by + intro x + simp only [Function.comp_apply,decide_eq_true_eq] + by_cases h : x.2 simp [StackAddition.value] + | succ k ih => + rw [List.ofFn_succ,StackAddition.value,ih,Fin.sum_univ_succ] + simp only [Fin.val_zero,pow_zero,Nat.mul_one,Fin.val_succ,pow_succ] + rw [Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro i _ + ring + rw [hv] + change _=∑ i : Fin k, (finTwoEquiv.symm (bits i)).val*2^i.val + apply Finset.sum_congr rfl + intro i _ + cases bits i <;> rfl + +omit [Codec A] [Inhabited A] in +theorem listWordChoice_ofFn (xs : List A) (k : ℕ) (bits : Fin k → Bool) : + listWordChoice (xs,List.ofFn bits)=FairBits.listBitDraw xs k bits := by + simp only [listWordChoice,FairBits.listBitDraw,bitValue_eq_word] + +omit [Codec A] [Inhabited A] in +/-- The literal binary program has the previously proved dyadic proposal +law, including all unused indices that return `none`. -/ +theorem listWordChoice_mass [Fintype A] [DecidableEq A] + (xs : List A) (hxs : xs.Nodup) (k : ℕ) (hk : xs.length≤2^k) (a : A) : + (FirstSuccess.mapLaw + (FirstSuccess.uniformLaw (α := Fin k → Bool)) + (fun bits => listWordChoice (xs,List.ofFn bits))).mass (some a)= + if a∈xs then 1/(2:ℚ)^k else 0 := by + simp_rw [listWordChoice_ofFn] + exact FairBits.listBitDraw_mass xs hxs k hk a + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/LiteralProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/LiteralProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7fab371ee8261cee61ff1f5cfa5c9b3d101a7db7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/LiteralProgram.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.MatchingCount.Tapes.PackedExecution +import OAI.Combinatorics.MatchingCount.Machines.OnlinePhysicalProgram +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramMap +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramSeal + +namespace OAI + +/-! # Public binary input and output for typed finite programs + +Literal packing is independent of the counting algorithm. Its cost includes every packing, execution, and printing step. +-/ + +namespace ContingencyTables.LiteralProgram +open MatchingFPRAS Turing PhysicalPost PhysicalStream LiteralPacked TreeTyped Polynomial + +noncomputable def pack : Program := Program.ofTM1 packCode .start (fun _ => 0) +noncomputable def erase : Program := Program.ofTM1 (LiteralTape.eraseCode header.length) () () +noncomputable def unpack : Program := Program.ofTM1 unpackCode .start (fun _ => 0) +noncomputable def post : Program := erase.seq unpack +noncomputable def packTime (n : ℕ) : ℕ := + (1+LiteralBlockMap.budget 1 (18*width) n 0)*MachineCost.programCost packCode +noncomputable def postTime (n : ℕ) : ℕ := + MachineCost.programCost (LiteralTape.eraseCode header.length)+ + (1+LiteralBlockMap.budget (18*width) 1 n 0)*MachineCost.programCost unpackCode + +lemma packTime_mono {n m : ℕ} (h : n ≤ m) : packTime n ≤ packTime m := by + unfold packTime LiteralBlockMap.budget + gcongr + +lemma postTime_mono {n m : ℕ} (h : n ≤ m) : postTime n ≤ postTime m := by + unfold postTime LiteralBlockMap.budget + gcongr + +lemma pack_realizes (as : List Symbol) (ha : ∀ a∈as,a≠0) : + pack.Realizes (Tape.mk₁ as) (.done (Tape.mk₁ (TreePost.packed as))) (packTime as.length) := + Program.realizes_TM1 _ _ _ _ _ _ _ (pack_exec as ha) + +lemma post_realizes (as : List Symbol) (ha : ∀ a∈as,a≠6 ∧ a≠7) : + post.Realizes (Tape.mk₁ (TreePost.packed as)) (.done (Tape.mk₁ as)) (postTime as.length) := by + have h1 : erase.Realizes (Tape.mk₁ (TreePost.packed as)) + (.done (Tape.mk₁ (as.reverse.flatMap chunk))) + (MachineCost.programCost (LiteralTape.eraseCode header.length)) := by + rw [packed_eq] + exact (Program.realizes_TM1 _ _ _ _ _ _ _ + (LiteralTape.erase_exec header (as.reverse.flatMap chunk))).mono (by simp only [Nat.one_mul]; rfl) + have h2 : unpack.Realizes (Tape.mk₁ (as.reverse.flatMap chunk)) (.done (Tape.mk₁ as)) + ((1+LiteralBlockMap.budget (18*width) 1 as.length 0)*MachineCost.programCost unpackCode) := + Program.realizes_TM1 _ _ _ _ _ _ _ (unpack_exec as ha) + exact Program.seq_realizes erase unpack _ (.done (Tape.mk₁ (as.reverse.flatMap chunk))) + (fun _ => .done (Tape.mk₁ as)) _ _ h1 h2 + +noncomputable def wrap {f : List Symbol → Experiment (List Symbol)} + (F : OnlineTree.Realizer f) : Program := (pack.seq (OnlineTree.physicalProgram F)).seq post + +noncomputable def wrapTime {f : List Symbol → Experiment (List Symbol)} + (F : OnlineTree.Realizer f) (as : List Symbol) : ℕ := + packTime as.length+OnlineTree.physicalCost F as+postTime ((f as).worst List.length) + +private lemma experiment_all_and {A : Type} {p : Experiment A} {P Q : A → Prop} + (hp : p.All P) (hq : p.All Q) : p.All (fun a => P a ∧ Q a) := by + induction p with + | done a => exact ⟨hp,hq⟩ + | read p ih => exact ⟨ih false hp.1 hq.1,ih true hp.2 hq.2⟩ + | delay n p ih => exact ih hp hq + +lemma wrap_realizes {f : List Symbol → Experiment (List Symbol)} + (F : OnlineTree.Realizer f) (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : (f as).All (fun bs => ∀ b∈bs,b≠6 ∧ b≠7)) : + (wrap F).Realizes (Tape.mk₁ as) ((f as).map Tape.mk₁) (wrapTime F as) := by + have h1 : (pack.seq (OnlineTree.physicalProgram F)).Realizes (Tape.mk₁ as) + ((f as).map (fun bs => Tape.mk₁ (TreePost.packed bs))) + (packTime as.length+OnlineTree.physicalCost F as) := + Program.seq_realizes pack (OnlineTree.physicalProgram F) _ (.done (Tape.mk₁ (TreePost.packed as))) + (fun _ => (f as).map (fun bs => Tape.mk₁ (TreePost.packed bs))) _ _ + (pack_realizes as ha) (OnlineTree.physical_realizes F as) + exact Program.seq_realizes_map _ _ _ (f as) (fun bs => Tape.mk₁ (TreePost.packed bs)) + (fun bs => .done (Tape.mk₁ bs)) _ _ h1 + ((experiment_all_and hout (Experiment.all_worst (f as) List.length)).mono + (fun bs hbs => (post_realizes bs hbs.1).mono (postTime_mono hbs.2))) + +/-- A polynomial representing the exact elementary block-map cost. -/ +noncomputable def budgetPolynomial (w H : ℕ) (p q : Polynomial ℕ) : Polynomial ℕ := + (p+1)*(C (3+w+H)+2*(q+p*C (H+w))) + +lemma eval_budgetPolynomial (w H : ℕ) (p q : Polynomial ℕ) (n : ℕ) : + (budgetPolynomial w H p q).eval n=LiteralBlockMap.budget w H (p.eval n) (q.eval n) := by + simp only [budgetPolynomial,LiteralBlockMap.budget,eval_mul,eval_add,eval_C,eval_one,eval_ofNat] + +/-- Any polynomial bound on the typed experiment gives a polynomial bound +on the complete public binary execution. -/ +theorem polynomial_wrap {f : List Symbol → Experiment (List Symbol)} + (F : OnlineTree.Realizer f) (p : Polynomial ℕ) + (hp : ∀ as,F.cost as+(f as).worst weight ≤ p.eval (weight as)) : + ∃ q : Polynomial ℕ,∀ as,wrapTime F as ≤ q.eval as.length := by + let b : Polynomial ℕ := 18*X+1 + let v := p.comp b + let a := OnlineStack.accesses F.program.code + let o := OnlineStack.overhead F.program.code + let pk : Polynomial ℕ := (1+budgetPolynomial 1 (18*width) X 0)*C (MachineCost.programCost packCode) + let out : Polynomial ℕ := C (MachineCost.programCost (LiteralTape.eraseCode header.length))+ + (1+budgetPolynomial (18*width) 1 v 0)*C (MachineCost.programCost unpackCode) + let fac : Polynomial ℕ := C o*(1+2*C a*(b+v*C a+1))+1 + refine ⟨pk+v*fac+out,fun as => ?_⟩ + have hv : v.eval as.length=p.eval (weight as) := by + simp only [v,b,eval_comp,eval_add,eval_mul,eval_ofNat,eval_X,eval_one,LiteralCodec.weight_word] + have hc : F.cost as ≤ v.eval as.length := by rw [hv]; exact (Nat.le_add_right _ _).trans (hp as) + have hw : (f as).worst weight ≤ v.eval as.length := by rw [hv]; exact (Nat.le_add_left _ _).trans (hp as) + have hl : (f as).worst List.length ≤ v.eval as.length := + Experiment.worst_le _ _ _ ((Experiment.all_worst _ weight).mono + (fun bs hbs => (list_length_le_weight bs).trans (hbs.trans hw))) + have hf : OnlineStack.Executes.factor F.program.code (weight as) (F.cost as) ≤ fac.eval as.length := by + have he : fac.eval as.length=OnlineStack.Executes.factor F.program.code (weight as) (v.eval as.length) := by + simp only [fac,b,eval_add,eval_mul,eval_C,eval_ofNat,eval_one,eval_X, + OnlineStack.Executes.factor,LiteralCodec.weight_word,a,o] + rw [he] + exact OnlineStack.Executes.factor_mono _ _ _ _ le_rfl hc + have hpk : pk.eval as.length=packTime as.length := by + simp only [pk,eval_mul,eval_add,eval_one,eval_C,eval_budgetPolynomial,eval_X,eval_zero,packTime] + have hout : out.eval as.length=postTime (v.eval as.length) := by + simp only [out,eval_add,eval_mul,eval_one,eval_C,eval_budgetPolynomial,eval_zero,postTime] + simp only [eval_add,eval_mul,hpk,hout] + unfold wrapTime OnlineTree.physicalCost + exact Nat.add_le_add (Nat.add_le_add_left (Nat.mul_le_mul hc hf) _) (postTime_mono hl) + +/-- Deterministic typed programs therefore execute on the public binary +tape with one fixed finite transition table and a polynomial time bound. -/ +theorem deterministic_compiles {f : List Symbol → List Symbol} + (F : TreeTyped.Realizer f) (hF : PolynomialTime F) + (hout : ∀ as,∀ b∈f as,b≠6 ∧ b≠7) : + ∃ (A : RandomMachine) (q : Polynomial ℕ),∀ as,(∀ a∈as,a≠0) → + ∀ t,q.eval as.length ≤ t → ∀ bits : Fin t → Bool, + (run A as bits).state=none ∧ (run A as bits).tape.right₀=ListBlank.mk (f as) := by + obtain ⟨p,hp⟩ := hF + obtain ⟨q,hq⟩ := polynomial_wrap (OnlineTree.deterministic F) p hp + refine ⟨(wrap (OnlineTree.deterministic F)).machine,q,?_⟩ + intro as ha t ht bits + have hr := wrap_realizes (OnlineTree.deterministic F) as ha (hout as) + apply hr.run_all (fun T => T.right₀=ListBlank.mk (f as)) _ t ((hq as).trans ht) bits + change (Tape.mk₁ (f as)).right₀=ListBlank.mk (f as) + simp only [Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + +end ContingencyTables.LiteralProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/LowerCapacityProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/LowerCapacityProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..1089d7ebf9c1da5f5065eca4f4c8d65ad28f0b7f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/LowerCapacityProgram.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ListSubtractProgram + +namespace OAI + +/-! # Executable subtraction of a lower bound from a capacity matrix -/ + +namespace ContingencyTables.LowerCapacityProgram + +open MatchingFPRAS.TreeTyped Polynomial ResidualGraphProgram + +abbrev Input := (NatMatrix×(ℕ×ℕ))×ℕ +abbrev RowInput := Input×ℕ + +def readRow (z : RowInput) : List ℕ := z.1.1.1.getD z.2 [] + +def readRowRealizer : Realizer readRow := + composition (pair (composition (composition first first) first) second) (getDFast []) + +lemma polynomial_readRow : PolynomialTime readRowRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) (polynomial_getDFast []) + +def selected (z : RowInput) : Bool := decide (z.2=z.1.1.2.1) + +def selectedRealizer : Realizer selected := + composition (pair second (composition (composition (composition first first) second) first)) natEqual + +lemma polynomial_selected : PolynomialTime selectedRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_first)) polynomial_natEqual + +def shiftedInput (z : RowInput) : ListSubtractProgram.Input := + ((readRow z,z.1.1.2.2),z.1.2) + +def shiftedInputRealizer : Realizer shiftedInput := + pair (pair readRowRealizer + (composition (composition (composition first first) second) second)) + (composition first second) + +lemma polynomial_shiftedInput : PolynomialTime shiftedInputRealizer := + polynomial_pair (polynomial_pair polynomial_readRow + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second)) + (polynomial_composition polynomial_first polynomial_second) + +def row (z : RowInput) : List ℕ := + if z.2=z.1.1.2.1 then ListSubtractProgram.subtractAt (shiftedInput z) else readRow z + +def rowRealizer : Realizer row := + (choose selectedRealizer + (composition (f := shiftedInput) (g := ListSubtractProgram.subtractAt) + shiftedInputRealizer ListSubtractProgram.subtractAtRealizer) readRowRealizer).congr (by + intro z + simp only [Function.comp_apply,row,selected,decide_eq_true_eq]) + +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_congr _ (polynomial_choose polynomial_selected + (polynomial_composition polynomial_shiftedInput ListSubtractProgram.polynomial_subtractAt) + polynomial_readRow) + +def indices (z : Input) : List ℕ := List.range z.1.1.length + +def indicesRealizer : Realizer indices := + composition (composition (composition first first) listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def matrix (z : Input) : NatMatrix := (indices z).map (fun i=>row (z,i)) +def matrixRealizer : Realizer matrix := + composition (pair identity indicesRealizer) (mapWith rowRealizer) +lemma polynomial_matrix : PolynomialTime matrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_row) + +lemma matrix_code {m n : ℕ} (b : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) : + matrix ((natCode b,(i₀.val,j₀.val)),t)=natCode (BoundedCellShift.lower b i₀ j₀ t) := by + simp only [matrix,indices,natCode,List.length_ofFn,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map, + List.map_ofFn] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply] + have hr : readRow ((((List.ofFn (fun i=>List.ofFn (b i)),(i₀.val,j₀.val)),t),i.val))= + List.ofFn (b i) := by + simp only [readRow,List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt, + dite_true,Option.getD_some,Fin.eta] + by_cases hi : i=i₀ + · subst i + simp only [row,ite_true,shiftedInput,hr] + rw [ListSubtractProgram.subtractAt_ofFn] + apply congrArg List.ofFn + funext j + simp [BoundedCellShift.margin,BoundedCellShift.lower] + · have hn : i.val≠i₀.val := fun he=>hi (Fin.ext he) + simp only [row,hn,ite_false,hr] + apply congrArg List.ofFn + funext j + simp [BoundedCellShift.lower,hi] + +end ContingencyTables.LowerCapacityProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixCodeEquality.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixCodeEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..66fad7eb41e75c7c3eafa242c48b746e5957d685 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixCodeEquality.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileCodeEquality +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram + +namespace OAI + +/-! # Polynomial equality of explicitly stored rectangular arrays -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped + +def matrixSignature (X : MatrixCode) : List ℕ×List ℕ := (X.map List.length,X.flatten) + +def matrixSignatureRealizer : Realizer matrixSignature := pair (map listLength) flatten + +lemma polynomial_matrixSignature : PolynomialTime matrixSignatureRealizer := + polynomial_pair (polynomial_map polynomial_listLength) polynomial_flatten + +lemma matrixSignature_injective : Function.Injective matrixSignature := by + intro X Y h + exact List.eq_iff_flatten_eq.mpr ⟨congrArg Prod.snd h,congrArg Prod.fst h⟩ + +def matrixEqual : Realizer (fun z : MatrixCode×MatrixCode => decide (z.1=z.2)) := + (composition (pair (composition first matrixSignatureRealizer) + (composition second matrixSignatureRealizer)) ProfilePrograms.profileCodeEqual).congr (by + intro z + simp only [Function.comp_apply,matrixSignature_injective.eq_iff]) + +lemma polynomial_matrixEqual : PolynomialTime matrixEqual := by + unfold matrixEqual + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_matrixSignature) + (polynomial_composition polynomial_second polynomial_matrixSignature)) + ProfilePrograms.polynomial_profileCodeEqual + +lemma matrixCode_injective {m n : ℕ} : + Function.Injective (matrixCode (m := m) (n := n)) := by + intro X Y h + have hi := List.ofFn_injective h + funext i + exact List.ofFn_injective (congrFun hi i) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixEncoding.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..8743076039eff1c054d4039bcec7be78e60168a2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixEncoding.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram + +namespace OAI + +/-! # The public matrix encoding uniquely identifies a fixed-shape table -/ + +namespace ContingencyTables.Algorithms +open MatchingFPRAS MatchingFPRAS.LiteralParse Turing + +lemma encodeMatrix_flat {m n : ℕ} (X : Fin m → Fin n → ℕ) : + encodeMatrix X=((List.ofFn fun i => List.ofFn (X i)).flatten).flatMap encodeNat := by + rw [←GreedyFeasibleTable.printMatrix_ofFn] + simp only [GreedyFeasibleTable.printMatrix,List.flatten_eq_flatMap,List.flatMap_assoc,id_eq] + +lemma matrix_flat_injective (m n : ℕ) (X Y : Fin m → Fin n → ℕ) + (h : (List.ofFn (fun i => List.ofFn (X i))).flatten= + (List.ofFn (fun i => List.ofFn (Y i))).flatten) : X=Y := by + have hr : List.ofFn (fun i => List.ofFn (X i))=List.ofFn (fun i => List.ofFn (Y i)) := + List.eq_iff_flatten_eq.mpr ⟨h,by + simp only [List.map_ofFn] + congr 1 + funext i + exact (List.length_ofFn).trans (List.length_ofFn.symm)⟩ + have hf := List.ofFn_injective hr + funext i + exact List.ofFn_injective (congrFun hf i) + +lemma encodeMatrix_injective {m n : ℕ} : + Function.Injective (encodeMatrix (m := m) (n := n)) := by + intro X Y h + have hp := congrArg parse h + rw [encodeMatrix_flat,encodeMatrix_flat,GreedyFeasibleTable.parse_natWords, + GreedyFeasibleTable.parse_natWords] at hp + exact matrix_flat_injective m n X Y hp + +lemma parse_blank_extension (as : List Symbol) (n : ℕ) : + parse (as++List.replicate n (0:Symbol))=parse as := by + have hz : (List.replicate n (0:Symbol)).foldr (fun a ns => numStep (a,ns)) []=[] := by + induction n with + | zero => rfl + | succ n ih => + simp only [List.replicate_succ,List.foldr_cons,ih] + rfl + unfold parse + rw [List.foldr_append,hz] + +/-- Parsing natural-number fields is unchanged by trailing tape blanks. -/ +def blankNumbers (tape : ListBlank Symbol) : List ℕ := + tape.liftOn parse (by + rintro as _ ⟨n,rfl⟩ + exact (parse_blank_extension as n).symm) + +lemma blankMatrix_injective {m n : ℕ} (X Y : Fin m → Fin n → ℕ) + (h : ListBlank.mk (encodeMatrix X)=ListBlank.mk (encodeMatrix Y)) : X=Y := by + have hp := congrArg blankNumbers h + change parse (encodeMatrix X)=parse (encodeMatrix Y) at hp + rw [encodeMatrix_flat,encodeMatrix_flat,GreedyFeasibleTable.parse_natWords, + GreedyFeasibleTable.parse_natWords] at hp + exact matrix_flat_injective m n X Y hp + +end ContingencyTables.Algorithms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixSubtractProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixSubtractProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..600c20815cd83c0fdaba14a29c86952e9ebb5963 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/MatrixSubtractProgram.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram +import OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSCode +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid + +namespace OAI + +/-! # Entrywise natural subtraction on a supplied matrix shape -/ + +namespace ContingencyTables.MatrixSubtractProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial DensePrograms + +abbrev Input := MatrixCode × MatrixCode +abbrev RowInput := Input × ℕ + +def entry (z : RowInput × ℕ) : ℕ := + matrixEntry (z.1.1.1,(z.1.2,z.2))-matrixEntry (z.1.1.2,(z.1.2,z.2)) +def entryRealizer : Realizer entry := by + let left : Realizer (fun z : RowInput × ℕ => matrixEntry (z.1.1.1,(z.1.2,z.2))) := + composition (f := fun z : RowInput × ℕ => (z.1.1.1,(z.1.2,z.2))) (g := matrixEntry) + (pair (composition (composition first first) first) + (pair (composition first second) second)) matrixEntryRealizer + let right : Realizer (fun z : RowInput × ℕ => matrixEntry (z.1.1.2,(z.1.2,z.2))) := + composition (f := fun z : RowInput × ℕ => (z.1.1.2,(z.1.2,z.2))) (g := matrixEntry) + (pair (composition (composition first first) second) + (pair (composition first second) second)) matrixEntryRealizer + exact composition (f := fun z : RowInput × ℕ => + (matrixEntry (z.1.1.1,(z.1.2,z.2)),matrixEntry (z.1.1.2,(z.1.2,z.2)))) + (g := fun p : ℕ × ℕ => p.1-p.2) (pair left right) subtract +lemma polynomial_entry : PolynomialTime entryRealizer := by + unfold entryRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_matrixEntry) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_matrixEntry)) polynomial_subtract + +def sourceRow (z : RowInput) : List ℕ := z.1.1.getD z.2 [] +def sourceRowRealizer : Realizer sourceRow := + composition (pair (composition first first) second) (getDFast []) +lemma polynomial_sourceRow : PolynomialTime sourceRowRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast []) + +def columns (z : RowInput) : List ℕ := List.range (sourceRow z).length +def columnsRealizer : Realizer columns := + composition (f := sourceRow) (g := fun xs : List ℕ => List.range xs.length) + sourceRowRealizer (composition listLength range) +lemma polynomial_columns : PolynomialTime columnsRealizer := by + apply polynomial_composition polynomial_sourceRow + apply polynomial_boundedRange polynomial_listLength X + intro xs + simpa only [eval_X] using list_length_le_weight xs + +def row (z : RowInput) : List ℕ := (columns z).map (fun j => entry (z,j)) +def rowRealizer : Realizer row := + composition (pair identity columnsRealizer) (mapWith entryRealizer) +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_columns) + (polynomial_mapWith polynomial_entry) + +def indices (z : Input) : List ℕ := List.range z.1.length +def indicesRealizer : Realizer indices := composition (composition first listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def matrix (z : Input) : MatrixCode := (indices z).map (fun i => row (z,i)) +def matrixRealizer : Realizer matrix := + composition (pair identity indicesRealizer) (mapWith rowRealizer) +theorem polynomial_matrix : PolynomialTime matrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_row) + +theorem matrix_code {m n : ℕ} (B Y : Fin m → Fin n → ℕ) : + matrix (matrixCode B,matrixCode Y)=matrixCode (fun i j => B i j-Y i j) := by + simp only [matrix,indices,matrixCode,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,Function.comp_def] + apply congrArg List.ofFn + funext i + simp only [row,columns,sourceRow,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,dite_true,Option.getD_some,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,Function.comp_def,entry] + apply congrArg List.ofFn + funext j + exact congrArg₂ Nat.sub (matrixEntry_code B i j) (matrixEntry_code Y i j) + +end ContingencyTables.MatrixSubtractProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/MaximalListProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/MaximalListProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3e41544817f200d7b820a5e458a69994ebcfa82 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/MaximalListProgram.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeIndex + +namespace OAI + +/-! # Computing a maximal margin in binary -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped + +def maximumIndex (xs : List ℕ) : ℕ := xs.idxOf (listMaximum (xs,0)) + +def maximumIndexRealizer : Realizer maximumIndex := + composition (pair (composition (pair identity (constant 0)) listMaximumRealizer) identity) + (indexOf natEqual) + +theorem polynomial_maximumIndex : PolynomialTime maximumIndexRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 0)) + polynomial_listMaximum) polynomial_identity) (polynomial_indexOf polynomial_natEqual) + +lemma listMaximum_mem_or_default (xs : List ℕ) (a : ℕ) : + listMaximum (xs,a)=a ∨ listMaximum (xs,a)∈xs := by + induction xs generalizing a with + | nil => exact Or.inl rfl + | cons b bs ih => + change listMaximum (bs,max b a)=a ∨ listMaximum (bs,max b a)∈b::bs + rcases ih (max b a) with he|hm + · rw [he] + rcases le_total b a with h|h + · exact Or.inl (max_eq_right h) + · exact Or.inr (by simp [max_eq_left h]) + · exact Or.inr (List.mem_cons_of_mem b hm) + +lemma listMaximum_mem (xs : List ℕ) (hx : xs≠[]) : listMaximum (xs,0)∈xs := by + cases xs with + | nil => exact (hx rfl).elim + | cons a xs => + change listMaximum (xs,max a 0)∈a::xs + rw [Nat.max_zero] + rcases listMaximum_mem_or_default xs a with he|hm + · simp [he] + · exact List.mem_cons_of_mem a hm + +theorem maximumIndex_lt (xs : List ℕ) (hx : xs≠[]) : maximumIndex xs < xs.length := + List.idxOf_lt_length_iff.mpr (listMaximum_mem xs hx) + +theorem maximumIndex_value (xs : List ℕ) (hx : xs≠[]) : + xs.getD (maximumIndex xs) 0=listMaximum (xs,0) := by + rw [List.getD_eq_getElem xs 0 (maximumIndex_lt xs hx)] + exact List.getElem_idxOf (maximumIndex_lt xs hx) + +theorem maximumIndex_maximal (xs : List ℕ) (hx : xs≠[]) (a : ℕ) (ha : a∈xs) : + a≤xs.getD (maximumIndex xs) 0 := by + rw [maximumIndex_value xs hx] + exact le_listMaximum_member xs 0 a ha + +def maximumPosition {n : ℕ} (f : Fin (n+1) → ℕ) : Fin (n+1) := + ⟨maximumIndex (List.ofFn f),by + simpa only [List.length_ofFn] using maximumIndex_lt (List.ofFn f) + (by intro h; have := congrArg List.length h; simp only [List.length_ofFn,List.length_nil] at this; omega)⟩ + +theorem maximumPosition_spec {n : ℕ} (f : Fin (n+1) → ℕ) (i : Fin (n+1)) : + f i≤f (maximumPosition f) := by + have hx : List.ofFn f≠[] := by + intro h + have := congrArg List.length h + simp only [List.length_ofFn,List.length_nil] at this + omega + have hm := maximumIndex_maximal (List.ofFn f) hx (f i) (List.mem_ofFn.mpr ⟨i,rfl⟩) + have he : (List.ofFn f).getD (maximumIndex (List.ofFn f)) 0=f (maximumPosition f) := by + rw [List.getD_eq_getElem (List.ofFn f) 0 (maximumIndex_lt (List.ofFn f) hx),List.getElem_ofFn] + rfl + rwa [he] at hm + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/MedianFractionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/MedianFractionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..51d997d04f01924063f30a32ba28381f6b3e704e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/MedianFractionProgram.lean @@ -0,0 +1,248 @@ +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Binary fraction median with polynomial running time -/ + +namespace ContingencyTables.MedianFractionProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.TreeFraction Polynomial + +abbrev State := Fraction × (List Fraction × List Fraction) + +def insertRaw (q : Fraction) : List Fraction → List Fraction + | [] => [q] + | x::xs => if TreeFraction.less (x,q) then x::insertRaw q xs else q::x::xs + +def step (z : Fraction × State) : State := + (z.2.1,(z.1::z.2.2.1, + if TreeFraction.less (z.1,z.2.1) then z.1::z.2.2.2 else z.2.1::z.1::z.2.2.1)) + +def stepRealizer : Realizer step := by + let q : Realizer (fun z : Fraction × State => z.2.1) := composition second first + let xs : Realizer (fun z : Fraction × State => z.1::z.2.2.1) := + composition (pair first (composition (composition second second) first)) listCons + let yes : Realizer (fun z : Fraction × State => z.1::z.2.2.2) := + composition (pair first (composition (composition second second) second)) listCons + let no : Realizer (fun z : Fraction × State => z.2.1::z.1::z.2.2.1) := + composition (pair q xs) listCons + exact pair q (pair xs (choose (composition (pair first q) TreeFraction.lessRealizer) yes no)) + +lemma polynomial_step : PolynomialTime stepRealizer := by + unfold stepRealizer + exact polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first)) polynomial_listCons) + (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) TreeFraction.polynomial_less) + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_second)) polynomial_listCons) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first)) polynomial_listCons)) polynomial_listCons))) + +def insert (z : Fraction × List Fraction) : List Fraction := + (z.2.reverse.foldl (fun s x => step (x,s)) (z.1,([],[z.1]))).2.2 + +lemma insert_fold (q : Fraction) (xs : List Fraction) : + xs.reverse.foldl (fun s x => step (x,s)) (q,([],[q])) = (q,(xs,insertRaw q xs)) := by + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.reverse_cons,List.foldl_append,ih,List.foldl_cons,List.foldl_nil] + rfl + +lemma insert_eq (q : Fraction) (xs : List Fraction) : insert (q,xs)=insertRaw q xs := by + unfold insert + rw [insert_fold] + +lemma insert_weight (q : Fraction) (xs : List Fraction) : + weight (insertRaw q xs)=1+weight q+weight xs := by + induction xs with + | nil => simp [insertRaw] + | cons x xs ih => + simp only [insertRaw] + split <;> simp only [weight_cons,ih] + all_goals omega + +lemma fold_weight (xs : List Fraction) (q : Fraction) (zs ys : List Fraction) : + let t := xs.foldl (fun s x => step (x,s)) (q,(zs,ys)) + t.1=q ∧ weight t.2.1+1=weight zs+weight xs ∧ + weight t.2.2 ≤ max (weight ys) (weight q+weight zs+1)+weight xs := by + induction xs generalizing zs ys with + | nil => + exact ⟨rfl,by simp only [List.foldl_nil,weight_nil],by + simpa only [List.foldl_nil,weight_nil] using + (Nat.le_max_left (weight ys) (weight q+weight zs+1)).trans (Nat.le_succ _)⟩ + | cons x xs ih => + rw [List.foldl_cons] + change (let t := xs.foldl (fun s x => step (x,s)) (q,(x::zs,if TreeFraction.less (x,q) then x::ys else q::x::zs)); + t.1=q ∧ weight t.2.1+1=weight zs+weight (x::xs) ∧ + weight t.2.2 ≤ max (weight ys) (weight q+weight zs+1)+weight (x::xs)) + have hh := ih (x::zs) (if TreeFraction.less (x,q) then x::ys else q::x::zs) + dsimp only at hh ⊢ + refine ⟨hh.1,?_,?_⟩ + · simp only [weight_cons] at hh ⊢; omega + · by_cases h : TreeFraction.less (x,q)=true + · simp only [h,ite_true,weight_cons] at hh ⊢; omega + · simp only [h,Bool.false_eq_true,ite_false,weight_cons] at hh ⊢; omega + +lemma state_weight (s : State) : + weight s=1+weight s.1+(1+weight s.2.1+weight s.2.2) := by + rcases s with ⟨q,xs,ys⟩ + simp only [weight_prod] + +lemma polynomial_stepFold : PolynomialTime (fold stepRealizer) := by + apply polynomial_fold polynomial_step (5*X+5) + intro xs s pre post he + rcases s with ⟨q,zs,ys⟩ + have hh := fold_weight pre q zs ys + have hp := weight_prefix he + simp only [eval_add,eval_mul,eval_ofNat,eval_X,weight_prod] + rw [state_weight,hh.1] + omega + +def insertRealizer : Realizer insert := by + let prep : Realizer (fun z : Fraction × List Fraction => (z.2.reverse,(z.1,([],[z.1])))) := + pair (composition second reverse) + (pair first (pair (constant ([] : List Fraction)) (composition (pair first (constant ([] : List Fraction))) listCons))) + let tail : Realizer (fun z : List Fraction × State => + (z.1.foldl (fun s x => step (x,s)) z.2).2.2) := + composition (f := fun z : List Fraction × State => + (z.1.foldl (fun s x => step (x,s)) z.2).2) (g := fun z => z.2) + (composition (fold stepRealizer) second) second + exact composition + (f := fun z : Fraction × List Fraction => (z.2.reverse,(z.1,([],[z.1])))) + (g := fun z : List Fraction × State => + (z.1.foldl (fun s x => step (x,s)) z.2).2.2) prep tail + +lemma polynomial_insert : PolynomialTime insertRealizer := by + unfold insertRealizer + exact polynomial_composition + (polynomial_pair (polynomial_composition polynomial_second polynomial_reverse) + (polynomial_pair polynomial_first (polynomial_pair (polynomial_constant ([] : List Fraction)) + (polynomial_composition (polynomial_pair polynomial_first (polynomial_constant ([] : List Fraction))) + polynomial_listCons)))) + (polynomial_composition (polynomial_composition polynomial_stepFold polynomial_second) + polynomial_second) + +def sort (xs : List Fraction) : List Fraction := + xs.reverse.foldl (fun s x => insert (x,s)) [] + +def sortRealizer : Realizer sort := + composition (f := fun xs : List Fraction => (xs.reverse,([] : List Fraction))) + (g := fun z : List Fraction × List Fraction => z.1.foldl (fun s x => insert (x,s)) z.2) + (pair reverse (constant [])) (fold insertRealizer) + +lemma sortFold_weight (xs zs : List Fraction) : + weight (xs.foldl (fun s x => insert (x,s)) zs)+1=weight zs+weight xs := by + induction xs generalizing zs with + | nil => simp + | cons x xs ih => + have hh := ih (insert (x,zs)) + simp only [List.foldl_cons,insert_eq,insert_weight,weight_cons] at hh ⊢ + omega + +lemma polynomial_insertFold : PolynomialTime (fold insertRealizer) := by + apply polynomial_fold polynomial_insert (2*X) + intro xs zs pre post he + have hh := sortFold_weight pre zs + have hp := weight_prefix he + simp only [eval_mul,eval_ofNat,eval_X,weight_prod] + omega + +lemma polynomial_sort : PolynomialTime sortRealizer := + polynomial_composition (polynomial_pair polynomial_reverse (polynomial_constant ([] : List Fraction))) + polynomial_insertFold + +lemma insert_pos (q : Fraction) (xs : List Fraction) (hq : 0 < q.2) + (hx : ∀ x∈xs,0 < x.2) : ∀ y∈insertRaw q xs,0 < y.2 := by + induction xs with + | nil => simpa only [insertRaw,List.mem_singleton] using fun y hy => hy ▸ hq + | cons x xs ih => + have hxx := hx x (by simp) + have ht := ih (fun y hy => hx y (by simp [hy])) + simp only [insertRaw] + split <;> intro y hy <;> simp only [List.mem_cons] at hy + · rcases hy with rfl|hy + · exact hxx + · exact ht y hy + · rcases hy with rfl|rfl|hy + · exact hq + · exact hxx + · exact hx y (by simp [hy]) + +lemma insert_map (q : Fraction) (xs : List Fraction) (hq : 0 < q.2) + (hx : ∀ x∈xs,0 < x.2) : + (insertRaw q xs).map val=(xs.map val).orderedInsert (·≤·) (val q) := by + induction xs with + | nil => rfl + | cons x xs ih => + have hxx := hx x (by simp) + have ht := ih (fun y hy => hx y (by simp [hy])) + simp only [insertRaw,List.map_cons,List.orderedInsert_cons,TreeFraction.less_val x q hxx hq] + by_cases h : val x < val q + · simp [h,not_le.mpr h,ht] + · simp [h,le_of_not_gt h] + +lemma sort_cons (x : Fraction) (xs : List Fraction) : sort (x::xs)=insert (x,sort xs) := by + simp only [sort,List.reverse_cons,List.foldl_append,List.foldl_cons,List.foldl_nil] + +lemma sort_pos (xs : List Fraction) (hx : ∀ x∈xs,0 < x.2) : ∀ y∈sort xs,0 < y.2 := by + induction xs with + | nil => simp [sort] + | cons x xs ih => + rw [sort_cons,insert_eq] + exact insert_pos x (sort xs) (hx x (by simp)) + (ih (fun y hy => hx y (by simp [hy]))) + +lemma sort_map (xs : List Fraction) (hx : ∀ x∈xs,0 < x.2) : + (sort xs).map val=(xs.map val).mergeSort (·≤·) := by + rw [List.mergeSort_eq_insertionSort] + induction xs with + | nil => rfl + | cons x xs ih => + have ht : ∀ y∈xs,0 < y.2 := fun y hy => hx y (by simp [hy]) + rw [sort_cons,insert_eq,insert_map x (sort xs) (hx x (by simp)) (sort_pos xs ht),ih ht] + rfl + +def median (xs : List Fraction) : Fraction := + (sort (xs.map TreeFraction.normalize)).getD (xs.length/2) (0,1) + +def medianRealizer : Realizer median := + composition (f := fun xs : List Fraction => (sort (xs.map TreeFraction.normalize),xs.length/2)) + (g := fun z : List Fraction × ℕ => z.1.getD z.2 (0,1)) (pair (composition (f := fun xs : List Fraction => xs.map TreeFraction.normalize) + (g := sort) (TreeTyped.map normalizeRealizer) sortRealizer) + (composition (pair listLength (constant 2)) quotient)) (getDFast (0,1)) + +lemma polynomial_median : PolynomialTime medianRealizer := + polynomial_composition + (polynomial_pair (polynomial_composition (polynomial_map TreeFraction.polynomial_normalize) + polynomial_sort) + (polynomial_composition (polynomial_pair polynomial_listLength (polynomial_constant 2)) + polynomial_quotient)) (polynomial_getDFast (0,1)) + +lemma median_val (xs : List Fraction) : + val (median xs)=CommonBasesFPRAS.rationalMedian (xs.map val) := by + have hs := sort_map (xs.map TreeFraction.normalize) (by + intro y hy + obtain ⟨x,_,rfl⟩ := List.mem_map.mp hy + exact normalize_den_pos x) + have hm : (xs.map TreeFraction.normalize).map val=xs.map val := by + simp only [List.map_map,Function.comp_def,normalize_val] + rw [hm] at hs + unfold median CommonBasesFPRAS.rationalMedian + rw [←hs,List.length_map] + simp only [List.getD_eq_getElem?_getD,List.getElem?_map] + cases (sort (xs.map TreeFraction.normalize))[xs.length/2]? <;> simp only [Option.getD_none,Option.map_none,Option.getD_some,Option.map_some,val, Nat.cast_zero,zero_div] + +end ContingencyTables.MedianFractionProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/NatListEquality.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/NatListEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba9b90bd591deb7e15f561d7f327daaae1f25eb5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/NatListEquality.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # Binary list equality for matching tabulated states and outputs -/ + +namespace ContingencyTables.NatListEquality +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def indices (z : List ℕ×List ℕ) : List ℕ := List.range z.1.length + +def indicesRealizer : Realizer indices := composition (composition first listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) + Polynomial.X + intro z + simpa only [Polynomial.eval_X,Function.comp_apply] using + (list_length_le_weight z.1).trans (weight_fst z) + +def atEqual (z : (List ℕ×List ℕ)×ℕ) : Bool := decide (z.1.1.getD z.2 0=z.1.2.getD z.2 0) + +def atEqualRealizer : Realizer atEqual := + composition (pair + (composition (pair (composition first first) second) (getDFast 0)) + (composition (pair (composition first second) second) (getDFast 0))) natEqual + +lemma polynomial_atEqual : PolynomialTime atEqualRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast 0))) polynomial_natEqual + +def listEqual (z : List ℕ×List ℕ) : Bool := + decide (z.1.length=z.2.length) && (indices z).all (fun i => atEqual (z,i)) + +def listEqualRealizer : Realizer listEqual := + (composition (pair + (composition (pair (composition first listLength) (composition second listLength)) natEqual) + (composition (composition (pair identity indicesRealizer) (mapWith atEqualRealizer)) all)) + boolAnd).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,listEqual]) + +theorem polynomial_listEqual : PolynomialTime listEqualRealizer := by + unfold listEqualRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_listLength) + (polynomial_composition polynomial_second polynomial_listLength)) polynomial_natEqual) + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_atEqual)) polynomial_all)) polynomial_boolAnd + +theorem listEqual_true (xs ys : List ℕ) : listEqual (xs,ys)=true ↔ xs=ys := by + simp only [listEqual,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true] + constructor + · rintro ⟨hlen,h⟩ + apply List.ext_getElem hlen + intro i hi hj + have hv:=of_decide_eq_true (h i (List.mem_range.mpr hi)) + simpa only [atEqual,List.getD_eq_getElem?_getD,List.getElem?_eq_getElem hi, + List.getElem?_eq_getElem hj,Option.getD_some] using hv + · intro h + subst ys + exact ⟨rfl,fun _ _ => by simp [atEqual]⟩ + +end ContingencyTables.NatListEquality + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/NaturalBlockProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/NaturalBlockProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a067dcec5cb0850d8277527959a75c0090422e6d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/NaturalBlockProgram.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Machines.DependentWordProgram +import Mathlib.Data.List.SplitLengths + +namespace OAI + +/-! # Bounded scans of natural-number blocks + +Numeric widths select bounded slices of the supplied list. They never +control an allocation, so malformed widths preserve polynomial cost. +-/ + +namespace ContingencyTables.NaturalBlockProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +abbrev Input := List ℕ × List ℕ +abbrev Entry := Input × ℕ + +def start (z : Entry) : ℕ := (z.1.1.take z.2).sum +def startRealizer : Realizer start := + composition (composition (pair (composition first first) second) takeFast) listSum +lemma polynomial_start : PolynomialTime startRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_takeFast) polynomial_listSum + +def block (z : Entry) : List ℕ := + (z.1.2.drop (start z)).take (z.1.1.getD z.2 0) +def blockRealizer : Realizer block := + composition (pair + (composition (pair (composition first second) startRealizer) dropFast) + (composition (pair (composition first first) second) (getDFast 0))) takeFast +lemma polynomial_block : PolynomialTime blockRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_start) + polynomial_dropFast) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0))) polynomial_takeFast + +def indices (z : Input) : List ℕ := List.range z.1.length +def indicesRealizer : Realizer indices := composition (composition first listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def blocks (z : Input) : List (List ℕ) := (indices z).map (fun i => block (z,i)) +def blocksRealizer : Realizer blocks := + composition (pair identity indicesRealizer) (mapWith blockRealizer) +theorem polynomial_blocks : PolynomialTime blocksRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_block) + +lemma block_splitLengths (widths values : List ℕ) (i : ℕ) : + block ((widths,values),i)=(widths.splitLengths values).getD i [] := by + induction widths generalizing values i with + | nil => simp [block,start] + | cons w ws ih => + cases i with + | zero => simp [block,start,List.splitLengths_cons] + | succ i => + simpa only [block,start,List.take_succ_cons,List.sum_cons,List.getD_cons_succ, + List.splitLengths_cons,List.drop_drop,Nat.add_comm] using ih (values.drop w) i + +theorem blocks_eq_splitLengths (widths values : List ℕ) : + blocks (widths,values)=widths.splitLengths values := by + apply List.ext_getElem + · simp [blocks,indices] + · intro i hi hj + have hiw : i < widths.length := by + simpa only [blocks,indices,List.length_map,List.length_range] using hi + simp only [blocks,indices,List.getElem_map,List.getElem_range] + have h := block_splitLengths widths values i + simpa only [List.getD_eq_getElem?_getD,List.getElem?_eq_getElem hj,Option.getD_some] using h + +lemma splitLengths_flatten (rows : List (List ℕ)) : + (rows.map List.length).splitLengths rows.flatten=rows := by + induction rows with + | nil => rfl + | cons row rows ih => + simpa only [List.map_cons,List.flatten_cons,List.splitLengths_cons, + List.take_left,List.drop_left] using congrArg (List.cons row) ih + +/-- A literal list of rows is recovered exactly from its stored row +lengths and its flattened code, including rows of length zero. -/ +theorem blocks_flatten (rows : List (List ℕ)) : + blocks (rows.map List.length,rows.flatten)=rows := by + rw [blocks_eq_splitLengths,splitLengths_flatten] + +end ContingencyTables.NaturalBlockProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkCapacityProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkCapacityProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c996cb19601487e89c80f094d21ab1b0acfae153 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkCapacityProgram.lean @@ -0,0 +1,233 @@ +import OAI.Combinatorics.ContingencyTables.Transport.NetworkVertexCode +import OAI.Combinatorics.ContingencyTables.Machines.FlowLoopProgram + +namespace OAI + +/-! # Constructing the bounded-table capacity network in binary -/ + +namespace ContingencyTables.NetworkCapacityProgram + +open MatchingFPRAS.TreeTyped Polynomial NetworkVertexCode ResidualGraphProgram + +abbrev EntryInput := Input×(ℕ×ℕ) + +def kindRealizer : Realizer (fun z : ℕ×ℕ=>kind z.1 z.2) := + (choose (composition (pair second (constant 0)) natEqual) (constant 0) + (choose (composition (pair second (constant 1)) natEqual) (constant 1) + (choose (composition (pair second (composition (pair (constant 2) first) add)) less) + (constant 2) (constant 3)))).congr (by + intro z + simp only [Function.comp_apply,kind,decide_eq_true_eq]) + +lemma polynomial_kind : PolynomialTime kindRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 0)) + polynomial_natEqual) (polynomial_constant 0) + (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 1)) + polynomial_natEqual) (polynomial_constant 1) + (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_first) + polynomial_add)) polynomial_less) + (polynomial_constant 2) (polynomial_constant 3)))) + +def rowCount (z : EntryInput) : ℕ := z.1.1.1.length + +def rowCountRealizer : Realizer rowCount := + composition (composition (composition first first) first) listLength + +lemma polynomial_rowCount : PolynomialTime rowCountRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_listLength + +def columnBase (z : EntryInput) : ℕ := 2+rowCount z + +def columnBaseRealizer : Realizer columnBase := + composition (f := fun z : EntryInput=>(2,rowCount z)) + (g := fun a : ℕ×ℕ=>a.1+a.2) (pair (constant 2) rowCountRealizer) add + +lemma polynomial_columnBase : PolynomialTime columnBaseRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_rowCount) + polynomial_add + +def kinds (z : EntryInput) : ℕ×ℕ := + (kind (rowCount z) z.2.1,kind (rowCount z) z.2.2) + +def kindsRealizer : Realizer kinds := + pair (composition (pair rowCountRealizer (composition second first)) kindRealizer) + (composition (pair rowCountRealizer (composition second second)) kindRealizer) + +lemma polynomial_kinds : PolynomialTime kindsRealizer := + polynomial_pair (polynomial_composition (polynomial_pair polynomial_rowCount + (polynomial_composition polynomial_second polynomial_first)) polynomial_kind) + (polynomial_composition (polynomial_pair polynomial_rowCount + (polynomial_composition polynomial_second polynomial_second)) polynomial_kind) + +def pattern (a b : ℕ) (z : EntryInput) : Bool := + decide ((kinds z).1=a) && decide ((kinds z).2=b) + +def patternRealizer (a b : ℕ) : Realizer (pattern a b) := + composition kindsRealizer (composition (pair + (composition (pair first (constant a)) natEqual) + (composition (pair second (constant b)) natEqual)) boolAnd) + +lemma polynomial_pattern (a b : ℕ) : PolynomialTime (patternRealizer a b) := + polynomial_composition polynomial_kinds (polynomial_composition + (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first (polynomial_constant a)) + polynomial_natEqual) + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant b)) + polynomial_natEqual)) polynomial_boolAnd) + +def rowRead (z : EntryInput) : ℕ := z.1.1.1.getD (z.2.2-2) 0 + +def rowReadRealizer : Realizer rowRead := + composition (pair (composition (composition first first) first) + (composition (pair (composition second second) (constant 2)) subtract)) (getDFast 0) + +lemma polynomial_rowRead : PolynomialTime rowReadRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_second) (polynomial_constant 2)) + polynomial_subtract)) (polynomial_getDFast 0) + +def columnRead (z : EntryInput) : ℕ := z.1.1.2.getD (z.2.1-columnBase z) 0 + +def columnReadRealizer : Realizer columnRead := + composition (pair (composition (composition first first) second) + (composition (pair (composition second first) columnBaseRealizer) subtract)) (getDFast 0) + +lemma polynomial_columnRead : PolynomialTime columnReadRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) polynomial_columnBase) + polynomial_subtract)) (polynomial_getDFast 0) + +def boundRead (z : EntryInput) : ℕ := + capacityEntry (z.1.2,(z.2.1-2,z.2.2-columnBase z)) + +def boundReadRealizer : Realizer boundRead := + composition (pair (composition first second) + (pair (composition (pair (composition second first) (constant 2)) subtract) + (composition (pair (composition second second) columnBaseRealizer) subtract))) + capacityEntryRealizer + +lemma polynomial_boundRead : PolynomialTime boundReadRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) (polynomial_constant 2)) + polynomial_subtract) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_second) polynomial_columnBase) + polynomial_subtract))) polynomial_capacityEntry + +def entryRealizer : Realizer entry := + (choose (patternRealizer 0 2) rowReadRealizer + (choose (patternRealizer 2 3) boundReadRealizer + (choose (patternRealizer 3 1) columnReadRealizer (constant 0)))).congr (by + intro z + have hp (a b : ℕ) : pattern a b z=true ↔ + kind z.1.1.1.length z.2.1=a ∧ kind z.1.1.1.length z.2.2=b := by + change ((decide (kind z.1.1.1.length z.2.1=a)) && + (decide (kind z.1.1.1.length z.2.2=b)))=true ↔ _ + rw [Bool.and_eq_true] + constructor + · rintro ⟨ha,hb⟩ + exact ⟨_root_.of_decide_eq_true ha,_root_.of_decide_eq_true hb⟩ + · rintro ⟨ha,hb⟩ + exact ⟨_root_.decide_eq_true ha,_root_.decide_eq_true hb⟩ + simp only [hp,columnBase,rowRead,columnRead,boundRead,entry,rowCount]) + +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_congr _ (polynomial_choose (polynomial_pattern 0 2) polynomial_rowRead + (polynomial_choose (polynomial_pattern 2 3) polynomial_boundRead + (polynomial_choose (polynomial_pattern 3 1) polynomial_columnRead (polynomial_constant 0)))) + +def vertexCountRealizer : Realizer vertexCount := + composition (f := fun z : Input=>(2,z.1.1.length+z.1.2.length)) + (g := fun a : ℕ×ℕ=>a.1+a.2) + (pair (constant 2) (composition + (f := fun z : Input=>(z.1.1.length,z.1.2.length)) + (g := fun a : ℕ×ℕ=>a.1+a.2) + (pair (composition (composition first first) listLength) + (composition (composition first second) listLength)) add)) add + +lemma polynomial_vertexCount : PolynomialTime vertexCountRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 2) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength)) polynomial_add)) polynomial_add + +def vertices (z : Input) : List ℕ := List.range (vertexCount z) +def verticesRealizer : Realizer vertices := composition vertexCountRealizer range + +lemma polynomial_vertices : PolynomialTime verticesRealizer := by + apply polynomial_boundedRange polynomial_vertexCount (2+2*X) + intro z + have hr := (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + have hc := (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + simp only [vertexCount,eval_add,eval_ofNat,eval_mul,eval_X] + omega + +def row (z : Input×ℕ) : List ℕ := + (vertices z.1).map (fun v=>entry (z.1,(z.2,v))) + +def rowRealizer : Realizer row := + composition (pair identity (composition first verticesRealizer)) + (mapWith (composition + (pair (composition first first) (pair (composition first second) second)) entryRealizer)) + +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_vertices)) + (polynomial_mapWith (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_entry)) + +def matrixRealizer : Realizer matrix := + composition (pair identity verticesRealizer) (mapWith rowRealizer) + +lemma polynomial_matrix : PolynomialTime matrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_vertices) + (polynomial_mapWith polynomial_row) + +def solve (z : Input) : FlowMatrix := FlowLoopProgram.run (matrix z,(0,1)) + +def solveRealizer : Realizer solve := + composition (pair matrixRealizer (constant (0,1))) FlowLoopProgram.runRealizer + +lemma polynomial_solve : PolynomialTime solveRealizer := + polynomial_composition (polynomial_pair polynomial_matrix (polynomial_constant (0,1))) + FlowLoopProgram.polynomial_run + +theorem solve_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + solve (data r c b)=flowCode (EdmondsKarpAlgorithm.maxFlow + (BoundedTableFeasibility.networkCapacity r c b) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.source) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.sink)) := by + have hs : (BoundedTableFeasibility.vertices m n (LayeredTableNetwork.source : + LayeredTableNetwork.Vertex m n)).val=0 := index_vertices _ + have ht : (BoundedTableFeasibility.vertices m n (LayeredTableNetwork.sink : + LayeredTableNetwork.Vertex m n)).val=1 := index_vertices _ + unfold solve + rw [matrix_code] + simpa only [hs,ht] using FlowLoopProgram.run_code + (BoundedTableFeasibility.networkCapacity r c b) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.source) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.sink) + BoundedTableFeasibility.source_ne_sink + +end ContingencyTables.NetworkCapacityProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkFeasibilityProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkFeasibilityProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..892b8d4fdecc0ad9ee6362020d4e3a1012575398 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkFeasibilityProgram.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Machines.NetworkCapacityProgram + +namespace OAI + +/-! # The actual polynomial binary bounded-table feasibility test -/ + +namespace ContingencyTables.NetworkFeasibilityProgram + +open MatchingFPRAS.TreeTyped NetworkVertexCode NetworkCapacityProgram ResidualGraphProgram +open scoped BigOperators + +def sourcePair (z : Input) : SignedPairProgram.Signed := + SignedPairProgram.sum ((solve z).getD 0 []) + +def sourcePairRealizer : Realizer sourcePair := + composition (composition (pair solveRealizer (constant 0)) (getDFast [])) + SignedPairProgram.sumRealizer + +lemma polynomial_sourcePair : PolynomialTime sourcePairRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_solve (polynomial_constant 0)) (polynomial_getDFast [])) + SignedPairProgram.polynomial_sum + +def inputValues (z : Input) : (ℕ×ℕ)×SignedPairProgram.Signed := + ((z.1.1.sum,z.1.2.sum),sourcePair z) + +def inputValuesRealizer : Realizer inputValues := + pair (pair (composition (composition first first) listSum) + (composition (composition first second) listSum)) sourcePairRealizer + +lemma polynomial_inputValues : PolynomialTime inputValuesRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listSum) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listSum)) polynomial_sourcePair + +def testValues (z : (ℕ×ℕ)×SignedPairProgram.Signed) : Bool := + decide (z.1.1=z.1.2) && decide (z.2.1=z.1.1+z.2.2) + +def testValuesRealizer : Realizer testValues := + composition (pair (composition first natEqual) + (composition (pair (composition second first) + (composition (pair (composition first first) (composition second second)) add)) + natEqual)) boolAnd + +lemma polynomial_testValues : PolynomialTime testValuesRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_natEqual) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add)) + polynomial_natEqual)) polynomial_boolAnd + +def test (z : Input) : Bool := testValues (inputValues z) +def testRealizer : Realizer test := composition inputValuesRealizer testValuesRealizer + +lemma polynomial_test : PolynomialTime testRealizer := + polynomial_composition polynomial_inputValues polynomial_testValues + +lemma flowCode_row_value {n : ℕ} (f : PublishedEdmondsKarp.Flow n) (s : Fin n) : + SignedPairProgram.value (SignedPairProgram.sum ((flowCode f).getD s.val []))= + PublishedEdmondsKarp.value s f := by + have hr : (flowCode f).getD s.val []= + List.ofFn (fun v=>ForestAffineProgram.signedParts (f s v)) := by + simp only [flowCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn,s.isLt, + dite_true,Option.getD_some,Fin.eta] + rw [hr,SignedPairProgram.value_sum] + simp only [List.map_ofFn,Function.comp_def,SignedPairProgram.value, + ForestAffineProgram.signedParts_sub,List.sum_ofFn,PublishedEdmondsKarp.value] + +lemma sourcePair_value {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + SignedPairProgram.value (sourcePair (data r c b))= + LayeredTableNetwork.value (BoundedTableFeasibility.computedFlow r c b) := by + unfold sourcePair + rw [solve_code] + have hs : (BoundedTableFeasibility.vertices m n (LayeredTableNetwork.source : + LayeredTableNetwork.Vertex m n)).val=0 := index_vertices _ + rw [←hs,flowCode_row_value] + exact (BoundedTableFeasibility.pull_value _).symm + +lemma test_eq_feasible {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + test (data r c b)=BoundedTableFeasibility.feasibleTest r c b := by + apply Bool.eq_iff_iff.mpr + simp only [test,testValues,inputValues,Bool.and_eq_true,decide_eq_true_eq, + BoundedTableFeasibility.feasibleTest,data,List.sum_ofFn] + have hv := sourcePair_value r c b + have he : (sourcePair (data r c b)).1= + (∑ i,r i)+(sourcePair (data r c b)).2 ↔ + SignedPairProgram.value (sourcePair (data r c b))=∑ i,(r i:ℤ) := by + unfold SignedPairProgram.value + rw [←Nat.cast_sum] + omega + exact and_congr_right (fun _=>he.trans (by rw [hv])) + +theorem test_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + test (data r c b)=true ↔ ∃ X,HasMargins X r c ∧ ∀ i j,X i j≤b i j := by + rw [test_eq_feasible] + exact BoundedTableFeasibility.feasibleTest_correct hEK r c b + +end ContingencyTables.NetworkFeasibilityProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkTableProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkTableProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c781b01f0acc2c695c08c3c282a62688f3315174 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/NetworkTableProgram.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram + +namespace OAI + +/-! # Extracting the bounded table from the executed flow + +The output reads the row-to-column arcs of the computed flow. Both the +matrix dimensions and the encoded entries are obtained from the input; +there is no choice of a mathematical witness in the program. +-/ + +namespace ContingencyTables.NetworkTableProgram + +open MatchingFPRAS.TreeTyped Polynomial NetworkVertexCode ResidualGraphProgram +open scoped BigOperators + +abbrev Prepared := (List ℕ×List ℕ)×FlowMatrix +abbrev CellInput := Prepared×(ℕ×ℕ) + +def cell (z : CellInput) : ℕ := + let a := flowEntry (z.1.2,(2+z.2.1,2+z.1.1.1.length+z.2.2)) + a.1-a.2 + +def cellRealizer : Realizer cell := by + let F : Realizer (fun z : CellInput=>z.1.2) := composition first second + let I : Realizer (fun z : CellInput=>2+z.2.1) := + composition (f := fun z : CellInput=>(2,z.2.1)) + (g := fun a : ℕ×ℕ=>a.1+a.2) (pair (constant 2) (composition second first)) add + let J : Realizer (fun z : CellInput=>2+z.1.1.1.length+z.2.2) := + composition (f := fun z : CellInput=>(2+z.1.1.1.length,z.2.2)) + (g := fun a : ℕ×ℕ=>a.1+a.2) + (pair (composition (f := fun z : CellInput=>(2,z.1.1.1.length)) + (g := fun a : ℕ×ℕ=>a.1+a.2) + (pair (constant 2) (composition (composition (composition first first) first) listLength)) add) + (composition second second)) add + exact composition (f := fun z : CellInput=> + flowEntry (z.1.2,(2+z.2.1,2+z.1.1.1.length+z.2.2))) + (g := fun a : SignedPairProgram.Signed=>a.1-a.2) + (composition (f := fun z : CellInput=> + (z.1.2,(2+z.2.1,2+z.1.1.1.length+z.2.2))) (g := flowEntry) + (pair F (pair I J)) flowEntryRealizer) subtract + +lemma polynomial_cell : PolynomialTime cellRealizer := by + unfold cellRealizer + apply polynomial_composition + · apply polynomial_composition + · exact polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) + (polynomial_composition polynomial_second polynomial_first)) polynomial_add) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_listLength)) polynomial_add) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add)) + · exact polynomial_flowEntry + · exact polynomial_subtract + +def rowIndices (z : Prepared) : List ℕ := List.range z.1.1.length +def columnIndices (z : Prepared) : List ℕ := List.range z.1.2.length + +def rowIndicesRealizer : Realizer rowIndices := + composition (composition (composition first first) listLength) range + +def columnIndicesRealizer : Realizer columnIndices := + composition (composition (composition first second) listLength) range + +lemma polynomial_rowIndices : PolynomialTime rowIndicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +lemma polynomial_columnIndices : PolynomialTime columnIndicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + +def row (z : Prepared×ℕ) : List ℕ := + (columnIndices z.1).map (fun j=>cell (z.1,(z.2,j))) + +def rowRealizer : Realizer row := + composition (pair identity (composition first columnIndicesRealizer)) + (mapWith (composition (f := fun z : (Prepared×ℕ)×ℕ=>(z.1.1,(z.1.2,z.2))) + (g := cell) (pair (composition first first) + (pair (composition first second) second)) cellRealizer)) + +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_columnIndices)) + (polynomial_mapWith (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_cell)) + +def table (z : Prepared) : NatMatrix := + (rowIndices z).map (fun i=>row (z,i)) + +def tableRealizer : Realizer table := + composition (pair identity rowIndicesRealizer) (mapWith rowRealizer) + +lemma polynomial_table : PolynomialTime tableRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_rowIndices) + (polynomial_mapWith polynomial_row) + +def prepare (z : Input) : Prepared := + (z.1,NetworkCapacityProgram.solve z) + +def prepareRealizer : Realizer prepare := + pair first NetworkCapacityProgram.solveRealizer + +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair polynomial_first NetworkCapacityProgram.polynomial_solve + +def output (z : Input) : NatMatrix := table (prepare z) +def outputRealizer : Realizer output := composition prepareRealizer tableRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare polynomial_table + +private lemma signedParts_toNat (z : ℤ) : + (ForestAffineProgram.signedParts z).1-(ForestAffineProgram.signedParts z).2=z.toNat := by + cases z <;> simp [ForestAffineProgram.signedParts] + +lemma cell_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : + cell (prepare (data r c b),(i.val,j.val))= + LayeredTableNetwork.decode (BoundedTableFeasibility.computedFlow r c b) i j := by + let f := EdmondsKarpAlgorithm.maxFlow (BoundedTableFeasibility.networkCapacity r c b) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.source) + (BoundedTableFeasibility.vertices m n LayeredTableNetwork.sink) + have he := flowEntry_code f + (BoundedTableFeasibility.vertices m n (LayeredTableNetwork.row i)) + (BoundedTableFeasibility.vertices m n (LayeredTableNetwork.column j)) + simp only [index_vertices,LayeredTableNetwork.row,LayeredTableNetwork.column,index] at he + have hlen : (data r c b).1.1.length=m := by simp only [data,List.length_ofFn] + dsimp only [cell,prepare] + rw [hlen,NetworkCapacityProgram.solve_code,he] + change (ForestAffineProgram.signedParts (f _ _)).1- + (ForestAffineProgram.signedParts (f _ _)).2=(f _ _).toNat + exact signedParts_toNat _ + +lemma output_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + output (data r c b)=natCode + (LayeredTableNetwork.decode (BoundedTableFeasibility.computedFlow r c b)) := by + simp only [output,table,row,rowIndices,columnIndices,prepare,data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn,natCode] + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + exact cell_code r c b i j + +/-- The computed list output encodes a table with the supplied margins and +bounds whenever the concrete feasibility test accepts. -/ +theorem output_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (ht : NetworkFeasibilityProgram.test (data r c b)=true) : + ∃ X, output (data r c b)=natCode X ∧ HasMargins X r c ∧ ∀ i j,X i j≤b i j := by + have hp : (∑ i,r i)=∑ j,c j ∧ + LayeredTableNetwork.value (BoundedTableFeasibility.computedFlow r c b)=∑ i,(r i:ℤ) := by + simpa only [NetworkFeasibilityProgram.test_eq_feasible, + BoundedTableFeasibility.feasibleTest,decide_eq_true_eq] using ht + exact ⟨_,output_code r c b,LayeredTableNetwork.decode_boundedTable r c b _ + (BoundedTableFeasibility.computedFlow_feasible hEK r c b) hp.2 hp.1⟩ + +end ContingencyTables.NetworkTableProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/OffsetCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/OffsetCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..eddc9f4427644b7607e6a830a1b3dd7c8a3cbd2f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/OffsetCountProgram.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScaledWordProgram +import Mathlib.Algebra.Order.Floor.Div + +namespace OAI + +/-! # Exact binary tabulation of the bounded offset law -/ + +namespace ContingencyTables.OffsetCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def ceilQuotient (z : ℕ×ℕ) : ℕ := (z.1+z.2-1)/z.2 + +def ceilQuotientRealizer : Realizer ceilQuotient := + composition (pair + (composition (pair (composition (pair first second) add) (constant 1)) subtract) + second) quotient + +lemma polynomial_ceilQuotient : PolynomialTime ceilQuotientRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first polynomial_second) polynomial_add) + (polynomial_constant 1)) polynomial_subtract) + polynomial_second) polynomial_quotient + +lemma ceilQuotient_eq (n d : ℕ) (hd : 0 simp⟩ + +def prepareProc : RegisterProc.Proc (K Reg) := + RegisterProc.seq (copy 0 1 (by decide)) (cons 1 2 (by decide)) +def retryProc : RegisterProc.Proc (K Reg) := + RegisterProc.seq (split 1 2 (by decide)) + (RegisterProc.seq (copy 1 0 (by decide)) (clear 1)) +def finishProc : RegisterProc.Proc (K Reg) := + RegisterProc.seq (clear 1) + (RegisterProc.seq (split 1 2 (by decide)) (clear 1)) + +lemma prepare_exec (x s : Data) : + RegisterProc.Exec prepareProc (encodeEnv (env x .nil s)) + (encodeEnv (env x .nil (.cons x s))) (5*TreeFunction.size x+8) := by + exact ((copy01 x .nil s).seq (cons12 x x s)).mono (by simp only [size_nil]; omega) + +lemma retry_exec (x y s : Data) : + RegisterProc.Exec retryProc (encodeEnv (env y .nil (.cons x s))) + (encodeEnv (env x .nil s)) (6*TreeFunction.size x+TreeFunction.size y+11) := by + exact ((split12 y .nil x s).seq ((copy10 y x s).seq (clear1 x x s))).mono + (by simp only [size_nil]; omega) + +lemma finish_exec (x y s : Data) : + RegisterProc.Exec finishProc (encodeEnv (env y (bit true) (.cons x s))) + (encodeEnv (env y .nil s)) (3*TreeFunction.size x+12) := by + exact ((clear1 y (bit true) (.cons x s)).seq + ((split12 y .nil x s).seq (clear1 y x s))).mono (by + simp only [bit,ite_true,size_cons,size_nil] + omega) + +variable {A B : Type} [Codec A] [Codec B] [Inhabited B] +variable {f : A → Experiment (Option B)} (F : OnlineTree.Realizer f) + +def instructions : Label → OnlineControl.Instr Reg Label + | .prepare => .call (OnlineProc.deterministic prepareProc) .trial + | .trial => .call F.program .decode + | .decode => .call (OnlineProc.deterministic (split 1 0 (by decide))) .test + | .test => .branch 1 .retry .finish + | .retry => .call (OnlineProc.deterministic retryProc) .prepare + | .finish => .call (OnlineProc.deterministic finishProc) .halt + | .halt => .halt + +/-- A single finite control graph, independent of the number of retries. -/ +def program : OnlineProc.Proc (K Reg) := OnlineControl.compile (instructions F) + +def output (a : A) (s : Data) : Option B → Option Label×Env Reg + | none => (some .prepare,env (TreeTyped.encode a) .nil s) + | some b => (none,env (TreeTyped.encode b) .nil s) + +def prefixExperiment (a : A) : ℕ → Experiment (Option B) + | 0 => .done none + | N+1 => (f a).bind (fun b => b.elim (prefixExperiment a N) (fun b => .done (some b))) + +def stepCost (a : A) : ℕ := F.cost a+12*TreeFunction.size (TreeTyped.encode a)+TreeFunction.size (TreeTyped.encode (default : B))+40 + +lemma prefix_step (a : A) (s : Data) (rest : Experiment (Option B)) + (hrest : OnlineRetryPrefix.At (instructions F) (output a s) + (some .prepare) (env (TreeTyped.encode a) .nil s) rest) : + ∃ q,OnlineRetryPrefix.At (instructions F) (output a s) + (some .prepare) (env (TreeTyped.encode a) .nil s) q ∧ + (∀ g : Option B → ℚ,q.mean g= + ((f a).bind (fun b => b.elim rest (fun b => .done (some b)))).mean g) ∧ + q.cost ≤ rest.cost+stepCost F a := by + classical + let M:=instructions F + let out : Option B → Option Label×Env Reg := output a s + obtain ⟨u,hu,hum,huc⟩:=F.correct a (.cons (TreeTyped.encode a) s) + have next (b : Option B) : ∃ q, + OnlineRetryPrefix.At M out (some .decode) + (env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode a) s)) q ∧ + (∀ g : Option B → ℚ,q.mean g=(b.elim rest (fun b => .done (some b))).mean g) ∧ + q.cost ≤ rest.cost+6*TreeFunction.size (TreeTyped.encode a)+TreeFunction.size (TreeTyped.encode (default : B))+27 := by + cases b with + | none => + obtain ⟨v,hv,hvm,hvc⟩:=OnlineRetryPrefix.deterministicCall M out .retry .prepare + retryProc rfl _ _ _ (retry_exec (TreeTyped.encode a) (TreeTyped.encode (default : B)) s) rest hrest + have ht:=OnlineRetryPrefix.nilBranch M out .test .retry .finish 1 rfl + (env (TreeTyped.encode (default : B)) (bit false) (.cons (TreeTyped.encode a) s)) rfl v hv + obtain ⟨q,hq,hqm,hqc⟩:=OnlineRetryPrefix.deterministicCall M out .decode .test + (split 1 0 (by decide)) rfl _ _ _ + (split10 (bit false) (TreeTyped.encode (default : B)) .nil (.cons (TreeTyped.encode a) s)) + (.delay 1 v) ht + refine ⟨q,hq,?_,?_⟩ + · intro g + exact (hqm g).trans (hvm g) + · simp only [Experiment.cost,bit,Bool.false_eq_true,ite_false,size_nil] at hqc + omega + | some b => + have hh:=OnlineRetryPrefix.halt M out .halt rfl (some b) rfl + obtain ⟨v,hv,hvm,hvc⟩:=OnlineRetryPrefix.deterministicCall M out .finish .halt + finishProc rfl _ _ _ (finish_exec (TreeTyped.encode a) (TreeTyped.encode b) s) + (.delay 1 (.done (some b))) hh + have ht:=OnlineRetryPrefix.consBranch M out .test .retry .finish 1 rfl + (env (TreeTyped.encode b) (bit true) (.cons (TreeTyped.encode a) s)) .nil .nil rfl v hv + obtain ⟨q,hq,hqm,hqc⟩:=OnlineRetryPrefix.deterministicCall M out .decode .test + (split 1 0 (by decide)) rfl _ _ _ + (split10 (bit true) (TreeTyped.encode b) .nil (.cons (TreeTyped.encode a) s)) (.delay 1 v) ht + refine ⟨q,hq,?_,?_⟩ + · intro g + exact (hqm g).trans (hvm g) + · simp only [Experiment.cost,bit,ite_true,size_cons,size_nil] at hqc hvc + omega + choose v hv hvm hvc using next + have ht:=OnlineRetryPrefix.call M out .trial .decode F.program rfl + (env (TreeTyped.encode a) .nil (.cons (TreeTyped.encode a) s)) + (fun b => env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode a) s)) u hu v hv + obtain ⟨q,hq,hqm,hqc⟩:=OnlineRetryPrefix.deterministicCall M out .prepare .trial + prepareProc rfl _ _ _ (prepare_exec (TreeTyped.encode a) s) (.delay 1 (u.bind v)) ht + refine ⟨q,hq,?_,?_⟩ + · intro g + rw [hqm,Experiment.mean,Experiment.mean_bind] + simp_rw [hvm] + rw [Experiment.mean_bind] + exact hum _ + · have hb:=Experiment.cost_bind_le u v + (rest.cost+6*TreeFunction.size (TreeTyped.encode a)+TreeFunction.size (TreeTyped.encode (default : B))+27) hvc + simp only [Experiment.cost] at hqc + unfold stepCost + omega + +/-- All finite prefix laws belong to the same fixed looping program. +Failure leaves the original input at the live retry entry. -/ +theorem prefix_correct (a : A) (s : Data) (N : ℕ) : + ∃ q,OnlineRetryPrefix.At (instructions F) (output a s) + (some .prepare) (env (TreeTyped.encode a) .nil s) q ∧ + (∀ g : Option B → ℚ,q.mean g=(prefixExperiment (f := f) a N).mean g) ∧ + q.cost ≤ N*stepCost F a := by + induction N with + | zero => exact ⟨.done none,.done none,fun _ => rfl,by simp [Experiment.cost]⟩ + | succ N ih => + obtain ⟨p,hp,hpm,hpc⟩:=ih + obtain ⟨q,hq,hqm,hqc⟩:=prefix_step F a s p hp + refine ⟨q,hq,?_,?_⟩ + · intro g + rw [hqm,prefixExperiment,Experiment.mean_bind,Experiment.mean_bind] + congr 1 + funext b + cases b <;> simp only [Option.elim_none,Option.elim_some,hpm] + · rw [Nat.succ_mul] + omega + +/-- The finite prefixes also execute on the actual compiled tape machine. +The failed endpoint still has a live control state. -/ +theorem physical_prefix (a : A) (s : Data) (N H : ℕ) + (hH : StackCost.StackBound (OnlineTree.initial (program F) (TreeTyped.encode a) s).stk H) : + ∃ q,PhysicalPost.Implements (OnlineStack.table (program F).code (program F).coin) + (fun b => OnlineStack.cfg (OnlineControl.cfg (instructions F) + (output a s b).1 (output a s b).2)) + (OnlineStack.cfg (OnlineTree.initial (program F) (TreeTyped.encode a) s)) q ∧ + (∀ g : Option B → ℚ,q.mean g=(prefixExperiment (f := f) a N).mean g) ∧ + q.cost ≤ (N*stepCost F a)* + OnlineStack.Executes.factor (program F).code H (N*stepCost F a) := by + obtain ⟨p,hp,hpm,hpc⟩:=prefix_correct F a s N + have hp' : Executes (program F).code (program F).coin + (fun b => OnlineControl.cfg (instructions F) (output a s b).1 (output a s b).2) + (OnlineTree.initial (program F) (TreeTyped.encode a) s) p := hp + obtain ⟨q,hq,hqm,hqc⟩:=hp'.compile H hH + refine ⟨q,hq,fun g => (hqm g).trans (hpm g),?_⟩ + exact hqc.trans (Nat.mul_le_mul hpc + (OnlineStack.Executes.factor_mono H H p.cost (N*stepCost F a) le_rfl hpc)) + +end ContingencyTables.OnlineIntegerRetry + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlinePartialCall.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlinePartialCall.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb0468ab229ee9f7626341ab9c1b680b1cdd8df0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlinePartialCall.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.ContingencyTables.Machines.OnlineRetryPrefix + +namespace OAI + +/-! # Calling the actual retry loop without pretending it has halted -/ + +namespace ContingencyTables.OnlinePartialCall +open MatchingFPRAS MatchingFPRAS.TreeData +open MatchingFPRAS.TreeMachine (Env K encodeEnv) +open MatchingFPRAS.OnlineStack MatchingFPRAS.OnlineControl +open MatchingFPRAS.PhysicalStream Turing + +variable {R Λ α : Type} [DecidableEq R] + +def embed (M : Λ → Instr R Λ) (l : Λ) : + (procedure (M l)).Label → Label M := fun u => .inr ⟨l,u⟩ + +def callCfg (M : Λ → Instr R Λ) (l : Λ) + (c : TM2.Cfg (fun _ : K R => Bool) (procedure (M l)).Label RegisterProc.Store) := + StackComposition.mapCfg (embed M l) ((successor (M l)).map Sum.inl) c + +/-- A finite prefix of a called procedure can end at a live internal label. +Only actual halts return to the continuation label. -/ +theorem partial_call (M : Λ → Instr R Λ) (l : Λ) + (hcall : ∃ P next, M l = .call P next) (E : Env R) + (out : α → TM2.Cfg (fun _ : K R => Bool) (procedure (M l)).Label RegisterProc.Store) + (p : Experiment α) + (hp : Executes (procedure (M l)).code (procedure (M l)).coin out + ⟨some default,none,encodeEnv E⟩ p) : + Executes (code M) (coins M) (fun a => callCfg M l (out a)) + (OnlineControl.cfg M (some l) E) (.delay 1 p) := by + have hh := hp.relabel (code M) (coins M) (embed M l) + ((successor (M l)).map Sum.inl) (fun _ => rfl) (fun _ => rfl) + obtain ⟨P,next,h⟩ := hcall + apply Executes.step _ _ _ _ rfl + simpa only [OnlineControl.cfg,code,h,TM2.stepAux,callCfg,StackComposition.mapCfg_some,embed] using hh + +abbrev Config (M : Λ → Instr R Λ) := + TM2.Cfg (fun _ : K R => Bool) (Label M) RegisterProc.Store + +def At (M : Λ → Instr R Λ) (out : α → Config M) + (l : Option Λ) (E : Env R) (p : Experiment α) : Prop := + Executes (code M) (coins M) out (OnlineControl.cfg M l E) p + +lemma halt (M : Λ → Instr R Λ) (out : α → Config M) + (l : Λ) (h : M l=.halt) (a : α) (E : Env R) (ha : out a=OnlineControl.cfg M none E) : + At M out (some l) E (.delay 1 (.done a)) := by + apply Executes.step _ _ _ _ rfl + simp only [code,h,TM2.stepAux] + change Executes (code M) (coins M) out (OnlineControl.cfg M none E) (.done a) + rw [←ha] + exact .done a + +lemma nilBranch (M : Λ → Instr R Λ) (out : α → Config M) + (l a b : Λ) (i : R) (h : M l=.branch i a b) + (E : Env R) (hi : E i=.nil) (p : Experiment α) + (hp : At M out (some a) E p) : At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons, + Option.getD_some,Bool.cond_false,OnlineControl.cfg,Option.map_some] using hp + +lemma consBranch (M : Λ → Instr R Λ) (out : α → Config M) + (l a b : Λ) (i : R) (h : M l=.branch i a b) + (E : Env R) (x y : Data) (hi : E i=.cons x y) (p : Experiment α) + (hp : At M out (some b) E p) : At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons, + Option.getD_some,Bool.cond_true,OnlineControl.cfg,Option.map_some] using hp + +lemma call {β : Type} (M : Λ → Instr R Λ) (out : α → Config M) + (l next : Λ) (P : OnlineProc.Proc (K R)) (h : M l=.call P next) + (E : Env R) (F : β → Env R) (q : Experiment β) + (hq : Executes P.code P.coin (fun b => ⟨none,none,encodeEnv (F b)⟩) + ⟨some default,none,encodeEnv E⟩ q) + (p : β → Experiment α) (hp : ∀ b,At M out (some next) (F b) (p b)) : + At M out (some l) E (.delay 1 (q.bind p)) := by + have hq' : Executes (procedure (M l)).code (procedure (M l)).coin + (fun b => ⟨none,none,encodeEnv (F b)⟩) ⟨some default,none,encodeEnv E⟩ q := by + rw [show procedure (M l)=P by rw [h]; rfl] + exact hq + have hh:=hq'.relabel (code M) (coins M) (fun u => Sum.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) (fun _ => rfl) (fun _ => rfl) + apply Executes.step _ _ _ _ rfl + have hb:=hh.bind p out (fun b => by + simpa only [At,OnlineControl.cfg,StackComposition.mapCfg_none,h,successor,Option.map_some] using hp b) + simpa only [code,h,TM2.stepAux,StackComposition.mapCfg_some] using hb + +lemma deterministicCall (M : Λ → Instr R Λ) (out : α → Config M) + (l next : Λ) (P : RegisterProc.Proc (K R)) + (h : M l=.call (OnlineProc.deterministic P) next) + (E F : Env R) (n : ℕ) (he : RegisterProc.Exec P (encodeEnv E) (encodeEnv F) n) + (p : Experiment α) (hp : At M out (some next) F p) : + ∃ q,At M out (some l) E q ∧ (∀ f : α → ℚ,q.mean f=p.mean f) ∧ + q.cost ≤ n+1+p.cost := by + obtain ⟨k,hk,he⟩:=he + obtain ⟨r,hr,hm,hc⟩:=Executes.of_run P.code k _ _ _ he + refine ⟨.delay 1 (r.bind (fun _ => p)), + call M out l next (OnlineProc.deterministic P) h E (fun _ : Unit => F) + r hr (fun _ => p) (fun _ => hp),?_,?_⟩ + · intro f + simpa only [Experiment.mean,Experiment.mean_bind] using hm (fun _ => p.mean f) + · have hh:=Experiment.cost_bind_le r (fun _ => p) p.cost (fun _ => le_rfl) + simp only [Experiment.cost] + omega + +end ContingencyTables.OnlinePartialCall + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryPrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..41591cf42a79b0281ad5c4b4bcc44a16d4c74d69 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryPrefix.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.MatchingCount.Machines.OnlineControl + +namespace OAI + +/-! # Finite execution prefixes of the unbounded exact-rejection loop -/ + +namespace ContingencyTables.OnlineRetryPrefix +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.PhysicalStream +open MatchingFPRAS.TreeMachine (Env K encodeEnv) +open MatchingFPRAS.RegisterProc MatchingFPRAS.OnlineStack +open MatchingFPRAS.OnlineControl Turing + +variable {R Λ α : Type} [DecidableEq R] + +/-- A failed finite prefix ends at the live retry label, while a successful +prefix ends in the machine's halted configuration. -/ +def At (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l : Option Λ) (E : Env R) (p : Experiment α) : Prop := + Executes (code M) (coins M) (fun a => OnlineControl.cfg M (out a).1 (out a).2) (OnlineControl.cfg M l E) p + +lemma done (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) (a : α) : + At M out (out a).1 (out a).2 (.done a) := .done a + +lemma halt (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l : Λ) (h : M l=.halt) (a : α) (ha : (out a).1=none) : + At M out (some l) (out a).2 (.delay 1 (.done a)) := by + apply Executes.step _ _ _ _ rfl + have hd:=done M out a + simpa only [At,code,h,TM2.stepAux,OnlineControl.cfg,ha,Option.map_none] using hd + +lemma go (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l k : Λ) (h : M l=.go k) (E : Env R) (p : Experiment α) + (hp : At M out (some k) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,OnlineControl.cfg,Option.map_some] using hp + +lemma nilBranch (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l a b : Λ) (i : R) (h : M l=.branch i a b) + (E : Env R) (hi : E i=.nil) (p : Experiment α) + (hp : At M out (some a) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons, + Option.getD_some,Bool.cond_false,OnlineControl.cfg,Option.map_some] using hp + +lemma consBranch (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l a b : Λ) (i : R) (h : M l=.branch i a b) + (E : Env R) (x y : Data) (hi : E i=.cons x y) (p : Experiment α) + (hp : At M out (some b) E p) : + At M out (some l) E (.delay 1 p) := by + apply Executes.step _ _ _ _ rfl + simpa only [At,code,h,TM2.stepAux,encodeEnv,hi,encode,List.head?_cons, + Option.getD_some,Bool.cond_true,OnlineControl.cfg,Option.map_some] using hp + +lemma call {β : Type} (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l next : Λ) (P : OnlineProc.Proc (K R)) (h : M l=.call P next) + (E : Env R) (F : β → Env R) (q : Experiment β) + (hq : Executes P.code P.coin (fun b => ⟨none,none,encodeEnv (F b)⟩) + ⟨some default,none,encodeEnv E⟩ q) + (p : β → Experiment α) (hp : ∀ b,At M out (some next) (F b) (p b)) : + At M out (some l) E (.delay 1 (q.bind p)) := by + have hq' : Executes (procedure (M l)).code (procedure (M l)).coin + (fun b => ⟨none,none,encodeEnv (F b)⟩) ⟨some default,none,encodeEnv E⟩ q := by + rw [show procedure (M l)=P by rw [h]; rfl] + exact hq + have hh:=hq'.relabel (code M) (coins M) (fun u => Sum.inr ⟨l,u⟩) + ((successor (M l)).map Sum.inl) (fun _ => rfl) (fun _ => rfl) + apply Executes.step _ _ _ _ rfl + have hb:=hh.bind p (fun a => OnlineControl.cfg M (out a).1 (out a).2) (fun b => by + simpa only [At,OnlineControl.cfg,StackComposition.mapCfg_none,h,successor,Option.map_some] using hp b) + simpa only [code,h,TM2.stepAux,StackComposition.mapCfg_some] using hb + +lemma deterministicCall (M : Λ → Instr R Λ) (out : α → Option Λ×Env R) + (l next : Λ) (P : RegisterProc.Proc (K R)) + (h : M l=.call (OnlineProc.deterministic P) next) + (E F : Env R) (n : ℕ) (he : RegisterProc.Exec P (encodeEnv E) (encodeEnv F) n) + (p : Experiment α) (hp : At M out (some next) F p) : + ∃ q,At M out (some l) E q ∧ (∀ f : α → ℚ,q.mean f=p.mean f) ∧ + q.cost ≤ n+1+p.cost := by + obtain ⟨k,hk,he⟩:=he + obtain ⟨r,hr,hm,hc⟩:=Executes.of_run P.code k _ _ _ he + refine ⟨.delay 1 (r.bind (fun _ => p)), + call M out l next (OnlineProc.deterministic P) h E (fun _ : Unit => F) + r hr (fun _ => p) (fun _ => hp),?_,?_⟩ + · intro f + simpa only [Experiment.mean,Experiment.mean_bind] using hm (fun _ => p.mean f) + · have hh:=Experiment.cost_bind_le r (fun _ => p) p.cost (fun _ => le_rfl) + simp only [Experiment.cost] + omega + +end ContingencyTables.OnlineRetryPrefix + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..5269f378cdbf6b231cee25d13bc741625e21f488 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/OnlineRetryRuntime.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRetryTail + +namespace OAI + +/-! # Expected physical time of the implemented online rejection loop -/ + +namespace ContingencyTables.OnlineRetryRuntime +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost + +variable {A B : Type} [TreeTyped.Codec A] [TreeTyped.Codec B] [Inhabited B] +variable {f : A → Experiment (Option B)} (F : OnlineTree.Realizer f) + +noncomputable def machineTable := + OnlineStack.table (OnlineIntegerRetry.program F).code (OnlineIntegerRetry.program F).coin + +noncomputable def initialCfg (a : A) (s : TreeData.Data) := + OnlineStack.cfg (OnlineTree.initial (OnlineIntegerRetry.program F) (TreeTyped.encode a) s) + +noncomputable def outputCfg (a : A) (s : TreeData.Data) (b : Option B) := + OnlineStack.cfg (OnlineControl.cfg (OnlineIntegerRetry.instructions F) + (OnlineIntegerRetry.output a s b).1 (OnlineIntegerRetry.output a s b).2) + +noncomputable def attemptBound (a : A) (H : ℕ) : ℕ := + OnlineIntegerRetry.stepCost F a * + OnlineStack.Executes.factor (OnlineIntegerRetry.program F).code H + (OnlineIntegerRetry.stepCost F a) + 1 + +lemma output_halted (a : A) (s : TreeData.Data) (b : B) : + (outputCfg F a s (some b)).state=none := rfl + +/-- This statement concerns the fixed physical transition table of the +online loop, not only the abstract number of rejection attempts. -/ +theorem expected_time (a : A) (s : TreeData.Data) (H : ℕ) + (hH : StackCost.StackBound + (OnlineTree.initial (OnlineIntegerRetry.program F) (TreeTyped.encode a) s).stk H) + (hf : ∀ N,(OnlineIntegerRetry.prefixExperiment (f := f) a N).mean + (fun b => if b=none then 1 else 0) ≤ (1/2:ℚ)^N) : + Summable (PhysicalRetryTail.tail (machineTable F) (initialCfg F a s)) ∧ + (∑' t,PhysicalRetryTail.tail (machineTable F) (initialCfg F a s) t) ≤ + 2*(attemptBound F a H:ℝ) := by + apply GeometricRuntime.expected_time_half _ (attemptBound F a H) (Nat.zero_lt_succ _) + (PhysicalRetryTail.tail_nonnegative _ _) (PhysicalRetryTail.tail_antitone _ _) + intro N + obtain ⟨q,hq,hqm,hqc⟩:=PhysicalRetryIteration.linear_physical_prefix F a s H hH N + have hc : q.cost ≤ N*attemptBound F a H := + hqc.trans (Nat.mul_le_mul_left N (Nat.le_add_right _ _)) + have hb:=PhysicalRetryTail.tail_le_failure (machineTable F) (outputCfg F a s) + (initialCfg F a s) q hq (output_halted F a s) _ hc + have hp : (q.mean (fun b => if b=none then 1 else 0):ℝ) ≤ (1/2:ℝ)^N := by + rw [hqm] + have h := (Rat.cast_le (K := ℝ)).mpr (hf N) + norm_num only [Rat.cast_pow,Rat.cast_div,Rat.cast_one,Rat.cast_ofNat] at h + exact h + exact hb.trans hp + +end ContingencyTables.OnlineRetryRuntime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PackedMatrixInjective.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PackedMatrixInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..f88a0c8c8f6febb922a11fe32e902d81a328f181 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PackedMatrixInjective.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram +import OAI.Combinatorics.ContingencyTables.Machines.MatrixEncoding +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicMachine + +namespace OAI + +/-! # Packed physical output still identifies its contingency table -/ + +namespace ContingencyTables.PackedMatrixInjective +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing + +lemma deterministic_unique (P : Program) (input X Y : Tape Symbol) (n m : ℕ) + (hX : P.Realizes input (.done X) n) (hY : P.Realizes input (.done Y) m) : X=Y := by + obtain ⟨p,hp,hpm,_⟩ := hX + obtain ⟨q,hq,hqm,_⟩ := hY + have ha : p.All (fun T => T=X) := Experiment.all_of_mean_eq hpm _ rfl + have hb : q.All (fun T => T=Y) := Experiment.all_of_mean_eq hqm _ rfl + have he := hp.padded_execution (fun _ => rfl) (p.cost+q.cost) (Nat.le_add_right _ _) (fun _ => false) + have hf := hq.padded_execution (fun _ => rfl) (p.cost+q.cost) (Nat.le_add_left _ _) (fun _ => false) + rw [Experiment.all_run p _ ha] at he + rw [Experiment.all_run q _ hb] at hf + exact congrArg Cfg.tape (he.symm.trans hf) + +lemma table_injective {m n : ℕ} {r : Fin m → ℕ} {c : Fin n → ℕ} (X Y : Table r c) + (h : Tape.mk₁ (TreePost.packed (GreedyFeasibleTable.printMatrix (DensePrograms.matrixCode X.val)))= + Tape.mk₁ (TreePost.packed (GreedyFeasibleTable.printMatrix (DensePrograms.matrixCode Y.val)))) : X=Y := by + have hx := LiteralProgram.post_realizes (GreedyFeasibleTable.printMatrix (DensePrograms.matrixCode X.val)) + (ProfilePrograms.printMatrix_alphabet _) + have hy := LiteralProgram.post_realizes (GreedyFeasibleTable.printMatrix (DensePrograms.matrixCode Y.val)) + (ProfilePrograms.printMatrix_alphabet _) + rw [←h] at hy + have ht := deterministic_unique LiteralProgram.post _ _ _ _ _ hx hy + have he := congrArg Tape.right₀ ht + simp only [Tape.mk₁,Tape.mk₂,Tape.mk'_right₀,DensePrograms.matrixCode,GreedyFeasibleTable.printMatrix_ofFn] at he + exact Subtype.ext (Algorithms.blankMatrix_injective X.val Y.val he) + +end ContingencyTables.PackedMatrixInjective + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedCatalogProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedCatalogProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..35237087369262e5957a0038dd59ecad9d6af938 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedCatalogProgram.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CanonicalInitialEncoding + +namespace OAI + +/-! # Computing paired-coordinate metadata from a binary profile + +Consecutive coordinates are paired by the bounded list scan +(0,1),(2,3),.... This is the exact metadata of the canonical paired-label +order, rather than a catalog supplied as an external oracle. +-/ + +namespace ContingencyTables.PairedCatalogProgram + +open MatchingFPRAS.TreeTyped ProfilePrograms + +def indexPair (i : ℕ) : ℕ×ℕ := (2*i,2*i+1) + +def twiceRealizer : Realizer (fun i : ℕ => 2*i) := + composition (f := fun i : ℕ => (2,i)) (g := fun z : ℕ×ℕ => z.1*z.2) + (pair (constant 2) identity) multiply + +def indexPairRealizer : Realizer indexPair := + pair twiceRealizer + (composition (f := fun i : ℕ => (2*i,1)) (g := fun z : ℕ×ℕ => z.1+z.2) + (pair twiceRealizer (constant 1)) add) + +lemma polynomial_indexPair : PolynomialTime indexPairRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_identity) + polynomial_multiply) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_identity) + polynomial_multiply) (polynomial_constant 1)) polynomial_add) + +def indicesRealizer : Realizer (fun xs : List ℕ => List.range (xs.length/2)) := + composition (composition (pair listLength (constant 2)) quotient) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_pair polynomial_listLength (polynomial_constant 2)) + polynomial_quotient) Polynomial.X + intro xs + simpa only [Function.comp_apply,Polynomial.eval_X] using + (Nat.div_le_self xs.length 2).trans (list_length_le_weight xs) + +def catalog (xs : List ℕ) : List (ℕ×ℕ) := (List.range (xs.length/2)).map indexPair + +def catalogRealizer : Realizer catalog := composition indicesRealizer (map indexPairRealizer) + +theorem polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition polynomial_indices (polynomial_map polynomial_indexPair) + +def pairList {α : Type*} : List α → List (α×Bool) + | [] => [] + | a::xs => (a,false)::(a,true)::pairList xs + +lemma pairList_length {α : Type*} (xs : List α) : (pairList xs).length=2*xs.length := by + induction xs with + | nil => rfl + | cons a xs ih => simp only [pairList,List.length_cons,ih]; omega + +lemma pairList_product {α : Type*} (xs : List α) : pairList xs=xs.product [false,true] := by + induction xs with + | nil => rfl + | cons a xs ih => + change (a,false)::(a,true)::pairList xs=(a,false)::(a,true)::xs.product [false,true] + rw [ih] + +lemma pairList_get_even {α : Type*} (xs : List α) (i : ℕ) (hi : i simp at hi + | cons a xs ih => + cases i with + | zero => rfl + | succ i => + simpa only [pairList,Nat.mul_succ,List.getElem_cons_succ] using + ih i (Nat.lt_of_succ_lt_succ hi) + +lemma pairList_get_odd {α : Type*} (xs : List α) (i : ℕ) (hi : i simp at hi + | cons a xs ih => + cases i with + | zero => rfl + | succ i => + simpa only [pairList,Nat.mul_succ,List.getElem_cons_succ,Nat.add_assoc] using + ih i (Nat.lt_of_succ_lt_succ hi) + +noncomputable section +open CanonicalInitialEncoding InitialTransversals CompanionArithmeticProposal +open scoped Classical +variable {q : ℕ} (b : Fin q → ℕ) + +def labelOrder : Fin (copyOrder b).length ≃ Copy b := + List.Nodup.getEquivOfForallMemList (copyOrder b) (copyOrder_nodup b) (copyOrder_mem b) + +lemma coordinate_false (i : Fin (copyOrder b).length) : + (CanonicalInitialEncoding.coordinateEquiv b (labelOrder b i,false)).val=2*i.val := by + have hl : (pairOrder b).length=2*(copyOrder b).length := by + change ((copyOrder b).product [false,true]).length=2*(copyOrder b).length + rw [←pairList_product] + exact pairList_length _ + let k : Fin (pairOrder b).length := ⟨2*i.val,by rw [hl]; omega⟩ + have hk : (CanonicalInitialEncoding.coordinateEquiv b).symm k=(labelOrder b i,false) := by + change (pairOrder b)[k.val]=((copyOrder b)[i.val],false) + simpa only [pairOrder,←pairList_product,k] using pairList_get_even (copyOrder b) i.val i.isLt + have he := congrArg (fun a => (CanonicalInitialEncoding.coordinateEquiv b a).val) hk + simpa only [Equiv.apply_symm_apply,k] using he.symm + +lemma coordinate_true (i : Fin (copyOrder b).length) : + (CanonicalInitialEncoding.coordinateEquiv b (labelOrder b i,true)).val=2*i.val+1 := by + have hl : (pairOrder b).length=2*(copyOrder b).length := by + change ((copyOrder b).product [false,true]).length=2*(copyOrder b).length + rw [←pairList_product] + exact pairList_length _ + let k : Fin (pairOrder b).length := ⟨2*i.val+1,by rw [hl]; omega⟩ + have hk : (CanonicalInitialEncoding.coordinateEquiv b).symm k=(labelOrder b i,true) := by + change (pairOrder b)[k.val]=((copyOrder b)[i.val],true) + simpa only [pairOrder,←pairList_product,k] using pairList_get_odd (copyOrder b) i.val i.isLt + have he := congrArg (fun a => (CanonicalInitialEncoding.coordinateEquiv b a).val) hk + simpa only [Equiv.apply_symm_apply,k] using he.symm + +/-- Every state encoded in the canonical order has exactly the pair +catalog computed by the polynomial consecutive-coordinate scan. -/ +theorem catalog_encode (S : Set (Copy b×Bool)) : + catalog (encodeSet (CanonicalInitialEncoding.coordinateEquiv b) S)= + List.ofFn (fun i : Fin (copyOrder b).length => + ((CanonicalInitialEncoding.coordinateEquiv b (labelOrder b i,false)).val, + (CanonicalInitialEncoding.coordinateEquiv b (labelOrder b i,true)).val)) := by + have hl : (pairOrder b).length=2*(copyOrder b).length := by + change ((copyOrder b).product [false,true]).length=2*(copyOrder b).length + rw [←pairList_product] + exact pairList_length _ + simp only [catalog,encodeSet,List.length_ofFn,hl] + rw [Nat.mul_div_cancel_left _ (by decide : 0<2)] + apply List.ext_getElem + · simp + · intro i hi hj + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,indexPair, + coordinate_false,coordinate_true] + +end +end ContingencyTables.PairedCatalogProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedDemandProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedDemandProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9ba25cb1c6637c2fe2d7bb590dedd80d1e7d209 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedDemandProgram.lean @@ -0,0 +1,213 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PairedProfileSemantics +import OAI.Combinatorics.ContingencyTables.Machines.SparseViewMatrixProgram +import OAI.Combinatorics.ContingencyTables.Machines.MatrixSubtractProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWalkProgram + +namespace OAI + +/-! # Replacing the oracle demand by the current encoded paired state + +Only the retained-cell catalog and the supplied state are scanned. The +large cells receive zero in each sparse view and hence retain their full +capacity in the complemented column demand. +-/ + +namespace ContingencyTables.PairedDemandProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev Input := RootedDemandProgram.Input × List ℕ + +def cellInput (d : RootedForestCatalog.Data) : CompanionCellCatalog.Input := + ((d.1.2,d.2),d.1.1.2) +def cellInputRealizer : Realizer cellInput := + pair (pair (composition first second) second) (composition (composition first first) second) +lemma polynomial_cellInput : PolynomialTime cellInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + +def cells (z : Input) : CompanionCellCatalog.Input := cellInput z.1.1 +def cellsRealizer : Realizer cells := + composition (f := fun z : Input => z.1.1) (g := cellInput) + (composition first first) cellInputRealizer +lemma polynomial_cells : PolynomialTime cellsRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_cellInput + +def counts (z : Input) : List (ℕ × ℕ) := + PairedProfileProgram.profileRows (CompanionCellCatalog.capacities (cells z),z.2) +def countsRealizer : Realizer counts := + composition (f := fun z : Input => (CompanionCellCatalog.capacities (cells z),z.2)) + (g := PairedProfileProgram.profileRows) + (pair (composition (f := cells) (g := CompanionCellCatalog.capacities) + cellsRealizer CompanionCellCatalog.capacitiesRealizer) second) + PairedProfileProgram.profileRowsRealizer +lemma polynomial_counts : PolynomialTime countsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_cells CompanionCellCatalog.polynomial_capacities) + polynomial_second) PairedProfileProgram.polynomial_profileRows + +def sideEntry (z : Bool × (ℕ × ℕ)) : ℕ := if z.1 then z.2.2 else z.2.1 +def sideEntryRealizer : Realizer sideEntry := + choose first (composition second second) (composition second first) +lemma polynomial_sideEntry : PolynomialTime sideEntryRealizer := + polynomial_choose polynomial_first + (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_second polynomial_first) + +def values (z : Input × Bool) : List ℕ := (counts z.1).map (fun p => sideEntry (z.2,p)) +def valuesRealizer : Realizer values := + composition (f := fun z : Input × Bool => (z.2,counts z.1)) + (g := fun p : Bool × List (ℕ × ℕ) => p.2.map (fun a => sideEntry (p.1,a))) + (pair second (composition (f := Prod.fst) (g := counts) first countsRealizer)) + (mapWith sideEntryRealizer) +lemma polynomial_values : PolynomialTime valuesRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_counts)) + (polynomial_mapWith polynomial_sideEntry) + +def viewInput (z : Input × Bool) : SparseViewMatrixProgram.Input := + (z.1.1.1.1.2,(CompanionCellCatalog.catalog (cells z.1),values z)) +def viewInputRealizer : Realizer viewInput := + pair (composition (composition (composition (composition first first) first) first) second) + (pair (composition (f := fun z : Input × Bool => cells z.1) + (g := CompanionCellCatalog.catalog) + (composition (f := Prod.fst) (g := cells) first cellsRealizer) + CompanionCellCatalog.catalogRealizer) valuesRealizer) +lemma polynomial_viewInput : PolynomialTime viewInputRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_first) polynomial_second) + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_cells) + CompanionCellCatalog.polynomial_catalog) polynomial_values) + +def viewMatrix (z : Input × Bool) : MatrixCode := SparseViewMatrixProgram.matrix (viewInput z) +def viewMatrixRealizer : Realizer viewMatrix := + composition (f := viewInput) (g := SparseViewMatrixProgram.matrix) + viewInputRealizer SparseViewMatrixProgram.matrixRealizer +lemma polynomial_viewMatrix : PolynomialTime viewMatrixRealizer := + polynomial_composition polynomial_viewInput SparseViewMatrixProgram.polynomial_matrix + +def complement (z : Input) : MatrixCode := + MatrixSubtractProgram.matrix (z.1.1.2,viewMatrix (z,true)) +def complementRealizer : Realizer complement := + composition (f := fun z : Input => (z.1.1.2,viewMatrix (z,true))) + (g := MatrixSubtractProgram.matrix) + (pair (composition (composition first first) second) + (composition (f := fun z : Input => (z,true)) (g := viewMatrix) + (pair identity (constant true)) viewMatrixRealizer)) MatrixSubtractProgram.matrixRealizer +lemma polynomial_complement : PolynomialTime complementRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant true)) + polynomial_viewMatrix)) MatrixSubtractProgram.polynomial_matrix + +def output (z : Input) : RootedDemandProgram.Input := + (z.1.1,(z.1.2.1,(viewMatrix (z,false),complement z))) +def outputRealizer : Realizer output := + pair (composition first first) + (pair (composition (composition first second) first) + (pair (composition (f := fun z : Input => (z,false)) (g := viewMatrix) + (pair identity (constant false)) viewMatrixRealizer) complementRealizer)) +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) + (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_constant false)) polynomial_viewMatrix) + polynomial_complement)) + +noncomputable section +open CompanionFactorialApplication CompanionArithmeticProposal PairedProfileSemantics +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles SmallGraphProfiles + +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +lemma cells_data (x q : Fin m → Fin n → ℕ) (code : List ℕ) : + cells (RootedDemandProgram.data A x q,code)=CompanionCellCatalog.input A := rfl + +lemma catalog_eq : + CompanionCellCatalog.catalog (CompanionCellCatalog.input A)= + cellCatalog A.small (CompanionCellCatalog.cellEquiv A) := by + rw [cellCatalog] + symm + calc + List.ofFn (fun i => + ((CompanionCellCatalog.cellEquiv A i).val.1.val, + (CompanionCellCatalog.cellEquiv A i).val.2.val))= + List.ofFn (fun i : Fin (CompanionCellCatalog.catalog + (CompanionCellCatalog.input A)).length => + (CompanionCellCatalog.catalog (CompanionCellCatalog.input A))[i.val]) := by + apply congrArg List.ofFn + funext i + exact CompanionCellCatalog.catalogCell_coordinates A i + _=_ := List.ofFn_get _ + +lemma values_data (x q : Fin m → Fin n → ℕ) (S : Set (Labels A × Bool)) (side : Bool) : + values ((RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S),side)= + viewList A.small (CompanionCellCatalog.cellEquiv A) + (CompanionWeightOracle.profile A S) side := by + unfold values counts + rw [cells_data,CompanionCellCatalog.capacities_eq] + change (PairedProfileProgram.profileRows + (List.ofFn (CompanionComputedInitial.capacities A), + encodeSet (CompanionComputedInitial.coordinateOrder A) S)).map _=_ + rw [profileRows_physical] + simp only [List.map_ofFn,Function.comp_def,viewList,sideEntry] + cases side <;> rfl + +lemma viewMatrix_data (x q : Fin m → Fin n → ℕ) (S : Set (Labels A × Bool)) (side : Bool) : + viewMatrix ((RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S),side)= + matrixCode (smallView A.small (CompanionWeightOracle.profile A S) side) := by + let z : Input := (RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S) + have hi : viewInput (z,side)= + ((List.ofFn (fun i => (A.r i).toNat),List.ofFn (fun j => (A.c j).toNat)), + (cellCatalog A.small (CompanionCellCatalog.cellEquiv A), + viewList A.small (CompanionCellCatalog.cellEquiv A) + (CompanionWeightOracle.profile A S) side)) := by + apply Prod.ext + · rfl + · apply Prod.ext + · exact (congrArg CompanionCellCatalog.catalog (cells_data A x q _)).trans (catalog_eq A) + · exact values_data A x q S side + change SparseViewMatrixProgram.matrix (viewInput (z,side))=_ + rw [hi] + rw [SparseViewMatrixProgram.matrix_ofFn] + apply congrArg matrixCode + funext i j + exact lookupView_eq A.small (CompanionCellCatalog.cellEquiv A) + (CompanionWeightOracle.profile A S) side i j + +/-- The current code replaces both demand arrays; the old demand only +provides the immutable graph, capacities, margins and baseline. -/ +theorem output_data (x q : Fin m → Fin n → ℕ) (S : Set (Labels A × Bool)) : + output (RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S)= + RootedDemandProgram.data A + (ForestCountIdentification.smallX A.small (CompanionWeightOracle.profile A S)) + (fun i j => A.b i j- + ForestCountIdentification.smallY A.small (CompanionWeightOracle.profile A S) i j) := by + have hq : complement (RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S)= + matrixCode (fun i j => A.b i j- + smallView A.small (CompanionWeightOracle.profile A S) true i j) := by + change MatrixSubtractProgram.matrix (matrixCode A.b,viewMatrix + ((RootedDemandProgram.data A x q, + encodeSet (CompanionComputedInitial.coordinateOrder A) S),true))=_ + rw [viewMatrix_data] + exact MatrixSubtractProgram.matrix_code _ _ + unfold output + rw [viewMatrix_data,hq] + rfl + +end +end ContingencyTables.PairedDemandProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedFactorialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedFactorialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..3650ec1fa017728e6149a2912d819ef7dcfa2071 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedFactorialProgram.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PairedProfileSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FractionAggregateProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts + +namespace OAI + +/-! # The exact factorial multiplier from the encoded paired state + +Every factorial argument is bounded by the supplied code length. In a +valid code each cell block has length twice its capacity, so the computed +denominator is exactly the manuscript's capacity factorial. +-/ + +namespace ContingencyTables.PairedFactorialProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial PairedProfileProgram +open scoped BigOperators Classical + +def sideFactor (z : List ℕ × Bool) : ℕ := (sideCount z).factorial +def sideFactorRealizer : Realizer sideFactor := composition sideCountRealizer factorial +lemma polynomial_sideFactor : PolynomialTime sideFactorRealizer := by + apply polynomial_boundedFactorial polynomial_sideCount X + intro z + simpa only [eval_X] using (sideCount_le z.1 z.2).trans + ((list_length_le_weight z.1).trans (weight_fst z)) + +def pairCount (xs : List ℕ) : ℕ := xs.length/2 +def pairCountRealizer : Realizer pairCount := + composition (pair listLength (constant 2)) quotient +lemma polynomial_pairCount : PolynomialTime pairCountRealizer := + polynomial_composition (polynomial_pair polynomial_listLength (polynomial_constant 2)) + polynomial_quotient + +def denominator (xs : List ℕ) : ℕ := (pairCount xs).factorial +def denominatorRealizer : Realizer denominator := composition pairCountRealizer factorial +lemma polynomial_denominator : PolynomialTime denominatorRealizer := by + apply polynomial_boundedFactorial polynomial_pairCount X + intro xs + simpa only [eval_X,pairCount] using (Nat.div_le_self xs.length 2).trans (list_length_le_weight xs) + +def numerator (xs : List ℕ) : ℕ := sideFactor (xs,false)*sideFactor (xs,true) +def numeratorRealizer : Realizer numerator := + composition (f := fun xs : List ℕ => (sideFactor (xs,false),sideFactor (xs,true))) + (g := fun p : ℕ × ℕ => p.1*p.2) + (pair + (composition (f := fun xs : List ℕ => (xs,false)) (g := sideFactor) + (pair identity (constant false)) sideFactorRealizer) + (composition (f := fun xs : List ℕ => (xs,true)) (g := sideFactor) + (pair identity (constant true)) sideFactorRealizer)) multiply +lemma polynomial_numerator : PolynomialTime numeratorRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant false)) + polynomial_sideFactor) + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant true)) + polynomial_sideFactor)) polynomial_multiply + +def rowRatio (xs : List ℕ) : TreeFraction.Fraction := + TreeFraction.normalize (numerator xs,denominator xs) +def rowRatioRealizer : Realizer rowRatio := + composition (pair numeratorRealizer denominatorRealizer) TreeFraction.normalizeRealizer +lemma polynomial_rowRatio : PolynomialTime rowRatioRealizer := + polynomial_composition (polynomial_pair polynomial_numerator polynomial_denominator) + TreeFraction.polynomial_normalize + +def output (z : PairedProfileProgram.Input) : TreeFraction.Fraction := + FractionAggregateProgram.product ((rows z).map rowRatio) +def outputRealizer : Realizer output := + composition (composition rowsRealizer (map rowRatioRealizer)) + FractionAggregateProgram.productRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_composition polynomial_rows + (polynomial_map polynomial_rowRatio)) FractionAggregateProgram.polynomial_product + +lemma rowRatio_value (xs : List ℕ) : + TreeFraction.val (rowRatio xs)= + ((sideCount (xs,false)).factorial:ℚ)*(sideCount (xs,true)).factorial / + (xs.length/2).factorial := by + rw [rowRatio,TreeFraction.normalize_val] + simp only [TreeFraction.val,numerator,sideFactor,denominator,pairCount,Nat.cast_mul] + +noncomputable section +open PairedProfileSemantics InitialTransversals CanonicalInitialEncoding +open CompanionArithmeticProposal CompanionFactorialApplication + +variable {q : ℕ} (b : Fin q → ℕ) + +theorem output_canonical (S : Set (Copy b × Bool)) : + TreeFraction.val (output (List.ofFn b,encodeSet (coordinateEquiv b) S))= + ∏ i : Fin q, + ((∑ k : Fin (b i), if ((⟨i,k⟩ : Copy b),false) ∈ S then 1 else 0).factorial:ℚ)* + (∑ k : Fin (b i), if ((⟨i,k⟩ : Copy b),true) ∈ S then 1 else 0).factorial / + (b i).factorial := by + rw [output,FractionAggregateProgram.product_value,rows_encode] + simp only [cellRows,List.map_ofFn,List.prod_ofFn,Function.comp_apply] + apply Finset.prod_congr rfl + intro i _ + rw [rowRatio_value] + have hc := counts_cellRow b S i + have hfalse := congrArg Prod.fst hc + have htrue := congrArg Prod.snd hc + change sideCount (_,false)=_ at hfalse + change sideCount (_,true)=_ at htrue + rw [hfalse,htrue,interleave_length,List.length_ofFn, + Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +/-- The multiplier used by the executed weight oracle is the literal +factorial ratio, for every subset, not just transversal states. -/ +theorem output_physical (S : Set (Labels A × Bool)) : + TreeFraction.val (output (List.ofFn (CompanionComputedInitial.capacities A), + encodeSet (CompanionComputedInitial.coordinateOrder A) S))= + CompanionWeightOracle.factorialRatio A S := by + rw [CompanionComputedInitial.encodeSet_reindex,output_canonical] + have hp (i) (side : Bool) := + (physical_profile_reindex A S ((CompanionComputedInitial.cellOrder A).symm i) side).trans + (by rw [Equiv.apply_symm_apply,copy_viewCount]) + simp_rw [←hp] + symm + unfold CompanionWeightOracle.factorialRatio CompanionWeightOracle.factorialNumerator + CompanionWeightOracle.factorialDenominator + simp only [Nat.cast_prod,Fintype.prod_prod_type,Fintype.prod_bool,Nat.cast_mul] + rw [←Finset.prod_div_distrib] + exact Fintype.prod_equiv (CompanionComputedInitial.cellOrder A) _ _ (fun s => by + simp only [Equiv.symm_apply_apply,CompanionComputedInitial.capacities] + ring) + +end +end ContingencyTables.PairedFactorialProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedProfileProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedProfileProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c40d56c6747c78599cac0b4a0461bf163cf928bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PairedProfileProgram.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.ContingencyTables.Machines.NaturalBlockProgram +import OAI.Combinatorics.ContingencyTables.Machines.PairedCatalogProgram + +namespace OAI + +/-! # Reading the two cell counts from the actual paired code + +The block widths come from the stored capacity list. Each count scans +only supplied code entries and clips them to one, including on malformed +input. No numeric capacity controls an unbounded allocation. +-/ + +namespace ContingencyTables.PairedProfileProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +abbrev ReadInput := (List ℕ × Bool) × (ℕ × ℕ) + +def sideValue (z : ReadInput) : ℕ := + min (z.1.1.getD (if z.1.2 then z.2.2 else z.2.1) 0) 1 +def sideValueRealizer : Realizer sideValue := + composition (f := fun z : ReadInput => + (z.1.1.getD (if z.1.2 then z.2.2 else z.2.1) 0,1)) + (g := fun p : ℕ × ℕ => min p.1 p.2) + (pair (composition (pair (composition first first) + (choose (composition first second) (composition second second) + (composition second first))) (getDFast 0)) (constant 1)) minimum +lemma polynomial_sideValue : PolynomialTime sideValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_choose (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_second polynomial_first))) (polynomial_getDFast 0)) + (polynomial_constant 1)) polynomial_minimum + +def sideEntries (z : List ℕ × Bool) : List ℕ := + (PairedCatalogProgram.catalog z.1).map (fun p => sideValue (z,p)) +def sideEntriesRealizer : Realizer sideEntries := + composition (pair identity (composition first PairedCatalogProgram.catalogRealizer)) + (mapWith sideValueRealizer) +lemma polynomial_sideEntries : PolynomialTime sideEntriesRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first PairedCatalogProgram.polynomial_catalog)) + (polynomial_mapWith polynomial_sideValue) + +def sideCount (z : List ℕ × Bool) : ℕ := (sideEntries z).sum +def sideCountRealizer : Realizer sideCount := composition sideEntriesRealizer listSum +lemma polynomial_sideCount : PolynomialTime sideCountRealizer := + polynomial_composition polynomial_sideEntries polynomial_listSum + +lemma sideCount_le (xs : List ℕ) (side : Bool) : sideCount (xs,side) ≤ xs.length := by + have hs : (sideEntries (xs,side)).sum ≤ (sideEntries (xs,side)).length := by + simpa using (List.sum_le_length_nsmul (sideEntries (xs,side)) 1 (by + intro a ha + obtain ⟨p,_,rfl⟩ := List.mem_map.mp ha + exact Nat.min_le_right _ _)) + exact hs.trans (by + simp only [sideEntries,PairedCatalogProgram.catalog,List.length_map,List.length_range] + exact Nat.div_le_self _ _) + +abbrev Input := List ℕ × List ℕ + +def width (n : ℕ) : ℕ := 2*n +def widthRealizer : Realizer width := + composition (f := fun n : ℕ => (2,n)) (g := fun p : ℕ × ℕ => p.1*p.2) + (pair (constant 2) identity) multiply +lemma polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_identity) + polynomial_multiply + +def rows (z : Input) : List (List ℕ) := + NaturalBlockProgram.blocks (z.1.map width,z.2) +def rowsRealizer : Realizer rows := + composition (pair (composition first (map widthRealizer)) second) + NaturalBlockProgram.blocksRealizer +lemma polynomial_rows : PolynomialTime rowsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first (polynomial_map polynomial_width)) polynomial_second) + NaturalBlockProgram.polynomial_blocks + +def counts (xs : List ℕ) : ℕ × ℕ := (sideCount (xs,false),sideCount (xs,true)) +def countsRealizer : Realizer counts := + pair (composition (f := fun xs : List ℕ => (xs,false)) (g := sideCount) + (pair identity (constant false)) sideCountRealizer) + (composition (f := fun xs : List ℕ => (xs,true)) (g := sideCount) + (pair identity (constant true)) sideCountRealizer) +lemma polynomial_counts : PolynomialTime countsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant false)) + polynomial_sideCount) + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant true)) + polynomial_sideCount) + +def profileRows (z : Input) : List (ℕ × ℕ) := (rows z).map counts +def profileRowsRealizer : Realizer profileRows := composition rowsRealizer (map countsRealizer) +theorem polynomial_profileRows : PolynomialTime profileRowsRealizer := + polynomial_composition polynomial_rows (polynomial_map polynomial_counts) + +def interleave : List (ℕ × ℕ) → List ℕ + | [] => [] + | p :: ps => p.1 :: p.2 :: interleave ps + +lemma interleave_length (xs : List (ℕ × ℕ)) : (interleave xs).length=2*xs.length := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [interleave,List.length_cons,ih]; omega + +lemma interleave_get_even (xs : List (ℕ × ℕ)) (i : ℕ) (hi : i < xs.length) : + (interleave xs)[2*i]'(by rw [interleave_length]; omega)=xs[i].1 := by + induction xs generalizing i with + | nil => simp at hi + | cons x xs ih => + cases i with + | zero => rfl + | succ i => + simpa only [interleave,Nat.mul_succ,List.getElem_cons_succ] using + ih i (Nat.lt_of_succ_lt_succ hi) + +lemma interleave_get_odd (xs : List (ℕ × ℕ)) (i : ℕ) (hi : i < xs.length) : + (interleave xs)[2*i+1]'(by rw [interleave_length]; omega)=xs[i].2 := by + induction xs generalizing i with + | nil => simp at hi + | cons x xs ih => + cases i with + | zero => rfl + | succ i => + simpa only [interleave,Nat.mul_succ,List.getElem_cons_succ,Nat.add_assoc] using + ih i (Nat.lt_of_succ_lt_succ hi) + +lemma sideEntries_interleave (xs : List (ℕ × ℕ)) (side : Bool) : + sideEntries (interleave xs,side)= + xs.map (fun p => min (if side then p.2 else p.1) 1) := by + apply List.ext_getElem + · simp only [sideEntries,PairedCatalogProgram.catalog,List.length_map,List.length_range, + interleave_length,Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + · intro i hi _ + have hii : i < xs.length := by + simpa only [sideEntries,PairedCatalogProgram.catalog,List.length_map,List.length_range, + interleave_length,Nat.mul_div_cancel_left _ (by decide : 0 < 2)] using hi + simp only [sideEntries,PairedCatalogProgram.catalog,List.getElem_map,List.getElem_range, + sideValue,PairedCatalogProgram.indexPair] + cases side with + | false => + have hidx : 2*i < (interleave xs).length := by rw [interleave_length]; omega + simp only [Bool.false_eq_true,ite_false,List.getD_eq_getElem?_getD, + List.getElem?_eq_getElem hidx,Option.getD_some,interleave_get_even xs i hii] + | true => + have hidx : 2*i+1 < (interleave xs).length := by rw [interleave_length]; omega + simp only [ite_true,List.getD_eq_getElem?_getD, + List.getElem?_eq_getElem hidx,Option.getD_some,interleave_get_odd xs i hii] + +lemma interleave_flatMap (xs : List (ℕ × ℕ)) : + interleave xs=xs.flatMap (fun p => [p.1,p.2]) := by + induction xs with + | nil => rfl + | cons p xs ih => + change p.1 :: p.2 :: interleave xs=p.1 :: p.2 :: xs.flatMap (fun p => [p.1,p.2]) + rw [ih] + +end ContingencyTables.PairedProfileProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PowerApproximationProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PowerApproximationProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..dce88f2baa2be58399119c7db5a95c3f3c1f0680 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PowerApproximationProgram.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Machines.RoundedPowerProgram + +namespace OAI + +/-! # The executed power-of-two approximation used by the weight oracle + +Both stages are concrete binary programs: compute the rounded signed +power, then bisect using natural cross-products and shared denominators. +The two allowance lists determine the precision parameters. +-/ + +namespace ContingencyTables.PowerApproximationProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Input := SignedFloorProgram.Input×(List Bool×List Bool) + +def prepare (z : Input) : DyadicRootProgram.Input := + ((RoundedPowerProgram.output (z.1,z.2.1),z.2.1),z.2.2) +def prepareRealizer : Realizer prepare := + pair (pair + (composition (f := fun z : Input => (z.1,z.2.1)) (g := RoundedPowerProgram.output) + (pair first (composition second first)) RoundedPowerProgram.outputRealizer) + (composition second first)) (composition second second) +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) + RoundedPowerProgram.polynomial_output) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition polynomial_second polynomial_second) + +def output (z : Input) : TreeFraction.Fraction := DyadicRootProgram.output (prepare z) +def outputRealizer : Realizer output := + composition prepareRealizer DyadicRootProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare DyadicRootProgram.polynomial_output + +theorem output_value (p n d : ℕ) (degree depth : List Bool) + (hlo: -2≤((p:ℚ)-n)/d) (hhi: ((p:ℚ)-n)/d≤2) : + TreeFraction.val (output (((p,n),d),(degree,depth)))= + PowerOfTwoApproximation.approximation (((p:ℚ)-n)/d) degree.length depth.length := by + unfold output prepare + rw [DyadicRootProgram.output_value _ (RoundedPowerProgram.output_denominator_pos _), + RoundedPowerProgram.output_value p n d degree hlo hhi] + rfl + +/-- The encoded output agrees exactly with the rational value used by +the existing finite-word correction laws. -/ +theorem output_approximate (p n d : ℕ) (degree depth : List Bool) (sigma : ℚ) + (hdegree: degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth: depth.length=PowerOfTwoApproximation.depth sigma) + (hlo: -2≤((p:ℚ)-n)/d) (hhi: ((p:ℚ)-n)/d≤2) : + TreeFraction.val (output (((p,n),d),(degree,depth)))= + PowerOfTwoApproximation.approximate (((p:ℚ)-n)/d) sigma := by + rw [output_value p n d degree depth hlo hhi,hdegree,hdepth] + rfl + +theorem output_error (p n d : ℕ) (degree depth : List Bool) (sigma : ℚ) + (hdegree: degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth: depth.length=PowerOfTwoApproximation.depth sigma) + (hlo: -2≤((p:ℚ)-n)/d) (hhi: ((p:ℚ)-n)/d≤2) (hsigma: 0 (z.1,preparedGap z)) := + pair first preparedGapRealizer + let powered := composition pin BoundedPowerPrograms.powerRealizer + exact choose (composition (composition second countProposalInputRealizer) hasProposalRealizer) + powered (constant 0) + +/-- The allowance is supplied once. Enumerating a row or the whole matrix +then uses only polynomial-time operations on binary entries. -/ +theorem polynomial_preparedOffCount : PolynomialTime preparedOffCountRealizer := by + unfold preparedOffCountRealizer + exact polynomial_choose + (polynomial_composition (polynomial_composition polynomial_second polynomial_countProposalInput) + polynomial_hasProposal) + (polynomial_composition (polynomial_pair polynomial_first polynomial_preparedGap) + BoundedPowerPrograms.polynomial_power) (polynomial_constant 0) + +lemma preparedOffCount_eq (xs : List Bool) (z : CountInput) (h : xs.length=8*z.1.2^5) : + preparedOffCount (xs,z)=offCountCode z := by + unfold preparedOffCount offCountCode + simp only [BoundedPowerPrograms.power_eq,BinaryPowerPrograms.power_eq,preparedGap, + countPowerInput,h] + +lemma offCountCode_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (a b : Grid (I := Fin (m*n)) (4*d^8)) : + offCountCode ((((marginCode R,marginCode P),gridNatCode a),d),gridNatCode b)= + FiniteAcceptCounts.offCount a + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d finProdFinEquiv b- + denseExponent R P d finProdFinEquiv a) (8*d^5) b := by + rw [offCountCode_eq] + by_cases hba : b=a + · subst b + have hn : ¬Neighbor a a := fun h => neighbor_ne a a h rfl + simp [FiniteAcceptCounts.offCount,hn] + · simp only [FiniteAcceptCounts.offCount,ite_eq_right hba] + rw [axisCodeStep_count (dense_proposal_code_bound d (m*n) hq)] + split_ifs <;> simp + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedOffsetCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedOffsetCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..436f29fe0d8c8542761c9103be75eb1b2c7a0a3b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedOffsetCount.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BoundedPowerProgram +import OAI.Combinatorics.ContingencyTables.Machines.OffsetCountProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseSuccessCounts + +namespace OAI + +/-! # Binary evaluation of the offset numerator product -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary FairBits +open scoped BigOperators + +/-- A shared bit allowance, widths, actual bit lengths and offsets. -/ +abbrev PreparedOffsetData := ((List Bool×List ℕ)×List ℕ)×List ℕ + +def preparedOffsetInput (z : PreparedOffsetData×ℕ) : OffsetCountPrograms.Input := + ((z.1.1.1.2.getD z.2 0, + BoundedPowerPrograms.power (z.1.1.1.1, + z.1.1.1.1.length-z.1.1.2.getD z.2 0)),z.1.2.getD z.2 0) + +def preparedOffsetInputRealizer : Realizer preparedOffsetInput := by + let cap : Realizer (fun z : PreparedOffsetData×ℕ => z.1.1.1.1) := + composition (composition (composition first first) first) first + let widths : Realizer (fun z : PreparedOffsetData×ℕ => z.1.1.1.2) := + composition (composition (composition first first) first) second + let lengths : Realizer (fun z : PreparedOffsetData×ℕ => z.1.1.2) := + composition (composition first first) second + let offsets : Realizer (fun z : PreparedOffsetData×ℕ => z.1.2) := composition first second + let M := composition (pair widths second) (getDFast 0) + let r := composition (pair lengths second) (getDFast 0) + let beta := composition (pair offsets second) (getDFast 0) + let gap := composition (pair (composition cap listLength) r) subtract + let Q := composition (pair cap gap) BoundedPowerPrograms.powerRealizer + exact pair (pair M Q) beta + +lemma polynomial_preparedOffsetInput : PolynomialTime preparedOffsetInputRealizer := by + have hcap : PolynomialTime (composition (composition (composition + (first (A := PreparedOffsetData) (B := ℕ)) first) first) first) := by tree_poly + have hw : PolynomialTime (composition (composition (composition + (first (A := PreparedOffsetData) (B := ℕ)) first) first) second) := by tree_poly + have hr : PolynomialTime (composition (composition + (first (A := PreparedOffsetData) (B := ℕ)) first) second) := by tree_poly + have ho : PolynomialTime (composition + (first (A := PreparedOffsetData) (B := ℕ)) second) := by tree_poly + have hM := polynomial_composition (polynomial_pair hw polynomial_second) (polynomial_getDFast 0) + have hR := polynomial_composition (polynomial_pair hr polynomial_second) (polynomial_getDFast 0) + have hB := polynomial_composition (polynomial_pair ho polynomial_second) (polynomial_getDFast 0) + have hg := polynomial_composition (polynomial_pair + (polynomial_composition hcap polynomial_listLength) hR) polynomial_subtract + have hQ := polynomial_composition (polynomial_pair hcap hg) BoundedPowerPrograms.polynomial_power + unfold preparedOffsetInputRealizer + exact polynomial_pair (polynomial_pair hM hQ) hB + +def preparedOffsetFactor (z : PreparedOffsetData×ℕ) : ℕ := + OffsetCountPrograms.offsetCount (preparedOffsetInput z) + +def preparedOffsetFactorRealizer : Realizer preparedOffsetFactor := + composition preparedOffsetInputRealizer OffsetCountPrograms.offsetCountRealizer + +lemma polynomial_preparedOffsetFactor : PolynomialTime preparedOffsetFactorRealizer := + polynomial_composition polynomial_preparedOffsetInput OffsetCountPrograms.polynomial_offsetCount + +def preparedOffsetIndices (z : PreparedOffsetData) : List ℕ := List.range z.1.1.2.length + +def preparedOffsetIndicesRealizer : Realizer preparedOffsetIndices := + composition (composition (composition (composition first first) second) listLength) range + +lemma polynomial_preparedOffsetIndices : PolynomialTime preparedOffsetIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_listLength) + Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1.1.2).trans + ((weight_snd z.1.1).trans ((weight_fst z.1).trans (weight_fst z))) + +def preparedOffsetProduct (z : PreparedOffsetData) : ℕ := + ((preparedOffsetIndices z).map (fun i => preparedOffsetFactor (z,i))).prod + +def preparedOffsetProductRealizer : Realizer preparedOffsetProduct := + composition (composition (pair identity preparedOffsetIndicesRealizer) + (mapWith preparedOffsetFactorRealizer)) listProd + +/-- The product uses binary ceiling divisions and shared bounded powers. +It is polynomial in its supplied bit allowance and integer data. -/ +theorem polynomial_preparedOffsetProduct : PolynomialTime preparedOffsetProductRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_preparedOffsetIndices) + (polynomial_mapWith polynomial_preparedOffsetFactor)) polynomial_listProd + +lemma preparedOffsetFactor_ofFn {q : ℕ} (cap : List Bool) (w r o : Fin q → ℕ) + (j : Fin q) (hr : r j≤cap.length) : + preparedOffsetFactor ((((cap,List.ofFn w),List.ofFn r),List.ofFn o),j.val)= + OffsetCountPrograms.offsetCount ((w j,2^r j),o j) := by + unfold preparedOffsetFactor preparedOffsetInput + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,j.isLt,dite_true,Option.getD_some] + rw [BoundedPowerPrograms.power_eq,Nat.sub_sub_self hr] + +private lemma range_prod (f : ℕ → ℕ) (q : ℕ) : + ((List.range q).map f).prod=∏ j : Fin q,f j.val := by + induction q with + | zero => simp + | succ q ih => + rw [List.prod_range_succ,Fin.prod_univ_castSucc,ih] + rfl + +theorem preparedOffsetProduct_ofFn {q : ℕ} (cap : List Bool) (w r o : Fin q → ℕ) + (hr : ∀ j,r j≤cap.length) : + preparedOffsetProduct (((cap,List.ofFn w),List.ofFn r),List.ofFn o)= + ∏ j : Fin q,OffsetCountPrograms.offsetCount ((w j,2^r j),o j) := by + unfold preparedOffsetProduct preparedOffsetIndices + rw [List.length_ofFn,range_prod] + apply Finset.prod_congr rfl + intro j _ + exact preparedOffsetFactor_ofFn cap w r o j (hr j) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedTransitionCache.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedTransitionCache.lean new file mode 100644 index 0000000000000000000000000000000000000000..7989040001378a5ee68f1ca2446b290f2325e45f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PreparedTransitionCache.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCount + +namespace OAI + +/-! # Computing the dense cache and the unused-bit multiplicity -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +attribute [local irreducible] residualParameters residualParametersRealizer canonicalBitCount + canonicalBitCountRealizer completionWeights completionWeightsRealizer + +abbrev TransitionCacheParameters := ResidualParameters×ℕ + +def completionMultiplicity (z : TransitionCacheParameters) : ℕ := + BinaryPowerPrograms.power (2,z.2-canonicalBitCount (residualParameters z.1)) + +def completionMultiplicityRealizer : Realizer completionMultiplicity := by + let used : Realizer (fun z : TransitionCacheParameters => + canonicalBitCount (residualParameters z.1)) := + composition (f := fun z : TransitionCacheParameters => residualParameters z.1) + (g := canonicalBitCount) + (composition (f := fun z : TransitionCacheParameters => z.1) (g := residualParameters) + first residualParametersRealizer) canonicalBitCountRealizer + let remaining : Realizer (fun z : TransitionCacheParameters => + z.2-canonicalBitCount (residualParameters z.1)) := + composition (f := fun z : TransitionCacheParameters => + (z.2,canonicalBitCount (residualParameters z.1))) + (g := fun z : ℕ×ℕ => z.1-z.2) (pair second used) subtract + exact composition (f := fun z : TransitionCacheParameters => + (2,z.2-canonicalBitCount (residualParameters z.1))) (g := BinaryPowerPrograms.power) + (pair (constant 2) remaining) BinaryPowerPrograms.powerRealizer + +def prepareTransitionCache (z : TransitionCacheParameters) : TransitionCache := + (z.1,(completionMultiplicity z,completionWeights (residualParameters z.1))) + +def prepareTransitionCacheRealizer : Realizer prepareTransitionCache := + pair first (pair completionMultiplicityRealizer + (composition (f := fun z : TransitionCacheParameters => residualParameters z.1) + (g := completionWeights) + (composition (f := fun z : TransitionCacheParameters => z.1) (g := residualParameters) + first residualParametersRealizer) completionWeightsRealizer)) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc + +lemma completionMultiplicity_encoded (b h : ℕ) (x : PaperStates r c) : + completionMultiplicity ((((stateCodeData r c e x,d^12),(d,h)),25*(d+b+h+1)^62))= + 2^(25*(d+b+h+1)^62-normalizedDrawBits (R x) (P x) d h) := by + unfold completionMultiplicity + rw [residualParameters_code r c hr hc e,BinaryPowerPrograms.power_eq, + canonicalBitCount_code (R x) (P x) (by have := listed_dimension_fourteen r c hr hc; omega) + (listed_paper_totals r c hr hc x)] + +lemma prepareTransitionCache_encoded (b h : ℕ) (x : PaperStates r c) : + prepareTransitionCache ((((stateCodeData r c e x,d^12),(d,h)),25*(d+b+h+1)^62))= + (((stateCodeData r c e x,d^12),(d,h)), + (2^(25*(d+b+h+1)^62-normalizedDrawBits (R x) (P x) d h), + completionWeights ((marginCode (R x),marginCode (P x)),(d,h)))) := by + unfold prepareTransitionCache + rw [completionMultiplicity_encoded r c e hr hc, + residualParameters_code r c hr hc e] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/PublicInputLength.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/PublicInputLength.lean new file mode 100644 index 0000000000000000000000000000000000000000..84ded19fab10ca7b3cc61dfb9abdb96b83055301 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/PublicInputLength.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.AlgorithmStatements +import Mathlib.Data.Nat.Size + +namespace OAI + +/-! # Binary input lengths for the sampling machine -/ + +namespace ContingencyTables.Algorithms +open MatchingFPRAS +open scoped BigOperators + +lemma encodeNat_length (n : ℕ) : (encodeNat n).length=n.size+1 := by + simp only [encodeNat,List.length_append,List.length_map,List.length_singleton,Nat.size_eq_bits_len] + +lemma encodeNat_length_le (n N : ℕ) (hn : n ≤ N) : + (encodeNat n).length ≤ Nat.clog 2 (N+1)+1 := by + rw [encodeNat_length] + have hs : n.size ≤ Nat.clog 2 (N+1) := Nat.size_le.mpr + ((Nat.lt_succ_of_le hn).trans_le (Nat.le_pow_clog (by decide) (N+1))) + omega + +private lemma natWords_length (ns : List ℕ) (N : ℕ) (h : ∀ n∈ns,n ≤ N) : + (ns.flatMap encodeNat).length ≤ ns.length*(Nat.clog 2 (N+1)+1) := by + induction ns with + | nil => simp + | cons n ns ih => + have hn := encodeNat_length_le n N (h n (by simp)) + have ht := ih (fun a ha => h a (by simp [ha])) + simp only [List.flatMap_cons,List.length_append,List.length_cons,Nat.add_mul,Nat.one_mul] + omega + +lemma encodeMargins_length {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) : + (encodeMargins r c).length ≤ m+n+2+(m+n)*(Nat.clog 2 ((∑ i,r i)+1)+1) := by + have hm : (encodeNat m).length ≤ m+1 := by + rw [encodeNat_length] + exact Nat.add_le_add_right (Nat.size_le.mpr (Nat.lt_two_pow_self)) 1 + have hn : (encodeNat n).length ≤ n+1 := by + rw [encodeNat_length] + exact Nat.add_le_add_right (Nat.size_le.mpr (Nat.lt_two_pow_self)) 1 + have hr := natWords_length (List.ofFn r) (∑ i,r i) (by + intro a ha + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp ha + exact Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ i)) + have hc := natWords_length (List.ofFn c) (∑ i,r i) (by + intro a ha + obtain ⟨j,rfl⟩ := List.mem_ofFn.mp ha + rw [htotal] + exact Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)) + simp only [List.length_ofFn] at hr hc + simp only [List.flatMap_def,←List.ofFn_comp'] at hr hc + unfold encodeMargins + simp only [List.length_append] + nlinarith + +/-- The bit input length is polynomial in the parameters used by the +paper's public sampling statement. -/ +theorem encodeSamplingInput_length {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) : + (encodeSamplingInput r c k).length ≤ 5*(samplingSize n r k)^2 := by + have hM := encodeMargins_length r c htotal + have hk : (encodeNat k).length ≤ k+1 := by + rw [encodeNat_length] + exact Nat.add_le_add_right (Nat.size_le.mpr (Nat.lt_two_pow_self)) 1 + rw [encodeSamplingInput,List.length_append] + let S := samplingSize n r k + have hS : 1 ≤ S := by dsimp [S,samplingSize]; omega + have hmn : m+n ≤ S := by dsimp [S,samplingSize]; omega + have hl : Nat.clog 2 ((∑ i,r i)+1)+1 ≤ S := by dsimp [S,samplingSize]; omega + have hkS : k+1 ≤ S := by dsimp [S,samplingSize]; omega + have hp := Nat.mul_le_mul hmn hl + change _ ≤ 5*S^2 + nlinarith + +end ContingencyTables.Algorithms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/QuadraticPrefixRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/QuadraticPrefixRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9e080e1e9da36fd1895808a6481a8c6c4373617 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/QuadraticPrefixRuntime.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Machines.GeometricRuntime +import Mathlib.Analysis.PSeries +import Mathlib.Analysis.SpecificLimits.Normed + +namespace OAI + +/-! # Expected time from geometrically accurate quadratic-cost prefixes -/ + +namespace ContingencyTables.QuadraticPrefixRuntime +open scoped BigOperators + +lemma weighted_geometric : HasSum (fun k : ℕ => (2*(k:ℝ)+3)*(1/2:ℝ)^k) 10 := by + have h0 := hasSum_geometric_of_norm_lt_one (by norm_num : ‖(1/2:ℝ)‖<1) + have h1 := hasSum_coe_mul_geometric_of_norm_lt_one (by norm_num : ‖(1/2:ℝ)‖<1) + convert (h1.mul_left 2).add (h0.mul_left 3) using 1 + · funext k; ring + · norm_num + +/-- Quadratic simulation overhead preserves a finite expected running time. +The small prefactor `δ` is retained through the entire estimate. -/ +theorem quadratic_bound (f : ℕ → ℝ) (T : ℕ) (hT : 0 T*(N+1)^2 + have hu : Monotone u := by + intro a b hab + dsimp only [u] + exact Nat.mul_le_mul_left T (Nat.pow_le_pow_left (by omega) 2) + have hup (N : ℕ) : 0 (hm (Nat.zero_le t)).trans hstart) + _ = T*δ := by simp [u] + have hb (k : ℕ) : (u (k+1)-u k) • f (u k)≤ + (T:ℝ)*δ*((2*(k:ℝ)+3)*(1/2:ℝ)^k) := by + have he : u (k+1)=u k+T*(2*k+3) := by dsimp only [u]; ring + rw [he,Nat.add_sub_cancel_left,nsmul_eq_mul,Nat.cast_mul,Nat.cast_add, + Nat.cast_mul,Nat.cast_ofNat] + have hh := mul_le_mul_of_nonneg_left (hstep k) (by positivity : (0:ℝ)≤T*(2*k+3)) + exact hh.trans_eq (by ring) + have hr : ∑ k ∈ Finset.range R,(u (k+1)-u k) • f (u k)≤10*T*δ := by + calc + _ ≤ ∑ k ∈ Finset.range R,(T:ℝ)*δ*((2*(k:ℝ)+3)*(1/2:ℝ)^k) := + Finset.sum_le_sum (fun k _ => hb k) + _ = (T:ℝ)*δ*(∑ k ∈ Finset.range R,(2*(k:ℝ)+3)*(1/2:ℝ)^k) := by rw [Finset.mul_sum] + _ ≤ (T:ℝ)*δ*10 := mul_le_mul_of_nonneg_left + ((weighted_geometric.summable.sum_le_tsum (Finset.range R) + (fun k _ => by positivity)).trans_eq weighted_geometric.tsum_eq) (by positivity) + _ = 10*T*δ := by ring + have hi : ∑ t ∈ Finset.range R,f t≤∑ t ∈ Finset.range (u R),f t := + Finset.sum_le_sum_of_subset_of_nonneg (Finset.range_mono hR) (fun t _ _ => h0 t) + exact (hi.trans hs).trans ((add_le_add hp hr).trans_eq (by ring)) + exact ⟨summable_of_sum_range_le h0 hbound,Real.tsum_le_of_sum_range_le h0 hbound⟩ + +/-- A bounded cheap prefix followed by a rare quadratic-cost correction. -/ +theorem expected_time (tail : ℕ → ℝ) (S T : ℕ) (hT : 0 tail (t+S)) T hT δ hδ + (fun t => h0 _) (fun _ _ h => hm (Nat.add_le_add_right h S)) + (by simpa only [Nat.zero_add] using hgate) + (by intro N; simpa only [Nat.add_comm] using hstep N) + have ht : Summable tail := (summable_nat_add_iff S).mp hs + refine ⟨ht,?_⟩ + rw [←ht.sum_add_tsum_nat_add S] + have hp : ∑ t ∈ Finset.range S,tail t≤(S:ℝ) := by + calc + _ ≤ ∑ _t ∈ Finset.range S,(1:ℝ) := Finset.sum_le_sum (fun t _ => h1 t) + _ = (S:ℝ) := by simp + exact add_le_add hp hb + +end ContingencyTables.QuadraticPrefixRuntime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/RationalIntervalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/RationalIntervalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8bcb134fa0ebfec28d010ca960c33b3db1fb8ee --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/RationalIntervalProgram.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FractionAcceptanceProgram +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledPenalty + +namespace OAI + +/-! # Exact binary arithmetic for a forest interval penalty + +A signed affine numerator is stored as a difference of two naturals. +Its distance outside the interval [0,1] is a nonnegative fraction with +the same denominator; no signed rational comparison is required. +-/ + +namespace ContingencyTables.RationalIntervalProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Input := (ℕ×ℕ)×ℕ + +def numerator (z : Input) : ℕ := (z.1.2-z.1.1)+(z.1.1-(z.1.2+z.2)) + +def numeratorRealizer : Realizer numerator := by + let P : Realizer (fun z : Input => z.1.1) := composition first first + let N : Realizer (fun z : Input => z.1.2) := composition first second + let D : Realizer (fun z : Input => z.2) := second + exact composition (pair (composition (pair N P) subtract) + (composition (pair P (composition (pair N D) add)) subtract)) add + +lemma polynomial_numerator : PolynomialTime numeratorRealizer := by + unfold numeratorRealizer + have hp := polynomial_composition + (polynomial_first (A := ℕ×ℕ) (B := ℕ)) polynomial_first + have hn := polynomial_composition + (polynomial_first (A := ℕ×ℕ) (B := ℕ)) polynomial_second + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hn hp) polynomial_subtract) + (polynomial_composition (polynomial_pair hp + (polynomial_composition (polynomial_pair hn polynomial_second) polynomial_add)) + polynomial_subtract)) polynomial_add + +def intervalCode (z : Input) : TreeFraction.Fraction := + TreeFraction.normalize (numerator z,z.2) + +def intervalCodeRealizer : Realizer intervalCode := + composition (f := fun z : Input => (numerator z,z.2)) (g := TreeFraction.normalize) + (pair numeratorRealizer second) TreeFraction.normalizeRealizer + +theorem polynomial_intervalCode : PolynomialTime intervalCodeRealizer := + polynomial_composition (polynomial_pair polynomial_numerator polynomial_second) + TreeFraction.polynomial_normalize + +lemma intervalCode_denominator (z : Input) : 0<(intervalCode z).2 := + TreeFraction.normalize_den_pos _ + +noncomputable section + +/-- Exact agreement with the interval cost in the forest density. The +only side condition is the strictly positive tree capacity denominator. -/ +theorem intervalCode_value (p n d : ℕ) (hd : 0 (wordChunks (z.1.2.2,z.2),z.1.2.1)) + (g := fun p : List (List Bool)×ℕ => p.1.take p.2) + (pair + (composition (f := fun z : Input X => (z.1.2.2,z.2)) (g := wordChunks) + (pair (composition (composition first second) second) second) wordChunksRealizer) + (composition (composition first second) first)) takeFast +lemma polynomial_words : PolynomialTime (wordsRealizer (X:=X)) := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_second) polynomial_wordChunks) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first)) + polynomial_takeFast + +variable {f : X×List Bool→TreeFraction.Fraction} + +def sample (f : X×List Bool→TreeFraction.Fraction) (z : Input X×List Bool) : TreeFraction.Fraction := + f (z.1.1.1,z.2) +def sampleRealizer (F : Realizer f) : Realizer (sample f) := + composition (f := fun z : Input X×List Bool => (z.1.1.1,z.2)) (g := f) + (pair (composition (composition first first) first) second) F +lemma polynomial_sample (F : Realizer f) (hF : PolynomialTime F) : + PolynomialTime (sampleRealizer F) := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) hF + +def samples (f : X×List Bool→TreeFraction.Fraction) (z : Input X) : List TreeFraction.Fraction := + (words z).map (fun bits => sample f (z,bits)) +def samplesRealizer (F : Realizer f) : Realizer (samples f) := + composition (pair identity wordsRealizer) (mapWith (sampleRealizer F)) +lemma polynomial_samples (F : Realizer f) (hF : PolynomialTime F) : + PolynomialTime (samplesRealizer F) := + polynomial_composition (polynomial_pair polynomial_identity polynomial_words) + (polynomial_mapWith (polynomial_sample F hF)) + +attribute [local irreducible] samples + +def output (f : X×List Bool→TreeFraction.Fraction) (z : Input X) : TreeFraction.Fraction := + MedianFractionProgram.median (samples f z) +def outputRealizer (F : Realizer f) : Realizer (output f) := + composition (f := samples f) (g := MedianFractionProgram.median) + (samplesRealizer F) MedianFractionProgram.medianRealizer +lemma polynomial_output (F : Realizer f) (hF : PolynomialTime F) : + PolynomialTime (outputRealizer F) := + polynomial_composition (polynomial_samples F hF) MedianFractionProgram.polynomial_median + +open GridBoundary CommonBasesFPRAS + +omit [Codec X] in +theorem output_ofFn (x : X) (r w : ℕ) (hw : 0 < w) (bits : Fin (r*w)→Bool) : + TreeFraction.val (output f ((x,(r,w)),List.ofFn bits))= + rationalMedian (List.ofFn (fun i : Fin r => + TreeFraction.val (f (x,List.ofFn (gridWordEquiv r w bits i))))) := by + rw [output,MedianFractionProgram.median_val] + have hwords : words ((x,(r,w)),List.ofFn bits)= + List.ofFn (fun i : Fin r => List.ofFn (gridWordEquiv r w bits i)) := by + change (wordChunks (w,List.ofFn bits)).take r=_ + rw [wordChunks_ofFn hw] + exact List.take_of_length_le (by simp) + unfold samples + rw [hwords] + simp only [List.map_ofFn] + rfl + +end ContingencyTables.RepeatedFractionProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualDenseProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualDenseProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b670830b88427a4e224303141547a356c2a07fa9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualDenseProgram.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalProgram + +namespace OAI + +/-! # A computed dense completion call from a retained small profile -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev ResidualParameters := (ProfileCheckData×ℕ)×(ℕ×ℕ) +abbrev ResidualDrawData := ResidualParameters×List Bool + +def residualParameters (z : ResidualParameters) : DensePrograms.CanonicalParameters := + ((profilePaddedMargins true z.1,profilePaddedMargins false z.1),z.2) + +def residualParametersRealizer : Realizer residualParameters := by + let rows : Realizer (fun z : ResidualParameters => profilePaddedMargins true z.1) := + composition (f := fun z : ResidualParameters => z.1) (g := profilePaddedMargins true) + first (profilePaddedMarginsRealizer true) + let columns : Realizer (fun z : ResidualParameters => profilePaddedMargins false z.1) := + composition (f := fun z : ResidualParameters => z.1) (g := profilePaddedMargins false) + first (profilePaddedMarginsRealizer false) + exact pair (pair rows columns) second + +theorem polynomial_residualParameters : PolynomialTime residualParametersRealizer := by + unfold residualParametersRealizer + exact polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first (polynomial_profilePaddedMargins true)) + (polynomial_composition polynomial_first (polynomial_profilePaddedMargins false))) + polynomial_second + +def residualDenseDraw (z : ResidualDrawData) : DensePrograms.MatrixCode := + DensePrograms.canonicalDenseDraw (residualParameters z.1,z.2) + +def residualDenseDrawRealizer : Realizer residualDenseDraw := + composition (pair (composition first residualParametersRealizer) second) + DensePrograms.canonicalDenseDrawRealizer + +/-- The actual completion call computes the residual margins, selects +their large rectangle, initializes it, and draws a dense matrix. -/ +theorem polynomial_residualDenseDraw : PolynomialTime residualDenseDrawRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_residualParameters) polynomial_second) + DensePrograms.polynomial_canonicalDenseDraw + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualGraphProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualGraphProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3b62d8e4b4766a95c8327f4b993a2048cdb554a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualGraphProgram.lean @@ -0,0 +1,205 @@ +import OAI.Combinatorics.ContingencyTables.Machines.DirectedBFSRuntime +import OAI.Combinatorics.ContingencyTables.Machines.SignedPairProgram +import OAI.Combinatorics.ContingencyTables.Transport.ResidualSearch + +namespace OAI + +/-! # Binary construction and search of the actual residual graph -/ + +namespace ContingencyTables.ResidualGraphProgram + +open MatchingFPRAS.TreeTyped DirectedBFSProgram SignedPairProgram + +abbrev NatMatrix := List (List ℕ) +abbrev FlowMatrix := List (List Signed) +abbrev Data := NatMatrix×FlowMatrix +abbrev ArcInput := Data×(ℕ×ℕ) + +def matrixIndices (C : NatMatrix) : List ℕ := List.range C.length + +def matrixIndicesRealizer : Realizer matrixIndices := composition listLength range + +lemma polynomial_matrixIndices : PolynomialTime matrixIndicesRealizer := by + apply polynomial_boundedRange polynomial_listLength Polynomial.X + intro C + simpa only [Function.comp_apply,Polynomial.eval_X] using list_length_le_weight C + +def capacityEntry (z : NatMatrix×(ℕ×ℕ)) : ℕ := + (z.1.getD z.2.1 []).getD z.2.2 0 + +def capacityEntryRealizer : Realizer capacityEntry := + composition (pair (composition (pair first (composition second first)) (getDFast [])) + (composition second second)) (getDFast 0) + +lemma polynomial_capacityEntry : PolynomialTime capacityEntryRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_first)) + (polynomial_getDFast [])) (polynomial_composition polynomial_second polynomial_second)) + (polynomial_getDFast 0) + +def flowEntry (z : FlowMatrix×(ℕ×ℕ)) : Signed := + (z.1.getD z.2.1 []).getD z.2.2 (0,0) + +def flowEntryRealizer : Realizer flowEntry := + composition (pair (composition (pair first (composition second first)) (getDFast [])) + (composition second second)) (getDFast (0,0)) + +lemma polynomial_flowEntry : PolynomialTime flowEntryRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_first)) + (polynomial_getDFast [])) (polynomial_composition polynomial_second polynomial_second)) + (polynomial_getDFast (0,0)) + +def arcData (z : ArcInput) : ℕ×Signed := + (capacityEntry (z.1.1,z.2),flowEntry (z.1.2,z.2)) + +def arcDataRealizer : Realizer arcData := + pair (composition (pair (composition first first) second) capacityEntryRealizer) + (composition (pair (composition first second) second) flowEntryRealizer) + +lemma polynomial_arcData : PolynomialTime arcDataRealizer := + polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_capacityEntry) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_flowEntry) + +def residualValue (z : ℕ×Signed) : ℕ := (z.1+z.2.2)-z.2.1 + +def residualValueRealizer : Realizer residualValue := + composition (pair (composition (pair first (composition second second)) add) + (composition second first)) subtract + +lemma polynomial_residualValue : PolynomialTime residualValueRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_second)) + polynomial_add) (polynomial_composition polynomial_second polynomial_first)) polynomial_subtract + +def positive (z : ℕ×Signed) : Bool := decide (z.2.1< z.1+z.2.2) + +def positiveRealizer : Realizer positive := + composition (pair (composition second first) + (composition (pair first (composition second second)) add)) less + +lemma polynomial_positive : PolynomialTime positiveRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) polynomial_add)) polynomial_less + +def arc (z : ArcInput) : Bool := positive (arcData z) +def arcRealizer : Realizer arc := composition arcDataRealizer positiveRealizer +lemma polynomial_arc : PolynomialTime arcRealizer := + polynomial_composition polynomial_arcData polynomial_positive + +def arcRow (z : Data×ℕ) : List Bool := + (List.range z.1.1.length).map (fun v=>arc (z.1,(z.2,v))) + +def arcRowRealizer : Realizer arcRow := + composition + (f := fun z : Data×ℕ=>(z,List.range z.1.1.length)) + (g := fun z : (Data×ℕ)×List ℕ=>z.2.map (fun v=>arc (z.1.1,(z.1.2,v)))) + (pair identity (composition + (f := fun z : Data×ℕ=>z.1.1) (g := matrixIndices) + (composition first first) matrixIndicesRealizer)) + (mapWith (composition + (f := fun z : (Data×ℕ)×ℕ=>(z.1.1,(z.1.2,z.2))) (g := arc) + (pair (composition first first) (pair (composition first second) second)) arcRealizer)) + +lemma polynomial_arcRow : PolynomialTime arcRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_matrixIndices)) + (polynomial_mapWith (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_arc)) + +def graph (z : Data) : DirectedBFSCode.Graph := + (List.range z.1.length).map (fun u=>arcRow (z,u)) + +def graphRealizer : Realizer graph := + composition + (f := fun z : Data=>(z,List.range z.1.length)) + (g := fun z : Data×List ℕ=>z.2.map (fun u=>arcRow (z.1,u))) + (pair identity (composition (f := fun z : Data=>z.1) (g := matrixIndices) + first matrixIndicesRealizer)) (mapWith arcRowRealizer) + +lemma polynomial_graph : PolynomialTime graphRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_matrixIndices)) + (polynomial_mapWith polynomial_arcRow) + +def natCode {m n : ℕ} (c : Fin m→Fin n→ℕ) : NatMatrix := + List.ofFn (fun u=>List.ofFn (c u)) + +def flowCode {m n : ℕ} (f : Fin m→Fin n→ℤ) : FlowMatrix := + List.ofFn (fun u=>List.ofFn (fun v=>ForestAffineProgram.signedParts (f u v))) + +lemma capacityEntry_code {m n : ℕ} (c : Fin m→Fin n→ℕ) (u : Fin m) (v : Fin n) : + capacityEntry (natCode c,(u.val,v.val))=c u v := by + simp only [capacityEntry,natCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + u.isLt,v.isLt,dite_true,Option.getD_some,Fin.eta] + +lemma flowEntry_code {m n : ℕ} (f : Fin m→Fin n→ℤ) (u : Fin m) (v : Fin n) : + flowEntry (flowCode f,(u.val,v.val))=ForestAffineProgram.signedParts (f u v) := by + simp only [flowEntry,flowCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + u.isLt,v.isLt,dite_true,Option.getD_some,Fin.eta] + +lemma residualValue_correct (c : ℕ) (z : Signed) : + residualValue (c,z)=((c:ℤ)-SignedPairProgram.value z).toNat := by + unfold residualValue SignedPairProgram.value + dsimp only + omega + +lemma positive_correct (c : ℕ) (z : Signed) : + positive (c,z)=decide (0<(c:ℤ)-SignedPairProgram.value z) := by + apply Bool.eq_iff_iff.mpr + change (decide (z.1 < c+z.2)=true) ↔ + (decide (0<(c:ℤ)-SignedPairProgram.value z)=true) + rw [decide_eq_true_eq,decide_eq_true_eq] + change z.1 < c+z.2 ↔ 0<(c:ℤ)-((z.1:ℤ)-z.2) + omega + +lemma arc_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (f : PublishedEdmondsKarp.Flow n) (u v : Fin n) : + arc ((natCode c,flowCode f),(u.val,v.val))=ResidualSearch.edge c f u v := by + simp only [arc,arcData,capacityEntry_code,flowEntry_code,positive_correct, + SignedPairProgram.value,ForestAffineProgram.signedParts_sub,ResidualSearch.edge] + +lemma graph_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (f : PublishedEdmondsKarp.Flow n) : + graph (natCode c,flowCode f)=DirectedBFSCode.graphCode (ResidualSearch.edge c f) := by + simp only [graph,arcRow,natCode,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,DirectedBFSCode.graphCode] + apply congrArg List.ofFn + funext u + apply congrArg List.ofFn + funext v + exact arc_code c f u v + +def search (z : Data×(ℕ×ℕ)) : Option (List ℕ) := + DirectedBFSCode.search (graph z.1) z.2.1 z.2.2 + +def searchRealizer : Realizer search := + composition (pair (pair (composition first graphRealizer) (composition second first)) + (composition second second)) DirectedBFSRuntime.searchRealizer + +lemma polynomial_search : PolynomialTime searchRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_graph) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition polynomial_second polynomial_second)) + DirectedBFSRuntime.polynomial_search + +lemma search_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (f : PublishedEdmondsKarp.Flow n) (s t : Fin n) : + search ((natCode c,flowCode f),(s.val,t.val))= + (ResidualSearch.search c f s t).map (List.map Fin.val) := by + rw [search,graph_code,DirectedBFSCode.search_code] + rfl + +end ContingencyTables.ResidualGraphProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualWeightProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualWeightProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b173f4cee60b0b4fc952fc92c71ab0aea7af50ff --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ResidualWeightProgram.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerResidualCorrection +import OAI.Combinatorics.ContingencyTables.Machines.VectorRetryProgram + +namespace OAI + +/-! # Binary computation of the rare branch's integer weights -/ + +namespace ContingencyTables.ResidualWeightPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators Classical + +abbrev Input := (ℕ×ℕ)×(ℕ×ℕ) + +/-- Common denominator, inverse branch probability, number of tables, +and the ordinary draw's numerator. -/ +def count (z : Input) : ℕ := z.1.1*z.1.2-z.2.1*(z.1.2-1)*z.2.2 + +def countRealizer : Realizer count := by + let denominator : Realizer (fun z : Input => z.1.1) := composition first first + let branch : Realizer (fun z : Input => z.1.2) := composition first second + let cardinality : Realizer (fun z : Input => z.2.1) := composition second first + let numerator : Realizer (fun z : Input => z.2.2) := composition second second + let left := composition (pair denominator branch) multiply + let right := composition (pair (composition (pair cardinality + (composition branch predecessor)) multiply) numerator) multiply + exact composition (pair left right) subtract + +lemma polynomial_count : PolynomialTime countRealizer := by + unfold countRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_first polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_predecessor)) polynomial_multiply) + (polynomial_composition polynomial_second polynomial_second)) polynomial_multiply)) + polynomial_subtract + +lemma count_actual {A : Type*} [Fintype A] {Q : ℕ} (p : IntegerLaw A Q) + (T : ℕ) (hT : 0 (p.count x:ℤ)) a= + ((Q*T:ℕ):ℤ)-((Fintype.card A*(T-1)*p.count a:ℕ):ℤ) := by + unfold ResidualMixture.residualNumerator + rw [ht] + push_cast + rfl + rw [IntegerResidualCorrection.count,he,Int.toNat_sub] + rfl + +end ContingencyTables.ResidualWeightPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/RetryNumeratorProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/RetryNumeratorProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae4d3821eeaf4fe0f046320fbbec0de0e56027fa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/RetryNumeratorProgram.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw + +namespace OAI + +/-! # Binary first-success numerators via a two-coordinate recurrence -/ + +namespace ContingencyTables.RetryNumeratorPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +/-- Unary trial count; denominator, failure count, success count, fallback match. -/ +abbrev Input := List Bool×((ℕ×ℕ)×(ℕ×Bool)) + +def twoEntries {A : Type} [Codec A] : Realizer (fun x : A×A => [x.1,x.2]) := + composition (pair first (composition second BinaryPowerPrograms.singleton)) listCons + +lemma polynomial_twoEntries {A : Type} [Codec A] : PolynomialTime (twoEntries (A := A)) := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second BinaryPowerPrograms.polynomial_singleton)) + polynomial_listCons + +def setup (z : Input) : ℕ×(List (List ℕ)×List ℕ) := + (z.1.length,([[z.2.1.2,z.2.2.1],[0,z.2.1.1]],[(if z.2.2.2 then 1 else 0),1])) + +def setupRealizer : Realizer setup := by + let Q : Realizer (fun z : Input => z.2.1.1) := composition (composition second first) first + let phi : Realizer (fun z : Input => z.2.1.2) := composition (composition second first) second + let alpha : Realizer (fun z : Input => z.2.2.1) := composition (composition second second) first + let hit : Realizer (fun z : Input => z.2.2.2) := composition (composition second second) second + let column1 := composition (pair phi alpha) twoEntries + let column2 := composition (pair (constant 0) Q) twoEntries + let matrix := composition (pair column1 column2) twoEntries + let initial := choose hit (constant 1) (constant 0) + let vector := composition (pair initial (constant 1)) twoEntries + exact pair (composition first listLength) (pair matrix vector) + +lemma polynomial_setup : PolynomialTime setupRealizer := by + have hQ : PolynomialTime (composition (composition + (second (A := List Bool) (B := (ℕ×ℕ)×(ℕ×Bool))) first) first) := by tree_poly + have hphi : PolynomialTime (composition (composition + (second (A := List Bool) (B := (ℕ×ℕ)×(ℕ×Bool))) first) second) := by tree_poly + have halpha : PolynomialTime (composition (composition + (second (A := List Bool) (B := (ℕ×ℕ)×(ℕ×Bool))) second) first) := by tree_poly + have hhit : PolynomialTime (composition (composition + (second (A := List Bool) (B := (ℕ×ℕ)×(ℕ×Bool))) second) second) := by tree_poly + unfold setupRealizer + exact polynomial_pair (polynomial_composition polynomial_first polynomial_listLength) + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hphi halpha) polynomial_twoEntries) + (polynomial_composition (polynomial_pair (polynomial_constant 0) hQ) polynomial_twoEntries)) + polynomial_twoEntries) + (polynomial_composition (polynomial_pair + (polynomial_choose hhit (polynomial_constant 1) (polynomial_constant 0)) + (polynomial_constant 1)) polynomial_twoEntries)) + +def count (z : Input) : ℕ := (IntegerMatrixPrograms.iterate (setup z)).headD 0 + +def countRealizer : Realizer count := + composition (composition setupRealizer IntegerMatrixPrograms.iterateRealizer) (head 0) + +/-- All stored numbers are binary; only the supplied trial marker controls +iteration, so evaluation is polynomial in that marker and binary data. -/ +theorem polynomial_count : PolynomialTime countRealizer := by + have hi : PolynomialTime (composition setupRealizer IntegerMatrixPrograms.iterateRealizer) := by + obtain ⟨p,hp⟩ := polynomial_setup + apply work_composition ⟨p,hp⟩ IntegerMatrixPrograms.work_iterate (Polynomial.X+p) + intro z + have hl := (list_length_le_weight z.1).trans (weight_fst z) + have hw := weight_snd (setup z) + have hc := hp z + simp only [Polynomial.eval_add,Polynomial.eval_X,setup] at * + omega + exact polynomial_composition hi (polynomial_head 0) + +def recurrence (Q phi alpha initial : ℕ) : ℕ → ℕ + | 0 => initial + | n+1 => phi*recurrence Q phi alpha initial n+alpha*Q^n + +private lemma iterate_eq (B : List (List ℕ)) (v : List ℕ) (N : ℕ) : + IntegerMatrixPrograms.iterate (N,(B,v))= + ((fun v => IntegerMatrixPrograms.propagate (B,v))^[N]) v := by + induction N generalizing v with + | zero => rfl + | succ N ih => + rw [IntegerMatrixPrograms.iterate_succ,ih,Function.iterate_succ_apply] + +private lemma propagate_two (Q phi alpha x y : ℕ) : + IntegerMatrixPrograms.propagate ([[phi,alpha],[0,Q]],[x,y])= + [phi*x+alpha*y,Q*y] := by + simp [IntegerMatrixPrograms.propagate,IntegerMatrixPrograms.dot_cons, + IntegerMatrixPrograms.dot_nil,Nat.mul_comm] + +lemma count_eq (xs : List Bool) (Q phi alpha : ℕ) (hit : Bool) : + count (xs,((Q,phi),(alpha,hit)))= + recurrence Q phi alpha (if hit then 1 else 0) xs.length := by + have hiter (N initial : ℕ) : + ((fun v => IntegerMatrixPrograms.propagate ([[phi,alpha],[0,Q]],v))^[N]) [initial,1]= + [recurrence Q phi alpha initial N,Q^N] := by + induction N with + | zero => simp [recurrence] + | succ N ih => + rw [Function.iterate_succ_apply',ih,propagate_two] + simp only [recurrence,pow_succ] + rw [Nat.mul_comm Q (Q^N)] + unfold count setup + rw [iterate_eq,hiter] + rfl + +lemma recurrence_retry {A : Type*} [Fintype A] [DecidableEq A] {Q : ℕ} + (p : IntegerLaw (Option A) Q) (fallback x : A) (N : ℕ) : + recurrence Q (p.count none) (p.count (some x)) (if x=fallback then 1 else 0) N= + IntegerLaw.retryCount p fallback N x := by + induction N with + | zero => rfl + | succ N ih => + rw [recurrence,ih,IntegerLaw.retryCount] + exact Nat.add_comm _ _ + +end ContingencyTables.RetryNumeratorPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/RoundedPowerProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/RoundedPowerProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..3112252c63bd4049f9d2ffef5b559b271e08cc3b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/RoundedPowerProgram.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.ContingencyTables.Machines.SignedFloorProgram +import OAI.Combinatorics.ContingencyTables.Machines.DyadicRootProgram +import OAI.Combinatorics.ContingencyTables.Transport.PowerOfTwoApproximation + +namespace OAI + +/-! # Executing the rounded power used by the correction oracle + +The exponent lies in [-2,2]. Clipping the computed signed floor +at twice the supplied degree allowance plus one is therefore inactive +on valid inputs, and keeps every binary execution polynomial even on +arbitrary malformed numerator/denominator data. +-/ + +namespace ContingencyTables.RoundedPowerProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial SignedPairProgram + +abbrev Input := SignedFloorProgram.ScaledInput + +def normalized (z : Input) : Signed := SignedPairProgram.normalize (SignedFloorProgram.scaledFloor z) +def normalizedRealizer : Realizer normalized := + composition SignedFloorProgram.scaledFloorRealizer SignedPairProgram.normalizeRealizer +lemma polynomial_normalized : PolynomialTime normalizedRealizer := + polynomial_composition SignedFloorProgram.polynomial_scaledFloor SignedPairProgram.polynomial_normalize + +def cap (z : Input) : ℕ := 2*z.2.length+1 +def capRealizer : Realizer cap := composition + (f:=fun z : Input=>2*z.2.length) (g:=Nat.succ) + (composition (f:=fun z : Input=>(2,z.2.length)) (g:=fun p : ℕ×ℕ=>p.1*p.2) + (pair (constant 2) (composition second listLength)) multiply) successor +lemma polynomial_cap : PolynomialTime capRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 2) + (polynomial_composition polynomial_second polynomial_listLength)) polynomial_multiply) + polynomial_successor + +def clipped (z : Input) : Signed := + (min (normalized z).1 (cap z),min (normalized z).2 (cap z)) +def clippedRealizer : Realizer clipped := pair + (composition (pair (composition normalizedRealizer first) capRealizer) minimum) + (composition (pair (composition normalizedRealizer second) capRealizer) minimum) +lemma polynomial_clipped : PolynomialTime clippedRealizer := polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_normalized polynomial_first) polynomial_cap) polynomial_minimum) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_normalized polynomial_second) polynomial_cap) polynomial_minimum) + +def positiveInput (z : Input) : ℕ×ℕ := (2,(clipped z).1) +def negativeInput (z : Input) : ℕ×ℕ := (2,(clipped z).2) +def positiveInputRealizer : Realizer positiveInput := pair (constant 2) (composition clippedRealizer first) +def negativeInputRealizer : Realizer negativeInput := pair (constant 2) (composition clippedRealizer second) +lemma polynomial_positiveInput : PolynomialTime positiveInputRealizer := + polynomial_pair (polynomial_constant 2) (polynomial_composition polynomial_clipped polynomial_first) +lemma polynomial_negativeInput : PolynomialTime negativeInputRealizer := + polynomial_pair (polynomial_constant 2) (polynomial_composition polynomial_clipped polynomial_second) + +def positivePower (z : Input) : ℕ := BinaryPowerPrograms.power (positiveInput z) +def negativePower (z : Input) : ℕ := BinaryPowerPrograms.power (negativeInput z) +def positivePowerRealizer : Realizer positivePower := + composition positiveInputRealizer BinaryPowerPrograms.powerRealizer +def negativePowerRealizer : Realizer negativePower := + composition negativeInputRealizer BinaryPowerPrograms.powerRealizer + +lemma polynomial_positivePower : PolynomialTime positivePowerRealizer := by + apply work_composition polynomial_positiveInput BinaryPowerPrograms.work_power (2*X+10) + intro z + have hl: z.2.length ≤ weight z:=(list_length_le_weight z.2).trans (weight_snd z) + have hm: (clipped z).1 ≤ cap z:=min_le_right _ _ + have ht: weight (2:ℕ) ≤ 9:=by decide + simp only [positiveInput,cap,eval_add,eval_mul,eval_ofNat,eval_X] at * + omega + +lemma polynomial_negativePower : PolynomialTime negativePowerRealizer := by + apply work_composition polynomial_negativeInput BinaryPowerPrograms.work_power (2*X+10) + intro z + have hl: z.2.length ≤ weight z:=(list_length_le_weight z.2).trans (weight_snd z) + have hm: (clipped z).2 ≤ cap z:=min_le_right _ _ + have ht: weight (2:ℕ) ≤ 9:=by decide + simp only [negativeInput,cap,eval_add,eval_mul,eval_ofNat,eval_X] at * + omega + +def output (z : Input) : TreeFraction.Fraction := + TreeFraction.normalize (positivePower z,negativePower z) +def outputRealizer : Realizer output := + composition (pair positivePowerRealizer negativePowerRealizer) TreeFraction.normalizeRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_positivePower polynomial_negativePower) + TreeFraction.polynomial_normalize + +lemma floor_bounds (beta : ℚ) (hlo : -2 ≤ beta) (hhi : beta ≤ 2) (s : ℕ) : + -2*(s:ℤ) ≤ ⌊(s:ℚ)*beta⌋ ∧ ⌊(s:ℚ)*beta⌋ ≤ 2*(s:ℤ) := by + have hL:=mul_le_mul_of_nonneg_left hlo (Nat.cast_nonneg s : (0:ℚ) ≤ s) + have hU:=mul_le_mul_of_nonneg_left hhi (Nat.cast_nonneg s : (0:ℚ) ≤ s) + constructor + · apply Int.le_floor.mpr + push_cast + linarith + · have hf: (⌊(s:ℚ)*beta⌋:ℚ) ≤ 2*s:=(Int.floor_le _).trans (by linarith) + exact_mod_cast hf + +lemma clipped_eq (p n d : ℕ) (xs : List Bool) + (hlo: -2 ≤ ((p:ℚ)-n)/d) (hhi: ((p:ℚ)-n)/d ≤ 2) : + clipped (((p,n),d),xs)= + ((⌊(xs.length:ℚ)*(((p:ℚ)-n)/d)⌋:ℤ).toNat, + (-⌊(xs.length:ℚ)*(((p:ℚ)-n)/d)⌋:ℤ).toNat) := by + have hb:=floor_bounds _ hlo hhi xs.length + have hp: (⌊(xs.length:ℚ)*(((p:ℚ)-n)/d)⌋:ℤ).toNat ≤ 2*xs.length+1:=by omega + have hn: (-⌊(xs.length:ℚ)*(((p:ℚ)-n)/d)⌋:ℤ).toNat ≤ 2*xs.length+1:=by omega + simp only [clipped,normalized,SignedPairProgram.normalize_eq,SignedFloorProgram.scaledFloor_value, + ForestAffineProgram.signedParts,cap,min_eq_left hp,min_eq_left hn] + +/-- The returned natural fraction is exactly the rational power used +by the approximation, including negative rounded exponents. -/ +theorem output_value (p n d : ℕ) (xs : List Bool) + (hlo: -2 ≤ ((p:ℚ)-n)/d) (hhi: ((p:ℚ)-n)/d ≤ 2) : + TreeFraction.val (output (((p,n),d),xs))= + (2:ℚ)^PowerOfTwoApproximation.numerator (((p:ℚ)-n)/d) xs.length := by + rw [output,TreeFraction.normalize_val] + simp only [positivePower,negativePower,positiveInput,negativeInput, + BinaryPowerPrograms.power_eq,clipped_eq p n d xs hlo hhi,TreeFraction.val,Nat.cast_pow,Nat.cast_ofNat] + let q:ℤ:=⌊(xs.length:ℚ)*(((p:ℚ)-n)/d)⌋ + change (2:ℚ)^q.toNat/(2:ℚ)^(-q).toNat=(2:ℚ)^q + have he: (q.toNat:ℤ)-(-q).toNat=q:=by omega + conv_rhs => rw [←he] + rw [zpow_sub₀ (by norm_num : (2:ℚ)≠0),zpow_natCast,zpow_natCast] + +theorem output_denominator_pos (z : Input) : 0<(output z).2 := + TreeFraction.normalize_den_pos _ + +end ContingencyTables.RoundedPowerProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..559a9987bc66fb5a888ec41d591b5e35c207ca03 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleBounds.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleProgram + +namespace OAI + +/-! # Numeric bounds for the fixed arithmetic circuits -/ + +namespace ContingencyTables.ScalarScheduleProgram +open Polynomial +noncomputable section + +def Expr.bound : Expr → Polynomial ℕ + | .input _ => X + | .number n => C n + | .plus a b => a.bound+b.bound + | .times a b => a.bound*b.bound + +lemma Expr.eval_le (e : Expr) (xs : List ℕ) (M : ℕ) + (h : ∀ i,xs.getD i 0 ≤ M) : e.eval xs ≤ e.bound.eval M := by + induction e with + | input i => simpa only [Expr.eval,Expr.bound,Polynomial.eval_X] using h i + | number n => simp only [Expr.eval,Expr.bound,eval_C,le_refl] + | plus a b ha hb => + simp only [Expr.eval,Expr.bound,Polynomial.eval_add] + exact Nat.add_le_add ha hb + | times a b ha hb => + simp only [Expr.eval,Expr.bound,Polynomial.eval_mul] + exact Nat.mul_le_mul ha hb + +lemma getD_le_of_mem (xs : List ℕ) (M : ℕ) (h : ∀ x∈xs,x ≤ M) : + ∀ i,xs.getD i 0 ≤ M := by + induction xs with + | nil => intro i; simp + | cons x xs ih => + intro i + cases i with + | zero => simpa using h x (by simp) + | succ i => + simpa using ih (fun y hy => h y (by simp only [List.mem_cons]; exact Or.inr hy)) i + +lemma Expr.eval_le_of_mem (e : Expr) (xs : List ℕ) (M : ℕ) (h : ∀ x∈xs,x ≤ M) : + e.eval xs ≤ e.bound.eval M := e.eval_le xs M (getD_le_of_mem xs M h) + +end +end ContingencyTables.ScalarScheduleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbdf194f5930848882cd94a64efd0c500d3a2f23 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScalarScheduleProgram.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialDivision + +namespace OAI + +/-! # Fixed arithmetic circuits for the scalar counting schedules + +These circuits only read a fixed finite list and perform binary addition +and multiplication. Their syntax describes the fixed program, not a +numeric loop selected by the input. +-/ + +namespace ContingencyTables.ScalarScheduleProgram +open MatchingFPRAS.TreeTyped + +inductive Expr where + | input : ℕ → Expr + | number : ℕ → Expr + | plus : Expr → Expr → Expr + | times : Expr → Expr → Expr + +def Expr.eval : Expr → List ℕ → ℕ + | .input i, xs => xs.getD i 0 + | .number n, _ => n + | .plus a b, xs => a.eval xs+b.eval xs + | .times a b, xs => a.eval xs*b.eval xs + +def Expr.realizer : (e : Expr) → Realizer e.eval + | .input i => composition (pair identity (constant i)) (getDFast 0) + | .number n => constant n + | .plus a b => composition (pair a.realizer b.realizer) add + | .times a b => composition (pair a.realizer b.realizer) multiply + +lemma Expr.polynomial (e : Expr) : PolynomialTime e.realizer := by + induction e with + | input i => exact polynomial_composition (polynomial_pair polynomial_identity + (polynomial_constant i)) (polynomial_getDFast 0) + | number n => exact polynomial_constant n + | plus a b ha hb => exact polynomial_composition (polynomial_pair ha hb) polynomial_add + | times a b ha hb => exact polynomial_composition (polynomial_pair ha hb) polynomial_multiply + +def Expr.pow (a : Expr) : ℕ → Expr + | 0 => .number 1 + | n+1 => .times (a.pow n) a + +lemma Expr.eval_pow (a : Expr) (n : ℕ) (xs : List ℕ) : + (a.pow n).eval xs=(a.eval xs)^n := by + induction n with + | zero => rfl + | succ n ih => simp only [Expr.pow,Expr.eval,ih,pow_succ] + + +instance (n : ℕ) : OfNat Expr n := ⟨.number n⟩ +instance : Add Expr := ⟨.plus⟩ +instance : Mul Expr := ⟨.times⟩ +instance : Pow Expr ℕ := ⟨Expr.pow⟩ + +@[simp] lemma Expr.eval_power (a : Expr) (n : ℕ) (xs : List ℕ) : + (a^n).eval xs=(a.eval xs)^n := Expr.eval_pow a n xs + +@[simp] lemma Expr.eval_add (a b : Expr) (xs : List ℕ) : + (a+b).eval xs=a.eval xs+b.eval xs := rfl +@[simp] lemma Expr.eval_mul (a b : Expr) (xs : List ℕ) : + (a*b).eval xs=a.eval xs*b.eval xs := rfl +@[simp] lemma Expr.eval_ofNat (n : ℕ) (xs : List ℕ) : + (OfNat.ofNat n : Expr).eval xs=n := rfl + +def vector (es : List Expr) (xs : List ℕ) : List ℕ := es.map (fun e => e.eval xs) + +def vectorRealizer : (es : List Expr) → Realizer (vector es) + | [] => constant [] + | e::es => composition (pair e.realizer (vectorRealizer es)) listCons + +lemma polynomial_vector (es : List Expr) : PolynomialTime (vectorRealizer es) := by + induction es with + | nil => exact polynomial_constant [] + | cons e es ih => exact polynomial_composition (polynomial_pair e.polynomial ih) polynomial_listCons + + +end ContingencyTables.ScalarScheduleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScaledWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScaledWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..4387f247f1412953905ae1f567a232e9da50323e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScaledWordProgram.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteScaledDraw + +namespace OAI + +/-! # Polynomial binary execution of the bounded quotient draw -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def scaledWordValue (x : ℕ×List Bool) : ℕ := + x.1*StackAddition.value x.2/2^x.2.length + +def scaledWordRealizer : Realizer scaledWordValue := + (composition (pair + (composition (pair first (composition second bitValue)) multiply) + (composition second bitDenominatorRealizer)) quotient).congr (by + intro x + simp only [Function.comp_apply,bitDenominator_eq,scaledWordValue]) + +theorem polynomial_scaledWord : PolynomialTime scaledWordRealizer := by + unfold scaledWordRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_bitValue)) polynomial_multiply) + (polynomial_composition polynomial_second polynomial_bitDenominator)) polynomial_quotient) + +theorem scaledWordValue_ofFn (M k : ℕ) (hM : 0 bits[i] + have he : List.ofFn w=bits := List.ofFn_getElem + rw [←he,scaledWordValue_ofFn M bits.length hM w] + exact (FairBits.scaledBitInteger M bits.length hM w).isLt + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountInput.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b23b4fda5cbf020a2e278723141d0c930720f17 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountInput.lean @@ -0,0 +1,233 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalOuterVector +import OAI.Combinatorics.ContingencyTables.Sampling.UnitOuterVector +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileScheduleSemantics +import OAI.Combinatorics.ContingencyTables.Transport.UnaryMarkers + +namespace OAI + +/-! # Supplying the finite count evaluator from the public sampling parameters -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +attribute [local irreducible] initialCheck marginPadding parameterDimension parameterAccuracy + parameterCompletionWidth parameterSteps parameterProposalWidth hasLargeRectangle parameterTrials + profileBoxIndex outerVector UnitCountPrograms.outerVector + +/-- The same cache parameters used by the executed approximate sampler. -/ +def scheduledCacheParameters (z : SamplingParameters) : TransitionCacheParameters := + (((initialCheck z.1,marginPadding z.1),(parameterDimension z,parameterAccuracy z)), + parameterCompletionWidth z) + +def scheduledCacheParametersRealizer : Realizer scheduledCacheParameters := + pair (pair (pair (composition (f := fun z : SamplingParameters => z.1) (g := initialCheck) first initialCheckRealizer) + (composition (f := fun z : SamplingParameters => z.1) (g := marginPadding) first marginPaddingRealizer)) + (pair parameterDimensionRealizer parameterAccuracyRealizer)) parameterCompletionWidthRealizer + +lemma polynomial_scheduledCacheParameters : PolynomialTime scheduledCacheParametersRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_initialCheck) + (polynomial_composition polynomial_first polynomial_marginPadding)) + (polynomial_pair polynomial_parameterDimension polynomial_parameterAccuracy)) + polynomial_parameterCompletionWidth + +def scheduledDenseWidth (z : SamplingParameters) : ℕ := + parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z)+parameterCompletionWidth z + +def scheduledDenseWidthRealizer : Realizer scheduledDenseWidth := + composition (f := fun z : SamplingParameters => + (parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z),parameterCompletionWidth z)) + (g := fun p : ℕ×ℕ => p.1+p.2) + (pair (composition (f := fun z : SamplingParameters => + (parameterSteps z,parameterProposalWidth z+parameterCompletionWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair parameterStepsRealizer (composition + (f := fun z : SamplingParameters => (parameterProposalWidth z,parameterCompletionWidth z)) + (g := fun p : ℕ×ℕ => p.1+p.2) + (pair parameterProposalWidthRealizer parameterCompletionWidthRealizer) add)) multiply) + parameterCompletionWidthRealizer) add + +lemma polynomial_scheduledDenseWidth : PolynomialTime scheduledDenseWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_parameterSteps (polynomial_composition + (polynomial_pair polynomial_parameterProposalWidth polynomial_parameterCompletionWidth) + polynomial_add)) polynomial_multiply) polynomial_parameterCompletionWidth) polynomial_add + +def scheduledUnitWidth (z : SamplingParameters) : ℕ := parameterSteps z*parameterProposalWidth z + +def scheduledUnitWidthRealizer : Realizer scheduledUnitWidth := + composition (f := fun z : SamplingParameters => (parameterSteps z,parameterProposalWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair parameterStepsRealizer parameterProposalWidthRealizer) multiply + +lemma polynomial_scheduledUnitWidth : PolynomialTime scheduledUnitWidthRealizer := + polynomial_composition (polynomial_pair polynomial_parameterSteps polynomial_parameterProposalWidth) + polynomial_multiply + +attribute [local irreducible] scheduledDenseWidth scheduledUnitWidth + +/-- The all-small branch uses only the proposal bits of each walk. -/ +def scheduledTrialWidth (z : SamplingParameters) : ℕ := + if hasLargeRectangle z then scheduledDenseWidth z else scheduledUnitWidth z + +def scheduledTrialWidthRealizer : Realizer scheduledTrialWidth := + choose hasLargeRectangleRealizer scheduledDenseWidthRealizer scheduledUnitWidthRealizer + +lemma polynomial_scheduledTrialWidth : PolynomialTime scheduledTrialWidthRealizer := + polynomial_choose polynomial_hasLargeRectangle polynomial_scheduledDenseWidth polynomial_scheduledUnitWidth + +attribute [local irreducible] scheduledTrialWidth + +/-- Numeric loop lengths are charged explicitly, in addition to binary input size. -/ +def scheduledCountInputMeasure (z : SamplingParameters) : ℕ := + parameterSteps z+parameterTrials z+parameterProposalWidth z+scheduledTrialWidth z+weight z + +lemma weight_le_scheduledCountInputMeasure (z : SamplingParameters) : + weight z ≤ X.eval (scheduledCountInputMeasure z) := by + simp only [eval_X,scheduledCountInputMeasure] + omega + +def scheduledMatrixParameters (z : SamplingParameters) : MatrixParameters := + (scheduledCacheParameters z,unaryMarkers (parameterProposalWidth z)) + +def scheduledMatrixParametersRealizer : Realizer scheduledMatrixParameters := + pair scheduledCacheParametersRealizer + (composition (f := parameterProposalWidth) (g := unaryMarkers) + parameterProposalWidthRealizer unaryMarkersRealizer) + +attribute [local irreducible] scheduledMatrixParameters + +lemma work_scheduledMatrixParameters : + WorkBound scheduledMatrixParametersRealizer scheduledCountInputMeasure := by + unfold scheduledMatrixParametersRealizer scheduledMatrixParameters + have hm : WorkBound (composition parameterProposalWidthRealizer unaryMarkersRealizer) + scheduledCountInputMeasure := by + apply work_composition (work_of_polynomial polynomial_parameterProposalWidth X + weight_le_scheduledCountInputMeasure) work_unaryMarkers X + intro z + simp only [id_eq,eval_X,scheduledCountInputMeasure] + omega + exact work_pair (work_of_polynomial polynomial_scheduledCacheParameters X + weight_le_scheduledCountInputMeasure) hm X weight_le_scheduledCountInputMeasure + +def scheduledStartIndex (z : SamplingParameters) : ℕ := profileBoxIndex (initialCheck z.1) + +def scheduledStartIndexRealizer : Realizer scheduledStartIndex := + composition (composition (f := fun z : SamplingParameters => z.1) (g := initialCheck) first initialCheckRealizer) profileBoxIndexRealizer + +lemma polynomial_scheduledStartIndex : PolynomialTime scheduledStartIndexRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_initialCheck) + polynomial_profileBoxIndex + +def scheduledWalkInput (z : SamplingParameters) : WalkCountInput := + (scheduledMatrixParameters z,(parameterSteps z,scheduledStartIndex z)) + +def scheduledWalkInputRealizer : Realizer scheduledWalkInput := + pair scheduledMatrixParametersRealizer (pair parameterStepsRealizer scheduledStartIndexRealizer) + +attribute [local irreducible] scheduledWalkInput + +lemma work_scheduledWalkInput : WorkBound scheduledWalkInputRealizer scheduledCountInputMeasure := by + unfold scheduledWalkInputRealizer scheduledWalkInput + exact work_pair work_scheduledMatrixParameters + (work_of_polynomial (polynomial_pair polynomial_parameterSteps polynomial_scheduledStartIndex) + X weight_le_scheduledCountInputMeasure) X weight_le_scheduledCountInputMeasure + +def scheduledTrialInput (z : SamplingParameters) : TrialVectorInput := (scheduledWalkInput z,z.1) + +def scheduledTrialInputRealizer : Realizer scheduledTrialInput := pair scheduledWalkInputRealizer first + +attribute [local irreducible] scheduledTrialInput + +lemma work_scheduledTrialInput : WorkBound scheduledTrialInputRealizer scheduledCountInputMeasure := by + unfold scheduledTrialInputRealizer scheduledTrialInput + exact work_pair work_scheduledWalkInput (work_of_polynomial polynomial_first X + weight_le_scheduledCountInputMeasure) X weight_le_scheduledCountInputMeasure + +def scheduledTrialDenominator (z : SamplingParameters) : ℕ := + BinaryPowerPrograms.power (2,scheduledTrialWidth z) + +def scheduledTrialDenominatorRealizer : Realizer scheduledTrialDenominator := + composition (f := fun z : SamplingParameters => (2,scheduledTrialWidth z)) + (g := BinaryPowerPrograms.power) + (pair (constant 2) scheduledTrialWidthRealizer) BinaryPowerPrograms.powerRealizer + +attribute [local irreducible] scheduledTrialDenominator + +lemma work_scheduledTrialDenominator : + WorkBound scheduledTrialDenominatorRealizer scheduledCountInputMeasure := by + unfold scheduledTrialDenominatorRealizer scheduledTrialDenominator + apply work_composition (work_of_polynomial + (polynomial_pair (polynomial_constant 2) polynomial_scheduledTrialWidth) + X weight_le_scheduledCountInputMeasure) BinaryPowerPrograms.work_power (X+C (weight (2:ℕ))) + intro z + simp only [eval_add,eval_X,eval_C,scheduledCountInputMeasure] + omega + +def scheduledOuterInput (z : SamplingParameters) : OuterVectorInput := + (scheduledTrialInput z,((unaryMarkers (parameterTrials z),scheduledTrialDenominator z), + GreedyFeasibleTable.listMatrix z.1.1 z.1.2)) + +def scheduledOuterInputRealizer : Realizer scheduledOuterInput := + pair scheduledTrialInputRealizer + (pair (pair (composition (f := parameterTrials) (g := unaryMarkers) + parameterTrialsRealizer unaryMarkersRealizer) scheduledTrialDenominatorRealizer) + (composition (f := fun z : SamplingParameters => z.1) + (g := fun p => GreedyFeasibleTable.listMatrix p.1 p.2) first GreedyFeasibleTable.tableRealizer)) + +attribute [local irreducible] scheduledOuterInput + +lemma work_scheduledOuterInput : WorkBound scheduledOuterInputRealizer scheduledCountInputMeasure := by + unfold scheduledOuterInputRealizer scheduledOuterInput + have hm : WorkBound (composition parameterTrialsRealizer unaryMarkersRealizer) + scheduledCountInputMeasure := by + apply work_composition (work_of_polynomial polynomial_parameterTrials X + weight_le_scheduledCountInputMeasure) work_unaryMarkers X + intro z + simp only [id_eq,eval_X,scheduledCountInputMeasure] + omega + exact work_pair work_scheduledTrialInput + (work_pair (work_pair hm work_scheduledTrialDenominator X weight_le_scheduledCountInputMeasure) + (work_of_polynomial (polynomial_composition polynomial_first GreedyFeasibleTable.polynomial_table) + X weight_le_scheduledCountInputMeasure) X weight_le_scheduledCountInputMeasure) + X weight_le_scheduledCountInputMeasure + +/-- All first-success numerators, computed from the public binary margins. -/ +def scheduledCounts (z : SamplingParameters) : List ℕ := + if hasLargeRectangle z then outerVector (scheduledOuterInput z) + else UnitCountPrograms.outerVector (scheduledOuterInput z) + +def scheduledCountsRealizer : Realizer scheduledCounts := + choose hasLargeRectangleRealizer + (composition (f := scheduledOuterInput) (g := outerVector) + scheduledOuterInputRealizer outerVectorRealizer) + (composition (f := scheduledOuterInput) (g := UnitCountPrograms.outerVector) + scheduledOuterInputRealizer UnitCountPrograms.outerVectorRealizer) + +attribute [local irreducible] scheduledCounts + +def scheduledCountsMeasure (z : SamplingParameters) : ℕ := scheduledCountInputMeasure z+ + outerVectorMeasure (scheduledOuterInput z)+UnitCountPrograms.outerVectorMeasure (scheduledOuterInput z) + +lemma work_scheduledCounts : WorkBound scheduledCountsRealizer scheduledCountsMeasure := by + have hi (z : SamplingParameters) : scheduledCountInputMeasure z ≤ X.eval (scheduledCountsMeasure z) := by + simp only [eval_X,scheduledCountsMeasure] + omega + have hb := work_remeasure work_scheduledOuterInput X hi + have hw (z : SamplingParameters) : weight z ≤ X.eval (scheduledCountsMeasure z) := + (weight_le_scheduledCountInputMeasure z).trans (by simpa only [eval_X] using hi z) + unfold scheduledCountsRealizer scheduledCounts + apply work_choose (work_of_polynomial polynomial_hasLargeRectangle X hw) + · apply work_composition hb work_outerVector X + intro z + simp only [eval_X,scheduledCountsMeasure] + omega + · apply work_composition hb UnitCountPrograms.work_outerVector X + intro z + simp only [eval_X,scheduledCountsMeasure] + omega + · exact hw + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..02d6a0c4db0a807f87a0d72efb99cd1b35ccc2a0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledCountSemantics.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountInput +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxPush +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingAccuracy + +namespace OAI + +/-! # The scheduled executable numerator vector is the public sampler's law -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts OriginalTableBox ResidualMixture FirstSuccess +open scoped BigOperators Classical +noncomputable section +attribute [local irreducible] scheduledTrialDenominator scheduledTrialWidth + scheduledCounts scheduledOuterInput listedOuterCounts unitOuterCounts matrixInput + scheduledTableDraw listedOuterDraw unitCodeOuterDraw + +private lemma dyadic_trialDenom (N s f : ℕ) : + (2:ℕ)^(N*(s+f)+f)=(2^(s+f))^N*2^f := by + rw [pow_add,←pow_mul] + congr 2 + exact Nat.mul_comm _ _ + + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +lemma scheduledTrialDenominator_dense (k : ℕ) + (hlarge : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true) : + scheduledTrialDenominator ((List.ofFn r,List.ofFn c),k)= + (2^(s+25*(d+b+outerAccuracy d b k+1)^62))^(outerSteps d b k)* + 2^(25*(d+b+outerAccuracy d b k+1)^62) := by + rw [scheduledTrialDenominator,BinaryPowerPrograms.power_eq,scheduledTrialWidth,hlarge] + simp only [ite_true,scheduledDenseWidth,parameterSteps_ofFn,parameterProposalWidth_ofFn,parameterCompletionWidth_ofFn] + exact dyadic_trialDenom _ _ _ + +lemma scheduledTrialDenominator_unit (k : ℕ) + (hlarge : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)≠true) : + scheduledTrialDenominator ((List.ofFn r,List.ofFn c),k)=(2^s)^(outerSteps d b k) := by + rw [scheduledTrialDenominator,BinaryPowerPrograms.power_eq,scheduledTrialWidth,ite_eq_right hlarge] + rw [scheduledUnitWidth,parameterSteps_ofFn,parameterProposalWidth_ofFn,←pow_mul,Nat.mul_comm] + +lemma scheduledTrialDenominator_pos (z : SamplingParameters) : 0 Q^(outerTrials d k)) (scheduledTrialDenominator_dense r c k hlarge).symm) + else + (unitOuterCounts r c (computedCellEquiv r c) (allSmall_of_no_large r c k hlarge) + (tableState r c (GreedyFeasibleTable.table r c htotal)) (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.table r c htotal)).rebase + (congrArg (fun Q => Q^(outerTrials d k)) (scheduledTrialDenominator_unit r c k hlarge).symm) + +lemma scheduledDraw_dense (htotal : ∑ i,r i=∑ j,c j) (k : ℕ) + (hlarge : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true) : + scheduledTableDraw r c htotal k= + listedOuterDraw r c (computedCellEquiv r c) + ((hasLargeRectangle_spec r c k).mp hlarge).1 ((hasLargeRectangle_spec r c k).mp hlarge).2 + b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 + (tableState r c (GreedyFeasibleTable.table r c htotal)) (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.table r c htotal) := by + funext bits + unfold scheduledTableDraw + rw [dite_eq_left hlarge] + +lemma scheduledDraw_unit (htotal : ∑ i,r i=∑ j,c j) (k : ℕ) + (hlarge : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)≠true) : + scheduledTableDraw r c htotal k=fun bits => + unitCodeOuterDraw r c (computedCellEquiv r c) (allSmallFibre r c (allSmall_of_no_large r c k hlarge)) + (tableState r c (GreedyFeasibleTable.table r c htotal)) (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.table r c htotal) (prefixWord (unitCodeBits_le r c k) bits) := by + funext bits + unfold scheduledTableDraw + rw [dite_eq_right hlarge] + +lemma scheduledCountsLaw_law (htotal : ∑ i,r i=∑ j,c j) (k : ℕ) : + (scheduledCountsLaw r c htotal k).toRational + (pow_pos (scheduledTrialDenominator_pos _) _)= + mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c k) → Bool)) + (scheduledTableDraw r c htotal k) := by + unfold scheduledCountsLaw + split_ifs with hlarge + · rw [scheduledDraw_dense r c htotal k hlarge] + exact (IntegerLaw.toRational_rebase _ _ (by positivity) _).trans + (listedOuterCounts_law r c _ _ _ _ _ _ htotal _ _ _ _) + · rw [scheduledDraw_unit r c htotal k hlarge] + exact (IntegerLaw.toRational_rebase _ _ (by positivity) _).trans + ((unitOuterCounts_law r c _ htotal _ _ _ _ _).trans + (padded_draw_law (unitCodeBits_le r c k) _).symm) + +/-- Every literal vector entry equals the corresponding embedded table count, +including zero at infeasible matrices in the original bounding box. -/ +lemma scheduledCounts_actual (htotal : ∑ i,r i=∑ j,c j) (k : ℕ) : + scheduledCounts ((List.ofFn r,List.ofFn c),k)= + List.ofFn (((scheduledCountsLaw r c htotal k).push (index r c le_rfl)).count) := by + unfold scheduledCounts + by_cases hlarge : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true + · rw [ite_eq_left hlarge,scheduledOuterInput_code r c htotal] + conv_lhs => rw [scheduledTrialDenominator_dense r c k hlarge] + rw [outerVector_actual r c (computedCellEquiv r c) + ((hasLargeRectangle_spec r c k).mp hlarge).1 ((hasLargeRectangle_spec r c k).mp hlarge).2 + b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 htotal _ _ + (unaryMarkers_length _) _ _ _] + apply congrArg List.ofFn + funext j + rw [OriginalBoxLaw.retry_count_some,OriginalBoxLaw.push_count] + simp only [scheduledCountsLaw,dite_eq_left hlarge,IntegerLaw.rebase,listedOuterCounts] + simp only [IntegerLaw.retry,unaryMarkers_length] + · rw [ite_eq_right hlarge,scheduledOuterInput_code r c htotal] + conv_lhs => rw [scheduledTrialDenominator_unit r c k hlarge] + rw [unit_outerVector_actual r c (computedCellEquiv r c) b (outerAccuracy d b k) + (allSmall_of_no_large r c k hlarge) htotal _ _ (unaryMarkers_length _) _ _ _] + apply congrArg List.ofFn + funext j + rw [OriginalBoxLaw.retry_count_some,OriginalBoxLaw.push_count] + simp only [scheduledCountsLaw,dite_eq_right hlarge,IntegerLaw.rebase,unitOuterCounts] + simp only [IntegerLaw.retry,unaryMarkers_length] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d509801881d6737e6945abc16919dbe6d9f614a9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualLaw.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountSemantics +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledResidualProgram +import OAI.Combinatorics.ContingencyTables.Sampling.CompiledResidualCorrection + +namespace OAI + +/-! # Correctness and positivity of the executed correction vector -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms OriginalTableBox ResidualMixture FirstSuccess CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "D" => correctionPrecision r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +lemma scheduledCounts_domination + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + ∀ X,(1-1/((2^D:ℕ):ℚ))* + ((scheduledCountsLaw r c htotal (2*D)).toRational + (pow_pos (scheduledTrialDenominator_pos _) _)).mass X≤uniformMass (α := Table r c) := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + dsimp only + rw [scheduledCountsLaw_law] + obtain ⟨residual,hr⟩ := scheduled_residual_correction r c hPL hCheeger htotal + intro X + have hn : 0≤(1/(2:ℚ)^D)*residual.mass X := + mul_nonneg (by positivity) (residual.nonnegative X) + simp only [Nat.cast_pow,Nat.cast_ofNat] + linarith [hr X] + +/-- The explicit correction vector is the embedded integer residual law. -/ +theorem scheduledResidualCounts_actual + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + scheduledResidualCounts (((List.ofFn r,List.ofFn c),2*D),2^D)= + List.ofFn ((IntegerResidualCorrection.law (scheduledCountsLaw r c htotal (2*D)) (2^D) + (pow_pos (scheduledTrialDenominator_pos _) _) (by positivity) + (scheduledCounts_domination r c hPL hCheeger htotal)).push (index r c le_rfl)).count := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + dsimp only + unfold scheduledResidualCounts cachedResidualCounts cachedResidualInput scheduledResidualCache + rw [scheduledCounts_actual r c htotal,List.sum_ofFn,(IntegerLaw.push _ _).total] + exact OriginalBoxLaw.residualVector_law r c _ (GreedyFeasibleTable.table r c htotal) _ + (pow_pos (scheduledTrialDenominator_pos _) _) (by positivity) + (scheduledCounts_domination r c hPL hCheeger htotal) + +/-- Positive total weight makes the exact weighted rejection loop applicable. -/ +theorem scheduledResidualCounts_sum + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + 0<(scheduledResidualCounts (((List.ofFn r,List.ofFn c),2*D),2^D)).sum := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + rw [scheduledResidualCounts_actual r c hPL hCheeger htotal,List.sum_ofFn,(IntegerLaw.push _ _).total] + exact Nat.mul_pos Fintype.card_pos (pow_pos (scheduledTrialDenominator_pos _) _) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebf174dec09e6139454e9f9225a16bf197bcd326 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledResidualProgram.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountInput +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalResidualVector + +namespace OAI + +/-! # Executing residual weights from margins, precision, and branch denominator -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +attribute [local irreducible] scheduledCounts residualVector originalCandidates originalCardinality + +/-- Ordinary count vector, original margins, and reciprocal branch probability. -/ +abbrev ScheduledResidualCache := List ℕ×(CompletionMargins×ℕ) + +def scheduledResidualCache (z : SamplingParameters×ℕ) : ScheduledResidualCache := + (scheduledCounts z.1,(z.1.1,z.2)) + +def scheduledResidualCacheRealizer : Realizer scheduledResidualCache := + pair (composition (f := fun z : SamplingParameters×ℕ => z.1) (g := scheduledCounts) + first scheduledCountsRealizer) (pair (composition first first) second) + +def scheduledResidualMeasure (z : SamplingParameters×ℕ) : ℕ := + scheduledCountsMeasure z.1+originalEnumerationMeasure z.1.1+weight z + +lemma work_scheduledResidualCache : + WorkBound scheduledResidualCacheRealizer scheduledResidualMeasure := by + have hi (z : SamplingParameters×ℕ) : weight z ≤ X.eval (scheduledResidualMeasure z) := by + simp only [eval_X,scheduledResidualMeasure] + omega + have hc : WorkBound (composition (first (B := ℕ)) scheduledCountsRealizer) + scheduledResidualMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_scheduledCounts X + intro z + simp only [eval_X,scheduledResidualMeasure] + omega + exact work_pair hc (work_of_polynomial (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) X hi) X hi + +def cachedResidualInput (z : ScheduledResidualCache) : ResidualVectorCache := + ((originalCandidates z.2.1,z.1),((z.1.sum,z.2.2),originalCardinality z.2.1)) + +def cachedResidualInputRealizer : Realizer cachedResidualInput := + pair (pair (composition (f := fun z : ScheduledResidualCache => z.2.1) (g := originalCandidates) + (composition second first) originalCandidatesRealizer) first) + (pair (pair (composition first listSum) (composition second second)) + (composition (f := fun z : ScheduledResidualCache => z.2.1) (g := originalCardinality) + (composition second first) originalCardinalityRealizer)) + +def cachedResidualMeasure (z : ScheduledResidualCache) : ℕ := + originalEnumerationMeasure z.2.1+weight z + +lemma work_cachedResidualInput : WorkBound cachedResidualInputRealizer cachedResidualMeasure := by + have hi (z : ScheduledResidualCache) : weight z ≤ X.eval (cachedResidualMeasure z) := by + simp only [eval_X,cachedResidualMeasure] + omega + have he : WorkBound (composition (composition (second (A := List ℕ)) first) + originalCandidatesRealizer) cachedResidualMeasure := by + apply work_composition (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) + X hi) work_originalCandidates X + intro z + simp only [eval_X,cachedResidualMeasure,Function.comp_apply] + omega + have hn : WorkBound (composition (composition (second (A := List ℕ)) first) + originalCardinalityRealizer) cachedResidualMeasure := by + apply work_composition (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) + X hi) work_originalCardinality X + intro z + simp only [eval_X,cachedResidualMeasure,Function.comp_apply] + omega + exact work_pair (work_pair he (work_of_polynomial polynomial_first X hi) X hi) + (work_pair (work_of_polynomial (polynomial_pair + (polynomial_composition polynomial_first polynomial_listSum) + (polynomial_composition polynomial_second polynomial_second)) X hi) hn X hi) X hi + +def cachedResidualCounts (z : ScheduledResidualCache) : List ℕ := + residualVector (cachedResidualInput z) + +def cachedResidualCountsRealizer : Realizer cachedResidualCounts := + composition (f := cachedResidualInput) (g := residualVector) + cachedResidualInputRealizer residualVectorRealizer + +lemma work_cachedResidualCounts : WorkBound cachedResidualCountsRealizer cachedResidualMeasure := + work_then_polynomial work_cachedResidualInput polynomial_residualVector + +attribute [local irreducible] scheduledResidualCache cachedResidualCounts + +/-- This computes the complete correction vector; it asks for no probability oracle. -/ +def scheduledResidualCounts (z : SamplingParameters×ℕ) : List ℕ := + cachedResidualCounts (scheduledResidualCache z) + +def scheduledResidualCountsRealizer : Realizer scheduledResidualCounts := + composition (f := scheduledResidualCache) (g := cachedResidualCounts) + scheduledResidualCacheRealizer cachedResidualCountsRealizer + +lemma work_scheduledResidualCounts : + WorkBound scheduledResidualCountsRealizer scheduledResidualMeasure := by + unfold scheduledResidualCountsRealizer scheduledResidualCounts + obtain ⟨p,hp⟩ := work_scheduledResidualCache + apply work_composition ⟨p,hp⟩ work_cachedResidualCounts (X+p) + intro z + have hw := hp z + simp only [scheduledResidualCache] at hw + simp only [eval_add,eval_X,cachedResidualMeasure,scheduledResidualCache] + have hm : originalEnumerationMeasure z.1.1 ≤ scheduledResidualMeasure z := by + unfold scheduledResidualMeasure + omega + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledScalarBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledScalarBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..a118a72e7d1e6dc15b41669550bfdcf84b5aa206 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/ScheduledScalarBounds.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactInputBounds +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountInput + +namespace OAI + +/-! # Charging scalar tabulation loops to the ordinary sampler's word -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +lemma parameterDimension_pos (z : SamplingParameters) : 0 < parameterDimension z := by + unfold parameterDimension marginDimension + omega + +lemma parameterBinaryLength_pos (z : SamplingParameters) : 0 < parameterBinaryLength z := by + have h := parameterDimension_pos z + unfold parameterBinaryLength marginBinaryLength parameterDimension at * + omega + +lemma parameterSteps_pos (z : SamplingParameters) : 0 < parameterSteps z := by + unfold parameterSteps + exact Nat.mul_pos (pow_pos (parameterDimension_pos z) _) + (pow_pos (by have := parameterBinaryLength_pos z; omega) _) + +lemma parameterTrials_pos (z : SamplingParameters) : 0 < parameterTrials z := by + unfold parameterTrials + exact Nat.mul_pos (pow_pos (parameterDimension_pos z) _) (by omega) + +lemma parameterCompletionWidth_pos (z : SamplingParameters) : 0 < parameterCompletionWidth z := by + unfold parameterCompletionWidth + exact Nat.mul_pos (by decide) (pow_pos (by omega) _) + +lemma parameterDimension_le_steps (z : SamplingParameters) : + parameterDimension z ≤ parameterSteps z := by + have hd : 1 ≤ parameterDimension z := parameterDimension_pos z + have hb : 1 ≤ z.2+parameterBinaryLength z := by have := parameterBinaryLength_pos z; omega + exact (Nat.le_self_pow (by decide : 200 ≠ 0) _).trans (by + unfold parameterSteps + simpa only [Nat.mul_one] using Nat.mul_le_mul_left ((parameterDimension z)^200) + (one_le_pow₀ hb : 1 ≤ (z.2+parameterBinaryLength z)^2)) + +lemma parameterBinaryLength_le_steps (z : SamplingParameters) : + parameterBinaryLength z ≤ parameterSteps z := by + have hd : 1 ≤ (parameterDimension z)^200 := one_le_pow₀ (parameterDimension_pos z) + have hb : parameterBinaryLength z ≤ (z.2+parameterBinaryLength z)^2 := + (Nat.le_add_left _ _).trans (Nat.le_self_pow (by decide) _) + unfold parameterSteps + exact hb.trans (by simpa only [Nat.one_mul] using + Nat.mul_le_mul_right ((z.2+parameterBinaryLength z)^2) hd) + +lemma parameterAccuracy_le_steps (z : SamplingParameters) : + parameterAccuracy z ≤ parameterSteps z := by + unfold parameterAccuracy parameterSteps + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (parameterDimension_pos z) (by decide)) + +theorem schedule_numeric_polynomial : ∃ p : Polynomial ℕ,∀ z, + parameterDimension z+parameterAccuracy z+parameterCompletionWidth z ≤ + p.eval (scheduledCountInputMeasure z) := by + refine ⟨2*X+25*(3*X+1)^62,?_⟩ + intro z + let M := scheduledCountInputMeasure z + have hs : parameterSteps z ≤ M := by unfold M scheduledCountInputMeasure; omega + have hd := (parameterDimension_le_steps z).trans hs + have hb := (parameterBinaryLength_le_steps z).trans hs + have ha := (parameterAccuracy_le_steps z).trans hs + have hf : parameterCompletionWidth z ≤ 25*(3*M+1)^62 := by + unfold parameterCompletionWidth + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _) + simp only [eval_add,eval_mul,eval_pow,eval_ofNat,eval_X,eval_one] + change _ ≤ 2*M+25*(3*M+1)^62 + omega + +lemma scheduledCountInputMeasure_le (z : SamplingParameters) : + scheduledCountInputMeasure z ≤ 4*parameterWordCount z+weight z := by + let N := parameterSteps z + let J := parameterTrials z + let P := parameterProposalWidth z + let F := parameterCompletionWidth z + let A := N*(P+F)+F + have hN : 1 ≤ N := parameterSteps_pos z + have hJ : 1 ≤ J := parameterTrials_pos z + have hF : 1 ≤ F := parameterCompletionWidth_pos z + have hNF : N ≤ N*(P+F) := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left N (show 1 ≤ P+F by omega) + have hPF : P+F ≤ N*(P+F) := by + simpa only [Nat.one_mul] using Nat.mul_le_mul_right (P+F) hN + have hA : 1 ≤ A := by unfold A; omega + have hAW : A ≤ J*A := by + simpa only [Nat.one_mul] using Nat.mul_le_mul_right A hJ + have hJW : J ≤ J*A := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left J hA + have hT : scheduledTrialWidth z ≤ A := by + unfold scheduledTrialWidth scheduledDenseWidth scheduledUnitWidth + change (if hasLargeRectangle z then N*(P+F)+F else N*P) ≤ A + split_ifs + · exact le_rfl + · unfold A + exact (Nat.mul_le_mul_left N (Nat.le_add_right P F)).trans (Nat.le_add_right _ _) + change N+J+P+scheduledTrialWidth z+weight z ≤ 4*(J*A)+weight z + have hNA : N ≤ A := by unfold A; omega + have hPA : P ≤ A := by unfold A; omega + have hnw := hNA.trans hAW + have hpw := hPA.trans hAW + have htw := hT.trans hAW + omega + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms Polynomial +open scoped BigOperators Classical +noncomputable section + +theorem exact_count_input_measure_polynomial : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → + scheduledCountInputMeasure (exactSamplingParameters (List.ofFn r,List.ofFn c)) ≤ + p.eval (Algorithms.samplingSize n r 0) := by + obtain ⟨p,hp⟩ := exact_ordinary_bits_polynomial + obtain ⟨q,hq⟩ := exact_margin_weight_polynomial + obtain ⟨u,hu⟩ := polynomial_exactSamplingParameters + refine ⟨4*p+u.comp q,?_⟩ + intro m n r c htotal + have hw : weight (exactSamplingParameters (List.ofFn r,List.ofFn c)) ≤ + u.eval (q.eval (Algorithms.samplingSize n r 0)) := + (Nat.le_add_left _ _).trans ((hu (List.ofFn r,List.ofFn c)).trans + (polynomial_eval_monotone u (hq m n r c htotal))) + have hb : parameterWordCount (exactSamplingParameters (List.ofFn r,List.ofFn c)) ≤ + p.eval (Algorithms.samplingSize n r 0) := hp m n r c + have hs := scheduledCountInputMeasure_le (exactSamplingParameters (List.ofFn r,List.ofFn c)) + simp only [eval_add,eval_mul,eval_ofNat,eval_comp] + omega + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/SignedFloorProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/SignedFloorProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a36bdc76e14ac0e62e4e499078823a518f1bf3c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/SignedFloorProgram.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Machines.SignedPairProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps +import Mathlib.Data.Rat.Floor + +namespace OAI + +/-! # Binary floor of a signed rational + +Two natural quotients and the comparison of their remainders compute +the exact floor. No loop depends on the numeric numerator or denominator. +-/ + +namespace ContingencyTables.SignedFloorProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped SignedPairProgram + +abbrev Input := Signed×ℕ + +def numeratorQuotient (z : Input) : ℕ := z.1.1/z.2 +def numeratorQuotientRealizer : Realizer numeratorQuotient := + composition (pair (composition first first) second) quotient +lemma polynomial_numeratorQuotient : PolynomialTime numeratorQuotientRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_quotient + +def negativeQuotient (z : Input) : ℕ := z.1.2/z.2 +def negativeQuotientRealizer : Realizer negativeQuotient := + composition (pair (composition first second) second) quotient +lemma polynomial_negativeQuotient : PolynomialTime negativeQuotientRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_quotient + +def carry (z : Input) : Bool := decide (z.1.1%z.2by simp only [floorCode,Function.comp_apply,decide_eq_true_eq]) +theorem polynomial_floorCode : PolynomialTime floorCodeRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 0)) + polynomial_natEqual) (polynomial_constant (0,0)) polynomial_raw) + +lemma raw_value (p n d : ℕ) (hd : 0 simp only [normalize,ForestAffineProgram.signedParts,value] + · omega + · omega + +lemma value_normalize (a : Signed) : value (normalize a)=value a := by + rw [normalize_eq] + exact ForestAffineProgram.signedParts_sub (value a) + +def plusRealizer : Realizer plus := + pair + (composition (pair (composition first first) (composition second first)) add) + (composition (pair (composition first second) (composition second second)) add) + +def negRealizer : Realizer neg := pair second first + +def minusRealizer : Realizer minus := + composition (pair first (composition second negRealizer)) plusRealizer + +def timesRealizer : Realizer times := + pair + (composition (pair + (composition (pair (composition first first) (composition second first)) multiply) + (composition (pair (composition first second) (composition second second)) multiply)) add) + (composition (pair + (composition (pair (composition first first) (composition second second)) multiply) + (composition (pair (composition first second) (composition second first)) multiply)) add) + +def normalizeRealizer : Realizer normalize := + pair subtract (composition (pair second first) subtract) + +lemma polynomial_plus : PolynomialTime plusRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_add) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add) + +lemma polynomial_neg : PolynomialTime negRealizer := + polynomial_pair polynomial_second polynomial_first + +lemma polynomial_minus : PolynomialTime minusRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_neg)) polynomial_plus + +lemma polynomial_times : PolynomialTime timesRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_multiply) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_multiply)) polynomial_add) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_second)) polynomial_multiply) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_first)) polynomial_multiply)) polynomial_add) + +lemma polynomial_normalize : PolynomialTime normalizeRealizer := + polynomial_pair polynomial_subtract + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_subtract) + +def sum (xs : List Signed) : Signed := ((xs.map Prod.fst).sum,(xs.map Prod.snd).sum) + +def sumRealizer : Realizer sum := + pair (composition (map first) listSum) (composition (map second) listSum) + +lemma polynomial_sum : PolynomialTime sumRealizer := + polynomial_pair + (polynomial_composition (polynomial_map polynomial_first) polynomial_listSum) + (polynomial_composition (polynomial_map polynomial_second) polynomial_listSum) + +lemma value_sum (xs : List Signed) : value (sum xs)=(xs.map value).sum := by + induction xs with + | nil => simp [sum,value] + | cons a xs ih => + simp only [sum,List.map_cons,List.sum_cons,value,Nat.cast_add] at * + rw [←ih] + ring + +end ContingencyTables.SignedPairProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/SparseViewMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/SparseViewMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed885c0d0da0476a580326eb23083b0e697c292e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/SparseViewMatrixProgram.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallViewLookupProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram +import OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSCode +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid + +namespace OAI + +/-! # Materializing a sparse retained-cell view in a rectangular matrix -/ + +namespace ContingencyTables.SparseViewMatrixProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial ProfilePrograms DensePrograms + +abbrev Input := (List ℕ × List ℕ) × (List (ℕ × ℕ) × List ℕ) +abbrev RowInput := Input × ℕ + +def entry (z : RowInput × ℕ) : ℕ := lookupView (z.1.1.2,(z.1.2,z.2)) +def entryRealizer : Realizer entry := + composition (f := fun z : RowInput × ℕ => (z.1.1.2,(z.1.2,z.2))) (g := lookupView) + (pair (composition (composition first first) second) + (pair (composition first second) second)) lookupViewRealizer +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_lookupView + +def columns (z : RowInput) : List ℕ := List.range z.1.1.2.length +def columnsRealizer : Realizer columns := + composition (composition (composition (composition first first) second) listLength) range +lemma polynomial_columns : PolynomialTime columnsRealizer := by + apply polynomial_boundedRange (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight z.1.1.2).trans + ((weight_snd z.1.1).trans ((weight_fst z.1).trans (weight_fst z))) + +def row (z : RowInput) : List ℕ := (columns z).map (fun j => entry (z,j)) +def rowRealizer : Realizer row := + composition (pair identity columnsRealizer) (mapWith entryRealizer) +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_columns) + (polynomial_mapWith polynomial_entry) + +def rowIndices (z : Input) : List ℕ := List.range z.1.1.length +def rowIndicesRealizer : Realizer rowIndices := + composition (composition (composition first first) listLength) range +lemma polynomial_rowIndices : PolynomialTime rowIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight z.1.1).trans + ((weight_fst z.1).trans (weight_fst z)) + +def matrix (z : Input) : MatrixCode := (rowIndices z).map (fun i => row (z,i)) +def matrixRealizer : Realizer matrix := + composition (pair identity rowIndicesRealizer) (mapWith rowRealizer) +theorem polynomial_matrix : PolynomialTime matrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_rowIndices) + (polynomial_mapWith polynomial_row) + +theorem matrix_ofFn {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (catalog : List (ℕ × ℕ)) (values : List ℕ) : + matrix ((List.ofFn r,List.ofFn c),(catalog,values))= + matrixCode (fun i : Fin m => fun j : Fin n => + lookupView ((catalog,values),(i.val,j.val))) := by + simp only [matrix,rowIndices,row,columns,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,Function.comp_def,entry,matrixCode] + +end ContingencyTables.SparseViewMatrixProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/TableIndexProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/TableIndexProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..92cc404a2aa9aa99ea2e458f17444bb13e2c7cd4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/TableIndexProgram.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTableCoordinates +import OAI.Combinatorics.ContingencyTables.Dense.GridIndexProgram +import OAI.Combinatorics.ContingencyTables.Transport.IndexedTableLaw + +namespace OAI + +/-! # Computing the position of a table in the completion enumeration -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators Classical + +def tableFreeCoordinates (z : ExponentData) : List ℕ := + (tableFreeCells z).map (fun ij => tableFreeValue (z,ij)) + +def tableFreeCoordinatesRealizer : Realizer tableFreeCoordinates := + composition (pair identity tableFreeCellsRealizer) (mapWith tableFreeValueRealizer) + +lemma polynomial_tableFreeCoordinates : PolynomialTime tableFreeCoordinatesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_tableFreeCells) + (polynomial_mapWith polynomial_tableFreeValue) + +lemma tableFreeCoordinates_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) : + tableFreeCoordinates (tableCoordinatesCode R P d X)= + List.ofFn (fun k : Fin (m*n) => + X.val (some (finProdFinEquiv.symm k).1) (some (finProdFinEquiv.symm k).2)) := by + rw [tableFreeCoordinates,tableFreeCells_code,List.map_ofFn] + apply congrArg List.ofFn + funext k + exact tableFreeValue_code R P d X _ _ + +def tableIndexInput (z : CompletionData) : GridIndexData := + (tableFreeCoordinates (z,0),z.1.1.sum+1) + +def tableIndexInputRealizer : Realizer tableIndexInput := + pair (composition (pair identity (constant 0)) tableFreeCoordinatesRealizer) + (composition (composition (composition first first) listSum) successor) + +lemma polynomial_tableIndexInput : PolynomialTime tableIndexInputRealizer := + polynomial_pair (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_constant 0)) polynomial_tableFreeCoordinates) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_listSum) + polynomial_successor) + +def tableIndex (z : CompletionData) : ℕ := gridIndex (tableIndexInput z) + +def tableIndexRealizer : Realizer tableIndex := + composition tableIndexInputRealizer gridIndexRealizer + +theorem polynomial_tableIndex : PolynomialTime tableIndexRealizer := + polynomial_composition polynomial_tableIndexInput polynomial_gridIndex + +theorem tableIndex_actual {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (X : Table R P) : + tableIndex ((marginCode R,marginCode P),tableOutput X)= + (IndexedTableLaw.index R P (le_refl (∑ i,R i)) X).val := by + unfold tableIndex tableIndexInput + change gridIndex (tableFreeCoordinates (tableCoordinatesCode R P 0 X), + (marginCode R).sum+1)=_ + rw [tableFreeCoordinates_code] + have hsum : (marginCode R).sum=∑ i,R i := by + simp only [marginCode,List.sum_cons,List.sum_ofFn,Fintype.sum_option] + rw [hsum] + change gridIndex (List.ofFn (fun k => + (BoxCompletion.encode R P (le_refl (∑ i,R i)) X k).val),(∑ i,R i)+1)=_ + rw [gridIndex_ofFn] + rfl + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/TightenedInputProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/TightenedInputProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a87a77ee1adc7e243c10d118e37fd1d967fca7d8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/TightenedInputProgram.lean @@ -0,0 +1,228 @@ +import OAI.Combinatorics.ContingencyTables.Machines.EndpointMatrixProgram +import OAI.Combinatorics.ContingencyTables.Transport.ComputedTableTightening +import OAI.Combinatorics.ContingencyTables.Machines.NetworkTableProgram + +namespace OAI + +/-! # Executed endpoint translation and a feasible tightened baseline + +The lower and upper matrices are computed by the endpoint scans. Binary +subtraction updates the capacities and both margins, then the same proved +flow program produces a baseline table in the translated instance. +-/ + +namespace ContingencyTables.TightenedInputProgram + +open MatchingFPRAS.TreeTyped Polynomial ResidualGraphProgram NetworkVertexCode +open scoped BigOperators Classical + +abbrev TranslationInput := Input×NatMatrix +abbrev MarginInput := TranslationInput×ℕ +abbrev CellInput := MarginInput×ℕ + +def rowValue (z : MarginInput) : ℕ := + z.1.1.1.1.getD z.2 0-(z.1.1.2.getD z.2 []).sum +def rowValueRealizer : Realizer rowValue := + composition (pair + (composition (pair (composition (composition (composition first first) first) first) second) + (getDFast 0)) + (composition (composition (pair (composition (composition first first) second) second) + (getDFast [])) listSum)) subtract +lemma polynomial_rowValue : PolynomialTime rowValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_first) + polynomial_second) (polynomial_getDFast 0)) + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) (polynomial_getDFast [])) polynomial_listSum)) + polynomial_subtract + +def columnValue (z : MarginInput) : ℕ := + z.1.1.1.2.getD z.2 0-(BoundedComplementProgram.columnValues (z.1.1,z.2)).sum +def columnValueRealizer : Realizer columnValue := + composition (pair + (composition (pair (composition (composition (composition first first) first) second) second) + (getDFast 0)) + (composition (composition + (pair (composition first first) second) BoundedComplementProgram.columnValuesRealizer) + listSum)) subtract +lemma polynomial_columnValue : PolynomialTime columnValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_second) (polynomial_getDFast 0)) + (polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second) + BoundedComplementProgram.polynomial_columnValues) polynomial_listSum)) polynomial_subtract + +def position (z : CellInput) : ℕ×ℕ := (z.1.2,z.2) +def positionRealizer : Realizer position := pair (composition first second) second +lemma polynomial_position : PolynomialTime positionRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second + +def cellValue (z : CellInput) : ℕ := + capacityEntry (z.1.1.2,position z)-capacityEntry (z.1.1.1.2,position z) +def cellValueRealizer : Realizer cellValue := + composition (pair + (composition (pair (composition (composition first first) second) positionRealizer) + capacityEntryRealizer) + (composition (pair (composition (composition (composition first first) first) second) + positionRealizer) capacityEntryRealizer)) subtract +lemma polynomial_cellValue : PolynomialTime cellValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_position) polynomial_capacityEntry) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_position) polynomial_capacityEntry)) polynomial_subtract + +def rowIndices (z : TranslationInput) : List ℕ := BoundedComplementProgram.rowIndices z.1 +def rowIndicesRealizer : Realizer rowIndices := + composition first BoundedComplementProgram.rowIndicesRealizer +lemma polynomial_rowIndices : PolynomialTime rowIndicesRealizer := + polynomial_composition polynomial_first BoundedComplementProgram.polynomial_rowIndices + +def columnIndices (z : TranslationInput) : List ℕ := BoundedComplementProgram.columnIndices z.1 +def columnIndicesRealizer : Realizer columnIndices := + composition first BoundedComplementProgram.columnIndicesRealizer +lemma polynomial_columnIndices : PolynomialTime columnIndicesRealizer := + polynomial_composition polynomial_first BoundedComplementProgram.polynomial_columnIndices + +def capacityRow (z : MarginInput) : List ℕ := + (columnIndices z.1).map (fun j=>cellValue (z,j)) +def capacityRowRealizer : Realizer capacityRow := + composition (pair identity (composition first columnIndicesRealizer)) (mapWith cellValueRealizer) +lemma polynomial_capacityRow : PolynomialTime capacityRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_columnIndices)) + (polynomial_mapWith polynomial_cellValue) + +def translate (z : TranslationInput) : Input := + (((rowIndices z).map (fun i=>rowValue (z,i)), + (columnIndices z).map (fun j=>columnValue (z,j))), + (rowIndices z).map (fun i=>capacityRow (z,i))) +def translateRealizer : Realizer translate := + pair (pair + (composition (pair identity rowIndicesRealizer) (mapWith rowValueRealizer)) + (composition (pair identity columnIndicesRealizer) (mapWith columnValueRealizer))) + (composition (pair identity rowIndicesRealizer) (mapWith capacityRowRealizer)) +lemma polynomial_translate : PolynomialTime translateRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity polynomial_rowIndices) + (polynomial_mapWith polynomial_rowValue)) + (polynomial_composition (polynomial_pair polynomial_identity polynomial_columnIndices) + (polynomial_mapWith polynomial_columnValue))) + (polynomial_composition (polynomial_pair polynomial_identity polynomial_rowIndices) + (polynomial_mapWith polynomial_capacityRow)) + +lemma rowValue_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (l u : Fin m→Fin n→ℕ) (i : Fin m) : + rowValue ((data r c l,natCode u),i.val)=TableTightening.rows r l i := by + simp only [rowValue,data,natCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,dite_true,Option.getD_some,Fin.eta,List.sum_ofFn,TableTightening.rows] + +lemma columnValue_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (l u : Fin m→Fin n→ℕ) (j : Fin n) : + columnValue ((data r c l,natCode u),j.val)=TableTightening.columns c l j := by + simp only [columnValue,BoundedComplementProgram.columnValues,data,natCode,List.map_ofFn, + Function.comp_def,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + j.isLt,dite_true,Option.getD_some,Fin.eta,List.sum_ofFn,TableTightening.columns] + +lemma cellValue_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (l u : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : + cellValue (((data r c l,natCode u),i.val),j.val)=TableTightening.bounds l u i j := by + change capacityEntry (natCode u,(i.val,j.val))-capacityEntry (natCode l,(i.val,j.val))=_ + rw [capacityEntry_code,capacityEntry_code] + rfl + +lemma translate_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (l u : Fin m→Fin n→ℕ) : + translate (data r c l,natCode u)=data (TableTightening.rows r l) + (TableTightening.columns c l) (TableTightening.bounds l u) := by + unfold translate + apply Prod.ext + · apply Prod.ext + · simp only [rowIndices,BoundedComplementProgram.rowIndices,data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact rowValue_code r c l u i + · simp only [columnIndices,BoundedComplementProgram.columnIndices,data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn] + apply congrArg List.ofFn + funext j + exact columnValue_code r c l u j + · simp only [rowIndices,BoundedComplementProgram.rowIndices,data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn,natCode] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply] + simp only [capacityRow,columnIndices,BoundedComplementProgram.columnIndices,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn] + apply congrArg List.ofFn + funext j + exact cellValue_code r c l u i j + +def prepare (z : Input) : TranslationInput := + ((z.1,EndpointMatrixProgram.lowerMatrix z),EndpointMatrixProgram.upperMatrix z) +def prepareRealizer : Realizer prepare := + pair (pair first EndpointMatrixProgram.lowerMatrixRealizer) EndpointMatrixProgram.upperMatrixRealizer +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair polynomial_first EndpointMatrixProgram.polynomial_lowerMatrix) + EndpointMatrixProgram.polynomial_upperMatrix + +def compute (z : Input) : Input := translate (prepare z) +def computeRealizer : Realizer compute := + composition (f:=prepare) (g:=translate) prepareRealizer translateRealizer +lemma polynomial_compute : PolynomialTime computeRealizer := + polynomial_composition polynomial_prepare polynomial_translate + +lemma compute_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + compute (data r c b)=data (ComputedTableTightening.newRows r c b) + (ComputedTableTightening.newColumns r c b) (ComputedTableTightening.newBounds r c b) := by + unfold compute prepare + rw [EndpointMatrixProgram.lowerMatrix_code,EndpointMatrixProgram.upperMatrix_code] + exact translate_code r c (ComputedTableTightening.lower r c b) (ComputedTableTightening.upper r c b) + +def baseline (z : Input) : NatMatrix := NetworkTableProgram.output (compute z) +def baselineRealizer : Realizer baseline := + composition (f:=compute) (g:=NetworkTableProgram.output) computeRealizer NetworkTableProgram.outputRealizer +lemma polynomial_baseline : PolynomialTime baselineRealizer := + polynomial_composition polynomial_compute NetworkTableProgram.polynomial_output + +/-- Endpoint translation preserves a concrete feasible witness. -/ +theorem translated_nonempty {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) : + ∃ Y,HasMargins Y (ComputedTableTightening.newRows r c b) + (ComputedTableTightening.newColumns r c b) ∧ + ∀ i j,Y i j≤ComputedTableTightening.newBounds r c b i j := by + obtain ⟨X,hX⟩ := hne + let x : BoundedTable r c b := ⟨⟨X,hX.1⟩,hX.2⟩ + let y := ComputedTableTightening.tighten hEK r c b ⟨X,hX⟩ x + exact ⟨y.val.val,y.val.property,y.property⟩ + +/-- The stored baseline comes from the executed flow decoder, with all +its margin and capacity obligations discharged by endpoint translation. -/ +theorem baseline_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) : + ∃ Y,baseline (data r c b)=natCode Y ∧ + HasMargins Y (ComputedTableTightening.newRows r c b) + (ComputedTableTightening.newColumns r c b) ∧ + ∀ i j,Y i j≤ComputedTableTightening.newBounds r c b i j := by + have ht := (NetworkFeasibilityProgram.test_correct hEK + (ComputedTableTightening.newRows r c b) + (ComputedTableTightening.newColumns r c b) + (ComputedTableTightening.newBounds r c b)).mpr (translated_nonempty hEK r c b hne) + have h := NetworkTableProgram.output_correct hEK + (ComputedTableTightening.newRows r c b) + (ComputedTableTightening.newColumns r c b) + (ComputedTableTightening.newBounds r c b) ht + simpa only [baseline,compute_code] using h + +end ContingencyTables.TightenedInputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/TransitionCacheRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/TransitionCacheRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..304178cd46d5c314beec0b487efee71d79a7a220 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/TransitionCacheRuntime.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PreparedTransitionCache + +namespace OAI + +/-! # Work bounds for cached completion multiplicities -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +attribute [local irreducible] completionMultiplicityRealizer prepareTransitionCacheRealizer + residualParametersRealizer canonicalBitCountRealizer completionWeightsRealizer + residualParameters canonicalBitCount completionWeights + +/-- The cache is charged by the finite completion box and the requested +reserved word length; no random-tape enumeration appears in this measure. -/ +def transitionCacheMeasure (z : TransitionCacheParameters) : ℕ := + z.2+completionWeightMeasure (residualParameters z.1)+weight z + +private lemma weight_le_cacheMeasure (z : TransitionCacheParameters) : + weight z≤transitionCacheMeasure z := by unfold transitionCacheMeasure; omega + +lemma work_completionMultiplicity : + WorkBound completionMultiplicityRealizer transitionCacheMeasure := by + have hu : PolynomialTime + (composition (composition (first (B := ℕ)) residualParametersRealizer) canonicalBitCountRealizer) := + polynomial_composition (polynomial_composition polynomial_first polynomial_residualParameters) + polynomial_canonicalBitCount + have hr := polynomial_composition (polynomial_pair polynomial_second hu) polynomial_subtract + have hp : WorkBound (pair (constant 2) (composition (pair second + (composition (composition first residualParametersRealizer) canonicalBitCountRealizer)) subtract)) + transitionCacheMeasure := + work_of_polynomial (polynomial_pair (polynomial_constant 2) hr) Polynomial.X + (fun z => by simpa using weight_le_cacheMeasure z) + obtain ⟨p,hp'⟩ := hp + unfold completionMultiplicityRealizer + apply work_composition ⟨p,hp'⟩ BinaryPowerPrograms.work_power (Polynomial.X+p) + intro z + have hw := hp' z + simp only [Polynomial.eval_add,Polynomial.eval_X] + change (z.2-canonicalBitCount (residualParameters z.1))+weight (2:ℕ)≤_ + change _+weight (2,z.2-canonicalBitCount (residualParameters z.1))≤ + p.eval (transitionCacheMeasure z) at hw + have ht : weight (2:ℕ)≤weight (2,z.2-canonicalBitCount (residualParameters z.1)) := + weight_fst (2,z.2-canonicalBitCount (residualParameters z.1)) + have hn : z.2-canonicalBitCount (residualParameters z.1)≤transitionCacheMeasure z := by + unfold transitionCacheMeasure + omega + omega + +lemma work_prepareTransitionCache : + WorkBound prepareTransitionCacheRealizer transitionCacheMeasure := by + have hr : WorkBound (composition (first (B := ℕ)) residualParametersRealizer) + transitionCacheMeasure := + work_of_polynomial (polynomial_composition polynomial_first polynomial_residualParameters) + Polynomial.X (fun z => by simpa using weight_le_cacheMeasure z) + have hc : WorkBound (composition (composition first residualParametersRealizer) + completionWeightsRealizer) transitionCacheMeasure := by + apply work_composition hr work_completionWeights Polynomial.X + intro z + simp only [Polynomial.eval_X,transitionCacheMeasure,Function.comp_apply] + omega + have hi : WorkBound (first (A := ResidualParameters) (B := ℕ)) transitionCacheMeasure := + work_of_polynomial polynomial_first Polynomial.X + (fun z => by simpa using weight_le_cacheMeasure z) + unfold prepareTransitionCacheRealizer + exact work_pair hi (work_pair work_completionMultiplicity hc Polynomial.X + (fun z => by simpa using weight_le_cacheMeasure z)) Polynomial.X + (fun z => by simpa using weight_le_cacheMeasure z) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/TranslationDecisionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/TranslationDecisionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4fd871f7dfdf9556e101a1b42e71b89ca0f5408 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/TranslationDecisionProgram.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCompletionProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram +import OAI.Combinatorics.ContingencyTables.Transport.SignedMarginTranslation +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialSemantics + +namespace OAI + +/-! # Binary arithmetic for the completion translation test -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms CompletionTranslation +open scoped BigOperators + +abbrev MarginPair := List ℕ×List ℕ +abbrev TranslationCell := (MarginPair×MarginPair)×(ℕ×ℕ) +abbrev TranslationData := (MarginPair×MarginPair)×MatrixCode + +def starParts (z : MarginPair×(ℕ×ℕ)) : ℕ×ℕ := + completionParts ((z.1,[]),z.2) + +def starPartsRealizer : Realizer starParts := + composition (pair (pair first (constant [])) second) completionPartsRealizer + +theorem polynomial_starParts : PolynomialTime starPartsRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair polynomial_first (polynomial_constant [])) polynomial_second) + polynomial_completionParts + +def translationParts (z : TranslationCell) : ℕ×ℕ := + let old := starParts (z.1.1,z.2) + let new := starParts (z.1.2,z.2) + (new.1+old.2,new.2+old.1) + +def translationPartsRealizer : Realizer translationParts := by + let old : Realizer (fun z : TranslationCell => starParts (z.1.1,z.2)) := + composition (f := fun z : TranslationCell => (z.1.1,z.2)) (g := starParts) + (pair (composition first first) second) starPartsRealizer + let new : Realizer (fun z : TranslationCell => starParts (z.1.2,z.2)) := + composition (f := fun z : TranslationCell => (z.1.2,z.2)) (g := starParts) + (pair (composition first second) second) starPartsRealizer + exact pair (composition (pair (composition new first) (composition old second)) add) + (composition (pair (composition new second) (composition old first)) add) + +theorem polynomial_translationParts : PolynomialTime translationPartsRealizer := by + have ho : PolynomialTime (composition (pair (composition + (first (A := MarginPair×MarginPair) (B := ℕ×ℕ)) first) second) starPartsRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_starParts + have hn : PolynomialTime (composition (pair (composition + (first (A := MarginPair×MarginPair) (B := ℕ×ℕ)) second) second) starPartsRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_starParts + unfold translationPartsRealizer + exact polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition hn polynomial_first) + (polynomial_composition ho polynomial_second)) polynomial_add) + (polynomial_composition (polynomial_pair (polynomial_composition hn polynomial_second) + (polynomial_composition ho polynomial_first)) polynomial_add) + +def translatedCell (z : TranslationData×(ℕ×ℕ)) : Bool := + let p := translationParts (z.1.1,z.2) + decide (p.2 ≤ matrixEntry (z.1.2,z.2)+p.1) + +def translatedCellRealizer : Realizer translatedCell := by + let parts : Realizer (fun z : TranslationData×(ℕ×ℕ) => translationParts (z.1.1,z.2)) := + composition (pair (composition first first) second) translationPartsRealizer + let entry : Realizer (fun z : TranslationData×(ℕ×ℕ) => matrixEntry (z.1.2,z.2)) := + composition (pair (composition first second) second) matrixEntryRealizer + exact composition (pair (composition parts second) + (composition (pair entry (composition parts first)) add)) leNat + +theorem polynomial_translatedCell : PolynomialTime translatedCellRealizer := by + have hp : PolynomialTime (composition (pair (composition + (first (A := TranslationData) (B := ℕ×ℕ)) first) second) translationPartsRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_translationParts + have he : PolynomialTime (composition (pair (composition + (first (A := TranslationData) (B := ℕ×ℕ)) second) second) matrixEntryRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_matrixEntry + unfold translatedCellRealizer + exact polynomial_composition (polynomial_pair (polynomial_composition hp polynomial_second) + (polynomial_composition (polynomial_pair he (polynomial_composition hp polynomial_first)) + polynomial_add)) polynomial_leNat + +def translationValid (z : TranslationData) : Bool := + (cellPairs z.1.1).all (fun ij => translatedCell (z,ij)) + +def translationValidRealizer : Realizer translationValid := + (composition (composition (pair identity (composition (composition first first) cellPairsRealizer)) + (mapWith translatedCellRealizer)) all).congr + (by intro z; simp only [Function.comp_apply,Function.comp_def,List.all_map,id_eq,translationValid]) + +theorem polynomial_translationValid : PolynomialTime translationValidRealizer := + polynomial_congr _ (polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_cellPairs)) (polynomial_mapWith polynomial_translatedCell)) polynomial_all) + +lemma starParts_code {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (i : Option (Fin m)) (j : Option (Fin n)) : + ((starParts ((marginCode R,marginCode P),(optionIndex i,optionIndex j))).1:ℤ)- + (starParts ((marginCode R,marginCode P),(optionIndex i,optionIndex j))).2= + CompletionTranslation.star (fun i => (R i:ℤ)) (fun j => (P j:ℤ)) i j := by + cases i <;> cases j <;> + simp [starParts,completionParts,optionIndex,marginCode,List.sum_ofFn, + matrixTotal,rowTotal,columnTotal,matrixEntry,CompletionTranslation.star] + +lemma translationParts_code {m n : ℕ} + (R₀ R₁ : Option (Fin m) → ℕ) (P₀ P₁ : Option (Fin n) → ℕ) + (i : Option (Fin m)) (j : Option (Fin n)) : + let p := translationParts (((marginCode R₀,marginCode P₀),(marginCode R₁,marginCode P₁)), + (optionIndex i,optionIndex j)) + (p.1:ℤ)-p.2=between R₀ R₁ P₀ P₁ i j := by + have h₀ := starParts_code R₀ P₀ i j + have h₁ := starParts_code R₁ P₁ i j + dsimp only [translationParts] + simp only [Nat.cast_add] + rw [show between R₀ R₁ P₀ P₁ i j= + CompletionTranslation.star (fun i => (R₁ i:ℤ)) (fun j => (P₁ j:ℤ)) i j- + CompletionTranslation.star (fun i => (R₀ i:ℤ)) (fun j => (P₀ j:ℤ)) i j by + cases i <;> cases j <;> simp only [between,CompletionTranslation.star,Finset.sum_sub_distrib] <;> omega] + omega + +lemma tableOutput_entry {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (X : Table R P) (i : Option (Fin m)) (j : Option (Fin n)) : + matrixEntry (tableOutput X,(optionIndex i,optionIndex j))=X.val i j := by + have hi : optionIndex i=((finSuccEquiv m).symm i).val := by + cases i <;> simp only [optionIndex,finSuccEquiv_symm_none,finSuccEquiv_symm_some, + Fin.val_zero,Fin.val_succ] + have hj : optionIndex j=((finSuccEquiv n).symm j).val := by + cases j <;> simp only [optionIndex,finSuccEquiv_symm_none,finSuccEquiv_symm_some, + Fin.val_zero,Fin.val_succ] + rw [hi,hj] + unfold tableOutput + rw [matrixEntry_code] + simp only [Equiv.apply_symm_apply] + +/-- Each binary comparison is the literal translated nonnegativity +condition in the Markov-chain acceptance decision. -/ +theorem translatedCell_code {m n : ℕ} + (R₀ R₁ : Option (Fin m) → ℕ) (P₀ P₁ : Option (Fin n) → ℕ) + (X : Table R₀ P₀) (i : Option (Fin m)) (j : Option (Fin n)) : + translatedCell ((((marginCode R₀,marginCode P₀),(marginCode R₁,marginCode P₁)), + tableOutput X),(optionIndex i,optionIndex j))=true ↔ + 0 ≤ (X.val i j:ℤ)+between R₀ R₁ P₀ P₁ i j := by + have hp := translationParts_code R₀ R₁ P₀ P₁ i j + dsimp only at hp + simp only [translatedCell,decide_eq_true_eq,tableOutput_entry] + omega + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/VectorRetryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/VectorRetryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5456337b176d9a5cee018b41785750716c749f0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/VectorRetryProgram.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Machines.RetryNumeratorProgram + +namespace OAI + +/-! # First-success propagation of an entire vector of integer counts -/ + +namespace ContingencyTables.VectorRetryPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators + +/-- Trial marker, denominator, success counts, fallback index. -/ +abbrev Input := (List Bool×ℕ)×(List ℕ×ℕ) + +def failure (z : Input) : ℕ := z.1.2-z.2.1.sum + +def failureRealizer : Realizer failure := + composition (pair (composition first second) + (composition (composition second first) listSum)) subtract + +lemma polynomial_failure : PolynomialTime failureRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_listSum)) polynomial_subtract + +def entryInput (z : Input×ℕ) : RetryNumeratorPrograms.Input := + (z.1.1.1,((z.1.1.2,failure z.1),(z.1.2.1.getD z.2 0,decide (z.2=z.1.2.2)))) + +def entryInputRealizer : Realizer entryInput := by + let markers : Realizer (fun z : Input×ℕ => z.1.1.1) := + composition (composition first first) first + let denominator : Realizer (fun z : Input×ℕ => z.1.1.2) := + composition (composition first first) second + let success : Realizer (fun z : Input×ℕ => z.1.2.1.getD z.2 0) := + composition (pair (composition (composition first second) first) second) (getDFast 0) + let hit : Realizer (fun z : Input×ℕ => decide (z.2=z.1.2.2)) := + composition (pair second (composition (composition first second) second)) natEqual + exact pair markers (pair (pair denominator (composition first failureRealizer)) (pair success hit)) + +lemma polynomial_entryInput : PolynomialTime entryInputRealizer := by + unfold entryInputRealizer + exact polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_failure)) + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_second) (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_natEqual))) + +def indices (z : Input) : List ℕ := List.range z.2.1.length + +def indicesRealizer : Realizer indices := + composition (composition (composition second first) listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition + polynomial_second polynomial_first) polynomial_listLength) Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.2.1).trans ((weight_fst z.2).trans (weight_snd z)) + +def counts (z : Input) : List ℕ := + (indices z).map (fun j => RetryNumeratorPrograms.count (entryInput (z,j))) + +def countsRealizer : Realizer counts := + composition (pair identity indicesRealizer) + (mapWith (composition entryInputRealizer RetryNumeratorPrograms.countRealizer)) + +/-- Binary vector propagation uses time polynomial in the success-vector +encoding and in the supplied number of trial markers. -/ +theorem polynomial_counts : PolynomialTime countsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith (polynomial_composition polynomial_entryInput + RetryNumeratorPrograms.polynomial_count)) + +lemma failure_ofFn {r Q : ℕ} (p : IntegerLaw (Option (Fin r)) Q) + (xs : List Bool) (fallback : Fin r) : + failure ((xs,Q),(List.ofFn (fun a => p.count (some a)),fallback.val))=p.count none := by + have ht := p.total + rw [Fintype.sum_option] at ht + simp only [failure,List.sum_ofFn] + omega + +theorem counts_actual {r Q : ℕ} (p : IntegerLaw (Option (Fin r)) Q) + (xs : List Bool) (fallback : Fin r) : + counts ((xs,Q),(List.ofFn (fun a => p.count (some a)),fallback.val))= + List.ofFn ((p.retry fallback xs.length).count) := by + unfold counts indices + rw [List.length_ofFn] + apply List.ext_getElem + · simp + · intro j hj _ + have hjr : j Fin.ext h,fun h => congrArg Fin.val h⟩ + simp only [decide_eq_true_eq,hhit] + exact RetryNumeratorPrograms.recurrence_retry p fallback ⟨j,hjr⟩ xs.length + +end ContingencyTables.VectorRetryPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/WeightedArgmaxProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/WeightedArgmaxProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..67747302920a7248ebd1fd89cb47510a09e68a89 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/WeightedArgmaxProgram.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram +import Mathlib.Data.List.MinMax + +namespace OAI + +/-! # Binary scan selecting a greatest weighted edge + +The accumulator is either empty or one stored edge. Its binary size is +bounded by the input list size even when capacities are numerically large. +-/ + +namespace ContingencyTables.WeightedArgmaxProgram + +open MatchingFPRAS.TreeTyped Polynomial + +abbrev Edge := (ℕ×ℕ)×ℕ +abbrev Input := Edge×Option Edge + +def advance (z : Input) : Option Edge := + match z.2 with + | none => Option.some z.1 + | Option.some old => if old.2 + if z.2.2 simp [Function.comp_apply,compareInput,h]) +private lemma polynomial_choose : PolynomialTime chooseRealizer := + polynomial_congr _ (MatchingFPRAS.TreeTyped.polynomial_choose + (polynomial_composition polynomial_compare polynomial_less) + (polynomial_composition polynomial_first polynomial_some) + (polynomial_composition polynomial_second polynomial_some)) + +def advanceRealizer : Realizer advance := + (optionCases some chooseRealizer).congr (by + rintro ⟨e,o⟩ + cases o <;> rfl) +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_congr _ (polynomial_optionCases polynomial_some polynomial_choose) + +private lemma some_weight (e : Edge) : + weight (Option.some e)=1+weight true+weight e := by + change weight (true,e)=_ + exact weight_prod _ _ + +private lemma none_large : 1+weight true≤weight (none : Option Edge) := by decide + +lemma advance_weight (e : Edge) (o : Option Edge) : + weight (advance (e,o))≤weight o+weight e+1 := by + cases o with + | none=> + simp only [advance,some_weight] + have h := none_large + omega + | some a=> + simp only [advance] + split <;> simp only [some_weight] <;> omega + +lemma fold_weight (xs : List Edge) (o : Option Edge) : + weight (xs.foldl (fun o e=>advance (e,o)) o)≤weight o+weight xs := by + induction xs generalizing o with + | nil=>simp only [List.foldl_nil,weight_nil]; omega + | cons e xs ih=> + have h := ih (advance (e,o)) + have hs := advance_weight e o + simp only [List.foldl_cons,weight_cons] + omega + +lemma polynomial_scan : PolynomialTime (fold advanceRealizer) := by + apply polynomial_fold polynomial_advance X + intro xs o pre post he + have hp := weight_prefix he + have hf := fold_weight pre o + simp only [eval_X,weight_prod] + omega + +def best (xs : List Edge) : Option Edge := xs.foldl (fun o e=>advance (e,o)) none +def bestRealizer : Realizer best := + composition (f := fun xs : List Edge=>(xs,(none : Option Edge))) + (g := fun z : List Edge×Option Edge=>z.1.foldl (fun o e=>advance (e,o)) z.2) + (pair identity (constant none)) (fold advanceRealizer) +lemma polynomial_best : PolynomialTime bestRealizer := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant none)) + polynomial_scan + +lemma best_argmax (xs : List Edge) : best xs=xs.argmax Prod.snd := by + have hf : (fun o e=>advance (e,o))= + List.argAux (fun a b : Edge=>b.2 rfl + unfold best List.argmax + rw [hf] + +lemma best_mem {xs : List Edge} {e : Edge} (he : best xs=some e) : e∈xs := by + rw [best_argmax] at he + exact List.argmax_mem he + +lemma best_max {xs : List Edge} {e : Edge} (he : best xs=some e) + {a : Edge} (ha : a∈xs) : a.2≤e.2 := by + rw [best_argmax] at he + exact List.le_of_mem_argmax (f := Prod.snd) ha he + +lemma best_none (xs : List Edge) : best xs=none ↔ xs=[] := by + rw [best_argmax,List.argmax_eq_none] + +end ContingencyTables.WeightedArgmaxProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Main.lean b/lean/OAI/Combinatorics/ContingencyTables/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6bb4c0042e5590ec6d6621bc96ca42cd5d87ff7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Main.lean @@ -0,0 +1,12 @@ +import OAI.Combinatorics.ContingencyTables.FactorialLift +import OAI.Combinatorics.ContingencyTables.UnconditionalMain +/-! +# Sampling and counting contingency tables + +Almost-uniform sampling has polynomial cost on every execution, while +exact uniform sampling has polynomial expected bit cost. Cell-bounded +counting admits a fully polynomial randomized approximation scheme, +including structural zeros and infeasible inputs. The finite-box +Prékopa–Leindler inequality, finite Cheeger inequality and shortest +augmenting path bound supply the analytic and feasibility estimates. +-/ diff --git a/lean/OAI/Combinatorics/ContingencyTables/Model.lean b/lean/OAI/Combinatorics/ContingencyTables/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..752af7a458733e26a31cf1c1bf12a87a9cac8a54 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Model.lean @@ -0,0 +1,154 @@ +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Data.Finset.Pi +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! +# Contingency tables with arbitrary margins + +The feasible sets in result 200 are represented by natural-valued +matrices, without a positivity, balance, or sparsity restriction on +the margins. The finite encoding bound is proved rather than assumed. +-/ + +namespace ContingencyTables + +open Finset + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The row and column equations in both papers. -/ +def HasMargins (X : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) : Prop := + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) + +/-- Unrestricted nonnegative integer tables with the specified margins. -/ +def Table (r : I → ℕ) (c : J → ℕ) := {X : I → J → ℕ // HasMargins X r c} + +/-- The entry constraints for the companion paper, including structural zeros. -/ +def BoundedTable (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) := + {X : Table r c // ∀ i j, X.val i j ≤ b i j} + +theorem totals_equal {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) : ∑ i, r i = ∑ j, c j := by + simp_rw [← h.1, ← h.2] + exact sum_comm + +theorem entry_le_row {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ r i := by + rw [← h.1 i] + exact single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ j) + +theorem entry_le_total {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ ∑ i, r i := + (entry_le_row h i j).trans (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)) + +/-- Binary margins may be large, but the feasible set is finite. -/ +instance table_finite (r : I → ℕ) (c : J → ℕ) : Finite (Table r c) := by + let encode : Table r c → I → J → Fin ((∑ i, r i) + 1) := + fun X i j => ⟨X.val i j, Nat.lt_succ_of_le (entry_le_total X.property i j)⟩ + apply Finite.of_injective encode + intro X Y h + apply Subtype.ext + funext i j + exact congrArg Fin.val (congrFun (congrFun h i) j) + +noncomputable instance table_fintype (r : I → ℕ) (c : J → ℕ) : Fintype (Table r c) := + Fintype.ofFinite _ + +noncomputable instance boundedTable_fintype (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) : + Fintype (BoundedTable r c b) := by + classical + unfold BoundedTable + infer_instance + +/-- The bound used in the exact correction's exhaustive branch. -/ +theorem table_card_le (r : I → ℕ) (c : J → ℕ) : + Fintype.card (Table r c) ≤ ((∑ i, r i) + 1) ^ (Fintype.card I * Fintype.card J) := by + classical + let encode : Table r c → I → J → Fin ((∑ i, r i) + 1) := + fun X i j => ⟨X.val i j, Nat.lt_succ_of_le (entry_le_total X.property i j)⟩ + have hinj : Function.Injective encode := by + intro X Y h + apply Subtype.ext + funext i j + exact congrArg Fin.val (congrFun (congrFun h i) j) + have h := Fintype.card_le_of_injective encode hinj + simpa only [Fintype.card_fun, Fintype.card_fin, ← pow_mul, Nat.mul_comm] using h + +section Existence + +variable [DecidableEq I] [DecidableEq J] + +private theorem sum_decrease_one (r : I → ℕ) (i : I) (hi : 0 < r i) : + (∑ k, Function.update r i (r i - 1) k) + 1 = ∑ k, r k := by + rw [sum_update_of_mem (mem_univ i)] + have hsum := sum_erase_add (univ : Finset I) r (mem_univ i) + simp only [sdiff_singleton_eq_erase] at * + omega + +/-- Equal total nonnegative margins always admit an unrestricted table. +The proof removes one unit at a positive row and a positive column. +It is an existence argument; no polynomial runtime is asserted here. -/ +theorem exists_table (r : I → ℕ) (c : J → ℕ) (htotal : ∑ i, r i = ∑ j, c j) : + ∃ X, HasMargins X r c := by + suffices ∀ N (r : I → ℕ) (c : J → ℕ), + (∑ i, r i) = N → (∑ j, c j) = N → ∃ X, HasMargins X r c by + exact this _ r c rfl htotal.symm + intro N + induction N with + | zero => + intro r c hr hc + refine ⟨fun _ _ => 0, ?_, ?_⟩ + · intro i + have hri := single_le_sum (f := r) (fun _ _ => Nat.zero_le _) (mem_univ i) + rw [hr] at hri + simpa using (Nat.eq_zero_of_le_zero hri).symm + · intro j + have hcj := single_le_sum (f := c) (fun _ _ => Nat.zero_le _) (mem_univ j) + rw [hc] at hcj + simpa using (Nat.eq_zero_of_le_zero hcj).symm + | succ N ih => + intro r c hr hc + obtain ⟨i₀, _, hi₀⟩ := exists_ne_zero_of_sum_ne_zero + (s := (univ : Finset I)) (f := r) (by rw [hr]; exact Nat.succ_ne_zero _) + obtain ⟨j₀, _, hj₀⟩ := exists_ne_zero_of_sum_ne_zero + (s := (univ : Finset J)) (f := c) (by rw [hc]; exact Nat.succ_ne_zero _) + let r' := Function.update r i₀ (r i₀ - 1) + let c' := Function.update c j₀ (c j₀ - 1) + have hr' : ∑ i, r' i = N := by + have h := sum_decrease_one r i₀ (Nat.pos_of_ne_zero hi₀) + dsimp [r'] + omega + have hc' : ∑ j, c' j = N := by + have h := sum_decrease_one c j₀ (Nat.pos_of_ne_zero hj₀) + dsimp [c'] + omega + obtain ⟨X, hXr, hXc⟩ := ih r' c' hr' hc' + refine ⟨fun i j => X i j + if i = i₀ ∧ j = j₀ then 1 else 0, ?_, ?_⟩ + · intro i + rw [sum_add_distrib, hXr i] + by_cases hi : i = i₀ + · subst i + simp only [true_and, sum_ite_eq', mem_univ, ite_true, r', Function.update_self] + omega + · simp [hi, r'] + · intro j + rw [sum_add_distrib, hXc j] + by_cases hj : j = j₀ + · subst j + simp only [and_true, sum_ite_eq', mem_univ, ite_true, c', Function.update_self] + omega + · simp [hj, c'] + +theorem table_nonempty (r : I → ℕ) (c : J → ℕ) (htotal : ∑ i, r i = ∑ j, c j) : + Nonempty (Table r c) := by + obtain ⟨X, hX⟩ := exists_table r c htotal + exact ⟨⟨X, hX⟩⟩ + +end Existence + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Parameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Parameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f5412516b3989831311839bce71fa0ea0d83ed4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Parameters.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.Padding +import OAI.Combinatorics.ContingencyTables.Sampling.ResidualMixture +import Mathlib.Tactic.NormNum + +namespace OAI + +/-! +# Parameter arithmetic for the samplers + +The manuscript's padding and rare tabulation estimates give explicit +inequalities for successful unpadding and expected correction cost. +-/ + +namespace ContingencyTables + +open scoped BigOperators + +private theorem padding_error_le_half (d s : ℕ) (hd : 14 ≤ d) (hs : s ≤ d) : + (s : ℝ) * (4 * (d : ℝ) ^ 12 * (d : ℝ) ^ 3 / (d : ℝ) ^ 20) ≤ 1 / 2 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hd₁₄ : (14 : ℝ) ≤ d := by exact_mod_cast hd + have hs' : (s : ℝ) ≤ d := by exact_mod_cast hs + have hfour : (8 : ℝ) ≤ (d : ℝ) ^ 4 := by + have h := pow_le_pow_left₀ (by norm_num : (0 : ℝ) ≤ 14) hd₁₄ 4 + norm_num at h + linarith + have htwenty : (d : ℝ) ^ 20 = (d : ℝ) ^ 16 * (d : ℝ) ^ 4 := by ring + have hpow : (0 : ℝ) ≤ (d : ℝ) ^ 16 := by positivity + have hlarge := mul_le_mul_of_nonneg_left hfour hpow + have hnum : 8 * (s : ℝ) * (d : ℝ) ^ 12 * (d : ℝ) ^ 3 ≤ (d : ℝ) ^ 20 := by + calc + _ ≤ 8 * (d : ℝ) * (d : ℝ) ^ 12 * (d : ℝ) ^ 3 := by gcongr + _ = 8 * (d : ℝ) ^ 16 := by ring + _ ≤ (d : ℝ) ^ 20 := by rw [htwenty]; linarith + rw [← mul_div_assoc, div_le_iff₀ (pow_pos hd₀ 20)] + nlinarith + +/-- For the actual choices `L=d¹²`, `U=d²⁰`, the uniform padded table +unpads successfully with probability at least one half. -/ +theorem padding_success_half {I J : Type*} [Fintype I] [Fintype J] + [DecidableEq I] [DecidableEq J] + (r : I → ℕ) (c : J → ℕ) (htotal : ∑ i, r i = ∑ j, c j) + (K : Finset (I × J)) (d : ℕ) (hd : 14 ≤ d) + (hrows : Fintype.card I ≤ d) (hcols : Fintype.card J ≤ d) + (hK : K.card ≤ d) (hrow : ∀ p ∈ K, d ^ 20 ≤ r p.1) + (hcol : ∀ p ∈ K, d ^ 20 ≤ c p.2) : + (1 / 2 : ℝ) ≤ (Fintype.card (Table r c) : ℝ) / + Fintype.card (Table (paddedRows r (largePadding K (d ^ 12))) + (paddedColumns c (largePadding K (d ^ 12)))) := by + have hd₀ : 0 < d := by omega + have hU : 4 * d ≤ d ^ 20 := by + have hd₄ : 4 ≤ d := by omega + have hpow : d ≤ d ^ 19 := Nat.le_self_pow (by decide) d + calc + 4 * d ≤ d * d ^ 19 := Nat.mul_le_mul hd₄ hpow + _ = d ^ 20 := by ring + have hL : 2 * d ^ 12 ≤ d ^ 20 := by + have hpow : d ≤ d ^ 8 := Nat.le_self_pow (by decide) d + have hd₂ : 2 ≤ d ^ 8 := by omega + calc + 2 * d ^ 12 ≤ d ^ 8 * d ^ 12 := Nat.mul_le_mul_right _ hd₂ + _ = d ^ 20 := by ring + have h := padding_success_fraction r c htotal K (d ^ 12) (d ^ 20) d + hd₀ hrows hcols hrow hcol hU hL + have he := padding_error_le_half d K.card hd hK + push_cast at h + linarith + +/-- The exponentially costly exact tabulation branch has exponentially +smaller probability for the manuscript's `D=d⁶b²`. -/ +theorem rare_tabulation_exponent (d b : ℕ) (hd : 14 ≤ d) (_hb : 1 ≤ b) : + 500 * d * b ≤ d ^ 6 * b ^ 2 := by + have hfive : 500 ≤ d ^ 5 := by + have h := Nat.pow_le_pow_left hd 5 + norm_num at h + omega + have hb₂ : b ≤ b ^ 2 := Nat.le_self_pow (by decide) b + calc + 500 * d * b ≤ d ^ 5 * d * b := Nat.mul_le_mul_right b (Nat.mul_le_mul_right d hfive) + _ = d ^ 6 * b := by ring + _ ≤ d ^ 6 * b ^ 2 := Nat.mul_le_mul_left _ hb₂ + +theorem rare_tabulation_cost (d b : ℕ) (hd : 14 ≤ d) (hb : 1 ≤ b) : + (2 : ℚ) ^ (500 * d * b) / (2 : ℚ) ^ (d ^ 6 * b ^ 2) ≤ 1 := by + apply (div_le_one (by positivity)).mpr + exact pow_le_pow_right₀ (by norm_num) (rare_tabulation_exponent d b hd hb) + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/PublishedInputs.lean b/lean/OAI/Combinatorics/ContingencyTables/PublishedInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..dce230d3ab2890346a50bf30cc079f9c3656eca7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/PublishedInputs.lean @@ -0,0 +1,87 @@ +import Mathlib.MeasureTheory.Integral.Bochner.Set +import Mathlib.MeasureTheory.Measure.Lebesgue.Basic +import Mathlib.MeasureTheory.Constructions.Pi +import Mathlib.Analysis.SpecialFunctions.Pow.Real + +namespace OAI + +/-! +# The published analytic input for result 200 + +Prékopa, *On logarithmic concave measures and functions*, Acta Sci. Math. +(Szeged) 34 (1973), 335–343, Theorem 3, equation (2.3), with two source +functions. Source: https://acta.bibl.u-szeged.hu/14411/1/math_034_335-343.pdf +The one-dimensional input is Leindler (1972), *On a certain converse of +Hölder's inequality II*, 217–223, as identified in Prékopa's §2. + +The finite-box specialization allows positive continuous functions on a +common compact coordinate box and finite unions of open boxes. +-/ + +namespace ContingencyTables.PublishedInputs + +open MeasureTheory + +abbrev Point (q : ℕ) := Fin q → ℝ + +/-- The bounded finite unions of open coordinate boxes used by the bin +conductance argument. Empty unions and empty coordinate boxes are allowed. -/ +def IsFiniteBoxUnion {q : ℕ} (S : Set (Point q)) : Prop := + ∃ (n : ℕ) (lower upper : Fin n → Point q), + S = {x | ∃ k : Fin n, ∀ i, lower k i < x i ∧ x i < upper k i} + +/-- The weighted Minkowski interpolation with the manuscript convention. -/ +def interpolate {q : ℕ} (t : ℝ) (S T : Set (Point q)) : Set (Point q) := + {z | ∃ x ∈ S, ∃ y ∈ T, z = (1 - t) • x + t • y} + +/-- Precisely the previously published finite-box integral interpolation +input. The functions need only be positive and continuous on the common +compact coordinate box; all integrals are Lebesgue integrals. -/ +def FiniteBoxPrekopaLeindler (q : ℕ) : Prop := + ∀ (t : ℝ), 0 < t → t < 1 → + ∀ (lower upper : Point q) (S₀ S₁ S₂ : Set (Point q)) + (f₀ f₁ f₂ : Point q → ℝ), + IsFiniteBoxUnion S₀ → IsFiniteBoxUnion S₁ → IsFiniteBoxUnion S₂ → + closure S₀ ⊆ Set.Icc lower upper → + closure S₁ ⊆ Set.Icc lower upper → + closure S₂ ⊆ Set.Icc lower upper → + ContinuousOn f₀ (Set.Icc lower upper) → + ContinuousOn f₁ (Set.Icc lower upper) → + ContinuousOn f₂ (Set.Icc lower upper) → + (∀ x ∈ Set.Icc lower upper, 0 < f₀ x) → + (∀ x ∈ Set.Icc lower upper, 0 < f₁ x) → + (∀ x ∈ Set.Icc lower upper, 0 < f₂ x) → + interpolate t S₁ S₂ ⊆ S₀ → + (∀ x ∈ S₁, ∀ y ∈ S₂, + (f₁ x) ^ (1 - t) * (f₂ y) ^ t ≤ f₀ ((1 - t) • x + t • y)) → + (∫ x in S₁, f₁ x) ^ (1 - t) * (∫ y in S₂, f₂ y) ^ t ≤ + ∫ z in S₀, f₀ z + +/-- Log-concavity is needed only on the common ambient box. -/ +def LogConcaveOn {q : ℕ} (ρ : Point q → ℝ) (K : Set (Point q)) : Prop := + ∀ x ∈ K, ∀ y ∈ K, ∀ t : ℝ, 0 < t → t < 1 → + (ρ x) ^ (1 - t) * (ρ y) ^ t ≤ ρ ((1 - t) • x + t • y) + +/-- Specialization of the published input to the one log-concave density +used for bin conductance. The geometric hypotheses specify the common ambient box. -/ +theorem density_interpolation {q : ℕ} (hPL : FiniteBoxPrekopaLeindler q) + (t : ℝ) (ht : 0 < t) (ht1 : t < 1) + (lower upper : Point q) (S T : Set (Point q)) (ρ : Point q → ℝ) + (hS : IsFiniteBoxUnion S) (hT : IsFiniteBoxUnion T) + (hM : IsFiniteBoxUnion (interpolate t S T)) + (hSc : closure S ⊆ Set.Icc lower upper) + (hTc : closure T ⊆ Set.Icc lower upper) + (hMc : closure (interpolate t S T) ⊆ Set.Icc lower upper) + (hρ : ContinuousOn ρ (Set.Icc lower upper)) + (hpos : ∀ x ∈ Set.Icc lower upper, 0 < ρ x) + (hlc : LogConcaveOn ρ (Set.Icc lower upper)) : + (∫ x in S, ρ x) ^ (1 - t) * (∫ y in T, ρ y) ^ t ≤ + ∫ z in interpolate t S T, ρ z := by + apply hPL t ht ht1 lower upper (interpolate t S T) S T ρ ρ ρ + hM hS hT hMc hSc hTc hρ hρ hρ hpos hpos hpos Set.Subset.rfl + intro x hx y hy + exact hlc x (hSc (subset_closure hx)) y (hTc (subset_closure hy)) t ht ht1 + +end ContingencyTables.PublishedInputs + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedForestCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedForestCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3bde43a580ed4f9675d5b565295062a9f35fb75 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedForestCode.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ComputedLargeForest + +namespace OAI + +/-! # The computed forest retains its literal adjacency-list code -/ + +namespace ContingencyTables.ComputedLargeForest +open SimpleGraph MaximumForest ForestCapacity ForestGreedySemantics +open FiniteGraphRootProgram LargeEdgeCatalogProgram +open scoped Classical + +variable {m n : ℕ} + +private lemma code_congr {N : ℕ} (G H : SimpleGraph (Fin N)) + [DecidableRel G.Adj] [DecidableRel H.Adj] (h : G=H) : graphCode G=graphCode H := by + subst H + apply congrArg (@graphCode N G) + exact Subsingleton.elim _ _ + +lemma computed_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (W : ℕ) (hW : 1 ≤ W) : + graphCode ((computed r c b W).comap finSumFinEquiv.symm)= + ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W) := by + obtain ⟨F,hF,_⟩ := iterate_optimal (graph b W) ⊥ (capacities b) + (catalog (NetworkVertexCode.data r c b,W)) (catalog_correct r c b W) + (capacity_positive b W hW) (MaximumForestExchange.bottom_extendible _ _) + ((m+n)*(m+n)) (by + have hb := unordered_pair_budget (n:=m+n) + omega) + have hzero (d : DecidableRel (⊥ : SimpleGraph (Fin (m+n))).Adj) : + @graphCode (m+n) ⊥ d=ForestGreedyProgram.emptyGraph (NetworkVertexCode.data r c b,W) := by + symm + simp only [ForestGreedyProgram.emptyGraph,vertexCount_code,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,graphCode] + apply congrArg List.ofFn + funext v + simp [adjacencyRow] + have hout : ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W)=graphCode F := by + unfold ForestGreedyProgram.forest ForestGreedyProgram.prepare + rw [←hzero (fun a b => Classical.propDecidable _),execute_iterate,graphCode_length] + exact congrArg Prod.fst hF + have hc : (computed r c b W).comap finSumFinEquiv.symm= + decoded (ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W)) := by + ext u v + change (decoded (ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W))).Adj + (vertexEquiv (finSumFinEquiv.symm u)) (vertexEquiv (finSumFinEquiv.symm v)) ↔ _ + simp only [vertexEquiv,Equiv.apply_symm_apply] + have he : (computed r c b W).comap finSumFinEquiv.symm=F := by + simpa only [hout,decoded_graphCode] using hc + exact (code_congr _ _ he).trans hout.symm + +end ContingencyTables.ComputedLargeForest + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedLargeForest.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedLargeForest.lean new file mode 100644 index 0000000000000000000000000000000000000000..b77d00ba497f601e1823588a9c8c654cdcca50dc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedLargeForest.lean @@ -0,0 +1,192 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestGreedySemantics +import OAI.Combinatorics.ContingencyTables.Rooted.ForestCapacity + +namespace OAI + +/-! # The executed maximum-capacity forest on the original cell vertices + +The program uses the concrete row-then-column natural indexing. The +returned adjacency list is decoded and transported back to the original +bipartite vertex type. Its catalog and optimality obligations follow +from the stored capacities, rather than supplied correctness predicates. +-/ + +namespace ContingencyTables.ComputedLargeForest + +open SimpleGraph MaximumForest ForestCapacity ForestGreedySemantics +open FiniteGraphRootProgram LargeEdgeCatalogProgram +open scoped BigOperators Classical + +variable {m n : ℕ} + +abbrev vertexEquiv : (Fin m⊕Fin n) ≃ Fin (m+n) := finSumFinEquiv + +def small (b : Fin m→Fin n→ℕ) (W : ℕ) (i : Fin m) (j : Fin n) : Bool := + decide (b i j + cases d with + | inl k=>exact False.elim h + | inr j=> + left + have hb : W≤b i j := by simpa only [cellGraph,cellAdj,small, + decide_eq_false_iff_not,not_lt] using h + apply (mem_catalog_code r c b W _).mpr + refine ⟨i,j,hb,?_⟩ + rw [capacities_cell] + simp only [vertexEquiv,finSumFinEquiv_apply_left, + finSumFinEquiv_apply_right,Fin.val_castAdd,Fin.val_natAdd] + | inr j=> + cases d with + | inr k=>exact False.elim h + | inl i=> + right + have hb : W≤b i j := by simpa only [cellGraph,cellAdj,small, + decide_eq_false_iff_not,not_lt] using h + apply (mem_catalog_code r c b W _).mpr + refine ⟨i,j,hb,?_⟩ + rw [show s(vertexEquiv (.inr j),vertexEquiv (.inl i))= + s(vertexEquiv (.inl i),vertexEquiv (.inr j)) from Sym2.eq_swap] + rw [capacities_cell] + simp only [vertexEquiv,finSumFinEquiv_apply_left, + finSumFinEquiv_apply_right,Fin.val_castAdd,Fin.val_natAdd] + +lemma capacity_positive (b : Fin m→Fin n→ℕ) (W : ℕ) (hW : 1≤W) : + ∀ e∈(graph b W).edgeSet,0 + obtain ⟨a,rfl⟩ := vertexEquiv.surjective u + obtain ⟨d,rfl⟩ := vertexEquiv.surjective v + have hm := SimpleGraph.map_adj_apply (G:=cellGraph (small b W)) + (f:=vertexEquiv.toEmbedding) (a:=a) (b:=d) + have h : (cellGraph (small b W)).Adj a d := hm.mp he + cases a with + | inl i=> + cases d with + | inl k=>exact False.elim h + | inr j=> + have hb : W≤b i j := by simpa only [cellGraph,cellAdj,small, + decide_eq_false_iff_not,not_lt] using h + rw [capacities_cell b i j] + omega + | inr j=> + cases d with + | inr k=>exact False.elim h + | inl i=> + rw [show s(vertexEquiv (.inr j),vertexEquiv (.inl i))= + s(vertexEquiv (.inl i),vertexEquiv (.inr j)) from Sym2.eq_swap] + have hb : W≤b i j := by simpa only [cellGraph,cellAdj,small, + decide_eq_false_iff_not,not_lt] using h + rw [capacities_cell b i j] + omega + +lemma empty_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (W : ℕ) : + ForestGreedyProgram.emptyGraph (NetworkVertexCode.data r c b,W)= + graphCode (⊥ : SimpleGraph (Fin (m+n))) := by + simp only [ForestGreedyProgram.emptyGraph,vertexCount_code,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,graphCode] + apply congrArg List.ofFn + funext v + simp [adjacencyRow] + +/-- The output list itself determines the forest. -/ +noncomputable def computed (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (W : ℕ) : + SimpleGraph (Fin m⊕Fin n) := + (decoded (ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W))).comap vertexEquiv + +private lemma weight_transport {V U : Type*} [Fintype V] [Fintype U] + (e : V≃U) (G : SimpleGraph V) (b : Sym2 V→ℕ) : + weight (G.map e.toEmbedding) (fun a=>b (Sym2.map e.symm a))=weight G b := by + rw [weight_eq,weight_eq,edgeFinset_map,Finset.sum_map] + apply Finset.sum_congr rfl + intro a _ + change b (Sym2.map e.symm (Sym2.map e a))=b a + congr 1 + induction a using Sym2.inductionOn with + | _ u v=>simp only [Sym2.map_mk,Equiv.symm_apply_apply] + +/-- The executed list program gives a maximum-capacity forest on the +actual row and column vertices. -/ +theorem computed_spec (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (W : ℕ) (hW : 1≤W) : + computed r c b W≤cellGraph (small b W) ∧ (computed r c b W).IsAcyclic ∧ + ∀ F : SimpleGraph (Fin m⊕Fin n),F≤cellGraph (small b W) → F.IsAcyclic → + weight F (capacity b)≤weight (computed r c b W) (capacity b) := by + have ht := execute_optimal (graph b W) ⊥ (capacities b) + (catalog (NetworkVertexCode.data r c b,W)) (catalog_correct r c b W) + (capacity_positive b W hW) (MaximumForestExchange.bottom_extendible _ _) + have hzero (d : DecidableRel (⊥ : SimpleGraph (Fin (m+n))).Adj) : + @graphCode (m+n) ⊥ d=ForestGreedyProgram.emptyGraph (NetworkVertexCode.data r c b,W) := by + symm + simp only [ForestGreedyProgram.emptyGraph,vertexCount_code,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn,graphCode] + apply congrArg List.ofFn + funext v + simp [adjacencyRow] + dsimp only at ht + rw [hzero] at ht + change let T:=decoded (ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W)); + T≤graph b W ∧ T.IsAcyclic ∧ + ∀ H,H≤graph b W → H.IsAcyclic → weight H (capacities b)≤weight T (capacities b) at ht + dsimp only at ht + let T : SimpleGraph (Fin (m+n)) := + decoded (ForestGreedyProgram.forest (NetworkVertexCode.data r c b,W)) + have hback : (T.comap vertexEquiv).map vertexEquiv.toEmbedding=T := by + rw [←SimpleGraph.comap_symm] + ext u v + change T.Adj (vertexEquiv (vertexEquiv.symm u)) + (vertexEquiv (vertexEquiv.symm v)) ↔ T.Adj u v + simp only [Equiv.apply_symm_apply] + have hT : T.comap vertexEquiv≤cellGraph (small b W) := by + intro u v huv + exact (SimpleGraph.map_adj_apply (G:=cellGraph (small b W)) + (f:=vertexEquiv.toEmbedding) (a:=u) (b:=v)).mp (ht.1 huv) + refine ⟨hT,ht.2.1.of_comap vertexEquiv.toEmbedding,?_⟩ + intro F hF hac + have hle : F.map vertexEquiv.toEmbedding≤graph b W := map_monotone _ hF + have ha : (F.map vertexEquiv.toEmbedding).IsAcyclic := + (SimpleGraph.Iso.map vertexEquiv F).isAcyclic_iff.mp hac + have hw := ht.2.2 (F.map vertexEquiv.toEmbedding) hle ha + have h1 := weight_transport vertexEquiv F (capacity b) + have h2 := weight_transport vertexEquiv (T.comap vertexEquiv) (capacity b) + rw [hback] at h2 + exact h1.symm.trans_le (hw.trans_eq h2) + +end ContingencyTables.ComputedLargeForest + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedRootedInput.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedRootedInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..66852c8508f722b83da1e458d1a23d1e65b0afb0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ComputedRootedInput.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ComputedForestCode +import OAI.Combinatorics.ContingencyTables.Transport.ComputedCompanionInstance +import OAI.Combinatorics.ContingencyTables.Rooted.RootedDemandProgram + +namespace OAI + +/-! # Rooted-oracle metadata from the executed original-input preprocessing -/ + +namespace ContingencyTables.ComputedRootedInput +open MatchingFPRAS MatchingFPRAS.TreeTyped +open DensePrograms NetworkVertexCode + +abbrev Input := NetworkVertexCode.Input×ℕ + +def forestFrame (z : Input) : LargeEdgeCatalogProgram.Input := + (TightenedInputProgram.compute z.1,z.2) +def forestFrameRealizer : Realizer forestFrame := + pair (composition (f := fun z : Input => z.1) (g := TightenedInputProgram.compute) + first TightenedInputProgram.computeRealizer) second +lemma polynomial_forestFrame : PolynomialTime forestFrameRealizer := + polynomial_pair (polynomial_composition polynomial_first TightenedInputProgram.polynomial_compute) + polynomial_second + +def catalogData (z : Input) : RootedForestCatalog.Data := + (((ForestGreedyProgram.forest (forestFrame z),z.2),(TightenedInputProgram.compute z.1).1), + (TightenedInputProgram.compute z.1).2) +def catalogDataRealizer : Realizer catalogData := + pair (pair (pair + (composition (f := forestFrame) (g := ForestGreedyProgram.forest) + forestFrameRealizer ForestGreedyProgram.forestRealizer) second) + (composition (composition (f := fun z : Input => z.1) (g := TightenedInputProgram.compute) + first TightenedInputProgram.computeRealizer) first)) + (composition (composition (f := fun z : Input => z.1) (g := TightenedInputProgram.compute) + first TightenedInputProgram.computeRealizer) second) +lemma polynomial_catalogData : PolynomialTime catalogDataRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_forestFrame ForestGreedyProgram.polynomial_forest) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first TightenedInputProgram.polynomial_compute) + polynomial_first)) + (polynomial_composition (polynomial_composition polynomial_first TightenedInputProgram.polynomial_compute) + polynomial_second) + +def prepared (z : Input) : RootedForestCatalog.Data×MatrixCode := + (catalogData z,TightenedInputProgram.baseline z.1) +def preparedRealizer : Realizer prepared := + pair catalogDataRealizer (composition (f := fun z : Input => z.1) + (g := TightenedInputProgram.baseline) first TightenedInputProgram.baselineRealizer) +lemma polynomial_prepared : PolynomialTime preparedRealizer := + polynomial_pair polynomial_catalogData + (polynomial_composition polynomial_first TightenedInputProgram.polynomial_baseline) + +open scoped Classical +variable {m n : ℕ} + +lemma catalogData_instance (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2 ≤ W) : + catalogData (data r c b,W)=RootedForestCatalog.data + (ComputedCompanionInstance.instanceData hEK r c b hne W hW) := by + unfold catalogData forestFrame + rw [TightenedInputProgram.compute_code] + unfold RootedForestCatalog.data ComputedCompanionInstance.instanceData + rw [ComputedLargeForest.computed_code _ _ _ W (by omega)] + simp only [data,Int.toNat_natCast,ResidualGraphProgram.natCode,matrixCode] + +lemma baseline_instance (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2 ≤ W) : + TightenedInputProgram.baseline (data r c b)=matrixCode + (fun i j => ((ComputedCompanionInstance.instanceData hEK r c b hne W hW).X i j).toNat) := by + obtain ⟨Y,hY,_,_⟩ := TightenedInputProgram.baseline_correct hEK r c b hne + rw [hY] + unfold matrixCode + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + simp only [ComputedCompanionInstance.instanceData,ComputedCompanionInstance.baseline, + hY,ResidualGraphProgram.natCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,j.isLt,dite_true,Option.getD_some,Fin.eta,Int.toNat_natCast] + +lemma prepared_instance (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2 ≤ W) : + prepared (data r c b,W)= + (RootedForestCatalog.data (ComputedCompanionInstance.instanceData hEK r c b hne W hW), + matrixCode (fun i j => + ((ComputedCompanionInstance.instanceData hEK r c b hne W hW).X i j).toNat)) := by + exact Prod.ext (catalogData_instance hEK r c b hne W hW) + (baseline_instance hEK r c b hne W hW) + +end ContingencyTables.ComputedRootedInput + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineCoefficients.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..9766a8b6d3f068aed52c16a07d63b37f5f26a211 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineCoefficients.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication +import OAI.Combinatorics.ContingencyTables.Transport.AffinePenalty + +namespace OAI + +/-! # The actual maximum-forest cut coefficients of tree completions -/ + +namespace ContingencyTables.ForestAffineCoefficients + +open scoped BigOperators Classical +open CompanionFactorialApplication GraphIntegralCompletion GraphCompletionCounts +open ForestCapacity ForestCut MaximumForest + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def edge (t : I×J) : Sym2 (I⊕J) := s(Sum.inl t.1,Sum.inr t.2) + +noncomputable def cutVertex (A : Instance I J) (t : TreeCell A.T) : I⊕J := + Classical.choose (exists_root_avoiding_side A.T A.hT t.property + (componentRoot A.T (.inl t.val.1)) (componentRoot_reachable A.T (.inl t.val.1)).symm) + +noncomputable def cutSide (A : Instance I J) (t : TreeCell A.T) (v : I⊕J) : Bool := + side (A.T.deleteEdges {edge t.val}) (cutVertex A t) v + +lemma cut_properties (A : Instance I J) (t : TreeCell A.T) : + A.T.Reachable (componentRoot A.T (.inl t.val.1)) (cutVertex A t) ∧ + cutSide A t (componentRoot A.T (.inl t.val.1))=false ∧ + cutSide A t (.inl t.val.1)≠cutSide A t (.inr t.val.2) := + Classical.choose_spec (exists_root_avoiding_side A.T A.hT t.property + (componentRoot A.T (.inl t.val.1)) (componentRoot_reachable A.T (.inl t.val.1)).symm) + +noncomputable def sign (A : Instance I J) (t : TreeCell A.T) (a : I×J) : ℝ := + indicator (cutSide A t (.inl a.1))-indicator (cutSide A t (.inr a.2)) + +lemma sign_abs_le_one (A : Instance I J) (t : TreeCell A.T) (a : I×J) : + |sign A t a| ≤ 1 := by + unfold sign + cases cutSide A t (.inl a.1) <;> cases cutSide A t (.inr a.2) <;> norm_num [indicator] + +lemma sign_abs_self (A : Instance I J) (t : TreeCell A.T) : |sign A t t.val|=1 := + abs_indicator_sub (cut_properties A t).2.2 + +lemma sign_self_ne_zero (A : Instance I J) (t : TreeCell A.T) : sign A t t.val≠0 := by + intro hz + have hh := sign_abs_self A t + rw [hz,abs_zero] at hh + norm_num at hh + +noncomputable def coefficient (A : Instance I J) (t : TreeCell A.T) (a : I×J) : ℝ := + if A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + then -sign A t a/sign A t t.val else 0 + +lemma coefficient_abs_le_one (A : Instance I J) (t : TreeCell A.T) (a : I×J) : + |coefficient A t a| ≤ 1 := by + unfold coefficient + split_ifs + · rw [abs_div,abs_neg,sign_abs_self,div_one] + exact sign_abs_le_one A t a + · norm_num + +/-- A nonzero tree coefficient crosses the actual edge-deletion cut, +so maximum total capacity bounds the contributing free capacity. -/ +lemma capacity_le_of_coefficient_ne_zero (A : Instance I J) (t : TreeCell A.T) (a : I×J) + (ha : coefficient A t a≠0) : A.b a.1 a.2 ≤ A.b t.val.1 t.val.2 := by + have hfree : A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) := by + by_contra hh + exact ha (by simp only [coefficient,hh,ite_false]) + have hcross : cutSide A t (.inl a.1)≠cutSide A t (.inr a.2) := by + intro he + apply ha + simp [coefficient, hfree, sign, he] + have hh := crossing_free_edge_le (cellGraph A.small) A.T (capacity A.b) + A.hTG A.hT A.hmax (edge t.val) (by simpa [edge] using t.property) + (cutVertex A t) (show (cellGraph A.small).Adj (.inl a.1) (.inr a.2) from hfree.1) + hfree.2 hcross + simpa only [edge,capacity_cell] using hh + +/-- Scaling a free coordinate by (b_free+1)/B and normalizing a tree +value by b_tree gives coefficients at most 2/B, including structural +zero coefficients. This is the precise forest input to the evaluator's +Lipschitz estimate. -/ +theorem normalized_coefficient_bound (A : Instance I J) (t : TreeCell A.T) (a : I×J) + (B : ℝ) (hB : 0 < B) : + |coefficient A t a*((A.b a.1 a.2:ℝ)+1)/B/(A.b t.val.1 t.val.2:ℝ)| ≤ 2/B := by + have hbNat := (A.hlarge _ _ (A.hTG t.property)).2 + have hb : (1:ℝ) ≤ A.b t.val.1 t.val.2 := by exact_mod_cast hbNat + by_cases ha : coefficient A t a=0 + · simp only [ha,zero_mul,zero_div,abs_zero] + positivity + have hcap : (A.b a.1 a.2:ℝ) ≤ A.b t.val.1 t.val.2 := by + exact_mod_cast capacity_le_of_coefficient_ne_zero A t a ha + rw [abs_div,abs_div,abs_mul,abs_of_pos hB,abs_of_pos (by linarith : (0:ℝ) (A.X i j:ℝ)) i=0) + (hc : ∀ j,Sum.inr j≠componentRoot A.T (.inr j) → + columnDifference A.small q z (fun i j => (A.X i j:ℝ)) j=0) : + z t.val.1 t.val.2=affineTree A t x q (fun a => z a.1 a.2) := by + let f : I×J → ℝ := fun a => cutTerm A.small + (fun i => cutSide A t (.inl i)) (fun j => cutSide A t (.inr j)) + x q z (fun i j => (A.X i j:ℝ)) a.1 a.2 + have hsum : (∑ a,f a)=0 := by + rw [Fintype.sum_prod_type] + exact cut_sum_zero A.small _ _ x q z _ + (fun i hi => hr i (selected_nonroot A t (.inl i) hi)) + (fun j hj => hc j (selected_nonroot A t (.inr j) hj)) + have hterm (a : I×J) : f a= + (if a=t.val then sign A t t.val*(z a.1 a.2-A.X a.1 a.2) else 0)+ + (if A.small a.1 a.2 then + indicator (cutSide A t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + indicator (cutSide A t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) else 0)- + sign A t t.val*coefficient A t a*(z a.1 a.2-A.X a.1 a.2) := by + by_cases he : a=t.val + · subst a + have hs : A.small t.val.1 t.val.2=false := A.hTG t.property + simp only [f,cutTerm,hs,Bool.false_eq_true,ite_false,ite_true,coefficient,t.property, + not_true_eq_false,and_false,sign,mul_zero,zero_mul,add_zero,sub_zero] + · by_cases hs : A.small a.1 a.2=true + · simp [f,cutTerm,hs,he,coefficient] + · have hs' : A.small a.1 a.2=false := Bool.eq_false_iff.mpr hs + by_cases ht : A.T.Adj (.inl a.1) (.inr a.2) + · have hz := other_tree_sign_zero A t a ht he + simp only [f,cutTerm,hs',Bool.false_eq_true,ite_false,he,coefficient,ht, + not_true_eq_false,and_false,zero_add,mul_zero,zero_mul,sub_zero] + change sign A t a*(z a.1 a.2-(A.X a.1 a.2:ℝ))=0 + rw [hz,zero_mul] + · simp only [f,cutTerm,hs',Bool.false_eq_true,ite_false,he,coefficient,ht, + not_false_eq_true,and_self,ite_true,zero_add,zero_sub] + change sign A t a*(z a.1 a.2-(A.X a.1 a.2:ℝ))= + -(sign A t t.val*(-sign A t a/sign A t t.val)*(z a.1 a.2-A.X a.1 a.2)) + field_simp [sign_self_ne_zero A t] + simp_rw [hterm] at hsum + rw [Finset.sum_sub_distrib,Finset.sum_add_distrib] at hsum + have hsingle : (∑ a : I×J,if a=t.val then sign A t t.val*(z a.1 a.2-A.X a.1 a.2) else 0)= + sign A t t.val*(z t.val.1 t.val.2-A.X t.val.1 t.val.2) := by simp + rw [hsingle] at hsum + change sign A t t.val*(z t.val.1 t.val.2-A.X t.val.1 t.val.2)+smallContribution A t x q- + (∑ a : I×J,sign A t t.val*coefficient A t a*(z a.1 a.2-A.X a.1 a.2))=0 at hsum + have hprod : (∑ a : I×J,sign A t t.val*coefficient A t a*(z a.1 a.2-A.X a.1 a.2))= + sign A t t.val*((∑ a : I×J,coefficient A t a*z a.1 a.2)- + ∑ a : I×J,coefficient A t a*(A.X a.1 a.2:ℝ)) := by + rw [mul_sub,Finset.mul_sum,Finset.mul_sum,← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro a _ + ring + rw [hprod] at hsum + unfold affineTree AffinePenalty.affineValue offset + apply (mul_left_cancel₀ (sign_self_ne_zero A t)) + rw [mul_add,mul_sub,mul_sub,← mul_div_assoc,mul_div_cancel_left₀ _ (sign_self_ne_zero A t)] + nlinarith [hsum] + +/-- In particular this affine display is the original integral solution +used inside h_j, rather than an unrelated continuous extension. -/ +theorem solved_eq_affine (A : Instance I J) (t : TreeCell A.T) + (x q free : I → J → ℤ) : + (solved A.small A.T A.r A.c x q free t.val.1 t.val.2:ℝ)= + affineTree A t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) + (fun a => (free a.1 a.2:ℝ)) := by + let z : I → J → ℝ := fun i j => (completed A.small A.T A.r A.c x q free i j:ℝ) + have hh := affine_of_nonroot_equations A t (fun i j => (x i j:ℝ)) + (fun i j => (q i j:ℝ)) z (by + intro i hi + have hr := row_completed_sum A.small A.T A.hTG A.r A.c x q free i hi + have hX := A.hXr i + unfold rowDifference + have he : (∑ j,if A.small i j then (x i j:ℝ) else z i j)=(A.r i:ℝ) := by + dsimp only [z] + exact_mod_cast hr + have hX' : (∑ j,(A.X i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast hX + calc + _=(∑ j,if A.small i j then (x i j:ℝ) else z i j)-(∑ j,(A.X i j:ℝ)) := by + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> rfl + _=0 := by rw [he,hX',sub_self]) (by + intro j hj + have hc := column_completed_sum A.small A.T A.hTG A.r A.c x q free j hj + have hX := A.hXc j + unfold columnDifference + have he : (∑ i,if A.small i j then (q i j:ℝ) else z i j)=(A.c j:ℝ) := by + dsimp only [z] + exact_mod_cast hc + have hX' : (∑ i,(A.X i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast hX + calc + _=(∑ i,if A.small i j then (q i j:ℝ) else z i j)-(∑ i,(A.X i j:ℝ)) := by + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> rfl + _=0 := by rw [he,hX',sub_self]) + have hz : z t.val.1 t.val.2=(solved A.small A.T A.r A.c x q free t.val.1 t.val.2:ℝ) := by + simp only [z,completed,t.property,ite_true] + rw [hz] at hh + rw [hh] + unfold affineTree AffinePenalty.affineValue + congr 1 + apply Finset.sum_congr rfl + intro a _ + by_cases ht : A.T.Adj (.inl a.1) (.inr a.2) + · simp only [coefficient,ht,not_true_eq_false,and_false,ite_false,zero_mul] + · simp only [z,completed,ht,ite_false] + +end ContingencyTables.ForestAffineCoefficients + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bbaef56118ee781c15929b635953c136b5a04a5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAffineProgram.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestIntegerEvaluation +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums + +namespace OAI + +/-! # Binary list evaluation of the forest's signed affine numerators + +Each coefficient is stored by its nonnegative and nonpositive parts. +The program performs two finite product sums and passes their difference +to the proved interval-cost routine. Large capacities are never iterated. +-/ + +namespace ContingencyTables.ForestAffineProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators Classical + +abbrev Term := (ℕ×ℕ)×ℕ +abbrev Input := ((ℕ×ℕ)×List Term)×ℕ + +def positiveTerm (z : Term) : ℕ := z.1.1*z.2 +def negativeTerm (z : Term) : ℕ := z.1.2*z.2 + +def positiveTermRealizer : Realizer positiveTerm := + composition (f := fun z : Term => (z.1.1,z.2)) (g := fun z : ℕ×ℕ => z.1*z.2) + (pair (composition first first) second) multiply + +def negativeTermRealizer : Realizer negativeTerm := + composition (f := fun z : Term => (z.1.2,z.2)) (g := fun z : ℕ×ℕ => z.1*z.2) + (pair (composition first second) second) multiply + +lemma polynomial_positiveTerm : PolynomialTime positiveTermRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_multiply + +lemma polynomial_negativeTerm : PolynomialTime negativeTermRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_multiply + +def positiveSumRealizer : Realizer (fun xs : List Term => (xs.map positiveTerm).sum) := + composition (map positiveTermRealizer) listSum + +def negativeSumRealizer : Realizer (fun xs : List Term => (xs.map negativeTerm).sum) := + composition (map negativeTermRealizer) listSum + +lemma polynomial_positiveSum : PolynomialTime positiveSumRealizer := + polynomial_composition (polynomial_map polynomial_positiveTerm) polynomial_listSum + +lemma polynomial_negativeSum : PolynomialTime negativeSumRealizer := + polynomial_composition (polynomial_map polynomial_negativeTerm) polynomial_listSum + +def parts (z : Input) : ℕ×ℕ := + (z.1.1.1+(z.1.2.map positiveTerm).sum,z.1.1.2+(z.1.2.map negativeTerm).sum) + +def partsRealizer : Realizer parts := + pair + (composition (pair (composition (composition first first) first) + (composition (composition first second) positiveSumRealizer)) add) + (composition (pair (composition (composition first first) second) + (composition (composition first second) negativeSumRealizer)) add) + +lemma polynomial_parts : PolynomialTime partsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_positiveSum)) polynomial_add) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_negativeSum)) polynomial_add) + +def evaluate (z : Input) : TreeFraction.Fraction := + RationalIntervalProgram.intervalCode (parts z,z.2) + +def evaluateRealizer : Realizer evaluate := + composition (f := fun z : Input => (parts z,z.2)) (g := RationalIntervalProgram.intervalCode) + (pair partsRealizer second) RationalIntervalProgram.intervalCodeRealizer + +theorem polynomial_evaluate : PolynomialTime evaluateRealizer := + polynomial_composition (polynomial_pair polynomial_parts polynomial_second) + RationalIntervalProgram.polynomial_intervalCode + +def signedParts (z : ℤ) : ℕ×ℕ := (z.toNat,(-z).toNat) + +lemma signedParts_sub (z : ℤ) : ((signedParts z).1:ℤ)-(signedParts z).2=z := by + change (z.toNat:ℤ)-((-z).toNat:ℤ)=z + omega + +noncomputable section +variable {q : ℕ} + +def data (offset : ℤ) (coefficient : Fin q → ℤ) (v : Fin q → ℕ) (den : ℕ) : Input := + ((signedParts offset,List.ofFn (fun i => (signedParts (coefficient i),v i))),den) + +lemma parts_data (offset : ℤ) (coefficient : Fin q → ℤ) (v : Fin q → ℕ) (den : ℕ) : + ((parts (data offset coefficient v den)).1:ℤ)-(parts (data offset coefficient v den)).2= + offset+∑ i,coefficient i*(v i:ℤ) := by + simp only [parts,data,List.map_ofFn,Function.comp_apply,positiveTerm,negativeTerm, + List.sum_ofFn,Nat.cast_add,Nat.cast_sum,Nat.cast_mul] + rw [add_sub_add_comm,←Finset.sum_sub_distrib,signedParts_sub] + congr 1 + apply Finset.sum_congr rfl + intro i _ + rw [←sub_mul,signedParts_sub] + +/-- All signs and products in an affine tree term are executed in +binary; the resulting fraction is its exact interval penalty. -/ +theorem evaluate_data (offset : ℤ) (coefficient : Fin q → ℤ) (v : Fin q → ℕ) + (den : ℕ) (hd : 0 ForestIntegerEvaluation.coefficient A t (e i).val* + ((A.b (e i).val.1 (e i).val.2:ℤ)+1)) + (fun i => v (e i)) (rationalBinWidth A C*A.b t.val.1 t.val.2) + +/-- This input is the literal cut-derived affine form of the manuscript. +The executable value is its exact contribution to the softened penalty. -/ +theorem evaluate_forest (A : Instance I J) (C : ℕ) (hC : 0 (v f:ℚ)) t) + (rationalScaledTree A C x y (fun f => (v f:ℚ)) t-1)) := by + have hB : 0 rfl) + unfold forestData + rw [evaluate_data _ _ _ _ hd,hn,Nat.cast_mul,ForestIntegerEvaluation.numerator_div A C hC] + +end +end ContingencyTables.ForestAffineProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAssignmentSplit.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAssignmentSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1559e288e0935615de14cf57823894bc90e2666 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestAssignmentSplit.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestLiteralCount +import OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration + +namespace OAI + +/-! +# Splitting actual large-cell assignments into tree and free choices + +The coordinate enumeration used for signatures and the graph completion +sum use exactly the same assignments. This finite equivalence records +that fact, including the larger signed tree intervals. +-/ + +namespace ContingencyTables.ForestAssignmentSplit + +open scoped BigOperators Classical +open SimpleGraph LargePairEnumeration GraphCompletionCounts ForestCapacity ForestLiteralCount + +variable {I J : Type*} + +@[reducible] def FreeCell (small : I → J → Bool) (T : SimpleGraph (I⊕J)) := + {a : I×J // small a.1 a.2=false ∧ ¬T.Adj (.inl a.1) (.inr a.2)} + +@[reducible] def FreeIndex (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b : I → J → ℕ) := (a : FreeCell small T) → Fin (b a.val.1 a.val.2+1) + +noncomputable def freeTable (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b : I → J → ℕ) (a : FreeIndex small T b) (i : I) (j : J) : ℕ := + if h : small i j=false ∧ ¬T.Adj (.inl i) (.inr j) then (a ⟨(i,j),h⟩).val else 0 + +lemma freeTable_bound (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b : I → J → ℕ) (a : FreeIndex small T b) (i : I) (j : J) + (hs : small i j=false) (ht : ¬T.Adj (.inl i) (.inr j)) : + freeTable small T b a i j≤b i j := by + unfold freeTable + rw [dite_eq_left ⟨hs,ht⟩] + have h := (a ⟨(i,j),⟨hs,ht⟩⟩).isLt + change (a ⟨(i,j),⟨hs,ht⟩⟩).val small a.1 a.2)) → + Fin (width T d b a.val.1 a.val.2+1)) ≃ TreeIndex T d b×FreeIndex small T b where + toFun a := + ((fun t => Fin.cast (by simp only [width,t.property,ite_true]) + (a ⟨t.val,hTG t.property⟩)), + fun f => Fin.cast (by simp only [width,f.property.2,ite_false]) + (a ⟨f.val,f.property.1⟩)) + invFun a l := if h : T.Adj (.inl l.val.1) (.inr l.val.2) then + Fin.cast (by simp only [width,h,ite_true]) (a.1 ⟨l.val,h⟩) + else Fin.cast (by simp only [width,h,ite_false]) (a.2 ⟨l.val,⟨l.property,h⟩⟩) + left_inv a := by + funext l + by_cases ht : T.Adj (.inl l.val.1) (.inr l.val.2) + · apply Fin.ext + simp [ht] + · apply Fin.ext + simp [ht] + right_inv a := by + apply Prod.ext + · funext t + apply Fin.ext + simp [t.property] + · funext f + apply Fin.ext + simp [f.property.2] + +/-- A tree/free split assignment gives precisely the cell counts in the +literal graph profile, before taking the complementary column view. -/ +lemma split_cellCount (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b : I → J → ℕ) + (a : TreeIndex T d b×FreeIndex small T b) + (l : LargeCell (fun a : I×J => small a.1 a.2)) : + (((assignmentSplit small T hTG d b).symm a l).val)= + cellCount T d b (freeTable small T b a.2) a.1 l.val.1 l.val.2 := by + by_cases ht : T.Adj (.inl l.val.1) (.inr l.val.2) + · simp [assignmentSplit,Equiv.symm,ht,cellCount] + · simp [assignmentSplit,Equiv.symm,ht,cellCount,freeTable,l.property] + +end ContingencyTables.ForestAssignmentSplit + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestBoxCardinality.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestBoxCardinality.lean new file mode 100644 index 0000000000000000000000000000000000000000..395b0c1ee31e1262f0e977c26a2b526fe12a83a7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestBoxCardinality.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication + +namespace OAI + +/-! # The expanded physical forest box still has a short cardinality bound + +The tree interval width 20db has at most (b+1)^2 integer positions +when every large capacity is at least 20d. This provides a uniform bound +for the positive equality-softened balanced sums before taking limits. +-/ + +namespace ContingencyTables.ForestBoxCardinality + +open scoped BigOperators Classical +open CompanionFactorialApplication ForestLiteralCount + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma width_add_one_le_square (A : Instance I J) (hW : 20*A.d ≤ A.W) (i : I) (j : J) : + width A.T A.d A.b i j+1 ≤ (A.b i j+1)^2 := by + unfold width + split_ifs with ht + · have hs : A.small i j=false := A.hTG ht + have hb : 20*A.d ≤ A.b i j := hW.trans (A.hlarge i j hs).1 + nlinarith + · nlinarith + +abbrev Assignments (A : Instance I J) := + (a : I×J) → Fin (width A.T A.d A.b a.1 a.2+1) + +theorem cardinality_le_square (A : Instance I J) (hW : 20*A.d ≤ A.W) : + Fintype.card (Assignments A) ≤ (∏ a : I×J,(A.b a.1 a.2+1))^2 := by + simp only [Assignments,Fintype.card_pi,Fintype.card_fin] + calc + _ ≤ ∏ a : I×J,(A.b a.1 a.2+1)^2 := by + apply Finset.prod_le_prod + intro a _ + exact width_add_one_le_square A hW a.1 a.2 + _ = _ := Finset.prod_pow Finset.univ 2 (fun a : I×J => A.b a.1 a.2+1) + +/-- The full balanced physical box, including every expanded tree +interval, has at most 2^K profiles under the source's bit-size allowance. -/ +theorem cardinality_le_two_pow (A : Instance I J) (hW : 20*A.d ≤ A.W) + (L K : ℕ) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) (hK : 2*L ≤ K) : + Fintype.card (Assignments A) ≤ 2^K := by + calc + _ ≤ (∏ a : I×J,(A.b a.1 a.2+1))^2 := cardinality_le_square A hW + _ ≤ (2^L)^2 := Nat.pow_le_pow_left hL 2 + _ = 2^(2*L) := by rw [← pow_mul]; congr 1; omega + _ ≤ _ := Nat.pow_le_pow_right (by omega) hK + +end ContingencyTables.ForestBoxCardinality + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCapacity.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCapacity.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5bab807a65ca2f912b7a3508b343f8323be6b6d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCapacity.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestCut + +namespace OAI + +/-! +# Actual bipartite cell forests and their completion intervals + +The graph vertices are the original row and column labels. Capacities +are attached to unordered row-column edges. The deletion-component cut +is constructed from the maximizing forest, so the hypotheses of the +physical cut estimate follow from actual graph properties. +-/ + +namespace ContingencyTables.ForestCapacity + +open scoped BigOperators Classical +open SimpleGraph +open MaximumForest ForestCut + +variable {I J : Type*} [Fintype I] [Fintype J] + +def cellAdj (small : I → J → Bool) : I⊕J → I⊕J → Prop + | .inl i,.inr j => small i j=false + | .inr j,.inl i => small i j=false + | _,_ => False + +def cellGraph (small : I → J → Bool) : SimpleGraph (I⊕J) where + Adj := cellAdj small + symm := ⟨by intro v w; cases v <;> cases w <;> exact id⟩ + loopless := ⟨by intro v; cases v <;> exact id⟩ + +def pairCapacity (b : I → J → ℕ) : I⊕J → I⊕J → ℕ + | .inl i,.inr j => b i j + | .inr j,.inl i => b i j + | _,_ => 0 + +def capacity (b : I → J → ℕ) : Sym2 (I⊕J) → ℕ := + Sym2.lift ⟨pairCapacity b,by intro v w; cases v <;> cases w <;> rfl⟩ + +omit [Fintype I] [Fintype J] in +@[simp] lemma capacity_cell (b : I → J → ℕ) (i : I) (j : J) : + capacity b s(Sum.inl i,Sum.inr j)=b i j := rfl + +omit [Fintype I] [Fintype J] in +lemma cell_edge_injective : Function.Injective + (fun a : I×J => s(Sum.inl a.1,Sum.inr a.2)) := by + rintro ⟨i,j⟩ ⟨i',j'⟩ h + simpa only [Sym2.eq_iff,Prod.mk.injEq,Sum.inl.injEq,Sum.inr.injEq, + Sum.inl_ne_inr,Sum.inr_ne_inl,false_and,or_false] using h + +noncomputable def treeCell (T : SimpleGraph (I⊕J)) (i : I) (j : J) : Bool := + decide (T.Adj (.inl i) (.inr j)) + +/-- The actual maximum-forest cut gives the source's displacement and +interval bounds for every solution of the selected nonroot equations. -/ +theorem completion_interval (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + weight F (capacity b)≤weight T (capacity b)) + (i₀ : I) (j₀ : J) (ht : T.Adj (.inl i₀) (.inr j₀)) (root : I⊕J) + (hroot : T.Reachable root (.inl i₀)) + (x q z X : I → J → ℝ) (d : ℝ) (W : ℕ) + (hd : 1≤d) (hcard : (Fintype.card I*Fintype.card J:ℕ)≤d) + (hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j) + (hsmall : ∀ i j, small i j=true → b i j side D r (.inl i) + let colU : J → Bool := fun j => side D r (.inr j) + have hs₀ : small i₀ j₀=false := hTG ht + have hB : (1:ℝ)≤b i₀ j₀ := by exact_mod_cast (hlarge i₀ j₀ hs₀).2 + have hdisp : |z i₀ j₀-X i₀ j₀|≤4*d*b i₀ j₀ := by + apply displacement_bound small (treeCell T) rowU colU x q z X + (fun i j => (b i j:ℝ)) i₀ j₀ d hcard hB hs₀ hcross + · intro i hi + change side D r (.inl i)=true at hi + apply hr i + · have hri : D.Reachable r (.inl i) := by + simpa only [side,decide_eq_true_eq] using hi + exact hrr.trans (hri.mono + (T.deleteEdges_le {t})) + · intro he + have hbad : side D r root=true := by simpa only [he] using hi + exact Bool.false_ne_true (hrootSide.symm.trans hbad) + · intro j hj + change side D r (.inr j)=true at hj + apply hc j + · have hrj : D.Reachable r (.inr j) := by + simpa only [side,decide_eq_true_eq] using hj + exact hrr.trans (hrj.mono + (T.deleteEdges_le {t})) + · intro he + have hbad : side D r root=true := by simpa only [he] using hj + exact Bool.false_ne_true (hrootSide.symm.trans hbad) + · exact hX + · intro i j hs + have hcap : b i j≤b i₀ j₀ := (Nat.le_of_lt (hsmall i j hs).1).trans + (hlarge i₀ j₀ hs₀).1 + exact ⟨by exact_mod_cast hcap,(hsmall i j hs).2⟩ + · intro i j htree hne + apply side_eq_of_tree_edge T t r + · exact of_decide_eq_true htree + · exact fun he => hne (cell_edge_injective he) + · intro i j hs htree + refine ⟨hfree i j hs htree,?_⟩ + intro hcut + have hgraph : (cellGraph small).Adj (.inl i) (.inr j) := hs + have hcap := crossing_free_edge_le (cellGraph small) T (capacity b) + hTG hT hmax t (by simpa [t] using ht) r hgraph + (by simpa only [treeCell,decide_eq_false_iff_not] using htree) hcut + exact_mod_cast hcap + exact physical_interval_of_displacement d (b i₀ j₀) (X i₀ j₀) (z i₀ j₀) + hd (Nat.cast_nonneg _) (hX i₀ j₀) hdisp + +end ContingencyTables.ForestCapacity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCountIdentification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCountIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..11149c01fbd2f73003fabac0d30b9308d5db99cc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestCountIdentification.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAssignmentSplit +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalLargeProfiles +import OAI.Combinatorics.ContingencyTables.Rooted.ForestLargeMarginal + +namespace OAI + +/-! +# The companion signature marginal is the literal weighted completion count + +The physical all-large product is split bijectively into tree and free +assignments. Exact nonroot equations then retain one tree completion per +free assignment, with exactly its root/tree exponential penalty. +-/ + +namespace ContingencyTables.ForestCountIdentification + +open scoped BigOperators Classical +open SimpleGraph LargePairEnumeration PhysicalLargeProfiles +open ForestCapacity GraphCompletionCounts ForestAssignmentSplit ForestLiteralCount + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def smallX (small : I → J → Bool) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) (i : I) (j : J) : ℕ := + if hs : small i j=true then z (⟨(i,j),hs⟩,false) else 0 + +noncomputable def smallY (small : I → J → Bool) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) (i : I) (j : J) : ℕ := + if hs : small i j=true then z (⟨(i,j),hs⟩,true) else 0 + +omit [Fintype I] [Fintype J] in +lemma split_profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b : I → J → ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (a : TreeIndex T d b×FreeIndex small T b) : + physicalProfile (fun a : I×J => small a.1 a.2) (fun p => width T d b p.1 p.2) z + ((assignmentSplit small T hTG d b).symm a)= + profile small T d b (smallX small z) (smallY small z) (freeTable small T b a.2) a.1 := by + funext u + rcases u with ⟨⟨i,j⟩,v⟩ + by_cases hs : small i j=true + · cases v <;> simp [physicalProfile,hs,profile,smallX,smallY] + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + have he := split_cellCount small T hTG d b a ⟨(i,j),hs'⟩ + cases v <;> simp [physicalProfile,hs,profile,he] + +private theorem physical_sum_split (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b : I → J → ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (F : (((I×J)×Bool) → ℕ) → ℝ) : + (∑ a : PhysicalAssignments (fun a : I×J => small a.1 a.2) + (fun a => width T d b a.1 a.2), + F (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => width T d b a.1 a.2) z a))= + ∑ f : FreeIndex small T b, ∑ t : TreeIndex T d b, + F (profile small T d b (smallX small z) (smallY small z) (freeTable small T b f) t) := by + have heq := Fintype.sum_equiv (assignmentSplit small T hTG d b) + (fun a => F (physicalProfile (fun a : I×J => small a.1 a.2) + (fun a => width T d b a.1 a.2) z a)) + (fun a => F (profile small T d b (smallX small z) (smallY small z) (freeTable small T b a.2) a.1)) + (by + intro a + apply congrArg F + have he := split_profile small T hTG d b z ((assignmentSplit small T hTG d b) a) + simpa only [Equiv.symm_apply_apply] using he) + rw [heq,Fintype.sum_prod_type,Finset.sum_comm] + +noncomputable def sourceMarginal (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (_d : ℕ) (b : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : ℝ := + ∑ f : FreeIndex small T b, (2:ℝ)^(-alpha*actualPenalty small T b + (smallX small z) (smallY small z) (freeTable small T b f) r c + (ForestPhysicalCompletion.solved small T r c + (fun i j => (smallX small z i j:ℤ)) + (fun i j => ((b i j-smallY small z i j:ℕ):ℤ)) + (fun i j => (freeTable small T b f i j:ℤ)))) + +theorem sourceMarginal_positive (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (d : ℕ) (b : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : + 0 0 + unfold sourceMarginal + apply lt_of_lt_of_le (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _) + exact Finset.single_le_sum (fun a _ => + (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _).le) (Finset.mem_univ f) + +/-- At annealing parameter zero the original count is exactly the +product of the free interval lengths. -/ +theorem sourceMarginal_zero (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (d : ℕ) (b : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : + sourceMarginal small T d b r c 0 z= + ∏ a : FreeCell small T, ((b a.val.1 a.val.2+1:ℕ):ℝ) := by + simp [sourceMarginal,Fintype.card_pi,Nat.cast_prod] + +/-- The source's actual free-assignment count is precisely the all-large +physical marginal with its raw removal signature. -/ +theorem sourceMarginal_eq_largeMarginal (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + MaximumForest.weight F (capacity b)≤MaximumForest.weight T (capacity b)) + (r : I → ℤ) (c : J → ℤ) (X : I → J → ℤ) + (d W : ℕ) (alpha : ℝ) (hd : 1≤d) (hcard : Fintype.card I*Fintype.card J≤d) + (hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j) + (hsmall : ∀ i j, small i j=true → b i j small a.1 a.2)) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (hz : ∀ u, z u≤b u.1.val.1 u.1.val.2) : + sourceMarginal small T d b r c alpha z= + ForestLargeMarginal.largeMarginal (fun a : I×J => small a.1 a.2) T b + (lower T d b) (width T d b) r c alpha e z := by + unfold ForestLargeMarginal.largeMarginal + rw [sum_joined_eq_physical (fun a : I×J => small a.1 a.2) + (fun a : I×J => width T d b a.1 a.2) e z + (ForestPenaltyApplication.physicalWeight T b (lower T d b) (width T d b) r c alpha)] + trans (∑ f : FreeIndex small T b, ∑ t : TreeIndex T d b, + ForestPenaltyApplication.physicalWeight T b (lower T d b) (width T d b) r c alpha + (profile small T d b (smallX small z) (smallY small z) (freeTable small T b f) t)) + · unfold sourceMarginal + have hsmall' : ∀ i j, small i j=true → + b i j cases b <;> simp_all [indicator] + +noncomputable def rowDifference (small : I → J → Bool) (x z X : I → J → ℝ) (i : I) : ℝ := + ∑ j, if small i j then x i j-X i j else z i j-X i j + +noncomputable def columnDifference (small : I → J → Bool) (q z X : I → J → ℝ) (j : J) : ℝ := + ∑ i, if small i j then q i j-X i j else z i j-X i j + +noncomputable def cutTerm (small : I → J → Bool) (rowU : I → Bool) (colU : J → Bool) + (x q z X : I → J → ℝ) (i : I) (j : J) : ℝ := + if small i j then indicator (rowU i)*(x i j-X i j)-indicator (colU j)*(q i j-X i j) + else (indicator (rowU i)-indicator (colU j))*(z i j-X i j) + +/-- Literal signed summation of the nonroot margin differences. -/ +theorem signed_cut_identity (small : I → J → Bool) (rowU : I → Bool) (colU : J → Bool) + (x q z X : I → J → ℝ) : + (∑ i, indicator (rowU i)*rowDifference small x z X i)- + (∑ j, indicator (colU j)*columnDifference small q z X j) = + ∑ i, ∑ j, cutTerm small rowU colU x q z X i j := by + unfold rowDifference columnDifference cutTerm + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm (f := fun j i => indicator (colU j)* + (if small i j then q i j-X i j else z i j-X i j))] + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + cases small i j <;> simp [sub_mul] + +/-- When U avoids roots, all selected nonroot equations hold, giving +the source's cut cancellation even on unbalanced small profiles. -/ +theorem cut_sum_zero (small : I → J → Bool) (rowU : I → Bool) (colU : J → Bool) + (x q z X : I → J → ℝ) + (hr : ∀ i, rowU i=true → rowDifference small x z X i=0) + (hc : ∀ j, colU j=true → columnDifference small q z X j=0) : + (∑ i, ∑ j, cutTerm small rowU colU x q z X i j)=0 := by + rw [← signed_cut_identity] + have hrow : ∀ i, indicator (rowU i)*rowDifference small x z X i=0 := by + intro i + cases hi : rowU i + · simp [indicator] + · simp [indicator,hr i hi] + have hcol : ∀ j, indicator (colU j)*columnDifference small q z X j=0 := by + intro j + cases hj : colU j + · simp [indicator] + · simp [indicator,hc j hj] + simp only [hrow,hcol,Finset.sum_const_zero,sub_self] + +omit [Fintype I] [Fintype J] in +lemma small_term_bound (small : I → J → Bool) (rowU : I → Bool) (colU : J → Bool) + (x q z X : I → J → ℝ) (i : I) (j : J) (b B : ℝ) + (hs : small i j=true) (hb : b≤B) + (hx : 0≤x i j ∧ x i j≤b) (hq : 0≤q i j ∧ q i j≤b) + (hX : 0≤X i j ∧ X i j≤b) : + |cutTerm small rowU colU x q z X i j|≤2*B := by + simp only [cutTerm,hs,ite_true] + have hmul : ∀ s : Bool, ∀ a : ℝ, |indicator s*a|≤|a| := by + intro s a + cases s <;> simp [indicator] + have hx' : |x i j-X i j|≤b := by + apply abs_le.mpr + constructor <;> linarith [hx.1,hx.2,hX.1,hX.2] + have hq' : |q i j-X i j|≤b := by + apply abs_le.mpr + constructor <;> linarith [hq.1,hq.2,hX.1,hX.2] + calc + _≤|indicator (rowU i)*(x i j-X i j)|+|indicator (colU j)*(q i j-X i j)| := abs_sub _ _ + _≤|x i j-X i j|+|q i j-X i j| := add_le_add (hmul _ _) (hmul _ _) + _≤2*B := by linarith + +omit [Fintype I] [Fintype J] in +lemma free_term_bound (small : I → J → Bool) (rowU : I → Bool) (colU : J → Bool) + (x q z X : I → J → ℝ) (i : I) (j : J) (b B : ℝ) + (hs : small i j=false) (hB : 1≤B) + (hcap : rowU i≠colU j → b≤B) + (hz : 0≤z i j ∧ z i j≤b+1) (hX : 0≤X i j ∧ X i j≤b) : + |cutTerm small rowU colU x q z X i j|≤2*B := by + by_cases hc : rowU i=colU j + · simp [cutTerm,hs,hc] + linarith + · have hb := hcap hc + have hdiff : |z i j-X i j|≤2*B := by + apply abs_le.mpr + constructor <;> linarith [hz.1,hz.2,hX.1,hX.2] + simp only [cutTerm,hs,Bool.false_eq_true,ite_false,abs_mul,abs_indicator_sub hc,one_mul] + exact hdiff + +/-- Isolating the sole crossing tree edge in the actual signed cut +equations gives the forest displacement bound. Small cells retain both +incidences, so the statement covers every unbalanced small profile. -/ +theorem displacement_bound (small tree : I → J → Bool) + (rowU : I → Bool) (colU : J → Bool) (x q z X b : I → J → ℝ) + (i₀ : I) (j₀ : J) (d : ℝ) + (hd : (Fintype.card I*Fintype.card J : ℕ)≤d) + (hB : 1≤b i₀ j₀) (hs₀ : small i₀ j₀=false) + (hcross : rowU i₀≠colU j₀) + (hr : ∀ i, rowU i=true → rowDifference small x z X i=0) + (hc : ∀ j, colU j=true → columnDifference small q z X j=0) + (hX : ∀ i j, 0≤X i j ∧ X i j≤b i j) + (hsmall : ∀ i j, small i j=true → + b i j≤b i₀ j₀ ∧ (0≤x i j ∧ x i j≤b i j) ∧ (0≤q i j ∧ q i j≤b i j)) + (htree : ∀ i j, tree i j=true → (i,j)≠(i₀,j₀) → rowU i=colU j) + (hfree : ∀ i j, small i j=false → tree i j=false → + (0≤z i j ∧ z i j≤b i j+1) ∧ (rowU i≠colU j → b i j≤b i₀ j₀)) : + |z i₀ j₀-X i₀ j₀|≤4*d*b i₀ j₀ := by + let f : I×J → ℝ := fun a => cutTerm small rowU colU x q z X a.1 a.2 + have hsum : (∑ a, f a)=0 := by + simpa only [Fintype.sum_prod_type,f] using cut_sum_zero small rowU colU x q z X hr hc + have hrest : ∀ a∈(Finset.univ.erase (i₀,j₀) : Finset (I×J)), |f a|≤2*b i₀ j₀ := by + rintro ⟨i,j⟩ ha + have hne : (i,j)≠(i₀,j₀) := (Finset.mem_erase.mp ha).1 + by_cases hs : small i j=true + · exact small_term_bound small rowU colU x q z X i j (b i j) (b i₀ j₀) + hs (hsmall i j hs).1 (hsmall i j hs).2.1 (hsmall i j hs).2.2 (hX i j) + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + by_cases ht : tree i j=true + · have he := htree i j ht hne + simp [f,cutTerm,hs',he] + linarith + · have ht' : tree i j=false := Bool.eq_false_iff.mpr ht + exact free_term_bound small rowU colU x q z X i j (b i j) (b i₀ j₀) + hs' hB (hfree i j hs' ht').2 (hfree i j hs' ht').1 (hX i j) + have hsplit := Finset.sum_erase_add (s := (Finset.univ : Finset (I×J))) + (a := (i₀,j₀)) f (Finset.mem_univ _) + have hisolate : f (i₀,j₀)=-(∑ a∈Finset.univ.erase (i₀,j₀), f a) := by + rw [hsum] at hsplit + linarith + have htarget : |f (i₀,j₀)|=|z i₀ j₀-X i₀ j₀| := by + simp only [f,cutTerm,hs₀,Bool.false_eq_true,ite_false,abs_mul, + abs_indicator_sub hcross,one_mul] + have hbound : |f (i₀,j₀)|≤(Fintype.card I*Fintype.card J:ℕ)*(2*b i₀ j₀) := by + rw [hisolate,abs_neg] + calc + |∑ a∈Finset.univ.erase (i₀,j₀), f a|≤ + ∑ a∈Finset.univ.erase (i₀,j₀), |f a| := Finset.abs_sum_le_sum_abs _ _ + _≤∑ _a∈(Finset.univ.erase (i₀,j₀) : Finset (I×J)), 2*b i₀ j₀ := + Finset.sum_le_sum hrest + _≤(Fintype.card I*Fintype.card J:ℕ)*(2*b i₀ j₀) := by + simp only [Finset.sum_const,Finset.card_erase_of_mem (Finset.mem_univ _), + Finset.card_univ,Fintype.card_prod,nsmul_eq_mul] + have hn : (Fintype.card I*Fintype.card J-1:ℕ)≤Fintype.card I*Fintype.card J := Nat.sub_le _ _ + exact mul_le_mul_of_nonneg_right (by exact_mod_cast hn) (by linarith) + rw [htarget] at hbound + have hdb : 0≤d := le_trans (Nat.cast_nonneg _) hd + have hn : (Fintype.card I*Fintype.card J:ℕ)* (2*b i₀ j₀)≤2*d*b i₀ j₀ := by + nlinarith + exact hbound.trans (hn.trans (by nlinarith)) + +/-- The interval bound needed in the equality-softening count argument +follows from the proved cut displacement estimate, with ample slack. -/ +lemma physical_interval_of_displacement (d b X z : ℝ) (hd : 1 ≤ d) (hb : 0 ≤ b) + (hX : 0 ≤ X ∧ X ≤ b) (hz : |z-X| ≤ 4*d*b) : + -10*d*b ≤ z ∧ z ≤ 10*d*b := by + have h := abs_le.mp hz + have hdb : 0 ≤ d*b := mul_nonneg (by linarith) hb + have hbdb : b ≤ d*b := by nlinarith + constructor <;> nlinarith + +end ContingencyTables.ForestCut + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestEdgeChoiceProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestEdgeChoiceProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf765787d037a1e1e9e2a990e581cfdea857934b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestEdgeChoiceProgram.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Machines.WeightedArgmaxProgram +import OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphCutProgram + +namespace OAI + +/-! # Choosing the heaviest edge between distinct forest components + +The filter runs the actual finite component-search program. The maximum +scan receives only eligible stored edges and retains their binary weights. +-/ + +namespace ContingencyTables.ForestEdgeChoiceProgram + +open MatchingFPRAS.TreeTyped WeightedArgmaxProgram FiniteGraphRootProgram +open FiniteGraphCutProgram +open scoped Classical + +abbrev Input := GraphCode×List Edge +abbrev TestInput := Input×Edge + +def query (z : TestInput) : FiniteGraphRootProgram.Input×ℕ := + ((z.1.1,z.2.1.1),z.2.1.2) +def queryRealizer : Realizer query := + pair (pair (composition first first) (composition (composition second first) first)) + (composition (composition second first) second) +lemma polynomial_query : PolynomialTime queryRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_first)) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_second) + +def eligible (z : TestInput) : Bool := !reachableCode (query z) +def eligibleRealizer : Realizer eligible := + composition (composition (f := query) (g := reachableCode) queryRealizer + reachableCodeRealizer) boolNot +lemma polynomial_eligible : PolynomialTime eligibleRealizer := + polynomial_composition (polynomial_composition polynomial_query polynomial_reachableCode) + polynomial_boolNot + +def filtered (z : Input) : List Edge := z.2.filter (fun e=>eligible (z,e)) +def filteredRealizer : Realizer filtered := + composition (pair identity second) (filterWith eligibleRealizer) +lemma polynomial_filtered : PolynomialTime filteredRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + (polynomial_filterWith polynomial_eligible) + +def choice (z : Input) : Option Edge := WeightedArgmaxProgram.best (filtered z) +def choiceRealizer : Realizer choice := + composition (f := filtered) (g := WeightedArgmaxProgram.best) + filteredRealizer WeightedArgmaxProgram.bestRealizer +lemma polynomial_choice : PolynomialTime choiceRealizer := + polynomial_composition polynomial_filtered WeightedArgmaxProgram.polynomial_best + +lemma eligible_code {n : ℕ} (T : SimpleGraph (Fin n)) [DecidableRel T.Adj] + (es : List Edge) (u v : Fin n) (w : ℕ) : + eligible ((graphCode T,es),((u.val,v.val),w))=true ↔ ¬T.Reachable u v := by + simp only [eligible,query,reachableCode,Bool.not_eq_true',decide_eq_false_iff_not, + reached_mem_iff] + +lemma choice_mem {z : Input} {e : Edge} (he : choice z=some e) : + e∈z.2 ∧ eligible (z,e)=true := + List.mem_filter.mp (WeightedArgmaxProgram.best_mem he) + +lemma choice_max {z : Input} {e a : Edge} (he : choice z=some e) + (ha : a∈z.2) (hel : eligible (z,a)=true) : a.2≤e.2 := + WeightedArgmaxProgram.best_max he (List.mem_filter.mpr ⟨ha,hel⟩) + +lemma choice_none {z : Input} (he : choice z=none) : + ∀ e∈z.2,eligible (z,e)=false := by + have hn : filtered z=[] := (WeightedArgmaxProgram.best_none _).mp he + intro e he + cases h : eligible (z,e) with + | false=>rfl + | true=> + have hm : e∈filtered z := List.mem_filter.mpr ⟨he,h⟩ + rw [hn] at hm + exact (List.not_mem_nil hm).elim + +end ContingencyTables.ForestEdgeChoiceProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedyProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedyProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d0c16dd747321b3a5e4e3be79206537149c9922 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedyProgram.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestJoinProgram +import OAI.Combinatorics.ContingencyTables.Rooted.LargeEdgeCatalogProgram + +namespace OAI + +/-! # Polynomial execution of the component-greedy forest loop + +The immutable weighted edge catalog is scanned after every insertion. +There are at most the square of the stored vertex count many iterations; +all adjacency rows stay inside that fixed vertex range. +-/ + +namespace ContingencyTables.ForestGreedyProgram + +open MatchingFPRAS.TreeTyped Polynomial FiniteGraphRootProgram WeightedArgmaxProgram + +abbrev State := ForestEdgeChoiceProgram.Input + +private def insert (z : State×Edge) : GraphCode := ForestJoinProgram.join (z.1.1,z.2.1) +private def insertRealizer : Realizer insert := + composition (f := fun z : State×Edge=>(z.1.1,z.2.1)) (g := ForestJoinProgram.join) + (pair (composition first first) (composition second first)) ForestJoinProgram.joinRealizer +private lemma polynomial_insert : PolynomialTime insertRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) ForestJoinProgram.polynomial_join + +def update (s : State) : GraphCode := + (ForestEdgeChoiceProgram.choice s).elim s.1 (fun e=>insert (s,e)) +def updateRealizer : Realizer update := + composition (f := fun s : State=>(s,ForestEdgeChoiceProgram.choice s)) + (g := fun z : State×Option Edge=>z.2.elim z.1.1 (fun e=>insert (z.1,e))) + (pair identity ForestEdgeChoiceProgram.choiceRealizer) (optionCases first insertRealizer) +lemma polynomial_update : PolynomialTime updateRealizer := + polynomial_composition (polynomial_pair polynomial_identity ForestEdgeChoiceProgram.polynomial_choice) + (polynomial_optionCases polynomial_first polynomial_insert) + +def advance (z : ℕ×State) : State := (update z.2,z.2.2) +def advanceRealizer : Realizer advance := + pair (composition (f := fun z : ℕ×State=>z.2) (g := update) second updateRealizer) + (composition second second) +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_update) + (polynomial_composition polynomial_second polynomial_second) + +lemma update_length (s : State) : (update s).length=s.1.length := by + unfold update + cases h : ForestEdgeChoiceProgram.choice s with + | none=>rfl + | some e=>exact ForestJoinProgram.join_length _ + +lemma update_weight (s : State) : + weight (update s)≤ max (weight s.1) + (s.1.length*(4*s.1.length^2+2*s.1.length+2)+1) := by + unfold update + cases h : ForestEdgeChoiceProgram.choice s with + | none=>exact le_max_left _ _ + | some e=>exact (ForestJoinProgram.join_weight _).trans (le_max_right _ _) + +lemma fold_edges (xs : List ℕ) (s : State) : + (xs.foldl (fun s a=>advance (a,s)) s).2=s.2 := by + induction xs generalizing s with + | nil=>rfl + | cons a xs ih=>exact ih (advance (a,s)) + +lemma fold_length (xs : List ℕ) (s : State) : + (xs.foldl (fun s a=>advance (a,s)) s).1.length=s.1.length := by + induction xs generalizing s with + | nil=>rfl + | cons a xs ih=> + exact (ih (advance (a,s))).trans (update_length s) + +lemma fold_weight (xs : List ℕ) (s : State) : + weight (xs.foldl (fun s a=>advance (a,s)) s).1≤ max (weight s.1) + (s.1.length*(4*s.1.length^2+2*s.1.length+2)+1) := by + induction xs generalizing s with + | nil=>exact le_max_left _ _ + | cons a xs ih=> + have h := ih (advance (a,s)) + simp only [advance,update_length] at h + exact h.trans (max_le (update_weight s) (le_max_right _ _)) + +lemma polynomial_loop : PolynomialTime (fold advanceRealizer) := by + apply polynomial_fold polynomial_advance (30*(X+1)^3) + intro xs s pre post he + let S := weight (xs,s) + let out := pre.foldl (fun s a=>advance (a,s)) s + have hs : weight s≤S := weight_snd (xs,s) + have hg : weight s.1≤S := (weight_fst s).trans hs + have hec : weight s.2≤S := (weight_snd s).trans hs + have hn : s.1.length≤S := (list_length_le_weight s.1).trans hg + have hb : s.1.length*(4*s.1.length^2+2*s.1.length+2)+1≤4*S^3+2*S^2+2*S+1 := by + have hpow := Nat.pow_le_pow_left hn 2 + have hmul := Nat.mul_le_mul hn (show 4*s.1.length^2+2*s.1.length+2≤4*S^2+2*S+2 by omega) + nlinarith + have ho : weight out.1≤4*S^3+2*S^2+3*S+1 := + (fold_weight pre s).trans (max_le (by omega) (by omega)) + have heq : out.2=s.2 := fold_edges pre s + have hw : weight out=1+weight out.1+weight out.2 := by + change weight (out.1,out.2)=_ + exact weight_prod _ _ + simp only [eval_mul,eval_ofNat,eval_add,eval_pow,eval_X,eval_one] + change weight out≤30*(S+1)^3 + rw [hw,heq] + nlinarith + +def slots (s : State) : List ℕ := List.range (s.1.length*s.1.length) +def slotsRealizer : Realizer slots := + composition (f := fun s : State=>s.1.length*s.1.length) (g := List.range) + (composition (f := fun s : State=>(s.1.length,s.1.length)) + (g := fun z : ℕ×ℕ=>z.1*z.2) + (pair (composition first listLength) (composition first listLength)) multiply) range +lemma polynomial_slots : PolynomialTime slotsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_listLength) + (polynomial_composition polynomial_first polynomial_listLength)) polynomial_multiply) (X^2) + intro s + have h : s.1.length≤weight s := (list_length_le_weight s.1).trans (weight_fst s) + simpa only [Function.comp_apply,eval_pow,eval_mul,eval_X,pow_two] using Nat.mul_self_le_mul_self h + +def execute (s : State) : State := (slots s).foldl (fun s a=>advance (a,s)) s +def executeRealizer : Realizer execute := + composition (f := fun s : State=>(slots s,s)) + (g := fun z : List ℕ×State=>z.1.foldl (fun s a=>advance (a,s)) z.2) + (pair slotsRealizer identity) (fold advanceRealizer) +lemma polynomial_execute : PolynomialTime executeRealizer := + polynomial_composition (polynomial_pair polynomial_slots polynomial_identity) polynomial_loop + +def emptyGraph (z : LargeEdgeCatalogProgram.Input) : GraphCode := + (List.range (LargeEdgeCatalogProgram.vertexCount z)).map (fun _=>[]) +def emptyGraphRealizer : Realizer emptyGraph := + composition (composition LargeEdgeCatalogProgram.vertexCountRealizer range) (map (constant [])) +lemma polynomial_emptyGraph : PolynomialTime emptyGraphRealizer := by + apply polynomial_composition + · apply polynomial_boundedRange LargeEdgeCatalogProgram.polynomial_vertexCount (2*X) + intro z + have hr : z.1.1.1.length≤weight z := (list_length_le_weight z.1.1.1).trans + ((weight_fst z.1.1).trans ((weight_fst z.1).trans (weight_fst z))) + have hc : z.1.1.2.length≤weight z := (list_length_le_weight z.1.1.2).trans + ((weight_snd z.1.1).trans ((weight_fst z.1).trans (weight_fst z))) + simp only [LargeEdgeCatalogProgram.vertexCount,eval_mul,eval_ofNat,eval_X] + omega + · exact polynomial_map (polynomial_constant []) + +def prepare (z : LargeEdgeCatalogProgram.Input) : State := + (emptyGraph z,LargeEdgeCatalogProgram.catalog z) +def prepareRealizer : Realizer prepare := + pair emptyGraphRealizer LargeEdgeCatalogProgram.catalogRealizer +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair polynomial_emptyGraph LargeEdgeCatalogProgram.polynomial_catalog + +def forest (z : LargeEdgeCatalogProgram.Input) : GraphCode := (execute (prepare z)).1 +def forestRealizer : Realizer forest := + composition (composition (f:=prepare) (g:=execute) prepareRealizer executeRealizer) first +lemma polynomial_forest : PolynomialTime forestRealizer := + polynomial_composition (polynomial_composition polynomial_prepare polynomial_execute) polynomial_first + +end ContingencyTables.ForestGreedyProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedySemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedySemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..854e9f8befa38284adc43fadbf8bfae142cd17e4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestGreedySemantics.lean @@ -0,0 +1,168 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestGreedyProgram +import OAI.Combinatorics.ContingencyTables.Rooted.MaximumForestExchange + +namespace OAI + +/-! # Correctness of the actual binary forest loop + +The invariant refers to the adjacency list produced by the program. +The final graph is decoded directly from that list. Optimal forests +occur only as proof witnesses for the safe-edge invariant. +-/ + +namespace ContingencyTables.ForestGreedySemantics + +open SimpleGraph MaximumForest MaximumForestExchange +open ForestGreedyProgram ForestEdgeChoiceProgram FiniteGraphRootProgram WeightedArgmaxProgram +open scoped Classical + +variable {n : ℕ} + +/-- Every stored edge is valid, and every graph edge is stored in at least +one orientation with its exact capacity. -/ +def Catalog (G : SimpleGraph (Fin n)) (b : Sym2 (Fin n)→ℕ) (es : List Edge) : Prop := + (∀ e∈es,∃ u v : Fin n,G.Adj u v ∧ e=((u.val,v.val),b s(u,v))) ∧ + (∀ u v,G.Adj u v → + ((u.val,v.val),b s(u,v))∈es ∨ ((v.val,u.val),b s(u,v))∈es) + +lemma chosen_spec {G T : SimpleGraph (Fin n)} {b : Sym2 (Fin n)→ℕ} {es : List Edge} + (hC : Catalog G b es) {e : Edge} (he : choice (graphCode T,es)=some e) : + ∃ u v : Fin n,e=((u.val,v.val),b s(u,v)) ∧ G.Adj u v ∧ ¬T.Reachable u v ∧ + ∀ a d,G.Adj a d → ¬T.Reachable a d → b s(a,d)≤b s(u,v) := by + have hm := choice_mem he + obtain ⟨u,v,hG,heq⟩ := hC.1 e hm.1 + subst e + have hnu : ¬T.Reachable u v := (eligible_code T es u v _).mp hm.2 + refine ⟨u,v,rfl,hG,hnu,?_⟩ + intro a d had hn + rcases hC.2 a d had with hmem|hmem + · exact choice_max he hmem ((eligible_code T es a d _).mpr hn) + · exact choice_max he hmem ((eligible_code T es d a _).mpr (fun hd=>hn hd.symm)) + +lemma none_spec {G T : SimpleGraph (Fin n)} {b : Sym2 (Fin n)→ℕ} {es : List Edge} + (hC : Catalog G b es) (he : choice (graphCode T,es)=none) : + ∀ u v,G.Adj u v → T.Reachable u v := by + intro u v hG + by_contra hn + rcases hC.2 u v hG with hmem|hmem + · have hfalse := choice_none he _ hmem + have htrue := (eligible_code T es u v (b s(u,v))).mpr hn + exact Bool.noConfusion (hfalse.symm.trans htrue) + · have hfalse := choice_none he _ hmem + have htrue := (eligible_code T es v u (b s(u,v))).mpr (fun hr=>hn hr.symm) + exact Bool.noConfusion (hfalse.symm.trans htrue) + +def iterate : ℕ→State→State + | 0,s=>s + | k+1,s=>iterate k (ForestGreedyProgram.advance (0,s)) + +lemma fold_eq_iterate (xs : List ℕ) (s : State) : + xs.foldl (fun s a=>ForestGreedyProgram.advance (a,s)) s=iterate xs.length s := by + induction xs generalizing s with + | nil=>rfl + | cons a xs ih=>simpa only [List.foldl_cons,List.length_cons,iterate,ForestGreedyProgram.advance] using ih (ForestGreedyProgram.advance (a,s)) + +lemma execute_iterate (s : State) : execute s=iterate (s.1.length*s.1.length) s := by + simpa only [execute,slots,List.length_range] using fold_eq_iterate (slots s) s + +lemma advance_none {s : State} (he : choice s=none) : ForestGreedyProgram.advance (0,s)=s := by + simp only [ForestGreedyProgram.advance,update,he,Option.elim_none] + +lemma iterate_none {s : State} (he : choice s=none) (k : ℕ) : iterate k s=s := by + induction k with + | zero=>rfl + | succ k ih=>simpa only [iterate,advance_none he] using ih + +lemma advance_code (T : SimpleGraph (Fin n)) (es : List Edge) (u v : Fin n) + (w : ℕ) (hne : u≠v) + (he : choice (graphCode T,es)=some ((u.val,v.val),w)) : + ForestGreedyProgram.advance (0,(graphCode T,es))=(graphCode (T⊔edge u v),es) := by + simp only [ForestGreedyProgram.advance,update,he,Option.elim_some] + change (ForestJoinProgram.join (graphCode T,(u.val,v.val)),es)=_ + rw [ForestJoinProgram.join_code T u v hne] + +private noncomputable def edgeCount (G : SimpleGraph (Fin n)) : ℕ := G.edgeFinset.card + +private lemma edgeCount_le (G : SimpleGraph (Fin n)) : + edgeCount G≤Fintype.card (Sym2 (Fin n)) := Finset.card_le_univ _ + +private lemma card_add (T : SimpleGraph (Fin n)) {u v : Fin n} + (hn : ¬T.Reachable u v) (huv : u≠v) : + edgeCount (T⊔edge u v)=edgeCount T+1 := by + have h := T.card_edgeFinset_sup_edge (fun ht=>hn ht.reachable) huv + unfold edgeCount + convert h using 1 + congr 1 + ext a + simp only [mem_edgeFinset] + +/-- A fuel count at least the number of missing unordered edges suffices +for the executed loop, without any tie-breaking assumption. -/ +theorem iterate_optimal (G T : SimpleGraph (Fin n)) (b : Sym2 (Fin n)→ℕ) + (es : List Edge) (hC : Catalog G b es) (hb : ∀ e∈G.edgeSet,0 + have hnone : choice (graphCode T,es)=none := by + cases he : choice (graphCode T,es) with + | none=>rfl + | some e=> + obtain ⟨u,v,_,hg,hn,_⟩ := chosen_spec hC he + have hc := card_add T hn hg.ne + have hle := edgeCount_le (T⊔edge u v) + omega + exact ⟨T,rfl,finished G T b hT (none_spec hC hnone)⟩ + | succ k ih=> + cases he : choice (graphCode T,es) with + | none=>exact ⟨T,iterate_none he _,finished G T b hT (none_spec hC he)⟩ + | some e=> + obtain ⟨u,v,rfl,hg,hn,hbest⟩ := chosen_spec hC he + have hnext := safe_edge G T b hb hT hg hn hbest + have hc := card_add T hn hg.ne + obtain ⟨F,hF,hopt⟩ := ih (T⊔edge u v) hnext (by omega) + refine ⟨F,?_,hopt⟩ + rw [iterate,advance_code T es u v _ hg.ne he] + convert hF using 1 + congr 3 + +def decoded (g : GraphCode) : SimpleGraph (Fin n) where + Adj u v := u≠v ∧ u.val∈g.getD v.val [] ∧ v.val∈g.getD u.val [] + symm := ⟨by intro u v h; exact ⟨Ne.symm h.1,h.2.2,h.2.1⟩⟩ + loopless := ⟨by intro u h; exact h.1 rfl⟩ + +lemma decoded_graphCode (G : SimpleGraph (Fin n)) : decoded (graphCode G)=G := by + ext u v + simp only [decoded,graphCode_getD,adjacencyRow_mem] + constructor + · rintro ⟨_,⟨a,ha,haG⟩,_⟩ + exact (Fin.ext ha) ▸ haG + · intro h + exact ⟨h.ne,⟨u,rfl,h⟩,⟨v,rfl,h.symm⟩⟩ + +lemma unordered_pair_budget : Fintype.card (Sym2 (Fin n))≤n*n := by + have hs : Function.Surjective (fun p : Fin n×Fin n=>s(p.1,p.2)) := by + intro e + induction e using Sym2.inductionOn with + | _ u v=>exact ⟨(u,v),rfl⟩ + simpa only [Fintype.card_prod,Fintype.card_fin] using Fintype.card_le_of_surjective _ hs + +/-- The graph is decoded from the literal result list, not selected from +an existence proof. -/ +theorem execute_optimal (G T : SimpleGraph (Fin n)) (b : Sym2 (Fin n)→ℕ) + (es : List Edge) (hC : Catalog G b es) (hb : ∀ e∈G.edgeSet,0 cases hc : cutSide A t (.inr a.2) <;> + norm_num [sign,indicator,rationalSign,rationalIndicator,hr,hc] + +lemma selfSign_square (A : Instance I J) (t : TreeCell A.T) : + (rationalSign A t t.val)^2=1 := by + have hn := (cut_properties A t).2.2 + cases hr : cutSide A t (.inl t.val.1) <;> + cases hc : cutSide A t (.inr t.val.2) <;> + simp_all [rationalSign,rationalIndicator] + +def coefficient (A : Instance I J) (t : TreeCell A.T) (a : I×J) : ℤ := + if A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + then -(sign A t a)*sign A t t.val else 0 + +lemma coefficient_cast (A : Instance I J) (t : TreeCell A.T) (a : I×J) : + (coefficient A t a:ℚ)=rationalCoefficient A t a := by + have hs := selfSign_square A t + have hn : rationalSign A t t.val≠0 := by intro h; rw [h] at hs; norm_num at hs + unfold coefficient rationalCoefficient + split_ifs + · simp only [Int.cast_mul,Int.cast_neg,sign_cast] + apply (eq_div_iff hn).mpr + calc + (-(rationalSign A t a)*rationalSign A t t.val)*rationalSign A t t.val= + -(rationalSign A t a)*(rationalSign A t t.val)^2 := by ring + _ = _ := by rw [hs,mul_one] + · exact Int.cast_zero + +def smallContribution (A : Instance I J) (t : TreeCell A.T) + (x q : I → J → ℤ) : ℤ := + ∑ a : I×J,if A.small a.1 a.2 then + indicator (cutSide A t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + indicator (cutSide A t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) else 0 + +lemma smallContribution_cast (A : Instance I J) (t : TreeCell A.T) + (x q : I → J → ℤ) : + (smallContribution A t x q:ℚ)=rationalSmallContribution A t x q := by + unfold smallContribution rationalSmallContribution + rw [Int.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs + · cases hr : cutSide A t (.inl a.1) <;> cases hc : cutSide A t (.inr a.2) <;> + simp_all [indicator,rationalIndicator] + · exact Int.cast_zero + +def offset (A : Instance I J) (t : TreeCell A.T) (x q : I → J → ℤ) : ℤ := + A.X t.val.1 t.val.2-smallContribution A t x q*sign A t t.val- + ∑ a : I×J,coefficient A t a*A.X a.1 a.2 + +lemma offset_cast (A : Instance I J) (t : TreeCell A.T) (x q : I → J → ℤ) : + (offset A t x q:ℚ)=rationalOffset A t x q := by + have hs := selfSign_square A t + have hn : rationalSign A t t.val≠0 := by intro h; rw [h] at hs; norm_num at hs + have he : rationalSmallContribution A t x q*rationalSign A t t.val= + rationalSmallContribution A t x q/rationalSign A t t.val := by + apply (eq_div_iff hn).mpr + rw [mul_assoc,←pow_two,hs,mul_one] + simp only [offset,rationalOffset,Int.cast_sub,Int.cast_mul,Int.cast_sum, + smallContribution_cast,sign_cast,coefficient_cast,he] + +def numerator (A : Instance I J) (C : ℕ) (t : TreeCell A.T) + (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℕ) : ℤ := + (rationalBinWidth A C:ℤ)*offset A t x q+ + ∑ f : FreeCell A.small A.T, + coefficient A t f.val*((A.b f.val.1 f.val.2:ℤ)+1)*(v f:ℤ) + +/-- The exact affine tree value is a signed integral numerator divided +by the explicit natural denominator, even when the original margins +have very large binary representations. -/ +theorem numerator_div (A : Instance I J) (C : ℕ) (hC : 0 (v f:ℚ)) t := by + have hd : (0:ℚ) (v f:ℚ)) t) + (rationalScaledTree A C x q (fun f => (v f:ℚ)) t-1)) := by + have hB : 0z.1.2) := composition first second + let u : Realizer (fun z : TestInput=>z.1.1.2.1) := + composition (composition (composition first first) second) first + let v : Realizer (fun z : TestInput=>z.1.1.2.2) := + composition (composition (composition first first) second) second + let old : Realizer (fun z : TestInput=>decide (z.2∈z.1.1.1.getD z.1.2 [])) := + composition (pair + (composition (pair (composition (composition first first) first) row) (getDFast [])) + second) membership + exact composition (pair old + (composition (pair + (composition (pair (composition (pair row u) natEqual) + (composition (pair second v) natEqual)) boolAnd) + (composition (pair (composition (pair row v) natEqual) + (composition (pair second u) natEqual)) boolAnd)) boolOr)) boolOr + +lemma polynomial_keep : PolynomialTime keepRealizer := by + unfold keepRealizer + have hr : PolynomialTime (composition (first (A:=RowInput) (B:=ℕ)) second) := + polynomial_composition polynomial_first polynomial_second + have hu : PolynomialTime (composition (composition + (composition (first (A:=RowInput) (B:=ℕ)) first) second) first) := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first + have hv : PolynomialTime (composition (composition + (composition (first (A:=RowInput) (B:=ℕ)) first) second) second) := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second + apply polynomial_composition _ polynomial_boolOr + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) hr) (polynomial_getDFast [])) polynomial_second) polynomial_membership + · apply polynomial_composition _ polynomial_boolOr + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hr hu) polynomial_natEqual) + (polynomial_composition (polynomial_pair polynomial_second hv) polynomial_natEqual)) + polynomial_boolAnd + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hr hv) polynomial_natEqual) + (polynomial_composition (polynomial_pair polynomial_second hu) polynomial_natEqual)) + polynomial_boolAnd + +def vertices (z : RowInput) : List ℕ := indices z.1.1 +def verticesRealizer : Realizer vertices := + composition (composition first first) indicesRealizer +lemma polynomial_vertices : PolynomialTime verticesRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_indices + +def row (z : RowInput) : List ℕ := (vertices z).filter (fun a=>keep (z,a)) +def rowRealizer : Realizer row := + composition (pair identity verticesRealizer) (filterWith keepRealizer) +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_vertices) + (polynomial_filterWith polynomial_keep) + +def join (z : Input) : GraphCode := (indices z.1).map (fun i=>row (z,i)) +def joinRealizer : Realizer join := + composition (pair identity (composition first indicesRealizer)) (mapWith rowRealizer) +lemma polynomial_join : PolynomialTime joinRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith polynomial_row) + +lemma join_length (z : Input) : (join z).length=z.1.length := by + simp only [join,List.length_map,indices,List.length_range] + +lemma row_weight (z : RowInput) : weight (row z)≤weight (indices z.1.1) := + weight_sublist (List.filter_sublist (p:=fun a=>keep (z,a)) (l:=vertices z)) + +lemma join_weight (z : Input) : + weight (join z)≤z.1.length*(4*z.1.length^2+2*z.1.length+2)+1 := by + have hi := indices_weight z.1 + have hs : ∀ i∈indices z.1,weight (row (z,i))≤4*z.1.length^2+2*z.1.length+1 := by + intro i _ + exact (row_weight (z,i)).trans (by nlinarith [hi]) + have h := weight_map_bound (as:=indices z.1) (f:=fun i=>row (z,i)) + (N:=4*z.1.length^2+2*z.1.length+1) hs + simpa only [join,indices,List.length_range,Nat.add_assoc] using h + +lemma keep_code {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + (u v r a : Fin n) (hne : u≠v) : + keep (((graphCode G,(u.val,v.val)),r.val),a.val)=true ↔ + (G⊔edge u v).Adj a r := by + simp only [keep,graphCode_getD,Bool.or_eq_true,Bool.and_eq_true,decide_eq_true_eq] + rw [adjacencyRow_mem] + have he : (∃ w : Fin n,w.val=a.val ∧ G.Adj w r) ↔ G.Adj a r := by + constructor + · rintro ⟨w,hw,hwr⟩ + exact (Fin.ext hw) ▸ hwr + · intro har + exact ⟨a,rfl,har⟩ + rw [he] + simp only [Fin.val_inj,SimpleGraph.sup_adj,SimpleGraph.edge_adj] + constructor + · rintro (h|(⟨hr,ha⟩|⟨hr,ha⟩)) + · exact Or.inl h + · subst r; subst a; exact Or.inr ⟨Or.inr ⟨rfl,rfl⟩,Ne.symm hne⟩ + · subst r; subst a; exact Or.inr ⟨Or.inl ⟨rfl,rfl⟩,hne⟩ + · rintro (h|⟨(⟨ha,hr⟩|⟨ha,hr⟩),_⟩) + · exact Or.inl h + · exact Or.inr (Or.inr ⟨hr,ha⟩) + · exact Or.inr (Or.inl ⟨hr,ha⟩) + +lemma join_code {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + (u v : Fin n) (hne : u≠v) : + join (graphCode G,(u.val,v.val))=graphCode (G⊔edge u v) := by + simp only [join,indices,graphCode_length,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map, + List.map_ofFn] + change List.ofFn (fun r : Fin n=>row ((graphCode G,(u.val,v.val)),r.val)) = + List.ofFn (adjacencyRow (G⊔edge u v)) + apply congrArg List.ofFn + funext r + simp only [row,vertices,indices,graphCode_length, + DirectedBFSCode.range_eq_map,List.filter_map,adjacencyRow] + apply congrArg (List.map Fin.val) + apply List.filter_congr + intro a _ + apply Bool.eq_iff_iff.mpr + simpa only [decide_eq_true_eq,Function.comp_apply] using keep_code G u v r a hne + +end ContingencyTables.ForestJoinProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLargeMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLargeMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..82647008716bf275a5ca961c42053ad08b9064df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLargeMarginal.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyApplication +import OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.EqualityReindex + +namespace OAI + +/-! +# The actual companion large-cell sum has its removal signature + +Small coordinates are the actual two views of small cells, and every +large cell is summed once at its physical balance width. All line and +unary factors have the manuscript's row/column and forest parameters. +-/ + +namespace ContingencyTables.ForestLargeMarginal + +open scoped BigOperators Classical +open SimpleGraph +open ForestPenaltyApplication LargePairEnumeration RowColumnPenalties BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def largeMarginal (small : I×J → Bool) + (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell small) (z : SmallView small → ℕ) : ℝ := + ∑ a : ((k : Fin n) → Fin (M (e k).val.1 (e k).val.2+1)), + physicalWeight T b ell M r c alpha + (joinedProfile (fun k => M (e k).val.1 (e k).val.2) z a ∘ + (physicalJoinEquiv small e).symm) + +theorem largeMarginal_nonnegative (small : I×J → Bool) + (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell small) (z : SmallView small → ℕ) : + 0≤largeMarginal small T b ell M r c alpha e z := by + apply Finset.sum_nonneg + intro a _ + exact physicalWeight_nonnegative T b ell M r c alpha _ + +private theorem largeMarginal_eq_eliminate (small : I×J → Bool) + (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell small) : + largeMarginal small T b ell M r c alpha e= + BalancedFamily.eliminate (widths (fun k => M (e k).val.1 (e k).val.2)) (fun q => + physicalWeight T b ell M r c alpha + (q ∘ (physicalCoordinateEquiv small e (fun k => M (e k).val.1 (e k).val.2)).symm)) := by + funext z + exact (eliminate_eq_actual_cells small e _ (physicalWeight T b ell M r c alpha) z).symm + +/-- This is a proved signature of the literal all-large finite count, +with the physical widths, retained small views, and coordinate map made +explicit. -/ +theorem largeMarginal_removal (small : I×J → Bool) + (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell small) (m : SmallView small → ℕ) (p : ℕ) + (ha : 0≤alpha) (hwidth : ∀ k, 2≤M (e k).val.1 (e k).val.2) : + RemovalSlice (largeMarginal small T b ell M r c alpha e) m p := by + let N : Fin n → ℕ := fun k => M (e k).val.1 (e k).val.2 + have hw : ∀ w ∈ widths N, 2≤w := widths_lower N hwidth + have hu : ∀ a, 0≤unaryRate T b alpha a := by + intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_refl 0 + have hs := EqualityReindex.physical_marginal_removal (widths N) m p + (physicalCoordinateEquiv small e N) cellLine (rootFlag T) (fun _ => alpha) + (lineOffset ell M r c) viewSlope (unaryRate T b alpha) (unaryEll ell) unarySlope (unaryCap b) + hw (fun _ => ha) hu + rw [largeMarginal_eq_eliminate small T b ell M r c alpha e] + + exact hs + +/-- Reflecting the retained views and every eliminated large pair proves +the complementary factorial lift's actual addition input. -/ +theorem largeMarginal_reflected (small : I×J → Bool) + (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell small) (m : SmallView small → ℕ) (p : ℕ) + (ha : 0≤alpha) (hwidth : ∀ k, 2≤M (e k).val.1 (e k).val.2) : + RemovalSlice (fun z => largeMarginal small T b ell M r c alpha e + (IntegerReflection.reflect m z)) m p := by + let N : Fin n → ℕ := fun k => M (e k).val.1 (e k).val.2 + have hu : ∀ a, 0≤unaryRate T b alpha a := by + intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_refl 0 + rw [largeMarginal_eq_eliminate small T b ell M r c alpha e] + exact EqualityReindex.physical_marginal_reflected (widths N) m p + (physicalCoordinateEquiv small e N) cellLine (rootFlag T) (fun _ => alpha) + (lineOffset ell M r c) viewSlope (unaryRate T b alpha) (unaryEll ell) unarySlope (unaryCap b) + (widths_lower N hwidth) (fun _ => ha) hu + +end ContingencyTables.ForestLargeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLiteralCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLiteralCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf912f4af5bb0f8a1044c92f86f459e0d6be31c3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestLiteralCount.lean @@ -0,0 +1,302 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyApplication + +namespace OAI + +/-! +# Literal doubled-coordinate profiles for companion completion counts + +Small views are retained separately. Every large pair is balanced, with +its physical tree or free-cell value represented in the prescribed finite +interval. These identities connect the concrete laminar factor family to +the actual graph completion sum. +-/ + +namespace ContingencyTables.ForestLiteralCount + +open scoped BigOperators Classical +open SimpleGraph +open GraphIntegralCompletion GraphCompletionCounts ForestCapacity + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def width (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) (i : I) (j : J) : ℕ := + if T.Adj (.inl i) (.inr j) then 20*d*b i j else b i j + +noncomputable def lower (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) (i : I) (j : J) : ℤ := + if T.Adj (.inl i) (.inr j) then -((10*d*b i j:ℕ):ℤ) else 0 + +noncomputable def cellCount (T : SimpleGraph (I⊕J)) (d : ℕ) (b free : I → J → ℕ) + (a : TreeIndex T d b) (i : I) (j : J) : ℕ := + if h : T.Adj (.inl i) (.inr j) then (a ⟨(i,j),h⟩).val else free i j + +noncomputable def profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (d : ℕ) (b x y free : I → J → ℕ) (a : TreeIndex T d b) (u : (I×J)×Bool) : ℕ := + if small u.1.1 u.1.2 then (if u.2 then y u.1.1 u.1.2 else x u.1.1 u.1.2) + else if u.2 then width T d b u.1.1 u.1.2-cellCount T d b free a u.1.1 u.1.2 + else cellCount T d b free a u.1.1 u.1.2 + +noncomputable def largeValue (T : SimpleGraph (I⊕J)) (tree : I → J → ℤ) + (free : I → J → ℕ) (i : I) (j : J) : ℤ := + if T.Adj (.inl i) (.inr j) then tree i j else free i j + +omit [Fintype I] [Fintype J] in +lemma cellCount_le (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (d : ℕ) (b free : I → J → ℕ) (a : TreeIndex T d b) + (hf : ∀ i j, small i j=false → ¬T.Adj (.inl i) (.inr j) → free i j≤b i j) + (i : I) (j : J) (hs : small i j=false) : cellCount T d b free a i j≤width T d b i j := by + by_cases ht : T.Adj (.inl i) (.inr j) + · simp only [cellCount,ht,dite_eq_left,width,ite_true] + have h := (a ⟨(i,j),ht⟩).isLt + change (a ⟨(i,j),ht⟩).val <20*d*b i j+1 at h + omega + · simp only [cellCount,ht,not_false_eq_true,dite_eq_right,width,ite_false] + exact hf i j hs ht + +omit [Fintype I] [Fintype J] in +lemma row_profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b x y free : I → J → ℕ) (a : TreeIndex T d b) + (i : I) (j : J) : + ForestPenaltyApplication.physicalRow (lower T d b) (profile small T d b x y free a) i j= + (if small i j then (x i j:ℤ) else largeValue T (physical T d b a) free i j : ℤ) := by + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + simp only [ForestPenaltyApplication.physicalRow,lower,profile,hs,Bool.false_eq_true, + ite_false,ht,ite_true,cellCount,dite_eq_left,largeValue,physical] + push_cast + ring + · simp only [ForestPenaltyApplication.physicalRow,lower,ht,ite_false,profile, + Bool.false_eq_true,cellCount,not_false_eq_true,dite_eq_right,largeValue] + split_ifs <;> norm_num + +omit [Fintype I] [Fintype J] in +lemma column_profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b x y free : I → J → ℕ) (a : TreeIndex T d b) + (hy : ∀ i j, small i j=true → y i j≤b i j) + (hf : ∀ i j, small i j=false → ¬T.Adj (.inl i) (.inr j) → free i j≤b i j) + (i : I) (j : J) : + ForestPenaltyApplication.physicalColumn (lower T d b) (width T d b) + (profile small T d b x y free a) i j= + (if small i j then ((b i j-y i j:ℕ):ℤ) + else largeValue T (physical T d b a) free i j : ℤ) := by + by_cases hs : small i j=true + · have ht : ¬T.Adj (.inl i) (.inr j) := by + intro h + have hh : small i j=false := hTG h + exact Bool.false_ne_true (hh.symm.trans hs) + simp only [ForestPenaltyApplication.physicalColumn,lower,width,ht,ite_false,profile, + hs,ite_true,Int.cast_zero,zero_add] + push_cast + rw [Nat.cast_sub (hy i j hs)] + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + have hbound := cellCount_le small T d b free a hf i j hs' + have hcol : ForestPenaltyApplication.physicalColumn (lower T d b) (width T d b) + (profile small T d b x y free a) i j= + ForestPenaltyApplication.physicalRow (lower T d b) (profile small T d b x y free a) i j := by + simp only [ForestPenaltyApplication.physicalColumn,ForestPenaltyApplication.physicalRow, + profile,hs',Bool.false_eq_true,ite_false,ite_true,Nat.cast_sub hbound] + ring + rw [hcol,row_profile small T hTG d b x y free a i j] + simp only [hs',Bool.false_eq_true,ite_false] + +noncomputable def actualDeviation (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b x y free : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (tree : I → J → ℤ) : I⊕J → ℝ := + Sum.elim + (fun i => ((∑ j, if small i j then (x i j:ℤ) else largeValue T tree free i j):ℤ)-r i) + (fun j => ((∑ i, if small i j then ((b i j-y i j:ℕ):ℤ) + else largeValue T tree free i j):ℤ)-c j) + +noncomputable def actualPenalty (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b x y free : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (tree : I → J → ℤ) : ℝ := + (∑ v, if ForestPenaltyApplication.rootFlag T v then + |actualDeviation small T b x y free r c tree v| else 0)+ + ∑ i, ∑ j, if T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-b i j))/(b i j:ℝ) else 0 + +lemma deviation_profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b x y free : I → J → ℕ) (a : TreeIndex T d b) + (r : I → ℤ) (c : J → ℤ) + (hy : ∀ i j, small i j=true → y i j≤b i j) + (hf : ∀ i j, small i j=false → ¬T.Adj (.inl i) (.inr j) → free i j≤b i j) : + ForestPenaltyApplication.deviation (lower T d b) (width T d b) r c + (profile small T d b x y free a)=actualDeviation small T b x y free r c (physical T d b a) := by + funext g + cases g with + | inl i => + simp only [ForestPenaltyApplication.deviation,actualDeviation,Sum.elim_inl] + push_cast + congr 1 + apply Finset.sum_congr rfl + intro j _ + simpa only [Int.cast_ite,Int.cast_natCast] using row_profile small T hTG d b x y free a i j + | inr j => + simp only [ForestPenaltyApplication.deviation,actualDeviation,Sum.elim_inr] + push_cast + congr 1 + apply Finset.sum_congr rfl + intro i _ + simpa only [Int.cast_ite,Int.cast_natCast] using column_profile small T hTG d b x y free a hy hf i j + +lemma penalty_profile (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (d : ℕ) (b x y free : I → J → ℕ) (a : TreeIndex T d b) + (r : I → ℤ) (c : J → ℤ) + (hy : ∀ i j, small i j=true → y i j≤b i j) + (hf : ∀ i j, small i j=false → ¬T.Adj (.inl i) (.inr j) → free i j≤b i j) : + ForestPenaltyApplication.penalty T b (lower T d b) (width T d b) r c + (profile small T d b x y free a)=actualPenalty small T b x y free r c (physical T d b a) := by + unfold ForestPenaltyApplication.penalty ForestPenaltyApplication.rootPenalty actualPenalty + rw [deviation_profile small T hTG d b x y free a r c hy hf] + congr 1 + unfold ForestPenaltyApplication.treePenalty + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + have hrow := row_profile small T hTG d b x y free a i j + simp only [hs,Bool.false_eq_true,ite_false,largeValue,ht,ite_true] at hrow + simp only [ht,ite_true,EqualitySoftening.affineDistance,mul_one] + rw [show (lower T d b i j:ℝ)+(profile small T d b x y free a ((i,j),false):ℝ)= + (physical T d b a i j:ℝ) from hrow] + · simp only [ht,ite_false] + +omit [Fintype I] [Fintype J] in +lemma row_pointwise (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (x free : I → J → ℕ) (tree : I → J → ℤ) + (hsupport : ∀ i j, ¬T.Adj (.inl i) (.inr j) → tree i j=0) (i : I) (j : J) : + (if small i j then (x i j:ℤ) else largeValue T tree free i j)=tree i j+ + ForestPhysicalCompletion.fixedRow small T (fun i j => (x i j:ℤ)) + (fun i j => (free i j:ℤ)) i j := by + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + simp only [hs,Bool.false_eq_true,ite_false,largeValue,ht,ite_true, + ForestPhysicalCompletion.fixedRow,add_zero] + · simp only [largeValue,ht,ite_false,hsupport i j ht,zero_add, + ForestPhysicalCompletion.fixedRow] + +omit [Fintype I] [Fintype J] in +lemma column_pointwise (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (b y free : I → J → ℕ) (tree : I → J → ℤ) + (hsupport : ∀ i j, ¬T.Adj (.inl i) (.inr j) → tree i j=0) (i : I) (j : J) : + (if small i j then ((b i j-y i j:ℕ):ℤ) else largeValue T tree free i j)=tree i j+ + ForestPhysicalCompletion.fixedColumn small T (fun i j => ((b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) i j := by + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + simp only [hs,Bool.false_eq_true,ite_false,largeValue,ht,ite_true, + ForestPhysicalCompletion.fixedColumn,add_zero] + · simp only [largeValue,ht,ite_false,hsupport i j ht,zero_add, + ForestPhysicalCompletion.fixedColumn] + +lemma nonroot_iff (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (b x y free : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) + (tree : I → J → ℤ) (hsupport : ∀ i j, ¬T.Adj (.inl i) (.inr j) → tree i j=0) : + (∀ g, ForestPenaltyApplication.rootFlag T g=false → + actualDeviation small T b x y free r c tree g=0) ↔ + NonrootMargins T + (ForestPhysicalCompletion.rowResidual small T r (fun i j => (x i j:ℤ)) + (fun i j => (free i j:ℤ))) + (ForestPhysicalCompletion.columnResidual small T c (fun i j => ((b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ))) tree := by + constructor + · intro h + constructor + · intro i hi + have hflag : ForestPenaltyApplication.rootFlag T (.inl i)=false := by + simpa only [ForestPenaltyApplication.rootFlag,decide_eq_false_iff_not] using hi + have hraw := h (.inl i) hflag + simp only [actualDeviation,Sum.elim_inl] at hraw + have hsum : (∑ j, if small i j then (x i j:ℤ) else largeValue T tree free i j)=r i := by + exact_mod_cast sub_eq_zero.mp hraw + simp_rw [row_pointwise small T hTG x free tree hsupport] at hsum + rw [Finset.sum_add_distrib] at hsum + unfold ForestPhysicalCompletion.rowResidual + omega + · intro j hj + have hflag : ForestPenaltyApplication.rootFlag T (.inr j)=false := by + simpa only [ForestPenaltyApplication.rootFlag,decide_eq_false_iff_not] using hj + have hraw := h (.inr j) hflag + simp only [actualDeviation,Sum.elim_inr] at hraw + have hsum : (∑ i, if small i j then ((b i j-y i j:ℕ):ℤ) + else largeValue T tree free i j)=c j := by exact_mod_cast sub_eq_zero.mp hraw + simp_rw [column_pointwise small T hTG b y free tree hsupport] at hsum + rw [Finset.sum_add_distrib] at hsum + unfold ForestPhysicalCompletion.columnResidual + omega + · intro h g hg + cases g with + | inl i => + have hi : Sum.inl i≠componentRoot T (.inl i) := by + simpa only [ForestPenaltyApplication.rootFlag,decide_eq_false_iff_not] using hg + have hsum : (∑ j, if small i j then (x i j:ℤ) else largeValue T tree free i j)=r i := by + simp_rw [row_pointwise small T hTG x free tree hsupport] + rw [Finset.sum_add_distrib,h.1 i hi] + exact sub_add_cancel _ _ + simp only [actualDeviation,Sum.elim_inl] + have hreal : (((∑ j, if small i j then (x i j:ℤ) + else largeValue T tree free i j):ℤ):ℝ)=(r i:ℝ) := by exact_mod_cast hsum + rw [hreal,sub_self] + | inr j => + have hj : Sum.inr j≠componentRoot T (.inr j) := by + simpa only [ForestPenaltyApplication.rootFlag,decide_eq_false_iff_not] using hg + have hsum : (∑ i, if small i j then ((b i j-y i j:ℕ):ℤ) + else largeValue T tree free i j)=c j := by + simp_rw [column_pointwise small T hTG b y free tree hsupport] + rw [Finset.sum_add_distrib,h.2 j hj] + exact sub_add_cancel _ _ + simp only [actualDeviation,Sum.elim_inr] + have hreal : (((∑ i, if small i j then ((b i j-y i j:ℕ):ℤ) + else largeValue T tree free i j):ℤ):ℝ)=(c j:ℝ) := by exact_mod_cast hsum + rw [hreal,sub_self] + +/-- For each actual small profile and free assignment, the concrete +laminar factor sum retains exactly the source's root/tree penalty at +the unique integral completion, with its tree values in the prescribed +completion intervals. -/ +theorem literal_tree_sum (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + MaximumForest.weight F (capacity b)≤MaximumForest.weight T (capacity b)) + (r : I → ℤ) (c : J → ℤ) (x y free : I → J → ℕ) (X : I → J → ℤ) + (d W : ℕ) (alpha : ℝ) (hd : 1≤d) (hcard : Fintype.card I*Fintype.card J≤d) + (hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j) + (hsmall : ∀ i j, small i j=true → b i j (x i j:ℤ)) + (fun i j => ((b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)))) := by + have hy : ∀ i j, small i j=true → y i j≤b i j := fun i j hs => (hsmall i j hs).2.2 + have hsum := ForestPhysicalCompletion.tree_indicator_sum small b T hTG hT hmax r c + (fun i j => (x i j:ℤ)) (fun i j => ((b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) X d W hd hcard hlarge + (by + intro i j hs + refine ⟨(hsmall i j hs).1,⟨Nat.cast_nonneg _,?_⟩,⟨Nat.cast_nonneg _,?_⟩⟩ + · exact_mod_cast (hsmall i j hs).2.1 + · exact_mod_cast Nat.sub_le (b i j) (y i j)) + (by + intro i j hs ht + exact ⟨Nat.cast_nonneg _,by exact_mod_cast hf i j hs ht⟩) + hX hXr hXc (fun tree => (2:ℝ)^(-alpha*actualPenalty small T b x y free r c tree)) + calc + _=(∑ a : TreeIndex T d b, + if NonrootMargins T + (ForestPhysicalCompletion.rowResidual small T r (fun i j => (x i j:ℤ)) + (fun i j => (free i j:ℤ))) + (ForestPhysicalCompletion.columnResidual small T c (fun i j => ((b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ))) (physical T d b a) + then (2:ℝ)^(-alpha*actualPenalty small T b x y free r c (physical T d b a)) else 0) := by + apply Finset.sum_congr rfl + intro a _ + rw [ForestPenaltyApplication.exact_eq,deviation_profile small T hTG d b x y free a r c hy hf, + penalty_profile small T hTG d b x y free a r c hy hf] + simp only [nonroot_iff small T hTG b x y free r c (physical T d b a) (physical_supported T d b a)] + _=_ := hsum + +end ContingencyTables.ForestLiteralCount + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..242d55e70fb30ff3d316c9e40e0cef0390d61afe --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyApplication.lean @@ -0,0 +1,184 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPhysicalCompletion +import OAI.Combinatorics.ContingencyTables.Transport.EqualitySoftening +import OAI.Combinatorics.ContingencyTables.Transport.RowColumnPenalties + +namespace OAI + +/-! +# Literal companion row/column and unary tree penalties + +The physical row view is ell+x; the physical column view is ell+M-y. +The line groups are the disjoint original row and column coordinates. +Roots are the actual chosen component roots of the large-cell forest. +Only the false (row) coordinate of each tree cell carries its interval +penalty. Thus the concrete exact factor family is precisely the source's +nonroot indicator times its root/tree penalty weight. +-/ + +namespace ContingencyTables.ForestPenaltyApplication + +open scoped BigOperators Classical Matrix +open SimpleGraph CommonBasesFPRAS +open EqualitySoftening ProductIntegerSignature ScalarPenalty +open ForestCapacity GraphIntegralCompletion RowColumnPenalties + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def physicalRow (ell : I → J → ℤ) (z : ((I×J)×Bool) → ℕ) (i : I) (j : J) : ℝ := + (ell i j:ℝ)+z ((i,j),false) + +noncomputable def physicalColumn (ell : I → J → ℤ) (M : I → J → ℕ) + (z : ((I×J)×Bool) → ℕ) (i : I) (j : J) : ℝ := + (ell i j:ℝ)+M i j-z ((i,j),true) + +noncomputable def lineOffset (ell : I → J → ℤ) (M : I → J → ℕ) + (r : I → ℤ) (c : J → ℤ) : I⊕J → ℝ := + Sum.elim (fun i => (∑ j, (ell i j:ℝ))-r i) + (fun j => (∑ i, ((ell i j:ℝ)+M i j))-c j) + +noncomputable def deviation (ell : I → J → ℤ) (M : I → J → ℕ) + (r : I → ℤ) (c : J → ℤ) (z : ((I×J)×Bool) → ℕ) : I⊕J → ℝ := + Sum.elim (fun i => (∑ j, physicalRow ell z i j)-r i) + (fun j => (∑ i, physicalColumn ell M z i j)-c j) + +lemma line_affine (ell : I → J → ℤ) (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) + (z : ((I×J)×Bool) → ℕ) (g : I⊕J) : + lineOffset ell M r c g+(lineTotal cellLine z g:ℝ)*viewSlope (I := I) (J := J) g= + deviation ell M r c z g := by + cases g with + | inl i => + rw [lineTotal_row] + simp only [lineOffset,deviation,Sum.elim_inl,viewSlope,mul_one,physicalRow,rowView] + push_cast + rw [Finset.sum_add_distrib] + ring + | inr j => + rw [lineTotal_column] + simp only [lineOffset,deviation,Sum.elim_inr,viewSlope,mul_neg_one,physicalColumn] + push_cast + rw [Finset.sum_sub_distrib] + ring + +noncomputable def rootFlag (T : SimpleGraph (I⊕J)) (v : I⊕J) : Bool := + decide (v=componentRoot T v) + +noncomputable def unaryRate (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) + (alpha : ℝ) (a : (I×J)×Bool) : ℝ := + if a.2=false ∧ T.Adj (.inl a.1.1) (.inr a.1.2) then alpha/b a.1.1 a.1.2 else 0 + +noncomputable def unaryEll (ell : I → J → ℤ) (a : (I×J)×Bool) : ℝ := ell a.1.1 a.1.2 + +def unarySlope (_ : (I×J)×Bool) : ℝ := 1 + +noncomputable def unaryCap (b : I → J → ℕ) (a : (I×J)×Bool) : ℝ := b a.1.1 a.1.2 + +noncomputable def rootPenalty (T : SimpleGraph (I⊕J)) (ell : I → J → ℤ) (M : I → J → ℕ) + (r : I → ℤ) (c : J → ℤ) (z : ((I×J)×Bool) → ℕ) : ℝ := + ∑ g, if rootFlag T g then |deviation ell M r c z g| else 0 + +noncomputable def treePenalty (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) + (ell : I → J → ℤ) (z : ((I×J)×Bool) → ℕ) : ℝ := + ∑ i, ∑ j, if T.Adj (.inl i) (.inr j) then + affineDistance (ell i j) 1 (b i j) (z ((i,j),false))/(b i j:ℝ) else 0 + +noncomputable def penalty (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (z : ((I×J)×Bool) → ℕ) : ℝ := + rootPenalty T ell M r c z+treePenalty T b ell z + +noncomputable def physicalWeight (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) : + (((I×J)×Bool) → ℕ) → ℝ := + exactWeight cellLine (rootFlag T) (fun _ => alpha) (lineOffset ell M r c) viewSlope + (unaryRate T b alpha) (unaryEll ell) unarySlope (unaryCap b) + +private lemma line_product_eq (T : SimpleGraph (I⊕J)) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) + (z : ((I×J)×Bool) → ℕ) + (h : ∀ g, rootFlag T g=false → deviation ell M r c z g=0) : + (∏ g, exactLineFactor (rootFlag T) (fun _ => alpha) (lineOffset ell M r c) + viewSlope g (lineTotal cellLine z g))=(2:ℝ)^(-alpha*rootPenalty T ell M r c z) := by + have hp : ∀ g, exactLineFactor (rootFlag T) (fun _ => alpha) (lineOffset ell M r c) + viewSlope g (lineTotal cellLine z g)= + (2:ℝ)^(-alpha*(if rootFlag T g then |deviation ell M r c z g| else 0)) := by + intro g + simp only [exactLineFactor,factor,line_affine] + cases hg : rootFlag T g + · simp [h g hg] + · simp + simp_rw [hp] + rw [← Real.rpow_sum_of_pos (by norm_num : (0:ℝ)<2)] + congr 1 + simp only [rootPenalty,Finset.mul_sum] + +private lemma unary_product_eq (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) + (ell : I → J → ℤ) (alpha : ℝ) (z : ((I×J)×Bool) → ℕ) : + (∏ a, unaryFactor (unaryRate T b alpha) (unaryEll ell) unarySlope (unaryCap b) a (z a))= + (2:ℝ)^(-alpha*treePenalty T b ell z) := by + unfold unaryFactor factor + rw [← Real.rpow_sum_of_pos (by norm_num : (0:ℝ)<2)] + congr 1 + rw [Fintype.sum_prod_type] + simp only [unaryRate,unaryEll,unarySlope,unaryCap,Fintype.sum_bool,Bool.true_eq_false, + false_and,ite_false,zero_mul,neg_zero,zero_add,true_and] + rw [Fintype.sum_prod_type] + simp only [treePenalty,Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> simp only [div_eq_mul_inv,mul_zero] <;> ring + +/-- This is the companion's literal root/tree exponential weight with +exact nonroot margin indicators, in the actual row/column coordinates. -/ +theorem exact_eq (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) (z : ((I×J)×Bool) → ℕ) : + physicalWeight T b ell M r c alpha z= + if (∀ g, rootFlag T g=false → deviation ell M r c z g=0) + then (2:ℝ)^(-alpha*penalty T b ell M r c z) else 0 := by + by_cases h : ∀ g, rootFlag T g=false → deviation ell M r c z g=0 + · rw [ite_eq_left h] + unfold physicalWeight exactWeight productWeight penalty + rw [line_product_eq T ell M r c alpha z h,unary_product_eq, + ← Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + ring + · rw [ite_eq_right h] + push Not at h + obtain ⟨g,hg,hdev⟩ := h + have hzero : exactLineFactor (rootFlag T) (fun _ => alpha) (lineOffset ell M r c) + viewSlope g (lineTotal cellLine z g)=0 := by + simp [exactLineFactor,hg,line_affine,hdev] + unfold physicalWeight exactWeight productWeight + rw [Finset.prod_eq_zero (Finset.mem_univ g) hzero,zero_mul] + +theorem physicalWeight_nonnegative (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) + (ell : I → J → ℤ) (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) + (alpha : ℝ) (z : ((I×J)×Bool) → ℕ) : 0≤physicalWeight T b ell M r c alpha z := by + rw [exact_eq] + split_ifs + · exact (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _).le + · exact le_refl 0 + +/-- The concrete unsummed factor family has the required raw removal +signature; its line and unary roles have all been physically instantiated. -/ +theorem exact_removal (T : SimpleGraph (I⊕J)) (b : I → J → ℕ) (ell : I → J → ℤ) + (M : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (alpha : ℝ) (ha : 0≤alpha) + (z : ((I×J)×Bool) → ℕ) : + OnePositiveDirection + (FactorialSignatures.integerRemovalMatrix (physicalWeight T b ell M r c alpha) z).toBilin' := by + have hu : ∀ a : (I×J)×Bool, 0≤unaryRate T b alpha a := by + intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_refl 0 + have hs := exactWeight_removal (C := (I×J)×Bool) (G := I⊕J) + cellLine (rootFlag T) (fun _ => alpha) (lineOffset ell M r c) + viewSlope (unaryRate T b alpha) (unaryEll ell) unarySlope (unaryCap b) + (fun _ => ha) hu z + convert hs using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +end ContingencyTables.ForestPenaltyApplication + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac48ce19cc61a1fb97a9ec60b6a22b325f75d6a7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyBound.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication +import OAI.Combinatorics.ContingencyTables.Rooted.ForestRootPenalty + +namespace OAI + +/-! # The literal companion completion penalty is bounded by H/A -/ + +namespace ContingencyTables.ForestPenaltyBound + +open scoped BigOperators Classical +open SimpleGraph CompanionFactorialApplication ForestCountIdentification +open ForestAssignmentSplit ForestPhysicalCompletion ForestLiteralCount ForestRootPenalty +open BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def penalty (A : Instance I J) (z : View A → ℕ) (f : FreeIndex A.small A.T A.b) : ℝ := + actualPenalty A.small A.T A.b (smallX A.small z) (smallY A.small z) + (freeTable A.small A.T A.b f) A.r A.c + (solved A.small A.T A.r A.c (fun i j => (smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-smallY A.small z i j:ℕ):ℤ)) + (fun i j => (freeTable A.small A.T A.b f i j:ℤ))) + +theorem penalty_bound (A : Instance I J) (z : View A → ℕ) (hz : InBox (bounds A) z) + (f : FreeIndex A.small A.T A.b) : + 0≤penalty A z f ∧ penalty A z f≤10*(A.d:ℝ)^2*((A.W:ℝ)+1) := by + let x := smallX A.small z + let y := smallY A.small z + let free := freeTable A.small A.T A.b f + let tree := solved A.small A.T A.r A.c (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) + have hx : ∀ i j, A.small i j=true → x i j≤A.b i j := by + intro i j hs + simpa only [x,smallX,hs,dite_eq_left,bounds] using hz (⟨(i,j),hs⟩,false) + have hroot := root_eq_large A.small A.b A.T A.hTG A.hT A.hmax + (fun i j hs => (A.hlarge i j hs).2) + have hR := rootPenalty_le A.small A.T A.hTG A.b x y free A.r A.c A.X + A.hXr A.hXc hroot hx A.hX + have hsmallSum : (∑ i, ∑ j, if A.small i j then (A.b i j:ℝ) else 0)≤ + (A.d:ℝ)*A.W := by + calc + _ ≤ ∑ _i : I, ∑ _j : J, (A.W:ℝ) := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + by_cases hs : A.small i j=true + · simp only [hs,ite_true] + exact_mod_cast (A.hsmall i j hs).le + · have hs' : A.small i j=false := Bool.eq_false_iff.mpr hs + simp [hs'] + _ = (Fintype.card I*Fintype.card J:ℕ)*(A.W:ℝ) := by simp; ring + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast A.hcard) (Nat.cast_nonneg _) + have hinterval := solved_in_intervals A.small A.b A.T A.hTG A.hT A.hmax A.r A.c + (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) A.X A.d A.W A.hd A.hcard A.hlarge + (by + intro i j hs + refine ⟨A.hsmall i j hs,⟨by positivity,by exact_mod_cast hx i j hs⟩, + ⟨by positivity,by exact_mod_cast Nat.sub_le (A.b i j) (y i j)⟩⟩) + (by + intro i j hs ht + exact ⟨by positivity,by exact_mod_cast freeTable_bound A.small A.T A.b f i j hs ht⟩) + A.hX A.hXr A.hXc + have hterm (i : I) (j : J) : + 0≤(if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0) ∧ + (if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0)≤10*(A.d:ℝ) := by + by_cases ht : A.T.Adj (.inl i) (.inr j) + · simp only [ht,ite_true] + have hb : (0:ℝ) linarith + · simp [ht] + have htree0 := Finset.sum_nonneg (s := Finset.univ) (fun i _ => + Finset.sum_nonneg (s := Finset.univ) (fun j _ => (hterm i j).1)) + have htree := Finset.sum_le_sum (s := Finset.univ) (fun i _ => + Finset.sum_le_sum (s := Finset.univ) (fun j _ => (hterm i j).2)) + have hcardR : (Fintype.card I*Fintype.card J:ℕ)≤(A.d:ℝ) := by exact_mod_cast A.hcard + have hdR : (1:ℝ)≤A.d := by exact_mod_cast A.hd + have hW : (0:ℝ)≤A.W := Nat.cast_nonneg _ + have htree' : (∑ i, ∑ j, if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0)≤10*(A.d:ℝ)^2 := by + calc + _ ≤ (Fintype.card I*Fintype.card J:ℕ)*(10*(A.d:ℝ)) := by simpa only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,Nat.cast_mul,mul_assoc] using htree + _ ≤ (A.d:ℝ)*(10*(A.d:ℝ)) := mul_le_mul_of_nonneg_right hcardR (by positivity) + _ = _ := by ring + change 0≤actualPenalty A.small A.T A.b x y free A.r A.c tree ∧ + actualPenalty A.small A.T A.b x y free A.r A.c tree≤_ + unfold actualPenalty + constructor + · apply add_nonneg _ htree0 + exact Finset.sum_nonneg (fun a _ => by split_ifs <;> positivity) + · have hsquare : (A.d:ℝ)≤(A.d:ℝ)^2 := by nlinarith + have hscale := mul_le_mul_of_nonneg_right hsquare hW + have hprod : 0≤(A.d:ℝ)^2*(A.W:ℝ) := mul_nonneg (sq_nonneg _) hW + nlinarith + +end ContingencyTables.ForestPenaltyBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac366aa30c7d5b609a8e8234d13a03d10c1c2daa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPenaltyProgram.lean @@ -0,0 +1,164 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineProgram + +namespace OAI + +/-! # Exact rational assembly of the companion forest penalty + +The natural root discrepancy and the finite list of tree affine forms +are combined by polynomial binary arithmetic to compute rationalD, +including the original maximum-forest cuts. +-/ + +namespace ContingencyTables.ForestPenaltyProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open CompanionFactorialApplication CompanionOracleDensity ForestAssignmentSplit GraphCompletionCounts +open ForestScaledPenalty +open scoped BigOperators Classical + +abbrev Input := (ℕ×ℕ)×List ForestAffineProgram.Input + +def rootFractionRealizer : Realizer (fun z : Input => (z.1.2,(1:ℕ))) := + pair (composition first second) (constant 1) + +def scaleFractionRealizer : Realizer (fun z : Input => (z.1.1,(1:ℕ))) := + pair (composition first first) (constant 1) + +def treeSum (z : Input) : TreeFraction.Fraction := + TreeFraction.sum (z.2.map ForestAffineProgram.evaluate) + +def treeSumRealizer : Realizer treeSum := + composition (f := fun z : Input => z.2.map ForestAffineProgram.evaluate) + (g := TreeFraction.sum) + (composition second (map ForestAffineProgram.evaluateRealizer)) TreeFraction.sumRealizer + +lemma polynomial_treeSum : PolynomialTime treeSumRealizer := + polynomial_composition (polynomial_composition polynomial_second + (polynomial_map ForestAffineProgram.polynomial_evaluate)) TreeFraction.polynomial_sum + +def penaltyCode (z : Input) : TreeFraction.Fraction := + TreeFraction.mul ((z.1.1,1),TreeFraction.add ((z.1.2,1),treeSum z)) + +def rootSumRealizer : Realizer (fun z : Input => TreeFraction.add ((z.1.2,1),treeSum z)) := + composition (f := fun z : Input => ((z.1.2,1),treeSum z)) (g := TreeFraction.add) + (pair rootFractionRealizer treeSumRealizer) TreeFraction.addRealizer + +lemma polynomial_rootSum : PolynomialTime rootSumRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_constant 1)) polynomial_treeSum) TreeFraction.polynomial_add + +def penaltyCodeRealizer : Realizer penaltyCode := + composition (f := fun z : Input => ((z.1.1,1),TreeFraction.add ((z.1.2,1),treeSum z))) + (g := TreeFraction.mul) + (pair scaleFractionRealizer rootSumRealizer) + TreeFraction.mulRealizer + +theorem polynomial_penaltyCode : PolynomialTime penaltyCodeRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) (polynomial_constant 1)) + polynomial_rootSum) TreeFraction.polynomial_mul + +lemma penaltyCode_value (z : Input) : + TreeFraction.val (penaltyCode z)=(z.1.1:ℚ)* + ((z.1.2:ℚ)+(z.2.map (fun t => TreeFraction.val (ForestAffineProgram.evaluate t))).sum) := by + rw [penaltyCode,TreeFraction.mul_val,TreeFraction.add_val _ _ (show (1:ℕ)≠0 from Nat.one_ne_zero) (by + exact (TreeFraction.sum_den _).ne')] + rw [show TreeFraction.val (z.1.1,1)=(z.1.1:ℚ) by simp [TreeFraction.val], + show TreeFraction.val (z.1.2,1)=(z.1.2:ℚ) by simp [TreeFraction.val]] + rw [treeSum,TreeFraction.sum_val] + · simp only [List.map_map,Function.comp_def] + · intro f hf + obtain ⟨t,_,rfl⟩ := List.mem_map.mp hf + exact RationalIntervalProgram.intervalCode_denominator _ + + +abbrev ExponentInput := (ℕ×ℕ)×Input + +def weightedPenalty (z : ExponentInput) : TreeFraction.Fraction := + TreeFraction.mul (z.1,penaltyCode z.2) + +def weightedPenaltyRealizer : Realizer weightedPenalty := + composition (f := fun z : ExponentInput => (z.1,penaltyCode z.2)) (g := TreeFraction.mul) + (pair first (composition (f := fun z : ExponentInput => z.2) (g := penaltyCode) + second penaltyCodeRealizer)) TreeFraction.mulRealizer + +lemma polynomial_weightedPenalty : PolynomialTime weightedPenaltyRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_penaltyCode)) TreeFraction.polynomial_mul + +def exponentCode (z : ExponentInput) : ℕ := (weightedPenalty z).1/(weightedPenalty z).2 + +def exponentCodeRealizer : Realizer exponentCode := + composition (f := weightedPenalty) (g := fun f : TreeFraction.Fraction => f.1/f.2) + weightedPenaltyRealizer quotient + +theorem polynomial_exponentCode : PolynomialTime exponentCodeRealizer := + polynomial_composition polynomial_weightedPenalty polynomial_quotient + +lemma exponentCode_value (z : ExponentInput) : + exponentCode z=⌊(z.1.1:ℚ)/z.1.2*TreeFraction.val (penaltyCode z.2)⌋₊ := by + have h := FractionAcceptanceProgram.fraction_threshold 0 (weightedPenalty z) + simp only [FairBits.rationalThreshold,pow_zero,one_mul,Nat.mul_one] at h + rw [exponentCode,←h,weightedPenalty,TreeFraction.mul_val] + rfl + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- This is the integral root part occurring in the source's exact +forest completion, before multiplying by the softening strength. -/ +def rootCount (A : Instance I J) (x y : I → J → ℤ) : ℕ := + ∑ a : I⊕J,if ForestPenaltyApplication.rootFlag A.T a then + (ForestRootPenalty.signedResidual A.small A.T A.r A.c x y 0 a).natAbs else 0 + +lemma rootCount_cast (A : Instance I J) (x y : I → J → ℤ) : + (rootCount A x y:ℚ)=rationalRootConstant A x y := by + unfold rootCount rationalRootConstant + rw [Nat.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs + · rw [←Int.cast_natCast,Int.natCast_natAbs,Int.cast_abs] + · exact Nat.cast_zero + +variable {q t : ℕ} + +def data (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (trees : Fin t ≃ TreeCell A.T) (free : Fin q ≃ FreeCell A.small A.T) + (v : FreeCell A.small A.T → ℕ) : Input := + ((C,rootCount A (rowCounts A z) (columnCounts A z)), + List.ofFn (fun i => ForestAffineProgram.forestData A C (trees i) + (rowCounts A z) (columnCounts A z) free v)) + +/-- The compiled finite arithmetic computes the actual rational penalty; +this statement uses no oracle or approximate-evaluation premise. -/ +theorem penaltyCode_data (A : Instance I J) (C : ℕ) (hC : 0 (v (index A i):ℚ)) := by + rw [penaltyCode_value] + simp only [data,List.map_ofFn,Function.comp_apply,List.sum_ofFn,rootCount_cast, + ForestAffineProgram.evaluate_forest A C hC] + unfold rationalD + congr 2 + have hv : (fun f : FreeCell A.small A.T => (v (index A ((index A).symm f)):ℚ))= + (fun f => (v f:ℚ)) := by + funext f + rw [Equiv.apply_symm_apply] + rw [hv] + exact Fintype.sum_equiv trees _ _ (fun _ => rfl) + + +theorem exponentCode_data (A : Instance I J) (C a : ℕ) (hC : 0 (v (index A i):ℚ))⌋₊ := by + rw [exponentCode_value,penaltyCode_data A C hC] + +end +end ContingencyTables.ForestPenaltyProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPhysicalCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPhysicalCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc21490ff27e96f28e04b286892775954cb14a1a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestPhysicalCompletion.lean @@ -0,0 +1,203 @@ +import OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionCounts + +namespace OAI + +/-! +# The companion's actual small/free profiles and tree intervals + +Residual margins subtract the two separate small views and the fixed +free values. The integral graph completion satisfies every nonroot line. +The maximum-forest cut bound then supplies, rather than assumes, the +physical tree interval used by the signature/count marginal. +-/ + +namespace ContingencyTables.ForestPhysicalCompletion + +open scoped BigOperators Classical +open SimpleGraph +open ForestCapacity GraphIntegralCompletion GraphCompletionCounts + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def fixedRow (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (x free : I → J → ℤ) (i : I) (j : J) : ℤ := + if small i j then x i j else if T.Adj (.inl i) (.inr j) then 0 else free i j + +noncomputable def fixedColumn (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (q free : I → J → ℤ) (i : I) (j : J) : ℤ := + if small i j then q i j else if T.Adj (.inl i) (.inr j) then 0 else free i j + +noncomputable def rowResidual (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (x free : I → J → ℤ) (i : I) : ℤ := + r i-∑ j, fixedRow small T x free i j + +noncomputable def columnResidual (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (c : J → ℤ) (q free : I → J → ℤ) (j : J) : ℤ := + c j-∑ i, fixedColumn small T q free i j + +noncomputable def solved (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) : I → J → ℤ := + tableCompletion T (rowResidual small T r x free) (columnResidual small T c q free) + +noncomputable def completed (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) (i : I) (j : J) : ℤ := + if T.Adj (.inl i) (.inr j) then solved small T r c x q free i j else free i j + +lemma row_pointwise (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) + (i : I) (j : J) : + (if small i j then x i j else completed small T r c x q free i j)= + solved small T r c x q free i j+fixedRow small T x free i j := by + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + simp only [hs,Bool.false_eq_true,ite_false,completed,ht,ite_true,fixedRow,add_zero] + · have hz : solved small T r c x q free i j=0 := tableCompletion_supported T _ _ i j ht + simp only [completed,ht,ite_false,hz,zero_add,fixedRow] + +lemma column_pointwise (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) + (i : I) (j : J) : + (if small i j then q i j else completed small T r c x q free i j)= + solved small T r c x q free i j+fixedColumn small T q free i j := by + by_cases ht : T.Adj (.inl i) (.inr j) + · have hs : small i j=false := hTG ht + simp only [hs,Bool.false_eq_true,ite_false,completed,ht,ite_true,fixedColumn,add_zero] + · have hz : solved small T r c x q free i j=0 := tableCompletion_supported T _ _ i j ht + simp only [completed,ht,ite_false,hz,zero_add,fixedColumn] + +lemma row_completed_sum (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) + (i : I) (hi : Sum.inl i≠componentRoot T (.inl i)) : + (∑ j, if small i j then x i j else completed small T r c x q free i j)=r i := by + simp_rw [row_pointwise small T hTG r c x q free] + rw [Finset.sum_add_distrib,show (∑ j, solved small T r c x q free i j)= + rowResidual small T r x free i from tableCompletion_row small T hTG _ _ i hi] + exact sub_add_cancel _ _ + +lemma column_completed_sum (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) + (j : J) (hj : Sum.inr j≠componentRoot T (.inr j)) : + (∑ i, if small i j then q i j else completed small T r c x q free i j)=c j := by + simp_rw [column_pointwise small T hTG r c x q free] + rw [Finset.sum_add_distrib,show (∑ i, solved small T r c x q free i j)= + columnResidual small T c q free j from tableCompletion_column small T hTG _ _ j hj] + exact sub_add_cancel _ _ + +omit [Fintype I] [Fintype J] in +lemma nonroot_of_root_component (T : SimpleGraph (I⊕J)) (u v : I⊕J) + (h : T.Reachable (componentRoot T u) v) (hv : v≠componentRoot T u) : + v≠componentRoot T v := by + have he : componentRoot T v=componentRoot T u := by + rw [← componentRoot_constant T h,componentRoot_idempotent] + simpa only [he] using hv + +/-- The completion interval holds for the literal residual +margin equations, including every box-valid unbalanced small profile. -/ +theorem solved_in_intervals (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + MaximumForest.weight F (capacity b)≤MaximumForest.weight T (capacity b)) + (r : I → ℤ) (c : J → ℤ) (x q free X : I → J → ℤ) (d W : ℕ) + (hd : 1≤d) (hcard : Fintype.card I*Fintype.card J≤d) + (hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j) + (hsmall : ∀ i j, small i j=true → b i j (x i j:ℝ)) (fun i j => (q i j:ℝ)) + (fun i j => (completed small T r c x q free i j:ℝ)) (fun i j => (X i j:ℝ)) + (d:ℝ) W (by exact_mod_cast hd) (by exact_mod_cast hcard) hlarge + (by + intro i j hs + exact ⟨(hsmall i j hs).1,by exact_mod_cast (hsmall i j hs).2.1, + by exact_mod_cast (hsmall i j hs).2.2⟩) + (by intro i j; exact_mod_cast hX i j) + (by + intro i j hs htree + have hn : ¬T.Adj (.inl i) (.inr j) := by + simpa only [treeCell,decide_eq_false_iff_not] using htree + simp only [completed,hn,ite_false] + have hf := hfree i j hs hn + constructor + · exact_mod_cast hf.1 + · have hcast : (free i j:ℝ)≤(b i j:ℝ) := by exact_mod_cast hf.2 + linarith) + (by + intro i hcomp hi + have hrow := row_completed_sum small T hTG r c x q free i + (nonroot_of_root_component T (.inl i₀) (.inl i) hcomp hi) + have hrowR : (∑ j, if small i j then (x i j:ℝ) else + (completed small T r c x q free i j:ℝ))=(r i:ℝ) := by exact_mod_cast hrow + have hXR : (∑ j, (X i j:ℝ))=(r i:ℝ) := by exact_mod_cast hXr i + unfold ForestCut.rowDifference + calc + _=(∑ j, if small i j then (x i j:ℝ) else + (completed small T r c x q free i j:ℝ))-(∑ j, (X i j:ℝ)) := by + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> rfl + _=0 := by rw [hrowR,hXR,sub_self]) + (by + intro j hcomp hj + have hcol := column_completed_sum small T hTG r c x q free j + (nonroot_of_root_component T (.inl i₀) (.inr j) hcomp hj) + have hcolR : (∑ i, if small i j then (q i j:ℝ) else + (completed small T r c x q free i j:ℝ))=(c j:ℝ) := by exact_mod_cast hcol + have hXC : (∑ i, (X i j:ℝ))=(c j:ℝ) := by exact_mod_cast hXc j + unfold ForestCut.columnDifference + calc + _=(∑ i, if small i j then (q i j:ℝ) else + (completed small T r c x q free i j:ℝ))-(∑ i, (X i j:ℝ)) := by + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> rfl + _=0 := by rw [hcolR,hXC,sub_self]) + simp only [completed,ht,ite_true] at hb + constructor + · have hlow : (-10:ℤ)*(d:ℤ)*(b i₀ j₀:ℤ) ≤ solved small T r c x q free i₀ j₀ := by + exact_mod_cast hb.1 + convert hlow using 1 + push_cast + ring + · exact_mod_cast hb.2 + +/-- For the literal small/free residual margins, the equality-limit +sum over the prescribed tree intervals retains exactly one term, with +precisely the weight of the source's solved tree values. -/ +theorem tree_indicator_sum (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + MaximumForest.weight F (capacity b)≤MaximumForest.weight T (capacity b)) + (r : I → ℤ) (c : J → ℤ) (x q free X : I → J → ℤ) (d W : ℕ) + (hd : 1≤d) (hcard : Fintype.card I*Fintype.card J≤d) + (hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j) + (hsmall : ∀ i j, small i j=true → b i j Finset.abs_sum_le_sum_abs _ _) + _ = _ := by + have he (a v : V) : |if root v=a then r v else 0|= + if root v=a then |r v| else 0 := by split_ifs <;> simp + simp_rw [he] + rw [Finset.sum_comm] + simp + +end Generic + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Maximum capacity makes every original large edge stay within a tree +component, which is the exact cancellation needed at component roots. -/ +lemma root_eq_large (small : I → J → Bool) (b : I → J → ℕ) + (T : SimpleGraph (I⊕J)) (hT : T≤ForestCapacity.cellGraph small) (hacyc : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph (I⊕J), F≤ForestCapacity.cellGraph small → F.IsAcyclic → + MaximumForest.weight F (ForestCapacity.capacity b)≤MaximumForest.weight T (ForestCapacity.capacity b)) + (hb : ∀ i j, small i j=false → 1≤b i j) (i : I) (j : J) (hs : small i j=false) : + componentRoot T (.inl i)=componentRoot T (.inr j) := by + have hcap : ∀ e∈(ForestCapacity.cellGraph small).edgeSet, 0 + cases v with + | inl i' => exact False.elim hg + | inr j => exact hb i j hg + | inr j => + cases v with + | inl i => exact hb i j hg + | inr j' => exact False.elim hg + have hspans := MaximumForest.maximum_spans (ForestCapacity.cellGraph small) T + (ForestCapacity.capacity b) hT hacyc hmax hcap + apply componentRoot_constant T + rw [hspans] + exact (show (ForestCapacity.cellGraph small).Adj (.inl i) (.inr j) from hs).reachable + +lemma tableCompletion_row_all (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) (i : I) : + (∑ j, tableCompletion T r c i j)= + r i-∑ v, if componentRoot T v=Sum.inl i then Sum.elim r (fun j => -c j) v else 0 := by + have hs := completionFlow_divergence_all T (Sum.elim r (fun j => -c j)) (.inl i) + rw [Fintype.sum_sum_type] at hs + have hzero : (∑ i', completionFlow T (Sum.elim r (fun j => -c j)) (.inl i) (.inl i'))=0 := by + apply Finset.sum_eq_zero + intro i' _ + apply completionFlow_supported + intro h + exact hT h + simpa only [hzero,zero_add,Sum.elim_inl,tableCompletion] using hs + +lemma tableCompletion_column_all (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) (j : J) : + -(∑ i, tableCompletion T r c i j)= + -c j-∑ v, if componentRoot T v=Sum.inr j then Sum.elim r (fun j => -c j) v else 0 := by + have hs := completionFlow_divergence_all T (Sum.elim r (fun j => -c j)) (.inr j) + rw [Fintype.sum_sum_type] at hs + have hzero : (∑ j', completionFlow T (Sum.elim r (fun j => -c j)) (.inr j) (.inr j'))=0 := by + apply Finset.sum_eq_zero + intro j' _ + apply completionFlow_supported + intro h + exact hT h + have hskew : (∑ i, completionFlow T (Sum.elim r (fun j => -c j)) (.inr j) (.inl i))= + -(∑ i, tableCompletion T r c i j) := by + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + exact completionFlow_skew T _ _ _ + simpa only [hzero,add_zero,Sum.elim_inr,hskew] using hs + +noncomputable def residualDemand (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) : I⊕J → ℤ := + Sum.elim (rowResidual small T r x free) (fun j => -columnResidual small T c q free j) + +noncomputable def componentTotal (T : SimpleGraph (I⊕J)) (d : I⊕J → ℤ) (a : I⊕J) : ℤ := + ∑ v, (if componentRoot T v=a then 1 else 0)*d v + +noncomputable def smallDemand (small : I → J → Bool) (X x q : I → J → ℤ) : I⊕J → ℤ := + Sum.elim (fun i => ∑ j, if small i j then X i j-x i j else 0) + (fun j => ∑ i, if small i j then q i j-X i j else 0) + +/-- Large-cell incidences cancel exactly within each component. The +component residual therefore depends only on the small views, not on +the chosen free values. -/ +theorem componentTotal_residual (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (c : J → ℤ) (x q free X : I → J → ℤ) + (hr : ∀ i, (∑ j, X i j)=r i) (hc : ∀ j, (∑ i, X i j)=c j) + (hroot : ∀ i j, small i j=false → componentRoot T (.inl i)=componentRoot T (.inr j)) + (a : I⊕J) : + componentTotal T (residualDemand small T r c x q free) a= + componentTotal T (smallDemand small X x q) a := by + let R : I → ℤ := fun i => if componentRoot T (.inl i)=a then 1 else 0 + let C : J → ℤ := fun j => if componentRoot T (.inr j)=a then 1 else 0 + have hrow (i : I) : R i*rowResidual small T r x free i= + ∑ j, R i*(X i j-fixedRow small T x free i j) := by + rw [rowResidual,← hr i,← Finset.sum_sub_distrib,Finset.mul_sum] + have hcol (j : J) : C j*(-columnResidual small T c q free j)= + ∑ i, C j*(fixedColumn small T q free i j-X i j) := by + rw [columnResidual,← hc j,neg_sub,← Finset.sum_sub_distrib,Finset.mul_sum] + unfold componentTotal residualDemand smallDemand + rw [Fintype.sum_sum_type,Fintype.sum_sum_type] + simp only [Sum.elim_inl,Sum.elim_inr] + change (∑ i, R i*rowResidual small T r x free i)+ + (∑ j, C j*(-columnResidual small T c q free j))= + (∑ i, R i*(∑ j, if small i j then X i j-x i j else 0))+ + ∑ j, C j*(∑ i, if small i j then q i j-X i j else 0) + simp_rw [hrow,hcol,Finset.mul_sum] + rw [Finset.sum_comm (f := fun j i => C j*(fixedColumn small T q free i j-X i j)), + Finset.sum_comm (f := fun j i => C j*(if small i j then q i j-X i j else 0)), + ← Finset.sum_add_distrib,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [← Finset.sum_add_distrib,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + by_cases hs : small i j=true + · simp [fixedRow,fixedColumn,hs] + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + have he : R i=C j := by unfold R C; rw [hroot i j hs'] + rw [he] + simp only [fixedRow,fixedColumn,hs',Bool.false_eq_true,ite_false] + ring + +noncomputable def signedResidual (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (r : I → ℤ) (c : J → ℤ) (x q free : I → J → ℤ) : I⊕J → ℤ := + Sum.elim + (fun i => (∑ j, if small i j then x i j else completed small T r c x q free i j)-r i) + (fun j => -((∑ i, if small i j then q i j else completed small T r c x q free i j)-c j)) + +/-- The actual completed table's signed root discrepancy is exactly the +negative component total of its original residual demands. -/ +theorem signedResidual_eq_component (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) + (x q free : I → J → ℤ) (a : I⊕J) : + signedResidual small T r c x q free a= + -(∑ v, if componentRoot T v=a then residualDemand small T r c x q free v else 0) := by + cases a with + | inl i => + simp only [signedResidual,Sum.elim_inl] + simp_rw [row_pointwise small T hT r c x q free] + rw [Finset.sum_add_distrib] + have hr := tableCompletion_row_all small T hT + (rowResidual small T r x free) (columnResidual small T c q free) i + change (∑ j, solved small T r c x q free i j)=_ at hr + rw [hr] + unfold residualDemand rowResidual columnResidual + ring + | inr j => + simp only [signedResidual,Sum.elim_inr] + simp_rw [column_pointwise small T hT r c x q free] + rw [Finset.sum_add_distrib] + have hc := tableCompletion_column_all small T hT + (rowResidual small T r x free) (columnResidual small T c q free) j + change -(∑ i, solved small T r c x q free i j)=_ at hc + have hc' : (∑ i, solved small T r c x q free i j)= + columnResidual small T c q free j+ + ∑ v, if componentRoot T v=Sum.inr j then + Sum.elim (rowResidual small T r x free) (fun j => -columnResidual small T c q free j) v else 0 := by + linarith + rw [hc'] + unfold residualDemand rowResidual columnResidual + ring + +theorem signedResidual_eq_small (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) + (x q free X : I → J → ℤ) + (hr : ∀ i, (∑ j, X i j)=r i) (hc : ∀ j, (∑ i, X i j)=c j) + (hroot : ∀ i j, small i j=false → componentRoot T (.inl i)=componentRoot T (.inr j)) + (a : I⊕J) : signedResidual small T r c x q free a= + -componentTotal T (smallDemand small X x q) a := by + rw [signedResidual_eq_component small T hT r c x q free a] + have he : (∑ v, if componentRoot T v=a then residualDemand small T r c x q free v else 0)= + componentTotal T (residualDemand small T r c x q free) a := by + simp [componentTotal,ite_mul] + rw [he,componentTotal_residual small T r c x q free X hr hc hroot a] + +/-- The original root deviations do not depend on the free assignment; +this follows from the actual integral completion, rather than an assumed +affine representation of the source count. -/ +theorem signedResidual_independent (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) + (x q free free' X : I → J → ℤ) + (hr : ∀ i, (∑ j, X i j)=r i) (hc : ∀ j, (∑ i, X i j)=c j) + (hroot : ∀ i j, small i j=false → componentRoot T (.inl i)=componentRoot T (.inr j)) : + signedResidual small T r c x q free=signedResidual small T r c x q free' := by + funext a + rw [signedResidual_eq_small small T hT r c x q free X hr hc hroot a, + signedResidual_eq_small small T hT r c x q free' X hr hc hroot a] + +theorem sum_abs_signedResidual_le (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (b : I → J → ℕ) + (r : I → ℤ) (c : J → ℤ) (x q free X : I → J → ℤ) + (hr : ∀ i, (∑ j, X i j)=r i) (hc : ∀ j, (∑ i, X i j)=c j) + (hroot : ∀ i j, small i j=false → componentRoot T (.inl i)=componentRoot T (.inr j)) + (hx : ∀ i j, small i j=true → 0≤x i j ∧ x i j≤b i j) + (hq : ∀ i j, small i j=true → 0≤q i j ∧ q i j≤b i j) + (hX : ∀ i j, 0≤X i j ∧ X i j≤b i j) : + (∑ a, |(signedResidual small T r c x q free a:ℝ)|)≤ + 2*∑ i, ∑ j, if small i j then (b i j:ℝ) else 0 := by + have he (a : I⊕J) : (signedResidual small T r c x q free a:ℝ)= + -(∑ v, if componentRoot T v=a then (smallDemand small X x q v:ℝ) else 0) := by + rw [signedResidual_eq_small small T hT r c x q free X hr hc hroot a] + unfold componentTotal + push_cast + congr 1 + apply Finset.sum_congr rfl + intro v _ + by_cases hv : componentRoot T v=a <;> simp [hv] + simp_rw [he,abs_neg] + apply (sum_abs_componentTotal (componentRoot T) (fun v => (smallDemand small X x q v:ℝ))).trans + have hrow (i : I) : + |((∑ j, if small i j then X i j-x i j else 0:ℤ):ℝ)|≤ + ∑ j, if small i j then (b i j:ℝ) else 0 := by + push_cast + apply (Finset.abs_sum_le_sum_abs _ _).trans + apply Finset.sum_le_sum + intro j _ + by_cases hs : small i j=true + · simp only [hs,ite_true] + have hh : |X i j-x i j|≤(b i j:ℤ) := by + apply abs_le.mpr + constructor <;> linarith [(hx i j hs).1,(hx i j hs).2,(hX i j).1,(hX i j).2] + exact_mod_cast hh + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + simp [hs'] + have hcol (j : J) : + |((∑ i, if small i j then q i j-X i j else 0:ℤ):ℝ)|≤ + ∑ i, if small i j then (b i j:ℝ) else 0 := by + push_cast + apply (Finset.abs_sum_le_sum_abs _ _).trans + apply Finset.sum_le_sum + intro i _ + by_cases hs : small i j=true + · simp only [hs,ite_true] + have hh : |q i j-X i j|≤(b i j:ℤ) := by + apply abs_le.mpr + constructor <;> linarith [(hq i j hs).1,(hq i j hs).2,(hX i j).1,(hX i j).2] + exact_mod_cast hh + · have hs' : small i j=false := Bool.eq_false_iff.mpr hs + simp [hs'] + rw [Fintype.sum_sum_type] + change (∑ i, |((∑ j, if small i j then X i j-x i j else 0:ℤ):ℝ)|)+ + (∑ j, |((∑ i, if small i j then q i j-X i j else 0:ℤ):ℝ)|)≤_ + have hrows := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hrow i) + have hcols := Finset.sum_le_sum (s := Finset.univ) (fun j _ => hcol j) + rw [Finset.sum_comm] at hcols + linarith + +lemma abs_actualDeviation_solved (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (b x y free : I → J → ℕ) (r : I → ℤ) (c : J → ℤ) (a : I⊕J) : + |actualDeviation small T b x y free r c + (solved small T r c (fun i j => (x i j:ℤ)) + (fun i j => ((b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ))) a|= + |(signedResidual small T r c (fun i j => (x i j:ℤ)) + (fun i j => ((b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) a:ℝ)| := by + cases a with + | inl i => + simp only [actualDeviation,signedResidual,Sum.elim_inl,completed,largeValue] + push_cast + rfl + | inr j => + simp only [actualDeviation,signedResidual,Sum.elim_inr,completed,largeValue] + push_cast + rw [abs_neg] + +/-- This is the root part of the source's actual penalty. Each small +cell contributes at most its capacity at each of its two incidences. -/ +theorem rootPenalty_le (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (b x y free : I → J → ℕ) + (r : I → ℤ) (c : J → ℤ) (X : I → J → ℤ) + (hr : ∀ i, (∑ j, X i j)=r i) (hc : ∀ j, (∑ i, X i j)=c j) + (hroot : ∀ i j, small i j=false → componentRoot T (.inl i)=componentRoot T (.inr j)) + (hx : ∀ i j, small i j=true → x i j≤b i j) + (hX : ∀ i j, 0≤X i j ∧ X i j≤b i j) : + (∑ a, if ForestPenaltyApplication.rootFlag T a then + |actualDeviation small T b x y free r c + (solved small T r c (fun i j => (x i j:ℤ)) + (fun i j => ((b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ))) a| else 0)≤ + 2*∑ i, ∑ j, if small i j then (b i j:ℝ) else 0 := by + apply le_trans (Finset.sum_le_sum (fun a _ => ?_)) + (sum_abs_signedResidual_le small T hT b r c + (fun i j => (x i j:ℤ)) (fun i j => ((b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) X hr hc hroot + (by intro i j hs; exact ⟨by positivity,by exact_mod_cast hx i j hs⟩) + (by intro i j _; exact ⟨by positivity,by exact_mod_cast Nat.sub_le (b i j) (y i j)⟩) + hX) + split_ifs + · exact (abs_actualDeviation_solved small T b x y free r c a).le + · exact abs_nonneg _ + +end ContingencyTables.ForestRootPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..178f06faa244bbb3c867241f241981ad18d1745e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledBounds.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledIdentification + +namespace OAI + +/-! # The actual continuous forest penalty stays within the source allowance -/ + +namespace ContingencyTables.ForestScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication GraphCompletionCounts ForestAssignmentSplit +open ForestAffineCoefficients ForestPhysicalCompletion ForestRootPenalty +open ForestCountIdentification BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def rowCounts (A : Instance I J) (z : View A → ℕ) : I → J → ℤ := + fun i j => (smallX A.small z i j:ℤ) + +noncomputable def columnCounts (A : Instance I J) (z : View A → ℕ) : I → J → ℤ := + fun i j => ((A.b i j-smallY A.small z i j:ℕ):ℤ) + +lemma rowCounts_bounds (A : Instance I J) (z : View A → ℕ) (hz : InBox (bounds A) z) + (i : I) (j : J) (hs : A.small i j=true) : + 0 ≤ rowCounts A z i j ∧ rowCounts A z i j ≤ A.b i j := by + refine ⟨Nat.cast_nonneg _,?_⟩ + have hh : smallX A.small z i j ≤ A.b i j := by + simpa only [smallX,hs,dite_eq_left,bounds] using hz (⟨(i,j),hs⟩,false) + change (smallX A.small z i j:ℤ) ≤ (A.b i j:ℤ) + exact_mod_cast hh + +lemma columnCounts_bounds (A : Instance I J) (z : View A → ℕ) (i : I) (j : J) : + 0 ≤ columnCounts A z i j ∧ columnCounts A z i j ≤ A.b i j := by + unfold columnCounts + exact ⟨Nat.cast_nonneg _,by exact_mod_cast Nat.sub_le (A.b i j) (smallY A.small z i j)⟩ + +lemma rootConstant_bound (A : Instance I J) (z : View A → ℕ) (hz : InBox (bounds A) z) : + rootConstant A (rowCounts A z) (columnCounts A z) ≤ 2*(A.d:ℝ)*A.W := by + have hroot := root_eq_large A.small A.b A.T A.hTG A.hT A.hmax + (fun i j hs => (A.hlarge i j hs).2) + have hh := sum_abs_signedResidual_le A.small A.T A.hTG A.b A.r A.c + (rowCounts A z) (columnCounts A z) 0 A.X A.hXr A.hXc hroot + (rowCounts_bounds A z hz) (fun i j _ => columnCounts_bounds A z i j) A.hX + have hsmall : (∑ i,∑ j,if A.small i j then (A.b i j:ℝ) else 0) ≤ (A.d:ℝ)*A.W := by + calc + _ ≤ ∑ _i : I,∑ _j : J,(A.W:ℝ) := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + cases hs : A.small i j + · simp only [Bool.false_eq_true,ite_false] + positivity + · simp only [ite_true] + exact_mod_cast (A.hsmall i j hs).le + _ = (Fintype.card I*Fintype.card J:ℕ)*(A.W:ℝ) := by simp; ring + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast A.hcard) (Nat.cast_nonneg _) + unfold rootConstant + calc + _ ≤ ∑ a,|(signedResidual A.small A.T A.r A.c (rowCounts A z) (columnCounts A z) 0 a:ℝ)| := by + apply Finset.sum_le_sum + intro a _ + split_ifs <;> first | exact le_rfl | exact abs_nonneg _ + _ ≤ _ := hh.trans (by linarith) + +noncomputable def zeroAssignment (A : Instance I J) : FreeIndex A.small A.T A.b := + fun _ => ⟨0,Nat.succ_pos _⟩ + +lemma integerCube_zero (A : Instance I J) (B : ℝ) : integerCube A B (zeroAssignment A)=0 := by + funext a + simp only [integerCube,zeroAssignment,Nat.cast_zero,mul_zero,zero_div,Pi.zero_apply] + +lemma zero_tree_bound (A : Instance I J) (B : ℝ) (hB : 0 < B) + (z : View A → ℕ) (hz : InBox (bounds A) z) (t : TreeCell A.T) : + intervalCost (scaledTree A B (rowCounts A z) (columnCounts A z) 0 t) ≤ 10*(A.d:ℝ) := by + have hzero : (fun i j => (freeTable A.small A.T A.b (zeroAssignment A) i j:ℤ))=0 := by + funext i j + unfold freeTable zeroAssignment + split_ifs <;> rfl + have hinterval := solved_in_intervals A.small A.b A.T A.hTG A.hT A.hmax A.r A.c + (rowCounts A z) (columnCounts A z) 0 A.X A.d A.W A.hd A.hcard A.hlarge + (by + intro i j hs + exact ⟨A.hsmall i j hs,rowCounts_bounds A z hz i j hs,columnCounts_bounds A z i j⟩) + (by intro i j _ _; exact ⟨le_rfl,Nat.cast_nonneg _⟩) A.hX A.hXr A.hXc + t.val.1 t.val.2 t.property + rw [← integerCube_zero A B,scaledTree_integer A B hB,hzero,intervalCost_div] + · have hb : (0:ℝ) < A.b t.val.1 t.val.2 := by exact_mod_cast (A.hlarge _ _ (A.hTG t.property)).2 + rw [div_le_iff₀ hb] + have hlo : -(10*(A.d:ℝ)*A.b t.val.1 t.val.2) ≤ + (solved A.small A.T A.r A.c (rowCounts A z) (columnCounts A z) 0 t.val.1 t.val.2:ℝ) := by + exact_mod_cast hinterval.1 + have hup : (solved A.small A.T A.r A.c (rowCounts A z) (columnCounts A z) 0 t.val.1 t.val.2:ℝ) ≤ + 10*(A.d:ℝ)*A.b t.val.1 t.val.2 := by exact_mod_cast hinterval.2 + apply max_le + · positivity + · apply max_le <;> linarith + · exact_mod_cast (A.hlarge _ _ (A.hTG t.property)).2 + +/-- The 1/8 local change bound and the actual baseline root/tree bounds +give D(v)≤H throughout the entire continuous bin cube, including its +boundary and the empty free-coordinate case. -/ +theorem penalty_cube_bound (A : Instance I J) (C B : ℝ) (hC : 0 ≤ C) (hB : 0 < B) + (z : View A → ℕ) (hz : InBox (bounds A) z) + (v : FreeCell A.small A.T → ℝ) (hv : ∀ f,0 ≤ v f ∧ v f ≤ B) : + 0 ≤ penalty A C B (rowCounts A z) (columnCounts A z) v ∧ + penalty A C B (rowCounts A z) (columnCounts A z) v ≤ C*(10*(A.d:ℝ)^2*((A.W:ℝ)+1)) := by + have hzero : penalty A C B (rowCounts A z) (columnCounts A z) 0 ≤ + C*(2*(A.d:ℝ)*A.W+10*(A.d:ℝ)^2) := by + unfold penalty + apply mul_le_mul_of_nonneg_left _ hC + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun t _ => zero_tree_bound A B hB z hz t) + have ht : (∑ t : TreeCell A.T,intervalCost (scaledTree A B (rowCounts A z) (columnCounts A z) 0 t)) ≤ + 10*(A.d:ℝ)^2 := by + calc + _ ≤ (Fintype.card (TreeCell A.T):ℝ)*(10*(A.d:ℝ)) := by simpa using hsum + _ ≤ (A.d:ℝ)*(10*(A.d:ℝ)) := mul_le_mul_of_nonneg_right + (by exact_mod_cast tree_card_le A) (by positivity) + _ = _ := by ring + linarith [rootConstant_bound A z hz] + have hchange := (le_abs_self _).trans (penalty_change A C B hC hB + (rowCounts A z) (columnCounts A z) v 0 B hB.le (by + intro f + simpa only [Pi.zero_apply,sub_zero,abs_of_nonneg (hv f).1] using (hv f).2)) + have hcancel : (2*C*(A.d:ℝ)^2/B)*B=2*C*(A.d:ℝ)^2 := div_mul_cancel₀ _ hB.ne' + rw [hcancel] at hchange + have hd : (1:ℝ) ≤ A.d := by exact_mod_cast A.hd + have hW : (2:ℝ) ≤ A.W := by exact_mod_cast A.hW + have hscalar : 2*(A.d:ℝ)*A.W+12*(A.d:ℝ)^2 ≤ 10*(A.d:ℝ)^2*((A.W:ℝ)+1) := by + have hdd : (A.d:ℝ) ≤ (A.d:ℝ)^2 := by nlinarith + have hprod := mul_le_mul_of_nonneg_right hdd (by positivity : (0:ℝ) ≤ A.W) + have hprod' := mul_le_mul_of_nonneg_left hW (sq_nonneg (A.d:ℝ)) + nlinarith + refine ⟨penalty_nonnegative A C B hC _ _ v,?_⟩ + nlinarith [mul_le_mul_of_nonneg_left hscalar hC] + +end ContingencyTables.ForestScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledIdentification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..e43e5f8b143f3b7d5cb7c6ba030a0bd34e1dc4d2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledIdentification.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyBound + +namespace OAI + +/-! # Integer free assignments use the original scaled affine tree values -/ + +namespace ContingencyTables.ForestScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication GraphCompletionCounts ForestAssignmentSplit +open ForestAffineCoefficients ForestPhysicalCompletion ForestRootPenalty + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma free_coefficient_sum (A : Instance I J) (t : TreeCell A.T) (F : I×J → ℝ) : + (∑ f : FreeCell A.small A.T,coefficient A t f.val*F f.val)= + ∑ a : I×J,coefficient A t a*F a := by + let p : I×J → Prop := fun a => A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + calc + _ = ∑ a ∈ Finset.univ.filter p,coefficient A t a*F a := + (Finset.sum_subtype (p := p) (Finset.univ.filter p) (fun _ => by simp) + (fun a => coefficient A t a*F a)).symm + _ = _ := by + apply Finset.sum_subset (Finset.filter_subset _ _) + intro a _ ha + have hp : ¬p a := by simpa only [Finset.mem_filter,Finset.mem_univ,true_and] using ha + change ¬(A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2)) at hp + simp only [coefficient,hp,ite_false,zero_mul] + +noncomputable def integerCube (A : Instance I J) (B : ℝ) (f : FreeIndex A.small A.T A.b) : + FreeCell A.small A.T → ℝ := fun a => B*(f a).val/((A.b a.val.1 a.val.2:ℝ)+1) + +/-- The scaled affine value at each original integer free assignment is +exactly the manuscript's solved tree value divided by its capacity. -/ +theorem scaledTree_integer (A : Instance I J) (B : ℝ) (hB : 0 < B) + (x q : I → J → ℤ) (f : FreeIndex A.small A.T A.b) (t : TreeCell A.T) : + scaledTree A B x q (integerCube A B f) t= + (solved A.small A.T A.r A.c x q + (fun i j => (freeTable A.small A.T A.b f i j:ℤ)) t.val.1 t.val.2:ℝ)/(A.b t.val.1 t.val.2:ℝ) := by + let F : I×J → ℝ := fun a => (freeTable A.small A.T A.b f a.1 a.2:ℝ) + have hterm (a : FreeCell A.small A.T) : + normalizedCoefficient A B t a*integerCube A B f a= + coefficient A t a.val*F a.val/(A.b t.val.1 t.val.2:ℝ) := by + have hN : (A.b a.val.1 a.val.2:ℝ)+1≠0 := by positivity + have hbt : (A.b t.val.1 t.val.2:ℝ)≠0 := by + exact_mod_cast (Nat.ne_of_gt (A.hlarge _ _ (A.hTG t.property)).2) + have hF : F a.val=(f a).val := by + simp [F,freeTable,a.property] + rw [hF] + unfold normalizedCoefficient integerCube + field_simp [hB.ne',hN,hbt] + unfold scaledTree AffinePenalty.affineValue normalizedOffset + simp_rw [hterm] + rw [← Finset.sum_div,free_coefficient_sum,← add_div] + have hh := solved_eq_affine A t x q + (fun i j => (freeTable A.small A.T A.b f i j:ℤ)) + unfold affineTree AffinePenalty.affineValue at hh + apply congrArg (fun z : ℝ => z/(A.b t.val.1 t.val.2:ℝ)) + simpa only [F,Int.cast_natCast] using hh.symm + +lemma intervalCost_div (x b : ℝ) (hb : 0 < b) : + intervalCost (x/b)=max 0 (max (-x) (x-b))/b := by + unfold intervalCost + have he : x/b-1=(x-b)/b := by field_simp [hb.ne'] + rw [he,← neg_div, max_div_div_right hb.le] + simpa only [zero_div] using max_div_div_right hb.le (0:ℝ) (max (-x) (x-b)) + +/-- The root residual in the continuous display is the original root +residual on every integer free assignment; it is independent of those +free values by the proved component-cut cancellation. -/ +theorem rootConstant_eq_assignment (A : Instance I J) (x q free : I → J → ℤ) : + rootConstant A x q= + ∑ a,if ForestPenaltyApplication.rootFlag A.T a then + |(signedResidual A.small A.T A.r A.c x q free a:ℝ)| else 0 := by + have hroot := root_eq_large A.small A.b A.T A.hTG A.hT A.hmax + (fun i j hs => (A.hlarge i j hs).2) + have hh := signedResidual_independent A.small A.T A.hTG A.r A.c x q free 0 A.X + A.hXr A.hXc hroot + unfold rootConstant + apply Finset.sum_congr rfl + intro a _ + rw [hh] + +lemma tree_sum_eq (A : Instance I J) (F : I×J → ℝ) : + (∑ t : TreeCell A.T,F t.val)= + ∑ i,∑ j,if A.T.Adj (.inl i) (.inr j) then F (i,j) else 0 := by + let p : I×J → Prop := fun a => A.T.Adj (.inl a.1) (.inr a.2) + calc + _ = ∑ a ∈ Finset.univ.filter p,F a := + (Finset.sum_subtype (p := p) (Finset.univ.filter p) (fun _ => by simp) F).symm + _ = ∑ a : I×J,if p a then F a else 0 := Finset.sum_filter _ _ + _ = _ := by rw [Fintype.sum_prod_type] + +/-- Thus the continuous display agrees term for term with the actual +root/tree penalty in the original finite definition of h_j. -/ +theorem penalty_at_integer (A : Instance I J) (C B : ℝ) (hB : 0 < B) + (z : View A → ℕ) (f : FreeIndex A.small A.T A.b) : + penalty A C B (fun i j => (ForestCountIdentification.smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ)) + (integerCube A B f)=C*ForestPenaltyBound.penalty A z f := by + let x := ForestCountIdentification.smallX A.small z + let y := ForestCountIdentification.smallY A.small z + let free := freeTable A.small A.T A.b f + let tree := solved A.small A.T A.r A.c (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) + have hroot : rootConstant A (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ))= + ∑ a,if ForestPenaltyApplication.rootFlag A.T a then + |ForestLiteralCount.actualDeviation A.small A.T A.b x y free A.r A.c tree a| else 0 := by + rw [rootConstant_eq_assignment A _ _ (fun i j => (free i j:ℤ))] + apply Finset.sum_congr rfl + intro a _ + rw [ForestRootPenalty.abs_actualDeviation_solved] + have htree : (∑ t : TreeCell A.T,intervalCost (scaledTree A B (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (integerCube A B f) t))= + ∑ i,∑ j,if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0 := by + calc + _ = ∑ t : TreeCell A.T, + max 0 (max (-(tree t.val.1 t.val.2:ℝ)) ((tree t.val.1 t.val.2:ℝ)-A.b t.val.1 t.val.2))/ + (A.b t.val.1 t.val.2:ℝ) := by + apply Finset.sum_congr rfl + intro t _ + rw [scaledTree_integer A B hB] + exact intervalCost_div _ _ (by exact_mod_cast (A.hlarge _ _ (A.hTG t.property)).2) + _ = _ := tree_sum_eq A (fun a => + max 0 (max (-(tree a.1 a.2:ℝ)) ((tree a.1 a.2:ℝ)-A.b a.1 a.2))/(A.b a.1 a.2:ℝ)) + unfold penalty + change C*(rootConstant A (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ))+_)=_ + rw [hroot,htree] + rfl + +end ContingencyTables.ForestScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledPenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledPenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d8e9cf08a320626ff6336935a9d73b59bbe06d3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/ForestScaledPenalty.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineCompletion +import OAI.Combinatorics.ContingencyTables.Rooted.ForestRootPenalty + +namespace OAI + +/-! # Convexity and the actual scaled forest-penalty Lipschitz bound -/ + +namespace ContingencyTables.ForestScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication GraphCompletionCounts ForestAssignmentSplit +open ForestAffineCoefficients ForestRootPenalty + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def intervalCost (x : ℝ) : ℝ := max 0 (max (-x) (x-1)) + +lemma intervalCost_nonnegative (x : ℝ) : 0 ≤ intervalCost x := le_max_left _ _ + +lemma intervalCost_change (x y : ℝ) : |intervalCost x-intervalCost y| ≤ |x-y| := by + have hsub (x y : ℝ) : intervalCost x ≤ intervalCost y+|x-y| := by + unfold intervalCost + apply max_le + · linarith [le_max_left (0:ℝ) (max (-y) (y-1)),abs_nonneg (x-y)] + · apply max_le + · have hh : -y ≤ max 0 (max (-y) (y-1)) := + (le_max_left _ _).trans (le_max_right _ _) + linarith [neg_le_abs (x-y)] + · have hh : y-1 ≤ max 0 (max (-y) (y-1)) := + (le_max_right _ _).trans (le_max_right _ _) + linarith [le_abs_self (x-y)] + apply abs_le.mpr + constructor + · have hh := hsub y x + rw [abs_sub_comm y x] at hh + linarith + · linarith [hsub x y] + +lemma intervalCost_combine (x y a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a+b=1) : + intervalCost (a*x+b*y) ≤ a*intervalCost x+b*intervalCost y := by + have hx0 := intervalCost_nonnegative x + have hy0 := intervalCost_nonnegative y + have hxl : -x ≤ intervalCost x := (le_max_left _ _).trans (le_max_right _ _) + have hyl : -y ≤ intervalCost y := (le_max_left _ _).trans (le_max_right _ _) + have hxu : x-1 ≤ intervalCost x := (le_max_right _ _).trans (le_max_right _ _) + have hyu : y-1 ≤ intervalCost y := (le_max_right _ _).trans (le_max_right _ _) + change max 0 (max (-(a*x+b*y)) (a*x+b*y-1)) ≤ a*intervalCost x+b*intervalCost y + apply max_le + · exact add_nonneg (mul_nonneg ha hx0) (mul_nonneg hb hy0) + · apply max_le + · nlinarith [mul_le_mul_of_nonneg_left hxl ha,mul_le_mul_of_nonneg_left hyl hb] + · nlinarith [mul_le_mul_of_nonneg_left hxu ha,mul_le_mul_of_nonneg_left hyu hb] + +noncomputable def normalizedOffset (A : Instance I J) (t : TreeCell A.T) + (x q : I → J → ℤ) : ℝ := + offset A t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ))/(A.b t.val.1 t.val.2:ℝ) + +noncomputable def normalizedCoefficient (A : Instance I J) (B : ℝ) (t : TreeCell A.T) + (f : FreeCell A.small A.T) : ℝ := + coefficient A t f.val*((A.b f.val.1 f.val.2:ℝ)+1)/B/(A.b t.val.1 t.val.2:ℝ) + +noncomputable def scaledTree (A : Instance I J) (B : ℝ) (x q : I → J → ℤ) + (v : FreeCell A.small A.T → ℝ) (t : TreeCell A.T) : ℝ := + AffinePenalty.affineValue (normalizedOffset A t x q) (normalizedCoefficient A B t) v + +noncomputable def rootConstant (A : Instance I J) (x q : I → J → ℤ) : ℝ := + ∑ a,if ForestPenaltyApplication.rootFlag A.T a then + |(signedResidual A.small A.T A.r A.c x q 0 a:ℝ)| else 0 + +noncomputable def penalty (A : Instance I J) (C B : ℝ) (x q : I → J → ℤ) + (v : FreeCell A.small A.T → ℝ) : ℝ := + C*(rootConstant A x q+∑ t : TreeCell A.T,intervalCost (scaledTree A B x q v t)) + +lemma penalty_nonnegative (A : Instance I J) (C B : ℝ) (hC : 0 ≤ C) + (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℝ) : + 0 ≤ penalty A C B x q v := by + unfold penalty rootConstant + apply mul_nonneg hC + apply add_nonneg + · exact Finset.sum_nonneg (fun a _ => by split_ifs <;> positivity) + · exact Finset.sum_nonneg (fun t _ => intervalCost_nonnegative _) + +lemma free_card_le (A : Instance I J) : Fintype.card (FreeCell A.small A.T) ≤ A.d := by + exact (Fintype.card_le_of_injective Subtype.val Subtype.val_injective).trans + (by simpa only [Fintype.card_prod] using A.hcard) + +lemma tree_card_le (A : Instance I J) : Fintype.card (TreeCell A.T) ≤ A.d := by + exact (Fintype.card_le_of_injective Subtype.val Subtype.val_injective).trans + (by simpa only [Fintype.card_prod] using A.hcard) + +/-- All coefficients are obtained from the actual maximum-forest cuts. +The bound is 2*C*d²/B, which equals 1/8 for the source B=16*C*d². -/ +theorem penalty_change (A : Instance I J) (C B : ℝ) (hC : 0 ≤ C) (hB : 0 < B) + (x q : I → J → ℤ) (v w : FreeCell A.small A.T → ℝ) (r : ℝ) (hr : 0 ≤ r) + (hvw : ∀ f,|v f-w f| ≤ r) : + |penalty A C B x q v-penalty A C B x q w| ≤ (2*C*(A.d:ℝ)^2/B)*r := by + have hterm (t : TreeCell A.T) : + |intervalCost (scaledTree A B x q v t)-intervalCost (scaledTree A B x q w t)| ≤ + (A.d:ℝ)*(2/B)*r := by + apply (intervalCost_change _ _).trans + have hh := AffinePenalty.affineValue_change (normalizedOffset A t x q) + (normalizedCoefficient A B t) v w (2/B) r (by positivity) + (fun f => normalized_coefficient_bound A t f.val B hB) hvw + exact hh.trans (mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right (by exact_mod_cast free_card_le A) (by positivity : (0:ℝ) ≤ 2/B)) hr) + have he : penalty A C B x q v-penalty A C B x q w= + C*∑ t : TreeCell A.T,(intervalCost (scaledTree A B x q v t)-intervalCost (scaledTree A B x q w t)) := by + unfold penalty + rw [Finset.sum_sub_distrib] + ring + rw [he,abs_mul,abs_of_nonneg hC] + calc + _ ≤ C*∑ t : TreeCell A.T,|intervalCost (scaledTree A B x q v t)-intervalCost (scaledTree A B x q w t)| := + mul_le_mul_of_nonneg_left (Finset.abs_sum_le_sum_abs _ _) hC + _ ≤ C*∑ _t : TreeCell A.T,(A.d:ℝ)*(2/B)*r := + mul_le_mul_of_nonneg_left (Finset.sum_le_sum (fun t _ => hterm t)) hC + _ = C*((Fintype.card (TreeCell A.T):ℝ)*((A.d:ℝ)*(2/B)*r)) := by simp + _ ≤ C*((A.d:ℝ)*((A.d:ℝ)*(2/B)*r)) := mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_right (by exact_mod_cast tree_card_le A) (by positivity)) hC + _ = _ := by ring + +theorem penalty_convex (A : Instance I J) (C B : ℝ) (hC : 0 ≤ C) (x q : I → J → ℤ) : + ConvexOn ℝ Set.univ (penalty A C B x q) := by + refine ⟨convex_univ,?_⟩ + intro v _ w _ a b ha hb hab + have hsum : (∑ t : TreeCell A.T,intervalCost (scaledTree A B x q (a • v+b • w) t)) ≤ + a*(∑ t : TreeCell A.T,intervalCost (scaledTree A B x q v t))+ + b*(∑ t : TreeCell A.T,intervalCost (scaledTree A B x q w t)) := by + rw [Finset.mul_sum,Finset.mul_sum,← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro t _ + unfold scaledTree + rw [AffinePenalty.affineValue_combine _ _ _ _ _ _ hab] + exact intervalCost_combine _ _ _ _ ha hb hab + unfold penalty + have hh := mul_le_mul_of_nonneg_left hsum hC + simp only [smul_eq_mul] + nlinarith [congrArg (fun z => C*z*rootConstant A x q) hab] + +theorem penalty_continuous (A : Instance I J) (C B : ℝ) (x q : I → J → ℤ) : + Continuous (penalty A C B x q) := by + apply continuous_const.mul + apply continuous_const.add + apply continuous_finsetSum + intro t _ + have hs : Continuous (fun v => scaledTree A B x q v t) := by + exact continuous_const.add (continuous_finsetSum Finset.univ + (fun f _ => continuous_const.mul (continuous_apply f))) + exact continuous_const.max (hs.neg.max (hs.sub continuous_const)) + +end ContingencyTables.ForestScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeEdgeCatalogProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeEdgeCatalogProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3cd211a1471d98e225b28c655dd63849b96c94d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeEdgeCatalogProgram.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCellCatalogProgram +import OAI.Combinatorics.ContingencyTables.Machines.WeightedArgmaxProgram +import OAI.Combinatorics.ContingencyTables.Transport.NetworkVertexCode + +namespace OAI + +/-! # The executed weighted catalog of large cells + +Rows and columns are indexed by their stored margin-list lengths. The +catalog contains each retained large cell once, with its actual binary +capacity and its row/column graph endpoints. +-/ + +namespace ContingencyTables.LargeEdgeCatalogProgram + +open MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms WeightedArgmaxProgram + +abbrev Input := CompanionCellCatalog.Input +abbrev CellInput := Input×(ℕ×ℕ) + +def vertexCount (z : Input) : ℕ := z.1.1.1.length+z.1.1.2.length +def vertexCountRealizer : Realizer vertexCount := + composition (pair + (composition (composition (composition first first) first) listLength) + (composition (composition (composition first first) second) listLength)) add +lemma polynomial_vertexCount : PolynomialTime vertexCountRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_listLength) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_listLength)) polynomial_add + +def endpoints (z : CellInput) : ℕ×ℕ := (z.2.1,z.1.1.1.1.length+z.2.2) +def endpointsRealizer : Realizer endpoints := + pair (composition second first) + (composition (pair + (composition (composition (composition (composition first first) first) first) listLength) + (composition second second)) add) +lemma polynomial_endpoints : PolynomialTime endpointsRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_first) polynomial_listLength) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add) + +def entry (z : CellInput) : Edge := (endpoints z,CompanionCellCatalog.entry z) +def entryRealizer : Realizer entry := pair endpointsRealizer CompanionCellCatalog.entryRealizer +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_pair polynomial_endpoints CompanionCellCatalog.polynomial_entry + +def large (z : CellInput) : Bool := !CompanionCellCatalog.retainedTest z +def largeRealizer : Realizer large := + composition CompanionCellCatalog.retainedTestRealizer boolNot +lemma polynomial_large : PolynomialTime largeRealizer := + polynomial_composition CompanionCellCatalog.polynomial_retainedTest polynomial_boolNot + +def cells (z : Input) : List (ℕ×ℕ) := + (cellPairs z.1.1).filter (fun a=>large (z,a)) +def cellsRealizer : Realizer cells := + composition (pair identity (composition (composition first first) cellPairsRealizer)) + (filterWith largeRealizer) +lemma polynomial_cells : PolynomialTime cellsRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_cellPairs)) (polynomial_filterWith polynomial_large) + +def catalog (z : Input) : List Edge := (cells z).map (fun a=>entry (z,a)) +def catalogRealizer : Realizer catalog := + composition (pair identity cellsRealizer) (mapWith entryRealizer) +lemma polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_cells) + (polynomial_mapWith polynomial_entry) + +variable {m n : ℕ} + +lemma entry_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (W : ℕ) (i : Fin m) (j : Fin n) : + entry ((NetworkVertexCode.data r c b,W),(i.val,j.val))= + ((i.val,m+j.val),b i j) := by + change ((i.val,(List.ofFn r).length+j.val),matrixEntry (matrixCode b,(i.val,j.val)))=_ + rw [List.length_ofFn,matrixEntry_code] + +lemma mem_cells_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (W : ℕ) (a : ℕ×ℕ) : + a∈cells (NetworkVertexCode.data r c b,W) ↔ + ∃ i : Fin m,∃ j : Fin n,a=(i.val,j.val) ∧ W≤b i j := by + rw [cells,List.mem_filter] + change (a∈cellPairs (List.ofFn r,List.ofFn c) ∧ + large ((NetworkVertexCode.data r c b,W),a)=true) ↔ _ + rw [mem_cellPairs] + simp only [List.length_ofFn] + constructor + · rintro ⟨⟨hi,hj⟩,ht⟩ + let i : Fin m := ⟨a.1,hi⟩ + let j : Fin n := ⟨a.2,hj⟩ + refine ⟨i,j,rfl,?_⟩ + have hn : ¬CompanionCellCatalog.entry + ((NetworkVertexCode.data r c b,W),(i.val,j.val)) largeIndexTest (z,i)) + +def largeIndicesRealizer : Realizer largeIndices := + composition (pair identity (composition (composition second listLength) range)) + (filterWith largeIndexTestRealizer) + +theorem polynomial_largeIndices : PolynomialTime largeIndicesRealizer := by + have hr : PolynomialTime (composition (composition + (second (A := ℕ) (B := List ℕ)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_listLength) + Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.2).trans (by rw [weight_prod]; omega) + exact polynomial_composition (polynomial_pair polynomial_identity hr) + (polynomial_filterWith polynomial_largeIndexTest) + +def selectList {A : Type} (a : A) (z : List ℕ×List A) : List A := + z.1.map (fun i => z.2.getD i a) + +def selectListRealizer {A : Type} [Codec A] (a : A) : Realizer (selectList a) := + composition (pair second first) (mapWith (getDFast a)) + +theorem polynomial_selectList {A : Type} [Codec A] (a : A) : + PolynomialTime (selectListRealizer a) := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith (polynomial_getDFast a)) + +def largePaddedMargins (row : Bool) (z : PaddingData) : List ℕ := + selectList 0 (largeIndices (z.1.2,marginList row z.1),paddedMargins row z) + +def largePaddedMarginsRealizer (row : Bool) : Realizer (largePaddedMargins row) := + composition (pair + (composition (pair (composition first second) + (composition first (marginListRealizer row))) largeIndicesRealizer) + (paddedMarginsRealizer row)) (selectListRealizer 0) + +theorem polynomial_largePaddedMargins (row : Bool) : + PolynomialTime (largePaddedMarginsRealizer row) := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_first (polynomial_marginList row))) + polynomial_largeIndices) (polynomial_paddedMargins row)) (polynomial_selectList 0) + +def profilePaddedMargins (row : Bool) (z : ProfileCheckData×ℕ) : List ℕ := + largePaddedMargins row + (((((z.1.1.1.1,if row then z.1.1.1.2.1 else complementValues (z.1.2,z.1.1.1.2.2)), + z.1.1.2),z.1.2)),z.2) + +def profilePaddedMarginsRealizer (row : Bool) : Realizer (profilePaddedMargins row) := + composition (pair (composition first (profileLineData row)) second) + (largePaddedMarginsRealizer row) + +theorem polynomial_profilePaddedMargins (row : Bool) : + PolynomialTime (profilePaddedMarginsRealizer row) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first (polynomial_profileLineData row)) polynomial_second) + (polynomial_largePaddedMargins row) + +lemma mem_largeIndices (U : ℕ) (r : List ℕ) (i : ℕ) : + i∈largeIndices (U,r) ↔ i paddedMarginAt row (z,i)) := by + change (largeIndices (z.1.2,marginList row z.1)).map + (fun i => (paddedMargins row z).getD i 0)=_ + apply List.map_congr_left + intro i hi + have hi' := (mem_largeIndices _ _ _).mp hi + rw [List.getD_eq_getElem (l := paddedMargins row z) (n := i) (d := 0) + (by simpa only [paddedMargins,List.length_map,List.length_range] using hi'.1)] + simp only [paddedMargins,List.getElem_map,List.getElem_range] + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginReference.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginReference.lean new file mode 100644 index 0000000000000000000000000000000000000000..cacf3cfce463dfa7392bddb878dabc88d226a9d7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginReference.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginSemantics +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalSemantics + +namespace OAI + +/-! # Computed reference coordinates for the large completion rectangle -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms SmallContextCoordinates SmallContextFibres +open PhysicalCompletionFibres FirstPaperProfiles PaddedCompletions CompletionCounts +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} + +def optionIndexEquiv (k : ℕ) (hk : 0 < k) : Option (Fin (k-1)) ≃ Fin k := by + cases k with + | zero => omega + | succ k => exact (finSuccEquiv k).symm + +lemma optionIndex_marginCode (k : ℕ) (hk : 0 < k) (f : Fin k → ℕ) : + marginCode (fun i => f (optionIndexEquiv k hk i))=List.ofFn f := by + cases k with + | zero => omega + | succ k => + rw [marginCode_ofFn] + apply congrArg List.ofFn + funext i + exact congrArg f ((finSuccEquiv k).symm_apply_apply i) + +def largeOptionEquiv (r : Fin m → ℕ) (U : ℕ) + (hr : 0 < (largeIndices (U,List.ofFn r)).length) : + Option (Fin ((largeIndices (U,List.ofFn r)).length-1)) ≃ LargeRows r U := + (optionIndexEquiv _ hr).trans (largeIndexEquiv r U) + +lemma largeIndices_pos (r : Fin m → ℕ) (U : ℕ) (i : LargeRows r U) : + 0 < (largeIndices (U,List.ofFn r)).length := by + apply List.length_pos_iff.mpr + intro he + have hm := (largeIndices_ofFn_mem r U i.val).mpr i.property + simp only [he,List.not_mem_nil] at hm + +lemma largeOption_marginCode (r : Fin m → ℕ) (U : ℕ) + (hr : 0 < (largeIndices (U,List.ofFn r)).length) (f : LargeRows r U → ℕ) : + marginCode (fun i => f (largeOptionEquiv r U hr i))= + List.ofFn (fun i => f (largeIndexEquiv r U i)) := + optionIndex_marginCode _ hr (fun i => f (largeIndexEquiv r U i)) + +def listedRows (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (B : Fin m → Fin n → ℕ) (hr : 0 < (largeIndices (U,List.ofFn r)).length) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + Option (Fin ((largeIndices (U,List.ofFn r)).length-1)) → ℕ := + fun i => residualRows (firstPaperSmall r c U) B r c L z (largeOptionEquiv r U hr i).val + +def listedColumns (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (B : Fin m → Fin n → ℕ) (hc : 0 < (largeIndices (U,List.ofFn c)).length) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + Option (Fin ((largeIndices (U,List.ofFn c)).length-1)) → ℕ := + fun j => residualColumns (firstPaperSmall r c U) B r c L z (largeOptionEquiv c U hc j).val + +theorem listedRows_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (B : Fin m → Fin n → ℕ) (hr : 0 < (largeIndices (U,List.ofFn r)).length) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + marginCode (listedRows r c U L B hr z)=largePaddedMargins true + (((((cellCatalog (firstPaperSmall r c U) e, + viewList (firstPaperSmall r c U) e (physicalProfile _ B r c L z) false), + (List.ofFn r,List.ofFn c)),U),L)) := by + unfold listedRows + rw [largeOption_marginCode r U hr + (fun i : LargeRows r U => residualRows (firstPaperSmall r c U) B r c L z i.val), + largePaddedRows_code] + rfl + +theorem listedColumns_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (B : Fin m → Fin n → ℕ) (hc : 0 < (largeIndices (U,List.ofFn c)).length) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (hB : ∀ a : Cells (firstPaperSmall r c U),B a.val.1 a.val.2=U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + marginCode (listedColumns r c U L B hc z)=largePaddedMargins false + (((((cellCatalog (firstPaperSmall r c U) e, + complementValues (U,viewList (firstPaperSmall r c U) e (physicalProfile _ B r c L z) true)), + (List.ofFn r,List.ofFn c)),U),L)) := by + unfold listedColumns + rw [largeOption_marginCode c U hc + (fun j : LargeColumns c U => residualColumns (firstPaperSmall r c U) B r c L z j.val), + largePaddedColumns_code r c U L e B hB] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..40792ff301dccafc008da872bdc9b41deef53dc2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargeMarginSemantics.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginProgram +import OAI.Combinatorics.ContingencyTables.Sampling.PaddedResidualSemantics +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBlock + +namespace OAI + +/-! # Exact indexing of the computed large residual margins -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms PaddedCompletions SmallContextCoordinates SmallContextFibres +open PhysicalCompletionFibres FirstPaperProfiles CompletionCounts +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} + +lemma largeIndices_ofFn_mem (r : Fin m → ℕ) (U : ℕ) (i : Fin m) : + i.val∈largeIndices (U,List.ofFn r) ↔ U≤r i := by + rw [mem_largeIndices] + simp only [List.length_ofFn,i.isLt,true_and,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,dite_true,Option.getD_some,Fin.eta] + +private def largeMemberEquiv (r : Fin m → ℕ) (U : ℕ) : + {i // i∈largeIndices (U,List.ofFn r)} ≃ LargeRows r U where + toFun x := by + have hm := (mem_largeIndices U (List.ofFn r) x.val).mp x.property + have hi : x.val < m := by simpa only [List.length_ofFn] using hm.1 + exact ⟨⟨x.val,hi⟩,(largeIndices_ofFn_mem r U ⟨x.val,hi⟩).mp x.property⟩ + invFun i := ⟨i.val.val,(largeIndices_ofFn_mem r U i.val).mpr i.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +/-- Increasing list order gives a fixed, computed indexing of every +large row. The same construction is used for columns. -/ +def largeIndexEquiv (r : Fin m → ℕ) (U : ℕ) : + Fin (largeIndices (U,List.ofFn r)).length ≃ LargeRows r U := + (List.Nodup.getEquiv _ (largeIndices_nodup U (List.ofFn r))).trans (largeMemberEquiv r U) + +lemma largeIndexEquiv_val (r : Fin m → ℕ) (U : ℕ) + (i : Fin (largeIndices (U,List.ofFn r)).length) : + (largeIndexEquiv r U i).val.val=(largeIndices (U,List.ofFn r))[i.val] := rfl + +lemma largePaddedMargins_ofFn (row : Bool) (z : PaddingData) : + largePaddedMargins row z=List.ofFn + (fun i : Fin (largeIndices (z.1.2,marginList row z.1)).length => + paddedMarginAt row (z,(largeIndices (z.1.2,marginList row z.1))[i.val])) := by + rw [largePaddedMargins_eq] + exact (List.ofFn_getElem_eq_map _ _).symm + +theorem largePaddedRows_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (z : SmallProfile (firstPaperSmall r c U)) : + largePaddedMargins true + (((((cellCatalog (firstPaperSmall r c U) e,viewList (firstPaperSmall r c U) e z false), + (List.ofFn r,List.ofFn c)),U),L))= + List.ofFn (fun i : Fin (largeIndices (U,List.ofFn r)).length => + r (largeIndexEquiv r U i).val- + smallRow (firstPaperSmall r c U) (smallView (firstPaperSmall r c U) z false) + (largeIndexEquiv r U i).val+ + rowLargeCount (firstPaperSmall r c U) (largeIndexEquiv r U i).val*L) := by + rw [largePaddedMargins_ofFn] + apply congrArg List.ofFn + funext i + exact paddedRowAt_code r c U L e z (largeIndexEquiv r U i).val + +theorem largePaddedColumns_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (B : Fin m → Fin n → ℕ) (hB : ∀ a : Cells (firstPaperSmall r c U),B a.val.1 a.val.2=U) + (z : SmallProfile (firstPaperSmall r c U)) : + largePaddedMargins false + (((((cellCatalog (firstPaperSmall r c U) e, + complementValues (U,viewList (firstPaperSmall r c U) e z true)), + (List.ofFn r,List.ofFn c)),U),L))= + List.ofFn (fun j : Fin (largeIndices (U,List.ofFn c)).length => + c (largeIndexEquiv c U j).val- + smallColumn (firstPaperSmall r c U) B (smallView (firstPaperSmall r c U) z true) + (largeIndexEquiv c U j).val+ + columnLargeCount (firstPaperSmall r c U) (largeIndexEquiv c U j).val*L) := by + rw [largePaddedMargins_ofFn] + apply congrArg List.ofFn + funext j + exact paddedColumnAt_code r c U L e B hB z (largeIndexEquiv c U j).val + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargePairEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargePairEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..02e066562e7ad255b6fe6b18a3f6d1b4f864d15a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/LargePairEnumeration.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedEnumeration +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! +# Physical indexing of all balanced large-cell pairs + +The recursively added pairs are identified with the actual finite cells, +and their assignments with the dependent product of the physical finite +intervals. No extra coordinate or assignment multiplicity is introduced. +-/ + +namespace ContingencyTables.LargePairEnumeration + +open scoped BigOperators Classical +open BalancedFamily BalancedEnumeration IntegerMarginal + +universe u + +/-- Widths in the explicit order supplied by a finite cell enumeration. -/ +def widths : {n : ℕ} → (Fin n → ℕ) → List ℕ + | 0,_ => [] + | _+1,M => M 0::widths (fun i => M i.succ) + +lemma widths_lower {n : ℕ} (M : Fin n → ℕ) (h : ∀ i, 2≤M i) : + ∀ w ∈ widths M, 2≤w := by + induction n with + | zero => intro w hw; exact False.elim (List.not_mem_nil hw) + | succ n ih => + intro w hw + simp only [widths,List.mem_cons] at hw + rcases hw with rfl|hw + · exact h 0 + · exact ih (fun i => M i.succ) (fun i => h i.succ) w hw + +private def pairSuccEquiv (n : ℕ) : ((Fin n×Bool)⊕Bool) ≃ Fin (n+1)×Bool where + toFun + | .inl (i,b) => (i.succ,b) + | .inr b => (0,b) + invFun p := Fin.cases (.inr p.2) (fun i => .inl (i,p.2)) p.1 + left_inv p := by cases p with + | inl p => rcases p with ⟨i,b⟩; rfl + | inr b => rfl + right_inv p := by + rcases p with ⟨i,b⟩ + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + +/-- The nested coordinate sums contain exactly the retained coordinates +and one doubled coordinate for each physical large cell. -/ +def coordinateEquiv (S : Type u) : {n : ℕ} → (M : Fin n → ℕ) → + Coordinates S (widths M) ≃ S⊕(Fin n×Bool) + | 0,_ => (Equiv.sumEmpty S (Fin 0×Bool)).symm + | n+1,M => + (Equiv.sumCongr (coordinateEquiv S (fun i => M i.succ)) (Equiv.refl Bool)).trans + ((Equiv.sumAssoc S (Fin n×Bool) Bool).trans + (Equiv.sumCongr (Equiv.refl S) (pairSuccEquiv n))) + +/-- Balanced choices are the dependent product of the actual intervals. -/ +def assignmentEquiv : {n : ℕ} → (M : Fin n → ℕ) → + Assignments (widths M) ≃ ((i : Fin n) → Fin (M i+1)) + | 0,_ => + { toFun := fun _ i => Fin.elim0 i + invFun := fun _ => PUnit.unit + left_inv := by intro a; cases a; rfl + right_inv := by intro a; funext i; exact Fin.elim0 i } + | n+1,M => + { toFun := fun a => Fin.cases a.2 (assignmentEquiv (fun i => M i.succ) a.1) + invFun := fun a => ((assignmentEquiv (fun i => M i.succ)).symm (fun i => a i.succ),a 0) + left_inv := by intro a; simp only [Fin.cases_zero,Fin.cases_succ,Equiv.symm_apply_apply]; exact Prod.eta a + right_inv := by + intro a + funext i + refine Fin.cases ?_ (fun j => ?_) i + · rfl + · exact congrFun ((assignmentEquiv (fun i => M i.succ)).apply_symm_apply + (fun i => a i.succ)) j } + +def joinedProfile {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (a : (i : Fin n) → Fin (M i+1)) : S⊕(Fin n×Bool) → ℕ + | .inl s => z s + | .inr (i,b) => if b then M i-(a i).val else (a i).val + +lemma embedding_coordinate {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (a : (i : Fin n) → Fin (M i+1)) (c : Coordinates S (widths M)) : + embedding (widths M) z ((assignmentEquiv M).symm a) c= + joinedProfile M z a (coordinateEquiv S M c) := by + induction n with + | zero => rfl + | succ n ih => + cases c with + | inl c => + change embedding (widths (fun i => M i.succ)) z + ((assignmentEquiv (fun i => M i.succ)).symm (fun i => a i.succ)) c=_ + rw [ih] + change joinedProfile (fun i => M i.succ) z (fun i => a i.succ) + (coordinateEquiv S (fun i => M i.succ) c)= + joinedProfile M z a (((Equiv.sumAssoc S (Fin n×Bool) Bool).trans + (Equiv.sumCongr (Equiv.refl S) (pairSuccEquiv n))) + (.inl (coordinateEquiv S (fun i => M i.succ) c))) + generalize hc : coordinateEquiv S (fun i => M i.succ) c=q + cases q with + | inl s => rfl + | inr p => rcases p with ⟨i,b⟩; rfl + | inr b => cases b <;> rfl + +/-- The recursively proved marginal is the direct finite sum over the +actual physical intervals. -/ +theorem eliminate_eq_physical_sum {S : Type*} {n : ℕ} (M : Fin n → ℕ) + (F : (S⊕(Fin n×Bool) → ℕ) → ℝ) (z : S → ℕ) : + eliminate (widths M) (fun q => F (q ∘ (coordinateEquiv S M).symm)) z= + ∑ a : ((i : Fin n) → Fin (M i+1)), F (joinedProfile M z a) := by + rw [eliminate_eq_sum] + apply Fintype.sum_equiv (assignmentEquiv M) + intro a + congr 1 + funext c + have h := embedding_coordinate M z ((assignmentEquiv M) a) ((coordinateEquiv S M).symm c) + simpa only [Equiv.symm_apply_apply,Equiv.apply_symm_apply,Function.comp_apply] using h + +variable {C : Type*} + +@[reducible] def SmallView (small : C → Bool) := {c : C // small c=true}×Bool + +@[reducible] def LargeCell (small : C → Bool) := {c : C // small c=false} + +/-- This is the actual partition of doubled cells into small views and +large pairs. -/ +noncomputable def partitionEquiv (small : C → Bool) : + SmallView small⊕(LargeCell small×Bool) ≃ C×Bool where + toFun + | .inl p => (p.1.val,p.2) + | .inr p => (p.1.val,p.2) + invFun p := if h : small p.1=true then .inl (⟨p.1,h⟩,p.2) + else .inr (⟨p.1,Bool.eq_false_iff.mpr h⟩,p.2) + left_inv p := by + cases p with + | inl p => simp only [p.1.property,dite_eq_left] + | inr p => simp only [p.1.property,Bool.false_eq_true,dite_false] + right_inv p := by + dsimp only + split_ifs <;> rfl + +noncomputable def physicalJoinEquiv (small : C → Bool) {n : ℕ} + (e : Fin n ≃ LargeCell small) : SmallView small⊕(Fin n×Bool) ≃ C×Bool := + (Equiv.sumCongr (Equiv.refl _) (Equiv.prodCongr e (Equiv.refl Bool))).trans + (partitionEquiv small) + +/-- Every finite enumeration of the large cells gives the same physical +coordinate space, with each original doubled cell appearing once. -/ +noncomputable def physicalCoordinateEquiv (small : C → Bool) {n : ℕ} + (e : Fin n ≃ LargeCell small) (M : Fin n → ℕ) : + Coordinates (SmallView small) (widths M) ≃ C×Bool := + (coordinateEquiv (SmallView small) M).trans (physicalJoinEquiv small e) + +theorem eliminate_eq_actual_cells (small : C → Bool) {n : ℕ} + (e : Fin n ≃ LargeCell small) (M : Fin n → ℕ) + (F : (C×Bool → ℕ) → ℝ) (z : SmallView small → ℕ) : + eliminate (widths M) (fun q => F (q ∘ (physicalCoordinateEquiv small e M).symm)) z= + ∑ a : ((i : Fin n) → Fin (M i+1)), + F (joinedProfile M z a ∘ (physicalJoinEquiv small e).symm) := by + exact eliminate_eq_physical_sum M (fun q => F (q ∘ (physicalJoinEquiv small e).symm)) z + +end ContingencyTables.LargePairEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForest.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForest.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd458723035e4ebb85c2f92391fdb4fa9cf61035 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForest.lean @@ -0,0 +1,204 @@ +import Mathlib.Combinatorics.SimpleGraph.Acyclic +import Mathlib.Combinatorics.SimpleGraph.Finite +import Mathlib.Combinatorics.SimpleGraph.Operations +import Mathlib.Data.Finset.Max +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! +# The companion's maximum-capacity forest + +Among finite acyclic subgraphs choose one of maximum total capacity. +Positive capacities make it spanning in each large-cell component. A +free edge can replace every tree edge on its path; optimality therefore +gives the exact path-capacity inequality used in the forest estimates. +-/ + +namespace ContingencyTables.MaximumForest + +open scoped BigOperators Classical +open SimpleGraph + +variable {V : Type*} [Fintype V] + +noncomputable def weight (G : SimpleGraph V) (b : Sym2 V → ℕ) : ℕ := + ∑ e ∈ G.edgeFinset, b e + +lemma weight_eq (G : SimpleGraph V) (b : Sym2 V → ℕ) [Fintype G.edgeSet] : + weight G b=∑ e∈G.edgeFinset,b e := by + unfold weight + apply Finset.sum_congr + · ext e + simp only [mem_edgeFinset] + · intro e _ + rfl + +theorem exists_maximum (G : SimpleGraph V) (b : Sym2 V → ℕ) : + ∃ T : SimpleGraph V, T ≤ G ∧ T.IsAcyclic ∧ + ∀ F : SimpleGraph V, F ≤ G → F.IsAcyclic → weight F b ≤ weight T b := by + let S : Finset (SimpleGraph V) := Finset.univ.filter (fun F => F ≤ G ∧ F.IsAcyclic) + have hS : S.Nonempty := ⟨⊥,by simp [S]⟩ + obtain ⟨T,hT,hmax⟩ := Finset.exists_max_image S (fun F => weight F b) hS + have hp := (Finset.mem_filter.mp hT).2 + refine ⟨T,hp.1,hp.2,?_⟩ + intro F hFG hacyc + exact hmax F (by simp [S,hFG,hacyc]) + +lemma weight_sup_edge (T : SimpleGraph V) (b : Sym2 V → ℕ) (u v : V) + (hn : ¬T.Adj u v) (hne : u≠v) : + weight (T ⊔ edge u v) b=b s(u,v)+weight T b := by + rw [weight_eq (T ⊔ edge u v),weight_eq T,T.edgeFinset_sup_edge hn hne,Finset.sum_cons] + +omit [Fintype V] in +/-- Deleting an edge of the unique tree path separates its endpoints. -/ +lemma not_reachable_delete_path_edge (T : SimpleGraph V) (hT : T.IsAcyclic) + {u v : V} (p : T.Walk u v) (hp : p.IsPath) (t : Sym2 V) (ht : t∈p.edges) : + ¬(T.deleteEdges {t}).Reachable u v := by + intro hreach + obtain ⟨q,hq⟩ := hreach.exists_isPath + have he : p=q.mapLe (T.deleteEdges_le {t}) := congrArg Subtype.val + ((hT.subsingleton_path u v).elim ⟨p,hp⟩ ⟨q.mapLe (T.deleteEdges_le {t}),hq.mapLe _⟩) + rw [he] at ht + simp only [Walk.edges_map,Hom.coe_ofLE,Sym2.map_id,List.map_id_fun,id_eq] at ht + have hmem := q.edges_subset_edgeSet ht + rw [edgeSet_deleteEdges] at hmem + exact hmem.2 (by simp) + +/-- This is the source's actual maximum-forest path inequality. -/ +theorem free_edge_le_path_edge (G T : SimpleGraph V) (b : Sym2 V → ℕ) + (hTG : T ≤ G) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph V, F ≤ G → F.IsAcyclic → weight F b ≤ weight T b) + {u v : V} (hG : G.Adj u v) (hfree : ¬T.Adj u v) + (p : T.Walk u v) (hp : p.IsPath) (t : Sym2 V) (ht : t∈p.edges) : + b s(u,v) ≤ b t := by + let D := T.deleteEdges {t} + have hDT : D ≤ T := T.deleteEdges_le {t} + have hDfree : ¬D.Adj u v := fun h => hfree (hDT h) + have hcut : ¬D.Reachable u v := not_reachable_delete_path_edge T hT p hp t ht + have hnew : (D ⊔ edge u v).IsAcyclic := (hT.anti hDT).sup_edge_of_not_reachable hcut + have hnewG : D ⊔ edge u v ≤ G := sup_le (hDT.trans hTG) ((G.edge_le_iff).mpr (Or.inr hG)) + have hopt := hmax (D ⊔ edge u v) hnewG hnew + have hsum := weight_sup_edge D b u v hDfree hG.ne + have hmem : t∈T.edgeFinset := by simpa using p.edges_subset_edgeSet ht + have hdelete : D.edgeFinset=T.edgeFinset.erase t := by + ext e + simp [D,edgeSet_deleteEdges,and_comm] + have hsumDelete : weight D b+b t=weight T b := by + rw [weight_eq D,weight_eq T,hdelete] + exact Finset.sum_erase_add (s := T.edgeFinset) (a := t) b hmem + omega + +/-- The same exchange argument applies directly to a separating cut; +this avoids choosing a path when using the forest's component cuts. -/ +theorem free_edge_le_separating_edge (G T : SimpleGraph V) (b : Sym2 V → ℕ) + (hTG : T ≤ G) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph V, F ≤ G → F.IsAcyclic → weight F b ≤ weight T b) + (t : Sym2 V) (ht : t∈T.edgeSet) {u v : V} + (hG : G.Adj u v) (hfree : ¬T.Adj u v) + (hcut : ¬(T.deleteEdges {t}).Reachable u v) : b s(u,v) ≤ b t := by + let D := T.deleteEdges {t} + have hDT : D ≤ T := T.deleteEdges_le {t} + have hDfree : ¬D.Adj u v := fun h => hfree (hDT h) + have hnew : (D ⊔ edge u v).IsAcyclic := (hT.anti hDT).sup_edge_of_not_reachable hcut + have hnewG : D ⊔ edge u v ≤ G := sup_le (hDT.trans hTG) ((G.edge_le_iff).mpr (Or.inr hG)) + have hopt := hmax (D ⊔ edge u v) hnewG hnew + have hsum := weight_sup_edge D b u v hDfree hG.ne + have hmem : t∈T.edgeFinset := by simpa using ht + have hdelete : D.edgeFinset=T.edgeFinset.erase t := by + ext e + simp [D,edgeSet_deleteEdges,and_comm] + have hsumDelete : weight D b+b t=weight T b := by + rw [weight_eq D,weight_eq T,hdelete] + exact Finset.sum_erase_add (s := T.edgeFinset) (a := t) b hmem + omega + +omit [Fintype V] in +noncomputable def side (D : SimpleGraph V) (u v : V) : Bool := decide (D.Reachable u v) + +omit [Fintype V] in +lemma side_self (D : SimpleGraph V) (u : V) : side D u u=true := by + simp [side] + +omit [Fintype V] in +lemma side_eq_of_reachable (D : SimpleGraph V) (u : V) {v w : V} + (h : D.Reachable v w) : side D u v=side D u w := by + apply Bool.eq_iff_iff.mpr + simp only [side,decide_eq_true_eq] + exact ⟨fun hv => hv.trans h,fun hw => hw.trans h.symm⟩ + +omit [Fintype V] in +lemma not_reachable_of_side_ne (D : SimpleGraph V) (u : V) {v w : V} + (h : side D u v≠side D u w) : ¬D.Reachable v w := by + exact fun hr => h (side_eq_of_reachable D u hr) + +omit [Fintype V] in +/-- Every other tree edge is internal to a deletion component. -/ +lemma side_eq_of_tree_edge (T : SimpleGraph V) (t : Sym2 V) (u : V) {v w : V} + (h : T.Adj v w) (hne : s(v,w)≠t) : + side (T.deleteEdges {t}) u v=side (T.deleteEdges {t}) u w := by + apply side_eq_of_reachable + exact (show (T.deleteEdges {t}).Adj v w by simp [h,hne]).reachable + +omit [Fintype V] in +/-- One deletion component contains an endpoint of the removed edge +and avoids the chosen root. This also works for isolated components. -/ +lemma exists_root_avoiding_side (T : SimpleGraph V) (hT : T.IsAcyclic) + {u v : V} (ht : T.Adj u v) (root : V) (hroot : T.Reachable root u) : + ∃ r : V, T.Reachable root r ∧ side (T.deleteEdges {s(u,v)}) r root=false ∧ + side (T.deleteEdges {s(u,v)}) r u≠side (T.deleteEdges {s(u,v)}) r v := by + let D := T.deleteEdges {s(u,v)} + have hsep : ¬D.Reachable u v := + isBridge_iff.mp (isAcyclic_iff_forall_adj_isBridge.mp hT ht) + by_cases hru : D.Reachable u root + · refine ⟨v,hroot.trans ht.reachable,?_,?_⟩ + · have hn : ¬D.Reachable v root := fun h => hsep (hru.trans h.symm) + simpa only [side,decide_eq_false_iff_not] using hn + · have hn : ¬D.Reachable v u := fun h => hsep h.symm + change side D v u≠side D v v + simp [side,hn] + · refine ⟨u,hroot,?_,?_⟩ + · simpa only [side,decide_eq_false_iff_not] using hru + · change side D u u≠side D u v + simp [side,hsep] + +/-- Capacities of actual free edges crossing a deletion component are +bounded by the capacity of its unique deleted tree edge. -/ +theorem crossing_free_edge_le (G T : SimpleGraph V) (b : Sym2 V → ℕ) + (hTG : T ≤ G) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph V, F ≤ G → F.IsAcyclic → weight F b ≤ weight T b) + (t : Sym2 V) (ht : t∈T.edgeSet) (r : V) {u v : V} + (hG : G.Adj u v) (hfree : ¬T.Adj u v) + (hcross : side (T.deleteEdges {t}) r u≠side (T.deleteEdges {t}) r v) : + b s(u,v) ≤ b t := + free_edge_le_separating_edge G T b hTG hT hmax t ht hG hfree + (not_reachable_of_side_ne _ r hcross) + +/-- Positive capacities force the maximizing acyclic subgraph to span +every original connected component, including isolated vertices. -/ +theorem maximum_spans (G T : SimpleGraph V) (b : Sym2 V → ℕ) + (hTG : T ≤ G) (hT : T.IsAcyclic) + (hmax : ∀ F : SimpleGraph V, F ≤ G → F.IsAcyclic → weight F b ≤ weight T b) + (hb : ∀ e∈G.edgeSet, 0 < b e) : T.Reachable=G.Reachable := by + have hadj : ∀ u v, G.Adj u v → T.Reachable u v := by + intro u v hG + by_contra hnreach + have hn : ¬T.Adj u v := fun h => hnreach h.reachable + have hnew := hT.sup_edge_of_not_reachable hnreach + have hle : T ⊔ edge u v ≤ G := sup_le hTG ((G.edge_le_iff).mpr (Or.inr hG)) + have hopt := hmax (T ⊔ edge u v) hle hnew + have hsum := weight_sup_edge T b u v hn hG.ne + have hpos := hb s(u,v) (by simpa using hG) + omega + funext u v + apply propext + constructor + · intro h; exact h.mono hTG + · rintro ⟨p⟩ + induction p with + | nil => exact ⟨Walk.nil⟩ + | cons h p ih => exact (hadj _ _ h).trans ih + +end ContingencyTables.MaximumForest + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForestExchange.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForestExchange.lean new file mode 100644 index 0000000000000000000000000000000000000000..0767569e39cac269304a574c690229e30c903ab2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/MaximumForestExchange.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.MaximumForest + +namespace OAI + +/-! # The safe-edge invariant for the executed maximum-forest algorithm + +At every step, choose a largest-capacity edge whose endpoints lie in +different current components. It extends the current forest inside a +maximum-weight forest. This is the exchange proof behind the binary +component-search implementation; no forest is enumerated by that program. +-/ + +namespace ContingencyTables.MaximumForestExchange + +open SimpleGraph MaximumForest +open scoped BigOperators Classical + +variable {V : Type*} [Fintype V] + +omit [Fintype V] in +/-- In an acyclic supergraph, an edge between vertices already joined by +the subgraph must itself belong to that subgraph. -/ +lemma adj_of_reachable_of_acyclic {T F : SimpleGraph V} (hTF : T≤F) + (hF : F.IsAcyclic) {u v : V} (hr : T.Reachable u v) (hf : F.Adj u v) : T.Adj u v := by + have hc : (T⊔edge u v).IsAcyclic := + hF.anti (sup_le hTF ((F.edge_le_iff).mpr (Or.inr hf))) + have h := (isAcyclic_sup_fromEdgeSet_iff.mp hc).2 hr + exact h.resolve_left hf.ne + +omit [Fintype V] in +/-- Every path between different current components contains an edge +between different current components. -/ +lemma path_crosses {T F : SimpleGraph V} {u v : V} (p : F.Walk u v) + (hn : ¬T.Reachable u v) : + ∃ a b,F.Adj a b ∧ s(a,b)∈p.edges ∧ ¬T.Reachable a b := by + induction p with + | nil => exact (hn (Reachable.refl _)).elim + | @cons u w v h p ih => + by_cases hu : T.Reachable u w + · obtain ⟨a,b,hab,he,hnab⟩ := ih (fun hw=>hn (hu.trans hw)) + exact ⟨a,b,hab,by simp only [Walk.edges_cons,List.mem_cons]; exact Or.inr he,hnab⟩ + · exact ⟨u,w,h,by simp only [Walk.edges_cons,List.mem_cons,true_or],hu⟩ + +lemma weight_delete {F : SimpleGraph V} (b : Sym2 V→ℕ) + {e : Sym2 V} (he : e∈F.edgeSet) : + weight (F.deleteEdges {e}) b+b e=weight F b := by + have hs : (F.deleteEdges {e}).edgeFinset=F.edgeFinset.erase e := by + ext a + simp [edgeSet_deleteEdges,and_comm] + rw [weight_eq (F.deleteEdges {e}),weight_eq F,hs] + exact Finset.sum_erase_add (s:=F.edgeFinset) (a:=e) b (by simpa using he) + +/-- The current forest is contained in some globally optimal forest. -/ +def Extendible (G T : SimpleGraph V) (b : Sym2 V→ℕ) : Prop := + ∃ F : SimpleGraph V,T≤F ∧ F≤G ∧ F.IsAcyclic ∧ + ∀ H : SimpleGraph V,H≤G → H.IsAcyclic → weight H b≤weight F b + +lemma bottom_extendible (G : SimpleGraph V) (b : Sym2 V→ℕ) : Extendible G ⊥ b := by + obtain ⟨F,hFG,hF,hmax⟩ := exists_maximum G b + exact ⟨F,bot_le,hFG,hF,hmax⟩ + +/-- A greatest edge joining two current components is safe. The argument +uses a maximum forest only as a witness for the invariant. -/ +theorem safe_edge (G T : SimpleGraph V) (b : Sym2 V→ℕ) + (hb : ∀ e∈G.edgeSet,0hnad h.reachable + have hTD : T≤D := by + intro x y hxy + have hne : s(x,y)≠t := by + intro hxyad + have ha : T.Adj a d := by + have hmem : t∈T.edgeSet := by rw [←hxyad]; simpa using hxy + simpa only [t,mem_edgeSet] using hmem + exact htT ha + exact (deleteEdges_adj).mpr ⟨hTF hxy,by simpa only [Set.mem_singleton_iff] using hne⟩ + have hDF : D≤F := F.deleteEdges_le {t} + have hDuv : ¬D.Reachable u v := + not_reachable_delete_path_edge F hF p hp t ht + have hDacyc : (D⊔edge u v).IsAcyclic := + (hF.anti hDF).sup_edge_of_not_reachable hDuv + have hDfree : ¬D.Adj u v := fun h=>hef (hDF h) + have hDG : D⊔edge u v≤G := + sup_le (hDF.trans hFG) ((G.edge_le_iff).mpr (Or.inr he)) + have hweight := weight_sup_edge D b u v hDfree he.ne + have hdelete := weight_delete b htF + have hbetter := hbest a d (hFG had) hnad + have hmono : weight F b≤weight (D⊔edge u v) b := by + dsimp only [D,t] at hweight hdelete hbetter ⊢ + omega + refine ⟨D⊔edge u v,sup_le_sup_right hTD _,hDG,hDacyc,?_⟩ + intro H hHG hH + exact (hmax H hHG hH).trans hmono + +/-- Once no edge joins different current components, the invariant +certifies global optimality of the current forest. -/ +theorem finished (G T : SimpleGraph V) (b : Sym2 V→ℕ) + (hT : Extendible G T b) + (hn : ∀ u v,G.Adj u v → T.Reachable u v) : + T≤G ∧ T.IsAcyclic ∧ + ∀ H : SimpleGraph V,H≤G → H.IsAcyclic → weight H b≤weight T b := by + obtain ⟨F,hTF,hFG,hF,hmax⟩ := hT + have hFT : F≤T := by + intro u v hf + exact adj_of_reachable_of_acyclic hTF hF (hn u v (hFG hf)) hf + have heq : F=T := le_antisymm hFT hTF + exact heq ▸ ⟨hFG,hF,hmax⟩ + +end ContingencyTables.MaximumForestExchange + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAffine.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAffine.lean new file mode 100644 index 0000000000000000000000000000000000000000..623f7aac99f85e87e5f84767cef66e07a4fc65fd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAffine.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCut +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineCoefficients + +namespace OAI + +/-! # Cut coefficients for an explicitly selected forest root + +The same signed cut calculation applies to the executed root selector. +In particular, coefficient size and the maximum-forest capacity bound +do not depend on a classical choice of cut representative. +-/ + +namespace ContingencyTables.RootedAffine + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedCut GraphCompletionCounts +open ForestCapacity ForestCut MaximumForest + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def coefficient (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) : ℝ := + if A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + then -sign A.T S t a/sign A.T S t t.val else 0 + +lemma coefficient_abs_le_one (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) : |coefficient A S t a|≤1 := by + unfold coefficient + split_ifs + · rw [abs_div,abs_neg,sign_abs_self A.T S A.hT,div_one] + exact sign_abs_le_one A.T S t a + · norm_num + +lemma capacity_le_of_coefficient_ne_zero (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) (ha : coefficient A S t a≠0) : + A.b a.1 a.2≤A.b t.val.1 t.val.2 := by + have hf : A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) := by + by_contra hn + exact ha (by simp only [coefficient,hn,ite_false]) + have hcross : treeCut A.T S t (.inl a.1)≠treeCut A.T S t (.inr a.2) := by + intro he + apply ha + simp [coefficient,hf,sign,he] + have h := crossing_free_edge_le (cellGraph A.small) A.T (capacity A.b) + A.hTG A.hT A.hmax (s(Sum.inl t.val.1,Sum.inr t.val.2)) + (by simpa using t.property) + (away A.T (.inl t.val.1) (.inr t.val.2) (S.root (.inl t.val.1))) + (show (cellGraph A.small).Adj (.inl a.1) (.inr a.2) from hf.1) hf.2 hcross + simpa only [capacity_cell] using h + +theorem normalized_coefficient_bound (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) (B : ℝ) (hB : 0 (A.X i j:ℝ)) i=0) + (hc : ∀ j,Sum.inr j≠S.root (.inr j) → + columnDifference A.small q z (fun i j => (A.X i j:ℝ)) j=0) : + z t.val.1 t.val.2=affineTree A S t x q (fun a => z a.1 a.2) := by + let f : I×J → ℝ := fun a => cutTerm A.small + (fun i => treeCut A.T S t (.inl i)) (fun j => treeCut A.T S t (.inr j)) + x q z (fun i j => (A.X i j:ℝ)) a.1 a.2 + have hsum : (∑ a,f a)=0 := by + rw [Fintype.sum_prod_type] + exact cut_sum_zero A.small _ _ x q z _ + (fun i hi => hr i (treeCut_nonroot A.T S A.hT t (.inl i) hi)) + (fun j hj => hc j (treeCut_nonroot A.T S A.hT t (.inr j) hj)) + have hterm (a : I×J) : f a= + (if a=t.val then sign A.T S t t.val*(z a.1 a.2-A.X a.1 a.2) else 0)+ + (if A.small a.1 a.2 then + indicator (treeCut A.T S t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + indicator (treeCut A.T S t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) else 0)- + sign A.T S t t.val*coefficient A S t a*(z a.1 a.2-A.X a.1 a.2) := by + by_cases he : a=t.val + · subst a + have hs : A.small t.val.1 t.val.2=false := A.hTG t.property + simp only [f,cutTerm,hs,Bool.false_eq_true,ite_false,ite_true,coefficient,t.property, + not_true_eq_false,and_false,sign,mul_zero,zero_mul,add_zero,sub_zero] + · by_cases hs : A.small a.1 a.2=true + · simp [f,cutTerm,hs,he,coefficient] + · have hs' : A.small a.1 a.2=false := Bool.eq_false_iff.mpr hs + by_cases ht : A.T.Adj (.inl a.1) (.inr a.2) + · have hz := other_tree_sign_zero A.T S t a ht he + simp only [f,cutTerm,hs',Bool.false_eq_true,ite_false,he,coefficient,ht, + not_true_eq_false,and_false,zero_add,mul_zero,zero_mul,sub_zero] + change sign A.T S t a*(z a.1 a.2-(A.X a.1 a.2:ℝ))=0 + rw [hz,zero_mul] + · simp only [f,cutTerm,hs',Bool.false_eq_true,ite_false,he,coefficient,ht, + not_false_eq_true,and_self,ite_true,zero_add,zero_sub] + change sign A.T S t a*(z a.1 a.2-(A.X a.1 a.2:ℝ))= + -(sign A.T S t t.val*(-sign A.T S t a/sign A.T S t t.val)* + (z a.1 a.2-A.X a.1 a.2)) + field_simp [sign_self_ne_zero A.T S A.hT t] + simp_rw [hterm] at hsum + rw [Finset.sum_sub_distrib,Finset.sum_add_distrib] at hsum + have hsingle : (∑ a : I×J, + if a=t.val then sign A.T S t t.val*(z a.1 a.2-A.X a.1 a.2) else 0)= + sign A.T S t t.val*(z t.val.1 t.val.2-A.X t.val.1 t.val.2) := by simp + rw [hsingle] at hsum + change sign A.T S t t.val*(z t.val.1 t.val.2-A.X t.val.1 t.val.2)+ + smallContribution A S t x q- + (∑ a : I×J,sign A.T S t t.val*coefficient A S t a*(z a.1 a.2-A.X a.1 a.2))=0 at hsum + have hprod : (∑ a : I×J,sign A.T S t t.val*coefficient A S t a*(z a.1 a.2-A.X a.1 a.2))= + sign A.T S t t.val*((∑ a : I×J,coefficient A S t a*z a.1 a.2)- + ∑ a : I×J,coefficient A S t a*(A.X a.1 a.2:ℝ)) := by + rw [mul_sub,Finset.mul_sum,Finset.mul_sum,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro a _ + ring + rw [hprod] at hsum + unfold affineTree AffinePenalty.affineValue offset + apply mul_left_cancel₀ (sign_self_ne_zero A.T S A.hT t) + rw [mul_add,mul_sub,mul_sub,←mul_div_assoc, + mul_div_cancel_left₀ _ (sign_self_ne_zero A.T S A.hT t)] + nlinarith [hsum] + +end ContingencyTables.RootedAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAnnealing.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAnnealing.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9015ebe7e7b55c3b773a4a58493fb9dcd7d0361 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedAnnealing.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledBounds +import OAI.Combinatorics.ContingencyTables.Rooted.RootedFactorialApplication +import OAI.Combinatorics.ContingencyTables.Counting.CompanionAnnealing + +namespace OAI + +/-! +# Adjacent selected-root weights and ideal multipliers + +The actual computed-root penalty satisfies the source height bound. +It gives the factor-two annealing estimates for the same literal +completion count used by the executed density evaluator. +-/ + +namespace ContingencyTables.RootedAnnealing + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication LabelledFactorial +open CompanionAnnealing (scale scale_positive source_parameter) +open ForestAssignmentSplit +open ForestScaledPenalty (rowCounts columnCounts integerCube) +open TwoLiftStates BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The selected-root penalty of an actual integer free assignment. -/ +noncomputable def penalty (A : Instance I J) (R : RootedCompletion.Selection A.T) + (z : View A → ℕ) (f : FreeIndex A.small A.T A.b) : ℝ := + RootedLiteralCount.actualPenalty A R + (ForestCountIdentification.smallX A.small z) (ForestCountIdentification.smallY A.small z) + (freeTable A.small A.T A.b f) + (RootedPhysicalCompletion.solved A R (rowCounts A z) (columnCounts A z) + (fun i j => (freeTable A.small A.T A.b f i j:ℤ))) + +/-- The source height bound holds for the selected, computed root too. -/ +theorem penalty_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) + (z : View A → ℕ) (hz : InBox (bounds A) z) + (f : FreeIndex A.small A.T A.b) : + 0≤ penalty A R z f ∧ penalty A R z f≤ scale A := by + have hv (a : FreeCell A.small A.T) : + 0≤ integerCube A 1 f a ∧ integerCube A 1 f a≤1 := by + have hp : (0:ℝ)<(A.b a.val.1 a.val.2:ℝ)+1 := by positivity + have hf : ((f a).val:ℝ)≤(A.b a.val.1 a.val.2:ℝ)+1 := by + exact_mod_cast (Nat.le_of_lt (f a).isLt) + unfold integerCube + simp only [one_mul] + exact ⟨div_nonneg (Nat.cast_nonneg _) hp.le,(div_le_one hp).mpr hf⟩ + have hb := RootedScaledPenalty.penalty_cube_bound A R 1 1 + (by norm_num) (by norm_num) z hz (integerCube A 1 f) hv + have he := RootedScaledPenalty.penalty_at_integer A R 1 1 (by norm_num) z f + have hr : (fun i j => (ForestCountIdentification.smallX A.small z i j:ℤ))=rowCounts A z := rfl + have hc : (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ))= + columnCounts A z := rfl + rw [hr,hc] at he + rw [he] at hb + simpa only [one_mul,penalty,scale] using hb + +noncomputable def weight (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) : Set (Labels A×Bool) → ℝ := + RootedFactorialApplication.f A R ((j:ℝ)/scale A) + +theorem count_adjacent (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (z : View A → ℕ) + (hz : InBox (bounds A) z) : + (1/2)*RootedCountIdentification.h A R ((j:ℝ)/scale A) z≤ RootedCountIdentification.h A R (((j+1:ℕ):ℝ)/scale A) z ∧ + RootedCountIdentification.h A R (((j+1:ℕ):ℝ)/scale A) z≤ RootedCountIdentification.h A R ((j:ℝ)/scale A) z := by + let K (k : ℕ) (a : ForestAssignmentSplit.FreeIndex A.small A.T A.b) : ℝ := + (2:ℝ)^(-((k:ℝ)/scale A)*penalty A R z a) + have hterm (a : ForestAssignmentSplit.FreeIndex A.small A.T A.b) : + (1/2)*K j a≤ K (j+1) a ∧ K (j+1) a≤ K j a := by + have hp := penalty_bound A R z hz a + have hQ := scale_positive A + have hPQ0 : 0≤ penalty A R z a/scale A := div_nonneg hp.1 hQ.le + have hPQ1 : penalty A R z a/scale A≤1 := (div_le_one hQ).mpr hp.2 + have hlo : (1/2:ℝ)≤(2:ℝ)^(-(penalty A R z a/scale A)) := by + calc + _ = (2:ℝ)^(-1:ℝ) := by norm_num + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + have hup : (2:ℝ)^(-(penalty A R z a/scale A))≤1 := by + calc + _ ≤ (2:ℝ)^(0:ℝ) := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + _ = _ := by norm_num + have he : K (j+1) a=K j a*(2:ℝ)^(-(penalty A R z a/scale A)) := by + unfold K + rw [← Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + push_cast + ring + have hK : 0≤ K j a := (Real.rpow_pos_of_pos (by norm_num) _).le + rw [he] + constructor + · nlinarith [mul_le_mul_of_nonneg_left hlo hK] + · nlinarith [mul_le_mul_of_nonneg_left hup hK] + change (1/2)*(∑ a, K j a)≤(∑ a, K (j+1) a) ∧ (∑ a, K (j+1) a)≤∑ a, K j a + constructor + · rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun a _ => (hterm a).1) + · exact Finset.sum_le_sum (fun a _ => (hterm a).2) + +theorem weight_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (S : Set (Labels A×Bool)) : + 0< weight A R j S := by + exact div_pos (mul_pos (RootedCountIdentification.h_positive A R _ _) (FactorialSignatures.factorialProduct_positive _)) + (CompanionFactorialApplication.denominator_positive A) + +theorem weight_adjacent (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2)*weight A R j S≤ weight A R (j+1) S ∧ weight A R (j+1) S≤ weight A R j S := by + have hz : InBox (bounds A) (groupCount (group (labelCell A)) S) := by + rw [← label_capacity] + exact SliceFactorial.groupCount_inBox _ _ + have h := count_adjacent A R j _ hz + have hc : 0≤ FactorialSignatures.factorialProduct (groupCount (group (labelCell A)) S)/ + CompanionFactorialApplication.denominator A := + (div_pos (FactorialSignatures.factorialProduct_positive _) + (CompanionFactorialApplication.denominator_positive A)).le + unfold weight RootedFactorialApplication.f firstLift + simp only [mul_div_assoc] + constructor + · nlinarith [mul_le_mul_of_nonneg_right h.1 hc] + · exact mul_le_mul_of_nonneg_right h.2 hc + +theorem total_adjacent (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (ps : List ((Labels A×Bool)×(Labels A×Bool))) (S : Set (Labels A×Bool)) : + (1/2)*slotTotal ps (weight A R j) S≤ slotTotal ps (weight A R (j+1)) S ∧ + slotTotal ps (weight A R (j+1)) S≤ slotTotal ps (weight A R j) S := by + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun T => (weight_adjacent A R j T).1) _ + · exact slotTotal_mono _ _ _ (fun T => (weight_adjacent A R j T).2) _ + +theorem ideal_adjacent (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) (hpr : p≠r) : + (slotTotal pairs (weight A R j) ∅/slotDefect pairs (weight A R j) ∅ p r)/2≤ + slotTotal pairs (weight A R (j+1)) ∅/slotDefect pairs (weight A R (j+1)) ∅ p r ∧ + slotTotal pairs (weight A R (j+1)) ∅/slotDefect pairs (weight A R (j+1)) ∅ p r≤ + 2*(slotTotal pairs (weight A R j) ∅/slotDefect pairs (weight A R j) ∅ p r) := by + have h0 := slotTotal_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh + have hd0 := slotDefect_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh p r hp hr hpr + have hd1 := slotDefect_pos pairs _ (weight_positive A R (j+1)) ∅ PairedLabels.fresh p r hp hr hpr + have ha := total_adjacent A R j pairs ∅ + have hb' : (1/2)*slotDefect pairs (weight A R j) ∅ p r≤ slotDefect pairs (weight A R (j+1)) ∅ p r ∧ + slotDefect pairs (weight A R (j+1)) ∅ p r≤ slotDefect pairs (weight A R j) ∅ p r := by + unfold slotDefect + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun S => (weight_adjacent A R j S).1) _ + · exact slotTotal_mono _ _ _ (fun S => (weight_adjacent A R j S).2) _ + constructor + · rw [div_div,div_le_div_iff₀ (mul_pos hd0 (by norm_num)) hd1] + nlinarith [mul_nonneg h0.le (sub_nonneg.mpr hb'.2),mul_nonneg hd0.le (sub_nonneg.mpr ha.1)] + · rw [← mul_div_assoc,div_le_div_iff₀ hd1 hd0] + nlinarith [mul_nonneg hd0.le (sub_nonneg.mpr ha.2),mul_nonneg h0.le (sub_nonneg.mpr hb'.1)] + +end ContingencyTables.RootedAnnealing + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedArithmeticStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedArithmeticStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6a4162737bd6596f16d76d7e6a07bc3335888b6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedArithmeticStep.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrajectory +import OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticStep + +namespace OAI + +/-! # Executed coordinate proposals for the selected-root phase walk -/ + +namespace ContingencyTables.RootedArithmeticStep + +open CommonBasesFPRAS FirstSuccess ResidualMixture FairBits GridBoundary +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open RootedBooleanPhase RealKernelApproximation +open CompanionBooleanPhase (State stepBits proposalBits stepWordEquiv) +open CompanionArithmeticStep (RestWord) +open scoped BigOperators Classical + +noncomputable section + +private def regroup (L P Q : Type*) : (L×(P×Q)) ≃ P×(L×Q) where + toFun b := (b.2.1,(b.1,b.2.2)) + invFun b := (b.2.1,(b.1,b.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +private lemma word_finish_law {B P Q X Z : Type*} + [Fintype B] [Fintype P] [Fintype Q] [Fintype X] [Fintype Z] + [Nonempty B] [Nonempty P] [Nonempty Q] [DecidableEq X] [DecidableEq Z] + (E : B ≃ P×Q) (draw : P → X) (finish : X → Q → Z) : + mapLaw (uniformLaw (α := B)) (fun b => finish (draw (E b).1) (E b).2)= + bindLaw (mapLaw (uniformLaw (α := P)) draw) + (fun x => mapLaw (uniformLaw (α := Q)) (finish x)) := by + have he := map_equiv E (uniformLaw (α := B)) (fun b : P×Q => finish (draw b.1) b.2) + rw [uniform_equiv,←uniform_product] at he + exact he.symm.trans (mapLaw_product_finish _ _ draw finish) + +variable {I J : Type} [Fintype I] [Fintype J] + +def wordSplit (A : Instance I J) (C K j k : ℕ) (xi : ℚ) : + (Fin (stepBits A C K j k xi) → Bool) ≃ + ((Fin (proposalBits A) → Bool)×RestWord A C K j k xi) := + (stepWordEquiv A C K j k xi).trans (regroup _ _ _) + +def finish (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (U : Option (State A)) (rest : RestWord A C K j k xi) : State A := + if rest.1 0 then S else + match U with + | none => S + | some T => + if rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A R C K j hK hW xi v w S.val T.val rest.2.1) + rest.2.2 then T else S + +def step (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (bits : Fin (stepBits A C K j k xi) → Bool) : State A := + let b := wordSplit A C K j k xi bits + finish A R C K j k hK hW xi v w S (CompanionArithmeticProposal.proposal A S b.1) b.2 + +private lemma source_step_eq_finish (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + (fun bits => finish A R C K j k hK hW xi v w S + (CompanionBooleanPhase.proposal A S (wordSplit A C K j k xi bits).1) + (wordSplit A C K j k xi bits).2)= + RootedBooleanPhase.step A R C K j k hK hW xi v w S := by + funext bits + simp only [finish,wordSplit,regroup,RootedBooleanPhase.step,Equiv.trans_apply,Equiv.coe_fn_mk] + by_cases hlazy : (stepWordEquiv A C K j k xi bits).1 0 = true + · simp only [hlazy,ite_true] + · simp only [hlazy] + cases CompanionBooleanPhase.proposal A S + (stepWordEquiv A C K j k xi bits).2.1 with + | none => simp only + | some T => + simp only + by_cases haccept : rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A R C K j hK hW xi v w S.val T.val + (stepWordEquiv A C K j k xi bits).2.2.1) + (stepWordEquiv A C K j k xi bits).2.2.2 + · simp only [haccept,ite_true] + · simp only [haccept,ite_false] + +/-- Exact equality of complete one-step laws, including all holding +probability. Weight calls and the acceptance coin have not been reused. -/ +theorem step_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + mapLaw (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A R C K j k hK hW xi v w S)= + transitionLaw A R C K j k hK hW xi v w S := by + have hnew := word_finish_law (wordSplit A C K j k xi) + (CompanionArithmeticProposal.proposal A S) (finish A R C K j k hK hW xi v w S) + have hold := word_finish_law (wordSplit A C K j k xi) + (CompanionBooleanPhase.proposal A S) (finish A R C K j k hK hW xi v w S) + change mapLaw _ (fun bits => finish A R C K j k hK hW xi v w S + (CompanionArithmeticProposal.proposal A S (wordSplit A C K j k xi bits).1) + (wordSplit A C K j k xi bits).2)=_ + rw [hnew,CompanionArithmeticProposal.proposal_law] + rw [source_step_eq_finish] at hold + exact hold.symm + +/-- The full recorded finite-word path therefore retains the proved +joint-history distribution, rather than merely its terminal marginal. -/ +def recordedWalk (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (bits : Fin (n*stepBits A C K j k xi) → Bool) : PathState (State A) N := + wordWalk (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +theorem recordedWalk_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (recordedWalk A R C K j k N n hK hW xi v w S)= + pathLaw A R C K j k N n hK hW xi v w S := by + unfold recordedWalk pathLaw + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + rw [show mapLaw (uniformLaw (α := Fin n → Fin (stepBits A C K j k xi) → Bool)) + (wordWalk (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n)= + wordWalkLaw (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n from rfl,wordWalkLaw_eq] + congr 1 + funext a + rw [←mapLaw_comp,step_law] + rfl + +end +end ContingencyTables.RootedArithmeticStep + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinDrawLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinDrawLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3c375c21fd3d1fd5e6e1b0e99b480bdfd25e2b8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinDrawLaw.lean @@ -0,0 +1,200 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBinFramesProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDraw + +namespace OAI + +/-! # The computed bin program has the analysed independent law + +The execution order is the computed free-cell catalog. The mathematical +law uses another enumeration. Dependent word equivalences identify their +independent Boolean inputs, while preserving each physical cell's draw. +-/ + +namespace ContingencyTables.RootedBinDrawLaw + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity FirstSuccess ResidualMixture FairBits +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +local instance freeCellDecidableEq (A : Instance (Fin m) (Fin n)) : + DecidableEq (FreeCell A.small A.T) := by + letI : DecidableEq (Fin m) := Classical.decEq _ + letI : DecidableEq (Fin n) := Classical.decEq _ + infer_instance + +abbrev FreeWords (A : Instance (Fin m) (Fin n)) (h : ℕ) := + (t : FreeCell A.small A.T) → Fin (offsetBitLength (freeRange A t) h A.d) → Bool + +abbrev Words (A : Instance (Fin m) (Fin n)) (h : ℕ) := + (i : Fin (RootedCatalogGrid.freeCount A)) → + Fin (offsetBitLength (freeRange A (RootedForestCatalog.freeEquiv A i)) h A.d) → Bool + +def freeWordEquiv (A : Instance (Fin m) (Fin n)) (h : ℕ) : + Words A h ≃ FreeWords A h := + Equiv.piCongrLeft (fun t : FreeCell A.small A.T => + Fin (offsetBitLength (freeRange A t) h A.d) → Bool) (RootedForestCatalog.freeEquiv A) + +def originalWordEquiv (A : Instance (Fin m) (Fin n)) (h : ℕ) : + BinWords A h ≃ FreeWords A h := + Equiv.piCongrLeft (fun t : FreeCell A.small A.T => + Fin (offsetBitLength (freeRange A t) h A.d) → Bool) (index A) + +def reindexWords (A : Instance (Fin m) (Fin n)) (h : ℕ) : + Words A h ≃ BinWords A h := + (freeWordEquiv A h).trans (originalWordEquiv A h).symm + +def wordBits (A : Instance (Fin m) (Fin n)) (h : ℕ) : ℕ := + ∑ i : Fin (RootedCatalogGrid.freeCount A), + offsetBitLength (freeRange A (RootedForestCatalog.freeEquiv A i)) h A.d + +def wordEquiv (A : Instance (Fin m) (Fin n)) (h : ℕ) : + (Fin (wordBits A h) → Bool) ≃ Words A h := + (Equiv.arrowCongr finSigmaFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.piCurry (fun _ _ => Bool)) + +lemma wordBits_eq (A : Instance (Fin m) (Fin n)) (h : ℕ) : + wordBits A h=binWordBits A h := by + unfold wordBits binWordBits + apply Fintype.sum_equiv (RootedCatalogGrid.coordinateEquiv A) + intro i + simp only [RootedCatalogGrid.coordinateEquiv,Equiv.trans_apply, + Equiv.apply_symm_apply] + +def draw (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (bits : Words A h) : FreeIndex A.small A.T A.b := + binWordDraw A K hK hW (RootedCatalogGrid.gridEquiv A K v) h (reindexWords A h bits) + +lemma draw_law (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) : + mapLaw (uniformLaw (α := Words A h)) (draw A K hK hW v h)= + approximateBinLaw A K hK hW (RootedCatalogGrid.gridEquiv A K v) h := by + have he := binWordDraw_law A K hK hW (RootedCatalogGrid.gridEquiv A K v) h + unfold draw + rw [←FairBits.map_equiv (reindexWords A h),FairBits.uniform_equiv] + apply RationalLaw.ext + funext f + exact congrArg (fun p => p.mass f) he + +private lemma interval_bits_le (K N beta h d : ℕ) (hK : 0 < K) (hN : 0 < N) + (hb : beta < K) : + offsetBitLength (intervalSize K N beta) h d ≤ offsetBitLength N h d := by + simpa only [offsetBitLength,BinVectorProgram.activeWidth,BinVectorProgram.reservedWidth, + BinIntervalProgram.intervalSize_eq] using + BinVectorProgram.active_le_reserved K N beta h d hK hN hb + +private lemma coordinate_scalar (K N beta h d : ℕ) (bits : List Bool) : + BinVectorProgram.coordinate ((((K,N),beta),(h,d)),bits)= + FairBits.endpoint K N beta+ProfilePrograms.scaledWordValue + (intervalSize K N beta,bits.take (offsetBitLength (intervalSize K N beta) h d)) := by + simp only [BinVectorProgram.coordinate,BinIntervalProgram.draw,BinIntervalProgram.endpoint_eq, + BinIntervalProgram.intervalSize_eq,BinVectorProgram.activeWidth,offsetBitLength] + +private lemma original_value (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) + (h : ℕ) (bits : FreeWords A h) (i : Fin (dimension A)) : + (binWordDraw A K hK hW v h ((originalWordEquiv A h).symm bits) (index A i)).val= + (intervalEquiv K (freeRange A (index A i)) (naturalBin A v (index A i)) + hK (Nat.succ_pos _) (naturalBin_lt A v _) + (scaledBitInteger (binSize A K v i) (offsetBitLength (binSize A K v i) h A.d) + (binSize_positive A K hK hW v i) + (prefixWord (binBits_le A K hK v h i) (bits (index A i))))).val := by + change ((Equiv.piCongrLeft (fun t : FreeCell A.small A.T => + {z : ℕ // z∈FairBits.fiber K (freeRange A t) (naturalBin A v t)}) (index A)) + (fun j => intervalEquiv K (freeRange A (index A j)) (naturalBin A v (index A j)) + hK (Nat.succ_pos _) (naturalBin_lt A v _) + (scaledBitInteger (binSize A K v j) (offsetBitLength (binSize A K v j) h A.d) + (binSize_positive A K hK hW v j) + (prefixWord (binBits_le A K hK v h j) + ((originalWordEquiv A h).symm bits j)))) (index A i)).val=_ + rw [Equiv.piCongrLeft_apply_apply] + simp only [originalWordEquiv,Equiv.piCongrLeft_symm_apply] + +private lemma original_free_value (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) + (h : ℕ) (bits : FreeWords A h) (t : FreeCell A.small A.T) + (hsize : 0 < intervalSize K (freeRange A t) (naturalBin A v t)) : + (binWordDraw A K hK hW v h ((originalWordEquiv A h).symm bits) t).val= + (intervalEquiv K (freeRange A t) (naturalBin A v t) + hK (Nat.succ_pos _) (naturalBin_lt A v t) + (scaledBitInteger (intervalSize K (freeRange A t) (naturalBin A v t)) + (offsetBitLength (intervalSize K (freeRange A t) (naturalBin A v t)) h A.d) + hsize (prefixWord (interval_bits_le K (freeRange A t) + (naturalBin A v t) h A.d hK (Nat.succ_pos _) (naturalBin_lt A v t)) + (bits t)))).val := by + obtain ⟨i,rfl⟩ := (index A).surjective t + simpa only [binSize] using original_value A K hK hW v h bits i + +lemma draw_coordinate (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (bits : Words A h) (i : Fin (RootedCatalogGrid.freeCount A)) : + BinVectorProgram.coordinate + ((((K,freeRange A (RootedForestCatalog.freeEquiv A i)),(v i).val.toNat),(h,A.d)), + List.ofFn (bits i))= + (draw A K hK hW v h bits (RootedForestCatalog.freeEquiv A i)).val := by + let w := RootedCatalogGrid.gridEquiv A K v + have hb : naturalBin A w (RootedForestCatalog.freeEquiv A i)=(v i).val.toNat := by + simp only [w,naturalBin,RootedCatalogGrid.gridEquiv_free,Equiv.symm_apply_apply] + have hp : 0 < intervalSize K (freeRange A (RootedForestCatalog.freeEquiv A i)) + (naturalBin A w (RootedForestCatalog.freeEquiv A i)) := by + simpa only [binSize,Equiv.apply_symm_apply] using + binSize_positive A K hK hW w ((index A).symm (RootedForestCatalog.freeEquiv A i)) + have hv := original_free_value A K hK hW w h (freeWordEquiv A h bits) + (RootedForestCatalog.freeEquiv A i) hp + let t := RootedForestCatalog.freeEquiv A i + let M := intervalSize K (freeRange A t) (naturalBin A w t) + let k := offsetBitLength M h A.d + have hk : k ≤ offsetBitLength (freeRange A t) h A.d := + interval_bits_le K (freeRange A t) (naturalBin A w t) h A.d hK + (Nat.succ_pos _) (naturalBin_lt A w t) + have hs := ProfilePrograms.scaledWordValue_ofFn M k hp + (prefixWord hk (freeWordEquiv A h bits t)) + change (draw A K hK hW v h bits t).val=FairBits.endpoint K (freeRange A t) + (naturalBin A w t)+(scaledBitInteger M k hp + (prefixWord hk (freeWordEquiv A h bits t))).val at hv + rw [←hs,←BinVectorProgram.take_ofFn_prefix hk] at hv + have hw : freeWordEquiv A h bits (RootedForestCatalog.freeEquiv A i)=bits i := + Equiv.piCongrLeft_apply_apply _ _ _ _ + dsimp only [t,M,k] at hv + rw [hw] at hv + rw [hb] at hv + rw [coordinate_scalar] + exact hv.symm + +def flatDraw (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (bits : Fin (wordBits A h) → Bool) : FreeIndex A.small A.T A.b := + draw A K hK hW v h (wordEquiv A h bits) + +theorem flatDraw_law (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) : + mapLaw (uniformLaw (α := Fin (wordBits A h) → Bool)) (flatDraw A K hK hW v h)= + approximateBinLaw A K hK hW (RootedCatalogGrid.gridEquiv A K v) h := by + unfold flatDraw + rw [←FairBits.map_equiv (wordEquiv A h),FairBits.uniform_equiv,draw_law] + +theorem program_flatDraw (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (bits : Fin (wordBits A h) → Bool) : + RootedBinFramesProgram.draw (RootedBinFramesProgram.data A h v,List.ofFn bits)= + List.ofFn (fun i => (flatDraw A K hK hW v h bits + (RootedForestCatalog.freeEquiv A i)).val) := by + unfold RootedBinFramesProgram.draw + rw [RootedBinFramesProgram.frames_data] + let frames : Fin (RootedCatalogGrid.freeCount A) → BinVectorProgram.Frame := fun i => + (((K,freeRange A (RootedForestCatalog.freeEquiv A i)),(v i).val.toNat),(h,A.d)) + have he := BinVectorProgram.output_ofFn frames bits + refine he.trans ?_ + apply congrArg List.ofFn + funext i + exact draw_coordinate A K hK hW v h (wordEquiv A h bits) i + +end +end ContingencyTables.RootedBinDrawLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinFramesProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinFramesProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..6290035892da3d0675ca042b0e9bf3a496220c86 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBinFramesProgram.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinVectorProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogGrid + +namespace OAI + +/-! # Preparing the actual bin draws from the computed free-cell catalog + +Only the capacity matrix, catalog metadata, grid coordinate list and +numeric sampling parameters are supplied. The program computes each +full range and bin index before invoking the proved vector draw. +-/ + +namespace ContingencyTables.RootedBinFramesProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open scoped BigOperators Classical + +/-- `(K,(precision,dimension))` and the catalog metadata/current bin. -/ +abbrev Input := (ℕ×(ℕ×ℕ))×(RootedForestCatalog.Data×List ℕ) + +def catalog (z : Input) : List (ℕ×ℕ) := RootedForestCatalog.catalog (z.2.1,false) +def catalogRealizer : Realizer catalog := + composition (f := fun z : Input => (z.2.1,false)) (g := RootedForestCatalog.catalog) + (pair (composition second first) (constant false)) RootedForestCatalog.catalogRealizer +lemma polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_constant false)) RootedForestCatalog.polynomial_catalog + +def cell (z : Input×ℕ) : ℕ×ℕ := (catalog z.1).getD z.2 (0,0) +def cellRealizer : Realizer cell := + composition (pair (composition first catalogRealizer) second) (getDFast (0,0)) +lemma polynomial_cell : PolynomialTime cellRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_catalog) + polynomial_second) (polynomial_getDFast (0,0)) + +def rangeSize (z : Input×ℕ) : ℕ := matrixEntry (z.1.2.1.2,cell z)+1 +def rangeSizeRealizer : Realizer rangeSize := + composition (composition (f := fun z : Input×ℕ => (z.1.2.1.2,cell z)) + (g := matrixEntry) + (pair (composition (composition (composition first second) first) second) cellRealizer) + matrixEntryRealizer) successor +lemma polynomial_rangeSize : PolynomialTime rangeSizeRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) polynomial_second) + polynomial_cell) polynomial_matrixEntry) polynomial_successor + +def coordinate (z : Input×ℕ) : ℕ := z.1.2.2.getD z.2 0 +def coordinateRealizer : Realizer coordinate := + composition (pair (composition (composition first second) second) second) (getDFast 0) +lemma polynomial_coordinate : PolynomialTime coordinateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_second) + (polynomial_getDFast 0) + +def item (z : Input×ℕ) : BinVectorProgram.Frame := + (((z.1.1.1,rangeSize z),coordinate z),z.1.1.2) +def itemRealizer : Realizer item := + pair (pair (pair (composition (composition first first) first) rangeSizeRealizer) + coordinateRealizer) (composition (composition first first) second) +lemma polynomial_item : PolynomialTime itemRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_rangeSize) polynomial_coordinate) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + +def indices (z : Input) : List ℕ := List.range (catalog z).length +def indicesRealizer : Realizer indices := + composition (f := catalog) (g := RootedTreeInputProgram.indices) + catalogRealizer RootedTreeInputProgram.indicesRealizer +lemma polynomial_indices : PolynomialTime indicesRealizer := + polynomial_composition polynomial_catalog RootedTreeInputProgram.polynomial_indices + +def frames (z : Input) : List BinVectorProgram.Frame := + (indices z).map (fun i => item (z,i)) +def framesRealizer : Realizer frames := + composition (pair identity indicesRealizer) (mapWith itemRealizer) +theorem polynomial_frames : PolynomialTime framesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_item) + +def draw (z : Input×List Bool) : List ℕ := BinVectorProgram.output (frames z.1,z.2) +def drawRealizer : Realizer draw := + composition (f := fun z : Input×List Bool => (frames z.1,z.2)) (g := BinVectorProgram.output) + (pair (composition first framesRealizer) second) BinVectorProgram.outputRealizer +theorem polynomial_draw : PolynomialTime drawRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_frames) + polynomial_second) BinVectorProgram.polynomial_output + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary + +noncomputable section +variable {m n K : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Input := + ((K,(h,A.d)),(RootedForestCatalog.data A,gridNatCode v)) + +lemma catalog_data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + catalog (data A h v)=List.ofFn (fun i => + ((RootedForestCatalog.freeEquiv A i).val.1.val, + (RootedForestCatalog.freeEquiv A i).val.2.val)) := + RootedTreeInputProgram.freeCatalog_ofFn A + +lemma cell_data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (i : Fin (RootedCatalogGrid.freeCount A)) : + cell (data A h v,i.val)= + ((RootedForestCatalog.freeEquiv A i).val.1.val, + (RootedForestCatalog.freeEquiv A i).val.2.val) := by + rw [cell,catalog_data] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true, + Option.getD_some,Fin.eta] + +lemma rangeSize_data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (i : Fin (RootedCatalogGrid.freeCount A)) : + rangeSize (data A h v,i.val)=CompanionOracleDensity.freeRange A (RootedForestCatalog.freeEquiv A i) := by + change matrixEntry (matrixCode A.b,cell (data A h v,i.val))+1=_ + rw [cell_data,matrixEntry_code] + rfl + +lemma item_data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (i : Fin (RootedCatalogGrid.freeCount A)) : + item (data A h v,i.val)= + (((K,CompanionOracleDensity.freeRange A (RootedForestCatalog.freeEquiv A i)), + (v i).val.toNat),(h,A.d)) := by + rw [item,rangeSize_data] + simp only [coordinate,data,gridNatCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,dite_true,Option.getD_some,Fin.eta] + rfl + +theorem frames_data (A : Instance (Fin m) (Fin n)) (h : ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + frames (data A h v)=List.ofFn (fun i => + (((K,CompanionOracleDensity.freeRange A (RootedForestCatalog.freeEquiv A i)), + (v i).val.toNat),(h,A.d))) := by + apply List.ext_getElem + · simp only [frames,indices,catalog_data,List.length_map,List.length_range,List.length_ofFn] + · intro i hi hj + have hin : i if draw x=y then (1:ℝ) else 0)= + ((mapLaw (uniformLaw (α := X)) draw).mass y:ℝ) := by + rw [word_expectation draw (fun z => if z=y then (1:ℝ) else 0)] + simp [expectation] + +private lemma independent_decision {A B C D : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype D] + (P : A → Prop) (Q : B → Prop) (R : C → D → Prop) + [DecidablePred P] [DecidablePred Q] [∀ c d,Decidable (R c d)] : + uniformAverage (fun z : A×(B×(C×D)) => + if P z.1 ∧ Q z.2.1 ∧ R z.2.2.1 z.2.2.2 then (1:ℝ) else 0)= + uniformAverage (fun a => if P a then (1:ℝ) else 0)* + uniformAverage (fun b => if Q b then (1:ℝ) else 0)* + uniformAverage (fun c => uniformAverage (fun d => if R c d then (1:ℝ) else 0)) := by + have he (z : A×(B×(C×D))) : + (if P z.1 ∧ Q z.2.1 ∧ R z.2.2.1 z.2.2.2 then (1:ℝ) else 0)= + (if P z.1 then 1 else 0)* + ((if Q z.2.1 then 1 else 0)*(if R z.2.2.1 z.2.2.2 then 1 else 0)) := by + by_cases hp : P z.1 <;> by_cases hq : Q z.2.1 <;> + by_cases hr : R z.2.2.1 z.2.2.2 <;> simp [hp,hq,hr] + have hs : (∑ a : A,∑ b : B,∑ c : C,∑ d : D, + (if P a then (1:ℝ) else 0)*((if Q b then 1 else 0)*(if R c d then 1 else 0)))= + (∑ a : A,if P a then (1:ℝ) else 0)*(∑ b : B,if Q b then (1:ℝ) else 0)* + (∑ c : C,∑ d : D,if R c d then (1:ℝ) else 0) := by + symm + simp only [Finset.sum_mul,mul_assoc] + simp only [Finset.mul_sum] + simp only [he,uniformAverage,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul, + ←Finset.sum_div] + rw [hs] + ring + +private lemma lazy_probability : + uniformAverage (fun b : Fin 1 → Bool => if b 0=false then (1:ℝ) else 0)=1/2 := by + rw [uniformAverage_fin_succ] + simp only [Fin.cons_zero,uniformAverage_const] + norm_num [uniformAverage] + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Every nontrivial output probability factors into its lazy bit, +unique neighbor code, and the actual rounded two-oracle acceptance. -/ +theorem transition_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + (rationalThresholdMass k + (acceptance A R C K j hK hW xi v w S.val T.val b):ℝ)) + else 0 := by + have hp : uniformAverage (fun b : Fin (proposalBits A) → Bool => + if proposal A S b=some T then (1:ℝ) else 0)= + if ExchangeAdjacent S.val T.val then 1/(2:ℝ)^proposalBits A else 0 := by + rw [word_probability,proposal_mass] + split_ifs <;> simp + have ha (b : WeightWord A C K j xi×WeightWord A C K j xi) : + uniformAverage (fun coin : Fin k → Bool => + if rationalThresholdAccept k + (acceptance A R C K j hK hW xi v w S.val T.val b) coin then (1:ℝ) else 0)= + (rationalThresholdMass k + (acceptance A R C K j hK hW xi v w S.val T.val b):ℝ) := by + exact rationalThreshold_expectation k _ + (acceptance_bounds A R C hC K j hK hW hB hj xi hx0 hx1 v w hw S.val T.val b).1 + (acceptance_bounds A R C hC K j hK hW hB hj xi hx0 hx1 v w hw S.val T.val b).2 + calc + _ = uniformAverage (fun bits => if step A R C K j k hK hW xi v w S bits=T then (1:ℝ) else 0) := + (word_probability _ T).symm + _ = uniformAverage (fun b : (Fin 1 → Bool)×((Fin (proposalBits A) → Bool)× + ((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool))) => + if b.1 0=false ∧ proposal A S b.2.1=some T ∧ + rationalThresholdAccept k + (acceptance A R C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then (1:ℝ) else 0) := by + simp_rw [step_eq_iff A R C K j k hK hW xi v w S T hST] + have he := uniformAverage_equiv (stepWordEquiv A C K j k xi) + (fun b : (Fin 1 → Bool)×((Fin (proposalBits A) → Bool)× + ((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool))) => + if b.1 0=false ∧ proposal A S b.2.1=some T ∧ + rationalThresholdAccept k + (acceptance A R C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then (1:ℝ) else 0) + convert he using 1 + _ = _ := by + rw [independent_decision (fun b : Fin 1 → Bool => b 0=false) + (fun b : Fin (proposalBits A) → Bool => proposal A S b=some T) + (fun b coin => rationalThresholdAccept k + (acceptance A R C K j hK hW xi v w S.val T.val b) coin),lazy_probability,hp] + simp_rw [ha] + split_ifs <;> ring + +/-- The exact target row is the source Metropolis chain, slowed by its +dyadic neighbor-code padding. The stationary distribution is unchanged. -/ +def referenceChain (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ)) (RootedAnnealing.weight A R j) + (fun p q => by exact_mod_cast hw p q) (RootedAnnealing.weight_positive A R j) + +private lemma chain_eq {X : Type*} [Fintype X] (C D : FiniteChain X) + (hP : C.P=D.P) (hpi : C.π=D.π) : C=D := by + cases C + cases D + dsimp only at hP hpi + cases hP + cases hpi + rfl + +/-- The degree completion used to prove the signature and concentration +theorems leaves every state and transition of the literal chain intact. -/ +theorem referenceChain_eq_completed (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 (w p q:ℝ)) + (DegreeCompletion.completeDegree (RootedAnnealing.weight A R j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + (fun p q => by exact_mod_cast hw p q) + (DegreeCompletion.completeDegree_positive _ _ (RootedWarmStart.actual_degree A R j).1) := by + have he (U : State A) : + chainWeight pairs (fun p q => (w p q:ℝ)) + (DegreeCompletion.completeDegree (RootedAnnealing.weight A R j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) U.val= + chainWeight pairs (fun p q => (w p q:ℝ)) (RootedAnnealing.weight A R j) U.val := by + simp only [chainWeight,DegreeCompletion.completeDegree, + U.property.ncard PairedLabels.fresh PairedLabels.cover,ite_true] + apply chain_eq + · funext S T + dsimp only [referenceChain,metropolisChain,FiniteChain.ofMoves] + simp only [metropolisMove,he] + · funext S + dsimp only [referenceChain,metropolisChain,FiniteChain.ofMoves] + rw [ObservableBounds.chainTotal_completion _ _ _ PairedLabels.fresh PairedLabels.cover,he] + +def targetChain (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 p y-q y) (Finset.univ.erase x) + have he := Finset.sum_erase_add (Finset.univ : Finset X) (fun y => |p y-q y|) + (Finset.mem_univ x) + rw [hd,abs_neg] at he + unfold distance + linarith + +private lemma average_abs {X : Type*} [Fintype X] (f : X → ℝ) : + |uniformAverage f|≤uniformAverage (fun x => |f x|) := by + unfold uniformAverage + rw [abs_div,abs_of_nonneg (show (0:ℝ)≤Fintype.card X from Nat.cast_nonneg _)] + exact div_le_div_of_nonneg_right (Finset.abs_sum_le_sum_abs f Finset.univ) + (Nat.cast_nonneg _) + +/-- The complete transition row loses at most half the acceptance error. +The diagonal is controlled by conservation of probability, rather than +an additional independent error assumption. -/ +theorem row_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 ((transitionLaw A R C K j k hK hW xi v w S).mass T:ℝ)) + ((targetChain A R j hp w hw).P S)≤(6*(xi:ℝ)+1/(2:ℝ)^k)/2 := by + let e : ℝ := 6*(xi:ℝ)+1/(2:ℝ)^k + let a : ℝ := 1/(2*(2:ℝ)^proposalBits A) + have he : 0≤e := by dsimp only [e]; positivity + have ha : 0≤a := by dsimp only [a]; positivity + have hpnt (T : State A) (hST : S≠T) : + |((transitionLaw A R C K j k hK hW xi v w S).mass T:ℝ)- + (targetChain A R j hp w hw).P S T|≤ + if ExchangeAdjacent S.val T.val then a*e else 0 := by + rw [transition_mass A R C hC K j k hK hW hB hj xi hx0 + (by linarith) v w hw S T hST,target_mass A R j hp w hw S T hST] + by_cases h : ExchangeAdjacent S.val T.val + · simp only [h,ite_true] + rw [←mul_sub,abs_mul,abs_of_nonneg ha] + apply mul_le_mul_of_nonneg_left _ ha + rw [←uniformAverage_sub_const] + exact (average_abs _).trans + (average_acceptance_error A R C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v w hw S.val T.val) + · simp [h] + have hm : (∑ T,((transitionLaw A R C K j k hK hW xi v w S).mass T:ℝ))= + ∑ T,(targetChain A R j hp w hw).P S T := by + rw [(targetChain A R j hp w hw).stochastic] + exact_mod_cast (transitionLaw A R C K j k hK hW xi v w S).total + have hc : ((Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val)).card:ℝ)≤ + (2:ℝ)^proposalBits A := by + have hh := proposal_codes A S + rw [Fintype.card_subtype] at hh + exact_mod_cast hh + calc + _ ≤ ∑ T∈Finset.univ.erase S, + |((transitionLaw A R C K j k hK hW xi v w S).mass T:ℝ)- + (targetChain A R j hp w hw).P S T| := distance_le_off_diagonal _ _ S hm + _ ≤ ∑ T∈Finset.univ.erase S, + if ExchangeAdjacent S.val T.val then a*e else 0 := by + apply Finset.sum_le_sum + intro T hT + exact hpnt T (Finset.mem_erase.mp hT).1.symm + _ ≤ ∑ T : State A,if ExchangeAdjacent S.val T.val then a*e else 0 := by + apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.erase_subset _ _) + intro T _ _ + split_ifs <;> positivity + _ = ((Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val)).card:ℝ)*(a*e) := by + rw [←Finset.sum_filter] + simp + _ ≤ (2:ℝ)^proposalBits A*(a*e) := mul_le_mul_of_nonneg_right hc (mul_nonneg ha he) + _ = e/2 := by dsimp only [a]; field_simp + +def pathLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + RationalLaw (PathState (State A) N) := + walkLaw (liftRational (transitionLaw A R C K j k hK hW xi v w) + (fun a : PathState (State A) N => pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T)) (pathInitial N S) n + +def targetPathMass (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T)).power n).P (pathInitial N S) + +/-- The error controls the whole recorded phase history, not merely its +last state. Every step uses a disjoint fresh oracle/acceptance word. -/ +theorem path_distance_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 ((pathLaw A R C K j k N n hK hW xi v w S).mass b:ℝ)) + (targetPathMass A R j hp w hw N n S)≤n*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + unfold pathLaw targetPathMass + apply walk_distance + intro a + apply (lifted_row_distance (transitionLaw A R C K j k hK hW xi v w) + (targetChain A R j hp w hw).kernel + (fun a : PathState (State A) N => pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T) a).trans + exact row_distance A R C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw (pathRead a) + +/-- The same finite step word records the newly sampled state, so the +history law is physically realized by the concatenated step words. -/ +def recordedWalk (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) + (bits : Fin (n*stepBits A C K j k xi) → Bool) : PathState (State A) N := + wordWalk (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +theorem recordedWalk_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (recordedWalk A R C K j k N n hK hW xi v w S)= + walkLaw (liftRational (transitionLaw A R C K j k hK hW xi v w) pathRead pathPut) + (pathInitial N S) n := by + unfold recordedWalk + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + rw [show mapLaw (uniformLaw (α := Fin n → Fin (stepBits A C K j k xi) → Bool)) + (wordWalk (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n)=wordWalkLaw + (fun a b => pathPut a (step A R C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n from rfl,wordWalkLaw_eq] + apply congrArg (fun Q => walkLaw Q (pathInitial N S) n) + funext a + exact (mapLaw_comp (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A R C K j k hK hW xi v w (pathRead a)) (pathPut a)).symm + +end +end ContingencyTables.RootedBooleanPhase + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBooleanPhase.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBooleanPhase.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab86d4392bab2604498a2416e31b5a00fb875b81 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedBooleanPhase.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleAcceptance +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanPhase + +namespace OAI + +/-! # Actual finite-word Metropolis steps using the selected-root oracle -/ + +namespace ContingencyTables.RootedBooleanPhase + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS FirstSuccess FairBits TwoLiftStates GridBoundary ResidualMixture +open CompanionBooleanPhase (State proposal proposal_mass proposalBits proposal_codes stepBits stepWordEquiv) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The realized step evaluates the current and proposed weights from +separate words, then uses a third independent word for its rational coin. -/ +def step (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : State A) (bits : Fin (stepBits A C K j k xi) → Bool) : State A := + let b := stepWordEquiv A C K j k xi bits + if b.1 0 then S else + match proposal A S b.2.1 with + | none => S + | some T => + if rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A R C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then T else S + +/-- A nontrivial move uses exactly its proposal code and the fresh +acceptance experiment. Failed codes and the independent holding bit +contribute only to the diagonal. -/ +theorem step_eq_iff (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : State A) (hST : S ≠ T) (bits : Fin (stepBits A C K j k xi) → Bool) : + step A R C K j k hK hW xi v w S bits=T ↔ + (stepWordEquiv A C K j k xi bits).1 0=false ∧ + proposal A S (stepWordEquiv A C K j k xi bits).2.1=some T ∧ + rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A R C K j hK hW xi v w S.val T.val + (stepWordEquiv A C K j k xi bits).2.2.1) + (stepWordEquiv A C K j k xi bits).2.2.2 := by + dsimp only [step] + generalize stepWordEquiv A C K j k xi bits = b + cases b.1 0 with + | true => simp [hST] + | false => + cases proposal A S b.2.1 with + | none => simp [hST] + | some U => + by_cases hUT : U=T + · subst U + simp [hST] + · by_cases ha : rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A R C K j hK hW xi v w S.val U.val b.2.2.1) b.2.2.2 + · simp [hUT,ha] + · simp [hST,hUT,ha] + +def transitionLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + RationalLaw (State A) := + mapLaw (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A R C K j k hK hW xi v w S) + +def walk (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) + (bits : Fin (n*stepBits A C K j k xi) → Bool) : State A := + wordWalk (step A R C K j k hK hW xi v w) S n + (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +/-- The actual flattened word gives independent repeated transitions; +its law follows from the accepted finite-word walk construction. -/ +theorem walk_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (walk A R C K j k n hK hW xi v w S)= + walkLaw (transitionLaw A R C K j k hK hW xi v w) S n := by + unfold walk + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + exact wordWalkLaw_eq _ _ _ + +end +end ContingencyTables.RootedBooleanPhase + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCappedReturn.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCappedReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..a29f78c9737e58b9c7c212c0fdd81c8e595c2ba6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCappedReturn.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTraceWords +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturn + +namespace OAI + +/-! # Actual selected-root capped returns with their literal fallback -/ + +namespace ContingencyTables.RootedCappedReturn + +open CommonBasesFPRAS RootedBooleanPhase RootedTraceWords +open CompanionFactorialApplication CompanionOracleDensity CompanionRationalUpdates +open CompanionBooleanPhase (State stepBits) +open CompanionCappedReturn (returnDefault returnDefault_event_upper) +open CompanionTraceWords (eventIndicator firstHit) +open CompanionPhaseTrajectory (historyPrefix) +open FirstSuccess RealKernelApproximation TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def returnWordDefault (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin ((n+1)*stepBits A C K j k xi) → Bool) : PlainIndex (pairs : List (Pair A)) := + (returnWord A R C K j k (n+1) hK hW xi v w S.val bits).getD S + +private theorem returnWordDefault_to_path (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + eventIndicator (E (returnWordDefault A R C K j k n hK hW xi v w S bits)))≤ + (targetChain A R j hp w hw).pathExpectation (n+1) S.val + (fun xs => eventIndicator (E (returnDefault (plainPredicate pairs) S xs)))+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + exact arithmetic_recorded_event_bound A R C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val + (fun xs => E (returnDefault (plainPredicate pairs) S xs)) + +private theorem target_returnDefault_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 eventIndicator (E (returnDefault (plainPredicate pairs) S xs)))≤ + (∑ T,(targetChain A R j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A R j hp w hw) S T*eventIndicator (E T))+ + (1-∑ T,(targetChain A R j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A R j hp w hw) n S T) := by + exact returnDefault_event_upper (targetChain A R j hp w hw) (plainPredicate pairs) + (targetKilled A R j hp w hw) (targetKilled_matches A R j hp w hw) E n S + +/-- The implemented total return step is compared to the exact trace, +with its cap loss left explicit for subsequent warm-law averaging. -/ +theorem returnWordDefault_event (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + eventIndicator (E (returnWordDefault A R C K j k n hK hW xi v w S bits)))≤ + (∑ T,(targetChain A R j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A R j hp w hw) S T*eventIndicator (E T))+ + (1-∑ T,(targetChain A R j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A R j hp w hw) n S T)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := returnWordDefault_to_path A R C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw S E + have ht := target_returnDefault_bound A R j hp w hw n S E + have hb := _root_.add_le_add ht + (le_refl (((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))) + exact he.trans hb + +end +end ContingencyTables.RootedCappedReturn + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogGrid.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..5273dbecf1f2703b297ee0fb08ee1611f6e9cff3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogGrid.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenaltyEvaluateProgram + +namespace OAI + +/-! # Computed catalog coordinates for the oracle grid + +The executable free-cell order need not agree with `Fintype.equivFin`. +Explicit reindexing identifies the grid exponent evaluated from the +catalog-ordered list. +-/ + +namespace ContingencyTables.RootedCatalogGrid + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open RootedCompletion +open scoped Classical + +noncomputable section +variable {m n : ℕ} + +abbrev freeCount (A : Instance (Fin m) (Fin n)) := + (RootedForestCatalog.catalog (RootedForestCatalog.data A,false)).length + +def coordinateEquiv (A : Instance (Fin m) (Fin n)) : + Fin (freeCount A) ≃ Fin (CompanionOracleDensity.dimension A) := + (RootedForestCatalog.freeEquiv A).trans (CompanionOracleDensity.index A).symm + +def gridEquiv (A : Instance (Fin m) (Fin n)) (K : ℕ) : + Grid (I := Fin (freeCount A)) K ≃ + Grid (I := Fin (CompanionOracleDensity.dimension A)) K where + toFun v i := v ((coordinateEquiv A).symm i) + invFun v i := v (coordinateEquiv A i) + left_inv v := by funext i; simp only [Equiv.symm_apply_apply] + right_inv v := by funext i; simp only [Equiv.apply_symm_apply] + +lemma gridEquiv_apply (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v : Grid (I := Fin (freeCount A)) K) (i : Fin (freeCount A)) : + gridEquiv A K v (coordinateEquiv A i)=v i := by + change v ((coordinateEquiv A).symm (coordinateEquiv A i))=v i + rw [Equiv.symm_apply_apply] + +lemma gridEquiv_free (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v : Grid (I := Fin (freeCount A)) K) (f : FreeCell A.small A.T) : + gridEquiv A K v ((CompanionOracleDensity.index A).symm f)= + v ((RootedForestCatalog.freeEquiv A).symm f) := by + change v ((coordinateEquiv A).symm ((CompanionOracleDensity.index A).symm f))=_ + simp only [coordinateEquiv,Equiv.symm_trans_apply,Equiv.symm_symm, + Equiv.apply_symm_apply] + +lemma gridEdge_iff (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v w : Grid (I := Fin (freeCount A)) K) (i : Fin (freeCount A)) : + IsGridEdge (gridEquiv A K v,gridEquiv A K w,coordinateEquiv A i) ↔ + IsGridEdge (v,w,i) := by + constructor + · rintro ⟨hstep,hrest⟩ + refine ⟨?_,?_⟩ + · simpa only [corner,gridEquiv_apply] using hstep + · intro j hj + have hji : coordinateEquiv A j≠coordinateEquiv A i := + fun h => hj ((coordinateEquiv A).injective h) + simpa only [gridEquiv_apply] using hrest (coordinateEquiv A j) hji + · rintro ⟨hstep,hrest⟩ + refine ⟨?_,?_⟩ + · simpa only [corner,gridEquiv_apply] using hstep + · intro j hj + have hji : (coordinateEquiv A).symm j≠i := by + intro h + exact hj ((Equiv.apply_symm_apply (coordinateEquiv A) j).symm.trans + (congrArg (coordinateEquiv A) h)) + exact hrest ((coordinateEquiv A).symm j) hji + +theorem neighbor_iff (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v w : Grid (I := Fin (freeCount A)) K) : + Neighbor (gridEquiv A K v) (gridEquiv A K w) ↔ Neighbor v w := by + constructor + · rintro ⟨i,side,hi⟩ + refine ⟨(coordinateEquiv A).symm i,side,?_⟩ + cases side with + | false => + change IsGridEdge (gridEquiv A K w,gridEquiv A K v,i) at hi + apply (gridEdge_iff A K w v ((coordinateEquiv A).symm i)).mp + simpa only [Equiv.apply_symm_apply] using hi + | true => + change IsGridEdge (gridEquiv A K v,gridEquiv A K w,i) at hi + apply (gridEdge_iff A K v w ((coordinateEquiv A).symm i)).mp + simpa only [Equiv.apply_symm_apply] using hi + · rintro ⟨i,side,hi⟩ + refine ⟨coordinateEquiv A i,side,?_⟩ + cases side with + | false => exact (gridEdge_iff A K w v i).mpr hi + | true => exact (gridEdge_iff A K v w i).mpr hi + +def naturalValues (A : Instance (Fin m) (Fin n)) {K : ℕ} + (v : Grid (I := Fin (freeCount A)) K) : FreeCell A.small A.T → ℕ := + fun f => (v ((RootedForestCatalog.freeEquiv A).symm f)).val.toNat + +theorem naturalBin_grid (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v : Grid (I := Fin (freeCount A)) K) : + CompanionOracleDensity.naturalBin A (gridEquiv A K v)=naturalValues A v := by + funext f + unfold CompanionOracleDensity.naturalBin naturalValues + rw [gridEquiv_free] + +theorem naturalValues_list (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v : Grid (I := Fin (freeCount A)) K) : + List.ofFn (fun i => naturalValues A v (RootedForestCatalog.freeEquiv A i))= + List.ofFn (fun i => (v i).val.toNat) := by + apply congrArg List.ofFn + funext i + simp only [naturalValues,Equiv.symm_apply_apply] + +theorem evaluatorInput_grid (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (x q : Fin m → Fin n → ℕ) (v : Grid (I := Fin (freeCount A)) K) : + RootedPenaltyEvaluateProgram.data A C a x q (naturalValues A v)= + (((A.d,A.W),(C,a)),(RootedDemandProgram.data A x q, + List.ofFn (fun i => (v i).val.toNat))) := by + unfold RootedPenaltyEvaluateProgram.data + rw [naturalValues_list] + +/-- Catalog-order evaluation is exactly the grid +exponent after reindexing. The runtime code never uses this equivalence. -/ +theorem evaluate_grid (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (freeCount A)) K) : + RootedPenaltyEvaluateProgram.evaluate + (((A.d,A.W),(C,a)), + (RootedDemandProgram.data A (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j), + List.ofFn (fun i => (v i).val.toNat)))= + RootedOracleDensity.gridExponent A (rowColumn A.T) C a z (gridEquiv A K v) := by + rw [←evaluatorInput_grid] + rw [RootedPenaltyEvaluateProgram.evaluate,RootedPenaltyEvaluateProgram.exponentInput_data] + have h := RootedOracleDensity.exponentCode_grid A (rowColumn A.T) C a hC z + (RootedForestCatalog.treeEquiv A) (RootedForestCatalog.freeEquiv A) (gridEquiv A K v) + rw [naturalBin_grid] at h + exact h + +end +end ContingencyTables.RootedCatalogGrid + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1b0f16422a71d46f7779cb49a925e7dba92a971 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogStep.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogGrid +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFiniteStep + +namespace OAI + +/-! # The actual oracle transition in computed catalog order + +Axis proposals are uniform over a bounded dyadic code space. Changing +the coordinate order preserves their frequencies, even though it need +not preserve the value obtained from an individual proposal word. +-/ + +namespace ContingencyTables.RootedCatalogGrid + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open RootedCompletion ResidualMixture FirstSuccess FairBits +open CompanionOracleDensity (oracleStepBits rationalHeight) +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +lemma freeCount_eq (A : Instance (Fin m) (Fin n)) : + freeCount A=CompanionOracleDensity.dimension A := by + simpa only [Fintype.card_fin] using Fintype.card_congr (RootedForestCatalog.freeEquiv A) + +lemma freeCount_le (A : Instance (Fin m) (Fin n)) : freeCount A≤A.d := by + rw [freeCount_eq] + exact ForestScaledPenalty.free_card_le A + +def exponent (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) : ℕ := + RootedOracleDensity.gridExponent A (rowColumn A.T) C a z (gridEquiv A K v) + +def finiteStepLaw (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) : + RationalLaw (Grid (I := Fin (freeCount A)) K) := + finiteAcceptLaw v (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (exponent A C a z w-exponent A C a z v) (rationalHeight A C)) + +theorem finiteStepLaw_eq (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) : + finiteStepLaw A C a z v= + equivLaw (gridEquiv A K).symm + (RootedOracleDensity.finiteOracleStepLaw A (rowColumn A.T) C a z (gridEquiv A K v)) := by + apply RationalLaw.eq_of_off_diagonal _ _ v + intro w hw + have hvw : v≠w := Ne.symm hw + have he : gridEquiv A K v≠gridEquiv A K w := + fun h => hvw ((gridEquiv A K).injective h) + change (finiteAcceptLaw v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun b => acceptDyadic (exponent A C a z b-exponent A C a z v) + (rationalHeight A C))).mass w= + (RootedOracleDensity.finiteOracleStepLaw A (rowColumn A.T) C a z + (gridEquiv A K v)).mass (gridEquiv A K w) + rw [finiteAcceptLaw_off_diagonal v w _ _ hvw, + RootedOracleDensity.finiteOracleStepLaw, + finiteAcceptLaw_off_diagonal (gridEquiv A K v) (gridEquiv A K w) _ _ he, + axisCodeStep_count (dense_proposal_code_bound A.d (freeCount A) (freeCount_le A)), + axisCodeStep_count (dense_proposal_code_bound A.d (CompanionOracleDensity.dimension A) + (ForestScaledPenalty.free_card_le A)),neighbor_iff] + rfl + +def bitStep (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) + (bits : Fin (oracleStepBits A C) → Bool) : Grid (I := Fin (freeCount A)) K := + let draw := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) bits + match axisCodeStep v draw.1 with + | none => v + | some w => if draw.2.val < 2^(rationalHeight A C-(exponent A C a z w-exponent A C a z v)) + then w else v + +def bitStepLaw (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) : + RationalLaw (Grid (I := Fin (freeCount A)) K) := + mapLaw (uniformLaw (α := Fin (oracleStepBits A C) → Bool)) (bitStep A C a z v) + +lemma bitStepLaw_eq_finite (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (freeCount A)) K) : + bitStepLaw A C a z v=finiteStepLaw A C a z v := by + let E := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) + let f := finiteAcceptStep v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (exponent A C a z w-exponent A C a z v) (rationalHeight A C)) + have hf : bitStep A C a z v=fun bits => f (E bits) := by + funext bits + dsimp [bitStep,f,E,finiteAcceptStep] + simp only [acceptDyadic] + cases axisCodeStep v ((pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C)) bits).1 with + | none => rfl + | some w => dsimp only; split_ifs <;> rfl + unfold bitStepLaw + rw [hf] + change mapLaw (uniformLaw (α := Fin (Nat.clog 2 (8*A.d)+rationalHeight A C) → Bool)) + (fun bits => f (E bits))=_ + rw [←map_equiv E,uniform_equiv,←uniform_product] + rfl + +/-- The actual catalog-order finite-word experiment has the exact +transition law of the oracle mixing theorem. -/ +theorem bitStepLaw_eq (A : Instance (Fin m) (Fin n)) (C a : ℕ) (hC : 0 < C) + (haH : a≤rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1≤K) (hKB : (K:ℝ)≤CompanionOracleDensity.binWidth A C) + (v : Grid (I := Fin (freeCount A)) K) : + bitStepLaw A C a z v= + equivLaw (gridEquiv A K).symm + (RootedOracleDensity.oracleTransitionLaw A (rowColumn A.T) C a z hK (gridEquiv A K v)) := by + rw [bitStepLaw_eq_finite,finiteStepLaw_eq, + RootedOracleDensity.finiteOracleStepLaw_eq A (rowColumn A.T) C a hC haH z hz hK hKB] + +end +end ContingencyTables.RootedCatalogGrid + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..91ae6221ea09a66cfc018c042589f9fb01cc1716 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCatalogWalk.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogStep + +namespace OAI + +/-! # Mixing of the executed catalog-order oracle walk -/ + +namespace ContingencyTables.RootedCatalogGrid + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open RootedCompletion ResidualMixture FirstSuccess +open CompanionOracleDensity (rationalHeight oracleTime) +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +theorem walkLaw_eq (A : Instance (Fin m) (Fin n)) (C a : ℕ) (hC : 0 < C) + (haH : a≤rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1≤K) (hKB : (K:ℝ)≤CompanionOracleDensity.binWidth A C) + (v : Grid (I := Fin (freeCount A)) K) (N : ℕ) : + FirstSuccess.walkLaw (bitStepLaw A C a z) v N= + equivLaw (gridEquiv A K).symm + (RootedOracleDensity.oracleWalkLaw A (rowColumn A.T) C a z hK (gridEquiv A K v) N) := by + induction N with + | zero => + apply RationalLaw.ext + funext w + simp only [RootedOracleDensity.oracleWalkLaw,FirstSuccess.walkLaw,equivLaw,pointLaw, + Equiv.symm_symm,Equiv.apply_eq_iff_eq] + | succ N ih => + have hm (b : Grid (I := Fin (freeCount A)) K) : + (FirstSuccess.walkLaw (bitStepLaw A C a z) v N).mass b= + (RootedOracleDensity.oracleWalkLaw A (rowColumn A.T) C a z hK + (gridEquiv A K v) N).mass (gridEquiv A K b) := + congrArg (fun p => p.mass b) ih + have hk (b w : Grid (I := Fin (freeCount A)) K) : + (bitStepLaw A C a z b).mass w= + (RootedOracleDensity.oracleTransitionLaw A (rowColumn A.T) C a z hK + (gridEquiv A K b)).mass (gridEquiv A K w) := + congrArg (fun p => p.mass w) (bitStepLaw_eq A C a hC haH z hz hK hKB b) + apply RationalLaw.ext + funext w + change (∑ b,(FirstSuccess.walkLaw (bitStepLaw A C a z) v N).mass b* + (bitStepLaw A C a z b).mass w)= + ∑ b,(RootedOracleDensity.oracleWalkLaw A (rowColumn A.T) C a z hK + (gridEquiv A K v) N).mass b* + (RootedOracleDensity.oracleTransitionLaw A (rowColumn A.T) C a z hK b).mass + (gridEquiv A K w) + simp_rw [hm,hk] + exact Fintype.sum_equiv (gridEquiv A K) _ _ (fun _ => rfl) + +theorem wordWalkLaw_eq (A : Instance (Fin m) (Fin n)) (C a : ℕ) (hC : 0 < C) + (haH : a≤rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1≤K) (hKB : (K:ℝ)≤CompanionOracleDensity.binWidth A C) + (v : Grid (I := Fin (freeCount A)) K) (N : ℕ) : + FirstSuccess.wordWalkLaw (bitStep A C a z) v N= + equivLaw (gridEquiv A K).symm + (RootedOracleDensity.oracleWalkLaw A (rowColumn A.T) C a z hK (gridEquiv A K v) N) := by + rw [FirstSuccess.wordWalkLaw_eq] + exact walkLaw_eq A C a hC haH z hz hK hKB v N + +/-- The original quantitative mixing estimate holds for the actual +catalog-order word walk, with the identical number of steps. -/ +theorem wordWalkLaw_variation (A : Instance (Fin m) (Fin n)) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a≤rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1≤K) (hQ : 0 < Q) (hKB : (K:ℝ)≤CompanionOracleDensity.binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (CompanionOracleDensity.dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger + (Grid (I := Fin (CompanionOracleDensity.dimension A)) K)) + (v : Grid (I := Fin (freeCount A)) K) : + (variation (FirstSuccess.wordWalkLaw (bitStep A C a z) v (oracleTime A C K Q theta)) + (equivLaw (gridEquiv A K).symm + (RootedOracleDensity.oracleStationaryLaw A (rowColumn A.T) C a z hK)):ℝ)≤theta/(8*Q) := by + rw [wordWalkLaw_eq A C a hC haH z hz hK hKB,variation_equiv] + apply RootedOracleDensity.oracleWalkLaw_variation A (rowColumn A.T) C a theta + hC _ htheta z hz K Q hK hQ hKB hPL hCheeger (gridEquiv A K v) + rw [←CompanionOracleDensity.rationalHeight_cast] + exact_mod_cast haH + +end +end ContingencyTables.RootedCatalogGrid + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCellDataProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCellDataProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..35531639754ccccee5ce91e588758bdcb0d08bbb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCellDataProgram.lean @@ -0,0 +1,209 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestDataProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetWidths + +namespace OAI + +/-! # Assembling the affine input from ordinary rectangular cell arrays + +The baseline and both stored views are binary natural matrices. The +program reads each cell once, computes its row/column vertex indices, +and constructs the offset evaluator input in row-major order. +-/ + +namespace ContingencyTables.RootedCellDataProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open FiniteGraphRootProgram FiniteGraphCutProgram +open scoped Classical + +abbrev Matrices := (MatrixCode×MatrixCode)×(MatrixCode×MatrixCode) +abbrev Frame := (EdgeInput×ℕ)×(List ℕ×List ℕ) +abbrev Input := Frame×Matrices +abbrev CellInput := Input×(ℕ×ℕ) + +def values (z : Matrices×(ℕ×ℕ)) : (ℕ×ℕ)×(ℕ×ℕ) := + ((matrixEntry (z.1.1.1,z.2),matrixEntry (z.1.1.2,z.2)), + (matrixEntry (z.1.2.1,z.2),matrixEntry (z.1.2.2,z.2))) + +def valuesRealizer : Realizer values := + pair + (pair + (composition (pair (composition (composition first first) first) second) matrixEntryRealizer) + (composition (pair (composition (composition first first) second) second) matrixEntryRealizer)) + (pair + (composition (pair (composition (composition first second) first) second) matrixEntryRealizer) + (composition (pair (composition (composition first second) second) second) matrixEntryRealizer)) + +lemma polynomial_values : PolynomialTime valuesRealizer := + polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) polynomial_matrixEntry) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) polynomial_matrixEntry)) + (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) polynomial_second) polynomial_matrixEntry) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_second) polynomial_matrixEntry)) + +def endpoints (z : Frame×(ℕ×ℕ)) : ℕ×ℕ := + (z.2.1,z.1.2.1.length+z.2.2) +def endpointsRealizer : Realizer endpoints := + pair (composition second first) + (composition (pair (composition (composition (composition first second) first) listLength) + (composition second second)) add) +lemma polynomial_endpoints : PolynomialTime endpointsRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_listLength) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add) + +def cellValues (z : CellInput) : (ℕ×ℕ)×(ℕ×ℕ) := values (z.1.2,z.2) +def cellValuesRealizer : Realizer cellValues := + composition (f := fun z : CellInput => (z.1.2,z.2)) (g := values) + (pair (composition first second) second) valuesRealizer +lemma polynomial_cellValues : PolynomialTime cellValuesRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_values + +def coefficientInput (z : CellInput) : RootedCoefficientProgram.Input := + ((z.1.1.1.1,endpoints (z.1.1,z.2)),(z.1.1.1.2,(cellValues z).1.1)) +def coefficientInputRealizer : Realizer coefficientInput := + pair + (pair (composition (composition (composition first first) first) first) + (composition (pair (composition first first) second) endpointsRealizer)) + (pair (composition (composition (composition first first) first) second) + (composition (composition cellValuesRealizer first) first)) +lemma polynomial_coefficientInput : PolynomialTime coefficientInputRealizer := + polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_endpoints)) + (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_cellValues polynomial_first) + polynomial_first)) + +def entry (z : CellInput) : RootedOffsetProgram.Entry := + ((coefficientInput z,(((cellValues z).2.1,0),((cellValues z).2.2,0))), + ((cellValues z).1.2,0)) +def entryRealizer : Realizer entry := + pair (pair coefficientInputRealizer + (pair (pair (composition (composition cellValuesRealizer second) first) (constant 0)) + (pair (composition (composition cellValuesRealizer second) second) (constant 0)))) + (pair (composition (composition cellValuesRealizer first) second) (constant 0)) +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_pair (polynomial_pair polynomial_coefficientInput + (polynomial_pair + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_cellValues + polynomial_second) polynomial_first) (polynomial_constant 0)) + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_cellValues + polynomial_second) polynomial_second) (polynomial_constant 0)))) + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_cellValues + polynomial_first) polynomial_second) (polynomial_constant 0)) + +def baselineCell (z : Frame) : ℕ×ℕ := + (z.1.1.2.1,z.1.1.2.2-z.2.1.length) +def baselineCellRealizer : Realizer baselineCell := + pair (composition (composition (composition first first) second) first) + (composition (pair (composition (composition (composition first first) second) second) + (composition (composition second first) listLength)) subtract) +lemma polynomial_baselineCell : PolynomialTime baselineCellRealizer := + polynomial_pair (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_listLength)) polynomial_subtract) + +def offsetInput (z : Input) : RootedOffsetProgram.Input := + ((matrixEntry (z.2.1.2,baselineCell z.1),0), + (cellPairs z.1.2).map (fun a => entry (z,a))) +def offsetInputRealizer : Realizer offsetInput := + pair (pair + (composition (pair (composition (composition second first) second) + (composition first baselineCellRealizer)) matrixEntryRealizer) (constant 0)) + (composition (pair identity (composition (composition first second) cellPairsRealizer)) + (mapWith entryRealizer)) +theorem polynomial_offsetInput : PolynomialTime offsetInputRealizer := + polynomial_pair + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_baselineCell)) polynomial_matrixEntry) + (polynomial_constant 0)) + (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_cellPairs)) (polynomial_mapWith polynomial_entry)) + +open CompanionFactorialApplication RootedCompletion + +noncomputable def data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) : Input := + ((((graphCode (A.T.comap finSumFinEquiv.symm), + ((finSumFinEquiv (m := m) (n := n) (.inl t.val.1)).val, + (finSumFinEquiv (m := m) (n := n) (.inr t.val.2)).val)),A.W), + (List.ofFn (fun i => (A.r i).toNat),List.ofFn (fun j => (A.c j).toNat))), + ((matrixCode A.b,matrixCode (fun i j => (A.X i j).toNat)),(matrixCode x,matrixCode q))) + +lemma values_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (i : Fin m) (j : Fin n) : + values ((data A t x q).2,(i.val,j.val))= + ((A.b i j,(A.X i j).toNat),(x i j,q i j)) := by + simp only [values,data,matrixEntry_code] + +lemma coefficientInput_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (i : Fin m) (j : Fin n) : + coefficientInput (data A t x q,(i.val,j.val))=RootedCoefficientProgram.input A t (i,j) := by + simp only [coefficientInput,cellValues,values_data] + simp only [endpoints,data,List.length_ofFn,RootedCoefficientProgram.input, + finSumFinEquiv_apply_left,finSumFinEquiv_apply_right,Fin.val_castAdd,Fin.val_natAdd] + +lemma entry_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (i : Fin m) (j : Fin n) : + entry (data A t x q,(i.val,j.val))=RootedOffsetProgram.entry A t + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) (i,j) := by + have hx : ForestAffineProgram.signedParts (A.X i j)=((A.X i j).toNat,0) := by + unfold ForestAffineProgram.signedParts + rw [Int.toNat_of_nonpos (neg_nonpos.mpr (A.hX i j).1)] + simp only [entry,coefficientInput_data,cellValues,values_data,RootedOffsetProgram.entry] + rw [hx] + simp only [ForestAffineProgram.signedParts,Int.toNat_natCast,Int.toNat_neg_natCast] + +theorem offsetInput_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) : + offsetInput (data A t x q)=RootedOffsetProgram.data A t + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) finProdFinEquiv.symm := by + have hx : ForestAffineProgram.signedParts (A.X t.val.1 t.val.2)= + ((A.X t.val.1 t.val.2).toNat,0) := by + unfold ForestAffineProgram.signedParts + rw [Int.toNat_of_nonpos (neg_nonpos.mpr (A.hX t.val.1 t.val.2).1)] + unfold offsetInput RootedOffsetProgram.data + apply Prod.ext + · simp only [data,baselineCell,List.length_ofFn,finSumFinEquiv_apply_left, + finSumFinEquiv_apply_right,Fin.val_castAdd,Fin.val_natAdd, + Nat.add_sub_cancel_left,matrixEntry_code,hx] + · change (cellPairs (List.ofFn (fun i => (A.r i).toNat), + List.ofFn (fun j => (A.c j).toNat))).map (fun a => entry (data A t x q,a))=_ + rw [DensePrograms.cellPairs_ofFn] + simp only [List.map_ofFn] + congr 1 + funext k + exact entry_data A t x q (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2 + +end ContingencyTables.RootedCellDataProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCoefficientProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCoefficientProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..16748b433fbd665459a0b67b91b88582be6f26b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCoefficientProgram.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.ContingencyTables.Machines.SignedPairProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCutReindex + +namespace OAI + +/-! # Computing signed affine coefficients from the actual forest graph + +The tree and cell endpoints are ordinary vertex indices. The program +computes the canonical cut flags, tests the capacity threshold and tree +adjacency, and returns the normalized signed coefficient. +-/ + +namespace ContingencyTables.RootedCoefficientProgram + +open MatchingFPRAS.TreeTyped +open SignedPairProgram FiniteGraphRootProgram FiniteGraphCutProgram +open scoped Classical + +abbrev Input := (EdgeInput×(ℕ×ℕ))×(ℕ×ℕ) + +def bit (b : Bool) : ℕ := if b then 1 else 0 + +def bitRealizer : Realizer bit := choose identity (constant 1) (constant 0) +lemma polynomial_bit : PolynomialTime bitRealizer := + polynomial_choose polynomial_identity (polynomial_constant 1) (polynomial_constant 0) + +def signs (z : EdgeInput×(ℕ×ℕ)) : Signed := + (bit (canonicalCutCode (z.1,z.2.1)),bit (canonicalCutCode (z.1,z.2.2))) + +def signsRealizer : Realizer signs := + pair + (composition (composition (pair first (composition second first)) canonicalCutCodeRealizer) + bitRealizer) + (composition (composition (pair first (composition second second)) canonicalCutCodeRealizer) + bitRealizer) + +lemma polynomial_signs : PolynomialTime signsRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) polynomial_canonicalCutCode) + polynomial_bit) + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) polynomial_canonicalCutCode) + polynomial_bit) + +def treeSigns (z : EdgeInput) : Signed := signs (z,z.2) +def treeSignsRealizer : Realizer treeSigns := composition (pair identity second) signsRealizer +lemma polynomial_treeSigns : PolynomialTime treeSignsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_second) polynomial_signs + +def adjacent (z : GraphCode×(ℕ×ℕ)) : Bool := decide (z.2.2 ∈ z.1.getD z.2.1 []) +def adjacentRealizer : Realizer adjacent := + composition (pair (composition (pair first (composition second first)) (getDFast [])) + (composition second second)) membership +lemma polynomial_adjacent : PolynomialTime adjacentRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast [])) + (polynomial_composition polynomial_second polynomial_second)) polynomial_membership + +def freeTest (z : Input) : Bool := + decide (z.2.1 ≤ z.2.2) && !adjacent (z.1.1.1,z.1.2) + +def freeTestRealizer : Realizer freeTest := + composition (pair (composition second leNat) + (composition (composition (pair (composition (composition first first) first) + (composition first second)) adjacentRealizer) boolNot)) boolAnd + +lemma polynomial_freeTest : PolynomialTime freeTestRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_leNat) + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition polynomial_first polynomial_second)) polynomial_adjacent) + polynomial_boolNot)) polynomial_boolAnd + +def coefficient (z : Input) : Signed := + if freeTest z then SignedPairProgram.normalize (neg (times (signs z.1,treeSigns z.1.1))) else (0,0) + +def coefficientRealizer : Realizer coefficient := + choose freeTestRealizer + (composition (composition (composition (pair (composition first signsRealizer) + (composition (composition first first) treeSignsRealizer)) timesRealizer) negRealizer) + normalizeRealizer) + (constant (0,0)) + +lemma polynomial_coefficient : PolynomialTime coefficientRealizer := + polynomial_choose polynomial_freeTest + (polynomial_composition (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_signs) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_treeSigns)) polynomial_times) polynomial_neg) polynomial_normalize) + (polynomial_constant (0,0)) + +lemma adjacent_graph {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + (u v : Fin n) : adjacent (graphCode G,(u.val,v.val))=decide (G.Adj u v) := by + apply Bool.eq_iff_iff.mpr + simp only [adjacent,decide_eq_true_eq,graphCode_getD,adjacencyRow_mem] + constructor + · rintro ⟨w,hw,he⟩ + have hwu : w=v := Fin.ext hw + subst w + exact G.adj_symm he + · intro h + exact ⟨v,rfl,G.adj_symm h⟩ + +open CompanionFactorialApplication RootedCompletion RootedIntegerEvaluation + +noncomputable def input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) : Input := + (((graphCode (A.T.comap finSumFinEquiv.symm), + ((finSumFinEquiv (m := m) (n := n) (.inl t.val.1)).val,(finSumFinEquiv (m := m) (n := n) (.inr t.val.2)).val)), + ((finSumFinEquiv (m := m) (n := n) (.inl a.1)).val,(finSumFinEquiv (m := m) (n := n) (.inr a.2)).val)), + (A.W,A.b a.1 a.2)) + +lemma signs_input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) : + value (signs (input A t a).1)=RootedIntegerEvaluation.sign A (rowColumn A.T) t a := by + unfold signs input + rw [RootedCutReindex.canonicalCut_treeCut,RootedCutReindex.canonicalCut_treeCut] + cases hr : RootedCut.treeCut A.T (rowColumn A.T) t (.inl a.1) <;> + cases hc : RootedCut.treeCut A.T (rowColumn A.T) t (.inr a.2) <;> + simp [SignedPairProgram.value,bit,RootedIntegerEvaluation.sign, + RootedIntegerEvaluation.integerIndicator,hr,hc] + +lemma treeSigns_input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) : + value (treeSigns (input A t a).1.1)=RootedIntegerEvaluation.sign A (rowColumn A.T) t t.val := by + change value (signs (input A t t.val).1)=_ + exact signs_input A t t.val + +lemma freeTest_input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) : + freeTest (input A t a)=decide (A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2)) := by + have hcut : A.W ≤ A.b a.1 a.2 ↔ A.small a.1 a.2=false := by + cases hs : A.small a.1 a.2 with + | false => exact ⟨fun _ => rfl,fun _ => (A.hlarge _ _ hs).1⟩ + | true => simp only [Bool.true_eq_false,iff_false]; exact Nat.not_le.mpr (A.hsmall _ _ hs) + unfold freeTest input + rw [adjacent_graph] + apply Bool.eq_iff_iff.mpr + simp only [Bool.and_eq_true,Bool.not_eq_true',decide_eq_true_eq,decide_eq_false_iff_not, + SimpleGraph.comap_adj,Equiv.symm_apply_apply,hcut] + +/-- The output is the literal signed coefficient, with no supplied +cut-membership or coefficient-correctness assumption. -/ +theorem coefficient_input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) : + value (coefficient (input A t a))=RootedIntegerEvaluation.coefficient A (rowColumn A.T) t a := by + unfold coefficient RootedIntegerEvaluation.coefficient + rw [freeTest_input] + by_cases h : A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + · simp [h,value_normalize,value_neg,value_times,signs_input,treeSigns_input] + · simp [h,value] + +end ContingencyTables.RootedCoefficientProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..59b0d8fa189e3f958fdd9b9c2f75735551a8028e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCompletion.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionUnique +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRoots + +namespace OAI + +/-! # Forest completion with an explicit component-root selector + +Only reachability and constancy on each component are needed for the +integral completion. Making these data explicit permits the executed +least-root selector to replace the original quotient representative, +without asserting that two different selectors are equal. +-/ + +namespace ContingencyTables.RootedCompletion + +open scoped BigOperators Classical +open SimpleGraph GraphIntegralCompletion ForestCut ForestCapacity MaximumForest + +variable {V : Type*} + +structure Selection (G : SimpleGraph V) where + root : V → V + reachable : ∀ v,G.Reachable v (root v) + constant : ∀ {u v},G.Reachable u v → root u=root v + +lemma Selection.idempotent {G : SimpleGraph V} (S : Selection G) (v : V) : + S.root (S.root v)=S.root v := (S.constant (S.reachable v)).symm + +noncomputable def original (G : SimpleGraph V) : Selection G where + root := componentRoot G + reachable := componentRoot_reachable G + constant := componentRoot_constant G + +def canonical {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] : Selection G where + root := FiniteGraphRoots.root G + reachable := FiniteGraphRoots.root_reachable G + constant := FiniteGraphRoots.root_constant G + +def Selection.map {W : Type*} {G : SimpleGraph V} {H : SimpleGraph W} + (S : Selection G) (e : G ≃g H) : Selection H where + root v := e (S.root (e.symm v)) + reachable v := by + have h := (S.reachable (e.symm v)).map e.toHom + change H.Reachable (e (e.symm v)) (e (S.root (e.symm v))) at h + simpa only [RelIso.apply_symm_apply] using h + constant h := congrArg e (S.constant (h.map e.symm.toHom)) + +/-- The concrete row-then-column vertex order of the contingency graph. -/ +def rowColumn {m n : ℕ} (T : SimpleGraph (Fin m⊕Fin n)) [DecidableRel T.Adj] : + Selection T := + (canonical (T.comap finSumFinEquiv.symm)).map (Iso.comap finSumFinEquiv.symm T) + +lemma rowColumn_root {m n : ℕ} (T : SimpleGraph (Fin m⊕Fin n)) [DecidableRel T.Adj] + (v : Fin m⊕Fin n) : + (rowColumn T).root v=finSumFinEquiv.symm + (FiniteGraphRoots.root (T.comap finSumFinEquiv.symm) (finSumFinEquiv v)) := rfl + +noncomputable def path {G : SimpleGraph V} (S : Selection G) (v : V) : G.Walk v (S.root v) := + Classical.choice (S.reachable v) + +variable [Fintype V] + +noncomputable def flow {G : SimpleGraph V} (S : Selection G) (r : V → ℤ) (a b : V) : ℤ := + ∑ v,r v*walkFlow (path S v) a b + +lemma flow_skew {G : SimpleGraph V} (S : Selection G) (r : V → ℤ) (a b : V) : + flow S r a b= -flow S r b a := by + unfold flow + rw [←Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro v _ + rw [walkFlow_skew,mul_neg] + +lemma flow_supported {G : SimpleGraph V} (S : Selection G) (r : V → ℤ) + (a b : V) (hab : ¬G.Adj a b) : flow S r a b=0 := by + unfold flow + apply Finset.sum_eq_zero + intro v _ + rw [walkFlow_supported _ a b hab,mul_zero] + +theorem flow_divergence_all {G : SimpleGraph V} (S : Selection G) (r : V → ℤ) (a : V) : + (∑ b,flow S r a b)=r a-∑ v,if S.root v=a then r v else 0 := by + unfold flow + rw [Finset.sum_comm] + simp_rw [←Finset.mul_sum,walkFlow_sum,mul_sub,Finset.sum_sub_distrib] + simp [mul_ite,eq_comm] + +theorem flow_divergence {G : SimpleGraph V} (S : Selection G) (r : V → ℤ) + (a : V) (ha : a≠S.root a) : (∑ b,flow S r a b)=r a := by + have hroot : ∀ v,S.root v≠a := by + intro v hv + have h := S.idempotent v + rw [hv] at h + exact ha h.symm + rw [flow_divergence_all] + simp only [hroot,ite_false,Finset.sum_const_zero,sub_zero] + +variable {I J : Type*} [Fintype I] [Fintype J] + +omit [Fintype V] in +noncomputable def table (T : SimpleGraph (I⊕J)) (S : Selection T) + (r : I → ℤ) (c : J → ℤ) (i : I) (j : J) : ℤ := + flow S (Sum.elim r (fun j => -c j)) (.inl i) (.inr j) + +omit [Fintype V] in +lemma table_supported (T : SimpleGraph (I⊕J)) (S : Selection T) + (r : I → ℤ) (c : J → ℤ) (i : I) (j : J) (h : ¬T.Adj (.inl i) (.inr j)) : + table T S r c i j=0 := flow_supported S _ _ _ h + +omit [Fintype V] in +lemma table_row (small : I → J → Bool) (T : SimpleGraph (I⊕J)) (S : Selection T) + (hT : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (i : I) + (hi : Sum.inl i≠S.root (.inl i)) : (∑ j,table T S r c i j)=r i := by + have hs := flow_divergence S (Sum.elim r (fun j => -c j)) (.inl i) hi + rw [Fintype.sum_sum_type] at hs + have hz : (∑ i',flow S (Sum.elim r (fun j => -c j)) (.inl i) (.inl i'))=0 := by + apply Finset.sum_eq_zero + intro i' _ + apply flow_supported + intro h + exact hT h + simpa only [hz,zero_add,Sum.elim_inl,table] using hs + +omit [Fintype V] in +lemma table_column (small : I → J → Bool) (T : SimpleGraph (I⊕J)) (S : Selection T) + (hT : T≤cellGraph small) (r : I → ℤ) (c : J → ℤ) (j : J) + (hj : Sum.inr j≠S.root (.inr j)) : (∑ i,table T S r c i j)=c j := by + have hs := flow_divergence S (Sum.elim r (fun j => -c j)) (.inr j) hj + rw [Fintype.sum_sum_type] at hs + have hz : (∑ j',flow S (Sum.elim r (fun j => -c j)) (.inr j) (.inr j'))=0 := by + apply Finset.sum_eq_zero + intro j' _ + apply flow_supported + intro h + exact hT h + have hskew : (∑ i,flow S (Sum.elim r (fun j => -c j)) (.inr j) (.inl i))= + -(∑ i,table T S r c i j) := by + rw [←Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + exact flow_skew S _ _ _ + simpa only [hz,add_zero,Sum.elim_inr,hskew,neg_inj] using hs + +omit [Fintype V] in +theorem zero_of_nonroot_sums (T : SimpleGraph (I⊕J)) (S : Selection T) + (hT : T.IsAcyclic) (z : I → J → ℝ) + (hsupport : ∀ i j,¬T.Adj (.inl i) (.inr j) → z i j=0) + (hr : ∀ i,Sum.inl i≠S.root (.inl i) → (∑ j,z i j)=0) + (hc : ∀ j,Sum.inr j≠S.root (.inr j) → (∑ i,z i j)=0) : + ∀ i j,z i j=0 := by + intro i₀ j₀ + by_cases ht : T.Adj (.inl i₀) (.inr j₀) + · let t : Sym2 (I⊕J) := s(Sum.inl i₀,Sum.inr j₀) + let D := T.deleteEdges {t} + let root := S.root (.inl i₀) + obtain ⟨v,hv,hroot,hcross⟩ := exists_root_avoiding_side T hT ht root + (S.reachable (.inl i₀)).symm + let rowU : I → Bool := fun i => side D v (.inl i) + let colU : J → Bool := fun j => side D v (.inr j) + have hcross' : rowU i₀≠colU j₀ := hcross + have hnonroot : ∀ a : I⊕J,side D v a=true → a≠S.root a := by + intro a ha he + have hva : D.Reachable v a := by simpa only [side,decide_eq_true_eq] using ha + have hcomp := hv.trans (hva.mono (T.deleteEdges_le {t})) + have hsame : S.root a=root := by + rw [←S.constant hcomp,S.idempotent] + have haroot : a=root := he.trans hsame + have hbad : side D v root=true := by simpa only [haroot] using ha + exact Bool.false_ne_true (hroot.symm.trans hbad) + let f : I×J → ℝ := fun a => cutTerm (fun _ _ => false) rowU colU 0 0 z 0 a.1 a.2 + have hsum : (∑ a,f a)=0 := by + rw [Fintype.sum_prod_type] + apply cut_sum_zero + · intro i hi + simpa only [rowDifference,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero] + using hr i (hnonroot (.inl i) hi) + · intro j hj + simpa only [columnDifference,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero] + using hc j (hnonroot (.inr j) hj) + have hother : ∀ a : I×J,a≠(i₀,j₀) → f a=0 := by + rintro ⟨i,j⟩ hne + by_cases hij : T.Adj (.inl i) (.inr j) + · have he : rowU i=colU j := side_eq_of_tree_edge T t v hij + (fun h => hne (cell_edge_injective h)) + simp [f,cutTerm,he] + · simp [f,cutTerm,hsupport i j hij] + have hisolate : (∑ a,f a)=f (i₀,j₀) := by + apply Finset.sum_eq_single (i₀,j₀) + · intro a _ hne + exact hother a hne + · simp + rw [hisolate] at hsum + have habs : |f (i₀,j₀)|=|z i₀ j₀| := by + simp only [f,cutTerm,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero, + abs_mul,abs_indicator_sub hcross',one_mul] + rw [hsum,abs_zero] at habs + exact abs_eq_zero.mp habs.symm + · exact hsupport i₀ j₀ ht + +omit [Fintype V] in +theorem table_unique (small : I → J → Bool) (T : SimpleGraph (I⊕J)) (S : Selection T) + (hTG : T≤cellGraph small) (hT : T.IsAcyclic) (r : I → ℤ) (c : J → ℤ) + (z : I → J → ℤ) + (hsupport : ∀ i j,¬T.Adj (.inl i) (.inr j) → z i j=0) + (hr : ∀ i,Sum.inl i≠S.root (.inl i) → (∑ j,z i j)=r i) + (hc : ∀ j,Sum.inr j≠S.root (.inr j) → (∑ i,z i j)=c j) : + z=table T S r c := by + let delta : I → J → ℝ := fun i j => (z i j:ℝ)-table T S r c i j + have hz := zero_of_nonroot_sums T S hT delta (by + intro i j hij + simp only [delta,hsupport i j hij,Int.cast_zero,table_supported T S r c i j hij,sub_self]) + (by + intro i hi + dsimp only [delta] + rw [Finset.sum_sub_distrib,←Int.cast_sum,←Int.cast_sum, + hr i hi,table_row small T S hTG r c i hi,sub_self]) + (by + intro j hj + dsimp only [delta] + rw [Finset.sum_sub_distrib,←Int.cast_sum,←Int.cast_sum, + hc j hj,table_column small T S hTG r c j hj,sub_self]) + funext i j + exact_mod_cast (sub_eq_zero.mp (hz i j)) + +omit [Fintype V] in +theorem table_original (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (hT : T.IsAcyclic) (r : I → ℤ) (c : J → ℤ) : + table T (original T) r c=tableCompletion T r c := + GraphCompletionUnique.tableCompletion_unique small T hTG hT r c _ + (table_supported T (original T) r c) + (table_row small T (original T) hTG r c) + (table_column small T (original T) hTG r c) + +end ContingencyTables.RootedCompletion + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..27b74ce8987f84c862e67ed0ad0e12d0f03097b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentCode.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentSemantics +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRootSemantics + +namespace OAI + +/-! # Computing every root label before summing its signed demand + +The input contains an adjacency list and one positive/negative demand +pair per vertex. The polynomial program computes the root labels itself. +-/ + +namespace ContingencyTables.RootedComponentCode + +open MatchingFPRAS.TreeTyped Polynomial +open RootedCompletion RootedComponentProgram FiniteGraphRootProgram +open scoped BigOperators Classical + +abbrev Input := GraphCode×List (ℕ×ℕ) + +def entry (z : Input×ℕ) : Record := + (rootCode (z.1.1,z.2),z.1.2.getD z.2 (0,0)) + +def entryRealizer : Realizer entry := + pair (composition (pair (composition first first) second) rootCodeRealizer) + (composition (pair (composition first second) second) (getDFast (0,0))) + +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_rootCode) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast (0,0))) + +def labels (z : Input) : List Record := + (List.range z.2.length).map (fun i => entry (z,i)) + +def indicesRealizer : Realizer (fun z : Input => List.range z.2.length) := + composition (composition second listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.2).trans (weight_snd z) + +def labelsRealizer : Realizer labels := + composition (pair identity indicesRealizer) (mapWith entryRealizer) + +lemma polynomial_labels : PolynomialTime labelsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_entry) + +def count (z : Input) : ℕ := total (labels z) +def countRealizer : Realizer count := composition labelsRealizer totalRealizer + +theorem polynomial_count : PolynomialTime countRealizer := + polynomial_composition polynomial_labels polynomial_total + +lemma labels_graph {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + (p q : Fin n → ℕ) : + labels (FiniteGraphRootProgram.graphCode G,List.ofFn (fun i => (p i,q i)))= + records (FiniteGraphRoots.root G) p q := by + apply List.ext_getElem + · simp only [labels,List.length_map,List.length_range,List.length_ofFn,records] + · intro i hi hj + have hin : i (p i,q i)))= + ∑ a,(∑ i,if FiniteGraphRoots.root G i=a then (p i:ℤ)-q i else 0).natAbs := by + rw [count,labels_graph,total_records] + +open CompanionFactorialApplication + +/-- The binary root computation produces the actual penalty metadata +for the canonical row-then-column root convention. -/ +theorem count_instance {m n : ℕ} (A : Instance (Fin m) (Fin n)) (z : View A → ℕ) : + count (FiniteGraphRootProgram.graphCode (A.T.comap finSumFinEquiv.symm), + List.ofFn (fun i : Fin (m+n) => + (positiveDemand A z (finSumFinEquiv.symm i), + negativeDemand A z (finSumFinEquiv.symm i))))= + RootedPenaltyProgram.rootCount A (rowColumn A.T) + (ForestScaledPenalty.rowCounts A z) (ForestScaledPenalty.columnCounts A z) := by + rw [count,labels_graph] + have hh := total_records_rootCount A (rowColumn A.T) + (ForestScaledPenalty.rowCounts A z) (ForestScaledPenalty.columnCounts A z) + finSumFinEquiv.symm + (fun i => positiveDemand A z (finSumFinEquiv.symm i)) + (fun i => negativeDemand A z (finSumFinEquiv.symm i)) + (fun i => naturalDemand_eq A z (finSumFinEquiv.symm i)) + simpa only [rowColumn_root,Equiv.apply_symm_apply,Equiv.symm_apply_apply] using hh + +end ContingencyTables.RootedComponentCode + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..1411581997b74d7e7d486b9706965d4dbbda51f7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentProgram.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRootPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineProgram + +namespace OAI + +/-! # Polynomial signed component sums for the executed root labels -/ + +namespace ContingencyTables.RootedComponentProgram + +open MatchingFPRAS.TreeTyped Polynomial +open scoped BigOperators Classical + +abbrev Record := ℕ×(ℕ×ℕ) +abbrev Input := ℕ×List Record + +def positiveTerm (z : ℕ×Record) : ℕ := if z.1=z.2.1 then z.2.2.1 else 0 +def negativeTerm (z : ℕ×Record) : ℕ := if z.1=z.2.1 then z.2.2.2 else 0 + +def positiveTermRealizer : Realizer positiveTerm := + (choose (composition (pair first (composition second first)) natEqual) + (composition (composition second second) first) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq,positiveTerm]) + +def negativeTermRealizer : Realizer negativeTerm := + (choose (composition (pair first (composition second first)) natEqual) + (composition (composition second second) second) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq,negativeTerm]) + +lemma polynomial_positiveTerm : PolynomialTime positiveTermRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) polynomial_natEqual) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first) (polynomial_constant 0)) + +lemma polynomial_negativeTerm : PolynomialTime negativeTermRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) polynomial_natEqual) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_second) (polynomial_constant 0)) + +def parts (z : Input) : ℕ×ℕ := + ((z.2.map (fun r => positiveTerm (z.1,r))).sum, + (z.2.map (fun r => negativeTerm (z.1,r))).sum) + +def partsRealizer : Realizer parts := + pair (composition (mapWith positiveTermRealizer) listSum) + (composition (mapWith negativeTermRealizer) listSum) + +lemma polynomial_parts : PolynomialTime partsRealizer := + polynomial_pair + (polynomial_composition (polynomial_mapWith polynomial_positiveTerm) polynomial_listSum) + (polynomial_composition (polynomial_mapWith polynomial_negativeTerm) polynomial_listSum) + +def absoluteDifference (z : ℕ×ℕ) : ℕ := z.1-z.2+(z.2-z.1) + +def absoluteDifferenceRealizer : Realizer absoluteDifference := + composition (pair subtract (composition (pair second first) subtract)) add + +lemma polynomial_absoluteDifference : PolynomialTime absoluteDifferenceRealizer := + polynomial_composition (polynomial_pair polynomial_subtract + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_subtract)) + polynomial_add + +lemma absoluteDifference_eq (p q : ℕ) : absoluteDifference (p,q)=( (p:ℤ)-q).natAbs := by + rcases Nat.le_total p q with hpq|hqp + · rw [Int.natAbs_natCast_sub_natCast_of_le hpq] + simp [absoluteDifference,Nat.sub_eq_zero_of_le hpq] + · rw [Int.natAbs_natCast_sub_natCast_of_ge hqp] + simp [absoluteDifference,Nat.sub_eq_zero_of_le hqp] + +def component (z : Input) : ℕ := absoluteDifference (parts z) +def componentRealizer : Realizer component := composition partsRealizer absoluteDifferenceRealizer + +lemma polynomial_component : PolynomialTime componentRealizer := + polynomial_composition polynomial_parts polynomial_absoluteDifference + +def total (rs : List Record) : ℕ := + ((List.range rs.length).map (fun a => component (a,rs))).sum + +def totalRealizer : Realizer total := + composition (composition (pair identity (composition listLength range)) + (mapWith (composition (pair second first) componentRealizer))) listSum + +theorem polynomial_total : PolynomialTime totalRealizer := by + have hr : PolynomialTime (composition (listLength (A := Record)) range) := by + apply polynomial_boundedRange polynomial_listLength X + intro rs + simpa only [Polynomial.eval_X] using list_length_le_weight rs + exact polynomial_composition + (polynomial_composition (polynomial_pair polynomial_identity hr) + (polynomial_mapWith (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) polynomial_component))) polynomial_listSum + +def records {n : ℕ} (root : Fin n → Fin n) (p q : Fin n → ℕ) : List Record := + List.ofFn (fun i => ((root i).val,(p i,q i))) + +lemma parts_records {n : ℕ} (root : Fin n → Fin n) (p q : Fin n → ℕ) (a : Fin n) : + ((parts (a.val,records root p q)).1:ℤ)-(parts (a.val,records root p q)).2= + ∑ i,if root i=a then (p i:ℤ)-q i else 0 := by + simp only [parts,records,List.map_ofFn,Function.comp_apply,positiveTerm,negativeTerm, + List.sum_ofFn,Nat.cast_sum] + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + by_cases h : root i=a + · simp [h] + · have hval : a.val≠(root i).val := by + intro he + exact h (Fin.ext he.symm) + simp [h,hval] + +theorem component_records {n : ℕ} (root : Fin n → Fin n) (p q : Fin n → ℕ) (a : Fin n) : + component (a.val,records root p q)=(∑ i,if root i=a then (p i:ℤ)-q i else 0).natAbs := by + rw [component,absoluteDifference_eq,parts_records] + +theorem total_records {n : ℕ} (root : Fin n → Fin n) (p q : Fin n → ℕ) : + total (records root p q)=∑ a,(∑ i,if root i=a then (p i:ℤ)-q i else 0).natAbs := by + have he : (List.range n).map (fun a => component (a,records root p q))= + List.ofFn (fun a : Fin n => component (a.val,records root p q)) := by + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + unfold total + rw [show (records root p q).length=n by simp only [records,List.length_ofFn]] + rw [he,List.sum_ofFn] + apply Finset.sum_congr rfl + intro a _ + exact component_records root p q a + +end ContingencyTables.RootedComponentProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..113c9b88d3e323c464d955d493407d2e82232c03 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComponentSemantics.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenaltyProgram + +namespace OAI + +/-! # The executed component sums equal the root penalty + +The root-only filter in the manuscript costs no separate test: every +nonroot has an empty root fibre. This connects the polynomial grouped +signed-sum program to the actual selected-root discrepancy. +-/ + +namespace ContingencyTables.RootedComponentProgram + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma componentTotal_zero (A : Instance I J) (S : Selection A.T) + (d : I⊕J → ℤ) (a : I⊕J) (ha : a≠S.root a) : + RootedRootPenalty.componentTotal A S d a=0 := by + have hroot (v : I⊕J) : S.root v≠a := by + intro hv + apply ha + calc + a=S.root v := hv.symm + _=S.root (S.root v) := (S.idempotent v).symm + _=S.root a := congrArg S.root hv + unfold RootedRootPenalty.componentTotal + apply Finset.sum_eq_zero + intro v _ + simp only [hroot v,ite_false,zero_mul] + +theorem rootCount_eq_componentTotals (A : Instance I J) (S : Selection A.T) + (x q : I → J → ℤ) : + RootedPenaltyProgram.rootCount A S x q= + ∑ a,(RootedRootPenalty.componentTotal A S + (ForestRootPenalty.smallDemand A.small A.X x q) a).natAbs := by + unfold RootedPenaltyProgram.rootCount + simp_rw [RootedRootPenalty.signedResidual_eq_small,Int.natAbs_neg] + apply Finset.sum_congr rfl + intro a _ + by_cases ha : a=S.root a + · have hflag : RootedPenalty.rootFlag S a=true := decide_eq_true ha + exact ite_eq_left hflag + · rw [componentTotal_zero A S _ a ha] + simp only [Int.natAbs_zero,ite_self] + +/-- The positive and negative entries may be the actual row and column +small-view sums. Their difference is the only representation invariant +needed by the finite signed component program. -/ +theorem total_records_rootCount (A : Instance I J) (S : Selection A.T) + (x q : I → J → ℤ) {n : ℕ} (e : Fin n ≃ I⊕J) (p m : Fin n → ℕ) + (hd : ∀ i,(p i:ℤ)-m i=ForestRootPenalty.smallDemand A.small A.X x q (e i)) : + total (records (fun i => e.symm (S.root (e i))) p m)= + RootedPenaltyProgram.rootCount A S x q := by + have hs (a : Fin n) : + (∑ i,if e.symm (S.root (e i))=a then (p i:ℤ)-m i else 0)= + RootedRootPenalty.componentTotal A S + (ForestRootPenalty.smallDemand A.small A.X x q) (e a) := by + calc + _=∑ i,if S.root (e i)=e a then + ForestRootPenalty.smallDemand A.small A.X x q (e i) else 0 := by + apply Finset.sum_congr rfl + intro i _ + rw [hd i] + simp only [Equiv.symm_apply_eq] + _=∑ v,if S.root v=e a then + ForestRootPenalty.smallDemand A.small A.X x q v else 0 := + Fintype.sum_equiv e _ _ (fun _ => rfl) + _=_ := by + simp only [RootedRootPenalty.componentTotal,ite_mul,one_mul,zero_mul] + rw [total_records] + calc + _=∑ a,(RootedRootPenalty.componentTotal A S + (ForestRootPenalty.smallDemand A.small A.X x q) (e a)).natAbs := by + apply Finset.sum_congr rfl + intro a _ + rw [hs] + _=∑ a,(RootedRootPenalty.componentTotal A S + (ForestRootPenalty.smallDemand A.small A.X x q) a).natAbs := + Fintype.sum_equiv e _ _ (fun _ => rfl) + _=_ := (rootCount_eq_componentTotals A S x q).symm + +noncomputable def positiveDemand (A : Instance I J) (z : View A → ℕ) : I⊕J → ℕ := + Sum.elim + (fun i => ∑ j,if A.small i j then (A.X i j).toNat else 0) + (fun j => ∑ i,if A.small i j then A.b i j-ForestCountIdentification.smallY A.small z i j else 0) + +noncomputable def negativeDemand (A : Instance I J) (z : View A → ℕ) : I⊕J → ℕ := + Sum.elim + (fun i => ∑ j,if A.small i j then ForestCountIdentification.smallX A.small z i j else 0) + (fun j => ∑ i,if A.small i j then (A.X i j).toNat else 0) + +theorem naturalDemand_eq (A : Instance I J) (z : View A → ℕ) (a : I⊕J) : + (positiveDemand A z a:ℤ)-negativeDemand A z a= + ForestRootPenalty.smallDemand A.small A.X (ForestScaledPenalty.rowCounts A z) + (ForestScaledPenalty.columnCounts A z) a := by + cases a with + | inl i => + simp only [positiveDemand,negativeDemand,Sum.elim_inl,Nat.cast_sum,Nat.cast_ite,Nat.cast_zero, + ForestRootPenalty.smallDemand] + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + cases A.small i j <;> + simp only [Bool.false_eq_true,ite_false,ite_true,sub_zero, + ForestScaledPenalty.rowCounts,Int.toNat_of_nonneg (A.hX i j).1] + | inr j => + simp only [positiveDemand,negativeDemand,Sum.elim_inr,Nat.cast_sum,Nat.cast_ite,Nat.cast_zero, + ForestRootPenalty.smallDemand] + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + cases A.small i j <;> + simp only [Bool.false_eq_true,ite_false,ite_true,sub_zero, + ForestScaledPenalty.columnCounts,Int.toNat_of_nonneg (A.hX i j).1] + +end ContingencyTables.RootedComponentProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComputedEstimator.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComputedEstimator.lean new file mode 100644 index 0000000000000000000000000000000000000000..9bf0c6983284886f47e6183854f02d16f9d5439e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedComputedEstimator.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorBlockProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSampleLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSampleLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorConfidence + +namespace OAI + +/-! # The executed blocks have the complete estimator law + +Only the physical sample programs differ from the original enumeration. +Exact independent-observable transport identifies their whole product +estimator, including every event used by the confidence proof. +-/ + +namespace ContingencyTables.RootedComputedEstimator + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity FirstSuccess ResidualMixture FiniteObservableTransport +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +abbrev RatioWords (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) := + Fin (sampleCount j delta failure) → + (Fin (oracleTime A C K 1 delta*oracleStepBits A C) → Bool) + +abbrev CorrectionWords (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) := + Fin (sampleCount j delta failure) → RootedCorrectionSampleLaw.Words A C + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) + +abbrev Inputs (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) := + (Fin j → RatioWords A C K j delta failure) × CorrectionWords A C K j delta failure + +def ratioAverage (A : Instance (Fin m) (Fin n)) (C K j a : ℕ) + (delta failure : ℚ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (draws : RatioWords A C K j delta failure) : ℚ := + (∑ i,RootedRatioSampleLaw.sample A C a z v (oracleTime A C K 1 delta) (draws i))/ + sampleCount j delta failure + +def correctionAverage (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (delta failure : ℚ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (draws : CorrectionWords A C K j delta failure) : ℚ := + (∑ i,RootedCorrectionSampleLaw.sample A C j K hK hW z (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) (draws i))/ + sampleCount j delta failure + +def estimate (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (delta failure : ℚ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (draws : Inputs A C K j delta failure) : ℚ := + (assignmentCount A:ℚ)*(∏ a : Fin j,ratioAverage A C K j a.val delta failure z v (draws.1 a))* + correctionAverage A C K j hK hW delta failure z v draws.2 + +private lemma ratioAverage_law (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (a : Fin j) : + SameLaw (ratioAverage A C K j a.val delta failure z v) + (fun draws : CompanionOracleDensity.RatioBlock A C K j delta failure => + rationalAverage (RootedOracleDensity.ratioSample A (RootedCompletion.rowColumn A.T) + C a.val z (RootedCatalogGrid.gridEquiv A K v) (oracleTime A C K 1 delta)) + (sampleCount j delta failure) draws) := by + have hsample := RootedRatioSampleLaw.sameLaw A C a.val K hC + (show a.val ≤ rationalHeight A C from Nat.le_trans (Nat.le_of_lt a.isLt) hj) + hK hB.le z hz v (oracleTime A C K 1 delta) + exact (hsample.independent (sampleCount j delta failure)).map + (fun qs : Fin (sampleCount j delta failure) → ℚ => (∑ i,qs i)/sampleCount j delta failure) + +private lemma correctionAverage_law (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + SameLaw (correctionAverage A C K j hK hW delta failure z v) + (fun draws : CompanionOracleDensity.CorrectionBlock A C K j delta failure => + rationalAverage (RootedOracleDensity.correctionSample A (RootedCompletion.rowColumn A.T) + C j z K hK hW (roundingTolerance delta) (RootedCatalogGrid.gridEquiv A K v) + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) + (sampleCount j delta failure) draws) := by + have hsample : SameLaw + (RootedCorrectionSampleLaw.sample A C j K hK hW z (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) + (RootedOracleDensity.correctionSample A (RootedCompletion.rowColumn A.T) C j z K hK hW + (roundingTolerance delta) (RootedCatalogGrid.gridEquiv A K v) + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) := + RootedCorrectionSampleLaw.sample_average A C j K hC hj hK hW hB.le z hz + (roundingTolerance delta) v _ _ + exact (hsample.independent (sampleCount j delta failure)).map + (fun qs : Fin (sampleCount j delta failure) → ℚ => (∑ i,qs i)/sampleCount j delta failure) + +/-- Exact equality of the whole rational estimator law; no extra oracle +or confidence hypothesis is introduced at the implementation boundary. -/ +theorem sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + SameLaw (estimate A C K j hK hW delta failure z v) + (RootedOracleDensity.estimateValue A (RootedCompletion.rowColumn A.T) C z K hK hW j + delta failure (RootedCatalogGrid.gridEquiv A K v)) := by + let originalRatio := fun (a : Fin j) (draws : CompanionOracleDensity.RatioBlock A C K j delta failure) => + rationalAverage (RootedOracleDensity.ratioSample A (RootedCompletion.rowColumn A.T) C a.val z + (RootedCatalogGrid.gridEquiv A K v) (oracleTime A C K 1 delta)) + (sampleCount j delta failure) draws + let originalCorrection := fun draws : CompanionOracleDensity.CorrectionBlock A C K j delta failure => + rationalAverage (RootedOracleDensity.correctionSample A (RootedCompletion.rowColumn A.T) + C j z K hK hW (roundingTolerance delta) (RootedCatalogGrid.gridEquiv A K v) + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) + (sampleCount j delta failure) draws + have hr := FiniteObservableTransport.indexed j + (fun a : Fin j => ratioAverage A C K j a.val delta failure z v) originalRatio + (fun a => ratioAverage_law A C K j hC hj hK hB delta failure z hz v a) + have hc := correctionAverage_law A C K j hC hj hK hW hB delta failure z hz v + have ht := (hr.prod hc).map (fun p : (Fin j → ℚ)×ℚ => (assignmentCount A:ℚ)*(∏ a,p.1 a)*p.2) + have ho (draws : EstimatorInput A C K j delta failure) : + (assignmentCount A:ℚ)*(∏ a,originalRatio a (draws.1 a))*originalCorrection draws.2= + RootedOracleDensity.estimateValue A (RootedCompletion.rowColumn A.T) C z K hK hW j + delta failure (RootedCatalogGrid.gridEquiv A K v) draws := by + rw [RootedOracleDensity.estimateValue,Fintype.prod_option] + simp only [RootedOracleDensity.observedFactor,originalRatio,originalCorrection] + ring + intro phi + have hh := ht phi + change uniformAverage (fun draws : Inputs A C K j delta failure => + phi (estimate A C K j hK hW delta failure z v draws)) = + uniformAverage (fun draws : EstimatorInput A C K j delta failure => + phi ((assignmentCount A:ℚ)*(∏ a,originalRatio a (draws.1 a))* + originalCorrection draws.2)) at hh + exact hh.trans (congrArg uniformAverage (funext (fun draws => congrArg phi (ho draws)))) + +end +end ContingencyTables.RootedComputedEstimator + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedConcentration.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedConcentration.lean new file mode 100644 index 0000000000000000000000000000000000000000..95017a77f10bc49afaf3d6e84eed2d65f5792b67 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedConcentration.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedMultiplierUpdate +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmStart +import OAI.Combinatorics.ContingencyTables.Counting.CompanionConcentration +import OAI.Combinatorics.ContingencyTables.Transport.ObservableTrajectory + +namespace OAI + +/-! # Concentration of the selected-root phase observables -/ + +namespace ContingencyTables.RootedConcentration + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing RootedMultiplierUpdate +open RootedWarmStart (actual_degree) +open CompanionConcentration (pairs_ne_nil square_width_one_le) +open TwoLiftStates BinaryContraction DegreeCompletion ObservableBounds + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma observable_constant_nonnegative (p q : ℝ) (hp : 0 ≤ p) (hq : 0 ≤ q) : + 0 ≤ observableConstant p q := by + unfold observableConstant + positivity + +private lemma bounded_variance_factor (p K v N : ℝ) (hK : 0 ≤ K) + (hN : 0 ≤ N) (hv : v ≤ 1) : + 2*(10*p^2)*K*v/N ≤ 20*p^2*K/N := by + apply div_le_div_of_nonneg_right _ hN + nlinarith [mul_le_mul_of_nonneg_left hv (show 0 ≤ 2*(10*p^2)*K by positivity)] + +/-- Every actual phase observable has the source's mean-square bound +20 p² Kobs/N under a 10 p²-warm start of its original labelled chain. -/ +theorem bounded_MSE (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0< Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) (o : PhaseObservables (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) + (nu : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs w (weight A R j) S.val/chainTotal pairs w (weight A R j)) + (N : ℕ) (hN : 0< N) : + let C := metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A R j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw.positive (completeDegree_positive _ _ (actual_degree A R j).1) + let G := fun S : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) => + phaseObservable pairs (ratio A R j) o S.val + (∑ S,nu S*C.squareMoment (fun S => G S-C.mean G) N S)/(N:ℝ)^2≤ + 20*(Fintype.card (Labels A):ℝ)^2* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/N := by + let gs : List ((Labels A×Bool)×(Labels A×Bool)) := pairs + let F := completeDegree (weight A R j) gs.length + have hF := completeDegree_positive (weight A R j) gs.length (actual_degree A R j).1 + let C := metropolisChain gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w F hw.positive hF + let G : Set (Labels A×Bool) → ℝ := phaseObservable gs (ratio A R j) o + have hG : ∀ S,0≤ G S ∧ G S≤1 := by + intro S + exact phaseObservable_bounded gs (ratio A R j) + (fun T _ => ⟨by linarith [(ratio_bounds A R j T).1],(ratio_bounds A R j T).2⟩) o S + have h := ObservableTrajectory.omission_chain_timeAverage gs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover w (weight A R j) G hw.positive (actual_degree A R j).1 (actual_degree A R j).2 + ((A.W:ℝ)^2) (square_width_one_le A) (phaseObservable_class gs (ratio A R j) o) + hw.lower hw.upper (10*(Fintype.card (Labels A):ℝ)^2) (by positivity) nu hwarm N hN + have hv := C.variance_le_one (fun S => G S.val) (fun S => hG S.val) + change C.variance (fun S => G S.val)≤1 at hv + rw [metropolisChain_variance,chainVariance_completion gs (weight A R j) G w + PairedLabels.fresh PairedLabels.cover] at hv + have hm : C.mean (fun S => G S.val)=chainMean gs w (weight A R j) G := by + rw [metropolisChain_mean,chainMean_completion gs (weight A R j) G w + PairedLabels.fresh PairedLabels.cover] + change (∑ S,nu S*C.squareMoment (fun S => G S.val-C.mean (fun T => G T.val)) N S)/(N:ℝ)^2≤ _ + rw [hm] + calc + _ ≤ 2*(10*(Fintype.card (Labels A):ℝ)^2)*ObservableBounds.observableConstant gs.length ((A.W:ℝ)^2)* + chainVariance gs w (weight A R j) G/N := h + _ ≤ 20*(Fintype.card (Labels A):ℝ)^2*observableConstant gs.length ((A.W:ℝ)^2)/N := + bounded_variance_factor _ _ _ _ + (observable_constant_nonnegative _ _ (Nat.cast_nonneg _) (sq_nonneg _)) (Nat.cast_nonneg _) hv + _ = _ := by simp only [gs,PairedLabels.length] + +/-- The source's finite union bound for all actual phase observables. +The warm-start hypothesis is the restart endpoint condition, rather than +an independent phase-concentration assumption. -/ +theorem phase_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0< Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) + (nu : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hnu : ∀ S,0≤ nu S) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs w (weight A R j) S.val/chainTotal pairs w (weight A R j)) + (N : ℕ) (hN : 0< N) (eta : ℝ) (heta : 0< eta) : + let C := metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A R j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw.positive (completeDegree_positive _ _ (actual_degree A R j).1) + C.pathProbability nu (N-1) (fun l => ∃ o : PhaseObservables (pairs : List ((Labels A×Bool)×(Labels A×Bool))), + eta*C.mean (fun S => phaseObservable pairs (ratio A R j) o S.val)< + |FiniteChain.pathSum (fun S => phaseObservable pairs (ratio A R j) o S.val) l/(N:ℝ)- + C.mean (fun S => phaseObservable pairs (ratio A R j) o S.val)|)≤ + 16000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/((N:ℝ)*eta^2) := by + let gs : List ((Labels A×Bool)×(Labels A×Bool)) := pairs + let F := completeDegree (weight A R j) gs.length + have hF := completeDegree_positive (weight A R j) gs.length (actual_degree A R j).1 + let C := metropolisChain gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w F hw.positive hF + let p : ℝ := Fintype.card (Labels A) + let K := ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) + have hpR : 0< p := by dsimp only [p]; exact_mod_cast hp + have hK : 0≤ K := observable_constant_nonnegative _ _ (Nat.cast_nonneg _) (sq_nonneg _) + have hNR : (0:ℝ)< N := by exact_mod_cast hN + have hmean (o : PhaseObservables gs) : + 1/(20*p^2)≤ C.mean (fun S => phaseObservable gs (ratio A R j) o S.val) := by + rw [metropolisChain_mean,chainMean_completion gs (weight A R j) + (phaseObservable gs (ratio A R j) o) w PairedLabels.fresh PairedLabels.cover] + have hh := phaseObservable_mean_lower gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + w (weight A R j) (ratio A R j) hw.positive (weight_positive A R j) + (fun S _ => (ratio_bounds A R j S).1) hw.lower hw.upper o + simpa only [p,gs,PairedLabels.length] using hh + have hb := C.relative_union_bound nu hnu + (fun o S => phaseObservable gs (ratio A R j) o S.val) + (1/(20*p^2)) eta (20*p^2*K/N) (by positivity) heta (by positivity) hmean N hN + (fun o => bounded_MSE A R j hp w hw o nu hwarm N hN) + have hJ : (Fintype.card (PhaseObservables gs):ℝ)≤2*p^2 := by + have hc := phaseObservables_card gs PairedLabels.fresh (pairs_ne_nil A hp) + simp only [gs,PairedLabels.length] at hc + dsimp only [p,gs] + exact_mod_cast hc + apply hb.trans + calc + _ ≤ (2*p^2)*(20*p^2*K/N)/(eta*(1/(20*p^2)))^2 := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right hJ (by positivity)) (sq_nonneg _) + _ = 16000*p^8*K/((N:ℝ)*eta^2) := by + field_simp [hpR.ne',heta.ne',hNR.ne'] + ring + +end ContingencyTables.RootedConcentration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..50091be978281333265f296588fe14c99ca42063 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionArithmetic.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleDraw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCorrectionArithmetic +import OAI.Combinatorics.ContingencyTables.Transport.PowerOfTwoApproximation + +namespace OAI + +/-! # Rational evaluation of the literal integer-population correction -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def correctionExponent (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : ℚ := + (gridExponent A R C a z (integerBin A K hK f):ℚ)- + (a:ℚ)/rationalHeight A C*rationalD A R C z (rationalIntegerPoint A C f) + +lemma correctionExponent_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + (correctionExponent A R C a z K hK f:ℝ)= + (gridExponent A R C a z (integerBin A K hK f):ℝ)- + (a:ℝ)/height A C*D A R C z (integerPoint A C f) := by + simp only [correctionExponent,Rat.cast_sub,Rat.cast_natCast,Rat.cast_mul,Rat.cast_div, + rationalHeight_cast,rationalD_cast,rationalIntegerPoint_cast] + +/-- The exponent passed to numerical approximation is a bounded rational, +although the original capacities may be arbitrarily large. -/ +theorem correctionExponent_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hB : (K:ℝ)=binWidth A C) (f : FreeIndex A.small A.T A.b) : + -2 ≤ correctionExponent A R C a z K hK f ∧ correctionExponent A R C a z K hK f ≤ 2 := by + have hCR : (0:ℝ) < C := by exact_mod_cast hC + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + have hd := exponent_change A R C a hCR (Nat.cast_nonneg _) haHR z + (realCorner (integerBin A K hK f)) (integerPoint A C f) 1 (by norm_num) + (fun i => by simpa only [abs_sub_comm] using integerPoint_distance A C K hK hB f i) + have he := gridExponent_eq_floor A R C a z (integerBin A K hK f) + have hlo := Int.floor_le ((a:ℝ)/height A C*D A R C z (realCorner (integerBin A K hK f))) + have hhi := Int.lt_floor_add_one ((a:ℝ)/height A C*D A R C z (realCorner (integerBin A K hK f))) + rw [←he] at hlo hhi + have hbounds : (-2:ℝ) ≤ (correctionExponent A R C a z K hK f:ℝ) ∧ + (correctionExponent A R C a z K hK f:ℝ) ≤ 2 := by + rw [correctionExponent_cast] + simp only [Int.cast_natCast] at hlo hhi + rcases abs_le.mp hd with ⟨hl,hu⟩ + constructor <;> linarith + constructor + · exact_mod_cast hbounds.1 + · exact_mod_cast hbounds.2 + +lemma correction_eq_population_power (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + correction A R C a z K hK f=(rationalPopulation A K hK f:ℝ)* + (2:ℝ)^(correctionExponent A R C a z K hK f:ℝ) := by + have hV : gridWeight A R C a z (integerBin A K hK f)= + (2:ℝ)^(-(gridExponent A R C a z (integerBin A K hK f):ℝ)) := by + unfold gridWeight V DenseWeights.binWeight + rw [←gridExponent_eq_floor] + simp only [Int.cast_natCast] + have hr : rho A R C a z (integerPoint A C f)/gridWeight A R C a z (integerBin A K hK f)= + (2:ℝ)^(correctionExponent A R C a z K hK f:ℝ) := by + rw [hV,correctionExponent_cast] + unfold rho DenseWeights.density + rw [←Real.rpow_sub (by norm_num : (0:ℝ)<2)] + congr 1 + ring + unfold correction + rw [mul_div_assoc,hr] + congr 1 + simp only [rationalPopulation,Rat.cast_div,Rat.cast_mul,Rat.cast_pow,Rat.cast_natCast] + +def computedCorrection (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (sigma : ℚ) (f : FreeIndex A.small A.T A.b) : ℚ := + rationalPopulation A K hK f* + PowerOfTwoApproximation.approximate (correctionExponent A R C a z K hK f) sigma + +/-- A deterministic pointwise relative-error guarantee for the actual +rational correction returned on every integer assignment. -/ +theorem computedCorrection_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hB : (K:ℝ)=binWidth A C) + (sigma : ℚ) (hsigma : 0 < sigma) (f : FreeIndex A.small A.T A.b) : + |(computedCorrection A R C a z K hK sigma f:ℝ)-correction A R C a z K hK f| ≤ + (sigma:ℝ)*correction A R C a z K hK f := by + have hb := correctionExponent_bounds A R C a hC haH z K hK hB f + have he := PowerOfTwoApproximation.approximate_error _ sigma hb.1 hb.2 hsigma + have hp : (0:ℝ) ≤ rationalPopulation A K hK f := by + exact_mod_cast (rationalPopulation_positive A K hK f).le + rw [correction_eq_population_power] + simp only [computedCorrection,Rat.cast_mul] + rw [←mul_sub,abs_mul,abs_of_nonneg hp] + exact (mul_le_mul_of_nonneg_left he hp).trans_eq (by ring) + +/-- Positivity and a uniform range hold on all executions, independently +of the statistical event used by the estimator. -/ +theorem computedCorrection_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (f : FreeIndex A.small A.T A.b) : + (1/16:ℝ) ≤ computedCorrection A R C a z K hK sigma f ∧ + (computedCorrection A R C a z K hK sigma f:ℝ) ≤ 8 := by + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + have hb := correction_bounds A R C a (by exact_mod_cast hC) (Nat.cast_nonneg _) haHR z K hK hW hB f + have he := computedCorrection_error A R C a hC haH z K hK hB sigma hsigma f + have hsR : (sigma:ℝ) ≤ 1/2 := by + simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_ofNat] using + (Rat.cast_le (K := ℝ)).mpr hsigmaHalf + have hprod : (sigma:ℝ)*correction A R C a z K hK f ≤ (1/2)*correction A R C a z K hK f := + mul_le_mul_of_nonneg_right hsR (by linarith [hb.1]) + rcases abs_le.mp he with ⟨hl,hu⟩ + constructor <;> nlinarith + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..03b17decd8207b6e8fcabe6c8148d2db7932049d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionProgram.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPointPenaltyProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBinFramesProgram +import OAI.Combinatorics.ContingencyTables.Machines.BinPopulationProgram +import OAI.Combinatorics.ContingencyTables.Machines.CorrectionValueProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWalkProgram + +namespace OAI + +/-! # The executed selected-root correction + +The stored grid point and sampled integer point share their literal +capacity, forest, baseline and small-view arrays. The program computes +the grid exponent, point penalty and population factor before the +bounded rational power approximation. +-/ + +namespace ContingencyTables.RootedCorrectionProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open scoped BigOperators Classical + +abbrev State := RootedOracleWalkProgram.State +abbrev Input := (State×List ℕ)×(List Bool×List Bool) + +def exponentInput (z : Input) : RootedPenaltyEvaluateProgram.Input := + (z.1.1.1.2.1,(z.1.1.1.2.2,z.1.1.2)) +def exponentInputRealizer : Realizer exponentInput := + pair (composition (composition (composition (composition first first) first) second) first) + (pair (composition (composition (composition (composition first first) first) second) second) + (composition (composition first first) second)) +lemma polynomial_exponentInput : PolynomialTime exponentInputRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) + +def pointInput (z : Input) : RootedForestPrepareProgram.Input := + ((((exponentInput z).1.2.1,RootedPenaltyEvaluateProgram.width (exponentInput z).1), + (exponentInput z).2.1),z.1.2) +def pointInputRealizer : Realizer pointInput := by + let params : Realizer (fun z : Input => (exponentInput z).1) := + composition (f := exponentInput) (g := fun z => z.1) exponentInputRealizer first + let c : Realizer (fun z : Input => (exponentInput z).1.2.1) := + composition (composition params second) first + let width : Realizer (fun z : Input => RootedPenaltyEvaluateProgram.width (exponentInput z).1) := + composition (f := fun z : Input => (exponentInput z).1) + (g := RootedPenaltyEvaluateProgram.width) params RootedPenaltyEvaluateProgram.widthRealizer + exact pair (pair (pair c width) + (composition (composition exponentInputRealizer second) first)) (composition first second) +lemma polynomial_pointInput : PolynomialTime pointInputRealizer := by + unfold pointInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_exponentInput polynomial_first) polynomial_second) + polynomial_first) + (polynomial_composition (polynomial_composition polynomial_exponentInput polynomial_first) + RootedPenaltyEvaluateProgram.polynomial_width)) + (polynomial_composition (polynomial_composition polynomial_exponentInput polynomial_second) + polynomial_first)) (polynomial_composition polynomial_first polynomial_second) + +def binInput (z : Input) : RootedBinFramesProgram.Input := + ((z.1.1.1.1,(0,z.1.1.1.2.1.1.1)),((exponentInput z).2.1.1,z.1.1.2)) +def binInputRealizer : Realizer binInput := + pair (pair (composition (composition (composition first first) first) first) + (pair (constant 0) (composition + (composition (composition (composition (composition (composition first first) first) + second) first) first) first))) + (pair (composition (composition (composition exponentInputRealizer second) first) first) + (composition (composition first first) second)) +lemma polynomial_binInput : PolynomialTime binInputRealizer := + polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_pair (polynomial_constant 0) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_first) polynomial_first) polynomial_first))) + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_exponentInput polynomial_second) polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) + +def populationInput (z : Input) : List BinIntervalProgram.Input := + (RootedBinFramesProgram.frames (binInput z)).map Prod.fst +def populationInputRealizer : Realizer populationInput := + composition (f := fun z : Input => RootedBinFramesProgram.frames (binInput z)) + (g := fun xs : List BinVectorProgram.Frame => xs.map Prod.fst) + (composition binInputRealizer RootedBinFramesProgram.framesRealizer) (map first) +lemma polynomial_populationInput : PolynomialTime populationInputRealizer := + polynomial_composition + (polynomial_composition polynomial_binInput RootedBinFramesProgram.polynomial_frames) + (polynomial_map polynomial_first) + +def phase (z : Input) : TreeFraction.Fraction := + ((exponentInput z).1.2.2,RootedPenaltyEvaluateProgram.height (exponentInput z).1) +def phaseRealizer : Realizer phase := + pair (composition (composition (composition exponentInputRealizer first) second) second) + (composition (f := fun z : Input => (exponentInput z).1) + (g := RootedPenaltyEvaluateProgram.height) + (composition exponentInputRealizer first) RootedPenaltyEvaluateProgram.heightRealizer) +lemma polynomial_phase : PolynomialTime phaseRealizer := + polynomial_pair (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_exponentInput polynomial_first) polynomial_second) + polynomial_second) + (polynomial_composition (polynomial_composition polynomial_exponentInput polynomial_first) + RootedPenaltyEvaluateProgram.polynomial_height) + +attribute [local irreducible] RootedPenaltyEvaluateProgram.evaluate + RootedPointPenaltyProgram.output BinPopulationProgram.output + +def exponentValue (z : Input) : ℕ := + RootedPenaltyEvaluateProgram.evaluate (exponentInput z) +def exponentValueRealizer : Realizer exponentValue := + composition (f := exponentInput) (g := RootedPenaltyEvaluateProgram.evaluate) + exponentInputRealizer RootedPenaltyEvaluateProgram.evaluateRealizer +lemma polynomial_exponentValue : PolynomialTime exponentValueRealizer := + polynomial_composition polynomial_exponentInput RootedPenaltyEvaluateProgram.polynomial_evaluate + +def pointValue (z : Input) : TreeFraction.Fraction := + RootedPointPenaltyProgram.output (pointInput z) +def pointValueRealizer : Realizer pointValue := + composition (f := pointInput) (g := RootedPointPenaltyProgram.output) + pointInputRealizer RootedPointPenaltyProgram.outputRealizer +lemma polynomial_pointValue : PolynomialTime pointValueRealizer := + polynomial_composition polynomial_pointInput RootedPointPenaltyProgram.polynomial_output + +def populationValue (z : Input) : TreeFraction.Fraction := + BinPopulationProgram.output (populationInput z) +def populationValueRealizer : Realizer populationValue := + composition (f := populationInput) (g := BinPopulationProgram.output) + populationInputRealizer BinPopulationProgram.outputRealizer +lemma polynomial_populationValue : PolynomialTime populationValueRealizer := + polynomial_composition polynomial_populationInput BinPopulationProgram.polynomial_output + +attribute [local irreducible] exponentValue pointValue populationValue + +def frame (z : Input) : CorrectionValueProgram.Frame := + ((exponentValue z,phase z),pointValue z) +def frameRealizer : Realizer frame := + pair (pair exponentValueRealizer phaseRealizer) pointValueRealizer +lemma polynomial_frame : PolynomialTime frameRealizer := + polynomial_pair (polynomial_pair polynomial_exponentValue polynomial_phase) polynomial_pointValue + +attribute [local irreducible] frame + +def prepare (z : Input) : CorrectionValueProgram.Input := ((frame z,populationValue z),z.2) +def prepareRealizer : Realizer prepare := pair (pair frameRealizer populationValueRealizer) second +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair polynomial_frame polynomial_populationValue) polynomial_second + +def output (z : Input) : TreeFraction.Fraction := CorrectionValueProgram.output (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := CorrectionValueProgram.output) + prepareRealizer CorrectionValueProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare CorrectionValueProgram.polynomial_output + +end ContingencyTables.RootedCorrectionProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..67026cd3755fa0d026388b9dd04ff76099cfd547 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleLaw.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSampleProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSamples + +namespace OAI + +/-! # Exact law of the executed correction sample + +The two coordinate enumerations need not agree on a fixed bit string. +Their independent finite-word laws agree, which preserves every real +observable of the computed rational sample. +-/ + +namespace ContingencyTables.RootedCorrectionSampleLaw + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity ResidualMixture FirstSuccess FairBits +open CommonBasesFPRAS FiniteLawMoments +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +local instance freeCellDecidableEq (A : Instance (Fin m) (Fin n)) : + DecidableEq (FreeCell A.small A.T) := by + letI : DecidableEq (Fin m) := Classical.decEq _ + letI : DecidableEq (Fin n) := Classical.decEq _ + infer_instance + +private lemma bind_equiv {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (p : RationalLaw X) (e : X ≃ Y) (f : Y → RationalLaw Z) : + bindLaw (equivLaw e p) f=bindLaw p (fun x => f (e x)) := by + apply RationalLaw.ext + funext z + change (∑ y,p.mass (e.symm y)*(f y).mass z)=∑ x,p.mass x*(f (e x)).mass z + symm + exact Fintype.sum_equiv e _ _ (fun x => by simp only [Equiv.symm_apply_apply]) + +abbrev Words (A : Instance (Fin m) (Fin n)) (C N h : ℕ) := + (Fin (N*oracleStepBits A C) → Bool) × (Fin (RootedBinDrawLaw.wordBits A h) → Bool) + +def integerDraw (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N h : ℕ) + (bits : Words A C N h) : FreeIndex A.small A.T A.b := + RootedBinDrawLaw.flatDraw A K (by omega) hW + (RootedOracleWalkProgram.flatGridWalk A C a z v N bits.1) h bits.2 + +lemma integerDraw_law (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hKB : (K:ℝ) ≤ binWidth A C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N h : ℕ) : + mapLaw (uniformLaw (α := Words A C N h)) (integerDraw A C a K hK hW z v N h)= + RootedOracleDensity.sampledIntegerLaw A (RootedCompletion.rowColumn A.T) C a z K hK hW + (RootedCatalogGrid.gridEquiv A K v) N h := by + unfold integerDraw + rw [←uniform_product] + rw [mapLaw_product_finish + (uniformLaw (α := Fin (N*oracleStepBits A C) → Bool)) + (uniformLaw (α := Fin (RootedBinDrawLaw.wordBits A h) → Bool)) + (RootedOracleWalkProgram.flatGridWalk A C a z v N) + (fun w bits => RootedBinDrawLaw.flatDraw A K (by omega) hW w h bits)] + rw [RootedOracleWalkProgram.flatGridWalk_law] + have hb (w : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) := + RootedBinDrawLaw.flatDraw_law A K (by omega) hW w h + simp_rw [hb] + rw [RootedCatalogGrid.wordWalkLaw_eq A C a hC haH z hz hK hKB] + rw [bind_equiv] + unfold RootedOracleDensity.sampledIntegerLaw + rw [RootedOracleDensity.oracleBitWalkLaw_eq A (RootedCompletion.rowColumn A.T) + C a hC haH z hz hK hKB] + congr 1 + funext w + simp only [Equiv.apply_symm_apply] + +def sample (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (z : View A → ℕ) + (sigma : ℚ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N h : ℕ) + (bits : Words A C N h) : ℚ := + RootedOracleDensity.computedCorrection A (RootedCompletion.rowColumn A.T) C a z K + (by omega) sigma (integerDraw A C a K hK hW z v N h bits) + +/-- Equality for arbitrary observables is exact equality in distribution +of the executed rational sample and the analysed correction sample. -/ +theorem sample_average (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hKB : (K:ℝ) ≤ binWidth A C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) (sigma : ℚ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N h : ℕ) (g : ℚ → ℝ) : + uniformAverage (fun bits : Words A C N h => g (sample A C a K hK hW z sigma v N h bits))= + uniformAverage (fun bits : Fin (oracleIntegerBits A C N h) → Bool => + g (RootedOracleDensity.correctionSample A (RootedCompletion.rowColumn A.T) C a z K + hK hW sigma (RootedCatalogGrid.gridEquiv A K v) N h bits)) := by + let obs := fun f : FreeIndex A.small A.T A.b => + g (RootedOracleDensity.computedCorrection A (RootedCompletion.rowColumn A.T) C a z K + (by omega) sigma f) + have hleft := word_expectation (integerDraw A C a K hK hW z v N h) obs + have hright := word_expectation + (RootedOracleDensity.oracleIntegerDraw A (RootedCompletion.rowColumn A.T) C a z K hK hW + (RootedCatalogGrid.gridEquiv A K v) N h) obs + rw [integerDraw_law A C a K hC haH hK hW hKB z hz v N h] at hleft + rw [RootedOracleDensity.oracleIntegerDraw_law] at hright + exact hleft.trans hright.symm + +theorem program_sample (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (z : View A → ℕ) + (sigma : ℚ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (N h : ℕ) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth : depth.length=PowerOfTwoApproximation.depth sigma) (bits : Words A C N h) : + MatchingFPRAS.TreeFraction.val (RootedCorrectionSampleProgram.output + (RootedCorrectionSampleProgram.data A C a K z v h degree depth + (List.ofFn bits.1) (List.ofFn bits.2)))= + sample A C a K hK hW z sigma v N h bits := + RootedCorrectionSampleProgram.output_data A C a K hC haH (by omega) hW hB z v h + degree depth sigma hdegree hdepth N bits.1 bits.2 + +end +end ContingencyTables.RootedCorrectionSampleLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8014eb4cb726cd69430cc358d075d2f3c222e75b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSampleProgram.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSemantics +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBinDrawLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFlatProgram + +namespace OAI + +/-! # Executing one selected-root correction sample + +Separate finite words drive the grid walk and the integer draw. The +computed final bin and sampled integer are then passed to the exact +population and rational-power correction program. +-/ + +namespace ContingencyTables.RootedCorrectionSampleProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open scoped Classical + +abbrev State := RootedOracleWalkProgram.State +abbrev Input := (State × ℕ) × ((List Bool × List Bool) × (List Bool × List Bool)) + +def walked (z : Input) : State := + RootedOracleWalkProgram.flatWalk (z.1.1,z.2.2.1) +def walkedRealizer : Realizer walked := + composition (f := fun z : Input => (z.1.1,z.2.2.1)) + (g := RootedOracleWalkProgram.flatWalk) + (pair (composition first first) (composition (composition second second) first)) + RootedOracleWalkProgram.flatWalkRealizer +lemma polynomial_walked : PolynomialTime walkedRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first)) RootedOracleWalkProgram.polynomial_flatWalk + +attribute [local irreducible] walked + +def binFrame (z : Input) : RootedBinFramesProgram.Input := + (((walked z).1.1,(z.1.2,(walked z).1.2.1.1.1)), + ((walked z).1.2.2.1,(walked z).2)) +def binFrameRealizer : Realizer binFrame := by + let k : Realizer (fun z : Input => (walked z).1.1) := + composition (composition walkedRealizer first) first + let d : Realizer (fun z : Input => (walked z).1.2.1.1.1) := + composition (composition (composition (composition (composition walkedRealizer first) + second) first) first) first + let catalog : Realizer (fun z : Input => (walked z).1.2.2.1) := + composition (composition (composition (composition walkedRealizer first) second) second) first + exact pair (pair k (pair (composition first second) d)) + (pair catalog (composition walkedRealizer second)) +lemma polynomial_binFrame : PolynomialTime binFrameRealizer := by + unfold binFrameRealizer + exact polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_walked polynomial_first) + polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_walked polynomial_first) + polynomial_second) polynomial_first) polynomial_first) polynomial_first))) + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_walked polynomial_first) polynomial_second) + polynomial_second) polynomial_first) + (polynomial_composition polynomial_walked polynomial_second)) + +attribute [local irreducible] binFrame + +def sampled (z : Input) : List ℕ := RootedBinFramesProgram.draw (binFrame z,z.2.2.2) +def sampledRealizer : Realizer sampled := + composition (f := fun z : Input => (binFrame z,z.2.2.2)) + (g := RootedBinFramesProgram.draw) + (pair binFrameRealizer (composition (composition second second) second)) + RootedBinFramesProgram.drawRealizer +lemma polynomial_sampled : PolynomialTime sampledRealizer := + polynomial_composition (polynomial_pair polynomial_binFrame + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_second)) RootedBinFramesProgram.polynomial_draw + +attribute [local irreducible] sampled + +def prepare (z : Input) : RootedCorrectionProgram.Input := + ((walked z,sampled z),z.2.1) +def prepareRealizer : Realizer prepare := + pair (pair walkedRealizer sampledRealizer) (composition second first) +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair polynomial_walked polynomial_sampled) + (polynomial_composition polynomial_second polynomial_first) + +attribute [local irreducible] prepare + +def output (z : Input) : TreeFraction.Fraction := RootedCorrectionProgram.output (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := RootedCorrectionProgram.output) + prepareRealizer RootedCorrectionProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare RootedCorrectionProgram.polynomial_output + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity FairBits +open scoped BigOperators + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (h : ℕ) + (degree depth walkBits binBits : List Bool) : Input := + ((RootedOracleWalkProgram.data A C a K z v,h),((degree,depth),(walkBits,binBits))) + +lemma walked_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (degree depth : List Bool) (N : ℕ) + (walkBits : Fin (N*oracleStepBits A C) → Bool) (binBits : List Bool) : + walked (data A C a K z v h degree depth (List.ofFn walkBits) binBits)= + RootedOracleWalkProgram.data A C a K z + (RootedOracleWalkProgram.flatGridWalk A C a z v N walkBits) := by + unfold walked data + exact RootedOracleWalkProgram.flatWalk_data A C a K hC z v N walkBits + +lemma binFrame_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (degree depth : List Bool) (N : ℕ) + (walkBits : Fin (N*oracleStepBits A C) → Bool) (binBits : List Bool) : + binFrame (data A C a K z v h degree depth (List.ofFn walkBits) binBits)= + RootedBinFramesProgram.data A h + (RootedOracleWalkProgram.flatGridWalk A C a z v N walkBits) := by + unfold binFrame + rw [walked_data A C a K hC] + rfl + +lemma sampled_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (degree depth : List Bool) (N : ℕ) + (walkBits : Fin (N*oracleStepBits A C) → Bool) + (binBits : Fin (RootedBinDrawLaw.wordBits A h) → Bool) : + sampled (data A C a K z v h degree depth (List.ofFn walkBits) (List.ofFn binBits))= + List.ofFn (fun i => (RootedBinDrawLaw.flatDraw A K hK hW + (RootedOracleWalkProgram.flatGridWalk A C a z v N walkBits) h binBits + (RootedForestCatalog.freeEquiv A i)).val) := by + unfold sampled + rw [binFrame_data A C a K hC] + exact RootedBinDrawLaw.program_flatDraw A K hK hW _ h binBits + +lemma bin_flatDraw (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (bits : Fin (RootedBinDrawLaw.wordBits A h) → Bool) : + integerBin A K hK (RootedBinDrawLaw.flatDraw A K hK hW v h bits)= + RootedCatalogGrid.gridEquiv A K v := by + have hm := binOffsetValue_mem A K hK (RootedCatalogGrid.gridEquiv A K v) + (fun i => scaledBitInteger (binSize A K (RootedCatalogGrid.gridEquiv A K v) i) + (offsetBitLength (binSize A K (RootedCatalogGrid.gridEquiv A K v) i) h A.d) + (binSize_positive A K hK hW _ i) + (FirstSuccess.prefixWord (binBits_le A K hK _ h i) + (RootedBinDrawLaw.reindexWords A h (RootedBinDrawLaw.wordEquiv A h bits) i))) + exact (Finset.mem_filter.mp hm).2 + +theorem output_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (h : ℕ) (degree depth : List Bool) (sigma : ℚ) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth : depth.length=PowerOfTwoApproximation.depth sigma) (N : ℕ) + (walkBits : Fin (N*oracleStepBits A C) → Bool) + (binBits : Fin (RootedBinDrawLaw.wordBits A h) → Bool) : + TreeFraction.val (output (data A C a K z v h degree depth + (List.ofFn walkBits) (List.ofFn binBits)))= + RootedOracleDensity.computedCorrection A (RootedCompletion.rowColumn A.T) C a z K hK sigma + (RootedBinDrawLaw.flatDraw A K hK hW + (RootedOracleWalkProgram.flatGridWalk A C a z v N walkBits) h binBits) := by + unfold output prepare + rw [walked_data A C a K hC,sampled_data A C a K hC hK hW] + exact RootedCorrectionProgram.output_data A C a K hC haH hK hB z _ _ degree depth sigma + hdegree hdepth (bin_flatDraw A K hK hW _ h binBits) + +end +end ContingencyTables.RootedCorrectionSampleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSamples.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSamples.lean new file mode 100644 index 0000000000000000000000000000000000000000..80be0979f960a1c076e693609e9f75fb6421ea2a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSamples.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionArithmetic +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawRelativeError +import OAI.Combinatorics.ContingencyTables.Transport.FiniteBiasedAverages + +namespace OAI + +/-! # Confidence for the actual rational correction samples -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteLawMoments FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def correctionMean (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : ℝ := + expectation (stationaryIntegerLaw A R C a z K hK hW) (correction A R C a z K (by omega)) + +lemma correctionMean_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : + correctionMean A R C a z K hK hW= + ∑ f : FreeIndex A.small A.T A.b, + correctedMass A R C a z K (by omega) f*correction A R C a z K (by omega) f := by + unfold correctionMean expectation + simp_rw [stationaryIntegerLaw_cast] + +lemma correctionMean_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) : + 1/8 ≤ correctionMean A R C a z K hK hW ∧ correctionMean A R C a z K hK hW ≤ 4 := by + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + exact expectation_bounds _ _ _ _ (correction_bounds A R C a (by exact_mod_cast hC) + (Nat.cast_nonneg _) haHR z K (by omega) hW hB) + +def correctionSample (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (sigma : ℚ) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) + (bits : Fin (oracleIntegerBits A C n h) → Bool) : ℚ := + computedCorrection A R C a z K (by omega) sigma (oracleIntegerDraw A R C a z K hK hW v n h bits) + +lemma correctionSample_mean (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (sigma : ℚ) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : + uniformAverage (fun bits => (correctionSample A R C a z K hK hW sigma v n h bits:ℝ))= + expectation (sampledIntegerLaw A R C a z K hK hW v n h) + (fun f => (computedCorrection A R C a z K (by omega) sigma f:ℝ)) := by + unfold correctionSample + rw [word_expectation (oracleIntegerDraw A R C a z K hK hW v n h) + (fun f => (computedCorrection A R C a z K (by omega) sigma f:ℝ)),oracleIntegerDraw_law] + +/-- Both finite sampling error and deterministic rational power error +are bounded relative to the literal correction mean. -/ +theorem correctionSample_mean_bias (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + |uniformAverage (fun bits => + (correctionSample A R C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ))- + correctionMean A R C a z K hK hW| ≤ + 16*(theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)))+ + (sigma:ℝ)*correctionMean A R C a z K hK hW := by + let g := fun f => (computedCorrection A R C a z K (by omega) sigma f:ℝ) + let p := sampledIntegerLaw A R C a z K hK hW v (oracleTime A C K Q theta) h + let q := stationaryIntegerLaw A R C a z K hK hW + have hsample : |expectation p g-expectation q g| ≤ + 16*(theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d))) := by + have he := expectation_difference p q g 8 (fun f => by + have hh := computedCorrection_bounds A R C a hC haH z K (by omega) hW hB sigma hsigma hsigmaHalf f + rw [abs_of_nonneg (by dsimp only [g]; linarith [hh.1])] + exact hh.2) + have hv := sampledIntegerLaw_variation A R C a theta hC haH htheta z hz K Q h hK hQ hW + hB.le hPL hCheeger v + exact he.trans (by nlinarith) + have hround : |expectation q g-correctionMean A R C a z K hK hW| ≤ + (sigma:ℝ)*correctionMean A R C a z K hK hW := + expectation_relative_error q (correction A R C a z K (by omega)) g sigma + (computedCorrection_error A R C a hC haH z K (by omega) hB sigma hsigma) + rw [correctionSample_mean] + calc + _ ≤ |expectation p g-expectation q g|+|expectation q g-correctionMean A R C a z K hK hW| := by + simpa only [sub_add_sub_cancel] using abs_add_le + (expectation p g-expectation q g) (expectation q g-correctionMean A R C a z K hK hW) + _ ≤ _ := add_le_add hsample hround + +/-- Independent finite words give confidence for the computed correction; +the displayed arithmetic tolerances are discharged by the outer schedule. -/ +theorem correctionSamples_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta delta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) (hdelta : 0 < delta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h N : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) (hN : 0 < N) + (hB : (K:ℝ)=binWidth A C) (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (hsigmaDelta : (sigma:ℝ) ≤ delta/4) + (hnoise : theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)) ≤ delta/1024) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin N → (Fin (oracleIntegerBits A C (oracleTime A C K Q theta) h) → Bool) => + if delta*correctionMean A R C a z K hK hW < + |sampleAverage (fun bits => + (correctionSample A R C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ)) N draws- + correctionMean A R C a z K hK hW| then (1:ℝ) else 0) ≤ 16384/(N*delta^2) := by + let g := fun bits => + (correctionSample A R C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ) + have hg bits : 0 ≤ g bits ∧ g bits ≤ 8 := by + have hh := computedCorrection_bounds A R C a hC haH z K (by omega) hW hB sigma hsigma hsigmaHalf + (oracleIntegerDraw A R C a z K hK hW v (oracleTime A C K Q theta) h bits) + exact ⟨by dsimp only [g,correctionSample]; linarith [hh.1],hh.2⟩ + have hb := correctionMean_bounds A R C a hC haH z K hK hW hB + have hmu : 0 < correctionMean A R C a z K hK hW := by linarith [hb.1] + have herr := correctionSample_mean_bias A R C a theta hC haH htheta z hz K Q h hK hQ hW hB sigma + hsigma hsigmaHalf hPL hCheeger v + have hround := mul_le_mul_of_nonneg_right hsigmaDelta hmu.le + have hbias : |uniformAverage g-correctionMean A R C a z K hK hW| ≤ + delta*correctionMean A R C a z K hK hW/2 := by + have hnoise' := mul_le_mul_of_nonneg_left hnoise (by norm_num : (0:ℝ) ≤ 16) + have hlo := mul_le_mul_of_nonneg_left hb.1 hdelta.le + dsimp only [g] + nlinarith + have hh := biased_target_failure g 8 _ delta hg hmu hdelta hbias N hN + apply hh.trans + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hs : (delta/8)^2 ≤ (delta*correctionMean A R C a z K hK hW)^2 := by + apply (sq_le_sq₀ (by positivity) (mul_nonneg hdelta.le hmu.le)).mpr + nlinarith [hb.1] + calc + 4*8^2/((N:ℝ)*(delta*correctionMean A R C a z K hK hW)^2) ≤ 256/(N*(delta/8)^2) := + div_le_div₀ (by norm_num) (by norm_num) (by positivity) (mul_le_mul_of_nonneg_left hs hNR.le) + _ = _ := by field_simp [hNR.ne',hdelta.ne']; ring + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a4dcdc8e80be330a0996532ed252fc3cf12fded --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCorrectionSemantics.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionProgram + +namespace OAI + +/-! # The executed correction equals the analysed rational correction -/ + +namespace ContingencyTables.RootedCorrectionProgram + +open MatchingFPRAS CompanionFactorialApplication ForestAssignmentSplit GridBoundary RootedCompletion +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : Input := + ((RootedOracleWalkProgram.data A C a K z v, + List.ofFn (fun i => (f (RootedForestCatalog.freeEquiv A i)).val)),(degree,depth)) + +lemma exponentInput_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + exponentInput (data A C a K z v f degree depth)= + RootedPenaltyEvaluateProgram.data A C a + (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j) + (RootedCatalogGrid.naturalValues A v) := by + rw [RootedCatalogGrid.evaluatorInput_grid] + rfl + +lemma exponent_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + RootedPenaltyEvaluateProgram.evaluate (exponentInput (data A C a K z v f degree depth))= + RootedOracleDensity.gridExponent A (rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K v) := + RootedCatalogGrid.evaluate_grid A C a K hC z v + +lemma pointInput_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + pointInput (data A C a K z v f degree depth)= + RootedForestPrepareProgram.data A C (rationalBinWidth A C) + (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j) + (fun t => (f t).val) := by + change (((C,RootedPenaltyEvaluateProgram.width ((A.d,A.W),(C,a))), + RootedDemandProgram.data A (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j)),_)=_ + rw [RootedPenaltyEvaluateProgram.width_data] + rfl + +lemma point_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + TreeFraction.val (RootedPointPenaltyProgram.output + (pointInput (data A C a K z v f degree depth)))= + RootedOracleDensity.rationalD A (rowColumn A.T) C z (rationalIntegerPoint A C f) := by + rw [pointInput_data] + exact RootedPointPenaltyProgram.output_integerPoint A C hC z f + +lemma populationInput_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + populationInput (data A C a K z v f degree depth)= + BinPopulationProgram.data A K (RootedCatalogGrid.gridEquiv A K v) := by + change (RootedBinFramesProgram.frames (RootedBinFramesProgram.data A 0 v)).map Prod.fst=_ + rw [RootedBinFramesProgram.frames_data,List.map_ofFn] + apply congrArg List.ofFn + funext i + simp only [Function.comp_apply,RootedCatalogGrid.naturalBin_grid, + RootedCatalogGrid.naturalValues,Equiv.symm_apply_apply] + +lemma population_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hK : 0 < K) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) + (hf : integerBin A K hK f=RootedCatalogGrid.gridEquiv A K v) : + TreeFraction.val (BinPopulationProgram.output + (populationInput (data A C a K z v f degree depth)))=rationalPopulation A K hK f := by + rw [populationInput_data,←hf] + exact BinPopulationProgram.output_integerBin A K hK f + +lemma phase_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) : + TreeFraction.val (phase (data A C a K z v f degree depth))=(a:ℚ)/rationalHeight A C := by + change (a:ℚ)/RootedPenaltyEvaluateProgram.height ((A.d,A.W),(C,a))=_ + rw [RootedPenaltyEvaluateProgram.height_data] + +theorem output_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 0 < K) + (hB : (K:ℝ)=binWidth A C) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (f : FreeIndex A.small A.T A.b) (degree depth : List Bool) (sigma : ℚ) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth : depth.length=PowerOfTwoApproximation.depth sigma) + (hf : integerBin A K hK f=RootedCatalogGrid.gridEquiv A K v) : + TreeFraction.val (output (data A C a K z v f degree depth))= + RootedOracleDensity.computedCorrection A (rowColumn A.T) C a z K hK sigma f := by + let input := data A C a K z v f degree depth + let frame : CorrectionValueProgram.Frame := + ((RootedPenaltyEvaluateProgram.evaluate (exponentInput input),phase input), + RootedPointPenaltyProgram.output (pointInput input)) + let population := BinPopulationProgram.output (populationInput input) + have hexponent : (frame.1.1:ℚ)-TreeFraction.val frame.1.2*TreeFraction.val frame.2= + RootedOracleDensity.correctionExponent A (rowColumn A.T) C a z K hK f := by + dsimp only [frame,input] + rw [exponent_data A C a K hC,phase_data,point_data A C a K hC,←hf] + rfl + have hb := RootedOracleDensity.correctionExponent_bounds A (rowColumn A.T) C a + hC haH z K hK hB f + have hlo : -2 ≤ (frame.1.1:ℚ)-TreeFraction.val frame.1.2*TreeFraction.val frame.2 := by + rw [hexponent]; exact hb.1 + have hhi : (frame.1.1:ℚ)-TreeFraction.val frame.1.2*TreeFraction.val frame.2 ≤ 2 := by + rw [hexponent]; exact hb.2 + have he := CorrectionValueProgram.output_approximate frame population degree depth sigma + hdegree hdepth hlo hhi + change TreeFraction.val (CorrectionValueProgram.output ((frame,population),(degree,depth)))=_ + rw [he,hexponent] + rw [show TreeFraction.val population=rationalPopulation A K hK f from + population_data A C a K hK z v f degree depth hf] + rfl + +end +end ContingencyTables.RootedCorrectionProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountIdentification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..411621d2948f99bc2dbee24ce46775a052d6ef7f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountIdentification.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLiteralCount +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLargeMarginal + +namespace OAI + +/-! # The selected-root physical marginal is its literal completion count -/ + +namespace ContingencyTables.RootedCountIdentification + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedPenalty RootedLiteralCount +open ForestCountIdentification ForestAssignmentSplit ForestLiteralCount +open PhysicalLargeProfiles LargePairEnumeration BalancedBox GraphCompletionCounts + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def h (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + (z : View A → ℕ) : ℝ := + ∑ f : FreeIndex A.small A.T A.b, + (2:ℝ)^(-alpha*RootedLiteralCount.actualPenalty A S + (smallX A.small z) (smallY A.small z) (freeTable A.small A.T A.b f) + (RootedPhysicalCompletion.solved A S (fun i j => (smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-smallY A.small z i j:ℕ):ℤ)) + (fun i j => (freeTable A.small A.T A.b f i j:ℤ)))) + +theorem h_positive (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + (z : View A → ℕ) : 0 0 + unfold h + apply lt_of_lt_of_le (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _) + exact Finset.single_le_sum (fun a _ => + (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _).le) (Finset.mem_univ f) + +theorem h_zero (A : Instance I J) (S : Selection A.T) (z : View A → ℕ) : + h A S 0 z=∏ a : FreeCell A.small A.T,((A.b a.val.1 a.val.2+1:ℕ):ℝ) := by + simp [h,Fintype.card_pi,Nat.cast_prod] + +private theorem physical_sum_split (A : Instance I J) (z : View A → ℕ) + (F : (((I×J)×Bool) → ℕ) → ℝ) : + (∑ a : PhysicalAssignments (fun a : I×J => A.small a.1 a.2) + (fun a => width A.T A.d A.b a.1 a.2), + F (physicalProfile (fun a : I×J => A.small a.1 a.2) + (fun a => width A.T A.d A.b a.1 a.2) z a))= + ∑ f : FreeIndex A.small A.T A.b,∑ t : TreeIndex A.T A.d A.b, + F (profile A.small A.T A.d A.b (smallX A.small z) (smallY A.small z) + (freeTable A.small A.T A.b f) t) := by + have heq := Fintype.sum_equiv (assignmentSplit A.small A.T A.hTG A.d A.b) + (fun a => F (physicalProfile (fun a : I×J => A.small a.1 a.2) + (fun a => width A.T A.d A.b a.1 a.2) z a)) + (fun a => F (profile A.small A.T A.d A.b (smallX A.small z) (smallY A.small z) + (freeTable A.small A.T A.b a.2) a.1)) (by + intro a + apply congrArg F + have he := split_profile A.small A.T A.hTG A.d A.b z + ((assignmentSplit A.small A.T A.hTG A.d A.b) a) + simpa only [Equiv.symm_apply_apply] using he) + rw [heq,Fintype.sum_prod_type,Finset.sum_comm] + +theorem h_eq_largeMarginal (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) + (z : View A → ℕ) (hz : InBox (bounds A) z) : + h A S alpha z=RootedLargeMarginal.largeMarginal A S alpha e z := by + unfold RootedLargeMarginal.largeMarginal RootedPenalty.widths + rw [sum_joined_eq_physical (fun a : I×J => A.small a.1 a.2) + (fun a : I×J => width A.T A.d A.b a.1 a.2) e z (physicalWeight A S alpha)] + trans (∑ f : FreeIndex A.small A.T A.b,∑ t : TreeIndex A.T A.d A.b, + physicalWeight A S alpha (profile A.small A.T A.d A.b + (smallX A.small z) (smallY A.small z) (freeTable A.small A.T A.b f) t)) + · unfold h + apply Finset.sum_congr rfl + intro f _ + apply (RootedLiteralCount.literal_tree_sum A S _ _ _ alpha ?_ ?_ ?_).symm + · intro i j hs + simpa only [smallX,hs,dite_eq_left,bounds] using hz (⟨(i,j),hs⟩,false) + · intro i j hs + simpa only [smallY,hs,dite_eq_left,bounds] using hz (⟨(i,j),hs⟩,true) + · exact freeTable_bound A.small A.T A.b f + · convert (physical_sum_split A z (physicalWeight A S alpha)).symm using 1 + all_goals + congr 1 + ext + simp + +theorem h_removal (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) (ha : 0≤ alpha) (R : ℕ) : + RemovalSlice (h A S alpha) (bounds A) R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + have hs := RootedLargeMarginal.largeMarginal_removal A S alpha ha e R + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (bounds A) z hz (h_eq_largeMarginal A S alpha e)] + convert hs z hz ht using 1 + +theorem h_reflected (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) (ha : 0≤ alpha) (R : ℕ) : + RemovalSlice (fun z => h A S alpha (IntegerReflection.reflect (bounds A) z)) (bounds A) R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + have hs := RootedLargeMarginal.largeMarginal_reflected A S alpha ha e R + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (bounds A) z hz (by + intro x _ + apply h_eq_largeMarginal A S alpha e + intro u + exact Nat.sub_le _ _)] + convert hs z hz ht using 1 + +end ContingencyTables.RootedCountIdentification + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingAmplification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingAmplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..17f2e31a395b9307ecd4730e6a0ed7047c2517ef --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingAmplification.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingSchedule +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMedianConfidence + +namespace OAI + +/-! # Logarithmic confidence for the actual adaptive counting estimator -/ + +namespace ContingencyTables.RootedCountingAmplification + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity RootedPhaseHistory RootedCountingSchedule +open CompanionTerminalMass (Endpoints tableCount tableCount_ge_one) +open CompanionTerminalApplication (finalPhase) +open CountingPhaseSchedule GridBoundary FiniteMedianConfidence +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def bitCount (A : Instance I J) (s : Settings A) (delta : ℚ) : ℕ := + repetitionCount delta * RootedCountingWords.bitCount A s + +def estimate (A : Instance I J) (R : RootedCompletion.Selection A.T) + (s : Settings A) (delta : ℚ) (bits : Fin (bitCount A s delta) → Bool) : ℚ := + rationalMedian (List.ofFn (fun i : Fin (repetitionCount delta) => + RootedCountingWords.flatEstimate A R s + (gridWordEquiv (repetitionCount delta) (RootedCountingWords.bitCount A s) bits i))) + +/-- The confidence parameter changes only the number of independent +complete runs, never the internal per-oracle failure allowance. -/ +theorem success (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (v : Grid (I := Fin (dimension A)) K) (E : Endpoints A) + (hW' : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) + (hfinal : H=finalPhase A L ((epsilon/2:ℚ):ℝ)) + (hC : 0 < C) (hB : (K:ℝ)=binWidth A C) (hH : H ≤ rationalHeight A C) + (hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (hp : 0 < Fintype.card (Labels A)) : + 1-(delta:ℝ) ≤ uniformAverage (fun bits : + Fin (bitCount A (settings A C K H L hK hW (epsilon/2) v) delta) → Bool => + if (1-(epsilon:ℝ))*tableCount A ≤ + (estimate A R (settings A C K H L hK hW (epsilon/2) v) delta bits:ℝ) ∧ + (estimate A R (settings A C K H L hK hW (epsilon/2) v) delta bits:ℝ) ≤ + (1+(epsilon:ℝ))*tableCount A then (1:ℝ) else 0) := by + let s := settings A C K H L hK hW (epsilon/2) v + let f := RootedCountingWords.flatEstimate A R s + have heh0 : (0:ℚ) < epsilon/2 := by positivity + have heh1 : epsilon/2 < 1 := by linarith + have hbase := constant_success A R C K H L hK hW (epsilon/2) heh0 heh1 v E + hW' hL hfinal hC hB hH hbox hPL hCheeger hp + have hbase' : 1-(1/256:ℝ) ≤ uniformAverage + (fun bits : Fin (RootedCountingWords.bitCount A s) → Bool => + if (1-((epsilon/2:ℚ):ℝ))*tableCount A ≤ (f bits:ℝ) ∧ + (f bits:ℝ) ≤ (1+((epsilon/2:ℚ):ℝ))*tableCount A then (1:ℝ) else 0) := by + refine (show 1-(1/256:ℝ) ≤ 255/256 by norm_num).trans (hbase.trans_eq ?_) + exact CompanionPhaseWords.average_ext_instances _ _ _ _ (fun bits => by split_ifs <;> rfl) + have hfailure := CompanionPhaseWords.failure_of_success + (fun bits : Fin (RootedCountingWords.bitCount A s) → Bool => + (1-((epsilon/2:ℚ):ℝ))*tableCount A ≤ (f bits:ℝ) ∧ + (f bits:ℝ) ≤ (1+((epsilon/2:ℚ):ℝ))*tableCount A) + (1/256) (hbase'.trans_eq + (CompanionPhaseWords.average_ext_instances _ _ _ _ (fun bits => by split_ifs <;> rfl))) + have hbad : uniformAverage (fun bits : Fin (RootedCountingWords.bitCount A s) → Bool => + if (f bits:ℝ) < (1-(epsilon:ℝ)/2)*tableCount A ∨ + (1+(epsilon:ℝ)/2)*tableCount A < (f bits:ℝ) then (1:ℝ) else 0) ≤ 5/16 := by + have hh : (1/256:ℝ) ≤ 5/16 := by norm_num + apply le_trans ?_ hh + simpa only [not_and_or,not_le,Rat.cast_div,Rat.cast_ofNat] using hfailure + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have hZ : (0:ℝ) < tableCount A := by linarith [tableCount_ge_one A] + have hm := median_confidence_real f + ((1-(epsilon:ℝ))*tableCount A) ((1-(epsilon:ℝ)/2)*tableCount A) + ((1+(epsilon:ℝ)/2)*tableCount A) ((1+(epsilon:ℝ))*tableCount A) + (by nlinarith) (by nlinarith) delta hd hbad + let test := fun words : Fin (repetitionCount delta) → + (Fin (RootedCountingWords.bitCount A s) → Bool) => + if (1-(epsilon:ℝ))*tableCount A ≤ + (rationalMedian (List.ofFn (fun i => f (words i))):ℝ) ∧ + (rationalMedian (List.ofFn (fun i => f (words i))):ℝ) ≤ + (1+(epsilon:ℝ))*tableCount A then (1:ℝ) else 0 + have heq := uniformAverage_equiv + (gridWordEquiv (repetitionCount delta) (RootedCountingWords.bitCount A s)) test + have htransport : uniformAverage test = uniformAverage + (fun bits : Fin (bitCount A s delta) → Bool => + if (1-(epsilon:ℝ))*tableCount A ≤ (estimate A R s delta bits:ℝ) ∧ + (estimate A R s delta bits:ℝ) ≤ (1+(epsilon:ℝ))*tableCount A + then (1:ℝ) else 0) := by + refine heq.symm.trans (CompanionPhaseWords.average_ext_instances _ _ _ _ ?_) + intro bits + rfl + exact hm.trans_eq htransport + +lemma bitCount_eq (A : Instance I J) (s : Settings A) (delta : ℚ) : + bitCount A s delta=64*(delta.den.bits.length+1)*RootedCountingWords.bitCount A s := rfl + +end +end ContingencyTables.RootedCountingAmplification + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..efc4631075add88dbb13cb2cca40aa4f3864cbc4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingSchedule.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingWords +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseSchedule + +namespace OAI + +/-! # An explicit constant-confidence schedule for the actual counting words -/ + +namespace ContingencyTables.RootedCountingSchedule + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity RootedPhaseHistory RootedHistoryStep +open CompanionTargetMixing (restartTime) +open CompanionTerminalMass (Endpoints tableCount) +open CompanionTerminalApplication (finalPhase) +open CountingPhaseSchedule GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +/-- Only natural/rational arithmetic selects the phase precision and +all finite loops. The supplied grid point is the evaluator's fixed start. -/ +def settings (A : Instance I J) (C K H L : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (epsilon : ℚ) + (v : Grid (I := Fin (dimension A)) K) : Settings A := + let p := Fintype.card (Labels A) + let tau := restartTime A H L + let eta := tolerance H epsilon + let N := observations p A.W H eta + let n := returnCap p H tau + let k := precision H tau N n eta + ⟨C,K,H,L,k,n,N,initialPrecision H,hK,hW,noise H tau N n eta,v⟩ + +lemma settings_positive (A : Instance I J) (C K H L : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (epsilon : ℚ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) : + 0 < (settings A C K H L hK hW epsilon v).xi ∧ + (settings A C K H L hK hW epsilon v).xi ≤ 1/4 ∧ + 0 < (settings A C K H L hK hW epsilon v).n := by + dsimp only [settings] + refine ⟨noise_pos _ _ _ _ _,?_,returnCap_pos _ _ _⟩ + exact (noise_le_tolerance _ _ _ _ _ (tolerance_pos H epsilon he0)).trans + (tolerance_le_quarter H epsilon he0 he1) + +lemma observable_cast (p W : ℕ) : + (observable p W:ℝ)=ObservableBounds.observableConstant (p:ℝ) ((W:ℝ)^2) := by + simp only [observable,ObservableBounds.observableConstant,Nat.cast_add,Nat.cast_mul, + Nat.cast_pow,Nat.cast_ofNat,Nat.cast_one] + ring + +lemma error_bound (A : Instance I J) (C K H L : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (epsilon : ℚ) (he : 0 < epsilon) + (v : Grid (I := Fin (dimension A)) K) : + error A (settings A C K H L hK hW epsilon v) (tolerance H epsilon:ℝ) H ≤ + 1/(256*((H:ℝ)+1)) := by + let p := Fintype.card (Labels A) + let tau := restartTime A H L + let eta := tolerance H epsilon + let N := observations p A.W H eta + let n := returnCap p H tau + let k := precision H tau N n eta + let xi := noise H tau N n eta + have he : 0 < eta := tolerance_pos H epsilon he + have hc : (observationCoefficient p A.W:ℝ)=32000*(p:ℝ)^8* + ObservableBounds.observableConstant p ((A.W:ℝ)^2) := by + simp only [observationCoefficient,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow, + observable_cast] + have hb := combine_error p H tau N n k (initialPrecision H) + (observationCoefficient p A.W) eta xi (1/(1024*((H:ℝ)+1))) + (by exact_mod_cast (noise_pos H tau N n eta).le) + (precision_error H tau N n eta) + (observations_error p A.W H eta he) + (initial_error H) + (cap_error p H tau) + (noise_error H tau N n eta) + have hfour : (4:ℝ)*(1/(1024*((H:ℝ)+1)))=1/(256*((H:ℝ)+1)) := by + field_simp + ring + rw [hfour] at hb + simpa only [error,settings,hc,p,tau,eta,N,n,k,xi] using hb + +lemma total_error_bound (A : Instance I J) (C K H L : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (epsilon : ℚ) (he : 0 < epsilon) + (v : Grid (I := Fin (dimension A)) K) : + (H:ℝ)*error A (settings A C K H L hK hW epsilon v) + (tolerance H epsilon:ℝ) H ≤ 1/256 := by + have hb := mul_le_mul_of_nonneg_left (error_bound A C K H L hK hW epsilon he v) + (Nat.cast_nonneg H : (0:ℝ) ≤ H) + refine hb.trans ?_ + rw [mul_one_div,div_le_iff₀ (by positivity : (0:ℝ) < 256*((H:ℝ)+1))] + linarith + +lemma logarithmic_bound (A : Instance I J) (C K H L : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (epsilon : ℚ) (he : 0 < epsilon) + (v : Grid (I := Fin (dimension A)) K) : + (H:ℝ)*(4*((settings A C K H L hK hW epsilon v).xi:ℝ)+ + 4*(tolerance H epsilon:ℝ)) ≤ (epsilon:ℝ)/50 := + logarithmic_error H (restartTime A H L) + (observations (Fintype.card (Labels A)) A.W H (tolerance H epsilon)) + (returnCap (Fintype.card (Labels A)) H (restartTime A H L)) epsilon he + +/-- Constant success for the actual finite Boolean estimator. The +binary confidence parameter is handled by independent medians afterward. -/ +theorem constant_success (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (epsilon : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) (E : Endpoints A) + (hW' : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) + (hfinal : H=finalPhase A L (epsilon:ℝ)) + (hC : 0 < C) (hB : (K:ℝ)=binWidth A C) (hH : H ≤ rationalHeight A C) + (hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (hp : 0 < Fintype.card (Labels A)) : + 255/256 ≤ uniformAverage (fun bits : + Fin (RootedCountingWords.bitCount A (settings A C K H L hK hW epsilon v)) → Bool => + if (1-(epsilon:ℝ))*tableCount A ≤ + (RootedCountingWords.flatEstimate A R (settings A C K H L hK hW epsilon v) bits:ℝ) ∧ + (RootedCountingWords.flatEstimate A R (settings A C K H L hK hW epsilon v) bits:ℝ) ≤ + (1+(epsilon:ℝ))*tableCount A then (1:ℝ) else 0) := by + let s := settings A C K H L hK hW epsilon v + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have heR1 : (epsilon:ℝ) < 1 := by exact_mod_cast he1 + have hs := settings_positive A C K H L hK hW epsilon he0 he1 v + have htR : (tolerance H epsilon:ℝ) ≤ 1/4 := by + have ht := tolerance_le_quarter H epsilon he0 he1 + have ht' : (tolerance H epsilon:ℝ) ≤ ((1/4:ℚ):ℝ) := Rat.cast_le.mpr ht + norm_num only [Rat.cast_div,Rat.cast_one,Rat.cast_ofNat] at ht' + exact ht' + have hprob := RootedCountingWords.accuracy A R s E epsilon heR heR1 hW' hL hfinal + hC hB hH hbox hs.1 hs.2.1 hPL hCheeger hp hs.2.2 + (tolerance H epsilon) (by exact_mod_cast tolerance_pos H epsilon he0) + htR + (logarithmic_bound A C K H L hK hW epsilon he0 v) + have hb := total_error_bound A C K H L hK hW epsilon he0 v + have hlaw := RootedCountingWords.flatEstimate_law A R s (fun estimate => + (1-(epsilon:ℝ))*tableCount A ≤ (estimate:ℝ) ∧ + (estimate:ℝ) ≤ (1+(epsilon:ℝ))*tableCount A) + apply ((show (255/256:ℝ) ≤ 1-(H:ℝ)*error A s (tolerance H epsilon:ℝ) H by + linarith).trans hprob).trans_eq + refine (CompanionPhaseWords.average_ext_instances _ _ _ _ ?_).trans + (hlaw.symm.trans (CompanionPhaseWords.average_ext_instances _ _ _ _ ?_)) + · intro words + split_ifs <;> rfl + · intro bits + split_ifs <;> rfl + +end +end ContingencyTables.RootedCountingSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e5ca4e5b2f2a080f09030dea730f5fb62bad001 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCountingWords.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedHistoryConfidence + +namespace OAI + +/-! # Actual adaptive finite-word counting output and its accuracy -/ + +namespace ContingencyTables.RootedCountingWords + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity RootedPhaseHistory RootedStoredHistory RootedHistoryStep +open RootedHistoryConfidence +open CompanionTerminalMass (Endpoints tableCount) +open CompanionTerminalApplication (finalPhase) +open GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def estimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (words : Fin s.H → Word A s) : ℚ := + (lookup A (decoded A R s (List.ofFn words)) s.H).estimate + +lemma estimate_accurate (A : Instance I J) (R : RootedCompletion.Selection A.T) + (s : Settings A) (E : Endpoints A) (epsilon : ℝ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (hW : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^s.L) + (hfinal : s.H=finalPhase A s.L epsilon) (eta : ℝ) + (herr : (s.H:ℝ)*(4*(s.xi:ℝ)+4*eta) ≤ epsilon/50) + (words : Fin s.H → Word A s) (hg : GoodWords A R s eta (List.ofFn words)) : + (1-epsilon)*tableCount A ≤ (estimate A R s words:ℝ) ∧ + (estimate A R s words:ℝ) ≤ (1+epsilon)*tableCount A := by + have hlen : (decoded A R s (List.ofFn words)).length=s.H := by + rw [decoded_length,List.length_ofFn] + have h := count_accuracy A R E s.L epsilon he0 he1 hW hL s.xi eta + (by simpa only [hfinal] using herr) (decoded A R s (List.ofFn words)) + (hlen.trans hfinal) hg + simpa only [hlen,estimate] using h + +/-- The actual stored rational value has the stated error probability. +No equality to an ideal empirical-ratio estimator is assumed. -/ +theorem accuracy (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (E : Endpoints A) (epsilon : ℝ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (hW : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^s.L) + (hfinal : s.H=finalPhase A s.L epsilon) + (hC : 0 < s.C) (hB : (s.K:ℝ)=binWidth A s.C) + (hH : s.H ≤ rationalHeight A s.C) + (hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ (2:ℝ)^s.L) + (hx0 : 0 < s.xi) (hx1 : s.xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) s.K)) + (hp : 0 < Fintype.card (Labels A)) (hn : 0 < s.n) + (eta : ℝ) (he0' : 0 < eta) (he1' : eta ≤ 1/4) + (herr : (s.H:ℝ)*(4*(s.xi:ℝ)+4*eta) ≤ epsilon/50) : + 1-(s.H:ℝ)*error A s eta s.H ≤ + uniformAverage (fun words : Fin s.H → Word A s => + if (1-epsilon)*tableCount A ≤ (estimate A R s words:ℝ) ∧ + (estimate A R s words:ℝ) ≤ (1+epsilon)*tableCount A then (1:ℝ) else 0) := by + have hg := history_success A R s hC hB hH hbox hx0 hx1 hPL hCheeger hp hn eta he0' he1' + apply hg.trans + apply uniformAverage_mono + intro words + by_cases h : GoodWords A R s eta (List.ofFn words) + · have ha := estimate_accurate A R s E epsilon he0 he1 hW hL hfinal eta herr words h + simp [h,ha] + · simp only [h,ite_false] + split_ifs <;> norm_num + +def bitCount (A : Instance I J) (s : Settings A) : ℕ := s.H*totalWidth A s + +def flatEstimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (bits : Fin (bitCount A s) → Bool) : ℚ := + estimate A R s (gridWordEquiv s.H (totalWidth A s) bits) + +lemma flatEstimate_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (P : ℚ → Prop) : + uniformAverage (fun bits : Fin (bitCount A s) → Bool => + if P (flatEstimate A R s bits) then (1:ℝ) else 0)= + uniformAverage (fun words : Fin s.H → Word A s => + if P (estimate A R s words) then (1:ℝ) else 0) := by + have he := uniformAverage_equiv (gridWordEquiv s.H (totalWidth A s)) + (fun words : Fin s.H → Word A s => + if P (estimate A R s words) then (1:ℝ) else 0) + refine (CompanionPhaseWords.average_ext_instances _ _ _ _ ?_).trans + (he.trans (CompanionPhaseWords.average_ext_instances _ _ _ _ ?_)) + · intro bits + rfl + · intro words + rfl + +end +end ContingencyTables.RootedCountingWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCut.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2f2e71ebdb5b13647ce285dc03b5180c4de84d1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCut.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCompletion +import OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionCounts + +namespace OAI + +/-! # The explicit endpoint on the side away from a selected root + +One reachability test in the edge-deleted forest selects the endpoint. +No choice of a component representative or of a cut vertex is needed. +-/ + +namespace ContingencyTables.RootedCut + +open scoped BigOperators Classical +open SimpleGraph MaximumForest RootedCompletion GraphCompletionCounts ForestCut +open ForestCapacity + +variable {V : Type*} + +noncomputable def away (T : SimpleGraph V) (u v root : V) : V := + if (T.deleteEdges {s(u,v)}).Reachable u root then v else u + +noncomputable def cut (T : SimpleGraph V) (u v root a : V) : Bool := + side (T.deleteEdges {s(u,v)}) (away T u v root) a + +theorem away_properties (T : SimpleGraph V) (hT : T.IsAcyclic) {u v : V} + (ht : T.Adj u v) (root : V) (hr : T.Reachable root u) : + T.Reachable root (away T u v root) ∧ cut T u v root root=false ∧ + cut T u v root u≠cut T u v root v := by + let D := T.deleteEdges {s(u,v)} + have hsep : ¬D.Reachable u v := + isBridge_iff.mp (isAcyclic_iff_forall_adj_isBridge.mp hT ht) + by_cases hru : D.Reachable u root + · have ha : away T u v root=v := ite_eq_left hru + refine ⟨by simpa only [ha] using hr.trans ht.reachable,?_,?_⟩ + · have hn : ¬D.Reachable v root := fun h => hsep (hru.trans h.symm) + change side D (away T u v root) root=false + rw [ha] + simpa only [side,decide_eq_false_iff_not] using hn + · have hn : ¬D.Reachable v u := fun h => hsep h.symm + change side D (away T u v root) u≠side D (away T u v root) v + rw [ha] + simp [side,hn] + · have ha : away T u v root=u := ite_eq_right hru + refine ⟨by simpa only [ha] using hr,?_,?_⟩ + · change side D (away T u v root) root=false + rw [ha] + simpa only [side,decide_eq_false_iff_not] using hru + · change side D (away T u v root) u≠side D (away T u v root) v + rw [ha] + simp [side,hsep] + +theorem selected_nonroot (T : SimpleGraph V) (S : Selection T) (hT : T.IsAcyclic) + {u v a : V} (ht : T.Adj u v) (ha : cut T u v (S.root u) a=true) : a≠S.root a := by + intro he + have hp := away_properties T hT ht (S.root u) (S.reachable u).symm + have hreach : (T.deleteEdges {s(u,v)}).Reachable (away T u v (S.root u)) a := by + simpa only [cut,side,decide_eq_true_eq] using ha + have hcomp := hp.1.trans (hreach.mono (T.deleteEdges_le {s(u,v)})) + have hsame : S.root a=S.root u := + (S.constant hcomp).symm.trans (S.idempotent u) + have hae : a=S.root u := he.trans hsame + have hbad : cut T u v (S.root u) (S.root u)=true := by simpa only [hae] using ha + exact Bool.false_ne_true (hp.2.1.symm.trans hbad) + +variable {I J : Type*} + +noncomputable def treeCut (T : SimpleGraph (I⊕J)) (S : Selection T) + (t : TreeCell T) (v : I⊕J) : Bool := + cut T (.inl t.val.1) (.inr t.val.2) (S.root (.inl t.val.1)) v + +lemma treeCut_self (T : SimpleGraph (I⊕J)) (S : Selection T) (hT : T.IsAcyclic) + (t : TreeCell T) : treeCut T S t (.inl t.val.1)≠treeCut T S t (.inr t.val.2) := + (away_properties T hT t.property _ (S.reachable _).symm).2.2 + +lemma treeCut_nonroot (T : SimpleGraph (I⊕J)) (S : Selection T) (hT : T.IsAcyclic) + (t : TreeCell T) (v : I⊕J) (hv : treeCut T S t v=true) : v≠S.root v := + selected_nonroot T S hT t.property hv + +noncomputable def sign (T : SimpleGraph (I⊕J)) (S : Selection T) + (t : TreeCell T) (a : I×J) : ℝ := + indicator (treeCut T S t (.inl a.1))-indicator (treeCut T S t (.inr a.2)) + +lemma sign_abs_self (T : SimpleGraph (I⊕J)) (S : Selection T) (hT : T.IsAcyclic) + (t : TreeCell T) : |sign T S t t.val|=1 := + abs_indicator_sub (treeCut_self T S hT t) + +lemma sign_self_ne_zero (T : SimpleGraph (I⊕J)) (S : Selection T) (hT : T.IsAcyclic) + (t : TreeCell T) : sign T S t t.val≠0 := by + intro hz + have hh := sign_abs_self T S hT t + rw [hz,abs_zero] at hh + norm_num at hh + +lemma sign_abs_le_one (T : SimpleGraph (I⊕J)) (S : Selection T) + (t : TreeCell T) (a : I×J) : |sign T S t a|≤1 := by + unfold sign + cases treeCut T S t (.inl a.1) <;> cases treeCut T S t (.inr a.2) <;> + norm_num [indicator] + +lemma other_tree_sign_zero (T : SimpleGraph (I⊕J)) (S : Selection T) + (t : TreeCell T) (a : I×J) (ha : T.Adj (.inl a.1) (.inr a.2)) (hne : a≠t.val) : + sign T S t a=0 := by + have hh := side_eq_of_tree_edge T (s(Sum.inl t.val.1,Sum.inr t.val.2)) + (away T (.inl t.val.1) (.inr t.val.2) (S.root (.inl t.val.1))) ha + (by intro he; exact hne (cell_edge_injective he)) + exact sub_eq_zero.mpr (congrArg indicator hh) + +end ContingencyTables.RootedCut + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCutReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCutReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..364b7cd18596c146475d909f8bc979c9763b4a1b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedCutReindex.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphCutSemantics +import OAI.Combinatorics.ContingencyTables.Rooted.RootedIntegerEvaluation + +namespace OAI + +/-! # Exact canonical cut flags in the row-then-column vertex encoding -/ + +namespace ContingencyTables.RootedCutReindex + +open SimpleGraph RootedCompletion +open scoped Classical + +variable {V W : Type*} + +lemma delete_comap (G : SimpleGraph V) (e : W ≃ V) (u v : W) : + (G.comap e).deleteEdges {s(u,v)}=(G.deleteEdges {s(e u,e v)}).comap e := by + ext a b + simp only [SimpleGraph.deleteEdges_adj,SimpleGraph.comap_adj,Set.mem_singleton_iff, + Sym2.eq_iff,e.injective.eq_iff] + +lemma reachable_comap (G : SimpleGraph V) (e : W ≃ V) (u v : W) : + (G.comap e).Reachable u v ↔ G.Reachable (e u) (e v) := by + constructor + · intro h + exact h.map (SimpleGraph.Iso.comap e G).toHom + · intro h + have hh := h.map (SimpleGraph.Iso.comap e G).symm.toHom + change (G.comap e).Reachable (e.symm (e u)) (e.symm (e v)) at hh + simpa only [Equiv.symm_apply_apply] using hh + +lemma away_comap (G : SimpleGraph V) (e : W ≃ V) (u v root : W) : + e (RootedCut.away (G.comap e) u v root)=RootedCut.away G (e u) (e v) (e root) := by + unfold RootedCut.away + rw [delete_comap,reachable_comap] + split_ifs <;> rfl + +lemma cut_comap (G : SimpleGraph V) (e : W ≃ V) (u v root a : W) : + RootedCut.cut (G.comap e) u v root a=RootedCut.cut G (e u) (e v) (e root) (e a) := by + apply Bool.eq_iff_iff.mpr + simp only [RootedCut.cut,MaximumForest.side,decide_eq_true_eq] + rw [delete_comap,reachable_comap,away_comap] + +/-- The Boolean program computes exactly the selected-root tree cut +used in the affine coefficient, with the concrete row/column order. -/ +lemma canonicalCut_treeCut {m n : ℕ} (T : SimpleGraph (Fin m⊕Fin n)) + [DecidableRel T.Adj] (t : GraphCompletionCounts.TreeCell T) (a : Fin m⊕Fin n) : + FiniteGraphCutProgram.canonicalCutCode + ((FiniteGraphRootProgram.graphCode (T.comap finSumFinEquiv.symm), + ((finSumFinEquiv (m := m) (n := n) (.inl t.val.1)).val,(finSumFinEquiv (m := m) (n := n) (.inr t.val.2)).val)), + (finSumFinEquiv a).val)=RootedCut.treeCut T (rowColumn T) t a := by + rw [FiniteGraphCutProgram.canonicalCutCode_graph] + rw [cut_comap] + simp only [RootedCut.treeCut,rowColumn_root,Equiv.symm_apply_apply] + +end ContingencyTables.RootedCutReindex + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedDemandProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedDemandProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d6fd4eb62acaa862a965aec495fa3be989b9ebe --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedDemandProgram.lean @@ -0,0 +1,310 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestCatalog +import OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentCode + +namespace OAI + +/-! # Computing the root-demand input from the actual cell arrays + +The two natural entries at a vertex encode its signed small-cell +discrepancy. They are formed by rectangular scans and then passed to the +component/root program. +-/ + +namespace ContingencyTables.RootedDemandProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms SignedPairProgram +open FiniteGraphRootProgram +open scoped BigOperators Classical + +abbrev Input := RootedForestCatalog.Data×(MatrixCode×(MatrixCode×MatrixCode)) +abbrev TermInput := (Input×ℕ)×(ℕ×ℕ) + +def values (z : TermInput) : (ℕ×ℕ)×(ℕ×ℕ) := + RootedCellDataProgram.values (((z.1.1.1.2,z.1.1.2.1),z.1.1.2.2),z.2) +def valuesRealizer : Realizer values := + composition (f := fun z : TermInput => + (((z.1.1.1.2,z.1.1.2.1),z.1.1.2.2),z.2)) (g := RootedCellDataProgram.values) (pair + (pair (pair (composition (composition (composition first first) first) second) + (composition (composition (composition first first) second) first)) + (composition (composition (composition first first) second) second)) + second) RootedCellDataProgram.valuesRealizer +lemma polynomial_values : PolynomialTime valuesRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first)) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second)) + polynomial_second) RootedCellDataProgram.polynomial_values + +def retainedTest (z : TermInput) : Bool := + !RootedForestCatalog.largeTest (z.1.1.1,z.2) +def retainedTestRealizer : Realizer retainedTest := + composition (composition (pair (composition (composition first first) first) second) + RootedForestCatalog.largeTestRealizer) boolNot +lemma polynomial_retainedTest : PolynomialTime retainedTestRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) RootedForestCatalog.polynomial_largeTest) polynomial_boolNot + +def rowTest (z : TermInput) : Bool := decide (z.1.2=z.2.1) +def rowTestRealizer : Realizer rowTest := + composition (pair (composition first second) (composition second first)) natEqual +lemma polynomial_rowTest : PolynomialTime rowTestRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_first)) polynomial_natEqual + +def columnTest (z : TermInput) : Bool := + decide (z.1.2=z.1.1.1.1.2.1.length+z.2.2) +def columnTestRealizer : Realizer columnTest := + composition (pair (composition first second) + (composition (pair + (composition (composition (composition (composition (composition (composition first first) + first) first) second) first) listLength) (composition second second)) add)) natEqual +lemma polynomial_columnTest : PolynomialTime columnTestRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_first + polynomial_first) polynomial_first) polynomial_first) polynomial_second) polynomial_first) + polynomial_listLength) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add)) polynomial_natEqual + +def rowPair (z : TermInput) : Signed := ((values z).1.2,(values z).2.1) +def rowPairRealizer : Realizer rowPair := + pair + (composition (f := values) (g := fun v : (ℕ×ℕ)×(ℕ×ℕ) => v.1.2) + valuesRealizer (composition first second)) + (composition (f := values) (g := fun v : (ℕ×ℕ)×(ℕ×ℕ) => v.2.1) + valuesRealizer (composition second first)) +lemma polynomial_rowPair : PolynomialTime rowPairRealizer := + polynomial_pair + (polynomial_composition polynomial_values (polynomial_composition polynomial_first polynomial_second)) + (polynomial_composition polynomial_values (polynomial_composition polynomial_second polynomial_first)) + +def columnPair (z : TermInput) : Signed := ((values z).2.2,(values z).1.2) +def columnPairRealizer : Realizer columnPair := + pair + (composition (f := values) (g := fun v : (ℕ×ℕ)×(ℕ×ℕ) => v.2.2) + valuesRealizer (composition second second)) + (composition (f := values) (g := fun v : (ℕ×ℕ)×(ℕ×ℕ) => v.1.2) + valuesRealizer (composition first second)) +lemma polynomial_columnPair : PolynomialTime columnPairRealizer := + polynomial_pair + (polynomial_composition polynomial_values (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition polynomial_values (polynomial_composition polynomial_first polynomial_second)) + +def term (z : TermInput) : Signed := + if retainedTest z then + plus ((if rowTest z then rowPair z else (0,0)), + (if columnTest z then columnPair z else (0,0))) + else (0,0) +def termRealizer : Realizer term := + choose retainedTestRealizer + (composition (pair (choose rowTestRealizer rowPairRealizer (constant (0,0))) + (choose columnTestRealizer columnPairRealizer (constant (0,0)))) plusRealizer) + (constant (0,0)) +lemma polynomial_term : PolynomialTime termRealizer := + polynomial_choose polynomial_retainedTest + (polynomial_composition (polynomial_pair + (polynomial_choose polynomial_rowTest polynomial_rowPair (polynomial_constant (0,0))) + (polynomial_choose polynomial_columnTest polynomial_columnPair (polynomial_constant (0,0)))) + polynomial_plus) (polynomial_constant (0,0)) + +def demand (z : Input×ℕ) : Signed := + sum ((cellPairs z.1.1.1.2).map (fun a => term (z,a))) +def demandRealizer : Realizer demand := + composition (composition (pair identity + (composition (composition (composition (composition first first) first) second) + cellPairsRealizer)) (mapWith termRealizer)) sumRealizer +lemma polynomial_demand : PolynomialTime demandRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_cellPairs)) (polynomial_mapWith polynomial_term)) polynomial_sum + +def vertexCount (z : Input) : ℕ := z.1.1.2.1.length+z.1.1.2.2.length +def vertexCountRealizer : Realizer vertexCount := + composition (pair + (composition (composition (composition (composition first first) second) first) listLength) + (composition (composition (composition (composition first first) second) second) listLength)) add +lemma polynomial_vertexCount : PolynomialTime vertexCountRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + polynomial_listLength) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second) + polynomial_listLength)) polynomial_add + +def vertices (z : Input) : List ℕ := List.range (vertexCount z) +def verticesRealizer : Realizer vertices := composition vertexCountRealizer range +lemma polynomial_vertices : PolynomialTime verticesRealizer := by + apply polynomial_boundedRange polynomial_vertexCount (2*Polynomial.X) + intro z + have h₁ : z.1.1.2.1.length≤weight z := (list_length_le_weight _).trans + ((weight_fst _).trans ((weight_snd _).trans ((weight_fst _).trans (weight_fst _)))) + have h₂ : z.1.1.2.2.length≤weight z := (list_length_le_weight _).trans + ((weight_snd _).trans ((weight_snd _).trans ((weight_fst _).trans (weight_fst _)))) + simp only [vertexCount,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + omega + +def demandList (z : Input) : List Signed := (vertices z).map (fun v => demand (z,v)) +def demandListRealizer : Realizer demandList := + composition (pair identity verticesRealizer) (mapWith demandRealizer) +lemma polynomial_demandList : PolynomialTime demandListRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_vertices) + (polynomial_mapWith polynomial_demand) + +def rootCount (z : Input) : ℕ := RootedComponentCode.count (z.1.1.1.1,demandList z) +def rootCountRealizer : Realizer rootCount := + composition (pair (composition (composition (composition first first) first) first) + demandListRealizer) RootedComponentCode.countRealizer +theorem polynomial_rootCount : PolynomialTime rootCountRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_first + polynomial_first) polynomial_first) polynomial_first) polynomial_demandList) + RootedComponentCode.polynomial_count + +open CompanionFactorialApplication RootedCompletion + +noncomputable def data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) : Input := + (RootedForestCatalog.data A, + (matrixCode (fun i j => (A.X i j).toNat),(matrixCode x,matrixCode q))) + +lemma values_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : ℕ) (i : Fin m) (j : Fin n) : + values ((data A x q,v),(i.val,j.val))= + ((A.b i j,(A.X i j).toNat),(x i j,q i j)) := by + simp only [values,data,RootedForestCatalog.data,RootedCellDataProgram.values,matrixEntry_code] + +lemma retainedTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : ℕ) (i : Fin m) (j : Fin n) : + retainedTest ((data A x q,v),(i.val,j.val))=A.small i j := by + unfold retainedTest RootedForestCatalog.largeTest + simp only [data,RootedForestCatalog.data,matrixEntry_code] + cases hs : A.small i j with + | false => simp [(A.hlarge _ _ hs).1] + | true => simp [Nat.not_le.mpr (A.hsmall _ _ hs)] + +lemma rowTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) (i : Fin m) (j : Fin n) : + rowTest ((data A x q,(finSumFinEquiv v).val),(i.val,j.val))=decide (v=Sum.inl i) := by + cases v with + | inl a => + simp only [rowTest,finSumFinEquiv_apply_left,Fin.val_castAdd,Sum.inl.injEq,Fin.ext_iff] + rfl + | inr b => + have hi : i.val < m := i.isLt + have hne : m+b.val≠i.val := by omega + simp only [rowTest,finSumFinEquiv_apply_right,Fin.val_natAdd,hne, + Sum.inr_ne_inl,decide_false] + +lemma columnTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) (i : Fin m) (j : Fin n) : + columnTest ((data A x q,(finSumFinEquiv v).val),(i.val,j.val))=decide (v=Sum.inr j) := by + apply Bool.eq_iff_iff.mpr + cases v with + | inl a => + simp only [columnTest,data,RootedForestCatalog.data,List.length_ofFn, + finSumFinEquiv_apply_left,Fin.val_castAdd,decide_eq_true_eq,Sum.inl_ne_inr,iff_false] + have ha := a.isLt + omega + | inr b => + simp only [columnTest,data,RootedForestCatalog.data,List.length_ofFn, + finSumFinEquiv_apply_right,Fin.val_natAdd,decide_eq_true_eq,Sum.inr.injEq, + Nat.add_left_cancel_iff,Fin.ext_iff] + +noncomputable def contribution {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) (a : Fin m×Fin n) : ℤ := + if A.small a.1 a.2 then + (if v=Sum.inl a.1 then A.X a.1 a.2-(x a.1 a.2:ℤ) else 0)+ + (if v=Sum.inr a.2 then (q a.1 a.2:ℤ)-A.X a.1 a.2 else 0) + else 0 + +lemma term_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) (i : Fin m) (j : Fin n) : + value (term ((data A x q,(finSumFinEquiv v).val),(i.val,j.val)))= + contribution A x q v (i,j) := by + rw [term,retainedTest_data,rowTest_data,columnTest_data] + by_cases hs : A.small i j=true <;> by_cases hr : v=Sum.inl i <;> + by_cases hc : v=Sum.inr j + all_goals simp [hs,hr,hc,rowPair,columnPair,values_data, + contribution,value,SignedPairProgram.plus,Int.toNat_of_nonneg (A.hX i j).1] + +lemma contribution_sum {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) : + (∑ a : Fin m×Fin n,contribution A x q v a)= + ForestRootPenalty.smallDemand A.small A.X + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) v := by + cases v with + | inl i => + have ht (k : Fin m) (j : Fin n) : contribution A x q (.inl i) (k,j)= + if k=i then (if A.small i j then A.X i j-(x i j:ℤ) else 0) else 0 := by + by_cases hk : k=i + · subst k; simp [contribution] + · simp [contribution,hk,Ne.symm hk] + simp only [Fintype.sum_prod_type,ht] + simp [ForestRootPenalty.smallDemand] + | inr j => + have ht (i : Fin m) (k : Fin n) : contribution A x q (.inr j) (i,k)= + if k=j then (if A.small i j then (q i j:ℤ)-A.X i j else 0) else 0 := by + by_cases hk : k=j + · subst k; simp [contribution] + · simp [contribution,hk,Ne.symm hk] + simp only [Fintype.sum_prod_type,ht] + simp [ForestRootPenalty.smallDemand] + +lemma demand_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) (v : Fin m⊕Fin n) : + value (demand (data A x q,(finSumFinEquiv v).val))= + ForestRootPenalty.smallDemand A.small A.X + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) v := by + have hc : cellPairs (data A x q).1.1.2= + List.ofFn (fun a : Fin (m*n) => + (((finProdFinEquiv : Fin m×Fin n≃Fin (m*n)).symm a).1.val, + ((finProdFinEquiv : Fin m×Fin n≃Fin (m*n)).symm a).2.val)) := + DensePrograms.cellPairs_ofFn _ _ + rw [demand,value_sum,hc] + simp only [List.map_ofFn,Function.comp_apply,List.sum_ofFn,term_data] + calc + _=∑ a : Fin m×Fin n,contribution A x q v a := + Fintype.sum_equiv (finProdFinEquiv : Fin m×Fin n≃Fin (m*n)).symm _ _ (fun _ => rfl) + _=_ := contribution_sum A x q v + +lemma demandList_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) : + demandList (data A x q)=List.ofFn (fun i : Fin (m+n) => demand (data A x q,i.val)) := by + apply List.ext_getElem + · simp only [demandList,vertices,vertexCount,data,RootedForestCatalog.data,List.length_map, + List.length_range,List.length_ofFn] + · intro i hi hj + simp only [demandList,vertices,vertexCount,data,RootedForestCatalog.data,List.length_ofFn, + List.getElem_map,List.getElem_range,List.getElem_ofFn] + +/-- The actual binary root program has exactly the selected-root penalty +value; no signed-demand representation assumption is supplied. -/ +theorem rootCount_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (x q : Fin m → Fin n → ℕ) : + rootCount (data A x q)=RootedPenaltyProgram.rootCount A (rowColumn A.T) + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) := by + rw [rootCount,demandList_data] + change RootedComponentCode.count + (graphCode (A.T.comap finSumFinEquiv.symm),List.ofFn (fun i : Fin (m+n) => + ((demand (data A x q,i.val)).1,(demand (data A x q,i.val)).2)))=_ + rw [RootedComponentCode.count,RootedComponentCode.labels_graph] + have ht := RootedComponentProgram.total_records_rootCount A (rowColumn A.T) + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) finSumFinEquiv.symm + (fun i => (demand (data A x q,i.val)).1) (fun i => (demand (data A x q,i.val)).2) + (fun i => by + have h := demand_data A x q (finSumFinEquiv.symm i) + simpa only [Equiv.apply_symm_apply,value] using h) + simpa only [rowColumn_root,Equiv.apply_symm_apply,Equiv.symm_apply_apply] using ht + +end ContingencyTables.RootedDemandProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorAmplification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorAmplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c7ffd976f290e94fe88fca4b6a3d3cc897a8630 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorAmplification.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWords +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorAmplification +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMedianConfidence + +namespace OAI + +/-! # Logarithmic confidence amplification of the actual weight estimator -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteMedianConfidence +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def medianEstimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (epsilon delta : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool) : ℚ := + rationalMedian (List.ofFn (fun i : Fin (repetitionCount delta) => + wordEstimate A R C z K hK hW j (epsilon/2) 1 v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i))) + +theorem medianEstimate_success (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + 1-(delta:ℝ) ≤ uniformAverage (fun bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool => + if (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ≤ + (medianEstimate A R C z K hK hW j epsilon delta v bits:ℝ) ∧ + (medianEstimate A R C z K hK hW j epsilon delta v bits:ℝ) ≤ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z + then (1:ℝ) else 0) := by + have heh0 : 0 < epsilon/2 := by positivity + have heh1 : epsilon/2 < 1 := by linarith + have ht : 0 < RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z := RootedCountIdentification.h_positive A R _ _ + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have hbase := wordEstimate_failure A R C hC z hz K hK hW hB j hj (epsilon/2) 1 heh0 heh1 + (by norm_num) hPL hCheeger v + have hbad : uniformAverage (fun bits : Fin (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) → Bool => + if (wordEstimate A R C z K hK hW j (epsilon/2) 1 v bits:ℝ) < + (1-(epsilon:ℝ)/2)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ)/2)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (wordEstimate A R C z K hK hW j (epsilon/2) 1 v bits:ℝ) + then (1:ℝ) else 0) ≤ 5/16 := by + have hh : (1:ℝ)/4 ≤ 5/16 := by norm_num + apply le_trans ?_ hh + simpa only [Rat.cast_div,Rat.cast_ofNat,Rat.cast_one] using hbase + have hm := median_confidence_real + (wordEstimate A R C z K hK hW j (epsilon/2) 1 v) + ((1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z) + ((1-(epsilon:ℝ)/2)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z) + ((1+(epsilon:ℝ)/2)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z) + ((1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z) + (by nlinarith) (by nlinarith) delta hd hbad + let test := fun xs : Fin (repetitionCount delta) → + (Fin (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) → Bool) => + if (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ≤ + (rationalMedian (List.ofFn (fun i => wordEstimate A R C z K hK hW j (epsilon/2) 1 v (xs i))):ℝ) ∧ + (rationalMedian (List.ofFn (fun i => wordEstimate A R C z K hK hW j (epsilon/2) 1 v (xs i))):ℝ) ≤ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z + then (1:ℝ) else 0 + have he := uniformAverage_equiv + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1)) test + change 1-(delta:ℝ) ≤ uniformAverage (fun bits => test + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits)) + exact hm.trans_eq he.symm + +/-- Amplification also preserves the proved range on every word, +including statistically unsuccessful words. -/ +theorem medianEstimate_range (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (medianEstimate A R C z K hK hW j epsilon delta v bits:ℝ) ∧ + (medianEstimate A R C z K hK hW j epsilon delta v bits:ℝ) ≤ 8*assignmentCount A := by + let samples := List.ofFn (fun i : Fin (repetitionCount delta) => + wordEstimate A R C z K hK hW j (epsilon/2) 1 v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i)) + have hmem := rationalMedian_mem samples (by + dsimp only [samples] + rw [List.length_ofFn] + exact repetitionCount_pos delta) + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hmem + have hr := wordEstimate_range A R C hC z hz K hK hW hB j hj (epsilon/2) 1 + (by positivity) (by linarith) (by norm_num) v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i) + change _ ≤ (rationalMedian samples:ℝ) ∧ (rationalMedian samples:ℝ) ≤ _ + rw [←hi] + exact hr + + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorBlockProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorBlockProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..640c4cc096577edee13c77a82ad3b8be2feabb7b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorBlockProgram.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSampleProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSampleProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionAggregateProgram + +namespace OAI + +/-! # Executed sample blocks and the product weight estimator + +The lists contain the actual sample inputs and their disjoint finite +words. Each sample is evaluated by the checked binary program before +its average or product is formed. +-/ + +namespace ContingencyTables.RootedEstimatorBlockProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev RatioBlock := List RootedRatioSampleProgram.SampleInput +abbrev CorrectionBlock := List RootedCorrectionSampleProgram.Input + +def ratioAverage (xs : RatioBlock) : TreeFraction.Fraction := + FractionAggregateProgram.average (xs.map RootedRatioSampleProgram.output) +def ratioAverageRealizer : Realizer ratioAverage := + composition (f := fun xs : RatioBlock => xs.map RootedRatioSampleProgram.output) + (g := FractionAggregateProgram.average) (map RootedRatioSampleProgram.outputRealizer) + FractionAggregateProgram.averageRealizer +lemma polynomial_ratioAverage : PolynomialTime ratioAverageRealizer := + polynomial_composition (polynomial_map RootedRatioSampleProgram.polynomial_output) + FractionAggregateProgram.polynomial_average + +def correctionAverage (xs : CorrectionBlock) : TreeFraction.Fraction := + FractionAggregateProgram.average (xs.map RootedCorrectionSampleProgram.output) +def correctionAverageRealizer : Realizer correctionAverage := + composition (f := fun xs : CorrectionBlock => xs.map RootedCorrectionSampleProgram.output) + (g := FractionAggregateProgram.average) (map RootedCorrectionSampleProgram.outputRealizer) + FractionAggregateProgram.averageRealizer +lemma polynomial_correctionAverage : PolynomialTime correctionAverageRealizer := + polynomial_composition (polynomial_map RootedCorrectionSampleProgram.polynomial_output) + FractionAggregateProgram.polynomial_average + +abbrev Input := (ℕ × List RatioBlock) × CorrectionBlock + +attribute [local irreducible] ratioAverage correctionAverage + +def ratioProduct (z : Input) : TreeFraction.Fraction := + FractionAggregateProgram.product (z.1.2.map ratioAverage) +def ratioProductRealizer : Realizer ratioProduct := + composition (f := fun z : Input => z.1.2.map ratioAverage) + (g := FractionAggregateProgram.product) + (composition (f := fun z : Input => z.1.2) (g := fun xs : List RatioBlock => xs.map ratioAverage) + (composition first second) (map ratioAverageRealizer)) FractionAggregateProgram.productRealizer +lemma polynomial_ratioProduct : PolynomialTime ratioProductRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) + (polynomial_map polynomial_ratioAverage)) FractionAggregateProgram.polynomial_product + +def factors (z : Input) : TreeFraction.Fraction := + TreeFraction.mul (ratioProduct z,correctionAverage z.2) +def factorsRealizer : Realizer factors := + composition (f := fun z : Input => (ratioProduct z,correctionAverage z.2)) (g := TreeFraction.mul) + (pair ratioProductRealizer (composition (f := fun z : Input => z.2) + (g := correctionAverage) second correctionAverageRealizer)) TreeFraction.mulRealizer +lemma polynomial_factors : PolynomialTime factorsRealizer := + polynomial_composition (polynomial_pair polynomial_ratioProduct + (polynomial_composition polynomial_second polynomial_correctionAverage)) TreeFraction.polynomial_mul + +def output (z : Input) : TreeFraction.Fraction := TreeFraction.mul ((z.1.1,1),factors z) +def outputRealizer : Realizer output := + composition (f := fun z : Input => ((z.1.1,1),factors z)) (g := TreeFraction.mul) + (pair (pair (composition first first) (constant 1)) factorsRealizer) TreeFraction.mulRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) (polynomial_constant 1)) + polynomial_factors) TreeFraction.polynomial_mul + +lemma ratioAverage_value (xs : RatioBlock) : + TreeFraction.val (ratioAverage xs)= + (xs.map (fun z => TreeFraction.val (RootedRatioSampleProgram.output z))).sum/(xs.length:ℚ) := by + rw [ratioAverage,FractionAggregateProgram.average_value] + simp only [List.map_map,Function.comp_def,List.length_map] + +lemma correctionAverage_value (xs : CorrectionBlock) : + TreeFraction.val (correctionAverage xs)= + (xs.map (fun z => TreeFraction.val (RootedCorrectionSampleProgram.output z))).sum/(xs.length:ℚ) := by + rw [correctionAverage,FractionAggregateProgram.average_value] + simp only [List.map_map,Function.comp_def,List.length_map] + +lemma output_value (z : Input) : + TreeFraction.val (output z)=(z.1.1:ℚ)* + (z.1.2.map (fun xs => TreeFraction.val (ratioAverage xs))).prod* + TreeFraction.val (correctionAverage z.2) := by + rw [output,TreeFraction.mul_val,factors,TreeFraction.mul_val,ratioProduct, + FractionAggregateProgram.product_value] + rw [show TreeFraction.val (z.1.1,1)=(z.1.1:ℚ) by + simp only [TreeFraction.val,Nat.cast_one,div_one]] + simp only [List.map_map,Function.comp_def] + ring + +end ContingencyTables.RootedEstimatorBlockProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorConfidence.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorConfidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca5140652e205dfba29ce71abc7cfc11d3e44c2c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorConfidence.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleEstimator +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorConfidence + +namespace OAI + +/-! # Confidence of the complete bounded-word weight estimator -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def badFactor (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (i : Option (Fin j)) + (draws : EstimatorInput A C K j delta failure) : Prop := + (delta:ℝ)*targetFactor A R C z K hK hW j i < + |(observedFactor A R C z K hK hW j delta failure v draws i:ℝ)-targetFactor A R C z K hK hW j i| + +lemma factor_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd0 : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (i : Option (Fin j)) : + uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if badFactor A R C z K hK hW j delta failure v i draws then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + let : Nonempty (Fin j → RatioBlock A C K j delta failure) := ⟨fun _ _ _ _ => false⟩ + let : Nonempty (CorrectionBlock A C K j delta failure) := ⟨fun _ _ => false⟩ + cases i with + | none => + simp only [badFactor,observedFactor,targetFactor,rationalAverage_cast] + convert scheduled_correction_failure A R C j j hC hj delta failure hd0 hd1 hf z hz K hK hW hB hPL hCheeger v using 1 + rw [uniformAverage_prod] + dsimp only + convert uniformAverage_const (X := Fin j → RatioBlock A C K j delta failure) + (uniformAverage (fun draws : CorrectionBlock A C K j delta failure => + if (delta:ℝ)*correctionMean A R C j z K hK hW < + |sampleAverage (fun bits => (correctionSample A R C j z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) bits:ℝ)) + (sampleCount j delta failure) draws-correctionMean A R C j z K hK hW| then 1 else 0)) using 1 + | some a => + simp only [badFactor,observedFactor,targetFactor,rationalAverage_cast] + convert scheduled_ratio_failure A R C a.val j hC (by omega) delta failure hd0 hf z hz K hK hB hPL hCheeger v using 1 + rw [uniformAverage_prod] + dsimp only + have hc (x : Fin j → RatioBlock A C K j delta failure) := + uniformAverage_const (X := CorrectionBlock A C K j delta failure) + (if (delta:ℝ)*ratioMean A R C a.val z K < + |sampleAverage (fun bits => (ratioSample A R C a.val z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) (x a)-ratioMean A R C a.val z K| then 1 else 0) + simp_rw [hc] + convert uniformAverage_coordinate (X := fun _ : Fin j => RatioBlock A C K j delta failure) a (fun draws : RatioBlock A C K j delta failure => + if (delta:ℝ)*ratioMean A R C a.val z K < + |sampleAverage (fun bits => (ratioSample A R C a.val z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) draws-ratioMean A R C a.val z K| then 1 else 0) using 1 + exact average_fintype_irrel _ _ _ + +/-- All ratio and correction block failures share one explicit budget. +The statement concerns the actual bounded Boolean experiment. -/ +theorem goodEstimate_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd0 : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if ¬GoodEstimate A R C z K hK hW j delta failure v draws then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + have he (draws : EstimatorInput A C K j delta failure) : + (¬GoodEstimate A R C z K hK hW j delta failure v draws) ↔ + ∃ i,badFactor A R C z K hK hW j delta failure v i draws := by + simp only [GoodEstimate,badFactor,not_forall,not_le] + simp_rw [he] + calc + _ ≤ ∑ i : Option (Fin j),uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if badFactor A R C z K hK hW j delta failure v i draws then (1:ℝ) else 0) := + uniform_union_bound _ + _ ≤ ∑ _i : Option (Fin j),(failure:ℝ)/(4*((j:ℝ)+1)) := + Finset.sum_le_sum (fun i _ => factor_failure A R C hC z hz K hK hW hB j hj delta failure + hd0 hd1 hf hPL hCheeger v i) + _ = _ := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_option,Fintype.card_fin,nsmul_eq_mul, + Nat.cast_add,Nat.cast_one] + field_simp + +/-- A concrete rational estimator with bounded independent Boolean input +has the required relative-error guarantee for the original h-value. -/ +theorem estimateValue_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : EstimatorInput A C K j (innerTolerance epsilon j) failure => + if (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + have ht : 0 ≤ RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z := (RootedCountIdentification.h_positive A R _ _).le + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have hp (draws : EstimatorInput A C K j (innerTolerance epsilon j) failure) : + (if (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0) ≤ + if ¬GoodEstimate A R C z K hK hW j (innerTolerance epsilon j) failure v draws then 1 else 0 := by + by_cases hg : GoodEstimate A R C z K hK hW j (innerTolerance epsilon j) failure v draws + · have ha := goodEstimate_accuracy A R C hC z hz K hK hW hB j hj epsilon failure he0 he1 v draws hg + have hn : ¬((estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ)) := by + rintro (hb|hb) <;> nlinarith + simp only [hn,hg,not_true_eq_false,ite_false,le_refl] + · simp only [hg,not_false_eq_true,ite_true] + split_ifs <;> norm_num + exact (uniformAverage_mono _ _ hp).trans + (goodEstimate_failure A R C hC z hz K hK hW hB j hj (innerTolerance epsilon j) failure + (innerTolerance_pos epsilon j he0) (innerTolerance_lt_one epsilon j he1) hf hPL hCheeger v) + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorExecution.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba04db73499d8b082e046eb73edc0abc8ea5d680 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorExecution.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedComputedEstimator +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorRange + +namespace OAI + +/-! # Literal input and output of the executed estimator blocks -/ + +namespace ContingencyTables.RootedEstimatorExecution + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity RootedComputedEstimator +open MatchingFPRAS FiniteObservableTransport CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def ratioBlock (A : Instance (Fin m) (Fin n)) (C K j a : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (draws : RootedComputedEstimator.RatioWords A C K j delta failure) : + RootedEstimatorBlockProgram.RatioBlock := + List.ofFn (fun i => (RootedOracleWalkProgram.data A C a K z v,List.ofFn (draws i))) + +def correctionBlock (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (draws : RootedComputedEstimator.CorrectionWords A C K j delta failure) : + RootedEstimatorBlockProgram.CorrectionBlock := + List.ofFn (fun i => RootedCorrectionSampleProgram.data A C j K z v (offsetAccuracy A delta) + degree depth (List.ofFn (draws i).1) (List.ofFn (draws i).2)) + +def data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (draws : Inputs A C K j delta failure) : + RootedEstimatorBlockProgram.Input := + ((assignmentCount A,List.ofFn (fun a : Fin j => ratioBlock A C K j a.val delta failure z v (draws.1 a))), + correctionBlock A C K j delta failure z v degree depth draws.2) + +lemma ratioBlock_value (A : Instance (Fin m) (Fin n)) (C K j a : ℕ) (hC : 0 < C) + (delta failure : ℚ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (hB : (K:ℝ)=binWidth A C) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (draws : RootedComputedEstimator.RatioWords A C K j delta failure) : + TreeFraction.val (RootedEstimatorBlockProgram.ratioAverage + (ratioBlock A C K j a delta failure z v draws))= + RootedComputedEstimator.ratioAverage A C K j a delta failure z v draws := by + rw [RootedEstimatorBlockProgram.ratioAverage_value] + simp only [ratioBlock,List.map_ofFn,List.sum_ofFn,List.length_ofFn] + unfold RootedComputedEstimator.ratioAverage + congr 1 + apply Finset.sum_congr rfl + intro i _ + exact RootedRatioSampleLaw.program_sample A C a K hC z hz hB.le v _ (draws i) + +lemma correctionBlock_value (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) + (draws : RootedComputedEstimator.CorrectionWords A C K j delta failure) : + TreeFraction.val (RootedEstimatorBlockProgram.correctionAverage + (correctionBlock A C K j delta failure z v degree depth draws))= + RootedComputedEstimator.correctionAverage A C K j hK hW delta failure z v draws := by + rw [RootedEstimatorBlockProgram.correctionAverage_value] + simp only [correctionBlock,List.map_ofFn,List.sum_ofFn,List.length_ofFn] + unfold RootedComputedEstimator.correctionAverage + congr 1 + apply Finset.sum_congr rfl + intro i _ + exact RootedCorrectionSampleLaw.program_sample A C j K hC hj hK hW hB z + (roundingTolerance delta) v _ _ degree depth hdegree hdepth (draws i) + +/-- The actual list program returns the exact value of the transported +finite experiment, including unsuccessful statistical outcomes. -/ +theorem output_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) + (draws : Inputs A C K j delta failure) : + TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j delta failure z v degree depth draws))= + RootedComputedEstimator.estimate A C K j hK hW delta failure z v draws := by + rw [RootedEstimatorBlockProgram.output_value] + simp only [data,List.map_ofFn,List.prod_ofFn] + rw [correctionBlock_value A C K j hC hj hK hW hB delta failure z v degree depth hdegree hdepth] + have hp : (∏ a : Fin j,TreeFraction.val (RootedEstimatorBlockProgram.ratioAverage + (ratioBlock A C K j a.val delta failure z v (draws.1 a))))= + ∏ a : Fin j,RootedComputedEstimator.ratioAverage A C K j a.val delta failure z v (draws.1 a) := by + apply Finset.prod_congr rfl + intro a _ + exact ratioBlock_value A C K j a.val hC delta failure z hz hB v (draws.1 a) + simp only [Function.comp_apply] + rw [hp] + rfl + + +private lemma property_of_sameLaw {X Y Z : Type*} [Fintype X] [Fintype Y] + (f : X → Z) (g : Y → Z) (h : SameLaw f g) (P : Z → Prop) + (hg : ∀ y,P (g y)) (x : X) : P (f x) := by + by_contra hx + let bad : Z → ℝ := fun z => if P z then 0 else 1 + have he := h bad + have hzero : uniformAverage (fun y => bad (g y))=0 := by + simp only [bad,hg,ite_true,uniformAverage,Finset.sum_const_zero,zero_div] + rw [hzero] at he + have hnonneg (t : X) : 0 ≤ bad (f t) := by + dsimp only [bad] + split_ifs <;> norm_num + have hsum : (∑ t : X,bad (f t))=0 := by + have he' := (div_eq_zero_iff).mp he + rcases he' with he'|he' + · exact he' + · have hc : Fintype.card X≠0 := by + let : Nonempty X := ⟨x⟩ + exact Fintype.card_ne_zero + exact False.elim (hc (by exact_mod_cast he')) + have hxsum := Finset.single_le_sum (fun t _ => hnonneg t) (Finset.mem_univ x) + rw [hsum] at hxsum + simp only [bad,hx,ite_false] at hxsum + norm_num at hxsum + +/-- Full finite support transfers the proved deterministic range to +all physical sample words, not only to the high-probability event. -/ +theorem output_range (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (delta failure : ℚ) + (hd0 : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) + (draws : Inputs A C K j delta failure) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j delta failure z v degree depth draws)):ℝ) ∧ + (TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j delta failure z v degree depth draws)):ℝ) ≤ 8*assignmentCount A := by + simp only [output_data A C K j hC hj hK hW hB delta failure z hz v degree depth hdegree hdepth] + exact property_of_sameLaw _ _ + (RootedComputedEstimator.sameLaw A C K j hC hj hK hW hB delta failure z hz v) + (fun q : ℚ => (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ (q:ℝ) ∧ (q:ℝ) ≤ 8*assignmentCount A) + (fun ys => RootedOracleDensity.estimateValue_range A (RootedCompletion.rowColumn A.T) + C hC z hz K hK hW hB j hj delta failure hd0 hd1 hf (RootedCatalogGrid.gridEquiv A K v) ys) draws + +theorem output_failure (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) (epsilon failure : ℚ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance epsilon j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance epsilon j))) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + uniformAverage (fun draws : Inputs A C K j (innerTolerance epsilon j) failure => + if (TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j (innerTolerance epsilon j) failure z v degree depth draws)):ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z < + (TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j (innerTolerance epsilon j) failure z v degree depth draws)):ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + let bad : ℚ → ℝ := fun q => if (q:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z < (q:ℝ) then 1 else 0 + have hlaw := RootedComputedEstimator.sameLaw A C K j hC hj hK hW hB + (innerTolerance epsilon j) failure z hz v bad + have hdata := output_data A C K j hC hj hK hW hB (innerTolerance epsilon j) + failure z hz v degree depth hdegree hdepth + change uniformAverage (fun draws => bad (TreeFraction.val (RootedEstimatorBlockProgram.output + (data A C K j (innerTolerance epsilon j) failure z v degree depth draws)))) ≤ _ + simp_rw [hdata] + rw [hlaw] + exact RootedOracleDensity.estimateValue_failure A (RootedCompletion.rowColumn A.T) C hC z hz + K hK hW hB j hj epsilon failure he0 he1 hf hPL hCheeger (RootedCatalogGrid.gridEquiv A K v) + +end +end ContingencyTables.RootedEstimatorExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorLayoutProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorLayoutProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fff95579c9e6eb3dc909d6acb52f8a5af70c72b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorLayoutProgram.lean @@ -0,0 +1,210 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorExecution + +namespace OAI + +/-! # Computed sizes of the estimator's disjoint word banks + +The schedule supplies the phase and sample counts and the two walk times. +The catalog itself supplies both the integer-draw widths and the initial +free-assignment count. No list is allocated from a binary count here. +-/ + +namespace ContingencyTables.RootedEstimatorLayoutProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev State := RootedOracleWalkProgram.State +abbrev Schedule := (ℕ×ℕ)×((ℕ×ℕ)×ℕ) +abbrev Context := State×Schedule + +def stepWidth (z : Context) : ℕ := RootedOracleWalkProgram.stepWidth z.1.1 +def stepWidthRealizer : Realizer stepWidth := + composition (f := fun z : Context => z.1.1) (g := RootedOracleWalkProgram.stepWidth) + (composition first first) RootedOracleWalkProgram.stepWidthRealizer +lemma polynomial_stepWidth : PolynomialTime stepWidthRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) + RootedOracleWalkProgram.polynomial_stepWidth + +def ratioWidth (z : Context) : ℕ := z.2.2.1.1*stepWidth z +def ratioWidthRealizer : Realizer ratioWidth := + composition (f := fun z : Context => (z.2.2.1.1,stepWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (composition (composition second second) first) first) stepWidthRealizer) + multiply +lemma polynomial_ratioWidth : PolynomialTime ratioWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_second) polynomial_first) polynomial_first) + polynomial_stepWidth) polynomial_multiply + +def ratioBlockWidth (z : Context) : ℕ := z.2.1.2*ratioWidth z +def ratioBlockWidthRealizer : Realizer ratioBlockWidth := + composition (f := fun z : Context => (z.2.1.2,ratioWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (composition second first) second) ratioWidthRealizer) multiply +lemma polynomial_ratioBlockWidth : PolynomialTime ratioBlockWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second) + polynomial_ratioWidth) polynomial_multiply + +def ratioBankWidth (z : Context) : ℕ := z.2.1.1*ratioBlockWidth z +def ratioBankWidthRealizer : Realizer ratioBankWidth := + composition (f := fun z : Context => (z.2.1.1,ratioBlockWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (composition second first) first) ratioBlockWidthRealizer) multiply +lemma polynomial_ratioBankWidth : PolynomialTime ratioBankWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_first) + polynomial_ratioBlockWidth) polynomial_multiply + +def binFrame (z : Context) : RootedBinFramesProgram.Input := + ((z.1.1.1,(z.2.2.2,z.1.1.2.1.1.1)),(z.1.1.2.2.1,z.1.2)) +def binFrameRealizer : Realizer binFrame := by + let k : Realizer (fun z : Context => z.1.1.1) := composition (composition first first) first + let h : Realizer (fun z : Context => z.2.2.2) := composition (composition second second) second + let d : Realizer (fun z : Context => z.1.1.2.1.1.1) := + composition (composition (composition (composition (composition first first) second) first) first) first + let catalog : Realizer (fun z : Context => z.1.1.2.2.1) := + composition (composition (composition (composition first first) second) second) first + exact pair (pair k (pair h d)) (pair catalog (composition first second)) +lemma polynomial_binFrame : PolynomialTime binFrameRealizer := by + unfold binFrameRealizer + exact polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_second) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_first) polynomial_first) polynomial_first))) + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) polynomial_first) + (polynomial_composition polynomial_first polynomial_second)) + +def frames (z : Context) : List BinVectorProgram.Frame := RootedBinFramesProgram.frames (binFrame z) +def framesRealizer : Realizer frames := + composition (f := binFrame) (g := RootedBinFramesProgram.frames) + binFrameRealizer RootedBinFramesProgram.framesRealizer +lemma polynomial_frames : PolynomialTime framesRealizer := + polynomial_composition polynomial_binFrame RootedBinFramesProgram.polynomial_frames + +attribute [local irreducible] frames + +def binWidth (z : Context) : ℕ := ((frames z).map BinVectorProgram.reservedWidth).sum +def binWidthRealizer : Realizer binWidth := + composition (f := frames) (g := fun xs : List BinVectorProgram.Frame => + (xs.map BinVectorProgram.reservedWidth).sum) framesRealizer + (composition (map BinVectorProgram.reservedWidthRealizer) listSum) +lemma polynomial_binWidth : PolynomialTime binWidthRealizer := + polynomial_composition polynomial_frames + (polynomial_composition (polynomial_map BinVectorProgram.polynomial_reservedWidth) polynomial_listSum) + +def assignmentCount (z : Context) : ℕ := ((frames z).map (fun x => x.1.1.2)).prod +def rangeValue (x : BinVectorProgram.Frame) : ℕ := x.1.1.2 +def rangeValueRealizer : Realizer rangeValue := composition (composition first first) second +lemma polynomial_rangeValue : PolynomialTime rangeValueRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + +def rangeValues (xs : List BinVectorProgram.Frame) : List ℕ := xs.map rangeValue +def rangeValuesRealizer : Realizer rangeValues := MatchingFPRAS.TreeTyped.map rangeValueRealizer +lemma polynomial_rangeValues : PolynomialTime rangeValuesRealizer := polynomial_map polynomial_rangeValue + +attribute [local irreducible] rangeValue rangeValues + +def assignmentCountRealizer : Realizer assignmentCount := by + let values : Realizer (fun z : Context => rangeValues (frames z)) := + composition (f := frames) (g := rangeValues) framesRealizer rangeValuesRealizer + exact (composition (f := fun z : Context => rangeValues (frames z)) + (g := (List.prod : List ℕ → ℕ)) values listProd).congr (by + intro z + unfold assignmentCount rangeValues rangeValue + rfl) +lemma polynomial_assignmentCount : PolynomialTime assignmentCountRealizer := by + unfold assignmentCountRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_composition polynomial_frames polynomial_rangeValues) + polynomial_listProd + +def correctionWalkWidth (z : Context) : ℕ := z.2.2.1.2*stepWidth z +def correctionWalkWidthRealizer : Realizer correctionWalkWidth := + composition (f := fun z : Context => (z.2.2.1.2,stepWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (composition (composition second second) first) second) stepWidthRealizer) + multiply +lemma polynomial_correctionWalkWidth : PolynomialTime correctionWalkWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_second) polynomial_first) polynomial_second) + polynomial_stepWidth) polynomial_multiply + +def correctionWidth (z : Context) : ℕ := correctionWalkWidth z+binWidth z +def correctionWidthRealizer : Realizer correctionWidth := + composition (f := fun z : Context => (correctionWalkWidth z,binWidth z)) + (g := fun p : ℕ×ℕ => p.1+p.2) (pair correctionWalkWidthRealizer binWidthRealizer) add +lemma polynomial_correctionWidth : PolynomialTime correctionWidthRealizer := + polynomial_composition (polynomial_pair polynomial_correctionWalkWidth polynomial_binWidth) polynomial_add + +def wordWidth (z : Context) : ℕ := ratioBankWidth z+z.2.1.2*correctionWidth z +def wordWidthRealizer : Realizer wordWidth := + composition (f := fun z : Context => (ratioBankWidth z,z.2.1.2*correctionWidth z)) + (g := fun p : ℕ×ℕ => p.1+p.2) (pair ratioBankWidthRealizer + (composition (f := fun z : Context => (z.2.1.2,correctionWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (composition second first) second) correctionWidthRealizer) multiply)) add +lemma polynomial_wordWidth : PolynomialTime wordWidthRealizer := + polynomial_composition (polynomial_pair polynomial_ratioBankWidth + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second) + polynomial_correctionWidth) polynomial_multiply)) polynomial_add + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Context := + (RootedOracleWalkProgram.data A C 0 K z v,((j,S),((Tr,Tc),h))) + +lemma frames_data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + frames (data A C K j S Tr Tc h z v)=List.ofFn (fun i => + (((K,CompanionOracleDensity.freeRange A (RootedForestCatalog.freeEquiv A i)), + (v i).val.toNat),(h,A.d))) := by + unfold frames + change RootedBinFramesProgram.frames (RootedBinFramesProgram.data A h v)=_ + exact RootedBinFramesProgram.frames_data A h v + +lemma binWidth_data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + binWidth (data A C K j S Tr Tc h z v)=RootedBinDrawLaw.wordBits A h := by + rw [binWidth,frames_data] + simp only [List.map_ofFn,List.sum_ofFn,BinVectorProgram.reservedWidth, + RootedBinDrawLaw.wordBits,FairBits.offsetBitLength,Function.comp_apply] + +lemma assignmentCount_data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + assignmentCount (data A C K j S Tr Tc h z v)=CompanionOracleDensity.assignmentCount A := by + rw [assignmentCount,frames_data,CompanionOracleDensity.assignmentCount_eq_prod] + simp only [List.map_ofFn,List.prod_ofFn] + exact Fintype.prod_equiv (RootedForestCatalog.freeEquiv A) _ _ (fun _ => rfl) + +lemma ratioWidth_data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + ratioWidth (data A C K j S Tr Tc h z v)=Tr*CompanionOracleDensity.oracleStepBits A C := by + change Tr*RootedOracleWalkProgram.stepWidth (RootedOracleWalkProgram.data A C 0 K z v).1=_ + rw [RootedOracleWalkProgram.stepWidth_data] + +lemma correctionWalkWidth_data (A : Instance (Fin m) (Fin n)) (C K j S Tr Tc h : ℕ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + correctionWalkWidth (data A C K j S Tr Tc h z v)=Tc*CompanionOracleDensity.oracleStepBits A C := by + change Tc*RootedOracleWalkProgram.stepWidth (RootedOracleWalkProgram.data A C 0 K z v).1=_ + rw [RootedOracleWalkProgram.stepWidth_data] + +end +end ContingencyTables.RootedEstimatorLayoutProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..44c1387de3c860ef80df61adb43230def8ee5c06 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianLaw.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorMedianProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorAmplification + +namespace OAI + +/-! # The executed inner median is the analysed amplified weight oracle -/ + +namespace ContingencyTables.RootedEstimatorMedianProgram + +open MatchingFPRAS CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity RootedEstimatorLayoutProgram CommonBasesFPRAS +open FiniteObservableTransport +open scoped Classical + +noncomputable section +variable {m n : ℕ} + +def context (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (epsilon : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Context := + RootedEstimatorWordProgram.scheduledContext A C K j (innerTolerance (epsilon/2) j) 1 z v + +def value (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (epsilon delta : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) + (bits : Fin (repetitionCount delta*wordWidth (context A C K j epsilon z v)) → Bool) : ℚ := + TreeFraction.val (output ((context A C K j epsilon z v,repetitionCount delta), + ((degree,depth),List.ofFn bits))) + +/-- Exact observable transport, including the outputs on inaccurate +sample histories, lets the original median analysis apply unchanged. -/ +theorem sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon delta : ℚ) (he : 0 < epsilon) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance (epsilon/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance (epsilon/2) j))) : + SameLaw (value A C K j epsilon delta z v degree depth) + (RootedOracleDensity.medianEstimate A (RootedCompletion.rowColumn A.T) C z K hK hW j + epsilon delta (RootedCatalogGrid.gridEquiv A K v)) := by + have heh : 0 < epsilon/2 := by positivity + have hs := RootedEstimatorWordProgram.sameLaw_word A C K j hC hj hK hW hB + (epsilon/2) 1 heh (by norm_num) z hz v degree depth hdegree hdepth + have hp := (hs.independent (repetitionCount delta)).map + (fun qs : Fin (repetitionCount delta) → ℚ => rationalMedian (List.ofFn qs)) + have hw := RootedEstimatorWordProgram.scheduledWidth_positive A C K j hC hK + (innerTolerance (epsilon/2) j) 1 (innerTolerance_pos (epsilon/2) j heh) + (by norm_num) z v + intro phi + have hleft := uniformAverage_equiv + (gridWordEquiv (repetitionCount delta) (wordWidth (context A C K j epsilon z v))) + (fun xs => phi (rationalMedian (List.ofFn (fun i => TreeFraction.val + (RootedEstimatorWordProgram.output (RootedEstimatorWordProgram.input + (context A C K j epsilon z v) (degree,depth) (xs i))))))) + have hright := uniformAverage_equiv + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1)) + (fun xs => phi (rationalMedian (List.ofFn (fun i => RootedOracleDensity.wordEstimate A + (RootedCompletion.rowColumn A.T) C z K hK hW j (epsilon/2) 1 + (RootedCatalogGrid.gridEquiv A K v) (xs i))))) + have hout : uniformAverage (fun bits => phi (value A C K j epsilon delta z v degree depth bits))= + uniformAverage (fun bits => phi (rationalMedian (List.ofFn (fun i : Fin (repetitionCount delta) => + TreeFraction.val (RootedEstimatorWordProgram.output (RootedEstimatorWordProgram.input + (context A C K j epsilon z v) (degree,depth) + (gridWordEquiv (repetitionCount delta) (wordWidth (context A C K j epsilon z v)) bits i))))))) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (output_ofFn (context A C K j epsilon z v) (repetitionCount delta) + hw (degree,depth) bits) + exact hout.trans (hleft.trans ((hp phi).trans hright.symm)) + +theorem success (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance (epsilon/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance (epsilon/2) j))) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Fin (repetitionCount delta*wordWidth (context A C K j epsilon z v)) → Bool => + if (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ≤ (value A C K j epsilon delta z v degree depth bits:ℝ) ∧ + (value A C K j epsilon delta z v degree depth bits:ℝ) ≤ + (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z then (1:ℝ) else 0) := by + let event := fun q : ℚ => if + (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ≤ (q:ℝ) ∧ + (q:ℝ) ≤ (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z then (1:ℝ) else 0 + have heq := sameLaw A C K j hC hj hK hW hB epsilon delta he0 z hz v degree depth hdegree hdepth event + exact (RootedOracleDensity.medianEstimate_success A (RootedCompletion.rowColumn A.T) C hC z hz + K hK hW hB j hj epsilon delta he0 he1 hd hPL hCheeger + (RootedCatalogGrid.gridEquiv A K v)).trans_eq heq.symm + +end +end ContingencyTables.RootedEstimatorMedianProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0cb02696e19e575b31535ba4802787cee8fe9670 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorMedianProgram.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordLaw +import OAI.Combinatorics.ContingencyTables.Machines.MedianFractionProgram + +namespace OAI + +/-! # Executing independent complete estimators and their rational median -/ + +namespace ContingencyTables.RootedEstimatorMedianProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open RootedEstimatorLayoutProgram + +abbrev Input := (Context×ℕ)×((List Bool×List Bool)×List Bool) + +def words (z : Input) : List (List Bool) := + (wordChunks (wordWidth z.1.1,z.2.2)).take z.1.2 +def wordsRealizer : Realizer words := by + let chunks : Realizer (fun z : Input => wordChunks (wordWidth z.1.1,z.2.2)) := + composition (f := fun z : Input => (wordWidth z.1.1,z.2.2)) (g := wordChunks) + (pair (composition (f := fun z : Input => z.1.1) (g := wordWidth) + (composition first first) wordWidthRealizer) (composition second second)) wordChunksRealizer + exact composition (f := fun z : Input => (wordChunks (wordWidth z.1.1,z.2.2),z.1.2)) + (g := fun p : List (List Bool)×ℕ => p.1.take p.2) + (pair chunks (composition first second)) takeFast +lemma polynomial_words : PolynomialTime wordsRealizer := by + unfold wordsRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_wordWidth) (polynomial_composition polynomial_second polynomial_second)) + polynomial_wordChunks) + (polynomial_composition polynomial_first polynomial_second)) polynomial_takeFast + +def sample (z : Input×List Bool) : TreeFraction.Fraction := + RootedEstimatorWordProgram.output (z.1.1.1,(z.1.2.1,z.2)) +def sampleRealizer : Realizer sample := + composition (f := fun z : Input×List Bool => (z.1.1.1,(z.1.2.1,z.2))) + (g := RootedEstimatorWordProgram.output) + (pair (composition (composition first first) first) + (pair (composition (composition first second) first) second)) + RootedEstimatorWordProgram.outputRealizer +lemma polynomial_sample : PolynomialTime sampleRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_second)) RootedEstimatorWordProgram.polynomial_output + +def samples (z : Input) : List TreeFraction.Fraction := (words z).map (fun bits => sample (z,bits)) +def samplesRealizer : Realizer samples := + composition (pair identity wordsRealizer) (mapWith sampleRealizer) +lemma polynomial_samples : PolynomialTime samplesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_words) + (polynomial_mapWith polynomial_sample) + +attribute [local irreducible] samples + +def output (z : Input) : TreeFraction.Fraction := MedianFractionProgram.median (samples z) +def outputRealizer : Realizer output := + composition (f := samples) (g := MedianFractionProgram.median) + samplesRealizer MedianFractionProgram.medianRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_samples MedianFractionProgram.polynomial_median + +open GridBoundary CommonBasesFPRAS +open scoped Classical + +theorem output_ofFn (c : Context) (R : ℕ) (hw : 0 < wordWidth c) + (markers : List Bool×List Bool) (bits : Fin (R*wordWidth c) → Bool) : + TreeFraction.val (output ((c,R),(markers,List.ofFn bits)))= + rationalMedian (List.ofFn (fun i : Fin R => TreeFraction.val + (RootedEstimatorWordProgram.output (RootedEstimatorWordProgram.input c markers + (gridWordEquiv R (wordWidth c) bits i))))) := by + rw [output,MedianFractionProgram.median_val] + have hwords : words ((c,R),(markers,List.ofFn bits))= + List.ofFn (fun i : Fin R => List.ofFn (gridWordEquiv R (wordWidth c) bits i)) := by + change (wordChunks (wordWidth c,List.ofFn bits)).take R=_ + rw [wordChunks_ofFn hw] + exact List.take_of_length_le (by simp) + unfold samples + rw [hwords] + simp only [List.map_ofFn] + rfl + +end ContingencyTables.RootedEstimatorMedianProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorRange.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorRange.lean new file mode 100644 index 0000000000000000000000000000000000000000..54fa3d3d79e847fbbc3316af6cb06f4af93a8dc9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorRange.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleEstimator +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorRange + +namespace OAI + +/-! # Output range on every execution of the finite-word estimator -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma observed_ratio_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) (a : Fin j) : + 1/2 ≤ (observedFactor A R C z K hK hW j delta failure v draws (some a):ℝ) ∧ + (observedFactor A R C z K hK hW j delta failure v draws (some a):ℝ) ≤ 1 := by + apply rationalAverage_bounds _ _ (sampleCount_positive j delta failure hd hf) + intro bits + rw [ratioSample_cast] + exact ratioObservable_bounds A R C (by exact_mod_cast hC) a.val z hz hB.le _ + +lemma observed_correction_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) + (hf : 0 < failure) (v : Grid (I := Fin (dimension A)) K) + (draws : EstimatorInput A C K j delta failure) : + 1/16 ≤ (observedFactor A R C z K hK hW j delta failure v draws none:ℝ) ∧ + (observedFactor A R C z K hK hW j delta failure v draws none:ℝ) ≤ 8 := by + apply rationalAverage_bounds _ _ (sampleCount_positive j delta failure hd hf) + intro bits + apply computedCorrection_bounds A R C j hC hj z K (by omega) hW hB (roundingTolerance delta) + · unfold roundingTolerance + positivity + · unfold roundingTolerance + linarith + +/-- These bounds hold for every Boolean input, including executions on +which the empirical averages are statistically inaccurate. -/ +theorem estimateValue_range (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ (estimateValue A R C z K hK hW j delta failure v draws:ℝ) ∧ + (estimateValue A R C z K hK hW j delta failure v draws:ℝ) ≤ 8*assignmentCount A := by + let r := fun a : Fin j => (observedFactor A R C z K hK hW j delta failure v draws (some a):ℝ) + let q := (observedFactor A R C z K hK hW j delta failure v draws none:ℝ) + have hr := observed_ratio_bounds A R C hC z hz K hK hW hB j delta failure hd hf v draws + have hq := observed_correction_bounds A R C hC z K hK hW hB j hj delta failure hd hd1 hf v draws + have hrlow : (1/2:ℝ)^j ≤ ∏ a,r a := by + have hh := Finset.prod_le_prod₀ (s := Finset.univ) + (fun _ _ => by norm_num : ∀ a : Fin j,a∈Finset.univ → (0:ℝ) ≤ 1/2) + (fun a _ => (hr a).1) + simpa only [Finset.prod_const,Finset.card_univ,Fintype.card_fin] using hh + have hrup : (∏ a,r a) ≤ 1 := by + have hh := Finset.prod_le_prod₀ (s := Finset.univ) + (fun a _ => show (0:ℝ) ≤ r a from (by have h := (hr a).1; linarith)) (fun a _ => (hr a).2) + simpa only [Finset.prod_const_one] using hh + have hr0 : (0:ℝ) ≤ ∏ a,r a := Finset.prod_nonneg (fun a _ => by have h := (hr a).1; linarith) + have hq0 : 0 ≤ q := by dsimp only [q]; linarith [hq.1] + have hlow : (1/16:ℝ)*(1/2:ℝ)^j ≤ q*(∏ a,r a) := + mul_le_mul hq.1 hrlow (by positivity) hq0 + have hupp : q*(∏ a,r a) ≤ 8 := by + calc + _ ≤ 8*1 := mul_le_mul hq.2 hrup hr0 (by norm_num) + _ = _ := by norm_num + have hMf : (0:ℝ) ≤ assignmentCount A := Nat.cast_nonneg _ + have he : (estimateValue A R C z K hK hW j delta failure v draws:ℝ)= + (assignmentCount A:ℝ)*(q*∏ a,r a) := by + simp only [estimateValue,Rat.cast_mul,Rat.cast_natCast,Rat.cast_prod,Fintype.prod_option] + rfl + rw [he] + constructor + · have hh := mul_le_mul_of_nonneg_left hlow hMf + nlinarith + · have hh := mul_le_mul_of_nonneg_left hupp hMf + nlinarith + +theorem estimateValue_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + 0 < estimateValue A R C z K hK hW j delta failure v draws := by + have hMf : (0:ℝ) < assignmentCount A := by exact_mod_cast assignmentCount_positive A + have hh := (estimateValue_range A R C hC z hz K hK hW hB j hj delta failure hd hd1 hf v draws).1 + have hp : (0:ℝ) < (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 := by positivity + exact_mod_cast lt_of_lt_of_le hp hh + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e5330421cbdda9370836f7794457c944b9878d1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordLaw.lean @@ -0,0 +1,256 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorWords +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWords + +namespace OAI + +/-! # Exact finite-word law of the executed selected-root weight oracle -/ + +namespace ContingencyTables.RootedEstimatorWordProgram + +open MatchingFPRAS CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity RootedEstimatorLayoutProgram CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def scheduledContext (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Context := + RootedEstimatorLayoutProgram.data A C K j (sampleCount j delta failure) + (oracleTime A C K 1 delta) (oracleTime A C K 1 (correctionTheta delta)) + (offsetAccuracy A delta) z v + +def scheduledEquiv (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + (Fin (wordWidth (scheduledContext A C K j delta failure z v)) → Bool) ≃ + RootedComputedEstimator.Inputs A C K j delta failure := + (wordEquiv (scheduledContext A C K j delta failure z v)).trans + (recodeBanks + (ratioWidth_data A C K j _ _ _ _ z v) + (correctionWalkWidth_data A C K j _ _ _ _ z v) + (binWidth_data A C K j _ _ _ _ z v)) + +lemma scheduledWordWidth (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (delta failure : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + wordWidth (scheduledContext A C K j delta failure z v)= + estimatorWordBits A C K j delta failure := by + change j*(sampleCount j delta failure*ratioWidth + (scheduledContext A C K j delta failure z v))+ + sampleCount j delta failure*(correctionWalkWidth + (scheduledContext A C K j delta failure z v)+ + RootedEstimatorLayoutProgram.binWidth (scheduledContext A C K j delta failure z v))=_ + simp only [scheduledContext,ratioWidth_data,correctionWalkWidth_data,binWidth_data, + RootedBinDrawLaw.wordBits_eq,estimatorWordBits,oracleIntegerBits] + +private lemma oracleTime_positive (A : Instance (Fin m) (Fin n)) (C K : ℕ) + (hC : 0 < C) (hK : 1 ≤ K) (theta : ℝ) (htheta : 0 < theta) : + 0 < oracleTime A C K 1 theta := by + have hd : (0:ℝ) < A.d := by exact_mod_cast (lt_of_lt_of_le Nat.zero_lt_one A.hd) + have hk : (0:ℝ) < K := by exact_mod_cast (lt_of_lt_of_le Nat.zero_lt_one hK) + have hh := height_positive A C (by exact_mod_cast hC) + have hm : 0 < mixingConstant A K := by unfold mixingConstant; positivity + have hp : 0 < mixingConstant A K*(height A C+A.d*K+16*1/theta+2) := by positivity + have hn := Nat.le_ceil (mixingConstant A K*(height A C+A.d*K+16*1/theta+2)) + have hc : (0:ℝ) < oracleTime A C K 1 theta := by + simpa only [oracleTime,Nat.cast_one] using hp.trans_le hn + exact_mod_cast hc + +theorem scheduledWidth_positive (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hK : 1 ≤ K) (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + 0 < wordWidth (scheduledContext A C K j delta failure z v) := by + have hdelta : (0:ℝ) < delta := by exact_mod_cast hd + have htime := oracleTime_positive A C K hC hK (correctionTheta delta) + (by unfold correctionTheta; positivity) + have hstep := RootedOracleWalkProgram.stepWidth_pos A C hC + have hs := sampleCount_positive j delta failure hd hf + have ht : 0 < correctionWalkWidth (scheduledContext A C K j delta failure z v) := by + rw [scheduledContext,correctionWalkWidth_data] + exact Nat.mul_pos htime hstep + have hc : 0 < correctionWidth (scheduledContext A C K j delta failure z v) := by + unfold correctionWidth + omega + have hp := Nat.mul_pos hs hc + change 0 < _ + sampleCount j delta failure* + correctionWidth (scheduledContext A C K j delta failure z v) + omega + +/-- Parsing the one flat word produces precisely the sample inputs +used in the independent estimator experiment. -/ +theorem prepare_scheduled (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hK : 1 ≤ K) (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) + (bits : Fin (wordWidth (scheduledContext A C K j delta failure z v)) → Bool) : + prepare (input (scheduledContext A C K j delta failure z v) (degree,depth) bits)= + RootedEstimatorExecution.data A C K j delta failure z v degree depth + (scheduledEquiv A C K j delta failure z v bits) := by + have hdelta : (0:ℝ) < delta := by exact_mod_cast hd + have hstep := RootedOracleWalkProgram.stepWidth_pos A C hC + have hrtime := oracleTime_positive A C K hC hK delta hdelta + have hctime := oracleTime_positive A C K hC hK (correctionTheta delta) + (by unfold correctionTheta; positivity) + have hs : 0 < (scheduledContext A C K j delta failure z v).2.1.2 := + sampleCount_positive j delta failure hd hf + have hr : 0 < ratioWidth (scheduledContext A C K j delta failure z v) := by + rw [scheduledContext,ratioWidth_data] + exact Nat.mul_pos hrtime hstep + have ht : 0 < correctionWidth (scheduledContext A C K j delta failure z v) := by + unfold correctionWidth + have ht : 0 < correctionWalkWidth (scheduledContext A C K j delta failure z v) := by + rw [scheduledContext,correctionWalkWidth_data] + exact Nat.mul_pos hctime hstep + omega + rw [prepare_input _ _ hs hr ht] + unfold bankInput + have hc := encodeBanks_recode (ratioWidth_data A C K j _ _ _ _ z v) + (correctionWalkWidth_data A C K j _ _ _ _ z v) + (binWidth_data A C K j _ _ _ _ z v) + (scheduledContext A C K j delta failure z v).1 + (scheduledContext A C K j delta failure z v).2.2.2 + (RootedEstimatorLayoutProgram.assignmentCount (scheduledContext A C K j delta failure z v)) + (degree,depth) (wordEquiv (scheduledContext A C K j delta failure z v) bits) + refine hc.symm.trans ?_ + change encodeBanks (RootedOracleWalkProgram.data A C 0 K z v) j + (offsetAccuracy A delta) (RootedEstimatorLayoutProgram.assignmentCount + (scheduledContext A C K j delta failure z v)) (degree,depth) + (scheduledEquiv A C K j delta failure z v bits)=_ + have hcount : RootedEstimatorLayoutProgram.assignmentCount + (scheduledContext A C K j delta failure z v)=CompanionOracleDensity.assignmentCount A := + assignmentCount_data A C K j _ _ _ _ z v + rw [hcount] + unfold encodeBanks RootedEstimatorExecution.data RootedEstimatorExecution.ratioBlock + RootedEstimatorExecution.correctionBlock RootedCorrectionSampleProgram.data + simp only [phase_data] + +theorem output_scheduled (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) + (bits : Fin (wordWidth (scheduledContext A C K j delta failure z v)) → Bool) : + TreeFraction.val (output (input (scheduledContext A C K j delta failure z v) + (degree,depth) bits))=RootedComputedEstimator.estimate A C K j hK hW delta failure z v + (scheduledEquiv A C K j delta failure z v bits) := by + rw [output,prepare_scheduled A C K j hC hK delta failure hd hf z v degree depth bits] + exact RootedEstimatorExecution.output_data A C K j hC hj hK hW hB delta failure z hz v + degree depth hdegree hdepth _ + +theorem sameLaw_estimateValue (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) : + FiniteObservableTransport.SameLaw + (fun bits => TreeFraction.val (output (input + (scheduledContext A C K j delta failure z v) (degree,depth) bits))) + (RootedOracleDensity.estimateValue A (RootedCompletion.rowColumn A.T) C z K hK hW j + delta failure (RootedCatalogGrid.gridEquiv A K v)) := by + intro phi + let test := fun draws : RootedComputedEstimator.Inputs A C K j delta failure => + phi (RootedComputedEstimator.estimate A C K j hK hW delta failure z v draws) + have hp := output_scheduled A C K j hC hj hK hW hB delta failure hd hf z hz v + degree depth hdegree hdepth + have he := uniformAverage_equiv (scheduledEquiv A C K j delta failure z v) test + have ho : uniformAverage (fun bits => phi (TreeFraction.val (output (input + (scheduledContext A C K j delta failure z v) (degree,depth) bits))))= + uniformAverage (fun bits => test (scheduledEquiv A C K j delta failure z v bits)) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (hp bits) + exact ho.trans (he.trans (RootedComputedEstimator.sameLaw A C K j hC hj hK hW hB + delta failure z hz v phi)) + +theorem sameLaw_word (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon failure : ℚ) (he : 0 < epsilon) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance epsilon j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance epsilon j))) : + FiniteObservableTransport.SameLaw + (fun bits => TreeFraction.val (output (input + (scheduledContext A C K j (innerTolerance epsilon j) failure z v) (degree,depth) bits))) + (RootedOracleDensity.wordEstimate A (RootedCompletion.rowColumn A.T) C z K hK hW j + epsilon failure (RootedCatalogGrid.gridEquiv A K v)) := by + intro phi + have hs := sameLaw_estimateValue A C K j hC hj hK hW hB (innerTolerance epsilon j) + failure (innerTolerance_pos epsilon j he) hf z hz v degree depth hdegree hdepth phi + have he := uniformAverage_equiv (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure) + (fun draws => phi (RootedOracleDensity.estimateValue A (RootedCompletion.rowColumn A.T) + C z K hK hW j (innerTolerance epsilon j) failure (RootedCatalogGrid.gridEquiv A K v) draws)) + exact hs.trans he.symm + +theorem output_range (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance delta)) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance delta)) + (bits : Fin (wordWidth (scheduledContext A C K j delta failure z v)) → Bool) : + (CompanionOracleDensity.assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (TreeFraction.val (output (input (scheduledContext A C K j delta failure z v) + (degree,depth) bits)):ℝ) ∧ + (TreeFraction.val (output (input (scheduledContext A C K j delta failure z v) + (degree,depth) bits)):ℝ) ≤ 8*CompanionOracleDensity.assignmentCount A := by + rw [output,prepare_scheduled A C K j hC hK delta failure hd hf z v degree depth bits] + exact RootedEstimatorExecution.output_range A C K j hC hj hK hW hB delta failure hd hd1 hf + z hz v degree depth hdegree hdepth _ + +/-- The actual polynomial list program, on its prescribed finite word, +inherits the proved relative-error bound of the complete weight oracle. -/ +theorem output_failure (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance epsilon j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance epsilon j))) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + uniformAverage (fun bits : Fin (wordWidth + (scheduledContext A C K j (innerTolerance epsilon j) failure z v)) → Bool => + if (TreeFraction.val (output (input + (scheduledContext A C K j (innerTolerance epsilon j) failure z v) (degree,depth) bits)):ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z < + (TreeFraction.val (output (input + (scheduledContext A C K j (innerTolerance epsilon j) failure z v) (degree,depth) bits)):ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + let test := fun draws : RootedComputedEstimator.Inputs A C K j (innerTolerance epsilon j) failure => + if (TreeFraction.val (RootedEstimatorBlockProgram.output + (RootedEstimatorExecution.data A C K j (innerTolerance epsilon j) failure z v + degree depth draws)):ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A (RootedCompletion.rowColumn A.T) + ((j:ℝ)*C/height A C) z < + (TreeFraction.val (RootedEstimatorBlockProgram.output + (RootedEstimatorExecution.data A C K j (innerTolerance epsilon j) failure z v + degree depth draws)):ℝ) then (1:ℝ) else 0 + have he := uniformAverage_equiv + (scheduledEquiv A C K j (innerTolerance epsilon j) failure z v) test + have hp := prepare_scheduled A C K j hC hK (innerTolerance epsilon j) failure + (innerTolerance_pos epsilon j he0) hf z v degree depth + simp only [output] + simp_rw [hp] + exact he.trans_le (RootedEstimatorExecution.output_failure A C K j hC hj hK hW hB + epsilon failure he0 he1 hf z hz v degree depth hdegree hdepth hPL hCheeger) + +end +end ContingencyTables.RootedEstimatorWordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..515b040b6da585cfd97f8533b4b9540a48c499db --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordProgram.lean @@ -0,0 +1,234 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorLayoutProgram + +namespace OAI + +/-! # One flat word executes the complete weight estimator + +The number of generated rows is bounded by the supplied word length. +The binary schedule therefore remains safe even on malformed inputs. +-/ + +namespace ContingencyTables.RootedEstimatorWordProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open RootedEstimatorLayoutProgram + +abbrev Input := Context×((List Bool×List Bool)×List Bool) + +def phase (z : State×ℕ) : State := + ((z.1.1.1,((z.1.1.2.1.1,(z.1.1.2.1.2.1,z.2)),z.1.1.2.2)),z.1.2) +def phaseRealizer : Realizer phase := by + let k : Realizer (fun z : State×ℕ => z.1.1.1) := composition (composition first first) first + let dw : Realizer (fun z : State×ℕ => z.1.1.2.1.1) := + composition (composition (composition (composition first first) second) first) first + let c : Realizer (fun z : State×ℕ => z.1.1.2.1.2.1) := + composition (composition (composition (composition (composition first first) second) first) second) first + let demand : Realizer (fun z : State×ℕ => z.1.1.2.2) := + composition (composition (composition first first) second) second + exact pair (pair k (pair (pair dw (pair c second)) demand)) (composition first second) +lemma polynomial_phase : PolynomialTime phaseRealizer := by + unfold phaseRealizer + exact polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_first) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_first) polynomial_second) polynomial_first) + polynomial_second)) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second))) + (polynomial_composition polynomial_first polynomial_second) + +def ratioPrefix (z : Input) : List Bool := z.2.2.take (ratioBankWidth z.1) +def ratioPrefixRealizer : Realizer ratioPrefix := + composition (f := fun z : Input => (z.2.2,ratioBankWidth z.1)) + (g := fun p : List Bool×ℕ => p.1.take p.2) + (pair (composition second second) + (composition (f := fun z : Input => z.1) (g := ratioBankWidth) first ratioBankWidthRealizer)) takeFast +lemma polynomial_ratioPrefix : PolynomialTime ratioPrefixRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_first polynomial_ratioBankWidth)) polynomial_takeFast + +def ratioRows (z : Input) : List ℕ := completeWordRows (ratioBlockWidth z.1,ratioPrefix z) +def ratioRowsRealizer : Realizer ratioRows := + composition (f := fun z : Input => (ratioBlockWidth z.1,ratioPrefix z)) (g := completeWordRows) + (pair (composition (f := fun z : Input => z.1) (g := ratioBlockWidth) + first ratioBlockWidthRealizer) ratioPrefixRealizer) completeWordRowsRealizer +lemma polynomial_ratioRows : PolynomialTime ratioRowsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_ratioBlockWidth) polynomial_ratioPrefix) + polynomial_completeWordRows + +def ratioChunk (z : Input×ℕ) : List Bool := + wordChunk ((ratioBlockWidth z.1.1,ratioPrefix z.1),z.2) +def ratioChunkRealizer : Realizer ratioChunk := + composition (f := fun z : Input×ℕ => ((ratioBlockWidth z.1.1,ratioPrefix z.1),z.2)) + (g := wordChunk) + (pair (pair + (composition (f := fun z : Input×ℕ => z.1.1) (g := ratioBlockWidth) + (composition first first) ratioBlockWidthRealizer) + (composition (f := fun z : Input×ℕ => z.1) (g := ratioPrefix) first ratioPrefixRealizer)) + second) wordChunkRealizer +lemma polynomial_ratioChunk : PolynomialTime ratioChunkRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_ratioBlockWidth) + (polynomial_composition polynomial_first polynomial_ratioPrefix)) polynomial_second) + polynomial_wordChunk + +def ratioState (z : Input×ℕ) : State := phase (z.1.1.1,z.2) +def ratioStateRealizer : Realizer ratioState := + composition (f := fun z : Input×ℕ => (z.1.1.1,z.2)) (g := phase) + (pair (composition (composition first first) first) second) phaseRealizer +lemma polynomial_ratioState : PolynomialTime ratioStateRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) polynomial_phase + +def ratioWords (z : Input×ℕ) : List (List Bool) := wordChunks (ratioWidth z.1.1,ratioChunk z) +def ratioWordsRealizer : Realizer ratioWords := + composition (f := fun z : Input×ℕ => (ratioWidth z.1.1,ratioChunk z)) (g := wordChunks) + (pair (composition (f := fun z : Input×ℕ => z.1.1) (g := ratioWidth) + (composition first first) ratioWidthRealizer) ratioChunkRealizer) wordChunksRealizer +lemma polynomial_ratioWords : PolynomialTime ratioWordsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_ratioWidth) + polynomial_ratioChunk) polynomial_wordChunks + +def ratioBlock (z : Input×ℕ) : RootedEstimatorBlockProgram.RatioBlock := + (ratioWords z).map (fun bits => (ratioState z,bits)) +def ratioBlockRealizer : Realizer ratioBlock := + composition (f := fun z : Input×ℕ => (ratioState z,ratioWords z)) + (g := fun z : State×List (List Bool) => z.2.map (fun bits => (z.1,bits))) + (pair ratioStateRealizer ratioWordsRealizer) (mapWith identity) +lemma polynomial_ratioBlock : PolynomialTime ratioBlockRealizer := + polynomial_composition (polynomial_pair polynomial_ratioState polynomial_ratioWords) + (polynomial_mapWith polynomial_identity) + +def ratioBlocks (z : Input) : List RootedEstimatorBlockProgram.RatioBlock := + (ratioRows z).map (fun i => ratioBlock (z,i)) +def ratioBlocksRealizer : Realizer ratioBlocks := + composition (pair identity ratioRowsRealizer) (mapWith ratioBlockRealizer) +lemma polynomial_ratioBlocks : PolynomialTime ratioBlocksRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_ratioRows) + (polynomial_mapWith polynomial_ratioBlock) + +def correctionTail (z : Input) : List Bool := z.2.2.drop (ratioBankWidth z.1) +def correctionTailRealizer : Realizer correctionTail := + composition (f := fun z : Input => (z.2.2,ratioBankWidth z.1)) + (g := fun p : List Bool×ℕ => p.1.drop p.2) + (pair (composition second second) + (composition (f := fun z : Input => z.1) (g := ratioBankWidth) first ratioBankWidthRealizer)) dropFast +lemma polynomial_correctionTail : PolynomialTime correctionTailRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_first polynomial_ratioBankWidth)) polynomial_dropFast + +def correctionWords (z : Input) : List (List Bool) := + (wordChunks (correctionWidth z.1,correctionTail z)).take z.1.2.1.2 +def correctionWordsRealizer : Realizer correctionWords := by + let chunks : Realizer (fun z : Input => wordChunks (correctionWidth z.1,correctionTail z)) := + composition (f := fun z : Input => (correctionWidth z.1,correctionTail z)) (g := wordChunks) + (pair (composition (f := fun z : Input => z.1) (g := correctionWidth) + first correctionWidthRealizer) correctionTailRealizer) wordChunksRealizer + exact composition (f := fun z : Input => + (wordChunks (correctionWidth z.1,correctionTail z),z.1.2.1.2)) + (g := fun p : List (List Bool)×ℕ => p.1.take p.2) + (pair chunks (composition (composition (composition first second) first) second)) takeFast +lemma polynomial_correctionWords : PolynomialTime correctionWordsRealizer := by + unfold correctionWordsRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_correctionWidth) polynomial_correctionTail) + polynomial_wordChunks) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) polynomial_second)) + polynomial_takeFast + +def terminalState (z : Input) : State := phase (z.1.1,z.1.2.1.1) +def terminalStateRealizer : Realizer terminalState := + composition (f := fun z : Input => (z.1.1,z.1.2.1.1)) (g := phase) + (pair (composition first first) + (composition (composition (composition first second) first) first)) phaseRealizer +lemma polynomial_terminalState : PolynomialTime terminalStateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) polynomial_first)) + polynomial_phase + +def correctionSample (z : Input×List Bool) : RootedCorrectionSampleProgram.Input := + ((terminalState z.1,z.1.1.2.2.2), + (z.1.2.1,(z.2.take (correctionWalkWidth z.1.1),z.2.drop (correctionWalkWidth z.1.1)))) +def correctionSampleRealizer : Realizer correctionSample := by + let tw : Realizer (fun z : Input×List Bool => correctionWalkWidth z.1.1) := + composition (f := fun z : Input×List Bool => z.1.1) (g := correctionWalkWidth) + (composition first first) correctionWalkWidthRealizer + let args : Realizer (fun z : Input×List Bool => (z.2,correctionWalkWidth z.1.1)) := pair second tw + let terminal : Realizer (fun z : Input×List Bool => terminalState z.1) := + composition (f := fun z : Input×List Bool => z.1) (g := terminalState) first terminalStateRealizer + exact pair + (pair terminal (composition (composition (composition (composition first first) second) second) second)) + (pair (composition (composition first second) first) + (pair (composition args takeFast) (composition args dropFast))) +lemma polynomial_correctionSample : PolynomialTime correctionSampleRealizer := by + unfold correctionSampleRealizer + exact polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_terminalState) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) polynomial_second)) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_correctionWalkWidth)) polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_correctionWalkWidth)) polynomial_dropFast))) + +def correctionBlock (z : Input) : RootedEstimatorBlockProgram.CorrectionBlock := + (correctionWords z).map (fun bits => correctionSample (z,bits)) +def correctionBlockRealizer : Realizer correctionBlock := + composition (pair identity correctionWordsRealizer) (mapWith correctionSampleRealizer) +lemma polynomial_correctionBlock : PolynomialTime correctionBlockRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_correctionWords) + (polynomial_mapWith polynomial_correctionSample) + +def prepare (z : Input) : RootedEstimatorBlockProgram.Input := + ((assignmentCount z.1,ratioBlocks z),correctionBlock z) +def prepareRealizer : Realizer prepare := + pair (pair (composition (f := fun z : Input => z.1) (g := assignmentCount) + first assignmentCountRealizer) ratioBlocksRealizer) correctionBlockRealizer +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_assignmentCount) polynomial_ratioBlocks) + polynomial_correctionBlock + +attribute [local irreducible] prepare + +def output (z : Input) : TreeFraction.Fraction := RootedEstimatorBlockProgram.output (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := RootedEstimatorBlockProgram.output) + prepareRealizer RootedEstimatorBlockProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare RootedEstimatorBlockProgram.polynomial_output + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma phase_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + phase (RootedOracleWalkProgram.data A C 0 K z v,a)=RootedOracleWalkProgram.data A C a K z v := rfl + +end +end ContingencyTables.RootedEstimatorWordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e9905326b54eaece825cfbec2d3b0ff65a7eac3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWordSemantics.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordProgram +import OAI.Combinatorics.ContingencyTables.Counting.EstimatorWordBanks + +namespace OAI + +/-! # The executed estimator consumes exactly its independent sample banks -/ + +namespace ContingencyTables.RootedEstimatorWordProgram + +open MatchingFPRAS RootedEstimatorLayoutProgram +open DensePrograms GridBoundary +open scoped Classical + +abbrev Banks (c : Context) := EstimatorWordBanks.Banks c.2.1.1 c.2.1.2 + (ratioWidth c) (correctionWalkWidth c) (binWidth c) + +def wordEquiv (c : Context) : (Fin (wordWidth c) → Bool) ≃ Banks c := + EstimatorWordBanks.wordEquiv c.2.1.1 c.2.1.2 + (ratioWidth c) (correctionWalkWidth c) (binWidth c) + +def input (c : Context) (markers : List Bool×List Bool) + (bits : Fin (wordWidth c) → Bool) : Input := (c,(markers,List.ofFn bits)) + +def encodeBanks (state : State) (j h count : ℕ) (markers : List Bool×List Bool) + {S r t b : ℕ} (banks : EstimatorWordBanks.Banks j S r t b) : + RootedEstimatorBlockProgram.Input := + ((count,List.ofFn (fun a => List.ofFn (fun i => + (phase (state,a.val),List.ofFn (banks.1 a i))))), + List.ofFn (fun i => ((phase (state,j),h), + (markers,(List.ofFn (banks.2 i).1,List.ofFn (banks.2 i).2))))) + +def recodeBanks {j S r t b r' t' b' : ℕ} (hr : r=r') (ht : t=t') (hb : b=b') : + EstimatorWordBanks.Banks j S r t b ≃ EstimatorWordBanks.Banks j S r' t' b' := + Equiv.cast (by rw [hr,ht,hb]) + +lemma encodeBanks_recode {j S r t b r' t' b' : ℕ} (hr : r=r') (ht : t=t') (hb : b=b') + (state : State) (h count : ℕ) (markers : List Bool×List Bool) + (banks : EstimatorWordBanks.Banks j S r t b) : + encodeBanks state j h count markers (recodeBanks hr ht hb banks)= + encodeBanks state j h count markers banks := by + cases hr + cases ht + cases hb + rfl + +def bankInput (c : Context) (markers : List Bool×List Bool) (banks : Banks c) : + RootedEstimatorBlockProgram.Input := + encodeBanks c.1 c.2.1.1 c.2.2.2 (assignmentCount c) markers banks + +private lemma ratioBlock_input (c : Context) (markers : List Bool×List Bool) + (hr : 0 < ratioWidth c) (bits : Fin (wordWidth c) → Bool) (a : Fin c.2.1.1) : + ratioBlock (input c markers bits,a.val)=List.ofFn (fun i => + (phase (c.1,a.val),List.ofFn ((wordEquiv c bits).1 a i))) := by + change (DensePrograms.wordChunks (ratioWidth c, + DensePrograms.wordChunk ((c.2.1.2*ratioWidth c, + (List.ofFn bits).take (c.2.1.1*(c.2.1.2*ratioWidth c))),a.val))).map + (fun bs => (phase (c.1,a.val),bs))=_ + have hc := EstimatorWordBanks.ratio_chunks c.2.1.1 c.2.1.2 + (ratioWidth c) (correctionWalkWidth c) (binWidth c) hr bits a + have hm := congrArg (List.map (fun bs => (phase (c.1,a.val),bs))) hc + refine hm.trans ?_ + rw [List.map_ofFn] + rfl + +private lemma ratioBlocks_input (c : Context) (markers : List Bool×List Bool) + (hs : 0 < c.2.1.2) (hr : 0 < ratioWidth c) (bits : Fin (wordWidth c) → Bool) : + ratioBlocks (input c markers bits)=List.ofFn (fun a => List.ofFn (fun i => + (phase (c.1,a.val),List.ofFn ((wordEquiv c bits).1 a i)))) := by + have hrows : ratioRows (input c markers bits)=List.range c.2.1.1 := + EstimatorWordBanks.ratio_rows _ _ _ _ _ hs hr bits + unfold ratioBlocks + rw [hrows] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have hi' : i < c.2.1.1 := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + exact ratioBlock_input c markers hr bits ⟨i,hi'⟩ + +private lemma correctionBlock_input (c : Context) (markers : List Bool×List Bool) + (ht : 0 < correctionWidth c) (bits : Fin (wordWidth c) → Bool) : + correctionBlock (input c markers bits)=List.ofFn (fun i => + ((phase (c.1,c.2.1.1),c.2.2.2), + (markers,(List.ofFn ((wordEquiv c bits).2 i).1,List.ofFn ((wordEquiv c bits).2 i).2)))) := by + have hw : correctionWords (input c markers bits)=List.ofFn (fun i : Fin c.2.1.2 => + List.ofFn (gridWordEquiv c.2.1.2 (correctionWalkWidth c+binWidth c) + (FairBits.splitWordEquiv (c.2.1.1*(c.2.1.2*ratioWidth c)) + (c.2.1.2*(correctionWalkWidth c+binWidth c)) bits).2 i)) := + EstimatorWordBanks.correction_chunks _ _ _ _ _ ht bits + rw [correctionBlock,hw,List.map_ofFn] + apply congrArg List.ofFn + funext i + change ((phase (c.1,c.2.1.1),c.2.2.2), + (markers,((List.ofFn _).take (correctionWalkWidth c), + (List.ofFn _).drop (correctionWalkWidth c))))=_ + have htake := EstimatorWordBanks.correction_take c.2.1.1 c.2.1.2 + (ratioWidth c) (correctionWalkWidth c) (binWidth c) bits i + have hdrop := EstimatorWordBanks.correction_drop c.2.1.1 c.2.1.2 + (ratioWidth c) (correctionWalkWidth c) (binWidth c) bits i + exact congrArg (fun ws : List Bool × List Bool => + ((phase (c.1,c.2.1.1),c.2.2.2),(markers,ws))) (Prod.ext htake hdrop) + +/-- Every input bit belongs to exactly one prescribed sample word. +The positivity conditions merely ensure that complete-word parsing +retains all scheduled sample rows. -/ +theorem prepare_input (c : Context) (markers : List Bool×List Bool) + (hs : 0 < c.2.1.2) (hr : 0 < ratioWidth c) (ht : 0 < correctionWidth c) + (bits : Fin (wordWidth c) → Bool) : + prepare (input c markers bits)=bankInput c markers (wordEquiv c bits) := by + change ((assignmentCount c,ratioBlocks (input c markers bits)), + correctionBlock (input c markers bits))=_ + rw [ratioBlocks_input c markers hs hr bits,correctionBlock_input c markers ht bits] + rfl + +end ContingencyTables.RootedEstimatorWordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..141aa0788813fc55575875d1b3eb08e553a25e24 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedEstimatorWords.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorConfidence +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorRange +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorWords + +namespace OAI + +/-! # A single Boolean word for the literal companion weight estimator -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages FairBits +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def wordEstimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (epsilon failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool) : ℚ := + estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure bits) + +/-- The single fixed-length word has exactly the previously analyzed +independent-product law. -/ +theorem wordEstimate_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool => + if (wordEstimate A R C z K hK hW j epsilon failure v bits:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (wordEstimate A R C z K hK hW j epsilon failure v bits:ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + let test := fun draws : EstimatorInput A C K j (innerTolerance epsilon j) failure => + if (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z < + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0 + have he := uniformAverage_equiv + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure) test + change uniformAverage (fun bits => test + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure bits)) ≤ _ + exact he.trans_le + (estimateValue_failure A R C hC z hz K hK hW hB j hj epsilon failure he0 he1 hf hPL hCheeger v) + +theorem wordEstimate_range (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (wordEstimate A R C z K hK hW j epsilon failure v bits:ℝ) ∧ + (wordEstimate A R C z K hK hW j epsilon failure v bits:ℝ) ≤ 8*assignmentCount A := + estimateValue_range A R C hC z hz K hK hW hB j hj (innerTolerance epsilon j) failure + (innerTolerance_pos epsilon j he0) (innerTolerance_lt_one epsilon j he1) hf v _ + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFactorialApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFactorialApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..c64ae274047a743e3601e534047cc1d69a867428 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFactorialApplication.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountIdentification +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication + +namespace OAI + +/-! # Actual factorial lifts of the selected-root completion count -/ + +namespace ContingencyTables.RootedFactorialApplication + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS CompanionFactorialApplication +open LargePairEnumeration BalancedBox LabelledFactorial + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def f (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : Set (Labels A×Bool) → ℝ := + firstLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A) + +noncomputable def g (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : Set (Labels A×Bool) → ℝ := + secondLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A) + +/-- The manuscript's actual factorial lift is positive on its degree and +has its omission signature, derived from the literal count. -/ +theorem first_properties (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (ha : 0≤alpha) : + BinaryContraction.DegreePositive (f A R alpha) (Fintype.card (Labels A)) ∧ + BinaryContraction.OmissionProperty (f A R alpha) (Fintype.card (Labels A)) := by + change BinaryContraction.DegreePositive + (firstLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A)) _ ∧ + BinaryContraction.OmissionProperty + (firstLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A)) _ + constructor + · exact SliceFactorial.firstLift_degreePositive (TwoLiftStates.group (labelCell A)) + (RootedCountIdentification.h A R alpha) (denominator A) (Fintype.card (Labels A)) (denominator_positive A) + (fun z _ _ => RootedCountIdentification.h_positive A R alpha z) + · have hs : @RemovalSlice (View A) _ (Classical.decEq _) + (RootedCountIdentification.h A R alpha) (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) + (Fintype.card (Labels A)) := by + rw [label_capacity] + convert RootedCountIdentification.h_removal A R alpha ha _ using 1 + convert SliceFactorial.firstLift_omission_slice (TwoLiftStates.group (labelCell A)) + (RootedCountIdentification.h A R alpha) (denominator A) (Fintype.card (Labels A)) (denominator_positive A) + (fun z => (RootedCountIdentification.h_positive A R alpha z).le) hs using 1 + +/-- The dual factorial lift retains positivity and has its actual +addition signature from the globally reflected raw count. -/ +theorem second_properties (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (ha : 0≤alpha) : + BinaryContraction.DegreePositive (g A R alpha) (Fintype.card (Labels A)) ∧ + BinaryContraction.AdditionProperty (g A R alpha) (Fintype.card (Labels A)) := by + change BinaryContraction.DegreePositive + (secondLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A)) _ ∧ + BinaryContraction.AdditionProperty + (secondLift (TwoLiftStates.group (labelCell A)) (RootedCountIdentification.h A R alpha) (denominator A)) _ + constructor + · intro S _ + exact div_pos + (mul_pos (RootedCountIdentification.h_positive A R alpha _) (FactorialSignatures.factorialProduct_positive _)) + (denominator_positive A) + · have hs : @RemovalSlice (View A) _ (Classical.decEq _) + (fun z => RootedCountIdentification.h A R alpha (IntegerReflection.reflect + (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) z)) + (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) + (Fintype.card (Labels A×Bool)-Fintype.card (Labels A)) := by + rw [label_capacity] + convert RootedCountIdentification.h_reflected A R alpha ha _ using 1 + convert ReflectedSlices.secondLift_addition_reflected_slice (TwoLiftStates.group (labelCell A)) + (RootedCountIdentification.h A R alpha) (denominator A) (Fintype.card (Labels A)) + (by simp only [Fintype.card_prod,Fintype.card_bool]; omega) + (denominator_positive A) (fun z => (RootedCountIdentification.h_positive A R alpha z).le) hs using 1 + +/-- The actual paired-label chain has the required pointwise q=W² +comparison, with the source count appearing identically in both lifts. -/ +theorem chain_comparison (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (S : Set (Labels A×Bool)) + (hS : CommonBasesFPRAS.ChainState TwoLiftStates.pairs S) : + (1/(A.W:ℝ)^2)*f A R alpha S≤g A R alpha S ∧ g A R alpha S≤(A.W:ℝ)^2*f A R alpha S := by + apply TwoLiftStates.chain_lifts_compare (labelCell A) (RootedCountIdentification.h A R alpha) S hS A.W + (by have hW := A.hW; omega) + · intro s + rw [label_width] + exact A.hsmall _ _ s.property + · exact (RootedCountIdentification.h_positive A R alpha _).le + +end ContingencyTables.RootedFactorialApplication + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFarMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFarMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc6f9690d9ebba31d29a88367011ee874ffa840a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedFarMass.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalNormalizer + +namespace OAI + +/-! # Exponential far-penalty bound for the actual selected-root mass -/ + +namespace ContingencyTables.RootedFarMass + +open scoped BigOperators Classical +open CompanionFactorialApplication TreeMarginalSignature BalancedCellFibres + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def actualWeight (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (a : Profiles (cellWidth A)) : ℝ := + RootedPenalty.physicalWeight A R alpha (BalancedCellFibres.profile (cellWidth A) a) + +noncomputable def actualPenalty (A : Instance I J) (R : RootedCompletion.Selection A.T) (a : Profiles (cellWidth A)) : ℝ := + RootedPenalty.penalty A R (BalancedCellFibres.profile (cellWidth A) a) + +lemma weight_at_large_penalty (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (K : ℕ) + (a : Profiles (cellWidth A)) (ha : 4*(K:ℝ) ≤ alpha*actualPenalty A R a) : + actualWeight A R alpha a ≤ (2:ℝ)^(-(4*K:ℕ):ℝ) := by + unfold actualWeight + rw [RootedPenalty.exact_eq] + split_ifs + · apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + change -alpha*actualPenalty A R a ≤ -((4*K:ℕ):ℝ) + push_cast + linarith + · exact (Real.rpow_pos_of_pos (by norm_num : (0:ℝ) < 2) _).le + +/-- The true expanded physical box has at most 2^K summands, so the +entire terminal region whose penalty is at least 4K contributes at most +2^(-3K). Neither a table-count approximation nor an oracle is assumed. -/ +theorem far_mass_le (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (B K : ℕ) + (hW : 20*A.d ≤ A.W) (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) : + (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A R a + then actualWeight A R alpha a else 0) ≤ (2:ℝ)^(-(3*K:ℕ):ℝ) := by + have hcard : Fintype.card (Profiles (cellWidth A)) ≤ 2^K := + ForestBoxCardinality.cardinality_le_two_pow A hW B K hB hBK + have hcardR : (Fintype.card (Profiles (cellWidth A)):ℝ) ≤ (2:ℝ)^K := by exact_mod_cast hcard + have hp : 0 ≤ (2:ℝ)^(-(4*K:ℕ):ℝ) := (Real.rpow_pos_of_pos (by norm_num) _).le + calc + _ ≤ ∑ _a : Profiles (cellWidth A),(2:ℝ)^(-(4*K:ℕ):ℝ) := by + apply Finset.sum_le_sum + intro a _ + split_ifs with ha + · exact weight_at_large_penalty A R alpha K a ha + · exact hp + _ = (Fintype.card (Profiles (cellWidth A)):ℝ)*(2:ℝ)^(-(4*K:ℕ):ℝ) := by simp + _ ≤ (2:ℝ)^K*(2:ℝ)^(-(4*K:ℕ):ℝ) := mul_le_mul_of_nonneg_right hcardR hp + _ = _ := by + rw [← Real.rpow_natCast,← Real.rpow_add (by norm_num : (0:ℝ) < 2)] + congr 1 + push_cast + ring + +end ContingencyTables.RootedFarMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestCatalog.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestCatalog.lean new file mode 100644 index 0000000000000000000000000000000000000000..992e60296f374841623fa4fb91036a077d859fcc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestCatalog.lean @@ -0,0 +1,194 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCellDataProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCellCatalogProgram + +namespace OAI + +/-! # Computing the tree and free-cell catalogs + +Both catalogs scan the rectangular cell array. A free cell is selected +by its binary capacity and absence from the supplied forest graph; a +tree cell is selected by graph adjacency. Empty forests need no chosen +edge and are handled by the same program. +-/ + +namespace ContingencyTables.RootedForestCatalog + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open RootedCoefficientProgram FiniteGraphRootProgram +open scoped Classical + +abbrev Data := ((GraphCode×ℕ)×(List ℕ×List ℕ))×MatrixCode +abbrev Item := Data×(ℕ×ℕ) + +def edge (z : Item) : GraphCode×(ℕ×ℕ) := + (z.1.1.1.1,(z.2.1,z.1.1.2.1.length+z.2.2)) +def edgeRealizer : Realizer edge := + pair (composition (composition (composition first first) first) first) + (pair (composition second first) + (composition (pair (composition (composition (composition (composition first first) second) first) + listLength) (composition second second)) add)) +lemma polynomial_edge : PolynomialTime edgeRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + polynomial_listLength) + (polynomial_composition polynomial_second polynomial_second)) polynomial_add)) + +def treeTest (z : Item) : Bool := adjacent (edge z) +def treeTestRealizer : Realizer treeTest := composition edgeRealizer adjacentRealizer +lemma polynomial_treeTest : PolynomialTime treeTestRealizer := + polynomial_composition polynomial_edge polynomial_adjacent + +def largeTest (z : Item) : Bool := + decide (z.1.1.1.2 ≤ matrixEntry (z.1.2,z.2)) +def largeTestRealizer : Realizer largeTest := + composition (pair (composition (composition (composition first first) first) second) + (composition (pair (composition first second) second) matrixEntryRealizer)) leNat +lemma polynomial_largeTest : PolynomialTime largeTestRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_matrixEntry)) polynomial_leNat + +def freeTest (z : Item) : Bool := largeTest z && !treeTest z +def freeTestRealizer : Realizer freeTest := + composition (pair largeTestRealizer (composition treeTestRealizer boolNot)) boolAnd +lemma polynomial_freeTest : PolynomialTime freeTestRealizer := + polynomial_composition (polynomial_pair polynomial_largeTest + (polynomial_composition polynomial_treeTest polynomial_boolNot)) polynomial_boolAnd + +def selectedTest (z : (Data×Bool)×(ℕ×ℕ)) : Bool := + if z.1.2 then treeTest (z.1.1,z.2) else freeTest (z.1.1,z.2) +def selectedTestRealizer : Realizer selectedTest := + choose (composition first second) + (composition (f := fun z : (Data×Bool)×(ℕ×ℕ) => (z.1.1,z.2)) (g := treeTest) + (pair (composition first first) second) treeTestRealizer) + (composition (f := fun z : (Data×Bool)×(ℕ×ℕ) => (z.1.1,z.2)) (g := freeTest) + (pair (composition first first) second) freeTestRealizer) +lemma polynomial_selectedTest : PolynomialTime selectedTestRealizer := + polynomial_choose (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_treeTest) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_freeTest) + +def catalog (z : Data×Bool) : List (ℕ×ℕ) := + (cellPairs z.1.1.2).filter (fun a => selectedTest (z,a)) +def catalogRealizer : Realizer catalog := + composition (pair identity (composition (composition (composition first first) second) + cellPairsRealizer)) (filterWith selectedTestRealizer) +theorem polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_first + polynomial_first) polynomial_second) polynomial_cellPairs)) + (polynomial_filterWith polynomial_selectedTest) + +lemma catalog_nodup (z : Data×Bool) : (catalog z).Nodup := + (cellPairs_nodup z.1.1.2.1 z.1.1.2.2).filter _ + +open CompanionFactorialApplication ForestAssignmentSplit GraphCompletionCounts + +noncomputable def data {m n : ℕ} (A : Instance (Fin m) (Fin n)) : Data := + (((graphCode (A.T.comap finSumFinEquiv.symm),A.W), + (List.ofFn (fun i => (A.r i).toNat),List.ofFn (fun j => (A.c j).toNat))),matrixCode A.b) + +lemma treeTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (i : Fin m) (j : Fin n) : + treeTest (data A,(i.val,j.val))=decide (A.T.Adj (.inl i) (.inr j)) := by + change adjacent (graphCode (A.T.comap finSumFinEquiv.symm), + (i.val,(List.ofFn (fun k => (A.r k).toNat)).length+j.val))=_ + rw [List.length_ofFn] + have he := adjacent_graph (A.T.comap finSumFinEquiv.symm) + (finSumFinEquiv (m := m) (n := n) (.inl i)) + (finSumFinEquiv (m := m) (n := n) (.inr j)) + simpa only [SimpleGraph.comap_adj,Equiv.symm_apply_apply,finSumFinEquiv_apply_left, + finSumFinEquiv_apply_right,Fin.val_castAdd,Fin.val_natAdd, + finSumFinEquiv_symm_apply_castAdd,finSumFinEquiv_symm_apply_natAdd] using he + +lemma freeTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (i : Fin m) (j : Fin n) : + freeTest (data A,(i.val,j.val))= + decide (A.small i j=false ∧ ¬A.T.Adj (.inl i) (.inr j)) := by + have hlarge : A.W≤A.b i j ↔ A.small i j=false := by + cases hs : A.small i j with + | false => exact ⟨fun _ => rfl,fun _ => (A.hlarge _ _ hs).1⟩ + | true => simp only [Bool.true_eq_false,iff_false]; exact Nat.not_le.mpr (A.hsmall _ _ hs) + unfold freeTest largeTest + rw [treeTest_data] + simp only [data,matrixEntry_code] + apply Bool.eq_iff_iff.mpr + simp only [Bool.and_eq_true,Bool.not_eq_true',decide_eq_true_eq,decide_eq_false_iff_not,hlarge] + +def Selected {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) (a : Fin m×Fin n) : Prop := + if tree then A.T.Adj (.inl a.1) (.inr a.2) + else A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + +abbrev Cell {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) := + {a : Fin m×Fin n // Selected A tree a} + +lemma selectedTest_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) + (i : Fin m) (j : Fin n) : + selectedTest ((data A,tree),(i.val,j.val))=decide (Selected A tree (i,j)) := by + cases tree <;> simp only [selectedTest,Selected,Bool.false_eq_true,ite_false,ite_true, + treeTest_data,freeTest_data] + +lemma mem_catalog_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) + (ij : ℕ×ℕ) : ij∈catalog (data A,tree) ↔ ∃ a : Cell A tree,(a.val.1.val,a.val.2.val)=ij := by + rw [catalog,List.mem_filter] + change (ij∈cellPairs (List.ofFn (fun i => (A.r i).toNat), + List.ofFn (fun j => (A.c j).toNat)) ∧ selectedTest ((data A,tree),ij)=true) ↔ _ + rw [mem_cellPairs] + simp only [List.length_ofFn] + constructor + · rintro ⟨⟨hi,hj⟩,hs⟩ + let i : Fin m := ⟨ij.1,hi⟩ + let j : Fin n := ⟨ij.2,hj⟩ + have hp : Selected A tree (i,j) := by + apply of_decide_eq_true + rwa [←selectedTest_data] + exact ⟨⟨(i,j),hp⟩,rfl⟩ + · rintro ⟨a,rfl⟩ + exact ⟨⟨a.val.1.isLt,a.val.2.isLt⟩, + (selectedTest_data A tree a.val.1 a.val.2).trans (decide_eq_true a.property)⟩ + +noncomputable def catalogCell {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) + (i : Fin (catalog (data A,tree)).length) : Cell A tree := + Classical.choose ((mem_catalog_data A tree _).mp (List.getElem_mem i.isLt)) + +lemma catalogCell_coordinates {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) + (i : Fin (catalog (data A,tree)).length) : + ((catalogCell A tree i).val.1.val,(catalogCell A tree i).val.2.val)= + (catalog (data A,tree))[i.val] := + Classical.choose_spec ((mem_catalog_data A tree _).mp (List.getElem_mem i.isLt)) + +lemma catalogCell_bijective {m n : ℕ} (A : Instance (Fin m) (Fin n)) (tree : Bool) : + Function.Bijective (catalogCell A tree) := by + constructor + · intro i j h + have he := congrArg (fun a : Cell A tree => (a.val.1.val,a.val.2.val)) h + rw [catalogCell_coordinates,catalogCell_coordinates] at he + exact Fin.ext ((catalog_nodup (data A,tree)).getElem_inj_iff.mp he) + · intro a + have hm : (a.val.1.val,a.val.2.val)∈catalog (data A,tree) := + (mem_catalog_data A tree _).mpr ⟨a,rfl⟩ + obtain ⟨i,hi,hval⟩ := List.mem_iff_getElem.mp hm + refine ⟨⟨i,hi⟩,?_⟩ + have he := (catalogCell_coordinates A tree ⟨i,hi⟩).trans hval + apply Subtype.ext + exact Prod.ext (Fin.ext (congrArg Prod.fst he)) (Fin.ext (congrArg Prod.snd he)) + +noncomputable def freeEquiv {m n : ℕ} (A : Instance (Fin m) (Fin n)) : + Fin (catalog (data A,false)).length ≃ FreeCell A.small A.T := + Equiv.ofBijective (catalogCell A false) (catalogCell_bijective A false) + +noncomputable def treeEquiv {m n : ℕ} (A : Instance (Fin m) (Fin n)) : + Fin (catalog (data A,true)).length ≃ TreeCell A.T := + Equiv.ofBijective (catalogCell A true) (catalogCell_bijective A true) + +end ContingencyTables.RootedForestCatalog + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestDataProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestDataProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d723a5e5cbbfd2176ffc481c3a7e098bc2212303 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestDataProgram.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOffsetProgram + +namespace OAI + +/-! # Preparing a tree penalty from executed coefficients and offsets + +All signed affine data are computed internally from the graph, capacities, +baseline and two stored views. Only ordinary cell indices and values occur +in the input; no affine coefficient or offset is supplied. +-/ + +namespace ContingencyTables.RootedForestDataProgram + +open MatchingFPRAS.TreeTyped SignedPairProgram +open scoped Classical + +abbrev TermInput := RootedCoefficientProgram.Input×ℕ +abbrev Input := ((ℕ×ℕ)×RootedOffsetProgram.Input)×List TermInput + +def scale (z : ℕ×Signed) : Signed := + SignedPairProgram.normalize (times ((z.1,0),z.2)) + +def scaleRealizer : Realizer scale := + composition (f := fun z : ℕ×Signed => times ((z.1,0),z.2)) + (g := SignedPairProgram.normalize) + (composition (f := fun z : ℕ×Signed => ((z.1,0),z.2)) (g := times) + (pair (pair first (constant 0)) second) timesRealizer) normalizeRealizer + +lemma polynomial_scale : PolynomialTime scaleRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_pair polynomial_first (polynomial_constant 0)) polynomial_second) + polynomial_times) polynomial_normalize + +lemma scale_value (n : ℕ) (z : Signed) : + scale (n,z)=ForestAffineProgram.signedParts ((n:ℤ)*value z) := by + rw [scale,normalize_eq,value_times] + rfl + +def term (z : TermInput) : ForestAffineProgram.Term := + (scale (z.1.2.2+1,RootedCoefficientProgram.coefficient z.1),z.2) + +def termRealizer : Realizer term := + pair + (composition (f := fun z : TermInput => + (z.1.2.2+1,RootedCoefficientProgram.coefficient z.1)) (g := scale) (pair + (composition (composition (composition first second) second) successor) + (composition (f := fun z : TermInput => z.1) (g := RootedCoefficientProgram.coefficient) + first RootedCoefficientProgram.coefficientRealizer)) scaleRealizer) + second + +lemma polynomial_term : PolynomialTime termRealizer := + polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_successor) + (polynomial_composition polynomial_first RootedCoefficientProgram.polynomial_coefficient)) + polynomial_scale) polynomial_second + +def numeratorOffset (z : Input) : Signed := + scale (z.1.1.1,RootedOffsetProgram.offset z.1.2) + +def numeratorOffsetRealizer : Realizer numeratorOffset := + composition (f := fun z : Input => (z.1.1.1,RootedOffsetProgram.offset z.1.2)) (g := scale) + (pair (composition (composition first first) first) + (composition (f := fun z : Input => z.1.2) (g := RootedOffsetProgram.offset) + (composition first second) RootedOffsetProgram.offsetRealizer)) scaleRealizer + +lemma polynomial_numeratorOffset : PolynomialTime numeratorOffsetRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + RootedOffsetProgram.polynomial_offset)) polynomial_scale + +def prepare (z : Input) : ForestAffineProgram.Input := + ((numeratorOffset z,z.2.map term),z.1.1.1*z.1.1.2) + +def prepareRealizer : Realizer prepare := + pair (pair numeratorOffsetRealizer (composition second (map termRealizer))) + (composition (composition first first) multiply) + +theorem polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair polynomial_numeratorOffset + (polynomial_composition polynomial_second (polynomial_map polynomial_term))) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_multiply) + +open CompanionFactorialApplication RootedCompletion RootedIntegerEvaluation ForestAssignmentSplit + +lemma term_input {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (a : Fin m×Fin n) (v : ℕ) : + term (RootedCoefficientProgram.input A t a,v)= + (ForestAffineProgram.signedParts + (RootedIntegerEvaluation.coefficient A (rowColumn A.T) t a*((A.b a.1 a.2:ℤ)+1)),v) := by + unfold term + rw [scale_value,RootedCoefficientProgram.coefficient_input] + simp only [RootedCoefficientProgram.input,Nat.cast_add,Nat.cast_one] + congr 2 + ring + +noncomputable def data {m n nc nf : ℕ} (A : Instance (Fin m) (Fin n)) + (B : ℕ) (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (cells : Fin nc ≃ Fin m×Fin n) (free : Fin nf ≃ FreeCell A.small A.T) + (v : FreeCell A.small A.T → ℕ) : Input := + (((B,A.b t.val.1 t.val.2),RootedOffsetProgram.data A t x q cells), + List.ofFn (fun i => (RootedCoefficientProgram.input A t (free i).val,v (free i)))) + +/-- The generated binary input equals the exact affine tree input used +by the selected-root penalty evaluation. -/ +theorem prepare_data {m n nc nf : ℕ} (A : Instance (Fin m) (Fin n)) + (B : ℕ) (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (cells : Fin nc ≃ Fin m×Fin n) (free : Fin nf ≃ FreeCell A.small A.T) + (v : FreeCell A.small A.T → ℕ) : + prepare (data A B t x q cells free v)= + RootedIntegerEvaluation.forestData A (rowColumn A.T) B t x q free v := by + have ht : (List.ofFn (fun i : Fin nf => + (RootedCoefficientProgram.input A t (free i).val,v (free i)))).map term= + List.ofFn (fun i : Fin nf => (ForestAffineProgram.signedParts + (RootedIntegerEvaluation.coefficient A (rowColumn A.T) t (free i).val* + ((A.b (free i).val.1 (free i).val.2:ℤ)+1)),v (free i))) := by + rw [List.map_ofFn] + congr 1 + funext i + exact term_input A t (free i).val (v (free i)) + unfold prepare numeratorOffset data RootedIntegerEvaluation.forestData ForestAffineProgram.data + rw [RootedOffsetProgram.offset_data,scale_value,ht] + simp only [RootedOffsetProgram.value_parts] + +theorem evaluate_prepare {m n nc nf : ℕ} (A : Instance (Fin m) (Fin n)) + (B : ℕ) (hB : 0 (v f:ℚ)) t) + (rationalScaledTree A (rowColumn A.T) B x q (fun f => (v f:ℚ)) t-1)) := by + rw [prepare_data] + exact evaluate_forest A (rowColumn A.T) B hB t x q free v + +end ContingencyTables.RootedForestDataProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestPrepareProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestPrepareProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..17ca9d2f7f966194c53dfc2c85f5a0098ad57a28 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedForestPrepareProgram.lean @@ -0,0 +1,228 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeInputProgram + +namespace OAI + +/-! # Preparing the whole selected-root forest penalty + +The program takes the four cell arrays and the graph. It computes the +root discrepancy, both catalogs, every cut coefficient and every affine +offset before invoking the rational penalty evaluator. +-/ + +namespace ContingencyTables.RootedForestPrepareProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open scoped Classical + +abbrev Context := RootedDemandProgram.Input +abbrev TreeInput := ((Context×ℕ)×List ℕ)×(ℕ×ℕ) +abbrev Input := ((ℕ×ℕ)×Context)×List ℕ + +def treeFrame (z : TreeInput) : RootedCellDataProgram.Input := + RootedTreeInputProgram.treeInput (z.1.1.1,z.2) +def treeFrameRealizer : Realizer treeFrame := + composition (f := fun z : TreeInput => (z.1.1.1,z.2)) + (g := RootedTreeInputProgram.treeInput) + (pair (composition (composition first first) first) second) + RootedTreeInputProgram.treeInputRealizer +lemma polynomial_treeFrame : PolynomialTime treeFrameRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) RootedTreeInputProgram.polynomial_treeInput + +def freeCells (z : TreeInput) : List (ℕ×ℕ) := + RootedForestCatalog.catalog (z.1.1.1.1,false) +def freeCellsRealizer : Realizer freeCells := + composition (f := fun z : TreeInput => (z.1.1.1.1,false)) + (g := RootedForestCatalog.catalog) + (pair (composition (composition (composition first first) first) first) + (constant false)) RootedForestCatalog.catalogRealizer +lemma polynomial_freeCells : PolynomialTime freeCellsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_first) (polynomial_constant false)) RootedForestCatalog.polynomial_catalog + +def widthCapacity (z : TreeInput) : ℕ×ℕ := + (z.1.1.2,matrixEntry (z.1.1.1.1.2,z.2)) +def widthCapacityRealizer : Realizer widthCapacity := + pair (composition (composition first first) second) + (composition (f := fun z : TreeInput => (z.1.1.1.1.2,z.2)) + (g := matrixEntry) + (pair (composition (composition (composition (composition first first) first) first) + second) second) matrixEntryRealizer) +lemma polynomial_widthCapacity : PolynomialTime widthCapacityRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_first) polynomial_second) polynomial_second) polynomial_matrixEntry) + +def forestInput (z : TreeInput) : RootedForestDataProgram.Input := + ((widthCapacity z,RootedCellDataProgram.offsetInput (treeFrame z)), + RootedTreeInputProgram.terms ((treeFrame z,freeCells z),z.1.2)) +def forestInputRealizer : Realizer forestInput := + pair (pair widthCapacityRealizer + (composition (f := treeFrame) (g := RootedCellDataProgram.offsetInput) + treeFrameRealizer RootedCellDataProgram.offsetInputRealizer)) + (composition (f := fun z : TreeInput => ((treeFrame z,freeCells z),z.1.2)) + (g := RootedTreeInputProgram.terms) + (pair (pair treeFrameRealizer freeCellsRealizer) (composition first second)) + RootedTreeInputProgram.termsRealizer) +lemma polynomial_forestInput : PolynomialTime forestInputRealizer := + polynomial_pair (polynomial_pair polynomial_widthCapacity + (polynomial_composition polynomial_treeFrame RootedCellDataProgram.polynomial_offsetInput)) + (polynomial_composition (polynomial_pair + (polynomial_pair polynomial_treeFrame polynomial_freeCells) + (polynomial_composition polynomial_first polynomial_second)) + RootedTreeInputProgram.polynomial_terms) + +def prepareTree (z : TreeInput) : ForestAffineProgram.Input := + RootedForestDataProgram.prepare (forestInput z) +def prepareTreeRealizer : Realizer prepareTree := + composition (f := forestInput) (g := RootedForestDataProgram.prepare) + forestInputRealizer RootedForestDataProgram.prepareRealizer +lemma polynomial_prepareTree : PolynomialTime prepareTreeRealizer := + polynomial_composition polynomial_forestInput RootedForestDataProgram.polynomial_prepare + +def treeBundle (z : Input) : (Context×ℕ)×List ℕ := ((z.1.2,z.1.1.2),z.2) +def treeBundleRealizer : Realizer treeBundle := + pair (pair (composition first second) (composition (composition first first) second)) second +lemma polynomial_treeBundle : PolynomialTime treeBundleRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_second + +def treeCells (z : Input) : List (ℕ×ℕ) := + RootedForestCatalog.catalog (z.1.2.1,true) +def treeCellsRealizer : Realizer treeCells := + composition (f := fun z : Input => (z.1.2.1,true)) (g := RootedForestCatalog.catalog) + (pair (composition (composition first second) first) (constant true)) + RootedForestCatalog.catalogRealizer +lemma polynomial_treeCells : PolynomialTime treeCellsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) (polynomial_constant true)) RootedForestCatalog.polynomial_catalog + +def prepareTrees (z : Input) : List ForestAffineProgram.Input := + (treeCells z).map (fun a => prepareTree (treeBundle z,a)) +def prepareTreesRealizer : Realizer prepareTrees := + composition (f := fun z : Input => (treeBundle z,treeCells z)) + (g := fun z => z.2.map (fun a => prepareTree (z.1,a))) + (pair treeBundleRealizer treeCellsRealizer) (mapWith prepareTreeRealizer) +lemma polynomial_prepareTrees : PolynomialTime prepareTreesRealizer := + polynomial_composition (polynomial_pair polynomial_treeBundle polynomial_treeCells) + (polynomial_mapWith polynomial_prepareTree) + +def prepare (z : Input) : ForestPenaltyProgram.Input := + ((z.1.1.1,RootedDemandProgram.rootCount z.1.2),prepareTrees z) +def prepareRealizer : Realizer prepare := + pair (pair (composition (composition first first) first) + (composition (f := fun z : Input => z.1.2) (g := RootedDemandProgram.rootCount) + (composition first second) RootedDemandProgram.rootCountRealizer)) prepareTreesRealizer +theorem polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + RootedDemandProgram.polynomial_rootCount)) polynomial_prepareTrees + +def penaltyCode (z : Input) : MatchingFPRAS.TreeFraction.Fraction := + ForestPenaltyProgram.penaltyCode (prepare z) +def penaltyCodeRealizer : Realizer penaltyCode := + composition (f := prepare) (g := ForestPenaltyProgram.penaltyCode) + prepareRealizer ForestPenaltyProgram.penaltyCodeRealizer +theorem polynomial_penaltyCode : PolynomialTime penaltyCodeRealizer := + polynomial_composition polynomial_prepare ForestPenaltyProgram.polynomial_penaltyCode + +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit + +noncomputable def data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C B : ℕ) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : Input := + (((C,B),RootedDemandProgram.data A x q), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))) + +theorem forestInput_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (B : ℕ) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (v : FreeCell A.small A.T → ℕ) : + forestInput (((RootedDemandProgram.data A x q,B), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))), + (t.val.1.val,t.val.2.val))= + RootedForestDataProgram.data A B t (fun i j => (x i j:ℤ)) + (fun i j => (q i j:ℤ)) finProdFinEquiv.symm + (RootedForestCatalog.freeEquiv A) v := by + unfold forestInput RootedForestDataProgram.data + apply Prod.ext + · apply Prod.ext + · simp only [widthCapacity,RootedDemandProgram.data, + RootedForestCatalog.data,matrixEntry_code] + · rw [treeFrame,RootedTreeInputProgram.treeInput_data, + RootedCellDataProgram.offsetInput_data] + · exact RootedTreeInputProgram.terms_data A t x q v + +theorem prepareTree_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (B : ℕ) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (v : FreeCell A.small A.T → ℕ) : + prepareTree (((RootedDemandProgram.data A x q,B), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))), + (t.val.1.val,t.val.2.val))= + RootedIntegerEvaluation.forestData A (rowColumn A.T) B t + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) + (RootedForestCatalog.freeEquiv A) v := by + rw [prepareTree,forestInput_data,RootedForestDataProgram.prepare_data] + +lemma treeCatalog_ofFn {m n : ℕ} (A : Instance (Fin m) (Fin n)) : + RootedForestCatalog.catalog (RootedForestCatalog.data A,true)= + List.ofFn (fun i => (((RootedForestCatalog.treeEquiv A) i).val.1.val, + ((RootedForestCatalog.treeEquiv A) i).val.2.val)) := by + apply List.ext_getElem + · simp only [List.length_ofFn] + · intro i hi hj + simp only [List.getElem_ofFn] + exact (RootedForestCatalog.catalogCell_coordinates A true ⟨i,hi⟩).symm + +theorem prepare_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C : ℕ) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : + prepare (data A C (CompanionOracleDensity.rationalBinWidth A C) x q v)= + RootedPenaltyProgram.data A (rowColumn A.T) C + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) + (RootedForestCatalog.treeEquiv A) (RootedForestCatalog.freeEquiv A) v := by + have ht : prepareTrees (data A C (CompanionOracleDensity.rationalBinWidth A C) x q v)= + List.ofFn (fun i => RootedIntegerEvaluation.forestData A (rowColumn A.T) + (CompanionOracleDensity.rationalBinWidth A C) (RootedForestCatalog.treeEquiv A i) + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) + (RootedForestCatalog.freeEquiv A) v) := by + change (RootedForestCatalog.catalog (RootedForestCatalog.data A,true)).map + (fun a => prepareTree + (((RootedDemandProgram.data A x q,CompanionOracleDensity.rationalBinWidth A C), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))),a))=_ + have hc := congrArg (fun cells : List (ℕ×ℕ) => cells.map + (fun a => prepareTree + (((RootedDemandProgram.data A x q,CompanionOracleDensity.rationalBinWidth A C), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))),a))) + (treeCatalog_ofFn A) + refine hc.trans ?_ + rw [List.map_ofFn] + apply congrArg List.ofFn + funext i + exact prepareTree_data A _ (RootedForestCatalog.treeEquiv A i) x q v + unfold prepare RootedPenaltyProgram.data + apply Prod.ext + · exact congrArg (fun r => (C,r)) (RootedDemandProgram.rootCount_data A x q) + · exact ht + +theorem penaltyCode_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C : ℕ) + (hC : 0 (x i j:ℤ)) (fun i j => (q i j:ℤ)) (fun f => (v f:ℚ)) := by + rw [penaltyCode,prepare_data] + exact RootedPenaltyProgram.penaltyCode_data A (rowColumn A.T) C hC _ _ + (RootedForestCatalog.treeEquiv A) (RootedForestCatalog.freeEquiv A) v + +end ContingencyTables.RootedForestPrepareProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryConfidence.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryConfidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..7fa6b82a148fcc1bcbb384be0b7b638d8d1d2d01 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryConfidence.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedHistoryStep +import OAI.Combinatorics.ContingencyTables.Transport.FiniteUniformHistory + +namespace OAI + +/-! # Success probability of the actual adaptive selected-root history -/ + +namespace ContingencyTables.RootedHistoryConfidence + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity RootedPhaseHistory RootedStoredHistory RootedHistoryStep +open CompanionTraceWords (eventIndicator) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma success_of_failure {X : Type*} [Fintype X] [Nonempty X] + (P : X → Prop) (e : ℝ) + (hf : uniformAverage (fun x => eventIndicator (¬P x)) ≤ e) : + 1-e ≤ uniformAverage (fun x => if P x then (1:ℝ) else 0) := by + have hpoint (x : X) : (if P x then (1:ℝ) else 0)+eventIndicator (¬P x)=1 := by + by_cases hx : P x <;> simp [eventIndicator,hx] + have hadd := uniformAverage_add (fun x => if P x then (1:ℝ) else 0) + (fun x => eventIndicator (¬P x)) + simp_rw [hpoint] at hadd + rw [uniformAverage_const] at hadd + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +def GoodWords (A : Instance I J) (R : RootedCompletion.Selection A.T) + (s : Settings A) (eta : ℝ) (words : List (Word A s)) : Prop := + Good A R s.xi eta (decoded A R s words) + +lemma error_nonnegative (A : Instance I J) (s : Settings A) (eta : ℝ) + (hx : 0 ≤ s.xi) (j : ℕ) : 0 ≤ error A s eta j := by + have hxR : (0:ℝ) ≤ (s.xi:ℝ) := by exact_mod_cast hx + unfold error ObservableBounds.observableConstant + positivity + +/-- Each conditional probability is proved from the actual finite-word +phase; independent word histories then accumulate these losses. -/ +theorem history_success (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (hC : 0 < s.C) (hB : (s.K:ℝ)=binWidth A s.C) + (hH : s.H ≤ rationalHeight A s.C) + (hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ (2:ℝ)^s.L) + (hx0 : 0 < s.xi) (hx1 : s.xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) s.K)) + (hp : 0 < Fintype.card (Labels A)) (hn : 0 < s.n) + (eta : ℝ) (he0 : 0 < eta) (he1 : eta ≤ 1/4) : + 1-(s.H:ℝ)*error A s eta s.H ≤ + uniformAverage (fun words : Fin s.H → Word A s => + if GoodWords A R s eta (List.ofFn words) then (1:ℝ) else 0) := by + apply FiniteUniformHistory.good_probability (GoodWords A R s eta) s.H + (error A s eta s.H) (error_nonnegative A s eta hx0.le s.H) + · intro words hgood hlen + have hgood' : Good A R s.xi eta (decoded A R s words) := hgood + have hj : (decoded A R s words).length + eventIndicator (¬GoodWords A R s eta (words++[bits]))) ≤ error A s eta s.H := by + have heq : (fun bits : Word A s => eventIndicator (¬GoodWords A R s eta (words++[bits])))= + (fun bits : Word A s => eventIndicator (¬RootedPhaseTrial.ValidOutput A R words.length + (lookup A (decoded A R s words) words.length) s.xi eta + (step A R s (decoded A R s words) bits))) := by + funext bits + rw [hg bits] + rw [heq] + simpa only [decoded_length] using hf' + exact success_of_failure _ _ hf'' + · change Good A R s.xi eta (decoded A R s []) + rw [decoded_nil] + exact good_nil A R s.xi eta + +end +end ContingencyTables.RootedHistoryConfidence + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1bc3128327986a90c55a01b5e6bce9db8b044dc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedHistoryStep.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseHistory +import OAI.Combinatorics.ContingencyTables.Transport.FinitePaddedAverage + +namespace OAI + +/-! # Conditional accuracy of each actual adaptive outer phase -/ + +namespace ContingencyTables.RootedHistoryStep + +open CommonBasesFPRAS FirstSuccess FairBits CompanionFactorialApplication +open CompanionRationalUpdates CompanionOracleDensity RootedPhaseHistory RootedStoredHistory +open CompanionPhaseWords (Stored) +open CompanionTraceWords (eventIndicator) +open CompanionTargetMixing (restartTime) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma default_failure {X : Type*} (o : Option X) (d : X) (P : X → Prop) : + eventIndicator (¬P (o.getD d)) ≤ + eventIndicator (¬∃ x,o=some x ∧ P x) := by + cases o with + | none => by_cases hd : P d <;> simp [eventIndicator,hd] + | some x => by_cases hx : P x <;> simp [eventIndicator,hx] + +variable {I J : Type} [Fintype I] [Fintype J] + +def error (A : Instance I J) (s : Settings A) (eta : ℝ) (j : ℕ) : ℝ := + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((s.N+1:ℕ):ℝ)*eta^2)+ + (s.N:ℝ)*((6*(s.xi:ℝ)+1/(2:ℝ)^s.k)/2)+ + 2*(1/(2:ℝ)^s.h+(j:ℝ)*((restartTime A s.H s.L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(s.n:ℝ)+ + ((s.n+1:ℕ):ℝ)*((6*(s.xi:ℝ)+1/(2:ℝ)^s.k)/2))))+ + 2*((s.N+1:ℕ):ℝ)*(s.xi:ℝ) + +lemma error_mono (A : Instance I J) (s : Settings A) (eta : ℝ) (j l : ℕ) + (hj : j ≤ l) (hx : 0 ≤ s.xi) : error A s eta j ≤ error A s eta l := by + have hxR : (0:ℝ) ≤ (s.xi:ℝ) := by exact_mod_cast hx + have hcoef : 0 ≤ (restartTime A s.H s.L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(s.n:ℝ)+ + ((s.n+1:ℕ):ℝ)*((6*(s.xi:ℝ)+1/(2:ℝ)^s.k)/2)) := by positivity + have hmul := mul_le_mul_of_nonneg_right (show (j:ℝ) ≤ l by exact_mod_cast hj) hcoef + unfold error + linarith + +/-- On each good past history, the actual next stored value fails the +source update conditions with the proved common error bound. -/ +theorem step_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (hC : 0 < s.C) (hB : (s.K:ℝ)=binWidth A s.C) + (hH : s.H ≤ rationalHeight A s.C) + (hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ (2:ℝ)^s.L) + (hx0 : 0 < s.xi) (hx1 : s.xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) s.K)) + (hp : 0 < Fintype.card (Labels A)) (hn : 0 < s.n) + (eta : ℝ) (he0 : 0 < eta) (he1 : eta ≤ 1/4) + (history : List (Stored A)) (hg : Good A R s.xi eta history) + (hj : history.length < s.H) : + uniformAverage (fun bits : Word A s => + eventIndicator (¬RootedPhaseTrial.ValidOutput A R history.length + (lookup A history history.length) s.xi eta (step A R s history bits))) ≤ + error A s eta history.length := by + let j := history.length + let old := lookup A history j + let w : ℕ → Pair A → Pair A → ℚ := fun i => (lookup A history i).multiplier + let P : Stored A → Prop := RootedPhaseTrial.ValidOutput A R j old s.xi eta + let F : RootedRestartTrial.Words A s.C s.K s.H s.L j s.k s.n s.N s.h s.xi → ℝ := + fun bits => eventIndicator (¬∃ next, + RootedRestartTrial.run A R s.C s.K s.H s.L j s.k s.n s.N s.h s.hK s.hW s.xi + s.v w old.estimate bits=some next ∧ P next) + have hs := RootedRestartTrial.failure A R s.C hC s.K s.H s.L j s.k s.n s.N s.h + s.hK s.hW hB hH hj hbox s.xi hx0 hx1 hPL hCheeger s.v hp w + (fun i => (good_positive A R s.xi eta history hg i).1) + (fun i hi => good_multipliers A R s.xi eta history hg i hi) hn old.estimate + (good_positive A R s.xi eta history hg j).2 eta he0 he1 + have hpw (bits : Word A s) : + eventIndicator (¬P (step A R s history bits)) ≤ + F (split A s j (prefixWord (width_le A s j hj) bits)) := by + simp only [step,hj,dite_true] + exact default_failure _ old P + have havg := uniformAverage_mono _ _ hpw + have heq := padded_equiv_average (width_le A s j hj) (split A s j) F + rw [heq] at havg + have hbound : uniformAverage F ≤ error A s eta j := hs + exact havg.trans hbound + +end +end ContingencyTables.RootedHistoryStep + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntegerEvaluation.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntegerEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5be8e434edb1d234a49527375394cff5e8a9a0b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntegerEvaluation.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineProgram + +namespace OAI + +/-! # Integral coefficients of the executed selected-root affine penalty -/ + +namespace ContingencyTables.RootedIntegerEvaluation + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion GraphCompletionCounts ForestAssignmentSplit + +variable {I J : Type*} [Fintype I] [Fintype J] + +def integerIndicator (b : Bool) : ℤ := if b then 1 else 0 + +noncomputable def sign (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) : ℤ := + integerIndicator (RootedCut.treeCut A.T S t (.inl a.1))- + integerIndicator (RootedCut.treeCut A.T S t (.inr a.2)) + +lemma sign_real (A : Instance I J) (S : Selection A.T) (t : TreeCell A.T) (a : I×J) : + (sign A S t a:ℝ)=RootedCut.sign A.T S t a := by + cases hr : RootedCut.treeCut A.T S t (.inl a.1) <;> + cases hc : RootedCut.treeCut A.T S t (.inr a.2) <;> + norm_num [sign,integerIndicator,RootedCut.sign,ForestCut.indicator,hr,hc] + +lemma selfSign_square (A : Instance I J) (S : Selection A.T) (t : TreeCell A.T) : + (RootedCut.sign A.T S t t.val)^2=1 := by + have hn := RootedCut.treeCut_self A.T S A.hT t + cases hr : RootedCut.treeCut A.T S t (.inl t.val.1) <;> + cases hc : RootedCut.treeCut A.T S t (.inr t.val.2) <;> + simp_all [RootedCut.sign,ForestCut.indicator] + +noncomputable def coefficient (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) : ℤ := + if A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + then -(sign A S t a)*sign A S t t.val else 0 + +lemma coefficient_real (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (a : I×J) : + (coefficient A S t a:ℝ)=RootedAffine.coefficient A S t a := by + have hs := selfSign_square A S t + have hn := RootedCut.sign_self_ne_zero A.T S A.hT t + unfold coefficient RootedAffine.coefficient + split_ifs + · simp only [Int.cast_mul,Int.cast_neg,sign_real] + apply (eq_div_iff hn).mpr + calc + (-(RootedCut.sign A.T S t a)*RootedCut.sign A.T S t t.val)*RootedCut.sign A.T S t t.val= + -(RootedCut.sign A.T S t a)*(RootedCut.sign A.T S t t.val)^2 := by ring + _=_ := by rw [hs,mul_one] + · exact Int.cast_zero + +noncomputable def smallContribution (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (x q : I → J → ℤ) : ℤ := + ∑ a : I×J,if A.small a.1 a.2 then + integerIndicator (RootedCut.treeCut A.T S t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + integerIndicator (RootedCut.treeCut A.T S t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) else 0 + +lemma smallContribution_real (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (x q : I → J → ℤ) : + (smallContribution A S t x q:ℝ)=RootedAffine.smallContribution A S t + (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) := by + unfold smallContribution RootedAffine.smallContribution + rw [Int.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs + · cases hr : RootedCut.treeCut A.T S t (.inl a.1) <;> + cases hc : RootedCut.treeCut A.T S t (.inr a.2) <;> + simp_all [integerIndicator,ForestCut.indicator] + · exact Int.cast_zero + +noncomputable def offset (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (x q : I → J → ℤ) : ℤ := + A.X t.val.1 t.val.2-smallContribution A S t x q*sign A S t t.val- + ∑ a : I×J,coefficient A S t a*A.X a.1 a.2 + +lemma offset_real (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (x q : I → J → ℤ) : + (offset A S t x q:ℝ)=RootedAffine.offset A S t + (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) := by + have hs := selfSign_square A S t + have hn := RootedCut.sign_self_ne_zero A.T S A.hT t + have he : RootedAffine.smallContribution A S t (fun i j => (x i j:ℝ)) + (fun i j => (q i j:ℝ))*RootedCut.sign A.T S t t.val= + RootedAffine.smallContribution A S t (fun i j => (x i j:ℝ)) + (fun i j => (q i j:ℝ))/RootedCut.sign A.T S t t.val := by + apply (eq_div_iff hn).mpr + rw [mul_assoc,←pow_two,hs,mul_one] + simp only [offset,RootedAffine.offset,Int.cast_sub,Int.cast_mul,Int.cast_sum, + smallContribution_real,sign_real,coefficient_real,he] + +noncomputable def rationalScaledTree (A : Instance I J) (S : Selection A.T) + (B : ℕ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℚ) (t : TreeCell A.T) : ℚ := + (offset A S t x q:ℚ)/(A.b t.val.1 t.val.2:ℚ)+ + ∑ f : FreeCell A.small A.T, + ((coefficient A S t f.val:ℚ)*((A.b f.val.1 f.val.2:ℚ)+1)/B/ + (A.b t.val.1 t.val.2:ℚ))*v f + +lemma rationalScaledTree_cast (A : Instance I J) (S : Selection A.T) + (B : ℕ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℚ) (t : TreeCell A.T) : + (rationalScaledTree A S B x q v t:ℝ)= + RootedScaledPenalty.scaledTree A S (B:ℝ) x q (fun f => (v f:ℝ)) t := by + simp only [rationalScaledTree,RootedScaledPenalty.scaledTree,AffinePenalty.affineValue, + RootedScaledPenalty.normalizedOffset,RootedScaledPenalty.normalizedCoefficient, + Rat.cast_add,Rat.cast_div,Rat.cast_mul,Rat.cast_sum,Rat.cast_natCast,Rat.cast_one, + Rat.cast_intCast,offset_real,coefficient_real] + +noncomputable def numerator (A : Instance I J) (S : Selection A.T) + (B : ℕ) (t : TreeCell A.T) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℕ) : ℤ := + (B:ℤ)*offset A S t x q+ + ∑ f : FreeCell A.small A.T, + coefficient A S t f.val*((A.b f.val.1 f.val.2:ℤ)+1)*(v f:ℤ) + +theorem numerator_div (A : Instance I J) (S : Selection A.T) (B : ℕ) (hB : 0 (v f:ℚ)) t := by + have hBQ : (B:ℚ)≠0 := by exact_mod_cast hB.ne' + have hb : (A.b t.val.1 t.val.2:ℚ)≠0 := by + exact_mod_cast (lt_of_lt_of_le Nat.zero_lt_one (A.hlarge _ _ (A.hTG t.property)).2).ne' + have hsum : (∑ f : FreeCell A.small A.T, + ((coefficient A S t f.val:ℚ)*((A.b f.val.1 f.val.2:ℚ)+1)/B/ + (A.b t.val.1 t.val.2:ℚ))*(v f:ℚ))= + (∑ f : FreeCell A.small A.T, + (coefficient A S t f.val:ℚ)*((A.b f.val.1 f.val.2:ℚ)+1)*(v f:ℚ))/ + ((B:ℚ)*A.b t.val.1 t.val.2) := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro f _ + field_simp [hBQ,hb] + simp only [numerator,Int.cast_add,Int.cast_mul,Int.cast_natCast,Int.cast_sum,Int.cast_one, + rationalScaledTree,hsum] + field_simp [hBQ,hb] + +noncomputable def forestData (A : Instance I J) (S : Selection A.T) + (B : ℕ) (t : TreeCell A.T) (x y : I → J → ℤ) + {n : ℕ} (e : Fin n ≃ FreeCell A.small A.T) (v : FreeCell A.small A.T → ℕ) : + ForestAffineProgram.Input := + ForestAffineProgram.data ((B:ℤ)*offset A S t x y) + (fun i => coefficient A S t (e i).val*((A.b (e i).val.1 (e i).val.2:ℤ)+1)) + (fun i => v (e i)) (B*A.b t.val.1 t.val.2) + +theorem evaluate_forest (A : Instance I J) (S : Selection A.T) (B : ℕ) (hB : 0 (v f:ℚ)) t) + (rationalScaledTree A S B x y (fun f => (v f:ℚ)) t-1)) := by + have hb := (A.hlarge _ _ (A.hTG t.property)).2 + have hn : (((B:ℤ)*offset A S t x y:ℤ):ℚ)+ + ∑ i : Fin n, + ((coefficient A S t (e i).val*((A.b (e i).val.1 (e i).val.2:ℤ)+1):ℤ):ℚ)* + (v (e i):ℚ)=(numerator A S B t x y v:ℚ) := by + simp only [numerator,Int.cast_add,Int.cast_mul,Int.cast_natCast,Int.cast_one,Int.cast_sum] + congr 1 + exact Fintype.sum_equiv e _ _ (fun _ => rfl) + unfold forestData + rw [ForestAffineProgram.evaluate_data _ _ _ _ (Nat.mul_pos hB hb),hn,Nat.cast_mul, + numerator_div A S B hB] + +end ContingencyTables.RootedIntegerEvaluation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntervals.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntervals.lean new file mode 100644 index 0000000000000000000000000000000000000000..80cac1c16f9d2fc3f0cb9a0e6ed296a58ada4a03 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedIntervals.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalCompletion + +namespace OAI + +/-! # The actual tree intervals for an explicitly selected component root + +The maximum-forest cut estimate applies to every reachable root. Thus +the executed least-root convention retains the same finite tree box, +including for unbalanced retained small-cell views. +-/ + +namespace ContingencyTables.RootedIntervals + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedPhysicalCompletion +open ForestCapacity GraphCompletionCounts ForestCut + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma nonroot_of_component (A : Instance I J) (S : Selection A.T) + (u v : I⊕J) (h : A.T.Reachable (S.root u) v) (hv : v≠S.root u) : + v≠S.root v := by + have he : S.root v=S.root u := by + rw [←S.constant h,S.idempotent] + simpa only [he] using hv + +theorem solved_in_intervals (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) + (hsmall : ∀ i j,A.small i j=true → + (0≤ x i j ∧ x i j≤ A.b i j) ∧ (0≤ q i j ∧ q i j≤ A.b i j)) + (hfree : ∀ i j,A.small i j=false → ¬A.T.Adj (.inl i) (.inr j) → + 0≤ free i j ∧ free i j≤ A.b i j) : + ∀ i j,A.T.Adj (.inl i) (.inr j) → + -((10*A.d*A.b i j:ℕ):ℤ)≤ solved A S x q free i j ∧ + solved A S x q free i j≤(10*A.d*A.b i j:ℕ) := by + intro i₀ j₀ ht + let root := S.root (.inl i₀) + have hb := completion_interval A.small A.b A.T A.hTG A.hT A.hmax i₀ j₀ ht root + (S.reachable (.inl i₀)).symm + (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) + (fun i j => (completed A S x q free i j:ℝ)) (fun i j => (A.X i j:ℝ)) + (A.d:ℝ) A.W (by exact_mod_cast A.hd) (by exact_mod_cast A.hcard) A.hlarge + (by + intro i j hs + exact ⟨A.hsmall i j hs,by exact_mod_cast (hsmall i j hs).1, + by exact_mod_cast (hsmall i j hs).2⟩) + (by intro i j; exact_mod_cast A.hX i j) + (by + intro i j hs htree + have hn : ¬A.T.Adj (.inl i) (.inr j) := by + simpa only [treeCell,decide_eq_false_iff_not] using htree + simp only [completed,hn,ite_false] + have hf := hfree i j hs hn + constructor + · exact_mod_cast hf.1 + · have hcast : (free i j:ℝ)≤(A.b i j:ℝ) := by exact_mod_cast hf.2 + linarith) + (by + intro i hcomp hi + have hrow := row_completed_sum A S x q free i + (nonroot_of_component A S (.inl i₀) (.inl i) hcomp hi) + have hrowR : (∑ j,if A.small i j then (x i j:ℝ) else + (completed A S x q free i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast hrow + have hXR : (∑ j,(A.X i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast A.hXr i + unfold rowDifference + calc + _=(∑ j,if A.small i j then (x i j:ℝ) else + (completed A S x q free i j:ℝ))-(∑ j,(A.X i j:ℝ)) := by + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> rfl + _=0 := by rw [hrowR,hXR,sub_self]) + (by + intro j hcomp hj + have hcol := column_completed_sum A S x q free j + (nonroot_of_component A S (.inl i₀) (.inr j) hcomp hj) + have hcolR : (∑ i,if A.small i j then (q i j:ℝ) else + (completed A S x q free i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast hcol + have hXC : (∑ i,(A.X i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast A.hXc j + unfold columnDifference + calc + _=(∑ i,if A.small i j then (q i j:ℝ) else + (completed A S x q free i j:ℝ))-(∑ i,(A.X i j:ℝ)) := by + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> rfl + _=0 := by rw [hcolR,hXC,sub_self]) + simp only [completed,ht,ite_true] at hb + constructor + · have hlow : (-10:ℤ)*(A.d:ℤ)*(A.b i₀ j₀:ℤ)≤ solved A S x q free i₀ j₀ := by + exact_mod_cast hb.1 + convert hlow using 1 + push_cast + ring + · exact_mod_cast hb.2 + +end ContingencyTables.RootedIntervals + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLabelWeightProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLabelWeightProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f858eed138961cd4d079f6b893c62416810b6e7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLabelWeightProgram.lean @@ -0,0 +1,221 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PairedDemandProgram +import OAI.Combinatorics.ContingencyTables.Machines.PairedFactorialProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorMedianLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWeightOracle + +namespace OAI + +/-! # The executed weight oracle at a current paired state + +The immutable schedule and graph are shared. Each call reconstructs the +two small-cell views from its actual state, runs the independent median +estimator, and multiplies by the exact factorial ratio. +-/ + +namespace ContingencyTables.RootedLabelWeightProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open RootedEstimatorLayoutProgram + +abbrev Config := (Context × ℕ) × (List Bool × List Bool) +abbrev Input := Config × (List ℕ × List Bool) + +def replaceState (z : RootedOracleWalkProgram.State × List ℕ) : RootedOracleWalkProgram.State := + ((z.1.1.1,(z.1.1.2.1,PairedDemandProgram.output (z.1.1.2.2,z.2))),z.1.2) +def replaceStateRealizer : Realizer replaceState := by + let k : Realizer (fun z : RootedOracleWalkProgram.State × List ℕ => z.1.1.1) := + composition (composition first first) first + let parameters : Realizer (fun z : RootedOracleWalkProgram.State × List ℕ => z.1.1.2.1) := + composition (composition (composition first first) second) first + let demands : Realizer (fun z : RootedOracleWalkProgram.State × List ℕ => + PairedDemandProgram.output (z.1.1.2.2,z.2)) := + composition (f := fun z : RootedOracleWalkProgram.State × List ℕ => (z.1.1.2.2,z.2)) + (g := PairedDemandProgram.output) + (pair (composition (composition (composition first first) second) second) second) + PairedDemandProgram.outputRealizer + exact pair (pair k (pair parameters demands)) (composition first second) +lemma polynomial_replaceState : PolynomialTime replaceStateRealizer := by + unfold replaceStateRealizer + exact polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second) + polynomial_second) PairedDemandProgram.polynomial_output))) + (polynomial_composition polynomial_first polynomial_second) + +def stateInput (z : Input) : RootedOracleWalkProgram.State × List ℕ := + (z.1.1.1.1,z.2.1) +def stateInputRealizer : Realizer stateInput := + pair (composition (composition (composition first first) first) first) + (composition second first) +lemma polynomial_stateInput : PolynomialTime stateInputRealizer := + polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_first) + +def context (z : Input) : Context := + (replaceState (stateInput z),z.1.1.1.2) +def contextRealizer : Realizer context := + pair (composition (f := stateInput) (g := replaceState) stateInputRealizer replaceStateRealizer) + (composition (composition (composition first first) first) second) +lemma polynomial_context : PolynomialTime contextRealizer := + polynomial_pair (polynomial_composition polynomial_stateInput polynomial_replaceState) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + +def medianInput (z : Input) : RootedEstimatorMedianProgram.Input := + ((context z,z.1.1.2),(z.1.2,z.2.2)) +def medianInputRealizer : Realizer medianInput := + pair (pair contextRealizer (composition (composition first first) second)) + (pair (composition first second) (composition second second)) +lemma polynomial_medianInput : PolynomialTime medianInputRealizer := + polynomial_pair (polynomial_pair polynomial_context + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) + +def demandInput (z : Input) : PairedDemandProgram.Input := + ((stateInput z).1.1.2.2,z.2.1) +def demandInputRealizer : Realizer demandInput := + pair (composition (f := stateInput) + (g := fun s : RootedOracleWalkProgram.State × List ℕ => s.1.1.2.2) + stateInputRealizer (composition (composition (composition first first) second) second)) + (composition second first) +lemma polynomial_demandInput : PolynomialTime demandInputRealizer := + polynomial_pair (polynomial_composition polynomial_stateInput + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second)) + (polynomial_composition polynomial_second polynomial_first) + +def factorialInput (z : Input) : PairedProfileProgram.Input := + (CompanionCellCatalog.capacities (PairedDemandProgram.cells (demandInput z)),z.2.1) +def factorialInputRealizer : Realizer factorialInput := + pair (composition (f := demandInput) + (g := fun s : PairedDemandProgram.Input => CompanionCellCatalog.capacities (PairedDemandProgram.cells s)) + demandInputRealizer (composition (f := PairedDemandProgram.cells) + (g := CompanionCellCatalog.capacities) PairedDemandProgram.cellsRealizer + CompanionCellCatalog.capacitiesRealizer)) (composition second first) +lemma polynomial_factorialInput : PolynomialTime factorialInputRealizer := + polynomial_pair (polynomial_composition polynomial_demandInput + (polynomial_composition PairedDemandProgram.polynomial_cells CompanionCellCatalog.polynomial_capacities)) + (polynomial_composition polynomial_second polynomial_first) + +attribute [local irreducible] medianInput factorialInput + +def medianResult (z : Input) : TreeFraction.Fraction := RootedEstimatorMedianProgram.output (medianInput z) +def medianResultRealizer : Realizer medianResult := + composition (f := medianInput) (g := RootedEstimatorMedianProgram.output) + medianInputRealizer RootedEstimatorMedianProgram.outputRealizer +lemma polynomial_medianResult : PolynomialTime medianResultRealizer := + polynomial_composition polynomial_medianInput RootedEstimatorMedianProgram.polynomial_output + +def factorialResult (z : Input) : TreeFraction.Fraction := PairedFactorialProgram.output (factorialInput z) +def factorialResultRealizer : Realizer factorialResult := + composition (f := factorialInput) (g := PairedFactorialProgram.output) + factorialInputRealizer PairedFactorialProgram.outputRealizer +lemma polynomial_factorialResult : PolynomialTime factorialResultRealizer := + polynomial_composition polynomial_factorialInput PairedFactorialProgram.polynomial_output + +attribute [local irreducible] medianResult factorialResult + +def output (z : Input) : TreeFraction.Fraction := TreeFraction.mul (medianResult z,factorialResult z) +def outputRealizer : Realizer output := + composition (f := fun z : Input => (medianResult z,factorialResult z)) (g := TreeFraction.mul) + (pair medianResultRealizer factorialResultRealizer) TreeFraction.mulRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_medianResult polynomial_factorialResult) TreeFraction.polynomial_mul + +noncomputable section +open CompanionFactorialApplication CompanionArithmeticProposal GridBoundary +open CompanionOracleDensity FiniteObservableTransport CommonBasesFPRAS +open scoped Classical +variable {m n : ℕ} + +def config (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (epsilon delta : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) : Config := + ((RootedEstimatorMedianProgram.context A C K j epsilon z v,repetitionCount delta),(degree,depth)) + +lemma replaceState_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (S : Set (Labels A × Bool)) : + replaceState (RootedOracleWalkProgram.data A C a K z v, + encodeSet (CompanionComputedInitial.coordinateOrder A) S)= + RootedOracleWalkProgram.data A C a K (CompanionWeightOracle.profile A S) v := by + unfold replaceState RootedOracleWalkProgram.data + rw [PairedDemandProgram.output_data] + +lemma context_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (epsilon delta : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth bits : List Bool) (S : Set (Labels A × Bool)) : + context (config A C K j epsilon delta z v degree depth, + (encodeSet (CompanionComputedInitial.coordinateOrder A) S,bits))= + RootedEstimatorMedianProgram.context A C K j epsilon (CompanionWeightOracle.profile A S) v := by + unfold context stateInput config RootedEstimatorMedianProgram.context + RootedEstimatorWordProgram.scheduledContext RootedEstimatorLayoutProgram.data + rw [replaceState_data] + +lemma output_value (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (epsilon delta : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (S : Set (Labels A × Bool)) + (bits : Fin (repetitionCount delta*wordWidth + (RootedEstimatorMedianProgram.context A C K j epsilon (CompanionWeightOracle.profile A S) v)) → Bool) : + TreeFraction.val (output (config A C K j epsilon delta z v degree depth, + (encodeSet (CompanionComputedInitial.coordinateOrder A) S,List.ofFn bits)))= + RootedEstimatorMedianProgram.value A C K j epsilon delta + (CompanionWeightOracle.profile A S) v degree depth bits * CompanionWeightOracle.factorialRatio A S := by + rw [output,TreeFraction.mul_val] + unfold medianResult factorialResult + have hf : factorialInput (config A C K j epsilon delta z v degree depth, + (encodeSet (CompanionComputedInitial.coordinateOrder A) S,List.ofFn bits))= + (List.ofFn (CompanionComputedInitial.capacities A), + encodeSet (CompanionComputedInitial.coordinateOrder A) S) := by + unfold factorialInput demandInput stateInput config RootedEstimatorMedianProgram.context + RootedEstimatorWordProgram.scheduledContext RootedEstimatorLayoutProgram.data + RootedOracleWalkProgram.data + rw [PairedDemandProgram.cells_data,CompanionCellCatalog.capacities_eq] + rfl + rw [hf,PairedFactorialProgram.output_physical] + apply congrArg (fun q : ℚ => q*CompanionWeightOracle.factorialRatio A S) + unfold medianInput + rw [context_data] + rfl + +theorem sameLaw_weight (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (S : Set (Labels A × Bool)) : + SameLaw (fun bits : Fin (repetitionCount xi*wordWidth + (RootedEstimatorMedianProgram.context A C K j xi (CompanionWeightOracle.profile A S) v)) → Bool => + TreeFraction.val (output (config A C K j xi xi z v degree depth, + (encodeSet (CompanionComputedInitial.coordinateOrder A) S,List.ofFn bits)))) + (RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) C K hK hW j xi + (RootedCatalogGrid.gridEquiv A K v) S) := by + have h := (RootedEstimatorMedianProgram.sameLaw A C K j hC hj hK hW hB xi xi hxi + (CompanionWeightOracle.profile A S) (CompanionWeightOracle.profile_inBox A S) + v degree depth hdegree hdepth).map (fun q => q*CompanionWeightOracle.factorialRatio A S) + intro phi + have hl : (fun bits : Fin (repetitionCount xi*wordWidth + (RootedEstimatorMedianProgram.context A C K j xi (CompanionWeightOracle.profile A S) v)) → Bool => + phi (TreeFraction.val (output (config A C K j xi xi z v degree depth, + (encodeSet (CompanionComputedInitial.coordinateOrder A) S,List.ofFn bits)))))= + (fun bits => phi (RootedEstimatorMedianProgram.value A C K j xi xi + (CompanionWeightOracle.profile A S) v degree depth bits*CompanionWeightOracle.factorialRatio A S)) := by + funext bits + rw [output_value] + rw [hl] + exact h phi + +end +end ContingencyTables.RootedLabelWeightProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLargeMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLargeMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fb14febd493e12776cdae86b2e43a329f8b5873 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLargeMarginal.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.ForestLargeMarginal + +namespace OAI + +/-! # Actual balanced large-cell marginal for the explicit root selector + +The raw removal and reflected signatures are derived from the physical +line/unary factors. No signature of the marginal is postulated. +-/ + +namespace ContingencyTables.RootedLargeMarginal + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedPenalty +open LargePairEnumeration BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def largeMarginal (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) + (z : View A → ℕ) : ℝ := + ∑ a : ((k : Fin n) → Fin (RootedPenalty.widths A (e k).val.1 (e k).val.2+1)), + physicalWeight A S alpha + (joinedProfile (fun k => RootedPenalty.widths A (e k).val.1 (e k).val.2) z a ∘ + (physicalJoinEquiv (fun a : I×J => A.small a.1 a.2) e).symm) + +theorem largeMarginal_nonnegative (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + {n : ℕ} (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) + (z : View A → ℕ) : 0≤ largeMarginal A S alpha e z := by + apply Finset.sum_nonneg + intro a _ + exact physicalWeight_nonnegative A S alpha _ + +private theorem largeMarginal_eq_eliminate (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) {n : ℕ} (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) : + largeMarginal A S alpha e= + BalancedFamily.eliminate (LargePairEnumeration.widths + (fun k => RootedPenalty.widths A (e k).val.1 (e k).val.2)) (fun q => + physicalWeight A S alpha + (q ∘ (physicalCoordinateEquiv (fun a : I×J => A.small a.1 a.2) e + (fun k => RootedPenalty.widths A (e k).val.1 (e k).val.2)).symm)) := by + funext z + exact (eliminate_eq_actual_cells (fun a : I×J => A.small a.1 a.2) e _ + (physicalWeight A S alpha) z).symm + +lemma large_width (A : Instance I J) {n : ℕ} + (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) (k : Fin n) : + 2≤ RootedPenalty.widths A (e k).val.1 (e k).val.2 := by + have hb := (A.hlarge _ _ (e k).property).2 + by_cases ht : A.T.Adj (.inl (e k).val.1) (.inr (e k).val.2) + · simp only [RootedPenalty.widths,ForestLiteralCount.width,ht,ite_true] + have hd := A.hd + have hp : 0 A.small a.1 a.2)) (R : ℕ) : + RemovalSlice (largeMarginal A S alpha e) (bounds A) R := by + let N : Fin n → ℕ := fun k => RootedPenalty.widths A (e k).val.1 (e k).val.2 + have hu : ∀ a,0≤ ForestPenaltyApplication.unaryRate A.T A.b alpha a := by + intro a + unfold ForestPenaltyApplication.unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + have hs := EqualityReindex.physical_marginal_removal (LargePairEnumeration.widths N) + (bounds A) R (physicalCoordinateEquiv (fun a : I×J => A.small a.1 a.2) e N) + RowColumnPenalties.cellLine (rootFlag S) (fun _ => alpha) + (ForestPenaltyApplication.lineOffset (ell A) (RootedPenalty.widths A) A.r A.c) + RowColumnPenalties.viewSlope (ForestPenaltyApplication.unaryRate A.T A.b alpha) + (ForestPenaltyApplication.unaryEll (ell A)) ForestPenaltyApplication.unarySlope + (ForestPenaltyApplication.unaryCap A.b) + (widths_lower N (large_width A e)) (fun _ => ha) hu + rw [largeMarginal_eq_eliminate] + exact hs + +theorem largeMarginal_reflected (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) (ha : 0≤ alpha) {n : ℕ} + (e : Fin n ≃ LargeCell (fun a : I×J => A.small a.1 a.2)) (R : ℕ) : + RemovalSlice (fun z => largeMarginal A S alpha e + (IntegerReflection.reflect (bounds A) z)) (bounds A) R := by + let N : Fin n → ℕ := fun k => RootedPenalty.widths A (e k).val.1 (e k).val.2 + have hu : ∀ a,0≤ ForestPenaltyApplication.unaryRate A.T A.b alpha a := by + intro a + unfold ForestPenaltyApplication.unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + rw [largeMarginal_eq_eliminate] + exact EqualityReindex.physical_marginal_reflected (LargePairEnumeration.widths N) + (bounds A) R (physicalCoordinateEquiv (fun a : I×J => A.small a.1 a.2) e N) + RowColumnPenalties.cellLine (rootFlag S) (fun _ => alpha) + (ForestPenaltyApplication.lineOffset (ell A) (RootedPenalty.widths A) A.r A.c) + RowColumnPenalties.viewSlope (ForestPenaltyApplication.unaryRate A.T A.b alpha) + (ForestPenaltyApplication.unaryEll (ell A)) ForestPenaltyApplication.unarySlope + (ForestPenaltyApplication.unaryCap A.b) + (widths_lower N (large_width A e)) (fun _ => ha) hu + +end ContingencyTables.RootedLargeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLiteralCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLiteralCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a2edb2d0cdc46307899bed5d948ccbbc1a2c349 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedLiteralCount.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.RootedIntervals + +namespace OAI + +/-! # Multiplicity-one physical tree sum with the executed root convention -/ + +namespace ContingencyTables.RootedLiteralCount + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedPhysicalCompletion +open RootedPenalty ForestLiteralCount GraphCompletionCounts +open ForestPhysicalCompletion (rowResidual columnResidual) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def actualPenalty (A : Instance I J) (S : Selection A.T) + (x y free : I → J → ℕ) (tree : I → J → ℤ) : ℝ := + (∑ v,if rootFlag S v then + |actualDeviation A.small A.T A.b x y free A.r A.c tree v| else 0)+ + ∑ i,∑ j,if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0 + +def RootConditions (A : Instance I J) (S : Selection A.T) + (x q free tree : I → J → ℤ) : Prop := + (∀ i,Sum.inl i≠S.root (.inl i) → + (∑ j,tree i j)=rowResidual A.small A.T A.r x free i) ∧ + (∀ j,Sum.inr j≠S.root (.inr j) → + (∑ i,tree i j)=columnResidual A.small A.T A.c q free j) + +lemma penalty_profile (A : Instance I J) (S : Selection A.T) + (x y free : I → J → ℕ) (a : TreeIndex A.T A.d A.b) + (hy : ∀ i j,A.small i j=true → y i j≤ A.b i j) + (hf : ∀ i j,A.small i j=false → ¬A.T.Adj (.inl i) (.inr j) → free i j≤ A.b i j) : + penalty A S (profile A.small A.T A.d A.b x y free a)= + actualPenalty A S x y free (physical A.T A.d A.b a) := by + unfold penalty rootPenalty actualPenalty + rw [show ForestPenaltyApplication.deviation (ell A) (widths A) A.r A.c + (profile A.small A.T A.d A.b x y free a)= + actualDeviation A.small A.T A.b x y free A.r A.c (physical A.T A.d A.b a) from + deviation_profile A.small A.T A.hTG A.d A.b x y free a A.r A.c hy hf] + congr 1 + unfold ForestPenaltyApplication.treePenalty + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + by_cases ht : A.T.Adj (.inl i) (.inr j) + · have hs : A.small i j=false := A.hTG ht + have hrow := row_profile A.small A.T A.hTG A.d A.b x y free a i j + simp only [hs,Bool.false_eq_true,ite_false,largeValue,ht,ite_true] at hrow + simp only [ht,ite_true,EqualitySoftening.affineDistance,mul_one] + rw [show (ell A i j:ℝ)+(profile A.small A.T A.d A.b x y free a ((i,j),false):ℝ)= + (physical A.T A.d A.b a i j:ℝ) from hrow] + · simp only [ht,ite_false] + +lemma nonroot_iff (A : Instance I J) (S : Selection A.T) + (x y free : I → J → ℕ) (tree : I → J → ℤ) + (hsupport : ∀ i j,¬A.T.Adj (.inl i) (.inr j) → tree i j=0) : + (∀ g,rootFlag S g=false → + actualDeviation A.small A.T A.b x y free A.r A.c tree g=0) ↔ + RootConditions A S (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) tree := by + constructor + · intro h + constructor + · intro i hi + have hflag : rootFlag S (.inl i)=false := by + simpa only [rootFlag,decide_eq_false_iff_not] using hi + have hraw := h (.inl i) hflag + simp only [actualDeviation,Sum.elim_inl] at hraw + have hsum : (∑ j,if A.small i j then (x i j:ℤ) else largeValue A.T tree free i j)=A.r i := + by exact_mod_cast sub_eq_zero.mp hraw + simp_rw [ForestLiteralCount.row_pointwise A.small A.T A.hTG x free tree hsupport] at hsum + rw [Finset.sum_add_distrib] at hsum + unfold rowResidual + omega + · intro j hj + have hflag : rootFlag S (.inr j)=false := by + simpa only [rootFlag,decide_eq_false_iff_not] using hj + have hraw := h (.inr j) hflag + simp only [actualDeviation,Sum.elim_inr] at hraw + have hsum : (∑ i,if A.small i j then ((A.b i j-y i j:ℕ):ℤ) + else largeValue A.T tree free i j)=A.c j := by exact_mod_cast sub_eq_zero.mp hraw + simp_rw [ForestLiteralCount.column_pointwise A.small A.T A.hTG A.b y free tree hsupport] at hsum + rw [Finset.sum_add_distrib] at hsum + unfold columnResidual + omega + · intro h g hg + cases g with + | inl i => + have hi : Sum.inl i≠S.root (.inl i) := by + simpa only [rootFlag,decide_eq_false_iff_not] using hg + have hsum : (∑ j,if A.small i j then (x i j:ℤ) else largeValue A.T tree free i j)=A.r i := by + simp_rw [ForestLiteralCount.row_pointwise A.small A.T A.hTG x free tree hsupport] + rw [Finset.sum_add_distrib,h.1 i hi] + exact sub_add_cancel _ _ + simp only [actualDeviation,Sum.elim_inl] + have hreal : (((∑ j,if A.small i j then (x i j:ℤ) + else largeValue A.T tree free i j):ℤ):ℝ)=(A.r i:ℝ) := by exact_mod_cast hsum + rw [hreal,sub_self] + | inr j => + have hj : Sum.inr j≠S.root (.inr j) := by + simpa only [rootFlag,decide_eq_false_iff_not] using hg + have hsum : (∑ i,if A.small i j then ((A.b i j-y i j:ℕ):ℤ) + else largeValue A.T tree free i j)=A.c j := by + simp_rw [ForestLiteralCount.column_pointwise A.small A.T A.hTG A.b y free tree hsupport] + rw [Finset.sum_add_distrib,h.2 j hj] + exact sub_add_cancel _ _ + simp only [actualDeviation,Sum.elim_inr] + have hreal : (((∑ i,if A.small i j then ((A.b i j-y i j:ℕ):ℤ) + else largeValue A.T tree free i j):ℤ):ℝ)=(A.c j:ℝ) := by exact_mod_cast hsum + rw [hreal,sub_self] + +noncomputable def solutionIndex (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) + (hbox : ∀ i j,A.T.Adj (.inl i) (.inr j) → + -((10*A.d*A.b i j:ℕ):ℤ)≤ solved A S x q free i j ∧ + solved A S x q free i j≤(10*A.d*A.b i j:ℕ)) : TreeIndex A.T A.d A.b := fun e => + ⟨(solved A S x q free e.val.1 e.val.2+(10*A.d*A.b e.val.1 e.val.2:ℕ)).toNat,by + have h := hbox e.val.1 e.val.2 e.property + have hz : 0≤ solved A S x q free e.val.1 e.val.2+(10*A.d*A.b e.val.1 e.val.2:ℕ) := by omega + have hle : (solved A S x q free e.val.1 e.val.2+ + (10*A.d*A.b e.val.1 e.val.2:ℕ)).toNat≤20*A.d*A.b e.val.1 e.val.2 := by + exact_mod_cast (show ((solved A S x q free e.val.1 e.val.2+ + (10*A.d*A.b e.val.1 e.val.2:ℕ)).toNat:ℤ)≤(20*A.d*A.b e.val.1 e.val.2:ℕ) by + rw [Int.toNat_of_nonneg hz] + push_cast at h ⊢ + nlinarith) + omega⟩ + +lemma physical_solutionIndex (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) + (hbox : ∀ i j,A.T.Adj (.inl i) (.inr j) → + -((10*A.d*A.b i j:ℕ):ℤ)≤ solved A S x q free i j ∧ + solved A S x q free i j≤(10*A.d*A.b i j:ℕ)) : + physical A.T A.d A.b (solutionIndex A S x q free hbox)=solved A S x q free := by + funext i j + by_cases h : A.T.Adj (.inl i) (.inr j) + · have hz : 0≤ solved A S x q free i j+(10*A.d*A.b i j:ℕ) := by + have hb := hbox i j h + omega + simp only [physical,h,dite_eq_left,solutionIndex,Int.toNat_of_nonneg hz] + omega + · simp only [physical,h,not_false_eq_true,dite_eq_right, + solved_supported A S x q free i j h] + +theorem tree_indicator_sum (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) + (hsmall : ∀ i j,A.small i j=true → + (0≤ x i j ∧ x i j≤ A.b i j) ∧ (0≤ q i j ∧ q i j≤ A.b i j)) + (hfree : ∀ i j,A.small i j=false → ¬A.T.Adj (.inl i) (.inr j) → + 0≤ free i j ∧ free i j≤ A.b i j) + (weight : (I → J → ℤ) → ℝ) : + (∑ a : TreeIndex A.T A.d A.b,if RootConditions A S x q free (physical A.T A.d A.b a) + then weight (physical A.T A.d A.b a) else 0)=weight (solved A S x q free) := by + let hb := RootedIntervals.solved_in_intervals A S x q free hsmall hfree + let a₀ := solutionIndex A S x q free hb + have ha₀ : physical A.T A.d A.b a₀=solved A S x q free := physical_solutionIndex A S x q free hb + have hsol : RootConditions A S x q free (solved A S x q free) := + ⟨table_row A.small A.T S A.hTG _ _,table_column A.small A.T S A.hTG _ _⟩ + rw [Finset.sum_eq_single a₀] + · simp only [ha₀,hsol,ite_true] + · intro a _ hne + by_cases ha : RootConditions A S x q free (physical A.T A.d A.b a) + · have he := table_unique A.small A.T S A.hTG A.hT _ _ (physical A.T A.d A.b a) + (physical_supported A.T A.d A.b a) ha.1 ha.2 + have haa : a=a₀ := physical_injective A.T A.d A.b (he.trans ha₀.symm) + exact (hne haa).elim + · simp only [ha,ite_false] + · simp + +theorem literal_tree_sum (A : Instance I J) (S : Selection A.T) + (x y free : I → J → ℕ) (alpha : ℝ) + (hx : ∀ i j,A.small i j=true → x i j≤ A.b i j) + (hy : ∀ i j,A.small i j=true → y i j≤ A.b i j) + (hf : ∀ i j,A.small i j=false → ¬A.T.Adj (.inl i) (.inr j) → free i j≤ A.b i j) : + (∑ a : TreeIndex A.T A.d A.b, + physicalWeight A S alpha (profile A.small A.T A.d A.b x y free a))= + (2:ℝ)^(-alpha*actualPenalty A S x y free + (solved A S (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)))) := by + have hsum := tree_indicator_sum A S (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) + (by + intro i j hs + refine ⟨⟨Nat.cast_nonneg _,?_⟩,⟨Nat.cast_nonneg _,?_⟩⟩ + · exact_mod_cast hx i j hs + · exact_mod_cast Nat.sub_le (A.b i j) (y i j)) + (by + intro i j hs ht + exact ⟨Nat.cast_nonneg _,by exact_mod_cast hf i j hs ht⟩) + (fun tree => (2:ℝ)^(-alpha*actualPenalty A S x y free tree)) + calc + _=(∑ a : TreeIndex A.T A.d A.b, + if RootConditions A S (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (fun i j => (free i j:ℤ)) (physical A.T A.d A.b a) + then (2:ℝ)^(-alpha*actualPenalty A S x y free (physical A.T A.d A.b a)) else 0) := by + apply Finset.sum_congr rfl + intro a _ + rw [RootedPenalty.exact_eq, + show ForestPenaltyApplication.deviation (ell A) (widths A) A.r A.c + (profile A.small A.T A.d A.b x y free a)= + actualDeviation A.small A.T A.b x y free A.r A.c (physical A.T A.d A.b a) from + deviation_profile A.small A.T A.hTG A.d A.b x y free a A.r A.c hy hf, + penalty_profile A S x y free a hy hf] + simp only [nonroot_iff A S x y free _ (physical_supported A.T A.d A.b a)] + _=_ := hsum + +end ContingencyTables.RootedLiteralCount + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedMultiplierUpdate.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedMultiplierUpdate.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a363817c0a96b52ec8fd7d35d008d994917cf25 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedMultiplierUpdate.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedAnnealing +import OAI.Combinatorics.ContingencyTables.Counting.AnnealingMultipliers + +namespace OAI + +/-! +# Selected-root empirical multiplier and counting updates + +The observables and empirical counts are those of the actual labelled +chain. The update cancels the preceding multiplier, and the next-parameter +comparison is derived from the literal bounded forest penalty. +-/ + +namespace ContingencyTables.RootedMultiplierUpdate + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def ratio (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (S : Set (Labels A×Bool)) : ℝ := + weight A R (j+1) S/weight A R j S + +lemma ratio_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2:ℝ)≤ ratio A R j S ∧ ratio A R j S≤1 := by + have h := weight_adjacent A R j S + unfold ratio + constructor + · exact (le_div_iff₀ (weight_positive A R j S)).mpr h.1 + · exact (div_le_one (weight_positive A R j S)).mpr h.2 + +lemma ratio_mean (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) : + chainMean pairs w (weight A R j) (plainObservable pairs (ratio A R j))= + slotTotal pairs (weight A R (j+1)) ∅/chainTotal pairs w (weight A R j) := by + rw [plainObservable_mean pairs PairedLabels.fresh PairedLabels.cover] + congr 2 + funext S + unfold ratio + exact mul_div_cancel₀ _ (weight_positive A R j S).ne' + +/-- The explicit observed-type-count update gives good multipliers for +j+1. Its only statistical hypothesis is relative accuracy of the actual +finite observations at phase j. -/ +theorem successful_phase_learns (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0< w p r) (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) + (l : List (Set (Labels A×Bool))) + (hacc : AccuratePhase pairs w (weight A R j) (ratio A R j) eta l) : + GoodMultipliers pairs (weight A R (j+1)) (learnedMultipliers pairs w l) := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover w + (weight A R j) (weight_positive A R j) hw + have hp0 : 0< chainMean pairs w (weight A R j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos (slotTotal_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh) hZ + have hplain := accurate_plain pairs w (weight A R j) (ratio A R j) eta l hacc + have hp0h := AnnealingMultipliers.empirical_positive hp0 he hplain.1 + have hpt (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : 0< chainMean pairs w (weight A R j) (defectIndicator pairs p r) := by + rw [defectIndicator_mean pairs PairedLabels.fresh PairedLabels.cover _ _ p r hp hr hpr] + exact div_pos (mul_pos (hw p r) + (slotDefect_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh p r hp hr hpr)) hZ + have hpth (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : 0< empirical (defectIndicator pairs p r) l := + AnnealingMultipliers.empirical_positive (hpt p r hp hr hpr) he + (accurate_defect pairs w (weight A R j) (ratio A R j) eta l hacc p r hp hr hpr).1 + have hb (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : + (slotTotal pairs (weight A R (j+1)) ∅/slotDefect pairs (weight A R (j+1)) ∅ p r)/4≤ + learnedMultipliers pairs w l p r ∧ + learnedMultipliers pairs w l p r≤ + 4*(slotTotal pairs (weight A R (j+1)) ∅/slotDefect pairs (weight A R (j+1)) ∅ p r) := by + rw [learnedMultipliers,ite_eq_left ⟨hp,hr,hpr⟩] + have hu := AnnealingMultipliers.update_good hp0 (hpt p r hp hr hpr) (hw p r) + he0 he hplain (accurate_defect pairs w (weight A R j) (ratio A R j) eta l hacc p r hp hr hpr) + (by simpa only [mul_div_assoc] using (weight_mean_identity pairs PairedLabels.fresh + PairedLabels.cover (weight A R j) (weight_positive A R j) w hw p r hp hr hpr)) + (ideal_adjacent A R j p r hp hr hpr) + simpa only [mul_div_assoc] using hu + refine ⟨?_,?_,?_⟩ + · intro p r + unfold learnedMultipliers + split_ifs with ht + · exact mul_pos (hw p r) (div_pos hp0h (hpth p r ht.1 ht.2.1 ht.2.2)) + · exact hw p r + · intro p hp r hr hpr + simpa only [div_div,mul_comm] using (hb p r hp hr hpr).1 + · intro p hp r hr hpr + simpa only [mul_div_assoc] using (hb p r hp hr hpr).2 + +/-- Relative accuracy of the actual counting and plain observations +bounds one logarithmic counting-ratio error by 4 eta. -/ +theorem successful_phase_ratio_log (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0< w p r) (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) + (l : List (Set (Labels A×Bool))) + (hacc : AccuratePhase pairs w (weight A R j) (ratio A R j) eta l) : + |Real.log (empiricalRatio pairs (ratio A R j) l/ + (slotTotal pairs (weight A R (j+1)) ∅/slotTotal pairs (weight A R j) ∅))|≤4*eta := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover w + (weight A R j) (weight_positive A R j) hw + have hC := slotTotal_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh + have hC' := slotTotal_pos pairs _ (weight_positive A R (j+1)) ∅ PairedLabels.fresh + have hp : 0< chainMean pairs w (weight A R j) (plainObservable pairs (ratio A R j)) := by + rw [ratio_mean] + exact div_pos hC' hZ + have hq : 0< chainMean pairs w (weight A R j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos hC hZ + have hph := relative_error_bounds _ _ _ (hacc (.inr ())) + simp only [phaseObservable] at hph + have hqh := accurate_plain pairs w (weight A R j) (ratio A R j) eta l hacc + have h := (AnnealingMultipliers.relative_ratio hp hq he0 he hph hqh).2.2.2 + rw [ratio_mean,plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] at h + unfold empiricalRatio + convert h using 2 + congr 1 + field_simp [hZ.ne',hC.ne',hC'.ne'] + +end ContingencyTables.RootedMultiplierUpdate + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedNearMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedNearMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..21bc72be4e228404a91c7f59c48888760ff8a539 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedNearMass.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeExteriorMass +import OAI.Combinatorics.ContingencyTables.Rooted.RootedFarMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionNearMass + +namespace OAI + +/-! # Selected-root mass in the actual narrow exterior tree region -/ + +namespace ContingencyTables.RootedNearMass + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedPhysicalNormalizer RootedFarMass +open RootedTreeMarginal TreeExteriorPositions BalancedCellFibres +open TreeMarginalSignature (cellWidth) +open CompanionNearMass (cellPositions) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def nearMass (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) (gamma : ℝ) : ℝ := + ∑ a : Profiles (cellWidth A),if a t ∈ cellPositions A t gamma then actualWeight A R alpha a else 0 + +lemma nearMass_eq_fibres (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) (gamma : ℝ) : + nearMass A R alpha t gamma=∑ k ∈ cellPositions A t gamma,scalarExact A R alpha t k.val := by + have hh := weighted_fibre_sum (cellWidth A) + (RootedPenalty.physicalWeight A R alpha) t + (fun k => if k ∈ cellPositions A t gamma then 1 else 0) + have hs : (∑ k : Fin (cellWidth A t+1), + if k ∈ cellPositions A t gamma then scalarExact A R alpha t k.val else 0)=nearMass A R alpha t gamma := by + simp_rw [exact_eq_fibre] + simpa only [nearMass,actualWeight,mul_ite,mul_one,mul_zero] using hh + rw [← hs] + simpa only [Finset.filter_mem_eq_inter,Finset.univ_inter] using + (Finset.sum_filter (s := Finset.univ) (fun k => k ∈ cellPositions A t gamma) + (fun k => scalarExact A R alpha t k.val)).symm + +/-- This uses actual feasible endpoint tables, the proved raw marginal +signature and equality limit, and the exact count normalizer. -/ +theorem near_mass_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha gamma : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) (hg : 0 < gamma) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y0 Y1 : I → J → ℤ) + (hY0 : ∀ i j,0 ≤ Y0 i j ∧ Y0 i j ≤ A.b i j) + (hY1 : ∀ i j,0 ≤ Y1 i j ∧ Y1 i j ≤ A.b i j) + (hr0 : ∀ i,(∑ j,Y0 i j)=A.r i) (hc0 : ∀ j,(∑ i,Y0 i j)=A.c j) + (hr1 : ∀ i,(∑ j,Y1 i j)=A.r i) (hc1 : ∀ j,(∑ i,Y1 i j)=A.c j) + (hy0 : Y0 t.1 t.2=0) (hy1 : Y1 t.1 t.2=(A.b t.1 t.2:ℤ)) : + nearMass A R alpha t gamma/physicalMass A R alpha ≤ 4*gamma*K := by + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hbR : (0:ℝ) < A.b t.1 t.2 := by exact_mod_cast hb + have hpoint (k : Fin (cellWidth A t+1)) (hk : k ∈ cellPositions A t gamma) : + scalarExact A R alpha t k.val/physicalMass A R alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + have hh := (Finset.mem_filter.mp hk).2 + change (((ForestLiteralCount.lower A.T A.d A.b t.1 t.2+(k.val:ℤ)<0) ∧ _) ∨ + (((A.b t.1 t.2:ℤ) hpoint k hk) + _ = ((cellPositions A t gamma).card:ℝ)*((2*K:ℝ)/A.b t.1 t.2) := by simp + _ ≤ (2*(gamma*A.b t.1 t.2))*((2*K:ℝ)/A.b t.1 t.2) := + mul_le_mul_of_nonneg_right hcard (by positivity) + _ = _ := by field_simp [hbR.ne']; ring + +end ContingencyTables.RootedNearMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedObservableApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedObservableApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..6fd4d6beccb6cc5c4cd005f6f0bdc775899f5590 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedObservableApplication.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedFactorialApplication +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservableApplication + +namespace OAI + +/-! # Observable bounds from the actual selected-root factorial signatures -/ + +namespace ContingencyTables.RootedObservableApplication + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication TwoLiftStates +open ComplementChain ObservableBounds + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem transversal_variance (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (ha : 0≤alpha) + (H : Set (Labels A×Bool) → ℝ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r, 0 hp x) + simp only [Finset.sum_add_distrib] at h + unfold distance + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +theorem observed_failure_near (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (hp : 0 < Fintype.card (Labels A)) + (w : Pair A → Pair A → ℚ) (hw : ∀ p q,0 < w p q) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (w p q:ℝ))) + (p q : State A → ℝ) (hq : ∀ S,0 ≤ q S) (hmass : ∑ S,q S ≤ 1) + (hwarm : ∀ S,q S ≤ (10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j)) + (eta : ℝ) (heta : 0 < eta) : + (∑ S,p S*uniformAverage (fun bits : Fin (N*stepBits A C K j k xi) → Bool => + eventIndicator (¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (observedStates A R C K j k N hK hW xi v w S bits))))) ≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)+2*distance p q := by + let g : State A → ℝ := fun S => + uniformAverage (fun bits : Fin (N*stepBits A C K j k xi) → Bool => + eventIndicator (¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (observedStates A R C K j k N hK hW xi v w S bits)))) + have hg (S : State A) : 0 ≤ g S ∧ g S ≤ 1 := by + apply FiniteIndependentAverages.mean_bounds _ 0 1 + intro bits + unfold eventIndicator + split_ifs <;> norm_num + have he := bounded_expectation_error p q g hg + have hs := observed_failure A R C hC K j k N hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw hgood q hq hmass hwarm eta heta + dsimp only [g] at he + have hsadd := _root_.add_le_add hs (le_refl (2*distance p q)) + have hb := he.trans hsadd + exact hb + +end +end ContingencyTables.RootedObservationStart + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOffsetProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOffsetProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..076e5d45f3ec132cf0ee0b1970cc3eae6e82f871 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOffsetProgram.lean @@ -0,0 +1,220 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCoefficientProgram + +namespace OAI + +/-! # Computing the forest affine offset from the stored cell values + +Every summand uses the executed cut flags and coefficient. The input +contains the baseline and the two stored views, rather than an affine +offset supplied by an oracle. +-/ + +namespace ContingencyTables.RootedOffsetProgram + +open MatchingFPRAS.TreeTyped SignedPairProgram +open scoped BigOperators Classical + +abbrev WeightedInput := (ℕ×ℕ)×(Signed×Signed) +abbrev Entry := (RootedCoefficientProgram.Input×(Signed×Signed))×Signed +abbrev Input := Signed×List Entry + +def weightedDifference (z : WeightedInput) : Signed := + minus (times ((z.1.1,0),z.2.1),times ((z.1.2,0),z.2.2)) + +def weightedDifferenceRealizer : Realizer weightedDifference := + composition (pair + (composition (pair (pair (composition first first) (constant 0)) + (composition second first)) timesRealizer) + (composition (pair (pair (composition first second) (constant 0)) + (composition second second)) timesRealizer)) minusRealizer + +lemma polynomial_weightedDifference : PolynomialTime weightedDifferenceRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_constant 0)) + (polynomial_composition polynomial_second polynomial_first)) polynomial_times) + (polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_constant 0)) + (polynomial_composition polynomial_second polynomial_second)) polynomial_times)) + polynomial_minus + +lemma value_weightedDifference (z : WeightedInput) : + value (weightedDifference z)=(z.1.1:ℤ)*value z.2.1-(z.1.2:ℤ)*value z.2.2 := by + rw [weightedDifference,value_minus,value_times,value_times] + rfl + +lemma value_parts (z : ℤ) : value (ForestAffineProgram.signedParts z)=z := + ForestAffineProgram.signedParts_sub z + +def cellInput (z : Entry) : RootedCoefficientProgram.Input := z.1.1 +def cellInputRealizer : Realizer cellInput := composition first first +lemma polynomial_cellInput : PolynomialTime cellInputRealizer := + polynomial_composition polynomial_first polynomial_first + +def shifted (z : Entry) : Signed×Signed := + (minus (z.1.2.1,z.2),minus (z.1.2.2,z.2)) +def shiftedRealizer : Realizer shifted := + pair + (composition (f := fun z : Entry => (z.1.2.1,z.2)) (g := SignedPairProgram.minus) + (pair (composition (composition first second) first) second) minusRealizer) + (composition (f := fun z : Entry => (z.1.2.2,z.2)) (g := SignedPairProgram.minus) + (pair (composition (composition first second) second) second) minusRealizer) +lemma polynomial_shifted : PolynomialTime shiftedRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) polynomial_second) polynomial_minus) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_second) polynomial_minus) + +def cutTerm (z : Entry) : Signed := + weightedDifference (RootedCoefficientProgram.signs (cellInput z).1,shifted z) +def cutTermRealizer : Realizer cutTerm := + composition (pair (composition (composition cellInputRealizer first) + RootedCoefficientProgram.signsRealizer) shiftedRealizer) weightedDifferenceRealizer +lemma polynomial_cutTerm : PolynomialTime cutTermRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_cellInput polynomial_first) + RootedCoefficientProgram.polynomial_signs) polynomial_shifted) polynomial_weightedDifference + +def smallTest (z : Entry) : Bool := !decide ((cellInput z).2.1 ≤ (cellInput z).2.2) +def smallTestRealizer : Realizer smallTest := + composition (composition (composition cellInputRealizer second) leNat) boolNot +lemma polynomial_smallTest : PolynomialTime smallTestRealizer := + polynomial_composition + (polynomial_composition (polynomial_composition polynomial_cellInput polynomial_second) + polynomial_leNat) polynomial_boolNot + +def smallTerm (z : Entry) : Signed := if smallTest z then cutTerm z else (0,0) +def smallTermRealizer : Realizer smallTerm := + choose smallTestRealizer cutTermRealizer (constant (0,0)) +lemma polynomial_smallTerm : PolynomialTime smallTermRealizer := + polynomial_choose polynomial_smallTest polynomial_cutTerm (polynomial_constant (0,0)) + +def summand (z : Entry) : Signed := + plus (times (smallTerm z,RootedCoefficientProgram.treeSigns (cellInput z).1.1), + times (RootedCoefficientProgram.coefficient (cellInput z),z.2)) +def summandRealizer : Realizer summand := + composition (pair + (composition (pair smallTermRealizer + (composition (composition (composition cellInputRealizer first) first) + RootedCoefficientProgram.treeSignsRealizer)) timesRealizer) + (composition (pair (composition cellInputRealizer + RootedCoefficientProgram.coefficientRealizer) second) timesRealizer)) plusRealizer +lemma polynomial_summand : PolynomialTime summandRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_smallTerm + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_cellInput polynomial_first) + polynomial_first) RootedCoefficientProgram.polynomial_treeSigns)) polynomial_times) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_cellInput RootedCoefficientProgram.polynomial_coefficient) + polynomial_second) polynomial_times)) polynomial_plus + +def offset (z : Input) : Signed := + SignedPairProgram.normalize (minus (z.1,sum (z.2.map summand))) +def offsetRealizer : Realizer offset := + composition (f := fun z : Input => minus (z.1,sum (z.2.map summand))) + (g := SignedPairProgram.normalize) + (composition (f := fun z : Input => (z.1,sum (z.2.map summand))) (g := SignedPairProgram.minus) + (pair first (composition (composition second (map summandRealizer)) sumRealizer)) minusRealizer) + normalizeRealizer +theorem polynomial_offset : PolynomialTime offsetRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + polynomial_first + (polynomial_composition (polynomial_composition polynomial_second + (polynomial_map polynomial_summand)) polynomial_sum)) polynomial_minus) polynomial_normalize + +lemma value_offset (z : Input) : + value (offset z)=value z.1-(z.2.map (fun e => value (summand e))).sum := by + rw [offset,value_normalize,value_minus,value_sum] + simp only [List.map_map,Function.comp_def] + +open CompanionFactorialApplication RootedCompletion RootedIntegerEvaluation + +noncomputable def entry {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (a : Fin m×Fin n) : Entry := + ((RootedCoefficientProgram.input A t a, + (ForestAffineProgram.signedParts (x a.1 a.2),ForestAffineProgram.signedParts (q a.1 a.2))), + ForestAffineProgram.signedParts (A.X a.1 a.2)) + +lemma smallTest_entry {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (a : Fin m×Fin n) : smallTest (entry A t x q a)=A.small a.1 a.2 := by + unfold smallTest cellInput entry RootedCoefficientProgram.input + cases hs : A.small a.1 a.2 with + | false => simp [(A.hlarge _ _ hs).1] + | true => simp [Nat.not_le.mpr (A.hsmall _ _ hs)] + +lemma cutTerm_entry {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (a : Fin m×Fin n) : value (cutTerm (entry A t x q a))= + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) := by + rw [cutTerm,value_weightedDifference] + dsimp only [shifted,entry,cellInput] + rw [value_minus,value_minus] + simp only [value_parts] + unfold RootedCoefficientProgram.signs RootedCoefficientProgram.input + rw [RootedCutReindex.canonicalCut_treeCut,RootedCutReindex.canonicalCut_treeCut] + cases hr : RootedCut.treeCut A.T (rowColumn A.T) t (.inl a.1) <;> + cases hc : RootedCut.treeCut A.T (rowColumn A.T) t (.inr a.2) <;> + simp [RootedCoefficientProgram.bit,integerIndicator] + +lemma summand_entry {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (a : Fin m×Fin n) : value (summand (entry A t x q a))= + (if A.small a.1 a.2 then + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) + else 0)*sign A (rowColumn A.T) t t.val+ + RootedIntegerEvaluation.coefficient A (rowColumn A.T) t a*A.X a.1 a.2 := by + rw [summand,value_plus,value_times,value_times] + have ht := RootedCoefficientProgram.treeSigns_input A t a + have hc := RootedCoefficientProgram.coefficient_input A t a + have hb : value (entry A t x q a).2=(A.X a.1 a.2:ℤ) := by + exact value_parts _ + have hs : value (smallTerm (entry A t x q a))= + if A.small a.1 a.2 then + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inl a.1))*(x a.1 a.2-A.X a.1 a.2)- + integerIndicator (RootedCut.treeCut A.T (rowColumn A.T) t (.inr a.2))*(q a.1 a.2-A.X a.1 a.2) + else 0 := by + rw [smallTerm,smallTest_entry] + split_ifs + · exact cutTerm_entry A t x q a + · rfl + rw [hs,hb] + rw [show (cellInput (entry A t x q a))=RootedCoefficientProgram.input A t a by rfl,ht,hc] + +noncomputable def data {m n N : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (e : Fin N ≃ Fin m×Fin n) : Input := + (ForestAffineProgram.signedParts (A.X t.val.1 t.val.2), + List.ofFn (fun i => entry A t x q (e i))) + +/-- The executed normalized pair is the exact manuscript affine offset. -/ +theorem offset_data {m n N : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℤ) + (e : Fin N ≃ Fin m×Fin n) : + offset (data A t x q e)=ForestAffineProgram.signedParts + (RootedIntegerEvaluation.offset A (rowColumn A.T) t x q) := by + have he : (∑ i : Fin N,value (summand (entry A t x q (e i))))= + ∑ a : Fin m×Fin n,value (summand (entry A t x q a)) := + Fintype.sum_equiv e _ _ (fun _ => rfl) + rw [offset,normalize_eq] + congr 1 + rw [value_minus,value_sum] + simp only [data,List.map_ofFn,Function.comp_apply,List.sum_ofFn,value_parts] + rw [he] + simp only [summand_entry] + rw [Finset.sum_add_distrib,←Finset.sum_mul] + unfold RootedIntegerEvaluation.offset RootedIntegerEvaluation.smallContribution + ring + +end ContingencyTables.RootedOffsetProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f4ecf6a6d253926d0e48b62c68ebe5b01bcf728 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleAcceptance.lean @@ -0,0 +1,218 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseOracleError +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRationalThreshold + +namespace OAI + +/-! # Actual selected-root weight calls control the Metropolis decision -/ + +namespace ContingencyTables.RootedOracleAcceptance + +open CompanionFactorialApplication CompanionOracleDensity RootedWeightOracle CompanionRationalUpdates +open RootedPhaseWords CommonBasesFPRAS GridBoundary FairBits TwoLiftStates +open CompanionPhaseWords (independent_pair_failure) +open CompanionWeightOracle (WeightWord) +open scoped BigOperators Classical + +noncomputable section + +private lemma ratio_linear_bounds {u v uh vh e : ℝ} + (hu : 0 < u) (hv : 0 < v) (he0 : 0 ≤ e) (he1 : e ≤ 1/4) + (huh : (1-e)*u ≤ uh ∧ uh ≤ (1+e)*u) + (hvh : (1-e)*v ≤ vh ∧ vh ≤ (1+e)*v) : + (1-4*e)*(v/u) ≤ vh/uh ∧ vh/uh ≤ (1+4*e)*(v/u) := by + have huh0 := AnnealingMultipliers.empirical_positive hu he1 huh.1 + have ha0 : 0 ≤ 1-4*e := by linarith + have hp0 : 0 ≤ 1+4*e := by linarith + have hx : 0 < uh/u := div_pos huh0 hu + have hlo : 1-e ≤ uh/u := (le_div_iff₀ hu).mpr huh.1 + have hhi : uh/u ≤ 1+e := (div_le_iff₀ hu).mpr huh.2 + have hyl : 1-e ≤ vh/v := (le_div_iff₀ hv).mpr hvh.1 + have hyu : vh/v ≤ 1+e := (div_le_iff₀ hv).mpr hvh.2 + have hnorm : 1-4*e ≤ (vh/v)/(uh/u) ∧ (vh/v)/(uh/u) ≤ 1+4*e := by + constructor + · rw [le_div_iff₀ hx] + have hm := mul_le_mul_of_nonneg_left hhi ha0 + nlinarith [sq_nonneg e] + · rw [div_le_iff₀ hx] + have hm := mul_le_mul_of_nonneg_left hlo hp0 + have he : 0 ≤ 2*e-4*e^2 := by nlinarith + nlinarith + have hid : ((vh/v)/(uh/u))*(v/u)=vh/uh := by + field_simp [hu.ne',hv.ne',huh0.ne'] + constructor + · simpa only [hid] using mul_le_mul_of_nonneg_right hnorm.1 (div_pos hv hu).le + · simpa only [hid] using mul_le_mul_of_nonneg_right hnorm.2 (div_pos hv hu).le + +private lemma min_one_stability {a r s : ℝ} (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (h : (1-a)*r ≤ s ∧ s ≤ (1+a)*r) : |min 1 s-min 1 r| ≤ a := by + by_cases hr : r ≤ 1 <;> by_cases hs : s ≤ 1 + · rw [min_eq_right hs,min_eq_right hr,abs_le] + have hm := mul_nonneg ha0 (sub_nonneg.mpr hr) + constructor <;> nlinarith + · rw [min_eq_left (le_of_not_ge hs),min_eq_right hr,abs_le] + have hm := mul_nonneg ha0 (sub_nonneg.mpr hr) + constructor <;> nlinarith + · rw [min_eq_right hs,min_eq_left (le_of_not_ge hr),abs_le] + have hm := mul_nonneg (sub_nonneg.mpr ha1) (sub_nonneg.mpr (le_of_not_ge hr)) + constructor <;> nlinarith + · rw [min_eq_left (le_of_not_ge hs),min_eq_left (le_of_not_ge hr)] + simpa using ha0 + +variable {I J : Type*} [Fintype I] [Fintype J] + +def evaluatedWeight (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) (bits : WeightWord A C K j xi) : ℚ := + rationalMultiplier pairs w S*evaluate A R C K hK hW j xi v S bits + +def targetWeight (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) : ℝ := + (rationalMultiplier pairs w S:ℝ)*RootedAnnealing.weight A R j S + +lemma targetWeight_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) : targetWeight A R j w S= + chainWeight pairs (fun p q => (w p q:ℝ)) (RootedAnnealing.weight A R j) S := by + rw [targetWeight,rationalMultiplier_cast] + rfl + +lemma multiplier_positive (A : Instance I J) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) : 0 < rationalMultiplier pairs w S := by + unfold rationalMultiplier + split_ifs + · exact hw _ _ + · norm_num + +lemma targetWeight_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) : 0 < targetWeight A R j w S := by + apply mul_pos _ (RootedAnnealing.weight_positive A R j S) + exact_mod_cast multiplier_positive A w hw S + +def acceptance (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) : ℚ := + min 1 (evaluatedWeight A R C K j hK hW xi v w T bits.2/ + evaluatedWeight A R C K j hK hW xi v w S bits.1) + +def targetAcceptance (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S T : Set (Labels A×Bool)) : ℝ := min 1 (targetWeight A R j w T/targetWeight A R j w S) + +lemma targetAcceptance_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S T : ChainIndex (Γ := Labels A×Bool) pairs) : targetAcceptance A R j w S.val T.val= + metropolisAcceptance pairs (fun p q => (w p q:ℝ)) (RootedAnnealing.weight A R j) S T := by + simp only [targetAcceptance,targetWeight_eq,metropolisAcceptance] + +lemma evaluatedWeight_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) (bits : WeightWord A C K j xi) + (hg : accurateCall A R C K j hK hW xi v S bits) : + (1-(xi:ℝ))*targetWeight A R j w S ≤ (evaluatedWeight A R C K j hK hW xi v w S bits:ℝ) ∧ + (evaluatedWeight A R C K j hK hW xi v w S bits:ℝ) ≤ (1+(xi:ℝ))*targetWeight A R j w S := by + have hm : (0:ℝ) ≤ rationalMultiplier pairs w S := by + exact_mod_cast (multiplier_positive A w hw S).le + have hlo := mul_le_mul_of_nonneg_left hg.1 hm + have hhi := mul_le_mul_of_nonneg_left hg.2 hm + simpa only [evaluatedWeight,targetWeight,Rat.cast_mul,mul_left_comm,mul_assoc] using And.intro hlo hhi + +/-- Relative errors in both weight calls cause an absolute acceptance +error at most four times the call tolerance, even across clipping at 1. -/ +theorem acceptance_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) + (hS : accurateCall A R C K j hK hW xi v S bits.1) + (hT : accurateCall A R C K j hK hW xi v T bits.2) : + |(acceptance A R C K j hK hW xi v w S T bits:ℝ)-targetAcceptance A R j w S T| ≤ 4*(xi:ℝ) := by + have hb := ratio_linear_bounds (targetWeight_positive A R j w hw S) + (targetWeight_positive A R j w hw T) (by exact_mod_cast hx0) + (by + have h4 : (4:ℝ)*(xi:ℝ) ≤ 1 := by + exact_mod_cast (show (4:ℚ)*xi ≤ 1 by linarith) + linarith) + (evaluatedWeight_bounds A R C K j hK hW xi v w hw S bits.1 hS) + (evaluatedWeight_bounds A R C K j hK hW xi v w hw T bits.2 hT) + have hh := min_one_stability (show (0:ℝ) ≤ 4*(xi:ℝ) by exact_mod_cast mul_nonneg (by norm_num : (0:ℚ)≤4) hx0) + (show 4*(xi:ℝ) ≤ 1 by exact_mod_cast (show 4*xi ≤ (1:ℚ) by linarith)) hb + simpa only [acceptance,targetAcceptance,Rat.cast_min,Rat.cast_one,Rat.cast_div] using hh + +lemma acceptance_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) : + 0 ≤ acceptance A R C K j hK hW xi v w S T bits ∧ + acceptance A R C K j hK hW xi v w S T bits ≤ 1 := by + have hpos (X : Set (Labels A×Bool)) (b : WeightWord A C K j xi) : + 0 < evaluatedWeight A R C K j hK hW xi v w X b := + mul_pos (multiplier_positive A w hw X) + (evaluate_positive A R C hC K hK hW hB j hj xi hx0 hx1 v X b) + exact ⟨le_min (by norm_num) (div_pos (hpos T bits.2) (hpos S bits.1)).le,min_le_left _ _⟩ + +lemma targetAcceptance_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) : + 0 ≤ targetAcceptance A R j w S T ∧ targetAcceptance A R j w S T ≤ 1 := by + exact ⟨le_min (by norm_num) + (div_pos (targetWeight_positive A R j w hw T) (targetWeight_positive A R j w hw S)).le, + min_le_left _ _⟩ + +/-- This is the rounded acceptance probability of the implemented +decision, averaged over its two fresh independent weight-query words. -/ +theorem average_acceptance_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K j xi => + |(rationalThresholdMass k (acceptance A R C K j hK hW xi v w S T bits):ℝ)- + targetAcceptance A R j w S T|) ≤ 6*(xi:ℝ)+1/(2:ℝ)^k := by + let goodS := accurateCall A R C K j hK hW xi v S + let goodT := accurateCall A R C K j hK hW xi v T + have hx1' : xi < 1 := by linarith + have hbad : uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K j xi => + if ¬(goodS bits.1 ∧ goodT bits.2) then (1:ℝ) else 0) ≤ (xi:ℝ)+(xi:ℝ) := by + have hs := accurateCall_failure A R C hC K j hK hW hB hj xi hx0 hx1' hPL hCheeger v S + have ht := accurateCall_failure A R C hC K j hK hW hB hj xi hx0 hx1' hPL hCheeger v T + exact @independent_pair_failure (WeightWord A C K j xi) (WeightWord A C K j xi) + inferInstance inferInstance inferInstance inferInstance goodS goodT (xi:ℝ) (xi:ℝ) hs ht + have hpoint (bits : WeightWord A C K j xi × WeightWord A C K j xi) : + |(rationalThresholdMass k (acceptance A R C K j hK hW xi v w S T bits):ℝ)-targetAcceptance A R j w S T| ≤ + (4*(xi:ℝ)+1/(2:ℝ)^k)+(if ¬(goodS bits.1 ∧ goodT bits.2) then 1 else 0) := by + let q := acceptance A R C K j hK hW xi v w S T bits + have hq := acceptance_bounds A R C hC K j hK hW hB hj xi hx0 hx1' v w hw S T bits + have hr := rationalThreshold_error k q hq.1 + have hnon : (0:ℝ) ≤ (q:ℝ)-(rationalThresholdMass k q:ℝ) := by exact_mod_cast sub_nonneg.mpr hr.2.1 + have hround : |(rationalThresholdMass k q:ℝ)-(q:ℝ)| ≤ 1/(2:ℝ)^k := by + rw [abs_sub_comm,abs_of_nonneg hnon] + have hc : ((q-rationalThresholdMass k q:ℚ):ℝ) ≤ ((1/(2:ℚ)^k:ℚ):ℝ) := + Rat.cast_le.mpr hr.2.2.le + simpa only [Rat.cast_sub,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using hc + have htriangle := abs_add_le ((rationalThresholdMass k q:ℝ)-(q:ℝ)) + ((q:ℝ)-targetAcceptance A R j w S T) + have hcancel : (rationalThresholdMass k q:ℝ)-(q:ℝ)+((q:ℝ)-targetAcceptance A R j w S T)= + (rationalThresholdMass k q:ℝ)-targetAcceptance A R j w S T := by ring + rw [hcancel] at htriangle + by_cases hg : goodS bits.1 ∧ goodT bits.2 + · have herr := acceptance_error A R C K j hK hW xi hx0.le hx1 v w hw S T bits hg.1 hg.2 + simpa [q,hg,add_comm] using htriangle.trans (add_le_add hround herr) + · have ht := targetAcceptance_bounds A R j w hw S T + have hdiff : |(q:ℝ)-targetAcceptance A R j w S T| ≤ 1 := by + have hqR : (0:ℝ) ≤ q ∧ (q:ℝ) ≤ 1 := by exact_mod_cast hq + exact abs_le.mpr ⟨by linarith,by linarith⟩ + simp only [hg,not_false_eq_true,ite_true] + have hxR : (0:ℝ) ≤ xi := by exact_mod_cast hx0.le + linarith [htriangle] + have hh := uniformAverage_mono _ _ hpoint + rw [uniformAverage_add,uniformAverage_const] at hh + linarith + +end +end ContingencyTables.RootedOracleAcceptance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..a530972f273e3911b143b6b3df517bc39ab34954 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleChain.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleCut +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleCorrection +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleChain + +namespace OAI + +/-! # The actual bin chain for the computed-root forest penalty + +All cut geometry is proved from the selected-root density. The only +conditional inputs are the same finite-box Prékopa–Leindler inequality +and finite reversible-chain Cheeger theorem used by the original chain. +-/ + +namespace ContingencyTables.RootedOracleDensity + +open CommonBasesFPRAS GridBoundary CompanionFactorialApplication +open CompanionOracleDensity (dimension height proposal_bounds proposal_degree cutConstant) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +def oracleChain (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : FiniteChain (Grid (I := Fin (dimension A)) K) := by + letI : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + exact MetropolisChain.chain (gridWeight A R C a z) (fun _ => DenseWeights.binWeight_pos _ _ _) + Neighbor neighbor_symm (binProposal A.d) (proposal_bounds A.d A.hd).1.le + (2*dimension A) (fun v => by simpa using neighbor_degree v) + ((proposal_degree A).trans (by norm_num)) + +lemma oracleChain_pi (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + (oracleChain A R C a z hK).π v = gridWeight A R C a z v/ + ∑ w : Grid (I := Fin (dimension A)) K,gridWeight A R C a z w := rfl + +private lemma corner_injective {q K : ℕ} : + Function.Injective (corner (I := Fin q) (K := K)) := by + intro a b h + funext i + exact Subtype.ext (congrFun h i) + +/-- All geometric cut obligations are discharged for the literal forest +penalty. Only finite-box PL and finite-chain Cheeger remain conditional. -/ +theorem oracleChain_poincare (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + ∀ f, (oracleChain A R C a z hK).variance f ≤ + (2/(cutConstant A K)^2)*(oracleChain A R C a z hK).energy f := by + classical + let : DecidableEq (Grid (I := Fin (dimension A)) K) := Classical.decEq _ + let : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + let w := gridWeight A R C a z (K := K) + have hw : ∀ v,0 < w v := fun _ => DenseWeights.binWeight_pos _ _ _ + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hKR : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hb := (proposal_bounds A.d A.hd).1 + have hk : 0 < cutConstant A K := by unfold cutConstant; positivity + apply MetropolisChain.poincare_of_weighted_cut w hw Neighbor neighbor_symm + (binProposal A.d) hb.le (2*dimension A) (fun v => by simpa using neighbor_degree v) + ((proposal_degree A).trans (by norm_num)) hCheeger (cutConstant A K) hk + intro S + change cutConstant A K*min (∑ v ∈ S,w v) (∑ v ∈ Sᶜ,w v) ≤ + binProposal A.d*(∑ v ∈ S,∑ u ∈ Sᶜ,if Neighbor v u then min (w v) (w u) else 0) + have hS : 0 ≤ ∑ v ∈ S,w v := Finset.sum_nonneg (fun _ _ => (hw _).le) + have hSc : 0 ≤ ∑ v ∈ Sᶜ,w v := Finset.sum_nonneg (fun _ _ => (hw _).le) + by_cases hs : S.Nonempty + · by_cases hsc : Sᶜ.Nonempty + · let Q : (Fin (dimension A) → ℤ) → Prop := fun x => ∃ v ∈ S,corner v=x + have hQ (v : Grid (I := Fin (dimension A)) K) : Q (corner v) ↔ v∈S := by + constructor + · rintro ⟨u,hu,he⟩ + exact corner_injective he ▸ hu + · intro hv + exact ⟨v,hv,rfl⟩ + have hne : Nonempty (Selected K Q) := by + obtain ⟨v,hv⟩ := hs + exact ⟨⟨v,(hQ v).mpr hv⟩⟩ + have hne' : Nonempty (Selected K (fun x => ¬Q x)) := by + obtain ⟨v,hv⟩ := hsc + exact ⟨⟨v,fun h => (Finset.mem_compl.mp hv) ((hQ v).mp h)⟩⟩ + have hcut := weighted_min_cut A R C a hC ha haH z K hK hPL Q hne hne' + change (1/(128*(A.d:ℝ)*K))* + min (∑ v : Selected K Q,w v.val) (∑ v : Selected K (fun x => ¬Q x),w v.val) ≤ + ∑ e : CutEdge K Q,min (w e.val.1) (w e.val.2.1) at hcut + have hsum : (∑ v : Selected K Q,w v.val)=∑ v∈S,w v := by + rw [selected_sum_eq_filter Q w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ] + have hsum' : (∑ v : Selected K (fun x => ¬Q x),w v.val)=∑ v∈Sᶜ,w v := by + rw [selected_sum_eq_filter (fun x => ¬Q x) w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ,Finset.mem_compl] + rw [hsum,hsum'] at hcut + have hflow := cut_faces_le_neighbor_flow Q w (fun v => (hw v).le) + have hflow' : (∑ e : CutEdge K Q,min (w e.val.1) (w e.val.2.1)) ≤ + ∑ v∈S,∑ u∈Sᶜ,if Neighbor v u then min (w v) (w u) else 0 := by + convert hflow using 1 + apply Finset.sum_congr ?_ ?_ + · ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ] + · intro v _ + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext u + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ,Finset.mem_compl] + calc + _ = binProposal A.d*((1/(128*(A.d:ℝ)*K))*min (∑ v∈S,w v) (∑ v∈Sᶜ,w v)) := by + unfold cutConstant + ring + _ ≤ _ := mul_le_mul_of_nonneg_left (hcut.trans hflow') hb.le + · have he : Sᶜ=∅ := Finset.not_nonempty_iff_eq_empty.mp hsc + rw [he] + simp only [Finset.sum_empty,min_eq_right hS,mul_zero,Finset.sum_const_zero] + exact le_rfl + · have he : S=∅ := Finset.not_nonempty_iff_eq_empty.mp hs + rw [he] at hSc ⊢ + simp only [Finset.sum_empty,min_eq_left hSc,mul_zero] + exact le_rfl + +end +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4d39bcff3337fc1ca4c0c5cd57d0a9cf602eba3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigProgram.lean @@ -0,0 +1,248 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLabelWeightProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleProgram +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram + +namespace OAI + +/-! # Computing a phase's physical oracle configuration + +Numeric schedules use binary arithmetic. The supplied reserve bounds +the two materialized precision markers; no binary natural controls an +unbounded list allocation. +-/ + +namespace ContingencyTables.RootedOracleConfigProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram +open CountingOracleScheduleProgram DensePrograms + +abbrev Input := ((RootedOracleWalkProgram.State × Fraction) × ℕ) × List Bool + +def fields (z : Input) : List ℕ := + [z.1.1.1.1.2.1.1.1,z.1.1.1.1.1, + RootedPenaltyEvaluateProgram.height z.1.1.1.1.2.1,z.1.2] +private def consR {f : Input → ℕ} {g : Input → List ℕ} + (F : Realizer f) (G : Realizer g) : Realizer (fun z => f z::g z) := + composition (f := fun z : Input => (f z,g z)) (g := fun p : ℕ × List ℕ => p.1::p.2) + (pair F G) listCons +private lemma polynomial_consR {f : Input → ℕ} {g : Input → List ℕ} + (F : Realizer f) (G : Realizer g) (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (consR F G) := polynomial_composition (polynomial_pair hF hG) polynomial_listCons + +def fieldsRealizer : Realizer fields := by + let stateR : Realizer (fun z : Input => z.1.1.1) := composition (composition first first) first + let frameR : Realizer (fun z : Input => z.1.1.1.1) := composition stateR first + let parametersR : Realizer (fun z : Input => z.1.1.1.1.2.1) := + composition (composition frameR second) first + let dR : Realizer (fun z : Input => z.1.1.1.1.2.1.1.1) := + composition (composition parametersR first) first + let kR : Realizer (fun z : Input => z.1.1.1.1.1) := composition frameR first + let hR : Realizer (fun z : Input => RootedPenaltyEvaluateProgram.height z.1.1.1.1.2.1) := + composition (f := fun z : Input => z.1.1.1.1.2.1) + (g := RootedPenaltyEvaluateProgram.height) parametersR RootedPenaltyEvaluateProgram.heightRealizer + exact consR dR (consR kR (consR hR (consR (composition first second) (constant [])))) +lemma polynomial_fields : PolynomialTime fieldsRealizer := by + unfold fieldsRealizer + apply polynomial_consR + · tree_poly + apply polynomial_consR + · tree_poly + apply polynomial_consR + · exact polynomial_composition (by tree_poly) RootedPenaltyEvaluateProgram.polynomial_height + exact polynomial_consR _ _ (polynomial_composition polynomial_first polynomial_second) + (polynomial_constant []) + +def dim : Expr := .input 0 +def grid : Expr := .input 1 +def height : Expr := .input 2 +def phase : Expr := .input 3 +def mixing : Expr := 2*(10000*dim^2*grid)^2 +def allowance : Expr := height+dim*grid+2 +def relativeDenominator : Expr := 400*(phase+1) + +def scalar (e : Expr) (z : Input) : ℕ := e.eval (fields z) +def scalarRealizer (e : Expr) : Realizer (scalar e) := + composition (f := fields) (g := e.eval) fieldsRealizer e.realizer +lemma polynomial_scalar (e : Expr) : PolynomialTime (scalarRealizer e) := + polynomial_composition polynomial_fields e.polynomial + +def inner (z : Input) : Fraction := + TreeFraction.div (z.1.1.2,natural (scalar relativeDenominator z)) +def innerRealizer : Realizer inner := + composition (f := fun z : Input => (z.1.1.2,natural (scalar relativeDenominator z))) + (g := TreeFraction.div) + (pair (composition (composition first first) second) + (composition (f := scalar relativeDenominator) (g := natural) + (scalarRealizer relativeDenominator) naturalRealizer)) TreeFraction.divRealizer +lemma polynomial_inner : PolynomialTime innerRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_scalar relativeDenominator) polynomial_natural)) + TreeFraction.polynomial_div + +def correction (z : Input) : Fraction := TreeFraction.div (inner z,(256,1)) +def correctionRealizer : Realizer correction := + composition (f := fun z : Input => (inner z,(256,1))) (g := TreeFraction.div) + (pair innerRealizer (constant (256,1))) TreeFraction.divRealizer +lemma polynomial_correction : PolynomialTime correctionRealizer := + polynomial_composition (polynomial_pair polynomial_inner (polynomial_constant _)) TreeFraction.polynomial_div + +def samples (z : Input) : ℕ := CountingOracleScheduleProgram.sampleCount (z.1.2,(inner z,(1,1))) +def samplesRealizer : Realizer samples := + composition (f := fun z : Input => (z.1.2,(inner z,(1,1)))) + (g := CountingOracleScheduleProgram.sampleCount) + (pair (composition first second) (pair innerRealizer (constant (1,1)))) sampleCountRealizer +lemma polynomial_samples : PolynomialTime samplesRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_pair polynomial_inner (polynomial_constant _))) polynomial_sampleCount + +def timeInput (z : Input) : ℕ × ℕ := (scalar mixing z,scalar allowance z) +def timeInputRealizer : Realizer timeInput := pair (scalarRealizer mixing) (scalarRealizer allowance) +lemma polynomial_timeInput : PolynomialTime timeInputRealizer := + polynomial_pair (polynomial_scalar mixing) (polynomial_scalar allowance) + +def ratioTime (z : Input) : ℕ := CountingOracleScheduleProgram.oracleTime (timeInput z,inner z) +def ratioTimeRealizer : Realizer ratioTime := + composition (f := fun z : Input => (timeInput z,inner z)) + (g := CountingOracleScheduleProgram.oracleTime) (pair timeInputRealizer innerRealizer) oracleTimeRealizer +lemma polynomial_ratioTime : PolynomialTime ratioTimeRealizer := + polynomial_composition (polynomial_pair polynomial_timeInput polynomial_inner) polynomial_oracleTime + +def correctionTime (z : Input) : ℕ := CountingOracleScheduleProgram.oracleTime (timeInput z,correction z) +def correctionTimeRealizer : Realizer correctionTime := + composition (f := fun z : Input => (timeInput z,correction z)) + (g := CountingOracleScheduleProgram.oracleTime) (pair timeInputRealizer correctionRealizer) oracleTimeRealizer +lemma polynomial_correctionTime : PolynomialTime correctionTimeRealizer := + polynomial_composition (polynomial_pair polynomial_timeInput polynomial_correction) polynomial_oracleTime + +def offsetAccuracy (z : Input) : ℕ := CountingOracleScheduleProgram.offsetAccuracy (scalar dim z,inner z) +def offsetAccuracyRealizer : Realizer offsetAccuracy := + composition (f := fun z : Input => (scalar dim z,inner z)) + (g := CountingOracleScheduleProgram.offsetAccuracy) (pair (scalarRealizer dim) innerRealizer) + CountingOracleScheduleProgram.offsetAccuracyRealizer +lemma polynomial_offsetAccuracy : PolynomialTime offsetAccuracyRealizer := + polynomial_composition (polynomial_pair (polynomial_scalar dim) polynomial_inner) + CountingOracleScheduleProgram.polynomial_offsetAccuracy + +def normalizedNoise (z : Input) : Fraction := TreeFraction.normalize z.1.1.2 +def normalizedNoiseRealizer : Realizer normalizedNoise := + composition (composition (composition first first) second) TreeFraction.normalizeRealizer +lemma polynomial_normalizedNoise : PolynomialTime normalizedNoiseRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) TreeFraction.polynomial_normalize + +def repeats (z : Input) : ℕ := 64*((normalizedNoise z).2.bits.length+1) +def repeatsRealizer : Realizer repeats := + composition (f := fun z : Input => (64,(normalizedNoise z).2.bits.length+1)) + (g := fun p : ℕ × ℕ => p.1*p.2) + (pair (constant 64) (composition + (composition (composition (composition normalizedNoiseRealizer second) toBits) listLength) + successor)) multiply +lemma polynomial_repeats : PolynomialTime repeatsRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 64) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_normalizedNoise polynomial_second) polynomial_toBits) + polynomial_listLength) polynomial_successor)) polynomial_multiply + +def rootDegree (z : Input) : ℕ := ceiling (TreeFraction.div ((512,1),inner z)) +def rootDegreeRealizer : Realizer rootDegree := + composition (composition (f := fun z : Input => ((512,1),inner z)) (g := TreeFraction.div) + (pair (constant (512,1)) innerRealizer) TreeFraction.divRealizer) ceilingRealizer +lemma polynomial_rootDegree : PolynomialTime rootDegreeRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant _) polynomial_inner) TreeFraction.polynomial_div) polynomial_ceiling + +def depth (z : Input) : ℕ := Nat.clog 2 (rootDegree z) +def depthRealizer : Realizer depth := composition rootDegreeRealizer ceilLogTwoRealizer +lemma polynomial_depth : PolynomialTime depthRealizer := + polynomial_composition polynomial_rootDegree polynomial_ceilLogTwo + +def markers (z : Input) : List Bool × List Bool := (z.2.take (rootDegree z),z.2.take (depth z)) +def markersRealizer : Realizer markers := + pair (composition (pair second rootDegreeRealizer) takeFast) + (composition (pair second depthRealizer) takeFast) +lemma polynomial_markers : PolynomialTime markersRealizer := + polynomial_pair (polynomial_composition (polynomial_pair polynomial_second polynomial_rootDegree) polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second polynomial_depth) polynomial_takeFast) + +def schedule (z : Input) : RootedEstimatorLayoutProgram.Schedule := + ((z.1.2,samples z),((ratioTime z,correctionTime z),offsetAccuracy z)) +def scheduleRealizer : Realizer schedule := + pair (pair (composition first second) samplesRealizer) + (pair (pair ratioTimeRealizer correctionTimeRealizer) offsetAccuracyRealizer) +lemma polynomial_schedule : PolynomialTime scheduleRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_samples) + (polynomial_pair (polynomial_pair polynomial_ratioTime polynomial_correctionTime) polynomial_offsetAccuracy) + +def output (z : Input) : RootedLabelWeightProgram.Config := + (((z.1.1.1,schedule z),repeats z),markers z) +def outputRealizer : Realizer output := + pair (pair (pair (composition (composition first first) first) scheduleRealizer) repeatsRealizer) markersRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_schedule) polynomial_repeats) polynomial_markers + +attribute [local irreducible] output + +def context (z : Input) : RootedEstimatorLayoutProgram.Context := (output z).1.1 +def contextRealizer : Realizer context := + composition (composition (f := output) (g := fun c : RootedLabelWeightProgram.Config => c.1) + outputRealizer first) first +lemma polynomial_context : PolynomialTime contextRealizer := + polynomial_composition (polynomial_composition polynomial_output polynomial_first) polynomial_first +attribute [local irreducible] context + +def contextWidth (z : Input) : ℕ := RootedEstimatorLayoutProgram.wordWidth (context z) +def contextWidthRealizer : Realizer contextWidth := + composition (f := context) (g := RootedEstimatorLayoutProgram.wordWidth) + contextRealizer RootedEstimatorLayoutProgram.wordWidthRealizer +lemma polynomial_contextWidth : PolynomialTime contextWidthRealizer := + polynomial_composition polynomial_context RootedEstimatorLayoutProgram.polynomial_wordWidth +attribute [local irreducible] contextWidth + +def wordWidth (z : Input) : ℕ := repeats z*contextWidth z +def wordWidthRealizer : Realizer wordWidth := + composition (f := fun z : Input => (repeats z,contextWidth z)) + (g := fun p : ℕ × ℕ => p.1*p.2) (pair repeatsRealizer contextWidthRealizer) multiply +theorem polynomial_wordWidth : PolynomialTime wordWidthRealizer := + polynomial_composition (polynomial_pair polynomial_repeats polynomial_contextWidth) polynomial_multiply + +noncomputable section +open CompanionFactorialApplication GridBoundary CompanionOracleDensity +open scoped Classical +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : Input := + (((RootedOracleWalkProgram.data A C 0 K z v,xi),j),reserve) + +lemma fields_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + fields (data A C K j xi z v reserve)=[A.d,K,rationalHeight A C,j] := by + have hh : 10*(C*(A.d*A.d))*(A.W+1)=10*C*A.d^2*(A.W+1) := by ring + exact congrArg (fun h => [A.d,K,h,j]) hh + +lemma inner_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + TreeFraction.val (inner (data A C K j xi z v reserve))= + innerTolerance (TreeFraction.val xi/2) j := by + rw [inner,TreeFraction.div_val,natural_val,scalar,fields_data] + simp only [relativeDenominator,phase,Expr.eval,List.getD_cons_zero,List.getD_cons_succ, + Nat.cast_mul,Nat.cast_add,Nat.cast_one,Nat.cast_ofNat] + unfold innerTolerance + dsimp only [data] + field_simp + ring + +lemma repeats_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + repeats (data A C K j xi z v reserve)=CommonBasesFPRAS.repetitionCount (TreeFraction.val xi) := by + simp only [repeats,normalizedNoise,data,TreeFraction.normalize_repr,TreeFraction.repr, + CommonBasesFPRAS.repetitionCount] + +end +end ContingencyTables.RootedOracleConfigProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2d5375919bb35e32c2ebfe31f7a301a80810472 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleConfigSemantics.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigProgram + +namespace OAI + +/-! # Exact schedules in the computed weight-oracle configuration -/ + +namespace ContingencyTables.RootedOracleConfigProgram + +open MatchingFPRAS CompanionFactorialApplication CompanionOracleDensity GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma scalar_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) (e : ScalarScheduleProgram.Expr) : + scalar e (data A C K j xi z v reserve)=e.eval [A.d,K,rationalHeight A C,j] := by + rw [scalar,fields_data] + +lemma timeInput_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + timeInput (data A C K j xi z v reserve)= + (2*(10000*A.d^2*K)^2,rationalHeight A C+A.d*K+2) := by + simp only [timeInput,scalar_data,mixing,allowance,dim,grid,height, + ScalarScheduleProgram.Expr.eval_power,ScalarScheduleProgram.Expr.eval,List.getD_cons_zero,List.getD_cons_succ] + +lemma correction_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + TreeFraction.val (correction (data A C K j xi z v reserve))= + correctionTheta (innerTolerance (TreeFraction.val xi/2) j) := by + rw [correction,TreeFraction.div_val,inner_data] + simp only [TreeFraction.val,Nat.cast_ofNat,Nat.cast_one,div_one,correctionTheta,Rat.cast_div,Rat.cast_ofNat] + +lemma samples_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + samples (data A C K j xi z v reserve)=sampleCount j (innerTolerance (TreeFraction.val xi/2) j) 1 := by + unfold samples + rw [CountingOracleScheduleProgram.sampleCount_val,inner_data] + simp only [data,TreeFraction.val,Nat.cast_one,div_one] + +lemma ratioTime_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + ratioTime (data A C K j xi z v reserve)= + oracleTime A C K 1 (innerTolerance (TreeFraction.val xi/2) j) := by + rw [ratioTime,timeInput_data,CountingOracleScheduleProgram.oracleTime_instance,inner_data] + +lemma correctionTime_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + correctionTime (data A C K j xi z v reserve)= + oracleTime A C K 1 (correctionTheta (innerTolerance (TreeFraction.val xi/2) j)) := by + rw [correctionTime,timeInput_data,CountingOracleScheduleProgram.oracleTime_instance,correction_data] + +lemma offsetAccuracy_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + offsetAccuracy (data A C K j xi z v reserve)= + CompanionOracleDensity.offsetAccuracy A (innerTolerance (TreeFraction.val xi/2) j) := by + rw [offsetAccuracy,CountingOracleScheduleProgram.offsetAccuracy_val,inner_data,scalar_data] + rfl + +lemma context_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + context (data A C K j xi z v reserve)= + RootedEstimatorMedianProgram.context A C K j (TreeFraction.val xi) z v := by + unfold context output schedule + rw [samples_data,ratioTime_data,correctionTime_data,offsetAccuracy_data] + rfl + +lemma output_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + output (data A C K j xi z v reserve)= + RootedLabelWeightProgram.config A C K j (TreeFraction.val xi) (TreeFraction.val xi) z v + (reserve.take (rootDegree (data A C K j xi z v reserve))) + (reserve.take (depth (data A C K j xi z v reserve))) := by + have hc := context_data A C K j xi z v reserve + have hr := repeats_data A C K j xi z v reserve + change ((context _,repeats _),markers _)=_ + rw [hc,hr] + rfl + +lemma rootDegree_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + rootDegree (data A C K j xi z v reserve)= + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (TreeFraction.val xi/2) j)) := by + rw [rootDegree,CountingOracleScheduleProgram.ceiling_val,TreeFraction.div_val,inner_data] + unfold PowerOfTwoApproximation.rootDegree roundingTolerance + congr 1 + simp only [TreeFraction.val,Nat.cast_ofNat,Nat.cast_one,div_one,div_div_eq_mul_div] + ring + +lemma depth_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + depth (data A C K j xi z v reserve)= + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (TreeFraction.val xi/2) j)) := by + rw [depth,rootDegree_data] + rfl + +lemma marker_lengths (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (hdegree : rootDegree (data A C K j xi z v reserve) ≤ reserve.length) + (hdepth : depth (data A C K j xi z v reserve) ≤ reserve.length) : + (markers (data A C K j xi z v reserve)).1.length= + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (TreeFraction.val xi/2) j)) ∧ + (markers (data A C K j xi z v reserve)).2.length= + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (TreeFraction.val xi/2) j)) := by + simp only [markers,data,List.length_take] + exact ⟨(min_eq_left hdegree).trans (rootDegree_data A C K j xi z v reserve), + (min_eq_left hdepth).trans (depth_data A C K j xi z v reserve)⟩ + +lemma wordWidth_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : TreeFraction.Fraction) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + wordWidth (data A C K j xi z v reserve)= + medianEstimatorBits A C K j (TreeFraction.val xi) (TreeFraction.val xi) := by + rw [wordWidth,contextWidth,context_data,repeats_data, + RootedEstimatorMedianProgram.context,RootedEstimatorWordProgram.scheduledWordWidth] + rfl + +end +end ContingencyTables.RootedOracleConfigProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleCorrection.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleCorrection.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d97104f5d61b9c85187e417ed25434bc80f7403 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleCorrection.lean @@ -0,0 +1,236 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleDensity +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleJointLaw + +namespace OAI + +/-! # Exact population correction for the computed-root completion count + +Integer bins and their executable interval draws are the existing +physical bins. Only their positive density weights change with the +explicit root selector. All normalizer identities are finite sums. +-/ + +namespace ContingencyTables.RootedOracleDensity + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit GridBoundary +open CompanionOracleDensity (dimension index pull binWidth height integerPoint integerBin integerFiber + assignmentCount ownFiber_positive assignmentCount_positive integerFiber_nonempty) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def gridWeight (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℝ := + V A S C a z (realCorner v) + +lemma gridWeight_positive (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + 0 (freeTable A.small A.T A.b f i j:ℤ)))) := by + unfold rho DenseWeights.density D + rw [CompanionOracleDensity.pull_integerPoint] + have hp := RootedScaledPenalty.penalty_at_integer A S C (binWidth A C) + (CompanionOracleDensity.binWidth_positive A C hC) z f + have hr : (fun i j => (ForestCountIdentification.smallX A.small z i j:ℤ))= + ForestScaledPenalty.rowCounts A z := rfl + have hc : (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ))= + ForestScaledPenalty.columnCounts A z := rfl + rw [hr,hc] at hp + rw [hp] + congr 1 + ring + +lemma sum_density_integer (A : Instance I J) (S : Selection A.T) + (C a : ℝ) (hC : 0 ⟨0,by constructor <;> omega⟩⟩ + exact Finset.sum_pos (fun _ _ => gridWeight_positive _ _ _ _ _ _) Finset.univ_nonempty + +noncomputable def correctedMass (A : Instance I J) (S : Selection A.T) + (C a : ℝ) (z : View A → ℕ) (K : ℕ) (hK : 0 simp only [correctedMass,hf,ite_true,ite_false] + _=∑ f∈integerFiber A K hK v,gridWeight A S C a z v/binSum A S C a z K/ + (integerFiber A K hK v).card := by simp only [integerFiber,Finset.sum_filter] + _=_ := by rw [Finset.sum_const,nsmul_eq_mul]; field_simp [hc,hz] + calc + _=∑ v : Grid (I := Fin (dimension A)) K,∑ f : FreeIndex A.small A.T A.b, + if integerBin A K hK f=v then correctedMass A S C a z K hK f else 0 := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro f _ + simp + _=∑ v : Grid (I := Fin (dimension A)) K,gridWeight A S C a z v/binSum A S C a z K := + Finset.sum_congr rfl (fun v _ => hbin v) + _=1 := by rw [←Finset.sum_div]; exact div_self (binSum_positive A S C a z K hK).ne' + +noncomputable def ratioObservable (A : Instance I J) (S : Selection A.T) (C : ℝ) + (a : ℕ) (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℝ := + gridWeight A S C (a+1) z v/gridWeight A S C a z v + +noncomputable def ratioMean (A : Instance I J) (S : Selection A.T) + (C : ℝ) (a : ℕ) (z : View A → ℕ) (K : ℕ) : ℝ := + ∑ v : Grid (I := Fin (dimension A)) K, + (gridWeight A S C a z v/binSum A S C a z K)*ratioObservable A S C a z v + +lemma ratioMean_eq (A : Instance I J) (S : Selection A.T) + (C : ℝ) (a : ℕ) (z : View A → ℕ) (K : ℕ) (hK : 0 simp only [Finset.range_zero,Finset.prod_empty,Nat.cast_zero,binSum_zero,div_self hp] + | succ j ih => + rw [Finset.prod_range_succ,ih,ratioMean_eq A S C j z K hK] + have hz := (binSum_positive A S C j z K hK).ne' + push_cast + field_simp [hp,hz] + +theorem oracle_telescope (A : Instance I J) (S : Selection A.T) (C : ℝ) (hC : 0 ¬Q x))) : + (1/(128*(A.d:ℝ)*K))*min + (∑ v : Selected K Q,V A S C a z (realCorner v.val)) + (∑ v : Selected K (fun x => ¬Q x),V A S C a z (realCorner v.val)) ≤ + ∑ e : CutEdge K Q,min (V A S C a z (realCorner e.val.1)) + (V A S C a z (realCorner e.val.2.1)) := by + obtain ⟨ht,ht1,hr,hsize⟩ := interpolation_bounds A.d K (dimension A) A.hd hK + (ForestScaledPenalty.free_card_le A) + have hh := GridBoundary.weighted_min_cut hPL Q (denseInterpolation A.d K) ht ht1 hr hsize + (rho A S C a z) (fun v => V A S C a z (realCorner v)) + (fun v => DenseWeights.binWeight_pos _ _ _) (rho_continuous A S C a z).continuousOn + (fun x _ => rho_positive A S C a z x) + (fun x _ y _ t ht ht1 => rho_logConcave A S C a hC ha z x (Set.mem_univ _) y (Set.mem_univ _) t ht ht1) + (fun v x hx => by + have hclosed : ClosedBin (corner v) x := fun i => ⟨(hx i).1.le,(hx i).2.le⟩ + exact (bin_comparison A S C a hC ha haH z (realCorner v) x + (fun i => by simpa only [abs_sub_comm] using closedBin_distances A v x hclosed i)).1) + (fun e x hx => tube_comparison A S C a hC ha haH z e (denseInterpolation A.d K*K) + (by positivity) (by linarith) x hx.1) hne hne' + have hg := two_rpow_gain (denseInterpolation A.d K) ht.le + have hm : 0 ≤ min (∑ v : Selected K Q,V A S C a z (realCorner v.val)) + (∑ v : Selected K (fun x => ¬Q x),V A S C a z (realCorner v.val)) := by + apply le_min <;> exact Finset.sum_nonneg (fun _ _ => (DenseWeights.binWeight_pos _ _ _).le) + have he : 1/(128*(A.d:ℝ)*K)=denseInterpolation A.d K/32 := by + unfold denseInterpolation + ring + rw [he] + exact (mul_le_mul_of_nonneg_right (by linarith : denseInterpolation A.d K/32 ≤ + ((2:ℝ)^denseInterpolation A.d K-1)/16) hm).trans hh + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDensity.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDensity.lean new file mode 100644 index 0000000000000000000000000000000000000000..79d35a17876f71e803944155d3a4fd928ae3ec99 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDensity.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledBounds +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFibres + +namespace OAI + +/-! # The selected-root evaluator density on its actual finite bin cube -/ + +namespace ContingencyTables.RootedOracleDensity + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit +open CompanionOracleDensity (dimension index pull binWidth height) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def D (A : Instance I J) (S : Selection A.T) (C : ℝ) + (z : View A → ℕ) (v : Fin (dimension A) → ℝ) : ℝ := + RootedScaledPenalty.penalty A S C (binWidth A C) + (ForestScaledPenalty.rowCounts A z) (ForestScaledPenalty.columnCounts A z) (pull A v) + +lemma D_nonnegative (A : Instance I J) (S : Selection A.T) (C : ℝ) (hC : 0≤ C) + (z : View A → ℕ) (v : Fin (dimension A) → ℝ) : 0≤ D A S C z v := + RootedScaledPenalty.penalty_nonnegative A S C (binWidth A C) hC _ _ _ + +theorem D_bounds (A : Instance I J) (S : Selection A.T) (C : ℝ) (hC : 0 hv ((index A).symm f)) + refine ⟨hh.1,hh.2.trans_eq ?_⟩ + unfold height + ring + +theorem D_change (A : Instance I J) (S : Selection A.T) (C : ℝ) (hC : 0 hvw ((index A).symm f)) + have hd : (A.d:ℝ)≠0 := by exact_mod_cast (show A.d≠0 by have hh := A.hd; omega) + have he : (2*C*(A.d:ℝ)^2/binWidth A C)*r=r/8 := by + unfold binWidth + field_simp [hC.ne',hd] + ring + simpa only [D,he] using hh + +theorem D_continuous (A : Instance I J) (S : Selection A.T) (C : ℝ) + (z : View A → ℕ) : Continuous (D A S C z) := by + have hpull : Continuous (pull A) := continuous_pi (fun f => continuous_apply ((index A).symm f)) + exact (RootedScaledPenalty.penalty_continuous A S C (binWidth A C) + (ForestScaledPenalty.rowCounts A z) (ForestScaledPenalty.columnCounts A z)).comp hpull + +theorem D_convex (A : Instance I J) (S : Selection A.T) (C : ℝ) (hC : 0≤ C) + (z : View A → ℕ) : ConvexOn ℝ Set.univ (D A S C z) := by + refine ⟨convex_univ,?_⟩ + intro v _ w _ a b ha hb hab + exact (RootedScaledPenalty.penalty_convex A S C (binWidth A C) hC + (ForestScaledPenalty.rowCounts A z) (ForestScaledPenalty.columnCounts A z)).2 + (Set.mem_univ (pull A v)) (Set.mem_univ (pull A w)) ha hb hab + +noncomputable def rho (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) : (Fin (dimension A) → ℝ) → ℝ := + DenseWeights.density (a/height A C) (D A S C z) + +noncomputable def V (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) : (Fin (dimension A) → ℝ) → ℝ := + DenseWeights.binWeight (a/height A C) (D A S C z) + +theorem rho_continuous (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) : Continuous (rho A S C a z) := + DenseWeights.density_continuous _ _ (D_continuous A S C z) + +theorem rho_positive (A : Instance I J) (S : Selection A.T) (C a : ℝ) + (z : View A → ℕ) (v : Fin (dimension A) → ℝ) : 0 by simpa only [abs_sub_comm] using hvw i) + exact DenseWeights.bin_density_comparison _ _ w v (hh.trans (by norm_num)) + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb0ff26f9cf9334a04a1ab4e113289cf84b7de86 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleDraw.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFiniteStep +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDraw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # Actual fixed-word corrected draws for the selected-root count -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess FairBits +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +def stationaryIntegerLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : RationalLaw (FreeIndex A.small A.T A.b) := + bindLaw (oracleStationaryLaw A R C a z hK) (exactBinLaw A K (by omega) hW) + +/-- The stationary bin draw followed by the actual uniform integer +interval draw is precisely the corrected mass used in the exact h identity. -/ +theorem stationaryIntegerLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (f : FreeIndex A.small A.T A.b) : + ((stationaryIntegerLaw A R C a z K hK hW).mass f:ℝ)=correctedMass A R C a z K (by omega) f := by + change ((∑ v,(oracleStationaryLaw A R C a z hK).mass v* + (exactBinLaw A K (by omega) hW v).mass f:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,exactBinLaw_mass,oracleStationaryLaw_cast, + oracleChain_pi,apply_ite,Rat.cast_div,Rat.cast_one,Rat.cast_natCast,Rat.cast_zero] + calc + _ = ∑ v : Grid (I := Fin (dimension A)) K, + if integerBin A K (by omega) f=v then + gridWeight A R C a z v/binSum A R C a z K/(integerFiber A K (by omega) v).card else 0 := by + apply Finset.sum_congr rfl + intro v _ + split_ifs <;> simp only [binSum,div_eq_mul_inv,one_mul,mul_zero] + _ = _ := by simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true,correctedMass] + +def sampledIntegerLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : RationalLaw (FreeIndex A.small A.T A.b) := + bindLaw (oracleBitWalkLaw A R C a z v n) (fun w => approximateBinLaw A K (by omega) hW w h) + +/-- Both errors are accounted for once: mixing of the actual bin walk, +then bounded quotient sampling inside its selected bin. -/ +theorem sampledIntegerLaw_variation (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (sampledIntegerLaw A R C a z K hK hW v (oracleTime A C K Q theta) h) + (stationaryIntegerLaw A R C a z K hK hW):ℝ) ≤ + theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)) := by + have hb := variation_bind_uniform (oracleBitWalkLaw A R C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A R C a z hK) (fun w => approximateBinLaw A K (by omega) hW w h) + (exactBinLaw A K (by omega) hW) ((A.d:ℚ)/(2:ℚ)^(4*(h+A.d))) + (fun w => approximateBinLaw_variation A K (by omega) hW w h) + have hbR := (Rat.cast_le (K := ℝ)).mpr hb + simp only [Rat.cast_add,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat] at hbR + exact hbR.trans (add_le_add + (oracleBitWalkLaw_variation A R C a theta hC haH htheta z hz K Q hK hQ hKB hPL hCheeger v) le_rfl) + + +def flatOracleWalk (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) + (bits : Fin (n*oracleStepBits A C) → Bool) : Grid (I := Fin (dimension A)) K := + wordWalk (oracleBitStep A R C a z) v n (oracleWalkWordEquiv n (oracleStepBits A C) bits) + +lemma flatOracleWalk_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*oracleStepBits A C) → Bool)) (flatOracleWalk A R C a z v n)= + oracleBitWalkLaw A R C a z v n := by + unfold flatOracleWalk + rw [←map_equiv (oracleWalkWordEquiv n (oracleStepBits A C)),uniform_equiv] + rfl + +def oracleIntegerDraw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) + (bits : Fin (oracleIntegerBits A C n h) → Bool) : FreeIndex A.small A.T A.b := + let draws := splitWordEquiv (n*oracleStepBits A C) (binWordBits A h) bits + flatBinDraw A K (by omega) hW (flatOracleWalk A R C a z v n draws.1) h draws.2 + +/-- One fixed Boolean word drives the bin walk and then the integer draw. +The bin-dependent interval length never changes the reserved word length. -/ +theorem oracleIntegerDraw_law (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : + mapLaw (uniformLaw (α := Fin (oracleIntegerBits A C n h) → Bool)) + (oracleIntegerDraw A R C a z K hK hW v n h)=sampledIntegerLaw A R C a z K hK hW v n h := by + unfold oracleIntegerDraw oracleIntegerBits + dsimp only + rw [←map_equiv (splitWordEquiv (n*oracleStepBits A C) (binWordBits A h)) + (uniformLaw (α := Fin (n*oracleStepBits A C+binWordBits A h) → Bool)) + (fun draws => flatBinDraw A K (by omega) hW (flatOracleWalk A R C a z v n draws.1) h draws.2), + uniform_equiv,←uniform_product] + rw [mapLaw_product_finish + (uniformLaw (α := Fin (n*oracleStepBits A C) → Bool)) + (uniformLaw (α := Fin (binWordBits A h) → Bool)) + (flatOracleWalk A R C a z v n) (fun w bits => flatBinDraw A K (by omega) hW w h bits), + flatOracleWalk_law] + unfold sampledIntegerLaw + congr 1 + funext w + exact flatBinDraw_law A K (by omega) hW w h + +end +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleEstimator.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleEstimator.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b910b350b470fc11cd25673e1f193d66105e4d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleEstimator.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleSchedule +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleEstimator +import OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentFailures +import OAI.Combinatorics.ContingencyTables.Transport.FiniteProductAccuracy + +namespace OAI + +/-! # The literal rational product estimator for a companion h-value -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteLawMoments FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def observedFactor (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + Option (Fin j) → ℚ + | none => rationalAverage + (correctionSample A R C j z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) + (sampleCount j delta failure) draws.2 + | some a => rationalAverage + (ratioSample A R C a.val z v (oracleTime A C K 1 delta)) + (sampleCount j delta failure) (draws.1 a) + +def targetFactor (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) : Option (Fin j) → ℝ + | none => correctionMean A R C j z K hK hW + | some a => ratioMean A R C a.val z K + +def estimateValue (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : ℚ := + (assignmentCount A:ℚ)*∏ i,observedFactor A R C z K hK hW j delta failure v draws i + +/-- The exact means appearing in the implemented product telescope to +h, including the integer-population correction and the free-assignment count. -/ +theorem targetFactor_product (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) : + (assignmentCount A:ℝ)*(∏ i,targetFactor A R C z K hK hW j i)= + RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z := by + have hp : (∏ a : Fin j,ratioMean A R C a.val z K)= + ∏ a∈Finset.range j,ratioMean A R C a z K := + Fin.prod_univ_eq_prod_range (fun a : ℕ => ratioMean A R (C:ℝ) a z K) j + rw [Fintype.prod_option] + simp only [targetFactor] + rw [hp,correctionMean_eq] + have ht := oracle_telescope A R C (by exact_mod_cast hC) z K (by omega) j + convert ht using 1; ring + +lemma targetFactor_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) (i : Option (Fin j)) : + 0 < targetFactor A R C z K hK hW j i := by + cases i with + | none => + have hh := (correctionMean_bounds A R C j hC hj z K hK hW hB).1 + change 0 < correctionMean A R C j z K hK hW + linarith + | some a => + have hh := (ratioMean_bounds A R C a.val hC z hz hK hB.le).1 + change 0 < ratioMean A R C a.val z K + linarith + +def GoodEstimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : Prop := + ∀ i,|(observedFactor A R C z K hK hW j delta failure v draws i:ℝ)-targetFactor A R C z K hK hW j i| ≤ + (delta:ℝ)*targetFactor A R C z K hK hW j i + +/-- On the event certified by the actual independent block experiments, +the returned rational product estimates the literal original h-value. -/ +theorem goodEstimate_accuracy (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) + (draws : EstimatorInput A C K j (innerTolerance epsilon j) failure) + (hgood : GoodEstimate A R C z K hK hW j (innerTolerance epsilon j) failure v draws) : + (1-(epsilon:ℝ)/4)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z ≤ + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) ∧ + (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) ≤ + (1+(epsilon:ℝ)/4)*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) z := by + have htol : (innerTolerance epsilon j:ℝ)= + (epsilon:ℝ)/(200*(Fintype.card (Option (Fin j)):ℝ)) := by + simp only [innerTolerance,Rat.cast_div,Rat.cast_mul,Rat.cast_ofNat,Rat.cast_add, + Rat.cast_natCast,Rat.cast_one,Fintype.card_option,Fintype.card_fin,Nat.cast_add,Nat.cast_one] + have hprod := FiniteProductAccuracy.product_relative + (fun i => (observedFactor A R C z K hK hW j (innerTolerance epsilon j) failure v draws i:ℝ)) + (targetFactor A R C z K hK hW j) (targetFactor_positive A R C hC z hz K hK hW hB j hj) + epsilon (by exact_mod_cast he0) (by exact_mod_cast he1) + (by intro i; rw [←htol]; exact hgood i) (by simp) + have hcount : (0:ℝ) ≤ assignmentCount A := Nat.cast_nonneg _ + have hlow := mul_le_mul_of_nonneg_left hprod.1 hcount + have hupp := mul_le_mul_of_nonneg_left hprod.2 hcount + have htarget := targetFactor_product A R C hC z K hK hW j + have hvalue : (estimateValue A R C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ)= + (assignmentCount A:ℝ)*∏ i, + (observedFactor A R C z K hK hW j (innerTolerance epsilon j) failure v draws i:ℝ) := by + simp only [estimateValue,Rat.cast_mul,Rat.cast_natCast,Rat.cast_prod] + rw [hvalue] + rw [←htarget] + constructor + · simpa only [mul_left_comm] using hlow + · simpa only [mul_left_comm] using hupp + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFiniteStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFiniteStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce688cf0f1ec2a439adb9473a4d21a3bfab341a7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFiniteStep.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleKernel +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFiniteStep + +namespace OAI + +/-! # Fixed Boolean words realize the selected-root grid chain -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess FairBits +open CompanionOracleDensity (dimension binWidth rationalHeight rationalHeight_cast oracleStepBits oracleTime) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma oracle_acceptance_finite_coin (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v w : Grid (I := Fin (dimension A)) K) : + ((Finset.univ.filter (acceptDyadic + (gridExponent A R C a z w-gridExponent A R C a z v) (rationalHeight A C))).card:ℝ)/ + (2:ℝ)^rationalHeight A C= + min 1 (gridWeight A R C a z w/gridWeight A R C a z v) := by + rw [acceptDyadic_probability] + · rw [gridWeight_eq_dyadic,gridWeight_eq_dyadic,dyadic_ratio_min] + · exact (Nat.sub_le _ _).trans ((gridExponent_upper A R C a hC z hz hKB w).trans haH) + +def finiteOracleStepLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : RationalLaw (Grid (I := Fin (dimension A)) K) := + finiteAcceptLaw v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A R C a z w-gridExponent A R C a z v) (rationalHeight A C)) + +/-- Every valid direction has one code; unused directions, boundary +proposals and failed dyadic tests stay at the starting vertex. -/ +theorem finiteOracleStepLaw_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + finiteOracleStepLaw A R C a z v=oracleTransitionLaw A R C a z hK v := by + apply RationalLaw.eq_of_off_diagonal _ _ v + intro w hwv + apply Rat.cast_injective (α := ℝ) + change ((finiteAcceptLaw v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A R C a z w-gridExponent A R C a z v) + (rationalHeight A C))).mass w:ℝ)=(oracleTransition A R C a z v w:ℝ) + rw [finiteAcceptLaw_off_diagonal v w _ _ hwv.symm, + axisCodeStep_count (dense_proposal_code_bound A.d (dimension A) (ForestScaledPenalty.free_card_le A))] + simp only [Rat.cast_mul,Rat.cast_div,Rat.cast_natCast,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] + push_cast + rw [Finset.filter_congr_decidable (Finset.univ : Finset (Fin (2^rationalHeight A C))) + (acceptDyadic (gridExponent A R C a z w-gridExponent A R C a z v) (rationalHeight A C)) + (fun bits => Classical.propDecidable _)] + rw [oracle_acceptance_finite_coin A R C a hC haH z hz hKB v w] + unfold oracleTransition + rw [ite_eq_right hwv.symm,add_zero,oracleMove_cast] + unfold MetropolisChain.move binProposal + by_cases hvw : Neighbor v w <;> simp [hvw] + +def oracleBitStep (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (oracleStepBits A C) → Bool) : Grid (I := Fin (dimension A)) K := + let draw := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) bits + match axisCodeStep v draw.1 with + | none => v + | some w => if draw.2.val < 2^(rationalHeight A C-(gridExponent A R C a z w-gridExponent A R C a z v)) + then w else v + +def oracleBitStepLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : RationalLaw (Grid (I := Fin (dimension A)) K) := + mapLaw (uniformLaw (α := Fin (oracleStepBits A C) → Bool)) (oracleBitStep A R C a z v) + +lemma oracleBitStepLaw_eq_finite (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + oracleBitStepLaw A R C a z v=finiteOracleStepLaw A R C a z v := by + let E := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) + let f := finiteAcceptStep v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A R C a z w-gridExponent A R C a z v) (rationalHeight A C)) + have hf : oracleBitStep A R C a z v=fun bits => f (E bits) := by + funext bits + dsimp [oracleBitStep,f,E,finiteAcceptStep] + simp only [acceptDyadic] + cases axisCodeStep v ((pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C)) bits).1 with + | none => rfl + | some w => dsimp only; split_ifs <;> rfl + unfold oracleBitStepLaw + rw [hf] + change mapLaw (uniformLaw (α := Fin (Nat.clog 2 (8*A.d)+rationalHeight A C) → Bool)) + (fun bits => f (E bits))=_ + rw [←map_equiv E,uniform_equiv,←uniform_product] + rfl + +theorem oracleBitStepLaw_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + oracleBitStepLaw A R C a z v=oracleTransitionLaw A R C a z hK v := by + rw [oracleBitStepLaw_eq_finite] + exact finiteOracleStepLaw_eq A R C a hC haH z hz hK hKB v + +def oracleBitWalkLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : RationalLaw (Grid (I := Fin (dimension A)) K) := + wordWalkLaw (oracleBitStep A R C a z) v n + +/-- A fixed rectangular Boolean array realizes the complete independent +finite walk whose mixing estimate was proved for the real chain. -/ +theorem oracleBitWalkLaw_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + oracleBitWalkLaw A R C a z v n=oracleWalkLaw A R C a z hK v n := by + unfold oracleBitWalkLaw oracleWalkLaw + rw [wordWalkLaw_eq] + have he : (fun w : Grid (I := Fin (dimension A)) K => + mapLaw (uniformLaw (α := Fin (oracleStepBits A C) → Bool)) (oracleBitStep A R C a z w))= + oracleTransitionLaw A R C a z hK := by + funext w + exact oracleBitStepLaw_eq A R C a hC haH z hz hK hKB w + rw [he] + +theorem oracleBitWalkLaw_variation (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (oracleBitWalkLaw A R C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A R C a z hK):ℝ) ≤ theta/(8*Q) := by + rw [oracleBitWalkLaw_eq A R C a hC haH z hz hK hKB] + apply oracleWalkLaw_variation A R C a theta hC _ htheta z hz K Q hK hQ hKB hPL hCheeger v + rw [←rationalHeight_cast] + exact_mod_cast haH + +end +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFlatProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFlatProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a61820f9fc4db6a974e82e1ce2fed604ab53ff49 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleFlatProgram.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWalkProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogWalk +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk + +namespace OAI + +/-! # A polynomial flat-word program for the actual oracle walk -/ + +namespace ContingencyTables.RootedOracleWalkProgram + +open MatchingFPRAS.TreeTyped DensePrograms +open scoped Classical + +def proposalWidth (z : Frame) : ℕ := Nat.clog 2 (8*z.2.1.1.1) +def proposalWidthRealizer : Realizer proposalWidth := by + let D : Realizer (fun z : Frame => z.2.1.1.1) := + composition (composition (composition second first) first) first + let M : Realizer (fun z : Frame => 8*z.2.1.1.1) := + composition (f := fun z : Frame => (8,z.2.1.1.1)) + (g := fun x : ℕ×ℕ => x.1*x.2) (pair (constant 8) D) multiply + exact composition (f := fun z : Frame => 8*z.2.1.1.1) + (g := Nat.clog 2) M ceilLogTwoRealizer +lemma polynomial_proposalWidth : PolynomialTime proposalWidthRealizer := by + have hd : PolynomialTime (composition + (composition (composition (second (A := ℕ) (B := RootedPenaltyEvaluateProgram.Parameters× + RootedDemandProgram.Input)) first) first) first) := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_first) polynomial_first) polynomial_first + unfold proposalWidthRealizer + exact polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 8) hd) polynomial_multiply) polynomial_ceilLogTwo + +def stepWidth (z : Frame) : ℕ := proposalWidth z+RootedPenaltyEvaluateProgram.height z.2.1 +def stepWidthRealizer : Realizer stepWidth := + composition (f := fun z : Frame => (proposalWidth z,RootedPenaltyEvaluateProgram.height z.2.1)) + (g := fun x : ℕ×ℕ => x.1+x.2) + (pair proposalWidthRealizer + (composition (f := fun z : Frame => z.2.1) (g := RootedPenaltyEvaluateProgram.height) + (composition second first) RootedPenaltyEvaluateProgram.heightRealizer)) add +lemma polynomial_stepWidth : PolynomialTime stepWidthRealizer := + polynomial_composition (polynomial_pair polynomial_proposalWidth + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + RootedPenaltyEvaluateProgram.polynomial_height)) polynomial_add + +def flatWalk (z : State×List Bool) : State := + walkWords (z.1,wordChunks (stepWidth z.1.1,z.2)) +def flatWalkRealizer : Realizer flatWalk := + composition (f := fun z : State×List Bool => (z.1,wordChunks (stepWidth z.1.1,z.2))) + (g := walkWords) + (pair first (composition (f := fun z : State×List Bool => (stepWidth z.1.1,z.2)) + (g := wordChunks) + (pair (composition (f := fun z : State×List Bool => z.1.1) (g := stepWidth) + (composition first first) stepWidthRealizer) second) wordChunksRealizer)) walkWordsRealizer +theorem polynomial_flatWalk : PolynomialTime flatWalkRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_stepWidth) polynomial_second) polynomial_wordChunks)) polynomial_walkWords + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary FirstSuccess ResidualMixture + +noncomputable section +variable {m n : ℕ} + +lemma stepWidth_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + stepWidth (data A C a K z v).1=CompanionOracleDensity.oracleStepBits A C := by + change Nat.clog 2 (8*A.d)+RootedPenaltyEvaluateProgram.height ((A.d,A.W),(C,a))=_ + rw [RootedPenaltyEvaluateProgram.height_data] + rfl + +lemma stepWidth_pos (A : Instance (Fin m) (Fin n)) (C : ℕ) (hC : 0 < C) : + 0 < CompanionOracleDensity.oracleStepBits A C := by + have hd : 0 < A.d := lt_of_lt_of_le Nat.zero_lt_one A.hd + have hh : 0 < CompanionOracleDensity.rationalHeight A C := by + unfold CompanionOracleDensity.rationalHeight + positivity + exact hh.trans_le (Nat.le_add_left _ _) + +/-- Every flat input bit is split into the prescribed independent step +words, and the polynomial program computes their literal finite walk. -/ +theorem flatWalk_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (N : ℕ) (bits : Fin (N*CompanionOracleDensity.oracleStepBits A C) → Bool) : + flatWalk (data A C a K z v,List.ofFn bits)= + data A C a K z (wordWalk (RootedCatalogGrid.bitStep A C a z) v N + (gridWordEquiv N (CompanionOracleDensity.oracleStepBits A C) bits)) := by + unfold flatWalk + rw [stepWidth_data,wordChunks_ofFn (stepWidth_pos A C hC) bits] + exact walkWords_ofFn A C a K hC z v N _ + +def flatGridWalk (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) + (bits : Fin (N*CompanionOracleDensity.oracleStepBits A C) → Bool) : + Grid (I := Fin (RootedCatalogGrid.freeCount A)) K := + wordWalk (RootedCatalogGrid.bitStep A C a z) v N + (gridWordEquiv N (CompanionOracleDensity.oracleStepBits A C) bits) + +lemma flatGridWalk_law (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) : + mapLaw (uniformLaw (α := Fin (N*CompanionOracleDensity.oracleStepBits A C) → Bool)) + (flatGridWalk A C a z v N)=wordWalkLaw (RootedCatalogGrid.bitStep A C a z) v N := by + unfold flatGridWalk + rw [←FairBits.map_equiv (gridWordEquiv N (CompanionOracleDensity.oracleStepBits A C)), + FairBits.uniform_equiv] + rfl + +end +end ContingencyTables.RootedOracleWalkProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..3417ed460e987742a3264b9b360d53024c6951aa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleKernel.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleMixing +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleRational +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleKernel + +namespace OAI + +/-! # Exact rational grid transitions for the selected-root evaluator -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open CompanionOracleDensity (dimension height binWidth height_positive oracleProposalRat oracleTime) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem gridExponent_upper (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + gridExponent A R C a z v ≤ a := by + have hCR : (0:ℝ) < C := by exact_mod_cast hC + have hD := D_bounds A R C hCR z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + have hH := height_positive A C hCR + have hbound : (a:ℝ)/height A C*D A R C z (realCorner v) ≤ a := by + calc + _ ≤ (a:ℝ)/height A C*height A C := + mul_le_mul_of_nonneg_left hD.2 (div_nonneg (Nat.cast_nonneg _) hH.le) + _ = _ := div_mul_cancel₀ _ hH.ne' + have he := gridExponent_eq_floor A R C a z v + have hh := (Int.floor_le ((a:ℝ)/height A C*D A R C z (realCorner v))).trans hbound + rw [←he] at hh + exact_mod_cast hh + +lemma rationalGridWeight_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : 0 < rationalGridWeight A R C a z v := by + unfold rationalGridWeight + positivity +def oracleMove (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : ℚ := + if Neighbor v w then oracleProposalRat A.d*min 1 + (rationalGridWeight A R C a z w/rationalGridWeight A R C a z v) else 0 + +def oracleTransition (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : ℚ := + oracleMove A R C a z v w+if v=w then 1-∑ b,oracleMove A R C a z v b else 0 + +lemma oracleMove_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : + (oracleMove A R C a z v w:ℝ)= + MetropolisChain.move (gridWeight A R C a z) Neighbor (binProposal A.d) v w := by + unfold oracleMove MetropolisChain.move + split_ifs + · simp only [Rat.cast_mul,Rat.cast_min,Rat.cast_one,Rat.cast_div, + rationalGridWeight_cast,oracleProposalRat,binProposal,Rat.cast_pow,Rat.cast_ofNat] + · exact Rat.cast_zero + +theorem oracleTransition_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v w : Grid (I := Fin (dimension A)) K) : + (oracleTransition A R C a z v w:ℝ)=(oracleChain A R C a z hK).P v w := by + unfold oracleTransition + dsimp only [oracleChain,MetropolisChain.chain,FiniteChain.ofMoves] + by_cases hvw : v=w <;> + simp only [hvw,ite_true,ite_false,Rat.cast_add,Rat.cast_sub,Rat.cast_sum, + Rat.cast_one,Rat.cast_zero,oracleMove_cast] + +def oracleTransitionLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + RationalLaw (Grid (I := Fin (dimension A)) K) where + mass := oracleTransition A R C a z v + nonnegative := fun w => by + have hh := (oracleChain A R C a z hK).nonnegative v w + rw [←oracleTransition_cast A R C a z hK] at hh + exact_mod_cast hh + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum,oracleTransition_cast A R C a z hK,Rat.cast_one] + exact (oracleChain A R C a z hK).stochastic v + +def oracleWalkLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + RationalLaw (Grid (I := Fin (dimension A)) K) := + walkLaw (oracleTransitionLaw A R C a z hK) v n + +theorem oracleWalkLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (n : ℕ) (v w : Grid (I := Fin (dimension A)) K) : + ((oracleWalkLaw A R C a z hK v n).mass w:ℝ)= + ((oracleChain A R C a z hK).kernel.power n).P v w := by + induction n generalizing w with + | zero => + simp only [oracleWalkLaw,walkLaw,pointLaw,FiniteKernel.power,FiniteKernel.identity] + by_cases hvw : v=w + · subst w; simp + · simp [hvw,Ne.symm hvw] + | succ n ih => + change ((∑ b,(oracleWalkLaw A R C a z hK v n).mass b*oracleTransition A R C a z b w:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,ih,oracleTransition_cast A R C a z hK, + FiniteKernel.power,FiniteKernel.comp,FiniteChain.kernel] + +def oracleStationaryLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : RationalLaw (Grid (I := Fin (dimension A)) K) := by + let : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + let w := fun v : Grid (I := Fin (dimension A)) K => rationalGridWeight A R C a z v + have hw : ∀ v,0 < w v := rationalGridWeight_positive A R C a z + have hZ : 0 < ∑ v,w v := Finset.sum_pos (fun v _ => hw v) Finset.univ_nonempty + exact ⟨fun v => w v/∑ b,w b,fun v => (div_pos (hw v) hZ).le, + by rw [←Finset.sum_div]; exact div_self hZ.ne'⟩ + +theorem oracleStationaryLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + ((oracleStationaryLaw A R C a z hK).mass v:ℝ)=(oracleChain A R C a z hK).π v := by + change ((rationalGridWeight A R C a z v/ + ∑ w : Grid (I := Fin (dimension A)) K,rationalGridWeight A R C a z w:ℚ):ℝ)=_ + simp only [Rat.cast_div,Rat.cast_sum,rationalGridWeight_cast] + rfl + +/-- The rational finite-walk law inherits the proved source schedule. +No exact real-valued primitive is used to define its transitions. -/ +theorem oracleWalkLaw_variation (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : (a:ℝ) ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (oracleWalkLaw A R C a z hK v (oracleTime A C K Q theta)) + (oracleStationaryLaw A R C a z hK):ℝ) ≤ theta/(8*Q) := by + let P := oracleChain A R C a z hK + let n := oracleTime A C K Q theta + let delta : ℝ := theta/(8*Q) + have hpoint (w : Grid (I := Fin (dimension A)) K) : + |(P.kernel.power n).P v w-P.π w| ≤ P.π w*delta := by + have hm := oracleChain_scheduled_point_mixing A R C a theta + (by exact_mod_cast hC) (Nat.cast_nonneg _) haH htheta z hz K Q hK hQ hKB hPL hCheeger v w + change |P.iterate n (P.pointDensity w) v-1| ≤ delta at hm + rw [←P.kernel_power_density] at hm + calc + _ = P.π w*|(P.kernel.power n).P v w/P.π w-1| := by + calc + _ = |P.π w*((P.kernel.power n).P v w/P.π w-1)| := by + congr 1 + field_simp [(P.positive w).ne'] + _ = _ := by rw [abs_mul,abs_of_pos (P.positive w)] + _ ≤ _ := mul_le_mul_of_nonneg_left hm (P.positive w).le + have hsum := Finset.sum_le_sum (fun w (_ : w∈Finset.univ) => hpoint w) + rw [←Finset.sum_mul,P.normalized,one_mul] at hsum + unfold variation + simp only [Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat, + oracleWalkLaw_cast,oracleStationaryLaw_cast] + change (∑ w,|(P.kernel.power n).P v w-P.π w|)/2 ≤ delta + have hd : 0 ≤ delta := by dsimp only [delta]; positivity + linarith + +end +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..6809b68495d9247ee156314900957a2f340346c5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleMixing.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleChain +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleBudget + +namespace OAI + +/-! # Explicit point and total-variation mixing for the selected-root grid -/ + +namespace ContingencyTables.RootedOracleDensity + +open CommonBasesFPRAS GridBoundary CompanionFactorialApplication +open CompanionOracleDensity (dimension height binWidth height_positive oracle_grid_card + mixingConstant mixingConstant_ge_one cutConstant cutConstant_lower oracleTime oracle_time_error) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma gridWeight_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (_haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + (2:ℝ)^(-a) ≤ gridWeight A R C a z v ∧ gridWeight A R C a z v ≤ 1 := by + have hD := D_bounds A R C hC z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + have hH := height_positive A C hC + have he0 : 0 ≤ a/height A C*D A R C z (realCorner v) := + mul_nonneg (div_nonneg ha hH.le) hD.1 + have he1 : a/height A C*D A R C z (realCorner v) ≤ a := by + calc + _ ≤ a/height A C*height A C := + mul_le_mul_of_nonneg_left hD.2 (div_nonneg ha hH.le) + _ = a := div_mul_cancel₀ a hH.ne' + have hf0 : (0:ℤ) ≤ ⌊a/height A C*D A R C z (realCorner v)⌋ := + Int.floor_nonneg.mpr he0 + have hf1 := (Int.floor_le (a/height A C*D A R C z (realCorner v))).trans he1 + unfold gridWeight V DenseWeights.binWeight + constructor + · exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + · calc + _ ≤ (2:ℝ)^(0:ℝ) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by exact_mod_cast neg_nonpos.mpr hf0) + _ = 1 := Real.rpow_zero _ + +lemma oracleChain_pi_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hK : 1 ≤ K) + (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + (2:ℝ)^(-a)/(K:ℝ)^dimension A ≤ (oracleChain A R C a z hK).π v := by + let : Nonempty (Grid (I := Fin (dimension A)) K) := ⟨v⟩ + have hsumpos : 0 < ∑ w : Grid (I := Fin (dimension A)) K,gridWeight A R C a z w := + Finset.sum_pos (fun _ _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty + have hsum : (∑ w : Grid (I := Fin (dimension A)) K,gridWeight A R C a z w) ≤ + (K:ℝ)^dimension A := by + calc + _ ≤ ∑ _w : Grid (I := Fin (dimension A)) K,(1:ℝ) := + Finset.sum_le_sum (fun w _ => (gridWeight_bounds A R C a hC ha haH z hz hKB w).2) + _ = _ := by simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one, + oracle_grid_card,Nat.cast_pow] + rw [oracleChain_pi] + exact div_le_div₀ (DenseWeights.binWeight_pos _ _ _).le + (gridWeight_bounds A R C a hC ha haH z hz hKB v).1 hsumpos hsum + +theorem oracleChain_polynomial_poincare (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + ∀ f,(oracleChain A R C a z hK).variance f ≤ + mixingConstant A K*(oracleChain A R C a z hK).energy f := by + intro f + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hk : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hlo := cutConstant_lower A hK + have hb : 2/(cutConstant A K)^2 ≤ mixingConstant A K := by + calc + _ ≤ 2/(1/(10000*(A.d:ℝ)^2*K))^2 := by + apply div_le_div_of_nonneg_left (by norm_num) (by positivity) + exact pow_le_pow_left₀ (by positivity) hlo 2 + _ = _ := by unfold mixingConstant; field_simp [hd.ne',hk.ne'] + exact (oracleChain_poincare A R C a hC ha haH z hK hPL hCheeger f).trans + (mul_le_mul_of_nonneg_right hb (FiniteChain.energy_nonneg _ f)) + +/-- Pointwise relative mixing for the implemented dyadic-proposal +Metropolis chain; this also bounds total variation. -/ +theorem oracleChain_point_mixing (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hK : 1 ≤ K) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (n : ℕ) (v w : Grid (I := Fin (dimension A)) K) : + |(oracleChain A R C a z hK).iterate n ((oracleChain A R C a z hK).pointDensity w) v-1| ≤ + Real.exp (-(n:ℝ)/mixingConstant A K)/((2:ℝ)^(-a)/(K:ℝ)^dimension A) := by + have hKR : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + apply FiniteChain.point_mixing_exp + · exact mixingConstant_ge_one A hK + · positivity + · exact oracleChain_pi_lower A R C a hC ha haH z hz hK hKB + · exact oracleChain_polynomial_poincare A R C a hC ha haH z hK hPL hCheeger + +/-- The actual dyadic Metropolis chain attains the per-draw error used +in the evaluator's union bound at the explicit finite source schedule. -/ +theorem oracleChain_scheduled_point_mixing (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a theta : ℝ) + (hC : 0 < C) (ha : 0 ≤ a) (haH : a ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v w : Grid (I := Fin (dimension A)) K) : + |(oracleChain A R C a z hK).iterate (oracleTime A C K Q theta) + ((oracleChain A R C a z hK).pointDensity w) v-1| ≤ theta/(8*Q) := + (oracleChain_point_mixing A R C a hC ha haH z hz hK hKB hPL hCheeger _ v w).trans + (oracle_time_error A C a theta ha haH htheta K Q hK hQ) + +theorem oracleChain_scheduled_total_variation (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a theta : ℝ) + (hC : 0 < C) (ha : 0 ≤ a) (haH : a ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (w : Grid (I := Fin (dimension A)) K) : + let P := oracleChain A R C a z hK + (∑ v, |P.π v*P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-P.π v|)/2 ≤ + theta/(8*Q) := by + let P := oracleChain A R C a z hK + have hpoint (v : Grid (I := Fin (dimension A)) K) : + |P.π v*P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-P.π v| ≤ + P.π v*(theta/(8*Q)) := by + calc + _ = P.π v*|P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-1| := by + rw [←mul_sub_one,abs_mul,abs_of_pos (P.positive v)] + _ ≤ _ := mul_le_mul_of_nonneg_left + (oracleChain_scheduled_point_mixing A R C a theta hC ha haH htheta z hz K Q hK hQ + hKB hPL hCheeger v w) (P.positive v).le + have hsum := Finset.sum_le_sum (fun v (_ : v∈Finset.univ) => hpoint v) + rw [←Finset.sum_mul,P.normalized,one_mul] at hsum + change _ ≤ theta/(8*Q) + have he : (0:ℝ) ≤ theta/(8*Q) := by positivity + linarith + +end +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleRational.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b131d6314ab80bbe043744e685f989045541563 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleRational.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleCorrection +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenaltyProgram + +namespace OAI + +/-! # The computed-root grid weights are exactly dyadic rational values -/ + +namespace ContingencyTables.RootedOracleDensity + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit GraphCompletionCounts GridBoundary +open CompanionOracleDensity (dimension index height rationalHeight naturalBin) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def rationalD (A : Instance I J) (S : Selection A.T) (C : ℕ) + (z : View A → ℕ) (v : Fin (dimension A) → ℚ) : ℚ := + RootedPenaltyProgram.rationalPenalty A S C (ForestScaledPenalty.rowCounts A z) + (ForestScaledPenalty.columnCounts A z) (fun f => v ((index A).symm f)) + +theorem rationalD_cast (A : Instance I J) (S : Selection A.T) (C : ℕ) + (z : View A → ℕ) (v : Fin (dimension A) → ℚ) : + (rationalD A S C z v:ℝ)=D A S C z (fun i => (v i:ℝ)) := by + rw [rationalD,RootedPenaltyProgram.rationalPenalty_cast] + rfl + +lemma rationalD_nonnegative (A : Instance I J) (S : Selection A.T) (C : ℕ) + (z : View A → ℕ) (v : Fin (dimension A) → ℚ) : 0≤ rationalD A S C z v := by + have hh := D_nonnegative A S C (Nat.cast_nonneg C) z (fun i => (v i:ℝ)) + rw [←rationalD_cast] at hh + exact_mod_cast hh + +noncomputable def gridExponent (A : Instance I J) (S : Selection A.T) (C a : ℕ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℕ := + ⌊(a:ℚ)/rationalHeight A C*rationalD A S C z (fun i => (corner v i:ℚ))⌋₊ + +theorem gridExponent_eq_floor (A : Instance I J) (S : Selection A.T) (C a : ℕ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (gridExponent A S C a z v:ℤ)=⌊(a:ℝ)/height A C*D A S C z (realCorner v)⌋ := by + have hn := mul_nonneg (div_nonneg (Nat.cast_nonneg a) (Nat.cast_nonneg (rationalHeight A C))) + (rationalD_nonnegative A S C z (fun i => (corner v i:ℚ))) + rw [gridExponent,Int.natCast_floor_eq_floor hn] + have he : (((a:ℚ)/rationalHeight A C*rationalD A S C z (fun i => (corner v i:ℚ)):ℚ):ℝ)= + (a:ℝ)/height A C*D A S C z (realCorner v) := by + simp only [Rat.cast_mul,Rat.cast_div,Rat.cast_natCast, + CompanionOracleDensity.rationalHeight_cast,rationalD_cast,Rat.cast_intCast] + rfl + rw [←he,Rat.floor_cast] + +theorem gridWeight_eq_dyadic (A : Instance I J) (S : Selection A.T) (C a : ℕ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + gridWeight A S C a z v=1/(2:ℝ)^gridExponent A S C a z v := by + unfold gridWeight V DenseWeights.binWeight + rw [←gridExponent_eq_floor] + simp only [Int.cast_natCast,Real.rpow_neg (by norm_num : (0:ℝ)≤2),Real.rpow_natCast,one_div] + +noncomputable def rationalGridWeight (A : Instance I J) (S : Selection A.T) (C a : ℕ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℚ := + 1/(2:ℚ)^gridExponent A S C a z v + +theorem rationalGridWeight_cast (A : Instance I J) (S : Selection A.T) (C a : ℕ) + (z : View A → ℕ) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (rationalGridWeight A S C a z v:ℝ)=gridWeight A S C a z v := by + rw [gridWeight_eq_dyadic] + simp only [rationalGridWeight,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] + +theorem exponentCode_grid (A : Instance I J) (S : Selection A.T) (C a : ℕ) (hC : 0 (naturalBin A v f:ℚ))= + (fun f => (corner v ((index A).symm f):ℚ)) := by + funext f + exact_mod_cast CompanionOracleDensity.naturalBin_cast A v f + rw [RootedPenaltyProgram.exponentCode_data A S C a hC] + unfold gridExponent rationalD + rw [he] + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..272d5c10ac5d1d686660676c4a3625cc13703ebe --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleSchedule.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSamples +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSamples +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleSchedule + +namespace OAI + +/-! # Explicit accuracy and sample-count parameters for the weight oracle -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open FiniteLawMoments FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The concrete correction schedule discharges both arithmetic error +allowances; only the named published PL/Cheeger inputs remain. -/ +theorem scheduled_correction_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a j : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (delta failure : ℚ) + (hdelta : 0 < delta) (hdelta1 : delta < 1) (hfailure : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin (sampleCount j delta failure) → + (Fin (oracleIntegerBits A C (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) → Bool) => + if (delta:ℝ)*correctionMean A R C a z K hK hW < + |sampleAverage (fun bits => + (correctionSample A R C a z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) bits:ℝ)) + (sampleCount j delta failure) draws-correctionMean A R C a z K hK hW| then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hs : (0:ℚ) < roundingTolerance delta := by unfold roundingTolerance; positivity + have hsHalf : roundingTolerance delta ≤ 1/2 := by unfold roundingTolerance; linarith + have hsDelta : (roundingTolerance delta:ℝ) ≤ (delta:ℝ)/4 := by + simp only [roundingTolerance,Rat.cast_div,Rat.cast_ofNat,le_refl] + exact (correctionSamples_failure A R C a (correctionTheta delta) delta hC haH + (by unfold correctionTheta; positivity) hd z hz K 1 (offsetAccuracy A delta) + (sampleCount j delta failure) hK (by decide) hW (sampleCount_positive j delta failure hdelta hfailure) + hB (roundingTolerance delta) hs hsHalf hsDelta (by simpa only [Nat.cast_one] using correction_noise_budget A delta hdelta) + hPL hCheeger v).trans (sampleCount_budget j delta failure hdelta hfailure) + + +theorem scheduled_ratio_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a j : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (delta failure : ℚ) + (hdelta : 0 < delta) (hfailure : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K : ℕ) (hK : 1 ≤ K) (hB : (K:ℝ)=binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin (sampleCount j delta failure) → + RatioWords A C (oracleTime A C K 1 delta) => + if (delta:ℝ)*ratioMean A R C a z K < + |sampleAverage (fun bits => (ratioSample A R C a z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) draws-ratioMean A R C a z K| then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hn := sampleCount_positive j delta failure hdelta hfailure + have hh := ratioSamples_failure A R C a delta hC haH hd z hz K 1 (sampleCount j delta failure) + hK (by decide) hn hB.le hPL hCheeger v + apply hh.trans + calc + 16/((sampleCount j delta failure:ℝ)*(delta:ℝ)^2) ≤ + 16384/((sampleCount j delta failure:ℝ)*(delta:ℝ)^2) := + div_le_div_of_nonneg_right (by norm_num) (by positivity) + _ ≤ _ := sampleCount_budget j delta failure hdelta hfailure + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleStepProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleStepProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ff5fc6c91228d450581f7f5823db08ed60e97f3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleStepProgram.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogStep +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisSemantics + +namespace OAI + +/-! # Polynomial execution of the catalog-order oracle step + +The program uses the computed forest exponent twice, one arithmetic +axis proposal and one independent bounded dyadic acceptance word. +-/ + +namespace ContingencyTables.RootedOracleStepProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open scoped Classical + +abbrev Data := ℕ×RootedPenaltyEvaluateProgram.Input +abbrev StepInput := Data×(List Bool×List Bool) + +def replace (z : RootedPenaltyEvaluateProgram.Input×List ℕ) : + RootedPenaltyEvaluateProgram.Input := (z.1.1,(z.1.2.1,z.2)) +def replaceRealizer : Realizer replace := + pair (composition first first) (pair (composition (composition first second) first) second) +lemma polynomial_replace : PolynomialTime replaceRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) polynomial_second) + +def candidate (z : StepInput) : Option (List ℕ) := + axisWordStep ((z.1.1,z.1.2.2.2),z.2.1) +def candidateRealizer : Realizer candidate := + composition (f := fun z : StepInput => ((z.1.1,z.1.2.2.2),z.2.1)) (g := axisWordStep) + (pair (pair (composition first first) + (composition (composition (composition first second) second) second)) + (composition second first)) axisWordStepRealizer +lemma polynomial_candidate : PolynomialTime candidateRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_second)) + (polynomial_composition polynomial_second polynomial_first)) polynomial_axisWordStep + +def currentData (z : StepInput×List ℕ) : RootedPenaltyEvaluateProgram.Input := z.1.1.2 +def currentDataRealizer : Realizer currentData := composition (composition first first) second +lemma polynomial_currentData : PolynomialTime currentDataRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + +def candidateData (z : StepInput×List ℕ) : RootedPenaltyEvaluateProgram.Input := + replace (currentData z,z.2) +def candidateDataRealizer : Realizer candidateData := + composition (f := fun z : StepInput×List ℕ => (currentData z,z.2)) (g := replace) + (pair currentDataRealizer second) replaceRealizer +lemma polynomial_candidateData : PolynomialTime candidateDataRealizer := + polynomial_composition (polynomial_pair polynomial_currentData polynomial_second) polynomial_replace + +def gap (z : StepInput×List ℕ) : ℕ := + RootedPenaltyEvaluateProgram.evaluate (candidateData z)- + RootedPenaltyEvaluateProgram.evaluate (currentData z) +def gapRealizer : Realizer gap := + composition (f := fun z : StepInput×List ℕ => + (RootedPenaltyEvaluateProgram.evaluate (candidateData z), + RootedPenaltyEvaluateProgram.evaluate (currentData z))) (g := fun z => z.1-z.2) + (pair + (composition (f := candidateData) (g := RootedPenaltyEvaluateProgram.evaluate) + candidateDataRealizer RootedPenaltyEvaluateProgram.evaluateRealizer) + (composition (f := currentData) (g := RootedPenaltyEvaluateProgram.evaluate) + currentDataRealizer RootedPenaltyEvaluateProgram.evaluateRealizer)) subtract +lemma polynomial_gap : PolynomialTime gapRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_candidateData RootedPenaltyEvaluateProgram.polynomial_evaluate) + (polynomial_composition polynomial_currentData RootedPenaltyEvaluateProgram.polynomial_evaluate)) + polynomial_subtract + +def acceptCandidate (z : StepInput×List ℕ) : List ℕ := + if dyadicWordAccept (z.1.2.2,gap z) then z.2 else z.1.1.2.2.2 +def acceptCandidateRealizer : Realizer acceptCandidate := + choose + (composition (f := fun z : StepInput×List ℕ => (z.1.2.2,gap z)) (g := dyadicWordAccept) + (pair (composition (composition first second) second) gapRealizer) dyadicWordAcceptRealizer) + second (composition (composition currentDataRealizer second) second) +lemma polynomial_acceptCandidate : PolynomialTime acceptCandidateRealizer := + polynomial_choose (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_gap) polynomial_dyadicWordAccept) polynomial_second + (polynomial_composition (polynomial_composition polynomial_currentData polynomial_second) + polynomial_second) + +def step (z : StepInput) : List ℕ := + (candidate z).elim z.1.2.2.2 (fun xs => acceptCandidate (z,xs)) +def stepRealizer : Realizer step := + composition (f := fun z : StepInput => (z,candidate z)) + (g := fun z => z.2.elim z.1.1.2.2.2 (fun xs => acceptCandidate (z.1,xs))) + (pair identity candidateRealizer) + (optionCases (composition (composition (composition first second) second) second) + acceptCandidateRealizer) +theorem polynomial_step : PolynomialTime stepRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_candidate) + (polynomial_optionCases + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_second) + polynomial_acceptCandidate) + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary FairBits + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Data := + (K,(((A.d,A.W),(C,a)), + (RootedDemandProgram.data A (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j),gridNatCode v))) + +lemma evaluate_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + RootedPenaltyEvaluateProgram.evaluate (data A C a K z v).2= + RootedCatalogGrid.exponent A C a z v := + RootedCatalogGrid.evaluate_grid A C a K hC z v + +lemma replace_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (z : View A → ℕ) (v w : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + replace ((data A C a K z v).2,gridNatCode w)=(data A C a K z w).2 := rfl + +theorem step_pair (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + {p k : ℕ} (proposal : Fin p → Bool) (coins : Fin k → Bool) : + step (data A C a K z v,(List.ofFn proposal,List.ofFn coins))= + gridNatCode (match axisCodeStep v (binaryWordEquiv p proposal) with + | Option.none => v + | Option.some w => if acceptDyadic + (RootedCatalogGrid.exponent A C a z w-RootedCatalogGrid.exponent A C a z v) + k (binaryWordEquiv k coins) then w else v) := by + have hc : candidate (data A C a K z v,(List.ofFn proposal,List.ofFn coins))= + (axisCodeStep v (binaryWordEquiv p proposal)).map gridNatCode := + axisWordStep_eq v proposal + unfold step + rw [hc] + cases h : axisCodeStep v (binaryWordEquiv p proposal) with + | none => rfl + | some w => + simp only [Option.map_some,Option.elim_some,acceptCandidate,gap,candidateData,currentData, + replace_data,evaluate_data A C a K hC,dyadicWordAccept_ofFn,decide_eq_true_eq] + split_ifs <;> rfl + +end +end ContingencyTables.RootedOracleStepProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWalkProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWalkProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4b5afbbb965b778178f5b87c893d8e61d53fcd8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWalkProgram.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWordProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseStepGrowth + +namespace OAI + +/-! # Polynomial execution of an oracle walk + +The immutable graph and cell arrays are kept separately from the grid +coordinates. A coordinate changes by at most one per transition, which +bounds every accumulator reached by the binary list fold. +-/ + +namespace ContingencyTables.RootedOracleWalkProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial +open scoped Classical + +abbrev Frame := ℕ×(RootedPenaltyEvaluateProgram.Parameters×RootedDemandProgram.Input) +abbrev State := Frame×List ℕ + +def toData (z : State) : RootedOracleStepProgram.Data := + (z.1.1,(z.1.2.1,(z.1.2.2,z.2))) +def toDataRealizer : Realizer toData := + pair (composition first first) + (pair (composition (composition first second) first) + (pair (composition (composition first second) second) second)) +lemma polynomial_toData : PolynomialTime toDataRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_second)) + +def advance (z : List Bool×State) : State := + (z.2.1,RootedOracleStepProgram.wordStep (toData z.2,z.1)) +def advanceRealizer : Realizer advance := + pair (composition second first) + (composition (f := fun z : List Bool×State => (toData z.2,z.1)) + (g := RootedOracleStepProgram.wordStep) + (pair (composition (f := fun z : List Bool×State => z.2) (g := toData) + second toDataRealizer) first) RootedOracleStepProgram.wordStepRealizer) +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_toData) polynomial_first) + RootedOracleStepProgram.polynomial_wordStep) + +lemma step_growth (z : RootedOracleStepProgram.StepInput) (S : ℕ) + (hx : ∀ a∈z.1.2.2.2,a.size≤S) : + (RootedOracleStepProgram.step z).length=z.1.2.2.2.length ∧ + ∀ a∈RootedOracleStepProgram.step z,a.size≤S+2 := by + have hstay : z.1.2.2.2.length=z.1.2.2.2.length ∧ + ∀ a∈z.1.2.2.2,a.size≤S+2 := + ⟨rfl,fun a ha => (hx a ha).trans (Nat.le_add_right _ _)⟩ + unfold RootedOracleStepProgram.step + cases h : RootedOracleStepProgram.candidate z with + | none => exact hstay + | some ys => + have hy := axisListStep_growth + (((z.1.1,z.1.2.2.2),MatchingFPRAS.StackAddition.value z.2.1/2), + decide (MatchingFPRAS.StackAddition.value z.2.1%2=1)) ys S h hx + simp only [Option.elim_some,RootedOracleStepProgram.acceptCandidate] + split <;> assumption + +lemma advance_growth (state : State) (bits : List Bool) (S : ℕ) + (hx : ∀ a∈state.2,a.size≤S) : + (advance (bits,state)).2.length=state.2.length ∧ + ∀ a∈(advance (bits,state)).2,a.size≤S+2 := + step_growth _ S hx + +def walkWords (z : State×List (List Bool)) : State := + z.2.foldl (fun state bits => advance (bits,state)) z.1 +def walkWordsRealizer : Realizer walkWords := + composition (pair second first) (fold advanceRealizer) + +lemma fold_frame (bits : List (List Bool)) (state : State) : + let out := bits.foldl (fun state bits => advance (bits,state)) state + out.1=state.1 ∧ out.2.length=state.2.length := by + induction bits generalizing state with + | nil => exact ⟨rfl,rfl⟩ + | cons b bs ih => + have h := ih (advance (b,state)) + have hl : (advance (b,state)).2.length=state.2.length := by + exact (advance_growth state b (state.2.map Nat.size).sum + (fun a ha => List.single_le_sum (fun _ _ => Nat.zero_le _) a.size + (List.mem_map.mpr ⟨a,ha,rfl⟩))).1 + exact ⟨h.1,h.2.trans hl⟩ + +lemma fold_sizes (bits : List (List Bool)) (state : State) (S : ℕ) + (hx : ∀ a∈state.2,a.size≤S) : + ∀ a∈(bits.foldl (fun state bits => advance (bits,state)) state).2, + a.size≤S+2*bits.length := by + induction bits generalizing state S with + | nil => simpa using hx + | cons b bs ih => + have hs := ih (advance (b,state)) (S+2) (advance_growth state b S hx).2 + intro a ha + exact (hs a ha).trans_eq (by simp only [List.length_cons]; omega) + +theorem polynomial_walkWords : PolynomialTime walkWordsRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advance (20*(X+1)^2) + intro bits state pre post he + let S := weight (bits,state) + let out := pre.foldl (fun state bits => advance (bits,state)) state + have hd : weight state≤S := weight_snd (bits,state) + have hp : pre.length≤S := (list_length_le_weight pre).trans + ((weight_prefix he).trans (weight_fst (bits,state))) + have hxs : weight state.2≤S := (weight_snd state).trans hd + have hn : state.2.length≤S := (list_length_le_weight _).trans hxs + have hi : ∀ a∈state.2,a.size≤S := fun a ha => + (size_le_weight a).trans ((weight_mem ha).trans hxs) + have hs := fold_sizes pre state S hi + have ht := fold_frame pre state + have hw : weight out.2≤out.2.length*(4*(S+2*pre.length)+2)+1 := by + have h := weight_map_bound (f := id) (as := out.2) (N := 4*(S+2*pre.length)+1) + (fun a ha => (weight_nat_le a).trans (by have h := hs a ha; omega)) + simpa only [List.map_id_fun,id_eq,Nat.add_assoc] using h + have hf : weight out.1≤S := by + rw [ht.1] + exact (weight_fst state).trans hd + have hl : out.2.length≤S := ht.2.trans_le hn + have hmul : out.2.length*(4*(S+2*pre.length)+2)≤S*(12*S+2) := + Nat.mul_le_mul hl (by omega) + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + change weight out≤20*(S+1)^2 + have hweight : weight out=1+weight out.1+weight out.2 := by + change weight (out.1,out.2)=1+weight out.1+weight out.2 + exact weight_prod _ _ + nlinarith + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary FirstSuccess + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : State := + ((K,(((A.d,A.W),(C,a)), + RootedDemandProgram.data A (ForestCountIdentification.smallX A.small z) + (fun i j => A.b i j-ForestCountIdentification.smallY A.small z i j))),gridNatCode v) + +lemma advance_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (bits : Fin (CompanionOracleDensity.oracleStepBits A C) → Bool) : + advance (List.ofFn bits,data A C a K z v)= + data A C a K z (RootedCatalogGrid.bitStep A C a z v bits) := by + unfold advance data + apply Prod.ext + · rfl + · exact RootedOracleStepProgram.wordStep_data A C a K hC z v bits + +theorem walkWords_ofFn (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (N : ℕ) (bits : Fin N → Fin (CompanionOracleDensity.oracleStepBits A C) → Bool) : + walkWords (data A C a K z v,List.ofFn (fun i => List.ofFn (bits i)))= + data A C a K z (wordWalk (RootedCatalogGrid.bitStep A C a z) v N bits) := by + induction N with + | zero => rfl + | succ N ih => + unfold walkWords at ih ⊢ + rw [List.ofFn_succ',List.concat_eq_append,List.foldl_append] + change advance (List.ofFn (bits (Fin.last N)), + (List.ofFn (fun i => List.ofFn ((Fin.init bits) i))).foldl + (fun state bits => advance (bits,state)) (data A C a K z v))=_ + rw [ih (Fin.init bits)] + exact advance_data A C a K hC z _ _ + +end +end ContingencyTables.RootedOracleWalkProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a7da8212d977849d366a6e89b989d709451af64 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedOracleWordProgram.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleStepProgram + +namespace OAI + +/-! # A single fixed word drives an executed oracle transition -/ + +namespace ContingencyTables.RootedOracleStepProgram + +open MatchingFPRAS.TreeTyped DensePrograms +open scoped Classical + +abbrev WordInput := Data×List Bool + +def proposalWidth (z : WordInput) : ℕ := Nat.clog 2 (8*z.1.2.1.1.1) +def proposalWidthRealizer : Realizer proposalWidth := by + let D : Realizer (fun z : WordInput => z.1.2.1.1.1) := + composition (composition (composition (composition first second) first) first) first + let M : Realizer (fun z : WordInput => 8*z.1.2.1.1.1) := + composition (f := fun z : WordInput => (8,z.1.2.1.1.1)) + (g := fun x : ℕ×ℕ => x.1*x.2) (pair (constant 8) D) multiply + exact composition (f := fun z : WordInput => 8*z.1.2.1.1.1) + (g := Nat.clog 2) M ceilLogTwoRealizer +lemma polynomial_proposalWidth : PolynomialTime proposalWidthRealizer := by + have hd : PolynomialTime (composition + (composition (composition (composition (first (A := Data) (B := List Bool)) second) + first) first) first) := + polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_first) polynomial_first + unfold proposalWidthRealizer + exact polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 8) hd) polynomial_multiply) polynomial_ceilLogTwo + +def wordStep (z : WordInput) : List ℕ := + step (z.1,(z.2.take (proposalWidth z),z.2.drop (proposalWidth z))) +def wordStepRealizer : Realizer wordStep := + composition (f := fun z : WordInput => + (z.1,(z.2.take (proposalWidth z),z.2.drop (proposalWidth z)))) (g := step) + (pair first (pair + (composition (pair second proposalWidthRealizer) takeFast) + (composition (pair second proposalWidthRealizer) dropFast))) stepRealizer +theorem polynomial_wordStep : PolynomialTime wordStepRealizer := + polynomial_composition (polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_proposalWidth) + polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second polynomial_proposalWidth) + polynomial_dropFast))) polynomial_step + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary FairBits + +noncomputable section +variable {m n : ℕ} + +/-- Exact code agreement for the prescribed finite word, including +unused direction codes and unsuccessful acceptance tests. -/ +theorem wordStep_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) (hC : 0 < C) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (bits : Fin (CompanionOracleDensity.oracleStepBits A C) → Bool) : + wordStep (data A C a K z v,List.ofFn bits)= + gridNatCode (RootedCatalogGrid.bitStep A C a z v bits) := by + have ht := ofFn_split_take (p := Nat.clog 2 (8*A.d)) + (k := CompanionOracleDensity.rationalHeight A C) bits + have hd := ofFn_split_drop (p := Nat.clog 2 (8*A.d)) + (k := CompanionOracleDensity.rationalHeight A C) bits + have hp : ((List.ofFn bits).take (Nat.clog 2 (8*A.d)), + (List.ofFn bits).drop (Nat.clog 2 (8*A.d)))= + (List.ofFn (splitWordEquiv (Nat.clog 2 (8*A.d)) + (CompanionOracleDensity.rationalHeight A C) bits).1, + List.ofFn (splitWordEquiv (Nat.clog 2 (8*A.d)) + (CompanionOracleDensity.rationalHeight A C) bits).2) := Prod.ext ht hd + have hsplit := congrArg (fun coins => step (data A C a K z v,coins)) hp + change step (data A C a K z v,((List.ofFn bits).take (Nat.clog 2 (8*A.d)), + (List.ofFn bits).drop (Nat.clog 2 (8*A.d))))=_ + refine hsplit.trans ((step_pair A C a K hC z v + (splitWordEquiv (Nat.clog 2 (8*A.d)) (CompanionOracleDensity.rationalHeight A C) bits).1 + (splitWordEquiv (Nat.clog 2 (8*A.d)) (CompanionOracleDensity.rationalHeight A C) bits).2).trans ?_) + change gridNatCode (match axisCodeStep v + (pairWordEquiv (Nat.clog 2 (8*A.d)) (CompanionOracleDensity.rationalHeight A C) bits).1 with + | Option.none => v + | Option.some w => if acceptDyadic + (RootedCatalogGrid.exponent A C a z w-RootedCatalogGrid.exponent A C a z v) + (CompanionOracleDensity.rationalHeight A C) + (pairWordEquiv (Nat.clog 2 (8*A.d)) (CompanionOracleDensity.rationalHeight A C) bits).2 + then w else v)=_ + unfold RootedCatalogGrid.bitStep + dsimp only + cases axisCodeStep v + (pairWordEquiv (Nat.clog 2 (8*A.d)) (CompanionOracleDensity.rationalHeight A C) bits).1 with + | none => rfl + | some w => rfl + +end +end ContingencyTables.RootedOracleStepProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..81fcef909e6f66ccde0d18fe8368e51a4dc90e5b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenalty.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalCompletion +import OAI.Combinatorics.ContingencyTables.Rooted.ForestLiteralCount + +namespace OAI + +/-! # Physical factors with the executed component-root convention + +The line factors use the explicitly selected roots. Their tree factors, +widths and doubled row/column coordinates are exactly the source data. +-/ + +namespace ContingencyTables.RootedPenalty + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS CompanionFactorialApplication RootedCompletion +open ForestPenaltyApplication ForestLiteralCount EqualitySoftening +open ProductIntegerSignature RowColumnPenalties + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def ell (A : Instance I J) : I → J → ℤ := lower A.T A.d A.b +noncomputable def widths (A : Instance I J) : I → J → ℕ := width A.T A.d A.b + +noncomputable def rootFlag {T : SimpleGraph (I⊕J)} (S : Selection T) (v : I⊕J) : Bool := + decide (v=S.root v) + +noncomputable def rootPenalty (A : Instance I J) (S : Selection A.T) + (z : ((I×J)×Bool) → ℕ) : ℝ := + ∑ g,if rootFlag S g then |deviation (ell A) (widths A) A.r A.c z g| else 0 + +noncomputable def penalty (A : Instance I J) (S : Selection A.T) + (z : ((I×J)×Bool) → ℕ) : ℝ := + rootPenalty A S z+treePenalty A.T A.b (ell A) z + +noncomputable def physicalWeight (A : Instance I J) (S : Selection A.T) (alpha : ℝ) : + (((I×J)×Bool) → ℕ) → ℝ := + exactWeight cellLine (rootFlag S) (fun _ => alpha) + (lineOffset (ell A) (widths A) A.r A.c) viewSlope + (unaryRate A.T A.b alpha) (unaryEll (ell A)) unarySlope (unaryCap A.b) + +private lemma line_product_eq (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + (z : ((I×J)×Bool) → ℕ) + (h : ∀ g,rootFlag S g=false → deviation (ell A) (widths A) A.r A.c z g=0) : + (∏ g,exactLineFactor (rootFlag S) (fun _ => alpha) + (lineOffset (ell A) (widths A) A.r A.c) viewSlope g (lineTotal cellLine z g))= + (2:ℝ)^(-alpha*rootPenalty A S z) := by + have hp : ∀ g,exactLineFactor (rootFlag S) (fun _ => alpha) + (lineOffset (ell A) (widths A) A.r A.c) viewSlope g (lineTotal cellLine z g)= + (2:ℝ)^(-alpha*(if rootFlag S g then + |deviation (ell A) (widths A) A.r A.c z g| else 0)) := by + intro g + simp only [exactLineFactor,ScalarPenalty.factor,line_affine] + cases hg : rootFlag S g + · simp [h g hg] + · simp + simp_rw [hp] + rw [←Real.rpow_sum_of_pos (by norm_num : (0:ℝ)<2)] + congr 1 + simp only [rootPenalty,Finset.mul_sum] + +private lemma unary_product_eq (A : Instance I J) (alpha : ℝ) + (z : ((I×J)×Bool) → ℕ) : + (∏ a,unaryFactor (unaryRate A.T A.b alpha) (unaryEll (ell A)) unarySlope + (unaryCap A.b) a (z a))=(2:ℝ)^(-alpha*treePenalty A.T A.b (ell A) z) := by + unfold unaryFactor ScalarPenalty.factor + rw [←Real.rpow_sum_of_pos (by norm_num : (0:ℝ)<2)] + congr 1 + rw [Fintype.sum_prod_type] + simp only [unaryRate,unaryEll,unarySlope,unaryCap,Fintype.sum_bool,Bool.true_eq_false, + false_and,ite_false,zero_mul,neg_zero,zero_add,true_and] + rw [Fintype.sum_prod_type] + simp only [treePenalty,Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> simp only [div_eq_mul_inv,mul_zero] <;> ring + +theorem exact_eq (A : Instance I J) (S : Selection A.T) (alpha : ℝ) + (z : ((I×J)×Bool) → ℕ) : + physicalWeight A S alpha z= + if (∀ g,rootFlag S g=false → deviation (ell A) (widths A) A.r A.c z g=0) + then (2:ℝ)^(-alpha*penalty A S z) else 0 := by + by_cases h : ∀ g,rootFlag S g=false → deviation (ell A) (widths A) A.r A.c z g=0 + · rw [ite_eq_left h] + unfold physicalWeight exactWeight productWeight penalty + rw [line_product_eq A S alpha z h,unary_product_eq, + ←Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + ring + · rw [ite_eq_right h] + push Not at h + obtain ⟨g,hg,hdev⟩ := h + have hz : exactLineFactor (rootFlag S) (fun _ => alpha) + (lineOffset (ell A) (widths A) A.r A.c) viewSlope g (lineTotal cellLine z g)=0 := by + simp [exactLineFactor,hg,line_affine,hdev] + unfold physicalWeight exactWeight productWeight + rw [Finset.prod_eq_zero (Finset.mem_univ g) hz,zero_mul] + +theorem physicalWeight_nonnegative (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) (z : ((I×J)×Bool) → ℕ) : 0≤ physicalWeight A S alpha z := by + rw [exact_eq] + split_ifs + · exact (Real.rpow_pos_of_pos (by norm_num : (0:ℝ)<2) _).le + · exact le_rfl + +theorem physicalWeight_removal (A : Instance I J) (S : Selection A.T) + (alpha : ℝ) (ha : 0≤ alpha) (z : ((I×J)×Bool) → ℕ) : + OnePositiveDirection + (FactorialSignatures.integerRemovalMatrix (physicalWeight A S alpha) z).toBilin' := by + have hu : ∀ a : (I×J)×Bool,0≤ unaryRate A.T A.b alpha a := by + intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + have hs := exactWeight_removal cellLine (rootFlag S) (fun _ => alpha) + (lineOffset (ell A) (widths A) A.r A.c) viewSlope + (unaryRate A.T A.b alpha) (unaryEll (ell A)) unarySlope (unaryCap A.b) + (fun _ => ha) hu z + convert hs using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +end ContingencyTables.RootedPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyEvaluateProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyEvaluateProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..70156b3d5c1da41d985670ee736060e9f68d4b63 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyEvaluateProgram.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestPrepareProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleRational + +namespace OAI + +/-! # A polynomial binary program for the actual forest exponent + +The bin width and height are computed from the dimension allowance, +capacity scale and phase coefficient. All forest metadata is generated +from the cell arrays by `RootedForestPrepareProgram`. +-/ + +namespace ContingencyTables.RootedPenaltyEvaluateProgram + +open MatchingFPRAS.TreeTyped +open scoped Classical + +abbrev Parameters := (ℕ×ℕ)×(ℕ×ℕ) +abbrev Input := Parameters×(RootedDemandProgram.Input×List ℕ) + +def squareDimension (z : Parameters) : ℕ := z.1.1*z.1.1 +def squareDimensionRealizer : Realizer squareDimension := + composition (pair (composition first first) (composition first first)) multiply +lemma polynomial_squareDimension : PolynomialTime squareDimensionRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_first polynomial_first)) polynomial_multiply + +def scaledSquare (z : Parameters) : ℕ := z.2.1*squareDimension z +def scaledSquareRealizer : Realizer scaledSquare := + composition (f := fun z : Parameters => (z.2.1,squareDimension z)) (g := fun z => z.1*z.2) + (pair (composition second first) squareDimensionRealizer) multiply +lemma polynomial_scaledSquare : PolynomialTime scaledSquareRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) polynomial_squareDimension) + polynomial_multiply + +def width (z : Parameters) : ℕ := 16*scaledSquare z +def widthRealizer : Realizer width := + composition (f := fun z : Parameters => (16,scaledSquare z)) (g := fun z => z.1*z.2) + (pair (constant 16) scaledSquareRealizer) multiply +lemma polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 16) polynomial_scaledSquare) + polynomial_multiply + +def baseHeight (z : Parameters) : ℕ := 10*scaledSquare z +def baseHeightRealizer : Realizer baseHeight := + composition (f := fun z : Parameters => (10,scaledSquare z)) (g := fun z => z.1*z.2) + (pair (constant 10) scaledSquareRealizer) multiply +lemma polynomial_baseHeight : PolynomialTime baseHeightRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 10) polynomial_scaledSquare) + polynomial_multiply + +def height (z : Parameters) : ℕ := baseHeight z*(z.1.2+1) +def heightRealizer : Realizer height := + composition (f := fun z : Parameters => (baseHeight z,z.1.2+1)) (g := fun z => z.1*z.2) + (pair baseHeightRealizer (composition (composition first second) successor)) multiply +lemma polynomial_height : PolynomialTime heightRealizer := + polynomial_composition (polynomial_pair polynomial_baseHeight + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_successor)) polynomial_multiply + +def forestInput (z : Input) : RootedForestPrepareProgram.Input := + (((z.1.2.1,width z.1),z.2.1),z.2.2) +def forestInputRealizer : Realizer forestInput := + pair (pair (pair (composition (composition first second) first) + (composition (f := fun z : Input => z.1) (g := width) first widthRealizer)) + (composition second first)) (composition second second) +lemma polynomial_forestInput : PolynomialTime forestInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) + (polynomial_composition polynomial_first polynomial_width)) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition polynomial_second polynomial_second) + +def exponentInput (z : Input) : ForestPenaltyProgram.ExponentInput := + ((z.1.2.2,height z.1),RootedForestPrepareProgram.prepare (forestInput z)) +def exponentInputRealizer : Realizer exponentInput := + pair (pair (composition (composition first second) second) + (composition (f := fun z : Input => z.1) (g := height) first heightRealizer)) + (composition (f := forestInput) (g := RootedForestPrepareProgram.prepare) + forestInputRealizer RootedForestPrepareProgram.prepareRealizer) +lemma polynomial_exponentInput : PolynomialTime exponentInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) (polynomial_composition polynomial_first polynomial_height)) + (polynomial_composition polynomial_forestInput RootedForestPrepareProgram.polynomial_prepare) + +def evaluate (z : Input) : ℕ := ForestPenaltyProgram.exponentCode (exponentInput z) +def evaluateRealizer : Realizer evaluate := + composition (f := exponentInput) (g := ForestPenaltyProgram.exponentCode) + exponentInputRealizer ForestPenaltyProgram.exponentCodeRealizer +theorem polynomial_evaluate : PolynomialTime evaluateRealizer := + polynomial_composition polynomial_exponentInput ForestPenaltyProgram.polynomial_exponentCode + +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit + +noncomputable def data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C a : ℕ) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : Input := + (((A.d,A.W),(C,a)),(RootedDemandProgram.data A x q, + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i)))) + +lemma width_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C a : ℕ) : + width ((A.d,A.W),(C,a))=CompanionOracleDensity.rationalBinWidth A C := by + simp only [width,scaledSquare,squareDimension,CompanionOracleDensity.rationalBinWidth,pow_two] + ring + +lemma height_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C a : ℕ) : + height ((A.d,A.W),(C,a))=CompanionOracleDensity.rationalHeight A C := by + simp only [height,baseHeight,scaledSquare,squareDimension, + CompanionOracleDensity.rationalHeight,pow_two] + ring + +theorem exponentInput_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C a : ℕ) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : + exponentInput (data A C a x q v)= + ((a,CompanionOracleDensity.rationalHeight A C), + RootedPenaltyProgram.data A (rowColumn A.T) C + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) + (RootedForestCatalog.treeEquiv A) (RootedForestCatalog.freeEquiv A) v) := by + unfold exponentInput data forestInput + rw [width_data,height_data] + exact congrArg (fun p => ((a,CompanionOracleDensity.rationalHeight A C),p)) + (RootedForestPrepareProgram.prepare_data A C x q v) + +/-- The code evaluates the literal rational forest penalty with its +source normalization, without an affine-data or evaluator hypothesis. -/ +theorem evaluate_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) (C a : ℕ) (hC : 0 < C) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : + evaluate (data A C a x q v)= + ⌊(a:ℚ)/CompanionOracleDensity.rationalHeight A C* + RootedPenaltyProgram.rationalPenalty A (rowColumn A.T) C + (fun i j => (x i j:ℤ)) (fun i j => (q i j:ℤ)) (fun f => (v f:ℚ))⌋₊ := by + rw [evaluate,exponentInput_data] + exact RootedPenaltyProgram.exponentCode_data A (rowColumn A.T) C a hC _ _ + (RootedForestCatalog.treeEquiv A) (RootedForestCatalog.freeEquiv A) v + +end ContingencyTables.RootedPenaltyEvaluateProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..77b3a626e2eafc4a61553c77dbf9777b14beff4e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPenaltyProgram.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedIntegerEvaluation +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyProgram + +namespace OAI + +/-! # Exact binary penalty evaluation for the selected-root forest + +The signed affine and fraction programs compute the root-specific +geometric penalty from its explicit input metadata. +-/ + +namespace ContingencyTables.RootedPenaltyProgram + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion GraphCompletionCounts ForestAssignmentSplit +open MatchingFPRAS RootedIntegerEvaluation + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def rootCount (A : Instance I J) (S : Selection A.T) + (x q : I → J → ℤ) : ℕ := + ∑ a : I⊕J,if RootedPenalty.rootFlag S a then + (RootedRootPenalty.signedResidual A S x q 0 a).natAbs else 0 + +lemma rootCount_cast (A : Instance I J) (S : Selection A.T) (x q : I → J → ℤ) : + (rootCount A S x q:ℝ)=RootedScaledPenalty.rootConstant A S x q := by + unfold rootCount RootedScaledPenalty.rootConstant + rw [Nat.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs + · rw [←Int.cast_natCast,Int.natCast_natAbs,Int.cast_abs] + · exact Nat.cast_zero + +noncomputable def rationalPenalty (A : Instance I J) (S : Selection A.T) + (C : ℕ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℚ) : ℚ := + C*((rootCount A S x q:ℚ)+∑ t : TreeCell A.T,max 0 (max + (-rationalScaledTree A S (CompanionOracleDensity.rationalBinWidth A C) x q v t) + (rationalScaledTree A S (CompanionOracleDensity.rationalBinWidth A C) x q v t-1))) + +theorem rationalPenalty_cast (A : Instance I J) (S : Selection A.T) + (C : ℕ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℚ) : + (rationalPenalty A S C x q v:ℝ)=RootedScaledPenalty.penalty A S C + (CompanionOracleDensity.binWidth A C) x q (fun f => (v f:ℝ)) := by + simp only [rationalPenalty,RootedScaledPenalty.penalty,ForestScaledPenalty.intervalCost, + Rat.cast_mul,Rat.cast_natCast,Rat.cast_add,Rat.cast_sum,Rat.cast_max,Rat.cast_zero, + Rat.cast_neg,Rat.cast_sub,Rat.cast_one,rootCount_cast,rationalScaledTree_cast, + CompanionOracleDensity.rationalBinWidth_cast] + +noncomputable def data (A : Instance I J) (S : Selection A.T) (C : ℕ) + (x q : I → J → ℤ) {nt nf : ℕ} + (trees : Fin nt ≃ TreeCell A.T) (free : Fin nf ≃ FreeCell A.small A.T) + (v : FreeCell A.small A.T → ℕ) : ForestPenaltyProgram.Input := + ((C,rootCount A S x q),List.ofFn (fun i => + forestData A S (CompanionOracleDensity.rationalBinWidth A C) (trees i) x q free v)) + +theorem penaltyCode_data (A : Instance I J) (S : Selection A.T) (C : ℕ) (hC : 0 (v f:ℚ)) := by + have hB : 0 rfl) + +theorem exponentCode_data (A : Instance I J) (S : Selection A.T) (C a : ℕ) (hC : 0 (v f:ℚ))⌋₊ := by + rw [ForestPenaltyProgram.exponentCode_value,penaltyCode_data A S C hC] + +end ContingencyTables.RootedPenaltyProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..213b1aafa972f9ff113590c86053e4749e86fefc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseAccuracy.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseOracleError + +namespace OAI + +/-! # Actual selected-root guarded rational phase update and logarithmic error -/ + +namespace ContingencyTables.RootedPhaseAccuracy + +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing +open RootedMultiplierUpdate CompanionRationalUpdates RootedPhaseWords +open CompanionPhaseWords (phaseBits Stored) +open TwoLiftStates GridBoundary CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +private lemma indicator_sum {X : Type*} (P : X → Prop) (xs : List X) : + (xs.map (fun x => if P x then (1:ℝ) else 0)).sum= + (xs.countP (fun x => decide (P x)):ℝ) := by + induction xs with + | nil => simp + | cons x xs ih => by_cases h : P x <;> simp [h,ih,add_comm] + +private lemma count_positive_of_empirical {X : Type*} (P : Set X → Prop) + (xs : List (Set X)) + (h : 0 if P S then (1:ℝ) else 0) xs) : + 0 decide (P S)) := by + by_contra hn + have hz := Nat.eq_zero_of_not_pos hn + simp only [empirical,indicator_sum,hz,Nat.cast_zero,zero_div] at h + exact (lt_irrefl (0:ℝ)) h + +variable {I J : Type} [Fintype I] [Fintype J] + +theorem accurate_counts_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (w : Pair A → Pair A → ℝ) (hw : ∀ p q,0 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos (slotTotal_pos pairs _ (weight_positive A R j) ∅ PairedLabels.fresh) hZ + have hpemp := AnnealingMultipliers.empirical_positive hplain heta + (accurate_plain pairs w (weight A R j) (ratio A R j) eta xs hacc).1 + constructor + · exact count_positive_of_empirical (PlainState pairs) xs hpemp + · intro p hp q hq hpq + have hdef : 0 (old.multiplier p q:ℝ)) + (weight A R j) (ratio A R j) eta (List.ofFn states)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hcalls : accurateCalls A R C K j N hK hW xi v states bits) : + ∃ next,update A R C K j N hK hW xi v old states bits=some next ∧ + (∀ p q,0 (next.multiplier p q:ℝ)) ∧ + |Real.log ((next.estimate:ℝ)/((old.estimate:ℝ)* + (slotTotal pairs (weight A R (j+1)) ∅/slotTotal pairs (weight A R j) ∅)))|≤ + 4*(xi:ℝ)+4*eta := by + have hwr : ∀ p q,0<(old.multiplier p q:ℝ) := fun p q => by exact_mod_cast hw p q + have hc := accurate_counts_positive A R j _ hwr eta he1 (List.ofFn states) hacc + let next : Stored A := ⟨rationalLearn pairs old.multiplier (List.ofFn states), + old.estimate*observedRatio A R C K j N hK hW xi v states bits⟩ + have hu : update A R C K j N hK hW xi v old states bits=some next := by + simp only [update,hc,ite_true,next] + have hnpos : ∀ p q,0 (next.multiplier p q:ℝ))= + learnedMultipliers pairs (fun p q => (old.multiplier p q:ℝ)) (List.ofFn states) := by + funext p q + exact update_multiplier_cast A R C K j N hK hW xi v old next states bits hu p q + refine ⟨next,hu,hnpos,mul_pos hE ho,?_,?_⟩ + · rw [hcast] + exact hgood + · have hER : (old.estimate:ℝ)≠0 := by exact_mod_cast hE.ne' + change |Real.log (((old.estimate*observedRatio A R C K j N hK hW xi v states bits:ℚ):ℝ)/_)|≤_ + rw [Rat.cast_mul,mul_div_mul_left _ _ hER] + exact hobs.2 + +end +end ContingencyTables.RootedPhaseAccuracy + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseComposition.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..c73fc59c618104b2841790c9bce6fe06f5dad6a9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseComposition.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Counting.InitialMultiplierValues +import OAI.Combinatorics.ContingencyTables.Rooted.RootedMultiplierUpdate +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmStart +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseComposition + +namespace OAI + +/-! +# Actual companion phase history and counting-error composition + +Each stored multiplier is the explicit initial rational value followed by +the actual empirical plain/defect update. Successful finite observations +propagate goodness and add at most 4 eta to the logarithmic counting error. +-/ + +namespace ContingencyTables.RootedPhaseComposition + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing +open RootedMultiplierUpdate TwoLiftStates +open RootedWarmStart (total total_positive) +open CompanionPhaseComposition (weights) + +variable {I J : Type*} [Fintype I] [Fintype J] + +def Accurate (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) (eta : ℝ) (j : ℕ) : Prop := + AccuratePhase pairs (weights A samples j) (weight A R j) (ratio A R j) eta (samples j) + +/-- Goodness is obtained for the actual stored phase multipliers from +exact initialization and every preceding successful observation. -/ +theorem weights_good (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) (L : ℕ) + (hall : ∀ j< L,Accurate A R samples eta j) : + GoodMultipliers pairs (weight A R L) (weights A samples L) := by + induction L with + | zero => + rw [weights,RootedWarmStart.zero_weight_eq] + simpa only [CompanionAnnealing.weight,Nat.cast_zero,zero_div] using + CompanionInitialMultipliers.initial_good A + | succ L ih => + have hg := ih (by intro j hj; exact hall j (by omega)) + exact successful_phase_learns A R L (weights A samples L) hg.positive eta he0 he + (samples L) (hall L (by omega)) + +noncomputable def observedRatio (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) (j : ℕ) : ℝ := + empiricalRatio pairs (ratio A R j) (samples j) + +lemma observedRatio_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he : eta≤1/4) (j : ℕ) + (hw : ∀ p r,0< weights A samples j p r) (hacc : Accurate A R samples eta j) : + 0< observedRatio A R samples j := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover (weights A samples j) + (weight A R j) (weight_positive A R j) hw + have hp : 0< chainMean pairs (weights A samples j) (weight A R j) (plainObservable pairs (ratio A R j)) := by + rw [ratio_mean] + exact div_pos (total_positive A R (j+1)) hZ + have hq : 0< chainMean pairs (weights A samples j) (weight A R j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos (total_positive A R j) hZ + have hph := relative_error_bounds _ _ _ (hacc (.inr ())) + simp only [phaseObservable] at hph + have hqh := accurate_plain pairs (weights A samples j) (weight A R j) (ratio A R j) eta (samples j) hacc + exact div_pos (AnnealingMultipliers.empirical_positive hp he hph.1) + (AnnealingMultipliers.empirical_positive hq he hqh.1) + +noncomputable def estimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) : ℕ → ℝ + | 0 => total A R 0 + | j+1 => estimate A R samples j*observedRatio A R samples j + +/-- The actual product estimator has total logarithmic error at most +4 L eta on the event that every preceding phase observation is accurate. -/ +theorem estimate_log_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) (L : ℕ) + (hall : ∀ j< L,Accurate A R samples eta j) : + 0< estimate A R samples L ∧ + |Real.log (estimate A R samples L/total A R L)|≤4*(L:ℝ)*eta := by + induction L with + | zero => + have hT := total_positive A R 0 + exact ⟨hT,by simp [estimate,div_self hT.ne']⟩ + | succ L ih => + have hprev : ∀ j< L,Accurate A R samples eta j := by intro j hj; exact hall j (by omega) + have hE := ih hprev + have hg := weights_good A R samples eta he0 he L hprev + have hR := observedRatio_positive A R samples eta he L hg.positive (hall L (by omega)) + have hstep := successful_phase_ratio_log A R L (weights A samples L) hg.positive eta he0 he + (samples L) (hall L (by omega)) + change |Real.log (observedRatio A R samples L/(total A R (L+1)/total A R L))|≤4*eta at hstep + have hT := total_positive A R L + have hT' := total_positive A R (L+1) + have hid : estimate A R samples (L+1)/total A R (L+1)= + (estimate A R samples L/total A R L)*(observedRatio A R samples L/(total A R (L+1)/total A R L)) := by + change (estimate A R samples L*observedRatio A R samples L)/total A R (L+1)=_ + field_simp [hT.ne',hT'.ne'] + refine ⟨mul_pos hE.1 hR,?_⟩ + rw [hid,Real.log_mul (div_ne_zero hE.1.ne' hT.ne') + (div_ne_zero hR.ne' (div_ne_zero hT'.ne' hT.ne'))] + have hsum := abs_add_le (Real.log (estimate A R samples L/total A R L)) + (Real.log (observedRatio A R samples L/(total A R (L+1)/total A R L))) + push_cast + linarith [hE.2,hstep] + +end ContingencyTables.RootedPhaseComposition + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseExperiment.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseExperiment.lean new file mode 100644 index 0000000000000000000000000000000000000000..03625da5eba76b96e1e5c0083c6877bce2b54e40 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseExperiment.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseAccuracy +import OAI.Combinatorics.ContingencyTables.Rooted.RootedSlowConcentration +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTraceWords + +namespace OAI + +/-! # Accuracy of the selected-root executed finite-word phase history -/ + +namespace ContingencyTables.RootedPhaseExperiment + +open CommonBasesFPRAS FirstSuccess RealKernelApproximation +open CompanionFactorialApplication RootedBooleanPhase CompanionOracleDensity +open CompanionRationalUpdates RootedAnnealing RootedMultiplierUpdate +open RootedPhaseTrajectory RootedTraceWords TwoLiftStates GridBoundary +open CompanionPhaseTrajectory (position_put historyPrefix) +open CompanionTraceWords (eventIndicator) +open CompanionBooleanPhase (State stepBits) +open scoped BigOperators Classical + +noncomputable section + +private lemma wordWalk_position {X : Type*} {k : ℕ} + (step : X → (Fin k → Bool) → X) (N n : ℕ) (x : X) : + n≤N → ∀ bits : Fin n → Fin k → Bool, + (wordWalk (fun a b => pathPut a (step (pathRead a) b)) + (pathInitial N x) n bits).1.val=n := by + induction n with + | zero => intro _ bits; rfl + | succ n ih => + intro hn bits + let a := wordWalk (fun a b => pathPut a (step (pathRead a) b)) + (pathInitial N x) n (Fin.init bits) + have ha : a.1.val=n := ih (by omega) (Fin.init bits) + have hlt : a.1.val + ((RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v w S bits).2 i).val + +theorem observedStates_list (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : State A) (bits : Fin (N*stepBits A C K j k xi) → Bool) : + List.ofFn (observedStates A R C K j k N hK hW xi v w S bits)= + (historyPrefix (RootedArithmeticStep.recordedWalk + A R C K j k N N hK hW xi v w S bits)).map Subtype.val := by + have hp := wordWalk_position (RootedArithmeticStep.step A R C K j k hK hW xi v w) + N N S le_rfl (oracleWalkWordEquiv N (stepBits A C K j k xi) bits) + change (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v w S bits).1.val=N at hp + rw [full_prefix _ hp,List.map_ofFn] + rfl + +private lemma accuratePath_iff (A : Instance I J) (R : RootedCompletion.Selection A.T) (j N : ℕ) + (hp : 0 (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (l.map Subtype.val)) ↔ + ∃ o : PhaseObservables (pairs : List (Pair A)), + eta*(targetChain A R j hp w hw).mean + (fun S => phaseObservable pairs (ratio A R j) o S.val)< + |FiniteChain.pathSum (fun S => phaseObservable pairs (ratio A R j) o S.val) l/(N+1:ℕ)- + (targetChain A R j hp w hw).mean + (fun S => phaseObservable pairs (ratio A R j) o S.val)| := by + simp only [AccuratePhase,not_forall,not_le,empirical,List.map_map,List.length_map, + hlen,FiniteChain.pathSum,RootedSlowConcentration.target_mean,Function.comp_def] + +private theorem reference_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (j N : ℕ) + (hp : 0 (w p q:ℝ))) + (nu : State A → ℝ) (hnu : ∀ S,0≤nu S) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j)) + (eta : ℝ) (heta : 0 + ¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (l.map Subtype.val))≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2) := by + have he := (targetChain A R j hp w hw).pathProbability_congr_length nu N _ _ + (fun l hl => accuratePath_iff A R j N hp w hw eta l hl) + rw [he] + simpa only [Nat.add_sub_cancel] using + RootedSlowConcentration.phase_failure A R j hp w hw hgood nu hnu hwarm + (N+1) (by omega) eta heta + +/-- The actual recorded finite-word trajectory satisfies the source +concentration bound plus the accumulated proved one-step error. -/ +theorem observed_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 (w p q:ℝ))) + (nu : State A → ℝ) (hnu : ∀ S,0≤nu S) (hmass : ∑ S,nu S≤1) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j)) + (eta : ℝ) (heta : 0 + eventIndicator (¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (observedStates A R C K j k N hK hW xi v w S bits)))))≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + let E : List (State A) → Prop := fun l => + ¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (l.map Subtype.val) + let err : ℝ := (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) + have herr : 0≤err := by dsimp only [err]; positivity + have hpoint (S : State A) : + uniformAverage (fun bits : Fin (N*stepBits A C K j k xi) → Bool => + eventIndicator (¬AccuratePhase pairs (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (observedStates A R C K j k N hK hW xi v w S bits))))≤ + (targetChain A R j hp w hw).pathExpectation N S (fun l => eventIndicator (E l))+err := by + simpa only [observedStates_list] using + arithmetic_recorded_event_bound A R C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw N S E + have hs := Finset.sum_le_sum (fun S (_ : S∈Finset.univ) => + mul_le_mul_of_nonneg_left (hpoint S) (hnu S)) + have hm := mul_le_mul_of_nonneg_right hmass herr + simp only [mul_add,Finset.sum_add_distrib,←Finset.sum_mul,one_mul] at hs hm + dsimp only [err] at hs hm + have href := reference_failure A R j N hp w hw hgood nu hnu hwarm eta heta + change (∑ S,nu S*(targetChain A R j hp w hw).pathExpectation N S + (fun l => eventIndicator (E l)))≤_ at href + exact hs.trans (by linarith) + +end +end ContingencyTables.RootedPhaseExperiment + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed5bf04bdbcfe5b55a3131b74e79ea379722b3eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseHistory.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartTrial +import OAI.Combinatorics.ContingencyTables.Rooted.RootedStoredHistory +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding + +namespace OAI + +/-! # Actual adaptive phases on a common finite Boolean word space -/ + +namespace ContingencyTables.RootedPhaseHistory + +open CommonBasesFPRAS FirstSuccess FairBits CompanionFactorialApplication +open CompanionRationalUpdates CompanionOracleDensity +open CompanionPhaseWords (Stored) +open CompanionTraceWords (eventIndicator) +open CompanionBooleanPhase (stepBits) +open RootedStoredHistory +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +structure Settings (A : Instance I J) where + C : ℕ + K : ℕ + H : ℕ + L : ℕ + k : ℕ + n : ℕ + N : ℕ + h : ℕ + hK : 1 ≤ K + hW : 100*A.d*K ≤ A.W + xi : ℚ + v : Grid (I := Fin (dimension A)) K + +def width (A : Instance I J) (s : Settings A) (j : ℕ) : ℕ := + RootedRestartWords.initialStageBits A s.C s.K s.H s.L s.k s.n s.h j s.xi+ + (s.N*stepBits A s.C s.K j s.k s.xi+ + CompanionPhaseWords.phaseBits A s.C s.K j (s.N+1) s.xi) + +def totalWidth (A : Instance I J) (s : Settings A) : ℕ := + ∑ j : Fin s.H,width A s j.val + +abbrev Word (A : Instance I J) (s : Settings A) := Fin (totalWidth A s) → Bool + +def split (A : Instance I J) (s : Settings A) (j : ℕ) : + (Fin (width A s j) → Bool) ≃ + RootedRestartTrial.Words A s.C s.K s.H s.L j s.k s.n s.N s.h s.xi := + (splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + (splitWordEquiv _ _)) + +private lemma value_le_sum {N : ℕ} (f : Fin N → ℕ) (i : Fin N) : + f i ≤ ∑ j,f j := + Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + +lemma width_le (A : Instance I J) (s : Settings A) (j : ℕ) (hj : j < s.H) : + width A s j ≤ totalWidth A s := by + have h := value_le_sum (fun i : Fin s.H => width A s i.val) ⟨j,hj⟩ + exact h + +def step (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (history : List (Stored A)) (bits : Word A s) : Stored A := + let j := history.length + let old := lookup A history j + if hj : j < s.H then + (RootedRestartTrial.run A R s.C s.K s.H s.L j s.k s.n s.N s.h s.hK s.hW s.xi s.v + (fun i => (lookup A history i).multiplier) old.estimate + (split A s j (prefixWord (width_le A s j hj) bits))).getD old + else old + +def decoded (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (words : List (Word A s)) : List (Stored A) := + words.foldl (fun history bits => history++[step A R s history bits]) [] + +lemma decoded_nil (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) : + decoded A R s []=[] := rfl + +lemma decoded_snoc (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (words : List (Word A s)) (bits : Word A s) : + decoded A R s (words++[bits])= + decoded A R s words++[step A R s (decoded A R s words) bits] := by + simp only [decoded,List.foldl_append,List.foldl_cons,List.foldl_nil] + +private lemma fold_length {X Y : Type*} (f : List Y → X → Y) (xs : List X) (ys : List Y) : + (xs.foldl (fun history x => history++[f history x]) ys).length=ys.length+xs.length := by + induction xs generalizing ys with + | nil => simp + | cons x xs ih => + simp only [List.foldl_cons,ih,List.length_append,List.length_cons,List.length_nil] + omega + +lemma decoded_length (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (words : List (Word A s)) : (decoded A R s words).length=words.length := by + simpa only [decoded,List.length_nil,Nat.zero_add] using fold_length (step A R s) words [] + +lemma good_snoc_iff (A : Instance I J) (R : RootedCompletion.Selection A.T) (s : Settings A) + (eta : ℝ) (words : List (Word A s)) (bits : Word A s) : + Good A R s.xi eta (decoded A R s (words++[bits])) ↔ + Good A R s.xi eta (decoded A R s words) ∧ + RootedPhaseTrial.ValidOutput A R words.length + (lookup A (decoded A R s words) words.length) s.xi eta + (step A R s (decoded A R s words) bits) := by + rw [decoded_snoc,RootedStoredHistory.good_snoc,decoded_length] + +end +end ContingencyTables.RootedPhaseHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseOracleError.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseOracleError.lean new file mode 100644 index 0000000000000000000000000000000000000000..5afa18e4b24d1db3af77695faf8b0a603e711315 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseOracleError.lean @@ -0,0 +1,239 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseWords +import OAI.Combinatorics.ContingencyTables.Rooted.RootedMultiplierUpdate +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseOracleError + +namespace OAI + +/-! # Error of actual selected-root calls in a rational phase update -/ + +namespace ContingencyTables.RootedPhaseWords + +open CompanionFactorialApplication CompanionOracleDensity RootedWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS FiniteIndependentAverages GridBoundary TwoLiftStates +open CompanionPhaseWords (phaseBits phaseWordEquiv average_ext_instances failure_of_success + independent_pair_failure independent_reindex_failure) +open CompanionWeightOracle (WeightWord) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +def accurateCalls (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : Prop := + ∀ i,accurateCall A R C K j hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i).1 ∧ + accurateCall A R C K (j+1) hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i).2 + +lemma accurateCall_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi => + if ¬accurateCall A R C K j hK hW xi v S bits then (1:ℝ) else 0) ≤ (xi:ℝ) := by + have hs := evaluate_success A R C hC K hK hW hB j hj xi hx0 hx1 hPL hCheeger v S + exact @failure_of_success (WeightWord A C K j xi) inferInstance inferInstance + (accurateCall A R C K j hK hW xi v S) (xi:ℝ) hs + +lemma pairedCalls_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi => + if ¬(accurateCall A R C K j hK hW xi v S bits.1 ∧ + accurateCall A R C K (j+1) hK hW xi v S bits.2) then (1:ℝ) else 0) ≤ (xi:ℝ)+(xi:ℝ) := by + have hS := accurateCall_failure A R C hC K j hK hW hB (by omega) xi hx0 hx1 hPL hCheeger v S + have hT := accurateCall_failure A R C hC K (j+1) hK hW hB hj xi hx0 hx1 hPL hCheeger v S + exact @independent_pair_failure (WeightWord A C K j xi) (WeightWord A C K (j+1) xi) + inferInstance inferInstance inferInstance inferInstance + (accurateCall A R C K j hK hW xi v S) (accurateCall A R C K (j+1) hK hW xi v S) + (xi:ℝ) (xi:ℝ) hS hT + +/-- The calls use independent actual finite words even for a fixed, +arbitrary sequence of observed states. No sampling assumption on that +sequence is required for this oracle-error estimate. -/ +theorem accurateCalls_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) : + uniformAverage (fun bits : Fin (phaseBits A C K j N xi) → Bool => + if ¬accurateCalls A R C K j N hK hW xi v states bits then (1:ℝ) else 0) ≤ + 2*(N:ℝ)*(xi:ℝ) := by + let X := WeightWord A C K j xi × WeightWord A C K (j+1) xi + let Y := Fin (phaseBits A C K j N xi) → Bool + let good (i : Fin N) (b : X) := + accurateCall A R C K j hK hW xi v (states i) b.1 ∧ + accurateCall A R C K (j+1) hK hW xi v (states i) b.2 + have hbad (i : Fin N) : uniformAverage (fun b : X => if ¬good i b then (1:ℝ) else 0) ≤ + (xi:ℝ)+(xi:ℝ) := by + exact pairedCalls_failure A R C hC K j hK hW hB hj xi hx0 hx1 hPL hCheeger v (states i) + have he := @independent_reindex_failure X Y inferInstance inferInstance inferInstance N + (phaseWordEquiv A C K j N xi) good + have hfun : (fun bits : Y => + if ¬accurateCalls A R C K j N hK hW xi v states bits then (1:ℝ) else 0)= + (fun bits : Y => if ¬(∀ i,good i (phaseWordEquiv A C K j N xi bits i)) then (1:ℝ) else 0) := by + funext bits + have hi : accurateCalls A R C K j N hK hW xi v states bits ↔ + ∀ i,good i (phaseWordEquiv A C K j N xi bits i) := Iff.rfl + by_cases h : ∀ i,good i (phaseWordEquiv A C K j N xi bits i) + · simp [hi,h] + · simp [hi,h] + rw [hfun] + calc + _ ≤ ∑ i : Fin N,uniformAverage (fun b : X => if ¬good i b then (1:ℝ) else 0) := + by + convert he using 1 + · apply average_ext_instances + intro bits + by_cases hh : ∀ i,good i (phaseWordEquiv A C K j N xi bits i) <;> simp [hh] + · apply Finset.sum_congr rfl + intro i _ + apply average_ext_instances + intro b + by_cases hh : good i b <;> simp [hh] + _ ≤ ∑ _ : Fin N,((xi:ℝ)+(xi:ℝ)) := Finset.sum_le_sum (fun i _ => hbad i) + _ = 2*(N:ℝ)*(xi:ℝ) := by simp; ring + +/-- The exact empirical ratio written as the plain-state sum divided +by its integer plain-state population. -/ +def exactObservedRatio (A : Instance I J) (R : RootedCompletion.Selection A.T) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) : ℝ := + (∑ i,plainObservable pairs (RootedMultiplierUpdate.ratio A R j) (states i))/ + plainCount A (List.ofFn states) + +private lemma indicator_list_sum_real {X : Type*} (P : X → Prop) (l : List X) : + (l.map (fun x => if P x then (1:ℝ) else 0)).sum=(l.countP (fun x => decide (P x)):ℝ) := by + induction l with + | nil => simp + | cons x l ih => by_cases hx : P x <;> simp [hx,ih,add_comm] + +lemma exactObservedRatio_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) : + exactObservedRatio A R j N states= + empiricalRatio pairs (RootedMultiplierUpdate.ratio A R j) (List.ofFn states) := by + by_cases hN : N=0 + · subst N + simp [exactObservedRatio,empiricalRatio,empirical,plainCount] + · have hNR : (N:ℝ)≠0 := Nat.cast_ne_zero.mpr hN + unfold exactObservedRatio empiricalRatio empirical + unfold plainObservable + rw [indicator_list_sum_real] + simp only [List.map_ofFn,List.sum_ofFn,List.length_ofFn,plainCount] + exact (div_div_div_cancel_right₀ hNR _ _).symm + +private lemma ratio_exponential_bounds {u v uh vh e : ℝ} + (hu : 0 < u) (hv : 0 < v) (he0 : 0 ≤ e) (he1 : e ≤ 1/4) + (huh : (1-e)*u ≤ uh ∧ uh ≤ (1+e)*u) + (hvh : (1-e)*v ≤ vh ∧ vh ≤ (1+e)*v) : + Real.exp (-4*e)*(v/u) ≤ vh/uh ∧ vh/uh ≤ Real.exp (4*e)*(v/u) := by + have huh0 := AnnealingMultipliers.empirical_positive hu he1 huh.1 + have hr := AnnealingMultipliers.relative_ratio hv hu he0 he1 hvh huh + have hid : vh*u/(uh*v)=(vh/uh)/(v/u) := by + field_simp [hu.ne',hv.ne',huh0.ne'] + rw [hid] at hr + have hlo : Real.exp (-4*e) ≤ (vh/uh)/(v/u) := by + calc + _ ≤ Real.exp (Real.log ((vh/uh)/(v/u))) := + Real.exp_le_exp.mpr (by linarith [(abs_le.mp hr.2.2.2).1]) + _ = _ := Real.exp_log hr.1 + have hhi : (vh/uh)/(v/u) ≤ Real.exp (4*e) := by + calc + _ = Real.exp (Real.log ((vh/uh)/(v/u))) := (Real.exp_log hr.1).symm + _ ≤ _ := Real.exp_le_exp.mpr (abs_le.mp hr.2.2.2).2 + exact ⟨(le_div_iff₀ (div_pos hv hu)).mp hlo,(div_le_iff₀ (div_pos hv hu)).mp hhi⟩ + +lemma observedTerm_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) + (hcall : accurateCall A R C K j hK hW xi v S bits.1 ∧ + accurateCall A R C K (j+1) hK hW xi v S bits.2) : + Real.exp (-4*(xi:ℝ))*plainObservable pairs (RootedMultiplierUpdate.ratio A R j) S ≤ + (observedTerm A R C K j hK hW xi v S bits:ℝ) ∧ + (observedTerm A R C K j hK hW xi v S bits:ℝ) ≤ + Real.exp (4*(xi:ℝ))*plainObservable pairs (RootedMultiplierUpdate.ratio A R j) S := by + by_cases hp : PlainState pairs S + · simp only [observedTerm,plainObservable,hp,ite_true,Rat.cast_div, + RootedMultiplierUpdate.ratio] + exact ratio_exponential_bounds (RootedAnnealing.weight_positive A R j S) + (RootedAnnealing.weight_positive A R (j+1) S) (by exact_mod_cast hx0) + (by + have h4 : (4:ℝ)*(xi:ℝ) ≤ 1 := by + exact_mod_cast (show (4:ℚ)*xi ≤ 1 by linarith) + linarith) hcall.1 hcall.2 + · simp only [observedTerm,plainObservable,hp,ite_false,Rat.cast_zero,mul_zero,le_refl,and_self] + +lemma exactObservedRatio_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) (hc : 0 < plainCount A (List.ofFn states)) : + 0 < exactObservedRatio A R j N states := by + obtain ⟨S,hS,hplain⟩ := List.countP_pos_iff.mp hc + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hS + have hpi : PlainState pairs (states i) := by + rw [hi] + exact of_decide_eq_true hplain + have hterm : 0 < plainObservable pairs (RootedMultiplierUpdate.ratio A R j) (states i) := by + rw [plainObservable,ite_eq_left hpi] + exact lt_of_lt_of_le (by norm_num) (RootedMultiplierUpdate.ratio_bounds A R j (states i)).1 + unfold exactObservedRatio + apply div_pos _ (by exact_mod_cast hc) + apply hterm.trans_le + apply Finset.single_le_sum _ (Finset.mem_univ i) + intro k _ + by_cases hk : PlainState pairs (states k) + · rw [plainObservable,ite_eq_left hk] + exact le_trans (by norm_num) (RootedMultiplierUpdate.ratio_bounds A R j (states k)).1 + · simp only [plainObservable,hk,ite_false,le_refl] + +/-- Relative errors of all fresh calls remain bounded after averaging +the state ratios. The number of observations does not enlarge this +deterministic multiplicative error. -/ +theorem observedRatio_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hg : accurateCalls A R C K j N hK hW xi v states bits) : + Real.exp (-4*(xi:ℝ))*exactObservedRatio A R j N states ≤ + (observedRatio A R C K j N hK hW xi v states bits:ℝ) ∧ + (observedRatio A R C K j N hK hW xi v states bits:ℝ) ≤ + Real.exp (4*(xi:ℝ))*exactObservedRatio A R j N states := by + have hb (i : Fin N) := observedTerm_bounds A R C K j hK hW xi hx0 hx1 v (states i) + (phaseWordEquiv A C K j N xi bits i) (hg i) + simp only [observedRatio,exactObservedRatio,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast] + constructor + · rw [←mul_div_assoc] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun i _ => (hb i).1) + · rw [←mul_div_assoc] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun i _ => (hb i).2) + +theorem observedRatio_log_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (hc : 0 < plainCount A (List.ofFn states)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hg : accurateCalls A R C K j N hK hW xi v states bits) : + |Real.log ((observedRatio A R C K j N hK hW xi v states bits:ℝ)/ + exactObservedRatio A R j N states)| ≤ 4*(xi:ℝ) := by + have he := exactObservedRatio_positive A R j N states hc + have hb := observedRatio_bounds A R C K j N hK hW xi hx0 hx1 v states bits hg + have ho := lt_of_lt_of_le (mul_pos (Real.exp_pos _) he) hb.1 + have hl := (le_div_iff₀ he).mpr hb.1 + have hu := (div_le_iff₀ he).mpr hb.2 + have hlogl := Real.log_le_log (Real.exp_pos _) hl + have hlogu := Real.log_le_log (div_pos ho he) hu + rw [Real.log_exp] at hlogl hlogu + exact abs_le.mpr ⟨by linarith, hlogu⟩ + +end +end ContingencyTables.RootedPhaseWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrajectory.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrajectory.lean new file mode 100644 index 0000000000000000000000000000000000000000..7acb2f1e0974d49322b9f1c2083601096adebf0c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrajectory.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBooleanKernel +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrajectory + +namespace OAI + +/-! # The selected-root Boolean history has the exact source path comparison -/ + +namespace ContingencyTables.RootedPhaseTrajectory + +open CommonBasesFPRAS RealKernelApproximation RootedBooleanPhase +open FirstSuccess ResidualMixture FiniteLawMoments +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates TwoLiftStates GridBoundary +open CompanionBooleanPhase (State stepBits) +open CompanionPhaseTrajectory (historyPrefix initial_prefix_expectation) +open scoped BigOperators Classical + +noncomputable section + +private lemma event_le_distance {Y : Type*} [Fintype Y] (p q : Y → ℝ) + (hmass : ∑ y,p y=∑ y,q y) (E : Y → Prop) : + (∑ y,p y*(if E y then 1 else 0))≤ + (∑ y,q y*(if E y then 1 else 0))+distance p q := by + have h := distance_event p q hmass (Finset.univ.filter E) + rw [Finset.sum_filter,Finset.sum_filter] at h + simp only [mul_ite,mul_one,mul_zero] + linarith [le_abs_self ((∑ y,if E y then p y else 0)-(∑ y,if E y then q y else 0))] + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Every event of the actual observed Boolean trajectory is bounded by +the source list-path event plus one proved row error per transition. -/ +theorem recorded_event_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + if E (historyPrefix (recordedWalk A R C K j k N N hK hW xi v w S bits)) then (1:ℝ) else 0)≤ + (targetChain A R j hp w hw).pathExpectation N S (fun l => if E l then 1 else 0)+ + N*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + let p := pathLaw A R C K j k N N hK hW xi v w S + let q := targetPathMass A R j hp w hw N N S + have hq : ∑ b,q b=1 := by + have hh := initial_prefix_expectation (targetChain A R j hp w hw) N S (fun _ => (1:ℝ)) + simpa only [targetPathMass,q,mul_one,FiniteChain.pathExpectation_const] using hh + have hpq : (∑ b,(p.mass b:ℝ))=∑ b,q b := by rw [hq]; exact_mod_cast p.total + have he := event_le_distance (fun b => (p.mass b:ℝ)) q hpq (fun b => E (historyPrefix b)) + have hd := path_distance_bound A R C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw N N S + have hword := word_expectation (recordedWalk A R C K j k N N hK hW xi v w S) + (fun b => if E (historyPrefix b) then (1:ℝ) else 0) + rw [recordedWalk_law] at hword + change _=∑ b,(p.mass b:ℝ)*(if E (historyPrefix b) then 1 else 0) at hword + have htarget := initial_prefix_expectation (targetChain A R j hp w hw) N S + (fun l => if E l then (1:ℝ) else 0) + change (∑ b,q b*(if E (historyPrefix b) then 1 else 0))=_ at htarget + rw [hword] + exact he.trans (by rw [htarget]; exact add_le_add_right hd _) + +end +end ContingencyTables.RootedPhaseTrajectory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..9122c7d535de9bd70cf9236b535bab51684d6b57 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseTrial.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedObservationStart + +namespace OAI + +/-! # A complete finite-word selected-root phase trial + +The trajectory and its weight queries use disjoint words. The output is +the actual guarded rational multiplier and count update. +-/ + +namespace ContingencyTables.RootedPhaseTrial + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity RootedAnnealing RootedMultiplierUpdate +open RootedPhaseExperiment RootedPhaseWords RootedPhaseAccuracy RootedObservationStart +open CompanionBooleanPhase (State stepBits) +open CompanionPhaseWords (Stored phaseBits) +open CompanionTraceWords (eventIndicator) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +private lemma paired_average_bound {X Y : Type*} [Fintype X] [Fintype Y] + [Nonempty X] [Nonempty Y] (f : X × Y → ℝ) (g : X → ℝ) (q : X → Y → ℝ) + (e : ℝ) (hpoint : ∀ z,f z ≤ g z.1+q z.1 z.2) + (hq : ∀ x,uniformAverage (q x) ≤ e) : + uniformAverage f ≤ uniformAverage g+e := by + have hmean := uniformAverage_mono (fun x => uniformAverage (q x)) (fun _ : X => e) hq + rw [uniformAverage_const] at hmean + calc + uniformAverage f ≤ uniformAverage (fun z : X × Y => g z.1+q z.1 z.2) := + uniformAverage_mono _ _ hpoint + _ = uniformAverage g+uniformAverage (fun x => uniformAverage (q x)) := by + rw [uniformAverage_prod] + simp only [uniformAverage_add,uniformAverage_const] + _ ≤ uniformAverage g+e := _root_.add_le_add (le_refl (uniformAverage g)) hmean + +variable {I J : Type} [Fintype I] [Fintype J] + +abbrev TrialWords (A : Instance I J) (C K j k N : ℕ) (xi : ℚ) := + (Fin (N*stepBits A C K j k xi) → Bool) × + (Fin (phaseBits A C K j (N+1) xi) → Bool) + +def trial (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (old : Stored A) (S : State A) + (bits : TrialWords A C K j k N xi) : Option (Stored A) := + update A R C K j (N+1) hK hW xi v old + (observedStates A R C K j k N hK hW xi v old.multiplier S bits.1) bits.2 + +def ValidOutput (A : Instance I J) (R : RootedCompletion.Selection A.T) + (j : ℕ) (old : Stored A) (xi : ℚ) (eta : ℝ) (next : Stored A) : Prop := + (∀ p q,0 < next.multiplier p q) ∧ 0 < next.estimate ∧ + GoodMultipliers pairs (weight A R (j+1)) (fun p q => (next.multiplier p q:ℝ)) ∧ + |Real.log ((next.estimate:ℝ)/((old.estimate:ℝ)* + (slotTotal pairs (weight A R (j+1)) ∅/slotTotal pairs (weight A R j) ∅)))| ≤ + 4*(xi:ℝ)+4*eta + +theorem trial_success (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (old : Stored A) + (hw : ∀ p q,0 < old.multiplier p q) (hE : 0 < old.estimate) + (S : State A) (bits : TrialWords A C K j k N xi) (eta : ℝ) + (he0 : 0 ≤ eta) (he1 : eta ≤ 1/4) + (hacc : AccuratePhase pairs (fun p q => (old.multiplier p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (observedStates A R C K j k N hK hW xi v old.multiplier S bits.1))) + (hcalls : accurateCalls A R C K j (N+1) hK hW xi v + (observedStates A R C K j k N hK hW xi v old.multiplier S bits.1) bits.2) : + ∃ next,trial A R C K j k N hK hW xi v old S bits=some next ∧ + ValidOutput A R j old xi eta next := by + exact update_success A R C K j (N+1) hK hW xi hx0 hx1 v old hw hE eta he0 he1 + (observedStates A R C K j k N hK hW xi v old.multiplier S bits.1) hacc bits.2 hcalls + +private theorem calls_failure_indicator (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) : + uniformAverage (fun bits : Fin (phaseBits A C K j N xi) → Bool => + eventIndicator (¬accurateCalls A R C K j N hK hW xi v states bits)) ≤ + 2*(N:ℝ)*(xi:ℝ) := by + have ht := accurateCalls_failure A R C hC K j N hK hW hB hj xi hx0 hx1 hPL hCheeger v states + have he : uniformAverage (fun bits : Fin (phaseBits A C K j N xi) → Bool => + eventIndicator (¬accurateCalls A R C K j N hK hW xi v states bits))= + uniformAverage (fun bits : Fin (phaseBits A C K j N xi) → Bool => + if ¬accurateCalls A R C K j N hK hW xi v states bits then (1:ℝ) else 0) := by + apply CompanionPhaseWords.average_ext_instances + intro bits + exact CompanionTraceWords.eventIndicator_eq _ + exact he.trans_le ht + +/-- Actual guarded output failure is bounded by trajectory concentration, +the proved weight-call error, and the distance of its incoming law from +the exact warm reference. -/ +theorem trial_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (hp : 0 < Fintype.card (Labels A)) + (old : Stored A) (hw : ∀ p q,0 < old.multiplier p q) (hE : 0 < old.estimate) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (old.multiplier p q:ℝ))) + (p q : State A → ℝ) (hp0 : ∀ S,0 ≤ p S) (hp1 : ∑ S,p S=1) + (hq : ∀ S,0 ≤ q S) (hq1 : ∑ S,q S ≤ 1) + (hwarm : ∀ S,q S ≤ (10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (old.multiplier p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (old.multiplier p q:ℝ)) (weight A R j)) + (eta : ℝ) (he0 : 0 < eta) (he1 : eta ≤ 1/4) : + (∑ S,p S*uniformAverage (fun bits : TrialWords A C K j k N xi => + eventIndicator (¬∃ next,trial A R C K j k N hK hW xi v old S bits=some next ∧ + ValidOutput A R j old xi eta next))) ≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)+2*RealKernelApproximation.distance p q+ + 2*((N+1:ℕ):ℝ)*(xi:ℝ) := by + let states (S : State A) (bits : Fin (N*stepBits A C K j k xi) → Bool) := + observedStates A R C K j k N hK hW xi v old.multiplier S bits + let badObservation (S : State A) (bits : Fin (N*stepBits A C K j k xi) → Bool) := + ¬AccuratePhase pairs (fun p q => (old.multiplier p q:ℝ)) (weight A R j) (ratio A R j) + eta (List.ofFn (states S bits)) + have hpoint (S : State A) (bits : TrialWords A C K j k N xi) : + eventIndicator (¬∃ next,trial A R C K j k N hK hW xi v old S bits=some next ∧ + ValidOutput A R j old xi eta next) ≤ + eventIndicator (badObservation S bits.1)+ + eventIndicator (¬accurateCalls A R C K j (N+1) hK hW xi v (states S bits.1) bits.2) := by + by_cases ha : badObservation S bits.1 + · unfold eventIndicator + split_ifs <;> norm_num + · have ha' : AccuratePhase pairs (fun p q => (old.multiplier p q:ℝ)) (weight A R j) + (ratio A R j) eta (List.ofFn (states S bits.1)) := not_not.mp ha + by_cases hc : accurateCalls A R C K j (N+1) hK hW xi v (states S bits.1) bits.2 + · have hs := trial_success A R C K j k N hK hW xi hx0.le hx1 v old hw hE S bits + eta he0.le he1 ha' hc + simp only [eventIndicator,ha,hc,hs,not_true_eq_false,ite_false,zero_add] + exact le_rfl + · unfold eventIndicator + split_ifs <;> norm_num + have hlocal (S : State A) : + uniformAverage (fun bits : TrialWords A C K j k N xi => + eventIndicator (¬∃ next,trial A R C K j k N hK hW xi v old S bits=some next ∧ + ValidOutput A R j old xi eta next)) ≤ + uniformAverage (fun bits => eventIndicator (badObservation S bits))+ + 2*((N+1:ℕ):ℝ)*(xi:ℝ) := by + have hc (bits : Fin (N*stepBits A C K j k xi) → Bool) : + uniformAverage (fun fresh : Fin (phaseBits A C K j (N+1) xi) → Bool => + eventIndicator (¬accurateCalls A R C K j (N+1) hK hW xi v (states S bits) fresh)) ≤ + 2*((N+1:ℕ):ℝ)*(xi:ℝ) := by + exact calls_failure_indicator A R C hC K j (N+1) hK hW hB hj xi hx0 + (lt_of_le_of_lt hx1 (by norm_num)) hPL hCheeger v (states S bits) + exact paired_average_bound _ _ _ _ (hpoint S) hc + have hsum := Finset.sum_le_sum (fun S (_ : S∈Finset.univ) => + mul_le_mul_of_nonneg_left (hlocal S) (hp0 S)) + simp only [mul_add,Finset.sum_add_distrib,←Finset.sum_mul,hp1,one_mul] at hsum + have hobs := observed_failure_near A R C hC K j k N hK hW hB (by omega) xi hx0 hx1 + hPL hCheeger v hp old.multiplier hw hgood p q hq hq1 hwarm eta he0 + dsimp only [badObservation,states] at hsum + have hb := _root_.add_le_add hobs (le_refl (2*((N+1:ℕ):ℝ)*(xi:ℝ))) + exact hsum.trans hb + +end +end ContingencyTables.RootedPhaseTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a0f0b971378b4b958d08b46781f931bcd965fe2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhaseWords.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWeightOracle +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseWords + +namespace OAI + +/-! # Fresh selected-root oracle words and actual rational phase updates -/ + +namespace ContingencyTables.RootedPhaseWords + +open CompanionFactorialApplication CompanionOracleDensity RootedWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS GridBoundary FirstSuccess FairBits TwoLiftStates +open CompanionPhaseWords (phaseBits phaseWordEquiv Stored) +open CompanionWeightOracle (WeightWord) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +def observedTerm (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) : ℚ := + if PlainState pairs S then + evaluate A R C K hK hW (j+1) xi v S bits.2/evaluate A R C K hK hW j xi v S bits.1 + else 0 + +def observedRatio (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : ℚ := + (∑ i,observedTerm A R C K j hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i))/ + plainCount A (List.ofFn states) + +lemma observedTerm_nonneg (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) : + 0 ≤ observedTerm A R C K j hK hW xi v S bits := by + unfold observedTerm + split_ifs + · exact (div_pos (evaluate_positive A R C hC K hK hW hB (j+1) hj xi hx0 hx1 v S bits.2) + (evaluate_positive A R C hC K hK hW hB j (by omega) xi hx0 hx1 v S bits.1)).le + · rfl + +lemma observedRatio_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (hc : 0 < plainCount A (List.ofFn states)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : + 0 < observedRatio A R C K j N hK hW xi v states bits := by + obtain ⟨S,hS,hplain⟩ := List.countP_pos_iff.mp hc + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hS + have hpi : PlainState pairs (states i) := by + rw [hi] + exact of_decide_eq_true hplain + have hterm : 0 < observedTerm A R C K j hK hW xi v (states i) + (phaseWordEquiv A C K j N xi bits i) := by + rw [observedTerm,ite_eq_left hpi] + exact div_pos (evaluate_positive A R C hC K hK hW hB (j+1) hj xi hx0 hx1 v _ _) + (evaluate_positive A R C hC K hK hW hB j (by omega) xi hx0 hx1 v _ _) + unfold observedRatio + apply div_pos _ (by exact_mod_cast hc) + exact hterm.trans_le (Finset.single_le_sum + (fun k _ => observedTerm_nonneg A R C hC K j hK hW hB hj xi hx0 hx1 v _ _) + (Finset.mem_univ i)) + +def update (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (old : Stored A) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : Option (Stored A) := + if CountsPositive A (List.ofFn states) then + some ⟨rationalLearn pairs old.multiplier (List.ofFn states), + old.estimate*observedRatio A R C K j N hK hW xi v states bits⟩ + else none + +/-- A nonaborting update keeps every stored rational positive, even if +all its weight calls were statistically inaccurate. -/ +theorem update_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (old next : Stored A) + (hw : ∀ p q,0 < old.multiplier p q) (hE : 0 < old.estimate) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hu : update A R C K j N hK hW xi v old states bits=some next) : + (∀ p q,0 < next.multiplier p q) ∧ 0 < next.estimate := by + unfold update at hu + split_ifs at hu with hc + · cases Option.some.inj hu + constructor + · apply checkedUpdate_positive A old.multiplier hw (List.ofFn states) + simp only [checkedUpdate,hc,ite_true] + · exact mul_pos hE (observedRatio_positive A R C hC K j N hK hW hB hj xi hx0 hx1 v states hc.1 bits) + +lemma update_multiplier_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (old next : Stored A) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hu : update A R C K j N hK hW xi v old states bits=some next) (p q : Pair A) : + (next.multiplier p q:ℝ)= + learnedMultipliers pairs (fun p q => (old.multiplier p q:ℝ)) (List.ofFn states) p q := by + unfold update at hu + split_ifs at hu + · cases Option.some.inj hu + exact rationalLearn_cast _ _ _ _ _ + +end +end ContingencyTables.RootedPhaseWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..295b823e8f8715bb9d4a32d81a513bde733e88d0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalCompletion.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedAffine +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPhysicalCompletion + +namespace OAI + +/-! # Literal residual completion for the executed root convention + +The row and column small views remain distinct. The explicit selected +roots determine which incidence equations are enforced; the resulting +integral completion is exactly the selected-cut affine formula. +-/ + +namespace ContingencyTables.RootedPhysicalCompletion + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedAffine GraphCompletionCounts ForestCut +open ForestPhysicalCompletion + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def solved (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) : I → J → ℤ := + table A.T S (rowResidual A.small A.T A.r x free) + (columnResidual A.small A.T A.c q free) + +noncomputable def completed (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (i : I) (j : J) : ℤ := + if A.T.Adj (.inl i) (.inr j) then solved A S x q free i j else free i j + +lemma solved_supported (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (i : I) (j : J) (h : ¬A.T.Adj (.inl i) (.inr j)) : + solved A S x q free i j=0 := table_supported A.T S _ _ i j h + +lemma row_pointwise (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (i : I) (j : J) : + (if A.small i j then x i j else completed A S x q free i j)= + solved A S x q free i j+fixedRow A.small A.T x free i j := by + by_cases ht : A.T.Adj (.inl i) (.inr j) + · have hs : A.small i j=false := A.hTG ht + simp only [hs,Bool.false_eq_true,ite_false,completed,ht,ite_true,fixedRow,add_zero] + · simp only [completed,ht,ite_false,solved_supported A S x q free i j ht,zero_add,fixedRow] + +lemma column_pointwise (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (i : I) (j : J) : + (if A.small i j then q i j else completed A S x q free i j)= + solved A S x q free i j+fixedColumn A.small A.T q free i j := by + by_cases ht : A.T.Adj (.inl i) (.inr j) + · have hs : A.small i j=false := A.hTG ht + simp only [hs,Bool.false_eq_true,ite_false,completed,ht,ite_true,fixedColumn,add_zero] + · simp only [completed,ht,ite_false,solved_supported A S x q free i j ht,zero_add,fixedColumn] + +lemma row_completed_sum (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (i : I) (hi : Sum.inl i≠S.root (.inl i)) : + (∑ j,if A.small i j then x i j else completed A S x q free i j)=A.r i := by + simp_rw [row_pointwise] + rw [Finset.sum_add_distrib] + have he : (∑ j,solved A S x q free i j)=rowResidual A.small A.T A.r x free i := + table_row A.small A.T S A.hTG _ _ i hi + rw [he,rowResidual] + exact sub_add_cancel _ _ + +lemma column_completed_sum (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (j : J) (hj : Sum.inr j≠S.root (.inr j)) : + (∑ i,if A.small i j then q i j else completed A S x q free i j)=A.c j := by + simp_rw [column_pointwise] + rw [Finset.sum_add_distrib] + have he : (∑ i,solved A S x q free i j)=columnResidual A.small A.T A.c q free j := + table_column A.small A.T S A.hTG _ _ j hj + rw [he,columnResidual] + exact sub_add_cancel _ _ + +/-- The cut-defined coefficients evaluate the actual integral solution +for this root convention, including every unbalanced small profile. -/ +theorem solved_eq_affine (A : Instance I J) (S : Selection A.T) (t : TreeCell A.T) + (x q free : I → J → ℤ) : + (solved A S x q free t.val.1 t.val.2:ℝ)= + affineTree A S t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) + (fun a => (free a.1 a.2:ℝ)) := by + let z : I → J → ℝ := fun i j => (completed A S x q free i j:ℝ) + have hh := affine_of_nonroot_equations A S t (fun i j => (x i j:ℝ)) + (fun i j => (q i j:ℝ)) z (by + intro i hi + have hr := row_completed_sum A S x q free i hi + unfold rowDifference + have he : (∑ j,if A.small i j then (x i j:ℝ) else z i j)=(A.r i:ℝ) := by + dsimp only [z] + exact_mod_cast hr + have hX : (∑ j,(A.X i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast A.hXr i + calc + _=(∑ j,if A.small i j then (x i j:ℝ) else z i j)-(∑ j,(A.X i j:ℝ)) := by + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> rfl + _=0 := by rw [he,hX,sub_self]) (by + intro j hj + have hc := column_completed_sum A S x q free j hj + unfold columnDifference + have he : (∑ i,if A.small i j then (q i j:ℝ) else z i j)=(A.c j:ℝ) := by + dsimp only [z] + exact_mod_cast hc + have hX : (∑ i,(A.X i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast A.hXc j + calc + _=(∑ i,if A.small i j then (q i j:ℝ) else z i j)-(∑ i,(A.X i j:ℝ)) := by + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + split_ifs <;> rfl + _=0 := by rw [he,hX,sub_self]) + have hz : z t.val.1 t.val.2=(solved A S x q free t.val.1 t.val.2:ℝ) := by + simp only [z,completed,t.property,ite_true] + rw [hz] at hh + rw [hh] + unfold affineTree AffinePenalty.affineValue + congr 1 + apply Finset.sum_congr rfl + intro a _ + by_cases ht : A.T.Adj (.inl a.1) (.inr a.2) + · simp only [coefficient,ht,not_true_eq_false,and_false,ite_false,zero_mul] + · simp only [z,completed,ht,ite_false] + +end ContingencyTables.RootedPhysicalCompletion + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalNormalizer.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalNormalizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..6826724bdc0ae1468d94e593c76b6a902e43a7aa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalNormalizer.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedFactorialApplication +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalNormalizer + +namespace OAI + +/-! # The selected-root factorial normalizer is the literal physical mass -/ + +namespace ContingencyTables.RootedPhysicalNormalizer + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication TwoLiftStates RootedFactorialApplication +open BalancedCellFibres PhysicalLargeProfiles LargePairEnumeration TreeMarginalSignature +open CompanionPhysicalNormalizer (smallProfilesEquiv small_display_eq) + +private lemma finite_sum_congr {C : Type*} (F G : Fintype C) (f g : C → ℝ) + (h : ∀ c,f c=g c) : + @Finset.sum C ℝ _ (@Finset.univ C F) f=@Finset.sum C ℝ _ (@Finset.univ C G) g := by + have he : F=G := Subsingleton.elim _ _ + cases he + exact Finset.sum_congr rfl (fun c _ => h c) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def physicalMass (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : ℝ := + ∑ a : Profiles (cellWidth A),RootedPenalty.physicalWeight A R alpha + (BalancedCellFibres.profile (cellWidth A) a) + +lemma h_eq_physical_sum (A : Instance I J) (R : RootedCompletion.Selection A.T) + (alpha : ℝ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) : + RootedCountIdentification.h A R alpha z= + ∑ a : PhysicalAssignments (fun a : I×J => A.small a.1 a.2) (cellWidth A), + RootedPenalty.physicalWeight A R alpha + (physicalProfile (fun a : I×J => A.small a.1 a.2) (cellWidth A) z a) := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + rw [RootedCountIdentification.h_eq_largeMarginal A R alpha e z hz] + unfold RootedLargeMarginal.largeMarginal + convert sum_joined_eq_physical (fun a : I×J => A.small a.1 a.2) (cellWidth A) e z + (RootedPenalty.physicalWeight A R alpha) using 1 + all_goals + apply finite_sum_congr + intro a + rfl + +lemma physicalMass_eq_split (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : + physicalMass A R alpha= + ∑ s : SmallProfiles (fun a : I×J => A.small a.1 a.2) (cellWidth A), + ∑ a : PhysicalAssignments (fun a : I×J => A.small a.1 a.2) (cellWidth A), + RootedPenalty.physicalWeight A R alpha + (physicalProfile (fun a : I×J => A.small a.1 a.2) (cellWidth A) + (smallDisplay (fun a : I×J => A.small a.1 a.2) (cellWidth A) s) a) := by + let F := RootedPenalty.physicalWeight A R alpha + let small : I×J → Bool := fun a => A.small a.1 a.2 + change (∑ a : Profiles (cellWidth A),F (BalancedCellFibres.profile (cellWidth A) a))= + ∑ s : SmallProfiles small (cellWidth A),∑ a : PhysicalAssignments small (cellWidth A), + F (physicalProfile small (cellWidth A) (smallDisplay small (cellWidth A) s) a) + have he := Fintype.sum_equiv (partition small (cellWidth A)) + (fun a => F (BalancedCellFibres.profile (cellWidth A) a)) + (fun a => F (physicalProfile small (cellWidth A) (smallDisplay small (cellWidth A) a.1) a.2)) + (by + intro a + have hh := partition_profile small (cellWidth A) ((partition small (cellWidth A)) a) + simpa only [Equiv.symm_apply_apply] using congrArg F hh) + rw [he,Fintype.sum_prod_type] + +lemma total_eq_raw_profiles (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : + slotTotal pairs (RootedFactorialApplication.f A R alpha) ∅= + ∑ x : TransversalCount.Profile (fun s : SmallCell A => A.b s.val.1 s.val.2), + RootedCountIdentification.h A R alpha + (TransversalCount.display (fun s : SmallCell A => A.b s.val.1 s.val.2) x) := by + unfold RootedFactorialApplication.f + rw [CompanionInitialization.denominator_eq] + convert TransversalCount.slotTotal_eq_profiles + (fun s : SmallCell A => A.b s.val.1 s.val.2) (RootedCountIdentification.h A R alpha) using 1 + congr 1 + all_goals + congr 1 + ext + simp + +/-- Factorial cancellation and the actual physical partition identify +this selected-root normalizer with the mass used in terminal estimates. -/ +theorem normalizer_eq_physical_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : + slotTotal pairs (RootedFactorialApplication.f A R alpha) ∅=physicalMass A R alpha := by + rw [total_eq_raw_profiles,physicalMass_eq_split] + symm + apply Fintype.sum_equiv (smallProfilesEquiv A) + intro s + rw [small_display_eq] + symm + apply h_eq_physical_sum + intro u + rcases u with ⟨a,b⟩ + cases b + · exact Nat.le_of_lt_succ ((smallProfilesEquiv A s) a).isLt + · exact Nat.sub_le _ _ + +end ContingencyTables.RootedPhysicalNormalizer + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalTables.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..e93a791b3d2968a9da1bb14cb446a4454df91368 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPhysicalTables.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeFeasibleMass +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalNormalizer +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalTables + +namespace OAI + +/-! # Feasible physical tables retain unit mass for the selected roots -/ + +namespace ContingencyTables.RootedPhysicalTables + +open scoped BigOperators Classical +open CompanionFactorialApplication TreeMarginalSignature BalancedCellFibres +open CompanionPhysicalTables (Feasible PhysicalTables physicalTable assignment_physicalTable cardinality_eq) + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem feasible_weight_one (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (a : Profiles (cellWidth A)) + (ha : Feasible A a) : + RootedPenalty.physicalWeight A R alpha (BalancedCellFibres.profile (cellWidth A) a)=1 := by + have hh := RootedTreeMarginal.tableAssignment_unit A R alpha (physicalTable A a) ha.1 ha.2.1 ha.2.2 + rwa [assignment_physicalTable A a ha.1] at hh + +/-- Every original bounded table contributes exactly one unit, so the +actual normalizer always dominates the table count. -/ +theorem table_count_le_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) : + (Fintype.card (BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b):ℝ) ≤ + RootedPhysicalNormalizer.physicalMass A R alpha := by + have hcount : (∑ a : Profiles (cellWidth A),if Feasible A a then (1:ℝ) else 0)= + (Fintype.card (PhysicalTables A):ℝ) := by + simp only [Finset.sum_ite,Finset.sum_const_zero,add_zero,Finset.sum_const,nsmul_eq_mul,mul_one] + rw [Fintype.card_subtype] + rw [← cardinality_eq,← hcount] + unfold RootedPhysicalNormalizer.physicalMass + apply Finset.sum_le_sum + intro a _ + split_ifs with ha + · rw [feasible_weight_one A R alpha a ha] + · exact RootedPenalty.physicalWeight_nonnegative A R alpha _ + +end ContingencyTables.RootedPhysicalTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPlainTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPlainTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b3fb21d658d071a3d409d7d577711d47e0ec7c7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPlainTrial.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrial +import OAI.Combinatorics.ContingencyTables.Machines.FinitePlainLift + +namespace OAI + +/-! # A selected-root phase begun from its actual transversal law -/ + +namespace ContingencyTables.RootedPlainTrial + +open CommonBasesFPRAS FirstSuccess ResidualMixture RealKernelApproximation +open CompanionFactorialApplication CompanionRationalUpdates CompanionOracleDensity +open RootedAnnealing RootedWarmStart RootedPhaseTrial +open CompanionPhaseWords (Stored) +open CompanionConcentration (pairs_ne_nil) +open CompanionTraceWords (eventIndicator) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +lemma lift_warm (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 < Fintype.card (Labels A)) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (w p q:ℝ))) + (q : PlainIndex (pairs : List (Pair A)) → ℝ) + (hq : ∀ S,q S ≤ 2*law A R j S.val.val) + (S : ChainIndex (pairs : List (Pair A))) : + plainLift pairs q S ≤ (10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j) := by + have hpos : ∀ p q,0 < (w p q:ℝ) := fun p q => by exact_mod_cast hw p q + have htrace (T : PlainIndex (pairs : List (Pair A))) : + q T ≤ 2*(metropolisTrace pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A R j) hpos + (weight_positive A R j)).π T := by + rw [metropolisTrace_pi] + exact hq T + have h := plainLift_warm pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A R j) + (weight_positive A R j) hgood q htrace S + simpa only [PairedLabels.length] using h + +/-- The incoming law is the actual rational output law on transversals; +only the comparison reference is warm. -/ +theorem trial_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (hp : 0 < Fintype.card (Labels A)) + (old : Stored A) (hw : ∀ p q,0 < old.multiplier p q) (hE : 0 < old.estimate) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (old.multiplier p q:ℝ))) + (p : RationalLaw (PlainIndex (pairs : List (Pair A)))) + (q : PlainIndex (pairs : List (Pair A)) → ℝ) + (hq : ∀ S,0 ≤ q S) (hq1 : ∑ S,q S ≤ 1) + (hwarm : ∀ S,q S ≤ 2*law A R j S.val.val) + (eta : ℝ) (he0 : 0 < eta) (he1 : eta ≤ 1/4) : + (∑ S,(p.mass S:ℝ)*uniformAverage (fun bits : TrialWords A C K j k N xi => + eventIndicator (¬∃ next,trial A R C K j k N hK hW xi v old S.val bits=some next ∧ + ValidOutput A R j old xi eta next))) ≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)+ + 2*distance (fun S => (p.mass S:ℝ)) q+2*((N+1:ℕ):ℝ)*(xi:ℝ) := by + have hp0 (S : PlainIndex (pairs : List (Pair A))) : 0 ≤ (p.mass S:ℝ) := by + exact_mod_cast p.nonnegative S + have hp1 : (∑ S,(p.mass S:ℝ))=1 := by exact_mod_cast p.total + have hfull := RootedPhaseTrial.trial_failure A R C hC K j k N hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp old hw hE hgood + (plainLift pairs (fun S => (p.mass S:ℝ))) (plainLift pairs q) + (plainLift_nonneg pairs _ hp0) + (by rw [plainLift_mass]; exact hp1) + (plainLift_nonneg pairs _ hq) + (by rw [plainLift_mass]; exact hq1) + (lift_warm A R j hp old.multiplier hw hgood q hwarm) eta he0 he1 + rw [FinitePlainLift.sum_mul,FinitePlainLift.distance_lift] at hfull + exact hfull + +end +end ContingencyTables.RootedPlainTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPointPenaltyProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPointPenaltyProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8b2e404a356a10c41c69f4c4d7feef9b2dec6c8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedPointPenaltyProgram.lean @@ -0,0 +1,227 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestPrepareProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionArithmetic + +namespace OAI + +/-! # Executed penalty evaluation at a sampled integer assignment + +At an integer point, the coordinate scale in the affine coefficient +cancels its inverse in the coordinate. The program therefore forms the +unscaled signed affine numerator directly from the sampled integers. +-/ + +namespace ContingencyTables.RootedPointPenaltyProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped RootedForestPrepareProgram +open scoped BigOperators Classical + +def term (z : RootedForestDataProgram.TermInput) : ForestAffineProgram.Term := + (RootedCoefficientProgram.coefficient z.1,z.2) +def termRealizer : Realizer term := + pair (composition (f := fun z : RootedForestDataProgram.TermInput => z.1) + (g := RootedCoefficientProgram.coefficient) first RootedCoefficientProgram.coefficientRealizer) second +lemma polynomial_term : PolynomialTime termRealizer := + polynomial_pair (polynomial_composition polynomial_first + RootedCoefficientProgram.polynomial_coefficient) polynomial_second + +def tree (z : RootedForestDataProgram.Input) : ForestAffineProgram.Input := + ((RootedOffsetProgram.offset z.1.2,z.2.map term),z.1.1.2) +def treeRealizer : Realizer tree := + pair (pair (composition (f := fun z : RootedForestDataProgram.Input => z.1.2) + (g := RootedOffsetProgram.offset) (composition first second) RootedOffsetProgram.offsetRealizer) + (composition second (map termRealizer))) (composition (composition first first) second) +lemma polynomial_tree : PolynomialTime treeRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + RootedOffsetProgram.polynomial_offset) + (polynomial_composition polynomial_second (polynomial_map polynomial_term))) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + +def prepareTree (z : TreeInput) : ForestAffineProgram.Input := tree (forestInput z) +def prepareTreeRealizer : Realizer prepareTree := + composition (f := forestInput) (g := tree) forestInputRealizer treeRealizer +lemma polynomial_prepareTree : PolynomialTime prepareTreeRealizer := + polynomial_composition polynomial_forestInput polynomial_tree + +def trees (z : Input) : List ForestAffineProgram.Input := + (treeCells z).map (fun a => prepareTree (treeBundle z,a)) +def treesRealizer : Realizer trees := + composition (f := fun z : Input => (treeBundle z,treeCells z)) + (g := fun z => z.2.map (fun a => prepareTree (z.1,a))) + (pair treeBundleRealizer treeCellsRealizer) (mapWith prepareTreeRealizer) +lemma polynomial_trees : PolynomialTime treesRealizer := + polynomial_composition (polynomial_pair polynomial_treeBundle polynomial_treeCells) + (polynomial_mapWith polynomial_prepareTree) + +def prepare (z : Input) : ForestPenaltyProgram.Input := + ((z.1.1.1,RootedDemandProgram.rootCount z.1.2),trees z) +def prepareRealizer : Realizer prepare := + pair (pair (composition (composition first first) first) + (composition (f := fun z : Input => z.1.2) (g := RootedDemandProgram.rootCount) + (composition first second) RootedDemandProgram.rootCountRealizer)) treesRealizer +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + RootedDemandProgram.polynomial_rootCount)) polynomial_trees + +def output (z : Input) : TreeFraction.Fraction := ForestPenaltyProgram.penaltyCode (prepare z) +def outputRealizer : Realizer output := composition prepareRealizer ForestPenaltyProgram.penaltyCodeRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare ForestPenaltyProgram.polynomial_penaltyCode + +open CompanionFactorialApplication RootedCompletion ForestAssignmentSplit GraphCompletionCounts + +noncomputable section +variable {m n nf nc : ℕ} + +lemma coefficient_parts (z : RootedCoefficientProgram.Input) : + RootedCoefficientProgram.coefficient z=ForestAffineProgram.signedParts + (SignedPairProgram.value (RootedCoefficientProgram.coefficient z)) := by + unfold RootedCoefficientProgram.coefficient + split + · rw [SignedPairProgram.value_normalize] + exact SignedPairProgram.normalize_eq _ + · rfl + +lemma coefficient_parts_input (A : Instance (Fin m) (Fin n)) (t : TreeCell A.T) + (a : Fin m×Fin n) : + RootedCoefficientProgram.coefficient (RootedCoefficientProgram.input A t a)= + ForestAffineProgram.signedParts (RootedIntegerEvaluation.coefficient A (rowColumn A.T) t a) := by + rw [coefficient_parts,RootedCoefficientProgram.coefficient_input] + +lemma tree_data (A : Instance (Fin m) (Fin n)) (B : ℕ) (t : TreeCell A.T) + (x q : Fin m → Fin n → ℤ) (cells : Fin nc ≃ Fin m×Fin n) + (free : Fin nf ≃ FreeCell A.small A.T) (v : FreeCell A.small A.T → ℕ) : + tree (RootedForestDataProgram.data A B t x q cells free v)= + ForestAffineProgram.data (RootedIntegerEvaluation.offset A (rowColumn A.T) t x q) + (fun i => RootedIntegerEvaluation.coefficient A (rowColumn A.T) t (free i).val) + (fun i => v (free i)) (A.b t.val.1 t.val.2) := by + unfold tree RootedForestDataProgram.data ForestAffineProgram.data + rw [RootedOffsetProgram.offset_data] + simp only [List.map_ofFn,Function.comp_def,term,coefficient_parts_input] + +lemma rational_tree_integer (A : Instance (Fin m) (Fin n)) (B : ℕ) (hB : 0 (B:ℚ)*(v f:ℚ)/((A.b f.val.1 f.val.2:ℚ)+1)) t= + ((RootedIntegerEvaluation.offset A (rowColumn A.T) t x q:ℚ)+ + ∑ f : FreeCell A.small A.T, + (RootedIntegerEvaluation.coefficient A (rowColumn A.T) t f.val:ℚ)*(v f:ℚ))/ + A.b t.val.1 t.val.2 := by + have hBQ : (B:ℚ)≠0 := by exact_mod_cast hB.ne' + unfold RootedIntegerEvaluation.rationalScaledTree + rw [add_div,Finset.sum_div] + congr 1 + apply Finset.sum_congr rfl + intro f _ + have hN : (A.b f.val.1 f.val.2:ℚ)+1≠0 := by positivity + have ht : (A.b t.val.1 t.val.2:ℚ)≠0 := by + exact_mod_cast (Nat.lt_of_lt_of_le Nat.zero_lt_one + (A.hlarge _ _ (A.hTG t.property)).2).ne' + field_simp [hBQ,hN,ht] + +theorem tree_value (A : Instance (Fin m) (Fin n)) (B : ℕ) (hB : 0 (B:ℚ)*(v f:ℚ)/((A.b f.val.1 f.val.2:ℚ)+1)) t) + (RootedIntegerEvaluation.rationalScaledTree A (rowColumn A.T) B x q + (fun f => (B:ℚ)*(v f:ℚ)/((A.b f.val.1 f.val.2:ℚ)+1)) t-1)) := by + have ht : 0 rfl) + rw [he,rational_tree_integer A B hB] + +lemma trees_data (A : Instance (Fin m) (Fin n)) (C B : ℕ) + (x q : Fin m → Fin n → ℕ) (v : FreeCell A.small A.T → ℕ) : + trees (RootedForestPrepareProgram.data A C B x q v)= + List.ofFn (fun i => tree (RootedForestDataProgram.data A B + (RootedForestCatalog.treeEquiv A i) (fun i j => (x i j:ℤ)) + (fun i j => (q i j:ℤ)) finProdFinEquiv.symm (RootedForestCatalog.freeEquiv A) v)) := by + change (RootedForestCatalog.catalog (RootedForestCatalog.data A,true)).map + (fun a => prepareTree (((RootedDemandProgram.data A x q,B), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))),a))=_ + have hc := congrArg (fun cells : List (ℕ×ℕ) => cells.map + (fun a => prepareTree (((RootedDemandProgram.data A x q,B), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))),a))) + (RootedForestPrepareProgram.treeCatalog_ofFn A) + refine hc.trans ?_ + rw [List.map_ofFn] + apply congrArg List.ofFn + funext i + change tree (forestInput (((RootedDemandProgram.data A x q,B), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i))), + ((RootedForestCatalog.treeEquiv A i).val.1.val, + (RootedForestCatalog.treeEquiv A i).val.2.val)))=_ + exact congrArg tree (RootedForestPrepareProgram.forestInput_data A B + (RootedForestCatalog.treeEquiv A i) x q v) + +/-- The executed penalty is exactly the source's rational penalty at +the scaled integer assignment, with no numerical approximation. -/ +theorem output_data (A : Instance (Fin m) (Fin n)) (C : ℕ) (hC : 0 (x i j:ℤ)) (fun i j => (q i j:ℤ)) + (fun f => (CompanionOracleDensity.rationalBinWidth A C:ℚ)*(v f:ℚ)/ + ((A.b f.val.1 f.val.2:ℚ)+1)) := by + have hB : 0 TreeFraction.val (ForestAffineProgram.evaluate t))).sum)=_ + rw [RootedDemandProgram.rootCount_data,trees_data] + simp only [List.map_ofFn,Function.comp_apply,List.sum_ofFn] + unfold RootedPenaltyProgram.rationalPenalty + congr 2 + exact Fintype.sum_equiv (RootedForestCatalog.treeEquiv A) _ _ + (fun i => tree_value A _ hB (RootedForestCatalog.treeEquiv A i) _ _ + finProdFinEquiv.symm (RootedForestCatalog.freeEquiv A) v) + +theorem output_integerPoint (A : Instance (Fin m) (Fin n)) (C : ℕ) (hC : 0 A.b i j-ForestCountIdentification.smallY A.small z i j) + (fun t => (f t).val)))= + RootedOracleDensity.rationalD A (rowColumn A.T) C z + (CompanionOracleDensity.rationalIntegerPoint A C f) := by + have hpoint : (fun t : FreeCell A.small A.T => + CompanionOracleDensity.rationalIntegerPoint A C f + ((CompanionOracleDensity.index A).symm t))= + (fun t => (CompanionOracleDensity.rationalBinWidth A C:ℚ)*(f t).val/ + ((A.b t.val.1 t.val.2:ℚ)+1)) := by + funext t + change (CompanionOracleDensity.rationalBinWidth A C:ℚ)* + (f (CompanionOracleDensity.index A ((CompanionOracleDensity.index A).symm t))).val/ + CompanionOracleDensity.freeRange A + (CompanionOracleDensity.index A ((CompanionOracleDensity.index A).symm t))=_ + rw [Equiv.apply_symm_apply] + simp only [CompanionOracleDensity.freeRange,Nat.cast_add,Nat.cast_one] + rw [output_data A C hC] + unfold RootedOracleDensity.rationalD + rw [hpoint] + rfl + +theorem output_denominator_pos (z : Input) : 0<(output z).2 := + TreeFraction.normalize_den_pos _ + +end +end ContingencyTables.RootedPointPenaltyProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb3952740cb2d670524a08b5686d49d0cb73cc99 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleLaw.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSampleProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport + +namespace OAI + +/-! # The executed ratio sample has the exact analysed law -/ + +namespace ContingencyTables.RootedRatioSampleLaw + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity ResidualMixture FirstSuccess FiniteLawMoments +open CommonBasesFPRAS FiniteObservableTransport +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +private lemma expectation_equiv {X Y : Type*} [Fintype X] [Fintype Y] + (e : X ≃ Y) (p : RationalLaw X) (f : Y → ℝ) : + expectation (equivLaw e p) f=expectation p (fun x => f (e x)) := by + unfold expectation equivLaw + symm + exact Fintype.sum_equiv e _ _ (fun x => by simp only [Equiv.symm_apply_apply]) + +def sample (A : Instance (Fin m) (Fin n)) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) + (bits : Fin (N*oracleStepBits A C) → Bool) : ℚ := + RootedOracleDensity.rationalRatioObservable A (RootedCompletion.rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K (RootedOracleWalkProgram.flatGridWalk A C a z v N bits)) + +theorem sameLaw (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (hK : 1 ≤ K) + (hKB : (K:ℝ) ≤ binWidth A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) : + SameLaw (sample A C a z v N) + (RootedOracleDensity.ratioSample A (RootedCompletion.rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K v) N) := by + intro g + let obs := fun w : Grid (I := Fin (dimension A)) K => + g (RootedOracleDensity.rationalRatioObservable A (RootedCompletion.rowColumn A.T) C a z w) + have hl := word_expectation (RootedOracleWalkProgram.flatGridWalk A C a z v N) + (fun w => obs (RootedCatalogGrid.gridEquiv A K w)) + rw [RootedOracleWalkProgram.flatGridWalk_law, + RootedCatalogGrid.wordWalkLaw_eq A C a hC haH z hz hK hKB,expectation_equiv] at hl + simp only [Equiv.apply_symm_apply] at hl + have hr := word_expectation + (wordWalk (RootedOracleDensity.oracleBitStep A (RootedCompletion.rowColumn A.T) C a z) + (RootedCatalogGrid.gridEquiv A K v) N) obs + change uniformAverage (fun bits => g (RootedOracleDensity.ratioSample A + (RootedCompletion.rowColumn A.T) C a z (RootedCatalogGrid.gridEquiv A K v) N bits))= + expectation (RootedOracleDensity.oracleBitWalkLaw A (RootedCompletion.rowColumn A.T) + C a z (RootedCatalogGrid.gridEquiv A K v) N) obs at hr + rw [RootedOracleDensity.oracleBitWalkLaw_eq A (RootedCompletion.rowColumn A.T) + C a hC haH z hz hK hKB] at hr + exact hl.trans hr.symm + +lemma program_sample (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) + (bits : Fin (N*oracleStepBits A C) → Bool) : + MatchingFPRAS.TreeFraction.val (RootedRatioSampleProgram.output + (RootedOracleWalkProgram.data A C a K z v,List.ofFn bits))=sample A C a z v N bits := + RootedRatioSampleProgram.output_data A C a K hC z hz hKB v N bits + +end +end ContingencyTables.RootedRatioSampleLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..25e3ccdb3a664a72f6193e4164ff41de42008e26 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSampleProgram.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFlatProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSamples + +namespace OAI + +/-! # Polynomial execution of an adjacent-parameter ratio sample + +The exact ratio is either one or one half. The program compares the two +computed integer exponents and never materializes an exponential weight. +-/ + +namespace ContingencyTables.RootedRatioSampleProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open scoped Classical + +abbrev Input := RootedPenaltyEvaluateProgram.Input + +def bump (z : Input) : Input := ((z.1.1,(z.1.2.1,z.1.2.2+1)),z.2) +def bumpRealizer : Realizer bump := + pair (pair (composition first first) + (pair (composition (composition first second) first) + (composition (composition (composition first second) second) successor))) second +lemma polynomial_bump : PolynomialTime bumpRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_successor))) polynomial_second + +attribute [local irreducible] RootedPenaltyEvaluateProgram.evaluate + +def equalExponents (z : Input) : Bool := + decide (RootedPenaltyEvaluateProgram.evaluate (bump z)=RootedPenaltyEvaluateProgram.evaluate z) +def equalExponentsRealizer : Realizer equalExponents := + composition (f := fun z : Input => (RootedPenaltyEvaluateProgram.evaluate (bump z), + RootedPenaltyEvaluateProgram.evaluate z)) (g := fun x : ℕ×ℕ => decide (x.1=x.2)) + (pair (composition (f := bump) (g := RootedPenaltyEvaluateProgram.evaluate) + bumpRealizer RootedPenaltyEvaluateProgram.evaluateRealizer) + RootedPenaltyEvaluateProgram.evaluateRealizer) natEqual +lemma polynomial_equalExponents : PolynomialTime equalExponentsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_bump RootedPenaltyEvaluateProgram.polynomial_evaluate) + RootedPenaltyEvaluateProgram.polynomial_evaluate) polynomial_natEqual + +def ratio (z : Input) : TreeFraction.Fraction := if equalExponents z then (1,1) else (1,2) +def ratioRealizer : Realizer ratio := + choose equalExponentsRealizer (constant (1,1)) (constant (1,2)) +lemma polynomial_ratio : PolynomialTime ratioRealizer := + polynomial_choose polynomial_equalExponents (polynomial_constant _) (polynomial_constant _) + +abbrev SampleInput := RootedOracleWalkProgram.State×List Bool + +def currentInput (z : SampleInput) : Input := + (RootedOracleWalkProgram.toData (RootedOracleWalkProgram.flatWalk z)).2 +def currentInputRealizer : Realizer currentInput := + composition (f := RootedOracleWalkProgram.flatWalk) + (g := fun z : RootedOracleWalkProgram.State => (RootedOracleWalkProgram.toData z).2) + RootedOracleWalkProgram.flatWalkRealizer + (composition RootedOracleWalkProgram.toDataRealizer second) +lemma polynomial_currentInput : PolynomialTime currentInputRealizer := + polynomial_composition RootedOracleWalkProgram.polynomial_flatWalk + (polynomial_composition RootedOracleWalkProgram.polynomial_toData polynomial_second) + +def output (z : SampleInput) : TreeFraction.Fraction := ratio (currentInput z) +def outputRealizer : Realizer output := + composition (f := currentInput) (g := ratio) currentInputRealizer ratioRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_currentInput polynomial_ratio + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open CompanionOracleDensity RootedCompletion +open scoped BigOperators + +noncomputable section +variable {m n : ℕ} + +private lemma exponent_step (A : Instance (Fin m) (Fin n)) (C a : ℕ) + (hC : 0 < C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + RootedOracleDensity.gridExponent A (rowColumn A.T) C (a+1) z v= + RootedOracleDensity.gridExponent A (rowColumn A.T) C a z v ∨ + RootedOracleDensity.gridExponent A (rowColumn A.T) C (a+1) z v= + RootedOracleDensity.gridExponent A (rowColumn A.T) C a z v+1 := by + have hCR : (0:ℝ) < C := by exact_mod_cast hC + have hd := RootedOracleDensity.D_bounds A (rowColumn A.T) C hCR z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hi : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hi := (v i).property.2; omega) + exact hi.trans hKB) + let x := (a:ℝ)/height A C*RootedOracleDensity.D A (rowColumn A.T) C z (realCorner v) + let q := RootedOracleDensity.D A (rowColumn A.T) C z (realCorner v)/height A C + have hheight := height_positive A C hCR + have hq0 : 0 ≤ q := div_nonneg hd.1 hheight.le + have hq1 : q ≤ 1 := (div_le_one hheight).mpr hd.2 + have he : (((a+1:ℕ):ℝ)/height A C)*RootedOracleDensity.D A (rowColumn A.T) C z (realCorner v)=x+q := by + dsimp only [x,q] + push_cast + ring + have hlo := Int.floor_mono (show x ≤ x+q by linarith) + have hhi := Int.floor_mono (show x+q ≤ x+1 by linarith) + rw [Int.floor_add_one] at hhi + have hs : ⌊x+q⌋=⌊x⌋ ∨ ⌊x+q⌋=⌊x⌋+1 := by omega + have h0 := RootedOracleDensity.gridExponent_eq_floor A (rowColumn A.T) C a z v + have h1 := RootedOracleDensity.gridExponent_eq_floor A (rowColumn A.T) C (a+1) z v + rw [he] at h1 + rcases hs with hs|hs + · left + exact_mod_cast h1.trans (hs.trans h0.symm) + · right + have hh : (RootedOracleDensity.gridExponent A (rowColumn A.T) C (a+1) z v:ℤ)= + (RootedOracleDensity.gridExponent A (rowColumn A.T) C a z v:ℤ)+1 := by + rw [h1,hs,h0] + exact_mod_cast hh + +lemma ratio_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + TreeFraction.val (ratio (RootedOracleStepProgram.data A C a K z v).2)= + RootedOracleDensity.rationalRatioObservable A (rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K v) := by + have hb : bump (RootedOracleStepProgram.data A C a K z v).2= + (RootedOracleStepProgram.data A C (a+1) K z v).2 := rfl + unfold ratio equalExponents + rw [hb,RootedOracleStepProgram.evaluate_data A C (a+1) K hC, + RootedOracleStepProgram.evaluate_data A C a K hC] + rcases exponent_step A C a hC z hz hKB (RootedCatalogGrid.gridEquiv A K v) with he|he + · simp only [RootedCatalogGrid.exponent,he,decide_true,ite_true,TreeFraction.val, + Nat.cast_one,div_self (by norm_num : (1:ℚ)≠0), + RootedOracleDensity.rationalRatioObservable,RootedOracleDensity.rationalGridWeight] + exact (div_self (by positivity)).symm + · have hn : RootedOracleDensity.gridExponent A (rowColumn A.T) C (a+1) z + (RootedCatalogGrid.gridEquiv A K v)≠RootedOracleDensity.gridExponent A (rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K v) := by omega + simp only [RootedCatalogGrid.exponent,hn,decide_false,Bool.false_eq_true,ite_false] + simp only [TreeFraction.val,Nat.cast_one,Nat.cast_ofNat,RootedOracleDensity.rationalRatioObservable, + RootedOracleDensity.rationalGridWeight,he,pow_succ] + field_simp + +theorem output_data (A : Instance (Fin m) (Fin n)) (C a K : ℕ) + (hC : 0 < C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (N : ℕ) + (bits : Fin (N*oracleStepBits A C) → Bool) : + TreeFraction.val (output (RootedOracleWalkProgram.data A C a K z v,List.ofFn bits))= + RootedOracleDensity.rationalRatioObservable A (rowColumn A.T) C a z + (RootedCatalogGrid.gridEquiv A K (RootedOracleWalkProgram.flatGridWalk A C a z v N bits)) := by + unfold output currentInput + rw [RootedOracleWalkProgram.flatWalk_data A C a K hC z v N bits] + exact ratio_data A C a K hC z hz hKB _ + +end +end ContingencyTables.RootedRatioSampleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSamples.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSamples.lean new file mode 100644 index 0000000000000000000000000000000000000000..bcf73006cbf234c4be803d04b4c80bdbd4624ff5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRatioSamples.lean @@ -0,0 +1,192 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFiniteStep +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRatioSamples +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +import OAI.Combinatorics.ContingencyTables.Transport.FiniteBiasedAverages + +namespace OAI + +/-! # Concrete rational observations of the companion annealing ratios -/ + +namespace ContingencyTables.RootedOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open FiniteLawMoments FiniteIndependentAverages +open CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma floor_step (x q : ℝ) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) : + ⌊x+q⌋=⌊x⌋ ∨ ⌊x+q⌋=⌊x⌋+1 := by + have hlo := Int.floor_mono (show x ≤ x+q by linarith) + have hhi := Int.floor_mono (show x+q ≤ x+1 by linarith) + rw [Int.floor_add_one] at hhi + omega + +/-- The actual phase observable takes exactly the two source values, +since one annealing step changes its integer exponent by zero or one. -/ +theorem ratioObservable_cases (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℝ) (hC : 0 < C) + (a : ℕ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + ratioObservable A R C a z v=1 ∨ ratioObservable A R C a z v=1/2 := by + have hD := D_bounds A R C hC z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + let q := D A R C z (realCorner v)/height A C + have hq0 : 0 ≤ q := div_nonneg hD.1 (height_positive A C hC).le + have hq1 : q ≤ 1 := (div_le_one (height_positive A C hC)).mpr hD.2 + let x := (a:ℝ)/height A C*D A R C z (realCorner v) + have he : ((a:ℝ)+1)/height A C*D A R C z (realCorner v)=x+q := by + dsimp only [x,q] + ring + have hr : ratioObservable A R C a z v=(2:ℝ)^(-((⌊x+q⌋:ℤ):ℝ)+((⌊x⌋:ℤ):ℝ)) := by + unfold ratioObservable gridWeight V DenseWeights.binWeight + rw [he,←Real.rpow_sub (by norm_num : (0:ℝ)<2)] + congr 1 + change -((⌊x+q⌋:ℤ):ℝ)- -((⌊x⌋:ℤ):ℝ)=_ + ring + rcases floor_step x q hq0 hq1 with hf|hf + · left + rw [hr,hf] + simp + · right + rw [hr,hf] + have hh : -(((⌊x⌋:ℤ)+1:ℤ):ℝ)+((⌊x⌋:ℤ):ℝ)=(-1:ℝ) := by + push_cast + ring + rw [hh] + norm_num + +def rationalRatioObservable (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℚ := + rationalGridWeight A R C (a+1) z v/rationalGridWeight A R C a z v + +lemma rationalRatioObservable_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (rationalRatioObservable A R C a z v:ℝ)=ratioObservable A R C a z v := by + simp only [rationalRatioObservable,Rat.cast_div,rationalGridWeight_cast,Nat.cast_add, + Nat.cast_one,ratioObservable] + +lemma ratioObservable_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℝ) (hC : 0 < C) + (a : ℕ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + 1/2 ≤ ratioObservable A R C a z v ∧ ratioObservable A R C a z v ≤ 1 := by + rcases ratioObservable_cases A R C hC a z hz hKB v with h|h <;> rw [h] <;> norm_num + +lemma ratioMean_stationary (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : + expectation (oracleStationaryLaw A R C a z hK) (ratioObservable A R C a z)=ratioMean A R C a z K := by + unfold expectation ratioMean + apply Finset.sum_congr rfl + intro v _ + rw [oracleStationaryLaw_cast,oracleChain_pi] + rfl + +lemma ratioMean_bounds (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (hC : 0 < C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) : + 1/2 ≤ ratioMean A R C a z K ∧ ratioMean A R C a z K ≤ 1 := by + rw [←ratioMean_stationary A R C a z hK] + exact expectation_bounds _ _ _ _ (ratioObservable_bounds A R C (by exact_mod_cast hC) a z hz hKB) + +def ratioSample (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) (bits : RatioWords A C n) : ℚ := + rationalRatioObservable A R C a z (wordWalk (oracleBitStep A R C a z) v n bits) + +lemma ratioSample_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) (bits : RatioWords A C n) : + (ratioSample A R C a z v n bits:ℝ)= + ratioObservable A R C a z (wordWalk (oracleBitStep A R C a z) v n bits) := + rationalRatioObservable_cast A R C a z _ + +lemma ratioSample_mean (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + uniformAverage (fun bits : RatioWords A C n => (ratioSample A R C a z v n bits:ℝ))= + expectation (oracleBitWalkLaw A R C a z v n) (ratioObservable A R C a z) := by + simp_rw [ratioSample_cast] + exact word_expectation (wordWalk (oracleBitStep A R C a z) v n) _ + +/-- The actual finite walk has small expectation bias for the literal +ratio of consecutive normalizers. -/ +theorem ratioSample_mean_bias (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + |uniformAverage (fun bits : RatioWords A C (oracleTime A C K Q theta) => + (ratioSample A R C a z v (oracleTime A C K Q theta) bits:ℝ))-ratioMean A R C a z K| ≤ + theta/(4*Q) := by + rw [ratioSample_mean,←ratioMean_stationary A R C a z hK] + have hb := expectation_difference + (oracleBitWalkLaw A R C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A R C a z hK) (ratioObservable A R C a z) 1 (fun w => by + have hw := ratioObservable_bounds A R C (by exact_mod_cast hC) a z hz hKB w + rw [abs_of_nonneg (by linarith : 0 ≤ ratioObservable A R C a z w)] + exact hw.2) + have hm := oracleBitWalkLaw_variation A R C a theta hC haH htheta z hz K Q hK hQ + hKB hPL hCheeger v + apply hb.trans + calc + _ ≤ 2*1*(theta/(8*Q)) := mul_le_mul_of_nonneg_left hm (by norm_num) + _ = _ := by + have hQR : (Q:ℝ)≠0 := by exact_mod_cast hQ.ne' + field_simp [hQR] + ring + +/-- Independent Boolean arrays give an explicit confidence bound around +its exact annealing ratio, including the finite-walk mean bias. -/ +theorem ratioSamples_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q N : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hN : 0 < N) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin N → RatioWords A C (oracleTime A C K Q theta) => + if theta*ratioMean A R C a z K < + |sampleAverage (fun bits => (ratioSample A R C a z v (oracleTime A C K Q theta) bits:ℝ)) + N draws-ratioMean A R C a z K| then (1:ℝ) else 0) ≤ 16/(N*theta^2) := by + let g := fun bits : RatioWords A C (oracleTime A C K Q theta) => + (ratioSample A R C a z v (oracleTime A C K Q theta) bits:ℝ) + have hg (bits : RatioWords A C (oracleTime A C K Q theta)) : 0 ≤ g bits ∧ g bits ≤ 1 := by + dsimp only [g] + rw [ratioSample_cast] + have hh := ratioObservable_bounds A R C (by exact_mod_cast hC) a z hz hKB + (wordWalk (oracleBitStep A R C a z) v (oracleTime A C K Q theta) bits) + exact ⟨by linarith,hh.2⟩ + have hr := ratioMean_bounds A R C a hC z hz hK hKB + have hQR : (1:ℝ) ≤ Q := by exact_mod_cast (show 1 ≤ Q by omega) + have hb : |uniformAverage g-ratioMean A R C a z K| ≤ theta*ratioMean A R C a z K/2 := by + have hb := ratioSample_mean_bias A R C a theta hC haH htheta z hz K Q hK hQ hKB hPL hCheeger v + have h1 : theta/(4*(Q:ℝ)) ≤ theta/4 := by + apply div_le_div_of_nonneg_left htheta.le (by norm_num) + nlinarith + exact hb.trans (h1.trans (by nlinarith [hr.1])) + have hh := biased_target_failure g 1 (ratioMean A R C a z K) theta hg + (by linarith [hr.1]) htheta hb N hN + apply hh.trans + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hs : (theta/2)^2 ≤ (theta*ratioMean A R C a z K)^2 := by + apply (sq_le_sq₀ (by positivity) (mul_nonneg htheta.le (by linarith [hr.1]))).mpr + nlinarith [hr.1] + calc + 4*1^2/((N:ℝ)*(theta*ratioMean A R C a z K)^2) ≤ 4/(N*(theta/2)^2) := + div_le_div₀ (by norm_num) (by norm_num) (by positivity) (mul_le_mul_of_nonneg_left hs hNR.le) + _ = _ := by field_simp [hNR.ne',htheta.ne']; ring + +end + +end ContingencyTables.RootedOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReferenceAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReferenceAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..e14112117a84e82cc3020004bd2c9a018badf3b9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReferenceAccuracy.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseComposition +import OAI.Combinatorics.ContingencyTables.Counting.CompanionReferenceAccuracy + +namespace OAI + +/-! # Selected-root phase estimates have the required relative accuracy -/ + +namespace ContingencyTables.RootedReferenceAccuracy + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication RootedPhaseComposition RootedWarmStart +open CompanionReferenceAccuracy (tolerance relative_of_log_error) + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem accurate_phases_relative (A : Instance I J) (R : RootedCompletion.Selection A.T) + (samples : ℕ → List (Set (Labels A×Bool))) (epsilon : ℝ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) (H : ℕ) + (hall : ∀ j < H, Accurate A R samples (tolerance epsilon H) j) : + (1-epsilon/4)*total A R H ≤ estimate A R samples H ∧ + estimate A R samples H ≤ (1+epsilon/4)*total A R H := by + have hden : (0:ℝ) < 200*((H:ℝ)+1) := by positivity + have heta : 0 ≤ tolerance epsilon H := by unfold tolerance; positivity + have heta1 : tolerance epsilon H ≤ 1/4 := by + unfold tolerance + rw [div_le_iff₀ hden] + nlinarith [show (0:ℝ) ≤ H by positivity] + have hh := estimate_log_error A R samples (tolerance epsilon H) heta heta1 H hall + have hC := total_positive A R H + have herror : 4*(H:ℝ)*tolerance epsilon H ≤ epsilon/50 := by + unfold tolerance + rw [← mul_div_assoc,div_le_div_iff₀ hden (by norm_num : (0:ℝ) < 50)] + nlinarith [show (0:ℝ) ≤ H by positivity] + have hr := relative_of_log_error epsilon (estimate A R samples H/total A R H) he0 he1 + (div_pos hh.1 hC) (hh.2.trans herror) + constructor + · exact (le_div_iff₀ hC).mp hr.1 + · exact (div_le_iff₀ hC).mp hr.2 + +/-- Once the separately proved terminal contamination estimate is +available, the successful actual phase history estimates the table count. -/ +theorem reference_accuracy (A : Instance I J) (R : RootedCompletion.Selection A.T) + (samples : ℕ → List (Set (Labels A×Bool))) (epsilon Z : ℝ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) (hZ : 0 ≤ Z) (H : ℕ) + (hall : ∀ j < H, Accurate A R samples (tolerance epsilon H) j) + (hterminal : Z ≤ total A R H ∧ total A R H ≤ (1+epsilon/32)*Z) : + (1-epsilon)*Z ≤ estimate A R samples H ∧ estimate A R samples H ≤ (1+epsilon)*Z := by + apply final_estimate_accuracy epsilon Z (total A R H) (estimate A R samples H) he0 he1 hZ + · refine ⟨hterminal.1, hterminal.2.trans ?_⟩ + nlinarith [mul_nonneg he0.le hZ] + · exact accurate_phases_relative A R samples epsilon he0 he1 H hall + +end ContingencyTables.RootedReferenceAccuracy + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartAgreement.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartAgreement.lean new file mode 100644 index 0000000000000000000000000000000000000000..eab49434ab146f84bcd9d08571fe8e1df4e40c54 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartAgreement.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierAgreement +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartWords +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseExperiment + +namespace OAI + +/-! # Restart histories depend only on stored canonical pair entries -/ +namespace ContingencyTables.FirstSuccess +open scoped Classical +noncomputable section + +theorem varyingWalk_congr_prefix {X : Type*} [Fintype X] [DecidableEq X] + (width : ℕ → ℕ) + (f g : (i : ℕ) → X → (Fin (width i) → Bool) → X) + (x : X) (n : ℕ) (h : ∀ i,i < n → f i=g i) + (bits : VaryingWords width n) : + varyingWalk width f x n bits=varyingWalk width g x n bits := by + induction n with + | zero => rfl + | succ n ih => + simp only [varyingWalk] + rw [ih (fun i hi => h i (by omega)) (Fin.init bits),h n (by omega)] + +end +end ContingencyTables.FirstSuccess + +namespace ContingencyTables.CompanionMultiplierAgreement +open CompanionFactorialApplication CompanionRationalUpdates CompanionOracleDensity +open CompanionBooleanPhase (State stepBits) +open TwoLiftStates GridBoundary +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem observedStates_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k N : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedPhaseExperiment.observedStates A R C K j k N hK hW xi v w= + RootedPhaseExperiment.observedStates A R C K j k N hK hW xi v w' := by + funext S bits i + unfold RootedPhaseExperiment.observedStates + rw [recordedWalk_eq A R C K j k N N hK hW xi v w w' hw] + +end +end ContingencyTables.CompanionMultiplierAgreement + +namespace ContingencyTables.RootedRestartWords +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity CompanionWeightOracle TwoLiftStates GridBoundary FirstSuccess +open scoped BigOperators Classical +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem stages_agree (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k cap j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (w w' : ℕ → Pair A → Pair A → ℚ) + (hw : ∀ i,i < j → CompanionMultiplierAgreement.Agree A (w (i+1)) (w' (i+1))) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin (∑ i : Fin j,stageWidth A C K H L k cap xi i.val) → Bool) : + stages A R C K H L k cap j hK hW xi v w S bits= + stages A R C K H L k cap j hK hW xi v w' S bits := by + unfold stages + apply varyingWalk_congr_prefix + intro i hi + exact CompanionMultiplierAgreement.returns_eq A R C K (i+1) k cap + (CompanionTargetMixing.restartTime A H L) hK hW xi v (w (i+1)) (w' (i+1)) (hw i hi) + +theorem initializedStages_agree (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k cap h j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (w w' : ℕ → Pair A → Pair A → ℚ) + (hw : ∀ i,i < j → CompanionMultiplierAgreement.Agree A (w (i+1)) (w' (i+1))) + (bits : Fin (initialStageBits A C K H L k cap h j xi) → Bool) : + initializedStages A R C K H L k cap h j hK hW xi v w bits= + initializedStages A R C K H L k cap h j hK hW xi v w' bits := by + unfold initializedStages + exact stages_agree A R C K H L k cap j hK hW xi v w w' hw _ _ + +end +end ContingencyTables.RootedRestartWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartPrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..3298ee5945e9d54778974ed275e1f75d5ddbd1ee --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartPrefix.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartStages + +namespace OAI + +/-! # Restart accuracy from only the learned multiplier prefix + +The horizon controls the fixed mixing schedule. Goodness is required only +at the parameters which the actual restart has visited. +-/ + +namespace ContingencyTables.RootedRestartPrefix + +open CommonBasesFPRAS RealKernelApproximation CompanionFactorialApplication +open CompanionRationalUpdates RootedAnnealing RootedWarmStart RootedTargetTrace +open RootedTargetMixing RootedWarmReturn RootedReturnIteration RootedRestartStages +open CompanionTargetMixing (restartTime) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +private lemma accumulate (j : ℕ) (r s u e : ℝ) + (hr : r ≤ s+e) (hs : s ≤ u+(j:ℝ)*e) : + r ≤ u+((j+1:ℕ):ℝ)*e := by + push_cast + linarith + +theorem reference_two_warm_at (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (j : ℕ) (hj : j ≤ H) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (w j p q:ℝ))) + (S : PlainIndex (pairs : List (Pair A))) : + reference A R H L hp w hw j S ≤ 2*law A R j S.val.val := by + cases j with + | zero => + change law A R 0 S.val.val ≤ 2*law A R 0 S.val.val + have h := div_pos (weight_positive A R 0 S.val.val) (total_positive A R 0) + change 0 < law A R 0 S.val.val at h + linarith + | succ j => + exact restart_warm A R H L (j+1) hj hbox hp (w (j+1)) (hw (j+1)) + hgood (reference A R H L hp w hw j) + (reference_nonnegative A R H L hp w hw j) + (reference_mass A R H L hp w hw j).le S + +theorem reference_next_four_warm_at (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (j : ℕ) (hj : j ≤ H) + (hgood : GoodMultipliers pairs (weight A R j) (fun p q => (w j p q:ℝ))) + (S : PlainIndex (pairs : List (Pair A))) : + reference A R H L hp w hw j S ≤ 4*law A R (j+1) S.val.val := by + have h := reference_two_warm_at A R H L hbox hp w hw j hj hgood S + have ha := law_adjacent A R j S.val.val + linarith + +theorem implemented_distance_prefix (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K H L k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (hH : H ≤ CompanionOracleDensity.rationalHeight A C) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (CompanionOracleDensity.dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger + (Grid (I := Fin (CompanionOracleDensity.dimension A)) K)) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (hn : 0 < n) + (initial : PlainIndex (pairs : List (Pair A)) → ℝ) (j : ℕ) (hj : j ≤ H) + (hgood : ∀ i,i ≤ j → GoodMultipliers pairs (weight A R i) + (fun p q => (w i p q:ℝ))) : + distance (implemented A R C K H L k n hK hW xi v w initial j) + (reference A R H L hp w hw j) ≤ + distance initial (fun S => law A R 0 S.val.val)+ + (j:ℝ)*((restartTime A H L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))) := by + revert hj hgood + induction j with + | zero => + intro _ _ + simp only [implemented,reference,Nat.cast_zero,zero_mul,add_zero] + exact le_rfl + | succ j ih => + intro hj hgood + have hj0 : j ≤ H := by omega + have hs := repeated_return_distance A R C hC K (j+1) k n hK hW hB + (hj.trans hH) xi hx0 hx1 hPL hCheeger v hp (w (j+1)) (hw (j+1)) + (hgood (j+1) le_rfl) hn (reference A R H L hp w hw j) + (reference_nonnegative A R H L hp w hw j) + (reference_mass A R H L hp w hw j).le 4 (by norm_num) + (reference_next_four_warm_at A R H L hbox hp w hw j hj0 (hgood j (Nat.le_succ j))) + (restartTime A H L) + have hc := distance_push + ((returnKernel A R C K (j+1) k n hK hW xi v (w (j+1))).power (restartTime A H L)) + (implemented A R C K H L k n hK hW xi v w initial j) + (reference A R H L hp w hw j) + have ht := distance_triangle + (implemented A R C K H L k n hK hW xi v w initial (j+1)) + (((returnKernel A R C K (j+1) k n hK hW xi v (w (j+1))).power + (restartTime A H L)).push (reference A R H L hp w hw j)) + (reference A R H L hp w hw (j+1)) + have hprev := ih hj0 (fun i hi => hgood i (hi.trans (Nat.le_succ j))) + rw [show 5*(Fintype.card (Labels A):ℝ)^2*4= + 20*(Fintype.card (Labels A):ℝ)^2 by ring] at hs + have hsum := _root_.add_le_add hc hs + have hstep := ht.trans hsum + exact accumulate j _ _ _ _ hstep hprev + + +end +end ContingencyTables.RootedRestartPrefix + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartStages.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartStages.lean new file mode 100644 index 0000000000000000000000000000000000000000..8870d0760acdad0fb26b1ddaa098fdfe2e718524 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartStages.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnWords + +namespace OAI + +/-! # Successive selected-root restart stages + +The reference law is refreshed by the exact trace at each successive +parameter. Only that reference law is asserted to be warm. The actual +bounded-return law is compared to it by contraction and accumulated error. +-/ + +namespace ContingencyTables.RootedRestartStages + +open CommonBasesFPRAS RealKernelApproximation CompanionFactorialApplication +open CompanionRationalUpdates RootedAnnealing RootedWarmStart RootedTargetTrace +open RootedTargetMixing RootedWarmReturn RootedReturnIteration +open CompanionTargetMixing (restartTime) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma accumulate (j : ℕ) (r s u e : ℝ) + (hr : r ≤ s+e) (hs : s ≤ u+(j:ℝ)*e) : + r ≤ u+((j+1:ℕ):ℝ)*e := by + push_cast + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +def reference (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) : + ℕ → PlainIndex (pairs : List (Pair A)) → ℝ + | 0 => fun S => law A R 0 S.val.val + | j+1 => ((actualTrace A R (j+1) hp (w (j+1)) (hw (j+1))).kernel.power + (restartTime A H L)).push (reference A R H L hp w hw j) + +lemma reference_nonnegative (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) (j : ℕ) : + ∀ S,0 ≤ reference A R H L hp w hw j S := by + induction j with + | zero => + intro S + exact (div_pos (weight_positive A R 0 _) (total_positive A R 0)).le + | succ j ih => + exact ((actualTrace A R (j+1) hp (w (j+1)) (hw (j+1))).kernel.power + (restartTime A H L)).push_nonneg _ ih + +lemma reference_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) (j : ℕ) : + ∑ S,reference A R H L hp w hw j S=1 := by + induction j with + | zero => + exact (by simpa only [reference,actualTrace_pi] using + (actualTrace A R 0 hp (w 0) (hw 0)).normalized) + | succ j ih => + change ∑ S,((actualTrace A R (j+1) hp (w (j+1)) (hw (j+1))).kernel.power + (restartTime A H L)).push (reference A R H L hp w hw j) S=1 + rw [FiniteChain.power_push_mass] + exact ih + +theorem reference_two_warm (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (hgood : ∀ j,j ≤ H → GoodMultipliers pairs (weight A R j) + (fun p q => (w j p q:ℝ))) (j : ℕ) (hj : j ≤ H) + (S : PlainIndex (pairs : List (Pair A))) : + reference A R H L hp w hw j S ≤ 2*law A R j S.val.val := by + cases j with + | zero => + change law A R 0 S.val.val ≤ 2*law A R 0 S.val.val + have h := div_pos (weight_positive A R 0 S.val.val) (total_positive A R 0) + change 0 < law A R 0 S.val.val at h + linarith + | succ j => + exact restart_warm A R H L (j+1) hj hbox hp (w (j+1)) (hw (j+1)) + (hgood (j+1) hj) (reference A R H L hp w hw j) + (reference_nonnegative A R H L hp w hw j) + (reference_mass A R H L hp w hw j).le S + +theorem reference_next_four_warm (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L : ℕ) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (hgood : ∀ j,j ≤ H → GoodMultipliers pairs (weight A R j) + (fun p q => (w j p q:ℝ))) (j : ℕ) (hj : j ≤ H) + (S : PlainIndex (pairs : List (Pair A))) : + reference A R H L hp w hw j S ≤ 4*law A R (j+1) S.val.val := by + have h := reference_two_warm A R H L hbox hp w hw hgood j hj S + have ha := law_adjacent A R j S.val.val + linarith + +def implemented (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (w : ℕ → Pair A → Pair A → ℚ) + (initial : PlainIndex (pairs : List (Pair A)) → ℝ) : + ℕ → PlainIndex (pairs : List (Pair A)) → ℝ + | 0 => initial + | j+1 => ((returnKernel A R C K (j+1) k n hK hW xi v (w (j+1))).power + (restartTime A H L)).push (implemented A R C K H L k n hK hW xi v w initial j) + +/-- Every new stage starts from a four-warm exact reference. Errors of +the actual bounded-word implementation add, without conditioning on a +successful return or requiring its incoming distribution to be warm. -/ +theorem implemented_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K H L k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (hH : H ≤ CompanionOracleDensity.rationalHeight A C) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (CompanionOracleDensity.dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger + (Grid (I := Fin (CompanionOracleDensity.dimension A)) K)) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ j p q,0 < w j p q) + (hgood : ∀ j,j ≤ H → GoodMultipliers pairs (weight A R j) + (fun p q => (w j p q:ℝ))) (hn : 0 < n) + (initial : PlainIndex (pairs : List (Pair A)) → ℝ) (j : ℕ) (hj : j ≤ H) : + distance (implemented A R C K H L k n hK hW xi v w initial j) + (reference A R H L hp w hw j) ≤ + distance initial (fun S => law A R 0 S.val.val)+ + (j:ℝ)*((restartTime A H L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))) := by + revert hj + induction j with + | zero => + intro _ + simp only [implemented,reference,Nat.cast_zero,zero_mul,add_zero] + exact le_rfl + | succ j ih => + intro hj + have hj0 : j ≤ H := by omega + have hs := repeated_return_distance A R C hC K (j+1) k n hK hW hB + (hj.trans hH) xi hx0 hx1 hPL hCheeger v hp (w (j+1)) (hw (j+1)) + (hgood (j+1) hj) hn (reference A R H L hp w hw j) + (reference_nonnegative A R H L hp w hw j) + (reference_mass A R H L hp w hw j).le 4 (by norm_num) + (reference_next_four_warm A R H L hbox hp w hw hgood j hj0) + (restartTime A H L) + have hc := distance_push + ((returnKernel A R C K (j+1) k n hK hW xi v (w (j+1))).power (restartTime A H L)) + (implemented A R C K H L k n hK hW xi v w initial j) + (reference A R H L hp w hw j) + have ht := distance_triangle + (implemented A R C K H L k n hK hW xi v w initial (j+1)) + (((returnKernel A R C K (j+1) k n hK hW xi v (w (j+1))).power + (restartTime A H L)).push (reference A R H L hp w hw j)) + (reference A R H L hp w hw (j+1)) + have hprev := ih hj0 + rw [show 5*(Fintype.card (Labels A):ℝ)^2*4= + 20*(Fintype.card (Labels A):ℝ)^2 by ring] at hs + have hsum := _root_.add_le_add hc hs + have hstep := ht.trans hsum + exact accumulate j _ _ _ _ hstep hprev + +end +end ContingencyTables.RootedRestartStages + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..83343291cd276387c893ea9a7ac07210fca0e6b0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartTrial.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPlainTrial +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartWords +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # An actual initialized restart followed by the finite phase update -/ + +namespace ContingencyTables.RootedRestartTrial + +open CommonBasesFPRAS FirstSuccess ResidualMixture RealKernelApproximation +open CompanionFactorialApplication CompanionRationalUpdates CompanionOracleDensity +open RootedAnnealing RootedWarmStart RootedPhaseTrial RootedRestartWords +open RootedRestartStages RootedRestartPrefix +open CompanionPhaseWords (Stored) +open CompanionTraceWords (eventIndicator) +open CompanionTargetMixing (restartTime) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma replace_distance (r B d D e : ℝ) (hr : r ≤ B+2*d+e) (hd : d ≤ D) : + r ≤ B+2*D+e := by linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +abbrev Words (A : Instance I J) (C K H L j k n N h : ℕ) (xi : ℚ) := + (Fin (initialStageBits A C K H L k n h j xi) → Bool) × TrialWords A C K j k N xi + +def run (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L j k n N h : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (estimate : ℚ) (bits : Words A C K H L j k n N h xi) : Option (Stored A) := + trial A R C K j k N hK hW xi v ⟨w j,estimate⟩ + (initializedStages A R C K H L k n h j hK hW xi v w bits.1).val bits.2 + +/-- All source conditions concern the learned prefix. The words +for initialization, successive restarts, observations and weight calls +are independent, and all are part of this single finite experiment. -/ +theorem failure (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K H L j k n N h : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hH : H ≤ rationalHeight A C) (hj : j < H) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ i p q,0 < w i p q) + (hgood : ∀ i,i ≤ j → GoodMultipliers pairs (weight A R i) + (fun p q => (w i p q:ℝ))) (hn : 0 < n) + (estimate : ℚ) (hE : 0 < estimate) (eta : ℝ) (he0 : 0 < eta) (he1 : eta ≤ 1/4) : + uniformAverage (fun bits : Words A C K H L j k n N h xi => + eventIndicator (¬∃ next,run A R C K H L j k n N h hK hW xi v w estimate bits=some next ∧ + ValidOutput A R j ⟨w j,estimate⟩ xi eta next)) ≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/ + (((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)+ + 2*(1/(2:ℝ)^h+(j:ℝ)*((restartTime A H L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))))+ + 2*((N+1:ℕ):ℝ)*(xi:ℝ) := by + let draw := initializedStages A R C K H L k n h j hK hW xi v w + let p := mapLaw (uniformLaw (α := Fin (initialStageBits A C K H L k n h j xi) → Bool)) draw + let q := reference A R H L hp w hw j + let g (S : PlainIndex (pairs : List (Pair A))) : ℝ := + uniformAverage (fun bits : TrialWords A C K j k N xi => + eventIndicator (¬∃ next,trial A R C K j k N hK hW xi v ⟨w j,estimate⟩ S.val bits=some next ∧ + ValidOutput A R j ⟨w j,estimate⟩ xi eta next)) + have he : uniformAverage (fun bits : Words A C K H L j k n N h xi => + eventIndicator (¬∃ next,run A R C K H L j k n N h hK hW xi v w estimate bits=some next ∧ + ValidOutput A R j ⟨w j,estimate⟩ xi eta next))=∑ S,(p.mass S:ℝ)*g S := by + rw [uniformAverage_prod] + exact FiniteLawMoments.word_expectation draw g + have hpast := RootedPlainTrial.trial_failure A R C hC K j k N hK hW hB + ((Nat.succ_le_of_lt hj).trans hH) xi hx0 hx1 hPL hCheeger v hp + ⟨w j,estimate⟩ (hw j) hE (hgood j le_rfl) p q + (reference_nonnegative A R H L hp w hw j) + (reference_mass A R H L hp w hw j).le + (reference_two_warm_at A R H L hbox hp w hw j hj.le (hgood j le_rfl)) eta he0 he1 + have hd := initializedStages_distance A R C hC K H L k n h j hK hW hB hH hbox + xi hx0 hx1 hPL hCheeger v hp w hw hgood hn hj.le + rw [he] + exact replace_distance _ _ _ _ _ hpast hd + +end +end ContingencyTables.RootedRestartTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..938ee8f2e5b0a0bd798bbfd4087c41354a17fc62 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRestartWords.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartPrefix +import OAI.Combinatorics.ContingencyTables.Machines.FiniteVaryingWordWalk + +namespace OAI + +/-! # Actual finite Boolean words for all successive restart stages -/ + +namespace ContingencyTables.RootedRestartWords + +open CommonBasesFPRAS ResidualMixture FirstSuccess FairBits RealKernelApproximation +open CompanionFactorialApplication CompanionRationalUpdates CompanionOracleDensity +open CompanionTargetMixing (restartTime) +open CompanionReturnWords (returnBits) +open RootedReturnWords RootedWarmStart RootedRestartStages RootedRestartPrefix +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def stageWidth (A : Instance I J) (C K H L k n : ℕ) (xi : ℚ) (i : ℕ) : ℕ := + returnBits A C K (i+1) k n (restartTime A H L) xi + +def stageStep (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) (i : ℕ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin (stageWidth A C K H L k n xi i) → Bool) : + PlainIndex (pairs : List (Pair A)) := + booleanReturns A R C K (i+1) k n (restartTime A H L) hK hW xi v (w (i+1)) S bits + +def stages (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin (∑ i : Fin j,stageWidth A C K H L k n xi i.val) → Bool) : + PlainIndex (pairs : List (Pair A)) := + varyingWalk (stageWidth A C K H L k n xi) + (stageStep A R C K H L k n hK hW xi v w) S j + (varyingWordEquiv (stageWidth A C K H L k n xi) j bits) + +theorem stages_law (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + mapLaw (uniformLaw (α := Fin (∑ i : Fin j,stageWidth A C K H L k n xi i.val) → Bool)) + (stages A R C K H L k n j hK hW xi v w S)= + varyingLaw (stageWidth A C K H L k n xi) + (stageStep A R C K H L k n hK hW xi v w) (pointLaw S) j := + flatVaryingWalk_law _ _ S j + +private lemma stageStep_law (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (i : ℕ) (S : PlainIndex (pairs : List (Pair A))) : + mapLaw (uniformLaw (α := Fin (stageWidth A C K H L k n xi i) → Bool)) + (stageStep A R C K H L k n hK hW xi v w i S)= + booleanReturnsLaw A R C K (i+1) k n (restartTime A H L) hK hW xi v (w (i+1)) S := by + rfl + +theorem stageLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (p : RationalLaw (PlainIndex (pairs : List (Pair A)))) (j : ℕ) + (T : PlainIndex (pairs : List (Pair A))) : + ((varyingLaw (stageWidth A C K H L k n xi) + (stageStep A R C K H L k n hK hW xi v w) p j).mass T:ℝ)= + implemented A R C K H L k n hK hW xi v w (fun S => (p.mass S:ℝ)) j T := by + induction j generalizing T with + | zero => rfl + | succ j ih => + simp only [varyingLaw,stageStep_law,bindLaw,Rat.cast_sum,Rat.cast_mul, + ih,booleanReturnsLaw_cast,implemented,FiniteKernel.push] + +def initialStageBits (A : Instance I J) (C K H L k n h j : ℕ) (xi : ℚ) : ℕ := + CompanionInitialDraw.initialBits A (CompanionInitialDraw.precision A h)+ + ∑ i : Fin j,stageWidth A C K H L k n xi i.val + +def initializedStages (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n h j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) + (bits : Fin (initialStageBits A C K H L k n h j xi) → Bool) : + PlainIndex (pairs : List (Pair A)) := + let z := splitWordEquiv (CompanionInitialDraw.initialBits A (CompanionInitialDraw.precision A h)) + (∑ i : Fin j,stageWidth A C K H L k n xi i.val) bits + stages A R C K H L k n j hK hW xi v w + (CompanionInitialDraw.draw A (CompanionInitialDraw.precision A h) z.1) z.2 + +theorem initializedStages_law (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K H L k n h j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : ℕ → Pair A → Pair A → ℚ) : + mapLaw (uniformLaw (α := Fin (initialStageBits A C K H L k n h j xi) → Bool)) + (initializedStages A R C K H L k n h j hK hW xi v w)= + varyingLaw (stageWidth A C K H L k n xi) + (stageStep A R C K H L k n hK hW xi v w) + (mapLaw (uniformLaw (α := Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A h)) → Bool)) + (CompanionInitialDraw.draw A (CompanionInitialDraw.precision A h))) j := by + let r := CompanionInitialDraw.initialBits A (CompanionInitialDraw.precision A h) + let s := ∑ i : Fin j,stageWidth A C K H L k n xi i.val + let init := CompanionInitialDraw.draw A (CompanionInitialDraw.precision A h) + let run := stages A R C K H L k n j hK hW xi v w + change mapLaw (uniformLaw (α := Fin (r+s) → Bool)) + (fun bits => run (init (splitWordEquiv r s bits).1) (splitWordEquiv r s bits).2)=_ + have he := map_equiv (splitWordEquiv r s) + (uniformLaw (α := Fin (r+s) → Bool)) (fun z => run (init z.1) z.2) + rw [uniform_equiv,←uniform_product] at he + refine he.symm.trans ?_ + rw [mapLaw_product_finish] + dsimp only [run] + have hf : (fun x => mapLaw (uniformLaw (α := Fin s → Bool)) + (stages A R C K H L k n j hK hW xi v w x))= + (fun x => varyingLaw (stageWidth A C K H L k n xi) + (stageStep A R C K H L k n hK hW xi v w) (pointLaw x) j) := by + funext x + exact stages_law A R C K H L k n j hK hW xi v w x + have heq := congrArg (fun F : PlainIndex (pairs : List (Pair A)) → + RationalLaw (PlainIndex (pairs : List (Pair A))) => + bindLaw (mapLaw (uniformLaw (α := Fin r → Bool)) init) F) hf + exact heq.trans (varyingLaw_start _ _ _ _) + +/-- The actual initialized finite word is close to the exact warm +restart reference; it includes every fresh stage and initializer word. -/ +theorem initializedStages_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C : ℕ) (hC : 0 < C) (K H L k n h j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hH : H ≤ rationalHeight A C) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^L) + (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (hp : 0 < Fintype.card (Labels A)) + (w : ℕ → Pair A → Pair A → ℚ) (hw : ∀ i p q,0 < w i p q) + (hgood : ∀ i,i ≤ j → GoodMultipliers pairs (RootedAnnealing.weight A R i) + (fun p q => (w i p q:ℝ))) (hn : 0 < n) (hj : j ≤ H) : + distance (fun T => ((mapLaw (uniformLaw + (α := Fin (initialStageBits A C K H L k n h j xi) → Bool)) + (initializedStages A R C K H L k n h j hK hW xi v w)).mass T:ℝ)) + (reference A R H L hp w hw j) ≤ 1/(2:ℝ)^h+ + (j:ℝ)*((restartTime A H L:ℝ)*((20*(Fintype.card (Labels A):ℝ)^2)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))) := by + rw [initializedStages_law] + simp_rw [stageLaw_cast] + let initial : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + ((mapLaw (uniformLaw (α := Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A h)) → Bool)) + (CompanionInitialDraw.draw A (CompanionInitialDraw.precision A h))).mass S:ℝ) + have h0 : distance initial (fun S => law A R 0 S.val.val) ≤ 1/(2:ℝ)^h := + initial_distance A R h + have hh := implemented_distance_prefix A R C hC K H L k n hK hW hB hH hbox xi hx0 hx1 + hPL hCheeger v hp w hw hn initial j hj hgood + have hadd := _root_.add_le_add h0 (le_refl ((j:ℝ)*((restartTime A H L:ℝ)* + ((20*(Fintype.card (Labels A):ℝ)^2)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))))) + have hb := hh.trans hadd + simpa only [initial] using hb + +end +end ContingencyTables.RootedRestartWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnHistoryLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnHistoryLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3a4073b56b8ba26fab9a1cc2b4126f3016553c7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnHistoryLaw.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRecordedHistory +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFlatReturnProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCappedReturn + +namespace OAI + +/-! # The executed return scan has the reference capped-return law -/ + +namespace ContingencyTables.RootedReturnHistoryLaw + +open MatchingFPRAS CommonBasesFPRAS FirstSuccess ResidualMixture FiniteObservableTransport +open RealKernelApproximation +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates CompanionCappedReturn CompanionPhaseTrajectory +open CompanionComputedInitial CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open TwoLiftStates GridBoundary +open scoped Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem trace_return_sameLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + SameLaw (fun words : Fin (n+1) → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + returnDefault (plainPredicate pairs) S (traceStates + (RootedBooleanPhase.step A R C K j k hK hW xi v w) S.val (List.ofFn words))) + (RootedCappedReturn.returnWordDefault A R C K j k n hK hW xi v w S) := by + let F := RootedBooleanPhase.step A R C K j k hK hW xi v w + let ret := fun a : PathState (CompanionBooleanPhase.State A) (n+1) => + returnDefault (plainPredicate pairs) S (historyPrefix a) + have hb := RootedBooleanPhase.recordedWalk_law A R C K j k (n+1) (n+1) hK hW xi v w S.val + have ha := RootedArithmeticStep.recordedWalk_law A R C K j k (n+1) (n+1) hK hW xi v w S.val + have hp := SameLaw.of_mapLaw_eq + (RootedBooleanPhase.recordedWalk A R C K j k (n+1) (n+1) hK hW xi v w S.val) + (RootedArithmeticStep.recordedWalk A R C K j k (n+1) (n+1) hK hW xi v w S.val) + (hb.trans ha.symm) + have hm := hp.map ret + have hprefix (bits : Fin ((n+1)*CompanionBooleanPhase.stepBits A C K j k xi) → Bool) : + historyPrefix (RootedBooleanPhase.recordedWalk A R C K j k (n+1) (n+1) hK hW xi v w S.val bits)= + traceStates F S.val (List.ofFn (gridWordEquiv (n+1) + (CompanionBooleanPhase.stepBits A C K j k xi) bits)) := + recorded_prefix F (n+1) S.val (n+1) le_rfl _ + intro phi + have he := uniformAverage_equiv (gridWordEquiv (n+1) (CompanionBooleanPhase.stepBits A C K j k xi)) + (fun words => phi (returnDefault (plainPredicate pairs) S (traceStates F S.val (List.ofFn words)))) + have ht : uniformAverage (fun bits => phi (ret + (RootedBooleanPhase.recordedWalk A R C K j k (n+1) (n+1) hK hW xi v w S.val bits)))= + uniformAverage (fun words : Fin (n+1) → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + phi (returnDefault (plainPredicate pairs) S (traceStates F S.val (List.ofFn words)))) := by + calc + _ = uniformAverage (fun bits => phi (returnDefault (plainPredicate pairs) S + (traceStates F S.val (List.ofFn (gridWordEquiv (n+1) + (CompanionBooleanPhase.stepBits A C K j k xi) bits))))) := by + apply congrArg uniformAverage + funext bits + exact congrArg (fun xs => phi (returnDefault (plainPredicate pairs) S xs)) (hprefix bits) + _ = _ := he + refine ht.symm.trans ((hm phi).trans ?_) + rfl + +variable {m n : ℕ} + +/-- The physical flat-return program can replace the literal reference +return in every subsequent restart or adaptive phase experiment. -/ +theorem flatReturn_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k cap : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (Pair A))) : + SameLaw (fun bits : Fin ((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + CompanionFlatReturnProgram.output (CompanionFlatReturnProgram.data A C K j k (cap+1) + xi z v degree depth w S.val (List.ofFn bits))) + (fun bits => CompanionArithmeticProposal.encodeSet (coordinateOrder A) + (RootedCappedReturn.returnWordDefault A (RootedCompletion.rowColumn A.T) C K j k cap + hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits).val.val) := by + have h₁ := CompanionFlatReturnProgram.output_sameLaw A C K j k (cap+1) hC hj hK hW hB xi hxi + z v degree depth hdegree hdepth w S + have h₂ := (trace_return_sameLaw A (RootedCompletion.rowColumn A.T) C K j k cap hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S).map + (fun T => CompanionArithmeticProposal.encodeSet (coordinateOrder A) T.val.val) + intro phi + exact (h₁ phi).trans (h₂ phi) + +end +end ContingencyTables.RootedReturnHistoryLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnIteration.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..31507b6308a557db33dd2805aeb5ef68017a89ac --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnIteration.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmReturn +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTargetMixing +import OAI.Combinatorics.ContingencyTables.Transport.WarmKernelIteration + +namespace OAI + +/-! # Repeated actual selected-root returns and their stationary error -/ + +namespace ContingencyTables.RootedReturnIteration + +open CommonBasesFPRAS RealKernelApproximation CompanionFactorialApplication +open RootedBooleanPhase CompanionOracleDensity CompanionRationalUpdates +open RootedWarmReturn RootedTargetTrace RootedTargetMixing +open RootedAnnealing RootedWarmStart TwoLiftStates GridBoundary +open CompanionBooleanPhase (State) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem reference_mixing_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (H L j : ℕ) (hj : j≤H) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^L) + (hp : 0 (w p q:ℝ))) + (nu : PlainIndex (pairs : List (Pair A)) → ℝ) (hnu : ∀ S,0≤nu S) + (hmass : ∑ S,nu S=1) (t : ℕ) : + distance (((RootedTargetTrace.actualTrace A R j hp w hw).kernel.power t).push nu) + (fun S => law A R j S.val.val)≤ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2 := by + let D := RootedTargetTrace.actualTrace A R j hp w hw + have hmix (x y : PlainIndex (pairs : List (Pair A))) : + |(D.kernel.power t).P x y/D.π y-1|≤ + Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L := by + rw [actualTrace_pi] + exact target_point_mixing A R H L j hj hbox hp w hw hgood t x y + have hm := WarmKernelIteration.mixing_distance D nu hnu hmass t _ hmix + have hpi : D.π=(fun S => law A R j S.val.val) := by + funext S + exact actualTrace_pi A R j hp w hw S + rw [hpi] at hm + exact hm + +theorem repeated_return_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 by simpa only [actualTrace_pi] using hrwarm S) + exact WarmKernelIteration.power_distance + (RootedTargetTrace.actualTrace A R j hp w hw) + (returnKernel A R C K j k n hK hW xi v w) nu hnu hmass U _ hwar hstep t + +/-- The terminal law after repeated actual Boolean returns. The first +term is the accumulated implementation error; the second is mixing of +the exact literal trace. -/ +theorem repeated_return_stationary (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 law A R j S.val.val)≤ + (t:ℝ)*((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))+ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2 := by + have hr := repeated_return_distance A R C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw hgood hn nu hnu hmass.le U hU hwarm t + have hm := reference_mixing_distance A R H L j hjH hbox hp w hw hgood nu hnu hmass t + have ht := distance_triangle + (((returnKernel A R C K j k n hK hW xi v w).power t).push nu) + (((RootedTargetTrace.actualTrace A R j hp w hw).kernel.power t).push nu) + (fun S => law A R j S.val.val) + exact ht.trans (_root_.add_le_add hr hm) + +end +end ContingencyTables.RootedReturnIteration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..f319ee481f2e29087e92205be5df15e82bad5a0b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedReturnWords.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnIteration +import OAI.Combinatorics.ContingencyTables.Counting.CompanionReturnWords +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk + +namespace OAI + +/-! # A fixed Boolean word for selected-root repeated capped returns + +The restart routine iterates the actual defaulted return experiment. +Every iteration receives a disjoint block, and an optional initial +finite-word draw receives its own disjoint block as well. +-/ + +namespace ContingencyTables.RootedReturnWords + +open CommonBasesFPRAS ResidualMixture FirstSuccess FairBits RealKernelApproximation +open CompanionFactorialApplication RootedBooleanPhase CompanionOracleDensity +open CompanionBooleanPhase (stepBits) +open CompanionReturnWords (returnBits) +open RootedCappedReturn RootedWarmReturn RootedReturnIteration +open CompanionRationalUpdates RootedAnnealing TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private theorem walkLaw_cast_power {X : Type*} [Fintype X] [DecidableEq X] + (Q : X → RationalLaw X) (x : X) (n : ℕ) (y : X) : + ((walkLaw Q x n).mass y:ℝ)=((rationalKernel Q).power n).P x y := by + induction n generalizing y with + | zero => + simp only [walkLaw,pointLaw,FiniteKernel.power,FiniteKernel.identity] + by_cases h : x=y + · subst y; simp + · simp [h,Ne.symm h] + | succ n ih => + change ((∑ z,(walkLaw Q x n).mass z*(Q z).mass y:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,ih, + FiniteKernel.power,FiniteKernel.comp,rationalKernel] + +variable {I J : Type} [Fintype I] [Fintype J] + +def booleanReturns (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin (returnBits A C K j k n t xi) → Bool) : + PlainIndex (pairs : List (Pair A)) := + wordWalk (returnWordDefault A R C K j k n hK hW xi v w) S t + (gridWordEquiv t ((n+1)*stepBits A C K j k xi) bits) + +def booleanReturnsLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin (returnBits A C K j k n t xi) → Bool)) + (booleanReturns A R C K j k n t hK hW xi v w S) + +theorem booleanReturnsLaw_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + booleanReturnsLaw A R C K j k n t hK hW xi v w S= + walkLaw (returnLaw A R C K j k n hK hW xi v w) S t := by + let step := returnWordDefault A R C K j k n hK hW xi v w + change mapLaw (uniformLaw (α := Fin (t*((n+1)*stepBits A C K j k xi)) → Bool)) + (fun bits => wordWalk step S t + (gridWordEquiv t ((n+1)*stepBits A C K j k xi) bits))=_ + have he := map_equiv (gridWordEquiv t ((n+1)*stepBits A C K j k xi)) + (uniformLaw (α := Fin (t*((n+1)*stepBits A C K j k xi)) → Bool)) + (wordWalk step S t) + rw [uniform_equiv] at he + exact he.symm.trans (wordWalkLaw_eq step S t) + +theorem booleanReturnsLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : PlainIndex (pairs : List (Pair A))) : + ((booleanReturnsLaw A R C K j k n t hK hW xi v w S).mass T:ℝ)= + ((returnKernel A R C K j k n hK hW xi v w).power t).P S T := by + rw [booleanReturnsLaw_eq] + exact walkLaw_cast_power (returnLaw A R C K j k n hK hW xi v w) S t T + +def initializedReturns (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) + (bits : Fin (r+returnBits A C K j k n t xi) → Bool) : + PlainIndex (pairs : List (Pair A)) := + let b := splitWordEquiv r (returnBits A C K j k n t xi) bits + booleanReturns A R C K j k n t hK hW xi v w (initial b.1) b.2 + +def initializedReturnsLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) : + RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin (r+returnBits A C K j k n t xi) → Bool)) + (initializedReturns A R C K j k n t r hK hW xi v w initial) + +theorem initializedReturnsLaw_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) : + initializedReturnsLaw A R C K j k n t r hK hW xi v w initial= + bindLaw (mapLaw (uniformLaw (α := Fin r → Bool)) initial) + (booleanReturnsLaw A R C K j k n t hK hW xi v w) := by + unfold initializedReturnsLaw initializedReturns + dsimp only + have he := map_equiv (splitWordEquiv r (returnBits A C K j k n t xi)) + (uniformLaw (α := Fin (r+returnBits A C K j k n t xi) → Bool)) + (fun b => booleanReturns A R C K j k n t hK hW xi v w (initial b.1) b.2) + rw [uniform_equiv,←uniform_product] at he + exact he.symm.trans (mapLaw_product_finish _ _ initial + (booleanReturns A R C K j k n t hK hW xi v w)) + +theorem initializedReturnsLaw_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) + (T : PlainIndex (pairs : List (Pair A))) : + ((initializedReturnsLaw A R C K j k n t r hK hW xi v w initial).mass T:ℝ)= + ((returnKernel A R C K j k n hK hW xi v w).power t).push + (fun S => ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ)) T := by + rw [initializedReturnsLaw_eq] + simp only [bindLaw,Rat.cast_sum,Rat.cast_mul,booleanReturnsLaw_cast,FiniteKernel.push] + +/-- The initial word need only be close in total variation to a warm +reference law. No pointwise warmness of the actual initial word law is +assumed. -/ +theorem initializedReturns_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 ((initializedReturnsLaw A R C K j k n t r hK hW xi v w initial).mass T:ℝ)) + (fun S => RootedWarmStart.law A R j S.val.val)≤ + distance (fun S => ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ)) nu+ + ((t:ℝ)*((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))+ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2) := by + let p : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ) + let Q := (returnKernel A R C K j k n hK hW xi v w).power t + have he : + (fun T => ((initializedReturnsLaw A R C K j k n t r hK hW xi v w initial).mass T:ℝ))= + Q.push p := by + funext T + exact initializedReturnsLaw_cast A R C K j k n t r hK hW xi v w initial T + rw [he] + have hc := distance_push Q p nu + have hr := repeated_return_stationary A R C hC K H L j k n hK hW hB hj hjH hbox + xi hx0 hx1 hPL hCheeger v hp w hw hgood hn nu hnu hmass U hU hwarm t + have ht := distance_triangle (Q.push p) (Q.push nu) + (fun S => RootedWarmStart.law A R j S.val.val) + exact ht.trans (_root_.add_le_add hc hr) + +end +end ContingencyTables.RootedReturnWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRootPenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRootPenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..5dff81a831ef1eb078c1ba397dcbbe1628e943e7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedRootPenalty.lean @@ -0,0 +1,198 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLiteralCount +import OAI.Combinatorics.ContingencyTables.Rooted.ForestRootPenalty + +namespace OAI + +/-! # The selected-root discrepancy is independent of the free entries + +Every large-cell edge stays in a maximum-forest component. Its two +incidences therefore cancel in the selected-root component sum. +-/ + +namespace ContingencyTables.RootedRootPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion RootedPhysicalCompletion +open ForestPhysicalCompletion (rowResidual columnResidual fixedRow fixedColumn) +open ForestRootPenalty (residualDemand smallDemand) + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma componentSum_decidable (A : Instance I J) (S : Selection A.T) + (d : I⊕J → ℤ) (a : I⊕J) : + (∑ v,@ite ℤ (S.root v=a) (Classical.propDecidable _) (d v) 0)= + ∑ v,if S.root v=a then d v else 0 := by + apply Finset.sum_congr rfl + intro v _ + by_cases h : S.root v=a <;> simp only [h,ite_true,ite_false] + +lemma root_eq_large (A : Instance I J) (S : Selection A.T) (i : I) (j : J) + (hs : A.small i j=false) : S.root (.inl i)=S.root (.inr j) := by + have hcap : ∀ e∈(ForestCapacity.cellGraph A.small).edgeSet,0 + cases v with + | inl i' => exact False.elim hg + | inr j => exact (A.hlarge i j hg).2 + | inr j => + cases v with + | inl i => exact (A.hlarge i j hg).2 + | inr j' => exact False.elim hg + have hspans := MaximumForest.maximum_spans (ForestCapacity.cellGraph A.small) A.T + (ForestCapacity.capacity A.b) A.hTG A.hT A.hmax hcap + apply S.constant + rw [hspans] + exact (show (ForestCapacity.cellGraph A.small).Adj (.inl i) (.inr j) from hs).reachable + +noncomputable def componentTotal (A : Instance I J) (S : Selection A.T) + (d : I⊕J → ℤ) (a : I⊕J) : ℤ := + ∑ v,(if S.root v=a then 1 else 0)*d v + +lemma componentTotal_residual (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (a : I⊕J) : + componentTotal A S (residualDemand A.small A.T A.r A.c x q free) a= + componentTotal A S (smallDemand A.small A.X x q) a := by + let R : I → ℤ := fun i => if S.root (.inl i)=a then 1 else 0 + let C : J → ℤ := fun j => if S.root (.inr j)=a then 1 else 0 + have hrow (i : I) : R i*rowResidual A.small A.T A.r x free i= + ∑ j,R i*(A.X i j-fixedRow A.small A.T x free i j) := by + rw [rowResidual,←A.hXr i,←Finset.sum_sub_distrib,Finset.mul_sum] + have hcol (j : J) : C j*(-columnResidual A.small A.T A.c q free j)= + ∑ i,C j*(fixedColumn A.small A.T q free i j-A.X i j) := by + rw [columnResidual,←A.hXc j,neg_sub,←Finset.sum_sub_distrib,Finset.mul_sum] + unfold componentTotal residualDemand smallDemand + rw [Fintype.sum_sum_type,Fintype.sum_sum_type] + simp only [Sum.elim_inl,Sum.elim_inr] + change (∑ i,R i*rowResidual A.small A.T A.r x free i)+ + (∑ j,C j*(-columnResidual A.small A.T A.c q free j))= + (∑ i,R i*(∑ j,if A.small i j then A.X i j-x i j else 0))+ + ∑ j,C j*(∑ i,if A.small i j then q i j-A.X i j else 0) + simp_rw [hrow,hcol,Finset.mul_sum] + rw [Finset.sum_comm (f := fun j i => C j*(fixedColumn A.small A.T q free i j-A.X i j)), + Finset.sum_comm (f := fun j i => C j*(if A.small i j then q i j-A.X i j else 0)), + ←Finset.sum_add_distrib,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [←Finset.sum_add_distrib,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + by_cases hs : A.small i j=true + · simp [fixedRow,fixedColumn,hs] + · have hs' : A.small i j=false := Bool.eq_false_iff.mpr hs + have he : R i=C j := by unfold R C; rw [root_eq_large A S i j hs'] + rw [he] + simp only [fixedRow,fixedColumn,hs',Bool.false_eq_true,ite_false] + ring + +lemma table_row_all (A : Instance I J) (S : Selection A.T) + (r : I → ℤ) (c : J → ℤ) (i : I) : + (∑ j,table A.T S r c i j)= + r i-∑ v,if S.root v=Sum.inl i then Sum.elim r (fun j => -c j) v else 0 := by + have hs := flow_divergence_all S (Sum.elim r (fun j => -c j)) (.inl i) + rw [Fintype.sum_sum_type] at hs + have hz : (∑ i',flow S (Sum.elim r (fun j => -c j)) (.inl i) (.inl i'))=0 := by + apply Finset.sum_eq_zero + intro i' _ + apply flow_supported + intro h + exact A.hTG h + simp only [hz,zero_add,Sum.elim_inl] at hs + rw [componentSum_decidable] at hs + simpa only [table] using hs + +lemma table_column_all (A : Instance I J) (S : Selection A.T) + (r : I → ℤ) (c : J → ℤ) (j : J) : + -(∑ i,table A.T S r c i j)= + -c j-∑ v,if S.root v=Sum.inr j then Sum.elim r (fun j => -c j) v else 0 := by + have hs := flow_divergence_all S (Sum.elim r (fun j => -c j)) (.inr j) + rw [Fintype.sum_sum_type] at hs + have hz : (∑ j',flow S (Sum.elim r (fun j => -c j)) (.inr j) (.inr j'))=0 := by + apply Finset.sum_eq_zero + intro j' _ + apply flow_supported + intro h + exact A.hTG h + have hskew : (∑ i,flow S (Sum.elim r (fun j => -c j)) (.inr j) (.inl i))= + -(∑ i,table A.T S r c i j) := by + rw [←Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + exact flow_skew S _ _ _ + simp only [hz,add_zero,Sum.elim_inr,hskew] at hs + rw [componentSum_decidable] at hs + exact hs + +noncomputable def signedResidual (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) : I⊕J → ℤ := + Sum.elim + (fun i => (∑ j,if A.small i j then x i j else completed A S x q free i j)-A.r i) + (fun j => -((∑ i,if A.small i j then q i j else completed A S x q free i j)-A.c j)) + +theorem signedResidual_eq_small (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) (a : I⊕J) : + signedResidual A S x q free a=-componentTotal A S (smallDemand A.small A.X x q) a := by + suffices he : signedResidual A S x q free a= + -componentTotal A S (residualDemand A.small A.T A.r A.c x q free) a by + rw [he,componentTotal_residual] + have htotal : ∀ d : I⊕J → ℤ, + (∑ v,if S.root v=a then d v else 0)=componentTotal A S d a := by + intro d + simp [componentTotal,ite_mul] + cases a with + | inl i => + simp only [signedResidual,Sum.elim_inl] + simp_rw [row_pointwise] + rw [Finset.sum_add_distrib] + have hr := table_row_all A S (rowResidual A.small A.T A.r x free) + (columnResidual A.small A.T A.c q free) i + change (∑ j,solved A S x q free i j)=_ at hr + rw [hr,htotal] + unfold residualDemand rowResidual columnResidual + ring + | inr j => + simp only [signedResidual,Sum.elim_inr] + simp_rw [column_pointwise] + rw [Finset.sum_add_distrib] + have hc := table_column_all A S (rowResidual A.small A.T A.r x free) + (columnResidual A.small A.T A.c q free) j + change -(∑ i,solved A S x q free i j)=_ at hc + have hc' : (∑ i,solved A S x q free i j)=columnResidual A.small A.T A.c q free j+ + ∑ v,if S.root v=Sum.inr j then + Sum.elim (rowResidual A.small A.T A.r x free) + (fun j => -columnResidual A.small A.T A.c q free j) v else 0 := by linarith + rw [hc',htotal] + unfold residualDemand rowResidual columnResidual + ring + +theorem signedResidual_independent (A : Instance I J) (S : Selection A.T) + (x q free free' : I → J → ℤ) : + signedResidual A S x q free=signedResidual A S x q free' := by + funext a + rw [signedResidual_eq_small,signedResidual_eq_small] + +lemma abs_actualDeviation_solved (A : Instance I J) (S : Selection A.T) + (x y free : I → J → ℕ) (a : I⊕J) : + |ForestLiteralCount.actualDeviation A.small A.T A.b x y free A.r A.c + (solved A S (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ))) a|= + |(signedResidual A S (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) a:ℝ)| := by + cases a with + | inl i => + simp only [ForestLiteralCount.actualDeviation,signedResidual,Sum.elim_inl,completed, + ForestLiteralCount.largeValue] + push_cast + rfl + | inr j => + simp only [ForestLiteralCount.actualDeviation,signedResidual,Sum.elim_inr,completed, + ForestLiteralCount.largeValue] + push_cast + rw [abs_neg] + +end ContingencyTables.RootedRootPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a0f2016cafefe14e9f4b7f744b44e72674d7164 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledBounds.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledIdentification +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledBounds + +namespace OAI + +/-! # The source height bounds the entire selected-root density cube -/ + +namespace ContingencyTables.RootedScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion GraphCompletionCounts ForestAssignmentSplit +open RootedRootPenalty RootedPhysicalCompletion BalancedBox +open ForestScaledPenalty (rowCounts columnCounts rowCounts_bounds columnCounts_bounds + intervalCost intervalCost_div integerCube integerCube_zero zeroAssignment tree_card_le) + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma rootConstant_bound (A : Instance I J) (S : Selection A.T) + (z : View A → ℕ) (hz : InBox (bounds A) z) : + rootConstant A S (rowCounts A z) (columnCounts A z)≤2*(A.d:ℝ)*A.W := by + let d := ForestRootPenalty.smallDemand A.small A.X (rowCounts A z) (columnCounts A z) + have he (a : I⊕J) : (signedResidual A S (rowCounts A z) (columnCounts A z) 0 a:ℝ)= + -(∑ v,if S.root v=a then (d v:ℝ) else 0) := by + rw [signedResidual_eq_small] + unfold componentTotal + push_cast + congr 1 + apply Finset.sum_congr rfl + intro v _ + by_cases hv : S.root v=a <;> simp [hv,d] + have hrow (i : I) : |((∑ j,if A.small i j then A.X i j-rowCounts A z i j else 0:ℤ):ℝ)|≤ + ∑ j,if A.small i j then (A.b i j:ℝ) else 0 := by + push_cast + apply (Finset.abs_sum_le_sum_abs _ _).trans + apply Finset.sum_le_sum + intro j _ + by_cases hs : A.small i j=true + · simp only [hs,ite_true] + have hh : |A.X i j-rowCounts A z i j|≤(A.b i j:ℤ) := by + apply abs_le.mpr + constructor <;> linarith [(rowCounts_bounds A z hz i j hs).1, + (rowCounts_bounds A z hz i j hs).2,(A.hX i j).1,(A.hX i j).2] + exact_mod_cast hh + · have hs' : A.small i j=false := Bool.eq_false_iff.mpr hs + simp [hs'] + have hcol (j : J) : |((∑ i,if A.small i j then columnCounts A z i j-A.X i j else 0:ℤ):ℝ)|≤ + ∑ i,if A.small i j then (A.b i j:ℝ) else 0 := by + push_cast + apply (Finset.abs_sum_le_sum_abs _ _).trans + apply Finset.sum_le_sum + intro i _ + by_cases hs : A.small i j=true + · simp only [hs,ite_true] + have hh : |columnCounts A z i j-A.X i j|≤(A.b i j:ℤ) := by + apply abs_le.mpr + constructor <;> linarith [(columnCounts_bounds A z i j).1, + (columnCounts_bounds A z i j).2,(A.hX i j).1,(A.hX i j).2] + exact_mod_cast hh + · have hs' : A.small i j=false := Bool.eq_false_iff.mpr hs + simp [hs'] + have hdemand : (∑ a,|(d a:ℝ)|)≤2*∑ i,∑ j,if A.small i j then (A.b i j:ℝ) else 0 := by + rw [Fintype.sum_sum_type] + change (∑ i,|((∑ j,if A.small i j then A.X i j-rowCounts A z i j else 0:ℤ):ℝ)|)+ + (∑ j,|((∑ i,if A.small i j then columnCounts A z i j-A.X i j else 0:ℤ):ℝ)|)≤_ + have hr := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hrow i) + have hc := Finset.sum_le_sum (s := Finset.univ) (fun j _ => hcol j) + rw [Finset.sum_comm] at hc + linarith + have hsmall : (∑ i,∑ j,if A.small i j then (A.b i j:ℝ) else 0)≤(A.d:ℝ)*A.W := by + calc + _≤∑ _i : I,∑ _j : J,(A.W:ℝ) := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + cases hs : A.small i j + · simp only [Bool.false_eq_true,ite_false] + positivity + · simp only [ite_true] + exact_mod_cast (A.hsmall i j hs).le + _=(Fintype.card I*Fintype.card J:ℕ)*(A.W:ℝ) := by simp; ring + _≤_ := mul_le_mul_of_nonneg_right (by exact_mod_cast A.hcard) (Nat.cast_nonneg _) + unfold rootConstant + calc + _≤∑ a,|(signedResidual A S (rowCounts A z) (columnCounts A z) 0 a:ℝ)| := by + apply Finset.sum_le_sum + intro a _ + split_ifs <;> first | exact le_rfl | exact abs_nonneg _ + _=∑ a,|∑ v,if S.root v=a then (d v:ℝ) else 0| := by simp_rw [he,abs_neg] + _≤∑ v,|(d v:ℝ)| := ForestRootPenalty.sum_abs_componentTotal S.root (fun v => (d v:ℝ)) + _≤_ := hdemand.trans (by linarith) + +lemma zero_tree_bound (A : Instance I J) (S : Selection A.T) (B : ℝ) (hB : 0 (freeTable A.small A.T A.b (zeroAssignment A) i j:ℤ))=0 := by + funext i j + unfold freeTable zeroAssignment + split_ifs <;> rfl + have hinterval := RootedIntervals.solved_in_intervals A S + (rowCounts A z) (columnCounts A z) 0 + (by intro i j hs; exact ⟨rowCounts_bounds A z hz i j hs,columnCounts_bounds A z i j⟩) + (by intro i j _ _; exact ⟨le_rfl,Nat.cast_nonneg _⟩) + t.val.1 t.val.2 t.property + rw [←integerCube_zero A B,scaledTree_integer A S B hB,hzero,intervalCost_div] + · have hb : (0:ℝ) linarith + · exact_mod_cast (A.hlarge _ _ (A.hTG t.property)).2 + +theorem penalty_cube_bound (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hC : 0≤ C) (hB : 0 zero_tree_bound A S B hB z hz t) + have ht : (∑ t : TreeCell A.T,intervalCost (scaledTree A S B (rowCounts A z) (columnCounts A z) 0 t))≤ + 10*(A.d:ℝ)^2 := by + calc + _≤(Fintype.card (TreeCell A.T):ℝ)*(10*(A.d:ℝ)) := by simpa using hsum + _≤(A.d:ℝ)*(10*(A.d:ℝ)) := mul_le_mul_of_nonneg_right + (by exact_mod_cast tree_card_le A) (by positivity) + _=_ := by ring + linarith [rootConstant_bound A S z hz] + have hchange := (le_abs_self _).trans (penalty_change A S C B hC hB + (rowCounts A z) (columnCounts A z) v 0 B hB.le (by + intro f + simpa only [Pi.zero_apply,sub_zero,abs_of_nonneg (hv f).1] using (hv f).2)) + have hcancel : (2*C*(A.d:ℝ)^2/B)*B=2*C*(A.d:ℝ)^2 := div_mul_cancel₀ _ hB.ne' + rw [hcancel] at hchange + have hd : (1:ℝ)≤ A.d := by exact_mod_cast A.hd + have hW : (2:ℝ)≤ A.W := by exact_mod_cast A.hW + have hscalar : 2*(A.d:ℝ)*A.W+12*(A.d:ℝ)^2≤10*(A.d:ℝ)^2*((A.W:ℝ)+1) := by + have hdd : (A.d:ℝ)≤(A.d:ℝ)^2 := by nlinarith + have hp := mul_le_mul_of_nonneg_right hdd (by positivity : (0:ℝ)≤ A.W) + have hp' := mul_le_mul_of_nonneg_left hW (sq_nonneg (A.d:ℝ)) + nlinarith + refine ⟨penalty_nonnegative A S C B hC _ _ v,?_⟩ + nlinarith [mul_le_mul_of_nonneg_left hscalar hC] + +end ContingencyTables.RootedScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledIdentification.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..fecff7a59668def4c5e4a5977d8185338a2e3ab5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledIdentification.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountIdentification +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledIdentification + +namespace OAI + +/-! # The selected-root geometric density is the literal completion weight -/ + +namespace ContingencyTables.RootedScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion GraphCompletionCounts ForestAssignmentSplit +open RootedAffine RootedPhysicalCompletion RootedRootPenalty +open ForestScaledPenalty (integerCube intervalCost intervalCost_div tree_sum_eq) + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma free_coefficient_sum (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (F : I×J → ℝ) : + (∑ f : FreeCell A.small A.T,coefficient A S t f.val*F f.val)= + ∑ a : I×J,coefficient A S t a*F a := by + let p : I×J → Prop := fun a => A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + calc + _=∑ a ∈ Finset.univ.filter p,coefficient A S t a*F a := + (Finset.sum_subtype (p := p) (Finset.univ.filter p) (fun _ => by simp) + (fun a => coefficient A S t a*F a)).symm + _=_ := by + apply Finset.sum_subset (Finset.filter_subset _ _) + intro a _ ha + have hp : ¬p a := by simpa only [Finset.mem_filter,Finset.mem_univ,true_and] using ha + change ¬(A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2)) at hp + simp only [coefficient,hp,ite_false,zero_mul] + +theorem scaledTree_integer (A : Instance I J) (S : Selection A.T) (B : ℝ) (hB : 0 (freeTable A.small A.T A.b f i j:ℤ)) + t.val.1 t.val.2:ℝ)/(A.b t.val.1 t.val.2:ℝ) := by + let F : I×J → ℝ := fun a => (freeTable A.small A.T A.b f a.1 a.2:ℝ) + have hterm (a : FreeCell A.small A.T) : + normalizedCoefficient A S B t a*integerCube A B f a= + coefficient A S t a.val*F a.val/(A.b t.val.1 t.val.2:ℝ) := by + have hN : (A.b a.val.1 a.val.2:ℝ)+1≠0 := by positivity + have hbt : (A.b t.val.1 t.val.2:ℝ)≠0 := by + exact_mod_cast (Nat.ne_of_gt (A.hlarge _ _ (A.hTG t.property)).2) + have hF : F a.val=(f a).val := by simp [F,freeTable,a.property] + rw [hF] + unfold normalizedCoefficient integerCube + field_simp [hB.ne',hN,hbt] + unfold scaledTree AffinePenalty.affineValue normalizedOffset + simp_rw [hterm] + rw [←Finset.sum_div,free_coefficient_sum,←add_div] + have hh := solved_eq_affine A S t x q (fun i j => (freeTable A.small A.T A.b f i j:ℤ)) + unfold affineTree AffinePenalty.affineValue at hh + apply congrArg (fun z : ℝ => z/(A.b t.val.1 t.val.2:ℝ)) + simpa only [F,Int.cast_natCast] using hh.symm + +theorem rootConstant_eq_assignment (A : Instance I J) (S : Selection A.T) + (x q free : I → J → ℤ) : + rootConstant A S x q= + ∑ a,if RootedPenalty.rootFlag S a then |(signedResidual A S x q free a:ℝ)| else 0 := by + have hh := signedResidual_independent A S x q free 0 + unfold rootConstant + apply Finset.sum_congr rfl + intro a _ + rw [hh] + +theorem penalty_at_integer (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hB : 0 (ForestCountIdentification.smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ)) + (integerCube A B f)=C*RootedLiteralCount.actualPenalty A S + (ForestCountIdentification.smallX A.small z) (ForestCountIdentification.smallY A.small z) + (freeTable A.small A.T A.b f) + (solved A S (fun i j => (ForestCountIdentification.smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ)) + (fun i j => (freeTable A.small A.T A.b f i j:ℤ))) := by + let x := ForestCountIdentification.smallX A.small z + let y := ForestCountIdentification.smallY A.small z + let free := freeTable A.small A.T A.b f + let tree := solved A S (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ)) + (fun i j => (free i j:ℤ)) + have hroot : rootConstant A S (fun i j => (x i j:ℤ)) (fun i j => ((A.b i j-y i j:ℕ):ℤ))= + ∑ a,if RootedPenalty.rootFlag S a then + |ForestLiteralCount.actualDeviation A.small A.T A.b x y free A.r A.c tree a| else 0 := by + rw [rootConstant_eq_assignment A S _ _ (fun i j => (free i j:ℤ))] + apply Finset.sum_congr rfl + intro a _ + rw [abs_actualDeviation_solved] + have htree : (∑ t : TreeCell A.T,intervalCost (scaledTree A S B (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ)) (integerCube A B f) t))= + ∑ i,∑ j,if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(tree i j:ℝ)) ((tree i j:ℝ)-A.b i j))/(A.b i j:ℝ) else 0 := by + calc + _=∑ t : TreeCell A.T, + max 0 (max (-(tree t.val.1 t.val.2:ℝ)) ((tree t.val.1 t.val.2:ℝ)-A.b t.val.1 t.val.2))/ + (A.b t.val.1 t.val.2:ℝ) := by + apply Finset.sum_congr rfl + intro t _ + rw [scaledTree_integer A S B hB] + exact intervalCost_div _ _ (by exact_mod_cast (A.hlarge _ _ (A.hTG t.property)).2) + _=_ := tree_sum_eq A (fun a => + max 0 (max (-(tree a.1 a.2:ℝ)) ((tree a.1 a.2:ℝ)-A.b a.1 a.2))/(A.b a.1 a.2:ℝ)) + unfold penalty + change C*(rootConstant A S (fun i j => (x i j:ℤ)) + (fun i j => ((A.b i j-y i j:ℕ):ℤ))+_)=_ + rw [hroot,htree] + rfl + +theorem h_eq_integer_density_sum (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hB : 0 (ForestCountIdentification.smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ)) + (integerCube A B f)) := by + unfold RootedCountIdentification.h + apply Finset.sum_congr rfl + intro f _ + rw [penalty_at_integer A S C B hB z f,neg_mul] + +end ContingencyTables.RootedScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledPenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledPenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..85a236132eb06505651c28c07352fba2ebf94f2c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedScaledPenalty.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRootPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledPenalty + +namespace OAI + +/-! # Convexity and the physical scaled Lipschitz bound for selected roots -/ + +namespace ContingencyTables.RootedScaledPenalty + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedCompletion GraphCompletionCounts ForestAssignmentSplit +open RootedAffine RootedRootPenalty +open ForestScaledPenalty (intervalCost intervalCost_nonnegative intervalCost_change + intervalCost_combine free_card_le tree_card_le) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def normalizedOffset (A : Instance I J) (S : Selection A.T) + (t : TreeCell A.T) (x q : I → J → ℤ) : ℝ := + offset A S t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ))/(A.b t.val.1 t.val.2:ℝ) + +noncomputable def normalizedCoefficient (A : Instance I J) (S : Selection A.T) + (B : ℝ) (t : TreeCell A.T) (f : FreeCell A.small A.T) : ℝ := + coefficient A S t f.val*((A.b f.val.1 f.val.2:ℝ)+1)/B/(A.b t.val.1 t.val.2:ℝ) + +noncomputable def scaledTree (A : Instance I J) (S : Selection A.T) + (B : ℝ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℝ) (t : TreeCell A.T) : ℝ := + AffinePenalty.affineValue (normalizedOffset A S t x q) (normalizedCoefficient A S B t) v + +noncomputable def rootConstant (A : Instance I J) (S : Selection A.T) + (x q : I → J → ℤ) : ℝ := + ∑ a,if RootedPenalty.rootFlag S a then |(signedResidual A S x q 0 a:ℝ)| else 0 + +noncomputable def penalty (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℝ) : ℝ := + C*(rootConstant A S x q+∑ t : TreeCell A.T,intervalCost (scaledTree A S B x q v t)) + +lemma penalty_nonnegative (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hC : 0≤ C) (x q : I → J → ℤ) (v : FreeCell A.small A.T → ℝ) : + 0≤ penalty A S C B x q v := by + unfold penalty rootConstant + apply mul_nonneg hC + apply add_nonneg + · exact Finset.sum_nonneg (fun a _ => by split_ifs <;> positivity) + · exact Finset.sum_nonneg (fun t _ => intervalCost_nonnegative _) + +theorem penalty_change (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hC : 0≤ C) (hB : 0 normalized_coefficient_bound A S t f.val B hB) hvw + exact hh.trans (mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_right (by exact_mod_cast free_card_le A) (by positivity : (0:ℝ)≤2/B)) hr) + have he : penalty A S C B x q v-penalty A S C B x q w= + C*∑ t : TreeCell A.T,(intervalCost (scaledTree A S B x q v t)- + intervalCost (scaledTree A S B x q w t)) := by + unfold penalty + rw [Finset.sum_sub_distrib] + ring + rw [he,abs_mul,abs_of_nonneg hC] + calc + _≤ C*∑ t : TreeCell A.T,|intervalCost (scaledTree A S B x q v t)- + intervalCost (scaledTree A S B x q w t)| := + mul_le_mul_of_nonneg_left (Finset.abs_sum_le_sum_abs _ _) hC + _≤ C*∑ _t : TreeCell A.T,(A.d:ℝ)*(2/B)*r := + mul_le_mul_of_nonneg_left (Finset.sum_le_sum (fun t _ => hterm t)) hC + _=C*((Fintype.card (TreeCell A.T):ℝ)*((A.d:ℝ)*(2/B)*r)) := by simp + _≤ C*((A.d:ℝ)*((A.d:ℝ)*(2/B)*r)) := mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_right (by exact_mod_cast tree_card_le A) (by positivity)) hC + _=_ := by ring + +theorem penalty_convex (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (hC : 0≤ C) (x q : I → J → ℤ) : + ConvexOn ℝ Set.univ (penalty A S C B x q) := by + refine ⟨convex_univ,?_⟩ + intro v _ w _ a b ha hb hab + have hsum : (∑ t : TreeCell A.T,intervalCost (scaledTree A S B x q (a • v+b • w) t))≤ + a*(∑ t : TreeCell A.T,intervalCost (scaledTree A S B x q v t))+ + b*(∑ t : TreeCell A.T,intervalCost (scaledTree A S B x q w t)) := by + rw [Finset.mul_sum,Finset.mul_sum,←Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro t _ + unfold scaledTree + rw [AffinePenalty.affineValue_combine _ _ _ _ _ _ hab] + exact intervalCost_combine _ _ _ _ ha hb hab + unfold penalty + have hh := mul_le_mul_of_nonneg_left hsum hC + simp only [smul_eq_mul] + nlinarith [congrArg (fun z => C*z*rootConstant A S x q) hab] + +theorem penalty_continuous (A : Instance I J) (S : Selection A.T) + (C B : ℝ) (x q : I → J → ℤ) : Continuous (penalty A S C B x q) := by + apply continuous_const.mul + apply continuous_const.add + apply continuous_finsetSum + intro t _ + have hs : Continuous (fun v => scaledTree A S B x q v t) := by + exact continuous_const.add (continuous_finsetSum Finset.univ + (fun f _ => continuous_const.mul (continuous_apply f))) + exact continuous_const.max (hs.neg.max (hs.sub continuous_const)) + +end ContingencyTables.RootedScaledPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedSlowConcentration.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedSlowConcentration.lean new file mode 100644 index 0000000000000000000000000000000000000000..a06325b293474d70d83772e822ffc39a88027550 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedSlowConcentration.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBooleanKernel +import OAI.Combinatorics.ContingencyTables.Machines.FiniteTraceSlowdown + +namespace OAI + +/-! # Actual selected-root dyadic phase concentration -/ + +namespace ContingencyTables.RootedSlowConcentration + +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing RootedMultiplierUpdate +open RootedBooleanPhase CompanionRationalUpdates TwoLiftStates ObservableBounds +open RootedWarmStart (actual_degree) +open CompanionConcentration (pairs_ne_nil square_width_one_le) +open CompanionBooleanPhase (State slowdown slowdown_bounds) +open ObservableTrajectory FiniteChainSlowdown +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma constant_nonnegative (A : Instance I J) : + 0≤observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + unfold observableConstant + positivity + +lemma target_mean (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 G S.val)= + chainMean pairs (fun p q => (w p q:ℝ)) (weight A R j) G := by + change (referenceChain A R j hp w hw).mean (fun S => G S.val)=_ + exact metropolisChain_mean _ _ _ _ _ _ _ _ _ + +lemma target_pi (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j) := rfl + +/-- Mean-square concentration of the real chain implemented by the +actual padded proposal. -/ +theorem bounded_MSE (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) + (o : PhaseObservables (pairs : List (Pair A))) + (nu : State A → ℝ) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j)) + (N : ℕ) (hN : 0 phaseObservable pairs (ratio A R j) o S.val + (∑ S,nu S*D.squareMoment (fun S => G S-D.mean G) N S)/(N:ℝ)^2≤ + 40*(Fintype.card (Labels A):ℝ)^2* + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/N := by + let C := referenceChain A R j hp w hw + let D := targetChain A R j hp w hw + let G : Set (Labels A×Bool) → ℝ := phaseObservable pairs (ratio A R j) o + let g : State A → ℝ := fun S => G S.val- + chainMean pairs (fun p q => (w p q:ℝ)) (weight A R j) G + let K := observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) + have hdual (H : State A → ℝ) : (C.inner g H)^2≤K*C.inner g g*C.energy H := by + dsimp only [C] + rw [referenceChain_eq_completed] + simpa only [K,PairedLabels.length,g,G] using + omission_chain_dual pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) (weight A R j) G hgood.positive + (actual_degree A R j).1 (actual_degree A R j).2 ((A.W:ℝ)^2) (square_width_one_le A) + (phaseObservable_class pairs (ratio A R j) o) hgood.lower hgood.upper H + have hcmean : C.mean (fun S => G S.val)= + chainMean pairs (fun p q => (w p q:ℝ)) (weight A R j) G := by + exact target_mean A R j hp w hw G + have hvar : C.inner g g≤1 := by + have hb := C.variance_le_one (fun S => G S.val) (by + intro S + exact phaseObservable_bounded pairs (ratio A R j) + (fun T _ => ⟨by linarith [(ratio_bounds A R j T).1],(ratio_bounds A R j T).2⟩) o S.val) + simpa only [FiniteChain.variance,hcmean,g] using hb + have hwm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)*C.π S := by + intro S + have hpi : C.π S=chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j) := rfl + rw [hpi] + simpa only [mul_div_assoc] using hwarm S + have hm := warm_moment_bound C (slowdown A) + (by linarith [(slowdown_bounds A hp).1]) (slowdown_bounds A hp).2 + (slowdown_bounds A hp).1 K (10*(Fintype.card (Labels A):ℝ)^2) + (constant_nonnegative A) (by positivity) g hdual nu hwm N hN + have hmean : D.mean (fun S => G S.val)= + chainMean pairs (fun p q => (w p q:ℝ)) (weight A R j) G := target_mean A R j hp w hw G + change (∑ S,nu S*D.squareMoment (fun S => G S.val-D.mean (fun S => G S.val)) N S)/(N:ℝ)^2≤_ + rw [hmean] + apply hm.trans + have hN0 : (0:ℝ)≤N := Nat.cast_nonneg _ + apply div_le_div_of_nonneg_right _ hN0 + have hmul := mul_le_mul_of_nonneg_left hvar + (show 0≤4*(10*(Fintype.card (Labels A):ℝ)^2)*K from by + have := constant_nonnegative A + dsimp only [K] + positivity) + nlinarith + +/-- The full collection of phase observables obeys the source union +bound for the actual dyadic holding chain. -/ +theorem phase_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) + (nu : State A → ℝ) (hnu : ∀ S,0≤nu S) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs (fun p q => (w p q:ℝ)) (weight A R j) S.val/ + chainTotal pairs (fun p q => (w p q:ℝ)) (weight A R j)) + (N : ℕ) (hN : 0 ∃ o : PhaseObservables (pairs : List (Pair A)), + eta*D.mean (fun S => phaseObservable pairs (ratio A R j) o S.val)< + |FiniteChain.pathSum (fun S => phaseObservable pairs (ratio A R j) o S.val) l/(N:ℝ)- + D.mean (fun S => phaseObservable pairs (ratio A R j) o S.val)|)≤ + 32000*(Fintype.card (Labels A):ℝ)^8* + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/((N:ℝ)*eta^2) := by + let D := targetChain A R j hp w hw + let p : ℝ := Fintype.card (Labels A) + let K := observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) + have hpR : 0

phaseObservable pairs (ratio A R j) o S.val) := by + rw [target_mean] + have hh := phaseObservable_mean_lower pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A R j) (ratio A R j) + hgood.positive (weight_positive A R j) (fun S _ => (ratio_bounds A R j S).1) + hgood.lower hgood.upper o + simpa only [p,PairedLabels.length] using hh + have hb := D.relative_union_bound nu hnu + (fun o S => phaseObservable pairs (ratio A R j) o S.val) + (1/(20*p^2)) eta (40*p^2*K/N) (by positivity) heta (by positivity) + hmean N hN (fun o => bounded_MSE A R j hp w hw hgood o nu hwarm N hN) + have hJ : (Fintype.card (PhaseObservables (pairs : List (Pair A))):ℝ)≤2*p^2 := by + have hc := phaseObservables_card pairs PairedLabels.fresh (pairs_ne_nil A hp) + simp only [PairedLabels.length] at hc + dsimp only [p] + exact_mod_cast hc + apply hb.trans + calc + _ ≤ (2*p^2)*(40*p^2*K/N)/(eta*(1/(20*p^2)))^2 := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right hJ (by positivity)) (sq_nonneg _) + _ = 32000*p^8*K/((N:ℝ)*eta^2) := by + field_simp [hpR.ne',heta.ne',hNR.ne'] + ring + +end +end ContingencyTables.RootedSlowConcentration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredEstimate.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredEstimate.lean new file mode 100644 index 0000000000000000000000000000000000000000..42d2df9b620dd2ad6d71bc130f0aa4ca85db1461 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredEstimate.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrial +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTerminalApplication + +namespace OAI + +/-! # Soundness of the actual stored rational count estimate -/ + +namespace ContingencyTables.RootedStoredEstimate + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionPhaseWords (Stored) +open RootedWarmStart RootedPhaseTrial +open CompanionReferenceAccuracy (relative_of_log_error) +open CompanionTerminalMass (Endpoints tableCount tableCount_ge_one) +open CompanionTerminalApplication (finalPhase) +open TwoLiftStates +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def initialTotal (A : Instance I J) : ℚ := + (∏ a : ForestAssignmentSplit.FreeCell A.small A.T,((A.b a.val.1 a.val.2+1:ℕ):ℚ))* + ∏ s : SmallCell A,((A.b s.val.1 s.val.2+1:ℕ):ℚ) + +def initialStored (A : Instance I J) : Stored A := + ⟨initial A,initialTotal A⟩ + +lemma initialTotal_cast (A : Instance I J) (R : RootedCompletion.Selection A.T) : + (initialTotal A:ℝ)=total A R 0 := by + rw [total,total_zero] + simp only [initialTotal,CompanionInitialization.freeTotal,Rat.cast_mul,Rat.cast_prod, + Rat.cast_add,Rat.cast_natCast,Rat.cast_one,Nat.cast_add,Nat.cast_one] + +lemma initialStored_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) : + (∀ p q,0 < (initialStored A).multiplier p q) ∧ 0 < (initialStored A).estimate := by + constructor + · exact initial_positive A + · have h : (0:ℝ) < (initialTotal A:ℝ) := by + rw [initialTotal_cast A R] + exact total_positive A R 0 + exact_mod_cast h + +lemma initialStored_good (A : Instance I J) (R : RootedCompletion.Selection A.T) : + GoodMultipliers pairs (RootedAnnealing.weight A R 0) + (fun p q => ((initialStored A).multiplier p q:ℝ)) := by + have hw : (fun p q => ((initialStored A).multiplier p q:ℝ))= + CompanionInitialMultipliers.multiplier A := by + funext p q + exact initial_cast A p q + rw [hw,zero_weight_eq] + simpa only [CompanionAnnealing.weight,Nat.cast_zero,zero_div] using + CompanionInitialMultipliers.initial_good A + +/-- The actual rational estimates telescope through their proved +per-phase multiplicative errors, including every weight-oracle error. -/ +theorem stored_log_error (A : Instance I J) (R : RootedCompletion.Selection A.T) + (stored : ℕ → Stored A) (hinit : stored 0=initialStored A) + (xi : ℚ) (eta : ℝ) (H : ℕ) + (hstep : ∀ j,j < H → ValidOutput A R j (stored j) xi eta (stored (j+1))) : + 0 < (stored H).estimate ∧ + |Real.log (((stored H).estimate:ℝ)/total A R H)| ≤ + (H:ℝ)*(4*(xi:ℝ)+4*eta) := by + induction H with + | zero => + rw [hinit] + refine ⟨(initialStored_positive A R).2,?_⟩ + have he : ((initialStored A).estimate:ℝ)=total A R 0 := initialTotal_cast A R + rw [he,div_self (total_positive A R 0).ne'] + simp + | succ H ih => + have hprev := ih (fun j hj => hstep j (by omega)) + have hnext := hstep H (by omega) + have hold : (0:ℝ) < ((stored H).estimate:ℝ) := by exact_mod_cast hprev.1 + have hnew : (0:ℝ) < ((stored (H+1)).estimate:ℝ) := by exact_mod_cast hnext.2.1 + have hT := total_positive A R H + have hT' := total_positive A R (H+1) + have heq : ((stored (H+1)).estimate:ℝ)/total A R (H+1)= + (((stored H).estimate:ℝ)/total A R H)* + (((stored (H+1)).estimate:ℝ)/ + (((stored H).estimate:ℝ)*(total A R (H+1)/total A R H))) := by + field_simp [hold.ne',hT.ne',hT'.ne'] + refine ⟨hnext.2.1,?_⟩ + rw [heq,Real.log_mul (div_ne_zero hold.ne' hT.ne') + (div_ne_zero hnew.ne' (mul_ne_zero hold.ne' (div_ne_zero hT'.ne' hT.ne')))] + have hb := abs_add_le + (Real.log (((stored H).estimate:ℝ)/total A R H)) + (Real.log (((stored (H+1)).estimate:ℝ)/ + (((stored H).estimate:ℝ)*(total A R (H+1)/total A R H)))) + have hs : |Real.log (((stored (H+1)).estimate:ℝ)/ + (((stored H).estimate:ℝ)*(total A R (H+1)/total A R H)))| ≤ + 4*(xi:ℝ)+4*eta := hnext.2.2.2 + push_cast + nlinarith [hprev.2] + +theorem stored_count_accuracy (A : Instance I J) (R : RootedCompletion.Selection A.T) + (E : Endpoints A) (L : ℕ) (epsilon : ℝ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (hW : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) + (stored : ℕ → Stored A) (hinit : stored 0=initialStored A) + (xi : ℚ) (eta : ℝ) + (herr : (finalPhase A L epsilon:ℝ)*(4*(xi:ℝ)+4*eta) ≤ epsilon/50) + (hstep : ∀ j,j < finalPhase A L epsilon → + ValidOutput A R j (stored j) xi eta (stored (j+1))) : + (1-epsilon)*tableCount A ≤ ((stored (finalPhase A L epsilon)).estimate:ℝ) ∧ + ((stored (finalPhase A L epsilon)).estimate:ℝ) ≤ (1+epsilon)*tableCount A := by + have hs := stored_log_error A R stored hinit xi eta (finalPhase A L epsilon) hstep + have hZ := total_positive A R (finalPhase A L epsilon) + have hratio := relative_of_log_error epsilon + (((stored (finalPhase A L epsilon)).estimate:ℝ)/total A R (finalPhase A L epsilon)) + he0 he1 (div_pos (by exact_mod_cast hs.1) hZ) (hs.2.trans herr) + have hb : (1-epsilon/4)*total A R (finalPhase A L epsilon) ≤ + ((stored (finalPhase A L epsilon)).estimate:ℝ) ∧ + ((stored (finalPhase A L epsilon)).estimate:ℝ) ≤ + (1+epsilon/4)*total A R (finalPhase A L epsilon) := + ⟨(le_div_iff₀ hZ).mp hratio.1,(div_le_iff₀ hZ).mp hratio.2⟩ + apply final_estimate_accuracy epsilon (tableCount A) (total A R (finalPhase A L epsilon)) + ((stored (finalPhase A L epsilon)).estimate:ℝ) he0 he1 (by linarith [tableCount_ge_one A]) + · have ht := RootedTerminalApplication.terminal_normalizer A R E L epsilon he0 he1 hW hL + refine ⟨ht.1,ht.2.trans ?_⟩ + nlinarith [tableCount_ge_one A] + · exact hb + +end +end ContingencyTables.RootedStoredEstimate + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7a562fa482a80c3adfa08f9f14457c568071e45 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedStoredHistory.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedStoredEstimate +import Mathlib.Data.List.GetD + +namespace OAI + +/-! # Stored rational outputs of the actual outer phases + +The initial record is at index zero. Later records are the outputs +stored in the finite history; the initial record also supplies every +unused future entry to the restart's multiplier function. +-/ + +namespace ContingencyTables.RootedStoredHistory + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionPhaseWords (Stored) +open RootedStoredEstimate RootedPhaseTrial +open CompanionTerminalMass (Endpoints tableCount) +open CompanionTerminalApplication (finalPhase) +open TwoLiftStates +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def lookup (A : Instance I J) (history : List (Stored A)) : ℕ → Stored A + | 0 => initialStored A + | i+1 => history.getD i (initialStored A) + +lemma lookup_snoc_old (A : Instance I J) (history : List (Stored A)) + (next : Stored A) (i : ℕ) (hi : i ≤ history.length) : + lookup A (history++[next]) i=lookup A history i := by + cases i with + | zero => rfl + | succ i => exact List.getD_append history [next] (initialStored A) i (by omega) + +lemma lookup_snoc_new (A : Instance I J) (history : List (Stored A)) (next : Stored A) : + lookup A (history++[next]) (history.length+1)=next := by + simp only [lookup,List.getD_append_right history [next] (initialStored A) history.length le_rfl, + Nat.sub_self,List.getD_cons_zero] + +lemma lookup_future (A : Instance I J) (history : List (Stored A)) (i : ℕ) + (hi : history.length < i) : lookup A history i=initialStored A := by + cases i with + | zero => omega + | succ i => exact List.getD_eq_default history (initialStored A) (by omega) + +def Good (A : Instance I J) (R : RootedCompletion.Selection A.T) (xi : ℚ) (eta : ℝ) + (history : List (Stored A)) : Prop := + ∀ i,i < history.length → + ValidOutput A R i (lookup A history i) xi eta (lookup A history (i+1)) + +lemma good_nil (A : Instance I J) (R : RootedCompletion.Selection A.T) (xi : ℚ) (eta : ℝ) : + Good A R xi eta [] := by + intro i hi + simp at hi + +lemma good_snoc (A : Instance I J) (R : RootedCompletion.Selection A.T) (xi : ℚ) (eta : ℝ) + (history : List (Stored A)) (next : Stored A) : + Good A R xi eta (history++[next]) ↔ + Good A R xi eta history ∧ + ValidOutput A R history.length (lookup A history history.length) xi eta next := by + constructor + · intro h + constructor + · intro i hi + have hstep := h i (by simp; omega) + rw [lookup_snoc_old A history next i (by omega), + lookup_snoc_old A history next (i+1) (by omega)] at hstep + exact hstep + · have hstep := h history.length (by simp) + rw [lookup_snoc_old A history next history.length le_rfl, + lookup_snoc_new] at hstep + exact hstep + · rintro ⟨hold,hnext⟩ i hi + have hi' : i ≤ history.length := by simpa using Nat.le_of_lt_succ (by simpa using hi) + by_cases heq : i=history.length + · subst i + rw [lookup_snoc_old A history next history.length le_rfl,lookup_snoc_new] + exact hnext + · have hlt : i < history.length := by omega + rw [lookup_snoc_old A history next i hi', + lookup_snoc_old A history next (i+1) (by omega)] + exact hold i hlt + +lemma good_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (xi : ℚ) (eta : ℝ) + (history : List (Stored A)) (hg : Good A R xi eta history) (i : ℕ) : + (∀ p q,0 < (lookup A history i).multiplier p q) ∧ + 0 < (lookup A history i).estimate := by + by_cases hi : i ≤ history.length + · cases i with + | zero => exact initialStored_positive A R + | succ i => + have h := hg i (by omega) + exact ⟨h.1,h.2.1⟩ + · rw [lookup_future A history i (by omega)] + exact initialStored_positive A R + +lemma good_multipliers (A : Instance I J) (R : RootedCompletion.Selection A.T) (xi : ℚ) (eta : ℝ) + (history : List (Stored A)) (hg : Good A R xi eta history) (i : ℕ) + (hi : i ≤ history.length) : + GoodMultipliers pairs (RootedAnnealing.weight A R i) + (fun p q => ((lookup A history i).multiplier p q:ℝ)) := by + cases i with + | zero => exact initialStored_good A R + | succ i => exact (hg i (by omega)).2.2.1 + +/-- The rational value actually stored at the terminal history index +has the counting guarantee whenever every executed update is valid. -/ +theorem count_accuracy (A : Instance I J) (R : RootedCompletion.Selection A.T) + (E : Endpoints A) (L : ℕ) (epsilon : ℝ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (hW : 20*A.d ≤ A.W) (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) + (xi : ℚ) (eta : ℝ) + (herr : (finalPhase A L epsilon:ℝ)*(4*(xi:ℝ)+4*eta) ≤ epsilon/50) + (history : List (Stored A)) (hlen : history.length=finalPhase A L epsilon) + (hg : Good A R xi eta history) : + (1-epsilon)*tableCount A ≤ ((lookup A history history.length).estimate:ℝ) ∧ + ((lookup A history history.length).estimate:ℝ) ≤ (1+epsilon)*tableCount A := by + rw [hlen] + exact stored_count_accuracy A R E L epsilon he0 he1 hW hL (lookup A history) rfl xi eta + herr (fun j hj => hg j (by simpa only [hlen] using hj)) + +end +end ContingencyTables.RootedStoredHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..66e7b2e7a0e213d7aa10acede8e19ee648204739 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetMixing.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTargetTrace +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTrace +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetMixing + +namespace OAI + +/-! # Actual selected-root dyadic trace mixing and warm restart schedule -/ + +namespace ContingencyTables.RootedTargetMixing + +open CommonBasesFPRAS CompanionFactorialApplication RootedBooleanPhase RootedTargetTrace +open RootedTraceWords RootedAnnealing RootedWarmStart CompanionRationalUpdates TwoLiftStates +open DegreeCompletion ObservableBounds +open CompanionBooleanPhase (State slowdown slowdown_bounds) +open CompanionConcentration (pairs_ne_nil square_width_one_le) +open CompanionTargetMixing (restartTime restart_schedule) +open scoped BigOperators Classical + +noncomputable section + +private theorem trace_exit_congr {X : Type*} [Fintype X] + (C D : FiniteChain X) (B : X → Prop) [Nonempty (FiniteChain.Inside B)] + (h : C=D) + (hC : ∀ x : FiniteChain.Outside B,∃ y : FiniteChain.Inside B,0 (w p q:ℝ)) (weight A R j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A R j) + +theorem literalTrace_eq_completed (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 (w p q:ℝ)) + (fun p q => by exact_mod_cast hw p q) := by + let := plainIndex_nonempty (pairs : List (Pair A)) PairedLabels.fresh PairedLabels.cover + let F := completeDegree (weight A R j) (pairs : List (Pair A)).length + have hF := completeDegree_positive (weight A R j) (pairs : List (Pair A)).length + (actual_degree A R j).1 + have h := trace_exit_congr (referenceChain A R j hp w hw) + (metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) F (fun p q => by exact_mod_cast hw p q) hF) + (plainPredicate pairs) (referenceChain_eq_completed A R j hp w hw) + (metropolis_plain_exit pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) (weight A R j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A R j)) + (metropolis_plain_exit pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) F (fun p q => by exact_mod_cast hw p q) hF) + exact h + +private lemma literalTrace_poincare (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 (w p q:ℝ))) + (H : PlainIndex (pairs : List (Pair A)) → ℝ) : + (literalTrace A R j hp w hw).variance H≤ + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)* + (literalTrace A R j hp w hw).energy H := by + rw [literalTrace_eq_completed] + exact RootedTrace.trace_poincare A R j hp (fun p q => (w p q:ℝ)) hgood H + +theorem targetTrace_poincare (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (hp : 0 (w p q:ℝ))) + (H : PlainIndex (pairs : List (Pair A)) → ℝ) : + (RootedTargetTrace.actualTrace A R j hp w hw).variance H≤ + (2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))* + (RootedTargetTrace.actualTrace A R j hp w hw).energy H := by + let := plainIndex_nonempty (pairs : List (Pair A)) PairedLabels.fresh PairedLabels.cover + have hnonneg : 0≤observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + unfold observableConstant + positivity + have hh := FiniteChainSlowdown.trace_variance_bound (referenceChain A R j hp w hw) + (plainPredicate pairs) (sourceKilled A R j hp w hw) (by intro x y; rfl) + (slowdown A) (by linarith [(slowdown_bounds A hp).1]) (slowdown_bounds A hp).2 + (slowdown_bounds A hp).1 + (observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)) hnonneg H + (literalTrace_poincare A R j hp w hw hgood H) + exact hh + +theorem target_point_mixing (A : Instance I J) (R : RootedCompletion.Selection A.T) (H K j : ℕ) (hj : j≤H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^K) + (hp : 0 (w p q:ℝ))) (t : ℕ) + (x y : PlainIndex (pairs : List (Pair A))) : + |((RootedTargetTrace.actualTrace A R j hp w hw).kernel.power t).P x y/ + law A R j y.val.val-1|≤ + Real.exp (-(t:ℝ)/(2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/ + CompanionTrace.minimumMass A H K := by + have hpR : (1:ℝ)≤Fintype.card (Labels A) := by exact_mod_cast hp + have hK : 1≤2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + have hh := observableConstant_lower (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + have hp5 : (1:ℝ)≤(Fintype.card (Labels A):ℝ)^5 := one_le_pow₀ hpR + linarith + have hmin (S : PlainIndex (pairs : List (Pair A))) : + CompanionTrace.minimumMass A H K≤(RootedTargetTrace.actualTrace A R j hp w hw).π S := by + rw [actualTrace_pi] + have hh := RootedTrace.trace_minimum A R H K j hj hB hp + (fun p q => (w p q:ℝ)) (fun p q => by exact_mod_cast hw p q) S + rw [RootedTrace.trace_pi] at hh + exact hh + have hh := (RootedTargetTrace.actualTrace A R j hp w hw).kernel_point_mixing + (2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)) + (CompanionTrace.minimumMass A H K) hK (CompanionTrace.minimumMass_positive A H K) + hmin (targetTrace_poincare A R j hp w hw hgood) t x y + rwa [actualTrace_pi] at hh + +/-- The exact dyadic trace reaches the required two-warm law at the +explicit doubled schedule, including subprobability incoming laws. -/ +theorem restart_warm (A : Instance I J) (R : RootedCompletion.Selection A.T) (H K j : ℕ) (hj : j≤H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^K) + (hp : 0 (w p q:ℝ))) + (nu : PlainIndex (pairs : List (Pair A)) → ℝ) (hnu : ∀ S,0≤nu S) + (hmass : ∑ S,nu S≤1) (y : PlainIndex (pairs : List (Pair A))) : + ((RootedTargetTrace.actualTrace A R j hp w hw).kernel.power (restartTime A H K)).push nu y≤ + 2*law A R j y.val.val := by + have hy : 0 mul_le_mul_of_nonneg_left (hrow x) (hnu x)) + _ = (∑ x,nu x)*(2*law A R j y.val.val) := by rw [Finset.sum_mul] + _ ≤ _ := by nlinarith + +end +end ContingencyTables.RootedTargetMixing + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetTrace.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..5de9be120d388047d8e8507edf849d842b6770ba --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTargetTrace.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTraceWords +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmStart +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetTrace + +namespace OAI + +/-! # Selected-root dyadic trace return and explicit warm cap estimates -/ + +namespace ContingencyTables.RootedTargetTrace + +open CommonBasesFPRAS CompanionFactorialApplication RootedBooleanPhase RootedTraceWords +open CompanionCappedReturn RootedAnnealing RootedWarmStart TwoLiftStates +open CompanionBooleanPhase (State slowdown slowdown_bounds) +open CompanionConcentration (pairs_ne_nil) +open CompanionTargetTrace (capSteps) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def actualTrace (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ)) (weight A R j) := by + exact metropolis_insideMass pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A R j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A R j) + +theorem actualTrace_pi (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ)) (weight A R j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A R j) S + exact h + +theorem insideMass_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) : + 1/(5*(Fintype.card (Labels A):ℝ)^2)≤ + (targetChain A R j hp w hw).insideMass (plainPredicate pairs) := by + rw [insideMass_eq] + have h := plain_mass_lower pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A R j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A R j) hgood.upper + simpa only [PairedLabels.length,RootedWarmStart.total] using h + +private theorem warm_div_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) + (U : ℝ) (hU : 0≤U) : + U/(targetChain A R j hp w hw).insideMass (plainPredicate pairs)≤ + 5*(Fintype.card (Labels A):ℝ)^2*U := by + have hpR : (0:ℝ) (w p q:ℝ))) + (phi : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) → ℝ) + (hphi : ∀ S,0≤phi S ∧ phi S≤1) (n : ℕ) (hn : 0 phi (returnDefault (plainPredicate pairs) S xs))- + (∑ T,(targetChain A R j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A R j hp w hw) S T*phi T)|)≤ + (5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ) := by + let := plainIndex_nonempty (pairs : List (CompanionRationalUpdates.Pair A)) + PairedLabels.fresh PairedLabels.cover + have hh := warm_returnDefault_error (targetChain A R j hp w hw) (plainPredicate pairs) + (targetKilled A R j hp w hw) (targetKilled_matches A R j hp w hw) phi hphi n hn nu hnu U + (by + intro S + have hs := hwarm S + rw [←actualTrace_pi A R j hp w hw S] at hs + simpa only [actualTrace] using hs) + exact hh.trans (div_le_div_of_nonneg_right (warm_div_mass A R j hp w hw hgood U hU) + (Nat.cast_nonneg n)) + +theorem four_warm_cap_error (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) + (phi : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) → ℝ) + (hphi : ∀ S,0≤phi S ∧ phi S≤1) (budget : ℕ) (hb : 0 phi (returnDefault (plainPredicate pairs) S xs))- + (∑ T,(targetChain A R j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A R j hp w hw) S T*phi T)|)≤1/(budget:ℝ) := by + have hn : 0 hh t) + _ = (Fintype.card (TreeCell A):ℝ)*((4*gamma*K:ℝ)*physicalMass A R alpha) := by simp + _ ≤ (A.d:ℝ)*((4*gamma*K:ℝ)*physicalMass A R alpha) := + mul_le_mul_of_nonneg_right (by exact_mod_cast treeCell_card_le A) (by positivity) + _ = _ := by ring + +lemma mass_le_table_far_near (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha gamma : ℝ) (K : ℕ) + (ha : 0 < alpha) (hg1 : gamma ≤ 1) (hscale : 4*(K:ℝ) ≤ alpha*gamma) : + physicalMass A R alpha ≤ tableCount A+ + (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A R a + then actualWeight A R alpha a else 0)+ + ∑ t : TreeCell A,nearMass A R alpha t.val gamma := by + have hh := TerminalMassCover.mass_le_cover (actualWeight A R alpha) (Feasible A) + (fun a => 4*(K:ℝ) ≤ alpha*actualPenalty A R a) + (fun t : TreeCell A => fun a => a t.val ∈ cellPositions A t.val gamma) + (fun a => RootedPenalty.physicalWeight_nonnegative A R alpha _) + (fun a ha => feasible_weight_one A R alpha a ha) + (by + intro a hw hbad + rcases infeasible_in_far_or_near A R alpha gamma K ha hg1 hscale a hw hbad with hf|⟨t,ht,hn⟩ + · exact Or.inl hf + · exact Or.inr ⟨⟨t,ht⟩,hn⟩) + change physicalMass A R alpha ≤ _ at hh + rw [feasible_sum_eq_tableCount] at hh + apply hh.trans_eq + congr 1 + apply Finset.sum_congr rfl + intro t _ + unfold nearMass + apply Finset.sum_congr rfl + intro a _ + by_cases ha : a t.val∈cellPositions A t.val gamma <;> simp only [ha,ite_true,ite_false] + +/-- The terminal normalizer estimate follows from the finite table +bijection, root integrality, far bound and tree-marginal estimates. +The manuscript's explicit choices of K, gamma and the final coefficient +satisfy its arithmetic conditions. -/ +theorem terminal_count_estimate (A : Instance I J) (R : RootedCompletion.Selection A.T) (E : Endpoints A) + (alpha gamma epsilon : ℝ) (B K : ℕ) + (ha : 0 < alpha) (hg : 0 < gamma) (hg1 : gamma ≤ 1) + (he : 0 < epsilon) (he1 : epsilon < 1) + (hscale : 4*(K:ℝ) ≤ alpha*gamma) (hnear : 4*(A.d:ℝ)*gamma*K ≤ epsilon/128) + (hfar : (2:ℝ)^(-(3*K:ℕ):ℝ) ≤ epsilon/128) + (hW : 20*A.d ≤ A.W) (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) + (hBK : 2*B ≤ K) (hK : 0 < K) : + tableCount A ≤ CommonBasesFPRAS.slotTotal TwoLiftStates.pairs (RootedFactorialApplication.f A R alpha) ∅ ∧ + CommonBasesFPRAS.slotTotal TwoLiftStates.pairs (RootedFactorialApplication.f A R alpha) ∅ ≤ (1+epsilon/32)*tableCount A := by + rw [normalizer_eq_physical_mass] + have hZM : tableCount A ≤ physicalMass A R alpha := table_count_le_mass A R alpha + have hM1 := (tableCount_ge_one A).trans hZM + have hM : 0 ≤ physicalMass A R alpha := by linarith + have hcover := mass_le_table_far_near A R alpha gamma K ha hg1 hscale + have hfarMass := (far_mass_le A R alpha B K hW hB hBK).trans hfar + have hfarScaled : (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A R a + then actualWeight A R alpha a else 0) ≤ (epsilon/128)*physicalMass A R alpha := by + exact hfarMass.trans (by + simpa only [mul_one] using mul_le_mul_of_nonneg_left hM1 + (show 0 ≤ epsilon/128 by positivity)) + have hnearMass := total_near_mass_le A R E alpha gamma ha.le hg hW B K hB hBK hK + have hnearScaled : (∑ t : TreeCell A,nearMass A R alpha t.val gamma) ≤ + (epsilon/128)*physicalMass A R alpha := + hnearMass.trans (mul_le_mul_of_nonneg_right hnear hM) + have hbad : physicalMass A R alpha ≤ tableCount A+(epsilon/64)*physicalMass A R alpha := by + linarith + exact TerminalMassCover.relative_count_bound (tableCount A) (physicalMass A R alpha) epsilon + (by linarith [tableCount_ge_one A]) he he1 hZM hbad + +end ContingencyTables.RootedTerminalMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTerminalRegions.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTerminalRegions.lean new file mode 100644 index 0000000000000000000000000000000000000000..a53d4c5178b689db27f3333246afa4df79765805 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTerminalRegions.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalTables +import OAI.Combinatorics.ContingencyTables.Rooted.RootedNearMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalRegions + +namespace OAI + +/-! # Selected-root infeasibility lies in the literal far or near region -/ + +namespace ContingencyTables.RootedTerminalRegions + +open scoped BigOperators Classical +open CompanionFactorialApplication CompanionPhysicalTables RootedFarMass RootedNearMass +open ForestPenaltyApplication TreeMarginalSignature BalancedCellFibres EqualitySoftening +open CompanionTerminalRegions (integerDeviation deviation_eq_integer nonTree_bounded + treePenalty_nonnegative physicalRow_eq_table) +open CompanionNearMass (cellPositions) + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma rootPenalty_nonnegative (A : Instance I J) (R : RootedCompletion.Selection A.T) (a : Profiles (cellWidth A)) : + 0 ≤ RootedPenalty.rootPenalty A R (BalancedCellFibres.profile (cellWidth A) a) := by + unfold RootedPenalty.rootPenalty + apply Finset.sum_nonneg + intro v _ + split_ifs <;> first | exact abs_nonneg _ | exact le_rfl + +lemma root_deviation_le_penalty (A : Instance I J) (R : RootedCompletion.Selection A.T) (a : Profiles (cellWidth A)) (v : I⊕J) + (hv : RootedPenalty.rootFlag R v=true) : |(integerDeviation A a v:ℝ)| ≤ actualPenalty A R a := by + have hh := Finset.single_le_sum + (f := fun g => if RootedPenalty.rootFlag R g then + |deviation (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) + A.r A.c (BalancedCellFibres.profile (cellWidth A) a) g| else 0) + (fun g _ => by split_ifs <;> first | exact abs_nonneg _ | exact le_rfl) + (Finset.mem_univ v) + simp only [hv,ite_true,deviation_eq_integer] at hh + exact hh.trans (by + unfold actualPenalty RootedPenalty.penalty RootedPenalty.rootPenalty RootedPenalty.ell RootedPenalty.widths + simp_rw [deviation_eq_integer] + linarith [treePenalty_nonnegative A a]) + +lemma tree_distance_le_penalty (A : Instance I J) (R : RootedCompletion.Selection A.T) (a : Profiles (cellWidth A)) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) : + max 0 (max (-(physicalTable A a t.1 t.2:ℝ)) + ((physicalTable A a t.1 t.2:ℝ)-A.b t.1 t.2))/(A.b t.1 t.2:ℝ) ≤ actualPenalty A R a := by + let z := BalancedCellFibres.profile (cellWidth A) a + let D : I → J → ℝ := fun i j => if A.T.Adj (.inl i) (.inr j) then + affineDistance (ForestLiteralCount.lower A.T A.d A.b i j) 1 (A.b i j) (z ((i,j),false)) / + (A.b i j:ℝ) else 0 + have hD (i : I) (j : J) : 0 ≤ D i j := by + dsimp only [D] + split_ifs + · exact div_nonneg (le_max_left _ _) (Nat.cast_nonneg _) + · exact le_rfl + have hinner := Finset.single_le_sum (fun j _ => hD t.1 j) (Finset.mem_univ t.2) + have houter := Finset.single_le_sum + (f := fun i => ∑ j,D i j) + (fun i _ => Finset.sum_nonneg (fun j _ => hD i j)) (Finset.mem_univ t.1) + have hh : D t.1 t.2 ≤ treePenalty A.T A.b (ForestLiteralCount.lower A.T A.d A.b) z := + hinner.trans houter + dsimp only [D] at hh + rw [ite_eq_left ht] at hh + simp only [affineDistance,mul_one] at hh + have hrow := physicalRow_eq_table A a t.1 t.2 + change (ForestLiteralCount.lower A.T A.d A.b t.1 t.2:ℝ)+(z ((t.1,t.2),false):ℝ)=_ at hrow + rw [hrow] at hh + exact hh.trans (by + unfold actualPenalty RootedPenalty.penalty RootedPenalty.ell + linarith [rootPenalty_nonnegative A R a]) + +/-- Positive mass and penalty below one force every literal margin to +hold: nonroots are exact indicators and root discrepancies are integral. -/ +lemma margins_of_small_penalty (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) + (a : Profiles (cellWidth A)) (hw : 0 < actualWeight A R alpha a) + (hp : actualPenalty A R a < 1) : + (∀ i,(∑ j,physicalTable A a i j)=A.r i) ∧ + (∀ j,(∑ i,physicalTable A a i j)=A.c j) := by + have hnonroot : ∀ v,RootedPenalty.rootFlag R v=false → integerDeviation A a v=0 := by + have hh := hw + unfold actualWeight at hh + rw [RootedPenalty.exact_eq] at hh + by_cases h : ∀ g,RootedPenalty.rootFlag R g=false → + deviation (RootedPenalty.ell A) (RootedPenalty.widths A) + A.r A.c (BalancedCellFibres.profile (cellWidth A) a) g=0 + · intro v hv + have hz := h v hv + change deviation (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c + (BalancedCellFibres.profile (cellWidth A) a) v=0 at hz + rw [deviation_eq_integer] at hz + exact_mod_cast hz + · rw [ite_eq_right h] at hh + exact False.elim ((lt_irrefl (0:ℝ)) hh) + have hall (v : I⊕J) : integerDeviation A a v=0 := by + cases hv : RootedPenalty.rootFlag R v + · exact hnonroot v hv + · have hh := (root_deviation_le_penalty A R a v hv).trans_lt hp + have hz : |integerDeviation A a v| < (1:ℤ) := by exact_mod_cast hh + have hz' := abs_lt.mp hz + omega + constructor + · intro i + have hh := hall (.inl i) + simpa only [integerDeviation,Sum.elim_inl,sub_eq_zero] using hh + · intro j + have hh := hall (.inr j) + simpa only [integerDeviation,Sum.elim_inr,sub_eq_zero] using hh + +theorem infeasible_in_far_or_near (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha gamma : ℝ) (K : ℕ) + (ha : 0 < alpha) (hg1 : gamma ≤ 1) (hscale : 4*(K:ℝ) ≤ alpha*gamma) + (a : Profiles (cellWidth A)) (hw : 0 < actualWeight A R alpha a) (hbad : ¬Feasible A a) : + 4*(K:ℝ) ≤ alpha*actualPenalty A R a ∨ + ∃ t : I×J,A.T.Adj (.inl t.1) (.inr t.2) ∧ a t ∈ cellPositions A t gamma := by + by_cases hfar : 4*(K:ℝ) ≤ alpha*actualPenalty A R a + · exact Or.inl hfar + right + have hp : actualPenalty A R a < gamma := by + have hh : alpha*actualPenalty A R a < alpha*gamma := (lt_of_not_ge hfar).trans_le hscale + exact lt_of_mul_lt_mul_left hh ha.le + have hm := margins_of_small_penalty A R alpha a hw (hp.trans_le hg1) + have hcell : ¬∀ i j,0 ≤ physicalTable A a i j ∧ physicalTable A a i j ≤ A.b i j := by + intro hc + exact hbad ⟨hc,hm⟩ + obtain ⟨i,hi⟩ := not_forall.mp hcell + obtain ⟨j,hviol⟩ := not_forall.mp hi + have ht : A.T.Adj (.inl i) (.inr j) := by + by_contra ht + exact hviol (nonTree_bounded A a i j ht) + refine ⟨(i,j),ht,?_⟩ + have hb : (0:ℝ) < A.b i j := by exact_mod_cast (A.hlarge i j (A.hTG ht)).2 + have hd := (tree_distance_le_penalty A R a (i,j) ht).trans_lt hp + have hdist : max 0 (max (-(physicalTable A a i j:ℝ)) + ((physicalTable A a i j:ℝ)-A.b i j)) < gamma*A.b i j := (div_lt_iff₀ hb).mp hd + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + change ((physicalTable A a i j<0) ∧ -(physicalTable A a i j:ℝ) hviol ⟨hlo,hhi⟩),?_⟩ + exact (le_max_right _ _).trans (le_max_right _ _) |>.trans_lt hdist + · left + exact ⟨lt_of_not_ge hlo,(le_max_left _ _).trans (le_max_right _ _) |>.trans_lt hdist⟩ + +end ContingencyTables.RootedTerminalRegions + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTrace.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fddd34fe93e1d6a03b76aa469d5fc8390cf7f4a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTrace.lean @@ -0,0 +1,181 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmStart +import OAI.Combinatorics.ContingencyTables.Rooted.RootedObservableApplication +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrace + +namespace OAI + +/-! # Trace restart bounds for the selected-root companion weights + +The actual factorial lifts supply the trace inverse gap, and exact +binomial cancellation supplies its minimum mass. The restart stage +therefore has a two-warm endpoint from every initial subprobability law. +-/ + +namespace ContingencyTables.RootedTrace + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication RootedAnnealing TwoLiftStates +open CompanionAnnealing (scale scale_positive) +open CompanionTrace (integerConstant time minimumMass minimumMass_positive schedule_error) +open BinaryContraction DegreeCompletion TraceBounds ObservableBounds +open RootedWarmStart (actual_degree) +open CompanionConcentration (pairs_ne_nil square_width_one_le) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def trace (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) : FiniteChain (PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) := + metropolisTrace pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A R j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw (completeDegree_positive _ _ (actual_degree A R j).1) + +lemma trace_pi (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + (trace A R j hp w hw).π S=RootedWarmStart.law A R j S.val.val := by + exact completed_trace_pi pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (weight A R j) hw (actual_degree A R j).1 S + +private lemma actual_dual_degree (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) : + DegreePositive (RootedFactorialApplication.g A R ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length ∧ + AdditionProperty (RootedFactorialApplication.g A R ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length := by + have hg := RootedFactorialApplication.second_properties A R ((j:ℝ)/scale A) + (div_nonneg (Nat.cast_nonneg j) (scale_positive A).le) + simpa only [PairedLabels.length] using hg + +private lemma actual_plain_agreement (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (S : Set (Labels A×Bool)) (hS : PlainState pairs S) : + weight A R j S=RootedFactorialApplication.g A R ((j:ℝ)/scale A) S := by + exact (plain_lifts_agree (labelCell A) (RootedCountIdentification.h A R ((j:ℝ)/scale A)) S hS).symm + +private lemma actual_lift_comparison (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) + (S : Set (Labels A×Bool)) (hS : ChainState pairs S) : + weight A R j S≤(A.W:ℝ)^2*RootedFactorialApplication.g A R ((j:ℝ)/scale A) S := by + apply firstLift_le_square_secondLift (labelCell A) (RootedCountIdentification.h A R ((j:ℝ)/scale A)) S hS A.W + (by have hW := A.hW; omega) + · intro s + rw [label_width] + exact A.hsmall _ _ s.property + · exact (RootedCountIdentification.h_positive A R _ _).le + +private lemma omission_instance {X : Type*} [Fintype X] + (d e : DecidableEq X) (f : Set X → ℝ) (k : ℕ) + (h : @OmissionProperty X _ d f k) : @OmissionProperty X _ e f k := by + cases Subsingleton.elim d e + exact h + +private lemma addition_instance {X : Type*} [Fintype X] + (d e : DecidableEq X) (f : Set X → ℝ) (k : ℕ) + (h : @AdditionProperty X _ d f k) : @AdditionProperty X _ e f k := by + cases Subsingleton.elim d e + exact h + +private lemma trace_poincare_raw (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) + (H : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) : + (trace A R j hp w hw.positive).variance H ≤ + (2*(Fintype.card (Labels A):ℝ)^2*((Fintype.card (Labels A):ℝ)* + (1+8*(Fintype.card (Labels A):ℝ)*((A.W:ℝ)^2)^2)))* + (trace A R j hp w hw.positive).energy H := by + let d : DecidableEq (Labels A×Bool) := inferInstance + have hsigf := omission_instance (inferInstance : DecidableEq (Labels A×Bool)) d + (weight A R j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length (actual_degree A R j).2 + have hsigg := addition_instance (inferInstance : DecidableEq (Labels A×Bool)) d + (RootedFactorialApplication.g A R ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length + (actual_dual_degree A R j).2 + have hh := @omission_trace_poincare (Labels A×Bool) inferInstance d + pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover w (weight A R j) (RootedFactorialApplication.g A R ((j:ℝ)/scale A)) hw.positive + (actual_degree A R j).1 (actual_dual_degree A R j).1 + hsigf hsigg + ((A.W:ℝ)^2) (sq_nonneg _) hw.lower + (actual_plain_agreement A R j) (actual_lift_comparison A R j) H + change (trace A R j hp w hw.positive).variance H ≤ + (2*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)^2)* + (((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)* + (1+8*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)*((A.W:ℝ)^2)^2))* + (trace A R j hp w hw.positive).energy H at hh + have hcoef : (2*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)^2)* + (((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)* + (1+8*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)*((A.W:ℝ)^2)^2))= + 2*(Fintype.card (Labels A):ℝ)^2*((Fintype.card (Labels A):ℝ)* + (1+8*(Fintype.card (Labels A):ℝ)*((A.W:ℝ)^2)^2)) := by + rw [PairedLabels.length] + exact hh.trans_eq (congrArg (fun k : ℝ => k*(trace A R j hp w hw.positive).energy H) hcoef) + +theorem trace_poincare (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) + (H : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) : + (trace A R j hp w hw.positive).variance H ≤ + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)* + (trace A R j hp w hw.positive).energy H := by + have hpR : (1:ℝ) ≤ Fintype.card (Labels A) := by exact_mod_cast hp + have hcoef := trace_constant_le_observable (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + exact (trace_poincare_raw A R j hp w hw H).trans + (mul_le_mul_of_nonneg_right hcoef ((trace A R j hp w hw.positive).energy_nonneg H)) + +lemma trace_minimum (A : Instance I J) (R : RootedCompletion.Selection A.T) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + minimumMass A H K ≤ (trace A R j hp w hw).π S := by + rw [trace_pi] + apply le_trans _ (RootedWarmStart.plain_law_lower A R K j hB S.val.val S.property) + exact pow_le_pow_of_le_one (by norm_num : (0:ℝ) ≤ 1/2) (by norm_num) (by omega) + +/-- The pointwise error estimate has no new signature or minimum-mass +assumption: both are supplied by the actual count/lift application. -/ +theorem trace_point_mixing (A : Instance I J) (R : RootedCompletion.Selection A.T) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) (t : ℕ) + (x y : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + |((trace A R j hp w hw.positive).kernel.power t).P x y/ + RootedWarmStart.law A R j y.val.val-1| ≤ + Real.exp (-(t:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))/minimumMass A H K := by + let T := trace A R j hp w hw.positive + have hpR : (1:ℝ) ≤ Fintype.card (Labels A) := by exact_mod_cast hp + have hK : 1 ≤ observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + have hh := observableConstant_lower (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + have hp5 : (1:ℝ) ≤ (Fintype.card (Labels A):ℝ)^5 := one_le_pow₀ hpR + nlinarith + have hh := T.kernel_point_mixing _ _ hK (minimumMass_positive A H K) + (trace_minimum A R H K j hj hB hp w hw.positive) (trace_poincare A R j hp w hw) t x y + rwa [trace_pi] at hh + +/-- A stage with pointwise relative error at most one ends two-warm, +even when its incoming law is merely a subprobability law. -/ +theorem stage_warm (A : Instance I J) (R : RootedCompletion.Selection A.T) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A R j) w) (t : ℕ) + (ht : Real.exp (-(t:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))/minimumMass A H K ≤ 1) + (nu : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hnu : ∀ S,0 ≤ nu S) (hmass : ∑ S,nu S ≤ 1) + (y : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((trace A R j hp w hw.positive).kernel.power t).push nu y ≤ 2*RootedWarmStart.law A R j y.val.val := by + have hy : 0 < RootedWarmStart.law A R j y.val.val := + div_pos (weight_positive A R j _) (RootedWarmStart.total_positive A R j) + have hrow (x : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((trace A R j hp w hw.positive).kernel.power t).P x y ≤ + 2*RootedWarmStart.law A R j y.val.val := by + have hh := (le_abs_self _).trans ((trace_point_mixing A R H K j hj hB hp w hw t x y).trans ht) + apply (div_le_iff₀ hy).mp + linarith + calc + _ ≤ ∑ x,nu x*(2*RootedWarmStart.law A R j y.val.val) := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hrow x) (hnu x)) + _ = (∑ x,nu x)*(2*RootedWarmStart.law A R j y.val.val) := by rw [Finset.sum_mul] + _ ≤ _ := by nlinarith + +end ContingencyTables.RootedTrace + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTraceWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTraceWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..471d4e75ab3e1fda59fc24d46f36520c73de36aa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTraceWords.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedArithmeticStep +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceWords + +namespace OAI + +/-! # Actual bounded first-return words for the selected-root chain -/ + +namespace ContingencyTables.RootedTraceWords + +open CommonBasesFPRAS CompanionFactorialApplication RootedBooleanPhase +open RootedPhaseTrajectory CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates TwoLiftStates GridBoundary FirstSuccess ResidualMixture +open CompanionBooleanPhase (State stepBits slowdown slowdown_bounds) +open CompanionPhaseTrajectory (historyPrefix) +open CompanionTraceWords (eventIndicator firstHit return_event_expectation return_failure_expectation) +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def sourceKilled (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ)) (RootedAnnealing.weight A R j) + (fun p q => by exact_mod_cast hw p q) (RootedAnnealing.weight_positive A R j) + +def targetKilled (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 + if E (historyPrefix (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v w S bits)) + then (1:ℝ) else 0)= + uniformAverage (fun bits : Fin (N*stepBits A C K j k xi) → Bool => + if E (historyPrefix (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v w S bits)) + then (1:ℝ) else 0) := by + have hnew := FiniteLawMoments.word_expectation + (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v w S) + (fun a => if E (historyPrefix a) then (1:ℝ) else 0) + have hold := FiniteLawMoments.word_expectation + (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v w S) + (fun a => if E (historyPrefix a) then (1:ℝ) else 0) + rw [RootedArithmeticStep.recordedWalk_law] at hnew + rw [RootedBooleanPhase.recordedWalk_law] at hold + exact hnew.trans hold.symm + +theorem arithmetic_recorded_event_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + eventIndicator (E (historyPrefix + (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v w S bits))))≤ + (targetChain A R j hp w hw).pathExpectation N S (fun xs => eventIndicator (E xs))+ + N*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + exact (arithmetic_event_eq A R C K j k N hK hW xi v w S E).trans_le + (recorded_event_bound A R C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw N S E) + +/-- The concrete bounded return experiment has the capped trace event +bound plus one implementation error per used step. -/ +theorem returnWord_event (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + eventIndicator (∃ T,returnWord A R C K j k (n+1) hK hW xi v w S.val bits=some T ∧ E T))≤ + (∑ T,(targetChain A R j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A R j hp w hw) n S T*eventIndicator (E T))+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := arithmetic_recorded_event_bound A R C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val + (fun xs => ∃ T,firstHit (plainPredicate pairs) xs.tail=some T ∧ E T) + have ht := return_event_expectation (targetChain A R j hp w hw) (plainPredicate pairs) + (targetKilled A R j hp w hw) (targetKilled_matches A R j hp w hw) E n S + have hfinal := he.trans_eq (congrArg (fun t : ℝ => t+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)) ht) + exact hfinal + +/-- Capping the concrete word experiment adds the exact reference +nonreturn probability and the accumulated step-implementation error. -/ +theorem returnWord_failure (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 + eventIndicator (returnWord A R C K j k (n+1) hK hW xi v w S.val bits=none))≤ + 1-(∑ T,(targetChain A R j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A R j hp w hw) n S T)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := arithmetic_recorded_event_bound A R C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val (fun xs => firstHit (plainPredicate pairs) xs.tail=none) + have ht := return_failure_expectation (targetChain A R j hp w hw) (plainPredicate pairs) + (targetKilled A R j hp w hw) (targetKilled_matches A R j hp w hw) n S + have hfinal := he.trans_eq (congrArg (fun t : ℝ => t+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)) ht) + exact hfinal + +end +end ContingencyTables.RootedTraceWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..d150d8be459784b6fab21c2807f876be5ab1ce2f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeBounds.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeMarginal +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalBounds + +namespace OAI + +/-! # Selected-root physical tree interpolation after the equality limit -/ + +namespace ContingencyTables.RootedTreeMarginal + +open scoped BigOperators Classical Topology +open Filter CompanionFactorialApplication ForestPenaltyApplication +open LargePairEnumeration BalancedFamily BalancedBox EqualitySoftening RowColumnPenalties +open IntegerWeightedTransport +open TreeMarginalSignature (cellWidth otherWidths coordinateEquiv other_card_le_full) + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem scalar_soft_le_two_pow (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hK : 2*B ≤ K) (k : ℕ) : + scalarSoft A R alpha L t k ≤ (2:ℝ)^K := by + have hcard := (other_card_le_full A t).trans + (ForestBoxCardinality.cardinality_le_two_pow A hW B K hB hK) + have hu := BalancedEnumeration.eliminate_le_card (widths (otherWidths A t)) + (fun z => softenedWeight cellLine (RootedPenalty.rootFlag R) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) L (z ∘ (coordinateEquiv A t).symm)) + (by + intro z + apply softenedWeight_le_one + · exact fun _ => ha + · intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + · exact hL) + (childProfile (cellWidth A t) k) + exact hu.trans (by exact_mod_cast hcard) + +theorem scalar_exact_nonnegative (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (k : ℕ) (hk : k ≤ cellWidth A t) : + 0 ≤ scalarExact A R alpha t k := by + apply ge_of_tendsto (scalar_tendsto A R alpha t k) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + exact (scalar_positive A R alpha L t ha hL k hk).le + +lemma scalar_exact_le_soft (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) (k : ℕ) : + scalarExact A R alpha t k ≤ scalarSoft A R alpha L t k := by + unfold scalarExact exactMarginal scalarSoft soft + simp only [BalancedEnumeration.eliminate_eq_sum] + apply Finset.sum_le_sum + intro a _ + exact exactWeight_le_softenedWeight _ _ _ _ _ _ _ _ _ _ _ + +/-- A feasible table attaining the endpoint cell value supplies the +lower bound for finite interpolation through the equality limit. -/ +theorem scalar_exact_half_window (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 1 ≤ K) (hN : 0 < N) (hkN : k+N ≤ cellWidth A t) + (hend : 1 ≤ scalarExact A R alpha t (k+N)) + (r : ℕ) (hr : r*K ≤ N) : + scalarExact A R alpha t k/2 ≤ scalarExact A R alpha t (k+r) := by + apply le_of_tendsto_of_tendsto ((scalar_tendsto A R alpha t k).div_const 2) + (scalar_tendsto A R alpha t (k+r)) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + apply positive_sequence_half_window (fun q => scalarSoft A R alpha L t (k+q)) N K hK hN + · intro q hq + exact scalar_positive A R alpha L t ha hL _ (by omega) + · intro q hq + have hh := scalar_logConcave A R alpha L t ha hL (k+q) (by omega) + simpa only [Nat.add_assoc] using hh + · exact hend.trans (scalar_exact_le_soft A R alpha L t (k+N)) + · simpa only [Nat.add_zero] using scalar_soft_le_two_pow A R alpha L t ha hL hW B K hB hBK k + · exact hr + +/-- The same physical half-height estimate when the feasible endpoint +lies to the left of an exterior tree position. -/ +theorem scalar_exact_backward_half_window (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 1 ≤ K) (hN : 0 < N) (hNk : N ≤ k) (hk : k ≤ cellWidth A t) + (hend : 1 ≤ scalarExact A R alpha t (k-N)) (r : ℕ) (hr : r*K ≤ N) : + scalarExact A R alpha t k/2 ≤ scalarExact A R alpha t (k-r) := by + apply le_of_tendsto_of_tendsto ((scalar_tendsto A R alpha t k).div_const 2) + (scalar_tendsto A R alpha t (k-r)) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + apply positive_sequence_half_window (fun q => scalarSoft A R alpha L t (k-q)) N K hK hN + · intro q _ + exact scalar_positive A R alpha L t ha hL _ ((Nat.sub_le _ _).trans hk) + · intro q hq + have hqk : q+2 ≤ k := hq.trans hNk + have hh := scalar_logConcave A R alpha L t ha hL (k-(q+2)) (by omega) + rw [show k-(q+2)+2=k-q by omega,show k-(q+2)+1=k-(q+1) by omega] at hh + simpa only [mul_comm] using hh + · exact hend.trans (scalar_exact_le_soft A R alpha L t (k-N)) + · simpa only [Nat.sub_zero] using scalar_soft_le_two_pow A R alpha L t ha hL hW B K hB hBK k + · exact hr + +/-- The actual physical exterior point has normalized mass at most +2K/b whenever a feasible unit-mass endpoint lies at least b places to +its right, after eliminating all soft parameters. -/ +theorem scalar_exact_forward_point_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N b : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 0 < K) (hN : 0 < N) (hb : 0 < b) (hbN : b ≤ N) + (hkN : k+N ≤ cellWidth A t) (hend : 1 ≤ scalarExact A R alpha t (k+N)) : + scalarExact A R alpha t k/(∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A R alpha t q) ≤ + (2*K:ℝ)/b := by + have hnonneg : ∀ q,q ≤ cellWidth A t → 0 ≤ scalarExact A R alpha t q := + scalar_exact_nonnegative A R alpha t ha + have hmass := Finset.single_le_sum + (fun q hq => hnonneg q (by have := Finset.mem_range.mp hq; omega)) + (Finset.mem_range.mpr (show k+N < cellWidth A t+1 by omega)) + have hC : 0 < ∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A R alpha t q := by + linarith + apply half_window_mass_bound (scalarExact A R alpha t) (cellWidth A t) k N K b hK hb hbN hkN + hnonneg hC + intro r hr + exact scalar_exact_half_window A R alpha t ha hW B K k N hB hBK hK hN hkN hend r hr + +theorem scalar_exact_backward_point_bound (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N b : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 0 < K) (hN : 0 < N) (hb : 0 < b) (hbN : b ≤ N) + (hNk : N ≤ k) (hk : k ≤ cellWidth A t) (hend : 1 ≤ scalarExact A R alpha t (k-N)) : + scalarExact A R alpha t k/(∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A R alpha t q) ≤ + (2*K:ℝ)/b := by + let U := cellWidth A t + let a : ℕ → ℝ := fun q => scalarExact A R alpha t (U-q) + have hsum : (∑ q ∈ Finset.range (U+1),a q)= + ∑ q ∈ Finset.range (U+1),scalarExact A R alpha t q := by + simpa only [a,Nat.add_sub_cancel] using Finset.sum_range_reflect (scalarExact A R alpha t) (U+1) + have hnonneg : ∀ q,q ≤ U → 0 ≤ a q := by + intro q _ + exact scalar_exact_nonnegative A R alpha t ha _ (Nat.sub_le _ _) + have hend' : 1 ≤ a (U-k+N) := by + change 1 ≤ scalarExact A R alpha t (U-(U-k+N)) + rw [show U-(U-k+N)=k-N by dsimp only [U] at *; omega] + exact hend + have hmass := Finset.single_le_sum + (fun q hq => hnonneg q (by have := Finset.mem_range.mp hq; omega)) + (Finset.mem_range.mpr (show U-k+N < U+1 by dsimp only [U] at *; omega)) + have hC : 0 < ∑ q ∈ Finset.range (U+1),a q := by linarith + have hp := half_window_mass_bound a U (U-k) N K b hK hb hbN + (by dsimp only [U] at *; omega) hnonneg hC (by + intro r hr + have hrN : r ≤ N := by nlinarith + change scalarExact A R alpha t (U-(U-k))/2 ≤ scalarExact A R alpha t (U-(U-k+r)) + rw [show U-(U-k)=k by dsimp only [U] at *; omega, + show U-(U-k+r)=k-r by dsimp only [U] at *; omega] + exact scalar_exact_backward_half_window A R alpha t ha hW B K k N hB hBK hK hN hNk hk hend r hr) + change scalarExact A R alpha t (U-(U-k))/(∑ q ∈ Finset.range (U+1),a q) ≤ (2*K:ℝ)/b at hp + rw [show U-(U-k)=k by dsimp only [U] at *; omega,hsum] at hp + exact hp + +end ContingencyTables.RootedTreeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeExteriorMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeExteriorMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..58dcf098b1bdae7c5aef201481dbbf251f782d2d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeExteriorMass.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeBounds +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeFeasibleMass +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalNormalizer +import OAI.Combinatorics.ContingencyTables.Rooted.TreeExteriorPositions + +namespace OAI + +/-! # Selected-root exterior fibres normalized by their actual physical mass -/ + +namespace ContingencyTables.RootedTreeMarginal + +open scoped BigOperators Classical +open CompanionFactorialApplication RootedPhysicalNormalizer BalancedCellFibres +open ForestPenaltyApplication ForestLiteralCount +open TreeMarginalSignature (cellWidth) + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma scalar_sum_eq_physicalMass (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) : + (∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A R alpha t q)=physicalMass A R alpha := by + rw [← Fin.sum_univ_eq_sum_range] + simp_rw [exact_eq_fibre] + exact sum_fibre (cellWidth A) + (RootedPenalty.physicalWeight A R alpha) t + +/-- A lower exterior tree position is controlled by the actual feasible +table attaining its upper bound, exactly as in the manuscript. -/ +theorem lower_exterior_point (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=(A.b t.1 t.2:ℤ)) (k : ℕ) (hk : k < 10*A.d*A.b t.1 t.2) : + scalarExact A R alpha t k/physicalMass A R alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + let N := 10*A.d*A.b t.1 t.2+A.b t.1 t.2-k + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hend := upper_tree_endpoint A R alpha t ht Y hY hr hc hy + have hkN : k+N=10*A.d*A.b t.1 t.2+A.b t.1 t.2 := by dsimp only [N]; omega + have hwidth : cellWidth A t=20*A.d*A.b t.1 t.2 := by simp only [cellWidth,width,ht,ite_true] + have hprod : A.b t.1 t.2 ≤ A.d*A.b t.1 t.2 := by have hd := A.hd; nlinarith + have hh := scalar_exact_forward_point_bound A R alpha t ha hW B K k N (A.b t.1 t.2) hB hBK hK + (by dsimp only [N]; omega) hb (by dsimp only [N]; omega) + (by rw [hkN,hwidth]; nlinarith) (by rw [hkN]; exact hend) + rwa [scalar_sum_eq_physicalMass] at hh + +theorem upper_exterior_point (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=0) (k : ℕ) + (hk : 10*A.d*A.b t.1 t.2+A.b t.1 t.2 < k) (hkU : k ≤ cellWidth A t) : + scalarExact A R alpha t k/physicalMass A R alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + let N := k-10*A.d*A.b t.1 t.2 + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hend := lower_tree_endpoint A R alpha t ht Y hY hr hc hy + have hkN : k-N=10*A.d*A.b t.1 t.2 := by dsimp only [N]; omega + have hh := scalar_exact_backward_point_bound A R alpha t ha hW B K k N (A.b t.1 t.2) hB hBK hK + (by dsimp only [N]; omega) hb (by dsimp only [N]; omega) (by dsimp only [N]; omega) + hkU (by rw [hkN]; exact hend) + rwa [scalar_sum_eq_physicalMass] at hh + +end ContingencyTables.RootedTreeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeFeasibleMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeFeasibleMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1935af63fe179aa14e4f663ecb47a843d251077 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeFeasibleMass.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeMarginal +import OAI.Combinatorics.ContingencyTables.Rooted.TreeFeasibleMass + +namespace OAI + +/-! # Actual feasible tables contribute unit selected-root fibre mass -/ + +namespace ContingencyTables.RootedTreeMarginal + +open scoped BigOperators Classical +open CompanionFactorialApplication ForestPenaltyApplication ForestLiteralCount +open BalancedCellFibres EqualitySoftening +open TreeMarginalSignature (cellWidth tableAssignment tableAssignment_row tableAssignment_column + tableAssignment_tree_index) + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem tableAssignment_unit (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i, (∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) : + RootedPenalty.physicalWeight A R alpha + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY))=1 := by + have hdev : ∀ g,deviation (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) g=0 := by + intro g + cases g with + | inl i => + simp only [deviation,Sum.elim_inl] + simp_rw [tableAssignment_row] + have hh : (∑ j,(Y i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast hr i + rw [hh,sub_self] + | inr j => + simp only [deviation,Sum.elim_inr] + simp_rw [tableAssignment_column] + have hh : (∑ i,(Y i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast hc j + rw [hh,sub_self] + have hlines : ∀ g,RootedPenalty.rootFlag R g=false → + deviation (RootedPenalty.ell A) (RootedPenalty.widths A) A.r A.c + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) g=0 := + fun g _ => hdev g + rw [RootedPenalty.exact_eq,ite_eq_left hlines] + have hp : RootedPenalty.penalty A R + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY))=0 := by + unfold RootedPenalty.penalty RootedPenalty.rootPenalty RootedPenalty.ell RootedPenalty.widths treePenalty + simp only [hdev,abs_zero,ite_self,Finset.sum_const_zero,zero_add] + apply Finset.sum_eq_zero + intro i _ + apply Finset.sum_eq_zero + intro j _ + have hy0 : (0:ℝ) ≤ Y i j := by exact_mod_cast (hY i j).1 + have hyb : (Y i j:ℝ) ≤ A.b i j := by exact_mod_cast (hY i j).2 + have hh := tableAssignment_row A Y hY i j + unfold affineDistance + simp only [mul_one] + change (if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(physicalRow (lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j)) + (physicalRow (lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j-A.b i j)) / + (A.b i j:ℝ) else 0)=0 + rw [hh,max_eq_left (max_le (neg_nonpos.mpr hy0) (sub_nonpos.mpr hyb))] + simp + rw [hp,mul_zero,Real.rpow_zero] + +/-- A feasible table supplies an actual unit summand at its retained +physical coordinate. No endpoint-mass oracle is assumed. -/ +theorem scalar_exact_ge_one_at_table (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) (t : I×J) : + 1 ≤ scalarExact A R alpha t (tableAssignment A Y hY t).val := by + rw [exact_eq_fibre] + have hh := Finset.single_le_sum + (f := fun a : Profiles (cellWidth A) => + if a t=tableAssignment A Y hY t then + RootedPenalty.physicalWeight A R alpha + (BalancedCellFibres.profile (cellWidth A) a) else 0) + (fun a _ => by split_ifs; exact RootedPenalty.physicalWeight_nonnegative A R alpha _; exact le_rfl) + (Finset.mem_univ (tableAssignment A Y hY)) + simp only [ite_true,tableAssignment_unit A R alpha Y hY hr hc] at hh + apply hh.trans_eq + unfold fibre + apply Finset.sum_congr + · ext a + simp + · intro a _ + rfl + +/-- Tight upper-cell attainment supplies the endpoint on the right of +every lower exterior tree value. -/ +theorem upper_tree_endpoint (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=(A.b t.1 t.2:ℤ)) : + 1 ≤ scalarExact A R alpha t (10*A.d*A.b t.1 t.2+A.b t.1 t.2) := by + have hi := tableAssignment_tree_index A Y hY t ht + rw [hy] at hi + push_cast at hi + have hindex : (tableAssignment A Y hY t).val=10*A.d*A.b t.1 t.2+A.b t.1 t.2 := by + exact_mod_cast (show ((tableAssignment A Y hY t).val:ℤ)= + ((10*A.d*A.b t.1 t.2+A.b t.1 t.2:ℕ):ℤ) by push_cast; omega) + rw [← hindex] + exact scalar_exact_ge_one_at_table A R alpha Y hY hr hc t + +/-- Tight lower-cell attainment supplies the endpoint on the left of +every upper exterior tree value. -/ +theorem lower_tree_endpoint (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=0) : + 1 ≤ scalarExact A R alpha t (10*A.d*A.b t.1 t.2) := by + have hi := tableAssignment_tree_index A Y hY t ht + rw [hy,zero_add] at hi + have hindex : (tableAssignment A Y hY t).val=10*A.d*A.b t.1 t.2 := by exact_mod_cast hi + rw [← hindex] + exact scalar_exact_ge_one_at_table A R alpha Y hY hr hc t + +end ContingencyTables.RootedTreeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeInputProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeInputProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..654b18758b5e7a4aec1d2cfed87bbb7908630e61 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeInputProgram.lean @@ -0,0 +1,160 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedDemandProgram + +namespace OAI + +/-! # Building tree-local inputs from the common raw arrays + +The graph, capacity array, baseline and stored views are shared across +all tree terms. A term uses only its pair of cell indices; the program +builds its offset frame and reads the free-grid coordinates in catalog +order. +-/ + +namespace ContingencyTables.RootedTreeInputProgram + +open MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms +open scoped Classical + +abbrev Context := RootedDemandProgram.Input +abbrev Input := Context×(ℕ×ℕ) + +def metadata (z : Input) : RootedForestCatalog.Data := z.1.1 +def metadataRealizer : Realizer metadata := composition first first +lemma polynomial_metadata : PolynomialTime metadataRealizer := + polynomial_composition polynomial_first polynomial_first + +def edge (z : Input) : FiniteGraphCutProgram.EdgeInput := + RootedForestCatalog.edge (metadata z,z.2) +def edgeRealizer : Realizer edge := + composition (pair metadataRealizer second) RootedForestCatalog.edgeRealizer +lemma polynomial_edge : PolynomialTime edgeRealizer := + polynomial_composition (polynomial_pair polynomial_metadata polynomial_second) + RootedForestCatalog.polynomial_edge + +def treeInput (z : Input) : RootedCellDataProgram.Input := + (((edge z,(metadata z).1.1.2),(metadata z).1.2), + (((metadata z).2,z.1.2.1),z.1.2.2)) +def treeInputRealizer : Realizer treeInput := + pair + (pair (pair edgeRealizer + (composition (f := metadata) (g := fun d : RootedForestCatalog.Data => d.1.1.2) + metadataRealizer (composition (composition first first) second))) + (composition (f := metadata) (g := fun d : RootedForestCatalog.Data => d.1.2) + metadataRealizer (composition first second))) + (pair (pair (composition (f := metadata) (g := fun d : RootedForestCatalog.Data => d.2) + metadataRealizer second) + (composition (composition first second) first)) + (composition (composition first second) second)) +theorem polynomial_treeInput : PolynomialTime treeInputRealizer := + polynomial_pair + (polynomial_pair (polynomial_pair polynomial_edge + (polynomial_composition polynomial_metadata (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second))) + (polynomial_composition polynomial_metadata (polynomial_composition polynomial_first polynomial_second))) + (polynomial_pair (polynomial_pair (polynomial_composition polynomial_metadata polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first)) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + +abbrev TermBundle := (RootedCellDataProgram.Input×List (ℕ×ℕ))×List ℕ + +def termAt (z : TermBundle×ℕ) : RootedForestDataProgram.TermInput := + (RootedCellDataProgram.coefficientInput + (z.1.1.1,z.1.1.2.getD z.2 (0,0)),z.1.2.getD z.2 0) +def termAtRealizer : Realizer termAt := + pair + (composition (f := fun z : TermBundle×ℕ => (z.1.1.1,z.1.1.2.getD z.2 (0,0))) + (g := RootedCellDataProgram.coefficientInput) + (pair (composition (composition first first) first) + (composition (pair (composition (composition first first) second) second) + (getDFast (0,0)))) RootedCellDataProgram.coefficientInputRealizer) + (composition (pair (composition first second) second) (getDFast 0)) +lemma polynomial_termAt : PolynomialTime termAtRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) (polynomial_getDFast (0,0)))) + RootedCellDataProgram.polynomial_coefficientInput) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) (polynomial_getDFast 0)) + +def indices (xs : List (ℕ×ℕ)) : List ℕ := List.range xs.length +def indicesRealizer : Realizer indices := composition listLength range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange polynomial_listLength Polynomial.X + intro xs + simpa only [Polynomial.eval_X] using list_length_le_weight xs + +def terms (z : TermBundle) : List RootedForestDataProgram.TermInput := + (indices z.1.2).map (fun k => termAt (z,k)) +def termsRealizer : Realizer terms := + composition (pair identity (composition (composition first second) indicesRealizer)) + (mapWith termAtRealizer) +theorem polynomial_terms : PolynomialTime termsRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_indices)) (polynomial_mapWith polynomial_termAt) + +lemma terms_ofFn {n : ℕ} (frame : RootedCellDataProgram.Input) + (cells : Fin n → ℕ×ℕ) (v : Fin n → ℕ) : + terms ((frame,List.ofFn cells),List.ofFn v)= + List.ofFn (fun i => (RootedCellDataProgram.coefficientInput (frame,cells i),v i)) := by + apply List.ext_getElem + · simp only [terms,indices,List.length_map,List.length_range,List.length_ofFn] + · intro i hi hj + have hin : i (((RootedForestCatalog.freeEquiv A) i).val.1.val, + ((RootedForestCatalog.freeEquiv A) i).val.2.val)) := by + apply List.ext_getElem + · simp only [List.length_ofFn] + · intro i hi hj + simp only [List.getElem_ofFn] + exact (RootedForestCatalog.catalogCell_coordinates A false ⟨i,hi⟩).symm + +theorem terms_data {m n : ℕ} (A : Instance (Fin m) (Fin n)) + (t : GraphCompletionCounts.TreeCell A.T) (x q : Fin m → Fin n → ℕ) + (v : FreeCell A.small A.T → ℕ) : + terms ((treeInput (RootedDemandProgram.data A x q,(t.val.1.val,t.val.2.val)), + RootedForestCatalog.catalog (RootedForestCatalog.data A,false)), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i)))= + List.ofFn (fun i => + (RootedCoefficientProgram.input A t ((RootedForestCatalog.freeEquiv A) i).val, + v (RootedForestCatalog.freeEquiv A i))) := by + have hf := congrArg (fun frame : RootedCellDataProgram.Input => + terms ((frame,RootedForestCatalog.catalog (RootedForestCatalog.data A,false)), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i)))) + (treeInput_data A t x q) + have hc := congrArg (fun cells : List (ℕ×ℕ) => + terms ((RootedCellDataProgram.data A t x q,cells), + List.ofFn (fun i => v (RootedForestCatalog.freeEquiv A i)))) + (freeCatalog_ofFn A) + refine hf.trans (hc.trans ((terms_ofFn (RootedCellDataProgram.data A t x q) + (fun i => (((RootedForestCatalog.freeEquiv A) i).val.1.val, + ((RootedForestCatalog.freeEquiv A) i).val.2.val)) + (fun i => v (RootedForestCatalog.freeEquiv A i))).trans ?_)) + apply congrArg List.ofFn + funext i + exact congrArg (fun z => (z,v (RootedForestCatalog.freeEquiv A i))) + (RootedCellDataProgram.coefficientInput_data A t x q + ((RootedForestCatalog.freeEquiv A) i).val.1 ((RootedForestCatalog.freeEquiv A) i).val.2) + +end ContingencyTables.RootedTreeInputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..3067ee2dfc7d73691f2b315a930b3572e80ee5b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedTreeMarginal.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPenalty +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalEnumeration +import OAI.Combinatorics.ContingencyTables.Rooted.ForestBoxCardinality +import OAI.Combinatorics.ContingencyTables.Transport.PositiveSequenceInterpolation + +namespace OAI + +/-! # The actual one-tree physical marginal before the equality limit + +One physical cell is retained as its doubled Boolean pair. Every other +physical cell, including small capacities zero and one, is summed at +balance. The resulting positive scalar sequence has the proved raw +log-concavity and finite interpolation bounds. +-/ + +namespace ContingencyTables.RootedTreeMarginal + +open scoped BigOperators Classical Matrix Topology +open Filter CommonBasesFPRAS CompanionFactorialApplication ForestPenaltyApplication +open TreeMarginalSignature (keep singleView enumeration cellWidth otherWidths coordinateEquiv) +open LargePairEnumeration BalancedFamily BalancedBox EqualitySoftening IntegerWeightedTransport RowColumnPenalties + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def soft (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) : (Bool → ℕ) → ℝ := + eliminate (widths (otherWidths A t)) (fun z => + softenedWeight cellLine (RootedPenalty.rootFlag R) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) L (z ∘ (coordinateEquiv A t).symm)) + +noncomputable def exactMarginal (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) : (Bool → ℕ) → ℝ := + eliminate (widths (otherWidths A t)) (fun z => + RootedPenalty.physicalWeight A R alpha (z ∘ (coordinateEquiv A t).symm)) + +theorem soft_slices (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) : + PositiveSlice (soft A R alpha L t) (fun _ => cellWidth A t) (cellWidth A t) ∧ + RemovalSlice (soft A R alpha L t) (fun _ => cellWidth A t) (cellWidth A t) := by + apply EqualityReindex.physical_softened_slices_all + (widths (otherWidths A t)) (fun _ => cellWidth A t) (cellWidth A t) (coordinateEquiv A t) + · exact fun _ => ha + · intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + · exact hL + +noncomputable def scalarSoft (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) (k : ℕ) : ℝ := + soft A R alpha L t (childProfile (cellWidth A t) k) + +noncomputable def scalarExact (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) (k : ℕ) : ℝ := + exactMarginal A R alpha t (childProfile (cellWidth A t) k) + +theorem scalar_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (k : ℕ) (hk : k ≤ cellWidth A t) : + 0 < scalarSoft A R alpha L t k := + (soft_slices A R alpha L t ha hL).1 _ + (childProfile_inBox _ _ hk) (childProfile_total _ _ hk) + +theorem scalar_logConcave (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (k : ℕ) (hk : k+2 ≤ cellWidth A t) : + scalarSoft A R alpha L t k*scalarSoft A R alpha L t (k+2) ≤ + (scalarSoft A R alpha L t (k+1))^2 := + child_logConcave (soft A R alpha L t) _ (soft_slices A R alpha L t ha hL).1 + (soft_slices A R alpha L t ha hL).2 k hk + +/-- Every retained tree mass is the finite equality-softening limit of +its actual positive physical balanced sum. -/ +theorem scalar_tendsto (A : Instance I J) (R : RootedCompletion.Selection A.T) (alpha : ℝ) (t : I×J) (k : ℕ) : + Tendsto (fun L : ℝ => scalarSoft A R alpha L t k) atTop (nhds (scalarExact A R alpha t k)) := by + apply eliminate_tendsto (widths (otherWidths A t)) + intro z + exact softenedWeight_tendsto cellLine (RootedPenalty.rootFlag R) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) (z ∘ (coordinateEquiv A t).symm) + +/-- The selected-root retained-cell marginal is the actual physical fibre. -/ +theorem exact_eq_fibre (A : Instance I J) (R : RootedCompletion.Selection A.T) + (alpha : ℝ) (t : I×J) (k : Fin (cellWidth A t+1)) : + scalarExact A R alpha t k.val= + BalancedCellFibres.fibre (cellWidth A) (RootedPenalty.physicalWeight A R alpha) t k := by + unfold scalarExact exactMarginal + rw [TreeMarginalSignature.eliminate_eq_one_cell_sum,BalancedCellFibres.fibre_eq_sum] + apply Fintype.sum_equiv + (Equiv.piCongrLeft (fun c : {c : I×J // c≠t} => Fin (cellWidth A c.val+1)) + (TreeMarginalSignature.otherCells t)) + intro a + congr 1 + have h := TreeMarginalSignature.physical_one_cell_profile A t k + ((Equiv.piCongrLeft (fun c : {c : I×J // c≠t} => Fin (cellWidth A c.val+1)) + (TreeMarginalSignature.otherCells t)) a) + simpa only [Equiv.symm_apply_apply] using h + +end ContingencyTables.RootedTreeMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWarmReturn.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWarmReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..521b2708f6dc4bf96472050cee8a72a340724313 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWarmReturn.lean @@ -0,0 +1,191 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedTargetTrace +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCappedReturn +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # Warm input error of the actual selected-root bounded return law -/ + +namespace ContingencyTables.RootedWarmReturn + +open CommonBasesFPRAS ResidualMixture FirstSuccess FiniteLawMoments RealKernelApproximation +open CompanionFactorialApplication RootedBooleanPhase CompanionOracleDensity +open CompanionWeightOracle CompanionRationalUpdates RootedTraceWords +open RootedCappedReturn RootedTargetTrace RootedAnnealing RootedWarmStart +open CompanionConcentration (pairs_ne_nil) +open CompanionBooleanPhase (State stepBits) +open CompanionTraceWords (eventIndicator) +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma weighted_error {Y : Type*} [Fintype Y] + (nu f g loss : Y → ℝ) (delta e : ℝ) (hnu : ∀ y,0≤nu y) + (hmass : ∑ y,nu y≤1) (he : 0≤e) + (hpoint : ∀ y,f y≤g y+loss y+e) (hloss : ∑ y,nu y*loss y≤delta) : + (∑ y,nu y*f y)≤(∑ y,nu y*g y)+delta+e := by + have h := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => + mul_le_mul_of_nonneg_left (hpoint y) (hnu y)) + have hm := mul_le_mul_of_nonneg_right hmass he + simp only [mul_add,Finset.sum_add_distrib,←Finset.sum_mul,one_mul] at h hm + linarith + +private lemma push_observation {X Y : Type*} [Fintype X] [Fintype Y] + (K : FiniteKernel X Y) (nu : X → ℝ) (g : Y → ℝ) : + (∑ y,K.push nu y*g y)=∑ x,nu x*(∑ y,K.P x y*g y) := by + simp only [FiniteKernel.push,Finset.sum_mul,Finset.mul_sum,mul_assoc] + exact Finset.sum_comm + +private theorem distance_of_events {Y : Type*} [Fintype Y] + (p q : Y → ℝ) (delta : ℝ) (hmass : ∑ y,p y=∑ y,q y) + (hevent : ∀ E : Y → Prop,(∑ y,p y*eventIndicator (E y))≤ + (∑ y,q y*eventIndicator (E y))+delta) : distance p q≤delta := by + let E : Y → Prop := fun y => 0≤p y-q y + have hzero : (∑ y,(p y-q y))=0 := by + rw [Finset.sum_sub_distrib,hmass,sub_self] + have hpoint (y : Y) : |p y-q y|= + 2*((p y-q y)*eventIndicator (E y))-(p y-q y) := by + by_cases h : 0≤p y-q y + · simp only [E,eventIndicator,h,ite_true,abs_of_nonneg h,mul_one] + ring + · simp only [E,eventIndicator,h,ite_false,abs_of_neg (lt_of_not_ge h),mul_zero] + ring + have hsum : (∑ y,|p y-q y|)=2*(∑ y,(p y-q y)*eventIndicator (E y)) := by + simp only [hpoint,Finset.sum_sub_distrib,←Finset.mul_sum,hzero,sub_zero] + have hh := hevent E + simp only [sub_mul,Finset.sum_sub_distrib] at hsum + unfold distance + rw [hsum] + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +def returnLaw (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin ((n+1)*stepBits A C K j k xi) → Bool)) + (returnWordDefault A R C K j k n hK hW xi v w S) + +def returnKernel (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) : + FiniteKernel (PlainIndex (pairs : List (Pair A))) (PlainIndex (pairs : List (Pair A))) := + rationalKernel (returnLaw A R C K j k n hK hW xi v w) + +private lemma return_observation (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) (E : PlainIndex (pairs : List (Pair A)) → Prop) : + (∑ T,(returnKernel A R C K j k n hK hW xi v w).P S T*eventIndicator (E T))= + uniformAverage (fun bits : Fin ((n+1)*stepBits A C K j k xi) → Bool => + eventIndicator (E (returnWordDefault A R C K j k n hK hW xi v w S bits))) := by + exact (word_expectation (returnWordDefault A R C K j k n hK hW xi v w S) + (fun T => eventIndicator (E T))).symm + +theorem warm_cap_loss (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (hp : 0 (w p q:ℝ))) + (n : ℕ) (hn : 0 (w p q:ℝ))) + (hn : 0 + ∑ T,(returnKernel A R C K j k n hK hW xi v w).P S T*eventIndicator (E T) + let g : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + ∑ T,(RootedTargetTrace.actualTrace A R j hp w hw).kernel.P S T*eventIndicator (E T) + let loss : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + 1-∑ T,(targetChain A R j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A R j hp w hw) n S T + let err : ℝ := ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) + have herr : 0≤err := by dsimp only [err]; positivity + have hpoint (S) : f S≤g S+loss S+err := by + dsimp only [f,g,loss,err] + rw [return_observation] + exact returnWordDefault_event A R C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw S E + have hcap := warm_cap_loss A R j hp w hw hgood n hn nu hnu U hU hwarm + have hsum := @weighted_error (PlainIndex (pairs : List (Pair A))) inferInstance + nu f g loss ((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)) err + hnu hmass herr hpoint hcap + exact hsum + +/-- This is the law of the implemented Boolean return, compared to the +literal trace on the same incoming warm distribution. -/ +theorem warm_return_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 simp + | succ j ih => + have h := weight_adjacent A R j S + constructor + · rw [pow_succ] + nlinarith [mul_le_mul_of_nonneg_left ih.1 (show (0:ℝ)≤1/2 by norm_num)] + · exact h.2.trans ih.2 + +theorem total_bounds_zero (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) : + (1/2:ℝ)^j*total A R 0≤ total A R j ∧ total A R j≤ total A R 0 := by + unfold total + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun S => (weight_bounds_zero A R j S).1) _ + · exact slotTotal_mono _ _ _ (fun S => (weight_bounds_zero A R j S).2) _ + +lemma zero_weight_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) + (S : Set (Labels A×Bool)) : + freeTotal A/CompanionFactorialApplication.denominator A≤ weight A R 0 S := by + rw [zero_weight_eq] + exact CompanionWarmStart.zero_weight_lower A S + +/-- An explicit positive minimum mass for the actual transversal law. +Its binary size depends on j and the bounded small-cell capacities. -/ +theorem law_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2:ℝ)^j/(CompanionFactorialApplication.denominator A* + ∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤ law A R j S := by + have hM := free_positive A + have hD := CompanionFactorialApplication.denominator_positive A + have hB : 0<(∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) := + Finset.prod_pos (fun _ _ => by positivity) + have hweight := weight_bounds_zero A R j S + have hz := zero_weight_lower A R S + have hT := (total_bounds_zero A R j).2 + have hT0 : total A R 0=freeTotal A*∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1) := by + unfold total weight + exact total_zero A R + rw [hT0] at hT + have hpositive := total_positive A R j + have hpow : 0≤(1/2:ℝ)^j := by positivity + unfold law + rw [div_le_div_iff₀ (mul_pos hD hB) hpositive] + have hlo : (1/2:ℝ)^j*freeTotal A≤ weight A R j S*CompanionFactorialApplication.denominator A := by + have hz' := (div_le_iff₀ hD).mp hz + have hmul := mul_le_mul_of_nonneg_right hweight.1 hD.le + have hmul' := mul_le_mul_of_nonneg_left hz' hpow + nlinarith + have hupper := mul_le_mul_of_nonneg_left hT hpow + have hfinal := mul_le_mul_of_nonneg_right hlo hB.le + nlinarith + +/-- The existing executed initializer is exactly the selected-root phase-zero law. -/ +lemma law_zero_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (S : Set (Labels A×Bool)) : + law A R 0 S=CompanionWarmStart.law A 0 S := by + unfold law total CompanionWarmStart.law CompanionWarmStart.total + rw [zero_weight_eq] + +lemma ideal_initial_mass (A : Instance I J) (R : RootedCompletion.Selection A.T) + (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((CompanionInitialDraw.idealLaw A).mass S:ℝ)=law A R 0 S.val.val := by + rw [law_zero_eq] + exact CompanionInitialDraw.idealLaw_mass A S + +theorem initial_distance (A : Instance I J) (R : RootedCompletion.Selection A.T) (h : ℕ) : + RealKernelApproximation.distance + (fun S => ((FirstSuccess.mapLaw + (FirstSuccess.uniformLaw (α := Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A h)) → Bool)) + (CompanionInitialDraw.draw A (CompanionInitialDraw.precision A h))).mass S:ℝ)) + (fun S => law A R 0 S.val.val)≤1/(2:ℝ)^h := by + simp_rw [law_zero_eq] + exact CompanionInitialDraw.initial_distance A h + +lemma actual_degree (A : Instance I J) (R : RootedCompletion.Selection A.T) (j : ℕ) : + BinaryContraction.DegreePositive (weight A R j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length ∧ + BinaryContraction.OmissionProperty (weight A R j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length := by + have hs := RootedFactorialApplication.first_properties A R ((j:ℝ)/CompanionAnnealing.scale A) + (div_nonneg (Nat.cast_nonneg j) (CompanionAnnealing.scale_positive A).le) + simpa only [weight,PairedLabels.length] using hs + +lemma initial_weight_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) + (S : Set (Labels A×Bool)) (hS : PlainState pairs S) : + freeTotal A*(1/2:ℝ)^Fintype.card (Labels A)≤ weight A R 0 S := by + rw [zero_weight_eq] + exact CompanionMinMass.initial_weight_lower A S hS + +/-- The sharp source minimum mass uses only the original bounded-cell label count. -/ +theorem plain_law_lower (A : Instance I J) (R : RootedCompletion.Selection A.T) (K j : ℕ) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^K) + (S : Set (Labels A×Bool)) (hS : PlainState pairs S) : + (1/2:ℝ)^(j+Fintype.card (Labels A)+K)≤ law A R j S := by + have hM := free_positive A + have hT := (total_bounds_zero A R j).2 + have hT0 : total A R 0=freeTotal A*∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1) := + total_zero A R + rw [hT0] at hT + have hupper : total A R j≤ freeTotal A*(2:ℝ)^K := + hT.trans (mul_le_mul_of_nonneg_left hB hM.le) + have hw := (weight_bounds_zero A R j S).1 + have hi := initial_weight_lower A R S hS + have hlower : freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A))≤ weight A R j S := by + rw [pow_add] + nlinarith [mul_le_mul_of_nonneg_left hi (show (0:ℝ)≤(1/2:ℝ)^j by positivity)] + have hpos := total_positive A R j + unfold law + rw [le_div_iff₀ hpos,pow_add] + have hm := mul_le_mul_of_nonneg_left hupper + (show (0:ℝ)≤(1/2:ℝ)^(j+Fintype.card (Labels A))*(1/2:ℝ)^K by positivity) + have hcancel : (1/2:ℝ)^K*(2:ℝ)^K=1 := by + rw [←mul_pow] + norm_num + have he : ((1/2:ℝ)^(j+Fintype.card (Labels A))*(1/2:ℝ)^K)* + (freeTotal A*(2:ℝ)^K)=freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A)) := by + calc + _=freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A))* + ((1/2:ℝ)^K*(2:ℝ)^K) := by ring + _=_ := by rw [hcancel,mul_one] + rw [he] at hm + exact hm.trans hlower + +end ContingencyTables.RootedWarmStart + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWeightOracle.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWeightOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e60a0da2b5fae467ddfd508f3c9142ba50ae9e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedWeightOracle.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorAmplification +import OAI.Combinatorics.ContingencyTables.Rooted.RootedAnnealing +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWeightOracle + +namespace OAI + +/-! # The actual labelled-weight oracle used by the outer chain -/ + +namespace ContingencyTables.RootedWeightOracle + +open CompanionFactorialApplication CompanionOracleDensity GridBoundary LabelledFactorial TwoLiftStates +open CommonBasesFPRAS +open CompanionWeightOracle +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem weight_source (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (j : ℕ) + (S : Set (Labels A×Bool)) : + RootedAnnealing.weight A R j S= + RootedCountIdentification.h A R ((j:ℝ)*C/height A C) (profile A S)*(factorialRatio A S:ℝ) := by + rw [factorialRatio_cast] + have he : (j:ℝ)*(C:ℝ)/height A C=(j:ℝ)/CompanionAnnealing.scale A := by + simpa only [height,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow,Nat.cast_add,Nat.cast_one] using + CompanionAnnealing.source_parameter A C j hC + rw [he] + simp only [RootedAnnealing.weight,RootedFactorialApplication.f,firstLift,profile,mul_div_assoc] + +def evaluate (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : ℚ := + RootedOracleDensity.medianEstimate A R C (profile A S) K hK hW j xi xi v bits*factorialRatio A S + +/-- The relative-accuracy event for the rational labelled-weight estimate. -/ +def accurateCall (A : Instance I J) (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : Prop := + (1-(xi:ℝ))*RootedAnnealing.weight A R j S ≤ (evaluate A R C K hK hW j xi v S bits:ℝ) ∧ + (evaluate A R C K hK hW j xi v S bits:ℝ) ≤ (1+(xi:ℝ))*RootedAnnealing.weight A R j S + +lemma evaluate_positive (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : 0 < evaluate A R C K hK hW j xi v S bits := by + have hr := (RootedOracleDensity.medianEstimate_range A R C hC (profile A S) (profile_inBox A S) + K hK hW hB j hj xi xi hx0 hx1 v bits).1 + have hc : (0:ℝ) < assignmentCount A := by exact_mod_cast assignmentCount_positive A + have hm : (0:ℚ) < RootedOracleDensity.medianEstimate A R C (profile A S) K hK hW j xi xi v bits := by + exact_mod_cast lt_of_lt_of_le (by positivity : (0:ℝ) < (assignmentCount A:ℝ)*(1/2:ℝ)^j/16) hr + exact mul_pos hm (factorialRatio_positive A S) + +/-- Every query at the actual labelled state uses a fresh bounded word. +Only PL and finite Cheeger remain in the evaluation guarantee. -/ +theorem evaluate_success (A : Instance I J) (R : RootedCompletion.Selection A.T) (C : ℕ) (hC : 0 < C) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + 1-(xi:ℝ) ≤ uniformAverage (fun bits : WeightWord A C K j xi => + if accurateCall A R C K j hK hW xi v S bits then (1:ℝ) else 0) := by + unfold accurateCall + have hs := RootedOracleDensity.medianEstimate_success A R C hC (profile A S) (profile_inBox A S) + K hK hW hB j hj xi xi hx0 hx1 hx0 hPL hCheeger v + apply hs.trans + apply uniformAverage_mono + intro bits + by_cases hg : (1-(xi:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) (profile A S) ≤ + (RootedOracleDensity.medianEstimate A R C (profile A S) K hK hW j xi xi v bits:ℝ) ∧ + (RootedOracleDensity.medianEstimate A R C (profile A S) K hK hW j xi xi v bits:ℝ) ≤ + (1+(xi:ℝ))*RootedCountIdentification.h A R ((j:ℝ)*C/height A C) (profile A S) + · have hf : (0:ℝ) ≤ factorialRatio A S := by exact_mod_cast (factorialRatio_positive A S).le + have hlo := mul_le_mul_of_nonneg_right hg.1 hf + have hhi := mul_le_mul_of_nonneg_right hg.2 hf + have ho : (1-(xi:ℝ))*RootedAnnealing.weight A R j S ≤ (evaluate A R C K hK hW j xi v S bits:ℝ) ∧ + (evaluate A R C K hK hW j xi v S bits:ℝ) ≤ (1+(xi:ℝ))*RootedAnnealing.weight A R j S := by + rw [weight_source A R C hC j S] + simpa only [evaluate,Rat.cast_mul,mul_assoc] using And.intro hlo hhi + simp only [hg,ho,le_refl] + · simp only [hg,ite_false] + split_ifs <;> norm_num + +end + +end ContingencyTables.RootedWeightOracle + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedZeroLabels.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedZeroLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..928ae99d167373b3a7ea6d35febb022925433466 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/RootedZeroLabels.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule +import OAI.Combinatorics.ContingencyTables.Rooted.RootedWeightOracle + +namespace OAI + +/-! # Counting when the retained small cells have no positive capacities + +The paired transversal space then has one state. The terminal total is +one actual free-assignment weight, so the bounded-word +weight estimator applies directly; no Markov restart is needed. +-/ + +namespace ContingencyTables.RootedZeroLabels + +open CommonBasesFPRAS CompanionFactorialApplication CompanionOracleDensity CompanionRationalUpdates +open CompanionWeightOracle CompanionTerminalMass CompanionTerminalApplication +open TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +lemma small_capacity_zero (A : Instance I J) (hzero : Fintype.card (Labels A)=0) + (s : SmallCell A) : A.b s.val.1 s.val.2=0 := by + let : IsEmpty (Labels A) := Fintype.card_eq_zero_iff.mp hzero + by_contra hn + exact isEmptyElim (⟨s,⟨0,Nat.pos_of_ne_zero hn⟩⟩ : Labels A) + +lemma profile_zero (A : Instance I J) (hzero : Fintype.card (Labels A)=0) + (S : Set (Labels A×Bool)) : profile A S=fun _ => 0 := by + let : IsEmpty (Labels A) := Fintype.card_eq_zero_iff.mp hzero + funext u + simp only [profile,LabelledFactorial.groupCount,Finset.univ_eq_empty, + Finset.filter_empty,Finset.card_empty] + +lemma factorialRatio_one (A : Instance I J) (hzero : Fintype.card (Labels A)=0) + (S : Set (Labels A×Bool)) : factorialRatio A S=1 := by + simp only [factorialRatio,factorialNumerator,factorialDenominator,profile_zero A hzero] + have hz (s : SmallCell A) : A.b s.val.1 s.val.2=0 := small_capacity_zero A hzero s + simp only [hz,Nat.factorial_zero,Finset.prod_const_one,Nat.cast_one,div_self (one_ne_zero : (1:ℚ) ≠ 0)] + +lemma total_eq_h (A : Instance I J) (R : RootedCompletion.Selection A.T) + (hzero : Fintype.card (Labels A)=0) (C : ℕ) (hC : 0 < C) (j : ℕ) : + RootedWarmStart.total A R j= + RootedCountIdentification.h A R ((j:ℝ)*C/height A C) (fun _ => 0) := by + let : IsEmpty (Labels A) := Fintype.card_eq_zero_iff.mp hzero + have hp : (pairs : List (Pair A))=[] := by + simp only [pairs,Finset.univ_eq_empty,Finset.toList_empty,List.map_nil] + rw [RootedWarmStart.total,hp,slotTotal_nil,RootedWeightOracle.weight_source A R C hC, + profile_zero A hzero,factorialRatio_one A hzero] + simp only [Rat.cast_one,mul_one] + +/-- The direct all-large branch has arbitrary confidence using the +same actual finite-word evaluator, with no positive-label premise. -/ +theorem success (A : Instance I J) (R : RootedCompletion.Selection A.T) + (hzero : Fintype.card (Labels A)=0) (E : Endpoints A) + (C K L : ℕ) (hC : 0 < C) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (hW' : 20*A.d ≤ A.W) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (hL : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^L) + (hH : finalPhase A L (epsilon:ℝ) ≤ rationalHeight A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + 1-(delta:ℝ) ≤ uniformAverage (fun bits : + Fin (medianEstimatorBits A C K (finalPhase A L (epsilon:ℝ)) (epsilon/2) delta) → Bool => + let value := RootedOracleDensity.medianEstimate A R C (fun _ => 0) K hK hW + (finalPhase A L (epsilon:ℝ)) (epsilon/2) delta v bits + if (1-(epsilon:ℝ))*tableCount A ≤ (value:ℝ) ∧ + (value:ℝ) ≤ (1+(epsilon:ℝ))*tableCount A then (1:ℝ) else 0) := by + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have heR1 : (epsilon:ℝ) < 1 := by exact_mod_cast he1 + have hterminal := RootedTerminalApplication.terminal_normalizer A R E L epsilon + heR heR1 hW' hL + have ht := total_eq_h A R hzero C hC (finalPhase A L (epsilon:ℝ)) + rw [ht] at hterminal + have hm := RootedOracleDensity.medianEstimate_success A R C hC (fun _ => 0) + (by intro u; exact Nat.zero_le _) K hK hW hB + (finalPhase A L (epsilon:ℝ)) hH (epsilon/2) delta + (by positivity) (by linarith) hd hPL hCheeger v + apply hm.trans + apply uniformAverage_mono + intro bits + let value := RootedOracleDensity.medianEstimate A R C (fun _ => 0) K hK hW + (finalPhase A L (epsilon:ℝ)) (epsilon/2) delta v bits + by_cases hgood : + (1-((epsilon/2:ℚ):ℝ))*RootedCountIdentification.h A R + ((finalPhase A L (epsilon:ℝ):ℝ)*C/height A C) (fun _ => 0) ≤ (value:ℝ) ∧ + (value:ℝ) ≤ (1+((epsilon/2:ℚ):ℝ))*RootedCountIdentification.h A R + ((finalPhase A L (epsilon:ℝ):ℝ)*C/height A C) (fun _ => 0) + · have hlo := mul_le_mul_of_nonneg_left hterminal.1 + (show 0 ≤ 1-(epsilon:ℝ)/2 by linarith) + have hhi := mul_le_mul_of_nonneg_left hterminal.2 + (show 0 ≤ 1+(epsilon:ℝ)/2 by linarith) + have hZ := tableCount_ge_one A + have hout : (1-(epsilon:ℝ))*tableCount A ≤ (value:ℝ) ∧ + (value:ℝ) ≤ (1+(epsilon:ℝ))*tableCount A := by + simp only [Rat.cast_div,Rat.cast_ofNat] at hgood + constructor + · nlinarith + · nlinarith [mul_nonneg heR.le (show 0 ≤ tableCount A by linarith)] + dsimp only [value] at hgood hout + simp only [hgood,hout,le_refl] + · dsimp only [value] at hgood + simp only [hgood,ite_false] + split_ifs <;> norm_num + +end +end ContingencyTables.RootedZeroLabels + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b21c1cd3a5bfe5cffa3c1656c302cdde746c8ca --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorMass.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalBounds +import OAI.Combinatorics.ContingencyTables.Rooted.TreeFeasibleMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalNormalizer +import OAI.Combinatorics.ContingencyTables.Rooted.TreeExteriorPositions + +namespace OAI + +/-! # Actual exterior tree masses, normalized by the original companion count -/ + +namespace ContingencyTables.TreeMarginalSignature + +open scoped BigOperators Classical +open CompanionFactorialApplication CompanionPhysicalNormalizer BalancedCellFibres +open ForestPenaltyApplication ForestLiteralCount + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma scalar_sum_eq_physicalMass (A : Instance I J) (alpha : ℝ) (t : I×J) : + (∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A alpha t q)=physicalMass A alpha := by + rw [← Fin.sum_univ_eq_sum_range] + simp_rw [exact_eq_fibre] + exact sum_fibre (cellWidth A) + (physicalWeight A.T A.b (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c alpha) t + +/-- A lower exterior tree position is controlled by the actual feasible +table attaining its upper bound, exactly as in the manuscript. -/ +theorem lower_exterior_point (A : Instance I J) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=(A.b t.1 t.2:ℤ)) (k : ℕ) (hk : k < 10*A.d*A.b t.1 t.2) : + scalarExact A alpha t k/physicalMass A alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + let N := 10*A.d*A.b t.1 t.2+A.b t.1 t.2-k + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hend := upper_tree_endpoint A alpha t ht Y hY hr hc hy + have hkN : k+N=10*A.d*A.b t.1 t.2+A.b t.1 t.2 := by dsimp only [N]; omega + have hwidth : cellWidth A t=20*A.d*A.b t.1 t.2 := by simp only [cellWidth,width,ht,ite_true] + have hprod : A.b t.1 t.2 ≤ A.d*A.b t.1 t.2 := by have hd := A.hd; nlinarith + have hh := scalar_exact_forward_point_bound A alpha t ha hW B K k N (A.b t.1 t.2) hB hBK hK + (by dsimp only [N]; omega) hb (by dsimp only [N]; omega) + (by rw [hkN,hwidth]; nlinarith) (by rw [hkN]; exact hend) + rwa [scalar_sum_eq_physicalMass] at hh + +theorem upper_exterior_point (A : Instance I J) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=0) (k : ℕ) + (hk : 10*A.d*A.b t.1 t.2+A.b t.1 t.2 < k) (hkU : k ≤ cellWidth A t) : + scalarExact A alpha t k/physicalMass A alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + let N := k-10*A.d*A.b t.1 t.2 + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hend := lower_tree_endpoint A alpha t ht Y hY hr hc hy + have hkN : k-N=10*A.d*A.b t.1 t.2 := by dsimp only [N]; omega + have hh := scalar_exact_backward_point_bound A alpha t ha hW B K k N (A.b t.1 t.2) hB hBK hK + (by dsimp only [N]; omega) hb (by dsimp only [N]; omega) (by dsimp only [N]; omega) + hkU (by rw [hkN]; exact hend) + rwa [scalar_sum_eq_physicalMass] at hh + +end ContingencyTables.TreeMarginalSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorPositions.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorPositions.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfabee318539d222cab99cad3e1f9b2ed916f42b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeExteriorPositions.lean @@ -0,0 +1,89 @@ +import Mathlib.Algebra.Order.Floor.Semiring +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Order.Interval.Finset.Nat +import Mathlib.Data.Finset.Card +import Mathlib.Data.Fintype.Basic +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Linarith +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! # The narrow exterior tree intervals contain fewer than 2 gamma b positions -/ + +namespace ContingencyTables.TreeExteriorPositions + +open scoped Classical + +private lemma positive_integer_positions {C : Type*} [Fintype C] (q : C → ℤ) + (hq : Function.Injective q) (delta : ℝ) (hd : 0 < delta) : + ((Finset.univ.filter (fun c => 0 < q c ∧ (q c:ℝ) < delta)).card:ℝ) ≤ delta := by + let S := Finset.univ.filter (fun c => 0 < q c ∧ (q c:ℝ) < delta) + have hm : Set.MapsTo (fun c => (q c).toNat) S (Finset.Ico 1 (Nat.ceil delta)) := by + intro c hc + have hh := (Finset.mem_filter.mp hc).2 + have hn : (0:ℤ) ≤ q c := hh.1.le + have hcast : ((q c).toNat:ℝ)=(q c:ℝ) := by exact_mod_cast Int.toNat_of_nonneg hn + apply Finset.mem_Ico.mpr + constructor + · have hv := Int.toNat_of_nonneg hn + have hpos : 0 < q c := hh.1 + have hcast : (1:ℤ) ≤ ((q c).toNat:ℤ) := by rw [hv]; omega + exact_mod_cast hcast + · have hhR : ((q c).toNat:ℝ) < (Nat.ceil delta:ℝ) := by rw [hcast]; exact hh.2.trans_le (Nat.le_ceil delta) + exact_mod_cast hhR + have hi : (S:Set C).InjOn (fun c => (q c).toNat) := by + intro c hc c' hc' he + apply hq + have hh := (Finset.mem_filter.mp hc).2.1.le + have hh' := (Finset.mem_filter.mp hc').2.1.le + have h := congrArg (fun n : ℕ => (n:ℤ)) he + simpa only [Int.toNat_of_nonneg hh,Int.toNat_of_nonneg hh'] using h + have hc := Finset.card_le_card_of_injOn (fun c => (q c).toNat) hm hi + rw [Nat.card_Ico] at hc + have hceil : 1 ≤ Nat.ceil delta := Nat.one_le_ceil_iff.mpr hd + have hceilR : ((Nat.ceil delta-1:ℕ):ℝ) ≤ delta := by + rw [Nat.cast_sub hceil] + have hh := Nat.ceil_lt_add_one hd.le + push_cast + linarith + exact (by exact_mod_cast hc : (S.card:ℝ) ≤ (Nat.ceil delta-1:ℕ)).trans hceilR + +noncomputable def positions (ell : ℤ) (b U : ℕ) (delta : ℝ) : Finset (Fin (U+1)) := + Finset.univ.filter (fun k => + ((ell+(k.val:ℤ)<0) ∧ -((ell+(k.val:ℤ):ℤ):ℝ) + 0 < -(ell+(k.val:ℤ)) ∧ ((-(ell+(k.val:ℤ)):ℤ):ℝ) + 0 < ell+(k.val:ℤ)-(b:ℤ) ∧ ((ell+(k.val:ℤ)-(b:ℤ):ℤ):ℝ) -(ell+(k.val:ℤ))) _ delta hd + intro k k' he + dsimp only at he + apply Fin.ext + have hh : (k.val:ℤ)=(k'.val:ℤ) := by omega + exact_mod_cast hh + have hR : (R.card:ℝ) ≤ delta := by + apply positive_integer_positions (fun k : Fin (U+1) => ell+(k.val:ℤ)-(b:ℤ)) _ delta hd + intro k k' he + dsimp only at he + apply Fin.ext + have hh : (k.val:ℤ)=(k'.val:ℤ) := by omega + exact_mod_cast hh + have he : positions ell b U delta=L∪R := by + ext k + simp only [positions,L,R,Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_union, + neg_pos,sub_pos,Int.cast_neg,Int.cast_sub,Int.cast_natCast] + rw [he] + have hc : ((L∪R).card:ℝ) ≤ (L.card:ℝ)+(R.card:ℝ) := by exact_mod_cast Finset.card_union_le L R + linarith + +end ContingencyTables.TreeExteriorPositions + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeFeasibleMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeFeasibleMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..72b1eb70ae9246d7ccb808dbd5918fa192b9b572 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeFeasibleMass.lean @@ -0,0 +1,182 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalEnumeration + +namespace OAI + +/-! # Every feasible table contributes one unit to its actual cell fibre -/ + +namespace ContingencyTables.TreeMarginalSignature + +open scoped BigOperators Classical +open CompanionFactorialApplication ForestPenaltyApplication ForestLiteralCount +open BalancedCellFibres EqualitySoftening + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma lower_nonpositive (A : Instance I J) (i : I) (j : J) : + lower A.T A.d A.b i j ≤ 0 := by + unfold lower + split_ifs <;> omega + +lemma upper_ge_capacity (A : Instance I J) (i : I) (j : J) : + (A.b i j:ℤ) ≤ lower A.T A.d A.b i j+width A.T A.d A.b i j := by + unfold lower width + split_ifs + · have hd := A.hd + have hprod : A.b i j ≤ A.d*A.b i j := by nlinarith + have hh : ((A.b i j+10*A.d*A.b i j:ℕ):ℤ) ≤ (20*A.d*A.b i j:ℕ) := by + exact_mod_cast (show A.b i j+10*A.d*A.b i j ≤ 20*A.d*A.b i j by nlinarith) + push_cast at hh ⊢ + linarith + · simp + +noncomputable def tableAssignment (A : Instance I J) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) : Profiles (cellWidth A) := fun a => + ⟨(Y a.1 a.2-lower A.T A.d A.b a.1 a.2).toNat,by + have hlo := lower_nonpositive A a.1 a.2 + have hup := upper_ge_capacity A a.1 a.2 + have hz : 0 ≤ Y a.1 a.2-lower A.T A.d A.b a.1 a.2 := by linarith [(hY a.1 a.2).1] + have hb : Y a.1 a.2-lower A.T A.d A.b a.1 a.2 ≤ cellWidth A a := by + dsimp only [cellWidth] + linarith [(hY a.1 a.2).2] + have hn : (Y a.1 a.2-lower A.T A.d A.b a.1 a.2).toNat ≤ cellWidth A a := by + exact_mod_cast (show ((Y a.1 a.2-lower A.T A.d A.b a.1 a.2).toNat:ℤ) ≤ cellWidth A a by + rw [Int.toNat_of_nonneg hz] + exact hb) + omega⟩ + +lemma tableAssignment_row (A : Instance I J) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) (i : I) (j : J) : + physicalRow (lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j=(Y i j:ℝ) := by + have hz : 0 ≤ Y i j-lower A.T A.d A.b i j := by + linarith [(hY i j).1,lower_nonpositive A i j] + simp only [physicalRow,BalancedCellFibres.profile,Bool.false_eq_true,ite_false,tableAssignment] + have hn : (((Y i j-lower A.T A.d A.b i j).toNat:ℕ):ℝ)= + (Y i j:ℝ)-(lower A.T A.d A.b i j:ℝ) := by + exact_mod_cast Int.toNat_of_nonneg hz + rw [hn] + ring + +lemma tableAssignment_column (A : Instance I J) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) (i : I) (j : J) : + physicalColumn (lower A.T A.d A.b) (width A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j=(Y i j:ℝ) := by + have hk : (tableAssignment A Y hY (i,j)).val ≤ cellWidth A (i,j) := + Nat.le_of_lt_succ (tableAssignment A Y hY (i,j)).isLt + have hh := tableAssignment_row A Y hY i j + simp only [physicalColumn,BalancedCellFibres.profile,ite_true,Nat.cast_sub hk] + change (lower A.T A.d A.b i j:ℝ)+(cellWidth A (i,j):ℝ)- + ((cellWidth A (i,j):ℝ)-((tableAssignment A Y hY (i,j)).val:ℝ))=(Y i j:ℝ) + change (lower A.T A.d A.b i j:ℝ)+((tableAssignment A Y hY (i,j)).val:ℝ)=(Y i j:ℝ) at hh + linarith + +theorem tableAssignment_unit (A : Instance I J) (alpha : ℝ) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i, (∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) : + physicalWeight A.T A.b (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c alpha + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY))=1 := by + have hdev : ∀ g,deviation (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) g=0 := by + intro g + cases g with + | inl i => + simp only [deviation,Sum.elim_inl] + simp_rw [tableAssignment_row] + have hh : (∑ j,(Y i j:ℝ))=(A.r i:ℝ) := by exact_mod_cast hr i + rw [hh,sub_self] + | inr j => + simp only [deviation,Sum.elim_inr] + simp_rw [tableAssignment_column] + have hh : (∑ i,(Y i j:ℝ))=(A.c j:ℝ) := by exact_mod_cast hc j + rw [hh,sub_self] + rw [exact_eq,ite_eq_left (fun g _ => hdev g)] + have hp : penalty A.T A.b (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY))=0 := by + unfold penalty rootPenalty treePenalty + simp only [hdev,abs_zero,ite_self,Finset.sum_const_zero,zero_add] + apply Finset.sum_eq_zero + intro i _ + apply Finset.sum_eq_zero + intro j _ + have hy0 : (0:ℝ) ≤ Y i j := by exact_mod_cast (hY i j).1 + have hyb : (Y i j:ℝ) ≤ A.b i j := by exact_mod_cast (hY i j).2 + have hh := tableAssignment_row A Y hY i j + unfold affineDistance + simp only [mul_one] + change (if A.T.Adj (.inl i) (.inr j) then + max 0 (max (-(physicalRow (lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j)) + (physicalRow (lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) (tableAssignment A Y hY)) i j-A.b i j)) / + (A.b i j:ℝ) else 0)=0 + rw [hh,max_eq_left (max_le (neg_nonpos.mpr hy0) (sub_nonpos.mpr hyb))] + simp + rw [hp,mul_zero,Real.rpow_zero] + +/-- A feasible table supplies an actual unit summand at its retained +physical coordinate. No endpoint-mass oracle is assumed. -/ +theorem scalar_exact_ge_one_at_table (A : Instance I J) (alpha : ℝ) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) (t : I×J) : + 1 ≤ scalarExact A alpha t (tableAssignment A Y hY t).val := by + rw [exact_eq_fibre] + have hh := Finset.single_le_sum + (f := fun a : Profiles (cellWidth A) => + if a t=tableAssignment A Y hY t then + physicalWeight A.T A.b (lower A.T A.d A.b) (width A.T A.d A.b) A.r A.c alpha + (BalancedCellFibres.profile (cellWidth A) a) else 0) + (fun a _ => by split_ifs; exact physicalWeight_nonnegative _ _ _ _ _ _ _ _; exact le_rfl) + (Finset.mem_univ (tableAssignment A Y hY)) + simp only [ite_true,tableAssignment_unit A alpha Y hY hr hc] at hh + apply hh.trans_eq + unfold fibre + apply Finset.sum_congr + · ext a + simp + · intro a _ + rfl + +lemma tableAssignment_tree_index (A : Instance I J) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) : + ((tableAssignment A Y hY t).val:ℤ)=Y t.1 t.2+(10*A.d*A.b t.1 t.2:ℕ) := by + have hz : 0 ≤ Y t.1 t.2-lower A.T A.d A.b t.1 t.2 := by + linarith [(hY t.1 t.2).1,lower_nonpositive A t.1 t.2] + change ((Y t.1 t.2-lower A.T A.d A.b t.1 t.2).toNat:ℤ)=_ + rw [Int.toNat_of_nonneg hz] + simp only [lower,ht,ite_true,sub_neg_eq_add] + +/-- Tight upper-cell attainment supplies the endpoint on the right of +every lower exterior tree value. -/ +theorem upper_tree_endpoint (A : Instance I J) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=(A.b t.1 t.2:ℤ)) : + 1 ≤ scalarExact A alpha t (10*A.d*A.b t.1 t.2+A.b t.1 t.2) := by + have hi := tableAssignment_tree_index A Y hY t ht + rw [hy] at hi + push_cast at hi + have hindex : (tableAssignment A Y hY t).val=10*A.d*A.b t.1 t.2+A.b t.1 t.2 := by + exact_mod_cast (show ((tableAssignment A Y hY t).val:ℤ)= + ((10*A.d*A.b t.1 t.2+A.b t.1 t.2:ℕ):ℤ) by push_cast; omega) + rw [← hindex] + exact scalar_exact_ge_one_at_table A alpha Y hY hr hc t + +/-- Tight lower-cell attainment supplies the endpoint on the left of +every upper exterior tree value. -/ +theorem lower_tree_endpoint (A : Instance I J) (alpha : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) + (Y : I → J → ℤ) (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) + (hr : ∀ i,(∑ j,Y i j)=A.r i) (hc : ∀ j,(∑ i,Y i j)=A.c j) + (hy : Y t.1 t.2=0) : + 1 ≤ scalarExact A alpha t (10*A.d*A.b t.1 t.2) := by + have hi := tableAssignment_tree_index A Y hY t ht + rw [hy,zero_add] at hi + have hindex : (tableAssignment A Y hY t).val=10*A.d*A.b t.1 t.2 := by exact_mod_cast hi + rw [← hindex] + exact scalar_exact_ge_one_at_table A alpha Y hY hr hc t + +end ContingencyTables.TreeMarginalSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..021b243fbf825885b7305160fd252841e2e201b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalBounds.lean @@ -0,0 +1,221 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalSignature +import OAI.Combinatorics.ContingencyTables.Transport.SoftWeightUpper + +namespace OAI + +/-! # Uniform mass and interpolation bounds for the physical tree marginal + +The finite positive softening has at most the actual expanded physical +box's number of summands. Consequently its interpolation estimate passes +to the exact equality-constrained marginal even when that marginal has +zero entries outside its feasible interval. +-/ + +namespace ContingencyTables.EqualitySoftening + +open scoped BigOperators Classical +open ScalarPenalty ProductIntegerSignature + +variable {C G : Type*} [Fintype C] [Fintype G] + +/-- Softening only adds mass to an exact equality indicator. This +comparison holds for every parameter value, because all soft factors +are positive and the equality case has factor one. -/ +theorem exactWeight_le_softenedWeight (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) (z : C → ℕ) : + exactWeight line root rate offset slope urate ell uslope cap z ≤ + softenedWeight line root rate offset slope urate ell uslope cap L z := by + have hl (g : G) : exactLineFactor root rate offset slope g (lineTotal line z g) ≤ + lineFactor root rate offset slope L g (lineTotal line z g) := by + unfold exactLineFactor lineFactor + split_ifs + · exact le_rfl + · simp_all only [factor,mul_zero,Real.rpow_zero,le_refl] + · exact (factor_positive _ _ _).le + have hnonneg (g : G) : 0 ≤ exactLineFactor root rate offset slope g (lineTotal line z g) := by + unfold exactLineFactor + split_ifs + · exact (factor_positive _ _ _).le + · norm_num + · exact le_rfl + unfold exactWeight softenedWeight productWeight + exact mul_le_mul_of_nonneg_right + (Finset.prod_le_prod₀ (fun g _ => hnonneg g) (fun g _ => hl g)) + (Finset.prod_nonneg (fun _ _ => (factor_positive _ _ _).le)) + +end ContingencyTables.EqualitySoftening + +namespace ContingencyTables.TreeMarginalSignature + +open scoped BigOperators Classical Topology +open Filter CompanionFactorialApplication ForestPenaltyApplication +open LargePairEnumeration BalancedFamily BalancedBox EqualitySoftening RowColumnPenalties +open IntegerWeightedTransport + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma other_card_le_full (A : Instance I J) (t : I×J) : + Fintype.card (BalancedEnumeration.Assignments (widths (otherWidths A t))) ≤ + Fintype.card (ForestBoxCardinality.Assignments A) := by + have hc : 1 ≤ ∏ a : {a : I×J // ¬keep t a=false},(cellWidth A a.val+1) := by + exact Finset.one_le_prod (fun _ _ => by omega) + have hs := Fintype.prod_subtype_mul_prod_subtype (fun a : I×J => keep t a=false) + (fun a => cellWidth A a+1) + calc + _ = Fintype.card ((k : Fin (Fintype.card (LargeCell (keep t)))) → + Fin (otherWidths A t k+1)) := Fintype.card_congr (assignmentEquiv (otherWidths A t)) + _ = ∏ k,(otherWidths A t k+1) := by simp only [Fintype.card_pi,Fintype.card_fin] + _ = ∏ a : LargeCell (keep t),(cellWidth A a.val+1) := by + apply Fintype.prod_equiv (enumeration t) + intro k + rfl + _ ≤ ∏ a : I×J,(cellWidth A a+1) := by + rw [← hs] + exact le_mul_of_one_le_right (Nat.zero_le _) hc + _ = _ := by simp only [ForestBoxCardinality.Assignments,Fintype.card_pi, + Fintype.card_fin,cellWidth] + +theorem scalar_soft_le_two_pow (A : Instance I J) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hK : 2*B ≤ K) (k : ℕ) : + scalarSoft A alpha L t k ≤ (2:ℝ)^K := by + have hcard := (other_card_le_full A t).trans + (ForestBoxCardinality.cardinality_le_two_pow A hW B K hB hK) + have hu := BalancedEnumeration.eliminate_le_card (widths (otherWidths A t)) + (fun z => softenedWeight cellLine (rootFlag A.T) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) L (z ∘ (coordinateEquiv A t).symm)) + (by + intro z + apply softenedWeight_le_one + · exact fun _ => ha + · intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + · exact hL) + (childProfile (cellWidth A t) k) + exact hu.trans (by exact_mod_cast hcard) + +theorem scalar_exact_nonnegative (A : Instance I J) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (k : ℕ) (hk : k ≤ cellWidth A t) : + 0 ≤ scalarExact A alpha t k := by + apply ge_of_tendsto (scalar_tendsto A alpha t k) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + exact (scalar_positive A alpha L t ha hL k hk).le + +lemma scalar_exact_le_soft (A : Instance I J) (alpha L : ℝ) (t : I×J) (k : ℕ) : + scalarExact A alpha t k ≤ scalarSoft A alpha L t k := by + unfold scalarExact exactMarginal scalarSoft soft + simp only [BalancedEnumeration.eliminate_eq_sum] + apply Finset.sum_le_sum + intro a _ + exact exactWeight_le_softenedWeight _ _ _ _ _ _ _ _ _ _ _ + +/-- A feasible table attaining the endpoint cell value supplies the +lower bound for finite interpolation through the equality limit. -/ +theorem scalar_exact_half_window (A : Instance I J) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 1 ≤ K) (hN : 0 < N) (hkN : k+N ≤ cellWidth A t) + (hend : 1 ≤ scalarExact A alpha t (k+N)) + (r : ℕ) (hr : r*K ≤ N) : + scalarExact A alpha t k/2 ≤ scalarExact A alpha t (k+r) := by + apply le_of_tendsto_of_tendsto ((scalar_tendsto A alpha t k).div_const 2) + (scalar_tendsto A alpha t (k+r)) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + apply positive_sequence_half_window (fun q => scalarSoft A alpha L t (k+q)) N K hK hN + · intro q hq + exact scalar_positive A alpha L t ha hL _ (by omega) + · intro q hq + have hh := scalar_logConcave A alpha L t ha hL (k+q) (by omega) + simpa only [Nat.add_assoc] using hh + · exact hend.trans (scalar_exact_le_soft A alpha L t (k+N)) + · simpa only [Nat.add_zero] using scalar_soft_le_two_pow A alpha L t ha hL hW B K hB hBK k + · exact hr + +/-- The same physical half-height estimate when the feasible endpoint +lies to the left of an exterior tree position. -/ +theorem scalar_exact_backward_half_window (A : Instance I J) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 1 ≤ K) (hN : 0 < N) (hNk : N ≤ k) (hk : k ≤ cellWidth A t) + (hend : 1 ≤ scalarExact A alpha t (k-N)) (r : ℕ) (hr : r*K ≤ N) : + scalarExact A alpha t k/2 ≤ scalarExact A alpha t (k-r) := by + apply le_of_tendsto_of_tendsto ((scalar_tendsto A alpha t k).div_const 2) + (scalar_tendsto A alpha t (k-r)) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + apply positive_sequence_half_window (fun q => scalarSoft A alpha L t (k-q)) N K hK hN + · intro q _ + exact scalar_positive A alpha L t ha hL _ ((Nat.sub_le _ _).trans hk) + · intro q hq + have hqk : q+2 ≤ k := hq.trans hNk + have hh := scalar_logConcave A alpha L t ha hL (k-(q+2)) (by omega) + rw [show k-(q+2)+2=k-q by omega,show k-(q+2)+1=k-(q+1) by omega] at hh + simpa only [mul_comm] using hh + · exact hend.trans (scalar_exact_le_soft A alpha L t (k-N)) + · simpa only [Nat.sub_zero] using scalar_soft_le_two_pow A alpha L t ha hL hW B K hB hBK k + · exact hr + +/-- The actual physical exterior point has normalized mass at most +2K/b whenever a feasible unit-mass endpoint lies at least b places to +its right, after eliminating all soft parameters. -/ +theorem scalar_exact_forward_point_bound (A : Instance I J) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N b : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 0 < K) (hN : 0 < N) (hb : 0 < b) (hbN : b ≤ N) + (hkN : k+N ≤ cellWidth A t) (hend : 1 ≤ scalarExact A alpha t (k+N)) : + scalarExact A alpha t k/(∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A alpha t q) ≤ + (2*K:ℝ)/b := by + have hnonneg : ∀ q,q ≤ cellWidth A t → 0 ≤ scalarExact A alpha t q := + scalar_exact_nonnegative A alpha t ha + have hmass := Finset.single_le_sum + (fun q hq => hnonneg q (by have := Finset.mem_range.mp hq; omega)) + (Finset.mem_range.mpr (show k+N < cellWidth A t+1 by omega)) + have hC : 0 < ∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A alpha t q := by + linarith + apply half_window_mass_bound (scalarExact A alpha t) (cellWidth A t) k N K b hK hb hbN hkN + hnonneg hC + intro r hr + exact scalar_exact_half_window A alpha t ha hW B K k N hB hBK hK hN hkN hend r hr + +theorem scalar_exact_backward_point_bound (A : Instance I J) (alpha : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hW : 20*A.d ≤ A.W) (B K k N b : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) + (hK : 0 < K) (hN : 0 < N) (hb : 0 < b) (hbN : b ≤ N) + (hNk : N ≤ k) (hk : k ≤ cellWidth A t) (hend : 1 ≤ scalarExact A alpha t (k-N)) : + scalarExact A alpha t k/(∑ q ∈ Finset.range (cellWidth A t+1),scalarExact A alpha t q) ≤ + (2*K:ℝ)/b := by + let U := cellWidth A t + let a : ℕ → ℝ := fun q => scalarExact A alpha t (U-q) + have hsum : (∑ q ∈ Finset.range (U+1),a q)= + ∑ q ∈ Finset.range (U+1),scalarExact A alpha t q := by + simpa only [a,Nat.add_sub_cancel] using Finset.sum_range_reflect (scalarExact A alpha t) (U+1) + have hnonneg : ∀ q,q ≤ U → 0 ≤ a q := by + intro q _ + exact scalar_exact_nonnegative A alpha t ha _ (Nat.sub_le _ _) + have hend' : 1 ≤ a (U-k+N) := by + change 1 ≤ scalarExact A alpha t (U-(U-k+N)) + rw [show U-(U-k+N)=k-N by dsimp only [U] at *; omega] + exact hend + have hmass := Finset.single_le_sum + (fun q hq => hnonneg q (by have := Finset.mem_range.mp hq; omega)) + (Finset.mem_range.mpr (show U-k+N < U+1 by dsimp only [U] at *; omega)) + have hC : 0 < ∑ q ∈ Finset.range (U+1),a q := by linarith + have hp := half_window_mass_bound a U (U-k) N K b hK hb hbN + (by dsimp only [U] at *; omega) hnonneg hC (by + intro r hr + have hrN : r ≤ N := by nlinarith + change scalarExact A alpha t (U-(U-k))/2 ≤ scalarExact A alpha t (U-(U-k+r)) + rw [show U-(U-k)=k by dsimp only [U] at *; omega, + show U-(U-k+r)=k-r by dsimp only [U] at *; omega] + exact scalar_exact_backward_half_window A alpha t ha hW B K k N hB hBK hK hN hNk hk hend r hr) + change scalarExact A alpha t (U-(U-k))/(∑ q ∈ Finset.range (U+1),a q) ≤ (2*K:ℝ)/b at hp + rw [show U-(U-k)=k by dsimp only [U] at *; omega,hsum] at hp + exact hp + +end ContingencyTables.TreeMarginalSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..caaa0de1c336dfc1b2cb20193274410bf7403c8f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalEnumeration.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalSignature +import OAI.Combinatorics.ContingencyTables.Transport.BalancedCellFibres + +namespace OAI + +/-! # The physical one-cell marginal is exactly its balanced assignment fibre -/ + +namespace ContingencyTables.TreeMarginalSignature + +open scoped BigOperators Classical +open CompanionFactorialApplication ForestPenaltyApplication LargePairEnumeration +open PhysicalLargeProfiles BalancedFamily BalancedEnumeration BalancedCellFibres +open IntegerWeightedTransport + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def otherCells (t : I×J) : LargeCell (keep t) ≃ {a : I×J // a≠t} where + toFun a := ⟨a.val,by simpa only [keep,decide_eq_false_iff_not] using a.property⟩ + invFun a := ⟨a.val,by simpa only [keep,decide_eq_false_iff_not] using a.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +lemma one_view_reindex (A : Instance I J) (t : I×J) (z : Bool → ℕ) + (a : (k : Fin (Fintype.card (LargeCell (keep t)))) → Fin (otherWidths A t k+1)) : + joinedProfile (otherWidths A t) z a ∘ + ((Equiv.sumCongr (singleView t).symm (Equiv.refl _)).trans + (physicalJoinEquiv (keep t) (enumeration t))).symm= + joinedProfile (otherWidths A t) (z ∘ singleView t) a ∘ + (physicalJoinEquiv (keep t) (enumeration t)).symm := by + funext u + change joinedProfile (otherWidths A t) z a + ((Equiv.sumCongr (singleView t).symm (Equiv.refl _)).symm + ((physicalJoinEquiv (keep t) (enumeration t)).symm u))= + joinedProfile (otherWidths A t) (z ∘ singleView t) a + ((physicalJoinEquiv (keep t) (enumeration t)).symm u) + generalize (physicalJoinEquiv (keep t) (enumeration t)).symm u=q + cases q <;> rfl + +lemma eliminate_eq_view_sum (A : Instance I J) (t : I×J) + (F : ((I×J)×Bool → ℕ) → ℝ) (z : Bool → ℕ) : + eliminate (widths (otherWidths A t)) (fun q => F (q ∘ (coordinateEquiv A t).symm)) z= + ∑ a : ((k : Fin (Fintype.card (LargeCell (keep t)))) → Fin (otherWidths A t k+1)), + F (joinedProfile (otherWidths A t) (z ∘ singleView t) a ∘ + (physicalJoinEquiv (keep t) (enumeration t)).symm) := by + change eliminate (widths (otherWidths A t)) (fun q => + F ((q ∘ (LargePairEnumeration.coordinateEquiv Bool (otherWidths A t)).symm) ∘ + ((Equiv.sumCongr (singleView t).symm (Equiv.refl _)).trans + (physicalJoinEquiv (keep t) (enumeration t))).symm)) z=_ + rw [LargePairEnumeration.eliminate_eq_physical_sum (otherWidths A t) + (fun q => F (q ∘ ((Equiv.sumCongr (singleView t).symm (Equiv.refl _)).trans + (physicalJoinEquiv (keep t) (enumeration t))).symm)) z] + apply Finset.sum_congr rfl + intro a _ + exact congrArg F (one_view_reindex A t z a) + +theorem eliminate_eq_one_cell_sum (A : Instance I J) (t : I×J) + (F : ((I×J)×Bool → ℕ) → ℝ) (z : Bool → ℕ) : + eliminate (widths (otherWidths A t)) (fun q => F (q ∘ (coordinateEquiv A t).symm)) z= + ∑ a : PhysicalAssignments (keep t) (cellWidth A), + F (physicalProfile (keep t) (cellWidth A) (z ∘ singleView t) a) := by + rw [eliminate_eq_view_sum] + convert sum_joined_eq_physical (keep t) (cellWidth A) (enumeration t) (z ∘ singleView t) F using 1 + · rfl + · apply Finset.sum_congr + · ext a + simp + · intro a _ + rfl + +lemma physical_one_cell_profile (A : Instance I J) (t : I×J) + (k : Fin (cellWidth A t+1)) (a : BalancedCellFibres.Others (cellWidth A) t) : + physicalProfile (keep t) (cellWidth A) (childProfile (cellWidth A t) k.val ∘ singleView t) + ((Equiv.piCongrLeft (fun c : {c : I×J // c≠t} => Fin (cellWidth A c.val+1)) + (otherCells t)).symm a)= + BalancedCellFibres.profile (cellWidth A) (join (cellWidth A) t k a) := by + funext u + rcases u with ⟨c,b⟩ + by_cases hc : c=t + · subst c + cases b <;> simp [physicalProfile,keep,singleView,BalancedCellFibres.profile,join_at] <;> rfl + · have hkeep : keep t c=false := by simp only [keep,decide_eq_false_iff_not]; exact hc + simp only [physicalProfile,hkeep,Bool.false_eq_true,dite_false,BalancedCellFibres.profile] + rw [join_other (cellWidth A) t k a ⟨c,hc⟩] + rfl + +/-- No multiplicity or factorial appears: the exact retained-cell +balanced marginal is the literal full physical assignment fibre. -/ +theorem exact_eq_fibre (A : Instance I J) (alpha : ℝ) (t : I×J) + (k : Fin (cellWidth A t+1)) : + scalarExact A alpha t k.val= + fibre (cellWidth A) + (physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha) t k := by + unfold scalarExact exactMarginal + rw [eliminate_eq_one_cell_sum,fibre_eq_sum] + apply Fintype.sum_equiv + (Equiv.piCongrLeft (fun c : {c : I×J // c≠t} => Fin (cellWidth A c.val+1)) (otherCells t)) + intro a + congr 1 + have h := physical_one_cell_profile A t k + ((Equiv.piCongrLeft (fun c : {c : I×J // c≠t} => Fin (cellWidth A c.val+1)) (otherCells t)) a) + simpa only [Equiv.symm_apply_apply] using h + +end ContingencyTables.TreeMarginalSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalSignature.lean b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalSignature.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce1eed6a8033e8cfb85b2ba4b5304ec5e6ab29e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Rooted/TreeMarginalSignature.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllBalancedWidths +import OAI.Combinatorics.ContingencyTables.Rooted.ForestBoxCardinality +import OAI.Combinatorics.ContingencyTables.Transport.PositiveSequenceInterpolation + +namespace OAI + +/-! # The actual one-tree physical marginal before the equality limit + +One physical cell is retained as its doubled Boolean pair. Every other +physical cell, including small capacities zero and one, is summed at +balance. The resulting positive scalar sequence has the proved raw +log-concavity and finite interpolation bounds. +-/ + +namespace ContingencyTables.TreeMarginalSignature + +open scoped BigOperators Classical Matrix Topology +open Filter CommonBasesFPRAS CompanionFactorialApplication ForestPenaltyApplication +open LargePairEnumeration BalancedFamily BalancedBox EqualitySoftening IntegerWeightedTransport RowColumnPenalties + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def keep (t a : I×J) : Bool := decide (a=t) + +noncomputable def singleView (t : I×J) : SmallView (keep t) ≃ Bool where + toFun p := p.2 + invFun b := (⟨t,by simp [keep]⟩,b) + left_inv p := by + have hp : p.1.val=t := by simpa only [keep,decide_eq_true_eq] using p.1.property + rcases p with ⟨⟨a,ha⟩,b⟩ + dsimp only at hp + subst a + rfl + right_inv b := rfl + +noncomputable def enumeration (t : I×J) : Fin (Fintype.card (LargeCell (keep t))) ≃ LargeCell (keep t) := + (Fintype.equivFin _).symm + +noncomputable def cellWidth (A : Instance I J) (a : I×J) : ℕ := + ForestLiteralCount.width A.T A.d A.b a.1 a.2 + +noncomputable def otherWidths (A : Instance I J) (t : I×J) : + Fin (Fintype.card (LargeCell (keep t))) → ℕ := fun k => cellWidth A (enumeration t k).val + +noncomputable def coordinateEquiv (A : Instance I J) (t : I×J) : + Coordinates Bool (widths (otherWidths A t)) ≃ (I×J)×Bool := + (LargePairEnumeration.coordinateEquiv Bool (otherWidths A t)).trans + ((Equiv.sumCongr (singleView t).symm (Equiv.refl _)).trans + (physicalJoinEquiv (keep t) (enumeration t))) + +noncomputable def soft (A : Instance I J) (alpha L : ℝ) (t : I×J) : (Bool → ℕ) → ℝ := + eliminate (widths (otherWidths A t)) (fun z => + softenedWeight cellLine (rootFlag A.T) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) L (z ∘ (coordinateEquiv A t).symm)) + +noncomputable def exactMarginal (A : Instance I J) (alpha : ℝ) (t : I×J) : (Bool → ℕ) → ℝ := + eliminate (widths (otherWidths A t)) (fun z => + physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha (z ∘ (coordinateEquiv A t).symm)) + +theorem soft_slices (A : Instance I J) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) : + PositiveSlice (soft A alpha L t) (fun _ => cellWidth A t) (cellWidth A t) ∧ + RemovalSlice (soft A alpha L t) (fun _ => cellWidth A t) (cellWidth A t) := by + apply EqualityReindex.physical_softened_slices_all + (widths (otherWidths A t)) (fun _ => cellWidth A t) (cellWidth A t) (coordinateEquiv A t) + · exact fun _ => ha + · intro a + unfold unaryRate + split_ifs + · exact div_nonneg ha (Nat.cast_nonneg _) + · exact le_rfl + · exact hL + +noncomputable def scalarSoft (A : Instance I J) (alpha L : ℝ) (t : I×J) (k : ℕ) : ℝ := + soft A alpha L t (childProfile (cellWidth A t) k) + +noncomputable def scalarExact (A : Instance I J) (alpha : ℝ) (t : I×J) (k : ℕ) : ℝ := + exactMarginal A alpha t (childProfile (cellWidth A t) k) + +theorem scalar_positive (A : Instance I J) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (k : ℕ) (hk : k ≤ cellWidth A t) : + 0 < scalarSoft A alpha L t k := + (soft_slices A alpha L t ha hL).1 _ + (childProfile_inBox _ _ hk) (childProfile_total _ _ hk) + +theorem scalar_logConcave (A : Instance I J) (alpha L : ℝ) (t : I×J) + (ha : 0 ≤ alpha) (hL : 0 ≤ L) (k : ℕ) (hk : k+2 ≤ cellWidth A t) : + scalarSoft A alpha L t k*scalarSoft A alpha L t (k+2) ≤ + (scalarSoft A alpha L t (k+1))^2 := + child_logConcave (soft A alpha L t) _ (soft_slices A alpha L t ha hL).1 + (soft_slices A alpha L t ha hL).2 k hk + +/-- Every retained tree mass is the finite equality-softening limit of +its actual positive physical balanced sum. -/ +theorem scalar_tendsto (A : Instance I J) (alpha : ℝ) (t : I×J) (k : ℕ) : + Tendsto (fun L : ℝ => scalarSoft A alpha L t k) atTop (nhds (scalarExact A alpha t k)) := by + apply eliminate_tendsto (widths (otherWidths A t)) + intro z + exact softenedWeight_tendsto cellLine (rootFlag A.T) (fun _ => alpha) + (lineOffset (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c) + viewSlope (unaryRate A.T A.b alpha) (unaryEll (ForestLiteralCount.lower A.T A.d A.b)) + unarySlope (unaryCap A.b) (z ∘ (coordinateEquiv A t).symm) + +end ContingencyTables.TreeMarginalSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllBalancedWidths.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllBalancedWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..be1977da5df654eba1816d68d022feadcada200f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllBalancedWidths.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallBalancedMarginal +import OAI.Combinatorics.ContingencyTables.Transport.EqualityReindex + +namespace OAI + +/-! # The actual balanced finite family allows every small-cell capacity + +The proved zero/one boundary cases complete the finite balanced +elimination theorem. The physical equality-softened tree marginal can +therefore eliminate the original small cells directly. +-/ + +namespace ContingencyTables.BalancedBox + +open scoped BigOperators Classical +open IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +theorem marginal_removal_slice_all (F : ((I⊕Bool) → ℕ) → ℝ) + (m : I → ℕ) (R M : ℕ) + (hpos : PositiveSlice F (profile m M M) (R+M)) + (hsig : RemovalSlice F (profile m M M) (R+M)) : + RemovalSlice (marginal F M) m R := by + rcases M with _|M + · exact marginal_zero_removal_slice F m R (by simpa only [add_zero] using hsig) + rcases M with _|M + · exact marginal_one_removal_slice F m R hpos hsig + · exact marginal_removal_slice F m R _ (by omega) hpos hsig + +end ContingencyTables.BalancedBox + +namespace ContingencyTables.BalancedFamily + +open scoped BigOperators Classical +open IntegerMarginal BalancedBox + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- Every original small-cell width, including zero and one, may be +eliminated on its precise box-valid total slice. -/ +theorem eliminate_slices_all (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) + (hpos : PositiveSlice F (bounds m Ms) (R+Ms.sum)) + (hsig : RemovalSlice F (bounds m Ms) (R+Ms.sum)) : + PositiveSlice (eliminate Ms F) m R ∧ RemovalSlice (eliminate Ms F) m R := by + induction Ms with + | nil => simpa only [List.sum_nil,add_zero,eliminate,bounds] using And.intro hpos hsig + | cons M Ms ih => + have htotal : R+(M::Ms).sum=(R+Ms.sum)+M := by simp only [List.sum_cons]; omega + rw [htotal] at hpos hsig + exact ih (marginal F M) + (marginal_positive_slice F (bounds m Ms) (R+Ms.sum) M hpos) + (marginal_removal_slice_all F (bounds m Ms) (R+Ms.sum) M hpos hsig) + +end ContingencyTables.BalancedFamily + +namespace ContingencyTables.EqualityReindex + +open scoped BigOperators Classical +open EqualitySoftening BalancedFamily BalancedBox + +variable {S D G : Type*} [Fintype S] [DecidableEq S] [Fintype D] [Fintype G] + +omit [DecidableEq S] in +lemma softenedWeight_reindex (Ms : List ℕ) (e : Coordinates S Ms ≃ D) + (line : D → G) (root : G → Bool) (rate offset slope : G → ℝ) + (urate ell uslope cap : D → ℝ) (L : ℝ) (z : Coordinates S Ms → ℕ) : + softenedWeight (line ∘ e) root rate offset slope (urate ∘ e) (ell ∘ e) + (uslope ∘ e) (cap ∘ e) L z= + softenedWeight line root rate offset slope urate ell uslope cap L (z ∘ e.symm) := by + unfold softenedWeight + exact productWeight_reindex e line (lineFactor root rate offset slope L) + (unaryFactor urate ell uslope cap) z + +/-- The literal physical positive factor family can retain one tree +pair while summing all other original pairs, at every capacity. -/ +theorem physical_softened_slices_all (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : D → ℝ) (L : ℝ) + (hrate : ∀ g,0 ≤ rate g) (hu : ∀ d,0 ≤ urate d) (hL : 0 ≤ L) : + PositiveSlice (eliminate Ms (fun z => + softenedWeight line root rate offset slope urate ell uslope cap L (z ∘ e.symm))) m R ∧ + RemovalSlice (eliminate Ms (fun z => + softenedWeight line root rate offset slope urate ell uslope cap L (z ∘ e.symm))) m R := by + have heq : (fun z => softenedWeight line root rate offset slope urate ell uslope cap L + (z ∘ e.symm))=softenedWeight (line ∘ e) root rate offset slope + (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) L := by + funext z + exact (softenedWeight_reindex Ms e line root rate offset slope urate ell uslope cap L z).symm + rw [heq] + apply eliminate_slices_all Ms m R + · intro z _ _ + exact softenedWeight_positive (line ∘ e) root rate offset slope + (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) L z + · intro z _ _ + convert softenedWeight_removal (line ∘ e) root rate offset slope + (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) L hrate (fun i => hu (e i)) hL z using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +end ContingencyTables.EqualityReindex + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ad12b42c59e76187711d133e3f7b2d0fa8c76dd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingAccuracy.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingSemantics +import OAI.Combinatorics.ContingencyTables.Transport.ListedScheduledSampler + +namespace OAI + +/-! # Accuracy of the single computed sampler for arbitrary margins -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open ResidualMixture FirstSuccess FairBits SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +/-- The mathematical draw whose code is the output of the single public program. -/ +def scheduledTableDraw (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) + (bits : Fin (finiteSamplerBits r c k) → Bool) : Table r c := + if h : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true then + listedOuterDraw r c (computedCellEquiv r c) + ((hasLargeRectangle_spec r c k).mp h).1 ((hasLargeRectangle_spec r c k).mp h).2 + b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 + (tableState r c (GreedyFeasibleTable.table r c htotal)) + (outerSteps d b k) (outerTrials d k) (GreedyFeasibleTable.table r c htotal) bits + else + unitCodeOuterDraw r c (computedCellEquiv r c) (allSmallFibre r c (allSmall_of_no_large r c k h)) + (tableState r c (GreedyFeasibleTable.table r c htotal)) (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.table r c htotal) (prefixWord (unitCodeBits_le r c k) bits) + +theorem samplingMatrixAll_code (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) + (bits : Fin (finiteSamplerBits r c k) → Bool) : + samplingMatrixAll (((List.ofFn r,List.ofFn c),k),List.ofFn bits)= + matrixCode (scheduledTableDraw r c htotal k bits).val := by + unfold samplingMatrixAll scheduledTableDraw + by_cases h : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true + · rw [ite_eq_left h,dite_eq_left h] + exact samplingMatrix_code r c ((hasLargeRectangle_spec r c k).mp h).1 + ((hasLargeRectangle_spec r c k).mp h).2 htotal k bits + · rw [ite_eq_right h,dite_eq_right h] + exact unitSamplingMatrix_code r c (allSmall_of_no_large r c k h) htotal k bits + +theorem publicSamplingAll_spec (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) + (bits : Fin (finiteSamplerBits r c k) → Bool) : + publicSamplingAll (Algorithms.encodeSamplingInput r c k,List.ofFn bits)= + Algorithms.encodeMatrix (scheduledTableDraw r c htotal k bits).val := by + rw [publicSamplingAll,parsedSampling_spec,samplingMatrixAll_code r c htotal] + exact GreedyFeasibleTable.printMatrix_ofFn _ + +private lemma law_uniform_of_subsingleton {Y : Type*} [Fintype Y] [Subsingleton Y] + [Nonempty Y] (p : RationalLaw Y) : p=uniformLaw (α := Y) := by + apply RationalLaw.ext + funext y + let : Unique Y := ⟨⟨y⟩,fun z => Subsingleton.elim z y⟩ + have ht : p.mass (default : Y)=1 := by simpa using p.total + have hy : p.mass y=1 := (congrArg p.mass (Subsingleton.elim y default)).trans ht + simp only [uniformLaw,uniformMass,Fintype.card_unique,Nat.cast_one,div_one,hy] + +private lemma variation_uniform_of_subsingleton {Y : Type*} [Fintype Y] [Subsingleton Y] + [Nonempty Y] (p : RationalLaw Y) : variation p (uniformLaw (α := Y))=0 := by + rw [law_uniform_of_subsingleton p,variation_self] + +/-- Only the two cited published inputs on the completion grid are used. +The small and zero-dimensional branches need neither input. -/ +theorem scheduledTableDraw_accuracy + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) (hk : 1≤k) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + (variation (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c k) → Bool)) + (scheduledTableDraw r c htotal k)) (uniformLaw (α := Table r c)):ℝ)≤1/(2:ℝ)^k := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + let : Nonempty (PaperStates r c) := ⟨tableState r c (GreedyFeasibleTable.table r c htotal)⟩ + dsimp only + unfold scheduledTableDraw + split_ifs with h + · exact listedScheduledDraw_accuracy r c (computedCellEquiv r c) + ((hasLargeRectangle_spec r c k).mp h).1 ((hasLargeRectangle_spec r c k).mp h).2 + hPL hCheeger htotal (tableState r c (GreedyFeasibleTable.table r c htotal)) + (GreedyFeasibleTable.table r c htotal) k hk + · have hs := allSmall_of_no_large r c k h + rcases isEmpty_or_nonempty (Fin m) with hm|hm + · let := hm + let : Subsingleton (Table r c) := ⟨fun X Y => Subtype.ext (by funext i; exact isEmptyElim i)⟩ + rw [variation_uniform_of_subsingleton,Rat.cast_zero] + positivity + · rcases isEmpty_or_nonempty (Fin n) with hn|hn + · let := hn + let : Subsingleton (Table r c) := ⟨fun X Y => Subtype.ext (by funext i j; exact isEmptyElim j)⟩ + rw [variation_uniform_of_subsingleton,Rat.cast_zero] + positivity + · let := hm + let := hn + rw [padded_draw_law,unitCodeOuterDraw_law r c (computedCellEquiv r c) htotal] + exact unitOuterDraw_accuracy r c hs htotal k hk (allSmallFibre r c hs) + (tableState r c (GreedyFeasibleTable.table r c htotal)) (GreedyFeasibleTable.table r c htotal) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..993fa31b3a79687d406971b64614b7c5f0a88f74 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingMachine.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingAccuracy +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRuntimeBound +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordTableLaw + +namespace OAI + +/-! # The bounded public sampler on every margin pair -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +noncomputable def allSamplingMachine : RandomMachine := + FiniteWordExecution.machine publicWordCountRealizer publicSamplingAllRealizer +noncomputable def allSamplingMachineTime (as : List MatchingFPRAS.Symbol) : ℕ := + FiniteWordExecution.machineTime publicWordCountRealizer publicSamplingAllRealizer as + +lemma publicSamplingAll_alphabet (as : List MatchingFPRAS.Symbol) (bits : List Bool) : + ∀ a∈publicSamplingAll (as,bits),a≠6 ∧ a≠7 := printMatrix_alphabet _ + +lemma allSamplingMachineTime_polynomial : + ∃ p : Polynomial ℕ,∀ as,allSamplingMachineTime as≤p.eval + (FiniteWordExecution.wordMeasure publicWordCount as) := + FiniteWordExecution.machineTime_polynomial polynomial_publicWordCount polynomial_publicSamplingAll + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.TreeTyped Turing Algorithms Polynomial +open ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section + +lemma allSamplingMachineTime_public_bound : + ∃ C d : ℕ,0 ∃ X : Table r c, + tape.right₀=ListBlank.mk (encodeMatrix X.val) + have hf : ∀ bits : Bits (publicWordCount as),P (Tape.mk₁ (publicSamplingAll (as,List.ofFn bits))) := by + dsimp only [as] + rw [publicWordCount_spec] + intro bits + refine ⟨scheduledTableDraw r c htotal k bits,?_⟩ + rw [publicSamplingAll_spec r c htotal] + simp only [Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + have hP := FiniteWordExecution.machine_all publicWordCountRealizer publicSamplingAllRealizer as + (samplingInput_nonzero r c k) (publicSamplingAll_alphabet as) P hf t ht + have hhalt := (FiniteWordExecution.machine_law publicWordCountRealizer publicSamplingAllRealizer as + (samplingInput_nonzero r c k) (publicSamplingAll_alphabet as) t ht).1 + intro bits + obtain ⟨X,hX⟩ := hP bits + exact ⟨X,hhalt bits,hX⟩ + +lemma allSamplingMachine_mass (htotal : (∑ i,r i)=∑ j,c j) (k t : ℕ) + (ht : allSamplingMachineTime (encodeSamplingInput r c k)≤t) (X : Table r c) : + tableMass allSamplingMachine (encodeSamplingInput r c k) t X.val= + ((mapLaw (uniformLaw (α := Bits (finiteSamplerBits r c k))) + (scheduledTableDraw r c htotal k)).mass X:ℝ) := + FiniteWordExecution.machine_tableMass publicWordCountRealizer publicSamplingAllRealizer + (encodeSamplingInput r c k) (samplingInput_nonzero r c k) + (publicSamplingAll_alphabet _) (publicWordCount_spec r c k) (scheduledTableDraw r c htotal k) + (publicSamplingAll_spec r c htotal k) t ht X + +/-- Paper 200-01, main theorem (i), conditional only on Prékopa (1973) +Theorem 3/(2.3) on finite boxes and Levin--Peres (2017) Theorem 13.10, +(13.6), Lemma 13.7 on the completion grids. -/ +theorem boundedSampling_conditional + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q d,PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin q) (4*d^8))) : BoundedSamplingStatement := by + obtain ⟨C,D,hC,hbound⟩ := allSamplingMachineTime_public_bound + refine ⟨allSamplingMachine,C,D,hC,?_⟩ + intro m n r c htotal k hk + dsimp only + have ht := hbound m n r c htotal k + refine ⟨allSamplingMachine_outputs r c htotal k _ ht,?_⟩ + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + have hv := scheduledTableDraw_accuracy r c (hPL _) + (hCheeger _ (dimensionAllowance (I := Fin m) (J := Fin n))) htotal k hk + dsimp only at hv + simp_rw [allSamplingMachine_mass r c htotal k _ ht] + simpa only [variation,Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub, + Rat.cast_ofNat,Rat.cast_inv,uniformLaw,uniformMass,Rat.cast_one,Rat.cast_natCast,one_div] using hv + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8772dbf51815bcc80a9387fbd69821ed688e475a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingProgram.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicProgram + +namespace OAI + +/-! # A single computed sampler for large and all-small rectangles -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +def parameterUnitWords (z : SamplingParameters) : ℕ := + parameterTrials z*(parameterSteps z*parameterProposalWidth z) +def parameterUnitWordsRealizer : Realizer parameterUnitWords := + composition (f := fun z : SamplingParameters => + (parameterTrials z,parameterSteps z*parameterProposalWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair parameterTrialsRealizer + (composition (f := fun z : SamplingParameters => (parameterSteps z,parameterProposalWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair parameterStepsRealizer parameterProposalWidthRealizer) multiply)) multiply + +theorem polynomial_parameterUnitWords : PolynomialTime parameterUnitWordsRealizer := + polynomial_composition (polynomial_pair polynomial_parameterTrials + (polynomial_composition (polynomial_pair polynomial_parameterSteps polynomial_parameterProposalWidth) + polynomial_multiply)) polynomial_multiply + +attribute [local irreducible] parameterUnitWords + +abbrev SamplingWordInput := SamplingParameters×List Bool + +def unitSamplingBits (z : SamplingWordInput) : List Bool := + z.2.take (parameterUnitWords z.1) +def unitSamplingBitsRealizer : Realizer unitSamplingBits := + composition (f := fun z : SamplingWordInput => (z.2,parameterUnitWords z.1)) + (g := fun z : List Bool×ℕ => z.1.take z.2) + (pair (f := fun z : SamplingWordInput => z.2) + (g := fun z : SamplingWordInput => parameterUnitWords z.1) second + (composition (f := fun z : SamplingWordInput => z.1) + (g := parameterUnitWords) first parameterUnitWordsRealizer)) takeFast + +theorem polynomial_unitSamplingBits : PolynomialTime unitSamplingBitsRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_parameterUnitWords)) polynomial_takeFast + +def unitSamplingInput (z : SamplingWordInput) : ProfileRetryData := + (samplingRetryParameters z.1,unitSamplingBits z) +def unitSamplingInputRealizer : Realizer unitSamplingInput := + pair (composition (f := fun z : SamplingWordInput => z.1) (g := samplingRetryParameters) + first samplingRetryParametersRealizer) unitSamplingBitsRealizer + +theorem polynomial_unitSamplingInput : PolynomialTime unitSamplingInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_samplingRetryParameters) + polynomial_unitSamplingBits + +def unitSamplingMatrix (z : SamplingWordInput) : MatrixCode := unitProfileRetry (unitSamplingInput z) +def unitSamplingMatrixRealizer : Realizer unitSamplingMatrix := + composition (f := unitSamplingInput) (g := unitProfileRetry) + unitSamplingInputRealizer unitProfileRetryRealizer + +theorem polynomial_unitSamplingMatrix : PolynomialTime unitSamplingMatrixRealizer := + polynomial_composition polynomial_unitSamplingInput polynomial_unitProfileRetry + +def parameterLargeIndices (row : Bool) (z : SamplingParameters) : List ℕ := + largeIndices (marginThreshold z.1,if row then z.1.1 else z.1.2) +def parameterLargeIndicesRealizer (row : Bool) : Realizer (parameterLargeIndices row) := by + cases row with + | false => + exact composition + (f := fun z : SamplingParameters => (marginThreshold z.1,z.1.2)) (g := largeIndices) + (pair (composition (f := fun z : SamplingParameters => z.1) (g := marginThreshold) + first marginThresholdRealizer) (composition first second)) largeIndicesRealizer + | true => + exact composition + (f := fun z : SamplingParameters => (marginThreshold z.1,z.1.1)) (g := largeIndices) + (pair (composition (f := fun z : SamplingParameters => z.1) (g := marginThreshold) + first marginThresholdRealizer) (composition first first)) largeIndicesRealizer + +theorem polynomial_parameterLargeIndices (row : Bool) : PolynomialTime (parameterLargeIndicesRealizer row) := by + cases row with + | false => exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_marginThreshold) + (polynomial_composition polynomial_first polynomial_second)) polynomial_largeIndices + | true => exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_marginThreshold) + (polynomial_composition polynomial_first polynomial_first)) polynomial_largeIndices + +def hasLargeRectangle (z : SamplingParameters) : Bool := + decide (0<(parameterLargeIndices true z).length) && decide (0<(parameterLargeIndices false z).length) +def hasLargeRectangleRealizer : Realizer hasLargeRectangle := + composition (f := fun z : SamplingParameters => + (decide (0<(parameterLargeIndices true z).length),decide (0<(parameterLargeIndices false z).length))) + (g := fun p : Bool×Bool => p.1 && p.2) + (pair + (composition (f := fun z : SamplingParameters => (0,(parameterLargeIndices true z).length)) + (g := fun p : ℕ×ℕ => decide (p.1 (0,(parameterLargeIndices false z).length)) + (g := fun p : ℕ×ℕ => decide (p.1 z.1) (g := hasLargeRectangle) + first hasLargeRectangleRealizer) samplingMatrixRealizer unitSamplingMatrixRealizer + +theorem polynomial_samplingMatrixAll : PolynomialTime samplingMatrixAllRealizer := + polynomial_choose (polynomial_composition polynomial_first polynomial_hasLargeRectangle) + polynomial_samplingMatrix polynomial_unitSamplingMatrix + +def publicSamplingAll (z : List MatchingFPRAS.Symbol×List Bool) : List MatchingFPRAS.Symbol := + GreedyFeasibleTable.printMatrix (samplingMatrixAll (parsedSampling z.1,z.2)) +def publicSamplingAllRealizer : Realizer publicSamplingAll := + composition (f := fun z : List MatchingFPRAS.Symbol×List Bool => + samplingMatrixAll (parsedSampling z.1,z.2)) (g := GreedyFeasibleTable.printMatrix) + (composition (f := fun z : List MatchingFPRAS.Symbol×List Bool => (parsedSampling z.1,z.2)) + (g := samplingMatrixAll) (pair (composition (f := fun z : List MatchingFPRAS.Symbol×List Bool => z.1) + (g := parsedSampling) first parsedSamplingRealizer) second) samplingMatrixAllRealizer) + GreedyFeasibleTable.printMatrixRealizer + +theorem polynomial_publicSamplingAll : PolynomialTime publicSamplingAllRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_parsedSampling) polynomial_second) + polynomial_samplingMatrixAll) GreedyFeasibleTable.polynomial_printMatrix + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..550d00aaac220dca262c81e0329036eee5111aa8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSamplingSemantics.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicSemantics + +namespace OAI + +/-! # One executable program chooses the correct rectangle branch -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open FirstSuccess FairBits SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] unitProfileRetry unitCodeOuterDraw +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +lemma hasLargeRectangle_spec (k : ℕ) : + hasLargeRectangle ((List.ofFn r,List.ofFn c),k)=true ↔ + 0<(largeIndices (d^20,List.ofFn r)).length ∧ + 0<(largeIndices (d^20,List.ofFn c)).length := by + simp only [hasLargeRectangle,parameterLargeIndices,marginThreshold_ofFn, + ite_true,Bool.false_eq_true,ite_false,Bool.and_eq_true,decide_eq_true_eq] + +lemma allSmall_of_no_large (k : ℕ) + (h : hasLargeRectangle ((List.ofFn r,List.ofFn c),k)≠true) : + ∀ i j,paperSmall r c i j=true := by + intro i j + apply Bool.eq_true_of_ne_false + intro hij + obtain ⟨hi,hj⟩ := (firstPaperSmall_false_iff r c (d^20) i j).mp hij + have a := (largeIndexEquiv r (d^20)).symm ⟨i,hi⟩ + have b' := (largeIndexEquiv c (d^20)).symm ⟨j,hj⟩ + apply h + apply (hasLargeRectangle_spec r c k).mpr + exact ⟨Nat.zero_lt_of_lt a.isLt,Nat.zero_lt_of_lt b'.isLt⟩ + +lemma parameterUnitWords_ofFn (k : ℕ) : + parameterUnitWords ((List.ofFn r,List.ofFn c),k)=outerTrials d k*(outerSteps d b k*s) := by + rw [parameterUnitWords,parameterTrials_ofFn,parameterSteps_ofFn,parameterProposalWidth_ofFn] + +lemma unitCodeBits_le (k : ℕ) : outerTrials d k*(outerSteps d b k*s)≤finiteSamplerBits r c k := by + apply Nat.mul_le_mul_left + exact (Nat.mul_le_mul_left (outerSteps d b k) + (Nat.le_add_right s (25*(d+b+outerAccuracy d b k+1)^62))).trans (Nat.le_add_right _ _) + +lemma scheduled_steps_pos (k : ℕ) : 0 List.ofFn (GreedyFeasibleTable.matrix r c i)) := rfl + rw [hcode] at hdraw + simpa only [Table] using hdraw + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallBoolean.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallBoolean.lean new file mode 100644 index 0000000000000000000000000000000000000000..be33f0f3c7035cbcd1637d08486ba69b5f1f1dc6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallBoolean.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallRational +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanProposal +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDeterministicJoint +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealRejection + +namespace OAI + +/-! # Boolean implementation when all cells are retained -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits CompletionTranslation CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "s" => smallProposalBits (I := I) (J := J) +local instance : DecidableEq (PaperStates r c) := Classical.decEq _ + +def unitBitStep (x : PaperStates r c) (bits : Fin s → Bool) : PaperStates r c := + (smallBitProposal r c x bits).getD x + +lemma unitBitStep_law (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin s → Bool)) (unitBitStep r c x)=unitSmallStep r c x := by + unfold unitBitStep + calc + _ = mapLaw (mapLaw (uniformLaw (α := Fin s → Bool)) (smallBitProposal r c x)) + (fun z : Option (PaperStates r c) => z.getD x) := + (mapLaw_comp _ (smallBitProposal r c x) + (fun z : Option (PaperStates r c) => z.getD x)).symm + _ = _ := by rw [smallBitProposal_law_decidableEq r c _ x]; rfl + +def flatUnitWalk (x : PaperStates r c) (n : ℕ) (bits : Fin (n*s) → Bool) : PaperStates r c := + wordWalk (unitBitStep r c) x n (GridBoundary.gridWordEquiv n s bits) + +lemma flatUnitWalk_law (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (flatUnitWalk r c x n)= + walkLaw (unitSmallStep r c) x n := by + unfold flatUnitWalk + rw [←map_equiv (GridBoundary.gridWordEquiv n s),uniform_equiv] + change wordWalkLaw _ _ _=_ + rw [wordWalkLaw_eq] + exact congrArg (fun K => walkLaw K x n) (funext (unitBitStep_law r c)) + +lemma uniform_singleton_joint [Nonempty (PaperStates r c)] + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (fallback : (z : PaperStates r c) → PaperFibre r c z) : + mapLaw (uniformLaw (α := PaperStates r c)) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c))= + uniformLaw (α := PaperStateJoint r c) := by + rw [mapLaw_deterministicJoint] + have he (z : PaperStates r c) : pointLaw (fallback z)=uniformLaw (α := PaperFibre r c z) := by + let : Subsingleton (PaperFibre r c z) := + PhysicalCompletionFibres.completionFibre_subsingleton _ _ _ _ _ _ _ hsmall + exact pointLaw_eq_uniform _ + simp_rw [he] + apply dependentJointLaw_uniform + intro z + simp only [uniformLaw,uniformMass,paperFibre_card_allSmall r c hsmall, + Nat.cast_one,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + + +def unitJointDraw (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n : ℕ) (bits : Fin (n*s) → Bool) : PaperStateJoint r c := + let z := flatUnitWalk r c x n bits + ⟨z,fallback z⟩ + +lemma unitJointDraw_law (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (unitJointDraw r c fallback x n)= + mapLaw (walkLaw (unitSmallStep r c) x n) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c)) := by + unfold unitJointDraw + calc + _ = mapLaw (mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (flatUnitWalk r c x n)) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c)) := + (mapLaw_comp _ (flatUnitWalk r c x n) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c))).symm + _ = _ := by rw [flatUnitWalk_law] + +theorem unitJointDraw_variation [Nonempty I] [Nonempty J] [Nonempty (PaperStates r c)] + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n : ℕ) : + (variation (mapLaw (uniformLaw (α := Fin (n*s) → Bool)) + (unitJointDraw r c fallback x n)) (uniformLaw (α := PaperStateJoint r c)):ℝ) ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) := by + rw [unitJointDraw_law] + have hv := variation_map (walkLaw (unitSmallStep r c) x n) + (uniformLaw (α := PaperStates r c)) (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c)) + rw [uniform_singleton_joint r c hsmall fallback] at hv + exact ((Rat.cast_le (K := ℝ)).mpr hv).trans (unitSmallWalk_variation r c hsmall x n) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..0345d4666a89877d318bdef234b1f8decc9a4e6d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallChain.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallFibres +import OAI.Combinatorics.ContingencyTables.Sampling.UnitGraphEnergy + +namespace OAI + +/-! # The small-state walk when no dense completion remains + +Every retained completion then has weight one. The same local graph is +sampled by accepting every valid proposal; no reference row is chosen. +-/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CompletionCounts CommonBasesFPRAS FiniteExposureVariance + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] +local notation "d" => dimensionAllowance (I := I) (J := J) +local instance : DecidableEq (PaperStates r c) := Classical.decEq _ + +local notation "Adj" => physicalAdjacent r c (d^20) (d^12) (stateCapacity r c) (stateCapacity_small r c) + +def unitSmallChain : FiniteChain (PaperStates r c) := + MetropolisChain.chain (fun _ => 1) (fun _ => by norm_num) Adj + (physicalAdjacent_symmetric r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal d) ((smallProposal_bounds d (by unfold dimensionAllowance; omega)).1.le) + (5*d^2+1) + (physicalAdjacent_degree_allowance r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal_degree d (by unfold dimensionAllowance; omega)) + +lemma unitSmallChain_pi (z : PaperStates r c) : + (unitSmallChain r c).π z=1/(Fintype.card (PaperStates r c):ℝ) := by + simp only [unitSmallChain,MetropolisChain.chain,FiniteChain.ofMoves, + MetropolisChain.normalizer,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + +lemma unitSmallChain_energy (H : PaperStates r c → ℝ) : + (unitSmallChain r c).energy H= + (smallProposal d/(Fintype.card (PaperStates r c):ℝ))* + ((∑ x,∑ y,if Adj x y then (H x-H y)^2 else 0)/2) := by + exact MetropolisChain.unit_chain_energy Adj + (physicalAdjacent_symmetric r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal d) ((smallProposal_bounds d (by unfold dimensionAllowance; omega)).1.le) + (5*d^2+1) + (physicalAdjacent_degree_allowance r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal_degree d (by unfold dimensionAllowance; omega)) H + +omit [Nonempty (PaperStates r c)] in +lemma stateGraphEnergy_allSmall (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (H : PaperStates r c → ℝ) : + stateGraphEnergy r c H=(∑ x,∑ y,if Adj x y then (H x-H y)^2 else 0)/2 := by + have he := fullEnergy_physical_eq r c (d^20) (d^12) (stateCapacity r c) (stateCapacity_small r c) H + change stateGraphEnergy r c H=(∑ x,∑ y,if Adj x y then + min (stateWeight r c x) (stateWeight r c y)*(H x-H y)^2 else 0)/2 at he + simpa only [stateWeight_allSmall r c hsmall,min_self,one_mul] using he + +omit [LinearOrder I] [LinearOrder J] [Nonempty (PaperStates r c)] in +lemma allowance_fourteen [Nonempty I] [Nonempty J] : 14 ≤ d := by + have hi := Fintype.card_pos (α := I) + have hj := Fintype.card_pos (α := J) + unfold dimensionAllowance + nlinarith + +lemma unitSmallChain_pi_weight + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) (z : PaperStates r c) : + (unitSmallChain r c).π z=stateWeight r c z/(∑ y,stateWeight r c y) := by + rw [unitSmallChain_pi] + simp only [stateWeight_allSmall r c hsmall,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + +lemma unitSmallChain_energy_lower + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (H : PaperStates r c → ℝ) : + (smallProposal d)/(2*(∑ z,stateWeight r c z))*stateGraphEnergy r c H ≤ + (unitSmallChain r c).energy H := by + have hsum : (∑ z,stateWeight r c z)=(Fintype.card (PaperStates r c):ℝ) := by + simp only [stateWeight_allSmall r c hsmall,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + have hi := unitSmallChain_energy r c H + rw [←stateGraphEnergy_allSmall r c hsmall H] at hi + rw [hsum] + calc + _ = ((smallProposal d/(Fintype.card (PaperStates r c):ℝ))*stateGraphEnergy r c H)/2 := by ring + _ = (unitSmallChain r c).energy H/2 := by rw [hi] + _ ≤ (unitSmallChain r c).energy H := by linarith [(unitSmallChain r c).energy_nonneg H] + +/-- The full graph bound includes the empty large rectangle. -/ +theorem unitSmallChain_poincare [Nonempty I] [Nonempty J] + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (H : PaperStates r c → ℝ) : + (unitSmallChain r c).variance H ≤ (d:ℝ)^160*(unitSmallChain r c).energy H := by + let K : ℝ := 770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6 + have hβ := (smallProposal_bounds d (by unfold dimensionAllowance; omega)).1 + have hv : variance (stateWeight r c) H ≤ K*stateGraphEnergy r c H := + firstPaper_physical_variance r c H + have hp := chain_poincare_of_weighted_graph (unitSmallChain r c) (stateWeight r c) H + (stateWeight_positive r c) (unitSmallChain_pi_weight r c hsmall) + (stateGraphEnergy r c H) K (smallProposal d) (by dsimp [K]; positivity) hβ hv + (unitSmallChain_energy_lower r c hsmall H) + exact hp.trans (mul_le_mul_of_nonneg_right + (smallProposal_poincare_budget d allowance_fourteen) ((unitSmallChain r c).energy_nonneg H)) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..96a850ef0a2a36a5c6bea0333a45320d34e518c6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallFibres.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperJointLaw + +namespace OAI + +/-! # Empty large rectangles have a unique retained completion -/ + +namespace ContingencyTables.PhysicalCompletionFibres + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- When every cell is retained, both views are fixed by the profile. -/ +theorem completionFibre_subsingleton (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) + (hsmall : ∀ i j,small i j=true) : + Subsingleton (CompletionFibre small B r rbar c cbar z) := by + constructor + intro X Y + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · funext i j + exact (X.property.2.2.1 i j (hsmall i j)).1.trans + (Y.property.2.2.1 i j (hsmall i j)).1.symm + · funext i j + exact (X.property.2.2.1 i j (hsmall i j)).2.trans + (Y.property.2.2.1 i j (hsmall i j)).2.symm + +end ContingencyTables.PhysicalCompletionFibres + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts SmallContextFibres + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +omit [LinearOrder I] [LinearOrder J] in +lemma allSmall_of_no_large_rectangle + (hempty : IsEmpty (LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) ∨ + IsEmpty (LargeColumns c ((dimensionAllowance (I := I) (J := J))^20))) : + ∀ i j,paperSmall r c i j=true := by + intro i j + have he : r i<(dimensionAllowance (I := I) (J := J))^20 ∨ + c j<(dimensionAllowance (I := I) (J := J))^20 := by + rcases hempty with hr|hc + · left + by_contra h + exact hr.false ⟨i,by omega⟩ + · right + by_contra h + exact hc.false ⟨j,by omega⟩ + simpa only [paperSmall,firstPaperSmall,decide_eq_true_eq] using he + +lemma paperFibre_card_allSmall (hsmall : ∀ i j,paperSmall r c i j=true) + (z : PaperStates r c) : Fintype.card (PaperFibre r c z)=1 := by + let : Subsingleton (PaperFibre r c z) := completionFibre_subsingleton _ _ _ _ _ _ _ hsmall + let : Unique (PaperFibre r c z) := ⟨⟨Classical.choice inferInstance⟩,fun x => Subsingleton.elim x _⟩ + exact Fintype.card_unique + +/-- No dense sampler or numerical integral is needed in this branch. -/ +lemma stateWeight_allSmall (hsmall : ∀ i j,paperSmall r c i j=true) + (z : PaperStates r c) : stateWeight r c z=1 := by + change hardMarginal _ _ _ _ _ _=1 + rw [hardMarginal_eq_fibre_card (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + (physicalProfile _ (stateCapacity r c) r c _ z) (naturalProfile_bounded z.val.val)] + exact_mod_cast paperFibre_card_allSmall r c hsmall z + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallInitialization.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..befadc183442e858d72108285c902cd8c1633818 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallInitialization.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallFibres + +namespace OAI + +/-! # Reading the unique all-small completion directly from its profile -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open CompletionCounts PhysicalCompletionFibres PaddedCompletions + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +/-- The output data consists only of the two stored small views. Existence +of a completion supplies the erased proof that these are valid margins. -/ +noncomputable def allSmallFibre + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (z : PaperStates r c) : PaperFibre r c z := by + let p := SmallContextFibres.naturalProfile z.val.val + let views := (fun i j => p (⟨(i,j),hsmall i j⟩,false), + fun i j => stateCapacity r c i j-p (⟨(i,j),hsmall i j⟩,true)) + have hv : ∃ h, (⟨views,h⟩ : RowColumnPair + (fun i => r i+PaddedCompletions.rowLargeCount (FirstPaperPhysicalMarginal.paperSmall r c) i* + ((dimensionAllowance (I := I) (J := J))^12)) + (fun j => c j+PaddedCompletions.columnLargeCount (FirstPaperPhysicalMarginal.paperSmall r c) j* + ((dimensionAllowance (I := I) (J := J))^12))).val=views := by + obtain ⟨Z⟩ := (inferInstance : Nonempty (PaperFibre r c z)) + have he : views=Z.val.val := by + apply Prod.ext + · funext i j + exact (Z.property.2.2.1 i j (hsmall i j)).1.symm + · funext i j + exact (Z.property.2.2.1 i j (hsmall i j)).2.symm + exact ⟨by rw [he]; exact Z.val.property,rfl⟩ + let pair := (⟨views,hv.choose⟩ : RowColumnPair + (fun i => r i+PaddedCompletions.rowLargeCount (FirstPaperPhysicalMarginal.paperSmall r c) i* + ((dimensionAllowance (I := I) (J := J))^12)) + (fun j => c j+PaddedCompletions.columnLargeCount (FirstPaperPhysicalMarginal.paperSmall r c) j* + ((dimensionAllowance (I := I) (J := J))^12))) + refine ⟨pair,?_⟩ + obtain ⟨Z⟩ := (inferInstance : Nonempty (PaperFibre r c z)) + have he : pair=Z.val := by + apply Subtype.ext + apply Prod.ext + · funext i j + exact (Z.property.2.2.1 i j (hsmall i j)).1.symm + · funext i j + exact (Z.property.2.2.1 i j (hsmall i j)).2.symm + exact he.symm ▸ Z.property + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallOuter.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallOuter.lean new file mode 100644 index 0000000000000000000000000000000000000000..e43922a9d7722590d293995b76efca62f8d2ce3f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallOuter.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallBoolean +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallInitialization +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInitialization +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters + +namespace OAI + +/-! # Complete finite rejection sampling when the large rectangle is empty -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "s" => smallProposalBits (I := I) (J := J) +local instance : DecidableEq (PaperStates r c) := Classical.decEq _ + +/-- Each trial reads a disjoint word; failed trials use the feasible fallback. -/ +def unitOuterDraw (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n M : ℕ) (z₀ : Table r c) + (bits : Fin (M*(n*s)) → Bool) : Table r c := + wordRetry (fun w => stateTrial r c (unitJointDraw r c fallback x n w)) z₀ M + (GridBoundary.gridWordEquiv M (n*s) bits) + +lemma unitOuterDraw_law (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n M : ℕ) (z₀ : Table r c) : + mapLaw (uniformLaw (α := Fin (M*(n*s)) → Bool)) + (unitOuterDraw r c fallback x n M z₀)= + retryLaw (mapLaw (uniformLaw (α := Fin (n*s) → Bool)) + (unitJointDraw r c fallback x n)) (stateTrial r c) z₀ M := by + unfold unitOuterDraw + rw [←map_equiv (GridBoundary.gridWordEquiv M (n*s)),uniform_equiv] + change wordRetryLaw _ _ _=_ + rw [wordRetryLaw_eq,←retryLaw_map] + +lemma unitOuterDraw_error [Nonempty I] [Nonempty J] [Nonempty (PaperStates r c)] + [Nonempty (Table r c)] (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (htotal : (∑ i,r i)=∑ j,c j) + (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n M : ℕ) (z₀ : Table r c) : + (variation (mapLaw (uniformLaw (α := Fin (M*(n*s)) → Bool)) + (unitOuterDraw r c fallback x n M z₀)) (uniformLaw (α := Table r c)):ℝ) ≤ + Real.exp (-(M:ℝ)/(2*(1+(d:ℝ)^2)))+ + M*(((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(n:ℝ)/(d:ℝ)^160)) := by + have hd : 14 ≤ d := by + have hi := Fintype.card_pos (α := I) + have hj := Fintype.card_pos (α := J) + unfold dimensionAllowance + nlinarith + let p := mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (unitJointDraw r c fallback x n) + let q := uniformLaw (α := PaperStateJoint r c) + have hj := unitJointDraw_variation r c hsmall fallback x n + have hr := retryLaw_variation p q (stateTrial r c) z₀ M + have hi : (variation (retryLaw q (stateTrial r c) z₀ M) + (uniformLaw (α := Table r c)):ℝ) ≤ Real.exp (-(M:ℝ)/(2*(1+(d:ℝ)^2))) := by + apply uniform_partial_retry_exp (StateJointSuccess r c) (originalStateSuccessEquiv r c) + z₀ M (2*(1+(d:ℝ)^2)) + rw [paperStateJoint_card] + exact stationary_success_ratio r c htotal hd + have ht := variation_triangle (retryLaw p (stateTrial r c) z₀ M) + (retryLaw q (stateTrial r c) z₀ M) (uniformLaw (α := Table r c)) + rw [unitOuterDraw_law] + have hrR : (variation (retryLaw p (stateTrial r c) z₀ M) + (retryLaw q (stateTrial r c) z₀ M):ℝ) ≤ M*(variation p q:ℝ) := by + exact_mod_cast hr + have htR := (Rat.cast_le (K := ℝ)).mpr ht + simp only [Rat.cast_add] at htR + exact htR.trans (by nlinarith) + +/-- The all-small branch reaches the same requested error as the branch +with a nonempty large rectangle, using no completion-sampling oracle. -/ +theorem unitOuterDraw_accuracy [Nonempty I] [Nonempty J] [Nonempty (PaperStates r c)] + [Nonempty (Table r c)] (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) (hk : 1 ≤ k) + (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (z₀ : Table r c) : + (variation (mapLaw (uniformLaw (α := Fin (outerTrials d k*(outerSteps d (smallBinaryLength r c) k*s)) → Bool)) + (unitOuterDraw r c fallback x (outerSteps d (smallBinaryLength r c) k) (outerTrials d k) z₀)) + (uniformLaw (α := Table r c)):ℝ) ≤ 1/(2:ℝ)^k := by + have hd : 14 ≤ d := by + have hi := Fintype.card_pos (α := I) + have hj := Fintype.card_pos (α := J) + unfold dimensionAllowance + nlinarith + have he := outer_total_error d (smallBinaryLength r c) k (stateBound r c) hd + (smallBinaryLength_parameters r c).2.1 hk (smallBinaryLength_parameters r c).2.2 + have hv := unitOuterDraw_error r c hsmall htotal fallback x + (outerSteps d (smallBinaryLength r c) k) (outerTrials d k) z₀ + apply hv.trans + have hn : 0 ≤ (outerTrials d k:ℝ)*(outerSteps d (smallBinaryLength r c) k+1)/ + (2:ℝ)^(outerAccuracy d (smallBinaryLength r c) k) := + div_nonneg (mul_nonneg (Nat.cast_nonneg _) (by + exact add_nonneg (Nat.cast_nonneg _) zero_le_one)) (le_of_lt (pow_pos (by norm_num) _)) + nlinarith + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallRational.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad01eb962c4e83834f5f0f4d6304c6bbb0547991 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/AllSmallRational.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallChain +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProposal +import OAI.Combinatorics.ContingencyTables.Transport.FiniteProposalStay +import OAI.Combinatorics.ContingencyTables.Transport.RationalChainMixing + +namespace OAI + +/-! # The actual rational walk on an empty large rectangle -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts CommonBasesFPRAS + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) +local instance : DecidableEq (PaperStates r c) := Classical.decEq _ + +def unitSmallStep (x : PaperStates r c) : RationalLaw (PaperStates r c) := + proposalStayLaw (proposalWeights r c x) (proposalWeights_nonnegative r c x) + (proposalWeights_total r c x) x + +lemma unitSmallStep_mass (x y : PaperStates r c) : + (unitSmallStep r c x).mass y=proposalWeights r c x y+ + if x=y then 1-∑ z,proposalWeights r c x z else 0 := + proposalStayLaw_mass _ _ _ x y + +variable [Nonempty (PaperStates r c)] + +lemma unitSmallStep_cast (x y : PaperStates r c) : + ((unitSmallStep r c x).mass y:ℝ)=(unitSmallChain r c).P x y := by + rw [unitSmallStep_mass] + simp only [Rat.cast_add,apply_ite,Rat.cast_sub,Rat.cast_one,Rat.cast_zero,Rat.cast_sum] + simp only [proposalWeights,apply_ite,smallProposalRat_cast,Rat.cast_zero] + simp only [unitSmallChain,MetropolisChain.chain,FiniteChain.ofMoves,MetropolisChain.move, + div_self (one_ne_zero : (1:ℝ)≠0),min_self,mul_one] + by_cases hxy : x=y <;> simp only [hxy,ite_true,ite_false] + +lemma unitSmallChain_pi_lower + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (z : PaperStates r c) : + 1/(((stateBound r c+1:ℕ):ℝ)^(2*d)) ≤ (unitSmallChain r c).π z := by + have hs : 0 < ∑ y,stateWeight r c y := + Finset.sum_pos (fun y _ => stateWeight_positive r c y) Finset.univ_nonempty + rw [unitSmallChain_pi_weight r c hsmall] + exact (one_div_le_one_div_of_le hs (state_total_mass_le r c)).trans + (div_le_div_of_nonneg_right (stateWeight_ge_one r c z) hs.le) + +theorem unitSmallWalk_variation [Nonempty I] [Nonempty J] + (hsmall : ∀ i j,FirstPaperPhysicalMarginal.paperSmall r c i j=true) + (x : PaperStates r c) (n : ℕ) : + (variation (walkLaw (unitSmallStep r c) x n) + (uniformLaw (α := PaperStates r c)):ℝ) ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(n:ℝ)/(d:ℝ)^160) := by + have hd : (1:ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by unfold dimensionAllowance; omega) + have hm := (unitSmallChain r c).point_mixing_exp ((d:ℝ)^160) + (1/(((stateBound r c+1:ℕ):ℝ)^(2*d))) (one_le_pow₀ hd) (by positivity) + (unitSmallChain_pi_lower r c hsmall) (unitSmallChain_poincare r c hsmall) n x + apply rationalWalk_variation (unitSmallStep r c) (unitSmallChain r c) + (unitSmallStep_cast r c) (uniformLaw (α := PaperStates r c)) + (fun y => ?_) x n _ (by positivity) + · simpa only [one_div,div_eq_mul_inv,one_mul,inv_inv,mul_comm] using hm + · simp only [uniformLaw,uniformMass,Rat.cast_div,Rat.cast_one,Rat.cast_natCast, + unitSmallChain_pi] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/CompiledResidualCorrection.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/CompiledResidualCorrection.lean new file mode 100644 index 0000000000000000000000000000000000000000..241d6d06c22a86685af187f21ec94d0cfad21964 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/CompiledResidualCorrection.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingMachine +import OAI.Combinatorics.ContingencyTables.Transport.FiniteCorrectionLaw + +namespace OAI + +/-! # Exact residual correction for the compiled public draw -/ + +namespace ContingencyTables.SmallGraphProfiles +open ResidualMixture FirstSuccess CompletionCounts ProfilePrograms Algorithms +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "D" => correctionPrecision r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +lemma correctionPrecision_pos : 1≤D := by + have hd : 1≤d := by unfold dimensionAllowance; omega + have hb : 1 ≤ smallBinaryLength r c := hd.trans (smallBinaryLength_parameters r c).2.1 + exact Nat.mul_le_mul (one_le_pow₀ hd) (one_le_pow₀ hb) + +/-- The residual uses the compiled sampler's finite output law. -/ +theorem scheduled_residual_correction + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + ∃ residual : RationalLaw (Table r c),∀ X, + (1-1/(2:ℚ)^D)* + (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (scheduledTableDraw r c htotal (2*D))).mass X+ + (1/(2:ℚ)^D)*residual.mass X=uniformMass (α := Table r c) := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + have hD := correctionPrecision_pos r c + apply residual_from_variation + · positivity + · exact (div_le_one (by positivity)).mpr (one_le_pow₀ (by norm_num)) + · exact correction_card_mass r c + · have hpow : (1/(2:ℚ)^D)^2=1/(2:ℚ)^(2*D) := by + rw [div_pow,one_pow,←pow_mul,Nat.mul_comm D 2] + rw [hpow] + apply (Rat.cast_le (K := ℝ)).mp + simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using + scheduledTableDraw_accuracy r c hPL hCheeger htotal (2*D) (by omega) + +/-- Consequently the same exact mixture identity holds for every +sufficiently long execution of the physical finite-transition machine. -/ +theorem public_residual_correction + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (t : ℕ) + (ht : allSamplingMachineTime (encodeSamplingInput r c (2*D))≤t) : + ∃ residual : RationalLaw (Table r c),∀ X : Table r c, + (1-1/(2:ℝ)^D)*tableMass allSamplingMachine (encodeSamplingInput r c (2*D)) t X.val+ + (1/(2:ℝ)^D)*(residual.mass X:ℝ)=(Fintype.card (Table r c):ℝ)⁻¹ := by + obtain ⟨residual,hr⟩ := scheduled_residual_correction r c hPL hCheeger htotal + refine ⟨residual,fun X => ?_⟩ + rw [allSamplingMachine_mass r c htotal (2*D) t ht] + have h := congrArg (fun z : ℚ => (z:ℝ)) (hr X) + simpa only [Rat.cast_add,Rat.cast_mul,Rat.cast_sub,Rat.cast_div,Rat.cast_one, + Rat.cast_pow,Rat.cast_ofNat,Rat.cast_inv,uniformMass,Rat.cast_natCast,one_div] using h + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBoxBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBoxBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9aaa31a2d1e92b5f03aed1abc8ad202497d4664 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBoxBounds.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableEnumeration +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxEnumeration +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCorrectionBudget +import OAI.Combinatorics.ContingencyTables.Sampling.RareBranchRuntime + +namespace OAI + +/-! # The boxes actually enumerated by the exact correction have singly exponential size -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts SmallContextCoordinates +open PhysicalCompletionFibres FirstPaperPhysicalMarginal +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c + +lemma originalEnumeration_count : + gridStateCount (originalEnumerationData (List.ofFn r,List.ofFn c))=((∑ i,r i)+1)^(m*n) := by + rw [gridStateCount_eq] + simp only [originalEnumerationData,originalLayoutMargins,completionEnumerationData, + zeroGrid,List.tail_cons,cellPairs,List.length_map,List.length_range,List.length_ofFn, + List.sum_cons,List.sum_ofFn,zero_add] + +lemma originalEnumeration_count_bound : + gridStateCount (originalEnumerationData (List.ofFn r,List.ofFn c))≤2^(d*b) := by + rw [originalEnumeration_count] + have hN : (∑ i,r i)+1≤2^b := + (show (∑ i,r i)+1≤ stateBound r c+1 by unfold stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hdim : m*n≤d := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + calc + ((∑ i,r i)+1)^(m*n) ≤ (2^b)^(m*n) := Nat.pow_le_pow_left hN _ + _ = 2^(b*(m*n)) := (pow_mul _ _ _).symm + _ ≤ 2^(d*b) := Nat.pow_le_pow_right (by decide) (by nlinarith) + +lemma profileEnumeration_count (e : Fin q ≃ Cells (paperSmall r c)) (x : PaperStates r c) : + gridStateCount (profileEnumerationData (stateCodeData r c e x))=(d^20+1)^(q+q) := by + rw [gridStateCount_eq] + simp only [profileEnumerationData,stateCodeData,codeCheckData,cellCatalog,List.length_map, + List.length_append,List.length_ofFn] + +lemma profileEnumeration_count_bound (e : Fin q ≃ Cells (paperSmall r c)) (x : PaperStates r c) : + gridStateCount (profileEnumerationData (stateCodeData r c e x))≤2^(2*(d*b)) := by + rw [profileEnumeration_count] + have hU : d^20+1≤2^b := + (show d^20+1≤ stateBound r c+1 by unfold stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hq : q≤d := by + have he : q=Fintype.card (Cells (paperSmall r c)) := by + simpa only [Fintype.card_fin] using Fintype.card_congr e + rw [he] + exact (RowMajorEnumeration.small_card_le_dimension (paperSmall r c)).trans dimension_le_allowance + calc + (d^20+1)^(q+q) ≤ (2^b)^(q+q) := Nat.pow_le_pow_left hU _ + _ = 2^(b*(q+q)) := (pow_mul _ _ _).symm + _ ≤ 2^(2*(d*b)) := Nat.pow_le_pow_right (by decide) (by nlinarith) + +/-- Any fixed polynomial of the product of these enumeration sizes is +absorbed by the actual correction probability. -/ +lemma exact_boxes_absorbed (p : Polynomial ℕ) (A : ℕ) : + p.eval (A*2^(3*(d*b)))≤2^(correctionPrecision r c)* + (p.eval A*2^((3*p.natDegree)^2)) := by + apply RareBranchRuntime.polynomial_tabulation_bound + exact RareBranchRuntime.square_le_precision d b (by unfold dimensionAllowance; omega) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBranchChoice.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBranchChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..4686219f9e2bc721e6289b3287ea85b617deeddf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactBranchChoice.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactSamplingParameters +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram + +namespace OAI + +/-! # The exact dyadic gate that selects the rare correction branch -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream DensePrograms Polynomial + +/-- All zero bits select correction; every other word selects the ordinary draw. -/ +def rareWord (z : CompletionMargins×List Bool) : Bool := decide (StackAddition.value z.2=0) + +def rareWordRealizer : Realizer rareWord := + composition (f := fun z : CompletionMargins×List Bool => (StackAddition.value z.2,0)) + (g := fun p : ℕ×ℕ => decide (p.1=p.2)) + (pair (composition second bitValue) (constant 0)) natEqual + +lemma polynomial_rareWord : PolynomialTime rareWordRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_bitValue) + (polynomial_constant 0)) polynomial_natEqual + +def rareBranch (z : CompletionMargins) : Experiment Bool := + FiniteWordExecution.experiment exactPrecision rareWord z + +noncomputable def rareBranchRealizer : OnlineTree.Realizer rareBranch := + FiniteWordExecution.realizer exactPrecisionRealizer rareWordRealizer + +lemma work_rareBranch : OnlineTree.WorkBound rareBranchRealizer exactParameterMeasure := by + apply OnlineTree.work_remeasure + (FiniteWordExecution.work_realizer polynomial_exactPrecision polynomial_rareWord) X + intro z + simp only [FiniteWordExecution.wordMeasure,exactParameterMeasure,eval_X] + omega + +lemma rareBranch_probability (z : CompletionMargins) : + (rareBranch z).mean (fun rare => if rare then 1 else 0)=1/(2:ℚ)^(exactPrecision z) := by + rw [rareBranch,FiniteWordExecution.experiment_mean] + simp only [rareWord,decide_eq_true_eq,bitValue_eq_word] + let zeroWord : Fin (exactPrecision z) → Bool := + (FairBits.binaryWordEquiv (exactPrecision z)).symm ⟨0,by positivity⟩ + have he (bits : Fin (exactPrecision z) → Bool) : + (FairBits.binaryWordEquiv (exactPrecision z) bits).val=0 ↔ bits=zeroWord := by + constructor + · intro h + apply (FairBits.binaryWordEquiv (exactPrecision z)).injective + apply Fin.ext + simpa only [zeroWord,Equiv.apply_symm_apply] using h + · intro h + rw [h] + simp only [zeroWord,Equiv.apply_symm_apply] + simp only [he,average,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf65ca9b57488f36e5cc47f2891b69698939a31e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreCost.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreProgram + +namespace OAI + +/-! # Finite-prefix cost of the actual exact sampler control graph -/ + +namespace ContingencyTables.ExactCoreCost +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (Env K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms ExactCoreProgram + +noncomputable def retryCost (z : CompletionMargins) : ℕ := + OnlineIntegerRetry.stepCost ExactMatrixTrial.trialRealizer (exactMatrixInput z) + +noncomputable def branchBudget (z : CompletionMargins) (N : ℕ) : ℕ := + exactOrdinaryRealizer.cost z+exactMatrixInputRealizer.cost z+N*retryCost z+ + 2*TreeFunction.size (TreeTyped.encode z)+20 + +noncomputable def budget (z : CompletionMargins) (N : ℕ) : ℕ := + rareBranchRealizer.cost z+exactOrdinaryRealizer.cost z+exactMatrixInputRealizer.cost z+ + N*retryCost z+10*TreeFunction.size (TreeTyped.encode z)+50 + +/-- The failed endpoint is inside the actual retry subroutine. Its successful +endpoints have halted with the sampled matrix in the output register. -/ +theorem prefix_correct_cost (z : CompletionMargins) (s : Data) (N : ℕ) : + ∃ p,Executes program.code program.coin (output z s) + (OnlineTree.initial program (TreeTyped.encode z) s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=(prefixExperiment z N).mean g) ∧ + p.cost≤budget z N := by + let out := output z s + have halted (X : MatrixCode) : + OnlinePartialCall.At instructions out (some .halt) (env (TreeTyped.encode X) .nil s) + (.delay 1 (.done (some X))) := + OnlinePartialCall.halt instructions out .halt rfl (some X) _ rfl + have ordinary : ∃ p,OnlinePartialCall.At instructions out (some .ordinary) + (env (TreeTyped.encode z) .nil s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=((exactOrdinary z).map some).mean g) ∧ + p.cost≤exactOrdinaryRealizer.cost z+2 := by + obtain ⟨u,hu,hum,huc⟩ := exactOrdinaryRealizer.correct z s + refine ⟨.delay 1 (u.bind (fun X => .delay 1 (.done (some X)))),?_,?_,?_⟩ + · exact OnlinePartialCall.call instructions out .ordinary .halt exactOrdinaryRealizer.program + rfl _ (fun X => env (TreeTyped.encode X) .nil s) u hu _ halted + · intro g + simp only [Experiment.mean,Experiment.mean_bind,Experiment.mean_map] + exact hum _ + · have hc := Experiment.cost_bind_le u (fun X => .delay 1 (.done (some X))) 1 + (by intro X; rfl) + simp only [Experiment.cost] at hc ⊢ + omega + have rare : ∃ p,OnlinePartialCall.At instructions out (some .prepareRare) + (env (TreeTyped.encode z) .nil s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=(correctionPrefix z N).mean g) ∧ + p.cost≤exactMatrixInputRealizer.cost z+N*retryCost z+3 := by + obtain ⟨u,hu,hum,huc⟩ := OnlineIntegerRetry.prefix_correct ExactMatrixTrial.trialRealizer + (exactMatrixInput z) s N + let v : Option MatrixCode → Experiment (Option MatrixCode) := + fun o => match o with | none => .done none | some X => .delay 1 (.done (some X)) + have hcall := OnlinePartialCall.partial_call instructions .retry + ⟨_,.halt,rfl⟩ (env (TreeTyped.encode (exactMatrixInput z)) .nil s) + (fun o => OnlineControl.cfg (OnlineIntegerRetry.instructions ExactMatrixTrial.trialRealizer) + (OnlineIntegerRetry.output (exactMatrixInput z) s o).1 + (OnlineIntegerRetry.output (exactMatrixInput z) s o).2) u hu + have hv : Executes (OnlineControl.code instructions) (OnlineControl.coins instructions) out + (OnlineControl.cfg instructions (some .retry) + (env (TreeTyped.encode (exactMatrixInput z)) .nil s)) + ((Experiment.delay 1 u).bind v) := by + apply hcall.bind v out + intro o + cases o with + | none => exact .done none + | some X => exact halted X + obtain ⟨p,hp,hpm,hpc⟩ := OnlinePartialCall.deterministicCall instructions out .prepareRare .retry + exactMatrixInputRealizer.program rfl _ _ _ (exactMatrixInputRealizer.correct z s) + ((Experiment.delay 1 u).bind v) hv + refine ⟨p,hp,?_,?_⟩ + · intro g + rw [hpm,Experiment.mean_bind] + simp only [Experiment.mean] + have he : (fun o => (v o).mean g)=g := by funext o; cases o <;> rfl + rw [he,hum] + rfl + · have hv : ∀ o,(v o).cost≤1 := by intro o; cases o <;> simp only [v,Experiment.cost] <;> omega + have hc := Experiment.cost_bind_le (Experiment.delay 1 u) v 1 hv + simp only [Experiment.cost] at hc + change u.cost≤N*retryCost z at huc + omega + have branch (b : Bool) : ∃ p,OnlinePartialCall.At instructions out (some .choose) + (env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g= + (if b then correctionPrefix z N else (exactOrdinary z).map some).mean g) ∧ + p.cost≤branchBudget z N := by + cases b with + | false => + obtain ⟨p,hp,hpm,hpc⟩ := ordinary + obtain ⟨v,hv,hvm,hvc⟩ := OnlinePartialCall.deterministicCall instructions out + .ordinaryInput .ordinary (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode false) .nil (TreeTyped.encode z) s) p hp + refine ⟨.delay 1 v,?_,(fun g => hvm g |>.trans (hpm g)),?_⟩ + · exact OnlinePartialCall.nilBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ rfl v hv + · simp only [Experiment.cost] at ⊢ + have hb : TreeFunction.size (TreeTyped.encode false)≤3 := by decide + unfold branchBudget + omega + | true => + obtain ⟨p,hp,hpm,hpc⟩ := rare + obtain ⟨v,hv,hvm,hvc⟩ := OnlinePartialCall.deterministicCall instructions out + .rareInput .prepareRare (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode true) .nil (TreeTyped.encode z) s) p hp + refine ⟨.delay 1 v,?_,(fun g => hvm g |>.trans (hpm g)),?_⟩ + · exact OnlinePartialCall.consBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ + .nil .nil rfl v hv + · simp only [Experiment.cost] at ⊢ + have hb : TreeFunction.size (TreeTyped.encode true)≤3 := by decide + unfold branchBudget + omega + choose v hv hvm hvc using branch + obtain ⟨u,hu,hum,huc⟩ := rareBranchRealizer.correct z (.cons (TreeTyped.encode z) s) + have hgate := OnlinePartialCall.call instructions out .gate .choose rareBranchRealizer.program + rfl _ (fun b => env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) u hu v hv + obtain ⟨p,hp,hpm,hpc⟩ := OnlinePartialCall.deterministicCall instructions out .prepare .gate + OnlineIntegerRetry.prepareProc rfl _ _ _ (OnlineIntegerRetry.prepare_exec (TreeTyped.encode z) s) + (.delay 1 (u.bind v)) hgate + refine ⟨p,hp,?_,?_⟩ + · intro g + rw [hpm] + simp only [Experiment.mean,Experiment.mean_bind] + simp_rw [hvm] + rw [hum,prefixExperiment,Experiment.mean_bind] + · have hc := Experiment.cost_bind_le u v (branchBudget z N) hvc + simp only [Experiment.cost] at hpc + dsimp only [branchBudget,budget] at hc ⊢ + omega + +end ContingencyTables.ExactCoreCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8da98e758ea554ae8b3bc8fed8cea23d353232c4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCoreProgram.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.ContingencyTables.Machines.OnlinePartialCall +import OAI.Combinatorics.ContingencyTables.Sampling.ExactOrdinaryProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCorrectionPrefix + +namespace OAI + +/-! # One finite control graph for the ordinary and unbounded correction branches -/ + +namespace ContingencyTables.ExactCoreProgram +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (Env K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms + +inductive Phase where + | prepare | gate | choose | ordinaryInput | ordinary | rareInput | prepareRare | retry | halt + deriving DecidableEq, Inhabited + +instance : Fintype Phase := ⟨{.prepare,.gate,.choose,.ordinaryInput,.ordinary, + .rareInput,.prepareRare,.retry,.halt},by intro x; cases x <;> simp⟩ + +noncomputable def instructions : Phase → OnlineControl.Instr Reg Phase + | .prepare => .call (OnlineProc.deterministic OnlineIntegerRetry.prepareProc) .gate + | .gate => .call rareBranchRealizer.program .choose + | .choose => .branch 0 .ordinaryInput .rareInput + | .ordinaryInput => .call (OnlineProc.deterministic (split 0 2 (by decide))) .ordinary + | .ordinary => .call exactOrdinaryRealizer.program .halt + | .rareInput => .call (OnlineProc.deterministic (split 0 2 (by decide))) .prepareRare + | .prepareRare => .call (OnlineProc.deterministic exactMatrixInputRealizer.program) .retry + | .retry => .call (OnlineIntegerRetry.program ExactMatrixTrial.trialRealizer) .halt + | .halt => .halt + +noncomputable def program : OnlineProc.Proc (K Reg) := OnlineControl.compile instructions + +noncomputable def output (z : CompletionMargins) (s : Data) : + Option MatrixCode → OnlinePartialCall.Config instructions + | none => OnlinePartialCall.callCfg instructions .retry + (OnlineControl.cfg (OnlineIntegerRetry.instructions ExactMatrixTrial.trialRealizer) + (some .prepare) (env (TreeTyped.encode (exactMatrixInput z)) .nil s)) + | some X => OnlineControl.cfg instructions none (env (TreeTyped.encode X) .nil s) + +def prefixExperiment (z : CompletionMargins) (N : ℕ) : Experiment (Option MatrixCode) := + (rareBranch z).bind (fun rare => if rare then correctionPrefix z N else (exactOrdinary z).map some) + +/-- The failed endpoint is inside the actual retry subroutine. Its successful +endpoints have halted with the sampled matrix in the output register. -/ +theorem prefix_correct (z : CompletionMargins) (s : Data) (N : ℕ) : + ∃ p,Executes program.code program.coin (output z s) + (OnlineTree.initial program (TreeTyped.encode z) s) p ∧ + ∀ g : Option MatrixCode → ℚ,p.mean g=(prefixExperiment z N).mean g := by + let out := output z s + have halted (X : MatrixCode) : + OnlinePartialCall.At instructions out (some .halt) (env (TreeTyped.encode X) .nil s) + (.delay 1 (.done (some X))) := + OnlinePartialCall.halt instructions out .halt rfl (some X) _ rfl + have ordinary : ∃ p,OnlinePartialCall.At instructions out (some .ordinary) + (env (TreeTyped.encode z) .nil s) p ∧ + ∀ g : Option MatrixCode → ℚ,p.mean g=((exactOrdinary z).map some).mean g := by + obtain ⟨u,hu,hum,_⟩ := exactOrdinaryRealizer.correct z s + refine ⟨.delay 1 (u.bind (fun X => .delay 1 (.done (some X)))),?_,?_⟩ + · exact OnlinePartialCall.call instructions out .ordinary .halt exactOrdinaryRealizer.program + rfl _ (fun X => env (TreeTyped.encode X) .nil s) u hu _ halted + · intro g + simp only [Experiment.mean,Experiment.mean_bind,Experiment.mean_map] + exact hum _ + have rare : ∃ p,OnlinePartialCall.At instructions out (some .prepareRare) + (env (TreeTyped.encode z) .nil s) p ∧ + ∀ g : Option MatrixCode → ℚ,p.mean g=(correctionPrefix z N).mean g := by + obtain ⟨u,hu,hum,_⟩ := OnlineIntegerRetry.prefix_correct ExactMatrixTrial.trialRealizer + (exactMatrixInput z) s N + let v : Option MatrixCode → Experiment (Option MatrixCode) := + fun o => match o with | none => .done none | some X => .delay 1 (.done (some X)) + have hcall := OnlinePartialCall.partial_call instructions .retry + ⟨_,.halt,rfl⟩ (env (TreeTyped.encode (exactMatrixInput z)) .nil s) + (fun o => OnlineControl.cfg (OnlineIntegerRetry.instructions ExactMatrixTrial.trialRealizer) + (OnlineIntegerRetry.output (exactMatrixInput z) s o).1 + (OnlineIntegerRetry.output (exactMatrixInput z) s o).2) u hu + have hv : Executes (OnlineControl.code instructions) (OnlineControl.coins instructions) out + (OnlineControl.cfg instructions (some .retry) + (env (TreeTyped.encode (exactMatrixInput z)) .nil s)) + ((Experiment.delay 1 u).bind v) := by + apply hcall.bind v out + intro o + cases o with + | none => exact .done none + | some X => exact halted X + obtain ⟨p,hp,hpm,_⟩ := OnlinePartialCall.deterministicCall instructions out .prepareRare .retry + exactMatrixInputRealizer.program rfl _ _ _ (exactMatrixInputRealizer.correct z s) + ((Experiment.delay 1 u).bind v) hv + refine ⟨p,hp,?_⟩ + intro g + rw [hpm,Experiment.mean_bind] + simp only [Experiment.mean] + have he : (fun o => (v o).mean g)=g := by funext o; cases o <;> rfl + rw [he,hum] + rfl + have branch (b : Bool) : ∃ p,OnlinePartialCall.At instructions out (some .choose) + (env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) p ∧ + ∀ g : Option MatrixCode → ℚ,p.mean g= + (if b then correctionPrefix z N else (exactOrdinary z).map some).mean g := by + cases b with + | false => + obtain ⟨p,hp,hpm⟩ := ordinary + obtain ⟨v,hv,hvm,_⟩ := OnlinePartialCall.deterministicCall instructions out + .ordinaryInput .ordinary (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode false) .nil (TreeTyped.encode z) s) p hp + refine ⟨.delay 1 v,?_,fun g => hvm g |>.trans (hpm g)⟩ + exact OnlinePartialCall.nilBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ rfl v hv + | true => + obtain ⟨p,hp,hpm⟩ := rare + obtain ⟨v,hv,hvm,_⟩ := OnlinePartialCall.deterministicCall instructions out + .rareInput .prepareRare (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode true) .nil (TreeTyped.encode z) s) p hp + refine ⟨.delay 1 v,?_,fun g => hvm g |>.trans (hpm g)⟩ + exact OnlinePartialCall.consBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ + .nil .nil rfl v hv + choose v hv hvm using branch + obtain ⟨u,hu,hum,_⟩ := rareBranchRealizer.correct z (.cons (TreeTyped.encode z) s) + have hgate := OnlinePartialCall.call instructions out .gate .choose rareBranchRealizer.program + rfl _ (fun b => env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) u hu v hv + obtain ⟨p,hp,hpm,_⟩ := OnlinePartialCall.deterministicCall instructions out .prepare .gate + OnlineIntegerRetry.prepareProc rfl _ _ _ (OnlineIntegerRetry.prepare_exec (TreeTyped.encode z) s) + (.delay 1 (u.bind v)) hgate + refine ⟨p,hp,?_⟩ + intro g + rw [hpm] + simp only [Experiment.mean,Experiment.mean_bind] + simp_rw [hvm] + rw [hum,prefixExperiment,Experiment.mean_bind] + +end ContingencyTables.ExactCoreProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCorrectionPrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCorrectionPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ced2f2b4cd2e7873a4ccebc0d385966fbffc5fd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactCorrectionPrefix.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactResidualInput +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixTableLaw + +namespace OAI + +/-! # The executed correction prefixes converge to the exact residual law -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.PhysicalStream + +def correctionPrefix (z : DensePrograms.CompletionMargins) (N : ℕ) : + Experiment (Option DensePrograms.MatrixCode) := + OnlineIntegerRetry.prefixExperiment (f := ExactMatrixTrial.trial) (exactMatrixInput z) N + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms OriginalTableBox ResidualMixture FirstSuccess CompletionCounts +open MatchingFPRAS MatchingFPRAS.PhysicalStream +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "D" => correctionPrecision r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +lemma correctionPrefix_failure + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + (correctionPrefix (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=none then 1 else 0)≤(1/2:ℚ)^N := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + unfold correctionPrefix + rw [exactMatrixInput_code r c htotal,scheduledResidualCounts_actual r c hPL hCheeger htotal] + exact ExactMatrixTrial.prefix_failure _ _ + (ExactMatrixTrial.count_weight_pos _ (Nat.mul_pos Fintype.card_pos + (pow_pos (scheduledTrialDenominator_pos _) _))) N + +lemma correctionPrefix_limit + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (X : Table r c) : + Filter.Tendsto (fun N => ((correctionPrefix (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=some (matrixCode X.val) then 1 else 0):ℝ)) + Filter.atTop (nhds ((residualMass + (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (scheduledTableDraw r c htotal (2*D))) (1/(2:ℚ)^D) X):ℝ)) := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + unfold correctionPrefix + rw [exactMatrixInput_code r c htotal,scheduledResidualCounts_actual r c hPL hCheeger htotal] + have ht := ExactMatrixTrial.table_prefix_limit r c + (IntegerResidualCorrection.law (scheduledCountsLaw r c htotal (2*D)) (2^D) + (pow_pos (scheduledTrialDenominator_pos _) _) (by positivity) + (scheduledCounts_domination r c hPL hCheeger htotal)) + (Nat.mul_pos Fintype.card_pos (pow_pos (scheduledTrialDenominator_pos _) _)) + (GreedyFeasibleTable.table r c htotal) X + rw [IntegerResidualCorrection.law_mass,scheduledCountsLaw_law] at ht + simpa only [Nat.cast_pow,Nat.cast_ofNat] using ht + +/-- The ordinary draw and correction prefixes have uniform limiting table mass. -/ +theorem corrected_prefix_limit + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (X : Table r c) : + Filter.Tendsto (fun N => + (1-1/(2:ℝ)^D)* + ((mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (scheduledTableDraw r c htotal (2*D))).mass X:ℝ)+ + (1/(2:ℝ)^D)*((correctionPrefix (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=some (matrixCode X.val) then 1 else 0):ℝ)) + Filter.atTop (nhds ((Fintype.card (Table r c):ℝ)⁻¹)) := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.table r c htotal⟩ + have ht := (Filter.Tendsto.const_mul (1/(2:ℝ)^D) + (correctionPrefix_limit r c hPL hCheeger htotal X)).const_add + ((1-1/(2:ℝ)^D)* + ((mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (scheduledTableDraw r c htotal (2*D))).mass X:ℝ)) + have he := congrArg (fun x : ℚ => (x:ℝ)) + (ResidualMixture.mixture_exact + (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (scheduledTableDraw r c htotal (2*D))) + (show (1/(2:ℚ)^D)≠0 by positivity) X) + simp only [Rat.cast_add,Rat.cast_mul,Rat.cast_sub,Rat.cast_one,Rat.cast_pow, + Rat.cast_ofNat,uniformMass,Rat.cast_inv,Rat.cast_natCast,one_div] at he + simp only [one_div] at ht ⊢ + rw [he] at ht + exact ht + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactEntryBoxBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactEntryBoxBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4b31af6c10739e6249d283181f3f4d32faa7ae1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactEntryBoxBound.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ResidualBoxScale +import OAI.Combinatorics.ContingencyTables.Transport.TabulationPreparationBounds + +namespace OAI + +/-! # The actual transition-cache boxes in the exact sampler -/ + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms CompletionCounts Polynomial +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] unaryMarkers parameterProposalWidth scheduledCacheParameters + residualParameters canonicalCountInput + +private lemma proposalBox_eq (z : SamplingParameters) (u v : List ℕ×List ℕ) : + gridStateCount ((scheduledMatrixParameters z,(u,v)).1.2,2)=2^(parameterProposalWidth z) := by + have hm : (scheduledMatrixParameters z,(u,v)).1.2=unaryMarkers (parameterProposalWidth z) := by + unfold scheduledMatrixParameters + rfl + rw [hm,gridStateCount_eq,unaryMarkers_length] + +theorem exact_entry_box_bound : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), (∑ i,r i)=∑ j,c j → + ∀ u∈profileBoxViews (initialCheck (List.ofFn r,List.ofFn c)), + ∀ v∈profileBoxViews (initialCheck (List.ofFn r,List.ofFn c)), + matrixEntryBox (scheduledMatrixParameters (exactSamplingParameters (List.ofFn r,List.ofFn c)),(u,v)) ≤ + p.eval (Algorithms.samplingSize n r 0)*exactBoxScale r c := by + obtain ⟨a,ha⟩ := exact_count_input_measure_polynomial + obtain ⟨b,hb⟩ := tabulation_preparation_polynomial + obtain ⟨p,hp⟩ := matrixEntryBox_bound + let A := b.comp a + refine ⟨p.comp A+A+4,?_⟩ + intro m n r c htotal u hu v hv + let z := exactSamplingParameters (List.ofFn r,List.ofFn c) + let e : MatrixEntryInput := (scheduledMatrixParameters z,(u,v)) + let V := candidateData (initialCheck (List.ofFn r,List.ofFn c),u) + let dim := dimensionAllowance (I := Fin m) (J := Fin n) + let bits := smallBinaryLength r c + let S := Algorithms.samplingSize n r 0 + let E := exactBoxScale r c + have hd : 1 ≤ dim := by unfold dim dimensionAllowance; omega + have hbits : 1 ≤ bits := hd.trans (smallBinaryLength_parameters r c).2.1 + have h23 : dim^2 ≤ dim^3 := Nat.pow_le_pow_right hd (by decide) + have he : 1 ≤ E := exactBoxScale_pos r c + have hdim : parameterDimension z=dim := by + change marginDimension (List.ofFn r,List.ofFn c)=dim + exact marginDimension_ofFn r c + have hVrow : V.1.2.1=List.ofFn r := rfl + have hVcol : V.1.2.2=List.ofFn c := rfl + have hres : entryResidualParameters e=residualParameters ((V,dim^12),(dim,parameterAccuracy z)) := by + unfold entryResidualParameters + dsimp only [e,entryCacheParameters,sourceData,scheduledMatrixParameters,scheduledCacheParameters,matrixData] + unfold scheduledCacheParameters + dsimp only + rw [show z.1=(List.ofFn r,List.ofFn c) from rfl,marginPadding_ofFn,hdim] + have hnorm := normalized_profile_completion_count r c V hVrow hVcol (parameterAccuracy z) + have hdense := normalized_profile_dense_grid r c V hVrow hVcol (parameterAccuracy z) + have horig : gridStateCount (completionEnumerationData (entryResidualParameters e).1) ≤ E := by + rw [hres] + unfold residualParameters + have hh := arbitrary_profile_completion_count r c V hVrow hVcol + apply hh.trans + apply Nat.pow_le_pow_right (by decide) + have hmul : dim^2*bits ≤ dim^3*bits := Nat.mul_le_mul_right bits h23 + change 4*(dim^2*bits) ≤ 40*(dim^3*bits) + omega + have hprop : gridStateCount (e.1.2,2) ≤ E := by + rw [proposalBox_eq z u v,parameterProposalWidth,hdim] + apply Nat.pow_le_pow_right (by decide) + have hc : Nat.clog 2 (32*dim^2) ≤ 32*dim^2 := + Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self) + have hmul : dim^3 ≤ dim^3*bits := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (dim^3) hbits + exact hc.trans (by change 32*dim^2 ≤ 40*(dim^3*bits); nlinarith) + have hprepare := hb z + have hnum : parameterDimension z+parameterAccuracy z+parameterCompletionWidth z ≤ A.eval S := + hprepare.2.1.trans (by simp only [A,eval_comp]; exact polynomial_eval_monotone b (ha m n r c htotal)) + have hw : weight e ≤ A.eval S := (hprepare.2.2.2.2 u hu v hv).trans (by + simp only [A,eval_comp]; exact polynomial_eval_monotone b (ha m n r c htotal)) + have hpoly : p.eval (weight e) ≤ p.eval (A.eval S) := polynomial_eval_monotone p hw + have hbound := hp e + dsimp only at hbound + have hn : gridStateCount (completionEnumerationData (canonicalCountInput (entryResidualParameters e)).1.1) ≤ E := by + rw [hres] + exact hnorm + have hg : (4*(canonicalCountInput (entryResidualParameters e)).1.2.1^8)^ + tabulationDimension (canonicalCountInput (entryResidualParameters e)).1 ≤ E := by + rw [hres] + exact hdense + change matrixEntryBox e ≤ _ + have hrs : (entryResidualParameters e).2=(parameterDimension z,parameterAccuracy z) := by + rw [hres] + unfold residualParameters + rw [hdim] + have hcache : (entryCacheParameters e).2=parameterCompletionWidth z := by + unfold e entryCacheParameters scheduledMatrixParameters + unfold scheduledCacheParameters + rfl + have hnum' : (entryResidualParameters e).2.1+(entryResidualParameters e).2.2+ + (entryCacheParameters e).2 ≤ A.eval S := by + rw [hrs,hcache] + exact hnum + have hfirst : matrixEntryBox e ≤ 4*E+A.eval S+p.eval (A.eval S) := by + omega + apply hfirst.trans + have hA : A.eval S ≤ A.eval S*E := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (A.eval S) he + have hpA : p.eval (A.eval S) ≤ p.eval (A.eval S)*E := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (p.eval (A.eval S)) he + simp only [eval_add,eval_comp,eval_ofNat] + nlinarith + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactExpectedTime.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactExpectedTime.lean new file mode 100644 index 0000000000000000000000000000000000000000..c32108113f58676a614321529c8771c8dce4827d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactExpectedTime.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePublic +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicLaw +import OAI.Combinatorics.ContingencyTables.Machines.QuadraticPrefixRuntime + +namespace OAI + +/-! # Summability of the actual exact sampler's public runtime -/ + +namespace ContingencyTables.ExactExpectedTime +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open DensePrograms SmallGraphProfiles PhysicalRetryTail +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "dim" => CompletionCounts.dimensionAllowance (I := Fin m) (J := Fin n) + +attribute [local irreducible] ExactPublicPrefix.program ExactTablePrefix.experiment + PublishedInputs.FiniteBoxPrekopaLeindler PublishedInputs.FiniteCheeger + +/-- Expected runtime is bounded by the explicit costs of the ordinary +prefix and the probability-weighted correction branch. -/ +theorem bound + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin q) (4*k^8))) + (htotal : (∑ i,r i)=∑ j,c j) (B L : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) + (hL : ∀ X : Table r c,(ExactPublicPrefix.word r c X).length≤L) : + let S := ExactGatePublic.budget r c B L + let T := ExactPublicCost.budget r c 1 B L+1 + let tail := PhysicalRetryTail.tail ExactPublicPrefix.program.table + (ExactPublicPrefix.program.initial (Tape.mk₁ (Algorithms.encodeMargins r c))) + Summable tail ∧ (∑' t,tail t)≤(S:ℝ)+11*(1/(2:ℝ)^correctionPrecision r c)*T := by + dsimp only + let S := ExactGatePublic.budget r c B L + let T := ExactPublicCost.budget r c 1 B L+1 + let M := ExactPublicPrefix.program.table + let init := ExactPublicPrefix.program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)) + refine QuadraticPrefixRuntime.expected_time (PhysicalRetryTail.tail M init) S T + (Nat.zero_lt_succ _) (1/(2:ℝ)^correctionPrecision r c) (by positivity) + (tail_nonnegative M init) ?_ (tail_antitone M init) ?_ ?_ + · intro t + have h := PhysicalEventBounds.mean_mono (experiment M t init) live (fun _ => 1) live_le_one + rw [PhysicalPartialSequence.mean_const] at h + unfold PhysicalRetryTail.tail + exact_mod_cast h + · obtain ⟨p,hp,hm,hc⟩ := ExactGatePublic.prefix_correct_cost r c htotal B L hB hL + have h := tail_le_failure M (ExactGatePublic.publicOutput r c) init p hp + (ExactGatePublic.publicOutput_halted r c) S hc + rw [hm,ExactGatePublic.failure r c htotal] at h + simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using h + · intro N + obtain ⟨p,hp,hm,hc⟩ := ExactPublicCost.prefix_correct_cost r c htotal N B L hB hL + have hcost : p.cost≤S+T*(N+1)^2 := by + have hq := ExactPublicCost.quadratic_budget r c N B L + have ht := Nat.mul_le_mul_right ((N+1)^2) + (Nat.le_succ (ExactPublicCost.budget r c 1 B L)) + exact (hc.trans (hq.trans ht)).trans (Nat.le_add_left _ _) + have h := tail_le_failure M (ExactPublicPrefix.output r c) init p hp + (ExactPublicPrefix.output_halted r c) _ hcost + rw [hm] at h + have hf := ExactTablePrefix.failure_bound r c (hPL _) (hCheeger _ dim) htotal N + have hfr := (Rat.cast_le (K := ℝ)).mpr hf + exact h.trans (by + simpa only [Rat.cast_mul,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using hfr) + +/-- The physical tail is summable for every equal-total margin pair. -/ +theorem summable + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin q) (4*k^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + Summable (fun t => 1-Algorithms.haltMass ExactPublicPrefix.machine (Algorithms.encodeMargins r c) t) := by + obtain ⟨p,hp⟩ := ExactPrintCost.polynomial_print_bound + let B := p.eval (ExactPrintCost.matrixSize (n := n) r) + have hB (X : Table r c) : GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B := + (Nat.le_add_right _ _).trans (hp m n r c X) + have hL (X : Table r c) : (ExactPublicPrefix.word r c X).length≤B := + (MatchingFPRAS.TreeTyped.list_length_le_weight _).trans + ((Nat.le_add_left _ _).trans (hp m n r c X)) + have hs := (bound r c hPL hCheeger htotal B B hB hL).1 + have he : (fun t => 1-Algorithms.haltMass ExactPublicPrefix.machine (Algorithms.encodeMargins r c) t)= + PhysicalRetryTail.tail ExactPublicPrefix.program.table + (ExactPublicPrefix.program.initial (Tape.mk₁ (Algorithms.encodeMargins r c))) := by + funext t + exact PhysicalPublicLaw.tail_eq _ _ _ + rw [he] + exact hs + +end +end ContingencyTables.ExactExpectedTime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..c49d437e33149d7b897255bb7551ce483f6f96f4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateCost.lean @@ -0,0 +1,30 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePrefix + +namespace OAI + +/-! # Polynomial cost before the rare branch starts -/ + +namespace ContingencyTables.ExactGateCost +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +def measure (z : CompletionMargins) : ℕ := + exactParameterMeasure z+FiniteWordExecution.wordMeasure exactOrdinaryBits z + +lemma budget_polynomial : ∃ p : Polynomial ℕ, + ∀ z,ExactGatePrefix.budget z ≤ p.eval (measure z) := by + obtain ⟨p,hp⟩ := work_rareBranch + obtain ⟨q,hq⟩ := work_exactOrdinary + refine ⟨p+q+10*X+50,?_⟩ + intro z + have h1 : rareBranchRealizer.cost z ≤ p.eval (measure z) := + (Nat.le_add_right _ _).trans ((hp z).trans (polynomial_eval_monotone p (Nat.le_add_right _ _))) + have h2 : exactOrdinaryRealizer.cost z ≤ q.eval (measure z) := + (Nat.le_add_right _ _).trans ((hq z).trans (polynomial_eval_monotone q (Nat.le_add_left _ _))) + have h3 : weight z ≤ measure z := by unfold measure exactParameterMeasure; omega + change rareBranchRealizer.cost z+exactOrdinaryRealizer.cost z+10*weight z+50 ≤ _ + simp only [eval_add,eval_mul,eval_ofNat,eval_X] + omega + +end ContingencyTables.ExactGateCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePhysical.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePhysical.lean new file mode 100644 index 0000000000000000000000000000000000000000..de01b52d492c35f41fce0620dc2444b6af6bb9b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePhysical.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGateTyped + +namespace OAI + +/-! # The cheap exact-sampling prefix on the same physical program -/ + +namespace ContingencyTables.ExactGatePhysical +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost +open MatchingFPRAS.TreeTyped MatchingFPRAS.TreePost Turing +open DensePrograms ProfilePrograms + +attribute [local irreducible] ExactTypedProgram.program + +noncomputable def output (as : List Symbol) (o : Option MatrixCode) : + Cfg Symbol ExactPhysicalProgram.program.State := + upCfg (OnlineStack.cfg (ExactGateTyped.output as .nil o)) + +lemma output_some (as : List Symbol) (X : MatrixCode) : + output as (some X)=ExactPhysicalProgram.program.final + (Tape.mk₁ (packed (GreedyFeasibleTable.printMatrix X))) := by + change upCfg (OnlineStack.cfg + (⟨none,none,inputStacks (GreedyFeasibleTable.printMatrix X)⟩ : + OnlineTree.StoreCfg ExactTypedProgram.program))=_ + exact OnlineTree.cfg_packed ExactTypedProgram.program (GreedyFeasibleTable.printMatrix X) none + +lemma output_none_live (as : List Symbol) : (output as none).state≠none := by + change (some _ : Option ExactPhysicalProgram.program.State)≠none + exact Option.some_ne_none _ + +noncomputable def typedBudget (as : List Symbol) (B : ℕ) : ℕ := + exactParsedMarginsRealizer.cost as+ExactGatePrefix.budget (exactParsedMargins as)+B + +noncomputable def budget (as : List Symbol) (B : ℕ) : ℕ := + typedBudget as B*OnlineStack.Executes.factor ExactTypedProgram.program.code + (weight as) (typedBudget as B) + +theorem prefix_correct_cost (as : List Symbol) (B : ℕ) + (hB : (ExactGatePrefix.experiment (exactParsedMargins as)).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ q,Implements ExactPhysicalProgram.program.table (output as) + (ExactPhysicalProgram.program.initial (Tape.mk₁ (packed as))) q ∧ + (∀ g : Option MatrixCode → ℚ, + q.mean g=(ExactGatePrefix.experiment (exactParsedMargins as)).mean g) ∧ + q.cost≤budget as B := by + obtain ⟨p,hp,hpm,hpc⟩ := ExactGateTyped.prefix_correct_cost as .nil B hB + obtain ⟨q,hq,hqm,hqc⟩ := hp.compile (weight as) (inputStacks_bound as) + have hu := hq.up + have hi := OnlineTree.cfg_packed ExactTypedProgram.program as (some default) + change upCfg (OnlineStack.cfg (OnlineTree.initial ExactTypedProgram.program (encode as) .nil))= + ExactPhysicalProgram.program.initial (Tape.mk₁ (packed as)) at hi + rw [hi] at hu + refine ⟨q,hu,(fun g => (hqm g).trans (hpm g)),?_⟩ + exact hqc.trans (Nat.mul_le_mul hpc (OnlineStack.Executes.factor_mono + (weight as) (weight as) p.cost (typedBudget as B) le_rfl hpc)) + +end ContingencyTables.ExactGatePhysical + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePolynomial.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..e428ead3656f8195ada3baa3723a5011534c7f68 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePolynomial.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactInputBounds +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePublic +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalCostPolynomial + +namespace OAI + +/-! # A uniform polynomial bound for the cheap public prefix -/ + +namespace ContingencyTables.ExactGatePolynomial +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open ProfilePrograms DensePrograms Polynomial +open Algorithms (samplingSize encodeMargins) +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] ExactTypedProgram.program exactParsedMargins + ExactGatePrefix.budget ExactGateCost.measure + +def measure (as : List Symbol) (B : ℕ) : ℕ := + weight as+ExactGateCost.measure (exactParsedMargins as)+B + +theorem budget_polynomial : ∃ p : Polynomial ℕ,∀ as B, + LiteralProgram.packTime as.length+ExactGatePhysical.budget as B+LiteralProgram.postTime B ≤ + p.eval (measure as B) := by + obtain ⟨p,hp⟩ := polynomial_exactParsedMargins + obtain ⟨q,hq⟩ := ExactGateCost.budget_polynomial + let t : Polynomial ℕ := p+q+X + obtain ⟨v,hv⟩ := PhysicalCostPolynomial.bound + (OnlineStack.accesses ExactTypedProgram.program.code) + (OnlineStack.overhead ExactTypedProgram.program.code) t + refine ⟨v,?_⟩ + intro as B + let M := measure as B + have hw : weight as ≤ M := by unfold M measure; omega + have hg : ExactGateCost.measure (exactParsedMargins as) ≤ M := by unfold M measure; omega + have hB : B ≤ M := by unfold M measure; omega + have ht : ExactGatePhysical.typedBudget as B ≤ t.eval M := by + have hp' := (Nat.le_add_right _ _).trans ((hp as).trans (polynomial_eval_monotone p hw)) + have hq' := (hq _).trans (polynomial_eval_monotone q hg) + simpa only [ExactGatePhysical.typedBudget,t,eval_add,eval_X] using + Nat.add_le_add (Nat.add_le_add hp' hq') hB + have hb := hv (weight as) (ExactGatePhysical.typedBudget as B) as.length B M hw ht + ((list_length_le_weight as).trans hw) hB + simpa only [ExactGatePhysical.budget,OnlineStack.Executes.factor] using hb + +/-- Any fixed polynomial print allowance still gives a uniform public +polynomial bound for the prefix before the rare tabulation starts. -/ +theorem public_bound (print : Polynomial ℕ) : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → + let B := print.eval (ExactPrintCost.matrixSize (n := n) r) + ExactGatePublic.budget r c B B ≤ p.eval (samplingSize n r 0) := by + obtain ⟨p,hp⟩ := budget_polynomial + obtain ⟨q,hq⟩ := SmallGraphProfiles.exact_gate_measure_polynomial + let u : Polynomial ℕ := 91*X^2+q+print.comp (25*X^3) + refine ⟨p.comp u,?_⟩ + intro m n r c htotal + dsimp only + have hm : measure (encodeMargins r c) (print.eval (ExactPrintCost.matrixSize (n := n) r)) ≤ + u.eval (samplingSize n r 0) := by + simp only [measure,SmallGraphProfiles.exactParsedMargins_spec,u,eval_add,eval_mul, + eval_ofNat,eval_pow,eval_X,eval_comp] + exact Nat.add_le_add (Nat.add_le_add (SmallGraphProfiles.exact_public_weight r c htotal) + (hq m n r c htotal)) + (polynomial_eval_monotone print (SmallGraphProfiles.exact_matrix_size (n := n) r)) + have hb : LiteralProgram.packTime (encodeMargins r c).length+ + ExactGatePhysical.budget (encodeMargins r c) (print.eval (ExactPrintCost.matrixSize (n := n) r))+ + LiteralProgram.postTime (print.eval (ExactPrintCost.matrixSize (n := n) r)) ≤ + (p.comp u).eval (samplingSize n r 0) := + (hp (encodeMargins r c) (print.eval (ExactPrintCost.matrixSize (n := n) r))).trans (by + rw [eval_comp] + exact polynomial_eval_monotone p hm) + simpa only [ExactGatePublic.budget,ExactTablePrefix.input] using hb + +end +end ContingencyTables.ExactGatePolynomial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..97059d1605bdd486f29e26146b02469d0138e4f0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePrefix.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreCost +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPartialSequence + +namespace OAI + +/-! # A cheap prefix ending before rare-branch tabulation -/ + +namespace ContingencyTables.ExactGatePrefix +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (Env K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms ExactCoreProgram + +noncomputable def output (z : CompletionMargins) (s : Data) : + Option MatrixCode → OnlinePartialCall.Config instructions + | none => OnlineControl.cfg instructions (some .prepareRare) (env (TreeTyped.encode z) .nil s) + | some X => OnlineControl.cfg instructions none (env (TreeTyped.encode X) .nil s) + +def experiment (z : CompletionMargins) : Experiment (Option MatrixCode) := + (rareBranch z).bind (fun b => if b then .done none else (exactOrdinary z).map some) + +noncomputable def budget (z : CompletionMargins) : ℕ := + rareBranchRealizer.cost z+exactOrdinaryRealizer.cost z+10*TreeFunction.size (TreeTyped.encode z)+50 + +/-- The rare branch is selected but its potentially large tabulation has +not started at the failure endpoint of this bounded prefix. -/ +theorem prefix_correct_cost (z : CompletionMargins) (s : Data) : + ∃ p,Executes program.code program.coin (output z s) + (OnlineTree.initial program (TreeTyped.encode z) s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=(experiment z).mean g) ∧ p.cost≤budget z := by + let out := output z s + have halted (X : MatrixCode) : + OnlinePartialCall.At instructions out (some .halt) (env (TreeTyped.encode X) .nil s) + (.delay 1 (.done (some X))) := + OnlinePartialCall.halt instructions out .halt rfl (some X) _ rfl + have ordinary : ∃ p,OnlinePartialCall.At instructions out (some .ordinary) + (env (TreeTyped.encode z) .nil s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=((exactOrdinary z).map some).mean g) ∧ + p.cost≤exactOrdinaryRealizer.cost z+2 := by + obtain ⟨u,hu,hum,huc⟩ := exactOrdinaryRealizer.correct z s + refine ⟨.delay 1 (u.bind (fun X => .delay 1 (.done (some X)))),?_,?_,?_⟩ + · exact OnlinePartialCall.call instructions out .ordinary .halt exactOrdinaryRealizer.program + rfl _ (fun X => env (TreeTyped.encode X) .nil s) u hu _ halted + · intro g + simp only [Experiment.mean,Experiment.mean_bind,Experiment.mean_map] + exact hum _ + · have hc := Experiment.cost_bind_le u (fun X => .delay 1 (.done (some X))) 1 + (by intro X; rfl) + simp only [Experiment.cost] at hc ⊢ + omega + have branch (b : Bool) : ∃ p,OnlinePartialCall.At instructions out (some .choose) + (env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g= + (if b then (.done none : Experiment (Option MatrixCode)) else (exactOrdinary z).map some).mean g) ∧ + p.cost≤exactOrdinaryRealizer.cost z+2*TreeFunction.size (TreeTyped.encode z)+20 := by + cases b with + | false => + obtain ⟨p,hp,hpm,hpc⟩ := ordinary + obtain ⟨v,hv,hvm,hvc⟩ := OnlinePartialCall.deterministicCall instructions out + .ordinaryInput .ordinary (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode false) .nil (TreeTyped.encode z) s) p hp + refine ⟨.delay 1 v,?_,(fun g => (hvm g).trans (hpm g)),?_⟩ + · exact OnlinePartialCall.nilBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ rfl v hv + · have hb : TreeFunction.size (TreeTyped.encode false)≤3 := by decide + simp only [Experiment.cost] + omega + | true => + have hp : OnlinePartialCall.At instructions out (some .prepareRare) + (env (TreeTyped.encode z) .nil s) (.done none) := .done none + obtain ⟨v,hv,hvm,hvc⟩ := OnlinePartialCall.deterministicCall instructions out + .rareInput .prepareRare (split 0 2 (by decide)) rfl _ _ _ + (split02 (TreeTyped.encode true) .nil (TreeTyped.encode z) s) (.done none) hp + refine ⟨.delay 1 v,?_,hvm,?_⟩ + · exact OnlinePartialCall.consBranch instructions out .choose .ordinaryInput .rareInput 0 rfl _ + .nil .nil rfl v hv + · have hb : TreeFunction.size (TreeTyped.encode true)≤3 := by decide + simp only [Experiment.cost] at hvc ⊢ + omega + choose v hv hvm hvc using branch + obtain ⟨u,hu,hum,huc⟩ := rareBranchRealizer.correct z (.cons (TreeTyped.encode z) s) + have hgate := OnlinePartialCall.call instructions out .gate .choose rareBranchRealizer.program + rfl _ (fun b => env (TreeTyped.encode b) .nil (.cons (TreeTyped.encode z) s)) u hu v hv + obtain ⟨p,hp,hpm,hpc⟩ := OnlinePartialCall.deterministicCall instructions out .prepare .gate + OnlineIntegerRetry.prepareProc rfl _ _ _ (OnlineIntegerRetry.prepare_exec (TreeTyped.encode z) s) + (.delay 1 (u.bind v)) hgate + refine ⟨p,hp,?_,?_⟩ + · intro g + rw [hpm] + simp only [Experiment.mean,Experiment.mean_bind] + simp_rw [hvm] + rw [hum,experiment,Experiment.mean_bind] + · have hc := Experiment.cost_bind_le u v + (exactOrdinaryRealizer.cost z+2*TreeFunction.size (TreeTyped.encode z)+20) hvc + simp only [Experiment.cost] at hpc + unfold budget + omega + +lemma failure (z : CompletionMargins) : + (experiment z).mean (fun o => if o=none then 1 else 0)=1/(2:ℚ)^(exactPrecision z) := by + rw [experiment,Experiment.mean_bind] + have he : (fun b : Bool => (if b then (.done none : Experiment (Option MatrixCode)) + else (exactOrdinary z).map some).mean (fun o => if o=none then 1 else 0))= + (fun b => if b then 1 else 0) := by + funext b + cases b with + | true => rfl + | false => + simp only [Bool.false_eq_true,ite_false,Experiment.mean_map,Option.some_ne_none] + exact PhysicalPartialSequence.mean_const _ _ + rw [he,rareBranch_probability] + +end ContingencyTables.ExactGatePrefix + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePublic.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePublic.lean new file mode 100644 index 0000000000000000000000000000000000000000..2695b3ae099ea0149eac959500a9171c3c9d7b20 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGatePublic.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePhysical +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicCost + +namespace OAI + +/-! # The cheap gate prefix on public binary input -/ + +namespace ContingencyTables.ExactGatePublic +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open DensePrograms ProfilePrograms SmallGraphProfiles +open ExactTablePrefix (code decode code_decode decode_eq_iff input) +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +attribute [local irreducible] exactOrdinary + +lemma feasible (htotal : (∑ i,r i)=∑ j,c j) : + (ExactGatePrefix.experiment (List.ofFn r,List.ofFn c)).All (FeasibleOutcome r c) := by + rw [ExactGatePrefix.experiment,Experiment.all_bind] + apply (Experiment.all_true _).mono + intro rare _ + cases rare with + | false => + rw [ite_eq_right Bool.false_ne_true,Experiment.all_map] + exact exactOrdinary_feasible r c htotal + | true => trivial + +lemma print_bound (htotal : (∑ i,r i)=∑ j,c j) (B : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) : + (ExactGatePrefix.experiment (List.ofFn r,List.ofFn c)).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B) := by + exact (feasible r c htotal).mono (by + intro o ho + cases o with + | none => exact Nat.zero_le _ + | some X => obtain ⟨T,rfl⟩ := ho; exact hB T) + +def experiment : Experiment (Option (Table r c)) := + (ExactGatePrefix.experiment (List.ofFn r,List.ofFn c)).map (decode r c) + +lemma failure (htotal : (∑ i,r i)=∑ j,c j) : + (experiment r c).mean (fun o => if o=none then 1 else 0)=1/(2:ℚ)^(correctionPrecision r c) := by + rw [experiment,Experiment.mean_map] + have he := Experiment.mean_congr_all _ + (fun o => if decode r c o=none then (1:ℚ) else 0) + (fun o => if o=none then (1:ℚ) else 0) + ((feasible r c htotal).mono (by + intro o ho + simp only [decode_eq_iff r c ho none,code,Option.map_none])) + rw [he,ExactGatePrefix.failure,exactPrecision_ofFn] + +noncomputable def output (o : Option (Table r c)) : + Cfg Symbol ExactPhysicalProgram.program.State := ExactGatePhysical.output (input r c) (code r c o) + +lemma output_injective : Function.Injective (output r c) := by + intro a b h + cases a with + | none => + cases b with + | none => rfl + | some Y => + have he := congrArg Cfg.state h + change (ExactGatePhysical.output (input r c) none).state= + (ExactGatePhysical.output (input r c) (some (matrixCode Y.val))).state at he + rw [ExactGatePhysical.output_some] at he + exact False.elim (ExactGatePhysical.output_none_live _ he) + | some X => + cases b with + | none => + have he := congrArg Cfg.state h + change (ExactGatePhysical.output (input r c) (some (matrixCode X.val))).state= + (ExactGatePhysical.output (input r c) none).state at he + rw [ExactGatePhysical.output_some] at he + exact False.elim (ExactGatePhysical.output_none_live _ he.symm) + | some Y => + apply congrArg some + apply PackedMatrixInjective.table_injective X Y + change ExactGatePhysical.output _ (some (matrixCode X.val))= + ExactGatePhysical.output _ (some (matrixCode Y.val)) at h + rw [ExactGatePhysical.output_some,ExactGatePhysical.output_some] at h + simpa only [Program.final,Cfg.mk.injEq,true_and] using h + +theorem table_prefix (htotal : (∑ i,r i)=∑ j,c j) (B : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) : + ∃ p,Implements ExactPhysicalProgram.program.table (output r c) + (ExactPhysicalProgram.program.initial (Tape.mk₁ (TreePost.packed (input r c)))) p ∧ + (∀ g : Option (Table r c) → ℚ,p.mean g=(experiment r c).mean g) ∧ + p.cost≤ExactGatePhysical.budget (input r c) B := by + have hb : (ExactGatePrefix.experiment (exactParsedMargins (input r c))).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B) := by + rw [show exactParsedMargins (input r c)=(List.ofFn r,List.ofFn c) from exactParsedMargins_spec r c] + exact print_bound r c htotal B hB + obtain ⟨p,hp,hpm,hpc⟩ := ExactGatePhysical.prefix_correct_cost (input r c) B hb + have hm (g : Option MatrixCode → ℚ) : + p.mean g=(ExactGatePrefix.experiment (List.ofFn r,List.ofFn c)).mean g := by + simpa only [input,exactParsedMargins_spec] using hpm g + have hall : p.All (FeasibleOutcome r c) := Experiment.all_of_mean_eq hm _ (feasible r c htotal) + refine ⟨p.map (decode r c),hp.map_all (decode r c) (output r c) + (hall.mono (by intro o ho; unfold output; rw [code_decode r c ho])),?_,?_⟩ + · intro g + rw [Experiment.mean_map,hm,experiment,Experiment.mean_map] + · simpa only [Experiment.cost_map] using hpc + +noncomputable def budget (B L : ℕ) : ℕ := + LiteralProgram.packTime (input r c).length+ExactGatePhysical.budget (input r c) B+LiteralProgram.postTime L + +noncomputable def publicOutput := ExactPublicCost.output r c (output r c) + +lemma publicOutput_halted (X : Table r c) : (publicOutput r c (some X)).state=none := rfl + +theorem prefix_correct_cost (htotal : (∑ i,r i)=∑ j,c j) (B L : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) + (hL : ∀ X : Table r c,(ExactPublicPrefix.word r c X).length≤L) : + ∃ p,Implements ExactPublicPrefix.program.table (publicOutput r c) + (ExactPublicPrefix.program.initial (Tape.mk₁ (input r c))) p ∧ + (∀ g : Option (Table r c) → ℚ,p.mean g=(experiment r c).mean g) ∧ p.cost≤budget r c B L := by + obtain ⟨p,hp,hm,hc⟩ := table_prefix r c htotal B hB + have hout (X : Table r c) : output r c (some X)=ExactPhysicalProgram.program.final + (Tape.mk₁ (TreePost.packed (ExactPublicPrefix.word r c X))) := ExactGatePhysical.output_some _ _ + obtain ⟨q,hq,hqm,hqc⟩ := ExactPublicCost.wrap_prefix r c (output r c) + (output_injective r c) hout L hL p hp + refine ⟨q,hq,(fun g => (hqm g).trans (hm g)),?_⟩ + exact hqc.trans (by unfold budget; omega) + +end +end ContingencyTables.ExactGatePublic + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateTyped.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateTyped.lean new file mode 100644 index 0000000000000000000000000000000000000000..126aa73077974d90f64c1ced2bdceddb6edfe514 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactGateTyped.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePrefix + +namespace OAI + +/-! # Parsing and printing around the cheap pre-tabulation prefix -/ + +namespace ContingencyTables.ExactGateTyped +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms ExactTypedProgram + +noncomputable def printedOutput (z : CompletionMargins) (s : Data) : + Option MatrixCode → OnlineTree.StoreCfg printedProgram + | none => StackComposition.mapCfg Sum.inl (some (Sum.inr default)) (ExactGatePrefix.output z s none) + | some X => OnlineTree.final printedProgram (TreeTyped.encode (GreedyFeasibleTable.printMatrix X)) s + +noncomputable def output (as : List Symbol) (s : Data) (o : Option MatrixCode) : + OnlineTree.StoreCfg program := StackComposition.mapCfg Sum.inr none + (printedOutput (exactParsedMargins as) s o) + +theorem printed_correct_cost (z : CompletionMargins) (s : Data) (B : ℕ) + (hB : (ExactGatePrefix.experiment z).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ p,Executes printedProgram.code printedProgram.coin (printedOutput z s) + (OnlineTree.initial printedProgram (TreeTyped.encode z) s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=(ExactGatePrefix.experiment z).mean g) ∧ + p.cost≤ExactGatePrefix.budget z+B := by + obtain ⟨p,hp,hpm,hpc⟩ := ExactGatePrefix.prefix_correct_cost z s + have hp' := hp.relabel printedProgram.code printedProgram.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + have next (o : Option MatrixCode) : ∃ q, + Executes printedProgram.code printedProgram.coin (printedOutput z s) + (StackComposition.mapCfg Sum.inl (some (Sum.inr default)) (ExactGatePrefix.output z s o)) q ∧ + (∀ g : Option MatrixCode → ℚ,q.mean g=g o) ∧ + q.cost≤o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost := by + cases o with + | none => exact ⟨.done none,.done none,(fun _ => rfl),le_rfl⟩ + | some X => + obtain ⟨n,hnb,hn⟩ := GreedyFeasibleTable.printMatrixRealizer.correct X s + obtain ⟨q,hq,hqm,hqc⟩ := Executes.of_run GreedyFeasibleTable.printMatrixRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic GreedyFeasibleTable.printMatrixRealizer.program) + (TreeTyped.encode X) s) none (encodeEnv (env + (TreeTyped.encode (GreedyFeasibleTable.printMatrix X)) .nil s)) hn + have hq' := hq.relabel printedProgram.code printedProgram.coin Sum.inr none + (fun _ => rfl) (fun _ => rfl) + refine ⟨q.bind (fun _ => .done (some X)),?_,?_,?_⟩ + · exact hq'.bind _ _ (fun _ => .done (some X)) + · intro g + simpa only [Experiment.mean_bind,Experiment.mean] using hqm (fun _ => g (some X)) + · have hc := Experiment.cost_bind_le q (fun _ => .done (some X)) 0 (fun _ => le_rfl) + simp only [Option.elim_some,Nat.add_zero] at hc ⊢ + exact hc.trans (hqc.trans hnb) + choose q hq hqm hqc using next + refine ⟨p.bind q,hp'.bind q _ hq,?_,?_⟩ + · intro g + rw [Experiment.mean_bind] + simp_rw [hqm] + exact hpm g + · have hall := Experiment.all_of_mean_eq hpm _ hB + exact (Experiment.cost_bind_le_of_all p q B (hall.mono + (fun o ho => (hqc o).trans ho))).trans (Nat.add_le_add_right hpc B) + +theorem prefix_correct_cost (as : List Symbol) (s : Data) (B : ℕ) + (hB : (ExactGatePrefix.experiment (exactParsedMargins as)).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ p,Executes program.code program.coin (output as s) + (OnlineTree.initial program (TreeTyped.encode as) s) p ∧ + (∀ g : Option MatrixCode → ℚ, + p.mean g=(ExactGatePrefix.experiment (exactParsedMargins as)).mean g) ∧ + p.cost≤exactParsedMarginsRealizer.cost as+ExactGatePrefix.budget (exactParsedMargins as)+B := by + obtain ⟨p,hp,hpm,hpc⟩ := printed_correct_cost (exactParsedMargins as) s B hB + have hp' := hp.relabel program.code program.coin Sum.inr none (fun _ => rfl) (fun _ => rfl) + obtain ⟨n,hnb,hn⟩ := exactParsedMarginsRealizer.correct as s + obtain ⟨u,hu,hum,huc⟩ := Executes.of_run exactParsedMarginsRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic exactParsedMarginsRealizer.program) + (TreeTyped.encode as) s) none (encodeEnv (env (TreeTyped.encode (exactParsedMargins as)) .nil s)) hn + have hu' := hu.relabel program.code program.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + refine ⟨u.bind (fun _ => p),hu'.bind _ _ (fun _ => hp'),?_,?_⟩ + · intro g + rw [Experiment.mean_bind,hum] + exact hpm g + · have hc := Experiment.cost_bind_le u (fun _ => p) p.cost (fun _ => le_rfl) + omega + +end ContingencyTables.ExactGateTyped + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactInputBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactInputBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..85dfcf3b5af06d9a4da92bf63ac0693fd602823d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactInputBounds.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGateCost +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrintCost +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInputWordBudget + +namespace OAI + +/-! # Exact-sampler parameters in the public binary input size -/ + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralCodec +open ProfilePrograms DensePrograms Algorithms Polynomial +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "S" => samplingSize n r 0 + +lemma exact_public_length (htotal : (∑ i,r i)=∑ j,c j) : + (encodeMargins r c).length ≤ 5*S^2 := by + have h := encodeSamplingInput_length r c htotal 0 + have he : (encodeMargins r c).length ≤ (encodeSamplingInput r c 0).length := by + simp only [encodeSamplingInput,List.length_append] + omega + exact he.trans h + +lemma exact_public_weight (htotal : (∑ i,r i)=∑ j,c j) : + weight (encodeMargins r c) ≤ 91*S^2 := by + have h := exact_public_length r c htotal + have hS : 1 ≤ S^2 := one_le_pow₀ (by unfold samplingSize; omega) + rw [weight_word] + omega + +lemma exact_precision_bound : correctionPrecision r c ≤ 245^8*S^16 := by + let dim := CompletionCounts.dimensionAllowance (I := Fin m) (J := Fin n) + have hi := sampling_internal_size_bound r c 0 + have hd : dim ≤ 245*S^2 := by dsimp only [dim]; omega + have hb : smallBinaryLength r c ≤ 245*S^2 := by omega + change dim^6*(smallBinaryLength r c)^2 ≤ _ + calc + _ ≤ (245*S^2)^6*(245*S^2)^2 := + Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (Nat.pow_le_pow_left hb _) + _ = 245^8*S^16 := by ring + +lemma exact_margin_weight_polynomial : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → weight (List.ofFn r,List.ofFn c) ≤ p.eval (samplingSize n r 0) := by + obtain ⟨p,hp⟩ := polynomial_exactParsedMargins + refine ⟨p.comp (91*X^2),?_⟩ + intro m n r c htotal + have h := (Nat.le_add_left _ _).trans (hp (encodeMargins r c)) + rw [exactParsedMargins_spec] at h + exact h.trans (by + rw [eval_comp] + simp only [eval_mul,eval_ofNat,eval_pow,eval_X] + exact polynomial_eval_monotone p (exact_public_weight r c htotal)) + +lemma exact_parameter_polynomial : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → exactParameterMeasure (List.ofFn r,List.ofFn c) ≤ + p.eval (samplingSize n r 0) := by + obtain ⟨p,hp⟩ := exact_margin_weight_polynomial + refine ⟨C (245^8)*X^16+p,?_⟩ + intro m n r c htotal + simp only [exactParameterMeasure,exactPrecision_ofFn,eval_add,eval_mul,eval_C,eval_pow,eval_X] + exact Nat.add_le_add (exact_precision_bound r c) (hp m n r c htotal) + +lemma exact_total_weight : weight (∑ i,r i) ≤ 4*S+1 := by + have hs : (∑ i,r i).size ≤ Nat.clog 2 ((∑ i,r i)+1) := + Nat.size_le.mpr (Nat.lt_of_lt_of_le (Nat.lt_succ_self _) + (Nat.le_pow_clog (by decide) _)) + have hw := weight_nat_le (∑ i,r i) + unfold samplingSize + omega + +lemma exact_matrix_size : ExactPrintCost.matrixSize (n := n) r ≤ 25*S^3 := by + have hS : 1 ≤ S := by unfold samplingSize; omega + have hm : m ≤ S := by unfold samplingSize; omega + have hn : n ≤ S := by unfold samplingSize; omega + have hw : 4*weight (∑ i,r i)+2 ≤ 22*S := by + have := exact_total_weight (n := n) r + omega + have hpow : S ≤ S^3 := Nat.le_self_pow (by decide) _ + calc + _ ≤ S*(S*(22*S)+2)+1 := by unfold ExactPrintCost.matrixSize; gcongr + _ ≤ 25*S^3 := by nlinarith + +lemma exact_ordinary_bits_polynomial : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + exactOrdinaryBits (List.ofFn r,List.ofFn c) ≤ p.eval (samplingSize n r 0) := by + let q : Polynomial ℕ := X+2*(C (245^8)*X^16) + refine ⟨C (344^644)*q^1288,?_⟩ + intro m n r c + have hD := exact_precision_bound r c + have hS : samplingSize n r (2*correctionPrecision r c) ≤ q.eval (samplingSize n r 0) := by + simp only [q,eval_add,eval_mul,eval_ofNat,eval_C,eval_pow,eval_X] + unfold samplingSize at * + omega + rw [exactOrdinaryBits_ofFn] + have hf : finiteSamplerBits r c (2*correctionPrecision r c) ≤ + 344^644*(samplingSize n r (2*correctionPrecision r c))^1288 := + sampling_word_budget_polynomial r c (2*correctionPrecision r c) + have hp (k : ℕ) : + 344^644*(samplingSize n r (2*correctionPrecision r c))^k ≤ + (C (344^644)*q^k).eval (samplingSize n r 0) := by + rw [eval_mul,eval_C,eval_pow] + exact Nat.mul_le_mul_left (344^644) (Nat.pow_le_pow_left hS k) + exact hf.trans (hp 1288) + +lemma exact_gate_measure_polynomial : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → ExactGateCost.measure (List.ofFn r,List.ofFn c) ≤ + p.eval (samplingSize n r 0) := by + obtain ⟨p,hp⟩ := exact_parameter_polynomial + obtain ⟨q,hq⟩ := exact_margin_weight_polynomial + obtain ⟨u,hu⟩ := exact_ordinary_bits_polynomial + refine ⟨p+q+u,?_⟩ + intro m n r c htotal + simpa only [ExactGateCost.measure,FiniteWordExecution.wordMeasure,eval_add,add_assoc] + using Nat.add_le_add (hp m n r c htotal) + (Nat.add_le_add (hq m n r c htotal) (hu m n r c)) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerChoice.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..abb986ec07a463df0996637c1f2515f046636611 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerChoice.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FinitePartialDraw +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts + +namespace OAI + +/-! # Exact integer-weighted choice for the residual correction branch -/ + +namespace ContingencyTables.ExactIntegerChoice +open MatchingFPRAS MatchingFPRAS.FiniteChoice ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section +variable {r : ℕ} (w : Fin r → ℕ) + +def totalWeight : ℕ := ∑ i,w i + +def normalized : Fin r → ℚ := fun i => (w i:ℚ)/totalWeight w + +def prefixWeight (n : ℕ) : ℕ := ∑ i,if i.val simp + +lemma grid_scaled_cumulative (h : 0 z.val) he + exact hj (hv ▸ x.isLt) + simp only [intervalTrial,dite_eq_right hj,reduceCtorEq,hn] + +lemma intervalTrial_mass {V Q : ℕ} [NeZero Q] (h : V≤Q) (x : Fin V) : + (mapLaw (uniformLaw (α := Fin Q)) (intervalTrial h)).mass (some x)=1/(Q:ℚ) := by + simp only [mapLaw,uniformLaw,uniformMass,Fintype.card_fin] + simp_rw [intervalTrial_eq_some] + simp + +/-- A rational choice with integer weights, after a single binary rejection +trial. The sum of these masses is totalWeight / 2^k. -/ +def weightedTrial (h : 0 + choose (normalized w) (normalized_total w h) h j=i)).card:ℚ)=w i := by + change _/(totalWeight w:ℚ)=(w i:ℚ)/totalWeight w at he + exact (div_left_inj' hVpos.ne').mp he + have hsum : (∑ j : Fin (totalWeight w), + if choose (normalized w) (normalized_total w h) h j=i then 1/(Q:ℚ) else 0)= + (∑ j : Fin (totalWeight w), + if choose (normalized w) (normalized_total w h) h j=i then (1:ℚ) else 0)/(Q:ℚ) := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> simp + rw [hsum,Finset.sum_boole,hc] + +end +end ContingencyTables.ExactIntegerChoice + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerOnline.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerOnline.lean new file mode 100644 index 0000000000000000000000000000000000000000..36add6baeadef335bd757586434954bcd3e2366a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerOnline.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerRetry +import OAI.Combinatorics.ContingencyTables.Machines.OnlineIntegerRetry +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordExecution +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram + +namespace OAI + +/-! # The concrete fair-bit integer trial used by exact correction -/ + +namespace ContingencyTables.ExactIntegerOnline +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open ExactIntegerChoice ExactIntegerPrograms FirstSuccess ResidualMixture +open scoped BigOperators Classical + +def trialBits (w : List ℕ) : ℕ := Nat.clog 2 w.sum + +def trialBitsRealizer : Realizer trialBits := + composition listSum DensePrograms.ceilLogTwoRealizer + +lemma polynomial_trialBits : PolynomialTime trialBitsRealizer := + polynomial_composition polynomial_listSum DensePrograms.polynomial_ceilLogTwo + +def trial (w : List ℕ) : Experiment (Option ℕ) := + FiniteWordExecution.experiment trialBits weightedIndex w + +noncomputable def trialRealizer : OnlineTree.Realizer trial := + FiniteWordExecution.realizer trialBitsRealizer weightedIndexRealizer + +lemma trialBits_le_weight (w : List ℕ) : trialBits w ≤ weight w := by + rw [trialBits,DensePrograms.clog_two_eq_size_pred] + exact (Nat.size_le_size (Nat.sub_le _ _)).trans (IntegerMatrixPrograms.sum_size_le_weight w) + +theorem polynomial_trial : OnlineTree.PolynomialTime trialRealizer := by + apply OnlineTree.work_remeasure + (FiniteWordExecution.work_realizer polynomial_trialBits polynomial_weightedIndex) + (2*Polynomial.X) + intro w + have hb:=trialBits_le_weight w + simp only [FiniteWordExecution.wordMeasure,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X] + omega + +private lemma map_expectation {X Y : Type*} [Fintype X] [Fintype Y] [DecidableEq Y] + (p : RationalLaw X) (f : X → Y) (g : Y → ℚ) : + (∑ y,(mapLaw p f).mass y*g y)=∑ x,p.mass x*g (f x) := by + simp only [mapLaw,Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp [ite_mul] + +private lemma average_expectation {Y : Type*} [Fintype Y] [DecidableEq Y] + (k : ℕ) (f : (Fin k → Bool) → Y) (g : Y → ℚ) : + average (fun bits => g (f bits))= + ∑ y,(mapLaw (uniformLaw (α := Fin k → Bool)) f).mass y*g y := by + rw [map_expectation] + simp only [average,uniformLaw,uniformMass,Fintype.card_fun,Fintype.card_bool, + Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat,one_div,inv_mul_eq_div,Finset.sum_div] + +/-- The compiled variable-length trial has precisely the integer-grid +probabilities, with the unused suffix of the binary range returning none. -/ +theorem trial_mean {r : ℕ} (w : Fin r → ℕ) (h : 0 weightedIndex (List.ofFn w,bs)) := by + unfold trial FiniteWordExecution.experiment FiniteWordExecution.source + rw [hL] + rw [he,Experiment.mean_map,OnlineWord.mean_prepend_nil] + simp_rw [weightedIndex_ofFn w h hQ] + rw [average_expectation k (fun bits => weightedTrial w h hQ (FairBits.binaryWordEquiv k bits)) + (fun y => g (y.map Fin.val))] + have hlaw : mapLaw (uniformLaw (α := Fin k → Bool)) + (fun bits => weightedTrial w h hQ (FairBits.binaryWordEquiv k bits))=trialLaw w h hQ := by + rw [←FairBits.map_equiv (FairBits.binaryWordEquiv k),FairBits.uniform_equiv] + rw [hlaw] + +private lemma retry_mass_succ {B : Type*} [Fintype B] [DecidableEq B] + (p : RationalLaw (Option B)) (N : ℕ) (y : Option B) : + (retryLaw p (fun b => b.map some) none (N+1)).mass y= + (y.elim 0 (fun b => p.mass (some b)))+ + p.mass none*(retryLaw p (fun b => b.map some) none N).mass y := by + rw [retryLaw,retryStep_mass] + cases y <;> simp [successMass,failureMass] + +/-- Mean preservation for every finite prefix allows the online loop to +reuse the already proved exact rational retry law. -/ +lemma prefix_mean {A B C : Type} [Fintype B] [DecidableEq B] + (f : A → Experiment (Option C)) (a : A) (p : RationalLaw (Option B)) (e : B → C) + (hf : ∀ g : Option C → ℚ,(f a).mean g=∑ y,p.mass y*g (y.map e)) + (N : ℕ) (g : Option C → ℚ) : + (OnlineIntegerRetry.prefixExperiment (f := f) a N).mean g= + ∑ y,(retryLaw p (fun b => b.map some) none N).mass y*g (y.map e) := by + induction N with + | zero => simp [OnlineIntegerRetry.prefixExperiment,Experiment.mean,retryLaw,pointLaw] + | succ N ih => + rw [OnlineIntegerRetry.prefixExperiment,Experiment.mean_bind,hf] + simp only [Fintype.sum_option,Option.map_none,Option.map_some,Option.elim_none, + Option.elim_some,Experiment.mean,ih] + simp_rw [retry_mass_succ] + simp only [Option.elim_none,Option.elim_some,zero_add] + simp only [add_mul,Finset.sum_add_distrib,mul_assoc] + rw [←Finset.mul_sum] + ring + +theorem integer_prefix_mean {r : ℕ} (w : Fin r → ℕ) (h : 0 if y=none then 1 else 0)= + (failure w (Q := 2^Nat.clog 2 (totalWeight w)))^N := by + rw [integer_prefix_mean w h] + simp only [Option.map_eq_none_iff,mul_ite,mul_one,mul_zero,Finset.sum_ite_eq', + Finset.mem_univ,ite_true,retryIntegerLaw_none] + +end ContingencyTables.ExactIntegerOnline + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerPhysical.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerPhysical.lean new file mode 100644 index 0000000000000000000000000000000000000000..7158e1be199937af2594b340419603bf93877805 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactIntegerPhysical.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.ContingencyTables.Machines.OnlineRetryRuntime +import OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerOnline + +namespace OAI + +/-! # Finite expected machine time for exact binary weighted choice -/ + +namespace ContingencyTables.ExactIntegerPhysical +open MatchingFPRAS MatchingFPRAS.PhysicalStream ExactIntegerChoice + +theorem prefix_failure_bound {r : ℕ} (w : Fin r → ℕ) (h : 0 if b=none then 1 else 0) ≤ (1/2:ℚ)^N := by + rw [ExactIntegerOnline.integer_prefix_failure w h] + exact pow_le_pow_left₀ + (failure_nonnegative w (Nat.le_pow_clog (by decide : 1<2) (totalWeight w))) + (failure_lt_half w (clog_power_lt_twice (totalWeight w) h)).le N + +/-- The repeating finite-state bit program has summable physical halting +tail for every positive list of integer weights. -/ +theorem expected_time {r : ℕ} (w : Fin r → ℕ) (h : 0 TreeFraction.normalize (w,xs.sum)) +def weightsCodeRealizer : Realizer weightsCode := + composition (f := fun xs : List ℕ => (xs.sum,xs)) + (g := fun z : ℕ×List ℕ => z.2.map (fun w => TreeFraction.normalize (w,z.1))) + (pair listSum identity) + (mapWith (composition (pair second first) TreeFraction.normalizeRealizer)) + +lemma polynomial_weightsCode : PolynomialTime weightsCodeRealizer := + polynomial_composition (polynomial_pair polynomial_listSum polynomial_identity) + (polynomial_mapWith (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + TreeFraction.polynomial_normalize)) + +abbrev Input := List ℕ×List Bool + +def choiceInput (z : Input) : List TreeFraction.Fraction×TreeFraction.Fraction := + (weightsCode z.1,(StackAddition.value z.2,z.1.sum)) +def choiceInputRealizer : Realizer choiceInput := + pair (composition first weightsCodeRealizer) + (pair (composition second bitValue) (composition first listSum)) + +lemma polynomial_choiceInput : PolynomialTime choiceInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_weightsCode) + (polynomial_pair (polynomial_composition polynomial_second polynomial_bitValue) + (polynomial_composition polynomial_first polynomial_listSum)) + +/-- One trial returns an index or requests another independent word. +All integers are processed in binary; no weight is expanded into copies. -/ +def weightedIndex (z : Input) : Option ℕ := + if StackAddition.value z.2 TreeFraction.repr (normalized w i)) := by + simp only [weightsCode,List.sum_ofFn,List.map_ofFn,TreeFraction.normalize_repr] + rfl + +/-- The compiled binary trial is exactly the integer-grid experiment. -/ +lemma weightedIndex_ofFn {r k : ℕ} (w : Fin r → ℕ) (h : 0 x.map some) (some i)=p.mass (some i) := by + simp [successMass] + +private lemma lifted_no_success (p : RationalLaw (Option (Fin r))) : + successMass p (fun x => x.map some) none=0 := by + simp [successMass] + +private lemma lifted_failure (p : RationalLaw (Option (Fin r))) : + failureMass p (fun x => x.map some)=p.mass none := by + simp [failureMass] + +/-- `none` records that all supplied independent trials rejected; it is +not a fallback table. This is the finite prefix law of exact rejection. -/ +def retryIntegerLaw (N : ℕ) : RationalLaw (Option (Fin r)) := + retryLaw (trialLaw w h hQ) (fun x => x.map some) none N + +lemma retryIntegerLaw_none (N : ℕ) : + (retryIntegerLaw w h hQ N).mass none=(failure w (Q := Q))^N := by + rw [retryIntegerLaw,retryLaw_mass,outputMass,lifted_no_success,lifted_failure,trialLaw_none] + simp only [zero_mul,ite_true,zero_add] + +lemma retryIntegerLaw_some (N : ℕ) (i : Fin r) : + (retryIntegerLaw w h hQ N).mass (some i)= + normalized w i*(1-(failure w (Q := Q))^N) := by + rw [retryIntegerLaw,retryLaw_mass,outputMass,lifted_success,lifted_failure,trialLaw_none, + weightedTrial_mass] + simp only [reduceCtorEq,ite_false,add_zero] + have hV : (totalWeight w:ℚ)≠0 := by exact_mod_cast h.ne' + have hQt : (Q:ℚ)≠0 := by exact_mod_cast (NeZero.ne Q) + have he : (w i:ℚ)/Q=normalized w i*(1-failure w (Q := Q)) := by + unfold normalized failure + field_simp + ring + rw [he,mul_assoc] + congr 1 + have hg := geometric_balance (failure w (Q := Q)) N + linarith + +include hQ in +lemma failure_nonnegative : 0≤failure w (Q := Q) := by + unfold failure + have hQt : (0:ℚ) ((retryIntegerLaw w h hQ N).mass (some i):ℝ)) + Filter.atTop (nhds (normalized w i:ℝ)) := by + have hf0 : (0:ℝ)≤failure w (Q := Q) := by exact_mod_cast failure_nonnegative w hQ + have hf1 : (failure w (Q := Q):ℝ)<1 := by + have hh : (failure w (Q := Q):ℝ)<1/2 := by + have hh := (Rat.cast_lt (K := ℝ)).mpr (failure_lt_half w hshort) + norm_num at hh ⊢ + exact hh + linarith + have ht := tendsto_pow_atTop_nhds_zero_of_lt_one hf0 hf1 + have hout : Filter.Tendsto + (fun N => (normalized w i:ℝ)*(1-(failure w (Q := Q):ℝ)^N)) + Filter.atTop (nhds ((normalized w i:ℝ)*(1-0))) := + tendsto_const_nhds.mul (tendsto_const_nhds.sub ht) + simpa only [retryIntegerLaw_some,Rat.cast_mul,Rat.cast_sub,Rat.cast_one,Rat.cast_pow, + sub_zero,mul_one] using hout + +/-- The expected number of independent integer proposals is less than two. -/ +lemma retryIntegerLaw_expected_attempts (hshort : Q<2*totalWeight w) : + Summable (fun N => ((retryIntegerLaw w h hQ N).mass none:ℝ)) ∧ + (∑' N,((retryIntegerLaw w h hQ N).mass none:ℝ))<2 := by + have hf0 : (0:ℝ)≤failure w (Q := Q) := by exact_mod_cast failure_nonnegative w hQ + have hfhalf : (failure w (Q := Q):ℝ)<1/2 := by + have hh := (Rat.cast_lt (K := ℝ)).mpr (failure_lt_half w hshort) + norm_num at hh ⊢ + exact hh + have hf1 : (failure w (Q := Q):ℝ)<1 := by linarith + simp only [retryIntegerLaw_none,Rat.cast_pow] + refine ⟨summable_geometric_of_lt_one hf0 hf1,?_⟩ + rw [tsum_geometric_of_lt_one hf0 hf1] + rw [inv_lt_comm₀ (by linarith : (0:ℝ)<1-failure w (Q := Q)) (by norm_num)] + linarith + +lemma clog_power_lt_twice (V : ℕ) (hV : 0 if o=some X then 1 else 0)= + ∑ i : Fin K,if lookup (candidates,i.val)=X then + (retryIntegerLaw w hw (Nat.le_pow_clog (by decide : 1<2) (totalWeight w)) N).mass (some i) + else 0 := by + rw [prefix_mean candidates w hw,Fintype.sum_option] + simp only [Option.map_none,reduceCtorEq,ite_false,mul_zero,zero_add,Option.map_some, + Option.some.injEq,mul_ite,mul_one,mul_zero] + +/-- The integer rejection loop tends to the exact weighted pushforward, +including repeated matrix codes in a candidate list. -/ +theorem prefix_limit {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 + ((OnlineIntegerRetry.prefixExperiment (f := trial) (candidates,List.ofFn w) N).mean + (fun o => if o=some X then 1 else 0):ℝ)) + Filter.atTop (nhds ((∑ i : Fin K,if lookup (candidates,i.val)=X then normalized w i else 0:ℚ):ℝ)) := by + simp_rw [prefix_mass candidates w hw,Rat.cast_sum] + apply tendsto_finsetSum + intro i _ + by_cases hi : lookup (candidates,i.val)=X + · simp only [hi,ite_true] + exact retryIntegerLaw_limit w hw _ (clog_power_lt_twice (totalWeight w) hw) i + · simp only [hi,ite_false,Rat.cast_zero] + exact tendsto_const_nhds + +end +end ContingencyTables.ExactMatrixTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixLookup.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bc2fac10fd79c950bc1125c455e2b63f677a898 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixLookup.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixTrial +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxLaw + +namespace OAI + +/-! # Feasibility of every decoded candidate in the exact branch -/ + +namespace ContingencyTables.ExactMatrixTrial +open ProfilePrograms DensePrograms OriginalTableBox +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +lemma lookup_index (fallback X : Table r c) : + lookup ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val), + (index r c le_rfl X).val)=matrixCode X.val := by + rw [lookup,candidates_code] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,Fin.isLt,dite_true,Option.getD_some] + rw [OriginalBoxLaw.tableAt_index] + rfl + +/-- Even a malformed index returns the fixed feasible fallback. -/ +lemma lookup_feasible (fallback : Table r c) (i : ℕ) : + ∃ X : Table r c, + lookup ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val),i)= + matrixCode X.val := by + rw [lookup,candidates_code] + by_cases hi : i<((∑ j,r j)+1)^(m*n) + · simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,hi,dite_true,Option.getD_some] + cases hx : tableAt r c (⟨i,hi⟩ : Index m n (∑ j,r j)) with + | none => exact ⟨fallback,rfl⟩ + | some X => exact ⟨X,rfl⟩ + · simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,hi,dite_false,Option.getD_none] + exact ⟨fallback,rfl⟩ + +end +end ContingencyTables.ExactMatrixTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTableLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTableLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..684d0cba8a1343a2d4d6eeee8e9b3e1c0d58649f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTableLaw.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixLimits +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixLookup +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLawEmbedding +import OAI.Combinatorics.ContingencyTables.Machines.MatrixCodeEquality + +namespace OAI + +/-! # Exact weighted matrix selection realizes a table law -/ + +namespace ContingencyTables.ExactMatrixTrial +open MatchingFPRAS MatchingFPRAS.PhysicalStream DensePrograms ProfilePrograms OriginalTableBox +open ExactIntegerChoice ResidualMixture FirstSuccess +open scoped BigOperators Classical +noncomputable section +attribute [local irreducible] lookup originalCandidates + +lemma normalized_counts {K Q : ℕ} (p : IntegerLaw (Fin K) Q) + (hQ : 0 decide + (lookup ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val),i.val)=matrixCode X.val) + have hn (i : Index m n (∑ j,r j)) : + normalized (p.push (index r c le_rfl)).count i= + ((p.push (index r c le_rfl)).toRational hQ).mass i := + normalized_counts _ hQ i + simp_rw [hn] + have hm : (mapLaw ((p.push (index r c le_rfl)).toRational hQ) test).mass true= + (mapLaw (p.toRational hQ) (fun T => test (index r c le_rfl T))).mass true := by + rw [IntegerLaw.toRational_push,mapLaw_comp] + have he (T : Table r c) : test (index r c le_rfl T)=true ↔ T=X := by + simp only [test,decide_eq_true_eq,lookup_index] + exact ⟨fun h => Subtype.ext (matrixCode_injective h),fun h => by rw [h]⟩ + simp only [mapLaw] at hm + simp only [test,decide_eq_true_eq] at hm + rw [hm] + have htest (T : Table r c) : + (lookup ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val), + (index r c le_rfl T).val)=matrixCode X.val) ↔ T=X := by + simpa only [test,decide_eq_true_eq] using he T + simp only [htest,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + +/-- The finite prefixes of the actual exact matrix loop converge to the +input table law. -/ +theorem table_prefix_limit {m n Q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (p : IntegerLaw (Table r c) Q) (hQ : 0 + ((OnlineIntegerRetry.prefixExperiment (f := trial) + ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val), + List.ofFn (p.push (index r c le_rfl)).count) N).mean + (fun o => if o=some (matrixCode X.val) then 1 else 0):ℝ)) + Filter.atTop (nhds ((p.toRational hQ).mass X:ℝ)) := by + have h := prefix_limit (originalCandidates (List.ofFn r,List.ofFn c),matrixCode fallback.val) + (p.push (index r c le_rfl)).count (count_weight_pos _ hQ) (matrixCode X.val) + rw [table_normalized_event r c p hQ fallback X] at h + exact h + +end +end ContingencyTables.ExactMatrixTrial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..abc72e99a65ba9b1893fb5d681ccb75308eee03a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactMatrixTrial.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerOnline +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableBox +import OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerPhysical + +namespace OAI + +/-! # Returning a matrix from the exact integer-weighted trial -/ + +namespace ContingencyTables.ExactMatrixTrial +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open DensePrograms ProfilePrograms + +/-- Enumerated candidates together with a feasible fallback. -/ +abbrev Lookup := List (Option MatrixCode)×MatrixCode +abbrev Input := Lookup×List ℕ + +def lookup (z : Lookup×ℕ) : MatrixCode := (z.1.1.getD z.2 none).getD z.1.2 + +def lookupRealizer : Realizer lookup := + composition (f := fun z : Lookup×ℕ => (z.1.2,z.1.1.getD z.2 none)) + (g := fun z : MatrixCode×Option MatrixCode => z.2.getD z.1) + (pair (composition first second) + (composition (pair (composition first first) second) (getDFast none))) + FirstSuccessProgram.defaultRealizer + +lemma polynomial_lookup : PolynomialTime lookupRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) (polynomial_getDFast none))) FirstSuccessProgram.polynomial_default + +def decode (z : Lookup×Option ℕ) : Option MatrixCode := + z.2.map (fun i => lookup (z.1,i)) + +def decodeRealizer : Realizer decode := + (choose (composition second FirstSuccessProgram.isSomeRealizer) + (composition (composition + (pair first (composition (pair (constant (0:ℕ)) second) FirstSuccessProgram.defaultRealizer)) + lookupRealizer) some) (constant none)).congr (by + intro z + rcases z with ⟨cache,o⟩ + cases o <;> rfl) + +lemma polynomial_decode : PolynomialTime decodeRealizer := by + unfold decodeRealizer + apply polynomial_congr + exact polynomial_choose (polynomial_composition polynomial_second FirstSuccessProgram.polynomial_isSome) + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_second) + FirstSuccessProgram.polynomial_default)) polynomial_lookup) polynomial_some) + (polynomial_constant none) + +def trial (z : Input) : Experiment (Option MatrixCode) := + (ExactIntegerOnline.trial z.2).map (fun i => decode (z.1,i)) + +noncomputable def trialRealizer : OnlineTree.Realizer trial := + (OnlineTree.composition + (OnlineTree.pair (OnlineTree.deterministic first) + (OnlineTree.composition (OnlineTree.deterministic second) ExactIntegerOnline.trialRealizer)) + (OnlineTree.deterministic decodeRealizer)).congr (by + intro z g + simp only [Experiment.mean_bind,Experiment.mean,Experiment.mean_map,trial]) + +lemma polynomial_trial : OnlineTree.PolynomialTime trialRealizer := by + unfold trialRealizer + apply OnlineTree.work_congr + exact OnlineTree.polynomial_composition + (OnlineTree.polynomial_pair (OnlineTree.polynomial_deterministic polynomial_first) + (OnlineTree.polynomial_composition (OnlineTree.polynomial_deterministic polynomial_second) + ExactIntegerOnline.polynomial_trial)) + (OnlineTree.polynomial_deterministic polynomial_decode) + +noncomputable section +open ExactIntegerChoice ResidualMixture +open scoped BigOperators Classical + +lemma trial_mean {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 lookup (candidates,i.val))) := by + rw [trial,Experiment.mean_map,ExactIntegerOnline.trial_mean w hw] + apply Finset.sum_congr rfl + intro y _ + cases y <;> rfl + +lemma trial_failure {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 if o=none then 1 else 0)= + failure w (Q := 2^(Nat.clog 2 (totalWeight w))) := by + rw [trial_mean _ w hw,Fintype.sum_option] + simp only [Option.map_none,ite_true,Option.map_some,reduceCtorEq,ite_false,mul_zero, + Finset.sum_const_zero,add_zero,mul_one,trialLaw_none] + +lemma prefix_mean {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 lookup (candidates,i.val))) := + ExactIntegerOnline.prefix_mean trial (candidates,List.ofFn w) _ _ + (trial_mean candidates w hw) N g + +lemma prefix_failure {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 if o=none then 1 else 0)≤(1/2:ℚ)^N := by + rw [prefix_mean candidates w hw,Fintype.sum_option] + simp only [Option.map_none,ite_true,Option.map_some,reduceCtorEq,ite_false,mul_zero, + Finset.sum_const_zero,add_zero,mul_one] + exact retryIntegerLaw_failure_bound w hw _ + (clog_power_lt_twice (totalWeight w) hw) N + +/-- Exact weighted matrix selection has a summable physical halting tail. -/ +theorem expected_time {K : ℕ} (candidates : Lookup) (w : Fin K → ℕ) + (hw : 0 (exactSamplingParameters z.1,z.2)) + (g := samplingMatrixAll) + (pair (composition (f := Prod.fst) (g := exactSamplingParameters) + first exactSamplingParametersRealizer) second) samplingMatrixAllRealizer + +lemma polynomial_exactOrdinaryWord : PolynomialTime exactOrdinaryWordRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_exactSamplingParameters) polynomial_second) + polynomial_samplingMatrixAll + +def exactOrdinary (z : CompletionMargins) : Experiment MatrixCode := + FiniteWordExecution.experiment exactOrdinaryBits exactOrdinaryWord z + +noncomputable def exactOrdinaryRealizer : OnlineTree.Realizer exactOrdinary := + FiniteWordExecution.realizer exactOrdinaryBitsRealizer exactOrdinaryWordRealizer + +lemma work_exactOrdinary : OnlineTree.WorkBound exactOrdinaryRealizer + (FiniteWordExecution.wordMeasure exactOrdinaryBits) := + FiniteWordExecution.work_realizer polynomial_exactOrdinaryBits polynomial_exactOrdinaryWord + +/-- The gate retains the margins for either branch. -/ +def exactGate (z : CompletionMargins) : Experiment (Bool×CompletionMargins) := + (rareBranch z).map (fun rare => (rare,z)) + +noncomputable def exactGateRealizer : OnlineTree.Realizer exactGate := + (OnlineTree.pair rareBranchRealizer (OnlineTree.deterministic identity)).congr + (by intro z g; simp only [Experiment.mean_bind,Experiment.mean,Experiment.mean_map,exactGate,id_eq]) + +lemma work_exactGate : OnlineTree.WorkBound exactGateRealizer exactParameterMeasure := by + unfold exactGateRealizer + apply OnlineTree.work_congr + apply OnlineTree.work_pair work_rareBranch + (OnlineTree.work_of_polynomial (OnlineTree.polynomial_deterministic polynomial_identity) X + (by intro z; simp only [eval_X,exactParameterMeasure]; omega)) X + intro z + simp only [eval_X,exactParameterMeasure] + omega + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms MatchingFPRAS.PhysicalStream +open scoped BigOperators + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +lemma exactOrdinaryWord_code (htotal : (∑ i,r i)=∑ j,c j) + (bits : Fin (finiteSamplerBits r c (2*correctionPrecision r c)) → Bool) : + exactOrdinaryWord ((List.ofFn r,List.ofFn c),List.ofFn bits)= + matrixCode (scheduledTableDraw r c htotal (2*correctionPrecision r c) bits).val := by + rw [exactOrdinaryWord,exactSamplingParameters_ofFn,samplingMatrixAll_code r c htotal] + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdf25e9bbe3f5814c6afb75f3d82f7dba733c0f8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalCost.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedCost + +namespace OAI + +/-! # A physical cost bound for every finite prefix of the exact sampler -/ + +namespace ContingencyTables.ExactPhysicalCost +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost +open MatchingFPRAS.TreeTyped MatchingFPRAS.TreePost Turing +open DensePrograms ProfilePrograms ExactPhysicalProgram + +attribute [local irreducible] ExactTypedProgram.program + +noncomputable def typedBudget (as : List Symbol) (N B : ℕ) : ℕ := + exactParsedMarginsRealizer.cost as+ExactCoreCost.budget (exactParsedMargins as) N+B + +noncomputable def budget (as : List Symbol) (N B : ℕ) : ℕ := + typedBudget as N B*OnlineStack.Executes.factor ExactTypedProgram.program.code + (weight as) (typedBudget as N B) + +/-- The compiler's quadratic overhead is charged to the actual finite +prefix cost. The executable program is still the same unbounded sampler. -/ +theorem prefix_correct_cost (as : List Symbol) (N B : ℕ) + (hB : (ExactCoreProgram.prefixExperiment (exactParsedMargins as) N).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ q,Implements program.table (output as) + (program.initial (Tape.mk₁ (packed as))) q ∧ + (∀ g : Option MatrixCode → ℚ, + q.mean g=(ExactCoreProgram.prefixExperiment (exactParsedMargins as) N).mean g) ∧ + q.cost≤budget as N B := by + obtain ⟨p,hp,hpm,hpc⟩ := ExactTypedCost.prefix_correct_cost as .nil N B hB + obtain ⟨q,hq,hqm,hqc⟩ := hp.compile (weight as) (inputStacks_bound as) + have hu := hq.up + have hi := OnlineTree.cfg_packed ExactTypedProgram.program as (some default) + change upCfg (OnlineStack.cfg (OnlineTree.initial ExactTypedProgram.program (encode as) .nil))= + program.initial (Tape.mk₁ (packed as)) at hi + rw [hi] at hu + refine ⟨q,hu,(fun g => (hqm g).trans (hpm g)),?_⟩ + exact hqc.trans (Nat.mul_le_mul hpc (OnlineStack.Executes.factor_mono + (weight as) (weight as) p.cost (typedBudget as N B) le_rfl hpc)) + +lemma typedBudget_le_scaled (as : List Symbol) (N B : ℕ) : + typedBudget as N B≤typedBudget as 1 B*(N+1) := by + have hc := Nat.mul_le_mul_left (typedBudget as 0 B) (show 1≤N+1 by omega) + unfold typedBudget ExactCoreCost.budget at hc ⊢ + simp only [Nat.one_mul,Nat.zero_mul] at hc ⊢ + nlinarith + +lemma factor_le_scaled (H K V : ℕ) (hV : 1≤V) : + OnlineStack.Executes.factor ExactTypedProgram.program.code H (K*V)≤ + OnlineStack.Executes.factor ExactTypedProgram.program.code H K*V := by + let A := OnlineStack.accesses ExactTypedProgram.program.code + let O := OnlineStack.overhead ExactTypedProgram.program.code + have hH : H+1≤(H+1)*V := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (H+1) hV + have hinner : H+K*V*A+1≤(H+K*A+1)*V := by nlinarith + have hA := Nat.mul_le_mul_left (2*A) hinner + have hO : 1+2*A*(H+K*V*A+1)≤(1+2*A*(H+K*A+1))*V := by nlinarith + have hfinal := Nat.mul_le_mul_left O hO + change O*(1+2*A*(H+K*V*A+1))+1≤(O*(1+2*A*(H+K*A+1))+1)*V + nlinarith + +/-- One fixed coefficient bounds the compiler overhead for all prefix lengths. -/ +lemma quadratic_budget (as : List Symbol) (N B : ℕ) : + budget as N B≤budget as 1 B*(N+1)^2 := by + have ht := typedBudget_le_scaled as N B + have hf := OnlineStack.Executes.factor_mono (M := ExactTypedProgram.program.code) + (weight as) (weight as) (typedBudget as N B) (typedBudget as 1 B*(N+1)) le_rfl ht + have hs := factor_le_scaled (weight as) (typedBudget as 1 B) (N+1) (by omega) + calc + budget as N B≤(typedBudget as 1 B*(N+1))* + (OnlineStack.Executes.factor ExactTypedProgram.program.code (weight as) + (typedBudget as 1 B)*(N+1)) := Nat.mul_le_mul ht (hf.trans hs) + _ = budget as 1 B*(N+1)^2 := by unfold budget; ring + +end ContingencyTables.ExactPhysicalCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e5ca6a786af439b368200b786b7114ddb756b0d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPhysicalProgram.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedProgram +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPartialSequence + +namespace OAI + +/-! # Physical execution of the parsed and printed exact sampler -/ + +namespace ContingencyTables.ExactPhysicalProgram +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost +open MatchingFPRAS.TreeTyped MatchingFPRAS.TreePost Turing +open DensePrograms + +noncomputable def ofOnline (P : OnlineProc.Proc (TreeMachine.K TreeFunction.Reg)) : Program where + State := OnlineStack.Q (TreeMachine.K TreeFunction.Reg) (fun _ => Bool) + P.Label RegisterProc.Store + table := liftBool (OnlineStack.table P.code P.coin) + states := OnlineStack.states P.code + supported := liftBool_supported _ _ + (OnlineStack.table_supported P.code P.coin) + entry := OnlineStack.initialState + entry_mem := OnlineStack.initialState_mem P.code + +noncomputable def program : Program := ofOnline ExactTypedProgram.program + +attribute [local irreducible] ExactTypedProgram.program + +noncomputable def output (as : List Symbol) (o : Option MatrixCode) : Cfg Symbol program.State := + upCfg (OnlineStack.cfg (ExactTypedProgram.output as .nil o)) + +lemma output_some (as : List Symbol) (X : MatrixCode) : + output as (some X)=program.final (Tape.mk₁ (packed (GreedyFeasibleTable.printMatrix X))) := by + change upCfg (OnlineStack.cfg + (⟨none,none,inputStacks (GreedyFeasibleTable.printMatrix X)⟩ : + OnlineTree.StoreCfg ExactTypedProgram.program))=_ + exact OnlineTree.cfg_packed ExactTypedProgram.program (GreedyFeasibleTable.printMatrix X) none + +lemma output_none_live (as : List Symbol) : (output as none).state≠none := by + change (some _ : Option program.State)≠none + exact Option.some_ne_none _ + +/-- Every finite exact-sampling prefix runs on one fixed finite physical +transition table, including its live failure endpoint. -/ +theorem prefix_correct (as : List Symbol) (N : ℕ) : + ∃ q,Implements program.table (output as) + (program.initial (Tape.mk₁ (packed as))) q ∧ + ∀ g : Option MatrixCode → ℚ, + q.mean g=(ExactCoreProgram.prefixExperiment (ProfilePrograms.exactParsedMargins as) N).mean g := by + obtain ⟨p,hp,hpm⟩ := ExactTypedProgram.prefix_correct as .nil N + obtain ⟨q,hq,hqm,_⟩ := hp.compile (weight as) (inputStacks_bound as) + have hu := hq.up + have hi := OnlineTree.cfg_packed ExactTypedProgram.program as (some default) + change upCfg (OnlineStack.cfg (OnlineTree.initial ExactTypedProgram.program (encode as) .nil))= + program.initial (Tape.mk₁ (packed as)) at hi + rw [hi] at hu + exact ⟨q,hu,fun g => (hqm g).trans (hpm g)⟩ + +end ContingencyTables.ExactPhysicalProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixFeasibility.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixFeasibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7e6c195c3e1e50c6729f1394aff6460ecd209b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixFeasibility.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrefixLaw +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixLookup + +namespace OAI + +/-! # Feasibility is preserved on both branches and every finite retry prefix -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms MatchingFPRAS.PhysicalStream +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +attribute [local irreducible] exactOrdinary correctionPrefix exactMatrixInput + ExactCoreProgram.prefixExperiment scheduledTableDraw ExactIntegerOnline.trial + scheduledResidualCounts originalCandidates + +def FeasibleCode (X : MatrixCode) : Prop := ∃ T : Table r c,X=matrixCode T.val + +def FeasibleOutcome (o : Option MatrixCode) : Prop := o.elim True (FeasibleCode r c) + +lemma exactOrdinary_feasible (htotal : (∑ i,r i)=∑ j,c j) : + (exactOrdinary (List.ofFn r,List.ofFn c)).All (FeasibleCode r c) := by + rw [Experiment.all_indicator,exactOrdinary_mean r c htotal] + have he (bits : Bits (finiteSamplerBits r c (2*correctionPrecision r c))) : + (if FeasibleCode r c (matrixCode (scheduledTableDraw r c htotal + (2*correctionPrecision r c) bits).val) then (0:ℚ) else 1)=0 := + ite_eq_left ⟨_,rfl⟩ + simp_rw [he] + exact average_const _ _ + +lemma exactTrial_feasible (htotal : (∑ i,r i)=∑ j,c j) : + (ExactMatrixTrial.trial (exactMatrixInput (List.ofFn r,List.ofFn c))).All + (FeasibleOutcome r c) := by + rw [exactMatrixInput_code r c htotal,ExactMatrixTrial.trial,Experiment.all_map] + apply (Experiment.all_true _).mono + intro o _ + cases o with + | none => trivial + | some i => + exact ExactMatrixTrial.lookup_feasible r c (GreedyFeasibleTable.table r c htotal) i + +lemma correctionPrefix_feasible (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + (correctionPrefix (List.ofFn r,List.ofFn c) N).All (FeasibleOutcome r c) := by + unfold correctionPrefix + induction N with + | zero => trivial + | succ N ih => + rw [OnlineIntegerRetry.prefixExperiment,Experiment.all_bind] + apply (exactTrial_feasible r c htotal).mono + intro o ho + cases o with + | none => exact ih + | some X => exact ho + +lemma exactPrefix_feasible (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + (ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).All (FeasibleOutcome r c) := by + rw [ExactCoreProgram.prefixExperiment,Experiment.all_bind] + apply (Experiment.all_true _).mono + intro rare _ + cases rare with + | false => + rw [ite_eq_right Bool.false_ne_true,Experiment.all_map] + exact exactOrdinary_feasible r c htotal + | true => exact correctionPrefix_feasible r c htotal N + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f7071657b9ea46d114cb8e26bda4d2904a16a1b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrefixLaw.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreProgram + +namespace OAI + +/-! # The actual finite prefixes of the fixed exact-sampling program -/ + +namespace ContingencyTables.ExactCoreProgram +open MatchingFPRAS.PhysicalStream ProfilePrograms +attribute [local irreducible] rareBranch exactOrdinary correctionPrefix exactPrecision + +lemma bool_mean (p : Experiment Bool) (a b : ℚ) : + p.mean (fun x => if x then b else a)= + (1-p.mean (fun x => if x then 1 else 0))*a+ + p.mean (fun x => if x then 1 else 0)*b := by + induction p with + | done x => cases x <;> simp [Experiment.mean] + | delay n p ih => exact ih + | read p ih => + simp only [Experiment.mean,ih] + ring + +lemma prefix_mean (z : DensePrograms.CompletionMargins) (N : ℕ) + (g : Option DensePrograms.MatrixCode → ℚ) : + (prefixExperiment z N).mean g= + (1-1/(2:ℚ)^(exactPrecision z))*((exactOrdinary z).map some).mean g+ + (1/(2:ℚ)^(exactPrecision z))*(correctionPrefix z N).mean g := by + rw [prefixExperiment,Experiment.mean_bind] + have he (b : Bool) : + (if b then correctionPrefix z N else (exactOrdinary z).map some).mean g= + if b then (correctionPrefix z N).mean g else ((exactOrdinary z).map some).mean g := by + cases b <;> simp only [Bool.false_eq_true,ite_false,ite_true] + simp_rw [he] + rw [bool_mean,rareBranch_probability] + +end ContingencyTables.ExactCoreProgram + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms MatchingFPRAS MatchingFPRAS.PhysicalStream +open ResidualMixture FirstSuccess CompletionCounts +attribute [local irreducible] scheduledTableDraw exactOrdinary exactOrdinaryWord + exactSamplingParameters ExactCoreProgram.prefixExperiment correctionPrefix +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "D" => correctionPrecision r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +lemma exactOrdinary_mean (htotal : (∑ i,r i)=∑ j,c j) (g : MatrixCode → ℚ) : + (exactOrdinary (List.ofFn r,List.ofFn c)).mean g= + average (fun bits : Bits (finiteSamplerBits r c (2*D)) => + g (matrixCode (scheduledTableDraw r c htotal (2*D) bits).val)) := by + rw [exactOrdinary,FiniteWordExecution.experiment_mean,exactOrdinaryBits_ofFn] + simp_rw [exactOrdinaryWord_code r c htotal] + +lemma table_event_average {L : ℕ} (draw : Bits L → Table r c) (X : Table r c) : + average (fun bits => if matrixCode (draw bits).val=matrixCode X.val then (1:ℚ) else 0)= + (mapLaw (uniformLaw (α := Bits L)) draw).mass X := by + have he (Y : Table r c) : matrixCode Y.val=matrixCode X.val ↔ Y=X := by + constructor + · intro h + apply Subtype.ext + change List.ofFn (fun i => List.ofFn (Y.val i))=List.ofFn (fun i => List.ofFn (X.val i)) at h + funext i + exact List.ofFn_injective (congrFun (List.ofFn_injective h) i) + · rintro rfl; rfl + simp_rw [he] + simp only [average,mapLaw,uniformLaw,uniformMass,Fintype.card_fun,Fintype.card_bool, + Fintype.card_fin,Finset.sum_div] + apply Finset.sum_congr rfl + intro bits _ + split_ifs <;> simp + +lemma exactOrdinary_mass (htotal : (∑ i,r i)=∑ j,c j) (X : Table r c) : + (exactOrdinary (List.ofFn r,List.ofFn c)).mean + (fun Y => if Y=matrixCode X.val then 1 else 0)= + (mapLaw (uniformLaw (α := Bits (finiteSamplerBits r c (2*D)))) + (scheduledTableDraw r c htotal (2*D))).mass X := + (exactOrdinary_mean r c htotal _).trans (table_event_average r c _ X) + +lemma exactPrefix_failure + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + (ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=none then 1 else 0)≤(1/(2:ℚ)^D)*(1/2:ℚ)^N := by + rw [ExactCoreProgram.prefix_mean,exactPrecision_ofFn,Experiment.mean_map] + have hz : (exactOrdinary (List.ofFn r,List.ofFn c)).mean + (fun a => if some a=none then (1:ℚ) else 0)=0 := by + rw [exactOrdinary_mean r c htotal] + simp only [reduceCtorEq,ite_false,average_const] + rw [hz,mul_zero,zero_add] + exact mul_le_mul_of_nonneg_left (correctionPrefix_failure r c hPL hCheeger htotal N) + (by positivity) + +lemma exactPrefix_limit + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (X : Table r c) : + Filter.Tendsto (fun N => ((ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=some (matrixCode X.val) then 1 else 0):ℝ)) + Filter.atTop (nhds ((Fintype.card (Table r c):ℝ)⁻¹)) := by + have ht := corrected_prefix_limit r c hPL hCheeger htotal X + convert ht using 1 + funext N + rw [ExactCoreProgram.prefix_mean,exactPrecision_ofFn,Experiment.mean_map] + simp only [Option.some.injEq,exactOrdinary_mass r c htotal,Rat.cast_add,Rat.cast_mul, + Rat.cast_sub,Rat.cast_div,Rat.cast_pow,Rat.cast_one,Rat.cast_ofNat] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrintCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrintCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a3353807263a46a81503b587c03d17e53a53dc1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPrintCost.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrefixFeasibility +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram + +namespace OAI + +/-! # Uniform printing cost for every feasible exact-sampling output -/ + +namespace ContingencyTables.ExactPrintCost +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open DensePrograms SmallGraphProfiles Polynomial +open scoped BigOperators Classical +noncomputable section + +lemma weight_ofFn {A : Type} [Codec A] {n B : ℕ} (f : Fin n → A) + (h : ∀ i,weight (f i) ≤ B) : weight (List.ofFn f) ≤ n*(B+1)+1 := by + have hb := weight_map_bound (f := f) (as := List.finRange n) (fun i _ => h i) + simpa only [←List.ofFn_eq_map,List.length_finRange] using hb + +def matrixSize {m n : ℕ} (r : Fin m → ℕ) : ℕ := + m*(n*(4*weight (∑ i,r i)+2)+2)+1 + +lemma matrix_weight {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (X : Table r c) : + weight (matrixCode X.val) ≤ matrixSize (n := n) r := by + have row (i : Fin m) : weight (List.ofFn (X.val i)) ≤ n*(4*weight (∑ i,r i)+2)+1 := by + apply weight_ofFn + intro j + exact weight_nat_small (entry_le_total X.property i j) + exact weight_ofFn (fun i => List.ofFn (X.val i)) row + +/-- One fixed polynomial bounds both printing time and printed word length +uniformly over the feasible set. -/ +theorem polynomial_print_bound : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ) (X : Table r c), + GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)+ + weight (GreedyFeasibleTable.printMatrix (matrixCode X.val)) ≤ p.eval (matrixSize (n := n) r) := by + obtain ⟨p,hp⟩ := GreedyFeasibleTable.polynomial_printMatrix + exact ⟨p,fun _ _ r c X => (hp _).trans + (polynomial_eval_monotone p (matrix_weight r c X))⟩ + +lemma prefix_print_bound {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (B : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val) ≤ B) + (N : ℕ) : + (ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost ≤ B) := by + exact (exactPrefix_feasible r c htotal N).mono (by + intro o ho + cases o with + | none => exact Nat.zero_le _ + | some X => + obtain ⟨T,rfl⟩ := ho + exact hB T) + +end +end ContingencyTables.ExactPrintCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..43e313f8d5e47af27e087e448f4513ac62431874 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicCost.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicPrefix +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalCost +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrintCost + +namespace OAI + +/-! # Cost-preserving literal wrapping of exact-sampling prefixes -/ + +namespace ContingencyTables.ExactPublicCost +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open DensePrograms +open scoped Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +def middleOutput (out : Option (Table r c) → Cfg Symbol ExactPhysicalProgram.program.State) : + Option (Table r c) → Cfg Symbol ExactPublicPrefix.middle.State + | none => leftCfg LiteralProgram.post.entry (out none) + | some X => rightCfg (LiteralProgram.post.final (Tape.mk₁ (ExactPublicPrefix.word r c X))) + +def output (out : Option (Table r c) → Cfg Symbol ExactPhysicalProgram.program.State) + (o : Option (Table r c)) : Cfg Symbol ExactPublicPrefix.program.State := + rightCfg (middleOutput r c out o) + +theorem wrap_prefix (out : Option (Table r c) → Cfg Symbol ExactPhysicalProgram.program.State) + (hinj : Function.Injective out) + (hout : ∀ X,out (some X)=ExactPhysicalProgram.program.final + (Tape.mk₁ (TreePost.packed (ExactPublicPrefix.word r c X)))) + (L : ℕ) (hL : ∀ X,(ExactPublicPrefix.word r c X).length≤L) + (p : Experiment (Option (Table r c))) + (hp : Implements ExactPhysicalProgram.program.table out + (ExactPhysicalProgram.program.initial (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) p) : + ∃ q,Implements ExactPublicPrefix.program.table (output r c out) + (ExactPublicPrefix.program.initial (Tape.mk₁ (ExactTablePrefix.input r c))) q ∧ + (∀ g : Option (Table r c) → ℚ,q.mean g=p.mean g) ∧ + q.cost≤LiteralProgram.packTime (ExactTablePrefix.input r c).length+p.cost+LiteralProgram.postTime L := by + obtain ⟨v,hv,hvm,hvc⟩ := PhysicalPartialSequence.left_prefix_injective + ExactPhysicalProgram.program.table LiteralProgram.post.table LiteralProgram.post.entry out hinj _ p hp + have next (o : Option (Table r c)) : ∃ u, + Implements ExactPublicPrefix.middle.table (middleOutput r c out) + (leftCfg LiteralProgram.post.entry (out o)) u ∧ + (∀ g : Option (Table r c) → ℚ,u.mean g=g o) ∧ u.cost≤LiteralProgram.postTime L := by + cases o with + | none => exact ⟨.done none,.done none,(fun _ => rfl),Nat.zero_le _⟩ + | some X => + obtain ⟨u,hu,hum,huc⟩ := LiteralProgram.post_realizes (ExactPublicPrefix.word r c X) + (ProfilePrograms.printMatrix_alphabet _) + have hu' := hu.right (M := ExactPhysicalProgram.program.table) LiteralProgram.post.entry + have hall : u.All (fun T => T=Tape.mk₁ (ExactPublicPrefix.word r c X)) := + Experiment.all_of_mean_eq hum _ rfl + refine ⟨u.map (fun _ => some X),?_,?_,?_⟩ + · have h := hu'.map_all (fun _ => some X) (middleOutput r c out) + (hall.mono (by intro T hT; rw [hT]; rfl)) + rw [hout] + simpa only [ExactPublicPrefix.middle,Program.seq,leftCfg,Program.final,Program.initial, + Option.elim_none,rightCfg,Option.map_some] using h + · intro g + rw [Experiment.mean_map,PhysicalPartialSequence.mean_const] + · rw [Experiment.cost_map] + exact huc.trans (LiteralProgram.postTime_mono (hL X)) + choose u hu hum huc using next + let w := v.bind u + have hw : Implements ExactPublicPrefix.middle.table (middleOutput r c out) + (ExactPublicPrefix.middle.initial (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) w := + hv.bind u _ hu + have hwm (g : Option (Table r c) → ℚ) : w.mean g=p.mean g := by + change (v.bind u).mean g=p.mean g + rw [Experiment.mean_bind] + simp_rw [hum] + exact hvm g + have hwc : w.cost≤p.cost+LiteralProgram.postTime L := + (Experiment.cost_bind_le v u _ huc).trans (Nat.add_le_add_right hvc _) + have hi : ∀ a∈ExactTablePrefix.input r c,a≠0 := + GreedyFeasibleTable.encodeMargins_nonzero r c + obtain ⟨a,ha,ham,hac⟩ := LiteralProgram.pack_realizes (ExactTablePrefix.input r c) hi + obtain ⟨b,hb,hbm,hbc⟩ := PhysicalPartialSequence.left_prefix LiteralProgram.pack.table + ExactPublicPrefix.middle.table ExactPublicPrefix.middle.entry LiteralProgram.pack.final _ a ha + have hall : b.All (fun x => x=LiteralProgram.pack.final + (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) := by + rw [Experiment.all_indicator,hbm,ham] + simp only [Experiment.mean,ite_true] + have hw' := hw.right (M := LiteralProgram.pack.table) ExactPublicPrefix.middle.entry + refine ⟨b.bind (fun _ => w),?_,?_,?_⟩ + · apply hb.bind_all (fun _ => w) (output r c out) + exact hall.mono (by intro x hx; rw [hx]; exact hw') + · intro g + rw [Experiment.mean_bind,PhysicalPartialSequence.mean_const] + exact hwm g + · have h := Experiment.cost_bind_le b (fun _ => w) w.cost (fun _ => le_rfl) + omega + +/-- Table decoding preserves the finite-prefix work bound. -/ +theorem table_prefix (htotal : (∑ i,r i)=∑ j,c j) (N B : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) : + ∃ p,Implements ExactPhysicalProgram.program.table (ExactTablePrefix.output r c) + (ExactPhysicalProgram.program.initial (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) p ∧ + (∀ g : Option (Table r c) → ℚ,p.mean g=(ExactTablePrefix.experiment r c N).mean g) ∧ + p.cost≤ExactPhysicalCost.budget (ExactTablePrefix.input r c) N B := by + have hprint : (ExactCoreProgram.prefixExperiment + (ProfilePrograms.exactParsedMargins (ExactTablePrefix.input r c)) N).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B) := by + rw [show ProfilePrograms.exactParsedMargins (ExactTablePrefix.input r c)= + (List.ofFn r,List.ofFn c) from SmallGraphProfiles.exactParsedMargins_spec r c] + exact ExactPrintCost.prefix_print_bound r c htotal B hB N + obtain ⟨p,hp,hpm,hpc⟩ := ExactPhysicalCost.prefix_correct_cost (ExactTablePrefix.input r c) N B hprint + have hm (g : Option MatrixCode → ℚ) : + p.mean g=(ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean g := by + simpa only [ExactTablePrefix.input,SmallGraphProfiles.exactParsedMargins_spec] using hpm g + have hall : p.All (SmallGraphProfiles.FeasibleOutcome r c) := + Experiment.all_of_mean_eq hm _ (SmallGraphProfiles.exactPrefix_feasible r c htotal N) + refine ⟨p.map (ExactTablePrefix.decode r c),hp.map_all (ExactTablePrefix.decode r c) + (ExactTablePrefix.output r c) (hall.mono (by + intro o ho + unfold ExactTablePrefix.output + rw [ExactTablePrefix.code_decode r c ho])),?_,?_⟩ + · intro g + rw [Experiment.mean_map,hm,ExactTablePrefix.experiment,Experiment.mean_map] + · simpa only [Experiment.cost_map] using hpc + +noncomputable def budget (N B L : ℕ) : ℕ := + LiteralProgram.packTime (ExactTablePrefix.input r c).length+ + ExactPhysicalCost.budget (ExactTablePrefix.input r c) N B+LiteralProgram.postTime L + +theorem prefix_correct_cost (htotal : (∑ i,r i)=∑ j,c j) (N B L : ℕ) + (hB : ∀ X : Table r c,GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val)≤B) + (hL : ∀ X : Table r c,(ExactPublicPrefix.word r c X).length≤L) : + ∃ p,Implements ExactPublicPrefix.program.table (ExactPublicPrefix.output r c) + (ExactPublicPrefix.program.initial (Tape.mk₁ (ExactTablePrefix.input r c))) p ∧ + (∀ g : Option (Table r c) → ℚ,p.mean g=(ExactTablePrefix.experiment r c N).mean g) ∧ + p.cost≤budget r c N B L := by + obtain ⟨p,hp,hm,hc⟩ := table_prefix r c htotal N B hB + have hout (X : Table r c) : ExactTablePrefix.output r c (some X)= + ExactPhysicalProgram.program.final + (Tape.mk₁ (TreePost.packed (ExactPublicPrefix.word r c X))) := by + exact ExactPhysicalProgram.output_some _ _ + obtain ⟨q,hq,hqm,hqc⟩ := wrap_prefix r c (ExactTablePrefix.output r c) + (ExactTablePrefix.output_injective r c) hout L hL p hp + refine ⟨q,hq,(fun g => (hqm g).trans (hm g)),?_⟩ + exact hqc.trans (by unfold budget; omega) + +lemma quadratic_budget (N B L : ℕ) : + budget r c N B L≤budget r c 1 B L*(N+1)^2 := by + have hp := ExactPhysicalCost.quadratic_budget (ExactTablePrefix.input r c) N B + have hsq : 1≤(N+1)^2 := Nat.one_le_pow _ _ (by omega) + have hc := Nat.mul_le_mul_left (LiteralProgram.packTime (ExactTablePrefix.input r c).length+ + LiteralProgram.postTime L) hsq + unfold budget + nlinarith + +end +end ContingencyTables.ExactPublicCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dc7e52b49fc3fcf901838c8427fa5339c170934 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicLaw.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicPrefix +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPublicLaw + +namespace OAI + +/-! # Exact public output law and almost-sure termination -/ + +namespace ContingencyTables.ExactPublicLaw +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open PhysicalEventBounds PhysicalPublicLaw ExactPublicPrefix SmallGraphProfiles +open scoped BigOperators Classical +noncomputable section +attribute [local irreducible] ExactPublicPrefix.program ExactPublicPrefix.output + ExactTablePrefix.experiment correctionPrecision + PublishedInputs.FiniteBoxPrekopaLeindler PublishedInputs.FiniteCheeger + CompletionCounts.dimensionAllowance + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => CompletionCounts.dimensionAllowance (I := Fin m) (J := Fin n) + +def prefixError (N : ℕ) : ℝ := + (1/(2:ℝ)^(correctionPrecision r c))*(1/2:ℝ)^N + +lemma error_limit : Filter.Tendsto (prefixError r c) Filter.atTop (nhds 0) := by + have h := (tendsto_pow_atTop_nhds_zero_of_lt_one (by norm_num : (0:ℝ)≤1/2) + (by norm_num : (1/2:ℝ)<1)).const_mul (1/(2:ℝ)^correctionPrecision r c) + change Filter.Tendsto (fun N => (1/(2:ℝ)^(correctionPrecision r c))*(1/2:ℝ)^N) _ _ + simpa only [mul_zero] using h + +lemma event_output (X Y : Table r c) : + outputs (Algorithms.encodeMatrix X.val) (output r c (some Y)) ↔ Y=X := by + simp only [outputs,output_halted,output_tape,true_and] + constructor + · intro h + exact Subtype.ext (Algorithms.blankMatrix_injective _ _ h) + · rintro rfl; rfl + +section Conditional +variable + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin q) (4*k^8))) + (htotal : (∑ i,r i)=∑ j,c j) +include hPL hCheeger htotal + +lemma prefix_error (N : ℕ) : + ((ExactTablePrefix.experiment r c N).mean (fun o => if o=none then 1 else 0):ℝ)≤prefixError r c N := by + have h := ExactTablePrefix.failure_bound r c (hPL _) (hCheeger _ d) htotal N + have hR := (Rat.cast_le (K := ℝ)).mpr h + simpa only [prefixError,Rat.cast_mul,Rat.cast_div,Rat.cast_pow,Rat.cast_one,Rat.cast_ofNat] using hR + +theorem tableMass_limit (X : Table r c) : + Filter.Tendsto (fun t => Algorithms.tableMass machine (Algorithms.encodeMargins r c) t X.val) + Filter.atTop (nhds ((Fintype.card (Table r c):ℝ)⁻¹)) := by + apply tendsto_of_prefix_bounds _ + (fun N => ((ExactTablePrefix.experiment r c N).mean (fun o => if o=some X then 1 else 0):ℝ)) + (prefixError r c) _ (ExactTablePrefix.point_limit r c (hPL _) (hCheeger _ d) htotal X) (error_limit r c) + intro N + obtain ⟨p,hp,hm⟩ := prefix_correct r c htotal N + refine ⟨p.cost,?_⟩ + intro t ht + have h := stopped_event_bounds program.table (output r c) + (program.initial (Tape.mk₁ (ExactTablePrefix.input r c))) p hp + (output_halted r c) (outputs (Algorithms.encodeMatrix X.val)) t ht + have he : (fun o : Option (Table r c) => o.elim 0 + (fun Y => event (outputs (Algorithms.encodeMatrix X.val)) (output r c (some Y))))= + (fun o => if o=some X then 1 else 0) := by + funext o + cases o with + | none => simp + | some Y => simp only [Option.elim_some,event,event_output,Option.some.injEq] + rw [he,hm,hm] at h + have hl : ((ExactTablePrefix.experiment r c N).mean + (fun o => if o=some X then 1 else 0):ℝ)≤ + ((experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean + (event (outputs (Algorithms.encodeMatrix X.val))):ℝ) := by exact_mod_cast h.1 + have hu : ((experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean + (event (outputs (Algorithms.encodeMatrix X.val))):ℝ)≤ + ((ExactTablePrefix.experiment r c N).mean (fun o => if o=some X then 1 else 0):ℝ)+ + ((ExactTablePrefix.experiment r c N).mean (fun o => if o=none then 1 else 0):ℝ) := by + exact_mod_cast h.2 + have hm : Algorithms.tableMass machine (Algorithms.encodeMargins r c) t X.val= + ((experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean + (event (outputs (Algorithms.encodeMatrix X.val))):ℝ) := tableMass_eq program _ t X.val + exact ⟨hl.trans_eq hm.symm,hm.le.trans + (hu.trans (add_le_add le_rfl (prefix_error r c hPL hCheeger htotal N)))⟩ + +theorem tail_limit : + Filter.Tendsto (PhysicalRetryTail.tail program.table + (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))) Filter.atTop (nhds 0) := by + apply tendsto_of_prefix_bounds _ (fun _ => 0) (prefixError r c) 0 tendsto_const_nhds (error_limit r c) + intro N + obtain ⟨p,hp,hm⟩ := prefix_correct r c htotal N + refine ⟨p.cost,?_⟩ + intro t ht + have h := PhysicalRetryTail.tail_le_failure program.table (output r c) _ p hp + (output_halted r c) t ht + rw [hm] at h + exact ⟨PhysicalRetryTail.tail_nonnegative _ _ _, + (h.trans (prefix_error r c hPL hCheeger htotal N)).trans_eq (zero_add _).symm⟩ + +theorem haltMass_limit : + Filter.Tendsto (Algorithms.haltMass machine (Algorithms.encodeMargins r c)) + Filter.atTop (nhds 1) := by + have h := (tail_limit r c hPL hCheeger htotal).const_sub 1 + have he : (fun t => 1-PhysicalRetryTail.tail program.table + (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c))) t)= + Algorithms.haltMass machine (Algorithms.encodeMargins r c) := by + funext t + rw [←tail_eq] + change 1-(1-Algorithms.haltMass program.machine (Algorithms.encodeMargins r c) t)= + Algorithms.haltMass program.machine (Algorithms.encodeMargins r c) t + ring + simpa only [he,sub_zero] using h + +/-- Every finite halted public execution is feasible, including events of +arbitrarily small positive probability. -/ +theorem halted_feasible (t : ℕ) (bits : Bits t) + (hh : (MatchingFPRAS.run machine (Algorithms.encodeMargins r c) bits).state=none) : + ∃ X : Table r c,Algorithms.OutputsTable machine (Algorithms.encodeMargins r c) bits X.val := by + let bad : Cfg Symbol program.State → Prop := fun cfg => cfg.state=none ∧ + ¬∃ X : Table r c,cfg.tape.right₀=ListBlank.mk (Algorithms.encodeMatrix X.val) + have hb (N : ℕ) : + ((experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean + (event bad):ℝ)≤prefixError r c N := by + obtain ⟨p,hp,hm⟩ := prefix_correct r c htotal N + have h := absent_event_bound program.table (output r c) _ p hp (output_halted r c) bad + (fun cfg hd => hd.1) (by intro X hX; exact hX.2 ⟨X,output_tape r c X⟩) t + rw [hm] at h + exact (show ((experiment program.table t (program.initial + (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean (event bad):ℝ)≤ + ((ExactTablePrefix.experiment r c N).mean (fun o => if o=none then 1 else 0):ℝ) by + exact_mod_cast h).trans (prefix_error r c hPL hCheeger htotal N) + have hzR := ge_of_tendsto' (error_limit r c) hb + have hz : (experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean + (event bad)=0 := by + have hnonneg := (experiment program.table t (program.initial (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean_nonneg + (event bad) ((Experiment.all_true _).mono (fun cfg _ => event_nonneg bad cfg)) + exact le_antisymm (by exact_mod_cast hzR) hnonneg + have hall : (experiment program.table t (program.initial + (Tape.mk₁ (Algorithms.encodeMargins r c)))).All (fun cfg => ¬bad cfg) := by + rw [Experiment.all_indicator] + change (experiment program.table t (program.initial + (Tape.mk₁ (Algorithms.encodeMargins r c)))).mean (fun cfg => if ¬bad cfg then 0 else 1)=0 + have he : (fun cfg : Cfg Symbol program.State => if ¬bad cfg then (0:ℚ) else 1)=event bad := by + funext cfg + by_cases hb : bad cfg <;> simp [event,hb] + rw [he] + exact hz + have hn := Experiment.all_run _ _ hall (extend bits) + rw [experiment_run] at hn + have hh' := (run_halted_iff program (Algorithms.encodeMargins r c) t bits).mp hh + have hout : ∃ X : Table r c,(execute program.table t (program.initial + (Tape.mk₁ (Algorithms.encodeMargins r c))) (extend bits)).tape.right₀= + ListBlank.mk (Algorithms.encodeMatrix X.val) := by + by_contra h + exact hn ⟨hh',h⟩ + obtain ⟨X,hX⟩ := hout + exact ⟨X,hh,(congrArg Tape.right₀ (Program.run_tape program _ t bits)).trans hX⟩ + +end Conditional +end +end ContingencyTables.ExactPublicLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicPrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cbbc048cbc6f9f7412a4986c2f10082a3d1fb9e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactPublicPrefix.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactTablePrefix + +namespace OAI + +/-! # The fixed exact-sampling machine on the literal public binary tape -/ + +namespace ContingencyTables.ExactPublicPrefix +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open DensePrograms +open scoped Classical +noncomputable section + +/-- These two finite programs are independent of dimensions and margins. -/ +def middle : Program := ExactPhysicalProgram.program.seq LiteralProgram.post +def program : Program := LiteralProgram.pack.seq middle + +def machine : RandomMachine := program.machine + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +def word (X : Table r c) : List Symbol := GreedyFeasibleTable.printMatrix (matrixCode X.val) + +lemma word_eq (X : Table r c) : word r c X=Algorithms.encodeMatrix X.val := + GreedyFeasibleTable.printMatrix_ofFn X.val + +def middleOutput : Option (Table r c) → Cfg Symbol middle.State + | none => leftCfg LiteralProgram.post.entry (ExactTablePrefix.output r c none) + | some X => rightCfg (LiteralProgram.post.final (Tape.mk₁ (word r c X))) + +def output (o : Option (Table r c)) : Cfg Symbol program.State := rightCfg (middleOutput r c o) + +lemma middle_prefix (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + ∃ p,Implements middle.table (middleOutput r c) + (middle.initial (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) p ∧ + ∀ g : Option (Table r c) → ℚ,p.mean g=(ExactTablePrefix.experiment r c N).mean g := by + obtain ⟨p,hp,hpm⟩ := ExactTablePrefix.physical_prefix r c htotal N + obtain ⟨q,hq,hqm,_⟩ := PhysicalPartialSequence.left_prefix_injective + ExactPhysicalProgram.program.table LiteralProgram.post.table LiteralProgram.post.entry + (ExactTablePrefix.output r c) (ExactTablePrefix.output_injective r c) _ p hp + have next (o : Option (Table r c)) : ∃ u, + Implements middle.table (middleOutput r c) + (leftCfg LiteralProgram.post.entry (ExactTablePrefix.output r c o)) u ∧ + ∀ g : Option (Table r c) → ℚ,u.mean g=g o := by + cases o with + | none => exact ⟨.done none,.done none,fun _ => rfl⟩ + | some X => + obtain ⟨u,hu,hum,_⟩ := LiteralProgram.post_realizes (word r c X) + (ProfilePrograms.printMatrix_alphabet _) + have hu' := hu.right (M := ExactPhysicalProgram.program.table) LiteralProgram.post.entry + have hall : u.All (fun T => T=Tape.mk₁ (word r c X)) := + Experiment.all_of_mean_eq hum _ rfl + refine ⟨u.map (fun _ => some X),?_,?_⟩ + · have hv := hu'.map_all (fun _ => some X) (middleOutput r c) + (hall.mono (by intro T hT; rw [hT]; rfl)) + simpa only [middle,Program.seq,ExactTablePrefix.output,ExactTablePrefix.code,Option.map_some, + ExactPhysicalProgram.output_some,word,leftCfg,Program.final,Program.initial, + Option.elim_none,rightCfg,Option.map_some] using hv + · intro g + rw [Experiment.mean_map,PhysicalPartialSequence.mean_const] + choose u hu hum using next + refine ⟨q.bind u,hq.bind u _ hu,?_⟩ + intro g + rw [Experiment.mean_bind] + simp_rw [hum] + exact (hqm g).trans (hpm g) + +theorem prefix_correct (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + ∃ p,Implements program.table (output r c) + (program.initial (Tape.mk₁ (ExactTablePrefix.input r c))) p ∧ + ∀ g : Option (Table r c) → ℚ,p.mean g=(ExactTablePrefix.experiment r c N).mean g := by + obtain ⟨p,hp,hpm⟩ := middle_prefix r c htotal N + have hi : ∀ a∈ExactTablePrefix.input r c,a≠0 := by + intro a ha + exact GreedyFeasibleTable.encodeMargins_nonzero r c a ha + obtain ⟨u,hu,hum,_⟩ := LiteralProgram.pack_realizes (ExactTablePrefix.input r c) hi + obtain ⟨v,hv,hvm,_⟩ := PhysicalPartialSequence.left_prefix LiteralProgram.pack.table middle.table + middle.entry LiteralProgram.pack.final _ u hu + have hall : v.All (fun x => x=LiteralProgram.pack.final + (Tape.mk₁ (TreePost.packed (ExactTablePrefix.input r c)))) := by + rw [Experiment.all_indicator,hvm,hum] + simp only [Experiment.mean,ite_true] + have hp' := hp.right (M := LiteralProgram.pack.table) middle.entry + refine ⟨v.bind (fun _ => p),?_,?_⟩ + · apply hv.bind_all (fun _ => p) (output r c) + exact hall.mono (by intro x hx; rw [hx]; exact hp') + · intro g + rw [Experiment.mean_bind,PhysicalPartialSequence.mean_const] + exact hpm g + +lemma output_none_live : (output r c none).state≠none := by + change (some _ : Option program.State)≠none + exact Option.some_ne_none _ + +lemma output_halted (X : Table r c) : (output r c (some X)).state=none := rfl + +lemma output_tape (X : Table r c) : + (output r c (some X)).tape.right₀=ListBlank.mk (Algorithms.encodeMatrix X.val) := by + change (Tape.mk₁ (word r c X)).right₀=_ + rw [word_eq] + simp only [Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + +end +end ContingencyTables.ExactPublicPrefix + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc0ad2b5d46b1e9f5982aa478ae73c8a9a209dec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareCost.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePolynomial + +namespace OAI + +/-! # Polynomial dependence of the correction cost on its finite tabulation measure -/ + +namespace ContingencyTables.ExactRareCost +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open ProfilePrograms DensePrograms Polynomial +noncomputable section + +attribute [local irreducible] ExactTypedProgram.program exactParsedMargins + ExactGateCost.measure exactRareMeasure exactMatrixInput + +def measure (z : CompletionMargins) : ℕ := ExactGateCost.measure z+exactRareMeasure z + +theorem core_polynomial : ∃ p : Polynomial ℕ,∀ z, + ExactCoreCost.budget z 1 ≤ p.eval (measure z) := by + obtain ⟨g,hg⟩ := ExactGateCost.budget_polynomial + obtain ⟨p,hp⟩ := work_exactMatrixInput + obtain ⟨q,hq⟩ := ExactMatrixTrial.polynomial_trial + refine ⟨g+p+q.comp p+12*p+C (weight (default : MatrixCode)+40),?_⟩ + intro z + have hgate : ExactGatePrefix.budget z ≤ g.eval (measure z) := + (hg z).trans (polynomial_eval_monotone g (Nat.le_add_right _ _)) + have hmatrix : exactMatrixInputRealizer.cost z+weight (exactMatrixInput z) ≤ p.eval (measure z) := + (hp z).trans (polynomial_eval_monotone p (Nat.le_add_left _ _)) + have hw : weight (exactMatrixInput z) ≤ p.eval (measure z) := + (Nat.le_add_left _ _).trans hmatrix + have htrial := (Nat.le_add_right _ _).trans + ((hq (exactMatrixInput z)).trans (polynomial_eval_monotone q hw)) + change ExactMatrixTrial.trialRealizer.cost (exactMatrixInput z) ≤ q.eval (p.eval (measure z)) at htrial + change rareBranchRealizer.cost z+exactOrdinaryRealizer.cost z+exactMatrixInputRealizer.cost z+ + 1*(ExactMatrixTrial.trialRealizer.cost (exactMatrixInput z)+12*weight (exactMatrixInput z)+ + weight (default : MatrixCode)+40)+10*weight z+50 ≤ _ + change rareBranchRealizer.cost z+exactOrdinaryRealizer.cost z+10*weight z+50 ≤ _ at hgate + simp only [eval_add,eval_mul,eval_ofNat,eval_C,eval_comp] + omega + +def publicMeasure (as : List Symbol) (B : ℕ) : ℕ := + weight as+measure (exactParsedMargins as)+B + +/-- All copying and physical simulation costs are polynomial in the +already explicit finite-tabulation measure. -/ +theorem public_polynomial : ∃ p : Polynomial ℕ,∀ as B, + LiteralProgram.packTime as.length+ExactPhysicalCost.budget as 1 B+ + LiteralProgram.postTime B+1 ≤ p.eval (publicMeasure as B) := by + obtain ⟨p,hp⟩ := polynomial_exactParsedMargins + obtain ⟨q,hq⟩ := core_polynomial + let t : Polynomial ℕ := p+q+X + obtain ⟨v,hv⟩ := PhysicalCostPolynomial.bound + (OnlineStack.accesses ExactTypedProgram.program.code) + (OnlineStack.overhead ExactTypedProgram.program.code) t + refine ⟨v+1,?_⟩ + intro as B + let M := publicMeasure as B + have hw : weight as ≤ M := by unfold M publicMeasure; omega + have hg : measure (exactParsedMargins as) ≤ M := by unfold M publicMeasure; omega + have hB : B ≤ M := by unfold M publicMeasure; omega + have ht : ExactPhysicalCost.typedBudget as 1 B ≤ t.eval M := by + have hp' := (Nat.le_add_right _ _).trans ((hp as).trans (polynomial_eval_monotone p hw)) + have hq' := (hq _).trans (polynomial_eval_monotone q hg) + simpa only [ExactPhysicalCost.typedBudget,t,eval_add,eval_X] using + Nat.add_le_add (Nat.add_le_add hp' hq') hB + have hb := hv (weight as) (ExactPhysicalCost.typedBudget as 1 B) as.length B M hw ht + ((list_length_le_weight as).trans hw) hB + simpa only [ExactPhysicalCost.budget,OnlineStack.Executes.factor,eval_add,eval_one] + using Nat.add_le_add_right hb 1 + +end +end ContingencyTables.ExactRareCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareMeasureBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareMeasureBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..e73e7a711991eb26467d73a101551c9bf401b721 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRareMeasureBound.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactEntryBoxBound +import OAI.Combinatorics.ContingencyTables.Sampling.ExactResidualInput + +namespace OAI + +/-! # A single exponential scale for the executed rare-branch measure -/ + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms CompletionCounts Polynomial +open scoped BigOperators Classical +noncomputable section + +lemma originalEnumeration_scale {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + gridStateCount (originalEnumerationData (List.ofFn r,List.ofFn c)) ≤ exactBoxScale r c := by + apply (originalEnumeration_count_bound r c).trans + have hd : 1 ≤ dimensionAllowance (I := Fin m) (J := Fin n) := by unfold dimensionAllowance; omega + have hp := Nat.le_self_pow (by decide : 3 ≠ 0) (dimensionAllowance (I := Fin m) (J := Fin n)) + apply Nat.pow_le_pow_right (by decide) + nlinarith + +lemma initialProfile_scale {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) : + gridStateCount (profileEnumerationData (initialCheck (List.ofFn r,List.ofFn c))) ≤ exactBoxScale r c := by + rw [initialCheck_code r c htotal] + apply (profileEnumeration_count_bound r c _ _).trans + have hp := Nat.le_self_pow (by decide : 3 ≠ 0) (dimensionAllowance (I := Fin m) (J := Fin n)) + apply Nat.pow_le_pow_right (by decide) + nlinarith + +theorem exact_rare_measure_bound : ∃ p a : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), (∑ i,r i)=∑ j,c j → + exactRareMeasure (List.ofFn r,List.ofFn c) ≤ + p.eval (a.eval (Algorithms.samplingSize n r 0)*exactBoxScale r c) := by + obtain ⟨a,ha⟩ := exact_count_input_measure_polynomial + obtain ⟨b,hb⟩ := tabulation_preparation_polynomial + obtain ⟨c,hc⟩ := exact_entry_box_bound + obtain ⟨d,hd⟩ := exact_parameter_polynomial + obtain ⟨e,he⟩ := work_exactResidualInput + obtain ⟨q,hq⟩ := matrixEntryMeasure_polynomial + let base : Polynomial ℕ := a+b.comp a+c+d+e.comp d+1 + let Q : Polynomial ℕ := q+X + refine ⟨8*X+2*vectorMeasurePolynomial.comp Q,base,?_⟩ + intro m n r cols htotal + let z := exactSamplingParameters (List.ofFn r,List.ofFn cols) + let E := exactBoxScale r cols + let S := Algorithms.samplingSize n r 0 + let W := base.eval S*E + let M := Q.eval W + have hE : 1 ≤ E := exactBoxScale_pos r cols + have hbase : 1 ≤ base.eval S := by simp only [base,eval_add,eval_one]; omega + have hEW : E ≤ W := by simpa only [Nat.one_mul] using Nat.mul_le_mul_right E hbase + have hbaseW : base.eval S ≤ W := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (base.eval S) hE + have hWM : W ≤ M := by unfold M Q; simp only [eval_add,eval_X]; omega + have haW : a.eval S ≤ W := (by simp only [base,eval_add,eval_one]; omega : a.eval S ≤ base.eval S).trans hbaseW + have hbW : (b.comp a).eval S ≤ W := + (by simp only [base,eval_add,eval_one]; omega : (b.comp a).eval S ≤ base.eval S).trans hbaseW + have hcW : c.eval S*E ≤ W := Nat.mul_le_mul_right E (by simp only [base,eval_add,eval_one]; omega) + have hdW : d.eval S ≤ W := (by simp only [base,eval_add,eval_one]; omega : d.eval S ≤ base.eval S).trans hbaseW + have heW : (e.comp d).eval S ≤ W := + (by simp only [base,eval_add,eval_one]; omega : (e.comp d).eval S ≤ base.eval S).trans hbaseW + have hcount : scheduledCountInputMeasure z ≤ W := (ha m n r cols htotal).trans haW + have hparam : exactParameterMeasure (List.ofFn r,List.ofFn cols) ≤ W := (hd m n r cols htotal).trans hdW + have hres : weight (exactResidualInput (List.ofFn r,List.ofFn cols)) ≤ W := by + have ht : weight (exactResidualInput (List.ofFn r,List.ofFn cols)) ≤ + e.eval (d.eval S) := + (Nat.le_add_left _ _).trans ((he _).trans (polynomial_eval_monotone e (hd m n r cols htotal))) + exact ht.trans (by simpa only [eval_comp] using heW) + have hz : weight (List.ofFn r,List.ofFn cols) ≤ W := by + have hz' : weight z ≤ scheduledCountInputMeasure z := by + simpa only [eval_X] using weight_le_scheduledCountInputMeasure z + exact ((weight_fst z).trans hz').trans hcount + have hprep := hb z + have hprep_bound : b.eval (scheduledCountInputMeasure z) ≤ W := + (polynomial_eval_monotone b (ha m n r cols htotal)).trans (by simpa only [eval_comp] using hbW) + have houter : weight (scheduledOuterInput z) ≤ M := (hprep.1.trans hprep_bound).trans hWM + have hN : gridStateCount (profileEnumerationData (initialCheck (List.ofFn r,List.ofFn cols))) ≤ M := + (initialProfile_scale r cols htotal).trans (hEW.trans hWM) + have hO : gridStateCount (originalEnumerationData (List.ofFn r,List.ofFn cols)) ≤ W := + (originalEnumeration_scale r cols).trans hEW + have hv : ∀ v∈profileBoxViews (initialCheck (List.ofFn r,List.ofFn cols)),weight v ≤ M := by + intro v hv + exact ((hprep.2.2.1 v hv).trans hprep_bound).trans hWM + have ho : ∀ o∈originalCandidates (List.ofFn r,List.ofFn cols),weight o ≤ M ∧ weight (o.getD []) ≤ M := by + intro o ho + exact ⟨((hprep.2.2.2.1 o ho).1.trans hprep_bound).trans hWM, + ((hprep.2.2.2.1 o ho).2.trans hprep_bound).trans hWM⟩ + have hentry : ∀ u∈profileBoxViews (initialCheck (List.ofFn r,List.ofFn cols)), + ∀ v∈profileBoxViews (initialCheck (List.ofFn r,List.ofFn cols)), + matrixEntryMeasure (scheduledMatrixParameters z,(u,v)) ≤ M := by + intro u hu v hv + have hx := (hc m n r cols htotal u hu v hv).trans hcW + have ht := (hq (scheduledMatrixParameters z,(u,v))).trans (polynomial_eval_monotone q hx) + apply ht.trans + unfold M Q + simp only [eval_add,eval_X] + omega + have hsteps : parameterSteps z ≤ M := by + have hs : parameterSteps z ≤ scheduledCountInputMeasure z := by unfold scheduledCountInputMeasure; omega + exact hs.trans (hcount.trans hWM) + have hvector : outerVectorMeasure (scheduledOuterInput z) ≤ vectorMeasurePolynomial.eval M := + outerVectorMeasure_bound _ M houter hsteps (hO.trans hWM) hN hv ho hentry + have hunit := (unit_outerVectorMeasure_le (scheduledOuterInput z)).trans hvector + have hen : originalEnumerationMeasure (List.ofFn r,List.ofFn cols) ≤ 2*W := by + unfold originalEnumerationMeasure + omega + change _ ≤ (8*X+2*vectorMeasurePolynomial.comp Q).eval W + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_comp] + change exactParameterMeasure (List.ofFn r,List.ofFn cols)+ + (scheduledCountInputMeasure z+outerVectorMeasure (scheduledOuterInput z)+ + UnitCountPrograms.outerVectorMeasure (scheduledOuterInput z)+ + originalEnumerationMeasure (List.ofFn r,List.ofFn cols)+ + weight (exactResidualInput (List.ofFn r,List.ofFn cols)))+ + originalEnumerationMeasure (List.ofFn r,List.ofFn cols)+weight (List.ofFn r,List.ofFn cols) ≤ _ + change _ ≤ 8*W+2*vectorMeasurePolynomial.eval M + omega + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRarePublicBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRarePublicBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..16e9a5231e487dbfeaaf1e7428455c763c832432 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactRarePublicBound.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactRareMeasureBound +import OAI.Combinatorics.ContingencyTables.Sampling.ExactRareCost + +namespace OAI + +/-! # Absorbing the actual public correction cost by its branch probability -/ + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms CompletionCounts Polynomial +open scoped BigOperators Classical +noncomputable section + +lemma exact_scale_absorbed {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (p : Polynomial ℕ) (A : ℕ) : + p.eval (A*exactBoxScale r c) ≤ 2^(correctionPrecision r c)* + (p.eval A*2^((40*p.natDegree)^2)) := by + apply RareBranchRuntime.polynomial_tabulation_bound + change ((dimensionAllowance (I := Fin m) (J := Fin n))^3*smallBinaryLength r c)^2 ≤ + (dimensionAllowance (I := Fin m) (J := Fin n))^6*(smallBinaryLength r c)^2 + rw [mul_pow,←pow_mul] + +theorem exact_public_correction_bound (print : Polynomial ℕ) : ∃ p : Polynomial ℕ, + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), (∑ i,r i)=∑ j,c j → + let B := print.eval (ExactPrintCost.matrixSize (n := n) r) + ExactPublicCost.budget r c 1 B B+1 ≤ + 2^(correctionPrecision r c)*p.eval (Algorithms.samplingSize n r 0) := by + obtain ⟨p,hp⟩ := ExactRareCost.public_polynomial + obtain ⟨q,a,hq⟩ := exact_rare_measure_bound + obtain ⟨g,hg⟩ := exact_gate_measure_polynomial + let H := a+g+91*X^2+print.comp (25*X^3)+1 + let P := p.comp (X+q) + refine ⟨C (2^((40*P.natDegree)^2))*(P.comp H),?_⟩ + intro m n r c htotal + let B := print.eval (ExactPrintCost.matrixSize (n := n) r) + let S := Algorithms.samplingSize n r 0 + let E := exactBoxScale r c + let W := H.eval S*E + have hE : 1 ≤ E := exactBoxScale_pos r c + have hHW : H.eval S ≤ W := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (H.eval S) hE + have ha : a.eval S ≤ H.eval S := by simp only [H,eval_add,eval_one]; omega + have hrare : exactRareMeasure (List.ofFn r,List.ofFn c) ≤ q.eval W := + (hq m n r c htotal).trans (polynomial_eval_monotone q (Nat.mul_le_mul_right E ha)) + have hscalar : weight (Algorithms.encodeMargins r c)+ + ExactGateCost.measure (List.ofFn r,List.ofFn c)+B ≤ H.eval S := by + have hw := exact_public_weight r c htotal + have hgate := hg m n r c htotal + have hprint : print.eval (ExactPrintCost.matrixSize (n := n) r) ≤ print.eval (25*S^3) := + polynomial_eval_monotone print (exact_matrix_size (n := n) r) + simp only [H,eval_add,eval_mul,eval_ofNat,eval_pow,eval_X,eval_comp,eval_one] + unfold B S at * + omega + have hmeasure : ExactRareCost.publicMeasure (Algorithms.encodeMargins r c) B ≤ (X+q).eval W := by + change weight (Algorithms.encodeMargins r c)+ + (ExactGateCost.measure (ProfilePrograms.exactParsedMargins (Algorithms.encodeMargins r c))+ + exactRareMeasure (ProfilePrograms.exactParsedMargins (Algorithms.encodeMargins r c)))+B ≤ _ + rw [exactParsedMargins_spec] + simp only [eval_add,eval_X] + omega + have hcost : ExactPublicCost.budget r c 1 B B+1 ≤ P.eval W := by + have ht := (hp (Algorithms.encodeMargins r c) B).trans (polynomial_eval_monotone p hmeasure) + simpa only [ExactPublicCost.budget,ExactTablePrefix.input,P,eval_comp] using ht + have habsorb := exact_scale_absorbed r c P (H.eval S) + apply hcost.trans (habsorb.trans_eq ?_) + simp only [eval_mul,eval_C,eval_comp] + ring + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactResidualInput.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactResidualInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d07011c945228ce3b4dbc2dc837683e8e352746 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactResidualInput.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactSamplingParameters +import OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixTrial +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledResidualLaw + +namespace OAI + +/-! # Computing the complete input to the exact matrix rejection loop -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +attribute [local irreducible] exactResidualInput scheduledResidualCounts originalCandidates + +def exactRareMeasure (z : CompletionMargins) : ℕ := + exactParameterMeasure z+scheduledResidualMeasure (exactResidualInput z)+ + originalEnumerationMeasure z+weight z + +def exactRareWeights (z : CompletionMargins) : List ℕ := + scheduledResidualCounts (exactResidualInput z) + +def exactRareWeightsRealizer : Realizer exactRareWeights := + composition (f := exactResidualInput) (g := scheduledResidualCounts) + exactResidualInputRealizer scheduledResidualCountsRealizer + +lemma work_exactRareWeights : WorkBound exactRareWeightsRealizer exactRareMeasure := by + unfold exactRareWeightsRealizer + have hp : WorkBound exactResidualInputRealizer exactRareMeasure := + work_remeasure work_exactResidualInput X (by + intro z + simp only [eval_X,exactRareMeasure] + omega) + apply work_composition hp work_scheduledResidualCounts X + intro z + simp only [eval_X,exactRareMeasure] + omega + +attribute [local irreducible] exactRareWeights + +def exactMatrixInput (z : CompletionMargins) : ExactMatrixTrial.Input := + ((originalCandidates z,GreedyFeasibleTable.listMatrix z.1 z.2),exactRareWeights z) + +def exactMatrixInputRealizer : Realizer exactMatrixInput := + pair (pair originalCandidatesRealizer GreedyFeasibleTable.tableRealizer) exactRareWeightsRealizer + +lemma work_exactMatrixInput : WorkBound exactMatrixInputRealizer exactRareMeasure := by + have hi (z : CompletionMargins) : weight z ≤ X.eval (exactRareMeasure z) := by + simp only [eval_X,exactRareMeasure] + omega + have he : WorkBound originalCandidatesRealizer exactRareMeasure := + work_remeasure work_originalCandidates X (by + intro z + simp only [eval_X,exactRareMeasure] + omega) + exact work_pair (work_pair he (work_of_polynomial GreedyFeasibleTable.polynomial_table X hi) X hi) + work_exactRareWeights X hi + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms OriginalTableBox ResidualMixture FirstSuccess CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "D" => correctionPrecision r c +local notation "q" => largeTailCount r (d^20)*largeTailCount c (d^20) + +lemma exactRareWeights_pos + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) : + 0<(exactRareWeights (List.ofFn r,List.ofFn c)).sum := by + rw [exactRareWeights,exactResidualInput_ofFn] + exact scheduledResidualCounts_sum r c hPL hCheeger htotal + +lemma exactMatrixInput_code (htotal : (∑ i,r i)=∑ j,c j) : + exactMatrixInput (List.ofFn r,List.ofFn c)= + ((originalCandidates (List.ofFn r,List.ofFn c),matrixCode (GreedyFeasibleTable.table r c htotal).val), + scheduledResidualCounts (((List.ofFn r,List.ofFn c),2*D),2^D)) := by + unfold exactMatrixInput exactRareWeights + rw [exactResidualInput_ofFn,GreedyFeasibleTable.listMatrix_ofFn] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..f36f9cd7577503ebc165c217ae8659dfc7f8812b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingMachine.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactExpectedTime +import OAI.Combinatorics.ContingencyTables.Sampling.ExactRarePublicBound + +namespace OAI + +/-! # The exact public sampler in uniform expected polynomial bit time -/ + +namespace ContingencyTables.SmallGraphProfiles +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream Turing +open ProfilePrograms DensePrograms Polynomial Algorithms +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] ExactPublicPrefix.program + +theorem exact_expected_polynomial : ∃ p : Polynomial ℕ, + ∀ (_hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (_hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*k^8))), + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), (∑ i,r i)=∑ j,c j → + (∑' (t : ℕ), (1 - haltMass ExactPublicPrefix.machine (encodeMargins r c) t)) ≤ + ((p.eval (samplingSize n r 0) : ℕ) : ℝ) := by + obtain ⟨print,hprint⟩ := ExactPrintCost.polynomial_print_bound + obtain ⟨p,hp⟩ := ExactGatePolynomial.public_bound print + obtain ⟨q,hq⟩ := exact_public_correction_bound print + refine ⟨p+11*q,?_⟩ + intro hPL hCheeger m n r c htotal + let B := print.eval (ExactPrintCost.matrixSize (n := n) r) + let S := ExactGatePublic.budget r c B B + let T := ExactPublicCost.budget r c 1 B B+1 + let den : ℝ := (2:ℝ)^correctionPrecision r c + have hB (X : Table r c) : GreedyFeasibleTable.printMatrixRealizer.cost (matrixCode X.val) ≤ B := + (Nat.le_add_right _ _).trans (hprint m n r c X) + have hL (X : Table r c) : (ExactPublicPrefix.word r c X).length ≤ B := + (list_length_le_weight _).trans ((Nat.le_add_left _ _).trans (hprint m n r c X)) + have htail := (ExactExpectedTime.bound r c hPL hCheeger htotal B B hB hL).2 + have hgate : (S:ℝ) ≤ ((p.eval (samplingSize n r 0):ℕ):ℝ) := by exact_mod_cast hp m n r c htotal + have hT : (T:ℝ) ≤ den*((q.eval (samplingSize n r 0):ℕ):ℝ) := by + have hn : T ≤ 2^(correctionPrecision r c)*q.eval (samplingSize n r 0) := hq m n r c htotal + have ht : (T:ℝ) ≤ ((2^(correctionPrecision r c)*q.eval (samplingSize n r 0):ℕ):ℝ) := by + exact_mod_cast hn + simpa only [Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat,den] using ht + have hrare : (1/den)*T ≤ ((q.eval (samplingSize n r 0):ℕ):ℝ) := by + have hden : 0 < den := by unfold den; positivity + have ht : (T:ℝ)/den ≤ ((q.eval (samplingSize n r 0):ℕ):ℝ) := + (div_le_iff₀ hden).mpr (by simpa only [mul_comm] using hT) + simpa only [one_div,div_eq_mul_inv,mul_comm,one_mul] using ht + have he : (fun t => 1-haltMass ExactPublicPrefix.machine (encodeMargins r c) t)= + PhysicalRetryTail.tail ExactPublicPrefix.program.table + (ExactPublicPrefix.program.initial (Tape.mk₁ (encodeMargins r c))) := by + funext t + exact PhysicalPublicLaw.tail_eq _ _ _ + rw [←he] at htail + change _ ≤ (S:ℝ)+11*(1/den)*T at htail + simp only [eval_add,eval_mul,eval_ofNat,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat] + nlinarith + +/-- Paper 200-01, main theorem (ii), conditional on the cited finite-box +Prékopa--Leindler and finite-grid Cheeger inputs. The machine is fixed, +including parsing, printing, and the unbiased-bit implementation. -/ +theorem exactSampling_conditional + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*k^8))) : + ExactSamplingStatement := by + obtain ⟨p,hp⟩ := exact_expected_polynomial + refine ⟨ExactPublicPrefix.machine,p.eval 1+1,p.natDegree,by omega,?_⟩ + intro m n r c htotal + dsimp only + refine ⟨ExactPublicLaw.halted_feasible r c hPL hCheeger htotal, + ExactPublicLaw.tableMass_limit r c hPL hCheeger htotal, + ExactPublicLaw.haltMass_limit r c hPL hCheeger htotal, + ExactExpectedTime.summable r c hPL hCheeger htotal,?_⟩ + have hS : 1 ≤ samplingSize n r 0 := by unfold samplingSize; omega + have hpoly : p.eval (samplingSize n r 0) ≤ p.eval 1*(samplingSize n r 0)^p.natDegree := by + simpa only [one_mul,pow_one] using polynomial_scaled_power p 1 (samplingSize n r 0) 1 hS + have hnat := hpoly.trans (Nat.mul_le_mul_right _ (Nat.le_succ _)) + have hreal : ((p.eval (samplingSize n r 0):ℕ):ℝ) ≤ + (p.eval 1+1:ℕ)*(samplingSize n r 0:ℝ)^p.natDegree := by exact_mod_cast hnat + exact (hp hPL hCheeger m n r c htotal).trans hreal + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingParameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a47883baf7dae9aa771f6fcf5bb9d6a5c15f444 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactSamplingParameters.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledResidualProgram +import OAI.Combinatorics.ContingencyTables.Sampling.CompiledResidualCorrection + +namespace OAI + +/-! # Computing the exact sampler's precision from its margin-only input -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +attribute [local irreducible] marginDimension marginBinaryLength parameterWordCount + +def sixthPower : Realizer (fun n : ℕ => n^6) := + (composition (f := fun n : ℕ => n^3) (g := fun n : ℕ => n^2) + cubicPower squarePower).congr (by intro n; simp only [Function.comp_apply,←pow_mul]) + +lemma polynomial_sixthPower : PolynomialTime sixthPower := + polynomial_congr _ (polynomial_composition polynomial_cubicPower polynomial_squarePower) + +def exactPrecision (z : CompletionMargins) : ℕ := (marginDimension z)^6*(marginBinaryLength z)^2 + +def exactPrecisionRealizer : Realizer exactPrecision := + composition (f := fun z : CompletionMargins => ((marginDimension z)^6,(marginBinaryLength z)^2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (f := marginDimension) (g := fun n : ℕ => n^6) marginDimensionRealizer sixthPower) + (composition (f := marginBinaryLength) (g := fun n : ℕ => n^2) marginBinaryLengthRealizer squarePower)) + multiply + +lemma polynomial_exactPrecision : PolynomialTime exactPrecisionRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_marginDimension polynomial_sixthPower) + (polynomial_composition polynomial_marginBinaryLength polynomial_squarePower)) polynomial_multiply + +attribute [local irreducible] exactPrecision + +def exactSamplingParameters (z : CompletionMargins) : SamplingParameters := (z,2*exactPrecision z) + +def exactSamplingParametersRealizer : Realizer exactSamplingParameters := + pair identity (composition (f := fun z : CompletionMargins => (2,exactPrecision z)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair (constant 2) exactPrecisionRealizer) multiply) + +lemma polynomial_exactSamplingParameters : PolynomialTime exactSamplingParametersRealizer := + polynomial_pair polynomial_identity (polynomial_composition + (polynomial_pair (polynomial_constant 2) polynomial_exactPrecision) polynomial_multiply) + +def exactBranchDenominator (z : CompletionMargins) : ℕ := BinaryPowerPrograms.power (2,exactPrecision z) + +def exactBranchDenominatorRealizer : Realizer exactBranchDenominator := + composition (f := fun z : CompletionMargins => (2,exactPrecision z)) (g := BinaryPowerPrograms.power) + (pair (constant 2) exactPrecisionRealizer) BinaryPowerPrograms.powerRealizer + +def exactParameterMeasure (z : CompletionMargins) : ℕ := exactPrecision z+weight z + +lemma work_exactBranchDenominator : WorkBound exactBranchDenominatorRealizer exactParameterMeasure := by + unfold exactBranchDenominatorRealizer + apply work_composition (work_of_polynomial (polynomial_pair (polynomial_constant 2) + polynomial_exactPrecision) X (by intro z; simp only [eval_X,exactParameterMeasure]; omega)) + BinaryPowerPrograms.work_power (X+C (weight (2:ℕ))) + intro z + simp only [eval_add,eval_X,eval_C,exactParameterMeasure] + omega + +def exactResidualInput (z : CompletionMargins) : SamplingParameters×ℕ := + (exactSamplingParameters z,exactBranchDenominator z) + +def exactResidualInputRealizer : Realizer exactResidualInput := + pair exactSamplingParametersRealizer exactBranchDenominatorRealizer + +lemma work_exactResidualInput : WorkBound exactResidualInputRealizer exactParameterMeasure := + work_pair (work_of_polynomial polynomial_exactSamplingParameters X + (by intro z; simp only [eval_X,exactParameterMeasure]; omega)) + work_exactBranchDenominator X (by intro z; simp only [eval_X,exactParameterMeasure]; omega) + +/-- The ordinary branch needs precisely the existing public sampler's word. -/ +def exactOrdinaryBits (z : CompletionMargins) : ℕ := parameterWordCount (exactSamplingParameters z) + +def exactOrdinaryBitsRealizer : Realizer exactOrdinaryBits := + composition (f := exactSamplingParameters) (g := parameterWordCount) + exactSamplingParametersRealizer parameterWordCountRealizer + +lemma polynomial_exactOrdinaryBits : PolynomialTime exactOrdinaryBitsRealizer := + polynomial_composition polynomial_exactSamplingParameters polynomial_parameterWordCount + +def exactParsedMargins (as : List Symbol) : CompletionMargins := (parsedSampling as).1 + +def exactParsedMarginsRealizer : Realizer exactParsedMargins := + composition (f := parsedSampling) (g := fun p : SamplingParameters => p.1) parsedSamplingRealizer first + +lemma polynomial_exactParsedMargins : PolynomialTime exactParsedMarginsRealizer := + polynomial_composition polynomial_parsedSampling polynomial_first + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms MatchingFPRAS.LiteralParse +open scoped BigOperators + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +lemma exactPrecision_ofFn : exactPrecision (List.ofFn r,List.ofFn c)=correctionPrecision r c := by + rw [exactPrecision,marginDimension_ofFn,marginBinaryLength_ofFn] + rfl + +lemma exactSamplingParameters_ofFn : + exactSamplingParameters (List.ofFn r,List.ofFn c)= + ((List.ofFn r,List.ofFn c),2*correctionPrecision r c) := by + rw [exactSamplingParameters,exactPrecision_ofFn] + +lemma exactBranchDenominator_ofFn : + exactBranchDenominator (List.ofFn r,List.ofFn c)=2^(correctionPrecision r c) := by + rw [exactBranchDenominator,BinaryPowerPrograms.power_eq,exactPrecision_ofFn] + +lemma exactResidualInput_ofFn : + exactResidualInput (List.ofFn r,List.ofFn c)= + (((List.ofFn r,List.ofFn c),2*correctionPrecision r c),2^(correctionPrecision r c)) := by + rw [exactResidualInput,exactSamplingParameters_ofFn,exactBranchDenominator_ofFn] + +lemma exactOrdinaryBits_ofFn : + exactOrdinaryBits (List.ofFn r,List.ofFn c)=finiteSamplerBits r c (2*correctionPrecision r c) := by + rw [exactOrdinaryBits,exactSamplingParameters_ofFn,parameterWordCount_ofFn] + +lemma exactParsedMargins_spec : + exactParsedMargins (Algorithms.encodeMargins r c)=(List.ofFn r,List.ofFn c) := by + unfold exactParsedMargins parsedSampling samplingInput + rw [GreedyFeasibleTable.encodeMargins_natWords,GreedyFeasibleTable.parse_natWords] + have h := GreedyFeasibleTable.marginLists_spec m n (List.ofFn r) (List.ofFn c) [] + List.length_ofFn List.length_ofFn + simpa only [List.append_nil] using h + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTablePrefix.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTablePrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d83c44deddcfb0320dcf3907869792e26d39b73 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTablePrefix.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrefixFeasibility +import OAI.Combinatorics.ContingencyTables.Machines.PackedMatrixInjective + +namespace OAI + +/-! # Finite physical prefixes indexed by feasible tables -/ + +namespace ContingencyTables.ExactTablePrefix +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost +open DensePrograms SmallGraphProfiles Turing +open scoped Classical BigOperators +noncomputable section + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => CompletionCounts.dimensionAllowance (I := Fin m) (J := Fin n) +attribute [local irreducible] ExactCoreProgram.prefixExperiment + ExactPhysicalProgram.program ExactPhysicalProgram.output + +def code (o : Option (Table r c)) : Option MatrixCode := o.map (fun X => matrixCode X.val) + +lemma code_injective : Function.Injective (code r c) := by + intro X Y h + cases X with + | none => cases Y <;> simp_all [code] + | some X => + cases Y with + | none => simp [code] at h + | some Y => + apply congrArg some + apply Subtype.ext + have he : matrixCode X.val=matrixCode Y.val := Option.some.inj h + change List.ofFn (fun i => List.ofFn (X.val i))=List.ofFn (fun i => List.ofFn (Y.val i)) at he + funext i + exact List.ofFn_injective (congrFun (List.ofFn_injective he) i) + +def decode : Option MatrixCode → Option (Table r c) := Function.invFun (code r c) + +lemma decode_code (o : Option (Table r c)) : decode r c (code r c o)=o := + Function.leftInverse_invFun (code_injective r c) o + +lemma code_decode {o : Option MatrixCode} (h : FeasibleOutcome r c o) : + code r c (decode r c o)=o := by + cases o with + | none => exact congrArg (code r c) (decode_code r c none) + | some X => + obtain ⟨T,hT⟩ := h + subst X + exact congrArg (code r c) (decode_code r c (some T)) + +def experiment (N : ℕ) : Experiment (Option (Table r c)) := + (ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).map (decode r c) + +lemma decode_eq_iff {o : Option MatrixCode} (ho : FeasibleOutcome r c o) + (T : Option (Table r c)) : decode r c o=T ↔ o=code r c T := by + constructor + · intro h + exact (code_decode r c ho).symm.trans (congrArg (code r c) h) + · intro h + rw [h,decode_code] + +lemma event_mean (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) (T : Option (Table r c)) : + (experiment r c N).mean (fun o => if o=T then 1 else 0)= + (ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=code r c T then 1 else 0) := by + rw [experiment,Experiment.mean_map] + apply Experiment.mean_congr_all + exact (exactPrefix_feasible r c htotal N).mono (by + intro o ho + simp only [decode_eq_iff r c ho T]) + +lemma failure_bound + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler + (largeTailCount r (d^20)*largeTailCount c (d^20))) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid + (I := Fin (largeTailCount r (d^20)*largeTailCount c (d^20))) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + (experiment r c N).mean (fun o => if o=none then 1 else 0)≤ + (1/(2:ℚ)^(correctionPrecision r c))*(1/2:ℚ)^N := by + rw [event_mean r c htotal] + exact exactPrefix_failure r c hPL hCheeger htotal N + +lemma point_limit + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler + (largeTailCount r (d^20)*largeTailCount c (d^20))) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid + (I := Fin (largeTailCount r (d^20)*largeTailCount c (d^20))) (4*d^8))) + (htotal : (∑ i,r i)=∑ j,c j) (X : Table r c) : + Filter.Tendsto (fun N => ((experiment r c N).mean + (fun o => if o=some X then 1 else 0):ℝ)) Filter.atTop + (nhds ((Fintype.card (Table r c):ℝ)⁻¹)) := by + have he : (fun N => ((experiment r c N).mean (fun o => if o=some X then 1 else 0):ℝ))= + (fun N => ((ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean + (fun o => if o=some (matrixCode X.val) then 1 else 0):ℝ)) := by + funext N + exact congrArg (fun x : ℚ => (x:ℝ)) (event_mean r c htotal N (some X)) + rw [he] + exact exactPrefix_limit r c hPL hCheeger htotal X + +def input : List Symbol := Algorithms.encodeMargins r c + +def output (o : Option (Table r c)) : Cfg Symbol ExactPhysicalProgram.program.State := + ExactPhysicalProgram.output (input r c) (code r c o) + +lemma output_injective : Function.Injective (output r c) := by + intro a b h + cases a with + | none => + cases b with + | none => rfl + | some Y => + have he := congrArg Cfg.state h + change (ExactPhysicalProgram.output (input r c) none).state= + (ExactPhysicalProgram.output (input r c) (some (matrixCode Y.val))).state at he + rw [ExactPhysicalProgram.output_some] at he + exact False.elim (ExactPhysicalProgram.output_none_live _ he) + | some X => + cases b with + | none => + have he := congrArg Cfg.state h + change (ExactPhysicalProgram.output (input r c) (some (matrixCode X.val))).state= + (ExactPhysicalProgram.output (input r c) none).state at he + rw [ExactPhysicalProgram.output_some] at he + exact False.elim (ExactPhysicalProgram.output_none_live _ he.symm) + | some Y => + apply congrArg some + apply PackedMatrixInjective.table_injective X Y + change ExactPhysicalProgram.output _ (some (matrixCode X.val))= + ExactPhysicalProgram.output _ (some (matrixCode Y.val)) at h + rw [ExactPhysicalProgram.output_some,ExactPhysicalProgram.output_some] at h + simpa only [Program.final,Cfg.mk.injEq,true_and] using h + +theorem physical_prefix (htotal : (∑ i,r i)=∑ j,c j) (N : ℕ) : + ∃ p,Implements ExactPhysicalProgram.program.table (output r c) + (ExactPhysicalProgram.program.initial (Tape.mk₁ (TreePost.packed (input r c)))) p ∧ + ∀ g : Option (Table r c) → ℚ,p.mean g=(experiment r c N).mean g := by + obtain ⟨p,hp,hpm⟩ := ExactPhysicalProgram.prefix_correct (input r c) N + have hm (g : Option MatrixCode → ℚ) : + p.mean g=(ExactCoreProgram.prefixExperiment (List.ofFn r,List.ofFn c) N).mean g := by + simpa only [input,exactParsedMargins_spec] using hpm g + have hall : p.All (FeasibleOutcome r c) := + Experiment.all_of_mean_eq hm _ (exactPrefix_feasible r c htotal N) + refine ⟨p.map (decode r c),hp.map_all (decode r c) (output r c) + (hall.mono (by intro o ho; unfold output; rw [code_decode r c ho])),?_⟩ + intro g + rw [Experiment.mean_map,hm,experiment,Experiment.mean_map] + +end +end ContingencyTables.ExactTablePrefix + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedCost.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedCost.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2006aabfe687595a574f7f249aa9ccaf2323834 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedCost.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreCost + +namespace OAI + +/-! # Keeping prefix cost bounds through the actual parser and printer -/ + +namespace ContingencyTables.ExactTypedCost +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms ExactTypedProgram + +theorem printed_correct_cost (z : CompletionMargins) (s : Data) (N B : ℕ) + (hB : (ExactCoreProgram.prefixExperiment z N).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ p,Executes printedProgram.code printedProgram.coin (printedOutput z s) + (OnlineTree.initial printedProgram (TreeTyped.encode z) s) p ∧ + (∀ g : Option MatrixCode → ℚ,p.mean g=(ExactCoreProgram.prefixExperiment z N).mean g) ∧ + p.cost≤ExactCoreCost.budget z N+B := by + obtain ⟨p,hp,hpm,hpc⟩ := ExactCoreCost.prefix_correct_cost z s N + have hp' := hp.relabel printedProgram.code printedProgram.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + have next (o : Option MatrixCode) : ∃ q, + Executes printedProgram.code printedProgram.coin (printedOutput z s) + (StackComposition.mapCfg Sum.inl (some (Sum.inr default)) (ExactCoreProgram.output z s o)) q ∧ + (∀ g : Option MatrixCode → ℚ,q.mean g=g o) ∧ + q.cost≤o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost := by + cases o with + | none => exact ⟨.done none,.done none,(fun _ => rfl),le_rfl⟩ + | some X => + obtain ⟨n,hnb,hn⟩ := GreedyFeasibleTable.printMatrixRealizer.correct X s + obtain ⟨q,hq,hqm,hqc⟩ := Executes.of_run GreedyFeasibleTable.printMatrixRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic GreedyFeasibleTable.printMatrixRealizer.program) + (TreeTyped.encode X) s) none (encodeEnv (env + (TreeTyped.encode (GreedyFeasibleTable.printMatrix X)) .nil s)) hn + have hq' := hq.relabel printedProgram.code printedProgram.coin Sum.inr none + (fun _ => rfl) (fun _ => rfl) + refine ⟨q.bind (fun _ => .done (some X)),?_,?_,?_⟩ + · exact hq'.bind _ _ (fun _ => .done (some X)) + · intro g + simpa only [Experiment.mean_bind,Experiment.mean] using hqm (fun _ => g (some X)) + · have hc := Experiment.cost_bind_le q (fun _ => .done (some X)) 0 (fun _ => le_rfl) + simp only [Option.elim_some,Nat.add_zero] at hc ⊢ + exact hc.trans (hqc.trans hnb) + choose q hq hqm hqc using next + refine ⟨p.bind q,hp'.bind q _ hq,?_,?_⟩ + · intro g + rw [Experiment.mean_bind] + simp_rw [hqm] + exact hpm g + · have hall := Experiment.all_of_mean_eq hpm _ hB + exact (Experiment.cost_bind_le_of_all p q B (hall.mono + (fun o ho => (hqc o).trans ho))).trans (Nat.add_le_add_right hpc B) + +theorem prefix_correct_cost (as : List Symbol) (s : Data) (N B : ℕ) + (hB : (ExactCoreProgram.prefixExperiment (exactParsedMargins as) N).All + (fun o => o.elim 0 GreedyFeasibleTable.printMatrixRealizer.cost≤B)) : + ∃ p,Executes program.code program.coin (output as s) + (OnlineTree.initial program (TreeTyped.encode as) s) p ∧ + (∀ g : Option MatrixCode → ℚ, + p.mean g=(ExactCoreProgram.prefixExperiment (exactParsedMargins as) N).mean g) ∧ + p.cost≤exactParsedMarginsRealizer.cost as+ExactCoreCost.budget (exactParsedMargins as) N+B := by + obtain ⟨p,hp,hpm,hpc⟩ := printed_correct_cost (exactParsedMargins as) s N B hB + have hp' := hp.relabel program.code program.coin Sum.inr none (fun _ => rfl) (fun _ => rfl) + obtain ⟨n,hnb,hn⟩ := exactParsedMarginsRealizer.correct as s + obtain ⟨u,hu,hum,huc⟩ := Executes.of_run exactParsedMarginsRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic exactParsedMarginsRealizer.program) + (TreeTyped.encode as) s) none (encodeEnv (env (TreeTyped.encode (exactParsedMargins as)) .nil s)) hn + have hu' := hu.relabel program.code program.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + refine ⟨u.bind (fun _ => p),hu'.bind _ _ (fun _ => hp'),?_,?_⟩ + · intro g + rw [Experiment.mean_bind,hum] + exact hpm g + · have hc := Experiment.cost_bind_le u (fun _ => p) p.cost (fun _ => le_rfl) + omega + +end ContingencyTables.ExactTypedCost + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a8be149bf284b56026cc20f0cf6710eb658d008 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ExactTypedProgram.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreProgram +import OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram + +namespace OAI + +/-! # Parsing and printing around the same unbounded exact core -/ + +namespace ContingencyTables.ExactTypedProgram +open MatchingFPRAS MatchingFPRAS.TreeData MatchingFPRAS.TreeFunction +open MatchingFPRAS.TreeMachine (K encodeEnv) +open MatchingFPRAS.PhysicalStream MatchingFPRAS.OnlineStack +open ProfilePrograms DensePrograms + +noncomputable def printedProgram : OnlineProc.Proc (K Reg) := + OnlineProc.seq ExactCoreProgram.program + (OnlineProc.deterministic GreedyFeasibleTable.printMatrixRealizer.program) + +noncomputable def printedOutput (z : CompletionMargins) (s : Data) : + Option MatrixCode → OnlineTree.StoreCfg printedProgram + | none => StackComposition.mapCfg Sum.inl (some (Sum.inr default)) (ExactCoreProgram.output z s none) + | some X => OnlineTree.final printedProgram (TreeTyped.encode (GreedyFeasibleTable.printMatrix X)) s + +theorem printed_correct (z : CompletionMargins) (s : Data) (N : ℕ) : + ∃ p,Executes printedProgram.code printedProgram.coin (printedOutput z s) + (OnlineTree.initial printedProgram (TreeTyped.encode z) s) p ∧ + ∀ g : Option MatrixCode → ℚ,p.mean g=(ExactCoreProgram.prefixExperiment z N).mean g := by + obtain ⟨p,hp,hpm⟩ := ExactCoreProgram.prefix_correct z s N + have hp' := hp.relabel printedProgram.code printedProgram.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + have next (o : Option MatrixCode) : ∃ q, + Executes printedProgram.code printedProgram.coin (printedOutput z s) + (StackComposition.mapCfg Sum.inl (some (Sum.inr default)) (ExactCoreProgram.output z s o)) q ∧ + ∀ g : Option MatrixCode → ℚ,q.mean g=g o := by + cases o with + | none => exact ⟨.done none,.done none,fun _ => rfl⟩ + | some X => + obtain ⟨n,_,hn⟩ := GreedyFeasibleTable.printMatrixRealizer.correct X s + obtain ⟨q,hq,hqm,_⟩ := Executes.of_run GreedyFeasibleTable.printMatrixRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic GreedyFeasibleTable.printMatrixRealizer.program) + (TreeTyped.encode X) s) none (encodeEnv (env + (TreeTyped.encode (GreedyFeasibleTable.printMatrix X)) .nil s)) hn + have hq' := hq.relabel printedProgram.code printedProgram.coin Sum.inr none + (fun _ => rfl) (fun _ => rfl) + refine ⟨q.bind (fun _ => .done (some X)),?_,?_⟩ + · exact hq'.bind _ _ (fun _ => .done (some X)) + · intro g + simpa only [Experiment.mean_bind,Experiment.mean] using hqm (fun _ => g (some X)) + choose q hq hqm using next + refine ⟨p.bind q,hp'.bind q _ hq,?_⟩ + intro g + rw [Experiment.mean_bind] + simp_rw [hqm] + exact hpm g + +noncomputable def program : OnlineProc.Proc (K Reg) := + OnlineProc.seq (OnlineProc.deterministic exactParsedMarginsRealizer.program) printedProgram + +noncomputable def output (as : List Symbol) (s : Data) (o : Option MatrixCode) : + OnlineTree.StoreCfg program := StackComposition.mapCfg Sum.inr none + (printedOutput (exactParsedMargins as) s o) + +theorem prefix_correct (as : List Symbol) (s : Data) (N : ℕ) : + ∃ p,Executes program.code program.coin (output as s) + (OnlineTree.initial program (TreeTyped.encode as) s) p ∧ + ∀ g : Option MatrixCode → ℚ, + p.mean g=(ExactCoreProgram.prefixExperiment (exactParsedMargins as) N).mean g := by + obtain ⟨p,hp,hpm⟩ := printed_correct (exactParsedMargins as) s N + have hp' := hp.relabel program.code program.coin Sum.inr none (fun _ => rfl) (fun _ => rfl) + obtain ⟨n,_,hn⟩ := exactParsedMarginsRealizer.correct as s + obtain ⟨u,hu,hum,_⟩ := Executes.of_run exactParsedMarginsRealizer.program.code n + (OnlineTree.initial (OnlineProc.deterministic exactParsedMarginsRealizer.program) + (TreeTyped.encode as) s) none (encodeEnv (env (TreeTyped.encode (exactParsedMargins as)) .nil s)) hn + have hu' := hu.relabel program.code program.coin Sum.inl + (some (Sum.inr default)) (fun _ => rfl) (fun _ => rfl) + refine ⟨u.bind (fun _ => p),hu'.bind _ _ (fun _ => hp'),?_⟩ + intro g + rw [Experiment.mean_bind,hum] + exact hpm g + +end ContingencyTables.ExactTypedProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBinaryParameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBinaryParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..45c1c6e1d204bea773d5b768c8b43ce87c9f3301 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBinaryParameters.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallMixing +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperOuterBudget + +namespace OAI + +/-! # Binary lengths for the small-chain capacity bound -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) + +lemma stateBound_clog_le : + Nat.clog 2 (stateBound r c+2) ≤ Nat.clog 2 ((∑ i,r i)+1)+20*d+2 := by + have hd : 1 ≤ d := by unfold dimensionAllowance; omega + have h13 : d^13 ≤ 2^(20*d) := + (nat_pow_le_two_pow d 13).trans (Nat.pow_le_pow_right (by decide) (by omega)) + have h20 : d^20 ≤ 2^(20*d) := by simpa only [Nat.mul_comm] using nat_pow_le_two_pow d 20 + have h4 : 4 ≤ 2^(20*d) := by + exact (by decide : 4 ≤ 2^2).trans (Nat.pow_le_pow_right (by decide) (by omega)) + have hrest : d*d^12+d^20+4 ≤ 2^(20*d+2) := by + have he : d*d^12=d^13 := by ring + rw [he,pow_add] + norm_num + omega + have hpow : 1 ≤ 2^(20*d+2) := one_le_pow₀ (by decide) + have hn := Nat.le_pow_clog (by decide : 1<2) ((∑ i,r i)+1) + apply Nat.clog_le_of_le_pow + calc + stateBound r c+2=(∑ i,r i)+(d*d^12+d^20+4) := by unfold stateBound; omega + _ ≤ (∑ i,r i)+2^(20*d+2) := Nat.add_le_add_left hrest _ + _ ≤ ((∑ i,r i)+1)*2^(20*d+2) := by + have hm := Nat.mul_le_mul_left (∑ i,r i) hpow + simpa only [mul_one,add_mul,one_mul] using Nat.add_le_add_right hm (2^(20*d+2)) + _ ≤ 2^(Nat.clog 2 ((∑ i,r i)+1))*2^(20*d+2) := Nat.mul_le_mul_right _ hn + _ = 2^(Nat.clog 2 ((∑ i,r i)+1)+20*d+2) := by + rw [←pow_add] + congr 1 + +noncomputable def smallBinaryLength : ℕ := d+Nat.clog 2 (stateBound r c+2) + +lemma smallBinaryLength_parameters : + Nat.clog 2 (stateBound r c+2) ≤ smallBinaryLength r c ∧ + d ≤ smallBinaryLength r c ∧ stateBound r c+1 ≤ 2^(smallBinaryLength r c) := by + refine ⟨by unfold smallBinaryLength; omega,by unfold smallBinaryLength; omega,?_⟩ + have hb : Nat.clog 2 (stateBound r c+2) ≤ smallBinaryLength r c := by + unfold smallBinaryLength + omega + exact (show stateBound r c+1 ≤ stateBound r c+2 by omega).trans + ((Nat.le_pow_clog (by decide) (stateBound r c+2)).trans + (Nat.pow_le_pow_right (by decide) hb)) + +lemma smallBinaryLength_le : + smallBinaryLength r c ≤ 21*d+Nat.clog 2 ((∑ i,r i)+1)+2 := by + have h := stateBound_clog_le r c + unfold smallBinaryLength + omega + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bca0e5c6a326ec1fc13042e251097b5fe234e66 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanDraw.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanStep + +namespace OAI + +/-! # Fixed Boolean words for the entire small walk and outer sampler -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +variable (a : GridBoundary.Grid (I := Fin q) (4*(dimensionAllowance (I := I) (J := J))^8)) +variable (fallback : (z : PaperStates r c) → PaperFibre r c z) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +local notation "s" => smallProposalBits (I := I) (J := J) +local notation "f" => 25*(d+b+h+1)^62 + +def flatSmallWalk (x : PaperStates r c) (n : ℕ) + (bits : Fin (n*(s+f)) → Bool) : PaperStates r c := + wordWalk (smallBitStep r c i₀ j₀ e b h hb a fallback) x n + (GridBoundary.gridWordEquiv n (s+f) bits) + +theorem flatSmallWalk_law (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (flatSmallWalk r c i₀ j₀ e b h hb a fallback x n)= + walkLaw (implementedSmallKernel r c i₀ j₀ e b h hb a fallback) x n := by + unfold flatSmallWalk + rw [←map_equiv (GridBoundary.gridWordEquiv n (s+f)),uniform_equiv] + change wordWalkLaw _ _ _=_ + rw [wordWalkLaw_eq] + exact congrArg (fun K => walkLaw K x n) + (funext (smallBitStep_law r c i₀ j₀ e b h hb a fallback)) + +def smallJointDraw (x : PaperStates r c) (n : ℕ) + (bits : Fin (n*(s+f)+f) → Bool) : PaperStateJoint r c := + let draws := splitWordEquiv (n*(s+f)) f bits + let z := flatSmallWalk r c i₀ j₀ e b h hb a fallback x n draws.1 + ⟨z,completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z) draws.2⟩ + +/-- The terminal completion uses fresh bits at the adaptively obtained +state, with exactly the joint law used in the error proof. -/ +theorem smallJointDraw_law (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*(s+f)+f) → Bool)) + (smallJointDraw r c i₀ j₀ e b h hb a fallback x n)= + implementedJointLaw r c i₀ j₀ e b h hb a fallback x n := by + let E := splitWordEquiv (n*(s+f)) f + let F := fun ab : (Fin (n*(s+f)) → Bool) × (Fin f → Bool) => + let z := flatSmallWalk r c i₀ j₀ e b h hb a fallback x n ab.1 + (⟨z,completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z) ab.2⟩ : PaperStateJoint r c) + have he := map_equiv E (uniformLaw (α := Fin (n*(s+f)+f) → Bool)) F + rw [uniform_equiv,←uniform_product] at he + calc + _ = mapLaw (productLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (uniformLaw (α := Fin f → Bool))) F := he.symm + _ = dependentJointLaw + (mapLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (flatSmallWalk r c i₀ j₀ e b h hb a fallback x n)) + (fun z => mapLaw (uniformLaw (α := Fin f → Bool)) + (completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z))) := + mapLaw_dependent_product (A := Fin (n*(s+f)) → Bool) (B := Fin f → Bool) + (X := PaperStates r c) (Y := PaperFibre r c) + (uniformLaw (α := Fin (n*(s+f)) → Bool)) (uniformLaw (α := Fin f → Bool)) + (flatSmallWalk r c i₀ j₀ e b h hb a fallback x n) + (fun z => completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z)) + _ = _ := by rw [flatSmallWalk_law]; rfl + +def finiteOuterDraw (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) + (bits : Fin (J₀*(n*(s+f)+f)) → Bool) : Table r c := + wordRetry (fun bitword => stateTrial r c + (smallJointDraw r c i₀ j₀ e b h hb a fallback x n bitword)) z₀ J₀ + (GridBoundary.gridWordEquiv J₀ (n*(s+f)+f) bits) + +/-- All trial words are independent and failed trials return the fixed +feasible fallback. In particular, every bit word returns a feasible table. -/ +theorem finiteOuterDraw_law (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) : + mapLaw (uniformLaw (α := Fin (J₀*(n*(s+f)+f)) → Bool)) + (finiteOuterDraw r c i₀ j₀ e b h hb a fallback x n J₀ z₀)= + retryLaw (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stateTrial r c) z₀ J₀ := by + unfold finiteOuterDraw + rw [←map_equiv (GridBoundary.gridWordEquiv J₀ (n*(s+f)+f)),uniform_equiv] + change wordRetryLaw _ _ _=_ + rw [wordRetryLaw_eq,←retryLaw_map,smallJointDraw_law] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ec07fe4625fe75bc69e66b9c5d17079baec599e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanProposal.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProposal +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawDecidableEq + +namespace OAI + +/-! # Finite Boolean realization of the small graph proposal law -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +local notation "d" => dimensionAllowance (I := I) (J := J) + +abbrev smallProposalBits : ℕ := Nat.clog 2 (32*d^2) + +lemma smallProposal_codes (x : PaperStates r c) : + Fintype.card {y // physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x y} ≤ + 2^(smallProposalBits (I := I) (J := J)) := by + rw [Fintype.card_subtype] + apply (physicalAdjacent_degree_allowance r c _ _ (stateCapacity r c) + (stateCapacity_small r c) x).trans + have hd : 1 ≤ d := by unfold dimensionAllowance; omega + have hs : 1 ≤ d^2 := one_le_pow₀ hd + exact (show 5*d^2+1 ≤ 32*d^2 by omega).trans (Nat.le_pow_clog (by decide) _) + +def smallBitProposal (x : PaperStates r c) + (bits : Fin (smallProposalBits (I := I) (J := J)) → Bool) : Option (PaperStates r c) := + subsetBitDraw (physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x) + (smallProposalBits (I := I) (J := J)) (smallProposal_codes r c x) bits + +/-- The law is independent of the equality decision used by a consumer. -/ +theorem smallBitProposal_law_decidableEq (d₀ : DecidableEq (Option (PaperStates r c))) + (x : PaperStates r c) : + @mapLaw (Fin (smallProposalBits (I := I) (J := J)) → Bool) + (Option (PaperStates r c)) _ _ d₀ + (uniformLaw (α := Fin (smallProposalBits (I := I) (J := J)) → Bool)) + (smallBitProposal r c x)=smallProposalLaw r c x := by + apply law_ext_except _ _ none + intro y hy + cases y with + | none => exact False.elim (hy rfl) + | some y => + exact (subsetBitDraw_mass_decidableEq d₀ + (physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x) + (smallProposalBits (I := I) (J := J)) (smallProposal_codes r c x) y).trans + (smallProposalLaw_mass_some r c x y).symm + +/-- The coding assigns one bit word to each distinct neighbor and uses +all remaining words for the holding proposal. Enumeration cost is separate. -/ +theorem smallBitProposal_law (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin (smallProposalBits (I := I) (J := J)) → Bool)) + (smallBitProposal r c x)=smallProposalLaw r c x := + smallBitProposal_law_decidableEq r c _ x + + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dfd78d09c34c3931716ce3d2cc6f5c6f30ec3fd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBooleanStep.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperImplementedLaw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanProposal +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # The actual small transition driven by one fixed Boolean word -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +variable (a : GridBoundary.Grid (I := Fin q) (4*(dimensionAllowance (I := I) (J := J))^8)) +variable (fallback : (z : PaperStates r c) → PaperFibre r c z) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +local notation "s" => smallProposalBits (I := I) (J := J) +local notation "f" => 25*(d+b+h+1)^62 + +def smallBitStep (x : PaperStates r c) (bits : Fin (s+f) → Bool) : PaperStates r c := + let draws := splitWordEquiv s f bits + completionDecision R P x (smallBitProposal r c x draws.1) + (finiteBlockDraw r c i₀ j₀ e b h hb a fallback x draws.2) + +/-- The proposal and the completion consume disjoint fixed segments. -/ +theorem smallBitStep_law (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin (s+f) → Bool)) + (smallBitStep r c i₀ j₀ e b h hb a fallback x)= + implementedSmallKernel r c i₀ j₀ e b h hb a fallback x := by + let E := splitWordEquiv s f + let finish := fun (y : Option (PaperStates r c)) (word : Fin f → Bool) => + completionDecision R P x y (finiteBlockDraw r c i₀ j₀ e b h hb a fallback x word) + let F := fun ab : (Fin s → Bool) × (Fin f → Bool) => + finish (smallBitProposal r c x ab.1) ab.2 + have he := map_equiv E (uniformLaw (α := Fin (s+f) → Bool)) F + rw [uniform_equiv,←uniform_product] at he + calc + _ = mapLaw (productLaw (uniformLaw (α := Fin s → Bool)) + (uniformLaw (α := Fin f → Bool))) F := he.symm + _ = bindLaw (smallProposalLaw r c x) + (fun y => mapLaw (uniformLaw (α := Fin f → Bool)) (finish y)) := by + rw [mapLaw_product_finish,smallBitProposal_law] + _ = _ := by + have hfinish (y : Option (PaperStates r c)) : + mapLaw (uniformLaw (α := Fin f → Bool)) (finish y)= + mapLaw (finiteBlockLaw r c i₀ j₀ e b h hb a fallback x) + (completionDecision R P x y) := by + dsimp only [finish] + rw [←mapLaw_comp,finiteBlockDraw_law] + exact congrArg (fun K => bindLaw (smallProposalLaw r c x) K) (funext hfinish) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBoundedLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBoundedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..78afc280493e170c6e6aad6d79eafe339506c302 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperBoundedLaw.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperImplementedLaw + +namespace OAI + +/-! # The bounded finite sampling law reaches the requested accuracy -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] [Nonempty (Table r c)] +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) + +local notation "d" => dimensionAllowance (I := I) (J := J) + +/-- The concrete completion draw, literal small transition and repeated +success test have the full error guarantee on nonempty large rectangles. +The physical machine and empty-rectangle branch are separate constructions. -/ +theorem boundedOuterLaw_variation (b k : ℕ) + (hb : Nat.clog 2 (stateBound r c+2) ≤ b) (hdb : d ≤ b) (hk : 1 ≤ k) + (hC : stateBound r c+1 ≤ 2^b) + (a : GridBoundary.Grid (I := Fin q) (4*d^8)) + (fallback : (z : PaperStates r c) → PaperFibre r c z) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (z₀ : Table r c) : + (variation (retryLaw + (implementedJointLaw r c i₀ j₀ e b (outerAccuracy d b k) hb a fallback x (outerSteps d b k)) + (stateTrial r c) z₀ (outerTrials d k)) (uniformLaw (α := Table r c)):ℝ) ≤ 1/(2:ℝ)^k := by + have hv := implementedOuterLaw_variation r c i₀ j₀ e b (outerAccuracy d b k) hb a fallback + hPL hCheeger htotal x (outerSteps d b k) (outerTrials d k) z₀ + have he := outer_total_error d b k (stateBound r c) + (reference_dimension_fourteen r c _ i₀ j₀) hdb hk hC + apply hv.trans + convert he using 1 + push_cast + ring + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperChildMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperChildMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd0785b76dae99e72ed3efa93b15a347701daeed --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperChildMass.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextEnumeration + +namespace OAI + +/-! # Actual exposure child masses retain all physical completions -/ + +namespace ContingencyTables.SmallContextEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PaddedCompletions CompletionCounts +open FirstPaperProfiles FirstPaperPhysicalMarginal FirstPaperContextTransport +open LargePairEnumeration BalancedFamily IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +theorem eliminate_context_eq_child_card (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) (k : Fin (U+1)) + {n : ℕ} (e : Fin n ≃ Later small s) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) : + eliminate (widths (fun _ : Fin n => U)) + (contextHard small B r c L _ (contextEquiv small s hs e U) (prefixRaw small s σ U)) + (childProfile U k.val)= + (Fintype.card (SmallResidualChild small (r) (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) s σ k.val):ℝ) := by + rw [eliminate_context_eq_balanced_mass small B r c L s hs σ U hB hσ k e] + exact balanced_mass_eq_child_card small B r c L s σ k.val hs hcap + +/-- In the paper's actual parameters, no extra capacity hypothesis is +needed for the literal conditional completion count. -/ +theorem firstPaper_child_mass (r : I → ℕ) (c : J → ℕ) + (s : I×J) (hs : paperSmall r c s.1 s.2=true) (σ : I×J → ℕ) + (hσ : ∀ a : Earlier (paperSmall r c) s, + σ a.val.val ≤ (dimensionAllowance (I := I) (J := J))^20) + (k : Fin ((dimensionAllowance (I := I) (J := J))^20+1)) + {n : ℕ} (e : Fin n ≃ Later (paperSmall r c) s) : + let d := dimensionAllowance (I := I) (J := J) + let small := paperSmall r c + let B := paperCapacity small r d (d^12) (d^20) + eliminate (widths (fun _ : Fin n => d^20)) + (contextHard small B r c (d^12) _ (contextEquiv small s hs e (d^20)) + (prefixRaw small s σ (d^20))) (childProfile (d^20) k.val)= + (Fintype.card (SmallResidualChild small r (fun i => r i+rowLargeCount small i*d^12) + c (fun j => c j+columnLargeCount small j*d^12) s σ k.val):ℝ) := by + dsimp only + exact eliminate_context_eq_child_card _ _ r c _ s hs σ _ + (fun i j hij => by simp only [paperCapacity,hij,ite_true]) hσ k e + (paper_residual_capacity r c _ _ _ dimension_le_allowance) + +end ContingencyTables.SmallContextEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeNeighbors.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeNeighbors.lean new file mode 100644 index 0000000000000000000000000000000000000000..b13d91b93a304542c4b8ff62632a0c47d9ecaf52 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeNeighbors.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallInverseRepairList +import OAI.Combinatorics.ContingencyTables.Sampling.SmallExchangeListProgram +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperLocalNeighbors + +namespace OAI + +/-! # A binary program for the full physical neighbor list -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def repairInput : Realizer (fun z : ProfileCheckData => (z.1.1,z.2)) := + pair (composition first first) second + +lemma polynomial_repairInput : PolynomialTime repairInput := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second + +def rawCodeNeighbors (z : ProfileCheckData) : List (List ℕ×List ℕ) := + codeExchangeList z.1.1.2 ++ + (forwardRepairList (z.1.1,z.2) ++ checkedInverseRepairList (z.1.1,z.2)) + +def rawCodeNeighborsRealizer : Realizer rawCodeNeighbors := + composition (pair (composition profileViews codeExchangeListRealizer) + (composition (pair (composition repairInput forwardRepairListRealizer) + (composition repairInput checkedInverseRepairListRealizer)) append)) append + +lemma polynomial_rawCodeNeighbors : PolynomialTime rawCodeNeighborsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_profileViews polynomial_codeExchangeList) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_repairInput polynomial_forwardRepairList) + (polynomial_composition polynomial_repairInput polynomial_checkedInverseRepairList)) + polynomial_append)) polynomial_append + +def candidateData (z : ProfileCheckData×(List ℕ×List ℕ)) : ProfileCheckData := + (((z.1.1.1.1,z.2),z.1.1.2),z.1.2) + +def candidateDataRealizer : Realizer candidateData := + pair (pair (pair (composition (f := fun z : ProfileCheckData×(List ℕ×List ℕ) => z.1) + (g := fun z : ProfileCheckData => z.1.1.1) first profileCatalog) second) + (composition (f := fun z : ProfileCheckData×(List ℕ×List ℕ) => z.1) + (g := fun z : ProfileCheckData => z.1.2) first profileMargins)) (composition first second) + +lemma polynomial_candidateData : PolynomialTime candidateDataRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_profileCatalog) polynomial_second) + (polynomial_composition polynomial_first polynomial_profileMargins)) + (polynomial_composition polynomial_first polynomial_second) + +def codeNeighbors (z : ProfileCheckData) : List (List ℕ×List ℕ) := + ((rawCodeNeighbors z).filter (fun v => profileTest (candidateData (z,v)))).dedup + +def codeNeighborsRealizer : Realizer codeNeighbors := + composition (composition (pair identity rawCodeNeighborsRealizer) + (filterWith (composition candidateDataRealizer profileTestRealizer))) profileCodeDedup + +theorem polynomial_codeNeighbors : PolynomialTime codeNeighborsRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_rawCodeNeighbors) + (polynomial_filterWith (polynomial_composition polynomial_candidateData polynomial_profileTest))) + polynomial_profileCodeDedup + +lemma codeNeighbors_nodup (z : ProfileCheckData) : (codeNeighbors z).Nodup := + List.nodup_dedup _ + +theorem codeNeighbors_length (z : ProfileCheckData) (q : ℕ) + (hx : z.1.1.2.1.length=q) (hy : z.1.1.2.2.length=q) : + (codeNeighbors z).length≤6*q^2 := by + have h0 := ((rawCodeNeighbors z).filter + (fun v => profileTest (candidateData (z,v)))).dedup_sublist.length_le + have h1 := List.length_filter_le (fun v => profileTest (candidateData (z,v))) (rawCodeNeighbors z) + have he := codeExchangeList_length z.1.1.2 + have hf := forwardRepairList_length (z.1.1,z.2) + have hb := checkedInverseRepairList_length (z.1.1,z.2) + change (codeNeighbors z).length≤_ at h0 + simp only [rawCodeNeighbors,List.length_append] at h1 + simp only [hx,hy] at he hf hb + have ht := h0.trans h1 + nlinarith [ht] + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts + +noncomputable section +variable {m n q : ℕ} + +theorem mem_rawCodeNeighbors (r : Fin m → ℕ) (c : Fin n → ℕ) + (e : Fin q ≃ Cells (paperSmall r c)) (x y : PaperStates r c) : + profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) y) ∈ + rawCodeNeighbors (codeCheckData (cellCatalog (paperSmall r c) e) + (List.ofFn r) (List.ofFn c) ((dimensionAllowance (I := Fin m) (J := Fin n))^20) + (profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) x))) ↔ + ArithmeticEdge r c + (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) x) + (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) y) := by + let small := paperSmall r c + let B := stateCapacity r c + let U := (dimensionAllowance (I := Fin m) (J := Fin n))^20 + let L := (dimensionAllowance (I := Fin m) (J := Fin n))^12 + let v := physicalProfile small B r c L x + let w := physicalProfile small B r c L y + have hU : ∀ a : Cells small,B a.val.1 a.val.2=U := + fun a => stateCapacity_small r c _ _ a.property + have hv : ∀ a : Cells small,v (a,true)≤B a.val.1 a.val.2 := + fun a => (physicalProfile_feasible r c x).bounded (a,true) + have hw : ∀ a,w a≤B a.1.val.1 a.1.val.2 := (physicalProfile_feasible r c y).bounded + change profileCode small e w ∈ rawCodeNeighbors + (codeCheckData (cellCatalog small e) (List.ofFn r) (List.ofFn c) U (profileCode small e v)) ↔ + ArithmeticEdge r c v w + simp only [rawCodeNeighbors,codeCheckData,List.mem_append] + rw [mem_codeExchangeList,mem_forwardRepairList small e B U hU v hv, + mem_checkedInverseRepairList small e B U hU v w hw] + simp only [(profileCode_injective small e).eq_iff,ArithmeticEdge,ArithmeticRepair,Prod.exists] + rfl + +theorem mem_codeNeighbors (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (e : Fin q ≃ Cells (paperSmall r c)) (x y : PaperStates r c) : + profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) y) ∈ + codeNeighbors (codeCheckData (cellCatalog (paperSmall r c) e) + (List.ofFn r) (List.ofFn c) ((dimensionAllowance (I := Fin m) (J := Fin n))^20) + (profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) x))) ↔ + physicalAdjacent r c ((dimensionAllowance (I := Fin m) (J := Fin n))^20) + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) (stateCapacity r c) + (stateCapacity_small r c) x y := by + rw [codeNeighbors,List.mem_dedup,List.mem_filter] + have hp := (profileTest_iff r c htotal e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) y)).mpr (physicalProfile_feasible r c y) + change _ ∧ _ ↔ _ + have hc : profileTest (candidateData + (codeCheckData (cellCatalog (paperSmall r c) e) (List.ofFn r) (List.ofFn c) + ((dimensionAllowance (I := Fin m) (J := Fin n))^20) + (profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) x)), + profileCode (paperSmall r c) e (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) y)))=true := hp + simp only [hc,and_true] + rw [mem_rawCodeNeighbors,arithmeticEdge_iff] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed11ac671555e19e024fb97267da5c593188eba6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCodeProposal.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCodeNeighbors +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperLocalProposal + +namespace OAI + +/-! # The compiled neighbor draw has the small-chain proposal law -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def codeNeighborProposal (z : ProfileCheckData×List Bool) : Option (List ℕ×List ℕ) := + listWordChoice (codeNeighbors z.1,z.2) + +def codeNeighborProposalRealizer : Realizer codeNeighborProposal := + composition (pair (composition + (f := fun z : ProfileCheckData×List Bool => z.1) (g := codeNeighbors) + first codeNeighborsRealizer) second) listWordChoiceRealizer + +theorem polynomial_codeNeighborProposal : PolynomialTime codeNeighborProposalRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_codeNeighbors) polynomial_second) + polynomial_listWordChoice + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts FirstSuccess FairBits + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "small" => paperSmall r c +local notation "B" => stateCapacity r c +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "L" => d^12 +local notation "U" => d^20 +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +def stateCode (x : PaperStates r c) : List ℕ×List ℕ := + profileCode small e (physicalProfile small B r c L x) + +def stateCodeData (x : PaperStates r c) : ProfileCheckData := + codeCheckData (cellCatalog small e) (List.ofFn r) (List.ofFn c) U (stateCode r c e x) + +def decodeStateCode (v : List ℕ×List ℕ) : Option (PaperStates r c) := + if v.1.length=q ∧ v.2.length=q then decodeProfile r c (profileOfCode small e v) else none + +lemma decode_stateCode (x : PaperStates r c) : + decodeStateCode r c e (stateCode r c e x)=some x := by + unfold decodeStateCode stateCode + rw [ite_eq_left (by simp only [profileCode,viewList,List.length_ofFn,and_self]),profileOfCode_code] + exact (decodeProfile_eq_some_iff r c _ x).mpr rfl + +lemma stateCode_injective : Function.Injective (stateCode r c e) := by + intro x y h + have he := congrArg (decodeStateCode r c e) h + rw [decode_stateCode,decode_stateCode] at he + exact Option.some.inj he + +theorem decodeStateCode_eq_some_iff (v : List ℕ×List ℕ) (x : PaperStates r c) : + decodeStateCode r c e v=some x ↔ stateCode r c e x=v := by + constructor + · intro h + unfold decodeStateCode at h + split_ifs at h with hlen + have hx := (decodeProfile_eq_some_iff r c _ x).mp h + exact (congrArg (profileCode small e) hx).trans (profileCode_ofCode small e v hlen.1 hlen.2) + · rintro rfl + exact decode_stateCode r c e x + +def codeNeighborStates (x : PaperStates r c) : List (PaperStates r c) := + (codeNeighbors (stateCodeData r c e x)).filterMap (decodeStateCode r c e) + +lemma codeNeighborStates_nodup (x : PaperStates r c) : (codeNeighborStates r c e x).Nodup := by + apply List.Nodup.filterMap + · intro a b y ha hb + exact ((decodeStateCode_eq_some_iff r c e a y).mp ha).symm.trans + ((decodeStateCode_eq_some_iff r c e b y).mp hb) + · exact codeNeighbors_nodup _ + +theorem mem_codeNeighborStates (htotal : (∑ i,r i)=∑ j,c j) (x y : PaperStates r c) : + y∈codeNeighborStates r c e x ↔ physicalAdjacent r c U L B (stateCapacity_small r c) x y := by + simp only [codeNeighborStates,List.mem_filterMap] + constructor + · rintro ⟨v,hv,hy⟩ + have he := (decodeStateCode_eq_some_iff r c e v y).mp hy + rw [←he] at hv + exact (mem_codeNeighbors r c htotal e x y).mp hv + · intro h + exact ⟨stateCode r c e y,(mem_codeNeighbors r c htotal e x y).mpr h,decode_stateCode r c e y⟩ + +lemma codeNeighborStates_length (x : PaperStates r c) : + (codeNeighborStates r c e x).length≤6*d^2 := by + have hq : q≤d := by + calc + q = Fintype.card (Cells small) := by simpa only [Fintype.card_fin] using Fintype.card_congr e + _ ≤ Fintype.card (Fin m×Fin n) := Fintype.card_subtype_le _ + _ ≤ d := by simpa only [Fintype.card_prod] using (dimension_le_allowance (I := Fin m) (J := Fin n)) + have hc : (codeNeighbors (stateCodeData r c e x)).length≤6*q^2 := + codeNeighbors_length _ q (by simp [stateCodeData,codeCheckData,stateCode,profileCode,viewList]) + (by simp [stateCodeData,codeCheckData,stateCode,profileCode,viewList]) + exact (List.length_filterMap_le _ _).trans (hc.trans (by gcongr)) + +lemma codeNeighborStates_codes (x : PaperStates r c) : + (codeNeighborStates r c e x).length≤2^s := by + calc + _ ≤ 6*d^2 := codeNeighborStates_length r c e x + _ ≤ 32*d^2 := Nat.mul_le_mul_right _ (by decide) + _ ≤ 2^s := Nat.le_pow_clog (by decide) _ + +lemma codeNeighbors_decode_total (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) : + ∀ v∈codeNeighbors (stateCodeData r c e x),∃ y,decodeStateCode r c e v=some y := by + intro v hv + have hp := (List.mem_filter.mp (List.mem_dedup.mp hv)).2 + obtain ⟨y,hy⟩ := (profileTest_code_iff r c htotal e v).mp hp + exact ⟨y,(decodeStateCode_eq_some_iff r c e v y).mpr hy⟩ + +private lemma getElem_filterMap_total {A C : Type*} (f : A → Option C) (xs : List A) + (h : ∀ a∈xs,∃ b,f a=some b) (i : ℕ) : + (xs[i]?).bind f=(xs.filterMap f)[i]? := by + induction xs generalizing i with + | nil => simp + | cons a xs ih => + obtain ⟨b,hb⟩ := h a (by simp) + have ht : ∀ a∈xs,∃ b,f a=some b := fun a ha => h a (by simp [ha]) + cases i with + | zero => simp [hb] + | succ i => simpa only [List.getElem?_cons_succ,List.filterMap_cons,hb] using ih ht i + +def decodedCodeProposal (x : PaperStates r c) (bits : Fin s → Bool) : Option (PaperStates r c) := + (codeNeighborProposal (stateCodeData r c e x,List.ofFn bits)).bind (decodeStateCode r c e) + +lemma decodedCodeProposal_apply (x : PaperStates r c) (bits : Fin s → Bool) : + decodedCodeProposal r c e x bits= + (codeNeighborProposal (stateCodeData r c e x,List.ofFn bits)).bind (decodeStateCode r c e) := rfl + +lemma decodedCodeProposal_eq (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) + (bits : Fin s → Bool) : + decodedCodeProposal r c e x bits=listBitDraw (codeNeighborStates r c e x) s bits := by + unfold decodedCodeProposal codeNeighborProposal + rw [listWordChoice_ofFn] + exact getElem_filterMap_total (decodeStateCode r c e) _ + (codeNeighbors_decode_total r c e htotal x) _ + +/-- The implemented binary neighbor choice has exactly the proposal +law used by the already-proved small-chain mixing estimate. -/ +theorem decodedCodeProposal_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin s → Bool)) (decodedCodeProposal r c e x)=smallProposalLaw r c x := by + have he : decodedCodeProposal r c e x=listBitDraw (codeNeighborStates r c e x) s := by + funext bits + exact decodedCodeProposal_eq r c e htotal x bits + rw [he] + apply law_ext_except _ _ none + intro y hy + cases y with + | none => exact False.elim (hy rfl) + | some y => + rw [listBitDraw_mass_decidableEq (inferInstance : DecidableEq (Option (PaperStates r c))) + _ (codeNeighborStates_nodup r c e x) s (codeNeighborStates_codes r c e x) y, + smallProposalLaw_mass_some] + unfold proposalWeights + by_cases hxy : physicalAdjacent r c U L B (stateCapacity_small r c) x y + · have hy := (mem_codeNeighborStates r c e htotal x y).mpr hxy + simp only [ite_eq_left hy,ite_eq_left hxy,smallProposalRat] + · have hy := mt (mem_codeNeighborStates r c e htotal x y).mp hxy + simp only [ite_eq_right hy,ite_eq_right hxy] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionComparison.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9e6e035d88d89e9f3277ec261ca414b8f0d5430 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionComparison.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealKernel +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentApproximation + +namespace OAI + +/-! # Completion approximation through the fixed fibre equivalence -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +variable (a : GridBoundary.Grid (I := Fin q) (4*(dimensionAllowance (I := I) (J := J))^8)) +variable (fallback : (z : PaperStates r c) → PaperFibre r c z) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ +local notation "μB" => finiteBlockLaw r c i₀ j₀ e b h hb a fallback + +theorem finiteReferenceLaw_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (z : PaperStates r c) : + variation (μB z) (idealReferenceLaw r c i₀ j₀ z) ≤ 1/(2:ℚ)^h := by + unfold finiteBlockLaw idealReferenceLaw + rw [variation_equiv] + exact finiteFibreLaw_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger z + +theorem referenceStep_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (x : PaperStates r c) : + variation (completionStepLaw R P (smallProposalLaw r c) μB x) + (completionStepLaw R P (smallProposalLaw r c) (idealReferenceLaw r c i₀ j₀) x) ≤ + 1/(2:ℚ)^h := by + apply completionStep_variation + intro z + exact finiteReferenceLaw_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger z + +theorem finiteTerminalJoint_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (p q' : RationalLaw (PaperStates r c)) : + variation (dependentJointLaw p (finiteFibreLaw r c i₀ j₀ e b h hb a fallback)) + (dependentJointLaw q' (fun z => uniformLaw (α := PaperFibre r c z))) ≤ + variation p q'+1/(2:ℚ)^h := by + apply variation_dependentJoint_uniform + intro z + exact finiteFibreLaw_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger z + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionLaws.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionLaws.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4b369cbbd3192582ddf96a556cbfdae92ee723e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCompletionLaws.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceFiniteDraw + +namespace OAI + +/-! # Actual finite-word completion laws for the implemented small chain -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionCounts FairBits + +lemma dyadicError_cast (n : ℕ) : ((1/(2:ℚ)^n:ℚ):ℝ)=(2:ℝ)^(-(n:ℝ)) := by + simp only [one_div,Rat.cast_inv,Rat.cast_pow,Rat.cast_ofNat, + Real.rpow_neg_natCast,zpow_neg,zpow_natCast] + + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +variable (a : GridBoundary.Grid (I := Fin q) (4*(dimensionAllowance (I := I) (J := J))^8)) +variable (fallback : (z : PaperStates r c) → PaperFibre r c z) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +def finiteFibreLaw (z : PaperStates r c) : RationalLaw (PaperFibre r c z) := + mapLaw (uniformLaw (α := Fin (25*(d+b+h+1)^62) → Bool)) + (completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z)) + +def finiteBlockLaw (z : PaperStates r c) : RationalLaw (Table (R z) (P z)) := + equivLaw (paperReferenceEquiv r c i₀ j₀ z) (finiteFibreLaw r c i₀ j₀ e b h hb a fallback z) + + +def finiteBlockDraw (z : PaperStates r c) + (bits : Fin (25*(d+b+h+1)^62) → Bool) : Table (R z) (P z) := + paperReferenceEquiv r c i₀ j₀ z (completionPaddedDraw r c i₀ j₀ e b h hb a z (fallback z) bits) + +lemma finiteBlockDraw_law (z : PaperStates r c) : + mapLaw (uniformLaw (α := Fin (25*(d+b+h+1)^62) → Bool)) + (finiteBlockDraw r c i₀ j₀ e b h hb a fallback z)= + finiteBlockLaw r c i₀ j₀ e b h hb a fallback z := by + exact mapLaw_equiv_output (paperReferenceEquiv r c i₀ j₀ z) _ _ + + +theorem finiteFibreLaw_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (z : PaperStates r c) : + variation (finiteFibreLaw r c i₀ j₀ e b h hb a fallback z) + (uniformLaw (α := PaperFibre r c z)) ≤ 1/(2:ℚ)^h := by + apply (Rat.cast_le (K := ℝ)).mp + rw [dyadicError_cast] + unfold finiteFibreLaw + rw [completionPaddedDraw_law] + exact completionBooleanDraw_variation r c i₀ j₀ e hPL hCheeger h a z (fallback z) + +theorem finiteBlockLaw_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) + (z : PaperStates r c) : + let _ : Nonempty (Table (R z) (P z)) := ⟨paperReferenceEquiv r c i₀ j₀ z (fallback z)⟩ + variation (finiteBlockLaw r c i₀ j₀ e b h hb a fallback z) + (uniformLaw (α := Table (R z) (P z))) ≤ 1/(2:ℚ)^h := by + let : Nonempty (Table (R z) (P z)) := ⟨paperReferenceEquiv r c i₀ j₀ z (fallback z)⟩ + dsimp only + unfold finiteBlockLaw + rw [←uniform_equiv (paperReferenceEquiv r c i₀ j₀ z),variation_equiv] + exact finiteFibreLaw_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger z + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperComputedCatalog.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperComputedCatalog.lean new file mode 100644 index 0000000000000000000000000000000000000000..8840cbac5e60f341b3c933fca7b5f39bd5f63899 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperComputedCatalog.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCodeProposal +import OAI.Combinatorics.ContingencyTables.Machines.BinaryExchangeProgram + +namespace OAI + +/-! # The small-cell ordering is computed from the encoded margins -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "U" => d^20 +local notation "small" => paperSmall r c + +def computedCatalog : List (ℕ×ℕ) := smallCellCatalog ((List.ofFn r,List.ofFn c),U) + +lemma computedCatalog_nodup : (computedCatalog r c).Nodup := + (cellPairs_nodup (List.ofFn r) (List.ofFn c)).filter _ + +lemma mem_computedCatalog (ij : ℕ×ℕ) : + ij∈computedCatalog r c ↔ ∃ a : Cells small,((a.val.1.val,a.val.2.val):ℕ×ℕ)=ij := by + rw [computedCatalog,mem_smallCellCatalog] + simp only [List.length_ofFn] + constructor + · rintro ⟨hi,hj,hsmall⟩ + let i : Fin m := ⟨ij.1,hi⟩ + let j : Fin n := ⟨ij.2,hj⟩ + have hs : small i j=true := by + apply decide_eq_true + simpa only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,hi,hj,dite_true, + Option.getD_some] using hsmall + exact ⟨⟨(i,j),hs⟩,rfl⟩ + · rintro ⟨a,rfl⟩ + refine ⟨a.val.1.isLt,a.val.2.isLt,?_⟩ + have hs : r a.val.1 (a.val.1.val,a.val.2.val)) h + rw [catalogCell_coordinates,catalogCell_coordinates] at he + exact Fin.ext ((computedCatalog_nodup r c).getElem_inj_iff.mp he) + · intro a + have hm : (a.val.1.val,a.val.2.val)∈computedCatalog r c := + (mem_computedCatalog r c _).mpr ⟨a,rfl⟩ + obtain ⟨i,hi,hval⟩ := List.mem_iff_getElem.mp hm + refine ⟨⟨i,hi⟩,?_⟩ + have he := (catalogCell_coordinates r c ⟨i,hi⟩).trans hval + apply Subtype.ext + exact Prod.ext (Fin.ext (congrArg Prod.fst he)) (Fin.ext (congrArg Prod.snd he)) + +def computedCellEquiv : Fin (computedCatalog r c).length ≃ Cells small := + Equiv.ofBijective (catalogCell r c) (catalogCell_bijective r c) + +/-- The proof-level cell equivalence enumerates exactly the list made +by the polynomial catalog program, in the same order. -/ +theorem computedCellEquiv_catalog : + cellCatalog small (computedCellEquiv r c)=computedCatalog r c := by + apply List.ext_getElem + · simp only [cellCatalog,List.length_ofFn] + · intro i hi hj + simp only [cellCatalog,List.getElem_ofFn] + exact catalogCell_coordinates r c ⟨i,hj⟩ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextBox.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ec10ca8dafeeda827e4fa1a6d23bffb4a45c1cf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextBox.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextTransport +import OAI.Combinatorics.ContingencyTables.Transport.IntegerGraphTruncation + +namespace OAI + +/-! # Literal boxed physical context transport + +Auxiliary defect counts use the actual box and total-degree zero extension. +The energy is exactly the bounded physical exchange graph energy. Endpoint +masses and weighted means remain the literal completion-count sums. +-/ + +namespace ContingencyTables.FirstPaperContextTransport + +open scoped BigOperators Classical Topology +open LargePairEnumeration IntegerWeightedTransport BalancedFamily BalancedBox +open IntegerBoxTruncation + +universe u + +variable {I J C : Type u} [Fintype I] [Fintype J] [Fintype C] [DecidableEq C] + +omit [Fintype C] [DecidableEq C] in +lemma contextHard_nonnegative (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ : C → ℕ) (x : Coordinates Bool Ms → ℕ) : + 0 ≤ contextHard small B r c L Ms e σ x := by + apply ge_of_tendsto (contextSoft_tendsto small B r c L Ms e σ x) + exact Filter.Eventually.of_forall (fun a => contextSoft_nonnegative small B r c L Ms e σ a x) + +/-- The physical contextual transport inequality, with every auxiliary +profile and energy endpoint restricted to the declared box and degree. -/ +theorem context_box_transport (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ mC : C → ℕ) (m z : Bool → ℕ) (R W : ℕ) + (hprefix : InBox mC σ) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hz : InBox m z) (htotal : (∑ i, z i)=R+1) + (H : (Coordinates Bool Ms → ℕ) → ℝ) + (V : Finset (Coordinates Bool Ms → ℕ)) (hV : leafVertices Ms z ⊆ V) + (hs : 0 < oneHole (eliminate Ms (contextHard small B r c L Ms e σ)) z false) + (ht : 0 < oneHole (eliminate Ms (contextHard small B r c L Ms e σ)) z true) : + let f := contextHard small B r c L Ms e σ + let g := truncate f (bounds m Ms) (R+Ms.sum) + let s := oneHole (eliminate Ms f) z false + let t := oneHole (eliminate Ms f) z true + let aux := FactorialSignatures.integerRemovalMatrix (auxiliaryKernel Ms g) z false true + (oneHole (eliminate Ms (fun p => f p*H p)) z false/s- + oneHole (eliminate Ms (fun p => f p*H p)) z true/t)^2 ≤ + (1/s+1/t+2*((W:ℝ)+1)^2*aux/(s*t))* + integerGraphEnergy (V.filter (fun x => InBox (bounds m Ms) x ∧ (∑ i, x i)=R+Ms.sum)) f H := by + have h := integer_box_root_transport_limit Ms + (contextSoft small B r c L Ms e σ) _ H + (contextSoft_tendsto small B r c L Ms e σ) m z R W hlower hupper + (by + filter_upwards [Filter.eventually_ge_atTop (0:ℝ)] with a ha + exact ⟨contextSoft_nonnegative small B r c L Ms e σ a, + contextSoft_slices small B r c L Ms e σ mC m R hprefix a ha hlarge⟩) + hz htotal hs ht V hV + dsimp only at h ⊢ + rw [graphEnergy_truncate V _ H _ _ (contextHard_nonnegative small B r c L Ms e σ)] at h + exact h + +end ContingencyTables.FirstPaperContextTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextChildren.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextChildren.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5d0f88914a78d2a89886696f80662b4bdefd857 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextChildren.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextTransport +import OAI.Combinatorics.ContingencyTables.Transport.IntegerChildLogConcavity + +namespace OAI + +/-! # Child-mass minimum for the actual first-paper context + +Ordinary unexposed pairs are summed with their actual balances before +applying the proved two-coordinate removal inequality and its hard limit. +-/ + +namespace ContingencyTables.FirstPaperContextTransport + +open scoped BigOperators Classical Topology +open LargePairEnumeration IntegerWeightedTransport BalancedFamily BalancedBox + +universe u + +variable {I J C : Type u} [Fintype I] [Fintype J] [Fintype C] [DecidableEq C] + +theorem context_child_minimum (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ mC : C → ℕ) (U : ℕ) (hprefix : InBox mC σ) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) + (hlower : ∀ w ∈ Ms, 2 ≤ w) + (a j b : ℕ) (haj : a ≤ j) (hjb : j ≤ b) (hbU : b ≤ U) : + min (eliminate Ms (contextHard small B r c L Ms e σ) (childProfile U a)) + (eliminate Ms (contextHard small B r c L Ms e σ) (childProfile U b)) ≤ + eliminate Ms (contextHard small B r c L Ms e σ) (childProfile U j) := by + apply child_minimum_limit + (fun α => eliminate Ms (contextSoft small B r c L Ms e σ α)) _ U + (eliminate_tendsto Ms _ _ (contextSoft_tendsto small B r c L Ms e σ)) _ a j b haj hjb hbU + filter_upwards [Filter.eventually_ge_atTop (0:ℝ)] with α hα + have hp := contextSoft_slices small B r c L Ms e σ mC (fun _ => U) U hprefix α hα hlarge + exact eliminate_slices Ms (fun _ => U) U _ hlower hp.1 hp.2 + +end ContingencyTables.FirstPaperContextTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa0878cf70d3262e9adeca70192ac31e9f6f0b7b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperContextTransport.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalMarginal +import OAI.Combinatorics.ContingencyTables.Transport.IntegerContextSlices +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportLimit + +namespace OAI + +/-! # Raw transport for the literal first-paper completion counts + +An actual small-coordinate bijection isolates a fixed balanced prefix, +the special pair, and the remaining ordinary pairs. Large completions +are still the original physical finite sum; the prefix coordinates are +excluded from every exchange in the transport graph. +-/ + +namespace ContingencyTables.FirstPaperContextTransport + +open scoped BigOperators Classical Topology +open FirstPaperPhysicalMarginal LargePairEnumeration IntegerWeightedTransport +open BalancedFamily BalancedBox + +universe u + +variable {I J C : Type u} [Fintype I] [Fintype J] [Fintype C] + [DecidableEq C] + +noncomputable def contextHard (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ : C → ℕ) : (Coordinates Bool Ms → ℕ) → ℝ := + fun x => hardMarginal small B r c L ((Sum.elim σ x) ∘ e.symm) + +noncomputable def contextSoft (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ : C → ℕ) (a : ℝ) : (Coordinates Bool Ms → ℕ) → ℝ := + fun x => softMarginal small B r c L a ((Sum.elim σ x) ∘ e.symm) + +omit [Fintype C] [DecidableEq C] in +theorem contextSoft_nonnegative (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ : C → ℕ) (a : ℝ) (x : Coordinates Bool Ms → ℕ) : + 0 ≤ contextSoft small B r c L Ms e σ a x := by + unfold contextSoft softMarginal + apply Finset.sum_nonneg + intro v _ + exact (NestedPenaltyApplication.softWeight_positive _ _ _ _ _ _ _ _).le + +/-- The two needed slices are obtained from the physical large-cell +marginal's proved raw signature, then by a principal prefix restriction. -/ +theorem contextSoft_slices (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ mC : C → ℕ) (m : Bool → ℕ) (R : ℕ) + (hprefix : InBox mC σ) (a : ℝ) (ha : 0 ≤ a) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) : + PositiveSlice (contextSoft small B r c L Ms e σ a) (bounds m Ms) (R+Ms.sum) ∧ + RemovalSlice (contextSoft small B r c L Ms e σ a) (bounds m Ms) (R+Ms.sum) := by + apply context_slices e (softMarginal small B r c L a) mC σ (bounds m Ms) + (R+Ms.sum) hprefix + · exact (softMarginal_slices small B r c L a ha _ _ hlarge).1 + · exact (softMarginal_slices small B r c L a ha _ _ hlarge).2 + +omit [Fintype C] [DecidableEq C] in + +theorem contextSoft_tendsto (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ : C → ℕ) (x : Coordinates Bool Ms → ℕ) : + Filter.Tendsto (fun a : ℝ => contextSoft small B r c L Ms e σ a x) Filter.atTop + (nhds (contextHard small B r c L Ms e σ x)) := + softMarginal_tendsto small B r c L _ + +/-- Hard transport for the actual padded completion count, with the +prefix fixed and only the two endpoint count sums required positive. -/ +theorem context_transport (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (Ms : List ℕ) + (e : (C ⊕ Coordinates Bool Ms) ≃ SmallView (fun a : I×J => small a.1 a.2)) + (σ mC : C → ℕ) (m z : Bool → ℕ) (R W : ℕ) + (hprefix : InBox mC σ) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hz : InBox m z) (htotal : (∑ i, z i)=R+1) + (H : (Coordinates Bool Ms → ℕ) → ℝ) + (V : Finset (Coordinates Bool Ms → ℕ)) (hV : leafVertices Ms z ⊆ V) + (hs : 0 < oneHole (eliminate Ms (contextHard small B r c L Ms e σ)) z false) + (ht : 0 < oneHole (eliminate Ms (contextHard small B r c L Ms e σ)) z true) : + let f := contextHard small B r c L Ms e σ + let s := oneHole (eliminate Ms f) z false + let t := oneHole (eliminate Ms f) z true + let aux := FactorialSignatures.integerRemovalMatrix (auxiliaryKernel Ms f) z false true + (oneHole (eliminate Ms (fun p => f p*H p)) z false/s - + oneHole (eliminate Ms (fun p => f p*H p)) z true/t)^2 ≤ + (1/s+1/t+2*((W:ℝ)+1)^2*aux/(s*t))*integerGraphEnergy V f H := by + apply integer_root_graph_transport_limit Ms + (contextSoft small B r c L Ms e σ) _ H + (contextSoft_tendsto small B r c L Ms e σ) m z R W hlower hupper + _ hz htotal hs ht V hV + filter_upwards [Filter.eventually_ge_atTop (0:ℝ)] with a ha + exact ⟨contextSoft_nonnegative small B r c L Ms e σ a, + contextSoft_slices small B r c L Ms e σ mC m R hprefix a ha hlarge⟩ + +end ContingencyTables.FirstPaperContextTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCorrectionBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCorrectionBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..062086c234141162e7f1cd09e26e607a73d64b3d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperCorrectionBudget.lean @@ -0,0 +1,47 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters + +namespace OAI + +/-! # Cardinality and rare-branch precision for exact correction -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators +open CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] + +noncomputable def correctionPrecision (r : I → ℕ) (c : J → ℕ) : ℕ := + (dimensionAllowance (I := I) (J := J))^6*(smallBinaryLength r c)^2 + +lemma table_card_binary_bound (r : I → ℕ) (c : J → ℕ) : + Fintype.card (Table r c)≤ + 2^((dimensionAllowance (I := I) (J := J))*smallBinaryLength r c) := by + have hn : (∑ i,r i)+1≤2^(smallBinaryLength r c) := by + apply (show (∑ i,r i)+1 ≤ stateBound r c+1 by unfold stateBound; omega).trans + exact (smallBinaryLength_parameters r c).2.2 + have hdim : Fintype.card I*Fintype.card J≤dimensionAllowance (I := I) (J := J) := by + unfold dimensionAllowance + nlinarith + calc + _ ≤ ((∑ i,r i)+1)^(Fintype.card I*Fintype.card J) := table_card_le r c + _ ≤ (2^(smallBinaryLength r c))^(Fintype.card I*Fintype.card J) := Nat.pow_le_pow_left hn _ + _ = 2^(smallBinaryLength r c*(Fintype.card I*Fintype.card J)) := (pow_mul _ _ _).symm + _ ≤ _ := Nat.pow_le_pow_right (by decide) (by nlinarith) + +lemma table_card_correction_bound (r : I → ℕ) (c : J → ℕ) : + Fintype.card (Table r c)≤2^(correctionPrecision r c) := by + apply (table_card_binary_bound r c).trans + apply Nat.pow_le_pow_right (by decide) + exact Nat.mul_le_mul (Nat.le_self_pow (by decide : 6≠0) _) + (Nat.le_self_pow (by decide : 2≠0) _) + +lemma correction_card_mass (r : I → ℕ) (c : J → ℕ) : + (Fintype.card (Table r c):ℚ)*(1/(2:ℚ)^(correctionPrecision r c))≤1 := by + rw [mul_one_div] + apply (div_le_one (by positivity)).mpr + exact_mod_cast table_card_correction_bound r c + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperExposureVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperExposureVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..301210ee17a827d316103fb1d3618f7a5d95ea10 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperExposureVariance.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextChildVariance +import OAI.Combinatorics.ContingencyTables.Transport.RowMajorEnumeration + +namespace OAI + +/-! # The actual first-paper per-context exposure variance bound -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open LargePairEnumeration BalancedFamily BalancedBox IntegerWeightedTransport +open FirstPaperProfiles FirstPaperContextTransport FirstPaperPhysicalMarginal +open PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma later_card_le_allowance (small : I → J → Bool) (s : I×J) {n : ℕ} + (e : Fin n ≃ Later small s) : n ≤ dimensionAllowance (I := I) (J := J) := by + have hn : n=Fintype.card (Later small s) := by + simpa only [Fintype.card_fin] using Fintype.card_congr e + rw [hn] + exact (Fintype.card_le_of_injective (fun a : Later small s => a.val) Subtype.val_injective).trans + ((RowMajorEnumeration.small_card_le_dimension small).trans dimension_le_allowance) + +lemma exposure_coefficient (U n d : ℕ) (hd : 1 ≤ d) (hn : n ≤ d) : + ((U:ℝ)+1)^4*(2+2*n*((U:ℝ)+1)^2) ≤ 4*d*((U:ℝ)+1)^6 := by + have hn' : (n:ℝ) ≤ d := by exact_mod_cast hn + have hd' : (1:ℝ) ≤ d := by exact_mod_cast hd + have hq : (1:ℝ) ≤ ((U:ℝ)+1)^2 := by nlinarith [Nat.cast_nonneg (α := ℝ) U] + have hdq : (1:ℝ) ≤ d*((U:ℝ)+1)^2 := hq.trans (by + simpa only [one_mul] using mul_le_mul_of_nonneg_right hd' (sq_nonneg ((U:ℝ)+1))) + have hnum : (2:ℝ)+2*n*((U:ℝ)+1)^2 ≤ 4*d*((U:ℝ)+1)^2 := by + have hh := mul_le_mul_of_nonneg_right hn' (sq_nonneg ((U:ℝ)+1)) + nlinarith + calc + _ ≤ ((U:ℝ)+1)^4*(4*d*((U:ℝ)+1)^2) := + mul_le_mul_of_nonneg_left hnum (by positivity) + _ = _ := by ring + +/-- The literal source parameters discharge the box, capacity and +signature-side conditions. The only remaining conditions describe the +chosen bounded prefix and a positive-mass exposure context. -/ +theorem firstPaper_exposure_variance (r : I → ℕ) (c : J → ℕ) + (s : I×J) (hs : paperSmall r c s.1 s.2=true) (σ : I×J → ℕ) + (hσ : ∀ a : Earlier (paperSmall r c) s, + σ a.val.val ≤ (dimensionAllowance (I := I) (J := J))^20) + {n : ℕ} (e : Fin n ≃ Later (paperSmall r c) s) + (H : (Coordinates Bool (widths (fun _ : Fin n => (dimensionAllowance (I := I) (J := J))^20)) → ℕ) → ℝ) + (hZ : 0 < ∑ j : Fin ((dimensionAllowance (I := I) (J := J))^20+1), + eliminate (widths (fun _ : Fin n => (dimensionAllowance (I := I) (J := J))^20)) + (contextHard (paperSmall r c) + (paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20)) + r c ((dimensionAllowance (I := I) (J := J))^12) _ + (contextEquiv (paperSmall r c) s hs e ((dimensionAllowance (I := I) (J := J))^20)) + (prefixRaw (paperSmall r c) s σ ((dimensionAllowance (I := I) (J := J))^20))) + (childProfile ((dimensionAllowance (I := I) (J := J))^20) j.val)) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c (d^12) Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let z := fun j => eliminate Ms f (childProfile U j) + let μ := fun j => eliminate Ms (fun p => f p*H p) (childProfile U j)/z j + let E := integerGraphEnergy ((contextVertices U n).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum)) f H + (∑ j : Fin (U+1), z j.val*(μ j.val- + (∑ k : Fin (U+1),z k.val*μ k.val)/(∑ k : Fin (U+1),z k.val))^2) ≤ + 4*d*((U:ℝ)+1)^6*E := by + dsimp only + have hd : 2 ≤ dimensionAllowance (I := I) (J := J) := by unfold dimensionAllowance; omega + have hU : 2 ≤ (dimensionAllowance (I := I) (J := J))^20 := + hd.trans (Nat.le_self_pow (by decide) _) + have hv := physical_child_variance (paperSmall r c) + (paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20)) + r c _ s hs σ _ hU + (fun i j hij => by simp only [paperCapacity,hij,ite_true]) + (fun i j hij => by simp only [paperCapacity,hij,Bool.false_eq_true,ite_false]; omega) + hσ e (paper_residual_capacity r c _ _ _ dimension_le_allowance) H hZ + dsimp only at hv + refine hv.trans (mul_le_mul_of_nonneg_right + (exposure_coefficient _ n _ (by omega) (later_card_le_allowance _ s e)) ?_) + exact graphEnergy_nonnegative _ _ _ (contextHard_nonnegative _ _ r c _ _ _ _) + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFeasibility.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFeasibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..e87235b5f843014fa32717be7ae306f2978084dc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFeasibility.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalOriginalResiduals +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInitialization + +namespace OAI + +/-! # Arithmetic tests for the positive small-profile state space + +Feasibility is decided by coordinate bounds, the allowed local pattern, +and residual margin equations. No completion count is evaluated. +-/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open PhysicalCompletionFibres SmallContextFibres FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions FirstPaperProfiles + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +omit [LinearOrder I] [LinearOrder J] in +/-- Equal residual totals and zero margins outside a rectangle suffice +for a supported completion, including empty row or column types. -/ +lemma supported_completion_nonempty (small : I → J → Bool) + (p : I → Prop) (q : J → Prop) + (hrect : ∀ i j,small i j=false ↔ p i ∧ q j) + (R : I → ℕ) (C : J → ℕ) (ht : (∑ i,R i)=∑ j,C j) + (hR : ∀ i,¬p i → R i=0) (hC : ∀ j,¬q j → C j=0) : + Nonempty (LargeCompletion small R C) := by + obtain ⟨A⟩ : Nonempty (Table R C) := ⟨GreedyFeasibleTable.reindexed R C ht⟩ + refine ⟨⟨A,?_⟩⟩ + intro i j hs + by_cases hi : p i + · have hj : ¬q j := by + intro hj + exact Bool.noConfusion (hs.symm.trans ((hrect i j).mpr ⟨hi,hj⟩)) + have he : A.val i j ≤ C j := by + rw [←A.property.2 j] + exact Finset.single_le_sum (f := fun k => A.val k j) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + exact Nat.eq_zero_of_le_zero (he.trans_eq (hC j hj)) + · have he : A.val i j ≤ R i := by + rw [←A.property.1 i] + exact Finset.single_le_sum (f := fun k => A.val i k) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + exact Nat.eq_zero_of_le_zero (he.trans_eq (hR i hi)) + +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "U" => d^20 +local notation "L" => d^12 +local notation "small" => paperSmall r c +local notation "B" => stateCapacity r c + +/-- Padded residual margins can be computed before establishing feasibility. -/ +def profileRows (z : SmallProfile small) (i : I) : ℕ := + r i-smallRow small (smallView small z false) i+rowLargeCount small i*L + +def profileColumns (z : SmallProfile small) (j : J) : ℕ := + c j-smallColumn small B (smallView small z true) j+columnLargeCount small j*L + +/-- Each field is a finite integer test on the candidate profile. -/ +structure ProfileFeasible (z : SmallProfile small) : Prop where + bounded : ∀ a,z a ≤ B a.1.val.1 a.1.val.2 + pattern : Pattern small B z + residuals : OriginalResidualsNonnegative small B (smallView small z false) (smallView small z true) r c + rows_outside : ∀ i,¬U ≤ r i → profileRows r c z i=0 + columns_outside : ∀ j,¬U ≤ c j → profileColumns r c z j=0 + totals : (∑ i,profileRows r c z i)=∑ j,profileColumns r c z j + +omit [LinearOrder I] [LinearOrder J] in +lemma profile_capacity (z : SmallProfile small) : + ∀ i j,small i j=false → (∑ k,profileRows r c z k) ≤ B i j := + paper_capacity_excludes_none small (smallView small z false) r d L U dimension_le_allowance + +lemma physicalProfile_feasible (x : PaperStates r c) : + ProfileFeasible r c (physicalProfile small B r c L x) := by + have hcap := profile_capacity r c (physicalProfile small B r c L x) + exact ⟨naturalProfile_bounded x.val.val,x.val.property, + physical_original_residuals small B r c L x hcap, + physical_residual_row_zero r c U L B x hcap, + physical_residual_column_zero r c U L B x hcap, + physical_residual_totals small B r c L x hcap⟩ + +/-- A passing arithmetic test constructs a completion by the greedy +rectangle algorithm, proving that its weight is strictly positive. -/ +lemma profileFeasible_positive (z : SmallProfile small) (h : ProfileFeasible r c z) : + 0 < hardMarginal small B r c L z := by + have hne := supported_completion_nonempty small + (fun i => U ≤ r i) (fun j => U ≤ c j) (firstPaperSmall_false_iff r c U) + (profileRows r c z) (profileColumns r c z) h.totals h.rows_outside h.columns_outside + have hc := hardMarginal_eq_completionCount small B r c L z h.bounded (profile_capacity r c z) + rw [ite_eq_left h.residuals] at hc + rw [hc] + exact Nat.cast_pos.mpr (Fintype.card_pos_iff.mpr hne) + +/-- The successful integer tests recover an actual state without +searching the completion space. -/ +def stateOfFeasible (z : SmallProfile small) (h : ProfileFeasible r c z) : PaperStates r c := + ⟨⟨(fun a => ⟨z a,Nat.lt_succ_of_le (h.bounded a)⟩),h.pattern⟩, + profileFeasible_positive r c z h⟩ + +lemma stateOfFeasible_profile (z : SmallProfile small) (h : ProfileFeasible r c z) : + physicalProfile small B r c L (stateOfFeasible r c z h)=z := rfl + +/-- This is the complete test for membership in the chain's state space. -/ +theorem profileFeasible_iff (z : SmallProfile small) : + ProfileFeasible r c z ↔ ∃ x : PaperStates r c,physicalProfile small B r c L x=z := by + constructor + · intro h + exact ⟨stateOfFeasible r c z h,rfl⟩ + · rintro ⟨x,rfl⟩ + exact physicalProfile_feasible r c x + +/-- Failed candidates are discarded. Passing candidates retain all +completion multiplicity through the original physical state type. -/ +def decodeProfile (z : SmallProfile small) : Option (PaperStates r c) := + if h : ProfileFeasible r c z then some (stateOfFeasible r c z h) else none + +lemma decodeProfile_eq_some_iff (z : SmallProfile small) (x : PaperStates r c) : + decodeProfile r c z=some x ↔ physicalProfile small B r c L x=z := by + constructor + · intro hx + unfold decodeProfile at hx + split_ifs at hx with h + · have he := Option.some.inj hx + rw [←he] + exact stateOfFeasible_profile r c z h + · intro hx + have h : ProfileFeasible r c z := hx ▸ physicalProfile_feasible r c x + rw [decodeProfile,dite_eq_left h] + congr 1 + apply physicalProfile_injective small B r c L + exact (stateOfFeasible_profile r c z h).trans hx.symm + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFiniteSampler.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFiniteSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8c4bcfd0eae9bacca86f69a3a8cee5258ed1201 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFiniteSampler.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanDraw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBoundedLaw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInitialization +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters + +namespace OAI + +/-! # The initialized finite Boolean sampler on a nonempty large rectangle -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CompletionCounts ResidualMixture FirstSuccess FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "b" => smallBinaryLength r c +local notation "s" => smallProposalBits (I := I) (J := J) + +/-- The exact number of independent input bits used by the initialized +finite experiment. The physical simulation has additional operation cost. -/ +abbrev finiteSamplerBits (k : ℕ) : ℕ := + let h := outerAccuracy d b k + let n := outerSteps d b k + let f := 25*(d+b+h+1)^62 + outerTrials d k*(n*(s+f)+f) + +/-- Greedy arithmetic supplies all feasible fallbacks and the starting +state. Each word returns a member of the original margin fibre. -/ +def initializedFiniteDraw (k : ℕ) (htotal : (∑ i,r i)=∑ j,c j) + (a : GridBoundary.Grid (I := Fin q) (4*d^8)) + (bits : Fin (finiteSamplerBits r c k) → Bool) : Table r c := + finiteOuterDraw r c i₀ j₀ e b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 a + (greedyFibre r c i₀ j₀) (initialJoint r c htotal).1 (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.reindexed r c htotal) bits + +/-- Conditional accuracy of the entire actual finite-word experiment, +with no assumed sampler, starting state, or completion fallback. -/ +theorem initializedFiniteDraw_variation (k : ℕ) (hk : 1 ≤ k) + (htotal : (∑ i,r i)=∑ j,c j) + (a : GridBoundary.Grid (I := Fin q) (4*d^8)) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.reindexed r c htotal⟩ + (variation (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c k) → Bool)) + (initializedFiniteDraw r c i₀ j₀ e k htotal a)) + (uniformLaw (α := Table r c)):ℝ) ≤ 1/(2:ℝ)^k := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.reindexed r c htotal⟩ + let : Nonempty (PaperStates r c) := ⟨(initialJoint r c htotal).1⟩ + dsimp only + unfold initializedFiniteDraw + rw [finiteOuterDraw_law r c i₀ j₀ e b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 a + (greedyFibre r c i₀ j₀) (initialJoint r c htotal).1 (outerSteps d b k) (outerTrials d k) + (GreedyFeasibleTable.reindexed r c htotal)] + exact boundedOuterLaw_variation r c i₀ j₀ e b k (smallBinaryLength_parameters r c).1 + (smallBinaryLength_parameters r c).2.1 hk (smallBinaryLength_parameters r c).2.2 + a (greedyFibre r c i₀ j₀) hPL hCheeger htotal (initialJoint r c htotal).1 _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFullVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFullVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..652fb8e5649e7d544803f9544bc62c21c8c2b81a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperFullVariance.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairGraph +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperTransversalVariance +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphPoincareBudget + +namespace OAI + +/-! # The source Poincare bound for the full literal physical small graph -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts +open SmallContextEnumeration RowMajorEnumeration FiniteExposureVariance IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- The literal physical encoding consists of the balanced transversal +words and the positive single-defect profiles. Zero-weight transversal +words may be retained; they contribute zero to both variance and energy. -/ +theorem firstPaper_full_variance (r : I → ℕ) (c : J → ℕ) + (H : SmallProfile (paperSmall r c) → ℝ) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let small := paperSmall r c + let B := paperCapacity small r d L U + let hB := fun i j (hij : small i j=true) => show B i j=U by simp only [B,paperCapacity,hij,ite_true] + let w := wordWeight small B r c L U + let v := fun z : PositiveDefects small B r c L => hardMarginal small B r c L (naturalProfile z.val) + let G := wordObservable small U H + let K := fun z : PositiveDefects small B r c L => H (naturalProfile z.val) + variance (Sum.elim w v) (Sum.elim G K) ≤ 770*(d:ℝ)^4*(U:ℝ)^6*fullEnergy r c U L B hB H := by + dsimp only + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let small := paperSmall r c + let B := paperCapacity small r d L U + have hB : ∀ i j,small i j=true → B i j=U := fun i j hij => by simp only [B,paperCapacity,hij,ite_true] + have hcap : ∀ T : ResidualTables small r c (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L),∀ i j,T.val.val i j ≤ B i j := + paper_residual_capacity r c d L U dimension_le_allowance + let E := fullEnergy r c U L B hB H + have hE : 0 ≤ E := fullEnergy_nonnegative r c U L B hB H + have hd : 1 ≤ d := by dsimp only [d]; unfold dimensionAllowance; omega + have hU : 1 ≤ U := hd.trans (Nat.le_self_pow (by decide) _) + have hq : Fintype.card (Cells small) ≤ d := (small_card_le_dimension small).trans dimension_le_allowance + have hT : Fintype.card (Cells small×Cells small) ≤ d^2 := by + simpa only [Fintype.card_prod,pow_two] using Nat.mul_le_mul hq hq + have hvar : variance (wordWeight small B r c L U) (wordObservable small U H) ≤ + 4*(d:ℝ)^2*((U:ℝ)+1)^6*E := by + exact (firstPaper_transversal_variance r c H).trans + (mul_le_mul_of_nonneg_left (physicalEnergy_le_full r c U L B hB H) (by positivity)) + exact variance_repaired_graph_budget (wordWeight small B r c L U) + (fun z : PositiveDefects small B r c L => hardMarginal small B r c L (naturalProfile z.val)) + (wordObservable small U H) (fun z => H (naturalProfile z.val)) + (repairWord r c U L B hB) (defectLabels small B r c L) + (fun a => hardMarginal_nonnegative _ _ _ _ _ _) (fun z => le_of_lt z.property.2) + (repairWord_weight r c U L B hB hcap) (repairWord_type_injective r c U L B hB) + d U hd hU hT E hE hvar (actual_repair_energy_le r c U L B hB hcap H) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..d62fc11308b57700b3930da637777bc7b76024c3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealKernel.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProposal +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCompletionLaws + +namespace OAI + +/-! # Separate identification of the ideal small-state completion experiment -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +/-- The ideal reference draw is transported from the nonempty physical +completion fibre, so no additional existence assumption is needed. -/ +def idealReferenceLaw (z : PaperStates r c) : RationalLaw (Table (R z) (P z)) := + equivLaw (paperReferenceEquiv r c i₀ j₀ z) (uniformLaw (α := PaperFibre r c z)) + +lemma idealReferenceLaw_uniform (z : PaperStates r c) : + let _ : Nonempty (Table (R z) (P z)) := + ⟨paperReferenceEquiv r c i₀ j₀ z (Classical.choice (inferInstance : Nonempty (PaperFibre r c z)))⟩ + idealReferenceLaw r c i₀ j₀ z=uniformLaw (α := Table (R z) (P z)) := by + let : Nonempty (Table (R z) (P z)) := + ⟨paperReferenceEquiv r c i₀ j₀ z (Classical.choice (inferInstance : Nonempty (PaperFibre r c z)))⟩ + dsimp only + exact uniform_equiv (paperReferenceEquiv r c i₀ j₀ z) + +variable [Nonempty (PaperStates r c)] + +theorem smallIdealStep_eq (x : PaperStates r c) : + completionStepLaw R P (smallProposalLaw r c) (idealReferenceLaw r c i₀ j₀) x= + smallTransitionLaw r c i₀ j₀ x := by + let : ∀ z : PaperStates r c,Nonempty (Table (R z) (P z)) := fun z => + ⟨paperReferenceEquiv r c i₀ j₀ z (Classical.choice (inferInstance : Nonempty (PaperFibre r c z)))⟩ + have he : idealReferenceLaw r c i₀ j₀ = + fun z => uniformLaw (α := Table (R z) (P z)) := by + funext z + exact idealReferenceLaw_uniform r c i₀ j₀ z + rw [he] + rw [completionStepLaw_proposal_at R P (smallProposalLaw r c) + (fun _ => proposalLaw (proposalWeights r c x) (proposalWeights_nonnegative r c x) + (proposalWeights_total r c x)) _ x rfl] + apply uniformCompletionStep_eq R P + (proposalWeights r c x) (proposalWeights_nonnegative r c x) + (proposalWeights_total r c x) x (smallTransitionLaw r c i₀ j₀ x) + intro y hy + rw [smallTransitionLaw_mass_ne r c i₀ j₀ x y hy.symm] + unfold smallMoveRat proposalWeights + split_ifs <;> ring + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealRejection.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..218fb822015b52bc3b022c20f4d924fb1b092a4f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperIdealRejection.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessEvent +import OAI.Combinatorics.ContingencyTables.Transport.UniformPartialRejection +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperOuterBudget +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceDrawBounds + +namespace OAI + +/-! # The actual stationary outer rejection law and its polynomial trial budget -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +/-- Read balance and padding, then return the unique unpadded table. -/ +abbrev stateTrial : PaperStateJoint r c → Option (Table r c) := + partialEquivDraw (StateJointSuccess r c) (originalStateSuccessEquiv r c) + +theorem stationary_trial_mass [Nonempty (PaperStates r c)] [Nonempty (Table r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) (X : Table r c) : + successMass (stationaryJointLaw r c i₀ j₀) (stateTrial r c) X= + 1/(Fintype.card (PaperStateJoint r c):ℚ) := by + rw [stationaryJointLaw_uniform] + exact partialEquiv_success_mass _ _ X + +/-- No approximate draw is conditioned on success. Ideal complete trials +have fallback error exactly bounded by their geometric failure tail. -/ +theorem ideal_outer_variation [Nonempty (PaperStates r c)] [Nonempty (Table r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (htotal : ∑ i,r i=∑ j,c j) (fallback : Table r c) (n : ℕ) : + (variation (retryLaw (stationaryJointLaw r c i₀ j₀) (stateTrial r c) fallback n) + (uniformLaw (α := Table r c)):ℝ) ≤ + Real.exp (-(n:ℝ)/(2*(1+(dimensionAllowance (I := I) (J := J):ℝ)^2))) := by + rw [stationaryJointLaw_uniform] + apply uniform_partial_retry_exp (StateJointSuccess r c) (originalStateSuccessEquiv r c) + fallback n (2*(1+(dimensionAllowance (I := I) (J := J):ℝ)^2)) + rw [paperStateJoint_card] + exact stationary_success_ratio r c htotal (reference_dimension_fourteen r c _ i₀ j₀) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperImplementedLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperImplementedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d8a9edf8d63aa0f04730940024cd06e78ecdfc8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperImplementedLaw.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCompletionComparison +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCompletionLaws +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealRejection +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentApproximation + +namespace OAI + +/-! # The implemented small walk and outer rejection have the three stated errors -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [FI : Fintype I] [FJ : Fintype J] [LI : LinearOrder I] [LJ : LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +variable (a : GridBoundary.Grid (I := Fin q) (4*(dimensionAllowance (I := I) (J := J))^8)) +variable (fallback : (z : PaperStates r c) → PaperFibre r c z) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ +local notation "μ" => finiteFibreLaw r c i₀ j₀ e b h hb a fallback +local notation "μB" => finiteBlockLaw r c i₀ j₀ e b h hb a fallback + +def implementedSmallKernel (x : PaperStates r c) : RationalLaw (PaperStates r c) := + completionStepLaw R P (smallProposalLaw r c) μB x + +local notation "Q" => implementedSmallKernel r c i₀ j₀ e b h hb a fallback + +def implementedJointLaw (x : PaperStates r c) (n : ℕ) : RationalLaw (PaperStateJoint r c) := + dependentJointLaw (walkLaw Q x n) μ + +variable [Nonempty (PaperStates r c)] +variable (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) +variable (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) + (4*(dimensionAllowance (I := I) (J := J))^8))) + +include hPL hCheeger + +theorem implementedSmallKernel_variation (x : PaperStates r c) : + variation (Q x) (smallTransitionLaw r c i₀ j₀ x) ≤ 1/(2:ℚ)^h := by + have hv := @referenceStep_variation I J FI FJ LI LJ r c i₀ j₀ q e b h hb a fallback hPL hCheeger x + have hs := congrArg (fun p : RationalLaw (PaperStates r c) => variation (Q x) p) + (smallIdealStep_eq r c i₀ j₀ x) + exact hs ▸ hv + +/-- All adaptive transition errors and the independent terminal draw add +before rejection; the approximate kernel needs no stationarity claim. -/ +theorem implementedJointLaw_variation (x : PaperStates r c) (n : ℕ) : + (variation (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stationaryJointLaw r c i₀ j₀):ℝ) ≤ + ((n:ℝ)+1)/(2:ℝ)^h+((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(n:ℝ)/(d:ℝ)^160) := by + have hj := @finiteTerminalJoint_variation I J FI FJ LI LJ r c i₀ j₀ q e b h hb a fallback hPL hCheeger + (walkLaw Q x n) (smallStationaryLaw r c i₀ j₀) + have hw := walkLaw_variation Q (smallTransitionLaw r c i₀ j₀) (1/(2:ℚ)^h) + (implementedSmallKernel_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger) x n + have ht := variation_triangle (walkLaw Q x n) (smallWalkLaw r c i₀ j₀ x n) + (smallStationaryLaw r c i₀ j₀) + have hh : variation (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stationaryJointLaw r c i₀ j₀) ≤ + ((n:ℚ)+1)*(1/(2:ℚ)^h)+variation (smallWalkLaw r c i₀ j₀ x n) (smallStationaryLaw r c i₀ j₀) := by + change variation (walkLaw Q x n) (smallWalkLaw r c i₀ j₀ x n) ≤ _ at hw + change variation (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stationaryJointLaw r c i₀ j₀) ≤ _ at hj + linarith + have hhR := (Rat.cast_le (K := ℝ)).mpr hh + simp only [Rat.cast_add,Rat.cast_natCast,Rat.cast_one,Rat.cast_div, + Rat.cast_pow,Rat.cast_ofNat,mul_one_div] at hhR + exact hhR.trans (add_le_add_right (smallWalkLaw_variation r c i₀ j₀ x n) _) + +/-- This is the manuscript's three-term bound for the actual finite +completion subroutine, ideal mixing, and first-success fallback. -/ +theorem implementedOuterLaw_variation [Nonempty (Table r c)] + (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) : + (variation (retryLaw (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stateTrial r c) z₀ J₀) (uniformLaw (α := Table r c)):ℝ) ≤ + Real.exp (-(J₀:ℝ)/(2*(1+(d:ℝ)^2)))+ + (J₀:ℝ)*(((n:ℝ)+1)/(2:ℝ)^h+ + ((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(n:ℝ)/(d:ℝ)^160)) := by + have hr := retryLaw_variation (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) + (stationaryJointLaw r c i₀ j₀) (stateTrial r c) z₀ J₀ + have ht := variation_triangle + (retryLaw (implementedJointLaw r c i₀ j₀ e b h hb a fallback x n) (stateTrial r c) z₀ J₀) + (retryLaw (stationaryJointLaw r c i₀ j₀) (stateTrial r c) z₀ J₀) (uniformLaw (α := Table r c)) + have hrR := (Rat.cast_le (K := ℝ)).mpr hr + have htR := (Rat.cast_le (K := ℝ)).mpr ht + simp only [Rat.cast_add,Rat.cast_mul,Rat.cast_natCast] at hrR htR + have hj := mul_le_mul_of_nonneg_left + (implementedJointLaw_variation r c i₀ j₀ e b h hb a fallback hPL hCheeger x n) + (show (0:ℝ) ≤ J₀ by positivity) + have hi := ideal_outer_variation r c i₀ j₀ htotal z₀ J₀ + linarith + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInitialization.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..3cbc7e888ea406ac148b17b6594011fee265f24c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInitialization.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyFeasibleTable +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceFiniteDraw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessEvent + +namespace OAI + +/-! # Concrete initial state and completion fallbacks -/ + +namespace ContingencyTables.GreedyFeasibleTable + +open scoped BigOperators + +/-- Reindex the row/column recursion without changing its arithmetic. -/ +noncomputable def reindexed {I J : Type*} [Fintype I] [Fintype J] + (r : I → ℕ) (c : J → ℕ) (h : (∑ i,r i)=∑ j,c j) : Table r c := + (tableReindex (Fintype.equivFin I).symm (Fintype.equivFin J).symm r c).symm + (table (fun i => r ((Fintype.equivFin I).symm i)) + (fun j => c ((Fintype.equivFin J).symm j)) (by + rw [(Fintype.equivFin I).symm.sum_comp,(Fintype.equivFin J).symm.sum_comp] + exact h)) + +end ContingencyTables.GreedyFeasibleTable + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +/-- The image of a greedily filled original table is an actual positive +small state with its own successful retained completion. -/ +def initialJoint (htotal : (∑ i,r i)=∑ j,c j) : PaperStateJoint r c := + (originalStateSuccessEquiv r c (GreedyFeasibleTable.reindexed r c htotal)).val + +lemma initialJoint_success (htotal : (∑ i,r i)=∑ j,c j) : + StateJointSuccess r c (initialJoint r c htotal) := + (originalStateSuccessEquiv r c (GreedyFeasibleTable.reindexed r c htotal)).property + +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + +/-- A fallback is computed for the current residual margins, then moved +back through the entry-preserving completion equivalence. -/ +def greedyFibre (z : PaperStates r c) : PaperFibre r c z := + (paperReferenceEquiv r c i₀ j₀ z).symm + (GreedyFeasibleTable.reindexed + (referenceRows r c _ _ (stateCapacity r c) i₀ z) + (referenceColumns r c _ _ (stateCapacity r c) j₀ z) + (reference_totals r c _ _ _ i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z))) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInputWordBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInputWordBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c90b82d33dcaa605a284df76010207fbc2de430 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperInputWordBudget.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperWordBudget +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters +import OAI.Combinatorics.ContingencyTables.AlgorithmStatements + +namespace OAI + +/-! # The sampler's bit budget in the original binary input parameters -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators +open CompletionCounts Algorithms + +private lemma scaled_square_pow (a x n : ℕ) : (a*x^2)^n=a^n*x^(2*n) := by + rw [mul_pow,←pow_mul] + +private lemma scaled_square_pow644 (a x : ℕ) : (a*x^2)^644=a^644*x^1288 := by + have h := scaled_square_pow a x 644 + have he : a^644*x^(2*644)=a^644*x^1288 := + congrArg (fun t => a^644*x^t) (by decide) + exact h.trans he + +private lemma power_mono_left (a b e : ℕ) (h : a ≤ b) : a^e ≤ b^e := + Nat.pow_le_pow_left h e + +private lemma word_budget_scaled (d b k a S : ℕ) (hsize : d+b+k+100 ≤ a*S^2) : + smallSamplerWordBudget d b k ≤ a^644*S^1288 := by + calc + _ ≤ (d+b+k+100)^644 := smallSamplerWordBudget_polynomial d b k + _ ≤ (a*S^2)^644 := power_mono_left (d+b+k+100) (a*S^2) 644 hsize + _ = a^644*S^1288 := scaled_square_pow644 a S + +lemma sampling_dimension_bound (m n l k : ℕ) : + dimensionAllowance (I := Fin m) (J := Fin n) ≤ 11*(m+n+l+k+1)^2 := by + let S := m+n+l+k+1 + have hm : m+1 ≤ S := by omega + have hn : n+1 ≤ S := by omega + have hp : (m+1)*(n+1) ≤ S^2 := by simpa only [pow_two] using Nat.mul_le_mul hm hn + have hS : 1 ≤ S^2 := one_le_pow₀ (by omega : 1 ≤ S) + simp only [dimensionAllowance,Fintype.card_fin] + change 10+(m+1)*(n+1) ≤ 11*S^2 + omega + +lemma sampling_internal_size_bound {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : + dimensionAllowance (I := Fin m) (J := Fin n)+smallBinaryLength r c+k+1 ≤ + 245*(samplingSize n r k)^2 := by + let l := Nat.clog 2 ((∑ i,r i)+1) + let S := samplingSize n r k + have hb := smallBinaryLength_le r c + have hd := sampling_dimension_bound m n l k + change dimensionAllowance (I := Fin m) (J := Fin n) ≤ 11*S^2 at hd + have hS : S ≤ S^2 := Nat.le_self_pow (by decide) S + have hk : l+k+3 ≤ 3*S := by dsimp [S,samplingSize,l]; omega + change dimensionAllowance (I := Fin m) (J := Fin n)+smallBinaryLength r c+k+1 ≤ 245*S^2 + omega + +/-- All fixed random-bit segments together have a uniform polynomial +bound in dimensions, binary total margin, and requested accuracy. -/ +theorem sampling_word_budget_polynomial {m n : ℕ} + (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : + smallSamplerWordBudget (dimensionAllowance (I := Fin m) (J := Fin n)) + (smallBinaryLength r c) k ≤ + 344^644*(samplingSize n r k)^1288 := by + have hs : 1 ≤ (samplingSize n r k)^2 := one_le_pow₀ (by unfold samplingSize; omega) + have hi := sampling_internal_size_bound r c k + have hb : dimensionAllowance (I := Fin m) (J := Fin n)+smallBinaryLength r c+k+100 ≤ + 344*(samplingSize n r k)^2 := by omega + exact word_budget_scaled (dimensionAllowance (I := Fin m) (J := Fin n)) + (smallBinaryLength r c) k 344 (samplingSize n r k) hb + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperJointLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperJointLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a0f277b747fa18d1406d9a4db0e0577d5ff9941 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperJointLaw.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreEquiv +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperRationalMixing +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentLaw + +namespace OAI + +/-! # Uniformity of the actual state/completion joint law -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open ResidualMixture FirstSuccess CompletionTranslation SmallContextFibres + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev PaperFibre (r : I → ℕ) (c : J → ℕ) (z : PaperStates r c) := + CompletionFibre (paperSmall r c) (stateCapacity r c) r + (fun i => r i+rowLargeCount (paperSmall r c) i*((dimensionAllowance (I := I) (J := J))^12)) c + (fun j => c j+columnLargeCount (paperSmall r c) j*((dimensionAllowance (I := I) (J := J))^12)) + (physicalProfile _ (stateCapacity r c) r c _ z) + +noncomputable instance paperFibreNonempty (r : I → ℕ) (c : J → ℕ) (z : PaperStates r c) : + Nonempty (PaperFibre r c z) := by + apply Fintype.card_pos_iff.mp + have hp := stateWeight_positive r c z + change 0 < hardMarginal _ _ _ _ _ _ at hp + rw [hardMarginal_eq_fibre_card (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + (physicalProfile _ (stateCapacity r c) r c _ z) (naturalProfile_bounded z.val.val)] at hp + exact_mod_cast hp + +abbrev PaperStateJoint (r : I → ℕ) (c : J → ℕ) := (z : PaperStates r c) × PaperFibre r c z + +lemma paperFibre_card_block (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (z : PaperStates r c) : + Fintype.card (PaperFibre r c z)= + blockCount (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) z := + Fintype.card_congr (referenceFibreEquiv r c _ _ (stateCapacity r c) i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z)) + +noncomputable def stationaryJointLaw (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) : + RationalLaw (PaperStateJoint r c) := + dependentJointLaw (smallStationaryLaw r c i₀ j₀) (fun z => uniformLaw (α := PaperFibre r c z)) + +/-- The law keeps the completion multiplicity exactly: each full pair +has the same probability, including pairs above defective small states. -/ +theorem stationaryJointLaw_uniform (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) : + stationaryJointLaw r c i₀ j₀=uniformLaw (α := PaperStateJoint r c) := by + apply dependentJointLaw_uniform + intro z + simp only [paperFibre_card_block r c i₀ j₀] + rfl + +/-- Cardinality of the full joint space is the small chain normalizer. -/ +theorem paperStateJoint_card (r : I → ℕ) (c : J → ℕ) : + (Fintype.card (PaperStateJoint r c):ℝ)=∑ z,stateWeight r c z := by + rw [Fintype.card_sigma,Nat.cast_sum] + apply Finset.sum_congr rfl + intro z _ + exact (hardMarginal_eq_fibre_card (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + (physicalProfile _ (stateCapacity r c) r c _ z) (naturalProfile_bounded z.val.val)).symm + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalNeighbors.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalNeighbors.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c6725c144a1ccc55de9288a2d6630d792fad1bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalNeighbors.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFeasibility +import OAI.Combinatorics.ContingencyTables.Transport.IntegerExchangeArithmetic +import OAI.Combinatorics.ContingencyTables.Sampling.SmallDefectLabels +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCandidates + +namespace OAI + +/-! # Arithmetic enumeration of the first-paper chain's neighbors + +The list is obtained from ordered coordinate and cell pairs, then filtered +by arithmetic edge and feasibility tests. It never enumerates all states. +-/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open PhysicalCompletionFibres SmallContextFibres FirstPaperProfiles FirstPaperPhysicalMarginal +open CompletionCounts SmallContextCoordinates SmallContextEnumeration +open RowMajorEnumeration IntegerWeightedTransport + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "U" => d^20 +local notation "L" => d^12 +local notation "small" => paperSmall r c +local notation "B" => stateCapacity r c +local notation "profile" => physicalProfile small B r c L + +/-- A directed repair is identified by its two defect cells. -/ +def ArithmeticRepair (v w : SmallProfile small) : Prop := + ∃ st : Cells small×Cells small, + IsDefect (smallView small v false) (smallQ small B v) st.1.val st.2.val ∧ + w=repairedProfile small B v st.1.val st.2.val + +/-- All predicates are bounded integer-coordinate tests. -/ +def ArithmeticEdge (v w : SmallProfile small) : Prop := + (∃ i j,i≠j ∧ 0 small a.1 a.2))= + 2*Fintype.card (Cells small) := by + change Fintype.card (Cells small×Bool)=_ + rw [Fintype.card_prod,Fintype.card_bool] + omega + rw [hcoord] at he + change (localCandidates r c v).card ≤ _ at hs + nlinarith + +/-- Passing candidates are decoded with the arithmetic feasibility test. -/ +def localNeighborList (x : PaperStates r c) : List (PaperStates r c) := + ((localCandidates r c (profile x)).toList.filter + (fun w => ArithmeticEdge r c (profile x) w)).filterMap (decodeProfile r c) + +lemma localNeighborList_nodup (x : PaperStates r c) : + (localNeighborList r c x).Nodup := by + apply List.Nodup.filterMap + · intro a b y ha hb + have hya := (decodeProfile_eq_some_iff r c a y).mp ha + have hyb := (decodeProfile_eq_some_iff r c b y).mp hb + exact hya.symm.trans hyb + · exact (Finset.nodup_toList _).filter _ + +theorem mem_localNeighborList (x y : PaperStates r c) : + y ∈ localNeighborList r c x ↔ + physicalAdjacent r c U L B (stateCapacity_small r c) x y := by + simp only [localNeighborList,List.mem_filterMap,List.mem_filter,Finset.mem_toList, + decide_eq_true_eq] + constructor + · rintro ⟨w,⟨_,he⟩,hy⟩ + have hw := (decodeProfile_eq_some_iff r c w y).mp hy + rw [←hw] at he + exact (arithmeticEdge_iff r c x y).mp he + · intro he + refine ⟨profile y,⟨?_,(arithmeticEdge_iff r c x y).mpr he⟩,?_⟩ + · apply fullNeighbors_local r c U L B (stateCapacity_small r c) (profile x) + exact Finset.mem_image.mpr ⟨(profile x,profile y),Finset.mem_filter.mpr ⟨he,rfl⟩,rfl⟩ + · exact (decodeProfile_eq_some_iff r c _ y).mpr rfl + +theorem localNeighborList_length (x : PaperStates r c) : + (localNeighborList r c x).length ≤ 6*d^2 := by + have h := (List.length_filterMap_le (decodeProfile r c) + ((localCandidates r c (profile x)).toList.filter + (fun w => ArithmeticEdge r c (profile x) w))).trans + (List.length_filter_le _ _) + rw [Finset.length_toList] at h + have hc : Fintype.card (Cells small) ≤ d := + (Fintype.card_subtype_le _).trans ((Fintype.card_prod I J).le.trans dimension_le_allowance) + exact h.trans ((localCandidates_card r c _).trans (by gcongr)) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ef8c8ab61db6ac5e2ee5116e001089aea103739 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperLocalProposal.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperLocalNeighbors +import OAI.Combinatorics.ContingencyTables.Transport.ListBitProposal +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanProposal + +namespace OAI + +/-! # The small-chain proposal through the explicit local neighbor list -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "s" => smallProposalBits (I := I) (J := J) + +lemma localNeighborList_codes (x : PaperStates r c) : + (localNeighborList r c x).length ≤ 2^s := by + calc + _ ≤ 6*d^2 := localNeighborList_length r c x + _ ≤ 32*d^2 := Nat.mul_le_mul_right _ (by decide) + _ ≤ 2^s := Nat.le_pow_clog (by decide) _ + +/-- Binary lookup in the polynomial-length local list. -/ +def localBitProposal (x : PaperStates r c) (bits : Fin s → Bool) : Option (PaperStates r c) := + listBitDraw (localNeighborList r c x) s bits + +/-- The arithmetic enumeration implements exactly the proposal law used +in the accepted-chain and mixing proofs. -/ +theorem localBitProposal_law (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin s → Bool)) (localBitProposal r c x)= + smallProposalLaw r c x := by + apply law_ext_except _ _ none + intro y hy + cases y with + | none => exact False.elim (hy rfl) + | some y => + have h := listBitDraw_mass_decidableEq (inferInstance : DecidableEq (Option (PaperStates r c))) + (localNeighborList r c x) + (localNeighborList_nodup r c x) s (localNeighborList_codes r c x) y + change (mapLaw (uniformLaw (α := Fin s → Bool)) (localBitProposal r c x)).mass (some y)=_ + at h + rw [h,smallProposalLaw_mass_some] + unfold proposalWeights + by_cases hxy : physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x y + · have hy := (mem_localNeighborList r c x y).mpr hxy + simp only [ite_eq_left hy,ite_eq_left hxy,smallProposalRat] + · have hy := mt (mem_localNeighborList r c x y).mp hxy + simp only [ite_eq_right hy,ite_eq_right hxy] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperOuterBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperOuterBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..5449a66bf8673bd3fbb168860665aea89f8e0bad --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperOuterBudget.lean @@ -0,0 +1,156 @@ +import OAI.Combinatorics.ContingencyTables.Parameters +import Mathlib.Analysis.SpecialFunctions.Exp + +namespace OAI + +/-! # The first paper's explicit trial and approximation budgets -/ + +namespace ContingencyTables + +def outerTrials (d k : ℕ) : ℕ := d^4*(k+1) +def outerSteps (d b k : ℕ) : ℕ := d^200*(k+b)^2 +def outerAccuracy (d b k : ℕ) : ℕ := d^4*(k+b)^2 + +lemma two_pow_le_exp_nat (n : ℕ) : (2:ℝ)^n ≤ Real.exp (n:ℝ) := by + have hbase : (2:ℝ) ≤ Real.exp 1 := by linarith [Real.add_one_le_exp (1:ℝ)] + simpa only [← Real.exp_nat_mul,mul_one] using pow_le_pow_left₀ (by norm_num) hbase n + +lemma exp_neg_nat_le_inverse_two_pow (n : ℕ) : + Real.exp (-(n:ℝ)) ≤ 1/(2:ℝ)^n := by + rw [Real.exp_neg] + simpa only [one_div] using one_div_le_one_div_of_le (by positivity) (two_pow_le_exp_nat n) + +lemma outer_failure_error (d k : ℕ) (hd : 14 ≤ d) : + Real.exp (-(outerTrials d k:ℝ)/(2*(1+(d:ℝ)^2))) ≤ 1/(2:ℝ)^(k+2) := by + have hdR : (14:ℝ) ≤ d := by exact_mod_cast hd + have hsq : (196:ℝ) ≤ (d:ℝ)^2 := by nlinarith + have hc : 4*(1+(d:ℝ)^2) ≤ (d:ℝ)^4 := by nlinarith [sq_nonneg ((d:ℝ)^2-2)] + have hm := mul_le_mul_of_nonneg_right hc (show 0 ≤ (k:ℝ)+1 by positivity) + have ht : (k:ℝ)+2 ≤ (outerTrials d k:ℝ)/(2*(1+(d:ℝ)^2)) := by + apply (le_div_iff₀ (by positivity)).mpr + dsimp only [outerTrials] + push_cast + nlinarith [mul_nonneg (show (0:ℝ) ≤ k by positivity) (show 0 ≤ 1+(d:ℝ)^2 by positivity)] + exact (Real.exp_le_exp.mpr (by + rw [neg_div] + push_cast + exact neg_le_neg ht)).trans (exp_neg_nat_le_inverse_two_pow (k+2)) + +lemma outer_mixing_error (d b k C : ℕ) (hd : 14 ≤ d) (hb : d ≤ b) (hk : 1 ≤ k) + (hC : C+1 ≤ 2^b) : + (outerTrials d k:ℝ)*((C+1:ℕ):ℝ)^(2*d)* + Real.exp (-(outerSteps d b k:ℝ)/(d:ℝ)^160) ≤ 1/(2:ℝ)^(k+2) := by + let t : ℝ := (k:ℝ)+b + have ht : 15 ≤ t := by dsimp only [t]; exact_mod_cast (show 15 ≤ k+b by omega) + have hd0 : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hdt : (d:ℝ) ≤ t := by dsimp only [t]; exact_mod_cast (show d ≤ k+b by omega) + have hbt : (b:ℝ) ≤ t := by dsimp only [t]; linarith [Nat.cast_nonneg k (α := ℝ)] + have hkt : (k:ℝ) ≤ t := by dsimp only [t]; linarith [Nat.cast_nonneg b (α := ℝ)] + have hde : (d:ℝ) ≤ Real.exp (d:ℝ) := by linarith [Real.add_one_le_exp (d:ℝ)] + have hke : (k:ℝ)+1 ≤ Real.exp ((k:ℝ)+1) := by + linarith [Real.add_one_le_exp ((k:ℝ)+1)] + have hJ : (outerTrials d k:ℝ) ≤ Real.exp (4*(d:ℝ)+k+1) := by + calc + _ = (d:ℝ)^4*((k:ℝ)+1) := by simp only [outerTrials,Nat.cast_mul,Nat.cast_pow,Nat.cast_add,Nat.cast_one] + _ ≤ (Real.exp (d:ℝ))^4*Real.exp ((k:ℝ)+1) := + mul_le_mul (pow_le_pow_left₀ (by positivity) hde 4) hke (by positivity) (by positivity) + _ = _ := by rw [← Real.exp_nat_mul,← Real.exp_add]; congr 1; norm_num; ring + have hCe : (C+1:ℕ) ≤ Real.exp (b:ℝ) := + (show ((C+1:ℕ):ℝ) ≤ (2:ℝ)^b by exact_mod_cast hC).trans (two_pow_le_exp_nat b) + have hCP : (((C+1:ℕ):ℝ))^(2*d) ≤ Real.exp (2*(d:ℝ)*b) := by + calc + _ ≤ (Real.exp (b:ℝ))^(2*d) := pow_le_pow_left₀ (by positivity) hCe _ + _ = _ := by rw [← Real.exp_nat_mul]; congr 1; push_cast; ring + have hcoef : (3:ℝ) ≤ (d:ℝ)^40 := by + exact_mod_cast ((show 3 ≤ d by omega).trans (Nat.le_self_pow (by decide) d)) + have hdb : (d:ℝ)*b ≤ t^2 := by + have hh := mul_le_mul hdt hbt (by positivity : (0:ℝ) ≤ b) (by linarith : 0 ≤ t) + nlinarith + have hexp : 4*(d:ℝ)+k+1+2*(d:ℝ)*b+((k:ℝ)+2) ≤ (d:ℝ)^40*t^2 := by + have hh := mul_le_mul_of_nonneg_right hcoef (sq_nonneg t) + nlinarith + calc + _ ≤ Real.exp (4*(d:ℝ)+k+1)*Real.exp (2*(d:ℝ)*b)* + Real.exp (-(outerSteps d b k:ℝ)/(d:ℝ)^160) := + mul_le_mul_of_nonneg_right (mul_le_mul hJ hCP (by positivity) (by positivity)) (by positivity) + _ = Real.exp (4*(d:ℝ)+k+1+2*(d:ℝ)*b-(d:ℝ)^40*t^2) := by + rw [← Real.exp_add,← Real.exp_add] + congr 1 + dsimp only [outerSteps,t] + push_cast + field_simp + ring + _ ≤ Real.exp (-((k+2:ℕ):ℝ)) := Real.exp_le_exp.mpr (by push_cast; linarith) + _ ≤ _ := exp_neg_nat_le_inverse_two_pow (k+2) + +lemma nat_pow_le_two_pow (n a : ℕ) : n^a ≤ 2^(n*a) := by + calc + _ ≤ (2^n)^a := Nat.pow_le_pow_left n.lt_two_pow_self.le a + _ = _ := (pow_mul _ _ _).symm + +lemma outer_product_bit_bound (d b k : ℕ) (hd : 14 ≤ d) (hb : d ≤ b) (hk : 1 ≤ k) : + outerTrials d k*(outerSteps d b k+1)*2^(k+2) ≤ 2^(outerAccuracy d b k) := by + let t := k+b + have ht : 15 ≤ t := by dsimp only [t]; omega + have hpT : 1 ≤ outerSteps d b k := by + dsimp only [outerSteps] + have hd0 : 0 < d := by omega + have ht0 : 0 < k+b := by omega + exact Nat.succ_le_of_lt (Nat.mul_pos (pow_pos hd0 _) (pow_pos ht0 _)) + have hJ : outerTrials d k ≤ 2^(4*d+k+1) := by + unfold outerTrials + calc + _ ≤ 2^(d*4)*2^(k+1) := Nat.mul_le_mul (nat_pow_le_two_pow d 4) (k+1).lt_two_pow_self.le + _ = _ := by rw [← pow_add]; congr 1; omega + have hT : outerSteps d b k+1 ≤ 2^(200*d+2*t+1) := by + have hm : outerSteps d b k ≤ 2^(200*d+2*t) := by + unfold outerSteps + calc + _ ≤ 2^(d*200)*2^((k+b)*2) := Nat.mul_le_mul (nat_pow_le_two_pow d 200) + (nat_pow_le_two_pow (k+b) 2) + _ = _ := by rw [← pow_add]; congr 1; dsimp only [t]; omega + calc + _ ≤ 2*outerSteps d b k := by omega + _ ≤ 2*2^(200*d+2*t) := Nat.mul_le_mul_left 2 hm + _ = _ := by rw [pow_succ]; omega + have hexp : (4*d+k+1)+(200*d+2*t+1)+(k+2) ≤ outerAccuracy d b k := by + have hcoef : 209 ≤ d^4 := (by norm_num : 209 ≤ 14^4).trans (Nat.pow_le_pow_left hd 4) + have htq : t ≤ t^2 := Nat.le_self_pow (by decide) t + have hm := Nat.mul_le_mul hcoef htq + have hdt : d ≤ t := by dsimp only [t]; omega + have hkt : k ≤ t := by dsimp only [t]; omega + change _ ≤ d^4*t^2 + omega + calc + _ ≤ (2^(4*d+k+1)*2^(200*d+2*t+1))*2^(k+2) := + Nat.mul_le_mul_right _ (Nat.mul_le_mul hJ hT) + _ = 2^((4*d+k+1)+(200*d+2*t+1)+(k+2)) := by rw [← pow_add,← pow_add] + _ ≤ _ := Nat.pow_le_pow_right (by decide) hexp + +lemma outer_approximation_error (d b k : ℕ) (hd : 14 ≤ d) (hb : d ≤ b) (hk : 1 ≤ k) : + (outerTrials d k:ℝ)*(outerSteps d b k+1)/(2:ℝ)^(outerAccuracy d b k) ≤ + 1/(2:ℝ)^(k+2) := by + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + simp only [one_mul] + exact_mod_cast outer_product_bit_bound d b k hd hb hk + +theorem outer_total_error (d b k C : ℕ) (hd : 14 ≤ d) (hb : d ≤ b) (hk : 1 ≤ k) + (hC : C+1 ≤ 2^b) : + Real.exp (-(outerTrials d k:ℝ)/(2*(1+(d:ℝ)^2)))+ + (outerTrials d k:ℝ)*((C+1:ℕ):ℝ)^(2*d)* + Real.exp (-(outerSteps d b k:ℝ)/(d:ℝ)^160)+ + (outerTrials d k:ℝ)*(outerSteps d b k+1)/(2:ℝ)^(outerAccuracy d b k) ≤ + 1/(2:ℝ)^k := by + have h₁ := outer_failure_error d k hd + have h₂ := outer_mixing_error d b k C hd hb hk hC + have h₃ := outer_approximation_error d b k hd hb hk + have he : 4*(1/(2:ℝ)^(k+2))=1/(2:ℝ)^k := by + rw [pow_add] + norm_num + field_simp + have hp : 0 ≤ 1/(2:ℝ)^(k+2) := by positivity + linarith + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d4f3fc91262023f524af3abab90b4dc75c4022d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalMarginal.lean @@ -0,0 +1,245 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProfiles +import OAI.Combinatorics.ContingencyTables.Transport.NestedReindex + +namespace OAI + +/-! +# The first paper's physical hard marginal and its proved raw signature + +This bridges the finite balanced-pair elimination theorem to the actual +supported padded-completion count, in the original row/column coordinates. +-/ + +namespace ContingencyTables.FirstPaperPhysicalMarginal + +open scoped BigOperators Classical +open LargePairEnumeration PhysicalLargeProfiles FirstPaperProfiles CompletionCounts +open RowColumnPenalties PaddedCompletions NestedPenaltyApplication BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def fullHardFamily (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : (((I×J)×Bool) → ℕ) → ℝ := + hardWeight cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope + +noncomputable def fullSoftFamily (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (a : ℝ) : (((I×J)×Bool) → ℕ) → ℝ := + softWeight cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope a + +noncomputable def hardMarginal (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : ℝ := + ∑ a : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2), + fullHardFamily small B r c L + (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z a) + +noncomputable def softMarginal (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (a : ℝ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : ℝ := + ∑ u : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2), + fullSoftFamily small B r c L a + (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z u) + +private theorem hardMarginal_eq_eliminate (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) {n : ℕ} + (e : Fin n ≃ LargeCell (fun a : I×J => small a.1 a.2)) : + hardMarginal small B r c L= + BalancedFamily.eliminate (widths (fun k => B (e k).val.1 (e k).val.2)) + (fun q => fullHardFamily small B r c L + (q ∘ (physicalCoordinateEquiv (fun a : I×J => small a.1 a.2) e + (fun k => B (e k).val.1 (e k).val.2)).symm)) := by + funext z + symm + rw [eliminate_eq_actual_cells (fun a : I×J => small a.1 a.2) e + (fun k => B (e k).val.1 (e k).val.2) (fullHardFamily small B r c L) z, + sum_joined_eq_physical (fun a : I×J => small a.1 a.2) + (fun a : I×J => B a.1 a.2) e z (fullHardFamily small B r c L)] + unfold hardMarginal + congr 2 + exact Subsingleton.elim _ _ + +private theorem softMarginal_eq_eliminate (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (a : ℝ) {n : ℕ} + (e : Fin n ≃ LargeCell (fun a : I×J => small a.1 a.2)) : + softMarginal small B r c L a= + BalancedFamily.eliminate (widths (fun k => B (e k).val.1 (e k).val.2)) + (fun q => fullSoftFamily small B r c L a + (q ∘ (physicalCoordinateEquiv (fun a : I×J => small a.1 a.2) e + (fun k => B (e k).val.1 (e k).val.2)).symm)) := by + funext z + symm + rw [eliminate_eq_actual_cells (fun a : I×J => small a.1 a.2) e + (fun k => B (e k).val.1 (e k).val.2) (fullSoftFamily small B r c L a) z, + sum_joined_eq_physical (fun a : I×J => small a.1 a.2) + (fun a : I×J => B a.1 a.2) e z (fullSoftFamily small B r c L a)] + unfold softMarginal + congr 2 + exact Subsingleton.elim _ _ + +/-- The literal positive soft count has its raw removal signature on +every required profile box and degree, before taking the hard limit. -/ +theorem softMarginal_slices (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (a : ℝ) (ha : 0≤a) + (m : SmallView (fun a : I×J => small a.1 a.2) → ℕ) (R : ℕ) + (hwidth : ∀ i j, small i j=false → 2≤B i j) : + PositiveSlice (softMarginal small B r c L a) m R ∧ + RemovalSlice (softMarginal small B r c L a) m R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => small a.1 a.2))).symm + let N := fun k => B (e k).val.1 (e k).val.2 + rw [softMarginal_eq_eliminate small B r c L a e] + exact NestedReindex.physical_soft_marginal_slices (widths N) m R + (physicalCoordinateEquiv (fun a : I×J => small a.1 a.2) e N) + cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope a ha + (widths_lower N (fun k => hwidth _ _ (e k).property)) + +theorem softMarginal_tendsto (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) : + Filter.Tendsto (fun a : ℝ => softMarginal small B r c L a z) Filter.atTop + (nhds (hardMarginal small B r c L z)) := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => small a.1 a.2))).symm + simp_rw [softMarginal_eq_eliminate small B r c L _ e, + hardMarginal_eq_eliminate small B r c L e] + apply BalancedFamily.eliminate_tendsto + intro q + exact softWeight_tendsto cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope _ + +theorem hardMarginal_removal (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (m : SmallView (fun a : I×J => small a.1 a.2) → ℕ) (R : ℕ) + (hwidth : ∀ i j, small i j=false → 2≤B i j) : + RemovalSlice (hardMarginal small B r c L) m R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => small a.1 a.2))).symm + let N := fun k => B (e k).val.1 (e k).val.2 + rw [hardMarginal_eq_eliminate small B r c L e] + exact NestedReindex.physical_hard_marginal_removal (widths N) m R + (physicalCoordinateEquiv (fun a : I×J => small a.1 a.2) e N) + cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope + (widths_lower N (fun k => hwidth _ _ (e k).property)) + +theorem hardMarginal_reflected (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (m : SmallView (fun a : I×J => small a.1 a.2) → ℕ) (R : ℕ) + (hwidth : ∀ i j, small i j=false → 2≤B i j) : + RemovalSlice (fun z => hardMarginal small B r c L (IntegerReflection.reflect m z)) m R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => small a.1 a.2))).symm + let N := fun k => B (e k).val.1 (e k).val.2 + rw [hardMarginal_eq_eliminate small B r c L e] + exact NestedReindex.physical_hard_marginal_reflected (widths N) m R + (physicalCoordinateEquiv (fun a : I×J => small a.1 a.2) e N) + cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope + (widths_lower N (fun k => hwidth _ _ (e k).property)) + +/-- The exact finite marginal agrees with the original supported padded +completion count, on its actual capacity box. -/ +theorem hardMarginal_eq_completionCount (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (hz : ∀ u, z u≤B u.1.val.1 u.1.val.2) + (hB : ∀ i j, small i j=false → + (∑ k, (r k-smallRow small (smallView small z false) k+rowLargeCount small k*L))≤B i j) : + hardMarginal small B r c L z= + if OriginalResidualsNonnegative small B (smallView small z false) (smallView small z true) r c + then (Fintype.card (LargeCompletion small + (fun i => r i-smallRow small (smallView small z false) i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B (smallView small z true) j+columnLargeCount small j*L)):ℝ) + else 0 := by + unfold hardMarginal fullHardFamily + rw [physicalHardSum_eq_supported] + apply hard_count_eq + · intro i j hs + simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,false) + · intro i j hs + simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,true) + · exact hB + +@[reducible] noncomputable def paperSmall (r : I → ℕ) (c : J → ℕ) : I → J → Bool := + firstPaperSmall r c (dimensionAllowance (I := I) (J := J)^20) + +noncomputable def firstMarginal (r : I → ℕ) (c : J → ℕ) + (z : SmallView (fun a : I×J => paperSmall r c a.1 a.2) → ℕ) : ℝ := + firstPaperWeight r c (smallView (paperSmall r c) z false) (smallView (paperSmall r c) z true) + +/-- This specializes the finite-count identification to the manuscript's +exact d, d^12 padding, d^20 small capacity and C=N+dL+U+2. -/ +theorem firstMarginal_eq_hard (r : I → ℕ) (c : J → ℕ) + (z : SmallView (fun a : I×J => paperSmall r c a.1 a.2) → ℕ) + (hz : ∀ u, z u≤dimensionAllowance (I := I) (J := J)^20) : + firstMarginal r c z=hardMarginal (paperSmall r c) + (paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + (dimensionAllowance (I := I) (J := J)^12) (dimensionAllowance (I := I) (J := J)^20)) + r c (dimensionAllowance (I := I) (J := J)^12) z := by + have hx : ∀ i j, paperSmall r c i j=true → + smallView (paperSmall r c) z false i j≤dimensionAllowance (I := I) (J := J)^20 := by + intro i j hs + simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,false) + have hy : ∀ i j, paperSmall r c i j=true → + smallView (paperSmall r c) z true i j≤dimensionAllowance (I := I) (J := J)^20 := by + intro i j hs + simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,true) + unfold firstMarginal + rw [← firstPaperHardSum_eq_weight r c _ _ hx hy] + unfold firstPaperHardSum hardMarginal fullHardFamily + exact (physicalHardSum_eq_supported (paperSmall r c) + (paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + (dimensionAllowance (I := I) (J := J)^12) (dimensionAllowance (I := I) (J := J)^20)) + z r c (dimensionAllowance (I := I) (J := J)^12)).symm + +/-- The original supported completion weight inherits its hard-limit raw +signature. It is allowed to vanish; no hard degree positivity is claimed. -/ +theorem firstMarginal_removal (r : I → ℕ) (c : J → ℕ) (R : ℕ) : + RemovalSlice (firstMarginal r c) + (fun _ => dimensionAllowance (I := I) (J := J)^20) R := by + let d := dimensionAllowance (I := I) (J := J) + let small := paperSmall r c + let B := paperCapacity small r d (d^12) (d^20) + have hw : ∀ i j, small i j=false → 2≤B i j := by + intro i j hs + simp only [B,paperCapacity,hs,Bool.false_eq_true,ite_false] + omega + have hs := hardMarginal_removal small B r c (d^12) (fun _ => d^20) R hw + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (fun _ => d^20) z hz (firstMarginal_eq_hard r c)] + exact hs z hz ht + +theorem firstMarginal_reflected (r : I → ℕ) (c : J → ℕ) (R : ℕ) : + RemovalSlice (fun z => firstMarginal r c + (IntegerReflection.reflect (fun _ => dimensionAllowance (I := I) (J := J)^20) z)) + (fun _ => dimensionAllowance (I := I) (J := J)^20) R := by + let d := dimensionAllowance (I := I) (J := J) + let small := paperSmall r c + let B := paperCapacity small r d (d^12) (d^20) + have hw : ∀ i j, small i j=false → 2≤B i j := by + intro i j hs + simp only [B,paperCapacity,hs,Bool.false_eq_true,ite_false] + omega + have hs := hardMarginal_reflected small B r c (d^12) (fun _ => d^20) R hw + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (fun _ => d^20) z hz (by + intro x _ + apply firstMarginal_eq_hard r c + intro u + exact Nat.sub_le _ _)] + exact hs z hz ht + +end ContingencyTables.FirstPaperPhysicalMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..86b24cdc77a21f42888476e063aa916960a8d50d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPhysicalVariance.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFullVariance +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileEncoding + +namespace OAI + +/-! # The Poincare inequality on the actual feasible small states -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal CompletionCounts SmallContextEnumeration FiniteExposureVariance + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev PhysicalStates (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) := + {z : Profiles small B // 0 < hardMarginal small B r c L (naturalProfile z.val)} + +noncomputable instance physicalStatesFintype (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : Fintype (PhysicalStates small B r c L) := by + unfold PhysicalStates + infer_instance + +noncomputable def physicalProfile (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : PhysicalStates small B r c L) : SmallProfile small := + naturalProfile z.val.val + +lemma physicalProfile_injective (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : + Function.Injective (physicalProfile small B r c L) := by + intro x y h + apply Subtype.ext + apply Subtype.ext + exact naturalProfile_injective small B h + +noncomputable def physicalExtension (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (H : PhysicalStates small B r c L → ℝ) : SmallProfile small → ℝ := + Function.extend (physicalProfile small B r c L) H (fun _ => 0) + +lemma physicalExtension_at (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (H : PhysicalStates small B r c L → ℝ) + (z : PhysicalStates small B r c L) : + physicalExtension small B r c L H (physicalProfile small B r c L z)=H z := + (physicalProfile_injective small B r c L).extend_apply H (fun _ => 0) z + +/-- Zero-weight bounded profiles can be removed before applying the +full graph estimate, so this quantifies over every observable on the +actual positive-weight state space. -/ +theorem firstPaper_physical_variance (r : I → ℕ) (c : J → ℕ) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let small := paperSmall r c + let B := paperCapacity small r d L U + let hB := fun i j (hij : small i j=true) => show B i j=U by simp only [B,paperCapacity,hij,ite_true] + ∀ H : PhysicalStates small B r c L → ℝ, + variance (fun z => hardMarginal small B r c L (physicalProfile small B r c L z)) H ≤ + 770*(d:ℝ)^4*(U:ℝ)^6* + fullEnergy r c U L B hB (physicalExtension small B r c L H) := by + dsimp only + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let small := paperSmall r c + let B := paperCapacity small r d L U + have hB : ∀ i j,small i j=true → B i j=U := fun i j hij => by simp only [B,paperCapacity,hij,ite_true] + intro H + let G := physicalExtension small B r c L H + have hext : ∀ z : PhysicalStates small B r c L,G (naturalProfile z.val.val)=H z := + physicalExtension_at small B r c L H + have hv := variance_positive_support + (fun z : Profiles small B => hardMarginal small B r c L (naturalProfile z.val)) + (fun z => G (naturalProfile z.val)) (fun _ => hardMarginal_nonnegative _ _ _ _ _ _) + have hv' : variance (fun z : PhysicalStates small B r c L => + hardMarginal small B r c L (physicalProfile small B r c L z)) H = + variance (fun z : Profiles small B => hardMarginal small B r c L (naturalProfile z.val)) + (fun z => G (naturalProfile z.val)) := by + simpa only [physicalProfile,hext] using hv + rw [hv',← encoding_variance_eq small B r c L U hB G] + exact firstPaper_full_variance r c G + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPreparedProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPreparedProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4ccc7c0d2a85a230313ab620670d21c1e215d50 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperPreparedProposal.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperComputedCatalog + +namespace OAI + +/-! # Preparing the complete proposal input from binary margin lists -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def squareNat : Realizer (fun n : ℕ => n*n) := + composition (pair identity identity) multiply + +lemma polynomial_squareNat : PolynomialTime squareNat := + polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) polynomial_multiply + +def fourthPower : Realizer (fun n : ℕ => n^4) := + (composition squareNat squareNat).congr (by intro n; simp only [Function.comp_apply]; ring) + +lemma polynomial_fourthPower : PolynomialTime fourthPower := + polynomial_congr _ (polynomial_composition polynomial_squareNat polynomial_squareNat) + +def fifthPower : Realizer (fun n : ℕ => n^5) := + (composition (pair fourthPower identity) multiply).congr + (by intro n; simp only [Function.comp_apply,id_eq,pow_succ]) + +lemma polynomial_fifthPower : PolynomialTime fifthPower := + polynomial_congr _ (polynomial_composition + (polynomial_pair polynomial_fourthPower polynomial_identity) polynomial_multiply) + +def twentiethPower : Realizer (fun n : ℕ => n^20) := + (composition fifthPower fourthPower).congr (by + intro n + simp only [Function.comp_apply,←pow_mul]) + +lemma polynomial_twentiethPower : PolynomialTime twentiethPower := + polynomial_congr _ (polynomial_composition polynomial_fifthPower polynomial_fourthPower) + +def marginDimension (z : List ℕ×List ℕ) : ℕ := 10+(z.1.length+1)*(z.2.length+1) + +def marginDimensionRealizer : Realizer marginDimension := + composition (f := fun z : List ℕ×List ℕ => (10,(z.1.length+1)*(z.2.length+1))) + (g := fun z : ℕ×ℕ => z.1+z.2) (pair (constant 10) + (composition (f := fun z : List ℕ×List ℕ => (z.1.length+1,z.2.length+1)) + (g := fun z : ℕ×ℕ => z.1*z.2) + (pair (composition (composition first listLength) successor) + (composition (composition second listLength) successor)) multiply)) add + +theorem polynomial_marginDimension : PolynomialTime marginDimensionRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 10) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_listLength) + polynomial_successor) + (polynomial_composition (polynomial_composition polynomial_second polynomial_listLength) + polynomial_successor)) polynomial_multiply)) polynomial_add + +def marginThreshold (z : List ℕ×List ℕ) : ℕ := (marginDimension z)^20 + +def marginThresholdRealizer : Realizer marginThreshold := + composition (f := marginDimension) (g := fun n : ℕ => n^20) marginDimensionRealizer twentiethPower + +theorem polynomial_marginThreshold : PolynomialTime marginThresholdRealizer := + polynomial_composition polynomial_marginDimension polynomial_twentiethPower + +def marginCatalog (z : List ℕ×List ℕ) : List (ℕ×ℕ) := + smallCellCatalog (z,marginThreshold z) + +def marginCatalogRealizer : Realizer marginCatalog := + composition (pair identity marginThresholdRealizer) smallCellCatalogRealizer + +theorem polynomial_marginCatalog : PolynomialTime marginCatalogRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_marginThreshold) + polynomial_smallCellCatalog + +abbrev RawProfileInput := (List ℕ×List ℕ)×(List ℕ×List ℕ) + +def prepareProfileInput (z : RawProfileInput) : ProfileCheckData := + (((marginCatalog z.1,z.2),z.1),marginThreshold z.1) + +def prepareProfileInputRealizer : Realizer prepareProfileInput := + pair (pair (pair (composition (f := fun z : RawProfileInput => z.1) (g := marginCatalog) first marginCatalogRealizer) second) first) + (composition (f := fun z : RawProfileInput => z.1) (g := marginThreshold) first marginThresholdRealizer) + +theorem polynomial_prepareProfileInput : PolynomialTime prepareProfileInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_marginCatalog) polynomial_second) + polynomial_first) (polynomial_composition polynomial_first polynomial_marginThreshold) + +def preparedProposal (z : RawProfileInput×List Bool) : Option (List ℕ×List ℕ) := + codeNeighborProposal (prepareProfileInput z.1,z.2) + +def preparedProposalRealizer : Realizer preparedProposal := + composition (f := fun z : RawProfileInput×List Bool => (prepareProfileInput z.1,z.2)) + (g := codeNeighborProposal) + (pair (composition (f := fun z : RawProfileInput×List Bool => z.1) + (g := prepareProfileInput) first prepareProfileInputRealizer) second) codeNeighborProposalRealizer + +/-- A single binary program computes the threshold, small-cell catalog, +full neighbor list, and indexed proposal from the supplied margins. -/ +theorem polynomial_preparedProposal : PolynomialTime preparedProposalRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_prepareProfileInput) polynomial_second) + polynomial_codeNeighborProposal + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +lemma marginThreshold_ofFn : + marginThreshold (List.ofFn r,List.ofFn c)= + (dimensionAllowance (I := Fin m) (J := Fin n))^20 := by + simp only [marginThreshold,marginDimension,List.length_ofFn,dimensionAllowance,Fintype.card_fin] + +lemma prepareProfileInput_eq (x : PaperStates r c) : + prepareProfileInput ((List.ofFn r,List.ofFn c),stateCode r c (computedCellEquiv r c) x)= + stateCodeData r c (computedCellEquiv r c) x := by + unfold prepareProfileInput stateCodeData codeCheckData + rw [computedCellEquiv_catalog] + simp only [marginCatalog,marginThreshold_ofFn,computedCatalog] + +theorem preparedProposal_eq (x : PaperStates r c) + (bits : Fin (smallProposalBits (I := Fin m) (J := Fin n)) → Bool) : + (preparedProposal (((List.ofFn r,List.ofFn c),stateCode r c (computedCellEquiv r c) x), + List.ofFn bits)).bind (decodeStateCode r c (computedCellEquiv r c))= + decodedCodeProposal r c (computedCellEquiv r c) x bits := by + have hi := prepareProfileInput_eq r c x + have hp := congrArg (fun z => codeNeighborProposal (z,List.ofFn bits)) hi + have hb := congrArg (fun z => z.bind (decodeStateCode r c (computedCellEquiv r c))) hp + have hd := @decodedCodeProposal_apply m n (computedCatalog r c).length r c + (computedCellEquiv r c) x bits + simpa only [preparedProposal] using hb.trans hd.symm + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProfiles.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProfiles.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f1c62b2207c0009bb30bf9f6bb719657d8cdf17 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProfiles.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalLargeProfiles +import OAI.Combinatorics.ContingencyTables.Transport.CompletionCounts + +namespace OAI + +/-! # The first paper's supported assignments are its physical large choices -/ + +namespace ContingencyTables.FirstPaperProfiles + +open scoped BigOperators Classical +open LargePairEnumeration PhysicalLargeProfiles CompletionCounts + +variable {I J : Type*} + +noncomputable def smallView (small : I → J → Bool) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (v : Bool) (i : I) (j : J) : ℕ := + if hs : small i j=true then z (⟨(i,j),hs⟩,v) else 0 + +/-- A choice for each large cell extends uniquely by zero on small cells, +exactly as used by the manuscript's supported residual completion sum. -/ +noncomputable def supportedAssignmentEquiv (small : I → J → Bool) (B : I → J → ℕ) : + PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) ≃ + Assignment small B where + toFun a := ⟨fun i j => if hs : small i j=true then 0 + else a ⟨(i,j),Bool.eq_false_iff.mpr hs⟩, + by intro i j hs; simp only [hs,dite_eq_left,Fin.val_zero]⟩ + invFun a l := a.val l.val.1 l.val.2 + left_inv a := by + funext l + have hs : small l.val.1 l.val.2=false := l.property + simp [hs] + right_inv a := by + apply Subtype.ext + funext i j + by_cases hs : small i j=true + · apply Fin.ext + simp [hs,a.property i j hs] + · simp [hs] + +lemma physicalProfile_supported (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (a : Assignment small B) : + physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z + ((supportedAssignmentEquiv small B).symm a)= + PaddedCompletions.profile small B (smallView small z false) (smallView small z true) + (assignmentMatrix a) := by + funext u + rcases u with ⟨⟨i,j⟩,v⟩ + by_cases hs : small i j=true + · cases v <;> simp [physicalProfile,hs,PaddedCompletions.profile,smallView] + · cases v <;> simp [physicalProfile,hs,PaddedCompletions.profile, + supportedAssignmentEquiv,assignmentMatrix] <;> rfl + +variable [Fintype I] [Fintype J] + +/-- The finite product used in the signature proof counts exactly the +supported assignments used in the residual completion equivalence. -/ +theorem physicalHardSum_eq_supported (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallView (fun a : I×J => small a.1 a.2) → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : + (∑ a : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2), + NestedPenaltyApplication.hardWeight RowColumnPenalties.cellLine + (RowColumnPenalties.smallCoordinate small) + (RowColumnPenalties.fullOffset B + (fun i => r i+PaddedCompletions.rowLargeCount small i*L) + (fun j => c j+PaddedCompletions.columnLargeCount small j*L)) RowColumnPenalties.viewSlope + (RowColumnPenalties.smallOffset small B r c) RowColumnPenalties.viewSlope + (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z a))= + ∑ a : Assignment small B, + if fullPenalty small B (smallView small z false) (smallView small z true) + (assignmentMatrix a) r c L=0 then (1:ℝ) else 0 := by + apply Fintype.sum_equiv (supportedAssignmentEquiv small B) + intro a + have he := physicalProfile_supported small B z ((supportedAssignmentEquiv small B) a) + rw [Equiv.symm_apply_apply] at he + rw [he] + rfl + +end ContingencyTables.FirstPaperProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..a232e6340b5dc2a924d65849576a59db5f5b7bb3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperProposal.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallKernel +import OAI.Combinatorics.ContingencyTables.Transport.CompletionKernelIdentification + +namespace OAI + +/-! # The explicit small-state proposal realizes the proved ideal kernel -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +local notation "d" => dimensionAllowance (I := I) (J := J) + +def proposalWeights (x y : PaperStates r c) : ℚ := + if physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x y + then smallProposalRat d else 0 + +lemma proposalWeights_nonnegative (x y : PaperStates r c) : 0 ≤ proposalWeights r c x y := by + unfold proposalWeights + split_ifs + · unfold smallProposalRat + positivity + · rfl + +lemma smallProposalRat_cast (n : ℕ) : (smallProposalRat n:ℝ)=smallProposal n := by + simp only [smallProposalRat,smallProposal,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] + +lemma proposalWeights_total (x : PaperStates r c) : ∑ y,proposalWeights r c x y ≤ 1 := by + let Adj := physicalAdjacent r c (d^20) (d^12) (stateCapacity r c) (stateCapacity_small r c) x + have he : (∑ y,proposalWeights r c x y)= + ((Finset.univ.filter Adj).card:ℚ)*smallProposalRat d := by + change (∑ y,if Adj y then smallProposalRat d else 0)=_ + rw [←Finset.sum_filter] + simp only [Finset.sum_const,nsmul_eq_mul] + rw [he] + have hb : ((5*d^2+1:ℕ):ℝ)*smallProposal d ≤ 1/2 := + smallProposal_degree d (by unfold dimensionAllowance; omega) + have hd := physicalAdjacent_degree_allowance r c (d^20) (d^12) + (stateCapacity r c) (stateCapacity_small r c) x + have hp : 0 ≤ smallProposal d := (smallProposal_bounds d (by unfold dimensionAllowance; omega)).1.le + have hh : ((Finset.univ.filter Adj).card:ℝ)*smallProposal d ≤ 1 := + (mul_le_mul_of_nonneg_right (by exact_mod_cast hd) hp).trans (hb.trans (by norm_num)) + apply (Rat.cast_le (K := ℝ)).mp + simpa only [Rat.cast_mul,Rat.cast_natCast,smallProposalRat_cast,Rat.cast_one] using hh + +def smallProposalLaw (x : PaperStates r c) : RationalLaw (Option (PaperStates r c)) := + proposalLaw (proposalWeights r c x) (proposalWeights_nonnegative r c x) (proposalWeights_total r c x) + +lemma smallProposalLaw_mass_some (x y : PaperStates r c) : + (smallProposalLaw r c x).mass (some y)=proposalWeights r c x y := rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperRationalMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperRationalMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..d08e55ccd876059bb8887dd81afbb6c7f41b76fc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperRationalMixing.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallKernel + +namespace OAI + +/-! # Mixing in total variation for the actual rational small-walk law -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts CommonBasesFPRAS + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def smallStationaryRat (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x : PaperStates r c) : ℚ := + (blockCount (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) x:ℚ)/ + ∑ y : PaperStates r c,(blockCount (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) y:ℚ) + +lemma smallStationaryRat_cast (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x : PaperStates r c) : + (smallStationaryRat r c i₀ j₀ x:ℝ)=(paperSmallChain r c i₀ j₀).π x := by + unfold smallStationaryRat + simp only [Rat.cast_div,Rat.cast_sum,Rat.cast_natCast] + rfl + +noncomputable def smallStationaryLaw (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) : RationalLaw (PaperStates r c) where + mass := smallStationaryRat r c i₀ j₀ + nonnegative := fun x => by + have h := (paperSmallChain r c i₀ j₀).positive x + rw [←smallStationaryRat_cast] at h + exact_mod_cast h.le + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum,smallStationaryRat_cast,Rat.cast_one] + exact (paperSmallChain r c i₀ j₀).normalized + +/-- This is the rational finite-walk distribution, rather than a bound +only on real observables of an abstract chain. -/ +theorem smallWalkLaw_variation (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x : PaperStates r c) (n : ℕ) : + (variation (smallWalkLaw r c i₀ j₀ x n) (smallStationaryLaw r c i₀ j₀):ℝ) ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) := by + let C := paperSmallChain r c i₀ j₀ + let δ := ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) + have hpoint (y : PaperStates r c) : |(C.kernel.power n).P x y-C.π y| ≤ C.π y*δ := by + have h := paperSmallChain_point_mixing r c i₀ j₀ n x y + change |C.iterate n (C.pointDensity y) x-1| ≤ δ at h + rw [←C.kernel_power_density] at h + calc + _ = C.π y*|(C.kernel.power n).P x y/C.π y-1| := by + calc + _ = |C.π y*((C.kernel.power n).P x y/C.π y-1)| := by + congr 1 + field_simp [(C.positive y).ne'] + _ = _ := by rw [abs_mul,abs_of_pos (C.positive y)] + _ ≤ _ := mul_le_mul_of_nonneg_left h (C.positive y).le + have hsum := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => hpoint y) + rw [←Finset.sum_mul,C.normalized,one_mul] at hsum + unfold variation + simp only [Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat, + smallWalkLaw_cast,smallStationaryLaw,smallStationaryRat_cast] + change (∑ y,|(C.kernel.power n).P x y-C.π y|)/2 ≤ δ + have hd : 0 ≤ δ := by dsimp only [δ]; positivity + linarith + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..23801a26181ebe0d1a466efe34928191e7d224ed --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallChain.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceEdgeAcceptance +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPaperCapacity +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalSmallEnergy +import OAI.Combinatorics.ContingencyTables.Transport.CompletionEnergyComparison +import OAI.Combinatorics.ContingencyTables.Transport.FiniteChainGraphComparison +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProposal + +namespace OAI + +/-! # The literal first-paper completion chain has the stated Poincare bound -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CommonBasesFPRAS PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts +open CompletionTranslation FiniteExposureVariance + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable abbrev stateCapacity (r : I → ℕ) (c : J → ℕ) : I → J → ℕ := + paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + +abbrev PaperStates (r : I → ℕ) (c : J → ℕ) := + PhysicalStates (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + +/-- Keep one public enumeration instance for the paper's state type, so +rational laws and generic finite kernels share the same index. -/ +noncomputable instance paperStatesFintype (r : I → ℕ) (c : J → ℕ) : + Fintype (PaperStates r c) := + physicalStatesFintype (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + +omit [LinearOrder I] [LinearOrder J] in +lemma stateCapacity_small (r : I → ℕ) (c : J → ℕ) (i : I) (j : J) + (h : paperSmall r c i j=true) : + stateCapacity r c i j=(dimensionAllowance (I := I) (J := J))^20 := by + simp only [stateCapacity,paperCapacity,h,ite_true] + +noncomputable def paperSmallChain (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) : + FiniteChain (PaperStates r c) := + completionChain + (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) + (fun z => reference_totals r c _ _ (stateCapacity r c) i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z)) + (physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (physicalAdjacent_symmetric r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal (dimensionAllowance (I := I) (J := J))) + ((smallProposal_bounds _ (by unfold dimensionAllowance; omega)).1.le) + (5*(dimensionAllowance (I := I) (J := J))^2+1) + (physicalAdjacent_degree_allowance r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal_degree _ (by unfold dimensionAllowance; omega)) + +noncomputable def stateWeight (r : I → ℕ) (c : J → ℕ) (z : PaperStates r c) : ℝ := + hardMarginal (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + (physicalProfile _ (stateCapacity r c) r c _ z) + +noncomputable def stateGraphEnergy (r : I → ℕ) (c : J → ℕ) (H : PaperStates r c → ℝ) : ℝ := + fullEnergy r c ((dimensionAllowance (I := I) (J := J))^20) + ((dimensionAllowance (I := I) (J := J))^12) (stateCapacity r c) + (stateCapacity_small r c) (physicalExtension _ (stateCapacity r c) r c _ H) + +lemma stateWeight_positive (r : I → ℕ) (c : J → ℕ) (z : PaperStates r c) : + 0 < stateWeight r c z := z.property + +lemma paperSmallChain_pi (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (z : PaperStates r c) : + (paperSmallChain r c i₀ j₀).π z=stateWeight r c z/(∑ y,stateWeight r c y) := by + have hw (y : PaperStates r c) := physical_weight_reference_block r c _ _ (stateCapacity r c) + i₀ j₀ y (physical_paper_capacity _ r c _ _ _ dimension_le_allowance y) + change _=hardMarginal _ _ _ _ _ _/(∑ y,hardMarginal _ _ _ _ _ _) + simp_rw [hw] + rfl + +lemma paperSmallChain_energy_lower (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (H : PaperStates r c → ℝ) : + smallProposal (dimensionAllowance (I := I) (J := J))/(2*(∑ z,stateWeight r c z))* + stateGraphEnergy r c H ≤ (paperSmallChain r c i₀ j₀).energy H := by + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let B := stateCapacity r c + let R := referenceRows r c U L B i₀ + let P := referenceColumns r c U L B j₀ + have hcap := physical_paper_capacity (paperSmall r c) r c d L U dimension_le_allowance + have hw (z : PaperStates r c) : stateWeight r c z=(blockCount R P z:ℝ) := + physical_weight_reference_block r c U L B i₀ j₀ z (hcap z) + have hh := completionChain_energy_lower R P + (fun z => reference_totals r c U L B i₀ j₀ z (hcap z)) + (physicalAdjacent r c U L B (stateCapacity_small r c)) + (physicalAdjacent_symmetric r c U L B (stateCapacity_small r c)) + (smallProposal d) ((smallProposal_bounds d (by dsimp [d,dimensionAllowance]; omega)).1.le) + (5*d^2+1) + (physicalAdjacent_degree_allowance r c U L B (stateCapacity_small r c)) + (smallProposal_degree d (by dsimp [d,dimensionAllowance]; omega)) + (reference_edge_acceptance r c U B (stateCapacity_small r c) i₀ j₀ hcap) H + have hE := fullEnergy_physical_eq r c U L B (stateCapacity_small r c) H + change stateGraphEnergy r c H=(∑ x,∑ y, + if physicalAdjacent r c U L B (stateCapacity_small r c) x y then + min (stateWeight r c x) (stateWeight r c y)*(H x-H y)^2 else 0)/2 at hE + rw [hE] + simp_rw [hw] + exact hh + +/-- Every observable on the actual positive completion states satisfies + the source's `d^160` bound, with the actual dyadic proposal probability. -/ +theorem paperSmallChain_poincare (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (H : PaperStates r c → ℝ) : + (paperSmallChain r c i₀ j₀).variance H ≤ + (dimensionAllowance (I := I) (J := J):ℝ)^160*(paperSmallChain r c i₀ j₀).energy H := by + let d := dimensionAllowance (I := I) (J := J) + let K := 770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6 + have hv : variance (stateWeight r c) H ≤ K*stateGraphEnergy r c H := + firstPaper_physical_variance r c H + have hK : 0 ≤ K := by dsimp only [K]; positivity + have hb := smallProposal_bounds d (by dsimp [d,dimensionAllowance]; omega) + have hp := chain_poincare_of_weighted_graph (paperSmallChain r c i₀ j₀) + (stateWeight r c) H (stateWeight_positive r c) (paperSmallChain_pi r c i₀ j₀) + (stateGraphEnergy r c H) K (smallProposal d) hK hb.1 hv + (paperSmallChain_energy_lower r c i₀ j₀ H) + exact hp.trans (mul_le_mul_of_nonneg_right + (smallProposal_poincare_budget d (reference_dimension_ge_fourteen r c _ i₀ j₀)) + ((paperSmallChain r c i₀ j₀).energy_nonneg H)) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2d3b27faeb30ee5c6b35e9c8cf6a163b287eed1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallKernel.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallMixing +import OAI.Combinatorics.ContingencyTables.Transport.RationalChainCast + +namespace OAI + +/-! # The exact rational law of the actual small-state completion chain -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts CommonBasesFPRAS + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def smallProposalRat (d : ℕ) : ℚ := 1/(2:ℚ)^Nat.clog 2 (32*d^2) + +noncomputable def smallMoveRat (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x y : PaperStates r c) : ℚ := + if physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c) x y then + smallProposalRat (dimensionAllowance (I := I) (J := J))* + (acceptedCount (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) x y:ℚ)/ + (blockCount (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) x:ℚ) + else 0 + +noncomputable def smallTransitionRat (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x y : PaperStates r c) : ℚ := + smallMoveRat r c i₀ j₀ x y+if x=y then 1-∑ z,smallMoveRat r c i₀ j₀ x z else 0 + +lemma smallMoveRat_cast (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x y : PaperStates r c) : + (smallMoveRat r c i₀ j₀ x y:ℝ)= + completionMove (referenceRows r c _ _ (stateCapacity r c) i₀) + (referenceColumns r c _ _ (stateCapacity r c) j₀) + (physicalAdjacent r c _ _ (stateCapacity r c) (stateCapacity_small r c)) + (smallProposal (dimensionAllowance (I := I) (J := J))) x y := by + unfold smallMoveRat completionMove + split_ifs + · simp only [Rat.cast_div,Rat.cast_mul,Rat.cast_natCast,smallProposalRat,smallProposal, + Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] + · exact Rat.cast_zero + +lemma smallTransitionRat_cast (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x y : PaperStates r c) : + (smallTransitionRat r c i₀ j₀ x y:ℝ)=(paperSmallChain r c i₀ j₀).P x y := by + unfold smallTransitionRat + dsimp only [paperSmallChain,completionChain,FiniteChain.ofMoves] + by_cases hxy : x=y <;> + simp only [hxy,ite_true,ite_false,Rat.cast_add,Rat.cast_sub,Rat.cast_sum, + Rat.cast_one,Rat.cast_zero,smallMoveRat_cast] + +noncomputable def smallTransitionLaw (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x : PaperStates r c) : RationalLaw (PaperStates r c) where + mass := smallTransitionRat r c i₀ j₀ x + nonnegative := fun y => by + have h := (paperSmallChain r c i₀ j₀).nonnegative x y + rw [← smallTransitionRat_cast] at h + exact_mod_cast h + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum,smallTransitionRat_cast,Rat.cast_one] + exact (paperSmallChain r c i₀ j₀).stochastic x + +lemma smallTransitionLaw_mass_ne (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x y : PaperStates r c) (hxy : x≠y) : + (smallTransitionLaw r c i₀ j₀ x).mass y=smallMoveRat r c i₀ j₀ x y := by + change smallTransitionRat r c i₀ j₀ x y=_ + simp only [smallTransitionRat,hxy,ite_false,add_zero] + +noncomputable def smallWalkLaw (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (x : PaperStates r c) (n : ℕ) : RationalLaw (PaperStates r c) := + walkLaw (smallTransitionLaw r c i₀ j₀) x n + +lemma smallWalkLaw_cast (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (n : ℕ) (x y : PaperStates r c) : + ((smallWalkLaw r c i₀ j₀ x n).mass y:ℝ)= + ((paperSmallChain r c i₀ j₀).kernel.power n).P x y := by + exact walkLaw_cast_kernel (smallTransitionLaw r c i₀ j₀) (paperSmallChain r c i₀ j₀) + (smallTransitionRat_cast r c i₀ j₀) n x y + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ddeb86b0e761919e38557103e97f6d2bc905920 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSmallMixing.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallChain +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalMassBound + +namespace OAI + +/-! # Minimum mass and mixing of the actual small chain -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open CommonBasesFPRAS PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts +open SmallContextFibres + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def stateBound (r : I → ℕ) (_c : J → ℕ) : ℕ := + (∑ i,r i)+(dimensionAllowance (I := I) (J := J))* + ((dimensionAllowance (I := I) (J := J))^12)+ + (dimensionAllowance (I := I) (J := J))^20+2 + +omit [LinearOrder I] [LinearOrder J] in +lemma stateCapacity_le_bound (r : I → ℕ) (c : J → ℕ) (i : I) (j : J) : + stateCapacity r c i j ≤ stateBound r c := by + unfold stateCapacity paperCapacity stateBound + split_ifs <;> omega + +lemma stateWeight_ge_one (r : I → ℕ) (c : J → ℕ) (z : PaperStates r c) : + 1 ≤ stateWeight r c z := by + have he := hardMarginal_eq_fibre_card (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + (physicalProfile _ (stateCapacity r c) r c _ z) (naturalProfile_bounded z.val.val) + change 1 ≤ hardMarginal _ _ _ _ _ _ + rw [he] + have hp := stateWeight_positive r c z + change 0 < hardMarginal _ _ _ _ _ _ at hp + rw [he] at hp + have hn : 0 < Fintype.card (CompletionFibre (paperSmall r c) (stateCapacity r c) r + (fun i => r i+PaddedCompletions.rowLargeCount (paperSmall r c) i* + ((dimensionAllowance (I := I) (J := J))^12)) c + (fun j => c j+PaddedCompletions.columnLargeCount (paperSmall r c) j* + ((dimensionAllowance (I := I) (J := J))^12)) + (physicalProfile _ (stateCapacity r c) r c _ z)) := by exact_mod_cast hp + exact_mod_cast (Nat.succ_le_of_lt hn) + +lemma state_total_mass_le (r : I → ℕ) (c : J → ℕ) : + (∑ z,stateWeight r c z) ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J)) := + physical_total_mass_le (paperSmall r c) (stateCapacity r c) r c _ (stateBound r c) + (stateCapacity_le_bound r c) + +lemma paperSmallChain_pi_lower (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (z : PaperStates r c) : + 1/(((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))) ≤ + (paperSmallChain r c i₀ j₀).π z := by + have hsum : 0 < ∑ y,stateWeight r c y := + Finset.sum_pos (fun y _ => stateWeight_positive r c y) Finset.univ_nonempty + rw [paperSmallChain_pi] + exact (one_div_le_one_div_of_le hsum (state_total_mass_le r c)).trans + (div_le_div_of_nonneg_right (stateWeight_ge_one r c z) hsum.le) + +theorem paperSmallChain_point_mixing (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (n : ℕ) (x y : PaperStates r c) : + let C := paperSmallChain r c i₀ j₀ + |C.iterate n (C.pointDensity y) x-1| ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) := by + have hd : (1:ℝ) ≤ dimensionAllowance (I := I) (J := J) := by + exact_mod_cast (show 1 ≤ dimensionAllowance (I := I) (J := J) by + unfold dimensionAllowance + omega) + have h := (paperSmallChain r c i₀ j₀).point_mixing_exp + ((dimensionAllowance (I := I) (J := J):ℝ)^160) + (1/(((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J)))) + (one_le_pow₀ hd) (by positivity) (paperSmallChain_pi_lower r c i₀ j₀) + (paperSmallChain_poincare r c i₀ j₀) n x y + simpa only [one_div, div_eq_mul_inv, one_mul, inv_inv, mul_comm] using h + +/-- The manuscript's total-variation estimate, for the literal transition +law started at any actual physical state. -/ +theorem paperSmallChain_total_variation (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) + (n : ℕ) (y : PaperStates r c) : + let C := paperSmallChain r c i₀ j₀ + (∑ x,|C.π x*C.iterate n (C.pointDensity y) x-C.π x|)/2 ≤ + ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) := by + let C := paperSmallChain r c i₀ j₀ + let δ := ((stateBound r c+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J))* + Real.exp (-(n:ℝ)/(dimensionAllowance (I := I) (J := J):ℝ)^160) + have hpoint (x : PaperStates r c) : + |C.π x*C.iterate n (C.pointDensity y) x-C.π x| ≤ C.π x*δ := by + calc + _ = C.π x*|C.iterate n (C.pointDensity y) x-1| := by + calc + _ = |C.π x*(C.iterate n (C.pointDensity y) x-1)| := by + congr 1 + ring + _ = _ := by rw [abs_mul,abs_of_pos (C.positive x)] + _ ≤ _ := mul_le_mul_of_nonneg_left (paperSmallChain_point_mixing r c i₀ j₀ n x y) + (C.positive x).le + have hsum := Finset.sum_le_sum (fun x (_ : x ∈ Finset.univ) => hpoint x) + rw [← Finset.sum_mul,C.normalized,one_mul] at hsum + change _ ≤ δ + have hδ : 0 ≤ δ := by dsimp only [δ]; positivity + linarith + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperStationaryMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperStationaryMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..09b19c90c4392d1eacfdad71983079640a07f500 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperStationaryMass.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallMixing +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileEncoding + +namespace OAI + +/-! # Completion-retaining repair bounds the stationary normalizer -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts +open SmallContextEnumeration RowMajorEnumeration FiniteExposureVariance + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma physical_mass_eq_profiles (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : + (∑ z : PhysicalStates small B r c L,hardMarginal small B r c L + (physicalProfile small B r c L z))= + ∑ z : Profiles small B,hardMarginal small B r c L (naturalProfile z.val) := by + apply Fintype.sum_of_injective Subtype.val Subtype.val_injective + · intro z hz + have hn : ¬0 < hardMarginal small B r c L (naturalProfile z.val) := by + intro hp + exact hz ⟨⟨z,hp⟩,rfl⟩ + exact le_antisymm (le_of_not_gt hn) (hardMarginal_nonnegative _ _ _ _ _ _) + · intro z + rfl + +lemma physical_mass_eq_words_defects (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + (∑ z : PhysicalStates small B r c L,hardMarginal small B r c L + (physicalProfile small B r c L z))= + (∑ a,wordWeight small B r c L U a)+ + ∑ z : PositiveDefects small B r c L,hardMarginal small B r c L (naturalProfile z.val) := by + rw [physical_mass_eq_profiles] + have he := Fintype.sum_of_injective (encodeProfile small B r c L U hB) + (encodeProfile_injective small B r c L U hB) + (fun z => hardMarginal small B r c L (naturalProfile (encodeProfile small B r c L U hB z).val)) + (fun z => hardMarginal small B r c L (naturalProfile z.val)) + (outside_encoding_weight_zero small B r c L U hB) (fun _ => rfl) + rw [← he,Fintype.sum_sum_type] + rfl + +/-- The repair preserves all completions and has at most one preimage per +ordered defect label. Thus defect mass costs at most |S| squared. -/ +lemma defect_mass_le_words (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (hcap : ∀ T : ResidualTables (firstPaperSmall r c U) r c + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L),∀ i j,T.val.val i j ≤ B i j) : + (∑ z : PositiveDefects (firstPaperSmall r c U) B r c L, + hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val)) ≤ + (Fintype.card (Cells (firstPaperSmall r c U)×Cells (firstPaperSmall r c U)):ℝ)* + ∑ a,wordWeight (firstPaperSmall r c U) B r c L U a := by + have h := repair_center_mass (wordWeight (firstPaperSmall r c U) B r c L U) + (fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val)) + (fun _ => (1:ℝ)) (repairWord r c U L B hB) (defectLabels _ B r c L) + (fun _ => hardMarginal_nonnegative _ _ _ _ _ _) + (repairWord_weight r c U L B hB hcap) (repairWord_type_injective r c U L B hB) 0 + simpa only [sub_zero,one_pow,mul_one] using h + +/-- The normalizer of the actual small chain is bounded by balanced +completion mass times the manuscript's polynomial defect factor. -/ +theorem state_mass_le_balanced (r : I → ℕ) (c : J → ℕ) : + (∑ z,stateWeight r c z) ≤ + (1+(dimensionAllowance (I := I) (J := J):ℝ)^2)* + ∑ a,wordWeight (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) + ((dimensionAllowance (I := I) (J := J))^20) a := by + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let L := d^12 + let small := paperSmall r c + let B := stateCapacity r c + have hB : ∀ i j,small i j=true → B i j=U := stateCapacity_small r c + have hcap := paper_residual_capacity r c d L U dimension_le_allowance + have hmass := physical_mass_eq_words_defects small B r c L U hB + have hdef := defect_mass_le_words r c U L B hB hcap + have hq : Fintype.card (Cells small) ≤ d := + (small_card_le_dimension small).trans dimension_le_allowance + have hT : (Fintype.card (Cells small×Cells small):ℝ) ≤ (d:ℝ)^2 := by + exact_mod_cast (show Fintype.card (Cells small×Cells small) ≤ d^2 by + simpa only [Fintype.card_prod,pow_two] using Nat.mul_le_mul hq hq) + have hw : 0 ≤ ∑ a,wordWeight small B r c L U a := + Finset.sum_nonneg (fun _ _ => hardMarginal_nonnegative _ _ _ _ _ _) + have hm := mul_le_mul_of_nonneg_right hT hw + change (∑ z : PhysicalStates small B r c L,hardMarginal small B r c L + (physicalProfile small B r c L z)) ≤ (1+(d:ℝ)^2)*∑ a,wordWeight small B r c L U a + rw [hmass] + linarith + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessEvent.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessEvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3736a95602539fbbb887feb54c6bb460c10d3ad --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessEvent.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperJointLaw +import OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreTransport +import OAI.Combinatorics.ContingencyTables.Transport.SuccessfulJointBijection + +namespace OAI + +/-! # The actual joint-law success event counts every original table once -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal FirstPaperProfiles +open SmallContextFibres SmallContextCoordinates SmallContextEnumeration RowMajorEnumeration +open PaddedCompletions CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "small" => paperSmall r c +local notation "B" => stateCapacity r c + +/-- Forget the redundant small-profile coordinate while retaining both +full margin views. This projection is injective on all actual joint pairs. -/ +def stateJointProjection (a : PaperStateJoint r c) := a.2.val + +lemma stateJointProjection_injective : Function.Injective (stateJointProjection r c) := + fibre_projection_injective small B r _ c _ (physicalProfile small B r c (d^12)) + (physicalProfile_injective small B r c (d^12)) + (fun z => naturalProfile_bounded z.val.val) + +def paperJointState (a : PaperJoint r c) : PaperStates r c := by + have hp : 0 < hardMarginal small B r c (d^12) + (rawChoice small (d^20) (wordChoices small (d^20) a.1)) := by + rw [hardMarginal_eq_fibre_card small B r c (d^12) _ + (rawChoice_bounded small B (d^20) (stateCapacity_small r c) _)] + exact_mod_cast Fintype.card_pos_iff.mpr (⟨a.2⟩ : Nonempty _) + exact ⟨encodeProfile small B r c (d^12) (d^20) (stateCapacity_small r c) (.inl a.1),hp⟩ + +def paperJointEmbedding (a : PaperJoint r c) : PaperStateJoint r c := + ⟨paperJointState r c a,a.2⟩ + +lemma paperJointEmbedding_injective : Function.Injective (paperJointEmbedding r c) := by + intro a b hab + apply balancedJointTable_injective small B r c (d^12) (d^20) (stateCapacity_small r c) + apply Subtype.ext + exact congrArg (fun z : PaperStateJoint r c => z.2.val.val.1) hab + +lemma paperJointEmbedding_balanced (a : PaperJoint r c) : + Balanced small B (physicalProfile small B r c (d^12) (paperJointEmbedding r c a).1) := + rawChoice_balanced small B (d^20) (stateCapacity_small r c) _ + +def balancedJointFromState (a : PaperStateJoint r c) + (hb : Balanced small B (physicalProfile small B r c (d^12) a.1)) : PaperJoint r c := + ⟨balancedWord small B (d^20) (stateCapacity_small r c) a.1.val.val, + withProfile (balancedWord_profile small B (d^20) (stateCapacity_small r c) a.1.val.val hb).symm a.2⟩ + +lemma balancedJointFromState_projection (a : PaperStateJoint r c) + (hb : Balanced small B (physicalProfile small B r c (d^12) a.1)) : + (balancedJointFromState r c a hb).2.val=a.2.val := by + exact withProfile_val + (balancedWord_profile small B (d^20) (stateCapacity_small r c) a.1.val.val hb).symm a.2 + +lemma embedding_fromState (a : PaperStateJoint r c) + (hb : Balanced small B (physicalProfile small B r c (d^12) a.1)) : + paperJointEmbedding r c (balancedJointFromState r c a hb)=a := by + apply stateJointProjection_injective r c + exact balancedJointFromState_projection r c a hb + +lemma fromState_embedding (a : PaperJoint r c) : + balancedJointFromState r c (paperJointEmbedding r c a) (paperJointEmbedding_balanced r c a)=a := by + apply paperJointEmbedding_injective r c + exact embedding_fromState r c _ _ + +/-- The success test reads precisely balance and the lower padding bound. -/ +def StateJointSuccess (a : PaperStateJoint r c) : Prop := + Balanced small B (physicalProfile small B r c (d^12) a.1) ∧ + ∀ i j,small i j=false → d^12 ≤ a.2.val.val.1 i j + +abbrev SuccessfulStateJoint := {a : PaperStateJoint r c // StateJointSuccess r c a} + +def successStateEquiv : SuccessfulJoint r c ≃ SuccessfulStateJoint r c where + toFun a := ⟨paperJointEmbedding r c a.val,paperJointEmbedding_balanced r c a.val,a.property⟩ + invFun a := ⟨balancedJointFromState r c a.val a.property.1,a.property.2⟩ + left_inv a := by + apply Subtype.ext + exact fromState_embedding r c a.val + right_inv a := by + apply Subtype.ext + exact embedding_fromState r c a.val a.property.1 + +/-- Every accepted actual state/completion pair unpads to one original +table, and every original table has one such pair. -/ +def originalStateSuccessEquiv : Table r c ≃ SuccessfulStateJoint r c := + (successfulJointEquiv r c).trans (successStateEquiv r c) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessRatio.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessRatio.lean new file mode 100644 index 0000000000000000000000000000000000000000..55f8505adf477f343520d6e186c760f26fd8a276 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperSuccessRatio.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperStationaryMass +import OAI.Combinatorics.ContingencyTables.Transport.BalancedCompletionMass +import OAI.Combinatorics.ContingencyTables.Parameters + +namespace OAI + +/-! # The stationary successful-pair ratio of the first sampler -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open FirstPaperPhysicalMarginal PhysicalCompletionFibres PaddedCompletions CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def paperLarge (r : I → ℕ) (c : J → ℕ) : Finset (I×J) := + Finset.univ.filter (fun p => paperSmall r c p.1 p.2=false) + +lemma large_padding_rows (small : I → J → Bool) (r : I → ℕ) (L : ℕ) : + paddedRows r (largePadding (Finset.univ.filter (fun p : I×J => small p.1 p.2=false)) L)= + (fun i => r i+rowLargeCount small i*L) := by + funext i + unfold paddedRows rowLargeCount + rw [Finset.sum_mul] + congr 1 + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j <;> simp [largePadding,hs] + +lemma large_padding_columns (small : I → J → Bool) (c : J → ℕ) (L : ℕ) : + paddedColumns c (largePadding (Finset.univ.filter (fun p : I×J => small p.1 p.2=false)) L)= + (fun j => c j+columnLargeCount small j*L) := by + funext j + unfold paddedColumns columnLargeCount + rw [Finset.sum_mul] + congr 1 + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j <;> simp [largePadding,hs] + + +lemma paper_padded_count_le (r : I → ℕ) (c : J → ℕ) + (htotal : ∑ i,r i=∑ j,c j) (hd : 14 ≤ dimensionAllowance (I := I) (J := J)) : + (Fintype.card (Table + (fun i => r i+rowLargeCount (paperSmall r c) i*((dimensionAllowance (I := I) (J := J))^12)) + (fun j => c j+columnLargeCount (paperSmall r c) j*((dimensionAllowance (I := I) (J := J))^12))):ℝ) ≤ + 2*(Fintype.card (Table r c):ℝ) := by + let d := dimensionAllowance (I := I) (J := J) + let K := paperLarge r c + have hK : K.card ≤ d := + (Finset.card_filter_le _ _).trans (by simpa only [Finset.card_univ,Fintype.card_prod] using + (dimension_le_allowance (I := I) (J := J))) + have hrow : ∀ p ∈ K,d^20 ≤ r p.1 := by + intro p hp + exact ((firstPaperSmall_false_iff r c _ _ _).mp (Finset.mem_filter.mp hp).2).1 + have hcol : ∀ p ∈ K,d^20 ≤ c p.2 := by + intro p hp + exact ((firstPaperSmall_false_iff r c _ _ _).mp (Finset.mem_filter.mp hp).2).2 + have hr : Fintype.card I ≤ d := by dsimp only [d]; unfold dimensionAllowance; nlinarith + have hc : Fintype.card J ≤ d := by dsimp only [d]; unfold dimensionAllowance; nlinarith + have h := padding_success_half r c htotal K d hd hr hc hK hrow hcol + have htotal' : ∑ i,paddedRows r (largePadding K (d^12)) i= + ∑ j,paddedColumns c (largePadding K (d^12)) j := by + unfold paddedRows paddedColumns + rw [Finset.sum_add_distrib,Finset.sum_add_distrib,htotal,Finset.sum_comm] + have hpos : (0:ℝ) < Fintype.card + (Table (paddedRows r (largePadding K (d^12))) (paddedColumns c (largePadding K (d^12)))) := by + exact_mod_cast Fintype.card_pos_iff.mpr (table_nonempty _ _ htotal') + have hh := (le_div_iff₀ hpos).mp h + simp only [Fintype.card_eq_nat_card] at hh ⊢ + dsimp only [K,paperLarge] at hh + rw [large_padding_rows,large_padding_columns] at hh + change (Nat.card (Table (fun i => r i+rowLargeCount (paperSmall r c) i*d^12) + (fun j => c j+columnLargeCount (paperSmall r c) j*d^12)):ℝ) ≤ 2*Nat.card (Table r c) + linarith + +/-- The numerator counts original tables through the padding bijection; +the denominator counts all actual small-state/completion pairs. -/ +theorem state_mass_le_original_count (r : I → ℕ) (c : J → ℕ) + (htotal : ∑ i,r i=∑ j,c j) (hd : 14 ≤ dimensionAllowance (I := I) (J := J)) : + (∑ z,stateWeight r c z) ≤ + 2*(1+(dimensionAllowance (I := I) (J := J):ℝ)^2)*(Fintype.card (Table r c):ℝ) := by + have h₁ := state_mass_le_balanced r c + have h₂ := word_mass_le_padded_count (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + (stateCapacity_small r c) + have h₃ := paper_padded_count_le r c htotal hd + have h := h₁.trans (mul_le_mul_of_nonneg_left (h₂.trans h₃) (by positivity)) + convert h using 1 + ring + +theorem stationary_success_ratio (r : I → ℕ) (c : J → ℕ) [Nonempty (PaperStates r c)] + (htotal : ∑ i,r i=∑ j,c j) (hd : 14 ≤ dimensionAllowance (I := I) (J := J)) : + 1/(2*(1+(dimensionAllowance (I := I) (J := J):ℝ)^2)) ≤ + (Fintype.card (Table r c):ℝ)/(∑ z,stateWeight r c z) := by + have hm : 0 < ∑ z,stateWeight r c z := + Finset.sum_pos (fun z _ => stateWeight_positive r c z) Finset.univ_nonempty + apply (div_le_div_iff₀ (by positivity) hm).mpr + simpa only [one_mul,mul_comm] using state_mass_le_original_count r c htotal hd + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperTransversalVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperTransversalVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..09518421efd6319e106e6b1b37314cd6df8d7c14 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperTransversalVariance.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Transport.WordContextVariance +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperExposureVariance +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureBudget + +namespace OAI + +/-! # Global transversal variance for the literal first-paper profiles -/ + +namespace ContingencyTables.RowMajorEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open ExcessContextProfiles SmallGraphProfiles FiniteExposureVariance IntegerWeightedTransport +open FirstPaperContextTransport FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +theorem firstPaper_word_context_variance (r : I → ℕ) (c : J → ℕ) + (k : Fin (Fintype.card (Cells (paperSmall r c)))) + (τ : Fin k.val → Fin ((dimensionAllowance (I := I) (J := J))^20+1)) + (H : SmallProfile (paperSmall r c) → ℝ) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + let w := wordWeight small B r c (d^12) U + let G := wordObservable small U H + let cw := fun j : Fin (U+1) => fibreWeight + (fibreWeight w (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j + let σ := prefixExtension small (enumeration small k).val U (earlierWordChoices small U k τ) + variance (fun j => ∑ a,cw j a) (fun j => mean (cw j) G) ≤ + 4*d*((U:ℝ)+1)^6* + physicalContextEnergy small B (enumeration small k).val σ (hardMarginal small B r c (d^12)) H := by + dsimp only + have hd : 2 ≤ dimensionAllowance (I := I) (J := J) := by unfold dimensionAllowance; omega + have hU : 2 ≤ (dimensionAllowance (I := I) (J := J))^20 := + hd.trans (Nat.le_self_pow (by decide) _) + have hv := word_context_variance (paperSmall r c) + (paperCapacity (paperSmall r c) r (dimensionAllowance (I := I) (J := J)) + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20)) + r c _ _ hU + (fun i j hij => by simp only [paperCapacity,hij,ite_true]) + (fun i j hij => by simp only [paperCapacity,hij,Bool.false_eq_true,ite_false]; omega) + (paper_residual_capacity r c _ _ _ dimension_le_allowance) k τ H + dsimp only at hv + refine hv.trans (mul_le_mul_of_nonneg_right + (exposure_coefficient _ _ _ (by omega) + (later_card_le_allowance _ _ (laterEnumeration (paperSmall r c) k))) ?_) + exact physicalContextEnergy_nonnegative _ _ _ _ _ H (hardMarginal_nonnegative _ _ r c _) + +lemma firstPaper_prefixContribution_le (r : I → ℕ) (c : J → ℕ) + (k : Fin (Fintype.card (Cells (paperSmall r c)))) + (H : SmallProfile (paperSmall r c) → ℝ) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + prefixContribution (wordWeight small B r c (d^12) U) (wordObservable small U H) k ≤ + 4*d*((U:ℝ)+1)^6*physicalEnergy small B (hardMarginal small B r c (d^12)) H := by + dsimp only + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + let K : ℝ := 4*d*((U:ℝ)+1)^6 + let E := fun τ : Earlier small (enumeration small k).val → Fin (U+1) => + physicalContextEnergy small B (enumeration small k).val + (prefixExtension small (enumeration small k).val U τ) (hardMarginal small B r c (d^12)) H + have hs : (∑ τ : Fin k.val → Fin (U+1),E (earlierWordChoices small U k τ))=∑ τ,E τ := by + apply Fintype.sum_equiv (earlierWordChoices small U k) + intro τ + rfl + calc + _ ≤ ∑ τ : Fin k.val → Fin (U+1),K*E (earlierWordChoices small U k τ) := by + unfold prefixContribution partitionContribution + apply Finset.sum_le_sum + intro τ _ + exact firstPaper_word_context_variance r c k τ H + _ = K*∑ τ,E τ := by rw [← Finset.mul_sum,hs] + _ ≤ _ := mul_le_mul_of_nonneg_left + (sum_physicalContextEnergy_le small B (enumeration small k).val U + (fun i j hij => by simp only [B,paperCapacity,hij,ite_true]) + (hardMarginal small B r c (d^12)) H (hardMarginal_nonnegative _ _ _ _ _)) (by positivity) + +/-- Actual first-paper balanced choices, weighted by every physical +large completion, satisfy the paper's global transversal variance bound. -/ +theorem firstPaper_transversal_variance (r : I → ℕ) (c : J → ℕ) + (H : SmallProfile (paperSmall r c) → ℝ) : + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + variance (wordWeight small B r c (d^12) U) (wordObservable small U H) ≤ + 4*(d:ℝ)^2*((U:ℝ)+1)^6*physicalEnergy small B (hardMarginal small B r c (d^12)) H := by + dsimp only + let d := dimensionAllowance (I := I) (J := J) + let U := d^20 + let small := paperSmall r c + let B := paperCapacity small r d (d^12) U + let E := physicalEnergy small B (hardMarginal small B r c (d^12)) H + have hq : Fintype.card (Cells small) ≤ d := (small_card_le_dimension small).trans dimension_le_allowance + have hE : 0 ≤ E := graphEnergy_nonnegative (vertices small B) (hardMarginal small B r c (d^12)) H + (hardMarginal_nonnegative small B r c (d^12)) + exact variance_le_polynomial_budget (wordWeight small B r c (d^12) U) (wordObservable small U H) + (fun a => hardMarginal_nonnegative _ _ _ _ _ _) d U hq E hE + (fun k => firstPaper_prefixContribution_le r c k H) + +end ContingencyTables.RowMajorEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperWordBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperWordBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad1ccda7dccad2d7ab9674df8f609b09b1b647f2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/FirstPaperWordBudget.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperOuterBudget + +namespace OAI + +/-! # A polynomial bound for the full first-paper Boolean word -/ + +namespace ContingencyTables + +/-- Each outer trial contains a small walk and a fresh completion word. -/ +def smallSamplerWordBudget (d b k : ℕ) : ℕ := + let f := 25*(d+b+outerAccuracy d b k+1)^62 + outerTrials d k*(outerSteps d b k*(Nat.clog 2 (32*d^2)+f)+f) + +private lemma double_power_le {S : ℕ} (hS : 2 ≤ S) (n : ℕ) : + 2*S^n ≤ S^(n+1) := by + rw [pow_succ'] + exact Nat.mul_le_mul_right _ hS + +private lemma one_mul_power (S a b : ℕ) : S*(S^a)^b=S^(a*b+1) := by + rw [←pow_mul,pow_succ'] + +private lemma natPower_mul (S a b c : ℕ) (hc : a+b=c) : S^a*S^b=S^c := by + rw [←pow_add,hc] + +private lemma natPower_mono (S i j : ℕ) (hS : 1 ≤ S) (hij : i ≤ j) : S^i ≤ S^j := + Nat.pow_le_pow_right hS hij + +private theorem wordBudget_bound (d b k S : ℕ) (hinput : d+b+k+100 ≤ S) : + smallSamplerWordBudget d b k ≤ S^644 := by + have hS : 2 ≤ S := by omega + have hS1 : 1 ≤ S := by omega + have hd : d ≤ S := by omega + have hb : k+b ≤ S := by omega + have hk : k+1 ≤ S := by omega + have hn : outerSteps d b k ≤ S^202 := by + unfold outerSteps + calc + _ ≤ S^200*S^2 := Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (Nat.pow_le_pow_left hb _) + _ = _ := (pow_add S 200 2).symm + have hh : outerAccuracy d b k ≤ S^6 := by + unfold outerAccuracy + calc + _ ≤ S^4*S^2 := Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (Nat.pow_le_pow_left hb _) + _ = _ := (pow_add S 4 2).symm + have hlin : d+b+outerAccuracy d b k+1 ≤ S^7 := by + have hp := Nat.le_self_pow (by decide : 6≠0) S + exact (show d+b+outerAccuracy d b k+1 ≤ 2*S^6 by omega).trans (double_power_le hS 6) + have hf : 25*(d+b+outerAccuracy d b k+1)^62 ≤ S^435 := by + have hm := Nat.mul_le_mul (show 25 ≤ S by omega) (Nat.pow_le_pow_left hlin 62) + have he := one_mul_power S 7 62 + have hp : S^(7*62+1)=S^435 := congrArg (fun n => S^n) (by decide) + exact hm.trans_eq (he.trans hp) + have hs : Nat.clog 2 (32*d^2) ≤ S^3 := by + calc + _ ≤ 32*d^2 := Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self) + _ ≤ S*S^2 := Nat.mul_le_mul (by omega) (Nat.pow_le_pow_left hd _) + _ = _ := (pow_succ' S 2).symm + have hsum : Nat.clog 2 (32*d^2)+25*(d+b+outerAccuracy d b k+1)^62 ≤ S^436 := by + have hp : S^3 ≤ S^435 := natPower_mono S 3 435 hS1 (by decide) + calc + _ ≤ S^435+S^435 := Nat.add_le_add (hs.trans hp) hf + _ = 2*S^435 := (two_mul _).symm + _ ≤ S^(435+1) := double_power_le hS 435 + _ = S^436 := congrArg (fun n => S^n) (by decide) + have hinner : outerSteps d b k*(Nat.clog 2 (32*d^2)+25*(d+b+outerAccuracy d b k+1)^62)+ + 25*(d+b+outerAccuracy d b k+1)^62 ≤ S^639 := by + have hp : S^435 ≤ S^638 := natPower_mono S 435 638 hS1 (by decide) + calc + _ ≤ S^638+S^638 := Nat.add_le_add + ((Nat.mul_le_mul hn hsum).trans_eq (natPower_mul S 202 436 638 (by decide))) (hf.trans hp) + _ = 2*S^638 := (two_mul _).symm + _ ≤ S^(638+1) := double_power_le hS 638 + _ = S^639 := congrArg (fun n => S^n) (by decide) + have hJ : outerTrials d k ≤ S^5 := by + unfold outerTrials + calc + _ ≤ S^4*S := Nat.mul_le_mul (Nat.pow_le_pow_left hd _) hk + _ = _ := (pow_succ S 4).symm + unfold smallSamplerWordBudget + exact (Nat.mul_le_mul hJ hinner).trans_eq (natPower_mul S 5 639 644 (by decide)) + + +theorem smallSamplerWordBudget_polynomial (d b k : ℕ) : + smallSamplerWordBudget d b k ≤ (d+b+k+100)^644 := + wordBudget_bound d b k (d+b+k+100) le_rfl + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyCellMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyCellMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..5505a824e716af6ce7d81b684ddfb66535841641 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyCellMachine.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.MatchingCount.Machines.TreeListMore +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyFeasibleTable + +namespace OAI + +/-! # A binary arithmetic machine for one greedy table cell + +This is an existing finite tree-machine compiler applied to the actual +minimum/subtraction step. It supplies an executable component for the +feasible-table initializer, rather than an assumed arithmetic oracle. +-/ + +namespace ContingencyTables.GreedyFeasibleTable + +open MatchingFPRAS.TreeTyped + +/-- Assigned entry, remaining row margin, and remaining column margin. -/ +def cellUpdate (x : ℕ×ℕ) : ℕ×(ℕ×ℕ) := + (min x.1 x.2,(x.1-min x.1 x.2,x.2-min x.1 x.2)) + +/-- A fixed finite program over binary-encoded natural numbers. The +compiler's `correct` field proves its literal execution and step bound. -/ +def cellUpdateRealizer : Realizer cellUpdate := + (pair minimum (pair + (composition (pair first minimum) subtract) + (composition (pair second minimum) subtract))).congr (fun _ => rfl) + +lemma cellUpdate_balance (a c : ℕ) : + (cellUpdate (a,c)).1+(cellUpdate (a,c)).2.1=a ∧ + (cellUpdate (a,c)).1+(cellUpdate (a,c)).2.2=c := by + simp only [cellUpdate] + exact ⟨Nat.add_sub_of_le (min_le_left _ _),Nat.add_sub_of_le (min_le_right _ _)⟩ + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyFeasibleTable.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyFeasibleTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..421bcaa85a5ba643dd422685f5ce773659cb6dc9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyFeasibleTable.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Model +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Algebra.BigOperators.Fin + +namespace OAI + +/-! # A dimension-recursive feasible table constructor + +The constructor removes a column on each inner call and a row on each +outer call. Large binary margins are never processed one unit at a time. +-/ + +namespace ContingencyTables.GreedyFeasibleTable + +open scoped BigOperators + +structure RowSplit (n : ℕ) where + assigned : Fin n → ℕ + remaining : Fin n → ℕ + unused : ℕ + +def splitRow : {n : ℕ} → ℕ → (Fin n → ℕ) → RowSplit n + | 0,a,_ => ⟨Fin.elim0,Fin.elim0,a⟩ + | _n+1,a,c => + let b := min a (c 0) + let tail := splitRow (a-b) (fun i => c i.succ) + ⟨Fin.cons b tail.assigned,Fin.cons (c 0-b) tail.remaining,tail.unused⟩ + +lemma splitRow_columns {n : ℕ} (a : ℕ) (c : Fin n → ℕ) (i : Fin n) : + (splitRow a c).assigned i+(splitRow a c).remaining i=c i := by + induction n generalizing a with + | zero => exact Fin.elim0 i + | succ n ih => + refine Fin.cases ?_ (fun j => ?_) i + · simp only [splitRow,Fin.cons_zero] + omega + · simpa only [splitRow,Fin.cons_succ] using ih (a-min a (c 0)) (fun j => c j.succ) j + +lemma splitRow_balance {n : ℕ} (a : ℕ) (c : Fin n → ℕ) : + (∑ i,(splitRow a c).assigned i)+(splitRow a c).unused=a := by + induction n generalizing a with + | zero => simp [splitRow] + | succ n ih => + have ht := ih (a-min a (c 0)) (fun j => c j.succ) + simp only [splitRow,Fin.sum_univ_succ,Fin.cons_zero,Fin.cons_succ] + omega + +lemma splitRow_unused {n : ℕ} (a : ℕ) (c : Fin n → ℕ) : + (splitRow a c).unused=a-∑ i,c i := by + induction n generalizing a with + | zero => simp [splitRow] + | succ n ih => + simpa only [splitRow,Fin.sum_univ_succ] using + (ih (a-min a (c 0)) (fun j => c j.succ)).trans (by omega) + +lemma splitRow_sum {n : ℕ} (a : ℕ) (c : Fin n → ℕ) (ha : a ≤ ∑ i,c i) : + (∑ i,(splitRow a c).assigned i)=a := by + have hb := splitRow_balance a c + rw [splitRow_unused,Nat.sub_eq_zero_of_le ha,add_zero] at hb + exact hb + +lemma splitRow_remaining_sum {n : ℕ} (a : ℕ) (c : Fin n → ℕ) : + (∑ i,(splitRow a c).remaining i)=(∑ i,c i)-a := by + have hc : (∑ i,(splitRow a c).assigned i)+(∑ i,(splitRow a c).remaining i)=∑ i,c i := by + rw [←Finset.sum_add_distrib] + exact Finset.sum_congr rfl (fun i _ => splitRow_columns a c i) + have hb := splitRow_balance a c + rw [splitRow_unused] at hb + omega + +def matrix : {m n : ℕ} → (Fin m → ℕ) → (Fin n → ℕ) → Fin m → Fin n → ℕ + | 0,_,_,_ => Fin.elim0 + | _m+1,_,r,c => + let row := splitRow (r 0) c + Fin.cons row.assigned (matrix (fun i => r i.succ) row.remaining) + +/-- The arithmetic constructor fills any equal-total natural margins. -/ +theorem matrix_hasMargins {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) : HasMargins (matrix r c) r c := by + induction m generalizing c with + | zero => + constructor + · intro i + exact Fin.elim0 i + · intro j + have hc : c j ≤ ∑ k,c k := Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + simp only [Fin.sum_univ_zero] at htotal + simp only [Fin.sum_univ_zero] + omega + | succ m ih => + have ha : r 0 ≤ ∑ j,c j := by + rw [Fin.sum_univ_succ] at htotal + omega + have htail : (∑ i : Fin m,r i.succ)=∑ j,(splitRow (r 0) c).remaining j := by + rw [splitRow_remaining_sum] + rw [Fin.sum_univ_succ] at htotal + omega + have hm := ih (fun i => r i.succ) (splitRow (r 0) c).remaining htail + constructor + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · simpa only [matrix,Fin.cons_zero] using splitRow_sum (r 0) c ha + · simpa only [matrix,Fin.cons_succ] using hm.1 i + · intro j + simpa only [matrix,Fin.sum_univ_succ,Fin.cons_zero,Fin.cons_succ,hm.2 j] using + splitRow_columns (r 0) c j + +/-- A literal, dimension-recursive fallback for the sampling algorithm. -/ +def table {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) : Table r c := ⟨matrix r c,matrix_hasMargins r c htotal⟩ + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..08e070f90aa914efed88aa4659c7bc3d790706b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicMachine.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram +import OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram + +namespace OAI + +/-! # The greedy initializer on the public binary tape -/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS Turing +open scoped BigOperators + +private lemma encodeNat_nonzero (n : ℕ) (a : Symbol) (ha : a∈encodeNat n) : a≠0 := by + simp only [encodeNat,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide + +private lemma encodeNat_alphabet (n : ℕ) (a : Symbol) (ha : a∈encodeNat n) : a≠6 ∧ a≠7 := by + simp only [encodeNat,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide + +lemma publicGreedy_alphabet (as : List Symbol) : + ∀ a∈publicGreedy as,a≠6 ∧ a≠7 := by + intro a ha + obtain ⟨row,_,ha⟩ := List.mem_flatMap.mp ha + obtain ⟨n,_,ha⟩ := List.mem_flatMap.mp ha + exact encodeNat_alphabet n a ha + +lemma encodeMargins_nonzero {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + ∀ a∈Algorithms.encodeMargins r c,a≠0 := by + rw [encodeMargins_natWords] + intro a ha + obtain ⟨n,_,ha⟩ := List.mem_flatMap.mp ha + exact encodeNat_nonzero n a ha + +/-- A single finite transition table performs the feasible initialization +from the public margin encoding, with polynomial cost in its bit length. -/ +theorem publicGreedy_machine : + ∃ (A : RandomMachine) (p : Polynomial ℕ), + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → ∀ t, + p.eval (Algorithms.encodeMargins r c).length ≤ t → ∀ bits : Fin t → Bool, + ∃ X : Table r c,Algorithms.OutputsTable A (Algorithms.encodeMargins r c) bits X.val := by + obtain ⟨A,p,hp⟩ := LiteralProgram.deterministic_compiles publicGreedyRealizer + polynomial_publicGreedy publicGreedy_alphabet + refine ⟨A,p,?_⟩ + intro m n r c ht t htime bits + refine ⟨table r c ht,?_⟩ + have h := hp (Algorithms.encodeMargins r c) (encodeMargins_nonzero r c) t htime bits + simpa only [Algorithms.OutputsTable,publicGreedy_spec,table] using h + +/-- The same initializer accepts the precision parameter on sampling inputs. -/ +theorem publicGreedy_sampling_machine : + ∃ (A : RandomMachine) (p : Polynomial ℕ), + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i,r i)=∑ j,c j → ∀ k t, + p.eval (Algorithms.encodeSamplingInput r c k).length ≤ t → ∀ bits : Fin t → Bool, + ∃ X : Table r c,Algorithms.OutputsTable A (Algorithms.encodeSamplingInput r c k) bits X.val := by + obtain ⟨A,p,hp⟩ := LiteralProgram.deterministic_compiles publicGreedyRealizer + polynomial_publicGreedy publicGreedy_alphabet + refine ⟨A,p,?_⟩ + intro m n r c ht k t htime bits + have hnonzero : ∀ a∈Algorithms.encodeSamplingInput r c k,a≠0 := by + intro a ha + rcases List.mem_append.mp ha with hm|hk + · exact encodeMargins_nonzero r c a hm + · exact encodeNat_nonzero k a hk + refine ⟨table r c ht,?_⟩ + have h := hp (Algorithms.encodeSamplingInput r c k) hnonzero t htime bits + simpa only [Algorithms.OutputsTable,publicGreedy_sampling,table] using h + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..86dc6738001261fd368339bd5dc7c9d5a31c29d0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyPublicProgram.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyTableComplexity +import OAI.Combinatorics.ContingencyTables.AlgorithmStatements +import OAI.Combinatorics.MatchingCount.Tapes.Parse +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts + +namespace OAI + +/-! # Parsing the public margins and printing the greedy matrix + +All operations are existing binary list programs. The bounded take and +drop operations also terminate polynomially on malformed headers. +-/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS TreeTyped LiteralCodec LiteralParse +open scoped BigOperators + +/-- The first two natural numbers give the lengths of the two margins. -/ +def marginLists (ns : List ℕ) : List ℕ × List ℕ := + let m := ns.headD 0 + let n := ns.tail.headD 0 + let rest := ns.tail.tail + (rest.take m,(rest.drop m).take n) + +def marginListsRealizer : Realizer marginLists := by + let M : Realizer (fun ns : List ℕ => ns.headD 0) := head 0 + let N : Realizer (fun ns : List ℕ => ns.tail.headD 0) := composition tail (head 0) + let D : Realizer (fun ns : List ℕ => ns.tail.tail) := composition tail tail + exact (pair (composition (pair D M) takeFast) + (composition (pair (composition (pair D M) dropFast) N) takeFast)).congr (fun _ => rfl) + +lemma polynomial_marginLists : PolynomialTime marginListsRealizer := by + have hM : PolynomialTime (head (A := ℕ) 0) := polynomial_head 0 + have hN : PolynomialTime (composition (tail (A := ℕ)) (head 0)) := + polynomial_composition polynomial_tail (polynomial_head 0) + have hD : PolynomialTime (composition (tail (A := ℕ)) tail) := + polynomial_composition polynomial_tail polynomial_tail + unfold marginListsRealizer + exact polynomial_congr _ (polynomial_pair + (polynomial_composition (polynomial_pair hD hM) polynomial_takeFast) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hD hM) polynomial_dropFast) hN) + polynomial_takeFast)) + +def printMatrix (rows : List (List ℕ)) : List Symbol := + rows.flatMap (fun row => row.flatMap encodeNat) + +def printMatrixRealizer : Realizer printMatrix := + flatMapPoly (flatMapPoly natWordRealizer) + +lemma polynomial_printMatrix : PolynomialTime printMatrixRealizer := + polynomial_flatMapPoly (polynomial_flatMapPoly polynomial_natWord) + +def publicGreedy (as : List Symbol) : List Symbol := + let margins := marginLists (parse as) + printMatrix (listMatrix margins.1 margins.2) + +def publicGreedyRealizer : Realizer publicGreedy := + (composition (composition (composition parseRealizer marginListsRealizer) + tableRealizer) printMatrixRealizer).congr (fun _ => rfl) + +/-- One fixed program parses dimensions, computes all greedy cells and +prints the public binary matrix representation in polynomial bit time. -/ +theorem polynomial_publicGreedy : PolynomialTime publicGreedyRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_parse polynomial_marginLists) + polynomial_table) polynomial_printMatrix) + +lemma natWords_fold (ns tail : List ℕ) : + (ns.flatMap encodeNat).foldr (fun a ns => numStep (a,ns)) tail=ns++tail := by + induction ns with + | nil => rfl + | cons n ns ih => + simp only [List.flatMap_cons,List.foldr_append,ih,encodeNat_fold,List.cons_append] + +lemma parse_natWords (ns : List ℕ) : parse (ns.flatMap encodeNat)=ns := by + simpa only [parse,List.append_nil] using natWords_fold ns [] + +lemma encodeMargins_natWords {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + Algorithms.encodeMargins r c= + (m::n::(List.ofFn r++List.ofFn c)).flatMap encodeNat := by + simp only [Algorithms.encodeMargins,List.flatMap_cons,List.flatMap_append] + simp only [List.ofFn_comp',List.flatMap_def,List.append_assoc] + +lemma marginLists_spec (m n : ℕ) (rs cs tail : List ℕ) + (hr : rs.length=m) (hc : cs.length=n) : + marginLists (m::n::(rs++cs++tail))=(rs,cs) := by + simp only [marginLists,List.headD_cons,List.tail_cons] + rw [←hr,←hc] + simp only [List.append_assoc,List.take_left,List.drop_left] + +lemma printMatrix_ofFn {m n : ℕ} (X : Fin m → Fin n → ℕ) : + printMatrix (List.ofFn (fun i => List.ofFn (X i)))=Algorithms.encodeMatrix X := by + simp only [printMatrix,Algorithms.encodeMatrix,List.flatMap_def,List.ofFn_comp',List.map_map, + Function.comp_def] + +/-- The actual parser/program/printer computes the mathematically proved +initializer on the exact public input encoding. -/ +theorem publicGreedy_spec {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + publicGreedy (Algorithms.encodeMargins r c)=Algorithms.encodeMatrix (matrix r c) := by + unfold publicGreedy + rw [encodeMargins_natWords,parse_natWords] + have hm := marginLists_spec m n (List.ofFn r) (List.ofFn c) [] + (List.length_ofFn) (List.length_ofFn) + simp only [List.append_nil] at hm + rw [hm] + dsimp only + rw [listMatrix_ofFn,printMatrix_ofFn] + +/-- Extra encoded parameters after the margins do not change initialization. -/ +lemma publicGreedy_suffix {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (ns : List ℕ) : + publicGreedy (Algorithms.encodeMargins r c++ns.flatMap encodeNat)= + Algorithms.encodeMatrix (matrix r c) := by + unfold publicGreedy + rw [encodeMargins_natWords,←List.flatMap_append,parse_natWords] + have hm := marginLists_spec m n (List.ofFn r) (List.ofFn c) ns + List.length_ofFn List.length_ofFn + simp only [List.append_assoc] at hm + simp only [List.cons_append,List.append_assoc] + rw [hm] + dsimp only + rw [listMatrix_ofFn,printMatrix_ofFn] + +lemma publicGreedy_sampling {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : + publicGreedy (Algorithms.encodeSamplingInput r c k)=Algorithms.encodeMatrix (matrix r c) := by + simpa only [Algorithms.encodeSamplingInput,List.flatMap_cons,List.flatMap_nil,List.append_nil] + using publicGreedy_suffix r c [k] + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowComplexity.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowComplexity.lean new file mode 100644 index 0000000000000000000000000000000000000000..f355c28247b6bbb6b24655c748646ff047577bb1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowComplexity.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyRowMachine +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLists + +namespace OAI + +/-! # Polynomial binary cost of a greedy row pass -/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS.TreeTyped Polynomial + +lemma polynomial_cellMinimum : PolynomialTime minimum := by + unfold minimum + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_first polynomial_second) + +lemma polynomial_rowCell : PolynomialTime rowCellRealizer := by + have hA : PolynomialTime (composition + (second (A := ℕ) (B := RowAccumulator)) first) := + polynomial_composition polynomial_second polynomial_first + have hC : PolynomialTime (first (A := ℕ) (B := RowAccumulator)) := polynomial_first + have hQ := polynomial_composition (polynomial_pair hA hC) polynomial_cellMinimum + have hX : PolynomialTime (composition + (composition (second (A := ℕ) (B := RowAccumulator)) second) first) := + polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_first + have hY : PolynomialTime (composition + (composition (second (A := ℕ) (B := RowAccumulator)) second) second) := + polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_second + unfold rowCellRealizer + exact polynomial_congr _ (polynomial_pair + (polynomial_composition (polynomial_pair hA hQ) polynomial_subtract) + (polynomial_pair (polynomial_composition (polynomial_pair hQ hX) polynomial_listCons) + (polynomial_composition + (polynomial_pair (polynomial_composition (polynomial_pair hC hQ) polynomial_subtract) hY) + polynomial_listCons))) + +/-- No entry produced by a row pass exceeds its original column bound; +the binary list sizes therefore grow by only a constant factor. -/ +lemma listSplitRow_bounds (a : ℕ) (cs : List ℕ) : + (listSplitRow a cs).1≤a ∧ + weight (listSplitRow a cs).2.1≤4*weight cs ∧ + weight (listSplitRow a cs).2.2≤4*weight cs := by + induction cs generalizing a with + | nil => simp [listSplitRow,weight_nil] + | cons c cs ih => + have ht := ih (a-min a c) + have hq := weight_nat_small (min_le_right a c) + have hc := weight_nat_small (Nat.sub_le c (min a c)) + simp only [listSplitRow,weight_cons] + exact ⟨ht.1.trans (Nat.sub_le _ _),by omega,by omega⟩ + +lemma polynomial_rowFold : PolynomialTime (fold rowCellRealizer) := by + apply polynomial_fold polynomial_rowCell (12*X+10) + rintro cs ⟨a,xs,ys⟩ pre post he + have ht := listSplitRow_bounds a pre + have ha := weight_nat_small ht.1 + have hpre := weight_prefix he + have hx := weight_append (listSplitRow a pre).2.1.reverse xs + have hy := weight_append (listSplitRow a pre).2.2.reverse ys + rw [weight_reverse] at hx hy + rw [fold_rowCell] + simp only [weight_prod,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X] + omega + +theorem polynomial_rowSplit : PolynomialTime rowSplitRealizer := by + unfold rowSplitRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition + · apply polynomial_composition + · exact polynomial_pair polynomial_second + (polynomial_pair polynomial_first (polynomial_constant ([],[]))) + · exact polynomial_rowFold + · exact polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_reverse) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_reverse)) + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bdd34aeae04047f9930026629c699ab6e6fd08f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyRowMachine.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyCellMachine +import OAI.Combinatorics.MatchingCount.Machines.TreeFold + +namespace OAI + +/-! # A binary list program for one row of the greedy initializer -/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS.TreeTyped + +abbrev RowAccumulator := ℕ × (List ℕ × List ℕ) + +/-- A row pass keeps its residual margin and builds both output lists +in reverse order, using only binary minimum, subtraction and list cons. -/ +def rowCell (z : ℕ × RowAccumulator) : RowAccumulator := + let q := min z.2.1 z.1 + (z.2.1-q,(q::z.2.2.1,(z.1-q)::z.2.2.2)) + +def rowCellRealizer : Realizer rowCell := by + let A : Realizer (fun z : ℕ × RowAccumulator => z.2.1) := composition second first + let C : Realizer (fun z : ℕ × RowAccumulator => z.1) := first + let Q := composition (pair A C) minimum + let X : Realizer (fun z : ℕ × RowAccumulator => z.2.2.1) := + composition (composition second second) first + let Y : Realizer (fun z : ℕ × RowAccumulator => z.2.2.2) := + composition (composition second second) second + exact (pair (composition (pair A Q) subtract) + (pair (composition (pair Q X) listCons) + (composition (pair (composition (pair C Q) subtract) Y) listCons))).congr (fun _ => rfl) + +/-- The list version of the already proved dimension-recursive row split. -/ +def listSplitRow : ℕ → List ℕ → RowAccumulator + | a,[] => (a,([],[])) + | a,c::cs => + let q := min a c + let tail := listSplitRow (a-q) cs + (tail.1,(q::tail.2.1,(c-q)::tail.2.2)) + +lemma fold_rowCell (cs : List ℕ) (a : ℕ) (xs ys : List ℕ) : + cs.foldl (fun z c => rowCell (c,z)) (a,(xs,ys))= + let tail := listSplitRow a cs + (tail.1,(tail.2.1.reverse++xs,tail.2.2.reverse++ys)) := by + induction cs generalizing a xs ys with + | nil => rfl + | cons c cs ih => + rw [List.foldl_cons] + change cs.foldl (fun z c => rowCell (c,z)) + (a-min a c,(min a c::xs,(c-min a c)::ys))=_ + rw [ih] + simp only [listSplitRow,List.reverse_cons,List.append_assoc,List.singleton_append] + +def rowSplitRealizer : Realizer (fun z : ℕ × List ℕ => listSplitRow z.1 z.2) := by + let start : Realizer (fun z : ℕ × List ℕ => (z.2,(z.1,(([] : List ℕ),([] : List ℕ))))) := + pair second (pair first (constant ([],[]))) + let finish : Realizer (fun z : RowAccumulator => (z.1,(z.2.1.reverse,z.2.2.reverse))) := + pair first (pair (composition (composition second first) reverse) + (composition (composition second second) reverse)) + exact (composition (composition start (fold rowCellRealizer)) finish).congr (by + intro z + change (fun v : RowAccumulator => (v.1,(v.2.1.reverse,v.2.2.reverse))) + (z.2.foldl (fun s c => rowCell (c,s)) (z.1,([],[])))=listSplitRow z.1 z.2 + rw [fold_rowCell] + simp) + +lemma listSplitRow_balance (a : ℕ) (cs : List ℕ) : + (listSplitRow a cs).2.1.sum+(listSplitRow a cs).1=a := by + induction cs generalizing a with + | nil => simp [listSplitRow] + | cons c cs ih => + simp only [listSplitRow,List.sum_cons] + have ht := ih (a-min a c) + have hq := min_le_left a c + omega + +lemma listSplitRow_lengths (a : ℕ) (cs : List ℕ) : + (listSplitRow a cs).2.1.length=cs.length ∧ + (listSplitRow a cs).2.2.length=cs.length := by + induction cs generalizing a with + | nil => exact ⟨rfl,rfl⟩ + | cons c cs ih => + constructor + · simpa only [listSplitRow,List.length_cons] using congrArg Nat.succ (ih (a-min a c)).1 + · simpa only [listSplitRow,List.length_cons] using congrArg Nat.succ (ih (a-min a c)).2 + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableComplexity.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableComplexity.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c3910d836883d04c96d791099f41cd31be5db5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableComplexity.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyTableMachine +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyRowComplexity + +namespace OAI + +/-! # Polynomial binary cost of the full greedy table constructor -/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS.TreeTyped Polynomial + +private lemma listLE_trans {as bs cs : List ℕ} + (hab : List.Forall₂ (·≤·) as bs) (hbc : List.Forall₂ (·≤·) bs cs) : + List.Forall₂ (·≤·) as cs := by + induction hab generalizing cs with + | nil => cases hbc; exact .nil + | cons hab htail ih => + cases hbc with + | cons hbc hrest => exact .cons (hab.trans hbc) (ih hrest) + +private lemma weight_listLE {as bs : List ℕ} (h : List.Forall₂ (·≤·) as bs) : + weight as≤4*weight bs := by + induction h with + | nil => simp + | cons hab htail ih => + have hn := weight_nat_small hab + simp only [weight_cons] + omega + +lemma listSplitRow_le (a : ℕ) (cs : List ℕ) : + List.Forall₂ (·≤·) (listSplitRow a cs).2.1 cs ∧ + List.Forall₂ (·≤·) (listSplitRow a cs).2.2 cs := by + induction cs generalizing a with + | nil => exact ⟨.nil,.nil⟩ + | cons c cs ih => + exact ⟨.cons (min_le_right _ _) (ih (a-min a c)).1, + .cons (Nat.sub_le _ _) (ih (a-min a c)).2⟩ + +private lemma tableFold_bounds (rs cs base : List ℕ) (rows : List (List ℕ)) + (hc : List.Forall₂ (·≤·) cs base) : + List.Forall₂ (·≤·) (rs.foldl (fun z a => tableRow (a,z)) (cs,rows)).1 base ∧ + weight (rs.foldl (fun z a => tableRow (a,z)) (cs,rows)).2≤ + rs.length*(4*weight base+1)+weight rows := by + induction rs generalizing cs rows with + | nil => exact ⟨hc,by simp⟩ + | cons a rs ih => + have hr := listSplitRow_le a cs + have hout := weight_listLE (listLE_trans hr.1 hc) + have ht := ih (listSplitRow a cs).2.2 ((listSplitRow a cs).2.1::rows) + (listLE_trans hr.2 hc) + refine ⟨ht.1,?_⟩ + change weight (rs.foldl (fun z a => tableRow (a,z)) + ((listSplitRow a cs).2.2,(listSplitRow a cs).2.1::rows)).2≤_ + simp only [List.length_cons,weight_cons] at ht ⊢ + nlinarith [ht.2] + +lemma polynomial_tableRow : PolynomialTime tableRowRealizer := by + have hrow : PolynomialTime (composition + (pair (first (A := ℕ) (B := TableAccumulator)) (composition second first)) + rowSplitRealizer) := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) polynomial_rowSplit + have hrows : PolynomialTime (composition + (second (A := ℕ) (B := TableAccumulator)) second) := + polynomial_composition polynomial_second polynomial_second + unfold tableRowRealizer + exact polynomial_congr _ (polynomial_pair + (polynomial_composition (polynomial_composition hrow polynomial_second) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition hrow polynomial_second) polynomial_first) + hrows) polynomial_listCons)) + +lemma polynomial_tableFold : PolynomialTime (fold tableRowRealizer) := by + apply polynomial_fold polynomial_tableRow (12*(X+1)^2) + rintro rs ⟨cs,rows⟩ pre post he + have hc : List.Forall₂ (·≤·) cs cs := by + induction cs with + | nil => exact .nil + | cons c cs ih => exact .cons le_rfl ih + have ht := tableFold_bounds pre cs cs rows hc + have hw := weight_listLE ht.1 + have hp := (list_length_le_weight pre).trans (weight_prefix he) + let S := weight (rs,(cs,rows)) + have hrs : weight rs≤S := by dsimp [S]; simp only [weight_prod]; omega + have hcs : weight cs≤S := by dsimp [S]; simp only [weight_prod]; omega + have hrows : weight rows≤S := by dsimp [S]; simp only [weight_prod]; omega + have hpre : pre.length≤S := hp.trans hrs + change weight (pre.foldl (fun z a => tableRow (a,z)) (cs,rows))≤_ + rw [←Prod.eta (pre.foldl (fun z a => tableRow (a,z)) (cs,rows)),weight_prod] + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_pow, + Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + change _≤12*(S+1)^2 + have hm := Nat.mul_le_mul hpre (show 4*weight cs+1≤4*S+1 by omega) + nlinarith [ht.2] + +/-- The single fixed program has polynomial bit cost, uniformly in both +dimensions and all binary margin values. -/ +theorem polynomial_table : PolynomialTime tableRealizer := by + unfold tableRealizer + dsimp only + apply polynomial_congr + apply polynomial_composition _ polynomial_reverse + apply polynomial_composition _ polynomial_second + apply polynomial_composition _ polynomial_tableFold + exact polynomial_pair polynomial_first + (polynomial_pair polynomial_second (polynomial_constant [])) + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..df1fe7dc09eae07f3946c2d0e7367d3f43a2288c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/GreedyTableMachine.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyRowMachine + +namespace OAI + +/-! # A fixed binary list program constructing the greedy table -/ + +namespace ContingencyTables.GreedyFeasibleTable +open MatchingFPRAS.TreeTyped + +abbrev TableAccumulator := List ℕ × List (List ℕ) + +def tableRow (z : ℕ × TableAccumulator) : TableAccumulator := + let row := listSplitRow z.1 z.2.1 + (row.2.2,row.2.1::z.2.2) + +def tableRowRealizer : Realizer tableRow := by + let row : Realizer (fun z : ℕ × TableAccumulator => listSplitRow z.1 z.2.1) := + composition (pair first (composition second first)) rowSplitRealizer + exact (pair (composition (composition row second) second) + (composition (pair (composition (composition row second) first) + (composition second second)) listCons)).congr (fun _ => rfl) + +def listMatrix : List ℕ → List ℕ → List (List ℕ) + | [],_ => [] + | a::as,cs => + let row := listSplitRow a cs + row.2.1::listMatrix as row.2.2 + +lemma fold_tableRow (rs cs : List ℕ) (rows : List (List ℕ)) : + (rs.foldl (fun z a => tableRow (a,z)) (cs,rows)).2= + (listMatrix rs cs).reverse++rows := by + induction rs generalizing cs rows with + | nil => rfl + | cons a rs ih => + rw [List.foldl_cons] + change (rs.foldl (fun z a => tableRow (a,z)) + ((listSplitRow a cs).2.2,(listSplitRow a cs).2.1::rows)).2=_ + rw [ih] + simp only [listMatrix,List.reverse_cons,List.append_assoc,List.singleton_append] + +/-- Every loop is over an input row or column; binary margins are never +counted down one unit at a time. -/ +def tableRealizer : Realizer (fun z : List ℕ × List ℕ => listMatrix z.1 z.2) := by + let start : Realizer (fun z : List ℕ × List ℕ => (z.1,(z.2,([] : List (List ℕ))))) := + pair first (pair second (constant [])) + exact (composition (composition (composition start (fold tableRowRealizer)) second) reverse).congr (by + intro z + change ((z.1.foldl (fun s a => tableRow (a,s)) (z.2,[])).2).reverse=_ + rw [fold_tableRow] + simp) + +lemma listSplitRow_ofFn {n : ℕ} (a : ℕ) (cs : Fin n → ℕ) : + listSplitRow a (List.ofFn cs)= + ((splitRow a cs).unused, + (List.ofFn (splitRow a cs).assigned,List.ofFn (splitRow a cs).remaining)) := by + induction n generalizing a with + | zero => rfl + | succ n ih => + simp only [List.ofFn_succ,listSplitRow,splitRow,ih,Fin.cons_zero,Fin.cons_succ] + +/-- The compiled list program computes the same feasible matrix used +by the probability analysis. -/ +theorem listMatrix_ofFn {m n : ℕ} (rs : Fin m → ℕ) (cs : Fin n → ℕ) : + listMatrix (List.ofFn rs) (List.ofFn cs)= + List.ofFn (fun i => List.ofFn (matrix rs cs i)) := by + induction m generalizing cs with + | zero => rfl + | succ m ih => + simp only [List.ofFn_succ,listMatrix,listSplitRow_ofFn,ih,matrix,Fin.cons_zero, + Fin.cons_succ] + +end ContingencyTables.GreedyFeasibleTable + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/InverseSmallRepair.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/InverseSmallRepair.lean new file mode 100644 index 0000000000000000000000000000000000000000..8692105ce9fa144542867bb435549db027ff1402 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/InverseSmallRepair.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairWords + +namespace OAI + +/-! # Explicit arithmetic inverse of each labelled repair -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles + +noncomputable section +universe u +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +/-- Undo the row transfer, using only additions, subtractions and tests +against the two specified cells. -/ +def inverseRepairRow (small : I → J → Bool) (v : SmallProfile small) (s t : I×J) + (i : I) (j : J) : ℕ := + (transferInt (smallView small v false) (t.1,s.2) t i j).toNat + +def inverseRepairProfile (small : I → J → Bool) (B : I → J → ℕ) + (v : SmallProfile small) (s t : I×J) : SmallProfile small := fun a => + if a.2 then B a.1.val.1 a.1.val.2- + (transferInt (inverseRepairRow small v s t) t s a.1.val.1 a.1.val.2).toNat + else inverseRepairRow small v s t a.1.val.1 a.1.val.2 + +lemma inverseRepairRow_repaired (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (a : Cells small) : + inverseRepairRow small (repairedProfile small B z s t) s t a.val.1 a.val.2= + z (a,false) := by + have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells small)=a := Subtype.ext (Prod.eta a.val) + have he := repairMatrix_cast hd a.val.1 a.val.2 + unfold inverseRepairRow transferInt + simp only [transferInt,smallView,a.property,dite_eq_left,repairedProfile, + Bool.false_eq_true,ite_false,heta] at * + omega + +/-- The inverse is evaluated once per ordered defect label; no search +through bounded profiles is needed to recover a predecessor. -/ +theorem inverseRepairProfile_repaired (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hz : ∀ a,z a ≤ B a.1.val.1 a.1.val.2) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) : + inverseRepairProfile small B (repairedProfile small B z s t) s t=z := by + funext a + rcases a with ⟨a,b⟩ + cases b + · exact inverseRepairRow_repaired small B z s t hd a + · have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells small)=a := Subtype.ext (Prod.eta a.val) + have hr := inverseRepairRow_repaired small B z s t hd a + have hq := hd.2 a.val.1 a.val.2 + have hb := hz (a,true) + simp only [inverseRepairProfile,ite_true,transferInt,hr] + simp only [smallQ,smallView,a.property,dite_eq_left,transferInt,heta] at hq + dsimp only at hb + omega + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBalancedJoint.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBalancedJoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..66ab4c9c64228c2a600a92e0b60f13cbf01034ac --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBalancedJoint.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedJointConstruction +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallChain + +namespace OAI + +/-! # Every original table supplies its literal balanced padded joint object -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal FirstPaperProfiles +open SmallContextFibres SmallContextCoordinates SmallContextEnumeration RowMajorEnumeration +open PaddedCompletions CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def paddedOriginal (small : I → J → Bool) (L : ℕ) + {r : I → ℕ} {c : J → ℕ} (X : Table r c) : + Table (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L) := + ⟨fun i j => X.val i j+if small i j then 0 else L,by + constructor + · intro i + rw [Finset.sum_add_distrib,X.property.1] + dsimp only + unfold rowLargeCount + rw [Finset.sum_mul] + congr 1 + apply Finset.sum_congr rfl + intro j _ + cases small i j <;> simp + · intro j + rw [Finset.sum_add_distrib,X.property.2] + dsimp only + unfold columnLargeCount + rw [Finset.sum_mul] + congr 1 + apply Finset.sum_congr rfl + intro i _ + cases small i j <;> simp⟩ + +omit [LinearOrder I] [LinearOrder J] in +lemma paddedOriginal_small_rows (small : I → J → Bool) (L : ℕ) + {r : I → ℕ} {c : J → ℕ} (X : Table r c) (i : I) : + smallRow small (paddedOriginal small L X).val i ≤ r i := by + calc + _ = ∑ j,if small i j then X.val i j else 0 := by + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j <;> simp [paddedOriginal,hs] + _ ≤ ∑ j,X.val i j := Finset.sum_le_sum (fun j _ => by split_ifs <;> omega) + _ = _ := X.property.1 i + +omit [LinearOrder I] [LinearOrder J] in +lemma paddedOriginal_small_columns (small : I → J → Bool) (L : ℕ) + {r : I → ℕ} {c : J → ℕ} (X : Table r c) (j : J) : + smallColumnView small (paddedOriginal small L X).val j ≤ c j := by + calc + _ = ∑ i,if small i j then X.val i j else 0 := by + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j <;> simp [paddedOriginal,hs] + _ ≤ ∑ i,X.val i j := Finset.sum_le_sum (fun i _ => by split_ifs <;> omega) + _ = _ := X.property.2 j + +omit [LinearOrder I] [LinearOrder J] in +lemma original_small_entry_le (r : I → ℕ) (c : J → ℕ) (U : ℕ) (X : Table r c) + (i : I) (j : J) (hs : firstPaperSmall r c U i j=true) : X.val i j ≤ U := by + have hh : r i X.val i j) (fun _ _ => Nat.zero_le _) (Finset.mem_univ i) + exact hcol.trans (Nat.le_of_lt hc) + +noncomputable def paperOriginalJoint (r : I → ℕ) (c : J → ℕ) (X : Table r c) : + BalancedJoint (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) := by + let d := dimensionAllowance (I := I) (J := J) + let small := paperSmall r c + let Y := paddedOriginal small (d^12) X + have hR := paddedOriginal_small_rows small (d^12) X + have hC := paddedOriginal_small_columns small (d^12) X + refine jointOfTable small (stateCapacity r c) r c (d^12) (d^20) + (stateCapacity_small r c) Y ?_ hR hC ?_ + · intro i j hs + change X.val i j+(if small i j then 0 else d^12) ≤ d^20 + simpa only [hs,ite_true,Nat.add_zero] using original_small_entry_le r c (d^20) X i j hs + · intro i j _ + exact paper_residual_capacity r c d (d^12) (d^20) dimension_le_allowance ⟨Y,hR,hC⟩ i j + +lemma paperOriginalJoint_projection (r : I → ℕ) (c : J → ℕ) (X : Table r c) : + balancedJointTable (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + (stateCapacity_small r c) (paperOriginalJoint r c X)= + paddedOriginal (paperSmall r c) ((dimensionAllowance (I := I) (J := J))^12) X := by + apply Subtype.ext + rfl + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..82f80c94886ce7dbcdf3d3c7cc990976b61ff4f4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxLaw.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableBox +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw + +namespace OAI + +/-! # Embedding original-table laws in their computed finite box -/ + +namespace ContingencyTables.OriginalBoxLaw +open scoped BigOperators Classical +noncomputable section +variable {m n N Q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +open OriginalTableBox + +lemma tableAt_index (hN : (∑ i,r i)≤N) (X : Table r c) : + tableAt r c (index r c hN X)=some X := + (tableAt_eq_some r c hN _ X).mpr rfl + +lemma index_eq_iff (hN : (∑ i,r i)≤N) (X Y : Table r c) : + index r c hN X=index r c hN Y ↔ X=Y := by + constructor + · intro h + have he := congrArg (tableAt r c) h + rw [tableAt_index,tableAt_index] at he + exact Option.some.inj he + · rintro rfl + rfl + +def law (hN : (∑ i,r i)≤N) (p : IntegerLaw (Option (Table r c)) Q) : + IntegerLaw (Option (Index m n N)) Q := + p.push (Option.map (index r c hN)) + +lemma count_none (hN : (∑ i,r i)≤N) (p : IntegerLaw (Option (Table r c)) Q) : + (law r c hN p).count none=p.count none := by + simp [law,IntegerLaw.push,Fintype.sum_option] + +/-- Invalid box entries have zero count; every valid completion has +exactly the count of its unique feasible table. -/ +lemma count_some (hN : (∑ i,r i)≤N) + (p : IntegerLaw (Option (Table r c)) Q) (k : Index m n N) : + (law r c hN p).count (some k)= + (tableAt r c k).elim 0 (fun X => p.count (some X)) := by + simp only [law,IntegerLaw.push,Fintype.sum_option,Option.map_none,reduceCtorEq, + ite_false,zero_add,Option.map_some,Option.some.injEq] + simp_rw [←tableAt_eq_some r c hN] + cases tableAt r c k <;> simp + +lemma count_index (hN : (∑ i,r i)≤N) + (p : IntegerLaw (Option (Table r c)) Q) (X : Table r c) : + (law r c hN p).count (some (index r c hN X))=p.count (some X) := by + rw [count_some r c,tableAt_index] + rfl + +/-- Embedding tables into the explicit finite candidate list commutes +with every bounded first-success retry. -/ +theorem retry_count_index (hN : (∑ i,r i)≤N) + (p : IntegerLaw (Option (Table r c)) Q) (fallback X : Table r c) (J : ℕ) : + ((law r c hN p).retry (index r c hN fallback) J).count (index r c hN X)= + (p.retry fallback J).count X := by + change IntegerLaw.retryCount (law r c hN p) (index r c hN fallback) J (index r c hN X)= + IntegerLaw.retryCount p fallback J X + induction J with + | zero => simp only [IntegerLaw.retryCount,index_eq_iff r c] + | succ J ih => + rw [IntegerLaw.retryCount,IntegerLaw.retryCount,count_index r c,count_none,ih] + +/-- A retry keeps every invalid finite-box entry at zero. -/ +lemma retry_count_some (hN : (∑ i,r i)≤N) + (p : IntegerLaw (Option (Table r c)) Q) (fallback : Table r c) (J : ℕ) + (k : Index m n N) : + ((law r c hN p).retry (index r c hN fallback) J).count k= + (tableAt r c k).elim 0 (fun T => (p.retry fallback J).count T) := by + cases hk : tableAt r c k with + | none => + have hi : k≠index r c hN fallback := by + intro he + rw [he,tableAt_index] at hk + cases hk + change IntegerLaw.retryCount (law r c hN p) (index r c hN fallback) J k=0 + induction J with + | zero => simp only [IntegerLaw.retryCount,hi,ite_false] + | succ J ih => + rw [IntegerLaw.retryCount,count_some r c hN,hk,ih] + simp + | some T => + have he := (tableAt_eq_some r c hN k T).mp hk + rw [←he] + exact retry_count_index r c hN p fallback T J + +end +end ContingencyTables.OriginalBoxLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxPush.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxPush.lean new file mode 100644 index 0000000000000000000000000000000000000000..31766ef9a5a36ad929ca742cb16e7052b535c05f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalBoxPush.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalResidualVector + +namespace OAI + +/-! # Transporting weighted sums through the original-table enumeration -/ + +namespace ContingencyTables.OriginalBoxLaw +open OriginalTableBox ProfilePrograms DensePrograms +open scoped BigOperators Classical +noncomputable section +variable {m n N Q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + +lemma sum_tableAt (hN : (∑ i,r i)≤N) (w : Table r c → ℕ) : + (∑ k : Index m n N,(tableAt r c k).elim 0 w)=∑ X,w X := by + have he (k : Index m n N) : (tableAt r c k).elim 0 w= + ∑ X : Table r c,if tableAt r c k=some X then w X else 0 := by + cases tableAt r c k <;> simp + simp_rw [he] + rw [Finset.sum_comm] + simp_rw [tableAt_eq_some r c hN] + simp + +lemma push_count (hN : (∑ i,r i)≤N) (p : IntegerLaw (Table r c) Q) (k : Index m n N) : + (p.push (index r c hN)).count k=(tableAt r c k).elim 0 p.count := by + change (∑ X,if index r c hN X=k then p.count X else 0)=_ + simp_rw [←tableAt_eq_some r c hN] + cases tableAt r c k <;> simp + +/-- The literal correction vector is the integer residual law embedded in +its enumerated box, so its total and zero weights are exact. -/ +lemma residualVector_law (p : IntegerLaw (Table r c) Q) (fallback : Table r c) + (T : ℕ) (hQ : 0 z.1) (g := trialVector) + first trialVectorRealizer) + (composition (f := fun z : OuterVectorInput => (z.1.2,z.2.2)) (g := originalIndex) + (pair (composition first second) (composition second second)) originalIndexRealizer)) + +def outerVectorMeasure (z : OuterVectorInput) : ℕ := trialVectorMeasure z.1+weight z + +lemma work_outerVectorInput : WorkBound outerVectorInputRealizer outerVectorMeasure := by + have hi (z : OuterVectorInput) : weight z ≤ X.eval (outerVectorMeasure z) := by + simp only [Polynomial.eval_X,outerVectorMeasure] + omega + have hv : WorkBound (composition (first (B := (List Bool×ℕ)×MatrixCode)) trialVectorRealizer) + outerVectorMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_trialVector X + intro z + simp only [Polynomial.eval_X,outerVectorMeasure] + omega + have hp : PolynomialTime (composition + (f := fun z : OuterVectorInput => (z.1.2,z.2.2)) (g := originalIndex) + (pair (composition first second) (composition second second)) originalIndexRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_originalIndex + unfold outerVectorInputRealizer + exact work_pair (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) X hi) + (work_pair hv (work_of_polynomial hp X hi) X hi) X hi + +attribute [local irreducible] outerVectorInput + +def outerVector (z : OuterVectorInput) : List ℕ := VectorRetryPrograms.counts (outerVectorInput z) + +def outerVectorRealizer : Realizer outerVector := + composition (f := outerVectorInput) (g := VectorRetryPrograms.counts) + outerVectorInputRealizer VectorRetryPrograms.countsRealizer + +lemma work_outerVector : WorkBound outerVectorRealizer outerVectorMeasure := by + unfold outerVectorRealizer + exact work_then_polynomial work_outerVectorInput VectorRetryPrograms.polynomial_counts + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts OriginalTableBox +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +attribute [local irreducible] trialVector listedTrialCounts matrixInput outerVectorInput + +lemma outerVector_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) (js : List Bool) (fallback : Table r c) : + outerVector (((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)), + (List.ofFn r,List.ofFn c)),((js,(2^(s+f))^N*2^f),matrixCode fallback.val))= + List.ofFn ((OriginalBoxLaw.law r c le_rfl + (listedTrialCounts r c e hr hc b h hb z N)).retry + (OriginalTableBox.index r c le_rfl fallback) js.length).count := by + unfold outerVector outerVectorInput + rw [trialVector_actual r c e hr hc b h hb htotal z xs hs N,originalIndex_actual] + exact VectorRetryPrograms.counts_actual _ js _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalPointBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalPointBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b2960bfa198a7467115d0a0f01f984286128518 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalPointBounds.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Machines.EnumerationPointBounds +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableEnumeration + +namespace OAI + +/-! # Binary size of one candidate in the original-table enumeration -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +lemma originalCandidates_length (z : CompletionMargins) : + (originalCandidates z).length=gridStateCount (originalEnumerationData z) := by + simp only [originalCandidates,List.length_map,gridWords,List.length_range] + +theorem originalCandidates_point_polynomial : ∃ p : Polynomial ℕ,∀ z v, + v∈originalCandidates z → weight v ≤ p.eval (weight z) := by + obtain ⟨p,hp⟩ := polynomial_originalEnumerationData + obtain ⟨q,hq⟩ := polynomial_originalCandidate + let word : Polynomial ℕ := p*(4*p+2)+1 + refine ⟨q.comp (1+X+word),?_⟩ + intro z v hv + rw [originalCandidates] at hv + obtain ⟨w,hw,rfl⟩ := List.mem_map.mp hv + have hdata : weight (originalEnumerationData z) ≤ p.eval (weight z) := + (Nat.le_add_left _ _).trans (hp z) + have hlen : (originalEnumerationData z).1.length ≤ p.eval (weight z) := + (list_length_le_weight _).trans ((weight_fst _).trans hdata) + have hbase : weight (originalEnumerationData z).2 ≤ p.eval (weight z) := + (weight_snd _).trans hdata + have hword := gridWords_point_weight (originalEnumerationData z) (by + change 0 < (originalLayoutMargins z).1.sum+1 + omega) w hw + have hw' : weight w ≤ word.eval (weight z) := by + apply hword.trans + simp only [word,eval_add,eval_mul,eval_ofNat,eval_one] + exact Nat.add_le_add_right (Nat.mul_le_mul hlen (by omega)) 1 + have hin : weight (z,w) ≤ (1+X+word).eval (weight z) := by + simp only [weight_prod,eval_add,eval_one,eval_X] + omega + simpa only [eval_comp] using + (Nat.le_add_left _ _).trans ((hq (z,w)).trans (polynomial_eval_monotone q hin)) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileEntries.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileEntries.lean new file mode 100644 index 0000000000000000000000000000000000000000..370c6bd4ab60749e3c284085c9680c6e16be7b4a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileEntries.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.ContingencyTables.Transport.StateSuccessEntries +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCodeProposal + +namespace OAI + +/-! # The initial profile is read directly from the original table -/ + +namespace ContingencyTables.SmallGraphProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal FirstPaperProfiles +open PaddedCompletions CompletionCounts SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) + +def tableState (X : Table r c) : PaperStates r c := (originalStateSuccessEquiv r c X).val.1 + +lemma tableState_first (X : Table r c) (i : Fin m) (j : Fin n) + (hs : paperSmall r c i j=true) : + physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) (tableState r c X) + (⟨(i,j),hs⟩,false)=X.val i j := by + let a := originalStateSuccessEquiv r c X + have he := originalStateSuccessEquiv_symm_entry r c a i j + rw [Equiv.symm_apply_apply] at he + have hp : largePadding (paperLarge r c) (d^12) i j=0 := by + simp only [paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ,true_and,hs, + Bool.true_eq_false,ite_false] + rw [hp,Nat.sub_zero] at he + exact (a.val.2.property.2.2.1 i j hs).1.symm.trans he.symm + +lemma tableState_second (X : Table r c) (a : Cells (paperSmall r c)) : + physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) (tableState r c X) + (a,true)=d^20-X.val a.val.1 a.val.2 := by + have hb := (originalStateSuccessEquiv r c X).property.1 + have hsum := (balanced_iff_cellSums (paperSmall r c) (stateCapacity r c) + (physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) (tableState r c X)) + (fun a => (physicalProfile_feasible r c (tableState r c X)).bounded (a,true))).mp hb a + have he := tableState_first r c X a.val.1 a.val.2 a.property + have hcap := stateCapacity_small r c a.val.1 a.val.2 a.property + have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells (paperSmall r c))=a := + Subtype.ext (Prod.eta a.val) + rw [heta] at he + rw [he,hcap] at hsum + omega + +lemma tableState_code (e : Fin q ≃ Cells (paperSmall r c)) (X : Table r c) : + stateCode r c e (tableState r c X)= + (List.ofFn (fun i => X.val (e i).val.1 (e i).val.2), + List.ofFn (fun i => d^20-X.val (e i).val.1 (e i).val.2)) := by + apply Prod.ext + · apply congrArg List.ofFn + funext i + exact tableState_first r c X _ _ (e i).property + · apply congrArg List.ofFn + funext i + exact tableState_second r c X (e i) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee92bd04037e9e89d36beda1e37e77150ffecf87 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalProfileProgram.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalProfileEntries +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPreparedProposal +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram + +namespace OAI + +/-! # Computing the initial profile directly from the greedy table -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +abbrev OriginalViewInput := (List (ℕ×ℕ)×ℕ)×MatrixCode + +def originalFirstView (z : OriginalViewInput) : List ℕ := + z.1.1.map (fun ij => matrixEntry (z.2,ij)) +def originalFirstViewRealizer : Realizer originalFirstView := + composition (pair second (composition first first)) (mapWith matrixEntryRealizer) + +theorem polynomial_originalFirstView : PolynomialTime originalFirstViewRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) (polynomial_mapWith polynomial_matrixEntry) + +def originalViews (z : OriginalViewInput) : List ℕ×List ℕ := + (originalFirstView z,complementValues (z.1.2,originalFirstView z)) +def originalViewsRealizer : Realizer originalViews := + pair originalFirstViewRealizer + (composition (pair (composition first second) originalFirstViewRealizer) complementValuesRealizer) + +theorem polynomial_originalViews : PolynomialTime originalViewsRealizer := + polynomial_pair polynomial_originalFirstView + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_originalFirstView) polynomial_complementValues) + +def initialViewInput (z : List ℕ×List ℕ) : OriginalViewInput := + ((marginCatalog z,marginThreshold z),GreedyFeasibleTable.listMatrix z.1 z.2) +def initialViewInputRealizer : Realizer initialViewInput := + pair (pair marginCatalogRealizer marginThresholdRealizer) GreedyFeasibleTable.tableRealizer + +theorem polynomial_initialViewInput : PolynomialTime initialViewInputRealizer := + polynomial_pair (polynomial_pair polynomial_marginCatalog polynomial_marginThreshold) + GreedyFeasibleTable.polynomial_table + +def initialViews (z : List ℕ×List ℕ) : List ℕ×List ℕ := originalViews (initialViewInput z) +def initialViewsRealizer : Realizer initialViews := composition initialViewInputRealizer originalViewsRealizer + +theorem polynomial_initialViews : PolynomialTime initialViewsRealizer := + polynomial_composition polynomial_initialViewInput polynomial_originalViews + +def initialCheck (z : List ℕ×List ℕ) : ProfileCheckData := prepareProfileInput (z,initialViews z) +def initialCheckRealizer : Realizer initialCheck := + composition (pair identity initialViewsRealizer) prepareProfileInputRealizer + +theorem polynomial_initialCheck : PolynomialTime initialCheckRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_initialViews) polynomial_prepareProfileInput + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts SmallContextCoordinates FirstPaperPhysicalMarginal +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) + +lemma originalViews_code (e : Fin q ≃ Cells (paperSmall r c)) (X : Table r c) : + originalViews ((cellCatalog (paperSmall r c) e,d^20),matrixCode X.val)= + stateCode r c e (tableState r c X) := by + rw [tableState_code] + have he : originalFirstView ((cellCatalog (paperSmall r c) e,d^20),matrixCode X.val)= + List.ofFn (fun i => X.val (e i).val.1 (e i).val.2) := by + simp only [originalFirstView,cellCatalog,List.map_ofFn] + congr 1 + funext i + exact matrixEntry_code X.val (e i).val.1 (e i).val.2 + unfold originalViews + rw [he,complementValues_ofFn] + +lemma initialViews_code (htotal : (∑ i,r i)=∑ j,c j) : + initialViews (List.ofFn r,List.ofFn c)=stateCode r c (computedCellEquiv r c) + (tableState r c (GreedyFeasibleTable.table r c htotal)) := by + unfold initialViews initialViewInput + rw [GreedyFeasibleTable.listMatrix_ofFn] + have hc : marginCatalog (List.ofFn r,List.ofFn c)=cellCatalog (paperSmall r c) (computedCellEquiv r c) := by + rw [computedCellEquiv_catalog] + unfold marginCatalog + rw [marginThreshold_ofFn] + rfl + rw [hc,marginThreshold_ofFn] + exact originalViews_code r c (computedCellEquiv r c) (GreedyFeasibleTable.table r c htotal) + +lemma initialCheck_code (htotal : (∑ i,r i)=∑ j,c j) : + initialCheck (List.ofFn r,List.ofFn c)=stateCodeData r c (computedCellEquiv r c) + (tableState r c (GreedyFeasibleTable.table r c htotal)) := by + unfold initialCheck + rw [initialViews_code r c htotal,prepareProfileInput_eq] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalResidualVector.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalResidualVector.lean new file mode 100644 index 0000000000000000000000000000000000000000..e319415b7fb691e9bbab0239c3e5c42a65c5d617 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalResidualVector.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableCardinality +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxLaw +import OAI.Combinatorics.ContingencyTables.Machines.ResidualWeightProgram +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLawEmbedding + +namespace OAI + +/-! # Explicit integer correction weights on the original-table box -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +/-- Candidate matrices, ordinary numerators, denominator/branch size, and table count. -/ +abbrev ResidualVectorCache := (List (Option MatrixCode)×List ℕ)×((ℕ×ℕ)×ℕ) + +def residualVectorEntry (z : ResidualVectorCache×ℕ) : ℕ := + if (z.1.1.1.getD z.2 none).isSome then + ResidualWeightPrograms.count (z.1.2.1,(z.1.2.2,z.1.1.2.getD z.2 0)) else 0 + +def residualVectorEntryRealizer : Realizer residualVectorEntry := by + let candidate : Realizer (fun z : ResidualVectorCache×ℕ => z.1.1.1.getD z.2 none) := + composition (pair (composition (composition first first) first) second) (getDFast none) + let numerator : Realizer (fun z : ResidualVectorCache×ℕ => z.1.1.2.getD z.2 0) := + composition (pair (composition (composition first first) second) second) (getDFast 0) + let input : Realizer (fun z : ResidualVectorCache×ℕ => + (z.1.2.1,(z.1.2.2,z.1.1.2.getD z.2 0))) := + pair (composition (composition first second) first) + (pair (composition (composition first second) second) numerator) + exact choose (composition candidate FirstSuccessProgram.isSomeRealizer) + (composition input ResidualWeightPrograms.countRealizer) (constant 0) + +lemma polynomial_residualVectorEntry : PolynomialTime residualVectorEntryRealizer := by + unfold residualVectorEntryRealizer + exact polynomial_choose + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) (polynomial_getDFast none)) FirstSuccessProgram.polynomial_isSome) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) (polynomial_getDFast 0)))) ResidualWeightPrograms.polynomial_count) + (polynomial_constant 0) + +def residualVectorIndices (z : ResidualVectorCache) : List ℕ := List.range z.1.1.length + +def residualVectorIndicesRealizer : Realizer residualVectorIndices := + composition (composition (composition first first) listLength) range + +lemma polynomial_residualVectorIndices : PolynomialTime residualVectorIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def residualVector (z : ResidualVectorCache) : List ℕ := + (residualVectorIndices z).map (fun k => residualVectorEntry (z,k)) + +def residualVectorRealizer : Realizer residualVector := + composition (pair identity residualVectorIndicesRealizer) (mapWith residualVectorEntryRealizer) + +lemma polynomial_residualVector : PolynomialTime residualVectorRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_residualVectorIndices) + (polynomial_mapWith polynomial_residualVectorEntry) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.ProfilePrograms +open DensePrograms +open scoped BigOperators Classical + +lemma residualVector_ofFn {K : ℕ} (candidates : Fin K → Option MatrixCode) + (counts : Fin K → ℕ) (Q T N : ℕ) : + residualVector ((List.ofFn candidates,List.ofFn counts),((Q,T),N))= + List.ofFn (fun k => if (candidates k).isSome then + ResidualWeightPrograms.count ((Q,T),(N,counts k)) else 0) := by + unfold residualVector residualVectorIndices + rw [List.length_ofFn] + apply List.ext_getElem + · simp + · intro k hk _ + have hK : k + (tableAt r c k).elim 0 (fun X => IntegerResidualCorrection.count p T X)) := by + let : Nonempty (Table r c) := ⟨fallback⟩ + dsimp only + rw [candidates_code,originalCardinality_actual,residualVector_ofFn] + apply congrArg List.ofFn + funext k + cases hk : tableAt r c k with + | none => rfl + | some X => + simp only [Option.map_some,Option.isSome_some,ite_true,Option.elim_some] + have hindex := (tableAt_eq_some r c le_rfl k X).mp hk + rw [←hindex,IntegerLaw.push_count_injective p _ (index_injective r c)] + exact ResidualWeightPrograms.count_actual p T hT X + +end +end ContingencyTables.OriginalBoxLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableBox.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..53374dd0b630014d3b0834f54f458b9710b5d0fc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableBox.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableEnumeration + +namespace OAI + +/-! # The full original-table box and its unique feasible entries -/ + +namespace ContingencyTables.OriginalTableBox +open DensePrograms ProfilePrograms +open scoped BigOperators Classical +noncomputable section + +abbrev Box (m n N : ℕ) := Fin (m*n) → Fin (N+1) +abbrev Index (m n N : ℕ) := Fin ((N+1)^(m*n)) + +def matrix {m n N : ℕ} (z : Box m n N) : Fin m → Fin n → ℕ := + fun i j => (z (finProdFinEquiv (i,j))).val + +def decode {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (z : Box m n N) : Option (Table r c) := + if h : HasMargins (matrix z) r c then some ⟨matrix z,h⟩ else none + +def encode {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (T : Table r c) : Box m n N := fun k => + ⟨T.val (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2, + Nat.lt_succ_of_le ((entry_le_total T.property _ _).trans hN)⟩ + +lemma matrix_encode {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (T : Table r c) : matrix (encode r c hN T)=T.val := by + funext i j + simp only [matrix,encode,Equiv.symm_apply_apply] + +lemma decode_encode {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (T : Table r c) : decode r c (encode r c hN T)=some T := by + unfold decode + rw [matrix_encode] + simp only [T.property,dite_true] + rfl + +lemma decode_eq_some {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (z : Box m n N) (T : Table r c) : + decode r c z=some T ↔ z=encode r c hN T := by + constructor + · intro ht + unfold decode at ht + split at ht + next hm => + have he := congrArg Subtype.val (Option.some.inj ht) + funext k + apply Fin.ext + have hk := congrFun (congrFun he (finProdFinEquiv.symm k).1) (finProdFinEquiv.symm k).2 + simpa only [matrix,encode,Equiv.apply_symm_apply,Prod.mk.eta] using hk + next hm => cases ht + · rintro rfl + exact decode_encode r c hN T + +def index {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (T : Table r c) : Index m n N := finFunctionFinEquiv (encode r c hN T) + +def tableAt {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : Index m n N) : + Option (Table r c) := decode r c (finFunctionFinEquiv.symm k) + +lemma tableAt_eq_some {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (hN : (∑ i,r i)≤N) (k : Index m n N) (T : Table r c) : + tableAt r c k=some T ↔ index r c hN T=k := by + rw [tableAt,decode_eq_some r c hN] + constructor + · intro he + have hh := congrArg finFunctionFinEquiv he + simpa only [Equiv.apply_symm_apply,index] using hh.symm + · intro he + rw [←he,index,Equiv.symm_apply_apply] + +lemma freeMatrix_code {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (z : Box m n N) : + originalFreeMatrix ((List.ofFn r,List.ofFn c),List.ofFn (fun i => (z i).val))= + matrixCode (matrix z) := by + exact unflattenGrid_code (fun i : Option (Fin m) => i.elim 0 r) + (fun j : Option (Fin n) => j.elim 0 c) (fun i => (z i).val) + +lemma candidate_code {m n N : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (z : Box m n N) : + originalCandidate ((List.ofFn r,List.ofFn c),List.ofFn (fun i => (z i).val))= + (decode r c z).map (fun T => matrixCode T.val) := by + unfold originalCandidate + rw [freeMatrix_code] + unfold decode + by_cases h : HasMargins (matrix z) r c + · rw [ite_eq_left ((originalTableTest_code r c (matrix z)).mpr h),dite_eq_left h] + rfl + · rw [ite_eq_right (fun ht => h ((originalTableTest_code r c (matrix z)).mp ht)),dite_eq_right h] + rfl + +lemma candidates_code {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + originalCandidates (List.ofFn r,List.ofFn c)= + List.ofFn (fun k : Index m n (∑ i,r i) => + (tableAt r c k).map (fun T => matrixCode T.val)) := by + have hl : ((zeroGrid (0::List.ofFn r,0::List.ofFn c)).map + (fun _ => false)).length=m*n := by + simp only [zeroGrid,List.tail_cons,List.length_map,cellPairs, + List.length_range,List.length_ofFn] + unfold originalCandidates originalEnumerationData completionEnumerationData + simp only [originalLayoutMargins,List.sum_cons,zero_add,List.sum_ofFn] + rw [gridWords_finFunctions _ (∑ i,r i) (m*n) hl,List.map_ofFn] + apply congrArg List.ofFn + funext k + exact candidate_code r c (finFunctionFinEquiv.symm k) + +end +end ContingencyTables.OriginalTableBox + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCardinality.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCardinality.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fed04842156e9615a8ce35b0c44253af9215181 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCardinality.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableBox +import OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram + +namespace OAI + +/-! # Computing the number of feasible original-table box entries -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +def originalCardEntry (o : Option MatrixCode) : ℕ := if o.isSome then 1 else 0 + +def originalCardEntryRealizer : Realizer originalCardEntry := + choose FirstSuccessProgram.isSomeRealizer (constant 1) (constant 0) + +lemma polynomial_originalCardEntry : PolynomialTime originalCardEntryRealizer := + polynomial_choose FirstSuccessProgram.polynomial_isSome (polynomial_constant 1) (polynomial_constant 0) + +def originalCardinality (z : CompletionMargins) : ℕ := + ((originalCandidates z).map originalCardEntry).sum + +def originalCardinalityRealizer : Realizer originalCardinality := + composition (f := originalCandidates) (g := fun xs => (xs.map originalCardEntry).sum) + originalCandidatesRealizer (composition (map originalCardEntryRealizer) listSum) + +lemma work_originalCardinality : WorkBound originalCardinalityRealizer originalEnumerationMeasure := by + unfold originalCardinalityRealizer + exact work_then_polynomial work_originalCandidates + (polynomial_composition (polynomial_map polynomial_originalCardEntry) polynomial_listSum) + +lemma originalCardinality_actual {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + originalCardinality (List.ofFn r,List.ofFn c)=Fintype.card (Table r c) := by + classical + unfold originalCardinality + rw [OriginalTableBox.candidates_code,List.map_ofFn,List.sum_ofFn] + dsimp only [Function.comp_apply] + have he (k : OriginalTableBox.Index m n (∑ i,r i)) : + originalCardEntry ((OriginalTableBox.tableAt r c k).map (fun T => matrixCode T.val))= + ∑ T : Table r c,if OriginalTableBox.tableAt r c k=some T then 1 else 0 := by + cases hh : OriginalTableBox.tableAt r c k <;> simp [originalCardEntry] + simp_rw [he] + rw [Finset.sum_comm] + simp_rw [OriginalTableBox.tableAt_eq_some r c le_rfl] + have hl : (∑ T : Table r c,∑ k : OriginalTableBox.Index m n (∑ i,r i), + if OriginalTableBox.index r c le_rfl T=k then 1 else 0)=Fintype.card (Table r c) := by simp + exact hl + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCheck.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCheck.lean new file mode 100644 index 0000000000000000000000000000000000000000..646018187f8805d785a52e4ff5df26300802d585 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableCheck.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Machines.MatrixCodeEquality + +namespace OAI + +/-! # Binary row and column checks for original-table candidates -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev OriginalCheckInput := (List ℕ×List ℕ)×MatrixCode + +def originalColumnTotals (z : OriginalCheckInput) : List ℕ := + (List.range z.1.2.length).map (fun j => columnTotal (z.2,j)) + +def originalColumnTotalsRealizer : Realizer originalColumnTotals := + composition (pair second (composition + (composition (composition first second) listLength) range)) (mapWith columnTotalRealizer) + +lemma polynomial_originalColumnTotals : PolynomialTime originalColumnTotalsRealizer := by + unfold originalColumnTotalsRealizer + apply polynomial_composition _ (polynomial_mapWith polynomial_columnTotal) + apply polynomial_pair polynomial_second + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + +/-- Applied to the fixed rectangular shape generated by the enumerator. -/ +def originalTableTest (z : OriginalCheckInput) : Bool := + decide (z.2.map List.sum=z.1.1) && decide (originalColumnTotals z=z.1.2) + +def originalTableTestRealizer : Realizer originalTableTest := + composition (pair + (composition (pair (composition second (map listSum)) (composition first first)) listNatEqual) + (composition (pair originalColumnTotalsRealizer (composition first second)) listNatEqual)) boolAnd + +lemma polynomial_originalTableTest : PolynomialTime originalTableTestRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second (polynomial_map polynomial_listSum)) + (polynomial_composition polynomial_first polynomial_first)) polynomial_listNatEqual) + (polynomial_composition (polynomial_pair polynomial_originalColumnTotals + (polynomial_composition polynomial_first polynomial_second)) polynomial_listNatEqual)) polynomial_boolAnd + +lemma originalColumnTotals_code {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (X : Fin m → Fin n → ℕ) : + originalColumnTotals ((List.ofFn r,List.ofFn c),matrixCode X)= + List.ofFn (fun j => ∑ i,X i j) := by + unfold originalColumnTotals + rw [List.length_ofFn] + apply List.ext_getElem + · simp + · intro j hj hj' + have hjn : j (0,z.1)) + (g := fun z : ℕ×List ℕ => z.1::z.2) (pair (constant 0) first) listCons) + (composition (f := fun z : CompletionMargins => (0,z.2)) + (g := fun z : ℕ×List ℕ => z.1::z.2) (pair (constant 0) second) listCons) + +lemma polynomial_originalLayoutMargins : PolynomialTime originalLayoutMarginsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_first) polynomial_listCons) + (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_second) polynomial_listCons) + +def originalFreeMatrix (z : CompletionMargins×List ℕ) : MatrixCode := + unflattenGrid (originalLayoutMargins z.1,z.2) + +def originalFreeMatrixRealizer : Realizer originalFreeMatrix := + composition (pair (composition first originalLayoutMarginsRealizer) second) unflattenGridRealizer + +lemma polynomial_originalFreeMatrix : PolynomialTime originalFreeMatrixRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_originalLayoutMargins) polynomial_second) + polynomial_unflattenGrid + +def originalCandidate (z : CompletionMargins×List ℕ) : Option MatrixCode := + let X := originalFreeMatrix z + if originalTableTest (z.1,X) then some X else none + +def originalCandidateRealizer : Realizer originalCandidate := + choose (composition (pair first originalFreeMatrixRealizer) originalTableTestRealizer) + (composition originalFreeMatrixRealizer some) (constant none) + +lemma polynomial_originalCandidate : PolynomialTime originalCandidateRealizer := + polynomial_choose (polynomial_composition + (polynomial_pair polynomial_first polynomial_originalFreeMatrix) polynomial_originalTableTest) + (polynomial_composition polynomial_originalFreeMatrix polynomial_some) (polynomial_constant none) + +def originalEnumerationData (z : CompletionMargins) : GridEnumerationData := + completionEnumerationData (originalLayoutMargins z) + +def originalEnumerationDataRealizer : Realizer originalEnumerationData := + composition originalLayoutMarginsRealizer completionEnumerationDataRealizer + +lemma polynomial_originalEnumerationData : PolynomialTime originalEnumerationDataRealizer := + polynomial_composition polynomial_originalLayoutMargins polynomial_completionEnumerationData + +def originalCandidates (z : CompletionMargins) : List (Option MatrixCode) := + (gridWords (originalEnumerationData z)).map (fun v => originalCandidate (z,v)) + +def originalCandidatesRealizer : Realizer originalCandidates := + composition (pair identity (composition originalEnumerationDataRealizer gridWordsRealizer)) + (mapWith originalCandidateRealizer) + +def originalEnumerationMeasure (z : CompletionMargins) : ℕ := + gridStateCount (originalEnumerationData z)+weight z + +lemma work_originalCandidates : WorkBound originalCandidatesRealizer originalEnumerationMeasure := by + have hp : WorkBound originalEnumerationDataRealizer originalEnumerationMeasure := + work_of_polynomial polynomial_originalEnumerationData X + (fun z => by simp only [Polynomial.eval_X,originalEnumerationMeasure]; omega) + obtain ⟨p,hp'⟩ := hp + have hg : WorkBound (composition originalEnumerationDataRealizer gridWordsRealizer) + originalEnumerationMeasure := by + apply work_composition ⟨p,hp'⟩ work_gridWords (X+p) + intro z + have hw := hp' z + simp only [Polynomial.eval_add,Polynomial.eval_X] + change gridStateCount (originalEnumerationData z)+weight (originalEnumerationData z) ≤ _ + unfold originalEnumerationMeasure at hw ⊢ + omega + unfold originalCandidatesRealizer + apply work_then_polynomial _ (polynomial_mapWith polynomial_originalCandidate) + exact work_pair (work_of_polynomial polynomial_identity X + (fun z => by simp only [Polynomial.eval_X,originalEnumerationMeasure]; omega)) hg X + (fun z => by simp only [Polynomial.eval_X,originalEnumerationMeasure]; omega) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableIndex.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..6addb5500ab5dcdb4da7b9330305edf1c0317be3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTableIndex.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableBox +import OAI.Combinatorics.ContingencyTables.Dense.GridIndexProgram + +namespace OAI + +/-! # Binary lookup of an original table's finite-box index -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +def originalIndexInput (z : CompletionMargins×MatrixCode) : GridIndexData := + (z.2.flatten,z.1.1.sum+1) + +def originalIndexInputRealizer : Realizer originalIndexInput := + pair (composition second flatten) + (composition (composition (composition first first) listSum) successor) + +lemma polynomial_originalIndexInput : PolynomialTime originalIndexInputRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_flatten) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_listSum) polynomial_successor) + +def originalIndex (z : CompletionMargins×MatrixCode) : ℕ := gridIndex (originalIndexInput z) + +def originalIndexRealizer : Realizer originalIndex := + composition originalIndexInputRealizer gridIndexRealizer + +lemma polynomial_originalIndex : PolynomialTime originalIndexRealizer := + polynomial_composition polynomial_originalIndexInput polynomial_gridIndex + +lemma matrixCode_flatten {m n : ℕ} (X : Fin m → Fin n → ℕ) : + (matrixCode X).flatten=List.ofFn (fun k : Fin (m*n) => + X (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2) := by + rw [List.ofFn_mul] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + let k : Fin (m*n) := ⟨i.val*n+j.val,by nlinarith [i.isLt,j.isLt]⟩ + have hk : finProdFinEquiv (i,j)=k := Fin.ext (by dsimp [k,finProdFinEquiv]; ac_rfl) + change X i j=X (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2 + rw [←hk,Equiv.symm_apply_apply] + +lemma originalIndex_actual {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (T : Table r c) : + originalIndex ((List.ofFn r,List.ofFn c),matrixCode T.val)= + (OriginalTableBox.index r c le_rfl T).val := by + unfold originalIndex originalIndexInput + rw [matrixCode_flatten,List.sum_ofFn] + change gridIndex (List.ofFn (fun k => + (OriginalTableBox.encode r c le_rfl T k).val),(∑ i,r i)+1)=_ + rw [gridIndex_ofFn] + rfl + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTrialVector.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTrialVector.lean new file mode 100644 index 0000000000000000000000000000000000000000..1105c430e30025c74be3d7ee3f750a9fda310f88 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OriginalTrialVector.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialCountProgram +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxLaw + +namespace OAI + +/-! # Computing trial counts on every original-table candidate -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev OptionalTrialInput := WalkCountInput×Option MatrixCode + +def optionalTrialInput (z : OptionalTrialInput) : TrialCountInput := (z.1,z.2.getD []) + +def optionalTrialInputRealizer : Realizer optionalTrialInput := + pair first (composition (pair (constant ([] : MatrixCode)) second) FirstSuccessProgram.defaultRealizer) + +lemma polynomial_optionalTrialInput : PolynomialTime optionalTrialInputRealizer := + polynomial_pair polynomial_first (polynomial_composition + (polynomial_pair (polynomial_constant []) polynomial_second) FirstSuccessProgram.polynomial_default) + +def optionalTrialCount (z : OptionalTrialInput) : ℕ := + if z.2.isSome then trialCount (optionalTrialInput z) else 0 + +def optionalTrialCountRealizer : Realizer optionalTrialCount := + choose (composition second FirstSuccessProgram.isSomeRealizer) + (composition (f := optionalTrialInput) (g := trialCount) + optionalTrialInputRealizer trialCountRealizer) (constant 0) + +def optionalTrialMeasure (z : OptionalTrialInput) : ℕ := + trialCountMeasure (optionalTrialInput z)+weight z + +lemma work_optionalTrialCount : WorkBound optionalTrialCountRealizer optionalTrialMeasure := by + have hi (z : OptionalTrialInput) : weight z ≤ X.eval (optionalTrialMeasure z) := by + simp only [Polynomial.eval_X,optionalTrialMeasure] + omega + have ht : WorkBound (composition optionalTrialInputRealizer trialCountRealizer) + optionalTrialMeasure := by + apply work_composition (work_of_polynomial polynomial_optionalTrialInput X hi) work_trialCount X + intro z + simp only [Polynomial.eval_X,optionalTrialMeasure] + omega + unfold optionalTrialCountRealizer + exact work_choose (work_of_polynomial (polynomial_composition polynomial_second + FirstSuccessProgram.polynomial_isSome) X hi) ht + (work_of_polynomial (polynomial_constant 0) X hi) X hi + +abbrev TrialVectorInput := WalkCountInput×CompletionMargins + +def trialVector (z : TrialVectorInput) : List ℕ := + (originalCandidates z.2).map (fun o => optionalTrialCount (z.1,o)) + +def trialVectorRealizer : Realizer trialVector := + composition (f := fun z : TrialVectorInput => (z.1,originalCandidates z.2)) + (g := fun z : WalkCountInput×List (Option MatrixCode) => + z.2.map (fun o => optionalTrialCount (z.1,o))) + (pair first (composition second originalCandidatesRealizer)) + (mapWith optionalTrialCountRealizer) + +def trialVectorMeasure (z : TrialVectorInput) : ℕ := + originalEnumerationMeasure z.2+ + MeasuredMap.listMeasure optionalTrialMeasure (z.1,originalCandidates z.2)+weight z + +lemma work_trialVector : WorkBound trialVectorRealizer trialVectorMeasure := by + have hi (z : TrialVectorInput) : weight z ≤ X.eval (trialVectorMeasure z) := by + simp only [Polynomial.eval_X,trialVectorMeasure] + omega + have he : WorkBound (composition (second (A := WalkCountInput)) originalCandidatesRealizer) + trialVectorMeasure := by + apply work_composition (work_of_polynomial polynomial_second X hi) work_originalCandidates X + intro z + simp only [Polynomial.eval_X,trialVectorMeasure] + omega + unfold trialVectorRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_first X hi) he X hi) + (MeasuredMap.work_mapWith _ _ work_optionalTrialCount) X + intro z + simp only [Polynomial.eval_X,trialVectorMeasure,Function.comp_apply] + omega + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts OriginalTableBox +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +attribute [local irreducible] trialCount listedTrialCounts matrixInput + +lemma trialVector_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) : + trialVector ((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)), + (List.ofFn r,List.ofFn c))= + List.ofFn (fun k : OriginalTableBox.Index m n (∑ i,r i) => + (OriginalBoxLaw.law r c le_rfl (listedTrialCounts r c e hr hc b h hb z N)).count (some k)) := by + unfold trialVector + rw [candidates_code,List.map_ofFn] + apply congrArg List.ofFn + funext k + rw [OriginalBoxLaw.count_some] + dsimp only [Function.comp_apply] + cases he : tableAt r c k with + | none => rfl + | some T => + simp only [Option.map_some,optionalTrialCount,Option.isSome_some,ite_true,optionalTrialInput, + Option.getD_some,Option.elim_some] + exact trialCount_actual r c e hr hc b h hb htotal z xs hs N T + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterMatrixSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterMatrixSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb1395adef3f7bbb2369551399789fc31b85e372 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterMatrixSemantics.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OuterTrialProgram +import OAI.Combinatorics.ContingencyTables.Machines.TranslationDecisionProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallViewLookupProgram +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginReference + +namespace OAI + +/-! # Literal entries and acceptance of the original-table output program -/ + +namespace ContingencyTables.ProfilePrograms +open DensePrograms + +lemma paddingTest_matrixCode {m n : ℕ} (L : ℕ) (X : Fin m → Fin n → ℕ) : + paddingTest (L,matrixCode X)=true ↔ ∀ i j,L≤X i j := by + simp only [paddingTest,matrixCode,List.all_eq_true] + constructor + · intro h i j + exact of_decide_eq_true (h _ (List.mem_ofFn.mpr ⟨i,rfl⟩) _ (List.mem_ofFn.mpr ⟨j,rfl⟩)) + · intro h row hrow a ha + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hrow + obtain ⟨j,rfl⟩ := List.mem_ofFn.mp ha + exact decide_eq_true (h i j) + +lemma paddingTest_tableOutput {m n : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) (L : ℕ) (X : Table R P) : + paddingTest (L,tableOutput X)=true ↔ ∀ i j,L≤X.val i j := by + rw [tableOutput,paddingTest_matrixCode] + constructor + · intro h i j + simpa only [Equiv.apply_symm_apply] using + h ((finSuccEquiv m).symm i) ((finSuccEquiv n).symm j) + · intro h i j + exact h _ _ + +private lemma map_range_ofFn {α : Type*} (f : ℕ → α) (n : ℕ) : + (List.range n).map f=List.ofFn (fun i : Fin n => f i.val) := by + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi hj + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + +lemma outputMatrix_code {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (data : OuterTableData) : + outputMatrix ((List.ofFn r,List.ofFn c),data)= + matrixCode (fun i : Fin m => fun j : Fin n => outputEntry (data,(i.val,j.val))) := by + simp only [outputMatrix,outputRows,outputColumns,outputShape,completionRows,completionColumns, + outputRow,outputRowEntry,List.length_ofFn] + rw [map_range_ofFn] + apply congrArg List.ofFn + funext i + exact map_range_ofFn _ _ + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles +open scoped Classical + +noncomputable section +variable {m n q : ℕ} + +lemma optionIndexEquiv_val (k : ℕ) (hk : 0 omega + | succ k => + change ((finSuccEquiv k).symm i).val=optionIndex i + cases i <;> simp only [DensePrograms.finSuccEquiv_symm_none, + _root_.finSuccEquiv_symm_some,optionIndex,Fin.val_zero,Fin.val_succ] + +lemma largeOption_index (r : Fin m → ℕ) (U : ℕ) + (hr : 0<(largeIndices (U,List.ofFn r)).length) + (i : Option (Fin ((largeIndices (U,List.ofFn r)).length-1))) : + (largeIndices (U,List.ofFn r)).idxOf (largeOptionEquiv r U hr i).val.val=optionIndex i := by + change (largeIndices (U,List.ofFn r)).idxOf + (largeIndexEquiv r U (optionIndexEquiv _ hr i)).val.val=_ + rw [largeIndexEquiv_val,(largeIndices_nodup U (List.ofFn r)).idxOf_getElem] + exact optionIndexEquiv_val _ hr i + +lemma outputEntry_small (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + (z : SmallProfile small) (rows columns : List ℕ) (U L : ℕ) (X : MatrixCode) + (i : Fin m) (j : Fin n) (hs : small i j=true) : + outputEntry ((((cellCatalog small e,profileCode small e z),(rows,columns)),((U,L),X)), + (i.val,j.val))=smallView small z false i j := by + have hm := (mem_cellCatalog small e (i,j)).mpr hs + exact (ite_eq_left (List.idxOf_lt_length_iff.mpr hm)).trans (lookupView_eq small e z false i j) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTableProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTableProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..922a5f6d8951a1fc5629592eafa75e7a68585a73 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTableProgram.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionProgram + +namespace OAI + +/-! # Reconstructing and testing an original table from an outer trial -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev OuterTableData := + ((List (ℕ×ℕ)×(List ℕ×List ℕ))×(List ℕ×List ℕ))×((ℕ×ℕ)×MatrixCode) +abbrev OuterTableCell := OuterTableData×(ℕ×ℕ) + +def outputCellPosition (z : OuterTableCell) : ℕ := z.1.1.1.1.idxOf z.2 +def outputCellPositionRealizer : Realizer outputCellPosition := + composition (pair second (composition (composition (composition first first) first) first)) + cellLookupRealizer + +theorem polynomial_outputCellPosition : PolynomialTime outputCellPositionRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first)) + polynomial_cellLookup + +def outputSmallEntry (z : OuterTableCell) : ℕ := z.1.1.1.2.1.getD (outputCellPosition z) 0 +def outputSmallEntryRealizer : Realizer outputSmallEntry := + composition (pair (composition (composition (composition (composition first first) first) second) first) + outputCellPositionRealizer) (getDFast 0) + +theorem polynomial_outputSmallEntry : PolynomialTime outputSmallEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_first) polynomial_outputCellPosition) (polynomial_getDFast 0) + +def outputDensePosition (z : OuterTableCell) : ℕ×ℕ := + (z.1.1.2.1.idxOf z.2.1,z.1.1.2.2.idxOf z.2.2) +def outputDensePositionRealizer : Realizer outputDensePosition := + pair (composition (pair (composition second first) + (composition (composition (composition first first) second) first)) (indexOf natEqual)) + (composition (pair (composition second second) + (composition (composition (composition first first) second) second)) (indexOf natEqual)) + +theorem polynomial_outputDensePosition : PolynomialTime outputDensePositionRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first)) + (polynomial_indexOf polynomial_natEqual)) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second)) + (polynomial_indexOf polynomial_natEqual)) + +def outputLargeEntry (z : OuterTableCell) : ℕ := + matrixEntry (z.1.2.2,outputDensePosition z)-z.1.2.1.2 +def outputLargeEntryRealizer : Realizer outputLargeEntry := + composition (pair (composition (pair (composition (composition first second) second) + outputDensePositionRealizer) matrixEntryRealizer) + (composition (composition (composition first second) first) second)) subtract + +theorem polynomial_outputLargeEntry : PolynomialTime outputLargeEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_outputDensePosition) polynomial_matrixEntry) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_first) polynomial_second)) + polynomial_subtract + +def outputEntry (z : OuterTableCell) : ℕ := + if outputCellPosition z < z.1.1.1.1.length then outputSmallEntry z else outputLargeEntry z +def outputEntryRealizer : Realizer outputEntry := + (choose (composition (pair outputCellPositionRealizer + (composition (composition (composition (composition first first) first) first) listLength)) less) + outputSmallEntryRealizer outputLargeEntryRealizer).congr + (by intro z; simp only [Function.comp_apply,decide_eq_true_eq,outputEntry]) + +theorem polynomial_outputEntry : PolynomialTime outputEntryRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_outputCellPosition + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + polynomial_listLength)) polynomial_less) + polynomial_outputSmallEntry polynomial_outputLargeEntry) + +def paddingTest (z : ℕ×MatrixCode) : Bool := z.2.all (fun row => row.all (fun a => decide (z.1≤a))) +def paddingTestRealizer : Realizer paddingTest := + (composition (mapWith (composition (mapWith leNat) all)) all).congr + (by intro z; simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,paddingTest]) + +theorem polynomial_paddingTest : PolynomialTime paddingTestRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_mapWith (polynomial_composition (polynomial_mapWith polynomial_leNat) polynomial_all)) + polynomial_all) + +def outerSuccess (z : OuterTableData) : Bool := + balancedTest (z.1.1.2,z.2.1.1) && paddingTest (z.2.1.2,z.2.2) + +def outerSuccessRealizer : Realizer outerSuccess := + composition (pair + (composition (pair (composition (composition first first) second) + (composition (composition second first) first)) balancedTestRealizer) + (composition (pair (composition (composition second first) second) + (composition second second)) paddingTestRealizer)) boolAnd + +theorem polynomial_outerSuccess : PolynomialTime outerSuccessRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_first)) + polynomial_balancedTest) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_paddingTest)) polynomial_boolAnd + +abbrev OuterMatrixInput := (List ℕ×List ℕ)×OuterTableData + +def outputShape (z : OuterMatrixInput) : CompletionData := (z.1,[]) +def outputShapeRealizer : Realizer outputShape := pair first (constant []) + +theorem polynomial_outputShape : PolynomialTime outputShapeRealizer := + polynomial_pair polynomial_first (polynomial_constant []) + +def outputRows (z : OuterMatrixInput) : List ℕ := completionRows (outputShape z) +def outputColumns (z : OuterMatrixInput) : List ℕ := completionColumns (outputShape z) +def outputRowsRealizer : Realizer outputRows := composition outputShapeRealizer completionRowsRealizer +def outputColumnsRealizer : Realizer outputColumns := composition outputShapeRealizer completionColumnsRealizer + +theorem polynomial_outputRows : PolynomialTime outputRowsRealizer := + polynomial_composition polynomial_outputShape polynomial_completionRows +theorem polynomial_outputColumns : PolynomialTime outputColumnsRealizer := + polynomial_composition polynomial_outputShape polynomial_completionColumns + +def outputRowEntry (z : (OuterMatrixInput×ℕ)×ℕ) : ℕ := outputEntry (z.1.1.2,(z.1.2,z.2)) +def outputRowEntryRealizer : Realizer outputRowEntry := + composition (pair (composition (composition first first) second) + (pair (composition first second) second)) outputEntryRealizer + +theorem polynomial_outputRowEntry : PolynomialTime outputRowEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_outputEntry + +def outputRow (z : OuterMatrixInput×ℕ) : List ℕ := + (outputColumns z.1).map (fun j => outputRowEntry (z,j)) +def outputRowRealizer : Realizer outputRow := + composition (pair identity (composition first outputColumnsRealizer)) (mapWith outputRowEntryRealizer) + +theorem polynomial_outputRow : PolynomialTime outputRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_outputColumns)) + (polynomial_mapWith polynomial_outputRowEntry) + +def outputMatrix (z : OuterMatrixInput) : MatrixCode := + (outputRows z).map (fun i => outputRow (z,i)) +def outputMatrixRealizer : Realizer outputMatrix := + composition (pair identity outputRowsRealizer) (mapWith outputRowRealizer) + +theorem polynomial_outputMatrix : PolynomialTime outputMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_outputRows) + (polynomial_mapWith polynomial_outputRow) + +def acceptedTable (z : OuterMatrixInput) : Option MatrixCode := + if outerSuccess z.2 then some (outputMatrix z) else none +def acceptedTableRealizer : Realizer acceptedTable := + choose (composition second outerSuccessRealizer) + (composition outputMatrixRealizer MatchingFPRAS.TreeTyped.some) (constant none) + +theorem polynomial_acceptedTable : PolynomialTime acceptedTableRealizer := + polynomial_choose (polynomial_composition polynomial_second polynomial_outerSuccess) + (polynomial_composition polynomial_outputMatrix polynomial_some) (polynomial_constant none) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTrialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTrialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9d36e934c4c2d1370b3c478781ea96451b79ba6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/OuterTrialProgram.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OuterTableProgram + +namespace OAI + +/-! # Preparing the original-table return from a residual draw -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +abbrev OuterTrialInput := (ProfileCheckData×ℕ)×MatrixCode + +def outputLargeRows (z : OuterTrialInput) : List ℕ := largeIndices (z.1.1.2,z.1.1.1.2.1) +def outputLargeColumns (z : OuterTrialInput) : List ℕ := largeIndices (z.1.1.2,z.1.1.1.2.2) + +def outputLargeRowsRealizer : Realizer outputLargeRows := + composition (pair (composition (composition first first) second) + (composition (composition (composition (composition first first) first) second) first)) + largeIndicesRealizer +def outputLargeColumnsRealizer : Realizer outputLargeColumns := + composition (pair (composition (composition first first) second) + (composition (composition (composition (composition first first) first) second) second)) + largeIndicesRealizer + +theorem polynomial_outputLargeRows : PolynomialTime outputLargeRowsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_first)) polynomial_largeIndices +theorem polynomial_outputLargeColumns : PolynomialTime outputLargeColumnsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_second)) polynomial_largeIndices + +def outputData (z : OuterTrialInput) : OuterTableData := + ((z.1.1.1.1,(outputLargeRows z,outputLargeColumns z)),((z.1.1.2,z.1.2),z.2)) +def outputDataRealizer : Realizer outputData := + pair (pair (composition (composition (composition first first) first) first) + (pair outputLargeRowsRealizer outputLargeColumnsRealizer)) + (pair (pair (composition (composition first first) second) (composition first second)) second) + +theorem polynomial_outputData : PolynomialTime outputDataRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_pair polynomial_outputLargeRows polynomial_outputLargeColumns)) + (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) + +def prepareOutput (z : OuterTrialInput) : OuterMatrixInput := (z.1.1.1.2,outputData z) +def prepareOutputRealizer : Realizer prepareOutput := + pair (composition (composition (composition first first) first) second) outputDataRealizer + +theorem polynomial_prepareOutput : PolynomialTime prepareOutputRealizer := + polynomial_pair (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + polynomial_outputData + +def outerTrial (z : OuterTrialInput) : Option MatrixCode := acceptedTable (prepareOutput z) +def outerTrialRealizer : Realizer outerTrial := + composition prepareOutputRealizer acceptedTableRealizer + +theorem polynomial_outerTrial : PolynomialTime outerTrialRealizer := + polynomial_composition polynomial_prepareOutput polynomial_acceptedTable + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedCompletions.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedCompletions.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c913b082097c59132d5d824cd99d5ea04c5b32d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedCompletions.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RowColumnPenalties + +namespace OAI + +/-! +# Zero penalties are exactly padded residual completions + +Retain the small x,y views and fill every large cell with the balanced +pair (A,B-A). For an assignment supported on large cells, the full margin +equations are precisely the padded residual margin equations. The small +positive-part penalties enforce the original nonnegative residual tests. +-/ + +namespace ContingencyTables.PaddedCompletions + +open scoped BigOperators Classical +open RowColumnPenalties NestedPenaltyApplication BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def smallRow (small : I → J → Bool) (X : I → J → ℕ) (i : I) : ℕ := + ∑ j, if small i j then X i j else 0 + +noncomputable def smallColumn (small : I → J → Bool) (B Y : I → J → ℕ) (j : J) : ℕ := + ∑ i, if small i j then B i j-Y i j else 0 + +noncomputable def rowLargeCount (small : I → J → Bool) (i : I) : ℕ := + ∑ j, if small i j then 0 else 1 + +noncomputable def columnLargeCount (small : I → J → Bool) (j : J) : ℕ := + ∑ i, if small i j then 0 else 1 + +def profile (small : I → J → Bool) (B X Y A : I → J → ℕ) : ((I × J) × Bool) → ℕ := + fun u => if u.2 then (if small u.1.1 u.1.2 then Y u.1.1 u.1.2 else B u.1.1 u.1.2-A u.1.1 u.1.2) + else (if small u.1.1 u.1.2 then X u.1.1 u.1.2 else A u.1.1 u.1.2) + +def Supported (small : I → J → Bool) (A : I → J → ℕ) : Prop := + ∀ i j, small i j=true → A i j=0 + +def OriginalResidualsNonnegative (small : I → J → Bool) (B X Y : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) : Prop := + (∀ i, smallRow small X i ≤ r i) ∧ (∀ j, smallColumn small B Y j ≤ c j) + +omit [Fintype I] [Fintype J] in +lemma profile_inBox (small : I → J → Bool) (B X Y A : I → J → ℕ) + (hX : ∀ i j, small i j=true → X i j ≤ B i j) + (hY : ∀ i j, small i j=true → Y i j ≤ B i j) + (hA : ∀ i j, small i j=false → A i j ≤ B i j) : + InBox (fun u => B u.1.1 u.1.2) (profile small B X Y A) := by + rintro ⟨⟨i,j⟩,t⟩ + cases t <;> cases hs : small i j <;> simp only [profile,hs,ite_true] + · exact hA i j hs + · exact hX i j hs + · exact Nat.sub_le _ _ + · exact hY i j hs + +omit [Fintype I] in +lemma profile_row (small : I → J → Bool) (B X Y A : I → J → ℕ) + (hA : Supported small A) (i : I) : + (∑ j, rowView (profile small B X Y A) i j)=smallRow small X i+∑ j, A i j := by + unfold smallRow + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j + · simp [rowView,profile,hs] + · simp [rowView,profile,hs,hA i j hs] + +omit [Fintype J] in +lemma profile_column (small : I → J → Bool) (B X Y A : I → J → ℕ) + (hA : Supported small A) (hcap : ∀ i j, small i j=false → A i j ≤ B i j) (j : J) : + (∑ i, columnView B (profile small B X Y A) i j)=smallColumn small B Y j+∑ i, A i j := by + unfold smallColumn + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j + · simpa [columnView,profile,hs] using Nat.sub_sub_self (hcap i j hs) + · simp [columnView,profile,hs,hA i j hs] + +omit [Fintype I] in +lemma profile_small_row (small : I → J → Bool) (B X Y A : I → J → ℕ) (i : I) : + (∑ j, if small i j then rowView (profile small B X Y A) i j else 0)=smallRow small X i := by + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j <;> simp [rowView,profile,hs] + +omit [Fintype J] in +lemma profile_small_column (small : I → J → Bool) (B X Y A : I → J → ℕ) (j : J) : + (∑ i, if small i j then columnView B (profile small B X Y A) i j else 0)=smallColumn small B Y j := by + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j <;> simp [columnView,profile,hs] + +/-- No positivity or balance assumption is imposed on the retained +small profile. Thus this exact identity covers transversals and defects. -/ +theorem zero_penalty_iff_padded_completion (small : I → J → Bool) (B X Y A : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (hA : Supported small A) + (hX : ∀ i j, small i j=true → X i j ≤ B i j) + (hY : ∀ i j, small i j=true → Y i j ≤ B i j) + (hcap : ∀ i j, small i j=false → A i j ≤ B i j) : + penalty RowColumnPenalties.cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L)) + viewSlope (smallOffset small B r c) viewSlope (profile small B X Y A)=0 ↔ + OriginalResidualsNonnegative small B X Y r c ∧ + HasMargins A (fun i => r i-smallRow small X i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B Y j+columnLargeCount small j*L) := by + rw [penalty_zero_iff small B r _ c _ _ (profile_inBox small B X Y A hX hY hcap)] + simp only [FullConditions,profile_row small B X Y A hA,profile_column small B X Y A hA hcap, + profile_small_row,profile_small_column,OriginalResidualsNonnegative,HasMargins] + constructor + · rintro ⟨hr,hc,hsr,hsc⟩ + refine ⟨⟨hsr,hsc⟩,?_,?_⟩ + · intro i; have h := hr i; have hs := hsr i; omega + · intro j; have h := hc j; have hs := hsc j; omega + · rintro ⟨⟨hsr,hsc⟩,hr,hc⟩ + refine ⟨?_,?_,hsr,hsc⟩ + · intro i; have h := hr i; have hs := hsr i; omega + · intro j; have h := hc j; have hs := hsc j; omega + +end ContingencyTables.PaddedCompletions + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedEnumerationBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedEnumerationBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfab1b52dd06562676d7b5b2165e763911e42082 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedEnumerationBounds.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginProgram +import OAI.Combinatorics.ContingencyTables.Machines.CompletionEnumerationProgram + +namespace OAI + +/-! # Enumeration bounds uniform over all proposed small profiles -/ + +namespace ContingencyTables.ProfilePrograms +open DensePrograms + +lemma list_getD_le_sum (as : List ℕ) (i : ℕ) : as.getD i 0 ≤ as.sum := by + induction as generalizing i with + | nil => simp + | cons a as ih => + cases i with + | zero => simp + | succ i => + simpa only [List.getD_cons_succ,List.sum_cons] using + (ih i).trans (Nat.le_add_left as.sum a) + +lemma list_sum_le_length_mul (as : List ℕ) (B : ℕ) (h : ∀ a∈as,a ≤ B) : + as.sum ≤ as.length*B := by + induction as with + | nil => simp + | cons a as ih => + have ha := h a (by simp) + have hs := ih (by intro b hb; exact h b (by simp [hb])) + simp only [List.sum_cons,List.length_cons,Nat.add_mul,Nat.one_mul] + omega + +lemma largeCount_le_length (U : ℕ) (as : List ℕ) : largeCount (U,as) ≤ as.length := by + unfold largeCount + induction as with + | nil => simp + | cons a as ih => + simp only [List.map_cons,List.sum_cons,List.length_cons] + change (as.map (fun a => if U ≤ a then 1 else 0)).sum ≤ as.length at ih + change (if U ≤ a then 1 else 0)+(as.map (fun a => if U ≤ a then 1 else 0)).sum ≤ as.length+1 + split_ifs <;> omega + +/-- Rejected profiles can decrease residual margins but cannot enlarge +them beyond the original margin and its deterministic padding. -/ +lemma paddedMarginAt_le (row : Bool) (z : PaddingData) (i : ℕ) : + paddedMarginAt row (z,i) ≤ + (marginList row z.1).sum+(marginList (!row) z.1).length*z.2 := by + have ha := list_getD_le_sum (marginList row z.1) i + have hc := largeCount_le_length z.1.2 (marginList (!row) z.1) + have hs : (marginList row z.1).getD i 0-lineSum row (lineArgument row (z.1,i)) ≤ + (marginList row z.1).sum := (Nat.sub_le _ _).trans ha + unfold paddedMarginAt largeFlag + dsimp only + split_ifs + · simpa only [one_mul] using Nat.add_le_add hs (Nat.mul_le_mul_right z.2 hc) + · simpa only [zero_mul,add_zero] using hs.trans (Nat.le_add_right _ _) + +lemma largePaddedMargins_length (row : Bool) (z : PaddingData) : + (largePaddedMargins row z).length ≤ (marginList row z.1).length := by + rw [largePaddedMargins_eq,List.length_map] + exact (List.length_filter_le _ _).trans_eq List.length_range + +lemma largePaddedMargins_entry (row : Bool) (z : PaddingData) (a : ℕ) + (ha : a∈largePaddedMargins row z) : + a ≤ (marginList row z.1).sum+(marginList (!row) z.1).length*z.2 := by + rw [largePaddedMargins_eq] at ha + obtain ⟨i,_,rfl⟩ := List.mem_map.mp ha + exact paddedMarginAt_le row z i + +lemma largePaddedMargins_sum (row : Bool) (z : PaddingData) : + (largePaddedMargins row z).sum ≤ (marginList row z.1).length* + ((marginList row z.1).sum+(marginList (!row) z.1).length*z.2) := by + exact (list_sum_le_length_mul _ _ (largePaddedMargins_entry row z)).trans + (Nat.mul_le_mul_right _ (largePaddedMargins_length row z)) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..83776d3a0c30545cb149b851992c9e674e9ccdd9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualProgram.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallMarginTestProgram +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPreparedProposal + +namespace OAI + +/-! # Computing padded residual margins from the stored small profile -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def largeFlag (z : ℕ×ℕ) : ℕ := if z.1≤z.2 then 1 else 0 + +def largeFlagRealizer : Realizer largeFlag := + (choose leNat (constant 1) (constant 0)).congr + (by intro z; simp only [largeFlag,decide_eq_true_eq]) + +theorem polynomial_largeFlag : PolynomialTime largeFlagRealizer := + polynomial_congr _ (polynomial_choose polynomial_leNat (polynomial_constant 1) (polynomial_constant 0)) + +def largeCount (z : ℕ×List ℕ) : ℕ := (z.2.map (fun a => largeFlag (z.1,a))).sum + +def largeCountRealizer : Realizer largeCount := composition (mapWith largeFlagRealizer) listSum + +theorem polynomial_largeCount : PolynomialTime largeCountRealizer := + polynomial_composition (polynomial_mapWith polynomial_largeFlag) polynomial_listSum + +abbrev PaddingData := MarginCheckData×ℕ + +def paddedMarginAt (row : Bool) (z : PaddingData×ℕ) : ℕ := + let a := (marginList row z.1.1).getD z.2 0 + let used := lineSum row (lineArgument row (z.1.1,z.2)) + a-used+largeFlag (z.1.1.2,a)*largeCount (z.1.1.2,marginList (!row) z.1.1)*z.1.2 + +def paddedMarginAtRealizer (row : Bool) : Realizer (paddedMarginAt row) := by + let arg : Realizer (fun z : PaddingData×ℕ => (z.1.1,z.2)) := + pair (composition first first) second + let value := composition arg (marginValueRealizer row) + let used := composition arg (lineValueRealizer row) + let threshold : Realizer (fun z : PaddingData×ℕ => z.1.1.2) := + composition (composition first first) second + let pad : Realizer (fun z : PaddingData×ℕ => z.1.2) := composition first second + let flag := composition (pair threshold value) largeFlagRealizer + let count := composition (pair threshold + (composition (composition first first) (marginListRealizer (!row)))) largeCountRealizer + let amount := composition (pair (composition (pair flag count) multiply) pad) multiply + let remain := composition (pair value used) subtract + let result := composition (pair remain amount) add + exact result + +theorem polynomial_paddedMarginAt (row : Bool) : PolynomialTime (paddedMarginAtRealizer row) := by + have ha : PolynomialTime (pair (composition + (first (A := PaddingData) (B := ℕ)) first) second) := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second + have ht : PolynomialTime (composition (composition + (first (A := PaddingData) (B := ℕ)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + unfold paddedMarginAtRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition ha (polynomial_marginValue row)) + (polynomial_composition ha (polynomial_lineValue row))) polynomial_subtract) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair ht + (polynomial_composition ha (polynomial_marginValue row))) polynomial_largeFlag) + (polynomial_composition (polynomial_pair ht + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + (polynomial_marginList (!row)))) polynomial_largeCount)) polynomial_multiply) + (polynomial_composition polynomial_first polynomial_second)) polynomial_multiply)) polynomial_add + +def paddedMargins (row : Bool) (z : PaddingData) : List ℕ := + (List.range (marginList row z.1).length).map (fun i => paddedMarginAt row (z,i)) + +def paddedMarginsRealizer (row : Bool) : Realizer (paddedMargins row) := + composition (pair identity (composition first (marginIndices row))) (mapWith (paddedMarginAtRealizer row)) + +theorem polynomial_paddedMargins (row : Bool) : PolynomialTime (paddedMarginsRealizer row) := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first (polynomial_marginIndices row))) + (polynomial_mapWith (polynomial_paddedMarginAt row)) + +open scoped BigOperators + +lemma largeCount_ofFn {n : ℕ} (U : ℕ) (r : Fin n → ℕ) : + largeCount (U,List.ofFn r)=∑ i,if U≤r i then 1 else 0 := by + simp only [largeCount,List.map_ofFn,List.sum_ofFn,Function.comp_apply,largeFlag] + +lemma paddedMarginAt_eq (row : Bool) (z : PaddingData) (i : ℕ) : + paddedMarginAt row (z,i)= + (marginList row z.1).getD i 0-lineSum row (lineArgument row (z.1,i))+ + (if z.1.2≤(marginList row z.1).getD i 0 + then largeCount (z.1.2,marginList (!row) z.1)*z.2 else 0) := by + unfold paddedMarginAt largeFlag + dsimp only + split_ifs <;> simp only [one_mul,zero_mul,add_zero] + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..379ce2d0281c06d95ff337841f160b1b15e6bd70 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PaddedResidualSemantics.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PaddedResidualProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallMarginSemantics + +namespace OAI + +/-! # The residual program computes the literal padded margins -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms PaddedCompletions SmallContextCoordinates SmallContextFibres +open PhysicalCompletionFibres FirstPaperProfiles CompletionCounts +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} + +lemma rowLargeCount_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U : ℕ) (i : Fin m) : + rowLargeCount (firstPaperSmall r c U) i= + if U≤r i then largeCount (U,List.ofFn c) else 0 := by + rw [largeCount_ofFn] + unfold rowLargeCount + have he (j : Fin n) : (if firstPaperSmall r c U i j then 0 else 1)= + if U≤r i then (if U≤c j then 1 else 0) else 0 := by + simp only [firstPaperSmall,decide_eq_true_eq] + split_ifs <;> omega + simp_rw [he] + split_ifs <;> simp + +lemma columnLargeCount_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U : ℕ) (j : Fin n) : + columnLargeCount (firstPaperSmall r c U) j= + if U≤c j then largeCount (U,List.ofFn r) else 0 := by + rw [largeCount_ofFn] + unfold columnLargeCount + have he (i : Fin m) : (if firstPaperSmall r c U i j then 0 else 1)= + if U≤c j then (if U≤r i then 1 else 0) else 0 := by + simp only [firstPaperSmall,decide_eq_true_eq] + split_ifs <;> omega + simp_rw [he] + split_ifs <;> simp + +theorem paddedRowAt_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (z : SmallProfile (firstPaperSmall r c U)) (i : Fin m) : + paddedMarginAt true + (((((cellCatalog (firstPaperSmall r c U) e,viewList (firstPaperSmall r c U) e z false), + (List.ofFn r,List.ofFn c)),U),L),i.val)= + r i-smallRow (firstPaperSmall r c U) (smallView (firstPaperSmall r c U) z false) i+ + rowLargeCount (firstPaperSmall r c U) i*L := by + rw [paddedMarginAt_eq] + simp only [marginList,ite_true,Bool.not_true,Bool.false_eq_true,ite_false,lineArgument, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,dite_eq_left i.isLt,Option.getD_some,Fin.eta] + rw [storedRowSum_eq,rowLargeCount_code] + split_ifs <;> simp only [zero_mul] + +theorem paddedColumnAt_code (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) + (e : Fin q ≃ Cells (firstPaperSmall r c U)) + (B : Fin m → Fin n → ℕ) (hB : ∀ a : Cells (firstPaperSmall r c U),B a.val.1 a.val.2=U) + (z : SmallProfile (firstPaperSmall r c U)) (j : Fin n) : + paddedMarginAt false + (((((cellCatalog (firstPaperSmall r c U) e,complementValues (U,viewList (firstPaperSmall r c U) e z true)), + (List.ofFn r,List.ofFn c)),U),L),j.val)= + c j-smallColumn (firstPaperSmall r c U) B (smallView (firstPaperSmall r c U) z true) j+ + columnLargeCount (firstPaperSmall r c U) j*L := by + rw [paddedMarginAt_eq] + simp only [marginList,ite_true,Bool.not_false,Bool.false_eq_true,ite_false,lineArgument, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,dite_eq_left j.isLt,Option.getD_some,Fin.eta] + rw [complementedColumnSum_eq _ _ B _ U hB,columnLargeCount_code] + split_ifs <;> simp only [zero_mul] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/Padding.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/Padding.lean new file mode 100644 index 0000000000000000000000000000000000000000..eeaf4a48ce566c5362aab5995828c15bb52591d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/Padding.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallEntries +import Mathlib.Algebra.BigOperators.Field +import Mathlib.SetTheory.Cardinal.Finite + +namespace OAI + +/-! +# Padding and the successful-table bijection + +Padding a designated rectangle by a fixed amount gives a bijection from +original tables to enlarged-margin tables whose entries dominate the +padding. Each successful joint object therefore yields exactly one table. +-/ + +namespace ContingencyTables + +open Finset +open scoped Classical + +variable {I J : Type*} [Fintype I] [Fintype J] + +def paddedRows (r : I → ℕ) (P : I → J → ℕ) : I → ℕ := fun i => r i + ∑ j, P i j +def paddedColumns (c : J → ℕ) (P : I → J → ℕ) : J → ℕ := fun j => c j + ∑ i, P i j + +def padTable {r : I → ℕ} {c : J → ℕ} (P : I → J → ℕ) (X : Table r c) : + Table (paddedRows r P) (paddedColumns c P) := + ⟨fun i j => X.val i j + P i j, by + constructor + · intro i + rw [sum_add_distrib, X.property.1 i] + rfl + · intro j + rw [sum_add_distrib, X.property.2 j] + rfl⟩ + +def unpadTable {r : I → ℕ} {c : J → ℕ} (P : I → J → ℕ) + (Y : Table (paddedRows r P) (paddedColumns c P)) + (hY : ∀ i j, P i j ≤ Y.val i j) : Table r c := by + refine ⟨fun i j => Y.val i j - P i j, ?_, ?_⟩ + · intro i + have hsum := sum_congr (s₁ := (univ : Finset J)) (f := fun j => Y.val i j) + (g := fun j => (Y.val i j - P i j) + P i j) rfl + (fun j _ => (Nat.sub_add_cancel (hY i j)).symm) + rw [Y.property.1 i, sum_add_distrib] at hsum + exact Nat.add_right_cancel hsum.symm + · intro j + have hsum := sum_congr (s₁ := (univ : Finset I)) (f := fun i => Y.val i j) + (g := fun i => (Y.val i j - P i j) + P i j) rfl + (fun i _ => (Nat.sub_add_cancel (hY i j)).symm) + rw [Y.property.2 j, sum_add_distrib] at hsum + exact Nat.add_right_cancel hsum.symm + +/-- Successful enlarged tables are in exact bijection with original tables. -/ +def paddingEquiv (r : I → ℕ) (c : J → ℕ) (P : I → J → ℕ) : + Table r c ≃ {Y : Table (paddedRows r P) (paddedColumns c P) // + ∀ i j, P i j ≤ Y.val i j} where + toFun := fun X => ⟨padTable P X, fun _ _ => Nat.le_add_left _ _⟩ + invFun := fun Y => unpadTable P Y.val Y.property + left_inv := by + intro X + apply Subtype.ext + funext i j + exact Nat.add_sub_cancel _ _ + right_inv := by + intro Y + apply Subtype.ext + apply Subtype.ext + funext i j + exact Nat.sub_add_cancel (Y.property i j) + +theorem successful_card (r : I → ℕ) (c : J → ℕ) (P : I → J → ℕ) : + Fintype.card {Y : Table (paddedRows r P) (paddedColumns c P) // + ∀ i j, P i j ≤ Y.val i j} = Fintype.card (Table r c) := by + classical + exact (Fintype.card_congr (paddingEquiv r c P)).symm + +/-- The union bound as an injection with a deterministically chosen bad +cell label. This counts each bad table once, even if several entries fail. -/ +theorem card_exists_le_sum {α K : Type*} [Fintype α] [Fintype K] + (P : K → α → Prop) : + Fintype.card {x : α // ∃ k, P k x} ≤ ∑ k, Fintype.card {x : α // P k x} := by + classical + let encode : {x : α // ∃ k, P k x} → Σ k, {x : α // P k x} := + fun x => ⟨Classical.choose x.property, x.val, Classical.choose_spec x.property⟩ + have hinj : Function.Injective encode := by + intro x y h + apply Subtype.ext + exact congrArg (fun z : Σ k, {x : α // P k x} => z.2.val) h + simpa only [Fintype.card_sigma] using Fintype.card_le_of_injective encode hinj + +section SuccessFraction + +theorem fraction_not_exists {α K : Type*} [Fintype α] [Fintype K] + (P : K → α → Prop) (E : ℝ) (hcard : (0 : ℝ) < Fintype.card α) + (hbound : ∀ k, (Fintype.card {x : α // P k x} : ℝ) / Fintype.card α ≤ E) : + 1 - Fintype.card K * E ≤ + (Fintype.card {x : α // ¬∃ k, P k x} : ℝ) / Fintype.card α := by + have hunion := card_exists_le_sum P + have hunionR : (Fintype.card {x : α // ∃ k, P k x} : ℝ) ≤ + ∑ k, (Fintype.card {x : α // P k x} : ℝ) := by + have h : (Fintype.card {x : α // ∃ k, P k x} : ℝ) ≤ + (∑ k, Fintype.card {x : α // P k x} : ℕ) := Nat.cast_le.mpr hunion + simpa only [Nat.cast_sum] using h + have hbad : (Fintype.card {x : α // ∃ k, P k x} : ℝ) / Fintype.card α ≤ + Fintype.card K * E := by + calc + _ ≤ (∑ k, (Fintype.card {x : α // P k x} : ℝ)) / Fintype.card α := + div_le_div_of_nonneg_right hunionR hcard.le + _ = ∑ k, (Fintype.card {x : α // P k x} : ℝ) / Fintype.card α := + Finset.sum_div _ _ _ + _ ≤ ∑ _k : K, E := sum_le_sum fun k _ => hbound k + _ = _ := by simp + have hpart : Fintype.card {x : α // ¬∃ k, P k x} + + Fintype.card {x : α // ∃ k, P k x} = Fintype.card α := by + rw [Fintype.card_subtype_compl] + exact Nat.sub_add_cancel (Fintype.card_subtype_le _) + have hpartR : (Fintype.card {x : α // ¬∃ k, P k x} : ℝ) + + Fintype.card {x : α // ∃ k, P k x} = Fintype.card α := by exact_mod_cast hpart + have hsum : (Fintype.card {x : α // ¬∃ k, P k x} : ℝ) / Fintype.card α + + (Fintype.card {x : α // ∃ k, P k x} : ℝ) / Fintype.card α = 1 := by + rw [← add_div, hpartR, div_self (ne_of_gt hcard)] + linarith + +variable [DecidableEq I] [DecidableEq J] + +def largePadding (K : Finset (I × J)) (L : ℕ) : I → J → ℕ := + fun i j => if (i, j) ∈ K then L else 0 + +private theorem large_padding_good_card (r : I → ℕ) (c : J → ℕ) + (K : Finset (I × J)) (L : ℕ) : + Fintype.card {Y : Table (paddedRows r (largePadding K L)) + (paddedColumns c (largePadding K L)) // + ¬∃ p : K, Y.val p.val.1 p.val.2 < L} = Fintype.card (Table r c) := by + let P := largePadding K L + let T := Table (paddedRows r P) (paddedColumns c P) + have heq (Y : T) : (¬∃ p : K, Y.val p.val.1 p.val.2 < L) ↔ + ∀ i j, P i j ≤ Y.val i j := by + constructor + · intro hb i j + by_cases hij : (i, j) ∈ K + · have hn : ¬Y.val i j < L := fun h => hb ⟨⟨(i, j), hij⟩, h⟩ + simpa [P, largePadding, hij] using (show L ≤ Y.val i j by omega) + · simp [P, largePadding, hij] + · intro hg + rintro ⟨p, hp⟩ + have h := hg p.val.1 p.val.2 + have hm : (p.val.1, p.val.2) ∈ K := p.property + simp only [P, largePadding, hm, ite_true] at h + omega + have he : {Y : T // ¬∃ p : K, Y.val p.val.1 p.val.2 < L} ≃ + {Y : T // ∀ i j, P i j ≤ Y.val i j} := Equiv.subtypeEquivRight heq + rw [Fintype.card_congr he] + exact successful_card r c P + +/-- The successful enlarged-table fraction is bounded using the proved +small-entry estimate and the exact padding bijection. This is the counting +part of paper 200-01's stationary-success proposition. -/ +theorem padding_success_fraction (r : I → ℕ) (c : J → ℕ) + (htotal : ∑ i, r i = ∑ j, c j) (K : Finset (I × J)) (L U d : ℕ) + (hd : 0 < d) (hrows : Fintype.card I ≤ d) (hcols : Fintype.card J ≤ d) + (hrow : ∀ p ∈ K, U ≤ r p.1) (hcol : ∀ p ∈ K, U ≤ c p.2) + (hU : 4 * d ≤ U) (hL : 2 * L ≤ U) : + 1 - K.card * (4 * L * (d : ℝ) ^ 3 / U) ≤ + (Fintype.card (Table r c) : ℝ) / + Fintype.card (Table (paddedRows r (largePadding K L)) + (paddedColumns c (largePadding K L))) := by + classical + let P := largePadding K L + let r' := paddedRows r P + let c' := paddedColumns c P + have htotal' : ∑ i, r' i = ∑ j, c' j := by + dsimp [r', c', paddedRows, paddedColumns] + rw [sum_add_distrib, sum_add_distrib, htotal, sum_comm (f := P)] + let T := Table r' c' + let bad (Y : T) : Prop := ∃ p : K, Y.val p.val.1 p.val.2 < L + have hgood : Fintype.card {Y : T // ¬bad Y} = Fintype.card (Table r c) := + large_padding_good_card r c K L + have hcard : (0 : ℝ) < Fintype.card T := by + exact_mod_cast (Fintype.card_pos_iff.mpr (table_nonempty r' c' htotal')) + have hbound (p : K) : + (Fintype.card {Y : T // Y.val p.val.1 p.val.2 < L} : ℝ) / Fintype.card T ≤ + 4 * L * (d : ℝ) ^ 3 / U := + small_entry_probability htotal' p.val.1 p.val.2 U d L hd hrows hcols + ((hrow p.val p.property).trans (Nat.le_add_right _ _)) + ((hcol p.val p.property).trans (Nat.le_add_right _ _)) hU hL + have hfrac := fraction_not_exists (fun (p : K) (Y : T) => Y.val p.val.1 p.val.2 < L) + (4 * L * (d : ℝ) ^ 3 / U) hcard (fun p => by + simpa only [Fintype.card_eq_nat_card] using hbound p) + simp only [Fintype.card_eq_nat_card] at hfrac hgood ⊢ + change 1 - Nat.card K * (4 * L * (d : ℝ) ^ 3 / U) ≤ + (Nat.card {Y : T // ¬bad Y} : ℝ) / Nat.card T at hfrac + rw [hgood] at hfrac + simpa only [Nat.card_eq_finsetCard] using hfrac + +end SuccessFraction + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCompletionFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCompletionFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..e11a368132e1b06827e47ee953bc5f2a72f34cf5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCompletionFibres.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalMarginal +import OAI.Combinatorics.ContingencyTables.Sampling.RepairFibres + +namespace OAI + +/-! # Completion-retaining fibres of the literal hard marginal + +Each physical large-cell assignment with zero penalty is exactly one pair +of full row and column views. The retained small profile is prescribed, +while large entries agree. No completion multiplicity is discarded. +-/ + +namespace ContingencyTables.PhysicalCompletionFibres + +open scoped BigOperators Classical +open LargePairEnumeration PhysicalLargeProfiles RowColumnPenalties +open FirstPaperPhysicalMarginal PaddedCompletions NestedPenaltyApplication + +variable {I J : Type*} [Fintype I] [Fintype J] + +abbrev SmallProfile (small : I → J → Bool) := + SmallView (fun a : I×J => small a.1 a.2) → ℕ + +/-- Full row/column views with one prescribed small profile. -/ +def CompletionFibre (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) := + {Z : RowColumnPair rbar cbar // + (∀ i, smallRow small Z.val.1 i ≤ r i) ∧ + (∀ j, smallColumnView small Z.val.2 j ≤ c j) ∧ + (∀ i j (hs : small i j=true), + Z.val.1 i j=z (⟨(i,j),hs⟩,false) ∧ + Z.val.2 i j=B i j-z (⟨(i,j),hs⟩,true)) ∧ + (∀ i j, small i j=false → Z.val.1 i j=Z.val.2 i j) ∧ + (∀ i j, small i j=false → Z.val.1 i j ≤ B i j)} + +noncomputable instance completionFibreFintype (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) : + Fintype (CompletionFibre small B r rbar c cbar z) := by + unfold CompletionFibre + infer_instance + +omit [Fintype I] [Fintype J] in +lemma physical_inBox (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (hz : ∀ u, z u ≤ B u.1.val.1 u.1.val.2) + (a : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2)) : + BalancedBox.InBox (fun u => B u.1.1 u.1.2) + (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z a) := by + rintro ⟨⟨i,j⟩,b⟩ + by_cases hs : small i j=true + · simpa only [physicalProfile,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,b) + · cases b + · simpa only [physicalProfile,hs,dite_eq_right,Bool.false_eq_true,↓reduceIte,↓reduceDIte] using + Nat.le_of_lt_succ (a ⟨(i,j),Bool.eq_false_iff.mpr hs⟩).isLt + · simp only [physicalProfile,hs,↓reduceIte] + exact Nat.sub_le _ _ + +noncomputable def fibreAssignment {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {z : SmallProfile small} + (Z : CompletionFibre small B r rbar c cbar z) : + PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) := + fun a => ⟨Z.val.val.1 a.val.1 a.val.2, + Nat.lt_succ_of_le (Z.property.2.2.2.2 _ _ a.property)⟩ + +lemma fibreAssignment_views {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {z : SmallProfile small} + (Z : CompletionFibre small B r rbar c cbar z) : + let p := physicalProfile (fun a : I×J => small a.1 a.2) + (fun a => B a.1 a.2) z (fibreAssignment Z) + rowView p=Z.val.val.1 ∧ columnView B p=Z.val.val.2 := by + dsimp only + constructor + · funext i j + by_cases hs : small i j=true + · simpa only [rowView,physicalProfile,hs,dite_eq_left] using + (Z.property.2.2.1 i j hs).1.symm + · simp only [rowView,physicalProfile,hs,Bool.false_eq_true,↓reduceIte,↓reduceDIte] + rfl + · funext i j + by_cases hs : small i j=true + · simpa only [columnView,physicalProfile,hs,dite_eq_left] using + (Z.property.2.2.1 i j hs).2.symm + · simp only [columnView,physicalProfile,hs,Bool.false_eq_true,↓reduceIte,↓reduceDIte,fibreAssignment] + rw [Nat.sub_sub_self (Z.property.2.2.2.2 i j (Bool.eq_false_iff.mpr hs))] + exact Z.property.2.2.2.1 i j (Bool.eq_false_iff.mpr hs) + +noncomputable def zeroPhysicalEquiv (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) + (hz : ∀ u, z u ≤ B u.1.val.1 u.1.val.2) : + {a : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) // + penalty cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope + (physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z a)=0} ≃ + CompletionFibre small B (r) (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) z where + toFun a := by + let p := physicalProfile (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) z a.val + have hp := (penalty_zero_iff small B r _ c _ p (physical_inBox small B z hz a.val)).mp a.property + refine ⟨⟨(rowView p,columnView B p),hp.1,hp.2.1⟩,hp.2.2.1,hp.2.2.2,?_,?_,?_⟩ + · intro i j hs + simp [p,rowView,columnView,physicalProfile,hs] + · intro i j hs + have hcap := Nat.le_of_lt_succ (a.val ⟨(i,j),hs⟩).isLt + simpa only [p,rowView,columnView,physicalProfile,hs,Bool.false_eq_true,dite_eq_right, + ↓reduceIte,↓reduceDIte,Prod.fst,Prod.snd] using (Nat.sub_sub_self hcap).symm + · intro i j hs + simpa only [p,rowView,physicalProfile,hs,Bool.false_eq_true,dite_eq_right, + ↓reduceIte,↓reduceDIte,Prod.fst] using Nat.le_of_lt_succ (a.val ⟨(i,j),hs⟩).isLt + invFun Z := by + refine ⟨fibreAssignment Z,?_⟩ + have hp := fibreAssignment_views Z + apply (penalty_zero_iff small B r _ c _ _ (physical_inBox small B z hz _)).mpr + unfold FullConditions + rw [hp.1,hp.2] + exact ⟨Z.val.property.1,Z.val.property.2,Z.property.1,Z.property.2.1⟩ + left_inv a := by + apply Subtype.ext + funext l + apply Fin.ext + simp only [fibreAssignment,rowView,physicalProfile,l.property,Bool.false_eq_true, + ↓reduceIte,↓reduceDIte] + right_inv Z := by + apply Subtype.ext + apply Subtype.ext + exact Prod.ext (fibreAssignment_views Z).1 (fibreAssignment_views Z).2 + +/-- Exact equality, including all completion multiplicities. -/ +theorem hardMarginal_eq_fibre_card (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) + (hz : ∀ u, z u ≤ B u.1.val.1 u.1.val.2) : + hardMarginal small B r c L z= + (Fintype.card (CompletionFibre small B r (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) z):ℝ) := by + unfold hardMarginal fullHardFamily hardWeight + rw [Finset.sum_boole,←Fintype.card_subtype] + exact_mod_cast Fintype.card_congr (zeroPhysicalEquiv small B r c L z hz) + +/-- Forgetting the retained profile loses no information on a bounded +injective family of profiles. In particular all later fibre sums count +full state/completion pairs exactly once. -/ +theorem fibre_projection_injective {S : Type*} + (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (p : S → SmallProfile small) + (hp : Function.Injective p) (hbox : ∀ s u, p s u ≤ B u.1.val.1 u.1.val.2) : + Function.Injective (fun a : (s : S) × CompletionFibre small B r rbar c cbar (p s) => + a.2.val) := by + rintro ⟨s,X⟩ ⟨t,Y⟩ he + have hst : s=t := by + apply hp + funext u + rcases u with ⟨⟨⟨i,j⟩,hs⟩,b⟩ + cases b + · have hx := congrArg (fun Z : RowColumnPair rbar cbar => Z.val.1 i j) he + rw [(X.property.2.2.1 i j hs).1,(Y.property.2.2.1 i j hs).1] at hx + exact hx + · have hq := congrArg (fun Z : RowColumnPair rbar cbar => Z.val.2 i j) he + rw [(X.property.2.2.1 i j hs).2,(Y.property.2.2.1 i j hs).2] at hq + have hx := hbox s (⟨(i,j),hs⟩,true) + have hy := hbox t (⟨(i,j),hs⟩,true) + dsimp only at hx hy + omega + subst t + congr 1 + exact Subtype.ext he + +end ContingencyTables.PhysicalCompletionFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalContextVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalContextVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae2770ffd37a7923bed217e070ef2e67a0cd63cd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalContextVariance.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextGraphEnergy + +namespace OAI + +/-! # Actual physical context variance, including zero-mass contexts -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open IntegerWeightedTransport FirstPaperProfiles ExcessContextProfiles +open FirstPaperContextTransport FirstPaperPhysicalMarginal FiniteExposureVariance +open PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma physicalContextEnergy_nonnegative (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) (f H : SmallProfile small → ℝ) (hf : ∀ z,0 ≤ f z) : + 0 ≤ physicalContextEnergy small B s σ f H := by + unfold physicalContextEnergy + apply div_nonneg _ (by norm_num) + exact Finset.sum_nonneg (fun p _ => mul_nonneg (le_min (hf _) (hf _)) (sq_nonneg _)) + +/-- No positivity assumption is needed on the whole context. Its child +variance is bounded by its actual physical prefix exchange energy. -/ +theorem physical_context_variance (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hU : 2 ≤ U) (hB : ∀ i j,small i j=true → B i j=U) + (hlarge : ∀ i j,small i j=false → 2 ≤ B i j) + (hσ : ∀ a : Earlier small s,σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (hcap : ∀ T : ResidualTables small r c (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L),∀ i j,T.val.val i j ≤ B i j) + (H : SmallProfile small → ℝ) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let z := fun j : Fin (U+1) => eliminate Ms f (childProfile U j.val) + let μ := fun j : Fin (U+1) => + eliminate Ms (fun p => f p*H (assemble small s hs σ U e p)) (childProfile U j.val)/z j + variance z μ ≤ ((U:ℝ)+1)^4*(2+2*n*((U:ℝ)+1)^2)* + physicalContextEnergy small B s σ (hardMarginal small B r c L) H := by + dsimp only + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let z := fun j : Fin (U+1) => eliminate Ms f (childProfile U j.val) + have hz : ∀ j,0 ≤ z j := fun j => eliminate_nonnegative Ms f + (contextHard_nonnegative small B r c L Ms _ _) (childProfile U j.val) + have hc : 0 ≤ ((U:ℝ)+1)^4*(2+2*n*((U:ℝ)+1)^2) := by positivity + by_cases hZ : 0 < ∑ j,z j + · have hv := physical_child_variance small B r c L s hs σ U hU hB hlarge hσ e hcap + (fun p => H (assemble small s hs σ U e p)) hZ + have he := context_graphEnergy_le small B r c L s hs σ U (by omega) hB hσ e H + dsimp only at hv he + exact hv.trans (mul_le_mul_of_nonneg_left he hc) + · have hzero : (∑ j,z j)=0 := le_antisymm (le_of_not_gt hZ) (Finset.sum_nonneg (fun j _ => hz j)) + have hzw := zero_mass_weights z hz hzero + change variance z _ ≤ _ + unfold variance + simp only [hzw,zero_mul,Finset.sum_const_zero] + exact mul_nonneg hc (physicalContextEnergy_nonnegative small B s σ _ H + (hardMarginal_nonnegative small B r c L)) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCostPolynomial.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCostPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..fecb0f68b7a44ab9f73b0dd86eead5e506d507f5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalCostPolynomial.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomial + +namespace OAI + +/-! # Polynomial arithmetic for the physical compiler's explicit cost -/ + +namespace ContingencyTables.PhysicalCostPolynomial +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial +noncomputable section + +theorem bound (a o : ℕ) (t : Polynomial ℕ) : ∃ p : Polynomial ℕ, + ∀ H C N B M : ℕ,H ≤ M → C ≤ t.eval M → N ≤ M → B ≤ M → + LiteralProgram.packTime N+C*(o*(1+2*a*(H+C*a+1))+1)+LiteralProgram.postTime B ≤ + p.eval M := by + let fac : Polynomial ℕ := C o*(1+2*C a*(X+t*C a+1))+1 + let pk : Polynomial ℕ := (1+LiteralProgram.budgetPolynomial 1 (18*LiteralPacked.width) X 0)* + C (MachineCost.programCost LiteralPacked.packCode) + let out : Polynomial ℕ := C (MachineCost.programCost (LiteralTape.eraseCode LiteralPacked.header.length))+ + (1+LiteralProgram.budgetPolynomial (18*LiteralPacked.width) 1 X 0)* + C (MachineCost.programCost LiteralPacked.unpackCode) + refine ⟨pk+t*fac+out,?_⟩ + intro H K N B M hH hK hN hB + have hf : o*(1+2*a*(H+K*a+1))+1 ≤ fac.eval M := by + simp only [fac,eval_add,eval_mul,eval_C,eval_ofNat,eval_X,eval_one] + gcongr + have hpk : pk.eval M=LiteralProgram.packTime M := by + simp only [pk,eval_mul,eval_add,eval_one,eval_C,LiteralProgram.eval_budgetPolynomial, + eval_X,eval_zero,LiteralProgram.packTime] + have hout : out.eval M=LiteralProgram.postTime M := by + simp only [out,eval_add,eval_mul,eval_one,eval_C,LiteralProgram.eval_budgetPolynomial, + eval_X,eval_zero,LiteralProgram.postTime] + simp only [eval_add,eval_mul,hpk,hout] + exact Nat.add_le_add (Nat.add_le_add (LiteralProgram.packTime_mono hN) + (Nat.mul_le_mul hK hf)) (LiteralProgram.postTime_mono hB) + +end +end ContingencyTables.PhysicalCostPolynomial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEdgeMargins.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEdgeMargins.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c5bf1ae76daa7aa6cc50fb4f255b13504061da8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEdgeMargins.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairMargins +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalSmallGraph + +namespace OAI + +/-! # Every actual small-graph edge changes each residual margin by at most two -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions SmallContextFibres SmallContextCoordinates +open SmallContextEnumeration RowMajorEnumeration + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma designated_repair_residual_margins (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x y : PhysicalStates (firstPaperSmall r c U) B r c L) + (hxcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L x k) ≤ B i j) + (hycap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L y k) ≤ B i j) + (z : PositiveDefects (firstPaperSmall r c U) B r c L) + (hsource : naturalProfile z.val=physicalProfile _ B r c L x) + (htarget : rawChoice (firstPaperSmall r c U) U + (wordChoices _ U (repairWord r c U L B hB z))=physicalProfile _ B r c L y) : + (∀ i,|(residualRows (firstPaperSmall r c U) B r c L y i:ℤ)-residualRows _ B r c L x i| ≤ 1) ∧ + (∀ j,|(residualColumns (firstPaperSmall r c U) B r c L y j:ℤ)-residualColumns _ B r c L x j| ≤ 1) := by + let st := defectLabels (firstPaperSmall r c U) B r c L z + have hd := defectLabels_spec (firstPaperSmall r c U) B r c L z + have hcap := repair_small_capacity r c U L B hB (naturalProfile z.val) + (naturalProfile_bounded z.val) st.1.val st.2.val st.1.property st.2.property hd z.property.2 + have he := htarget.symm.trans (repairWord_profile r c U L B hB z) + rw [hsource] at hd hcap he + exact repair_residual_margins _ B r c L x y hxcap hycap st.1.val st.2.val hd st.2.property hcap he + +theorem physical_edge_residual_margins (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (hcap : ∀ z : PhysicalStates (firstPaperSmall r c U) B r c L,∀ i j, + firstPaperSmall r c U i j=false → (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) + (x y : PhysicalStates (firstPaperSmall r c U) B r c L) + (hxy : physicalAdjacent r c U L B hB x y) : + (∀ i,|(residualRows (firstPaperSmall r c U) B r c L y i:ℤ)-residualRows _ B r c L x i| ≤ 2) ∧ + (∀ j,|(residualColumns (firstPaperSmall r c U) B r c L y j:ℤ)-residualColumns _ B r c L x j| ≤ 2) := by + rcases Finset.mem_union.mp hxy with he|he + · exact exchange_residual_margins _ B r c L x y (hcap x) (hcap y) (Finset.mem_filter.mp he).2 + · rcases Finset.mem_union.mp he with he|he + · obtain ⟨z,_,he⟩ := Finset.mem_image.mp he + have hm := designated_repair_residual_margins r c U L B hB x y (hcap x) (hcap y) z + (congrArg Prod.fst he) (congrArg Prod.snd he) + exact ⟨fun i => (hm.1 i).trans (by norm_num),fun j => (hm.2 j).trans (by norm_num)⟩ + · obtain ⟨z,_,he⟩ := Finset.mem_image.mp he + have hm := designated_repair_residual_margins r c U L B hB y x (hcap y) (hcap x) z + (congrArg Prod.snd he) (congrArg Prod.fst he) + constructor + · intro i + rw [abs_sub_comm] + exact (hm.1 i).trans (by norm_num) + · intro j + rw [abs_sub_comm] + exact (hm.2 j).trans (by norm_num) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEventBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEventBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc1d0078b00fc7c9684964b72c3e8344a2bb53d4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalEventBounds.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPrefixTail +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramSeal + +namespace OAI + +/-! # Terminal-event bounds from finite stopping prefixes -/ + +namespace ContingencyTables.PhysicalEventBounds +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open scoped BigOperators Classical +noncomputable section +variable {Γ Q A : Type} [Inhabited Γ] + +def event (P : Cfg Γ Q → Prop) (c : Cfg Γ Q) : ℚ := if P c then 1 else 0 + +lemma event_nonneg (P : Cfg Γ Q → Prop) (c : Cfg Γ Q) : 0≤event P c := by + unfold event; split_ifs <;> norm_num +lemma event_le_one (P : Cfg Γ Q → Prop) (c : Cfg Γ Q) : event P c≤1 := by + unfold event; split_ifs <;> norm_num + +lemma mean_mono (p : Experiment A) (f g : A → ℚ) (h : ∀ a,f a≤g a) : + p.mean f≤p.mean g := by + induction p with + | done a => exact h a + | read p ih => simp only [Experiment.mean]; linarith [ih false,ih true] + | delay n p ih => exact ih + +lemma average_mono {n : ℕ} (f g : Bits n → ℚ) (h : ∀ b,f b≤g b) : + average f≤average g := by + unfold average + exact div_le_div_of_nonneg_right (Finset.sum_le_sum (fun b _ => h b)) (by positivity) + +/-- Only successful endpoints need be halted; the failure endpoint can be live. -/ +theorem stopped_event_bounds (M : PhysicalPost.Table Γ Q) (out : Option A → Cfg Γ Q) + (c : Cfg Γ Q) (p : Experiment (Option A)) (hp : Implements M out c p) + (hhalt : ∀ a,(out (some a)).state=none) (P : Cfg Γ Q → Prop) + (n : ℕ) (hn : p.cost≤n) : + p.mean (fun o => o.elim 0 (fun a => event P (out (some a))))≤ + (experiment M n c).mean (event P) ∧ + (experiment M n c).mean (event P)≤ + p.mean (fun o => o.elim 0 (fun a => event P (out (some a))))+ + p.mean (fun o => if o=none then 1 else 0) := by + have lower (b : Bits n) : + ((p.run (extend b)).1.elim 0 (fun a => event P (out (some a))))≤ + event P (execute M n c (extend b)) := by + cases he : (p.run (extend b)).1 with + | none => exact event_nonneg P _ + | some a => + have hh : (out (p.run (extend b)).1).state=none := by rw [he]; exact hhalt a + rw [PhysicalRetryTail.padded_halted_result M out c p hp n hn (extend b) hh,he] + exact le_rfl + have upper (b : Bits n) : event P (execute M n c (extend b))≤ + ((p.run (extend b)).1.elim 0 (fun a => event P (out (some a))))+ + (if (p.run (extend b)).1=none then 1 else 0) := by + cases he : (p.run (extend b)).1 with + | none => simpa only [Option.elim_none,ite_true,zero_add] using event_le_one P _ + | some a => + have hh : (out (p.run (extend b)).1).state=none := by rw [he]; exact hhalt a + rw [PhysicalRetryTail.padded_halted_result M out c p hp n hn (extend b) hh,he] + simp only [Option.elim_some,Option.some_ne_none,ite_false,add_zero,le_refl] + have hl := average_mono _ _ lower + have hu := average_mono _ _ upper + rw [physical_law,Experiment.average_run p + (fun o => o.elim 0 (fun a => event P (out (some a)))) n hn] at hl + rw [physical_law,average_add,Experiment.average_run p + (fun o => o.elim 0 (fun a => event P (out (some a)))) n hn, + Experiment.average_run p (fun o => if o=none then 1 else 0) n hn] at hu + exact ⟨hl,hu⟩ + +lemma terminal_event_monotone (M : PhysicalPost.Table Γ Q) (c : Cfg Γ Q) + (P : Cfg Γ Q → Prop) (hP : ∀ d,P d → d.state=none) : + Monotone (fun n => (experiment M n c).mean (event P)) := by + intro n m hnm + obtain ⟨k,rfl⟩ := Nat.exists_eq_add_of_le hnm + change (experiment M n c).mean (event P)≤(experiment M (n+k) c).mean (event P) + rw [PhysicalRetryTail.experiment_mean_add] + apply mean_mono + intro d + by_cases hd : P d + · rw [PhysicalRetryTail.halted_mean M k d (hP d hd)] + · have h := (experiment M k d).mean_nonneg (event P) + ((Experiment.all_true _).mono (fun d _ => event_nonneg P d)) + simpa only [event,ite_eq_right hd] using h + +/-- A terminal event absent at every successful endpoint is bounded by +prefix failure even at times earlier than the stopping-prefix budget. -/ +theorem absent_event_bound (M : PhysicalPost.Table Γ Q) (out : Option A → Cfg Γ Q) + (c : Cfg Γ Q) (p : Experiment (Option A)) (hp : Implements M out c p) + (hhalt : ∀ a,(out (some a)).state=none) (P : Cfg Γ Q → Prop) + (hP : ∀ d,P d → d.state=none) (habsent : ∀ a,¬P (out (some a))) (n : ℕ) : + (experiment M n c).mean (event P)≤p.mean (fun o => if o=none then 1 else 0) := by + have hu := (stopped_event_bounds M out c p hp hhalt P (max n p.cost) (le_max_right _ _)).2 + have hz : p.mean (fun o => o.elim 0 (fun a => event P (out (some a))))=0 := by + have he : (fun o : Option A => o.elim 0 (fun a => event P (out (some a))))= + (fun _ => (0:ℚ)) := by + funext o; cases o with + | none => rfl + | some a => simp only [Option.elim_some,event,ite_eq_right (habsent a)] + rw [he,PhysicalPartialSequence.mean_const] + rw [hz,zero_add] at hu + exact (terminal_event_monotone M c P hP (le_max_left _ _)).trans hu + +/-- Prefix accuracy transfers to physical time without assuming a +uniform bound on the number of steps in the prefix. -/ +lemma tendsto_of_prefix_bounds (f a b : ℕ → ℝ) (L : ℝ) + (ha : Filter.Tendsto a Filter.atTop (nhds L)) + (hb : Filter.Tendsto b Filter.atTop (nhds 0)) + (h : ∀ N,∃ S,∀ t,S≤t → a N≤f t ∧ f t≤a N+b N) : + Filter.Tendsto f Filter.atTop (nhds L) := by + apply Metric.tendsto_atTop.2 + intro ε hε + obtain ⟨Na,hNa⟩ := Metric.tendsto_atTop.1 ha (ε/2) (by linarith) + obtain ⟨Nb,hNb⟩ := Metric.tendsto_atTop.1 hb (ε/2) (by linarith) + obtain ⟨S,hS⟩ := h (max Na Nb) + refine ⟨S,?_⟩ + intro t ht + have h1 := hNa (max Na Nb) (le_max_left _ _) + have h2 := hNb (max Na Nb) (le_max_right _ _) + rw [Real.dist_eq] at h1 h2 ⊢ + have ha' := abs_lt.mp h1 + have hb' := abs_lt.mp h2 + have hh := hS t ht + exact abs_lt.mpr ⟨by linarith,by linarith⟩ + +lemma mean_one_sub (p : Experiment A) (f : A → ℚ) : + p.mean (fun a => 1-f a)=1-p.mean f := by + induction p with + | done a => rfl + | read p ih => simp only [Experiment.mean,ih]; ring + | delay n p ih => exact ih + +lemma run_halted_iff (P : Program) (input : List Symbol) (n : ℕ) (b : Bits n) : + (MatchingFPRAS.run P.machine input b).state=none ↔ + (execute P.table n (P.initial (Tape.mk₁ input)) (extend b)).state=none := by + let : Inhabited {q //q∈P.states} := ⟨⟨P.entry,P.entry_mem⟩⟩ + have he := congrArg Cfg.state (execute_lift P.table P.states P.supported n + ⟨some default,Tape.mk₁ input⟩ (extend b)) + rw [Program.machine,restrictedMachine_run] + change ((execute (restrict P.table P.states P.supported) n + ⟨some default,Tape.mk₁ input⟩ (extend b)).state.map enumeration)=none ↔ _ + change (execute P.table n (P.initial (Tape.mk₁ input)) (extend b)).state=_ at he + rw [he] + simp only [liftCfg,Option.map_eq_none_iff] + +end +end ContingencyTables.PhysicalEventBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalExchangeMargins.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalExchangeMargins.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1075c7cf8a57dc6bb2cfe36962d14a1b0d0abd2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalExchangeMargins.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCoordinateSums +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalOriginalResiduals + +namespace OAI + +/-! # Actual padded residual margins change by at most two on exchange edges -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions SmallContextFibres IntegerWeightedTransport + +lemma nat_residual_difference (r P A B : ℕ) (hA : A ≤ r) (hB : B ≤ r) : + |((r-A+P:ℕ):ℤ)-((r-B+P:ℕ):ℤ)|=|(A:ℤ)-B| := by + rw [Nat.cast_add,Nat.cast_add,Nat.cast_sub hA,Nat.cast_sub hB] + have he : (r:ℤ)-A+P-((r:ℤ)-B+P) = -((A:ℤ)-B) := by ring + rw [he,abs_neg] + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma exchange_residual_margins (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (x y : PhysicalStates small B r c L) + (hxcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L x k) ≤ B i j) + (hycap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L y k) ≤ B i j) + (hxy : IntegerExchangeAdjacent (physicalProfile small B r c L x) (physicalProfile small B r c L y)) : + (∀ i,|(residualRows small B r c L y i:ℤ)-residualRows small B r c L x i| ≤ 2) ∧ + (∀ j,|(residualColumns small B r c L y j:ℤ)-residualColumns small B r c L x j| ≤ 2) := by + have hx := physical_original_residuals small B r c L x hxcap + have hy := physical_original_residuals small B r c L y hycap + constructor + · intro i + unfold residualRows + rw [nat_residual_difference _ _ _ _ (hy.1 i) (hx.1 i)] + exact exchange_smallRow_abs small _ _ hxy i + · intro j + unfold residualColumns + rw [nat_residual_difference _ _ _ _ (hy.2 j) (hx.2 j)] + exact exchange_smallColumn_abs small B _ _ (naturalProfile_bounded x.val.val) + (naturalProfile_bounded y.val.val) hxy j + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphDegree.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0206ecd36c65e84eedf15b09060d701dfc5659c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphDegree.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairGraph +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeDegree +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRepairDegree + +namespace OAI + +/-! # The manuscript's finite neighbor bound on the physical small graph -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open CompletionCounts SmallContextEnumeration RowMajorEnumeration IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def fullNeighbors (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (v : SmallProfile (firstPaperSmall r c U)) := + ((fullEdges r c U L B hB).filter (fun p => p.1=v)).image Prod.snd + +lemma fullNeighbors_subset (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (v : SmallProfile (firstPaperSmall r c U)) : + fullNeighbors r c U L B hB v ⊆ exchangeCandidates v ∪ + repairNeighbors + (fun z : PositiveDefects (firstPaperSmall r c U) B r c L => naturalProfile z.val) + (fun z => rawChoice (firstPaperSmall r c U) U + (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z))) v := by + intro y hy + obtain ⟨p,hp,rfl⟩ := Finset.mem_image.mp hy + obtain ⟨he,hv⟩ := Finset.mem_filter.mp hp + rcases Finset.mem_union.mp he with he|he + · apply Finset.mem_union_left + have ha := (Finset.mem_filter.mp he).2 + rw [hv] at ha + exact adjacent_mem_candidates ha + · apply Finset.mem_union_right + rcases Finset.mem_union.mp he with he|he + · obtain ⟨z,_,hz⟩ := Finset.mem_image.mp he + subst p + exact mem_repairNeighbors_forward _ _ v z hv + · obtain ⟨z,_,hz⟩ := Finset.mem_image.mp he + subst p + exact mem_repairNeighbors_reverse _ _ v z hv + +/-- Counting distinct neighbors, with repeated exchange/repair edges +removed by the finite-set union, gives exactly the source bound. -/ +theorem fullNeighbors_card_le (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (v : SmallProfile (firstPaperSmall r c U)) : + (fullNeighbors r c U L B hB v).card ≤ 5*(Fintype.card (Cells (firstPaperSmall r c U)))^2+1 := by + let x := fun z : PositiveDefects (firstPaperSmall r c U) B r c L => naturalProfile z.val + let y := fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + rawChoice (firstPaperSmall r c U) U (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z)) + have hx : Function.Injective x := by + intro a b he + apply Subtype.ext + exact naturalProfile_injective _ B he + have hy : Function.Injective (fun z => (defectLabels _ B r c L z,y z)) := by + intro a b he + have hl := congrArg Prod.fst he + have hr := congrArg Prod.snd he + dsimp only at hl hr + have hw : repairWord r c U L B hB a=repairWord r c U L B hB b := + (wordChoices (firstPaperSmall r c U) U).injective + (rawChoice_injective (firstPaperSmall r c U) U hr) + exact repairWord_type_injective r c U L B hB (Prod.ext hl hw) + have hr := repairNeighbors_card_le x y hx (defectLabels _ B r c L) hy v + have hc := exchangeCandidates_card_le v + have hs := (Finset.card_le_card (fullNeighbors_subset r c U L B hB v)).trans (Finset.card_union_le _ _) + change (fullNeighbors r c U L B hB v).card ≤ (exchangeCandidates v).card+(repairNeighbors x y v).card at hs + have hcoord : Fintype.card (LargePairEnumeration.SmallView (fun a : I×J => firstPaperSmall r c U a.1 a.2))= + 2*Fintype.card (Cells (firstPaperSmall r c U)) := by + change Fintype.card (Cells (firstPaperSmall r c U)×Bool)=_ + rw [Fintype.card_prod,Fintype.card_bool] + omega + rw [Fintype.card_prod] at hr + change (repairNeighbors x y v).card ≤ _ at hr + rw [hcoord] at hc + nlinarith + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphVertices.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphVertices.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d323f0979af4d407bb0eede2846867e49aed55b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalGraphVertices.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextGraphMembership + +namespace OAI + +/-! # Finite physical vertices containing every contextual transport leaf -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open IntegerWeightedTransport FirstPaperProfiles ExcessContextProfiles + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable instance profilesFintype (small : I → J → Bool) (B : I → J → ℕ) : + Fintype (Profiles small B) := by unfold Profiles; infer_instance + +noncomputable def vertices (small : I → J → Bool) (B : I → J → ℕ) : Finset (SmallProfile small) := + Finset.univ.image (fun z : Profiles small B => naturalProfile z.val) + +lemma mem_vertices_iff (small : I → J → Bool) (B : I → J → ℕ) (z : SmallProfile small) : + z ∈ vertices small B ↔ (∀ a, z a ≤ B a.1.val.1 a.1.val.2) ∧ Pattern small B z := by + constructor + · intro hz + obtain ⟨p,_,rfl⟩ := Finset.mem_image.mp hz + exact ⟨naturalProfile_bounded p.val,p.property⟩ + · rintro ⟨hb,hp⟩ + let p : BoundedProfile small B := fun a => ⟨z a,Nat.lt_succ_of_le (hb a)⟩ + let q : Profiles small B := ⟨p,hp⟩ + exact Finset.mem_image.mpr ⟨q,Finset.mem_univ _,rfl⟩ + +/-- Every vertex used by the common conditional energy is an actual +bounded allowed small-graph profile after the physical coordinate map. -/ +theorem context_vertex_mem (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hU : 1 ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (x : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (hx : x ∈ contextVertices U n) + (hbox : InBox (bounds (fun _ : Bool => U) (widths (fun _ : Fin n => U))) x) : + assemble small s hs σ U e x ∈ vertices small B := by + obtain ⟨l,_,hx⟩ := Finset.mem_biUnion.mp hx + apply (mem_vertices_iff small B _).mpr + refine ⟨?_,leaf_pattern small B s hs σ U l.val hU (Nat.le_of_lt_succ l.isLt) hB hσ e x hx hbox⟩ + intro a + rw [hB _ _ a.1.property] + exact assemble_bounded small s hs σ U hσ e x hbox a + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalLargeProfiles.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalLargeProfiles.lean new file mode 100644 index 0000000000000000000000000000000000000000..d65c6c2de1c19e9563e7ba0ca5bc7169c0e00062 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalLargeProfiles.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration + +namespace OAI + +/-! # Removing the arbitrary enumeration from the physical large-cell sum -/ + +namespace ContingencyTables.PhysicalLargeProfiles + +open scoped BigOperators Classical +open LargePairEnumeration + +variable {C : Type*} + +@[reducible] def PhysicalAssignments (small : C → Bool) (M : C → ℕ) := + (l : LargeCell small) → Fin (M l.val+1) + +noncomputable def physicalProfile (small : C → Bool) (M : C → ℕ) + (z : SmallView small → ℕ) (a : PhysicalAssignments small M) (u : C×Bool) : ℕ := + if hs : small u.1=true then z (⟨u.1,hs⟩,u.2) + else if u.2 then M u.1-(a ⟨u.1,Bool.eq_false_iff.mpr hs⟩).val + else (a ⟨u.1,Bool.eq_false_iff.mpr hs⟩).val + +lemma joinedProfile_physical {n : ℕ} (small : C → Bool) (M : C → ℕ) + (e : Fin n ≃ LargeCell small) (z : SmallView small → ℕ) + (a : PhysicalAssignments small M) : + joinedProfile (fun k => M (e k).val) z + ((Equiv.piCongrLeft (fun l : LargeCell small => Fin (M l.val+1)) e).symm a) ∘ + (physicalJoinEquiv small e).symm=physicalProfile small M z a := by + funext u + rcases u with ⟨c,b⟩ + by_cases hs : small c=true + · simp [physicalJoinEquiv,partitionEquiv,joinedProfile,physicalProfile,hs] + · simp [physicalJoinEquiv,partitionEquiv,joinedProfile,physicalProfile,hs] + have hval := congrArg (fun l : LargeCell small => (a l).val) + (e.apply_symm_apply ⟨c,Bool.eq_false_iff.mpr hs⟩) + exact congrArg (fun t : ℕ => if b then M c-t else t) hval + +variable [Fintype C] + +/-- The physical finite sum is independent of the order used to enumerate +large cells in the recursive signature proof. -/ +theorem sum_joined_eq_physical {n : ℕ} (small : C → Bool) (M : C → ℕ) + (e : Fin n ≃ LargeCell small) (z : SmallView small → ℕ) + (F : (C×Bool → ℕ) → ℝ) : + (∑ a : ((k : Fin n) → Fin (M (e k).val+1)), + F (joinedProfile (fun k => M (e k).val) z a ∘ (physicalJoinEquiv small e).symm))= + ∑ a : PhysicalAssignments small M, F (physicalProfile small M z a) := by + apply Fintype.sum_equiv (Equiv.piCongrLeft (fun l : LargeCell small => Fin (M l.val+1)) e) + intro a + congr 1 + have h := joinedProfile_physical small M e z + ((Equiv.piCongrLeft (fun l : LargeCell small => Fin (M l.val+1)) e) a) + simpa only [Equiv.symm_apply_apply] using h + +end ContingencyTables.PhysicalLargeProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalMassBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalMassBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b0fda2e2225333217c64a2ab8df18098e8616e2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalMassBound.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalResidualMargins + +namespace OAI + +/-! # Count the small state and its large completion jointly -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres PhysicalLargeProfiles FirstPaperPhysicalMarginal +open SmallContextFibres LargePairEnumeration CompletionCounts NestedPenaltyApplication + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] + +lemma hardMarginal_le_assignments (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) : + hardMarginal small B r c L z ≤ + (Fintype.card (PhysicalAssignments (fun a : I×J => small a.1 a.2) + (fun a => B a.1 a.2)):ℝ) := by + unfold hardMarginal fullHardFamily hardWeight + rw [Finset.sum_boole,← Fintype.card_subtype] + exact_mod_cast Fintype.card_subtype_le _ + +lemma boundedProfile_card_le (small : I → J → Bool) (B : I → J → ℕ) + (C : ℕ) (hB : ∀ i j,B i j ≤ C) : + Fintype.card (BoundedProfile small B) ≤ + (C+1)^Fintype.card (SmallView (fun a : I×J => small a.1 a.2)) := by + change Fintype.card ((a : SmallView (fun a : I×J => small a.1 a.2)) → + Fin (B a.1.val.1 a.1.val.2+1)) ≤ _ + rw [Fintype.card_pi] + simp only [Fintype.card_fin] + calc + _ ≤ ∏ _a : SmallView (fun a : I×J => small a.1 a.2),(C+1) := + Finset.prod_le_prod (fun a _ => Nat.add_le_add_right (hB _ _) 1) + _ = _ := by simp + +lemma physicalAssignments_card_le (small : I → J → Bool) (B : I → J → ℕ) + (C : ℕ) (hB : ∀ i j,B i j ≤ C) : + Fintype.card (PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2)) ≤ + (C+1)^Fintype.card (LargeCell (fun a : I×J => small a.1 a.2)) := by + unfold PhysicalAssignments + rw [Fintype.card_pi] + simp only [Fintype.card_fin] + calc + _ ≤ ∏ _a : LargeCell (fun a : I×J => small a.1 a.2),(C+1) := + Finset.prod_le_prod (fun a _ => Nat.add_le_add_right (hB _ _) 1) + _ = _ := by simp + +variable [LinearOrder I] [LinearOrder J] + +theorem physical_total_mass_le (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L C : ℕ) (hB : ∀ i j,B i j ≤ C) : + (∑ z : PhysicalStates small B r c L,hardMarginal small B r c L + (physicalProfile small B r c L z)) ≤ + ((C+1:ℕ):ℝ)^(2*dimensionAllowance (I := I) (J := J)) := by + let s := Fintype.card (SmallView (fun a : I×J => small a.1 a.2)) + let l := Fintype.card (LargeCell (fun a : I×J => small a.1 a.2)) + have hs : Fintype.card (PhysicalStates small B r c L) ≤ (C+1)^s := + (Fintype.card_subtype_le _).trans + ((Fintype.card_subtype_le _).trans (by + simpa only [s,Fintype.card_eq_nat_card] using boundedProfile_card_le small B C hB)) + have hl : Nat.card (PhysicalAssignments (fun a : I×J => small a.1 a.2) + (fun a => B a.1 a.2)) ≤ (C+1)^l := by + simpa only [l,Fintype.card_eq_nat_card] using physicalAssignments_card_le small B C hB + have he := Fintype.card_congr (partitionEquiv (fun a : I×J => small a.1 a.2)) + simp only [Fintype.card_sum,Fintype.card_prod,Fintype.card_bool] at he + have hexp : s+l ≤ 2*dimensionAllowance (I := I) (J := J) := by + simp only [s,l,Fintype.card_prod,Fintype.card_bool] + nlinarith [dimension_le_allowance (I := I) (J := J)] + have hbound (z : PhysicalStates small B r c L) : hardMarginal small B r c L + (physicalProfile small B r c L z) ≤ (Nat.card (PhysicalAssignments + (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2)):ℝ) := by + simpa only [Fintype.card_eq_nat_card] using hardMarginal_le_assignments small B r c L + (physicalProfile small B r c L z) + calc + _ ≤ ∑ _z : PhysicalStates small B r c L, + (Nat.card (PhysicalAssignments (fun a : I×J => small a.1 a.2) + (fun a => B a.1 a.2)):ℝ) := + Finset.sum_le_sum (fun z _ => hbound z) + _ = (Fintype.card (PhysicalStates small B r c L):ℝ)* + Nat.card (PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2)) := by simp + _ ≤ ((C+1:ℕ):ℝ)^s*((C+1:ℕ):ℝ)^l := by + apply mul_le_mul + · exact_mod_cast hs + · exact_mod_cast hl + · positivity + · positivity + _ = ((C+1:ℕ):ℝ)^(s+l) := (pow_add _ _ _).symm + _ ≤ _ := by + exact_mod_cast Nat.pow_le_pow_right (show 1 ≤ C+1 by omega) hexp + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalOriginalResiduals.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalOriginalResiduals.lean new file mode 100644 index 0000000000000000000000000000000000000000..031546d45e6f7a5860a52be59808a8de888ff9f1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalOriginalResiduals.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalResidualMargins + +namespace OAI + +/-! # Positive completion weight enforces the original residual tests -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions SmallContextFibres + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma physical_original_residuals (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PhysicalStates small B r c L) + (hcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L z k) ≤ B i j) : + OriginalResidualsNonnegative small B + (smallView small (physicalProfile small B r c L z) false) + (smallView small (physicalProfile small B r c L z) true) r c := by + have hh := hardMarginal_eq_completionCount small B r c L + (physicalProfile small B r c L z) (naturalProfile_bounded z.val.val) hcap + by_contra hn + rw [ite_eq_right hn] at hh + have hp := z.property + change 0 < hardMarginal small B r c L (physicalProfile small B r c L z) at hp + rw [hh] at hp + exact lt_irrefl _ hp + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPaperCapacity.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPaperCapacity.lean new file mode 100644 index 0000000000000000000000000000000000000000..d892051281235dd5fe51b99fd9ef7d625239f6a8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPaperCapacity.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalResidualMargins + +namespace OAI + +/-! # The manuscript capacity bounds every physical residual completion -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles FirstPaperPhysicalMarginal CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma physical_paper_capacity (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (d L U : ℕ) (hd : Fintype.card I*Fintype.card J ≤ d) + (z : PhysicalStates small (paperCapacity small r d L U) r c L) : + ∀ i j,small i j=false → + (∑ k,residualRows small (paperCapacity small r d L U) r c L z k) ≤ + paperCapacity small r d L U i j := + paper_capacity_excludes_none small + (smallView small (physicalProfile small (paperCapacity small r d L U) r c L z) false) + r d L U hd + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPartialSequence.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPartialSequence.lean new file mode 100644 index 0000000000000000000000000000000000000000..711fc3bc35f111d51e350d7e58497ea48128b64c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPartialSequence.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRetryTail +import OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram + +namespace OAI + +/-! # Sequencing finite prefixes that can stop at a live configuration + +A called prefix may have reached the continuation, or may still be inside +its first program. The construction stops exactly at that interface. +-/ + +namespace ContingencyTables.PhysicalPartialSequence +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing + +variable {Γ Q R A : Type} [Inhabited Γ] + +lemma mean_const (p : Experiment A) (v : ℚ) : p.mean (fun _ => v)=v := by + induction p with + | done => rfl + | delay n p ih => exact ih + | read p ih => simp only [Experiment.mean,ih]; ring + +lemma halted_all {M : Table Γ Q} {out : A → Cfg Γ Q} {c : Cfg Γ Q} + {p : Experiment A} (h : Implements M out c p) (hc : c.state=none) : + p.All (fun a => out a=c) := by + induction h with + | done a => rfl + | read c p h ih => + have he (b : Bool) : PhysicalPost.tick M c b=c := by simp [PhysicalPost.tick,hc] + exact ⟨by simpa only [he] using ih false (by rw [he]; exact hc), + by simpa only [he] using ih true (by rw [he]; exact hc)⟩ + | delay c d n p hs hr ih => + have he : d=c := by + rw [←hs (fun _ => false)] + rcases c with ⟨q,T⟩ + cases hc + exact execute_halted M n T (fun _ => false) + subst d + exact ih hc + +lemma early_all_eq (M : Table Γ Q) (c d : Cfg Γ Q) (n : ℕ) + (h : ∀ b : Stream,execute M n c b=d) : + (early M n c).All (fun x => x=d) := by + classical + rw [Experiment.all_indicator,PhysicalPost.early_mean] + simp only [h,ite_true,average_const] + +/-- Relabelling a physical prefix for sequential composition may shorten +its post-halt padding, and preserves the law of its endpoint configuration. -/ +theorem left_prefix (M : Table Γ Q) (N : Table Γ R) (r₀ : R) + (out : A → Cfg Γ Q) (c : Cfg Γ Q) (p : Experiment A) + (h : Implements M out c p) : + ∃ q : Experiment (Cfg Γ Q), + Implements (seq M N r₀) (leftCfg r₀) (leftCfg r₀ c) q ∧ + (∀ f,q.mean f=p.mean (fun a => f (out a))) ∧ q.cost≤p.cost := by + induction h with + | done a => exact ⟨.done (out a),.done (out a),fun _ => rfl,le_rfl⟩ + | read c p h ih => + by_cases hc : c.state=none + · have hall := halted_all (Implements.read c p h) hc + refine ⟨.done c,.done c,?_,Nat.zero_le _⟩ + intro f + have hm := Experiment.mean_congr_all (.read p) (fun a => f (out a)) (fun _ => f c) + (hall.mono (by intro a ha; rw [ha])) + exact (hm.trans (mean_const _ _)).symm + · obtain ⟨q,hq,hqm,hqc⟩ := ih false + obtain ⟨r,hr,hrm,hrc⟩ := ih true + let v : Bool → Experiment (Cfg Γ Q) := fun b => if b then r else q + refine ⟨.read v,?_,?_,?_⟩ + · apply Implements.read + intro b + rcases c with ⟨state,T⟩ + cases state with + | none => exact False.elim (hc rfl) + | some s => + rw [tick_left] + cases b + · exact hq + · exact hr + · intro f + simp only [Experiment.mean,v,Bool.false_eq_true,ite_false,ite_true,hqm,hrm] + · simp only [Experiment.cost,v,Bool.false_eq_true,ite_false,ite_true] + omega + | delay c d n p hs hr ih => + obtain ⟨q,hq,hqm,hqc⟩ := ih + let u := early M n c + have hu := early_left M N r₀ n c + have hall : u.All (fun x => x=d) := early_all_eq M c d n hs + refine ⟨u.bind (fun _ => q),?_,?_,?_⟩ + · apply hu.bind_all (fun _ => q) (leftCfg r₀) + exact hall.mono (by intro x hx; rw [hx]; exact hq) + · intro f + rw [Experiment.mean_bind,mean_const,hqm] + rfl + · exact (Experiment.cost_bind_le u (fun _ => q) q.cost (fun _ => le_rfl)).trans + (Nat.add_le_add (early_cost M n c) hqc) + +/-- When endpoint configurations identify their labels, sequential composition +also preserves the complete label law, not just the endpoint law. -/ +theorem left_prefix_injective [Nonempty A] (M : Table Γ Q) (N : Table Γ R) (r₀ : R) + (out : A → Cfg Γ Q) (hinj : Function.Injective out) (c : Cfg Γ Q) (p : Experiment A) + (h : Implements M out c p) : + ∃ q : Experiment A, + Implements (seq M N r₀) (fun a => leftCfg r₀ (out a)) (leftCfg r₀ c) q ∧ + (∀ f,q.mean f=p.mean f) ∧ q.cost≤p.cost := by + classical + obtain ⟨q,hq,hqm,hqc⟩ := left_prefix M N r₀ out c p h + let dec : Cfg Γ Q → A := Function.invFun out + have hd (a : A) : dec (out a)=a := Function.leftInverse_invFun hinj a + have hall : q.All (fun x => out (dec x)=x) := by + apply Experiment.all_of_mean_eq (p := p.map out) (q := q) + · intro f + rw [Experiment.mean_map] + exact hqm f + · rw [Experiment.all_map] + exact (Experiment.all_true p).mono (by intro a _; rw [hd]) + refine ⟨q.map dec,hq.map_all dec (fun a => leftCfg r₀ (out a)) + (hall.mono (by intro x hx; rw [hx])),?_,?_⟩ + · intro f + rw [Experiment.mean_map,hqm] + simp only [hd] + · simpa only [Experiment.cost_map] using hqc + +end ContingencyTables.PhysicalPartialSequence + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixEnergies.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixEnergies.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e1816845059f2ca37b9846a65b0e5b7e564111b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixEnergies.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextGraphEnergy +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance + +namespace OAI + +/-! # Physical prefix contexts use each exchange edge at most once -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def prefixExtension (small : I → J → Bool) (s : I×J) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) : I×J → ℕ := fun a => + if h : small a.1 a.2=true ∧ RowMajorBefore a s then (τ ⟨⟨a,h.1⟩,h.2⟩).val else 0 + +omit [Fintype I] [Fintype J] in +lemma prefixExtension_at (small : I → J → Bool) (s : I×J) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (a : Earlier small s) : + prefixExtension small s U τ a.val.val=(τ a).val := by + unfold prefixExtension + rw [dite_eq_left ⟨a.val.property,a.property⟩] + exact congrArg (fun b : Earlier small s => (τ b).val) (Subtype.ext (Subtype.ext rfl)) + +omit [Fintype I] [Fintype J] in +lemma prefixExtension_bounded (small : I → J → Bool) (s : I×J) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (a : Earlier small s) : + prefixExtension small s U τ a.val.val ≤ U := by + rw [prefixExtension_at] + exact Nat.le_of_lt_succ (τ a).isLt + +noncomputable def prefixValues (small : I → J → Bool) (s : I×J) (U : ℕ) + (z : SmallProfile small) : Earlier small s → Fin (U+1) := + fun a => ⟨min (z (a.val,false)) U,Nat.lt_succ_of_le (min_le_right _ _)⟩ + +omit [Fintype I] [Fintype J] in +lemma physicalPrefix_iff_values (small : I → J → Bool) (s : I×J) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (z : SmallProfile small) + (hz : ∀ a : Earlier small s,z (a.val,false) ≤ U) : + PhysicalPrefix small s (prefixExtension small s U τ) z ↔ prefixValues small s U z=τ := by + constructor + · intro hp + funext a + apply Fin.ext + change min (z (a.val,false)) U=(τ a).val + rw [min_eq_left (hz a),hp a,prefixExtension_at] + · intro hp a + have h := congrArg Fin.val (congrFun hp a) + change min (z (a.val,false)) U=(τ a).val at h + rw [min_eq_left (hz a)] at h + rw [prefixExtension_at] + exact h + +noncomputable def physicalEdges (small : I → J → Bool) (B : I → J → ℕ) : + Finset (SmallProfile small×SmallProfile small) := + ((vertices small B) ×ˢ (vertices small B)).filter (fun p => IntegerExchangeAdjacent p.1 p.2) + +noncomputable def physicalEnergy (small : I → J → Bool) (B : I → J → ℕ) + (f H : SmallProfile small → ℝ) : ℝ := + (∑ p ∈ physicalEdges small B,edgeTerm f H p)/2 + +lemma physicalContextEdges_eq_filter (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (U : ℕ) (hB : ∀ i j,small i j=true → B i j=U) + (τ : Earlier small s → Fin (U+1)) : + physicalContextEdges small B s (prefixExtension small s U τ)= + (physicalEdges small B).filter (fun p => + prefixValues small s U p.1=prefixValues small s U p.2 ∧ prefixValues small s U p.1=τ) := by + ext p + simp only [physicalContextEdges,physicalEdges,Finset.mem_filter,Finset.mem_product] + constructor + · rintro ⟨⟨hx,hy⟩,ha,hpx,hpy⟩ + have hxb := (mem_vertices_iff small B p.1).mp hx + have hyb := (mem_vertices_iff small B p.2).mp hy + have hvx := (physicalPrefix_iff_values small s U τ p.1 (fun a => by + simpa only [hB _ _ a.val.property] using hxb.1 (a.val,false))).mp hpx + have hvy := (physicalPrefix_iff_values small s U τ p.2 (fun a => by + simpa only [hB _ _ a.val.property] using hyb.1 (a.val,false))).mp hpy + exact ⟨⟨⟨hx,hy⟩,ha⟩,hvx.trans hvy.symm,hvx⟩ + · rintro ⟨⟨⟨hx,hy⟩,ha⟩,hv,hτ⟩ + have hxb := (mem_vertices_iff small B p.1).mp hx + have hyb := (mem_vertices_iff small B p.2).mp hy + refine ⟨⟨hx,hy⟩,ha,?_,?_⟩ + · exact (physicalPrefix_iff_values small s U τ p.1 (fun a => by + simpa only [hB _ _ a.val.property] using hxb.1 (a.val,false))).mpr hτ + · exact (physicalPrefix_iff_values small s U τ p.2 (fun a => by + simpa only [hB _ _ a.val.property] using hyb.1 (a.val,false))).mpr (hv.symm.trans hτ) + +lemma sum_physicalContextEdgeTerms_le (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (U : ℕ) (hB : ∀ i j,small i j=true → B i j=U) + (f H : SmallProfile small → ℝ) (hf : ∀ z,0 ≤ f z) : + (∑ τ : Earlier small s → Fin (U+1), ∑ p ∈ + physicalContextEdges small B s (prefixExtension small s U τ), edgeTerm f H p) ≤ + ∑ p ∈ physicalEdges small B,edgeTerm f H p := by + simp_rw [physicalContextEdges_eq_filter small B s U hB] + simp only [Finset.sum_filter] + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro p _ + by_cases h : prefixValues small s U p.1=prefixValues small s U p.2 + · simp only [h,true_and,Finset.sum_ite_eq,Finset.mem_univ,↓reduceIte] + exact le_rfl + · simpa only [h,false_and,↓reduceIte,Finset.sum_const_zero,edgeTerm] using + mul_nonneg (le_min (hf p.1) (hf p.2)) (sq_nonneg (H p.1-H p.2)) + +/-- At a fixed exposed cell, prefix contexts partition eligible physical +edges. Nonnegative exchange energy is therefore counted at most once. -/ +theorem sum_physicalContextEnergy_le (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (U : ℕ) (hB : ∀ i j,small i j=true → B i j=U) + (f H : SmallProfile small → ℝ) (hf : ∀ z,0 ≤ f z) : + (∑ τ : Earlier small s → Fin (U+1), + physicalContextEnergy small B s (prefixExtension small s U τ) f H) ≤ + physicalEnergy small B f H := by + unfold physicalContextEnergy physicalEnergy + rw [← Finset.sum_div] + exact div_le_div_of_nonneg_right + (sum_physicalContextEdgeTerms_le small B s U hB f H hf) (by norm_num) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixTail.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixTail.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d0ca84f880480844ebeae3bdee26dcda69f89b6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPrefixTail.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPartialSequence + +namespace OAI + +/-! # Future halting tails after a bounded stopping prefix -/ + +namespace ContingencyTables.PhysicalPrefixTail +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open PhysicalRetryTail + +variable {Γ Q A : Type} [Inhabited Γ] + +lemma deterministic_mean (M : Table Γ Q) (c d : Cfg Γ Q) (k : ℕ) + (h : ∀ b : Stream,execute M k c b=d) (f : Cfg Γ Q → ℚ) : + (experiment M k c).mean f=f d := by + rw [←physical_law] + simp_rw [h] + exact average_const _ _ + +/-- A prefix may end at different times on different tapes. After its +worst-case budget, the future live probability is bounded by the average +future live probability at its actual endpoints. -/ +theorem after_prefix (M : Table Γ Q) (out : A → Cfg Γ Q) (c : Cfg Γ Q) + (p : Experiment A) (h : Implements M out c p) (S n : ℕ) (hS : p.cost≤S) : + (experiment M (S+n) c).mean live≤ + p.mean (fun a => (experiment M n (out a)).mean live) := by + induction h generalizing S n with + | done a => + have hm := tail_antitone M (out a) (show n≤S+n by omega) + unfold tail at hm + change (experiment M (S+n) (out a)).mean live≤(experiment M n (out a)).mean live + exact_mod_cast hm + | read c p h ih => + have hpos : 0 + have hk : k≤S := by simp only [Experiment.cost] at hS; omega + obtain ⟨r,hr⟩ := Nat.exists_eq_add_of_le hk + have hpbound : p.cost≤r := by simp only [Experiment.cost] at hS; omega + rw [hr,Nat.add_assoc,experiment_mean_add,deterministic_mean M c d k hs] + exact ih r n hpbound + +end ContingencyTables.PhysicalPrefixTail + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPublicLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPublicLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..aac5ac59e1e2aa2367df20adb062f781020340d7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalPublicLaw.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalEventBounds +import OAI.Combinatorics.ContingencyTables.AlgorithmStatements + +namespace OAI + +/-! # Public probabilities and physical terminal events -/ + +namespace ContingencyTables.PhysicalPublicLaw +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost Turing +open PhysicalEventBounds +open scoped BigOperators Classical +noncomputable section + +def outputs {Q : Type} (as : List Symbol) (d : Cfg Symbol Q) : Prop := + d.state=none ∧ d.tape.right₀=ListBlank.mk as + +lemma tableMass_eq (P : Program) (input : List Symbol) (t : ℕ) + {m n : ℕ} (X : Fin m → Fin n → ℕ) : + Algorithms.tableMass P.machine input t X= + ((experiment P.table t (P.initial (Tape.mk₁ input))).mean + (event (outputs (Algorithms.encodeMatrix X))):ℝ) := by + have he : ∀ b : Bits t,Algorithms.OutputsTable P.machine input b X ↔ + outputs (Algorithms.encodeMatrix X) + (execute P.table t (P.initial (Tape.mk₁ input)) (extend b)) := by + intro b + simp only [Algorithms.OutputsTable,outputs,run_halted_iff,Program.run_tape] + have hm := physical_law P.table t (P.initial (Tape.mk₁ input)) + (event (outputs (Algorithms.encodeMatrix X))) + have ha : average (fun b : Bits t => event (outputs (Algorithms.encodeMatrix X)) + (execute P.table t (P.initial (Tape.mk₁ input)) (extend b)))= + ((Finset.univ.filter fun b : Bits t => Algorithms.OutputsTable P.machine input b X).card:ℚ)/ + (2:ℚ)^t := by + simp only [average,event,←he,Finset.sum_boole] + rw [ha] at hm + have hc := congrArg (fun x : ℚ => (x:ℝ)) hm + simpa only [Algorithms.tableMass,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat] using hc + +lemma haltMass_eq (P : Program) (input : List Symbol) (t : ℕ) : + Algorithms.haltMass P.machine input t= + ((experiment P.table t (P.initial (Tape.mk₁ input))).mean + (event (fun d => d.state=none)):ℝ) := by + have hm := physical_law P.table t (P.initial (Tape.mk₁ input)) + (event (fun d => d.state=none)) + have ha : average (fun b : Bits t => event (fun d => d.state=none) + (execute P.table t (P.initial (Tape.mk₁ input)) (extend b)))= + ((Finset.univ.filter fun b : Bits t => (MatchingFPRAS.run P.machine input b).state=none).card:ℚ)/ + (2:ℚ)^t := by + simp only [average,event,←run_halted_iff,Finset.sum_boole] + rw [ha] at hm + have hc := congrArg (fun x : ℚ => (x:ℝ)) hm + simpa only [Algorithms.haltMass,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat] using hc + +lemma tail_eq (P : Program) (input : List Symbol) (t : ℕ) : + 1-Algorithms.haltMass P.machine input t= + PhysicalRetryTail.tail P.table (P.initial (Tape.mk₁ input)) t := by + rw [haltMass_eq] + have he : event (fun d : Cfg Symbol P.State => d.state=none)= + fun d => 1-PhysicalRetryTail.live d := by + funext d + unfold event PhysicalRetryTail.live + split_ifs <;> norm_num + rw [he,mean_one_sub] + simp only [Rat.cast_sub,Rat.cast_one,PhysicalRetryTail.tail] + ring + +end +end ContingencyTables.PhysicalPublicLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairGraph.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..886cb88db4afb9cd44b5354833b4afbb3f4db071 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairGraph.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairWords +import OAI.Combinatorics.ContingencyTables.Transport.RawSmallChoiceProperties +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSymmetricEnergy + +namespace OAI + +/-! # The actual small graph contains its exchanges and designated repairs -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts +open SmallContextEnumeration RowMajorEnumeration IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def repairEdges (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) : + Finset (SmallProfile (firstPaperSmall r c U)×SmallProfile (firstPaperSmall r c U)) := + let target := fun z => rawChoice (firstPaperSmall r c U) U + (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z)) + (Finset.univ.image (fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + (naturalProfile z.val,target z))) ∪ + (Finset.univ.image (fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + (target z,naturalProfile z.val))) + +noncomputable def fullEdges (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) := + physicalEdges (firstPaperSmall r c U) B ∪ repairEdges r c U L B hB + +noncomputable def fullEnergy (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (H : SmallProfile (firstPaperSmall r c U) → ℝ) : ℝ := + symmetricEnergy (fullEdges r c U L B hB) (hardMarginal (firstPaperSmall r c U) B r c L) H + +lemma physicalEnergy_le_full (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (H : SmallProfile (firstPaperSmall r c U) → ℝ) : + physicalEnergy (firstPaperSmall r c U) B (hardMarginal (firstPaperSmall r c U) B r c L) H ≤ + fullEnergy r c U L B hB H := + symmetricEnergy_mono _ _ Finset.subset_union_left _ _ (hardMarginal_nonnegative _ _ _ _ _) + +lemma fullEnergy_nonnegative (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (H : SmallProfile (firstPaperSmall r c U) → ℝ) : 0 ≤ fullEnergy r c U L B hB H := by + unfold fullEnergy symmetricEnergy + exact div_nonneg (Finset.sum_nonneg (fun p _ => pairTerm_nonnegative _ _ + (hardMarginal_nonnegative _ _ _ _ _) p)) (by norm_num) + +theorem actual_repair_energy_le (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (hcap : ∀ T : ResidualTables (firstPaperSmall r c U) r c + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L),∀ i j,T.val.val i j ≤ B i j) + (H : SmallProfile (firstPaperSmall r c U) → ℝ) : + (∑ z : PositiveDefects (firstPaperSmall r c U) B r c L, + hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val)* + (H (naturalProfile z.val)-wordObservable (firstPaperSmall r c U) U H (repairWord r c U L B hB z))^2) ≤ + fullEnergy r c U L B hB H := by + let x := fun z : PositiveDefects (firstPaperSmall r c U) B r c L => naturalProfile z.val + let y := fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + rawChoice (firstPaperSmall r c U) U (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z)) + have hx : Function.Injective x := by + intro a b he + apply Subtype.ext + exact naturalProfile_injective _ B he + have hxy : ∀ a b,x a≠y b := by + intro a b he + have hb := rawChoice_balanced (firstPaperSmall r c U) B U hB + (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB b)) + have hdef := a.property.1 + change SingleDefect _ B (x a) at hdef + rw [he] at hdef + exact balanced_not_defect _ B _ hb hdef + have he := repair_energy_le (fullEdges r c U L B hB) + (hardMarginal (firstPaperSmall r c U) B r c L) H (hardMarginal_nonnegative _ _ _ _ _) x y hx hxy + (fun z => Finset.mem_union_right _ (Finset.mem_union_left _ (Finset.mem_image.mpr ⟨z,Finset.mem_univ _,rfl⟩))) + (fun z => Finset.mem_union_right _ (Finset.mem_union_right _ (Finset.mem_image.mpr ⟨z,Finset.mem_univ _,rfl⟩))) + have hterm (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + pairTerm (hardMarginal (firstPaperSmall r c U) B r c L) H (x z,y z)= + hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val)* + (H (naturalProfile z.val)-wordObservable (firstPaperSmall r c U) U H (repairWord r c U L B hB z))^2 := by + change min (hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val)) + (wordWeight (firstPaperSmall r c U) B r c L U (repairWord r c U L B hB z)) * + (H (naturalProfile z.val)-wordObservable (firstPaperSmall r c U) U H + (repairWord r c U L B hB z))^2 = _ + rw [min_eq_left (repairWord_weight r c U L B hB hcap z)] + simp_rw [hterm] at he + exact he + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMargins.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMargins.lean new file mode 100644 index 0000000000000000000000000000000000000000..490fbd47aab86c99bcfd5cc827cde341c36f20f4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMargins.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalExchangeMargins +import OAI.Combinatorics.ContingencyTables.Sampling.RepairSmallMargins + +namespace OAI + +/-! # The physical padded residuals change by at most one on a repair -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions SmallContextFibres SmallContextCoordinates + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma repair_residual_margins (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (x y : PhysicalStates small B r c L) + (hxcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L x k) ≤ B i j) + (hycap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L y k) ≤ B i j) + (s t : I×J) + (hd : IsDefect (smallView small (physicalProfile small B r c L x) false) + (smallQ small B (physicalProfile small B r c L x)) s t) + (ht : small t.1 t.2=true) + (hcap : ∀ a : Cells small,repairMatrix + (smallView small (physicalProfile small B r c L x) false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) + (heq : physicalProfile small B r c L y=repairedProfile small B (physicalProfile small B r c L x) s t) : + (∀ i,|(residualRows small B r c L y i:ℤ)-residualRows small B r c L x i| ≤ 1) ∧ + (∀ j,|(residualColumns small B r c L y j:ℤ)-residualColumns small B r c L x j| ≤ 1) := by + have hx := physical_original_residuals small B r c L x hxcap + have hy := physical_original_residuals small B r c L y hycap + have hm := repair_small_margin_abs small B (physicalProfile small B r c L x) s t hd ht hcap + constructor + · intro i + unfold residualRows + rw [nat_residual_difference _ _ _ _ (hy.1 i) (hx.1 i),heq] + exact hm.1 i + · intro j + unfold residualColumns + rw [nat_residual_difference _ _ _ _ (hy.2 j) (hx.2 j),heq] + exact hm.2 j + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b3a3b21f5d7c36aadfc1b3bd95f91cd09fdd1ac --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRepairMass.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCapacity + +namespace OAI + +/-! # Literal completion-retaining repair dominates the physical weight -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def completionJointDefect (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) (s t : I×J) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (Z : CompletionFibre small B r rbar c cbar z) : JointDefect small r c rbar cbar s t := + ⟨Z.val,defect_fibre_views Z hs ht hd,Z.property.1,Z.property.2.1⟩ + +lemma jointRepair_small_entry (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) (s t : I×J) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (Z : CompletionFibre small B r rbar c cbar z) (i : I) (j : J) (hij : small i j=true) : + (jointRepair hs ht (completionJointDefect small B r rbar c cbar z s t hs ht hd Z)).val.val i j= + repairMatrix (smallView small z false) s t i j := by + change repairMatrix Z.val.val.1 s t i j=repairMatrix (smallView small z false) s t i j + apply repairMatrix_pointwise + have hx := (Z.property.2.2.1 i j hij).1 + simpa only [smallView,hij,dite_eq_left] using hx + +noncomputable def repairedCompletion (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) (s t : I×J) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (hsmall : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) + (hcap : ∀ T : ResidualTables small r c rbar cbar,∀ i j,T.val.val i j ≤ B i j) + (Z : CompletionFibre small B r rbar c cbar z) : + CompletionFibre small B r rbar c cbar (repairedProfile small B z s t) := by + let T := jointRepair hs ht (completionJointDefect small B r rbar c cbar z s t hs ht hd Z) + refine ⟨⟨(T.val.val,T.val.val),T.val.property.1,T.val.property.2⟩,T.property.1,T.property.2,?_,?_,?_⟩ + · intro i j hij + have he := jointRepair_small_entry small B r rbar c cbar z s t hs ht hd Z i j hij + change T.val.val i j=repairMatrix (smallView small z false) s t i j at he + constructor + · exact he + · change T.val.val i j=B i j-(B i j-repairMatrix (smallView small z false) s t i j) + rw [he] + exact (Nat.sub_sub_self (hsmall ⟨(i,j),hij⟩)).symm + · intro _ _ _ + rfl + · intro i j _ + exact hcap T i j + +lemma repairedCompletion_injective (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) (s t : I×J) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (hsmall : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) + (hcap : ∀ T : ResidualTables small r c rbar cbar,∀ i j,T.val.val i j ≤ B i j) : + Function.Injective (repairedCompletion small B r rbar c cbar z s t hs ht hd hsmall hcap) := by + intro X Y he + have htables : jointRepair hs ht (completionJointDefect small B r rbar c cbar z s t hs ht hd X)= + jointRepair hs ht (completionJointDefect small B r rbar c cbar z s t hs ht hd Y) := by + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun V => V.val.val.1) he + have hj := jointRepair_injective hs ht htables + apply Subtype.ext + exact congrArg (fun V : JointDefect small r c rbar cbar s t => V.val) hj + +/-- The repair is the manuscript's actual profile map, and the weight +inequality counts all completions through its explicit injective map. -/ +theorem physical_repair_weight_le (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (z : SmallProfile (firstPaperSmall r c U)) + (hz : ∀ a,z a ≤ B a.1.val.1 a.1.val.2) (s t : I×J) + (hs : firstPaperSmall r c U s.1 s.2=true) (ht : firstPaperSmall r c U t.1 t.2=true) + (hd : IsDefect (smallView (firstPaperSmall r c U) z false) + (smallQ (firstPaperSmall r c U) B z) s t) + (hcap : ∀ T : ResidualTables (firstPaperSmall r c U) r c + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L),∀ i j,T.val.val i j ≤ B i j) + (hf : 0 < hardMarginal (firstPaperSmall r c U) B r c L z) : + hardMarginal (firstPaperSmall r c U) B r c L z ≤ + hardMarginal (firstPaperSmall r c U) B r c L (repairedProfile (firstPaperSmall r c U) B z s t) := by + have hsmall := repair_small_capacity r c U L B hB z hz s t hs ht hd hf + rw [hardMarginal_eq_fibre_card _ _ _ _ _ z hz, + hardMarginal_eq_fibre_card _ _ _ _ _ _ (repairedProfile_bounded _ _ _ _ _ hsmall)] + exact_mod_cast Fintype.card_le_of_injective + (repairedCompletion _ B r _ c _ z s t hs ht hd hsmall hcap) + (repairedCompletion_injective _ B r _ c _ z s t hs ht hd hsmall hcap) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalResidualMargins.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalResidualMargins.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfa96135d14f693b41d7f0a7b2edf5480fa2a4fc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalResidualMargins.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalVariance +import OAI.Combinatorics.ContingencyTables.Transport.RectangleCompletions + +namespace OAI + +/-! # Literal padded residual completions of each positive physical state -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def residualRows (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : PhysicalStates small B r c L) (i : I) : ℕ := + r i-smallRow small (smallView small (physicalProfile small B r c L z) false) i+rowLargeCount small i*L + +noncomputable def residualColumns (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : PhysicalStates small B r c L) (j : J) : ℕ := + c j-smallColumn small B (smallView small (physicalProfile small B r c L z) true) j+columnLargeCount small j*L + +lemma physical_weight_completions (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PhysicalStates small B r c L) + (hcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L z k) ≤ B i j) : + hardMarginal small B r c L (physicalProfile small B r c L z)= + (Fintype.card (LargeCompletion small (residualRows small B r c L z) + (residualColumns small B r c L z)):ℝ) := by + have h := hardMarginal_eq_completionCount small B r c L + (physicalProfile small B r c L z) (naturalProfile_bounded z.val.val) hcap + split_ifs at h with hres + · exact h + · have hp := z.property + change 0 < hardMarginal small B r c L (physicalProfile small B r c L z) at hp + rw [h] at hp + exact False.elim (lt_irrefl _ hp) + +lemma physical_completions_nonempty (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PhysicalStates small B r c L) + (hcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L z k) ≤ B i j) : + Nonempty (LargeCompletion small (residualRows small B r c L z) + (residualColumns small B r c L z)) := by + apply Fintype.card_pos_iff.mp + have hp := z.property + change 0 < hardMarginal small B r c L (physicalProfile small B r c L z) at hp + rw [physical_weight_completions small B r c L z hcap] at hp + exact_mod_cast hp + +lemma physical_residual_totals (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PhysicalStates small B r c L) + (hcap : ∀ i j,small i j=false → (∑ k,residualRows small B r c L z k) ≤ B i j) : + (∑ i,residualRows small B r c L z i)=∑ j,residualColumns small B r c L z j := by + obtain ⟨A⟩ := physical_completions_nonempty small B r c L z hcap + calc + _ = ∑ i,∑ j,A.val.val i j := by simp_rw [A.val.property.1] + _ = ∑ j,∑ i,A.val.val i j := Finset.sum_comm + _ = _ := by simp_rw [A.val.property.2] + +/-- Rows outside the large-margin rectangle have zero residual, as +forced by the actual positive completion count. -/ +lemma physical_residual_row_zero (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) + (i : I) (hi : ¬U ≤ r i) : + residualRows (firstPaperSmall r c U) B r c L z i=0 := by + obtain ⟨A⟩ := physical_completions_nonempty _ B r c L z hcap + rw [← A.val.property.1 i] + apply Finset.sum_eq_zero + intro j _ + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hi ((firstPaperSmall_false_iff r c U i j).mp hs).1 + +lemma physical_residual_column_zero (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) + (j : J) (hj : ¬U ≤ c j) : + residualColumns (firstPaperSmall r c U) B r c L z j=0 := by + obtain ⟨A⟩ := physical_completions_nonempty _ B r c L z hcap + rw [← A.val.property.2 j] + apply Finset.sum_eq_zero + intro i _ + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hj ((firstPaperSmall_false_iff r c U i j).mp hs).2 + +/-- Thus the marginal used by the variance proof is exactly the number +of ordinary tables on the large rectangle, including empty rectangles. -/ +theorem physical_weight_rectangle (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) : + hardMarginal (firstPaperSmall r c U) B r c L (physicalProfile _ B r c L z)= + (Fintype.card (Table + (fun i : {i // U ≤ r i} => residualRows (firstPaperSmall r c U) B r c L z i.val) + (fun j : {j // U ≤ c j} => residualColumns (firstPaperSmall r c U) B r c L z j.val)):ℝ) := by + rw [physical_weight_completions _ B r c L z hcap] + convert congrArg (fun n : ℕ => (n:ℝ)) (Fintype.card_congr (rectangleCompletionEquiv (firstPaperSmall r c U) + (fun i => U ≤ r i) (fun j => U ≤ c j) (firstPaperSmall_false_iff r c U) + (residualRows _ B r c L z) (residualColumns _ B r c L z) + (physical_residual_row_zero r c U L B z hcap) + (physical_residual_column_zero r c U L B z hcap))) using 1 + all_goals + congr 3 + all_goals exact Subsingleton.elim _ _ + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryIteration.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3e265c295f5eb03d127d45b122217d3d26e4545 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryIteration.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Machines.OnlineIntegerRetry + +namespace OAI + +/-! # Composing physical retry prefixes with a uniform cost per attempt -/ + +namespace ContingencyTables.PhysicalRetryIteration +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost + +def repeatTrial {B : Type} (p : Experiment (Option B)) : ℕ → Experiment (Option B) + | 0 => .done none + | N+1 => p.bind (fun b => b.elim (repeatTrial p N) (fun b => .done (some b))) + +theorem repeat_cost {B : Type} (p : Experiment (Option B)) (N : ℕ) : (repeatTrial p N).cost ≤ N*p.cost := by + induction N with + | zero => simp [repeatTrial,Experiment.cost] + | succ N ih => + have hc:=Experiment.cost_bind_le p + (fun b => b.elim (repeatTrial p N) (fun b => .done (some b))) (N*p.cost) (by + intro b; cases b + · exact ih + · exact Nat.zero_le _) + simpa only [repeatTrial,Nat.succ_mul,Nat.add_comm] using hc + +theorem repeat_implements {Γ Q B : Type} [Inhabited Γ] (M : Table Γ Q) + (out : Option B → Cfg Γ Q) (c : Cfg Γ Q) (hc : out none=c) + (p : Experiment (Option B)) (hp : Implements M out c p) (N : ℕ) : + Implements M out c (repeatTrial p N) := by + induction N with + | zero => simpa only [repeatTrial,hc] using (Implements.done (M := M) (out := out) none) + | succ N ih => + apply hp.bind _ out + intro b + cases b with + | none => simpa only [Option.elim_none,hc] using ih + | some b => exact .done (some b) + +lemma repeat_mean {A B : Type} (f : A → Experiment (Option B)) (a : A) + (p : Experiment (Option B)) (hp : ∀ g,p.mean g=(f a).mean g) (N : ℕ) + (g : Option B → ℚ) : + (repeatTrial p N).mean g=(OnlineIntegerRetry.prefixExperiment (f := f) a N).mean g := by + induction N with + | zero => rfl + | succ N ih => + rw [repeatTrial,OnlineIntegerRetry.prefixExperiment,Experiment.mean_bind, + Experiment.mean_bind,hp] + congr 1 + funext b + cases b <;> simp only [Option.elim_none,Option.elim_some,ih] + +variable {A B : Type} [TreeTyped.Codec A] [TreeTyped.Codec B] [Inhabited B] +variable {f : A → Experiment (Option B)} (F : OnlineTree.Realizer f) + +/-- Compiling one attempt and composing its execution proof avoids any +growth of the compiler overhead with the number of preceding attempts. -/ +theorem linear_physical_prefix (a : A) (s : TreeData.Data) (H : ℕ) + (hH : StackCost.StackBound + (OnlineTree.initial (OnlineIntegerRetry.program F) (TreeTyped.encode a) s).stk H) + (N : ℕ) : + ∃ q,PhysicalPost.Implements + (OnlineStack.table (OnlineIntegerRetry.program F).code (OnlineIntegerRetry.program F).coin) + (fun b => OnlineStack.cfg (OnlineControl.cfg (OnlineIntegerRetry.instructions F) + (OnlineIntegerRetry.output a s b).1 (OnlineIntegerRetry.output a s b).2)) + (OnlineStack.cfg (OnlineTree.initial (OnlineIntegerRetry.program F) (TreeTyped.encode a) s)) q ∧ + (∀ g : Option B → ℚ,q.mean g= + (OnlineIntegerRetry.prefixExperiment (f := f) a N).mean g) ∧ + q.cost ≤ N*(OnlineIntegerRetry.stepCost F a* + OnlineStack.Executes.factor (OnlineIntegerRetry.program F).code H + (OnlineIntegerRetry.stepCost F a)) := by + obtain ⟨p,hp,hpm,hpc⟩:=OnlineIntegerRetry.physical_prefix F a s 1 H hH + simp only [one_mul] at hpc + have hm : ∀ g,p.mean g=(f a).mean g := by + intro g + rw [hpm,OnlineIntegerRetry.prefixExperiment,Experiment.mean_bind] + congr 1 + funext b + cases b <;> rfl + refine ⟨repeatTrial p N,repeat_implements _ _ _ rfl p hp N,repeat_mean f a p hm N,?_⟩ + exact (repeat_cost p N).trans (Nat.mul_le_mul_left N hpc) + +end ContingencyTables.PhysicalRetryIteration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryTail.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryTail.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f71c9c5e568ab0bd696ee6d149b0674b775a576 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalRetryTail.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRetryIteration +import OAI.Combinatorics.ContingencyTables.Machines.GeometricRuntime + +namespace OAI + +/-! # Physical halting tails from finite rejection prefixes -/ + +namespace ContingencyTables.PhysicalRetryTail +open MatchingFPRAS MatchingFPRAS.PhysicalStream MatchingFPRAS.PhysicalPost +open scoped BigOperators Classical + +variable {Γ Q B : Type} [Inhabited Γ] + +def live (c : Cfg Γ Q) : ℚ := if c.state=none then 0 else 1 + +private lemma mean_mono {A : Type} (p : Experiment A) (f g : A → ℚ) (h : ∀ a,f a≤g a) : + p.mean f≤p.mean g := by + induction p with + | done a => exact h a + | read p ih => simp only [Experiment.mean]; linarith [ih false,ih true] + | delay n p ih => exact ih + +private lemma mean_const {A : Type} (p : Experiment A) (c : ℚ) : p.mean (fun _ => c)=c := by + induction p with + | done => rfl + | read p ih => simp only [Experiment.mean,ih]; ring + | delay n p ih => exact ih + +lemma live_nonnegative (c : Cfg Γ Q) : 0≤live c := by unfold live; split_ifs <;> norm_num +lemma live_le_one (c : Cfg Γ Q) : live c≤1 := by unfold live; split_ifs <;> norm_num + +lemma experiment_mean_add (M : Table Γ Q) (n m : ℕ) (c : Cfg Γ Q) (g : Cfg Γ Q → ℚ) : + (experiment M (n+m) c).mean g= + (experiment M n c).mean (fun d => (experiment M m d).mean g) := by + induction n generalizing c with + | zero => simp only [Nat.zero_add,experiment,Experiment.mean] + | succ n ih => simp only [Nat.succ_add,experiment,Experiment.mean,ih] + +lemma halted_mean (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) (h : c.state=none) + (g : Cfg Γ Q → ℚ) : (experiment M n c).mean g=g c := by + induction n with + | zero => rfl + | succ n ih => + have ht (b : Bool) : PhysicalPost.tick M c b=c := by simp [PhysicalPost.tick,h] + simp only [experiment,Experiment.mean,ht,ih] + ring + +lemma future_live_le (M : Table Γ Q) (n : ℕ) (c : Cfg Γ Q) : + (experiment M n c).mean live≤live c := by + by_cases h : c.state=none + · rw [halted_mean M n c h] + · have hm:=mean_mono (experiment M n c) live (fun _ => 1) live_le_one + rw [mean_const] at hm + simpa only [live,ite_eq_right h] using hm + +def tail (M : Table Γ Q) (c : Cfg Γ Q) (n : ℕ) : ℝ := + ((experiment M n c).mean live:ℝ) + +lemma tail_nonnegative (M : Table Γ Q) (c : Cfg Γ Q) (n : ℕ) : 0≤tail M c n := by + have hm:=mean_mono (experiment M n c) (fun _ => 0) live live_nonnegative + rw [mean_const] at hm + unfold tail + exact_mod_cast hm + +lemma tail_antitone (M : Table Γ Q) (c : Cfg Γ Q) : Antitone (tail M c) := by + intro n m hnm + obtain ⟨k,rfl⟩:=Nat.exists_eq_add_of_le hnm + have hm : (experiment M (n+k) c).mean live≤(experiment M n c).mean live := by + rw [experiment_mean_add] + exact mean_mono _ _ _ (future_live_le M k) + unfold tail + exact_mod_cast hm + +lemma padded_halted_result (M : Table Γ Q) (out : B → Cfg Γ Q) (c : Cfg Γ Q) + (p : Experiment B) (hp : Implements M out c p) (n : ℕ) (hn : p.cost≤n) + (b : Stream) (hhalt : (out (p.run b).1).state=none) : + execute M n c b=out (p.run b).1 := by + have hb : (p.run b).2≤n := (Experiment.run_cost p b).trans hn + obtain ⟨k,hk⟩:=Nat.exists_eq_add_of_le hb + rw [hk,execute_add,hp.execution b] + have he : out (p.run b).1=⟨none,(out (p.run b).1).tape⟩ := by + cases e:out (p.run b).1 with + | mk state tape => + rw [e] at hhalt + change state=none at hhalt + subst state + rfl + rw [he,execute_halted] + +/-- All successful prefix executions have halted by the prefix cost. +This implication is enough even though the failed endpoint is still live. -/ +theorem tail_le_failure (M : Table Γ Q) (out : Option B → Cfg Γ Q) (c : Cfg Γ Q) + (p : Experiment (Option B)) (hp : Implements M out c p) + (hhalt : ∀ b,(out (some b)).state=none) (n : ℕ) (hn : p.cost≤n) : + tail M c n≤(p.mean (fun b => if b=none then 1 else 0):ℚ) := by + have hb : (experiment M n c).mean live≤p.mean (fun b => if b=none then 1 else 0) := by + rw [←physical_law,←Experiment.average_run p _ n hn] + unfold average + apply div_le_div_of_nonneg_right _ (by positivity) + apply Finset.sum_le_sum + intro b _ + cases he:(p.run (extend b)).1 with + | none => simp only [ite_true]; exact live_le_one _ + | some x => + have hh : (out (p.run (extend b)).1).state=none := by rw [he]; exact hhalt x + rw [padded_halted_result M out c p hp n hn (extend b) hh] + simp [he,live,hhalt] + unfold tail + exact_mod_cast hb + +end ContingencyTables.PhysicalRetryTail + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..b606539d20f056ab4148eee740e13f9cd73249c6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallEnergy.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalSmallGraph +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSupportEnergy + +namespace OAI + +/-! # Exact energy on the positive physical graph -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal CompletionCounts SmallContextEnumeration RowMajorEnumeration +open IntegerWeightedTransport + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma fullEdges_vertices (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (p : SmallProfile (firstPaperSmall r c U)×SmallProfile (firstPaperSmall r c U)) + (hp : p ∈ fullEdges r c U L B hB) : + p.1 ∈ vertices (firstPaperSmall r c U) B ∧ p.2 ∈ vertices (firstPaperSmall r c U) B := by + have hd (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + naturalProfile z.val ∈ vertices (firstPaperSmall r c U) B := + (mem_vertices_iff _ B _).mpr ⟨naturalProfile_bounded z.val,Or.inr z.property.1⟩ + have ht (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + rawChoice (firstPaperSmall r c U) U (wordChoices _ U (repairWord r c U L B hB z)) ∈ + vertices (firstPaperSmall r c U) B := + (mem_vertices_iff _ B _).mpr ⟨rawChoice_bounded _ B U hB _,Or.inl (rawChoice_balanced _ B U hB _)⟩ + rcases Finset.mem_union.mp hp with hp|hp + · exact Finset.mem_product.mp (Finset.mem_filter.mp hp).1 + · rcases Finset.mem_union.mp hp with hp|hp + · obtain ⟨z,_,rfl⟩ := Finset.mem_image.mp hp + exact ⟨hd z,ht z⟩ + · obtain ⟨z,_,rfl⟩ := Finset.mem_image.mp hp + exact ⟨ht z,hd z⟩ + +lemma positive_vertex_is_physical (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (v : SmallProfile small) + (hv : v ∈ vertices small B) (hp : 0 < hardMarginal small B r c L v) : + ∃ z : PhysicalStates small B r c L,physicalProfile small B r c L z=v := by + obtain ⟨hb,hpattern⟩ := (mem_vertices_iff small B v).mp hv + let b : BoundedProfile small B := fun a => ⟨v a,Nat.lt_succ_of_le (hb a)⟩ + let p : Profiles small B := ⟨b,hpattern⟩ + exact ⟨⟨p,hp⟩,rfl⟩ + +/-- Deleting zero-weight vertices preserves the exact unnormalized energy, +not merely an inequality for a restricted class of observables. -/ +theorem fullEnergy_physical_eq (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (H : PhysicalStates (firstPaperSmall r c U) B r c L → ℝ) : + fullEnergy r c U L B hB (physicalExtension _ B r c L H)= + (∑ x,∑ y,if physicalAdjacent r c U L B hB x y then + min (hardMarginal (firstPaperSmall r c U) B r c L (physicalProfile _ B r c L x)) + (hardMarginal (firstPaperSmall r c U) B r c L (physicalProfile _ B r c L y))* + (H x-H y)^2 else 0)/2 := by + have he := symmetricEnergy_restrict_observable (fullEdges r c U L B hB) + (hardMarginal (firstPaperSmall r c U) B r c L) (physicalExtension _ B r c L H) + (hardMarginal_nonnegative _ B r c L) (physicalProfile _ B r c L) + (physicalProfile_injective _ B r c L) (by + intro p hp + have hv := fullEdges_vertices r c U L B hB p hp + constructor + · intro h + exact positive_vertex_is_physical _ B r c L p.1 hv.1 + (lt_of_le_of_ne (hardMarginal_nonnegative _ B r c L p.1) (Ne.symm h)) + · intro h + exact positive_vertex_is_physical _ B r c L p.2 hv.2 + (lt_of_le_of_ne (hardMarginal_nonnegative _ B r c L p.2) (Ne.symm h))) H (physicalExtension_at _ B r c L H) + + convert he using 1 + · rfl + · apply congrArg (fun a : ℝ => a/2) + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + unfold physicalAdjacent + split_ifs <;> rfl + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallGraph.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..61c09dad1db7da25c54e5b1a1f89b1fc29eca925 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/PhysicalSmallGraph.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphDegree +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalVariance + +namespace OAI + +/-! # The finite graph on positive-weight physical states -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open CompletionCounts SmallContextEnumeration IntegerWeightedTransport + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma fullEdges_symmetric (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x y : SmallProfile (firstPaperSmall r c U)) : + (x,y) ∈ fullEdges r c U L B hB ↔ (y,x) ∈ fullEdges r c U L B hB := by + suffices hs : ∀ x y,(x,y) ∈ fullEdges r c U L B hB → (y,x) ∈ fullEdges r c U L B hB from + ⟨hs x y,hs y x⟩ + intro x y he + rcases Finset.mem_union.mp he with he|he + · apply Finset.mem_union_left + obtain ⟨hp,D,i,j,hij,hi,hj,hx,hy⟩ := Finset.mem_filter.mp he + exact Finset.mem_filter.mpr ⟨Finset.mem_product.mpr (Finset.mem_product.mp hp).symm, + D,j,i,hij.symm,hj,hi,hy,hx⟩ + · apply Finset.mem_union_right + rcases Finset.mem_union.mp he with he|he + · apply Finset.mem_union_right + obtain ⟨z,hz,he⟩ := Finset.mem_image.mp he + exact Finset.mem_image.mpr ⟨z,hz,Prod.ext (congrArg Prod.snd he) (congrArg Prod.fst he)⟩ + · apply Finset.mem_union_left + obtain ⟨z,hz,he⟩ := Finset.mem_image.mp he + exact Finset.mem_image.mpr ⟨z,hz,Prod.ext (congrArg Prod.snd he) (congrArg Prod.fst he)⟩ + +noncomputable def physicalAdjacent (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x y : PhysicalStates (firstPaperSmall r c U) B r c L) : Prop := + (physicalProfile _ B r c L x,physicalProfile _ B r c L y) ∈ fullEdges r c U L B hB + +lemma physicalAdjacent_symmetric (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x y : PhysicalStates (firstPaperSmall r c U) B r c L) : + physicalAdjacent r c U L B hB x y ↔ physicalAdjacent r c U L B hB y x := + fullEdges_symmetric r c U L B hB _ _ + +lemma physicalAdjacent_degree (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x : PhysicalStates (firstPaperSmall r c U) B r c L) : + (Finset.univ.filter (physicalAdjacent r c U L B hB x)).card ≤ + 5*(Fintype.card (Cells (firstPaperSmall r c U)))^2+1 := by + let p := physicalProfile (firstPaperSmall r c U) B r c L + have hsub : (Finset.univ.filter (physicalAdjacent r c U L B hB x)).image p ⊆ + fullNeighbors r c U L B hB (p x) := by + intro y hy + obtain ⟨z,hz,rfl⟩ := Finset.mem_image.mp hy + exact Finset.mem_image.mpr ⟨(p x,p z),Finset.mem_filter.mpr + ⟨(Finset.mem_filter.mp hz).2,rfl⟩,rfl⟩ + calc + _ = ((Finset.univ.filter (physicalAdjacent r c U L B hB x)).image p).card := + (Finset.card_image_of_injective _ (physicalProfile_injective _ B r c L)).symm + _ ≤ (fullNeighbors r c U L B hB (p x)).card := Finset.card_le_card hsub + _ ≤ _ := fullNeighbors_card_le r c U L B hB (p x) + +lemma physicalAdjacent_degree_allowance (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (x : PhysicalStates (firstPaperSmall r c U) B r c L) : + (Finset.univ.filter (physicalAdjacent r c U L B hB x)).card ≤ + 5*(dimensionAllowance (I := I) (J := J))^2+1 := by + have hc : Fintype.card (Cells (firstPaperSmall r c U)) ≤ dimensionAllowance (I := I) (J := J) := by + calc + _ ≤ Fintype.card (I×J) := Fintype.card_subtype_le _ + _ = Fintype.card I*Fintype.card J := Fintype.card_prod _ _ + _ ≤ _ := dimension_le_allowance + exact (physicalAdjacent_degree r c U L B hB x).trans (by gcongr) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..30ea3481c54ae28cb701beb940841e2547e32f39 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxEnumeration.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxIndex +import OAI.Combinatorics.ContingencyTables.Machines.CompletionEnumerationProgram + +namespace OAI + +/-! # Executable enumeration of the bounded two-view profile box -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +def profileEnumerationData (z : ProfileCheckData) : GridEnumerationData := + (((z.1.1.1++z.1.1.1).map (fun _ => false)),z.2+1) + +def profileEnumerationDataRealizer : Realizer profileEnumerationData := by + let catalog : Realizer (fun z : ProfileCheckData => z.1.1.1) := + composition (composition first first) first + let markers := composition (composition (pair catalog catalog) append) (map (constant false)) + exact pair markers (composition second successor) + +lemma polynomial_profileEnumerationData : PolynomialTime profileEnumerationDataRealizer := by + unfold profileEnumerationDataRealizer + exact polynomial_pair (polynomial_composition + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first)) + polynomial_append) (polynomial_map (polynomial_constant false))) + (polynomial_composition polynomial_second polynomial_successor) + +def profileBoxViews (z : ProfileCheckData) : List (List ℕ×List ℕ) := + (gridWords (profileEnumerationData z)).map (fun word => splitViews (z.1.1.1.length,word)) + +def profileBoxViewsRealizer : Realizer profileBoxViews := by + let width : Realizer (fun z : ProfileCheckData => z.1.1.1.length) := + composition (composition (composition first first) first) listLength + let words := composition profileEnumerationDataRealizer gridWordsRealizer + exact composition (pair width words) (mapWith splitViewsRealizer) + +lemma work_profileBoxViews : WorkBound profileBoxViewsRealizer + (fun z => gridStateCount (profileEnumerationData z)+weight z) := by + have hp : WorkBound profileEnumerationDataRealizer + (fun z => gridStateCount (profileEnumerationData z)+weight z) := + work_of_polynomial polynomial_profileEnumerationData Polynomial.X (fun z => by simp) + obtain ⟨p,hp'⟩ := hp + have hw : WorkBound (composition profileEnumerationDataRealizer gridWordsRealizer) + (fun z => gridStateCount (profileEnumerationData z)+weight z) := by + apply work_composition ⟨p,hp'⟩ work_gridWords (Polynomial.X+p) + intro z + have h := hp' z + simp only [Polynomial.eval_add,Polynomial.eval_X] + change gridStateCount (profileEnumerationData z)+weight (profileEnumerationData z)≤_ + change _≤p.eval (gridStateCount (profileEnumerationData z)+weight z) at h + omega + unfold profileBoxViewsRealizer + apply work_then_polynomial _ (polynomial_mapWith polynomial_splitViews) + apply work_pair _ hw Polynomial.X (fun z => by simp) + apply work_of_polynomial _ Polynomial.X (fun z => by simp) + exact polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_listLength + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) + +lemma profileBoxViews_actual (x : PaperStates r c) : + profileBoxViews (stateCodeData r c e x)= + List.ofFn (fun k : ProfileIndex (m := m) (n := n) (q := q) => + splitViews (q,List.ofFn (fun i => + ((finFunctionFinEquiv.symm k : ProfileBox (m := m) (n := n) (q := q)) i).val))) := by + have hlen : ((cellCatalog (paperSmall r c) e++cellCatalog (paperSmall r c) e).map + (fun _ => false)).length=q+q := by + simp only [List.length_map,List.length_append,cellCatalog,List.length_ofFn] + unfold profileBoxViews profileEnumerationData stateCodeData codeCheckData + rw [gridWords_finFunctions _ (d^20) (q+q) hlen,List.map_ofFn] + simp only [cellCatalog,List.length_ofFn] + rfl + +lemma profileBoxViews_decoded (x : PaperStates r c) : + (profileBoxViews (stateCodeData r c e x)).map (decodeStateCode r c e)= + List.ofFn (profileAt r c e) := by + rw [profileBoxViews_actual,List.map_ofFn] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxIndex.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..8566f7e5bcddb4e64d6975bfa740d18aa906e1db --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxIndex.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileSemantics +import OAI.Combinatorics.ContingencyTables.Dense.GridIndexProgram +import OAI.Combinatorics.ContingencyTables.Transport.BoxCompletion + +namespace OAI + +/-! # A computed finite-box index for the two small-profile views -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +def profileBoxIndex (z : ProfileCheckData) : ℕ := + gridIndex (flattenViews z.1.1.2,z.2+1) + +def profileBoxIndexRealizer : Realizer profileBoxIndex := + composition (pair (composition profileViews flattenViewsRealizer) + (composition second successor)) gridIndexRealizer + +lemma polynomial_profileBoxIndex : PolynomialTime profileBoxIndexRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_profileViews polynomial_flattenViews) + (polynomial_composition polynomial_second polynomial_successor)) polynomial_gridIndex + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "U" => d^20 + +abbrev ProfileBox := Fin (q+q) → Fin (U+1) +abbrev ProfileIndex := Fin ((U+1)^(q+q)) + +def profileBoxCoordinates (x : PaperStates r c) : ProfileBox (m := m) (n := n) (q := q) := + fun i => ⟨physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) x + (flatViewEquiv (paperSmall r c) e i), + Nat.lt_succ_of_le (stateCode_bounded r c x _ _)⟩ + +def profileIndex (x : PaperStates r c) : ProfileIndex (m := m) (n := n) (q := q) := + finFunctionFinEquiv (profileBoxCoordinates r c e x) + +attribute [local irreducible] physicalProfile + +lemma profileBoxCoordinates_code (x : PaperStates r c) : + List.ofFn (fun i => (profileBoxCoordinates r c e x i).val)= + flattenViews (stateCode r c e x) := by + unfold profileBoxCoordinates stateCode + exact (flatten_profileCode (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) x)).symm + +attribute [local irreducible] profileBoxCoordinates profileIndex + +lemma profileBoxIndex_actual (x : PaperStates r c) : + profileBoxIndex (stateCodeData r c e x)=(profileIndex r c e x).val := by + unfold profileBoxIndex stateCodeData codeCheckData + rw [←profileBoxCoordinates_code r c e x] + unfold profileIndex + exact gridIndex_ofFn _ + +def profileAt (k : ProfileIndex (m := m) (n := n) (q := q)) : Option (PaperStates r c) := + decodeStateCode r c e (splitViews (q,List.ofFn + (fun i => ((finFunctionFinEquiv.symm k : ProfileBox (m := m) (n := n) (q := q)) i).val))) + +lemma profileAt_index (x : PaperStates r c) : + profileAt r c e (profileIndex r c e x)=some x := by + unfold profileAt profileIndex + rw [Equiv.symm_apply_apply,profileBoxCoordinates_code] + have hl : (stateCode r c e x).1.length=q := by + simp only [stateCode,profileCode,viewList,List.length_ofFn] + have hs : splitViews (q,flattenViews (stateCode r c e x))=stateCode r c e x := by + calc + _=splitViews ((stateCode r c e x).1.length,flattenViews (stateCode r c e x)) := + congrArg (fun k => splitViews (k,flattenViews (stateCode r c e x))) hl.symm + _=_ := split_flattenViews _ + rw [hs] + exact decode_stateCode r c e x + +lemma profileIndex_injective : Function.Injective (profileIndex r c e) := by + intro x y hxy + have h := congrArg (profileAt r c e) hxy + simpa only [profileAt_index,Option.some.injEq] using h + +lemma profileAt_eq_some (k : ProfileIndex (m := m) (n := n) (q := q)) + (x : PaperStates r c) : profileAt r c e k=some x ↔ profileIndex r c e x=k := by + constructor + · intro h + have hc := (decodeStateCode_eq_some_iff r c e _ x).mp h + have he : List.ofFn (fun i => (profileBoxCoordinates r c e x i).val)= + List.ofFn (fun i => ((finFunctionFinEquiv.symm k : + ProfileBox (m := m) (n := n) (q := q)) i).val) := by + rw [profileBoxCoordinates_code] + exact (congrArg flattenViews hc).trans (by simp [flattenViews,splitViews]) + have hv : profileBoxCoordinates r c e x=finFunctionFinEquiv.symm k := by + funext i + exact Fin.ext (congrFun (List.ofFn_injective he) i) + unfold profileIndex + rw [hv,Equiv.apply_symm_apply] + · intro h + rw [←h] + exact profileAt_index r c e x + +/-- The finite box includes every positive profile exactly once; all +other vectors contribute zero to a decoded weighted sum. -/ +lemma sum_profileAt (w : PaperStates r c → ℕ) : + (∑ k : ProfileIndex (m := m) (n := n) (q := q),(profileAt r c e k).elim 0 w)= + ∑ x,w x := by + simp_rw [BoxCompletion.decode_elim_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp_rw [profileAt_eq_some r c e] + simp + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..973989e9fc07bc036ec6b35f03431ed11847c740 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileBoxLaw.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxIndex +import OAI.Combinatorics.ContingencyTables.Transport.ListedIntegerLaw +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLawEmbedding +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # The actual adaptive profile walk embedded in its enumerable box -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] listedStepCounts profileIndex + +/-- Invalid vectors get harmless stationary rows. Every actual profile +row is exactly the computed sampler transition transported to the box. -/ +def profileBoxStep (k : BoxIndex) : IntegerLaw BoxIndex (2^(s+f)) := + (profileAt r c e k).elim (IntegerLaw.point (2^(s+f)) k) + (fun x => (listedStepCounts r c e hr hc b h hb x).push (profileIndex r c e)) + +lemma profileBoxStep_index (x : PaperStates r c) : + profileBoxStep r c e hr hc b h hb (profileIndex r c e x)= + (listedStepCounts r c e hr hc b h hb x).push (profileIndex r c e) := by + unfold profileBoxStep + rw [profileAt_index] + rfl + +lemma profileBoxWalk_count (x : PaperStates r c) (N : ℕ) (k : BoxIndex) : + (IntegerLaw.walk (profileBoxStep r c e hr hc b h hb) (profileIndex r c e x) N).count k= + ((listedWalkCounts r c e hr hc b h hb x N).push (profileIndex r c e)).count k := + IntegerLaw.walk_push_count (listedStepCounts r c e hr hc b h hb) + (profileBoxStep r c e hr hc b h hb) (profileIndex r c e) + (profileBoxStep_index r c e hr hc b h hb) x N k + +lemma profileBoxWalk_actual_count (x y : PaperStates r c) (N : ℕ) : + (IntegerLaw.walk (profileBoxStep r c e hr hc b h hb) (profileIndex r c e x) N).count + (profileIndex r c e y)=(listedWalkCounts r c e hr hc b h hb x N).count y := by + rw [profileBoxWalk_count] + exact IntegerLaw.push_count_injective _ _ (profileIndex_injective r c e) y + +/-- Matrix propagation computes all box masses, including the zero +masses of invalid vectors, without enumerating random histories. -/ +lemma profileBox_iterate (x : PaperStates r c) (N : ℕ) : + IntegerMatrixPrograms.iterate (N, + (List.ofFn (fun target : BoxIndex => List.ofFn (fun source : BoxIndex => + (profileBoxStep r c e hr hc b h hb source).count target)), + List.ofFn (fun k : BoxIndex => if k=profileIndex r c e x then 1 else 0)))= + List.ofFn (fun k : BoxIndex => + ((listedWalkCounts r c e hr hc b h hb x N).push (profileIndex r c e)).count k) := by + rw [IntegerMatrixPrograms.iterate_ofFn] + apply congrArg List.ofFn + funext k + exact profileBoxWalk_count r c e hr hc b h hb x N k + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileCodeEquality.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileCodeEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..8afa48316feab2cc045dc1b56a28767637795a70 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileCodeEquality.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileFlatCode +import OAI.Combinatorics.MatchingCount.Machines.TreeCanonical + +namespace OAI + +/-! # Polynomial equality and duplicate removal for profile codes -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def listEntryEqual (z : (List ℕ×List ℕ)×ℕ) : Bool := + decide (z.1.1.getD z.2 0=z.1.2.getD z.2 0) + +def listEntryEqualRealizer : Realizer listEntryEqual := + composition (pair + (composition (pair (composition first first) second) (getDFast 0)) + (composition (pair (composition first second) second) (getDFast 0))) natEqual + +lemma polynomial_listEntryEqual : PolynomialTime listEntryEqualRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast 0))) polynomial_natEqual + +def equalityIndices : Realizer (fun z : List ℕ×List ℕ => List.range z.1.length) := + composition first profileIndices + +lemma polynomial_equalityIndices : PolynomialTime equalityIndices := + polynomial_composition polynomial_first polynomial_profileIndices + +def listNatTest (z : List ℕ×List ℕ) : Bool := + decide (z.1.length=z.2.length) && + (List.range z.1.length).all (fun i => listEntryEqual (z,i)) + +def listNatTestRealizer : Realizer listNatTest := + (composition (pair + (composition (pair (composition first listLength) (composition second listLength)) natEqual) + (composition (composition (pair identity equalityIndices) (mapWith listEntryEqualRealizer)) all)) + boolAnd).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,listNatTest]) + +lemma polynomial_listNatTest : PolynomialTime listNatTestRealizer := + polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_listLength) + (polynomial_composition polynomial_second polynomial_listLength)) polynomial_natEqual) + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_equalityIndices) + (polynomial_mapWith polynomial_listEntryEqual)) polynomial_all)) polynomial_boolAnd) + +lemma listNatTest_iff (z : List ℕ×List ℕ) : listNatTest z=true ↔ z.1=z.2 := by + rcases z with ⟨xs,ys⟩ + simp only [listNatTest,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true,List.mem_range, + listEntryEqual] + constructor + · rintro ⟨hlen,h⟩ + apply List.ext_getElem hlen + intro i hi hj + have he := h i hi + simpa only [List.getD_eq_getElem?_getD,List.getElem?_eq_getElem hi, + List.getElem?_eq_getElem hj,Option.getD_some,decide_eq_true_eq] using he + · rintro rfl + simp + +def listNatEqual : Realizer (fun z : List ℕ×List ℕ => decide (z.1=z.2)) := + listNatTestRealizer.congr (fun z => Bool.eq_iff_iff.mpr (by simp only [listNatTest_iff,decide_eq_true_eq])) + +theorem polynomial_listNatEqual : PolynomialTime listNatEqual := + polynomial_congr _ polynomial_listNatTest + +def profileCodeEqual : Realizer (fun z : (List ℕ×List ℕ)×(List ℕ×List ℕ) => + decide (z.1=z.2)) := pairEqual listNatEqual listNatEqual + +theorem polynomial_profileCodeEqual : PolynomialTime profileCodeEqual := + polynomial_pairEqual polynomial_listNatEqual polynomial_listNatEqual + +def profileCodeDedup : Realizer (List.dedup (α := List ℕ×List ℕ)) := dedup profileCodeEqual + +theorem polynomial_profileCodeDedup : PolynomialTime profileCodeDedup := + polynomial_dedup polynomial_profileCodeEqual + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileExchangeCandidates.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileExchangeCandidates.lean new file mode 100644 index 0000000000000000000000000000000000000000..801afd9d39fd944d4b0074c8d5583de400557955 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileExchangeCandidates.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections + +namespace OAI + +/-! # A polynomial binary program listing all coordinate exchanges -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def profileIndices : Realizer (fun xs : List ℕ => List.range xs.length) := + composition listLength range + +lemma polynomial_profileIndices : PolynomialTime profileIndices := by + apply polynomial_boundedRange polynomial_listLength X + intro xs + simpa only [Polynomial.eval_X] using list_length_le_weight xs + +def exchangeRow (z : List ℕ×ℕ) : List (List ℕ) := + (List.range z.1.length).map (fun j => listExchange (z.1,(z.2,j))) + +def exchangeRowRealizer : Realizer exchangeRow := by + let E : Realizer (fun z : (List ℕ×ℕ)×ℕ => listExchange (z.1.1,(z.1.2,z.2))) := + composition (pair (composition first first) (pair (composition first second) second)) + listExchangeRealizer + exact composition (pair identity (composition first profileIndices)) (mapWith E) + +lemma polynomial_exchangeRow : PolynomialTime exchangeRowRealizer := by + unfold exchangeRowRealizer + exact polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition polynomial_first polynomial_profileIndices)) + (polynomial_mapWith (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_listExchange)) + +def allExchanges (xs : List ℕ) : List (List ℕ) := + ((List.range xs.length).map (fun i => exchangeRow (xs,i))).flatten + +def allExchangesRealizer : Realizer allExchanges := + composition (composition (pair identity profileIndices) (mapWith exchangeRowRealizer)) flatten + +theorem polynomial_allExchanges : PolynomialTime allExchangesRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_profileIndices) + (polynomial_mapWith polynomial_exchangeRow)) polynomial_flatten + +lemma exchangeRow_length (z : List ℕ×ℕ) : (exchangeRow z).length=z.1.length := by + simp only [exchangeRow,List.length_map,List.length_range] + +theorem allExchanges_length (xs : List ℕ) : (allExchanges xs).length=xs.length^2 := by + simp only [allExchanges,List.length_flatten,List.map_map,Function.comp_def,exchangeRow_length] + simp [pow_two] + +/-- Every generated vector is an actual ordered-coordinate update, +and every such update occurs. Duplicate profiles can be removed later. -/ +theorem mem_allExchanges_ofFn {n : ℕ} (v : Fin n → ℕ) (xs : List ℕ) : + xs ∈ allExchanges (List.ofFn v) ↔ + ∃ i j : Fin n,xs=List.ofFn (IntegerWeightedTransport.exchangeTarget v i j) := by + simp only [allExchanges,List.mem_flatten,List.mem_map] + constructor + · rintro ⟨ys,⟨i,hi,rfl⟩,hxs⟩ + obtain ⟨j,hj,hxs⟩ := List.mem_map.mp hxs + have hi' : i z.1.1) := composition first first + let A : Realizer (fun z : ExchangeInput×ℕ => z.2) := second + let I : Realizer (fun z : ExchangeInput×ℕ => z.1.2.1) := + composition (composition first second) first + let J : Realizer (fun z : ExchangeInput×ℕ => z.1.2.2) := + composition (composition first second) second + let addOne := choose (composition (pair A I) natEqual) (constant 1) (constant 0) + let subOne := choose (composition (pair A J) natEqual) (constant 1) (constant 0) + exact (composition (pair (composition + (pair (composition (pair V A) (getDFast 0)) addOne) add) subOne) subtract).congr + (fun z => by simp only [Function.comp_apply,exchangeEntry,decide_eq_true_eq]) + +theorem polynomial_exchangeEntry : PolynomialTime exchangeEntryRealizer := by + have hV : PolynomialTime (composition + (first (A := ExchangeInput) (B := ℕ)) first) := + polynomial_composition polynomial_first polynomial_first + have hA : PolynomialTime (second (A := ExchangeInput) (B := ℕ)) := polynomial_second + have hI : PolynomialTime (composition + (composition (first (A := ExchangeInput) (B := ℕ)) second) first) := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first + have hJ : PolynomialTime (composition + (composition (first (A := ExchangeInput) (B := ℕ)) second) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second + have hi := polynomial_choose (polynomial_composition (polynomial_pair hA hI) polynomial_natEqual) + (polynomial_constant 1) (polynomial_constant 0) + have hj := polynomial_choose (polynomial_composition (polynomial_pair hA hJ) polynomial_natEqual) + (polynomial_constant 1) (polynomial_constant 0) + unfold exchangeEntryRealizer + exact polynomial_congr _ (polynomial_composition + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hV hA) (polynomial_getDFast 0)) hi) polynomial_add) hj) + polynomial_subtract) + +def listExchange (z : ExchangeInput) : List ℕ := + (List.range z.1.length).map (fun a => exchangeEntry (z,a)) + +def listExchangeRealizer : Realizer listExchange := + composition (pair identity (composition (composition first listLength) range)) + (mapWith exchangeEntryRealizer) + +/-- Its loop traverses the input profile once, even if the supplied +coordinate indices are much larger than its length. -/ +theorem polynomial_listExchange : PolynomialTime listExchangeRealizer := by + have hr : PolynomialTime (composition + (composition (first (A := List ℕ) (B := ℕ×ℕ)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simp only [Polynomial.eval_X] + exact (list_length_le_weight z.1).trans (by rw [weight_prod]; omega) + exact polynomial_composition (polynomial_pair polynomial_identity hr) + (polynomial_mapWith polynomial_exchangeEntry) + +lemma listExchange_length (z : ExchangeInput) : (listExchange z).length=z.1.length := by + simp only [listExchange,List.length_map,List.length_range] + +/-- The binary list program implements the exact coordinate update used +by the physical graph, with no bounded-integer overflow. -/ +theorem listExchange_ofFn {n : ℕ} (v : Fin n → ℕ) (i j : Fin n) : + listExchange (List.ofFn v,(i.val,j.val))= + List.ofFn (IntegerWeightedTransport.exchangeTarget v i j) := by + apply List.ext_getElem + · simp only [listExchange,List.length_map,List.length_range,List.length_ofFn] + · intro a ha _ + have han : a omega + +/-- Exactness holds for all input profiles; neither boundedness nor a +preexisting proof of a defect is needed to execute the inverse formula. -/ +theorem backwardViews_eq (B : I → J → ℕ) (v : SmallProfile small) (s t : I×J) : + backwardViews (viewList small e v false, + (List.ofFn (fun i => B (e i).val.1 (e i).val.2), + (cellIndex small e s,(cellIndex small e t,cellIndex small e (t.1,s.2)))))= + (viewList small e (inverseRepairProfile small B v s t) false, + viewList small e (inverseRepairProfile small B v s t) true) := by + let w : Fin n → ℕ := fun i => v (e i,false)+ + (if i.val=cellIndex small e t then 1 else 0)- + (if i.val=cellIndex small e (t.1,s.2) then 1 else 0) + have hw (i : Fin n) : w i=inverseRepairRow small v s t (e i).val.1 (e i).val.2 := by + change w i=(transferInt (smallView small v false) (t.1,s.2) t + (e i).val.1 (e i).val.2).toNat + have h := transfer_at_index small e (smallView small v false) (t.1,s.2) t i + have heta : (⟨((e i).val.1,(e i).val.2),(e i).property⟩ : Cells small)=e i := + Subtype.ext (Prod.eta (e i).val) + simpa only [w,smallView,(e i).property,dite_true,heta] using h.symm + have hq (i : Fin n) : + w i+(if i.val=cellIndex small e s then 1 else 0)- + (if i.val=cellIndex small e t then 1 else 0)= + (transferInt (inverseRepairRow small v s t) t s (e i).val.1 (e i).val.2).toNat := by + rw [hw] + exact (transfer_at_index small e (inverseRepairRow small v s t) t s i).symm + simp only [backwardViews,backwardRows,backwardColumns,viewList, + listExchange_ofFn_nat,listDifference_ofFn] + apply Prod.ext + · apply congrArg List.ofFn + funext i + exact hw i + · apply congrArg List.ofFn + funext i + exact congrArg (fun a => B (e i).val.1 (e i).val.2-a) (hq i) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntry.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntry.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6033e2c8babfc0d1aa18937faf0ad981065a5b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntry.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Machines.TransitionCacheRuntime +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxEnumeration + +namespace OAI + +/-! # Executable entries of the finite profile transition matrix -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev MatrixParameters := TransitionCacheParameters×List Bool +abbrev MatrixEntryInput := MatrixParameters×((List ℕ×List ℕ)×(List ℕ×List ℕ)) + +def matrixData (z : MatrixParameters) : ProfileCheckData := z.1.1.1.1 + +def matrixDataRealizer : Realizer matrixData := + composition (composition (composition first first) first) first + +lemma polynomial_matrixData : PolynomialTime matrixDataRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first + +def sourceData (z : MatrixEntryInput) : ProfileCheckData := + candidateData (matrixData z.1,z.2.1) + +def sourceDataRealizer : Realizer sourceData := + composition (pair (composition (f := fun z : MatrixEntryInput => z.1) (g := matrixData) first matrixDataRealizer) (composition second first)) + candidateDataRealizer + +lemma polynomial_sourceData : PolynomialTime sourceDataRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_matrixData) + (polynomial_composition polynomial_second polynomial_first)) polynomial_candidateData + +def targetData (z : MatrixEntryInput) : ProfileCheckData := + candidateData (matrixData z.1,z.2.2) + +def targetDataRealizer : Realizer targetData := + composition (pair (composition (f := fun z : MatrixEntryInput => z.1) (g := matrixData) first matrixDataRealizer) (composition second second)) + candidateDataRealizer + +lemma polynomial_targetData : PolynomialTime targetDataRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_matrixData) + (polynomial_composition polynomial_second polynomial_second)) polynomial_candidateData + +def entryCacheParameters (z : MatrixEntryInput) : TransitionCacheParameters := + (((sourceData z,z.1.1.1.1.2),z.1.1.1.2),z.1.1.2) + +def entryCacheParametersRealizer : Realizer entryCacheParameters := by + let params : Realizer (fun z : MatrixEntryInput => z.1.1) := composition first first + let resid : Realizer (fun z : MatrixEntryInput => z.1.1.1) := composition params first + let padding := composition (composition resid first) second + exact pair (pair (pair sourceDataRealizer padding) (composition resid second)) + (composition params second) + +lemma polynomial_entryCacheParameters : PolynomialTime entryCacheParametersRealizer := by + unfold entryCacheParametersRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair polynomial_sourceData + (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_first) polynomial_second)) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second)) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + +def entryQuery (z : MatrixEntryInput) : TransitionQuery := + ((prepareTransitionCache (entryCacheParameters z),z.2.2),z.1.2) + +def entryQueryRealizer : Realizer entryQuery := + pair (pair + (composition (f := entryCacheParameters) (g := prepareTransitionCache) + entryCacheParametersRealizer prepareTransitionCacheRealizer) + (composition second second)) (composition first second) + +def validMatrixEntry (z : MatrixEntryInput) : ℕ := transitionCount (entryQuery z) + +def validMatrixEntryRealizer : Realizer validMatrixEntry := + composition (f := entryQuery) (g := transitionCount) entryQueryRealizer transitionCountRealizer + +/-- The denominator includes the proposal word and its padded completion word. -/ +def matrixDenominator (z : MatrixParameters) : ℕ := + BinaryPowerPrograms.power (2,z.2.length+z.1.2) + +def matrixDenominatorRealizer : Realizer matrixDenominator := + composition (pair (constant 2) (composition (pair + (composition second listLength) (composition first second)) add)) BinaryPowerPrograms.powerRealizer + +def diagonalMatrixEntry (z : MatrixEntryInput) : ℕ := + if z.2.1=z.2.2 then matrixDenominator z.1 else 0 + +def diagonalMatrixEntryRealizer : Realizer diagonalMatrixEntry := + (choose (composition second profileCodeEqual) + (composition first matrixDenominatorRealizer) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq] + rfl) + +/-- Invalid source vectors are stationary. Invalid target vectors have +zero weight from every valid source. -/ +def matrixEntry (z : MatrixEntryInput) : ℕ := + if profileTest (sourceData z) then + if profileTest (targetData z) then validMatrixEntry z else 0 + else diagonalMatrixEntry z + +def matrixEntryRealizer : Realizer matrixEntry := + choose (composition sourceDataRealizer profileTestRealizer) + (choose (composition targetDataRealizer profileTestRealizer) + validMatrixEntryRealizer (constant 0)) diagonalMatrixEntryRealizer + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntryRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntryRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..504230ae8603bcd309df07f5b6eb222253e19953 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixEntryRuntime.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntry + +namespace OAI + +/-! # Finite-box work bound for the executable transition entries -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +attribute [local irreducible] prepareTransitionCache prepareTransitionCacheRealizer + entryCacheParameters entryCacheParametersRealizer transitionCount transitionCountRealizer + entryQueryRealizer + +def matrixEntryMeasure (z : MatrixEntryInput) : ℕ := + transitionCacheMeasure (entryCacheParameters z)+gridStateCount (z.1.2,2)+weight z + +private lemma input_le_measure (z : MatrixEntryInput) : weight z ≤ matrixEntryMeasure z := by + unfold matrixEntryMeasure + omega + +private lemma polynomial_work {B : Type} [Codec B] {f : MatrixEntryInput → B} + {F : Realizer f} (hF : PolynomialTime F) : WorkBound F matrixEntryMeasure := + work_of_polynomial hF X (fun z => by simpa using input_le_measure z) + +lemma work_entryCache : WorkBound + (composition entryCacheParametersRealizer prepareTransitionCacheRealizer) matrixEntryMeasure := by + apply work_composition (polynomial_work polynomial_entryCacheParameters) + work_prepareTransitionCache X + intro z + simp only [Polynomial.eval_X,matrixEntryMeasure] + omega + +lemma work_entryQuery : WorkBound entryQueryRealizer matrixEntryMeasure := by + have hi (z : MatrixEntryInput) : weight z ≤ X.eval (matrixEntryMeasure z) := by + simpa using input_le_measure z + have ht : WorkBound (composition (second (A := MatrixParameters)) second) + matrixEntryMeasure := polynomial_work + (polynomial_composition polynomial_second polynomial_second) + have hb : WorkBound (composition (first (B := (List ℕ×List ℕ)×(List ℕ×List ℕ))) second) + matrixEntryMeasure := polynomial_work + (polynomial_composition polynomial_first polynomial_second) + have hp := work_pair work_entryCache ht X hi + unfold entryQueryRealizer + exact work_pair hp hb X hi + +lemma work_validMatrixEntry : WorkBound validMatrixEntryRealizer matrixEntryMeasure := by + obtain ⟨p,hp⟩ := work_entryQuery + unfold validMatrixEntryRealizer + apply work_composition ⟨p,hp⟩ work_transitionCount (X+p) + intro z + have hw := hp z + simp only [Polynomial.eval_add,Polynomial.eval_X] + change gridStateCount (z.1.2,2)+weight (entryQuery z) ≤ _ + have hg : gridStateCount (z.1.2,2) ≤ matrixEntryMeasure z := by + unfold matrixEntryMeasure + omega + omega + +lemma work_matrixDenominator : WorkBound matrixDenominatorRealizer + (fun z : MatrixParameters => z.2.length+z.1.2+weight z) := by + have hi : WorkBound (pair (constant 2) (composition (pair + (composition (second (A := TransitionCacheParameters)) listLength) + (composition first second)) add)) + (fun z : MatrixParameters => z.2.length+z.1.2+weight z) := + work_of_polynomial (polynomial_pair (polynomial_constant 2) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_listLength) + (polynomial_composition polynomial_first polynomial_second)) polynomial_add)) X + (fun z => by simp only [Polynomial.eval_X]; omega) + unfold matrixDenominatorRealizer + apply work_composition hi BinaryPowerPrograms.work_power (X+9) + intro z + change z.2.length+z.1.2+weight (2:ℕ) ≤ (X+9).eval _ + have htwo : weight (2:ℕ) ≤ 9 := by simpa using weight_nat_numeric 2 + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat] + omega + +lemma work_entryDenominator : WorkBound + (composition (first (B := (List ℕ×List ℕ)×(List ℕ×List ℕ))) + matrixDenominatorRealizer) matrixEntryMeasure := by + apply work_composition (polynomial_work polynomial_first) work_matrixDenominator (2*X) + intro z + have hl := (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + have hf : z.1.1.2 ≤ transitionCacheMeasure (entryCacheParameters z) := by + unfold transitionCacheMeasure entryCacheParameters + omega + have hw := weight_fst z + simp only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,matrixEntryMeasure] + omega + +lemma work_diagonalMatrixEntry : WorkBound diagonalMatrixEntryRealizer matrixEntryMeasure := by + unfold diagonalMatrixEntryRealizer + apply work_congr + exact work_choose + (polynomial_work (polynomial_composition polynomial_second polynomial_profileCodeEqual)) + work_entryDenominator (polynomial_work (polynomial_constant 0)) + X (fun z => by simpa using input_le_measure z) + +lemma work_matrixEntry : WorkBound matrixEntryRealizer matrixEntryMeasure := by + unfold matrixEntryRealizer + apply work_choose + (polynomial_work (polynomial_composition polynomial_sourceData polynomial_profileTest)) _ + work_diagonalMatrixEntry X (fun z => by simpa using input_le_measure z) + exact work_choose + (polynomial_work (polynomial_composition polynomial_targetData polynomial_profileTest)) + work_validMatrixEntry (polynomial_work (polynomial_constant 0)) + X (fun z => by simpa using input_le_measure z) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5d6135d006faee29b3fe02e6f788c6a90cbb675 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixLaw.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixProgram + +namespace OAI + +/-! # Every entry of the computed profile matrix has its exact integer law -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical + +lemma push_count_not_range {A B : Type*} [Fintype A] [Fintype B] [DecidableEq B] + {Q : ℕ} (p : IntegerLaw A Q) (f : A → B) (b : B) (hb : ∀ a,f a≠b) : + (p.push f).count b=0 := by + change (∑ a,if f a=b then p.count a else 0)=0 + simp only [hb,ite_false,Finset.sum_const_zero] + +end ContingencyTables.IntegerLaw + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] stateCode stateCodeData listedStepCounts prepareTransitionCache + profileIndex profileAt ProfilePrograms.matrixEntry matrixInput IntegerLaw.push listedWalkCounts + +lemma boxCode_test_false (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (k : BoxIndex) (hk : profileAt r c e k=none) : + profileTest (candidateData (stateCodeData r c e z,boxCode k))=false := by + apply Bool.eq_false_iff.mpr + intro ht + obtain ⟨x,hx⟩ := (test_candidate_iff r c e htotal z _).mp ht + have hd : profileAt r c e k=some x := by + unfold profileAt + exact (decodeStateCode_eq_some_iff r c e _ x).mpr hx + rw [hk] at hd + cases hd + +lemma matrixDenominator_actual (z : PaperStates r c) (xs : List Bool) (hs : xs.length=s) : + matrixDenominator (matrixInput r c e b h z xs)=2^(s+f) := by + unfold matrixDenominator matrixInput + rw [BinaryPowerPrograms.power_eq,hs] + +lemma sourceData_input (z : PaperStates r c) (xs : List Bool) (u v : List ℕ×List ℕ) : + sourceData (matrixInput r c e b h z xs,(u,v))=candidateData (stateCodeData r c e z,u) := by + unfold sourceData matrixData matrixInput + rfl + +lemma targetData_input (z : PaperStates r c) (xs : List Bool) (u v : List ℕ×List ℕ) : + targetData (matrixInput r c e b h z xs,(u,v))=candidateData (stateCodeData r c e z,v) := by + unfold targetData matrixData matrixInput + rfl + +lemma matrixEntry_invalid_source (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (i j : BoxIndex) + (hi : profileAt r c e i=none) : + ProfilePrograms.matrixEntry (matrixInput r c e b h z xs,(boxCode i,boxCode j))= + if j=i then 2^(s+f) else 0 := by + have hp := boxCode_test_false r c e htotal z i hi + unfold ProfilePrograms.matrixEntry + rw [sourceData_input,hp] + simp only [Bool.false_eq_true,ite_false] + unfold diagonalMatrixEntry + rw [matrixDenominator_actual r c e b h z xs hs] + have hij : boxCode i=boxCode j ↔ i=j := + (boxCode_injective (m := m) (n := n) (q := q)).eq_iff + simp only [hij,eq_comm] + +lemma matrixEntry_invalid_target (htotal : ∑ i,r i=∑ j,c j) (z x : PaperStates r c) + (xs : List Bool) (j : BoxIndex) (hj : profileAt r c e j=none) : + ProfilePrograms.matrixEntry (matrixInput r c e b h z xs,(stateCode r c e x,boxCode j))=0 := by + have hx := (test_candidate_iff r c e htotal z (stateCode r c e x)).mpr ⟨x,rfl⟩ + have hj' := boxCode_test_false r c e htotal z j hj + unfold ProfilePrograms.matrixEntry + rw [sourceData_input,targetData_input,hx,hj'] + simp only [ite_true,Bool.false_eq_true,ite_false] + +lemma matrixEntry_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (i j : BoxIndex) : + ProfilePrograms.matrixEntry (matrixInput r c e b h z xs,(boxCode i,boxCode j))= + (profileBoxStep r c e hr hc b h hb i).count j := by + cases hi : profileAt r c e i with + | none => + rw [matrixEntry_invalid_source r c e b h htotal z xs hs i j hi] + unfold profileBoxStep + rw [hi] + rfl + | some x => + have hix : profileIndex r c e x=i := (profileAt_eq_some r c e i x).mp hi + have hcode : boxCode i=stateCode r c e x := by rw [←hix,boxCode_index] + rw [hcode] + unfold profileBoxStep + rw [hi] + simp only [Option.elim_some] + cases hj : profileAt r c e j with + | none => + rw [matrixEntry_invalid_target r c e b h htotal z x xs j hj] + symm + apply IntegerLaw.push_count_not_range + intro a hindex + rw [←hindex,profileAt_index] at hj + cases hj + | some y => + have hjy : profileIndex r c e y=j := (profileAt_eq_some r c e j y).mp hj + rw [←hjy,boxCode_index, + IntegerLaw.push_count_injective _ _ (profileIndex_injective r c e)] + exact matrixEntry_codes r c e hr hc b h hb htotal z x y xs hs + +lemma profileMatrix_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) : + profileMatrix (matrixInput r c e b h z xs)= + List.ofFn (fun j : BoxIndex => List.ofFn (fun i : BoxIndex => + (profileBoxStep r c e hr hc b h hb i).count j)) := by + have hv : profileBoxViews (matrixData (matrixInput r c e b h z xs))= + List.ofFn (boxCode (m := m) (n := n) (q := q)) := + by + unfold matrixData matrixInput + exact profileBoxViews_actual r c e z + unfold profileMatrix + rw [hv,List.map_ofFn] + apply congrArg List.ofFn + funext j + dsimp only [Function.comp_apply] + unfold matrixColumn + dsimp only [Prod.fst] + rw [hv,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact matrixEntry_actual r c e hr hc b h hb htotal z xs hs i j + +lemma profileMatrix_walk (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) : + IntegerMatrixPrograms.iterate (N,(profileMatrix (matrixInput r c e b h z xs), + List.ofFn (fun k : BoxIndex => if k=profileIndex r c e z then 1 else 0)))= + List.ofFn (fun k : BoxIndex => + ((listedWalkCounts r c e hr hc b h hb z N).push (profileIndex r c e)).count k) := by + rw [profileMatrix_actual r c e hr hc b h hb htotal z xs hs] + exact profileBox_iterate r c e hr hc b h hb z N + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..6acaa1c0f796e367a1e148315f6ba09a2c2c15bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixProgram.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntryRuntime +import OAI.Combinatorics.ContingencyTables.Transport.MeasuredMap + +namespace OAI + +/-! # Constructing the finite transition matrix by deterministic enumeration -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev MatrixColumnInput := MatrixParameters×(List ℕ×List ℕ) +abbrev MatrixColumnEntryInput := MatrixColumnInput×(List ℕ×List ℕ) + +def columnEntryInput (z : MatrixColumnEntryInput) : MatrixEntryInput := + (z.1.1,(z.2,z.1.2)) + +def columnEntryInputRealizer : Realizer columnEntryInput := + pair (composition first first) (pair second (composition first second)) + +lemma polynomial_columnEntryInput : PolynomialTime columnEntryInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_second)) + +def columnEntry (z : MatrixColumnEntryInput) : ℕ := matrixEntry (columnEntryInput z) + +def columnEntryRealizer : Realizer columnEntry := + composition (f := columnEntryInput) (g := matrixEntry) columnEntryInputRealizer matrixEntryRealizer + +def columnEntryMeasure (z : MatrixColumnEntryInput) : ℕ := + matrixEntryMeasure (columnEntryInput z) + +lemma work_columnEntry : WorkBound columnEntryRealizer columnEntryMeasure := by + unfold columnEntryRealizer + apply work_composition (work_of_polynomial polynomial_columnEntryInput X _) work_matrixEntry X + · intro z + simp only [columnEntryMeasure,Polynomial.eval_X] + exact le_rfl + · intro z + have hz : weight z=weight (columnEntryInput z) := by + rcases z with ⟨⟨p,t⟩,s⟩ + simp only [columnEntryInput,weight_prod] + omega + simp only [Polynomial.eval_X,columnEntryMeasure,matrixEntryMeasure] + omega + +def matrixColumn (z : MatrixColumnInput) : List ℕ := + (profileBoxViews (matrixData z.1)).map (fun source => columnEntry (z,source)) + +def matrixColumnRealizer : Realizer matrixColumn := + composition (f := fun z : MatrixColumnInput => (z,profileBoxViews (matrixData z.1))) + (g := fun z : MatrixColumnInput×List (List ℕ×List ℕ) => + z.2.map (fun source => columnEntry (z.1,source))) + (pair identity (composition + (f := fun z : MatrixColumnInput => matrixData z.1) (g := profileBoxViews) + (composition (f := fun z : MatrixColumnInput => z.1) (g := matrixData) + first matrixDataRealizer) profileBoxViewsRealizer)) (mapWith columnEntryRealizer) + +def matrixColumnMeasure (z : MatrixColumnInput) : ℕ := + gridStateCount (profileEnumerationData (matrixData z.1))+ + MeasuredMap.listMeasure columnEntryMeasure (z,profileBoxViews (matrixData z.1)) + +lemma work_matrixColumn : WorkBound matrixColumnRealizer matrixColumnMeasure := by + have hin (z : MatrixColumnInput) : weight z ≤ matrixColumnMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := weight_fst (z,profileBoxViews (matrixData z.1)) + simp only [matrixColumnMeasure,MeasuredMap.listMeasure] + omega + have hd : PolynomialTime (composition (first (B := List ℕ×List ℕ)) matrixDataRealizer) := + polynomial_composition polynomial_first polynomial_matrixData + have hv : WorkBound (composition (composition first matrixDataRealizer) profileBoxViewsRealizer) + matrixColumnMeasure := by + apply work_composition (work_of_polynomial hd X (fun z => by simpa using hin z)) + work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z.1) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans + ((weight_fst _).trans (weight_fst z)))) + simp only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + matrixColumnMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := weight_fst (z,profileBoxViews (matrixData z.1)) + omega + unfold matrixColumnRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_columnEntry) X + intro z + simp only [Polynomial.eval_X,matrixColumnMeasure,Function.comp_apply,id_eq] + omega + +def profileMatrix (z : MatrixParameters) : List (List ℕ) := + (profileBoxViews (matrixData z)).map (fun target => matrixColumn (z,target)) + +def profileMatrixRealizer : Realizer profileMatrix := + composition (f := fun z : MatrixParameters => (z,profileBoxViews (matrixData z))) + (g := fun z : MatrixParameters×List (List ℕ×List ℕ) => + z.2.map (fun target => matrixColumn (z.1,target))) + (pair identity (composition (f := matrixData) (g := profileBoxViews) + matrixDataRealizer profileBoxViewsRealizer)) (mapWith matrixColumnRealizer) + +def profileMatrixMeasure (z : MatrixParameters) : ℕ := + gridStateCount (profileEnumerationData (matrixData z))+ + MeasuredMap.listMeasure matrixColumnMeasure (z,profileBoxViews (matrixData z)) + +lemma work_profileMatrix : WorkBound profileMatrixRealizer profileMatrixMeasure := by + have hin (z : MatrixParameters) : weight z ≤ profileMatrixMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z)) := weight_fst (z,profileBoxViews (matrixData z)) + simp only [profileMatrixMeasure,MeasuredMap.listMeasure] + omega + have hv : WorkBound (composition matrixDataRealizer profileBoxViewsRealizer) + profileMatrixMeasure := by + apply work_composition (work_of_polynomial polynomial_matrixData X + (fun z => by simpa using hin z)) work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans (weight_fst z))) + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + profileMatrixMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z)) := weight_fst (z,profileBoxViews (matrixData z)) + omega + unfold profileMatrixRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_matrixColumn) X + intro z + simp only [Polynomial.eval_X,profileMatrixMeasure,Function.comp_apply,id_eq] + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e3502d5af8d982db31e0ddc61a6670c1005a58f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileMatrixSemantics.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntry +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCountSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxLaw + +namespace OAI + +/-! # The computed matrix is the actual profile transition law -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] stateCode stateCodeData prepareTransitionCache transitionCount + ProfilePrograms.matrixEntry validMatrixEntry listedStepCounts listedCompletionCounts + +def matrixInput (x : PaperStates r c) (xs : List Bool) : MatrixParameters := + ((((stateCodeData r c e x,d^12),(d,h)),f),xs) + +def boxCode (k : BoxIndex) : List ℕ×List ℕ := + splitViews (q,List.ofFn + (fun i => ((finFunctionFinEquiv.symm k : ProfileBox (m := m) (n := n) (q := q)) i).val)) + +lemma boxCode_injective : Function.Injective (boxCode (m := m) (n := n) (q := q)) := by + intro k l hkl + have hv := congrArg flattenViews hkl + simp only [boxCode,splitViews,flattenViews,List.take_append_drop] at hv + have he : (finFunctionFinEquiv.symm k : ProfileBox (m := m) (n := n) (q := q))= + finFunctionFinEquiv.symm l := by + funext i + exact Fin.ext (congrFun (List.ofFn_injective hv) i) + exact finFunctionFinEquiv.symm.injective he + +lemma boxCode_index (x : PaperStates r c) : + boxCode (profileIndex r c e x)=stateCode r c e x := by + exact ((decodeStateCode_eq_some_iff r c e _ x).mp (profileAt_index r c e x)).symm + +lemma candidate_stateCodeData (x y : PaperStates r c) : + candidateData (stateCodeData r c e x,stateCode r c e y)=stateCodeData r c e y := by + unfold candidateData stateCodeData codeCheckData + rfl + +lemma test_candidate_iff (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) + (v : List ℕ×List ℕ) : + profileTest (candidateData (stateCodeData r c e x,v))=true ↔ + ∃ y : PaperStates r c,stateCode r c e y=v := by + simpa only [candidateData,stateCodeData,codeCheckData,stateCode] using + (profileTest_code_iff r c htotal e v) + +lemma matrixEntry_codes (htotal : ∑ i,r i=∑ j,c j) (z x y : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) : + ProfilePrograms.matrixEntry (matrixInput r c e b h z xs,(stateCode r c e x,stateCode r c e y))= + (listedStepCounts r c e hr hc b h hb x).count y := by + have hx : profileTest (candidateData (stateCodeData r c e z,stateCode r c e x))=true := + (test_candidate_iff r c e htotal z _).mpr ⟨x,rfl⟩ + have hy : profileTest (candidateData (stateCodeData r c e z,stateCode r c e y))=true := + (test_candidate_iff r c e htotal z _).mpr ⟨y,rfl⟩ + unfold ProfilePrograms.matrixEntry sourceData targetData matrixData matrixInput + rw [hx,hy] + simp only [ite_true] + unfold validMatrixEntry entryQuery entryCacheParameters + dsimp only [sourceData,matrixData] + rw [candidate_stateCodeData] + exact transitionCount_actual r c e hr hc b h hb htotal x y xs hs + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ffec6f7186a08e6f38819632c7e0260b4757c94 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicMachine.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordOutput +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicMachine + +namespace OAI + +/-! # Physical execution of the computed public profile sampler -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.LiteralCodec Turing + +lemma printMatrix_alphabet (rows : DensePrograms.MatrixCode) : + ∀ a∈GreedyFeasibleTable.printMatrix rows,a≠6 ∧ a≠7 := by + intro a ha + obtain ⟨row,_,ha⟩ := List.mem_flatMap.mp ha + obtain ⟨n,_,ha⟩ := List.mem_flatMap.mp ha + simp only [encodeNat,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide + +lemma publicSampling_alphabet (as : List Symbol) (bits : List Bool) : + ∀ a∈publicSampling (as,bits),a≠6 ∧ a≠7 := printMatrix_alphabet _ + +lemma samplingInput_nonzero {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : + ∀ a∈Algorithms.encodeSamplingInput r c k,a≠0 := by + intro a ha + rcases List.mem_append.mp ha with hm|hk + · exact GreedyFeasibleTable.encodeMargins_nonzero r c a hm + · simp only [encodeNat,List.mem_append,List.mem_map,List.mem_singleton] at hk + rcases hk with ⟨b,_,rfl⟩|rfl + · cases b <;> decide + · decide + +noncomputable def samplingMachine : RandomMachine := + FiniteWordExecution.machine publicWordCountRealizer publicSamplingRealizer + +noncomputable def samplingMachineTime (as : List Symbol) : ℕ := + FiniteWordExecution.machineTime publicWordCountRealizer publicSamplingRealizer as + +/-- A single fixed transition table implements the public program, +with cost controlled by its computed word schedule. -/ +theorem samplingMachineTime_polynomial : + ∃ p : Polynomial ℕ,∀ as,samplingMachineTime as≤p.eval + (FiniteWordExecution.wordMeasure publicWordCount as) := + FiniteWordExecution.machineTime_polynomial polynomial_publicWordCount polynomial_publicSampling + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open MatchingFPRAS MatchingFPRAS.PhysicalStream Turing +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c + +/-- Every actual machine execution in the nonempty large-rectangle branch +halts and outputs a feasible original table. -/ +theorem samplingMachine_large_outputs + (hr : 0<(largeIndices (d^20,List.ofFn r)).length) + (hc : 0<(largeIndices (d^20,List.ofFn c)).length) + (htotal : (∑ i,r i)=∑ j,c j) (k t : ℕ) + (ht : samplingMachineTime (Algorithms.encodeSamplingInput r c k)≤t) : + ∀ bits : Bits t,∃ X : Table r c, + Algorithms.OutputsTable samplingMachine (Algorithms.encodeSamplingInput r c k) bits X.val := by + let as := Algorithms.encodeSamplingInput r c k + let P : Tape Symbol → Prop := fun tape => ∃ X : Table r c, + tape.right₀=ListBlank.mk (Algorithms.encodeMatrix X.val) + have hf : ∀ bits : Bits (publicWordCount as),P (Tape.mk₁ (publicSampling (as,List.ofFn bits))) := by + dsimp only [as] + rw [publicWordCount_spec] + intro bits + refine ⟨listedOuterDraw r c (computedCellEquiv r c) hr hc b (outerAccuracy d b k) + (smallBinaryLength_parameters r c).1 (tableState r c (GreedyFeasibleTable.table r c htotal)) + (outerSteps d b k) (outerTrials d k) (GreedyFeasibleTable.table r c htotal) bits,?_⟩ + rw [publicSampling_spec r c hr hc htotal] + simp only [Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + have hP := FiniteWordExecution.machine_all publicWordCountRealizer publicSamplingRealizer as + (samplingInput_nonzero r c k) (publicSampling_alphabet as) P hf t ht + have hhalt := (FiniteWordExecution.machine_law publicWordCountRealizer publicSamplingRealizer as + (samplingInput_nonzero r c k) (publicSampling_alphabet as) t ht).1 + intro bits + obtain ⟨X,hX⟩ := hP bits + exact ⟨X,hhalt bits,hX⟩ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa4fe5ab06e2d5a41b8d19ee7f008df0a9795f04 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicProgram.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileSamplingProgram + +namespace OAI + +/-! # The sampler's public binary parser and matrix printer -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralParse MatchingFPRAS.LiteralCodec +open DensePrograms + +/-- Safely locate the precision field after the two margin vectors. -/ +def samplingPrecision (ns : List ℕ) : ℕ := + (ns.drop (2+ns.headD 0+ns.tail.headD 0)).headD 0 + +def samplingPrecisionRealizer : Realizer samplingPrecision := by + let M : Realizer (fun ns : List ℕ => ns.headD 0) := head 0 + let N : Realizer (fun ns : List ℕ => ns.tail.headD 0) := composition tail (head 0) + let offset : Realizer (fun ns : List ℕ => 2+ns.headD 0+ns.tail.headD 0) := + composition (pair (composition (pair (constant 2) M) add) N) add + exact composition (composition (pair identity offset) dropFast) (head 0) + +theorem polynomial_samplingPrecision : PolynomialTime samplingPrecisionRealizer := by + unfold samplingPrecisionRealizer + exact polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) (polynomial_head 0)) + polynomial_add) + (polynomial_composition polynomial_tail (polynomial_head 0))) polynomial_add)) + polynomial_dropFast) (polynomial_head 0) + +def samplingInput (ns : List ℕ) : SamplingParameters := + (GreedyFeasibleTable.marginLists ns,samplingPrecision ns) + +def samplingInputRealizer : Realizer samplingInput := + pair GreedyFeasibleTable.marginListsRealizer samplingPrecisionRealizer + +theorem polynomial_samplingInput : PolynomialTime samplingInputRealizer := + polynomial_pair GreedyFeasibleTable.polynomial_marginLists polynomial_samplingPrecision + +def parsedSampling (as : List MatchingFPRAS.Symbol) : SamplingParameters := samplingInput (parse as) +def parsedSamplingRealizer : Realizer parsedSampling := composition (f := parse) (g := samplingInput) parseRealizer samplingInputRealizer + +theorem polynomial_parsedSampling : PolynomialTime parsedSamplingRealizer := + polynomial_composition polynomial_parse polynomial_samplingInput + +def publicWordCount (as : List MatchingFPRAS.Symbol) : ℕ := parameterWordCount (parsedSampling as) +def publicWordCountRealizer : Realizer publicWordCount := + composition (f := parsedSampling) (g := parameterWordCount) parsedSamplingRealizer parameterWordCountRealizer + +theorem polynomial_publicWordCount : PolynomialTime publicWordCountRealizer := + polynomial_composition polynomial_parsedSampling polynomial_parameterWordCount + +def publicSampling (z : List MatchingFPRAS.Symbol×List Bool) : List MatchingFPRAS.Symbol := + GreedyFeasibleTable.printMatrix (samplingMatrix (parsedSampling z.1,z.2)) + +def publicSamplingRealizer : Realizer publicSampling := + composition + (f := fun z : List MatchingFPRAS.Symbol×List Bool => samplingMatrix (parsedSampling z.1,z.2)) + (g := GreedyFeasibleTable.printMatrix) + (composition (f := fun z : List MatchingFPRAS.Symbol×List Bool => (parsedSampling z.1,z.2)) + (g := samplingMatrix) (pair (composition + (f := fun z : List MatchingFPRAS.Symbol×List Bool => z.1) (g := parsedSampling) + first parsedSamplingRealizer) second) samplingMatrixRealizer) GreedyFeasibleTable.printMatrixRealizer + +theorem polynomial_publicSampling : PolynomialTime publicSamplingRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_parsedSampling) polynomial_second) + polynomial_samplingMatrix) GreedyFeasibleTable.polynomial_printMatrix + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..de950a76778003ad0faa7e863e428a6211c0725b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfilePublicSemantics.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileScheduleSemantics + +namespace OAI + +/-! # Exact public input/output semantics of the profile sampler -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.LiteralParse MatchingFPRAS.LiteralCodec + +lemma samplingPrecision_spec (m n : ℕ) (rs cs : List ℕ) (k : ℕ) (tail : List ℕ) + (hr : rs.length=m) (hc : cs.length=n) : + samplingPrecision (m::n::(rs++cs++k::tail))=k := by + change ((m::n::(rs++cs++k::tail)).drop (2+m+n)).headD 0=k + have hlen : 2+m+n=(m::n::(rs++cs)).length := by + simp only [List.length_cons,List.length_append,hr,hc] + omega + rw [hlen] + change (((m::n::(rs++cs))++k::tail).drop (m::n::(rs++cs)).length).headD 0=k + rw [List.drop_left] + rfl + +lemma samplingInput_spec (m n : ℕ) (rs cs : List ℕ) (k : ℕ) + (hr : rs.length=m) (hc : cs.length=n) : + samplingInput (m::n::(rs++cs++[k]))=((rs,cs),k) := by + apply Prod.ext + · exact GreedyFeasibleTable.marginLists_spec m n rs cs [k] hr hc + · exact samplingPrecision_spec m n rs cs k [] hr hc + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open MatchingFPRAS.LiteralParse MatchingFPRAS.LiteralCodec +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c + +lemma parsedSampling_spec (k : ℕ) : + parsedSampling (Algorithms.encodeSamplingInput r c k)=((List.ofFn r,List.ofFn c),k) := by + unfold parsedSampling Algorithms.encodeSamplingInput + rw [GreedyFeasibleTable.encodeMargins_natWords] + have he : MatchingFPRAS.encodeNat k=([k].flatMap MatchingFPRAS.encodeNat) := by + simp only [List.flatMap_cons,List.flatMap_nil,List.append_nil] + rw [he,←List.flatMap_append,GreedyFeasibleTable.parse_natWords] + simp only [List.cons_append,List.append_assoc] + simpa only [List.append_assoc] using + samplingInput_spec m n (List.ofFn r) (List.ofFn c) k List.length_ofFn List.length_ofFn + +lemma publicWordCount_spec (k : ℕ) : + publicWordCount (Algorithms.encodeSamplingInput r c k)=finiteSamplerBits r c k := by + rw [publicWordCount,parsedSampling_spec,parameterWordCount_ofFn] + +/-- Each concrete public word prints the matrix of the proved finite draw. -/ +theorem publicSampling_spec + (hr : 0<(largeIndices (d^20,List.ofFn r)).length) + (hc : 0<(largeIndices (d^20,List.ofFn c)).length) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) + (bits : Fin (finiteSamplerBits r c k) → Bool) : + publicSampling (Algorithms.encodeSamplingInput r c k,List.ofFn bits)= + Algorithms.encodeMatrix (listedOuterDraw r c (computedCellEquiv r c) hr hc b + (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 + (tableState r c (GreedyFeasibleTable.table r c htotal)) + (outerSteps d b k) (outerTrials d k) (GreedyFeasibleTable.table r c htotal) bits).val := by + rw [publicSampling,parsedSampling_spec,samplingMatrix_code r c hr hc htotal] + exact GreedyFeasibleTable.printMatrix_ofFn _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRepairProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRepairProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a555cafd3917bde562b839ed9f5d5040490458eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRepairProgram.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileRepair + +namespace OAI + +/-! # A polynomial binary program for the literal small-profile repair -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def differenceEntry (z : (List ℕ×List ℕ)×ℕ) : ℕ := + z.1.1.getD z.2 0-z.1.2.getD z.2 0 + +def differenceEntryRealizer : Realizer differenceEntry := + composition (pair + (composition (pair (composition first first) second) (getDFast 0)) + (composition (pair (composition first second) second) (getDFast 0))) subtract + +lemma polynomial_differenceEntry : PolynomialTime differenceEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast 0))) polynomial_subtract + +/-- Preserve the second list's length, including malformed inputs. -/ +def listDifference (z : List ℕ×List ℕ) : List ℕ := + (List.range z.2.length).map (fun i => differenceEntry (z,i)) + +def listDifferenceRealizer : Realizer listDifference := + composition (pair identity (composition (composition second listLength) range)) + (mapWith differenceEntryRealizer) + +lemma polynomial_listDifference : PolynomialTime listDifferenceRealizer := by + have hr : PolynomialTime (composition + (composition (second (A := List ℕ) (B := List ℕ)) listLength) range) := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_listLength) X + intro z + simp only [Polynomial.eval_X] + exact (list_length_le_weight z.2).trans (by rw [weight_prod]; omega) + exact polynomial_composition (polynomial_pair polynomial_identity hr) + (polynomial_mapWith polynomial_differenceEntry) + +lemma listDifference_ofFn {n : ℕ} (b v : Fin n → ℕ) : + listDifference (List.ofFn b,List.ofFn v)=List.ofFn (fun i => b i-v i) := by + apply List.ext_getElem + · simp only [listDifference,List.length_map,List.length_range,List.length_ofFn] + · intro a ha _ + have han : a v a+(if a.val=i then 1 else 0)-(if a.val=j then 1 else 0)) := by + apply List.ext_getElem + · simp only [listExchange,List.length_map,List.length_range,List.length_ofFn] + · intro a ha _ + have han : a + listExchange (z.1,(z.2.2.2,z.2.2.1))) := + composition (pair first (pair + (composition (composition second second) second) + (composition (composition second second) first))) listExchangeRealizer + +lemma polynomial_repairRows : PolynomialTime repairRowsRealizer := + polynomial_composition (polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_first))) + polynomial_listExchange + +def repairedViewsRealizer : Realizer repairedViews := + pair repairRowsRealizer (composition + (pair (composition second first) repairRowsRealizer) listDifferenceRealizer) + +theorem polynomial_repairedViews : PolynomialTime repairedViewsRealizer := + polynomial_pair polynomial_repairRows (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_repairRows) + polynomial_listDifference) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms + +noncomputable section +universe u +variable {I J : Type u} [LinearOrder I] [LinearOrder J] +variable (small : I → J → Bool) {n : ℕ} (e : Fin n ≃ Cells small) + +/-- An absent large cell receives the out-of-range code `n`. -/ +def cellIndex (t : I×J) : ℕ := + if h : small t.1 t.2=true then (e.symm ⟨t,h⟩).val else n + +omit [LinearOrder I] [LinearOrder J] in +lemma cellIndex_eq (i : Fin n) (t : I×J) : + i.val=cellIndex small e t ↔ (e i).val=t := by + unfold cellIndex + split_ifs with ht + · constructor + · intro h + have hi : i=e.symm ⟨t,ht⟩ := Fin.ext h + rw [hi,Equiv.apply_symm_apply] + · intro h + have he : e i=⟨t,ht⟩ := Subtype.ext h + have hi := congrArg e.symm he + simpa only [Equiv.symm_apply_apply] using congrArg Fin.val hi + · constructor + · intro h + exact False.elim (Nat.ne_of_lt i.isLt h) + · intro h + exact False.elim (ht (h ▸ (e i).property)) + +def viewList (v : SmallProfile small) (b : Bool) : List ℕ := + List.ofFn (fun i => v (e i,b)) + +private lemma indexed_transfer (v : SmallProfile small) (s t : I×J) (i : Fin n) : + (transferInt (smallView small v false) s t (e i).val.1 (e i).val.2).toNat= + v (e i,false)+(if i.val=cellIndex small e t then 1 else 0)- + (if i.val=cellIndex small e s then 1 else 0) := by + have heta : (⟨((e i).val.1,(e i).val.2),(e i).property⟩ : Cells small)=e i := + Subtype.ext (Prod.eta (e i).val) + simp only [cellIndex_eq] + simp only [Prod.ext_iff,transferInt,smallView,(e i).property,dite_true,heta] + split_ifs <;> omega + +/-- The executable row transfer and complement produce exactly the +graph repair, including a large crossing cell outside the stored list. -/ +theorem repairedViews_eq (B : I → J → ℕ) (v : SmallProfile small) (s t : I×J) : + repairedViews (viewList small e v false, + (List.ofFn (fun i => B (e i).val.1 (e i).val.2), + (cellIndex small e t,cellIndex small e (t.1,s.2))))= + (viewList small e (repairedProfile small B v s t) false, + viewList small e (repairedProfile small B v s t) true) := by + let w : Fin n → ℕ := fun i => v (e i,false)+ + (if i.val=cellIndex small e (t.1,s.2) then 1 else 0)- + (if i.val=cellIndex small e t then 1 else 0) + have hw (i : Fin n) : w i=repairMatrix (smallView small v false) s t (e i).val.1 (e i).val.2 := + (indexed_transfer small e v t (t.1,s.2) i).symm + simp only [repairedViews,viewList,listExchange_ofFn_nat,listDifference_ofFn] + apply Prod.ext + · apply congrArg List.ofFn + funext i + exact hw i + · apply congrArg List.ofFn + funext i + exact congrArg (fun a => B (e i).val.1 (e i).val.2-a) (hw i) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a68c8beb269e6baaea2044c1b74bc31e7c1ab4b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetryProgram.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileWordProgram +import OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram + +namespace OAI + +/-! # A polynomial retry loop for the complete binary outer trial -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +abbrev ProfileRetryParameters := (ProfileConfiguration×ProfileWordSchedule)×MatrixCode +abbrev ProfileRetryData := ProfileRetryParameters×List Bool + +def profileTrialWidth (z : ProfileRetryData) : ℕ := + z.1.1.2.1.1*(z.1.1.2.1.2+z.1.1.2.2)+z.1.1.2.2 + +def profileRetryWordInput (z : ProfileRetryData) : ProfileWordInput := (z.1.1.2,z.2) +def profileRetryWordInputRealizer : Realizer profileRetryWordInput := + pair (composition (composition first first) second) second + +theorem polynomial_profileRetryWordInput : PolynomialTime profileRetryWordInputRealizer := + polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second + +def profileTrialWidthRealizer : Realizer profileTrialWidth := + composition (pair (composition profileRetryWordInputRealizer profileWalkWidthRealizer) + (composition (composition (composition first first) second) second)) add + +theorem polynomial_profileTrialWidth : PolynomialTime profileTrialWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_profileRetryWordInput polynomial_profileWalkWidth) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second)) + polynomial_add + +def profileRetryWords (z : ProfileRetryData) : List (List Bool) := + wordChunks (profileTrialWidth z,z.2) +def profileRetryWordsRealizer : Realizer profileRetryWords := + composition (pair profileTrialWidthRealizer second) wordChunksRealizer + +theorem polynomial_profileRetryWords : PolynomialTime profileRetryWordsRealizer := + polynomial_composition (polynomial_pair polynomial_profileTrialWidth polynomial_second) + polynomial_wordChunks + +def profileRetry (z : ProfileRetryData) : MatrixCode := + FirstSuccessProgram.retry packedProfileTrial (z.1,profileRetryWords z) +def profileRetryRealizer : Realizer profileRetry := + composition (pair first profileRetryWordsRealizer) + (FirstSuccessProgram.retryRealizer packedProfileTrialRealizer) + +theorem polynomial_profileRetry : PolynomialTime profileRetryRealizer := + polynomial_composition (polynomial_pair polynomial_first polynomial_profileRetryWords) + (FirstSuccessProgram.polynomial_retry polynomial_packedProfileTrial) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetrySemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetrySemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..14e081030b7921c4d485f898d6f4b211cfacb377 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRetrySemantics.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRetryProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialSemantics + +namespace OAI + +/-! # The executable retry program realizes the proved outer distribution -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres CompletionCounts +open FirstSuccess FairBits SmallContextCoordinates FirstPaperPhysicalMarginal +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +theorem profileRetry_code (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) + (steps attempts : ℕ) (fallback : Table r c) + (bits : Fin (attempts*(steps*(s+f)+f)) → Bool) : + profileRetry (((encodedConfiguration r c e h x x,((steps,s),f)),matrixCode fallback.val), + List.ofFn bits)= + matrixCode (listedOuterDraw r c e hr hc b h hb x steps attempts fallback bits).val := by + have hf : 0 + packedProfileTrial ((encodedConfiguration r c e h x x,((steps,s),f)),List.ofFn word))= + (fun word => (stateTrial r c (listedJointDraw r c e hr hc b h hb x steps word)).map + (fun T => matrixCode T.val)) := by + funext word + exact packedProfileTrial_code r c e hr hc b h hb htotal x steps word + rw [he,FirstSuccessProgram.wordRetry_map] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRuntimeBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRuntimeBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d68b27a070690cb74d070d558db065e31ba263e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileRuntimeBound.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicMachine +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInputWordBudget +import OAI.Combinatorics.ContingencyTables.Machines.PublicInputLength + +namespace OAI + +/-! # A uniform public polynomial bound for the physical sampler -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralCodec Polynomial +open scoped BigOperators + +lemma polynomial_scaled_power (p : Polynomial ℕ) (A x b : ℕ) (hx : 1≤x) : + p.eval (A*x^b)≤p.eval A*x^(b*p.natDegree) := by + rw [p.eval_eq_sum_range,p.eval_eq_sum_range,Finset.sum_mul] + apply Finset.sum_le_sum + intro i hi + have hi' : i≤p.natDegree := Nat.le_of_lt_succ (Finset.mem_range.mp hi) + rw [mul_pow,←pow_mul] + calc + p.coeff i*(A^i*x^(b*i))=(p.coeff i*A^i)*x^(b*i) := by ring + _ ≤ (p.coeff i*A^i)*x^(b*p.natDegree) := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hx (Nat.mul_le_mul_left b hi')) + _ = _ := by ring + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralCodec +open Algorithms Polynomial +open scoped BigOperators Classical + +noncomputable section + +private lemma wordMeasure_from_bounds (L W S A : ℕ) + (hL : L≤5*S^2) (hW : W≤A*S^1288) (hS : 1≤S) : + 18*L+1+W≤(A+91)*S^1288 := by + have hexp : (2:ℕ)≤1288 := by decide + have hpow : S^2≤S^1288 := pow_le_pow_right₀ hS hexp + have hone : 1≤S^1288 := one_le_pow₀ hS + calc + 18*L+1+W ≤ 18*(5*S^2)+S^1288+A*S^1288 := + Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ hL) hone) hW + _ ≤ 18*(5*S^1288)+S^1288+A*S^1288 := by gcongr + _ = (A+91)*S^1288 := by + rw [Nat.add_mul] + omega + +lemma public_wordMeasure_bound {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) : + FiniteWordExecution.wordMeasure publicWordCount (encodeSamplingInput r c k)≤ + (344^644+91)*(samplingSize n r k)^1288 := by + have hl := encodeSamplingInput_length r c htotal k + have hw := sampling_word_budget_polynomial r c k + have hS : 1 ≤ samplingSize n r k := by unfold samplingSize; omega + unfold FiniteWordExecution.wordMeasure + rw [weight_word,publicWordCount_spec] + change 18*(encodeSamplingInput r c k).length+1+finiteSamplerBits r c k≤_ + exact wordMeasure_from_bounds _ _ _ _ hl hw hS + +/-- The explicit binary word count and physical compiler yield one +polynomial bound in the manuscript's public input parameters. -/ +theorem samplingMachineTime_public_bound : + ∃ C d : ℕ,0 z.1) (g := initialCheck) first initialCheckRealizer) + (composition (f := fun z : SamplingParameters => z.1) (g := marginPadding) first marginPaddingRealizer)) + (pair parameterDimensionRealizer parameterAccuracyRealizer)) + (composition (f := fun z : SamplingParameters => z.1) (g := initialViews) first initialViewsRealizer) + +theorem polynomial_initialConfiguration : PolynomialTime initialConfigurationRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_initialCheck) + (polynomial_composition polynomial_first polynomial_marginPadding)) + (polynomial_pair polynomial_parameterDimension polynomial_parameterAccuracy)) + (polynomial_composition polynomial_first polynomial_initialViews) + +def samplingSchedule (z : SamplingParameters) : ProfileWordSchedule := + ((parameterSteps z,parameterProposalWidth z),parameterCompletionWidth z) + +def samplingScheduleRealizer : Realizer samplingSchedule := + pair (pair parameterStepsRealizer parameterProposalWidthRealizer) parameterCompletionWidthRealizer + +theorem polynomial_samplingSchedule : PolynomialTime samplingScheduleRealizer := + polynomial_pair (polynomial_pair polynomial_parameterSteps polynomial_parameterProposalWidth) + polynomial_parameterCompletionWidth + +def samplingRetryParameters (z : SamplingParameters) : ProfileRetryParameters := + ((initialConfiguration z,samplingSchedule z),GreedyFeasibleTable.listMatrix z.1.1 z.1.2) + +def samplingRetryParametersRealizer : Realizer samplingRetryParameters := + pair (pair initialConfigurationRealizer samplingScheduleRealizer) + (composition (f := fun z : SamplingParameters => z.1) (g := fun z => GreedyFeasibleTable.listMatrix z.1 z.2) first GreedyFeasibleTable.tableRealizer) + +theorem polynomial_samplingRetryParameters : PolynomialTime samplingRetryParametersRealizer := + polynomial_pair (polynomial_pair polynomial_initialConfiguration polynomial_samplingSchedule) + (polynomial_composition polynomial_first GreedyFeasibleTable.polynomial_table) + +def samplingMatrix (z : SamplingParameters×List Bool) : MatrixCode := + profileRetry (samplingRetryParameters z.1,z.2) + +def samplingMatrixRealizer : Realizer samplingMatrix := + composition (f := fun z : SamplingParameters×List Bool => (samplingRetryParameters z.1,z.2)) + (g := profileRetry) + (pair (composition (f := fun z : SamplingParameters×List Bool => z.1) + (g := samplingRetryParameters) first samplingRetryParametersRealizer) second) profileRetryRealizer + +theorem polynomial_samplingMatrix : PolynomialTime samplingMatrixRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_samplingRetryParameters) polynomial_second) + polynomial_profileRetry + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..53931d9ffb0ee4ae0880f117a4038b2719b204df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleProgram.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalProfileProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRetryProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialProgram +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters + +namespace OAI + +/-! # Computing the complete outer sampling schedule from binary margins -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +abbrev SamplingParameters := (List ℕ×List ℕ)×ℕ + +def squarePower : Realizer (fun n : ℕ => n^2) := + squareNat.congr (fun n => (pow_two n).symm) + +theorem polynomial_squarePower : PolynomialTime squarePower := + polynomial_congr _ polynomial_squareNat + +def cubicPower : Realizer (fun n : ℕ => n^3) := + (composition (pair squareNat identity) multiply).congr (by + intro n; simp only [Function.comp_apply,id_eq]; ring) + +theorem polynomial_cubicPower : PolynomialTime cubicPower := + polynomial_congr _ (polynomial_composition + (polynomial_pair polynomial_squareNat polynomial_identity) polynomial_multiply) + +def twelfthPower : Realizer (fun n : ℕ => n^12) := + (composition fourthPower cubicPower).congr (by + intro n; simp only [Function.comp_apply,←pow_mul]) + +theorem polynomial_twelfthPower : PolynomialTime twelfthPower := + polynomial_congr _ (polynomial_composition polynomial_fourthPower polynomial_cubicPower) + +def twoHundredthPower : Realizer (fun n : ℕ => n^200) := + (composition fiftiethPower fourthPower).congr (by + intro n; simp only [Function.comp_apply,←pow_mul]) + +theorem polynomial_twoHundredthPower : PolynomialTime twoHundredthPower := + polynomial_congr _ (polynomial_composition polynomial_fiftiethPower polynomial_fourthPower) + +def sixtySecondPower : Realizer (fun n : ℕ => n^62) := + (composition (pair (composition twentiethPower cubicPower) squareNat) multiply).congr (by + intro n; simp only [Function.comp_apply]; ring) + +theorem polynomial_sixtySecondPower : PolynomialTime sixtySecondPower := + polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_twentiethPower polynomial_cubicPower) + polynomial_squareNat) polynomial_multiply) + +def marginPadding (z : List ℕ×List ℕ) : ℕ := (marginDimension z)^12 + +def marginPaddingRealizer : Realizer marginPadding := + composition (f := fun z : List ℕ×List ℕ => marginDimension z) (g := fun n : ℕ => n^12) (marginDimensionRealizer) twelfthPower + +theorem polynomial_marginPadding : PolynomialTime marginPaddingRealizer := + polynomial_composition (f := fun z : List ℕ×List ℕ => marginDimension z) (g := fun n : ℕ => n^12) (polynomial_marginDimension) polynomial_twelfthPower + +def marginStateBound (z : List ℕ×List ℕ) : ℕ := (((z.1.sum+(marginDimension z*marginPadding z))+marginThreshold z)+2) + +def marginStateBoundRealizer : Realizer marginStateBound := + composition (f := fun z : List ℕ×List ℕ => (((z.1.sum+(marginDimension z*marginPadding z))+marginThreshold z),2)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : List ℕ×List ℕ => ((z.1.sum+(marginDimension z*marginPadding z)),marginThreshold z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : List ℕ×List ℕ => (z.1.sum,(marginDimension z*marginPadding z))) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : List ℕ×List ℕ => z.1) (g := List.sum) first listSum) (composition (f := fun z : List ℕ×List ℕ => (marginDimension z,marginPadding z)) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (marginDimensionRealizer) (marginPaddingRealizer)) multiply)) add) (marginThresholdRealizer)) add) (constant 2)) add + +theorem polynomial_marginStateBound : PolynomialTime marginStateBoundRealizer := + polynomial_composition (f := fun z : List ℕ×List ℕ => (((z.1.sum+(marginDimension z*marginPadding z))+marginThreshold z),2)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : List ℕ×List ℕ => ((z.1.sum+(marginDimension z*marginPadding z)),marginThreshold z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : List ℕ×List ℕ => (z.1.sum,(marginDimension z*marginPadding z))) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : List ℕ×List ℕ => z.1) (g := List.sum) polynomial_first polynomial_listSum) (polynomial_composition (f := fun z : List ℕ×List ℕ => (marginDimension z,marginPadding z)) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_marginDimension) (polynomial_marginPadding)) polynomial_multiply)) polynomial_add) (polynomial_marginThreshold)) polynomial_add) (polynomial_constant 2)) polynomial_add + +def marginBinaryLength (z : List ℕ×List ℕ) : ℕ := (marginDimension z+(Nat.clog 2) ((marginStateBound z+2))) + +def marginBinaryLengthRealizer : Realizer marginBinaryLength := + composition (f := fun z : List ℕ×List ℕ => (marginDimension z,(Nat.clog 2) ((marginStateBound z+2)))) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (marginDimensionRealizer) (composition (f := fun z : List ℕ×List ℕ => (marginStateBound z+2)) (g := Nat.clog 2) (composition (f := fun z : List ℕ×List ℕ => (marginStateBound z,2)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (marginStateBoundRealizer) (constant 2)) add) ceilLogTwoRealizer)) add + +theorem polynomial_marginBinaryLength : PolynomialTime marginBinaryLengthRealizer := + polynomial_composition (f := fun z : List ℕ×List ℕ => (marginDimension z,(Nat.clog 2) ((marginStateBound z+2)))) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_marginDimension) (polynomial_composition (f := fun z : List ℕ×List ℕ => (marginStateBound z+2)) (g := Nat.clog 2) (polynomial_composition (f := fun z : List ℕ×List ℕ => (marginStateBound z,2)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_marginStateBound) (polynomial_constant 2)) polynomial_add) polynomial_ceilLogTwo)) polynomial_add + +def parameterDimension (z : SamplingParameters) : ℕ := marginDimension z.1 + +def parameterDimensionRealizer : Realizer parameterDimension := + composition (f := fun z : SamplingParameters => z.1) (g := marginDimension) first marginDimensionRealizer + +theorem polynomial_parameterDimension : PolynomialTime parameterDimensionRealizer := + polynomial_composition (f := fun z : SamplingParameters => z.1) (g := marginDimension) polynomial_first polynomial_marginDimension + +def parameterBinaryLength (z : SamplingParameters) : ℕ := marginBinaryLength z.1 + +def parameterBinaryLengthRealizer : Realizer parameterBinaryLength := + composition (f := fun z : SamplingParameters => z.1) (g := marginBinaryLength) first marginBinaryLengthRealizer + +theorem polynomial_parameterBinaryLength : PolynomialTime parameterBinaryLengthRealizer := + polynomial_composition (f := fun z : SamplingParameters => z.1) (g := marginBinaryLength) polynomial_first polynomial_marginBinaryLength + +def parameterTrials (z : SamplingParameters) : ℕ := ((parameterDimension z)^4*(z.2+1)) + +def parameterTrialsRealizer : Realizer parameterTrials := + composition (f := fun z : SamplingParameters => ((parameterDimension z)^4,(z.2+1))) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^4) (parameterDimensionRealizer) fourthPower) (composition (f := fun z : SamplingParameters => (z.2,1)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (second) (constant 1)) add)) multiply + +theorem polynomial_parameterTrials : PolynomialTime parameterTrialsRealizer := + polynomial_composition (f := fun z : SamplingParameters => ((parameterDimension z)^4,(z.2+1))) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^4) (polynomial_parameterDimension) polynomial_fourthPower) (polynomial_composition (f := fun z : SamplingParameters => (z.2,1)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_second) (polynomial_constant 1)) polynomial_add)) polynomial_multiply + +def parameterSteps (z : SamplingParameters) : ℕ := ((parameterDimension z)^200*((z.2+parameterBinaryLength z))^2) + +def parameterStepsRealizer : Realizer parameterSteps := + composition (f := fun z : SamplingParameters => ((parameterDimension z)^200,((z.2+parameterBinaryLength z))^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^200) (parameterDimensionRealizer) twoHundredthPower) (composition (f := fun z : SamplingParameters => (z.2+parameterBinaryLength z)) (g := fun n : ℕ => n^2) (composition (f := fun z : SamplingParameters => (z.2,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (second) (parameterBinaryLengthRealizer)) add) squarePower)) multiply + +theorem polynomial_parameterSteps : PolynomialTime parameterStepsRealizer := + polynomial_composition (f := fun z : SamplingParameters => ((parameterDimension z)^200,((z.2+parameterBinaryLength z))^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^200) (polynomial_parameterDimension) polynomial_twoHundredthPower) (polynomial_composition (f := fun z : SamplingParameters => (z.2+parameterBinaryLength z)) (g := fun n : ℕ => n^2) (polynomial_composition (f := fun z : SamplingParameters => (z.2,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_second) (polynomial_parameterBinaryLength)) polynomial_add) polynomial_squarePower)) polynomial_multiply + +def parameterAccuracy (z : SamplingParameters) : ℕ := ((parameterDimension z)^4*((z.2+parameterBinaryLength z))^2) + +def parameterAccuracyRealizer : Realizer parameterAccuracy := + composition (f := fun z : SamplingParameters => ((parameterDimension z)^4,((z.2+parameterBinaryLength z))^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^4) (parameterDimensionRealizer) fourthPower) (composition (f := fun z : SamplingParameters => (z.2+parameterBinaryLength z)) (g := fun n : ℕ => n^2) (composition (f := fun z : SamplingParameters => (z.2,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (second) (parameterBinaryLengthRealizer)) add) squarePower)) multiply + +theorem polynomial_parameterAccuracy : PolynomialTime parameterAccuracyRealizer := + polynomial_composition (f := fun z : SamplingParameters => ((parameterDimension z)^4,((z.2+parameterBinaryLength z))^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^4) (polynomial_parameterDimension) polynomial_fourthPower) (polynomial_composition (f := fun z : SamplingParameters => (z.2+parameterBinaryLength z)) (g := fun n : ℕ => n^2) (polynomial_composition (f := fun z : SamplingParameters => (z.2,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_second) (polynomial_parameterBinaryLength)) polynomial_add) polynomial_squarePower)) polynomial_multiply + +def parameterProposalWidth (z : SamplingParameters) : ℕ := (Nat.clog 2) ((32*(parameterDimension z)^2)) + +def parameterProposalWidthRealizer : Realizer parameterProposalWidth := + composition (f := fun z : SamplingParameters => (32*(parameterDimension z)^2)) (g := Nat.clog 2) (composition (f := fun z : SamplingParameters => (32,(parameterDimension z)^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (constant 32) (composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^2) (parameterDimensionRealizer) squarePower)) multiply) ceilLogTwoRealizer + +theorem polynomial_parameterProposalWidth : PolynomialTime parameterProposalWidthRealizer := + polynomial_composition (f := fun z : SamplingParameters => (32*(parameterDimension z)^2)) (g := Nat.clog 2) (polynomial_composition (f := fun z : SamplingParameters => (32,(parameterDimension z)^2)) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_constant 32) (polynomial_composition (f := fun z : SamplingParameters => parameterDimension z) (g := fun n : ℕ => n^2) (polynomial_parameterDimension) polynomial_squarePower)) polynomial_multiply) polynomial_ceilLogTwo + +def parameterCompletionWidth (z : SamplingParameters) : ℕ := (25*((((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z)+1))^62) + +def parameterCompletionWidthRealizer : Realizer parameterCompletionWidth := + composition (f := fun z : SamplingParameters => (25,((((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z)+1))^62)) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (constant 25) (composition (f := fun z : SamplingParameters => (((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z)+1)) (g := fun n : ℕ => n^62) (composition (f := fun z : SamplingParameters => (((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z),1)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : SamplingParameters => ((parameterDimension z+parameterBinaryLength z),parameterAccuracy z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : SamplingParameters => (parameterDimension z,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (parameterDimensionRealizer) (parameterBinaryLengthRealizer)) add) (parameterAccuracyRealizer)) add) (constant 1)) add) sixtySecondPower)) multiply + +theorem polynomial_parameterCompletionWidth : PolynomialTime parameterCompletionWidthRealizer := + polynomial_composition (f := fun z : SamplingParameters => (25,((((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z)+1))^62)) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_constant 25) (polynomial_composition (f := fun z : SamplingParameters => (((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z)+1)) (g := fun n : ℕ => n^62) (polynomial_composition (f := fun z : SamplingParameters => (((parameterDimension z+parameterBinaryLength z)+parameterAccuracy z),1)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => ((parameterDimension z+parameterBinaryLength z),parameterAccuracy z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => (parameterDimension z,parameterBinaryLength z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_parameterDimension) (polynomial_parameterBinaryLength)) polynomial_add) (polynomial_parameterAccuracy)) polynomial_add) (polynomial_constant 1)) polynomial_add) polynomial_sixtySecondPower)) polynomial_multiply + +def parameterWordCount (z : SamplingParameters) : ℕ := (parameterTrials z*((parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z))+parameterCompletionWidth z)) + +def parameterWordCountRealizer : Realizer parameterWordCount := + composition (f := fun z : SamplingParameters => (parameterTrials z,((parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z))+parameterCompletionWidth z))) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (parameterTrialsRealizer) (composition (f := fun z : SamplingParameters => ((parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z)),parameterCompletionWidth z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (composition (f := fun z : SamplingParameters => (parameterSteps z,(parameterProposalWidth z+parameterCompletionWidth z))) (g := fun t : ℕ×ℕ => t.1*t.2) (pair (parameterStepsRealizer) (composition (f := fun z : SamplingParameters => (parameterProposalWidth z,parameterCompletionWidth z)) (g := fun t : ℕ×ℕ => t.1+t.2) (pair (parameterProposalWidthRealizer) (parameterCompletionWidthRealizer)) add)) multiply) (parameterCompletionWidthRealizer)) add)) multiply + +theorem polynomial_parameterWordCount : PolynomialTime parameterWordCountRealizer := + polynomial_composition (f := fun z : SamplingParameters => (parameterTrials z,((parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z))+parameterCompletionWidth z))) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_parameterTrials) (polynomial_composition (f := fun z : SamplingParameters => ((parameterSteps z*(parameterProposalWidth z+parameterCompletionWidth z)),parameterCompletionWidth z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_composition (f := fun z : SamplingParameters => (parameterSteps z,(parameterProposalWidth z+parameterCompletionWidth z))) (g := fun t : ℕ×ℕ => t.1*t.2) (polynomial_pair (polynomial_parameterSteps) (polynomial_composition (f := fun z : SamplingParameters => (parameterProposalWidth z,parameterCompletionWidth z)) (g := fun t : ℕ×ℕ => t.1+t.2) (polynomial_pair (polynomial_parameterProposalWidth) (polynomial_parameterCompletionWidth)) polynomial_add)) polynomial_multiply) (polynomial_parameterCompletionWidth)) polynomial_add)) polynomial_multiply + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..3516a5569224cc794a9a8404cbdbb92cf3ad212c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileScheduleSemantics.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileSamplingProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRetrySemantics +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFiniteSampler + +namespace OAI + +/-! # The computed schedule and initializer equal the proved sampler data -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] profileRetry listedOuterDraw tableState +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c + +lemma marginDimension_ofFn : marginDimension (List.ofFn r,List.ofFn c)=d := by + simp only [marginDimension,List.length_ofFn,dimensionAllowance,Fintype.card_fin] + +lemma marginPadding_ofFn : marginPadding (List.ofFn r,List.ofFn c)=d^12 := by + rw [marginPadding,marginDimension_ofFn] + +lemma marginStateBound_ofFn : marginStateBound (List.ofFn r,List.ofFn c)=stateBound r c := by + rw [marginStateBound,List.sum_ofFn,marginDimension_ofFn,marginPadding_ofFn,marginThreshold_ofFn] + rfl + +lemma marginBinaryLength_ofFn : marginBinaryLength (List.ofFn r,List.ofFn c)=b := by + rw [marginBinaryLength,marginDimension_ofFn,marginStateBound_ofFn] + rfl + +lemma parameterDimension_ofFn (k : ℕ) : parameterDimension ((List.ofFn r,List.ofFn c),k)=d := + marginDimension_ofFn r c + +lemma parameterBinaryLength_ofFn (k : ℕ) : parameterBinaryLength ((List.ofFn r,List.ofFn c),k)=b := + marginBinaryLength_ofFn r c + +lemma parameterTrials_ofFn (k : ℕ) : + parameterTrials ((List.ofFn r,List.ofFn c),k)=outerTrials d k := by + rw [parameterTrials,parameterDimension_ofFn] + rfl + +lemma parameterSteps_ofFn (k : ℕ) : + parameterSteps ((List.ofFn r,List.ofFn c),k)=outerSteps d b k := by + rw [parameterSteps,parameterDimension_ofFn,parameterBinaryLength_ofFn] + rfl + +lemma parameterAccuracy_ofFn (k : ℕ) : + parameterAccuracy ((List.ofFn r,List.ofFn c),k)=outerAccuracy d b k := by + rw [parameterAccuracy,parameterDimension_ofFn,parameterBinaryLength_ofFn] + rfl + +lemma parameterProposalWidth_ofFn (k : ℕ) : + parameterProposalWidth ((List.ofFn r,List.ofFn c),k)=smallProposalBits (I := Fin m) (J := Fin n) := by + rw [parameterProposalWidth,parameterDimension_ofFn] + +lemma parameterCompletionWidth_ofFn (k : ℕ) : + parameterCompletionWidth ((List.ofFn r,List.ofFn c),k)=25*(d+b+outerAccuracy d b k+1)^62 := by + rw [parameterCompletionWidth,parameterDimension_ofFn,parameterBinaryLength_ofFn, + parameterAccuracy_ofFn] + +lemma parameterWordCount_ofFn (k : ℕ) : + parameterWordCount ((List.ofFn r,List.ofFn c),k)=finiteSamplerBits r c k := by + rw [parameterWordCount,parameterTrials_ofFn,parameterSteps_ofFn,parameterProposalWidth_ofFn, + parameterCompletionWidth_ofFn] + +lemma initialConfiguration_code (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) : + initialConfiguration ((List.ofFn r,List.ofFn c),k)= + encodedConfiguration r c (computedCellEquiv r c) (outerAccuracy d b k) + (tableState r c (GreedyFeasibleTable.table r c htotal)) + (tableState r c (GreedyFeasibleTable.table r c htotal)) := by + unfold initialConfiguration + rw [initialCheck_code r c htotal,marginPadding_ofFn,parameterDimension_ofFn, + parameterAccuracy_ofFn,initialViews_code r c htotal] + rfl + +lemma samplingSchedule_ofFn (k : ℕ) : + samplingSchedule ((List.ofFn r,List.ofFn c),k)= + ((outerSteps d b k,smallProposalBits (I := Fin m) (J := Fin n)), + 25*(d+b+outerAccuracy d b k+1)^62) := by + rw [samplingSchedule,parameterSteps_ofFn,parameterProposalWidth_ofFn,parameterCompletionWidth_ofFn] + +/-- Equality of the actual list program with the listed finite-word draw. +The current theorem is for the nonempty large-rectangle branch. -/ +theorem samplingMatrix_code + (hr : 0<(largeIndices (d^20,List.ofFn r)).length) + (hc : 0<(largeIndices (d^20,List.ofFn c)).length) + (htotal : (∑ i,r i)=∑ j,c j) (k : ℕ) + (bits : Fin (finiteSamplerBits r c k) → Bool) : + samplingMatrix (((List.ofFn r,List.ofFn c),k),List.ofFn bits)= + matrixCode (listedOuterDraw r c (computedCellEquiv r c) hr hc b (outerAccuracy d b k) + (smallBinaryLength_parameters r c).1 (tableState r c (GreedyFeasibleTable.table r c htotal)) + (outerSteps d b k) (outerTrials d k) (GreedyFeasibleTable.table r c htotal) bits).val := by + have hdraw := profileRetry_code r c (computedCellEquiv r c) hr hc b (outerAccuracy d b k) + (smallBinaryLength_parameters r c).1 htotal + (tableState r c (GreedyFeasibleTable.table r c htotal)) + (outerSteps d b k) (outerTrials d k) (GreedyFeasibleTable.table r c htotal) bits + unfold samplingMatrix samplingRetryParameters + rw [initialConfiguration_code r c htotal,samplingSchedule_ofFn,GreedyFeasibleTable.listMatrix_ofFn] + have hcode : matrixCode (GreedyFeasibleTable.table r c htotal).val= + List.ofFn (fun i => List.ofFn (GreedyFeasibleTable.matrix r c i)) := rfl + rw [hcode] at hdraw + dsimp only at hdraw ⊢ + exact hdraw + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a7507b4c7bae6c0204a9011a9fd75ce3b4fd2ce --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalProgram.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CachedTerminalCount +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntryRuntime +import OAI.Combinatorics.ContingencyTables.Transport.MeasuredMap + +namespace OAI + +/-! # Computing terminal success weights at every enumerated profile -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev TerminalEntryInput := MatrixParameters×((List ℕ×List ℕ)×MatrixCode) + +def terminalSourceInput (z : TerminalEntryInput) : MatrixEntryInput := + (z.1,(z.2.1,z.2.1)) + +def terminalSourceInputRealizer : Realizer terminalSourceInput := + pair first (pair (composition second first) (composition second first)) + +lemma polynomial_terminalSourceInput : PolynomialTime terminalSourceInputRealizer := + polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) + +def terminalEntryQuery (z : TerminalEntryInput) : TransitionCache×MatrixCode := + (prepareTransitionCache (entryCacheParameters (terminalSourceInput z)),z.2.2) + +def terminalEntryQueryRealizer : Realizer terminalEntryQuery := + pair (composition (f := terminalSourceInput) + (g := fun z => prepareTransitionCache (entryCacheParameters z)) terminalSourceInputRealizer + (composition (f := entryCacheParameters) (g := prepareTransitionCache) + entryCacheParametersRealizer prepareTransitionCacheRealizer)) (composition second second) + +def terminalEntry (z : TerminalEntryInput) : ℕ := terminalCount (terminalEntryQuery z) + +def terminalEntryRealizer : Realizer terminalEntry := + composition (f := terminalEntryQuery) (g := terminalCount) terminalEntryQueryRealizer terminalCountRealizer + +def terminalEntryMeasure (z : TerminalEntryInput) : ℕ := + matrixEntryMeasure (terminalSourceInput z)+weight z + +lemma work_terminalEntry : WorkBound terminalEntryRealizer terminalEntryMeasure := by + have hin (z : TerminalEntryInput) : weight z ≤ X.eval (terminalEntryMeasure z) := by + simp only [Polynomial.eval_X,terminalEntryMeasure] + omega + have hc : WorkBound (composition terminalSourceInputRealizer + (composition entryCacheParametersRealizer prepareTransitionCacheRealizer)) terminalEntryMeasure := by + apply work_composition (work_of_polynomial polynomial_terminalSourceInput X hin) work_entryCache X + intro z + simp only [Polynomial.eval_X,terminalEntryMeasure] + omega + have ht : WorkBound (composition (second (A := MatrixParameters)) second) terminalEntryMeasure := + work_of_polynomial (polynomial_composition polynomial_second polynomial_second) X hin + unfold terminalEntryRealizer terminalEntryQueryRealizer + exact work_then_polynomial (work_pair hc ht X hin) polynomial_terminalCount + +abbrev TerminalColumnInput := MatrixParameters×MatrixCode +abbrev TerminalColumnEntryInput := TerminalColumnInput×(List ℕ×List ℕ) + +def terminalColumnEntryInput (z : TerminalColumnEntryInput) : TerminalEntryInput := + (z.1.1,(z.2,z.1.2)) + +def terminalColumnEntryInputRealizer : Realizer terminalColumnEntryInput := + pair (composition first first) (pair second (composition first second)) + +lemma polynomial_terminalColumnEntryInput : PolynomialTime terminalColumnEntryInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_second)) + +def terminalColumnEntry (z : TerminalColumnEntryInput) : ℕ := terminalEntry (terminalColumnEntryInput z) + +def terminalColumnEntryRealizer : Realizer terminalColumnEntry := + composition (f := terminalColumnEntryInput) (g := terminalEntry) + terminalColumnEntryInputRealizer terminalEntryRealizer + +def terminalColumnEntryMeasure (z : TerminalColumnEntryInput) : ℕ := + terminalEntryMeasure (terminalColumnEntryInput z)+weight z + +lemma work_terminalColumnEntry : WorkBound terminalColumnEntryRealizer terminalColumnEntryMeasure := by + unfold terminalColumnEntryRealizer + apply work_composition (work_of_polynomial polynomial_terminalColumnEntryInput X + (fun z => by simp only [Polynomial.eval_X,terminalColumnEntryMeasure]; omega)) + work_terminalEntry X + intro z + simp only [Polynomial.eval_X,terminalColumnEntryMeasure] + omega + +def terminalColumn (z : TerminalColumnInput) : List ℕ := + (profileBoxViews (matrixData z.1)).map (fun v => terminalColumnEntry (z,v)) + +def terminalColumnRealizer : Realizer terminalColumn := + composition (f := fun z : TerminalColumnInput => (z,profileBoxViews (matrixData z.1))) + (g := fun z : TerminalColumnInput×List (List ℕ×List ℕ) => + z.2.map (fun v => terminalColumnEntry (z.1,v))) + (pair identity (composition + (f := fun z : TerminalColumnInput => matrixData z.1) (g := profileBoxViews) + (composition (f := fun z : TerminalColumnInput => z.1) (g := matrixData) + first matrixDataRealizer) profileBoxViewsRealizer)) (mapWith terminalColumnEntryRealizer) + +def terminalColumnMeasure (z : TerminalColumnInput) : ℕ := + gridStateCount (profileEnumerationData (matrixData z.1))+ + MeasuredMap.listMeasure terminalColumnEntryMeasure (z,profileBoxViews (matrixData z.1)) + +lemma work_terminalColumn : WorkBound terminalColumnRealizer terminalColumnMeasure := by + have hin (z : TerminalColumnInput) : weight z ≤ terminalColumnMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := + weight_fst (z,profileBoxViews (matrixData z.1)) + simp only [terminalColumnMeasure,MeasuredMap.listMeasure] + omega + have hd : PolynomialTime (composition (first (B := MatrixCode)) matrixDataRealizer) := + polynomial_composition polynomial_first polynomial_matrixData + have hv : WorkBound (composition (composition first matrixDataRealizer) profileBoxViewsRealizer) + terminalColumnMeasure := by + apply work_composition (work_of_polynomial hd X (fun z => by simpa using hin z)) + work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z.1) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans + ((weight_fst _).trans (weight_fst z)))) + simp only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + terminalColumnMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := + weight_fst (z,profileBoxViews (matrixData z.1)) + omega + unfold terminalColumnRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_terminalColumnEntry) X + intro z + simp only [Polynomial.eval_X,terminalColumnMeasure,Function.comp_apply,id_eq] + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c610442e9ee420b4a84e65d2507e4cb162f841a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTerminalSemantics.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalProgram +import OAI.Combinatorics.ContingencyTables.Machines.CachedTerminalSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixLaw +import OAI.Combinatorics.ContingencyTables.Transport.IntegerMatrixPoint + +namespace OAI + +/-! # Exact trial counts from matrix propagation and cached terminal weights -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical + +lemma bind_count {A B : Type*} [Fintype A] [Fintype B] + {Q R : ℕ} (p : IntegerLaw A Q) (K : A → IntegerLaw B R) (b : B) : + (p.bind K).count b=∑ a,p.count a*(K a).count b := rfl + +lemma sum_push_mul {A B : Type*} [Fintype A] [Fintype B] [DecidableEq B] + {Q : ℕ} (p : IntegerLaw A Q) (f : A → B) (w : B → ℕ) : + (∑ b,(p.push f).count b*w b)=∑ a,p.count a*w (f a) := by + change (∑ b,(∑ a,if f a=b then p.count a else 0)*w b)=_ + simp_rw [Finset.sum_mul,ite_mul,zero_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + +end ContingencyTables.IntegerLaw + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] stateCode stateCodeData listedCompletionCounts listedWalkCounts + listedTrialCounts prepareTransitionCache terminalCount matrixInput IntegerLaw.push + +def terminalFibreCounts (x : PaperStates r c) : IntegerLaw (Option (Table r c)) (2^f) := + (listedCompletionCounts r c hr hc b h hb x).push (fun A => stateTrial r c ⟨x,A⟩) + +lemma terminalEntry_actual (z x : PaperStates r c) (xs : List Bool) (T : Table r c) : + terminalEntry (matrixInput r c e b h z xs,(stateCode r c e x,matrixCode T.val))= + (terminalFibreCounts r c hr hc b h hb x).count (some T) := by + unfold terminalEntry terminalEntryQuery terminalSourceInput entryCacheParameters + dsimp only [sourceData,matrixData] + unfold matrixInput + rw [candidate_stateCodeData] + exact terminalCount_actual r c e hr hc b h hb x T + +lemma terminalColumn_ofFn (z : PaperStates r c) (xs : List Bool) (T : Table r c) : + terminalColumn (matrixInput r c e b h z xs,matrixCode T.val)= + List.ofFn (fun k : BoxIndex => terminalEntry + (matrixInput r c e b h z xs,(boxCode k,matrixCode T.val))) := by + have hv : profileBoxViews (matrixData (matrixInput r c e b h z xs))=List.ofFn + (boxCode (m := m) (n := n) (q := q)) := by + unfold matrixData matrixInput + exact profileBoxViews_actual r c e z + unfold terminalColumn + dsimp only [Prod.fst] + rw [hv,List.map_ofFn] + rfl + +lemma listedTrialCounts_count (z : PaperStates r c) (N : ℕ) (T : Table r c) : + (listedTrialCounts r c e hr hc b h hb z N).count (some T)= + ∑ x,(listedWalkCounts r c e hr hc b h hb z N).count x* + (terminalFibreCounts r c hr hc b h hb x).count (some T) := by + unfold listedTrialCounts terminalFibreCounts + exact IntegerLaw.bind_count _ _ _ + +attribute [local irreducible] terminalFibreCounts + +lemma terminal_dot_trial (z : PaperStates r c) (xs : List Bool) (N : ℕ) (T : Table r c) : + IntegerMatrixPrograms.dot + (List.ofFn (fun k : BoxIndex => + ((listedWalkCounts r c e hr hc b h hb z N).push (profileIndex r c e)).count k), + terminalColumn (matrixInput r c e b h z xs,matrixCode T.val))= + (listedTrialCounts r c e hr hc b h hb z N).count (some T) := by + rw [terminalColumn_ofFn r c e b h z xs T,IntegerMatrixPrograms.dot_ofFn, + IntegerLaw.sum_push_mul] + change (∑ x,(listedWalkCounts r c e hr hc b h hb z N).count x* + terminalEntry (matrixInput r c e b h z xs,(boxCode (profileIndex r c e x),matrixCode T.val)))=_ + simp_rw [boxCode_index,terminalEntry_actual r c e hr hc b h hb] + exact (listedTrialCounts_count r c e hr hc b h hb z N T).symm + +lemma fromPoint_trial_count (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) (T : Table r c) : + IntegerMatrixPrograms.dot + (IntegerMatrixPrograms.fromPoint (N, + (profileMatrix (matrixInput r c e b h z xs),(profileIndex r c e z).val)), + terminalColumn (matrixInput r c e b h z xs,matrixCode T.val))= + (listedTrialCounts r c e hr hc b h hb z N).count (some T) := by + unfold IntegerMatrixPrograms.fromPoint + rw [profileMatrix_actual r c e hr hc b h hb htotal z xs hs, + IntegerMatrixPrograms.pointVector_ofFn] + rw [←profileMatrix_actual r c e hr hc b h hb htotal z xs hs, + profileMatrix_walk r c e hr hc b h hb htotal z xs hs N] + exact terminal_dot_trial r c e hr hc b h hb z xs N T + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc5206d415bed719b502244ba3922cab0f5168d2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCount.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CachedStepCount + +namespace OAI + +/-! # Counting the short proposal words with a shared dense cache -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open scoped BigOperators Classical + +/-- The scalar is the multiplicity of the ignored completion-bit suffix. -/ +abbrev TransitionCache := ResidualParameters×(ℕ×List (Option MatrixCode×ℕ)) +abbrev TransitionQuery := (TransitionCache×(List ℕ×List ℕ))×List Bool + +def cachedWordInput (z : TransitionQuery) : DecisionQuery×List (Option MatrixCode×ℕ) := + (((z.1.1.1,z.2),z.1.2),z.1.1.2.2) + +def cachedWordInputRealizer : Realizer cachedWordInput := by + let context : Realizer (fun z : TransitionQuery => z.1.1) := composition first first + let params := composition context first + let entries := composition (composition context second) second + exact pair (pair (pair params second) (composition first second)) entries + +lemma polynomial_cachedWordInput : PolynomialTime cachedWordInputRealizer := by + unfold cachedWordInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second) + +def cachedWordCount (z : TransitionQuery) : ℕ := + z.1.1.2.1*decisionWeightSum (cachedWordInput z) + +def cachedWordCountRealizer : Realizer cachedWordCount := by + let scalar : Realizer (fun z : TransitionQuery => z.1.1.2.1) := + composition (composition (composition first first) second) first + let value := composition cachedWordInputRealizer decisionWeightSumRealizer + exact composition (pair scalar value) multiply + +lemma polynomial_cachedWordCount : PolynomialTime cachedWordCountRealizer := by + unfold cachedWordCountRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + (polynomial_composition polynomial_cachedWordInput polynomial_decisionWeightSum)) polynomial_multiply + +def transitionCount (z : TransitionQuery) : ℕ := + ((booleanWords z.2).map (fun bits => cachedWordCount (z.1,bits))).sum + +def transitionCountRealizer : Realizer transitionCount := by + let input : Realizer (fun z : TransitionQuery => (z.1,booleanWords z.2)) := + pair first (composition (f := fun z : TransitionQuery => z.2) (g := booleanWords) + second booleanWordsRealizer) + let counts := composition (mapWith cachedWordCountRealizer) listSum + exact composition (f := fun z : TransitionQuery => (z.1,booleanWords z.2)) + (g := fun z : (TransitionCache×(List ℕ×List ℕ))×List (List Bool) => + (z.2.map (fun bits => cachedWordCount (z.1,bits))).sum) input counts + +lemma work_transitionCount : WorkBound transitionCountRealizer + (fun z => gridStateCount (z.2,2)+weight z) := by + have hw : WorkBound (composition (second (A := TransitionCache×(List ℕ×List ℕ))) + booleanWordsRealizer) (fun z : TransitionQuery => gridStateCount (z.2,2)+weight z) := by + apply work_composition (work_of_polynomial polynomial_second Polynomial.X + (fun z => by simp)) work_booleanWords Polynomial.X + intro z + simp only [Polynomial.eval_X] + exact Nat.add_le_add_left (weight_snd z) _ + unfold transitionCountRealizer + apply work_then_polynomial _ (polynomial_composition + (polynomial_mapWith polynomial_cachedWordCount) polynomial_listSum) + exact work_pair (work_of_polynomial polynomial_first Polynomial.X (fun z => by + simp only [Polynomial.eval_X]; omega)) hw Polynomial.X (fun z => by + simp only [Polynomial.eval_X]; omega) + +lemma transitionCount_words (z : TransitionCache×(List ℕ×List ℕ)) + (xs : List Bool) (s : ℕ) (hs : xs.length=s) : + transitionCount (z,xs)=∑ bits : Fin s → Bool,cachedWordCount (z,List.ofFn bits) := + sum_booleanWords xs s hs _ + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical +noncomputable section + +lemma booleanFinish_count {A B : Type*} [Fintype A] [Fintype B] [DecidableEq B] + {s f : ℕ} (p : IntegerLaw A (2^f)) (finish : (Fin s → Bool) → A → B) (b : B) : + (booleanFinish p finish).count b= + ∑ bits : Fin s → Bool,∑ a,if finish bits a=b then p.count a else 0 := by + change (∑ z : (Fin s → Bool)×A,if finish z.1 z.2=b then 1*p.count z.2 else 0)=_ + rw [Fintype.sum_prod_type] + simp only [one_mul] + +end +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCountSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCountSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..1158587d3d0151cd92b971545a683d348b366d28 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionCountSemantics.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PreparedTransitionCache +import OAI.Combinatorics.ContingencyTables.Transport.BooleanCountTransport + +namespace OAI + +/-! # Executed cached transitions have the actual walk's integer counts -/ + +namespace ContingencyTables.ProfilePrograms + +lemma cachedWordCount_eq (p : ResidualParameters) (M : ℕ) + (cache : List (Option DensePrograms.MatrixCode×ℕ)) (target : List ℕ×List ℕ) + (bits : List Bool) : + cachedWordCount (((p,(M,cache)),target),bits)= + M*decisionWeightSum (((p,bits),target),cache) := rfl + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +attribute [local irreducible] canonicalCounts listedStepCounts listedCompletionCounts + normalizedDrawBits prepareTransitionCache stateCode stateCodeData listedRows listedColumns + completionDecision transitionCount cachedWordCount cachedWordInput completionWeights decisionWeightSum + +def listedUnpaddedCounts (x : PaperStates r c) : + IntegerLaw (Table (R x) (P x)) (2^normalizedDrawBits (R x) (P x) d h) := + canonicalCounts (R x) (P x) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_paper_totals r c hr hc x) h + +def listedCompletionFactor (x : PaperStates r c) : ℕ := + 2^(f-normalizedDrawBits (R x) (P x) d h) + +def listedCachedDecision (x : PaperStates r c) (word : Fin s → Bool) + (A : Table (R x) (P x)) : PaperStates r c := + completionDecision R P x (decodedCodeProposal r c e x word) A + +attribute [local irreducible] listedUnpaddedCounts listedCompletionFactor listedCachedDecision + +lemma listedCompletionCounts_count (x : PaperStates r c) (A : PaperFibre r c x) : + (listedCompletionCounts r c hr hc b h hb x).count A= + (listedUnpaddedCounts r c hr hc h x).count (paperListedEquiv r c hr hc x A)* + listedCompletionFactor r c hr hc b h x := by + unfold listedUnpaddedCounts listedCompletionFactor listedCompletionCounts + rfl + +lemma listedStepCounts_sum (x y : PaperStates r c) : + (listedStepCounts r c e hr hc b h hb x).count y= + ∑ word : Fin s → Bool,∑ A : Table (R x) (P x), + if listedCachedDecision r c e hr hc x word A=y then + (listedUnpaddedCounts r c hr hc h x).count A* + listedCompletionFactor r c hr hc b h x else 0 := by + have he := IntegerLaw.booleanFinish_equiv_count + (listedCompletionCounts r c hr hc b h hb x) (listedUnpaddedCounts r c hr hc h x) + (paperListedEquiv r c hr hc x) (listedCompletionFactor r c hr hc b h x) + (listedCachedDecision r c e hr hc x) + (listedCompletionCounts_count r c hr hc b h hb x) y + simpa only [listedStepCounts,listedCachedDecision] using he + +lemma decisionWeightSum_listed (htotal : ∑ i,r i=∑ j,c j) + (x y : PaperStates r c) (word : Fin s → Bool) : + decisionWeightSum ((encodedShortStep r c e h x word,stateCode r c e y), + completionWeights ((marginCode (R x),marginCode (P x)),(d,h)))= + ∑ A : Table (R x) (P x),if listedCachedDecision r c e hr hc x word A=y + then (listedUnpaddedCounts r c hr hc h x).count A else 0 := by + unfold listedCachedDecision listedUnpaddedCounts + exact decisionWeightSum_actual r c e hr hc htotal h x y word + +lemma transitionCount_actual (htotal : ∑ i,r i=∑ j,c j) + (x y : PaperStates r c) (xs : List Bool) (hs : xs.length=s) : + transitionCount ((prepareTransitionCache + ((((stateCodeData r c e x,d^12),(d,h)),f)),stateCode r c e y),xs)= + (listedStepCounts r c e hr hc b h hb x).count y := by + rw [prepareTransitionCache_encoded r c e hr hc,transitionCount_words _ xs s hs, + listedStepCounts_sum r c e hr hc b h hb x y] + apply Finset.sum_congr rfl + intro word _ + rw [cachedWordCount_eq] + have he := decisionWeightSum_listed r c e hr hc h htotal x y word + unfold encodedShortStep at he + rw [he,Finset.mul_sum] + apply Finset.sum_congr rfl + intro A _ + unfold listedCompletionFactor + split_ifs + · exact Nat.mul_comm _ _ + · exact Nat.mul_zero _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..288f9d0f70de55475940ca75f8f86e8a1a3542af --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionProgram.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedReservedDraw +import OAI.Combinatorics.ContingencyTables.Transport.TranslationDecisionSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram + +namespace OAI + +/-! # A binary small-profile transition with a fresh dense completion -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev ProfileStepInput := ResidualParameters×(List Bool×List Bool) + +def stepCheck : Realizer (fun z : ProfileStepInput => z.1.1.1) := + composition (composition first first) first + +theorem polynomial_stepCheck : PolynomialTime stepCheck := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + +def stepViews : Realizer (fun z : ProfileStepInput => z.1.1.1.1.1.2) := + composition (f := fun z : ProfileStepInput => z.1.1.1) + (g := fun z : ProfileCheckData => z.1.1.2) stepCheck profileViews + +theorem polynomial_stepViews : PolynomialTime stepViews := + polynomial_composition polynomial_stepCheck polynomial_profileViews + +def stepProposal (z : ProfileStepInput) : Option (List ℕ×List ℕ) := + codeNeighborProposal (z.1.1.1,z.2.1) + +def stepProposalRealizer : Realizer stepProposal := + composition (pair stepCheck (composition second first)) codeNeighborProposalRealizer + +theorem polynomial_stepProposal : PolynomialTime stepProposalRealizer := + polynomial_composition (polynomial_pair polynomial_stepCheck + (polynomial_composition polynomial_second polynomial_first)) polynomial_codeNeighborProposal + +def stepCandidateViews (z : ProfileStepInput) : List ℕ×List ℕ := + (stepProposal z).getD z.1.1.1.1.1.2 + +def stepCandidateViewsRealizer : Realizer stepCandidateViews := + composition (pair stepViews stepProposalRealizer) FirstSuccessProgram.defaultRealizer + +theorem polynomial_stepCandidateViews : PolynomialTime stepCandidateViewsRealizer := + polynomial_composition (polynomial_pair polynomial_stepViews polynomial_stepProposal) + FirstSuccessProgram.polynomial_default + +def stepCandidate (z : ProfileStepInput) : ProfileCheckData := + candidateData (z.1.1.1,stepCandidateViews z) + +def stepCandidateRealizer : Realizer stepCandidate := + composition (pair stepCheck stepCandidateViewsRealizer) candidateDataRealizer + +theorem polynomial_stepCandidate : PolynomialTime stepCandidateRealizer := + polynomial_composition (polynomial_pair polynomial_stepCheck polynomial_stepCandidateViews) + polynomial_candidateData + +def stepCandidateParameters (z : ProfileStepInput) : ResidualParameters := + ((stepCandidate z,z.1.1.2),z.1.2) + +def stepCandidateParametersRealizer : Realizer stepCandidateParameters := + pair (pair stepCandidateRealizer (composition (composition first first) second)) + (composition first second) + +theorem polynomial_stepCandidateParameters : PolynomialTime stepCandidateParametersRealizer := + polynomial_pair (polynomial_pair polynomial_stepCandidate + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + (polynomial_composition polynomial_first polynomial_second) + +def stepOldMargins (z : ProfileStepInput) : DensePrograms.MarginPair := + (residualParameters z.1).1 + +def stepOldMarginsRealizer : Realizer stepOldMargins := + composition (f := fun z : ProfileStepInput => residualParameters z.1) + (g := fun z : DensePrograms.CanonicalParameters => z.1) + (composition (f := fun z : ProfileStepInput => z.1) (g := residualParameters) + first residualParametersRealizer) first + +theorem polynomial_stepOldMargins : PolynomialTime stepOldMarginsRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_residualParameters) + polynomial_first + +def stepNewMargins (z : ProfileStepInput) : DensePrograms.MarginPair := + (residualParameters (stepCandidateParameters z)).1 + +def stepNewMarginsRealizer : Realizer stepNewMargins := + composition (f := fun z : ProfileStepInput => residualParameters (stepCandidateParameters z)) + (g := fun z : DensePrograms.CanonicalParameters => z.1) + (composition (f := stepCandidateParameters) (g := residualParameters) + stepCandidateParametersRealizer residualParametersRealizer) first + +theorem polynomial_stepNewMargins : PolynomialTime stepNewMarginsRealizer := + polynomial_composition (polynomial_composition polynomial_stepCandidateParameters + polynomial_residualParameters) polynomial_first + +def stepCompletion (z : ProfileStepInput) : DensePrograms.MatrixCode := + reservedResidualDraw (z.1,z.2.2) + +def stepCompletionRealizer : Realizer stepCompletion := + composition (f := fun z : ProfileStepInput => (z.1,z.2.2)) + (g := reservedResidualDraw) (pair first (composition second second)) reservedResidualDrawRealizer + +theorem polynomial_stepCompletion : PolynomialTime stepCompletionRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) polynomial_reservedResidualDraw + +def stepTranslation (z : ProfileStepInput) : DensePrograms.TranslationData := + ((stepOldMargins z,stepNewMargins z),stepCompletion z) + +def stepTranslationRealizer : Realizer stepTranslation := + pair (pair stepOldMarginsRealizer stepNewMarginsRealizer) stepCompletionRealizer + +theorem polynomial_stepTranslation : PolynomialTime stepTranslationRealizer := + polynomial_pair (polynomial_pair polynomial_stepOldMargins polynomial_stepNewMargins) + polynomial_stepCompletion + +def profileStep (z : ProfileStepInput) : List ℕ×List ℕ := + if DensePrograms.translationValid (stepTranslation z) then stepCandidateViews z else z.1.1.1.1.1.2 + +def profileStepRealizer : Realizer profileStep := + (choose (composition stepTranslationRealizer DensePrograms.translationValidRealizer) + stepCandidateViewsRealizer stepViews).congr + (by intro z; simp only [profileStep,Function.comp_apply]) + +theorem polynomial_profileStep : PolynomialTime profileStepRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition polynomial_stepTranslation DensePrograms.polynomial_translationValid) + polynomial_stepCandidateViews polynomial_stepViews) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..0109fd9ec45a0c381aa2bf28da948d836d25cd78 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTransitionSemantics.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionProgram +import OAI.Combinatorics.ContingencyTables.Transport.ListedReferenceDecision + +namespace OAI + +/-! # Exact semantics of the binary outer transition -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical + +noncomputable section + +private lemma apply_decision {X Y : Type*} (encode : X → Y) (x y : X) + (test : Bool) (accept : Prop) [Decidable accept] (h : test=true ↔ accept) : + (if test then encode y else encode x)=encode (if accept then y else x) := by + by_cases hp : accept + · rw [ite_eq_left hp,ite_eq_left (h.mpr hp)] + · rw [ite_eq_right hp,ite_eq_right (fun ht => hp (h.mp ht))] + +private lemma completionDecision_some_formula {X I J : Type*} [Fintype I] [Fintype J] + (R : X → Option I → ℕ) (P : X → Option J → ℕ) (x y : X) (A : Table (R x) (P x)) : + completionDecision R P x (some y) A= + if ∀ i j,0 ≤ (A.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j then y else x := rfl + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) + +theorem codeProposal_encoded (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) + (bits : Fin (smallProposalBits (I := Fin m) (J := Fin n)) → Bool) : + codeNeighborProposal (stateCodeData r c e x,List.ofFn bits)= + (decodedCodeProposal r c e x bits).map (stateCode r c e) := by + cases hp : codeNeighborProposal (stateCodeData r c e x,List.ofFn bits) with + | none => simp only [decodedCodeProposal,hp,Option.bind_none,Option.map_none] + | some v => + have hv : v∈codeNeighbors (stateCodeData r c e x) := List.mem_of_getElem? hp + obtain ⟨y,hy⟩ := codeNeighbors_decode_total r c e htotal x v hv + have he := (decodeStateCode_eq_some_iff r c e v y).mp hy + simp only [decodedCodeProposal,hp,Option.bind_some,hy,Option.map_some,he] + +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +def encodedStepInput (x : PaperStates r c) (proposal : Fin s → Bool) (completion : Fin f → Bool) : + ProfileStepInput := (((stateCodeData r c e x,d^12),(d,h)),(List.ofFn proposal,List.ofFn completion)) + +lemma stepCandidate_encoded (x y : PaperStates r c) (proposal : Fin s → Bool) (completion : Fin f → Bool) + (hp : codeNeighborProposal (stateCodeData r c e x,List.ofFn proposal)=some (stateCode r c e y)) : + stepCandidateParameters (encodedStepInput r c e b h x proposal completion)= + ((stateCodeData r c e y,d^12),(d,h)) := by + simp only [stepCandidateParameters,stepCandidate,stepCandidateViews,stepProposal,encodedStepInput,hp, + Option.getD_some] + rfl + +lemma stepTranslation_encoded (x y : PaperStates r c) (proposal : Fin s → Bool) (completion : Fin f → Bool) + (hp : codeNeighborProposal (stateCodeData r c e x,List.ofFn proposal)=some (stateCode r c e y)) : + stepTranslation (encodedStepInput r c e b h x proposal completion)= + (((marginCode (R x),marginCode (P x)),(marginCode (R y),marginCode (P y))), + tableOutput (paperListedEquiv r c hr hc x (listedPaddedDraw r c hr hc b h hb x completion))) := by + unfold stepTranslation stepOldMargins stepNewMargins stepCompletion + rw [stepCandidate_encoded r c e b h x y proposal completion hp] + dsimp only [encodedStepInput] + rw [residualParameters_code, residualParameters_code,listedPaddedDraw_code] + +theorem profileStep_encoded (htotal : (∑ i,r i)=∑ j,c j) + (x : PaperStates r c) (proposal : Fin s → Bool) (completion : Fin f → Bool) : + profileStep (encodedStepInput r c e b h x proposal completion)= + stateCode r c e (completionDecision R P x (decodedCodeProposal r c e x proposal) + (paperListedEquiv r c hr hc x (listedPaddedDraw r c hr hc b h hb x completion))) := by + have hp := codeProposal_encoded r c e htotal x proposal + cases hd : decodedCodeProposal r c e x proposal with + | none => + rw [hd,Option.map_none] at hp + unfold profileStep + have hcand : stepCandidateViews (encodedStepInput r c e b h x proposal completion)=stateCode r c e x := by + simp only [stepCandidateViews,stepProposal,encodedStepInput,hp,Option.getD_none] + rfl + rw [hcand] + split_ifs <;> rfl + | some y => + rw [hd,Option.map_some] at hp + have ht := stepTranslation_encoded r c e hr hc b h hb x y proposal completion hp + have hv := translationValid_code (R x) (R y) (P x) (P y) + (paperListedEquiv r c hr hc x (listedPaddedDraw r c hr hc b h hb x completion)) + unfold profileStep + rw [ht] + have hcand : stepCandidateViews (encodedStepInput r c e b h x proposal completion)=stateCode r c e y := by + simp only [stepCandidateViews,stepProposal,encodedStepInput,hp,Option.getD_some] + rw [hcand] + rw [completionDecision_some_formula] + exact apply_decision (stateCode r c e) x y _ _ hv + + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..975e52864ae7ee27e05610c40a2e09d403452dcb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialCountProgram.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalSemantics + +namespace OAI + +/-! # Executed walk-and-terminal integer trial counts -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev WalkCountInput := MatrixParameters×(ℕ×ℕ) + +def walkCountData (z : WalkCountInput) : ℕ×(List (List ℕ)×ℕ) := + (z.2.1,(profileMatrix z.1,z.2.2)) + +def walkCountDataRealizer : Realizer walkCountData := + pair (composition second first) + (pair (composition (f := fun z : WalkCountInput => z.1) (g := profileMatrix) + first profileMatrixRealizer) (composition second second)) + +def walkCountMeasure (z : WalkCountInput) : ℕ := + z.2.1+profileMatrixMeasure z.1+weight z + +lemma work_walkCountData : WorkBound walkCountDataRealizer walkCountMeasure := by + have hi (z : WalkCountInput) : weight z ≤ X.eval (walkCountMeasure z) := by + simp only [Polynomial.eval_X,walkCountMeasure] + omega + have hm : WorkBound (composition (first (B := ℕ×ℕ)) profileMatrixRealizer) walkCountMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_profileMatrix X + intro z + simp only [Polynomial.eval_X,walkCountMeasure] + omega + unfold walkCountDataRealizer + exact work_pair (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) X hi) + (work_pair hm (work_of_polynomial + (polynomial_composition polynomial_second polynomial_second) X hi) X hi) X hi + +def walkCounts (z : WalkCountInput) : List ℕ := IntegerMatrixPrograms.fromPoint (walkCountData z) + +def walkCountsRealizer : Realizer walkCounts := + composition (f := walkCountData) (g := IntegerMatrixPrograms.fromPoint) + walkCountDataRealizer IntegerMatrixPrograms.fromPointRealizer + +lemma work_walkCounts : WorkBound walkCountsRealizer walkCountMeasure := by + obtain ⟨p,hp⟩ := work_walkCountData + unfold walkCountsRealizer + apply work_composition ⟨p,hp⟩ IntegerMatrixPrograms.work_fromPoint (X+p) + intro z + have hw := hp z + have hs : weight (profileMatrix z.1,z.2.2) ≤ weight (walkCountData z) := by + exact weight_snd (walkCountData z) + have hn : z.2.1 ≤ walkCountMeasure z := by unfold walkCountMeasure; omega + simp only [Polynomial.eval_add,Polynomial.eval_X] + change z.2.1+weight (profileMatrix z.1,z.2.2) ≤ _ + omega + +abbrev TrialCountInput := WalkCountInput×MatrixCode + +def trialCount (z : TrialCountInput) : ℕ := + IntegerMatrixPrograms.dot (walkCounts z.1,terminalColumn (z.1.1,z.2)) + +def trialCountRealizer : Realizer trialCount := + composition (pair (composition (f := fun z : TrialCountInput => z.1) (g := walkCounts) + first walkCountsRealizer) + (composition (f := fun z : TrialCountInput => (z.1.1,z.2)) (g := terminalColumn) + (pair (composition first first) second) terminalColumnRealizer)) IntegerMatrixPrograms.dotRealizer + +def trialCountMeasure (z : TrialCountInput) : ℕ := + walkCountMeasure z.1+terminalColumnMeasure (z.1.1,z.2)+weight z + +lemma work_trialCount : WorkBound trialCountRealizer trialCountMeasure := by + have hi (z : TrialCountInput) : weight z ≤ X.eval (trialCountMeasure z) := by + simp only [Polynomial.eval_X,trialCountMeasure] + omega + have hw : WorkBound (composition (first (B := MatrixCode)) walkCountsRealizer) trialCountMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_walkCounts X + intro z + simp only [Polynomial.eval_X,trialCountMeasure] + omega + have ht : WorkBound (composition (pair (composition first first) second) + terminalColumnRealizer) trialCountMeasure := by + apply work_composition (work_of_polynomial (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) X hi) + work_terminalColumn X + intro z + simp only [Polynomial.eval_X,trialCountMeasure,Function.comp_apply] + omega + unfold trialCountRealizer + exact work_then_polynomial (work_pair hw ht X hi) IntegerMatrixPrograms.polynomial_dot + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +lemma trialCount_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) (T : Table r c) : + trialCount ((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)),matrixCode T.val)= + (listedTrialCounts r c e hr hc b h hb z N).count (some T) := by + unfold trialCount walkCounts walkCountData + exact fromPoint_trial_count r c e hr hc b h hb htotal z xs hs N T + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..48c5270a5f922250ed504b09a2d9ac228c93b6b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialProgram.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileWalk +import OAI.Combinatorics.ContingencyTables.Sampling.OuterTrialProgram + +namespace OAI + +/-! # A complete polynomial outer trial on supplied independent words -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev ProfileTrialData := (ProfileConfiguration×List ProfileWord)×List Bool + +def trialState (z : ProfileTrialData) : ProfileConfiguration := profileWalk z.1 +def trialStateRealizer : Realizer trialState := composition first profileWalkRealizer + +theorem polynomial_trialState : PolynomialTime trialStateRealizer := + polynomial_composition polynomial_first polynomial_profileWalk + +def trialParameters (z : ProfileTrialData) : ResidualParameters := currentParameters (trialState z) +def trialParametersRealizer : Realizer trialParameters := + composition trialStateRealizer currentParametersRealizer + +theorem polynomial_trialParameters : PolynomialTime trialParametersRealizer := + polynomial_composition polynomial_trialState polynomial_currentParameters + +def trialCompletion (z : ProfileTrialData) : DensePrograms.MatrixCode := + reservedResidualDraw (trialParameters z,z.2) +def trialCompletionRealizer : Realizer trialCompletion := + composition (pair trialParametersRealizer second) reservedResidualDrawRealizer + +theorem polynomial_trialCompletion : PolynomialTime trialCompletionRealizer := + polynomial_composition (polynomial_pair polynomial_trialParameters polynomial_second) + polynomial_reservedResidualDraw + +def trialOutputInput (z : ProfileTrialData) : OuterTrialInput := + ((trialParameters z).1,trialCompletion z) +def trialOutputInputRealizer : Realizer trialOutputInput := + pair (composition trialParametersRealizer first) trialCompletionRealizer + +theorem polynomial_trialOutputInput : PolynomialTime trialOutputInputRealizer := + polynomial_pair (polynomial_composition polynomial_trialParameters polynomial_first) + polynomial_trialCompletion + +def profileTrial (z : ProfileTrialData) : Option DensePrograms.MatrixCode := + outerTrial (trialOutputInput z) +def profileTrialRealizer : Realizer profileTrial := + composition trialOutputInputRealizer outerTrialRealizer + +theorem polynomial_profileTrial : PolynomialTime profileTrialRealizer := + polynomial_composition polynomial_trialOutputInput polynomial_outerTrial + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bd413e35e396779c477d1e1f3f0d6b05a002926 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileTrialSemantics.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileWordProgram +import OAI.Combinatorics.ContingencyTables.Transport.ListedOutputSemantics +import OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileSemantics +import OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanDraw + +namespace OAI + +/-! # The polynomial outer trial implements the finite-word experiment -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open FirstSuccess FairBits CompletionCounts SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +lemma currentParameters_encoded (initial x : PaperStates r c) : + currentParameters (encodedConfiguration r c e h initial x)= + ((stateCodeData r c e x,d^12),(d,h)) := rfl + +theorem profileTrial_ofFn (htotal : (∑ i,r i)=∑ j,c j) + (initial x : PaperStates r c) (steps : ℕ) + (bits : Fin steps → Fin (s+f) → Bool) (terminal : Fin f → Bool) : + profileTrial ((encodedConfiguration r c e h initial x, + List.ofFn (fun i => (List.ofFn (splitWordEquiv s f (bits i)).1, + List.ofFn (splitWordEquiv s f (bits i)).2))),List.ofFn terminal)= + (stateTrial r c ⟨wordWalk (listedBitStep r c e hr hc b h hb) x steps bits, + listedPaddedDraw r c hr hc b h hb _ terminal⟩).map (fun T => matrixCode T.val) := by + unfold profileTrial trialOutputInput ProfilePrograms.trialCompletion trialParameters trialState + rw [profileWalk_ofFn r c e hr hc b h hb htotal,currentParameters_encoded] + rw [listedPaddedDraw_code r c hr hc e b h hb] + exact actualOuterTrial r c e hr hc _ _ + +theorem packedProfileTrial_code (htotal : (∑ i,r i)=∑ j,c j) + (x : PaperStates r c) (steps : ℕ) (bits : Fin (steps*(s+f)+f) → Bool) : + packedProfileTrial ((encodedConfiguration r c e h x x,((steps,s),f)),List.ofFn bits)= + (stateTrial r c (listedJointDraw r c e hr hc b h hb x steps bits)).map + (fun T => matrixCode T.val) := by + have hf : 0 (ho o ho').1)).trans + (Nat.add_le_add_right (Nat.mul_le_mul_right _ hlen) 1) + have hop (o : Option MatrixCode) (ho' : o∈os) : optionalTrialMeasure (z.1.1,o) ≤ B := by + have hT := (ho o ho').2 + have how := (ho o ho').1 + have ht : terminalColumnMeasure (z.1.1.1,o.getD []) ≤ terminal := + terminalColumnMeasure_le _ M hm hT hN hv (fun v hv' => he v hv' v hv') + change (z.1.1.2.1+profileMatrixMeasure z.1.1.1+weight z.1.1)+ + terminalColumnMeasure (z.1.1.1,o.getD [])+weight (z.1.1,o.getD [])+weight (z.1.1,o) ≤ B + simp only [weight_prod] + unfold B + omega + have hs := MeasuredMap.listMeasure_le optionalTrialMeasure z.1.1 os B hop + have hmul := Nat.mul_le_mul_right B hlen + have hpair : weight (z.1.1,os) ≤ 2+M+M*(M+1) := by + simp only [weight_prod] + omega + change originalEnumerationMeasure z.1.2+ + MeasuredMap.listMeasure optionalTrialMeasure (z.1.1,os)+weight z.1+weight z ≤ _ + have hz1 : weight z.1 ≤ M := (weight_fst _).trans hz + have horig : originalEnumerationMeasure z.1.2 ≤ 2*M := by + unfold originalEnumerationMeasure + omega + simp only [vectorMeasurePolynomial,eval_add,eval_mul,eval_pow,eval_X,eval_one,eval_ofNat] + change _ ≤ M*B+M*(M+1)+5*M+2 + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1d2985cd7813d25d56bd1b3f7cb110235865697 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ProfileWordProgram.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialProgram +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram + +namespace OAI + +/-! # Parsing the independent words of the physical outer trial -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +/-- The schedule contains the number of steps and the two step widths. -/ +abbrev ProfileWordSchedule := (ℕ×ℕ)×ℕ +abbrev ProfileWordInput := ProfileWordSchedule×List Bool + +def splitProfileWord (z : ℕ×List Bool) : ProfileWord := (z.2.take z.1,z.2.drop z.1) +def splitProfileWordRealizer : Realizer splitProfileWord := + pair (composition (pair second first) takeFast) (composition (pair second first) dropFast) + +theorem polynomial_splitProfileWord : PolynomialTime splitProfileWordRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_dropFast) + +def profileWordWidth (z : ProfileWordInput) : ℕ := z.1.1.2+z.1.2 +def profileWordWidthRealizer : Realizer profileWordWidth := + composition (pair (composition (composition first first) second) (composition first second)) add + +theorem polynomial_profileWordWidth : PolynomialTime profileWordWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_add + +def profileWalkWidth (z : ProfileWordInput) : ℕ := z.1.1.1*profileWordWidth z +def profileWalkWidthRealizer : Realizer profileWalkWidth := + composition (pair (composition (composition first first) first) profileWordWidthRealizer) multiply + +theorem polynomial_profileWalkWidth : PolynomialTime profileWalkWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_profileWordWidth) polynomial_multiply + +def profileWalkChunks (z : ProfileWordInput) : List (List Bool) := + wordChunks (profileWordWidth z,z.2.take (profileWalkWidth z)) +def profileWalkChunksRealizer : Realizer profileWalkChunks := + composition (pair profileWordWidthRealizer + (composition (pair second profileWalkWidthRealizer) takeFast)) wordChunksRealizer + +theorem polynomial_profileWalkChunks : PolynomialTime profileWalkChunksRealizer := + polynomial_composition (polynomial_pair polynomial_profileWordWidth + (polynomial_composition (polynomial_pair polynomial_second polynomial_profileWalkWidth) + polynomial_takeFast)) polynomial_wordChunks + +def profileWalkWords (z : ProfileWordInput) : List ProfileWord := + (profileWalkChunks z).map (fun bits => splitProfileWord (z.1.1.2,bits)) +def profileWalkWordsRealizer : Realizer profileWalkWords := + composition (pair (composition (composition first first) second) profileWalkChunksRealizer) + (mapWith splitProfileWordRealizer) + +theorem polynomial_profileWalkWords : PolynomialTime profileWalkWordsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_profileWalkChunks) (polynomial_mapWith polynomial_splitProfileWord) + +def profileTerminalWord (z : ProfileWordInput) : List Bool := z.2.drop (profileWalkWidth z) +def profileTerminalWordRealizer : Realizer profileTerminalWord := + composition (pair second profileWalkWidthRealizer) dropFast + +theorem polynomial_profileTerminalWord : PolynomialTime profileTerminalWordRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_profileWalkWidth) polynomial_dropFast + +abbrev PackedProfileTrial := (ProfileConfiguration×ProfileWordSchedule)×List Bool + +def profileTrialWords (z : PackedProfileTrial) : ProfileWordInput := (z.1.2,z.2) +def profileTrialWordsRealizer : Realizer profileTrialWords := pair (composition first second) second + +theorem polynomial_profileTrialWords : PolynomialTime profileTrialWordsRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second + +def prepareProfileTrial (z : PackedProfileTrial) : ProfileTrialData := + ((z.1.1,profileWalkWords (profileTrialWords z)),profileTerminalWord (profileTrialWords z)) +def prepareProfileTrialRealizer : Realizer prepareProfileTrial := + pair (pair (composition first first) + (composition profileTrialWordsRealizer profileWalkWordsRealizer)) + (composition profileTrialWordsRealizer profileTerminalWordRealizer) + +theorem polynomial_prepareProfileTrial : PolynomialTime prepareProfileTrialRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_profileTrialWords polynomial_profileWalkWords)) + (polynomial_composition polynomial_profileTrialWords polynomial_profileTerminalWord) + +def packedProfileTrial (z : PackedProfileTrial) : Option MatrixCode := profileTrial (prepareProfileTrial z) +def packedProfileTrialRealizer : Realizer packedProfileTrial := + composition prepareProfileTrialRealizer profileTrialRealizer + +theorem polynomial_packedProfileTrial : PolynomialTime packedProfileTrialRealizer := + polynomial_composition polynomial_prepareProfileTrial polynomial_profileTrial + +open FairBits GridBoundary +open scoped Classical +noncomputable section + +lemma splitProfileWord_ofFn {s f : ℕ} (bits : Fin (s+f) → Bool) : + splitProfileWord (s,List.ofFn bits)= + (List.ofFn (splitWordEquiv s f bits).1,List.ofFn (splitWordEquiv s f bits).2) := + Prod.ext (ofFn_split_take bits) (ofFn_split_drop bits) + +lemma profileWalkWords_ofFn {n s f : ℕ} (hw : 0 + let word := gridWordEquiv n (s+f) (splitWordEquiv (n*(s+f)) f bits).1 i + (List.ofFn (splitWordEquiv s f word).1,List.ofFn (splitWordEquiv s f word).2)) := by + unfold profileWalkWords profileWalkChunks + dsimp only [profileWordWidth,profileWalkWidth] + rw [ofFn_split_take,wordChunks_ofFn hw,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact splitProfileWord_ofFn _ + +lemma profileTerminalWord_ofFn {n s f : ℕ} (bits : Fin (n*(s+f)+f) → Bool) : + profileTerminalWord (((n,s),f),List.ofFn bits)= + List.ofFn (splitWordEquiv (n*(s+f)) f bits).2 := ofFn_split_drop bits + +end +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/RareBranchRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RareBranchRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..090e1748ae090616effa121b0b95d8d6e3a7c327 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RareBranchRuntime.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRuntimeBound + +namespace OAI + +/-! # The correction probability absorbs the cost of finite tabulation -/ + +namespace ContingencyTables.RareBranchRuntime +open Polynomial ProfilePrograms + +/-- The coefficient in a fixed exponential running-time bound need not be +smaller than the coefficient used in the sampler's precision schedule. -/ +lemma linear_le_square_add (k s : ℕ) : k * s ≤ s ^ 2 + k ^ 2 := by + have h := two_mul_le_add_sq (k : ℤ) (s : ℤ) + have : (k : ℤ)*s≤(s : ℤ)^2+(k : ℤ)^2 := by nlinarith + exact_mod_cast this + +lemma dyadic_linear_bound (k s D : ℕ) (hD : s^2≤D) : + (2:ℕ)^(k*s)≤2^D*2^(k^2) := by + rw [←pow_add] + exact Nat.pow_le_pow_right (by decide) ((linear_le_square_add k s).trans + (Nat.add_le_add_right hD _)) + +/-- A polynomial in an exponential tabulation size remains affordable +after multiplying by the rare-branch probability `2⁻ᴰ`. -/ +theorem polynomial_tabulation_bound (p : Polynomial ℕ) (A s a D : ℕ) + (hD : s^2≤D) : + p.eval (A*2^(a*s))≤2^D*(p.eval A*2^((a*p.natDegree)^2)) := by + calc + p.eval (A*2^(a*s))≤p.eval A*2^((a*s)*p.natDegree) := + polynomial_scaled_power p A 2 (a*s) (by decide) + _ = p.eval A*2^((a*p.natDegree)*s) := by + rw [Nat.mul_right_comm a s p.natDegree] + _ ≤ p.eval A*(2^D*2^((a*p.natDegree)^2)) := + Nat.mul_le_mul_left _ (dyadic_linear_bound (a*p.natDegree) s D hD) + _ = 2^D*(p.eval A*2^((a*p.natDegree)^2)) := by ring + +lemma square_le_precision (d b : ℕ) (hd : 1≤d) : + (d*b)^2≤d^6*b^2 := by + rw [mul_pow] + exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right hd (by decide : 2≤6)) + +/-- The manuscript's precision `d⁶ b²` absorbs any fixed polynomial of +the grid size `2^(10*d*b)`, up to a constant and a polynomial factor. -/ +theorem correction_tabulation_bound (p : Polynomial ℕ) (A d b : ℕ) + (hd : 1≤d) : + p.eval (A*2^(10*(d*b)))≤ + 2^(d^6*b^2)*(p.eval A*2^((10*p.natDegree)^2)) := + polynomial_tabulation_bound p A (d*b) 10 (d^6*b^2) (square_le_precision d b hd) + +theorem expected_correction_cost (p : Polynomial ℕ) (A d b : ℕ) + (hd : 1≤d) (T : ℕ) (hT : T≤p.eval (A*2^(10*(d*b)))) : + (T : ℝ)/(2:ℝ)^(d^6*b^2)≤p.eval A*2^((10*p.natDegree)^2) := by + have h := hT.trans (correction_tabulation_bound p A d b hd) + have hr : (T : ℝ)≤(2:ℝ)^(d^6*b^2)* + ((p.eval A*2^((10*p.natDegree)^2) : ℕ) : ℝ) := by exact_mod_cast h + exact (div_le_iff₀ (by positivity)).mpr (by simpa [mul_comm] using hr) + +/-- A finite ordinary prefix followed by a rare correction adds only the +probability-weighted correction tail to the expected physical runtime. -/ +theorem expected_branch_time (tail correction : ℕ → ℝ) (S : ℕ) (delta : ℝ) + (h0 : ∀ n,0≤tail n) (h1 : ∀ n,tail n≤1) + (hc : Summable correction) + (hafter : ∀ n,tail (n+S)≤delta*correction n) : + Summable tail ∧ (∑' n,tail n)≤(S:ℝ)+delta*(∑' n,correction n) := by + have hm := hc.mul_left delta + have hs : Summable (fun n => tail (n+S)) := + Summable.of_nonneg_of_le (fun n => h0 (n+S)) hafter hm + have ht : Summable tail := (summable_nat_add_iff S).mp hs + refine ⟨ht,?_⟩ + rw [←ht.sum_add_tsum_nat_add S] + have hprefix : (∑ n ∈ Finset.range S,tail n)≤(S:ℝ) := by + calc + _ ≤ ∑ _n ∈ Finset.range S,(1:ℝ) := Finset.sum_le_sum (fun n _ => h1 n) + _ = (S:ℝ) := by simp + have hrest : (∑' n,tail (n+S))≤delta*(∑' n,correction n) := by + simpa only [tsum_mul_left] using hs.tsum_le_tsum hafter hm + exact add_le_add hprefix hrest + +end ContingencyTables.RareBranchRuntime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/Repair.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/Repair.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbdb5e2e5356f8dcb2a8f7c22f426a547bba686b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/Repair.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallEntries + +namespace OAI + +/-! +# Repair of a defect with its large completion + +The two full matrices give the row and column views, agreeing at all +large cells. Moving one unit from the positive cell to the crossing cell +and resetting the column view preserves the enlarged margins. This is the +joint-object injection underlying the repair in paper 200-01. +-/ + +namespace ContingencyTables + +open Finset + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +/-- A single unit transfer, allowing source and receiver to coincide. -/ +def transferInt (X : I → J → ℕ) (source receiver : I × J) (i : I) (j : J) : ℤ := + X i j - (if i = source.1 ∧ j = source.2 then 1 else 0) + + (if i = receiver.1 ∧ j = receiver.2 then 1 else 0) + +omit [Fintype I] [Fintype J] in +theorem transferInt_nonnegative (X : I → J → ℕ) (source receiver : I × J) + (hsource : 0 < X source.1 source.2) (i : I) (j : J) : + 0 ≤ transferInt X source receiver i j := by + by_cases h : i = source.1 ∧ j = source.2 + · obtain ⟨rfl, rfl⟩ := h + simp only [transferInt, and_self, ite_true] + split_ifs <;> omega + · simp only [transferInt, h, ite_false, sub_zero] + split_ifs <;> omega + +omit [Fintype I] in +theorem transferInt_row (X : I → J → ℕ) (source receiver : I × J) (i : I) : + ∑ j, transferInt X source receiver i j = (∑ j, (X i j : ℤ)) - + (if i = source.1 then 1 else 0) + (if i = receiver.1 then 1 else 0) := by + simp only [transferInt, sum_add_distrib, sum_sub_distrib, ite_and] + simp + +omit [Fintype J] in +theorem transferInt_column (X : I → J → ℕ) (source receiver : I × J) (j : J) : + ∑ i, transferInt X source receiver i j = (∑ i, (X i j : ℤ)) - + (if j = source.2 then 1 else 0) + (if j = receiver.2 then 1 else 0) := by + have h (i : I) (p : I × J) : (i = p.1 ∧ j = p.2) ↔ (j = p.2 ∧ i = p.1) := and_comm + simp only [transferInt, sum_add_distrib, sum_sub_distrib, h, ite_and] + simp + +/-- The defect equation `q=x-e_t+e_s` identifies the sign convention. -/ +def IsDefect (x q : I → J → ℕ) (negative positive : I × J) : Prop := + negative ≠ positive ∧ + ∀ i j, (q i j : ℤ) = transferInt x positive negative i j + +omit [Fintype I] [Fintype J] in +theorem IsDefect.positive_entry {x q : I → J → ℕ} {s t : I × J} + (h : IsDefect x q s t) : 0 < x t.1 t.2 := by + have hst : ¬(t.1 = s.1 ∧ t.2 = s.2) := by + rintro ⟨h₁, h₂⟩ + exact h.1 (Prod.ext h₁.symm h₂.symm) + have heq := h.2 t.1 t.2 + simp only [transferInt, and_self, ite_true, hst, ite_false, add_zero] at heq + omega + +/-- The crossing receiver `(i',j)` in the manuscript. -/ +def repairMatrix (x : I → J → ℕ) (s t : I × J) : I → J → ℕ := + fun i j => (transferInt x t (t.1, s.2) i j).toNat + +omit [Fintype I] [Fintype J] in +theorem repairMatrix_cast {x q : I → J → ℕ} {s t : I × J} + (h : IsDefect x q s t) (i : I) (j : J) : + (repairMatrix x s t i j : ℤ) = transferInt x t (t.1, s.2) i j := + Int.toNat_of_nonneg (transferInt_nonnegative x t (t.1, s.2) h.positive_entry i j) + +/-- The repaired matrix has the old row totals and old column-view totals. +The crossing cell may be large, and either of its coordinates may coincide +with those of the original defect cells. -/ +theorem repairMatrix_margins {x q : I → J → ℕ} {s t : I × J} + (h : IsDefect x q s t) (r : I → ℕ) (c : J → ℕ) + (hr : ∀ i, ∑ j, x i j = r i) (hc : ∀ j, ∑ i, q i j = c j) : + HasMargins (repairMatrix x s t) r c := by + constructor + · intro i + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [repairMatrix_cast h] + rw [transferInt_row] + simp only [sub_add_cancel, ← Nat.cast_sum, hr] + · intro j + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [repairMatrix_cast h] + rw [transferInt_column] + have hcol : (∑ i, (q i j : ℤ)) = ∑ i, transferInt x t s i j := by + apply sum_congr rfl + intro i _ + exact h.2 i j + rw [transferInt_column, ← Nat.cast_sum, hc] at hcol + exact hcol.symm + +omit [Fintype I] [Fintype J] in +/-- Fixed defect labels make the repair injective on joint row/column +views, hence also on the state together with its large completion. -/ +theorem repairMatrix_injective {x q y p : I → J → ℕ} {s t : I × J} + (hx : IsDefect x q s t) (hy : IsDefect y p s t) + (heq : repairMatrix x s t = repairMatrix y s t) : x = y ∧ q = p := by + have hxy : x = y := by + funext i j + have h := congrArg (fun X : I → J → ℕ => (X i j : ℤ)) heq + rw [repairMatrix_cast hx, repairMatrix_cast hy] at h + simp only [transferInt] at h + exact Int.natCast_inj.mp (by omega) + refine ⟨hxy, ?_⟩ + funext i j + apply Int.natCast_inj.mp + rw [hx.2, hy.2, hxy] + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd0af7433f0cf4a49403c4bfdfff9566b3400c67 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairFibres.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.RepairResiduals + +namespace OAI + +/-! # Joint state-completion repair injections, including fixed contexts + +Full row and column views retain the large completion explicitly. Their +finite fibre cardinalities therefore count states with the correct +completion multiplicity. The target repair is a balanced full table. +-/ + +namespace ContingencyTables + +open scoped BigOperators Classical +open PaddedCompletions + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +def RowColumnPair (r : I → ℕ) (c : J → ℕ) := + {Z : (I → J → ℕ) × (I → J → ℕ) // + (∀ i, ∑ j, Z.1 i j=r i) ∧ (∀ j, ∑ i, Z.2 i j=c j)} + +instance rowColumnPairFinite (r : I → ℕ) (c : J → ℕ) : Finite (RowColumnPair r c) := by + let encode : RowColumnPair r c → ((i : I) → J → Fin (r i+1)) × ((j : J) → I → Fin (c j+1)) := + fun Z => (fun i j => ⟨Z.val.1 i j,Nat.lt_succ_of_le (by + rw [←Z.property.1 i] + exact Finset.single_le_sum (f := fun k => Z.val.1 i k) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ j))⟩, + fun j i => ⟨Z.val.2 i j,Nat.lt_succ_of_le (by + rw [←Z.property.2 j] + exact Finset.single_le_sum (f := fun k => Z.val.2 k j) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ i))⟩) + apply Finite.of_injective encode + intro X Y he + apply Subtype.ext + apply Prod.ext + · funext i j + exact congrArg Fin.val (congrFun (congrFun (congrArg Prod.fst he) i) j) + · funext i j + exact congrArg Fin.val (congrFun (congrFun (congrArg Prod.snd he) j) i) + +noncomputable instance rowColumnPairFintype (r : I → ℕ) (c : J → ℕ) : Fintype (RowColumnPair r c) := + Fintype.ofFinite _ + +def JointDefect (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) := + {Z : RowColumnPair rbar cbar // IsDefect Z.val.1 Z.val.2 s t ∧ + (∀ i, smallRow small Z.val.1 i ≤ r i) ∧ + (∀ j, smallColumnView small Z.val.2 j ≤ c j)} + +def ResidualTables (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) := + {T : Table rbar cbar // (∀ i, smallRow small T.val i ≤ r i) ∧ + (∀ j, smallColumnView small T.val j ≤ c j)} + +noncomputable instance jointDefectFintype (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) : + Fintype (JointDefect small r c rbar cbar s t) := by unfold JointDefect; infer_instance + +noncomputable instance residualTablesFintype (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) : + Fintype (ResidualTables small r c rbar cbar) := by unfold ResidualTables; infer_instance + +def jointRepair {small : I → J → Bool} {r : I → ℕ} {c : J → ℕ} + {rbar : I → ℕ} {cbar : J → ℕ} {s t : I×J} + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (Z : JointDefect small r c rbar cbar s t) : ResidualTables small r c rbar cbar := by + have hd := Z.property.1 + have hm := repairMatrix_margins hd rbar cbar Z.val.property.1 Z.val.property.2 + have hsmall := repairMatrix_small_sums hd hs ht + exact ⟨⟨repairMatrix Z.val.val.1 s t,hm⟩, + fun i => (hsmall.1 i).trans (Z.property.2.1 i), + fun j => (hsmall.2 j).trans (Z.property.2.2 j)⟩ + +theorem jointRepair_injective {small : I → J → Bool} {r : I → ℕ} {c : J → ℕ} + {rbar : I → ℕ} {cbar : J → ℕ} {s t : I×J} + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) : + Function.Injective (jointRepair (r := r) (c := c) (rbar := rbar) (cbar := cbar) hs ht) := by + intro X Y he + have hmatrix := congrArg (fun T => T.val.val) he + have hviews := repairMatrix_injective X.property.1 Y.property.1 hmatrix + exact Subtype.ext (Subtype.ext (Prod.ext hviews.1 hviews.2)) + +/-- Global typewise repair domination, retaining the large completion. -/ +theorem jointDefect_card_le (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) : + Fintype.card (JointDefect small r c rbar cbar s t) ≤ + Fintype.card (ResidualTables small r c rbar cbar) := + Fintype.card_le_of_injective (jointRepair hs ht) (jointRepair_injective hs ht) + +def JointDefectContext [LT I] [LT J] + (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) (σ : I×J → ℕ) (l : ℕ) := + {Z : JointDefect small r c rbar cbar s t // + (∀ w, RowMajorBefore w s → Z.val.val.1 w.1 w.2=σ w) ∧ Z.val.val.1 s.1 s.2=l-1} + +def ResidualChild [LT I] [LT J] + (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s : I×J) (σ : I×J → ℕ) (l : ℕ) := + {T : ResidualTables small r c rbar cbar // + (∀ w, RowMajorBefore w s → T.val.val w.1 w.2=σ w) ∧ T.val.val s.1 s.2=l} + +noncomputable instance jointDefectContextFintype [LT I] [LT J] + (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) (σ : I×J → ℕ) (l : ℕ) : + Fintype (JointDefectContext small r c rbar cbar s t σ l) := by + unfold JointDefectContext; infer_instance + +noncomputable instance residualChildFintype [LT I] [LT J] + (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s : I×J) (σ : I×J → ℕ) (l : ℕ) : + Fintype (ResidualChild small r c rbar cbar s σ l) := by + unfold ResidualChild; infer_instance + +/-- The entire fixed-prefix defect fibre maps into one fixed child. +The child choice depends only on the ordered defect type. -/ +theorem conditional_jointDefect_card_le [LinearOrder I] [LinearOrder J] + (small : I → J → Bool) (r : I → ℕ) (c : J → ℕ) + (rbar : I → ℕ) (cbar : J → ℕ) (s t : I×J) (σ : I×J → ℕ) (l : ℕ) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) (hst : RowMajorBefore s t) : + Fintype.card (JointDefectContext small r c rbar cbar s t σ l) ≤ + Fintype.card (ResidualChild small r c rbar cbar s σ (l-1+if t.1=s.1 then 1 else 0)) := by + let f : JointDefectContext small r c rbar cbar s t σ l → + ResidualChild small r c rbar cbar s σ (l-1+if t.1=s.1 then 1 else 0) := fun Z => + ⟨jointRepair hs ht Z.val, (fun w hw => by + rw [show (jointRepair hs ht Z.val).val.val w.1 w.2= + repairMatrix Z.val.val.val.1 s t w.1 w.2 from rfl] + rw [repairMatrix_prefix Z.val.property.1 hst hw] + exact Z.property.1 w hw), by + change repairMatrix Z.val.val.val.1 s t s.1 s.2=_ + rw [repairMatrix_special Z.val.property.1,Z.property.2]⟩ + apply Fintype.card_le_of_injective f + intro X Y he + apply Subtype.ext + apply jointRepair_injective hs ht + exact congrArg Subtype.val he + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairLargeMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairLargeMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..aedd4baeea276a714b71e765780876e51286146b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairLargeMass.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileRepair + +namespace OAI + +/-! # A repair adds at most one unit outside the retained small cells -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperProfiles SmallContextFibres PaddedCompletions + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +omit [Fintype I] [Fintype J] in +lemma repair_large_value (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (ht : small t.1 t.2=true) (i : I) (j : J) (hij : small i j=false) : + repairMatrix (smallView small z false) s t i j = if i=t.1 ∧ j=s.2 then 1 else 0 := by + have hne : ¬(i=t.1 ∧ j=t.2) := by + rintro ⟨rfl,rfl⟩ + rw [ht] at hij + contradiction + have he := repairMatrix_cast hd i j + have hz : smallView small z false i j=0 := by simp [smallView,hij] + simp only [transferInt,hz,ite_eq_right hne,Nat.cast_zero,sub_zero,zero_add] at he + split_ifs at he ⊢ <;> omega + +omit [Fintype I] in +lemma repair_large_row_le_one (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (ht : small t.1 t.2=true) (i : I) : + largeRow small (repairMatrix (smallView small z false) s t) i ≤ 1 := by + unfold largeRow + calc + _ ≤ ∑ j : J,if j=s.2 then 1 else 0 := by + apply Finset.sum_le_sum + intro j _ + cases hs : small i j + · rw [ite_eq_right Bool.false_ne_true,repair_large_value small B z s t hd ht i j hs] + split_ifs <;> simp_all + · simp only [ite_true] + split_ifs <;> simp_all + _ = _ := by simp + +omit [Fintype J] in +lemma repair_large_column_le_one (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (ht : small t.1 t.2=true) (j : J) : + largeColumnView small (repairMatrix (smallView small z false) s t) j ≤ 1 := by + unfold largeColumnView + calc + _ ≤ ∑ i : I,if i=t.1 then 1 else 0 := by + apply Finset.sum_le_sum + intro i _ + cases hs : small i j + · rw [ite_eq_right Bool.false_ne_true,repair_large_value small B z s t hd ht i j hs] + split_ifs <;> simp_all + · simp only [ite_true] + split_ifs <;> simp_all + _ = _ := by simp + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairPrefixes.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairPrefixes.lean new file mode 100644 index 0000000000000000000000000000000000000000..23d305dbbf8421a545227c9643a87dfb5d53befb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairPrefixes.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.Repair + +namespace OAI + +/-! # Literal repair values and row-major prefix preservation -/ + +namespace ContingencyTables + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +omit [Fintype I] [Fintype J] in +lemma IsDefect.negative_entry {x q : I → J → ℕ} {s t : I×J} + (h : IsDefect x q s t) : q s.1 s.2=x s.1 s.2+1 := by + have hst : ¬(s.1=t.1 ∧ s.2=t.2) := by + rintro ⟨h1,h2⟩ + exact h.1 (Prod.ext h1 h2) + have he := h.2 s.1 s.2 + simp only [transferInt,hst,↓reduceIte,and_self,sub_zero] at he + omega + +omit [Fintype I] [Fintype J] in +lemma repairMatrix_unchanged {x q : I → J → ℕ} {s t w : I×J} + (h : IsDefect x q s t) (hwt : w ≠ t) (hwv : w ≠ (t.1,s.2)) : + repairMatrix x s t w.1 w.2=x w.1 w.2 := by + apply Int.natCast_inj.mp + rw [repairMatrix_cast h] + have h1 : ¬(w.1=t.1 ∧ w.2=t.2) := fun hw => hwt (Prod.ext hw.1 hw.2) + have h2 : ¬(w.1=t.1 ∧ w.2=s.2) := fun hw => hwv (Prod.ext hw.1 hw.2) + simp only [transferInt,h1,h2,↓reduceIte,sub_zero,add_zero] + +omit [Fintype I] [Fintype J] in +lemma repairMatrix_special {x q : I → J → ℕ} {s t : I×J} + (h : IsDefect x q s t) : + repairMatrix x s t s.1 s.2=x s.1 s.2+(if t.1=s.1 then 1 else 0) := by + apply Int.natCast_inj.mp + rw [repairMatrix_cast h] + have hst : ¬(s.1=t.1 ∧ s.2=t.2) := fun hw => h.1 (Prod.ext hw.1 hw.2) + simp only [transferInt,hst,↓reduceIte,sub_zero,Nat.cast_add] + by_cases hr : t.1=s.1 + · simp [hr] + · simp [hr,Ne.symm hr] + +def RowMajorBefore [LT I] [LT J] (s t : I×J) : Prop := + s.1 exact lt_irrefl _ h + +omit [Fintype I] [Fintype J] in +theorem repairMatrix_prefix [LinearOrder I] [LinearOrder J] + {x q : I → J → ℕ} {s t w : I×J} (h : IsDefect x q s t) + (hst : RowMajorBefore s t) (hws : RowMajorBefore w s) : + repairMatrix x s t w.1 w.2=x w.1 w.2 := by + apply repairMatrix_unchanged h (hws.trans hst).ne + intro hw + have hv : RowMajorBefore w (t.1,s.2) := by + rcases hst with hr|⟨hr,_⟩ + · exact hws.trans (Or.inl hr) + · simpa only [←hr] using hws + exact hv.ne hw + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairResiduals.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairResiduals.lean new file mode 100644 index 0000000000000000000000000000000000000000..fff410edae5f381c01bbbc66ffb80a420877ff8b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/RepairResiduals.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.RepairPrefixes +import OAI.Combinatorics.ContingencyTables.Transport.CompletionCounts + +namespace OAI + +/-! # Original residual bounds are preserved by the literal repair + +Only a small source entry is lowered. Every large entry is unchanged or +increased. Since full row and column-view totals are preserved, the +small row/column sums cannot increase. +-/ + +namespace ContingencyTables + +open scoped BigOperators Classical +open PaddedCompletions CompletionCounts + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +noncomputable def largeRow (small : I → J → Bool) (X : I → J → ℕ) (i : I) : ℕ := + ∑ j, if small i j then 0 else X i j + +noncomputable def smallColumnView (small : I → J → Bool) (Q : I → J → ℕ) (j : J) : ℕ := + ∑ i, if small i j then Q i j else 0 + +noncomputable def largeColumnView (small : I → J → Bool) (Q : I → J → ℕ) (j : J) : ℕ := + ∑ i, if small i j then 0 else Q i j + +omit [Fintype I] [DecidableEq I] [DecidableEq J] in +lemma row_small_large (small : I → J → Bool) (X : I → J → ℕ) (i : I) : + smallRow small X i+largeRow small X i=∑ j, X i j := by + unfold smallRow largeRow + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + cases small i j <;> simp + +omit [Fintype J] [DecidableEq I] [DecidableEq J] in +lemma column_small_large (small : I → J → Bool) (Q : I → J → ℕ) (j : J) : + smallColumnView small Q j+largeColumnView small Q j=∑ i, Q i j := by + unfold smallColumnView largeColumnView + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + cases small i j <;> simp + +omit [Fintype I] [Fintype J] in +lemma repairMatrix_large {small : I → J → Bool} {x q : I → J → ℕ} {s t : I×J} + (h : IsDefect x q s t) (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (i : I) (j : J) (hij : small i j=false) : + q i j=x i j ∧ x i j ≤ repairMatrix x s t i j := by + have hne (w : I×J) (hw : small w.1 w.2=true) : ¬(i=w.1 ∧ j=w.2) := by + rintro ⟨rfl,rfl⟩ + rw [hw] at hij + contradiction + have hst := hne s hs + have htt := hne t ht + constructor + · apply Int.natCast_inj.mp + rw [h.2] + simp only [transferInt,hst,htt,↓reduceIte,sub_zero,add_zero] + · have he := repairMatrix_cast h i j + simp only [transferInt,htt,↓reduceIte,sub_zero] at he + split_ifs at he <;> omega + +/-- This covers small and large receivers and the two possible receiver +coincidences without a special case in the residual calculation. -/ +theorem repairMatrix_small_sums {small : I → J → Bool} {x q : I → J → ℕ} {s t : I×J} + (h : IsDefect x q s t) (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) : + (∀ i, smallRow small (repairMatrix x s t) i ≤ smallRow small x i) ∧ + (∀ j, smallColumnView small (repairMatrix x s t) j ≤ smallColumnView small q j) := by + have hm := repairMatrix_margins h (fun i => ∑ j, x i j) (fun j => ∑ i, q i j) + (fun _ => rfl) (fun _ => rfl) + constructor + · intro i + have hlarge : largeRow small x i ≤ largeRow small (repairMatrix x s t) i := by + apply Finset.sum_le_sum + intro j _ + cases hij : small i j + · exact (repairMatrix_large h hs ht i j hij).2 + · exact le_rfl + have h0 := row_small_large small x i + have h1 := row_small_large small (repairMatrix x s t) i + rw [hm.1] at h1 + dsimp only at h1 + omega + · intro j + have hlarge : largeColumnView small q j ≤ largeColumnView small (repairMatrix x s t) j := by + apply Finset.sum_le_sum + intro i _ + cases hij : small i j + · obtain ⟨he,hge⟩ := repairMatrix_large h hs ht i j hij + simpa [he] using hge + · exact le_rfl + have h0 := column_small_large small q j + have h1 := column_small_large small (repairMatrix x s t) j + rw [hm.2] at h1 + dsimp only at h1 + omega + +omit [Fintype I] [DecidableEq I] [DecidableEq J] in +lemma entry_le_smallRow (small : I → J → Bool) (X : I → J → ℕ) (i : I) (j : J) + (hij : small i j=true) : X i j ≤ smallRow small X i := by + have h := Finset.single_le_sum (fun k _ => Nat.zero_le (if small i k then X i k else 0)) + (Finset.mem_univ j) + simpa only [smallRow,smallColumnView,hij,↓reduceIte] using h + +omit [Fintype J] [DecidableEq I] [DecidableEq J] in +lemma entry_le_smallColumn (small : I → J → Bool) (Q : I → J → ℕ) (i : I) (j : J) + (hij : small i j=true) : Q i j ≤ smallColumnView small Q j := by + have h := Finset.single_le_sum (fun k _ => Nat.zero_le (if small k j then Q k j else 0)) + (Finset.mem_univ i) + simpa only [smallRow,smallColumnView,hij,↓reduceIte] using h + +/-- Every repaired small cell respects the manuscript's actual U box, +because one of its original incident margins is strictly below U. -/ +theorem repairMatrix_small_capacity {x q : I → J → ℕ} {s t : I×J} + (r : I → ℕ) (c : J → ℕ) (U : ℕ) (h : IsDefect x q s t) + (hs : firstPaperSmall r c U s.1 s.2=true) (ht : firstPaperSmall r c U t.1 t.2=true) + (hr : ∀ i, smallRow (firstPaperSmall r c U) x i ≤ r i) + (hc : ∀ j, smallColumnView (firstPaperSmall r c U) q j ≤ c j) + (i : I) (j : J) (hij : firstPaperSmall r c U i j=true) : + repairMatrix x s t i j < U := by + obtain ⟨hrow,hcol⟩ := repairMatrix_small_sums h hs ht + have h1 := (entry_le_smallRow _ (repairMatrix x s t) i j hij).trans ((hrow i).trans (hr i)) + have h2 := (entry_le_smallColumn _ (repairMatrix x s t) i j hij).trans ((hcol j).trans (hc j)) + have hinc : r i simp [smallQ,smallView,hs] + +omit [Fintype I] in +lemma repaired_small_row (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) (i : I) : + smallRow small (smallView small (repairedProfile small B z s t) false) i= + smallRow small (repairMatrix (smallView small z false) s t) i := by + unfold smallRow + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j <;> simp [smallView,repairedProfile,hs] + +omit [Fintype J] in +lemma repaired_small_column (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hcap : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) + (j : J) : + smallColumn small B (smallView small (repairedProfile small B z s t) true) j= + smallColumnView small (repairMatrix (smallView small z false) s t) j := by + unfold smallColumn smallColumnView + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j + · simp + · simp only [hs,ite_true,smallView,dite_eq_left,repairedProfile,ite_true] + exact Nat.sub_sub_self (hcap ⟨(i,j),hs⟩) + +/-- The only loss from a retained margin is the possible single unit +placed into the large receiver. This also covers coincident receiver slots. -/ +theorem repair_small_margin_abs (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) + (ht : small t.1 t.2=true) + (hcap : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) : + (∀ i,|(smallRow small (smallView small (repairedProfile small B z s t) false) i:ℤ)- + smallRow small (smallView small z false) i| ≤ 1) ∧ + (∀ j,|(smallColumn small B (smallView small (repairedProfile small B z s t) true) j:ℤ)- + smallColumn small B (smallView small z true) j| ≤ 1) := by + have hm := repairMatrix_margins hd (fun i => ∑ j,smallView small z false i j) + (fun j => ∑ i,smallQ small B z i j) (fun _ => rfl) (fun _ => rfl) + constructor + · intro i + rw [repaired_small_row] + have he := row_small_large small (repairMatrix (smallView small z false) s t) i + rw [hm.1 i] at he + dsimp only at he + rw [← selectedRow_eq small z false i,selectedRow_eq_smallRow] at he + have hb := repair_large_row_le_one small B z s t hd ht i + apply abs_le.mpr + constructor <;> omega + · intro j + rw [repaired_small_column small B z s t hcap] + have he := column_small_large small (repairMatrix (smallView small z false) s t) j + rw [hm.2 j] at he + dsimp only at he + rw [smallQ_column_sum] at he + have hb := repair_large_column_le_one small B z s t hd ht j + apply abs_le.mpr + constructor <;> omega + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/ResidualMixture.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ResidualMixture.lean new file mode 100644 index 0000000000000000000000000000000000000000..be3835c565501810a2dcf8ebe965a2d2103de306 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/ResidualMixture.lean @@ -0,0 +1,181 @@ +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Rat.Cast.Order +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Exact correction by a finite residual mixture + +Finite probability arithmetic gives the residual correction used in exact +sampling. The construction is that of Göbel, Liu, Manurangsi and Pappik, +*Perfect sampling from rapidly mixing Markov chains*, arXiv:2410.00882v2 +(2024), §3.1, Algorithm 1 and Theorem 6. + +All probabilities are rational, as required for the finite fair-bit sampler. +-/ + +open scoped BigOperators + +namespace ContingencyTables.ResidualMixture + +variable {α : Type*} [Fintype α] + +/-- A finite probability law with exactly represented rational masses. -/ +structure RationalLaw (α : Type*) [Fintype α] where + mass : α → ℚ + nonnegative : ∀ x, 0 ≤ mass x + total : ∑ x, mass x = 1 + +variable [Nonempty α] + +lemma card_pos : (0 : ℚ) < Fintype.card α := by + exact_mod_cast Fintype.card_pos + +/-- The uniform mass on a nonempty finite space. -/ +def uniformMass : ℚ := 1 / Fintype.card α + +lemma uniformMass_pos : 0 < uniformMass (α := α) := by + exact div_pos (by norm_num) card_pos + +lemma uniformMass_total : ∑ _x : α, uniformMass (α := α) = 1 := by + simp only [uniformMass, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + exact mul_one_div_cancel (ne_of_gt card_pos) + +/-- The residual point mass used on the rare correction branch. -/ +def residualMass (p : RationalLaw α) (δ : ℚ) (x : α) : ℚ := + (uniformMass (α := α) - (1 - δ) * p.mass x) / δ + +/-- The pointwise approximation and cardinality bound imply domination. +This is the estimate immediately before the definition of `r(z)` in 200-01. -/ +lemma approximate_domination (p : RationalLaw α) {δ : ℚ} + (hδ : 0 < δ) (hδone : δ ≤ 1) + (hcard : (Fintype.card α : ℚ) * δ ≤ 1) + (happrox : ∀ x, p.mass x ≤ uniformMass (α := α) + δ ^ 2) (x : α) : + (1 - δ) * p.mass x ≤ uniformMass (α := α) := by + have hδu : δ ≤ uniformMass (α := α) := by + rw [uniformMass, le_div_iff₀ card_pos] + nlinarith [hcard] + have hmul := mul_le_mul_of_nonneg_left (happrox x) (sub_nonneg.mpr hδone) + have hδsq : δ ^ 2 ≤ δ := by nlinarith + have herr : (1 - δ) * δ ^ 2 ≤ δ * uniformMass (α := α) := by + have hfirst := mul_le_mul_of_nonneg_left hδsq (sub_nonneg.mpr hδone) + have hsecond := mul_le_mul_of_nonneg_left hδu (le_of_lt hδ) + nlinarith [hfirst, hsecond] + nlinarith [hmul, herr] + +omit [Nonempty α] in +lemma residualMass_nonnegative (p : RationalLaw α) {δ : ℚ} (hδ : 0 < δ) + (hdom : ∀ x, (1 - δ) * p.mass x ≤ uniformMass (α := α)) (x : α) : + 0 ≤ residualMass p δ x := by + exact div_nonneg (sub_nonneg.mpr (hdom x)) (le_of_lt hδ) + +lemma residualMass_total (p : RationalLaw α) {δ : ℚ} (hδ : δ ≠ 0) : + ∑ x, residualMass p δ x = 1 := by + simp only [residualMass, ← Finset.sum_div, Finset.sum_sub_distrib, + ← Finset.mul_sum, uniformMass_total, p.total] + field_simp + ring + +/-- A residual law exists whenever the ordinary branch is pointwise dominated +by the target law. No additional existence assumption is used. -/ +def residualLaw (p : RationalLaw α) {δ : ℚ} (hδ : 0 < δ) + (hdom : ∀ x, (1 - δ) * p.mass x ≤ uniformMass (α := α)) : RationalLaw α where + mass := residualMass p δ + nonnegative := residualMass_nonnegative p hδ hdom + total := residualMass_total p (ne_of_gt hδ) + +omit [Nonempty α] in +/-- The two branches combine to give exactly uniform point masses. -/ +theorem mixture_exact (p : RationalLaw α) {δ : ℚ} (hδ : δ ≠ 0) (x : α) : + (1 - δ) * p.mass x + δ * residualMass p δ x = uniformMass (α := α) := by + dsimp [residualMass] + field_simp + ring + +/-- The complete finite residual-mixture consequence of the pointwise +approximation bound used by the manuscript. -/ +theorem exact_correction (p : RationalLaw α) {δ : ℚ} + (hδ : 0 < δ) (hδone : δ ≤ 1) + (hcard : (Fintype.card α : ℚ) * δ ≤ 1) + (happrox : ∀ x, p.mass x ≤ uniformMass (α := α) + δ ^ 2) : + ∃ r : RationalLaw α, ∀ x, + (1 - δ) * p.mass x + δ * r.mass x = uniformMass (α := α) := by + refine ⟨residualLaw p hδ (approximate_domination p hδ hδone hcard happrox), ?_⟩ + exact mixture_exact p (ne_of_gt hδ) + +/-- The integer numerator in equation `eq:residual-integers` of 200-01. +Here `Q = 2^R`, `T = 2^D`, and `a x` is the tabulated dyadic numerator. -/ +def residualNumerator (Q T : ℤ) (a : α → ℤ) (x : α) : ℤ := + Q * T - (Fintype.card α : ℤ) * (T - 1) * a x + +omit [Nonempty α] in +/-- The residual integer weights have the exact required total. -/ +lemma residualNumerator_total (Q T : ℤ) (a : α → ℤ) (ha : ∑ x, a x = Q) : + ∑ x, residualNumerator Q T a x = (Fintype.card α : ℤ) * Q := by + simp only [residualNumerator, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul, ← Finset.mul_sum, ha] + ring + +/-- The numerator realizes the residual law exactly as a rational quotient. -/ +lemma residualNumerator_quotient (Q T : ℤ) (a : α → ℤ) + (hQ : Q ≠ 0) (hT : T ≠ 0) (x : α) : + (residualNumerator Q T a x : ℚ) / + ((Fintype.card α : ℚ) * Q) = + (uniformMass (α := α) - (1 - 1 / (T : ℚ)) * ((a x : ℚ) / Q)) / + (1 / (T : ℚ)) := by + have hQc : (Q : ℚ) ≠ 0 := by exact_mod_cast hQ + have hTc : (T : ℚ) ≠ 0 := by exact_mod_cast hT + have hc : (Fintype.card α : ℚ) ≠ 0 := ne_of_gt card_pos + simp only [residualNumerator, Int.cast_sub, Int.cast_mul, Int.cast_natCast, + Int.cast_one, uniformMass] + field_simp + +/-- Pointwise domination makes the actual integer correction weights +nonnegative, so their cumulative sums define a finite exact draw. -/ +lemma residualNumerator_nonnegative {Q T : ℤ} (a : α → ℤ) + (hQ : 0 < Q) (hT : 0 < T) + (hdom : ∀ x, (1 - 1 / (T : ℚ)) * ((a x : ℚ) / Q) ≤ + uniformMass (α := α)) (x : α) : + 0 ≤ residualNumerator Q T a x := by + have hQc : (0 : ℚ) < Q := by exact_mod_cast hQ + have hTc : (0 : ℚ) < T := by exact_mod_cast hT + have hres : (0 : ℚ) ≤ + (uniformMass (α := α) - (1 - 1 / (T : ℚ)) * ((a x : ℚ) / Q)) / + (1 / (T : ℚ)) := + div_nonneg (sub_nonneg.mpr (hdom x)) (le_of_lt (one_div_pos.mpr hTc)) + rw [← residualNumerator_quotient Q T a (ne_of_gt hQ) (ne_of_gt hT) x] at hres + have hden : (0 : ℚ) < (Fintype.card α : ℚ) * Q := mul_pos card_pos hQc + have hnum : (0 : ℚ) ≤ residualNumerator Q T a x := + by simpa using (le_div_iff₀ hden).mp hres + exact_mod_cast hnum + +/-- Acceptance of a dyadic proposal has probability greater than one half +when the proposal range is less than twice the target range. This is the +probability estimate for the manuscript's exact integer rejection draw. -/ +lemma integer_rejection_acceptance {V Q : ℕ} (hV : 0 < V) + (hcover : V ≤ Q) (hshort : Q < 2 * V) : + (1 / 2 : ℚ) < (V : ℚ) / Q ∧ (V : ℚ) / Q ≤ 1 := by + have hQ : (0 : ℚ) < Q := by exact_mod_cast lt_of_lt_of_le hV hcover + have hcover' : (V : ℚ) ≤ Q := by exact_mod_cast hcover + have hshort' : (Q : ℚ) < 2 * V := by exact_mod_cast hshort + constructor + · rw [lt_div_iff₀ hQ] + nlinarith + · exact (div_le_iff₀ hQ).mpr (by simpa using hcover') + +/-- A branch with probability `δ` and conditional cost `correction` adds at +most the permitted rare-branch allowance to the ordinary cost bound. -/ +lemma expected_cost_bound {δ ordinary correction allowance : ℚ} + (hδ : 0 ≤ δ) (hordinary : 0 ≤ ordinary) + (hrare : δ * correction ≤ allowance) : + (1 - δ) * ordinary + δ * correction ≤ ordinary + allowance := by + have hprod := mul_nonneg hδ hordinary + nlinarith + +end ContingencyTables.ResidualMixture + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedEncoding.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..5333061212e30b96474d0ea89f25d7c7861e0dbe --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedEncoding.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairWords +import OAI.Combinatorics.ContingencyTables.Transport.RawSmallChoiceProperties + +namespace OAI + +/-! # Every bounded balanced small profile has its literal word encoding -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open SmallContextEnumeration RowMajorEnumeration + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def balancedChoices (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (z : BoundedProfile small B) : + Cells small → Fin (U+1) := fun a => + ⟨(z (a,false)).val,(z (a,false)).isLt.trans_le (by rw [hB _ _ a.property])⟩ + +omit [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] in +lemma balancedChoices_profile (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (z : BoundedProfile small B) + (hz : Balanced small B (naturalProfile z)) : + rawChoice small U (balancedChoices small B U hB z)=naturalProfile z := by + funext p + rcases p with ⟨a,b⟩ + cases b + · rfl + · have h := hz a.val.1 a.val.2 + have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells small)=a := Subtype.ext (Prod.eta a.val) + simp only [smallView,smallQ,a.property,dite_eq_left] at h + rw [heta] at h + dsimp only [naturalProfile] at h + have hy := (z (a,true)).isLt + have hb := hB _ _ a.property + change U-(z (a,false)).val=(z (a,true)).val + change (z (a,true)).val < B a.val.1 a.val.2+1 at hy + omega + +noncomputable def balancedWord (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (z : BoundedProfile small B) : + Fin (Fintype.card (Cells small)) → Fin (U+1) := + (wordChoices small U).symm (balancedChoices small B U hB z) + +lemma balancedWord_profile (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (z : BoundedProfile small B) + (hz : Balanced small B (naturalProfile z)) : + rawChoice small U (wordChoices small U (balancedWord small B U hB z))=naturalProfile z := by + unfold balancedWord + rw [Equiv.apply_symm_apply] + exact balancedChoices_profile small B U hB z hz + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1328218a159a683a94668d817ae3bdf64dcdf43e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBalancedMarginal.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedBox + +namespace OAI + +/-! # Balanced marginal closure at capacities zero and one + +Capacity one has two old quadratic blocks with a common mixed +functional. Each fresh coordinate is isotropic. This proves closure +directly on the raw integer forms, including the small cells that must +be eliminated to obtain an actual tree-coordinate marginal. +-/ + +namespace ContingencyTables + +open scoped BigOperators Classical Matrix +open LinearMap (BilinForm) + +theorem isotropic_kernel_nonpositive + {V : Type*} [AddCommGroup V] [Module ℝ V] + (B : BilinForm ℝ V) (hsymm : ∀ x y, B x y=B y x) + (hsig : OnePositiveDirection B) (e w : V) + (hee : B e e=0) (hew : B e w≠0) + (v : V) (hev : B e v=0) : B v v ≤ 0 := by + by_contra hn + have hv : 0 < B v v := lt_of_not_ge hn + let u := w-(B v w/B v v) • v + have hvu : B v u=0 := by + simp only [u,LinearMap.BilinForm.sub_right,LinearMap.BilinForm.smul_right] + field_simp [hv.ne'] + ring + have heu : B e u=B e w := by + simp only [u,LinearMap.BilinForm.sub_right,LinearMap.BilinForm.smul_right,hev, + mul_zero,sub_zero] + have hue : B u e=B e w := by rw [hsymm,heu] + have hve : B v e=0 := by rw [hsymm,hev] + let t := (1-B u u)/(2*B e w) + have horth : B v (u+t • e)=0 := by + simp only [LinearMap.BilinForm.add_right,LinearMap.BilinForm.smul_right,hvu,hve, + mul_zero,add_zero] + have hsquare : B (u+t • e) (u+t • e)=1 := by + simp only [LinearMap.BilinForm.add_left,LinearMap.BilinForm.add_right, + LinearMap.BilinForm.smul_left,LinearMap.BilinForm.smul_right,hee,heu,hue,mul_zero,add_zero] + dsimp only [t] + field_simp [hew] + ring + have hh := hsig v hv (u+t • e) horth + rw [hsquare] at hh + norm_num at hh + +namespace IntegerMarginal + +open CommonBasesFPRAS FactorialSignatures BalancedBox + +variable {I : Type*} [Fintype I] [DecidableEq I] + +theorem marginal_zero_removal_slice (F : ((I⊕Bool) → ℕ) → ℝ) + (m : I → ℕ) (R : ℕ) + (hsig : RemovalSlice F (profile m 0 0) R) : + RemovalSlice (marginal F 0) m R := by + intro z hz ht + have hs := hsig (profile z 0 0) + (profile_inBox m z 0 0 0 hz le_rfl le_rfl) + (by simp only [profile_total,ht,add_zero]) + rw [marginal_old_block] + simp only [Nat.zero_add,Finset.sum_range_one] + intro u hu v huv + exact hs (old u) hu (old v) huv + +lemma removeOne_total (z : I → ℕ) (i : I) (hi : 0 < z i) : + (∑ u,removeOne z i u)+1=∑ u,z u := by + have he : ∀ u,removeOne z i u+(if u=i then 1 else 0)=z u := by + intro u + by_cases hu : u=i + · subst u + simp only [removeOne,ite_true] + omega + · simp [removeOne,hu] + have hh := congrArg (fun f : I → ℕ => ∑ u,f u) (funext he) + simpa only [Finset.sum_add_distrib,Finset.sum_ite_eq',Finset.mem_univ,ite_true] using hh + +theorem marginal_one_removal_slice (F : ((I⊕Bool) → ℕ) → ℝ) + (m : I → ℕ) (R : ℕ) + (hpos : PositiveSlice F (profile m 1 1) (R+1)) + (hsig : RemovalSlice F (profile m 1 1) (R+1)) : + RemovalSlice (marginal F 1) m R := by + intro z hz ht + have hex : ∃ i,0 < z i := by + by_contra hn + push Not at hn + have hz0 : ∀ i,z i=0 := fun i => Nat.eq_zero_of_le_zero (hn i) + simp only [hz0,Finset.sum_const_zero] at ht + omega + obtain ⟨i,hi⟩ := hex + let B (j : ℕ) := (pairMatrix F 1 z j).toBilin' + let ell : (I → ℝ) →ₗ[ℝ] ℝ := cross F 1 z 1 + have hsigB (j : ℕ) (hj : j ≤ 1) : OnePositiveDirection (B j) := by + apply hsig _ (profile_inBox m z 1 j (1-j) hz hj (Nat.sub_le _ _)) + rw [profile_total,ht] + omega + have he0 : B 0 (Pi.single (.inr true) 1) (Pi.single (.inr true) 1)=0 := by + simp [B,Matrix.toBilin'_apply,pairMatrix_bb,innerWeight] + have he1 : B 1 (Pi.single (.inr false) 1) (Pi.single (.inr false) 1)=0 := by + simp [B,Matrix.toBilin'_apply,pairMatrix_aa,innerWeight] + have hcross0 (v : I → ℝ) : B 0 (old v) (Pi.single (.inr true) 1)=ell v := + cross_b F 1 z 0 (by omega) v + have hcross1 (v : I → ℝ) : B 1 (old v) (Pi.single (.inr false) 1)=ell v := + cross_a F 1 z 1 le_rfl v + have hpositive : 0 < F (profile (removeOne z i) 0 0) := by + apply hpos _ (profile_inBox m (removeOne z i) 1 0 0 + (fun u => (Nat.sub_le _ _).trans (hz u)) (by omega) (by omega)) + have hh := removeOne_total z i hi + rw [profile_total] + omega + have hell : ell (Pi.single i 1)≠0 := by + have hv : ValidPair (profile z 1 0) (.inl i) (.inr false) := by + simp [ValidPair,profile,hi] + have he : ell (Pi.single i 1)=F (profile (removeOne z i) 0 0) := by + dsimp only [ell] + rw [← cross_a F 1 z 1 le_rfl,old_single] + simp only [Pi.single_apply,ite_mul,one_mul,zero_mul,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + rw [pairMatrix,integerRemovalMatrix,ite_eq_left hv,profile_removeOldA] + rw [he] + exact hpositive.ne' + have hker (v : I → ℝ) (hv : ell v=0) : B 0 (old v) (old v)+B 1 (old v) (old v) ≤ 0 := by + have hs0 : ∀ x y,B 0 x y=B 0 y x := + fun x y => (matrix_bilin_symm _ (integerRemoval_symm _ _)).eq x y + have hs1 : ∀ x y,B 1 x y=B 1 y x := + fun x y => (matrix_bilin_symm _ (integerRemoval_symm _ _)).eq x y + have hh0 := isotropic_kernel_nonpositive (B 0) hs0 (hsigB 0 (by omega)) + (Pi.single (.inr true) 1) (old (Pi.single i 1)) he0 + (by rw [hs0,hcross0]; exact hell) (old v) (by rw [hs0,hcross0,hv]) + have hh1 := isotropic_kernel_nonpositive (B 1) hs1 (hsigB 1 le_rfl) + (Pi.single (.inr false) 1) (old (Pi.single i 1)) he1 + (by rw [hs1,hcross1]; exact hell) (old v) (by rw [hs1,hcross1,hv]) + linarith + apply onePositiveDirection_of_kernel _ + (fun x y => (matrix_bilin_symm _ (integerRemoval_symm _ _)).eq x y) ell + intro v hv + have hh := hker v hv + rw [marginal_old_block] + simpa only [Finset.sum_range_succ,Finset.sum_range_zero,zero_add, + LinearMap.add_apply,LinearMap.compl₁₂_apply,B] using hh + +end IntegerMarginal +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBoundsProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBoundsProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8b12a6462029a8ed18fcf74b809bc708e133827 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallBoundsProgram.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternProgram + +namespace OAI + +/-! # A binary program checking every stored coordinate bound -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def boundedValues (z : ℕ×List ℕ) : Bool := z.2.all (fun a => decide (a≤z.1)) + +def boundedValuesRealizer : Realizer boundedValues := + (composition (mapWith (composition (pair second first) leNat)) all).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,boundedValues]) + +theorem polynomial_boundedValues : PolynomialTime boundedValuesRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_mapWith (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) polynomial_leNat)) polynomial_all) + +lemma boundedValues_ofFn {n : ℕ} (U : ℕ) (v : Fin n → ℕ) : + boundedValues (U,List.ofFn v)=true ↔ ∀ i,v i≤U := by + simp only [boundedValues,List.all_eq_true,List.mem_ofFn,decide_eq_true_eq] + constructor + · intro h i + exact h (v i) ⟨i,rfl⟩ + · intro h a ha + obtain ⟨i,rfl⟩ := ha + exact h i + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +theorem boundedValues_views (z : SmallProfile small) (U : ℕ) : + (boundedValues (U,viewList small e z false) && + boundedValues (U,viewList small e z true))=true ↔ ∀ a,z a≤U := by + simp only [Bool.and_eq_true,viewList,boundedValues_ofFn] + constructor + · rintro ⟨hx,hy⟩ ⟨a,b⟩ + cases b + · simpa only [e.apply_symm_apply] using hx (e.symm a) + · simpa only [e.apply_symm_apply] using hy (e.symm a) + · intro h + exact ⟨fun i => h (e i,false),fun i => h (e i,true)⟩ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCellCatalogProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCellCatalogProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..13f124f3faea7df3d0d53402cce83c82e1506b37 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCellCatalogProgram.lean @@ -0,0 +1,115 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellIndexProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections + +namespace OAI + +/-! # Enumerating the actual small cells from binary margins -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def pairAt (z : ℕ×ℕ) : ℕ×ℕ := (z.2/z.1,z.2%z.1) + +def pairAtRealizer : Realizer pairAt := + composition (pair second first) (pair quotient remainder) + +lemma polynomial_pairAt : PolynomialTime pairAtRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_pair polynomial_quotient polynomial_remainder) + +def cellPairCodes : Realizer (fun z : List ℕ×List ℕ => + List.range (z.1.length*z.2.length)) := + composition (composition (pair (composition first listLength) + (composition second listLength)) multiply) range + +lemma polynomial_cellPairCodes : PolynomialTime cellPairCodes := by + apply polynomial_boundedRange (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_listLength) + (polynomial_composition polynomial_second polynomial_listLength)) polynomial_multiply) (X^2) + intro z + have hr : z.1.length≤weight z := + (list_length_le_weight z.1).trans (by rw [weight_prod]; omega) + have hc : z.2.length≤weight z := + (list_length_le_weight z.2).trans (by rw [weight_prod]; omega) + simpa only [Function.comp_apply,eval_pow,eval_mul,eval_X,pow_two] using Nat.mul_le_mul hr hc + +def cellPairs (z : List ℕ×List ℕ) : List (ℕ×ℕ) := + (List.range (z.1.length*z.2.length)).map (fun a => pairAt (z.2.length,a)) + +def cellPairsRealizer : Realizer cellPairs := + composition (pair (composition second listLength) cellPairCodes) (mapWith pairAtRealizer) + +theorem polynomial_cellPairs : PolynomialTime cellPairsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_listLength) polynomial_cellPairCodes) + (polynomial_mapWith polynomial_pairAt) + +lemma mem_cellPairs (r c : List ℕ) (i j : ℕ) : + (i,j)∈cellPairs (r,c) ↔ i z.1.1.1.getD z.2.1 0) := + composition (pair (composition (composition first first) first) + (composition second first)) (getDFast 0) + let C : Realizer (fun z : CellCatalogInput×(ℕ×ℕ) => z.1.1.2.getD z.2.2 0) := + composition (pair (composition (composition first first) second) + (composition second second)) (getDFast 0) + let U : Realizer (fun z : CellCatalogInput×(ℕ×ℕ) => z.1.2) := composition first second + exact (choose (composition (pair R U) less) (constant true) + (composition (pair C U) less)).congr (by + intro z + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,decide_eq_true_eq,smallCellTest] + split_ifs <;> simp_all) + +lemma polynomial_smallCellTest : PolynomialTime smallCellTestRealizer := by + unfold smallCellTestRealizer + apply polynomial_congr + apply polynomial_choose + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast 0)) + (polynomial_composition polynomial_first polynomial_second)) polynomial_less + · exact polynomial_constant true + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast 0)) + (polynomial_composition polynomial_first polynomial_second)) polynomial_less + +def smallCellCatalog (z : CellCatalogInput) : List (ℕ×ℕ) := + (cellPairs z.1).filter (fun a => smallCellTest (z,a)) + +def smallCellCatalogRealizer : Realizer smallCellCatalog := + composition (pair identity (composition first cellPairsRealizer)) (filterWith smallCellTestRealizer) + +theorem polynomial_smallCellCatalog : PolynomialTime smallCellCatalogRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_cellPairs)) + (polynomial_filterWith polynomial_smallCellTest) + +theorem mem_smallCellCatalog (r c : List ℕ) (U i j : ℕ) : + (i,j)∈smallCellCatalog ((r,c),U) ↔ + i z.2.idxOf z.1) := + indexOf (pairEqual natEqual natEqual) + +theorem polynomial_cellLookup : PolynomialTime cellLookupRealizer := + polynomial_indexOf (polynomial_pairEqual polynomial_natEqual polynomial_natEqual) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +def cellCatalog : List (ℕ×ℕ) := + List.ofFn (fun i => ((e i).val.1.val,(e i).val.2.val)) + +lemma cellCatalog_nodup : (cellCatalog small e).Nodup := by + apply List.nodup_ofFn.mpr + intro i j h + apply e.injective + apply Subtype.ext + exact Prod.ext (Fin.ext (congrArg Prod.fst h)) (Fin.ext (congrArg Prod.snd h)) + +lemma mem_cellCatalog (t : Fin m×Fin n) : + (t.1.val,t.2.val)∈cellCatalog small e ↔ small t.1 t.2=true := by + constructor + · intro h + obtain ⟨i,hi⟩ := List.mem_ofFn.mp h + have he : (e i).val=t := Prod.ext (Fin.ext (congrArg Prod.fst hi)) + (Fin.ext (congrArg Prod.snd hi)) + exact he ▸ (e i).property + · intro h + apply List.mem_ofFn.mpr + exact ⟨e.symm ⟨t,h⟩,by simp only [Equiv.apply_symm_apply]⟩ + +/-- Ordinary list search gives precisely the semantic small-cell index; +large crossing cells get the out-of-range index without extra cases. -/ +theorem cellCatalog_index (t : Fin m×Fin n) : + (cellCatalog small e).idxOf (t.1.val,t.2.val)=cellIndex small e t := by + by_cases ht : small t.1 t.2=true + · let i := e.symm ⟨t,ht⟩ + have hi : (cellCatalog small e)[i.val]'(by simp only [cellCatalog,List.length_ofFn]; exact i.isLt)= + (t.1.val,t.2.val) := by + simp only [cellCatalog,List.getElem_ofFn] + change ((e i).val.1.val,(e i).val.2.val)=(t.1.val,t.2.val) + simp only [i,Equiv.apply_symm_apply] + rw [←hi] + rw [(cellCatalog_nodup small e).idxOf_getElem] + exact (cellIndex_eq small e i t).mpr (by simp only [i,Equiv.apply_symm_apply]) + · rw [List.idxOf_eq_length ((mem_cellCatalog small e t).not.mpr ht)] + simp only [cellCatalog,List.length_ofFn,cellIndex,dite_eq_right ht] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallChainBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallChainBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d09681f16427245affc0beec7fc1cb0f47e4cec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallChainBudget.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphPoincareBudget + +namespace OAI + +/-! # Actual first-paper small-chain constants -/ + +namespace ContingencyTables + +lemma small_chain_poincare_constant (d : ℕ) (hd : 14 ≤ d) : + 128*(d:ℝ)^2*(770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6) ≤ (d:ℝ)^160 := by + have hcoef : (98560:ℝ) ≤ (d:ℝ)^34 := by + exact_mod_cast (show 98560 ≤ d^34 from + (by norm_num : 98560 ≤ 14^34).trans (Nat.pow_le_pow_left hd 34)) + calc + _ = 98560*(d:ℝ)^126 := by push_cast; ring + _ ≤ (d:ℝ)^34*(d:ℝ)^126 := mul_le_mul_of_nonneg_right hcoef (by positivity) + _ = _ := by ring + +lemma completion_rejection_lt_half (d : ℕ) (hd : 14 ≤ d) : + 40*(d:ℝ)^5/((d^12:ℕ):ℝ) < 1/2 := by + have hpos : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hp : (80:ℝ) < (d:ℝ)^7 := by + exact_mod_cast (show 80 < d^7 from + lt_of_lt_of_le (by norm_num : 80 < 14^7) (Nat.pow_le_pow_left hd 7)) + have hmul : 80*(d:ℝ)^5 < (d:ℝ)^12 := by + calc + _ < (d:ℝ)^7*(d:ℝ)^5 := mul_lt_mul_of_pos_right hp (pow_pos hpos 5) + _ = _ := by ring + push_cast + apply (div_lt_iff₀ (pow_pos hpos 12)).mpr + linarith + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallComplementProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallComplementProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..6af3916e7e91f21770e57a84c083941a59c1e90d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallComplementProgram.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallLineSumProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternProgram + +namespace OAI + +/-! # Binary execution of the complemented small column view -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def complementValues (z : ℕ×List ℕ) : List ℕ := z.2.map (fun a => z.1-a) + +def complementValuesRealizer : Realizer complementValues := mapWith subtract + +theorem polynomial_complementValues : PolynomialTime complementValuesRealizer := + polynomial_mapWith polynomial_subtract + +lemma complementValues_ofFn {n : ℕ} (U : ℕ) (v : Fin n → ℕ) : + complementValues (U,List.ofFn v)=List.ofFn (fun i => U-v i) := by + simp only [complementValues,List.map_ofFn,Function.comp_def] + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open PaddedCompletions ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +/-- The arithmetic complement needs no underflow assumption: it agrees +with the natural subtraction already present in the physical view. -/ +theorem lookupComplement_eq (B : Fin m → Fin n → ℕ) (z : SmallProfile small) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (i : Fin m) (j : Fin n) : + lookupView ((cellCatalog small e,complementValues (U,viewList small e z true)),(i.val,j.val))= + smallQ small B z i j := by + let v : SmallProfile small := fun a => U-z (a.1,true) + have hc : complementValues (U,viewList small e z true)=viewList small e v false := by + simp only [viewList,complementValues_ofFn] + rfl + rw [hc,lookupView_eq] + by_cases hs : small i j=true + · simp only [smallView,smallQ,hs,dite_true,v,hU ⟨(i,j),hs⟩] + · simp [smallView,smallQ,hs] + +theorem complementedColumnSum_eq (B : Fin m → Fin n → ℕ) (z : SmallProfile small) + (U : ℕ) (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) + (r : Fin m → ℕ) (j : Fin n) : + lineSum false (((cellCatalog small e,complementValues (U,viewList small e z true)), + List.ofFn r),j.val)=smallColumn small B (smallView small z true) j := by + have he : lineSum false (((cellCatalog small e,complementValues (U,viewList small e z true)), + List.ofFn r),j.val)=∑ i,smallQ small B z i j := by + apply lineSum_eq_sum false _ List.length_ofFn + intro i + exact lookupComplement_eq small e B z U hU i j + rw [he] + unfold smallColumn + apply Finset.sum_congr rfl + intro i _ + by_cases hs : small i j=true + · simp only [smallQ,smallView,hs,dite_true,ite_true] + · simp [smallQ,hs] + +theorem storedRowSum_eq (z : SmallProfile small) (c : Fin n → ℕ) (i : Fin m) : + lineSum true (((cellCatalog small e,viewList small e z false),List.ofFn c),i.val)= + smallRow small (smallView small z false) i := by + rw [rowSum_eq] + unfold smallRow + apply Finset.sum_congr rfl + intro j _ + by_cases hs : small i j=true + · simp only [hs,ite_true] + · simp [smallView,hs] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCompletionAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCompletionAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbbe31a07eec73345457787ebaeddb46033bea60 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCompletionAcceptance.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionAcceptance +import OAI.Combinatorics.ContingencyTables.Sampling.SmallChainBudget + +namespace OAI + +/-! # Half acceptance at the paper's actual padding scale -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] + +omit [Fintype I] [Fintype J] in +lemma padding_ge_twenty_dimension (d : ℕ) (hd : 14 ≤ d) : 20*d ≤ d^12 := by + have hp : 20 ≤ d^11 := + (by norm_num : 20 ≤ 14^11).trans (Nat.pow_le_pow_left hd 11) + calc + _ ≤ d^11*d := Nat.mul_le_mul_right d hp + _ = _ := by ring + +/-- Only the literal reference row and column are union bounded. -/ +theorem reference_acceptance_half + (R : Option I → ℕ) (P : Option J → ℕ) (D : Option I → Option J → ℤ) + (htotal : (∑ i,R i)=∑ j,P j) + (hzero : ∀ i j,D (some i) (some j)=0) + (d : ℕ) (hd : 14 ≤ d) + (hrows : Fintype.card (Option I) ≤ d) (hcols : Fintype.card (Option J) ≤ d) + (hcross : Fintype.card I+Fintype.card J+1 ≤ d) + (hrow : ∀ i,d^12 ≤ R i) (hcol : ∀ j,d^12 ≤ P j) + (hbound : ∀ i j,|D i j| ≤ (10*d:ℕ)) : + (Fintype.card (Table R P):ℝ)/2 ≤ Fintype.card (Accepted R P D) := by + have hpad := padding_ge_twenty_dimension d hd + have ht : 2*(10*d) ≤ d^12 := by omega + have hfour : 4*d ≤ d^12 := by omega + have hfrac := reference_acceptance R P D htotal hzero (d^12) d (10*d) + (by omega) hrows hcols hrow hcol hfour ht hbound + have hcrossR : (Fintype.card I+Fintype.card J+1:ℕ) ≤ (d:ℝ) := by exact_mod_cast hcross + have hu : ((Fintype.card I+Fintype.card J+1:ℕ):ℝ)* + (4*(10*d:ℕ)*(d:ℝ)^3/(d^12:ℕ)) ≤ 40*(d:ℝ)^5/(d^12:ℕ) := by + calc + _ ≤ (d:ℝ)*(4*(10*d:ℕ)*(d:ℝ)^3/(d^12:ℕ)) := + mul_le_mul_of_nonneg_right hcrossR (by positivity) + _ = _ := by push_cast; ring + have he := completion_rejection_lt_half d hd + have hc : (0:ℝ) < Fintype.card (Table R P) := by + exact_mod_cast Fintype.card_pos_iff.mpr (table_nonempty R P htotal) + have hh : (1/2:ℝ) ≤ (Fintype.card (Accepted R P D):ℝ)/Fintype.card (Table R P) := by linarith + have hm := (le_div_iff₀ hc).mp hh + linarith + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCoordinates.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..27108ac1449fd156aa2d713951df971ac5977c6b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCoordinates.lean @@ -0,0 +1,133 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextFibres +import OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration + +namespace OAI + +/-! # Actual row-major small-prefix coordinate splitting + +The retained prefix is precisely the earlier small cells. The remaining +ordinary cells all follow the next exposed cell, which is the condition +needed for the completion-retaining conditional repair injection. +-/ + +namespace ContingencyTables.SmallContextCoordinates + +open scoped Classical +open LargePairEnumeration BalancedFamily + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +lemma rowMajor_trichotomy (s t : I×J) : RowMajorBefore s t ∨ s=t ∨ RowMajorBefore t s := by + rcases lt_trichotomy s.1 t.1 with h|h|h + · exact Or.inl (Or.inl h) + · rcases lt_trichotomy s.2 t.2 with hc|hc|hc + · exact Or.inl (Or.inr ⟨h,hc⟩) + · exact Or.inr (Or.inl (Prod.ext h hc)) + · exact Or.inr (Or.inr (Or.inr ⟨h.symm,hc⟩)) + · exact Or.inr (Or.inr (Or.inl h)) + +abbrev Cells (small : I → J → Bool) := {a : I×J // small a.1 a.2=true} + +def Earlier (small : I → J → Bool) (s : I×J) := {a : Cells small // RowMajorBefore a.val s} +def Later (small : I → J → Bool) (s : I×J) := {a : Cells small // RowMajorBefore s a.val} + +noncomputable instance earlierFintype [Fintype I] [Fintype J] + (small : I → J → Bool) (s : I×J) : Fintype (Earlier small s) := by + unfold Earlier + infer_instance + +noncomputable instance laterFintype [Fintype I] [Fintype J] + (small : I → J → Bool) (s : I×J) : Fintype (Later small s) := by + unfold Later + infer_instance + +noncomputable def cellSplitEquiv (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) : + (Earlier small s ⊕ (Unit ⊕ Later small s)) ≃ Cells small where + toFun + | .inl a => a.val + | .inr (.inl _) => ⟨s,hs⟩ + | .inr (.inr a) => a.val + invFun a := + if hp : RowMajorBefore a.val s then .inl ⟨a,hp⟩ + else if he : a.val=s then .inr (.inl ()) + else .inr (.inr ⟨a,by + rcases rowMajor_trichotomy a.val s with h|h|h + · exact False.elim (hp h) + · exact False.elim (he h) + · exact h⟩) + left_inv a := by + cases a with + | inl a => + simp only [dite_eq_left a.property] + exact congrArg Sum.inl (Subtype.ext rfl) + | inr a => + cases a with + | inl a => + cases a + have hp : ¬RowMajorBefore s s := fun h => h.ne rfl + simp only [dite_eq_right hp,↓reduceDIte] + | inr a => + have hp : ¬RowMajorBefore a.val.val s := fun h => (h.trans a.property).ne rfl + have he : a.val.val≠s := a.property.ne.symm + simp only [dite_eq_right hp,dite_eq_right he] + exact congrArg Sum.inr (congrArg Sum.inr (Subtype.ext rfl)) + right_inv a := by + by_cases hp : RowMajorBefore a.val s + · simp only [dite_eq_left hp] + · by_cases he : a.val=s + · simp only [dite_eq_right hp,dite_eq_left he] + exact Subtype.ext he.symm + · simp only [dite_eq_right hp,dite_eq_right he] + +/-- Pack the prefix, special pair and suffix into the cell split. -/ +def splitPairEquiv (P T : Type u) : + ((P×Bool) ⊕ (Bool ⊕ (T×Bool))) ≃ (P ⊕ (Unit ⊕ T))×Bool where + toFun + | .inl (p,b) => (.inl p,b) + | .inr (.inl b) => (.inr (.inl ()),b) + | .inr (.inr (t,b)) => (.inr (.inr t),b) + invFun + | (.inl p,b) => .inl (p,b) + | (.inr (.inl _),b) => .inr (.inl b) + | (.inr (.inr t),b) => .inr (.inr (t,b)) + left_inv x := by rcases x with ⟨p,b⟩|b|⟨t,b⟩ <;> rfl + right_inv x := by rcases x with ⟨p|(_|t),b⟩ <;> rfl + +/-- The exact small-coordinate bijection required by physical context +transport. The suffix enumeration introduces no extra assignment. -/ +noncomputable def contextEquiv (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) {n : ℕ} (e : Fin n ≃ Later small s) (U : ℕ) : + ((Earlier small s×Bool) ⊕ Coordinates Bool (widths (fun _ : Fin n => U))) ≃ + SmallView (fun a : I×J => small a.1 a.2) := + (Equiv.sumCongr (Equiv.refl _) ((coordinateEquiv Bool (fun _ : Fin n => U)).trans + (Equiv.sumCongr (Equiv.refl Bool) (e.prodCongr (Equiv.refl Bool))))).trans + ((splitPairEquiv _ _).trans ((cellSplitEquiv small s hs).prodCongr (Equiv.refl Bool))) + +lemma contextEquiv_prefix (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) {n : ℕ} (e : Fin n ≃ Later small s) (U : ℕ) + (a : Earlier small s) (b : Bool) : + contextEquiv small s hs e U (.inl (a,b))=(a.val,b) := rfl + +lemma contextEquiv_special (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) {n : ℕ} (e : Fin n ≃ Later small s) (U : ℕ) (b : Bool) : + contextEquiv small s hs e U + (.inr ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inl b)))=(⟨s,hs⟩,b) := by + simp only [contextEquiv,Equiv.trans_apply,Equiv.sumCongr_apply,Sum.map_inr,Sum.map_inl,Equiv.refl_apply, + Equiv.apply_symm_apply] + rfl + +lemma contextEquiv_later (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) {n : ℕ} (e : Fin n ≃ Later small s) (U : ℕ) + (a : Fin n) (b : Bool) : + contextEquiv small s hs e U + (.inr ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inr (a,b))))=((e a).val,b) := by + simp only [contextEquiv,Equiv.trans_apply,Equiv.sumCongr_apply,Sum.map_inr, + Equiv.apply_symm_apply] + rfl + +end ContingencyTables.SmallContextCoordinates + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..42c255bc960c235c4e1a3a5fe2031e43606df5ba --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextCount.lean @@ -0,0 +1,213 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextFibres + +namespace OAI + +/-! # Literal contextual mass domination by repair + +Finite sums of the actual hard completion weights, including all large +completions, are compared by the concrete repair injection. +-/ + +namespace ContingencyTables.SmallContextFibres + +open scoped BigOperators Classical +open PaddedCompletions CompletionCounts FirstPaperProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + [LinearOrder I] [LinearOrder J] + +abbrev BalancedPairs (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (s : I×J) (σ : I×J → ℕ) (k : ℕ) := + (z : BalancedProfiles small B s σ k) × + CompletionFibre small B r rbar c cbar (naturalProfile z.val) + +noncomputable def balancedPairChild {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {s : I×J} {σ : I×J → ℕ} {k : ℕ} + (hs : small s.1 s.2=true) + (a : BalancedPairs small B r rbar c cbar s σ k) : + SmallResidualChild small r rbar c cbar s σ k := by + have hq := balanced_fibre_views a.2 a.1.property.1 + refine ⟨⟨⟨a.2.val.val.1,a.2.val.property.1,?_⟩,a.2.property.1,?_⟩,?_,?_⟩ + · simpa only [hq] using a.2.val.property.2 + · simpa only [hq] using a.2.property.2.1 + · intro i j hs hbefore + change a.2.val.val.1 i j=σ (i,j) + rw [(a.2.property.2.2.1 i j hs).1] + simpa only [smallView,hs,dite_eq_left] using a.1.property.2.1 i j hs hbefore + · change a.2.val.val.1 s.1 s.2=k + rw [(a.2.property.2.2.1 s.1 s.2 hs).1] + simpa only [smallView,hs,dite_eq_left] using a.1.property.2.2 + +omit [DecidableEq I] [DecidableEq J] in +lemma balancedPairChild_injective {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {s : I×J} {σ : I×J → ℕ} {k : ℕ} + (hs : small s.1 s.2=true) : + Function.Injective (balancedPairChild (B := B) (r := r) (rbar := rbar) + (c := c) (cbar := cbar) (σ := σ) (k := k) hs) := by + intro a b he + apply fibre_projection_injective small B r rbar c cbar + (fun z : BalancedProfiles small B s σ k => naturalProfile z.val) + (fun x y h => Subtype.ext (naturalProfile_injective small B h)) + (fun z => naturalProfile_bounded z.val) + apply Subtype.ext + have hx := congrArg (fun T : SmallResidualChild small r rbar c cbar s σ k => T.val.val.val) he + apply Prod.ext hx + rw [←balanced_fibre_views a.2 a.1.property.1,←balanced_fibre_views b.2 b.1.property.1] + exact hx + +omit [DecidableEq I] [DecidableEq J] in +/-- Every residual table has exactly one balanced retained profile and +one large completion, provided the declared capacities exclude none. -/ +lemma balancedPairChild_surjective {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {s : I×J} {σ : I×J → ℕ} {k : ℕ} + (hs : small s.1 s.2=true) + (hcap : ∀ T : ResidualTables small r c rbar cbar, ∀ i j, T.val.val i j ≤ B i j) : + Function.Surjective (balancedPairChild (B := B) (r := r) (rbar := rbar) + (c := c) (cbar := cbar) (σ := σ) (k := k) hs) := by + intro T + let z : BoundedProfile small B := fun u => + if u.2 then ⟨B u.1.val.1 u.1.val.2-T.val.val.val u.1.val.1 u.1.val.2, + Nat.lt_succ_of_le (Nat.sub_le _ _)⟩ + else ⟨T.val.val.val u.1.val.1 u.1.val.2, + Nat.lt_succ_of_le (hcap T.val _ _)⟩ + have hzfalse (i : I) (j : J) (hij : small i j=true) : + smallView small (naturalProfile z) false i j=T.val.val.val i j := by + simp only [smallView,hij,dite_eq_left,naturalProfile,z,Bool.false_eq_true,↓reduceIte] + have hztrue (i : I) (j : J) (hij : small i j=true) : + smallQ small B (naturalProfile z) i j=T.val.val.val i j := by + simp only [smallQ,hij,dite_eq_left,naturalProfile,z,↓reduceIte] + exact Nat.sub_sub_self (hcap T.val i j) + have hbal : ∀ i j, smallView small (naturalProfile z) false i j= + smallQ small B (naturalProfile z) i j := by + intro i j + cases hij : small i j + · simp only [smallView,smallQ,hij,Bool.false_eq_true,↓reduceDIte] + · rw [hzfalse i j hij,hztrue i j hij] + let w : BalancedProfiles small B s σ k := ⟨z,hbal, + (fun i j hij hbefore => by rw [hzfalse i j hij]; exact T.property.1 i j hij hbefore), + by rw [hzfalse s.1 s.2 hs]; exact T.property.2⟩ + let Z : CompletionFibre small B r rbar c cbar (naturalProfile w.val) := + ⟨⟨(T.val.val.val,T.val.val.val),T.val.val.property⟩,T.val.property.1,T.val.property.2, + (fun i j hij => ⟨by + change T.val.val.val i j=naturalProfile z (⟨(i,j),hij⟩,false) + simpa only [smallView,hij,dite_eq_left] using (hzfalse i j hij).symm,by + change T.val.val.val i j=B i j-naturalProfile z (⟨(i,j),hij⟩,true) + simpa only [smallQ,hij,dite_eq_left] using (hztrue i j hij).symm⟩), + (fun _ _ _ => rfl),(fun i j _ => hcap T.val i j)⟩ + refine ⟨⟨w,Z⟩,?_⟩ + apply Subtype.ext + apply Subtype.ext + apply Subtype.ext + rfl + +/-- A contextual child mass is the exact cardinality of full residual +tables in that child, including all large completion multiplicities. -/ +theorem balanced_mass_eq_child_card (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (s : I×J) (σ : I×J → ℕ) (k : ℕ) + (hs : small s.1 s.2=true) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) : + (∑ z : BalancedProfiles small B s σ k, + hardMarginal small B r c L (naturalProfile z.val))= + (Fintype.card (SmallResidualChild small r (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) s σ k):ℝ) := by + rw [sum_hard_eq_sigma_card small B r c L + (fun z : BalancedProfiles small B s σ k => naturalProfile z.val) + (fun z => naturalProfile_bounded z.val)] + exact_mod_cast Fintype.card_congr (Equiv.ofBijective (balancedPairChild hs) + ⟨balancedPairChild_injective hs,balancedPairChild_surjective hs hcap⟩) + +noncomputable def defectPairContext {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {s t : I×J} {σ : I×J → ℕ} {l : ℕ} + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (a : (z : DefectProfiles small B s t σ l) × + CompletionFibre small B r rbar c cbar (naturalProfile z.val)) : + SmallJointDefectContext small r rbar c cbar s t σ l := by + refine ⟨⟨a.2.val,defect_fibre_views a.2 hs ht a.1.property.1, + a.2.property.1,a.2.property.2.1⟩,?_,?_⟩ + · intro i j hij hbefore + rw [(a.2.property.2.2.1 i j hij).1] + simpa only [smallView,hij,dite_eq_left] using a.1.property.2.1 i j hij hbefore + · rw [(a.2.property.2.2.1 s.1 s.2 hs).1] + simpa only [smallView,hs,dite_eq_left] using a.1.property.2.2 + +lemma defectPairContext_injective {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {s t : I×J} {σ : I×J → ℕ} {l : ℕ} + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) : + Function.Injective (defectPairContext (B := B) (r := r) (rbar := rbar) + (c := c) (cbar := cbar) (σ := σ) (l := l) hs ht) := by + intro a b he + apply fibre_projection_injective small B r rbar c cbar + (fun z : DefectProfiles small B s t σ l => naturalProfile z.val) + (fun x y h => Subtype.ext (naturalProfile_injective small B h)) + (fun z => naturalProfile_bounded z.val) + exact congrArg (fun Z : SmallJointDefectContext small r rbar c cbar s t σ l => Z.val.val) he + +/-- Conditional repair domination for the actual weighted finite sums. -/ +theorem conditional_defect_mass_le + (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) + (L : ℕ) (s t : I×J) (σ : I×J → ℕ) (l : ℕ) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) (hst : RowMajorBefore s t) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) : + (∑ z : DefectProfiles small B s t σ l, + hardMarginal small B r c L (naturalProfile z.val)) ≤ + ∑ z : BalancedProfiles small B s σ (l-1+if t.1=s.1 then 1 else 0), + hardMarginal small B r c L (naturalProfile z.val) := by + rw [sum_hard_eq_sigma_card small B r c L + (fun z : DefectProfiles small B s t σ l => naturalProfile z.val) + (fun z => naturalProfile_bounded z.val), + balanced_mass_eq_child_card small B r c L s σ _ hs hcap] + exact_mod_cast (Fintype.card_le_of_injective (defectPairContext hs ht) + (defectPairContext_injective hs ht)).trans + (smallContext_card_le small r _ c _ s t σ l hs ht hst) + +omit [DecidableEq I] [DecidableEq J] [LinearOrder I] [LinearOrder J] in +/-- The manuscript's actual capacity excludes no residual table. -/ +theorem paper_residual_capacity (r : I → ℕ) (c : J → ℕ) (d L U : ℕ) + (hd : Fintype.card I*Fintype.card J ≤ d) + (T : ResidualTables (firstPaperSmall r c U) r c + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L)) (i : I) (j : J) : + T.val.val i j ≤ paperCapacity (firstPaperSmall r c U) r d L U i j := by + let small := firstPaperSmall r c U + change T.val.val i j ≤ paperCapacity small r d L U i j + cases hs : small i j + · have he := entry_le_total T.val.property i j + have hcount := (large_count_le_dimension small).trans hd + have heq : (∑ k, (r k+rowLargeCount small k*L))= + (∑ k, r k)+(∑ k, rowLargeCount small k)*L := by + rw [Finset.sum_add_distrib,Finset.sum_mul] + rw [heq] at he + have hb := Nat.mul_le_mul_right L hcount + simp only [paperCapacity,hs,Bool.false_eq_true,↓reduceIte] + omega + · have hr := (entry_le_smallRow small T.val.val i j hs).trans (T.property.1 i) + have hc := (entry_le_smallColumn small T.val.val i j hs).trans (T.property.2 j) + have hinc : r i omega + +/-- The literal first-paper contextual repair bound has no capacity +hypothesis: its formal C excludes no full padded completion. -/ +theorem firstPaper_conditional_defect_mass_le (r : I → ℕ) (c : J → ℕ) + (s t : I×J) (σ : I×J → ℕ) (l : ℕ) + (hs : paperSmall r c s.1 s.2=true) (ht : paperSmall r c t.1 t.2=true) + (hst : RowMajorBefore s t) : + let d := dimensionAllowance (I := I) (J := J) + let small := paperSmall r c + let B := paperCapacity small r d (d^12) (d^20) + (∑ z : DefectProfiles small B s t σ l, + hardMarginal small B r c (d^12) (naturalProfile z.val)) ≤ + ∑ z : BalancedProfiles small B s σ (l-1+if t.1=s.1 then 1 else 0), + hardMarginal small B r c (d^12) (naturalProfile z.val) := by + dsimp only + apply conditional_defect_mass_le _ _ r c _ s t σ l hs ht hst + exact paper_residual_capacity r c _ _ _ dimension_le_allowance + +end ContingencyTables.SmallContextFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3d8c513181eb2d86cec7d5f4e602fe7a3cb20cc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextEnumeration.lean @@ -0,0 +1,254 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCoordinates +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextChildren +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCount + +namespace OAI + +/-! # Physical enumeration of a balanced exposure child + +Every later small-cell choice occurs once, with the retained prefix fixed. +The large-cell capacities remain the original capacities throughout. +-/ + +namespace ContingencyTables.SmallContextEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres +open LargePairEnumeration BalancedEnumeration BalancedFamily IntegerWeightedTransport +open FirstPaperContextTransport FirstPaperPhysicalMarginal FirstPaperProfiles + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +noncomputable def splitChoices (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + (y : Later small s → Fin (U+1)) : Cells small → Fin (U+1) := + (Sum.elim τ (Sum.elim (fun _ : Unit => k) y)) ∘ (cellSplitEquiv small s hs).symm + +lemma splitChoices_prefix (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + (y : Later small s → Fin (U+1)) (a : Earlier small s) : + splitChoices small s hs U τ k y a.val=τ a := by + change Sum.elim τ (Sum.elim (fun _ : Unit => k) y) + ((cellSplitEquiv small s hs).symm ((cellSplitEquiv small s hs) (.inl a)))=τ a + rw [Equiv.symm_apply_apply] + rfl + +lemma splitChoices_special (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + (y : Later small s → Fin (U+1)) : + splitChoices small s hs U τ k y ⟨s,hs⟩=k := by + change Sum.elim τ (Sum.elim (fun _ : Unit => k) y) + ((cellSplitEquiv small s hs).symm ((cellSplitEquiv small s hs) (.inr (.inl ()))))=k + rw [Equiv.symm_apply_apply] + rfl + +lemma splitChoices_later (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + (y : Later small s → Fin (U+1)) (a : Later small s) : + splitChoices small s hs U τ k y a.val=y a := by + change Sum.elim τ (Sum.elim (fun _ : Unit => k) y) + ((cellSplitEquiv small s hs).symm ((cellSplitEquiv small s hs) (.inr (.inr a))))=y a + rw [Equiv.symm_apply_apply] + rfl + +noncomputable def choiceProfile (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (x : Cells small → Fin (U+1)) : BoundedProfile small B := fun a => + ⟨if a.2 then U-(x a.1).val else (x a.1).val,by + rw [hB _ _ a.1.property] + cases a.2 + · exact (x a.1).isLt + · exact Nat.lt_succ_of_le (Nat.sub_le _ _)⟩ + +omit [LinearOrder I] [LinearOrder J] in +lemma choiceProfile_balanced (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) (x : Cells small → Fin (U+1)) : + ∀ i j, smallView small (naturalProfile (choiceProfile small B U hB x)) false i j= + smallQ small B (naturalProfile (choiceProfile small B U hB x)) i j := by + intro i j + cases hij : small i j + · simp only [smallView,smallQ,hij,Bool.false_eq_true,↓reduceDIte] + · simp only [smallView,smallQ,hij,dite_eq_left,naturalProfile,choiceProfile, + Bool.false_eq_true,↓reduceIte,hB i j hij] + exact (Nat.sub_sub_self (Nat.le_of_lt_succ (x ⟨(i,j),hij⟩).isLt)).symm + +noncomputable def prefixChoices (small : I → J → Bool) (s : I×J) + (σ : I×J → ℕ) (U : ℕ) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) : Earlier small s → Fin (U+1) := + fun a => ⟨σ a.val.val,Nat.lt_succ_of_le (hσ a)⟩ + +noncomputable def balancedContext (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) (k : Fin (U+1)) + (y : Later small s → Fin (U+1)) : BalancedProfiles small B s σ k.val := by + let x := splitChoices small s hs U (prefixChoices small s σ U hσ) k y + refine ⟨choiceProfile small B U hB x,choiceProfile_balanced small B U hB x,?_,?_⟩ + · intro i j hij hbefore + simp only [smallView,hij,dite_eq_left,naturalProfile,choiceProfile,Bool.false_eq_true,↓reduceIte] + change (x ⟨(i,j),hij⟩).val=σ (i,j) + exact congrArg Fin.val (splitChoices_prefix small s hs U _ k y ⟨⟨(i,j),hij⟩,hbefore⟩) + · simp only [smallView,hs,dite_eq_left,naturalProfile,choiceProfile,Bool.false_eq_true,↓reduceIte] + change (x ⟨s,hs⟩).val=k.val + exact congrArg Fin.val (splitChoices_special small s hs U _ k y) + +lemma balanced_false_determines (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) (k : ℕ) + (x y : BalancedProfiles small B s σ k) + (he : ∀ a : Cells small, naturalProfile x.val (a,false)=naturalProfile y.val (a,false)) : + x=y := by + apply Subtype.ext + apply naturalProfile_injective small B + funext a + rcases a with ⟨a,b⟩ + cases b + · exact he a + · have hx := x.property.1 a.val.1 a.val.2 + have hy := y.property.1 a.val.1 a.val.2 + simp only [smallView,smallQ,a.property,dite_eq_left] at hx hy + change naturalProfile x.val (a,false)=B a.val.1 a.val.2-naturalProfile x.val (a,true) at hx + change naturalProfile y.val (a,false)=B a.val.1 a.val.2-naturalProfile y.val (a,true) at hy + have hbX := naturalProfile_bounded x.val (a,true) + have hbY := naturalProfile_bounded y.val (a,true) + dsimp only at hbX hbY + have he' := he a + omega + +noncomputable def suffixChoices (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) (k : Fin (U+1)) + (z : BalancedProfiles small B s σ k.val) : Later small s → Fin (U+1) := fun a => + ⟨naturalProfile z.val (a.val,false),by + have h := naturalProfile_bounded z.val (a.val,false) + rw [hB _ _ a.val.property] at h + exact Nat.lt_succ_of_le h⟩ + +noncomputable def balancedContextEquiv (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) (k : Fin (U+1)) : + (Later small s → Fin (U+1)) ≃ BalancedProfiles small B s σ k.val where + toFun := balancedContext small B s hs σ U hB hσ k + invFun := suffixChoices small B s σ U hB k + left_inv y := by + funext a + apply Fin.ext + change (splitChoices small s hs U (prefixChoices small s σ U hσ) k y a.val).val=(y a).val + rw [splitChoices_later] + right_inv z := by + apply balanced_false_determines small B s σ k.val + intro a + obtain ⟨q,rfl⟩ := (cellSplitEquiv small s hs).surjective a + rcases q with p|(_|t) + · change (splitChoices small s hs U (prefixChoices small s σ U hσ) k + (suffixChoices small B s σ U hB k z) p.val).val=naturalProfile z.val (p.val,false) + rw [splitChoices_prefix] + simpa only [prefixChoices,smallView,p.val.property,dite_eq_left] using + (z.property.2.1 _ _ p.val.property p.property).symm + · change (splitChoices small s hs U (prefixChoices small s σ U hσ) k + (suffixChoices small B s σ U hB k z) ⟨s,hs⟩).val=naturalProfile z.val (⟨s,hs⟩,false) + rw [splitChoices_special] + simpa only [smallView,hs,dite_eq_left] using z.property.2.2.symm + · change (splitChoices small s hs U (prefixChoices small s σ U hσ) k + (suffixChoices small B s σ U hB k z) t.val).val=naturalProfile z.val (t.val,false) + rw [splitChoices_later] + rfl + +def prefixRaw (small : I → J → Bool) (s : I×J) (σ : I×J → ℕ) (U : ℕ) : + Earlier small s×Bool → ℕ := fun a => if a.2 then U-σ a.1.val.val else σ a.1.val.val + +noncomputable def reindexChoices {n U : ℕ} (small : I → J → Bool) (s : I×J) + (e : Fin n ≃ Later small s) : + (Fin n → Fin (U+1)) ≃ (Later small s → Fin (U+1)) where + toFun y := y ∘ e.symm + invFun y := y ∘ e + left_inv y := by funext a; exact congrArg y (e.symm_apply_apply a) + right_inv y := by funext a; exact congrArg y (e.apply_symm_apply a) + +lemma embedding_coordinate_apply {n : ℕ} (M : Fin n → ℕ) (z : Bool → ℕ) + (q : Assignments (widths M)) (a : Coordinates Bool (widths M)) : + embedding (widths M) z q a= + joinedProfile M z ((assignmentEquiv M) q) (coordinateEquiv Bool M a) := by + have h := embedding_coordinate M z ((assignmentEquiv M) q) a + simpa only [Equiv.symm_apply_apply] using h + +lemma physical_embedding_eq (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) (k : Fin (U+1)) + {n : ℕ} (e : Fin n ≃ Later small s) (q : Assignments (widths (fun _ : Fin n => U))) : + (Sum.elim (prefixRaw small s σ U) + (embedding (widths (fun _ : Fin n => U)) (childProfile U k.val) q)) ∘ + (contextEquiv small s hs e U).symm= + naturalProfile (balancedContext small B s hs σ U hB hσ k + ((reindexChoices small s e) ((assignmentEquiv (fun _ : Fin n => U)) q))).val := by + funext a + obtain ⟨v,rfl⟩ := (contextEquiv small s hs e U).surjective a + simp only [Function.comp_apply,Equiv.symm_apply_apply] + cases v with + | inl p => + rcases p with ⟨p,b⟩ + rw [contextEquiv_prefix] + change (if b then U-σ p.val.val else σ p.val.val)= + if b then U-(splitChoices small s hs U (prefixChoices small s σ U hσ) k _ p.val).val + else (splitChoices small s hs U (prefixChoices small s σ U hσ) k _ p.val).val + rw [splitChoices_prefix] + rfl + | inr v => + obtain ⟨w,rfl⟩ := (coordinateEquiv Bool (fun _ : Fin n => U)).symm.surjective v + cases w with + | inl b => + rw [contextEquiv_special] + simp only [Sum.elim_inr] + rw [embedding_coordinate_apply,Equiv.apply_symm_apply] + change (if b then U-k.val else k.val)= + if b then U-(splitChoices small s hs U (prefixChoices small s σ U hσ) k _ ⟨s,hs⟩).val + else (splitChoices small s hs U (prefixChoices small s σ U hσ) k _ ⟨s,hs⟩).val + rw [splitChoices_special] + | inr p => + rcases p with ⟨i,b⟩ + rw [contextEquiv_later] + simp only [Sum.elim_inr] + rw [embedding_coordinate_apply,Equiv.apply_symm_apply] + change (if b then U-((assignmentEquiv (fun _ : Fin n => U)) q i).val + else ((assignmentEquiv (fun _ : Fin n => U)) q i).val)= + if b then U-(splitChoices small s hs U (prefixChoices small s σ U hσ) k _ (e i).val).val + else (splitChoices small s hs U (prefixChoices small s σ U hσ) k _ (e i).val).val + rw [splitChoices_later] + change (if b then U-((assignmentEquiv (fun _ : Fin n => U)) q i).val + else ((assignmentEquiv (fun _ : Fin n => U)) q i).val)= + if b then U-((assignmentEquiv (fun _ : Fin n => U)) q (e.symm (e i))).val + else ((assignmentEquiv (fun _ : Fin n => U)) q (e.symm (e i))).val + rw [Equiv.symm_apply_apply] + +variable [Fintype I] [Fintype J] + +/-- The recursive transport child is the literal sum over physical +bounded balanced profiles, retaining every large completion multiplicity. -/ +theorem eliminate_context_eq_balanced_mass (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) (k : Fin (U+1)) + {n : ℕ} (e : Fin n ≃ Later small s) : + eliminate (widths (fun _ : Fin n => U)) + (contextHard small B r c L _ (contextEquiv small s hs e U) (prefixRaw small s σ U)) + (childProfile U k.val)= + ∑ z : BalancedProfiles small B s σ k.val, hardMarginal small B r c L (naturalProfile z.val) := by + rw [eliminate_eq_sum] + apply Fintype.sum_equiv (((assignmentEquiv (fun _ : Fin n => U)).trans + (reindexChoices small s e)).trans (balancedContextEquiv small B s hs σ U hB hσ k)) + intro q + unfold contextHard + rw [physical_embedding_eq small B s hs σ U hB hσ k e q] + rfl + +end ContingencyTables.SmallContextEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c9980d60a85f033be9fc2d5304308cadef8ba8b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallContextFibres.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalCompletionFibres + +namespace OAI + +/-! # Actual small-prefix fibres and conditional repair + +Only small cells in the row-major prefix are fixed. Large completions +remain free and retain their full counting multiplicity. +-/ + +namespace ContingencyTables.SmallContextFibres + +open scoped BigOperators Classical +open PaddedCompletions CompletionCounts FirstPaperProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal LargePairEnumeration + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +abbrev BoundedProfile (small : I → J → Bool) (B : I → J → ℕ) := + (u : SmallView (fun a : I×J => small a.1 a.2)) → Fin (B u.1.val.1 u.1.val.2+1) + +def naturalProfile {small : I → J → Bool} {B : I → J → ℕ} + (z : BoundedProfile small B) : SmallProfile small := fun u => (z u).val + +omit [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] in +lemma naturalProfile_injective (small : I → J → Bool) (B : I → J → ℕ) : + Function.Injective (naturalProfile (small := small) (B := B)) := by + intro x y he + funext u + exact Fin.ext (congrFun he u) + +omit [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] in +lemma naturalProfile_bounded {small : I → J → Bool} {B : I → J → ℕ} + (z : BoundedProfile small B) (u) : naturalProfile z u ≤ B u.1.val.1 u.1.val.2 := + Nat.le_of_lt_succ (z u).isLt + +noncomputable def smallQ (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (i : I) (j : J) : ℕ := + if hs : small i j=true then B i j-z (⟨(i,j),hs⟩,true) else 0 + +def SmallPrefix [LT I] [LT J] (small : I → J → Bool) (s : I×J) + (σ : I×J → ℕ) (X : I → J → ℕ) : Prop := + ∀ i j, small i j=true → RowMajorBefore (i,j) s → X i j=σ (i,j) + +def BalancedProfiles [LT I] [LT J] (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) (k : ℕ) := + {z : BoundedProfile small B // + (∀ i j, smallView small (naturalProfile z) false i j=smallQ small B (naturalProfile z) i j) ∧ + SmallPrefix small s σ (smallView small (naturalProfile z) false) ∧ + smallView small (naturalProfile z) false s.1 s.2=k} + +def DefectProfiles [LT I] [LT J] (small : I → J → Bool) (B : I → J → ℕ) + (s t : I×J) (σ : I×J → ℕ) (l : ℕ) := + {z : BoundedProfile small B // + IsDefect (smallView small (naturalProfile z) false) (smallQ small B (naturalProfile z)) s t ∧ + SmallPrefix small s σ (smallView small (naturalProfile z) false) ∧ + smallView small (naturalProfile z) false s.1 s.2=l-1} + +def SmallResidualChild [LT I] [LT J] + (small : I → J → Bool) (r rbar : I → ℕ) (c cbar : J → ℕ) + (s : I×J) (σ : I×J → ℕ) (k : ℕ) := + {T : ResidualTables small r c rbar cbar // + SmallPrefix small s σ T.val.val ∧ T.val.val s.1 s.2=k} + +def SmallJointDefectContext [LT I] [LT J] + (small : I → J → Bool) (r rbar : I → ℕ) (c cbar : J → ℕ) + (s t : I×J) (σ : I×J → ℕ) (l : ℕ) := + {Z : JointDefect small r c rbar cbar s t // + SmallPrefix small s σ Z.val.val.1 ∧ Z.val.val.1 s.1 s.2=l-1} + +noncomputable instance balancedProfilesFintype [LT I] [LT J] + (small : I → J → Bool) (B : I → J → ℕ) (s : I×J) (σ : I×J → ℕ) (k : ℕ) : + Fintype (BalancedProfiles small B s σ k) := by unfold BalancedProfiles; infer_instance + +noncomputable instance defectProfilesFintype [LT I] [LT J] + (small : I → J → Bool) (B : I → J → ℕ) (s t : I×J) (σ : I×J → ℕ) (l : ℕ) : + Fintype (DefectProfiles small B s t σ l) := by unfold DefectProfiles; infer_instance + +noncomputable instance smallResidualChildFintype [LT I] [LT J] + (small : I → J → Bool) (r rbar : I → ℕ) (c cbar : J → ℕ) + (s : I×J) (σ : I×J → ℕ) (k : ℕ) : + Fintype (SmallResidualChild small r rbar c cbar s σ k) := by + unfold SmallResidualChild + infer_instance + +noncomputable instance smallJointDefectContextFintype [LT I] [LT J] + (small : I → J → Bool) (r rbar : I → ℕ) (c cbar : J → ℕ) + (s t : I×J) (σ : I×J → ℕ) (l : ℕ) : + Fintype (SmallJointDefectContext small r rbar c cbar s t σ l) := by + unfold SmallJointDefectContext + infer_instance + +/-- The contextual injection fixes only earlier small entries. -/ +theorem smallContext_card_le [LinearOrder I] [LinearOrder J] + (small : I → J → Bool) (r rbar : I → ℕ) (c cbar : J → ℕ) + (s t : I×J) (σ : I×J → ℕ) (l : ℕ) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) (hst : RowMajorBefore s t) : + Fintype.card (SmallJointDefectContext small r rbar c cbar s t σ l) ≤ + Fintype.card (SmallResidualChild small r rbar c cbar s σ + (l-1+if t.1=s.1 then 1 else 0)) := by + let f : SmallJointDefectContext small r rbar c cbar s t σ l → + SmallResidualChild small r rbar c cbar s σ (l-1+if t.1=s.1 then 1 else 0) := + fun Z => ⟨jointRepair hs ht Z.val,(fun i j hij hbefore => by + change repairMatrix Z.val.val.val.1 s t i j=σ (i,j) + rw [repairMatrix_prefix Z.val.property.1 hst hbefore] + exact Z.property.1 i j hij hbefore),by + change repairMatrix Z.val.val.val.1 s t s.1 s.2=_ + rw [repairMatrix_special Z.val.property.1,Z.property.2]⟩ + apply Fintype.card_le_of_injective f + intro X Y he + apply Subtype.ext + apply jointRepair_injective hs ht + exact congrArg Subtype.val he + +omit [DecidableEq I] [DecidableEq J] in +/-- A balanced small profile is balanced as a full pair of views. -/ +lemma balanced_fibre_views {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {z : SmallProfile small} + (Z : CompletionFibre small B r rbar c cbar z) + (hb : ∀ i j, smallView small z false i j=smallQ small B z i j) : + Z.val.val.1=Z.val.val.2 := by + funext i j + cases hs : small i j + · exact Z.property.2.2.2.1 i j hs + · obtain ⟨hx,hq⟩ := Z.property.2.2.1 i j hs + rw [hx,hq] + simpa only [smallView,smallQ,hs,dite_eq_left] using hb i j + +/-- The defect equation extends over the unchanged large completion. -/ +lemma defect_fibre_views {small : I → J → Bool} {B : I → J → ℕ} + {r rbar : I → ℕ} {c cbar : J → ℕ} {z : SmallProfile small} {s t : I×J} + (Z : CompletionFibre small B r rbar c cbar z) + (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) + (hd : IsDefect (smallView small z false) (smallQ small B z) s t) : + IsDefect Z.val.val.1 Z.val.val.2 s t := by + refine ⟨hd.1,?_⟩ + intro i j + cases hij : small i j + · have hns : ¬(i=s.1 ∧ j=s.2) := by rintro ⟨rfl,rfl⟩; rw [hs] at hij; contradiction + have hnt : ¬(i=t.1 ∧ j=t.2) := by rintro ⟨rfl,rfl⟩; rw [ht] at hij; contradiction + rw [←Z.property.2.2.2.1 i j hij] + simp only [transferInt,hns,hnt,↓reduceIte,sub_zero,add_zero] + · obtain ⟨hx,hq⟩ := Z.property.2.2.1 i j hij + have he := hd.2 i j + simp only [smallView,smallQ,hij,dite_eq_left,transferInt] at he + simpa only [transferInt,hx,hq] using he + +omit [DecidableEq I] [DecidableEq J] in +/-- Summing the literal hard weights is exactly counting the dependent +union of completion fibres. -/ +theorem sum_hard_eq_sigma_card {S : Type*} [Fintype S] + (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) + (L : ℕ) (p : S → SmallProfile small) + (hbox : ∀ s u, p s u ≤ B u.1.val.1 u.1.val.2) : + (∑ s, hardMarginal small B r c L (p s))= + (Fintype.card ((s : S) × CompletionFibre small B r + (fun i => r i+rowLargeCount small i*L) c + (fun j => c j+columnLargeCount small j*L) (p s)):ℝ) := by + simp_rw [hardMarginal_eq_fibre_card small B r c L _ (hbox _)] + rw [Fintype.card_sigma] + simp only [Nat.cast_sum] + +end ContingencyTables.SmallContextFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCoordinateSums.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCoordinateSums.lean new file mode 100644 index 0000000000000000000000000000000000000000..95cb20bc409052b27e5935444997948b86671ecb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallCoordinateSums.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeObservables +import OAI.Combinatorics.ContingencyTables.Transport.RectangleCompletions +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCoordinates + +namespace OAI + +/-! # Selected doubled-coordinate sums are the physical small margins -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles PaddedCompletions +open IntegerWeightedTransport CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def selectedRow (small : I → J → Bool) (z : SmallProfile small) (b : Bool) (i : I) : ℕ := + ∑ a,if a.1.val.1=i ∧ a.2=b then z a else 0 + +noncomputable def selectedColumn (small : I → J → Bool) (z : SmallProfile small) (b : Bool) (j : J) : ℕ := + ∑ a,if a.1.val.2=j ∧ a.2=b then z a else 0 + +omit [LinearOrder I] [LinearOrder J] in +lemma selected_bool_sum (small : I → J → Bool) (z : SmallProfile small) (b : Bool) + (p : Cells small → Prop) : + (∑ a : Cells small×Bool,if p a.1 ∧ a.2=b then z a else 0)= + ∑ a : Cells small,if p a then z (a,b) else 0 := by + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + cases b <;> simp + +omit [LinearOrder I] [LinearOrder J] in +lemma cell_sum_as_matrix (small : I → J → Bool) (z : SmallProfile small) (b : Bool) + (p : I×J → Prop) : + (∑ a : Cells small,if p a.val then z (a,b) else 0)= + ∑ a : I×J,if p a then smallView small z b a.1 a.2 else 0 := by + have hzero (a : I×J) (ha : ¬small a.1 a.2=true) : + (if p a then smallView small z b a.1 a.2 else 0)=0 := by + by_cases hp : p a + · simp only [hp,ite_true,smallView,dite_eq_right ha] + · rw [ite_eq_right hp] + have he := sum_subtype_eq_of_zero (fun a : I×J => small a.1 a.2=true) + (fun a => if p a then smallView small z b a.1 a.2 else 0) hzero + calc + _ = ∑ a : Cells small,if p a.val then smallView small z b a.val.1 a.val.2 else 0 := by + apply Finset.sum_congr rfl + intro a _ + simp only [smallView,a.property,dite_eq_left] + _ = _ := by + convert he using 1 + congr 2 + exact Subsingleton.elim _ _ + +omit [LinearOrder J] in +lemma selectedRow_eq (small : I → J → Bool) (z : SmallProfile small) (b : Bool) (i : I) : + selectedRow small z b i=∑ j,smallView small z b i j := by + unfold selectedRow + have hb : (∑ a,if a.1.val.1=i ∧ a.2=b then z a else 0)= + ∑ a : Cells small,if a.val.1=i then z (a,b) else 0 := by + convert selected_bool_sum small z b (fun a => a.val.1=i) using 1 + all_goals + congr 4 + first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + rw [hb] + have hc : (∑ a : Cells small,if a.val.1=i then z (a,b) else 0)= + ∑ a : I×J,if a.1=i then smallView small z b a.1 a.2 else 0 := by + convert cell_sum_as_matrix small z b (fun a => a.1=i) using 1 + all_goals + congr 4 + first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + rw [hc,Fintype.sum_prod_type] + simp_rw [Finset.sum_ite_irrel] + simp + +omit [LinearOrder I] in +lemma selectedColumn_eq (small : I → J → Bool) (z : SmallProfile small) (b : Bool) (j : J) : + selectedColumn small z b j=∑ i,smallView small z b i j := by + unfold selectedColumn + have hb : (∑ a,if a.1.val.2=j ∧ a.2=b then z a else 0)= + ∑ a : Cells small,if a.val.2=j then z (a,b) else 0 := by + convert selected_bool_sum small z b (fun a => a.val.2=j) using 1 + all_goals + congr 4 + first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + rw [hb] + have hc : (∑ a : Cells small,if a.val.2=j then z (a,b) else 0)= + ∑ a : I×J,if a.2=j then smallView small z b a.1 a.2 else 0 := by + convert cell_sum_as_matrix small z b (fun a => a.2=j) using 1 + all_goals + congr 4 + first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + rw [hc,Fintype.sum_prod_type,Finset.sum_comm] + simp_rw [Finset.sum_ite_irrel] + simp + +omit [LinearOrder J] in +lemma selectedRow_eq_smallRow (small : I → J → Bool) (z : SmallProfile small) (i : I) : + selectedRow small z false i=smallRow small (smallView small z false) i := by + rw [selectedRow_eq] + unfold smallRow + apply Finset.sum_congr rfl + intro j _ + cases hs : small i j <;> simp [smallView,hs] + +omit [LinearOrder I] in +lemma smallColumn_cast_selected (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (hz : ∀ a,z a ≤ B a.1.val.1 a.1.val.2) (j : J) : + (smallColumn small B (smallView small z true) j:ℤ)= + (∑ i,if small i j then (B i j:ℤ) else 0)-(selectedColumn small z true j:ℤ) := by + rw [selectedColumn_eq] + unfold smallColumn + rw [Nat.cast_sum,Nat.cast_sum,← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i _ + by_cases hs : small i j=true + · have hb := hz (⟨(i,j),hs⟩,true) + simp only [hs,ite_true,smallView,dite_eq_left] + exact Nat.cast_sub hb + · simp only [smallView,dite_eq_right hs,ite_eq_right hs,Nat.cast_zero,sub_zero] + +lemma exchange_smallRow_abs (small : I → J → Bool) (X Y : SmallProfile small) + (hxy : IntegerExchangeAdjacent X Y) (i : I) : + |(smallRow small (smallView small Y false) i:ℤ)-smallRow small (smallView small X false) i| ≤ 2 := by + rw [← selectedRow_eq_smallRow,← selectedRow_eq_smallRow] + unfold selectedRow + convert exchange_selected_sum_abs_le_two (fun a => a.1.val.1=i ∧ a.2=false) X Y hxy using 1 + congr 5 <;> first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + +lemma exchange_smallColumn_abs (small : I → J → Bool) (B : I → J → ℕ) + (X Y : SmallProfile small) (hX : ∀ a,X a ≤ B a.1.val.1 a.1.val.2) + (hY : ∀ a,Y a ≤ B a.1.val.1 a.1.val.2) + (hxy : IntegerExchangeAdjacent X Y) (j : J) : + |(smallColumn small B (smallView small Y true) j:ℤ)-smallColumn small B (smallView small X true) j| ≤ 2 := by + rw [smallColumn_cast_selected small B Y hY,smallColumn_cast_selected small B X hX] + have he : (∑ i,if small i j then (B i j:ℤ) else 0)-(selectedColumn small Y true j:ℤ)- + ((∑ i,if small i j then (B i j:ℤ) else 0)-(selectedColumn small X true j:ℤ))= + -((selectedColumn small Y true j:ℤ)-selectedColumn small X true j) := by ring + rw [he,abs_neg] + unfold selectedColumn + convert exchange_selected_sum_abs_le_two (fun a => a.1.val.2=j ∧ a.2=true) X Y hxy using 1 + congr 5 <;> first | exact Subsingleton.elim _ _ | (funext a; split_ifs <;> rfl) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectCodeTest.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectCodeTest.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1c0f7ff90f7d11ef1205a2d0da2b48ea0e8ecf7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectCodeTest.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCodeProgram + +namespace OAI + +/-! # The labelled defect predicate on two binary-coded views -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def repairLabelTest (z : LabelledRepairData) : Bool := + defectTest ((z.1.1.2,z.1.2),z.2) + +def repairLabelTestRealizer : Realizer repairLabelTest := + composition (pair (pair (composition (composition first first) second) + (composition first second)) second) defectTestRealizer + +theorem polynomial_repairLabelTest : PolynomialTime repairLabelTestRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) polynomial_defectTest + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +theorem repairLabelTest_iff (B : Fin m → Fin n → ℕ) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (z : SmallProfile small) + (hb : ∀ a : Cells small,z (a,true)≤B a.val.1 a.val.2) (s t : Cells small) : + repairLabelTest (((cellCatalog small e,profileCode small e z),U), + ((e.symm s).val,(e.symm t).val))=true ↔ + IsDefect (smallView small z false) (smallQ small B z) s.val t.val := by + rw [defect_iff_cellSums small B z hb s t] + simp only [repairLabelTest,profileCode,viewList,defectTest_ofFn] + constructor + · rintro ⟨hne,h⟩ + refine ⟨fun he => hne (congrArg e.symm he),?_⟩ + intro a + have hs : e.symm a=e.symm s ↔ a=s := e.symm.injective.eq_iff + have ht : e.symm a=e.symm t ↔ a=t := e.symm.injective.eq_iff + simpa only [Equiv.apply_symm_apply,hs,ht,hU] using h (e.symm a) + · rintro ⟨hne,h⟩ + refine ⟨fun he => hne (e.symm.injective he),?_⟩ + intro i + have hs : e i=s ↔ i=e.symm s := (Equiv.eq_symm_apply e).symm + have ht : e i=t ↔ i=e.symm t := (Equiv.eq_symm_apply e).symm + simpa only [hs,ht,hU] using h (e i) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectLabels.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5754eb194a158bcab398650e51a550f8ab601a8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallDefectLabels.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairWords + +namespace OAI + +/-! # The defect coordinates are determined by the two integer views -/ + +namespace ContingencyTables + +variable {I J : Type*} [DecidableEq I] [DecidableEq J] + +theorem IsDefect.labels_unique {x q : I → J → ℕ} {s t s' t' : I×J} + (h : IsDefect x q s t) (h' : IsDefect x q s' t') : s=s' ∧ t=t' := by + have hst : ¬(s.1=t.1 ∧ s.2=t.2) := fun he => h.1 (Prod.ext he.1 he.2) + have hs := h.2 s.1 s.2 + simp only [transferInt,hst,ite_false,and_self,ite_true,sub_zero] at hs + have hss : s=s' := by + by_contra he + have hss' : ¬(s.1=s'.1 ∧ s.2=s'.2) := fun hh => he (Prod.ext hh.1 hh.2) + have hs' := h'.2 s.1 s.2 + simp only [transferInt,hss',ite_false,add_zero] at hs' + split_ifs at hs' <;> omega + subst s' + refine ⟨rfl,?_⟩ + by_contra he + have htt : ¬(t.1=t'.1 ∧ t.2=t'.2) := fun hh => he (Prod.ext hh.1 hh.2) + have hts : ¬(t.1=s.1 ∧ t.2=s.2) := fun hh => h.1 (Prod.ext hh.1.symm hh.2.symm) + have ht := h.2 t.1 t.2 + have ht' := h'.2 t.1 t.2 + simp only [transferInt,htt,hts,ite_false,and_self,ite_true,sub_zero,add_zero] at ht ht' + omega + +namespace SmallGraphProfiles +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma defectLabels_eq_of_spec (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : PositiveDefects small B r c L) + (st : Cells small×Cells small) + (h : IsDefect (smallView small (naturalProfile z.val) false) + (smallQ small B (naturalProfile z.val)) st.1.val st.2.val) : + defectLabels small B r c L z=st := by + have he := (defectLabels_spec small B r c L z).labels_unique h + exact Prod.ext (Subtype.ext he.1) (Subtype.ext he.2) + +end SmallGraphProfiles +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallEntries.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallEntries.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d7834f76b992d0f31f466171415a9f06b6c15cb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallEntries.lean @@ -0,0 +1,262 @@ +import OAI.Combinatorics.ContingencyTables.Model +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Basic.Real.Basic + +namespace OAI + +/-! +# Four-cycle moves for the small-entry estimate + +The move raises the marked cell, lowers one donor in its row and one in +its column, and raises the opposite corner. No upper cell bound is used. +-/ + +namespace ContingencyTables + +open Finset + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +/-- The signed four-cycle update, before converting back to natural entries. -/ +def fourCycleInt (X : I → J → ℕ) (a b : I) (s t : J) (v : ℕ) (i : I) (j : J) : ℤ := + X i j + ((if i = a then 1 else 0) - (if i = b then 1 else 0)) * + ((if j = s then 1 else 0) - (if j = t then 1 else 0)) * v + +omit [Fintype I] [Fintype J] in +theorem fourCycleInt_nonnegative (X : I → J → ℕ) (a b : I) (s t : J) (v : ℕ) + (hab : a ≠ b) (hst : s ≠ t) (hrow : v ≤ X a t) (hcol : v ≤ X b s) + (i : I) (j : J) : 0 ≤ fourCycleInt X a b s t v i j := by + by_cases hi : i = a + · subst i + by_cases hj : j = s + · subst j + simp [fourCycleInt, hab, hst] + omega + · by_cases hj' : j = t + · subst j + simp [fourCycleInt, hab, Ne.symm hst] + omega + · simp [fourCycleInt, hab, hj, hj'] + · by_cases hi' : i = b + · subst i + by_cases hj : j = s + · subst j + simp [fourCycleInt, Ne.symm hab, hst] + omega + · by_cases hj' : j = t + · subst j + simp [fourCycleInt, Ne.symm hab, Ne.symm hst] + omega + · simp [fourCycleInt, Ne.symm hab, hj, hj'] + · simp [fourCycleInt, hi, hi'] + +omit [Fintype I] in +theorem fourCycleInt_rows (X : I → J → ℕ) (a b : I) (s t : J) (v : ℕ) (i : I) : + ∑ j, fourCycleInt X a b s t v i j = ∑ j, (X i j : ℤ) := by + simp only [fourCycleInt, sum_add_distrib, ← sum_mul, ← mul_sum, sum_sub_distrib] + simp + +omit [Fintype J] in +theorem fourCycleInt_columns (X : I → J → ℕ) (a b : I) (s t : J) (v : ℕ) (j : J) : + ∑ i, fourCycleInt X a b s t v i j = ∑ i, (X i j : ℤ) := by + simp only [fourCycleInt, sum_add_distrib, ← sum_mul, sum_sub_distrib] + simp + +/-- A nonnegative four-cycle is again a table with precisely the same margins. -/ +def fourCycle {r : I → ℕ} {c : J → ℕ} (X : Table r c) + (a b : I) (s t : J) (v : ℕ) (hab : a ≠ b) (hst : s ≠ t) + (hrow : v ≤ X.val a t) (hcol : v ≤ X.val b s) : Table r c := by + let Y := fun i j => (fourCycleInt X.val a b s t v i j).toNat + have hcast (i : I) (j : J) : (Y i j : ℤ) = fourCycleInt X.val a b s t v i j := + Int.toNat_of_nonneg (fourCycleInt_nonnegative X.val a b s t v hab hst hrow hcol i j) + refine ⟨Y, ?_, ?_⟩ + · intro i + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [hcast] + rw [fourCycleInt_rows, ← Nat.cast_sum, X.property.1 i] + · intro j + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [hcast] + rw [fourCycleInt_columns, ← Nat.cast_sum, X.property.2 j] + +@[simp] theorem fourCycle_cast {r : I → ℕ} {c : J → ℕ} (X : Table r c) + (a b : I) (s t : J) (v : ℕ) (hab : a ≠ b) (hst : s ≠ t) + (hrow : v ≤ X.val a t) (hcol : v ≤ X.val b s) (i : I) (j : J) : + ((fourCycle X a b s t v hab hst hrow hcol).val i j : ℤ) = + fourCycleInt X.val a b s t v i j := + Int.toNat_of_nonneg (fourCycleInt_nonnegative X.val a b s t v hab hst hrow hcol i j) + +@[simp] theorem fourCycle_marked {r : I → ℕ} {c : J → ℕ} (X : Table r c) + (a b : I) (s t : J) (v : ℕ) (hab : a ≠ b) (hst : s ≠ t) + (hrow : v ≤ X.val a t) (hcol : v ≤ X.val b s) : + (fourCycle X a b s t v hab hst hrow hcol).val a s = X.val a s + v := by + apply Int.natCast_inj.mp + rw [fourCycle_cast] + simp [fourCycleInt, hab, hst] + +/-- With the donor labels and step fixed, the target determines the source. -/ +theorem fourCycle_injective {r : I → ℕ} {c : J → ℕ} + (X Y : Table r c) (a b : I) (s t : J) (v : ℕ) (hab : a ≠ b) (hst : s ≠ t) + (hXrow : v ≤ X.val a t) (hXcol : v ≤ X.val b s) + (hYrow : v ≤ Y.val a t) (hYcol : v ≤ Y.val b s) + (heq : fourCycle X a b s t v hab hst hXrow hXcol = + fourCycle Y a b s t v hab hst hYrow hYcol) : X = Y := by + apply Subtype.ext + funext i j + have h := congrArg (fun Z : Table r c => (Z.val i j : ℤ)) heq + simp only [fourCycle_cast, fourCycleInt] at h + exact Int.natCast_inj.mp (add_right_cancel h) + +/-- Double counting the four-cycle moves. The source marked value and two +donor labels suffice to reverse a move: the target marked value determines +the step. The donor-existence condition is separated from the injection so +that the margin estimate can be checked independently. -/ +theorem small_entry_count_of_donors {r : I → ℕ} {c : J → ℕ} + (a : I) (s : J) (t V : ℕ) + (hdonors : ∀ X : Table r c, X.val a s < t → + ∃ p : I × J, a ≠ p.1 ∧ s ≠ p.2 ∧ V ≤ X.val a p.2 ∧ V ≤ X.val p.1 s) : + Fintype.card {X : Table r c // X.val a s < t} * V ≤ + Fintype.card (Table r c) * (Fintype.card I * Fintype.card J * t) := by + classical + let Bad := {X : Table r c // X.val a s < t} + let donor (X : Bad) : I × J := Classical.choose (hdonors X.val X.property) + have hdonor (X : Bad) : a ≠ (donor X).1 ∧ s ≠ (donor X).2 ∧ + V ≤ X.val.val a (donor X).2 ∧ V ≤ X.val.val (donor X).1 s := + Classical.choose_spec (hdonors X.val X.property) + let next (X : Bad) (v : Fin V) : Table r c := + fourCycle X.val a (donor X).1 s (donor X).2 (v.val + 1) + (hdonor X).1 (hdonor X).2.1 + ((Nat.succ_le_of_lt v.isLt).trans (hdonor X).2.2.1) + ((Nat.succ_le_of_lt v.isLt).trans (hdonor X).2.2.2) + let encode : Bad × Fin V → Table r c × ((I × J) × Fin t) := fun p => + (next p.1 p.2, donor p.1, ⟨p.1.val.val a s, p.1.property⟩) + have hinj : Function.Injective encode := by + rintro ⟨X, v⟩ ⟨Y, w⟩ heq + have hout : next X v = next Y w := congrArg Prod.fst heq + have hd : donor X = donor Y := congrArg (fun z => z.2.1) heq + have hh : X.val.val a s = Y.val.val a s := + congrArg (fun z => z.2.2.val) heq + have hmarked := congrArg (fun Z : Table r c => Z.val a s) hout + have hv : v = w := by + apply Fin.ext + dsimp [next] at hmarked + simp only [fourCycle_marked] at hmarked + omega + have hXY : X.val = Y.val := by + apply Subtype.ext + funext i j + have h := congrArg (fun Z : Table r c => (Z.val i j : ℤ)) hout + dsimp [next] at h + simp only [fourCycle_cast, fourCycleInt] at h + rw [← hd, ← hv] at h + exact Int.natCast_inj.mp (add_right_cancel h) + exact Prod.ext (Subtype.ext hXY) hv + simpa only [Fintype.card_prod, Fintype.card_fin] using + Fintype.card_le_of_injective encode hinj + +omit [Fintype I] [DecidableEq I] in +private theorem donor_from_line (x : J → ℕ) (s : J) (d V : ℕ) + (hsize : Fintype.card J ≤ d) (hV : 0 < V) + (hmass : x s + d * V ≤ ∑ j, x j) : + ∃ t, s ≠ t ∧ V ≤ x t := by + by_contra hn + have hlt (j : J) : (if j = s then 0 else x j) < V := by + by_cases hj : j = s + · simpa [hj] using hV + · simp only [hj, ite_false] + by_contra h + exact hn ⟨j, Ne.symm hj, by omega⟩ + have hsum : (∑ j, if j = s then 0 else x j) < Fintype.card J * V := by + have h := sum_lt_sum_of_nonempty (s := (univ : Finset J)) + ⟨s, mem_univ s⟩ (fun j _ => hlt j) + simpa using h + have hdecomp : (∑ j, if j = s then 0 else x j) + x s = ∑ j, x j := by + calc + _ = (∑ j, if j = s then 0 else x j) + (∑ j, if j = s then x s else 0) := by + simp + _ = ∑ j, ((if j = s then 0 else x j) + (if j = s then x s else 0)) := + sum_add_distrib.symm + _ = ∑ j, x j := by + apply sum_congr rfl + intro j _ + by_cases hj : j = s <;> simp [hj] + have hmul : Fintype.card J * V ≤ d * V := Nat.mul_le_mul_right V hsize + omega + +/-- Margin lower bounds supply the donors for each small marked entry. +`d * V + t ≤ a₀` is the discrete form of the manuscript's choice +`V = floor (a₀/(2d))` with `2t ≤ a₀`. -/ +theorem small_entry_count {r : I → ℕ} {c : J → ℕ} + (a : I) (s : J) (a₀ d t V : ℕ) + (hrows : Fintype.card I ≤ d) (hcols : Fintype.card J ≤ d) + (hrow : a₀ ≤ r a) (hcol : a₀ ≤ c s) + (hV : 0 < V) (hscale : d * V + t ≤ a₀) : + Fintype.card {X : Table r c // X.val a s < t} * V ≤ + Fintype.card (Table r c) * (Fintype.card I * Fintype.card J * t) := by + apply small_entry_count_of_donors + intro X hX + obtain ⟨t', ht', hXt'⟩ := donor_from_line (X.val a) s d V hcols hV (by + rw [X.property.1 a] + omega) + obtain ⟨b, hb, hXb⟩ := donor_from_line (fun i => X.val i s) a d V hrows hV (by + rw [X.property.2 s] + omega) + exact ⟨(b, t'), hb, ht', hXt', hXb⟩ + +/-- The complete small-entry estimate of paper 200-01, expressed as the +uniform finite counting probability. It also covers zero rows or columns +away from the marked cell. -/ +theorem small_entry_probability {r : I → ℕ} {c : J → ℕ} + (htotal : ∑ i, r i = ∑ j, c j) + (a : I) (s : J) (a₀ d t : ℕ) (hd : 0 < d) + (hrows : Fintype.card I ≤ d) (hcols : Fintype.card J ≤ d) + (hrow : a₀ ≤ r a) (hcol : a₀ ≤ c s) + (ha₀ : 4 * d ≤ a₀) (ht : 2 * t ≤ a₀) : + (Fintype.card {X : Table r c // X.val a s < t} : ℝ) / + Fintype.card (Table r c) ≤ 4 * t * (d : ℝ) ^ 3 / a₀ := by + classical + let V := a₀ / (2 * d) + have hV : 0 < V := Nat.div_pos (by omega) (by omega) + have hfloor := Nat.mul_div_le a₀ (2 * d) + change 2 * d * V ≤ a₀ at hfloor + have hscale : d * V + t ≤ a₀ := by nlinarith [hfloor, ht] + have hcount := small_entry_count a s a₀ d t V hrows hcols hrow hcol hV hscale + have hmod := Nat.mod_lt a₀ (show 0 < 2 * d by omega) + have hdiv := Nat.mod_add_div a₀ (2 * d) + change a₀ % (2 * d) + 2 * d * V = a₀ at hdiv + have hhalf : a₀ ≤ 4 * d * V := by nlinarith + have hcard : 0 < Fintype.card (Table r c) := + Fintype.card_pos_iff.mpr (table_nonempty r c htotal) + have hcardR : (0 : ℝ) < Fintype.card (Table r c) := by exact_mod_cast hcard + have haR : (0 : ℝ) < a₀ := by exact_mod_cast (show 0 < a₀ by omega) + have hfR : (a₀ : ℝ) ≤ 4 * d * V := by exact_mod_cast hhalf + have hcR : (Fintype.card {X : Table r c // X.val a s < t} : ℝ) * V ≤ + Fintype.card (Table r c) * (Fintype.card I * Fintype.card J * (t : ℝ)) := by + exact_mod_cast hcount + have hsR : (Fintype.card I : ℝ) * Fintype.card J ≤ (d : ℝ) ^ 2 := by + have h := Nat.mul_le_mul hrows hcols + exact_mod_cast (show Fintype.card I * Fintype.card J ≤ d ^ 2 by + simpa only [pow_two] using h) + apply (div_le_div_iff₀ hcardR haR).mpr + calc + (Fintype.card {X : Table r c // X.val a s < t} : ℝ) * a₀ ≤ + Fintype.card {X : Table r c // X.val a s < t} * (4 * d * V) := + mul_le_mul_of_nonneg_left hfR (Nat.cast_nonneg _) + _ = (4 * d) * (Fintype.card {X : Table r c // X.val a s < t} * (V : ℝ)) := by ring + _ ≤ (4 * d) * (Fintype.card (Table r c) * + (Fintype.card I * Fintype.card J * (t : ℝ))) := + mul_le_mul_of_nonneg_left hcR (by positivity) + _ ≤ (4 * d) * (Fintype.card (Table r c) * ((d : ℝ) ^ 2 * t)) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg _) + exact mul_le_mul_of_nonneg_right hsR (Nat.cast_nonneg _) + _ = (4 * t * (d : ℝ) ^ 3) * Fintype.card (Table r c) := by ring + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallExchangeListProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallExchangeListProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..274884aea94f3f8833e7edcfa06ae9debfd0882b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallExchangeListProgram.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileFlatCode +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram + +namespace OAI + +/-! # Enumerating all directed unit exchanges of a stored profile -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def positiveExchangeTest (z : List ℕ×(ℕ×ℕ)) : Bool := + decide (z.2.1≠z.2.2 ∧ 0 positiveExchangeTest (xs,ij)) + +def positiveExchangeIndicesRealizer : Realizer positiveExchangeIndices := + composition (pair identity (composition (pair identity identity) cellPairsRealizer)) + (filterWith positiveExchangeTestRealizer) + +lemma polynomial_positiveExchangeIndices : PolynomialTime positiveExchangeIndicesRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) + polynomial_cellPairs)) (polynomial_filterWith polynomial_positiveExchangeTest) + +lemma mem_positiveExchangeIndices (xs : List ℕ) (i j : ℕ) : + (i,j)∈positiveExchangeIndices xs ↔ + i codeExchange (v,ij)) + +def codeExchangeListRealizer : Realizer codeExchangeList := + composition (pair identity (composition flattenViewsRealizer positiveExchangeIndicesRealizer)) + (mapWith codeExchangeRealizer) + +theorem polynomial_codeExchangeList : PolynomialTime codeExchangeListRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_flattenViews polynomial_positiveExchangeIndices)) + (polynomial_mapWith polynomial_codeExchange) + +lemma codeExchangeList_length (v : List ℕ×List ℕ) : + (codeExchangeList v).length≤(v.1.length+v.2.length)^2 := by + have h := List.length_filter_le (fun ij => positiveExchangeTest (flattenViews v,ij)) + (cellPairs (flattenViews v,flattenViews v)) + simpa only [codeExchangeList,List.length_map,positiveExchangeIndices,cellPairs, + List.length_range,flattenViews,List.length_append,pow_two] using h + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles ProfilePrograms +open IntegerWeightedTransport + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +private lemma flat_getD (z : SmallProfile small) (i : Fin (q+q)) : + (flattenViews (profileCode small e z)).getD i.val 0=z (flatViewEquiv small e i) := by + rw [flatten_profileCode] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + +theorem mem_codeExchangeList (z : SmallProfile small) (w : List ℕ×List ℕ) : + w∈codeExchangeList (profileCode small e z) ↔ + ∃ i j : Cells small×Bool,i≠j ∧ 0 U)) → ℕ) + (i : Coordinates Bool (widths (fun _ : Fin n => U))) : + assemble small s hs σ U e (removeOne v i)= + removeOne (assemble small s hs σ U e v) (contextEquiv small s hs e U (.inr i)) := by + have he : Sum.elim (prefixRaw small s σ U) (removeOne v i)= + removeOne (Sum.elim (prefixRaw small s σ U) v) (.inr i) := by + funext a + cases a with + | inl a => simp only [removeOne,Sum.elim_inl,Sum.inl_ne_inr,↓reduceIte,Nat.sub_zero] + | inr a => simp only [removeOne,Sum.elim_inr,Sum.inr.injEq] + unfold assemble + rw [he] + exact removeOne_reindex (contextEquiv small s hs e U) _ (.inr i) + +/-- Every contextual transport edge is an actual doubled-small-coordinate +unit exchange, with no move involving the retained prefix. -/ +theorem assemble_exchange_adjacent (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) {n : ℕ} + (e : Fin n ≃ Later small s) + (X Y : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (hxy : IntegerExchangeAdjacent X Y) : + IntegerExchangeAdjacent (assemble small s hs σ U e X) (assemble small s hs σ U e Y) := by + obtain ⟨D,i,j,hij,hi,hj,rfl,rfl⟩ := hxy + refine ⟨assemble small s hs σ U e D,contextEquiv small s hs e U (.inr i), + contextEquiv small s hs e U (.inr j),?_,?_,?_,?_,?_⟩ + · intro he + exact hij (Sum.inr.inj ((contextEquiv small s hs e U).injective he)) + · rw [assemble_apply] + exact hi + · rw [assemble_apply] + exact hj + · exact assemble_removeOne small s hs σ U e D i + · exact assemble_removeOne small s hs σ U e D j + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallInverseRepairList.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallInverseRepairList.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ccebe6ad2bebe350a61b05b69c1facb8839748b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallInverseRepairList.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairListProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileCodeEquality + +namespace OAI + +/-! # Checking inverse repair candidates against their forward image -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def inverseLabelInput (z : LabelledRepairData) : LabelledRepairData := + (((z.1.1.1,inverseRepairCode z),z.1.2),z.2) + +def inverseLabelInputRealizer : Realizer inverseLabelInput := + pair (pair (pair repairDataCatalog inverseRepairCodeRealizer) + (composition first second)) second + +lemma polynomial_inverseLabelInput : PolynomialTime inverseLabelInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_pair polynomial_repairDataCatalog polynomial_inverseRepairCode) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second + +def inverseLabelTest (z : LabelledRepairData) : Bool := + repairLabelTest (inverseLabelInput z) && + decide (forwardRepairCode (inverseLabelInput z)=z.1.1.2) + +def inverseLabelTestRealizer : Realizer inverseLabelTest := + composition (pair + (composition inverseLabelInputRealizer repairLabelTestRealizer) + (composition (pair (composition inverseLabelInputRealizer forwardRepairCodeRealizer) + (composition (composition first first) second)) profileCodeEqual)) boolAnd + +lemma polynomial_inverseLabelTest : PolynomialTime inverseLabelTestRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_inverseLabelInput polynomial_repairLabelTest) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_inverseLabelInput polynomial_forwardRepairCode) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_profileCodeEqual)) polynomial_boolAnd + +def inverseRepairLabels (z : RepairData) : List (ℕ×ℕ) := + (repairPairs z).filter (fun st => inverseLabelTest (z,st)) + +def inverseRepairLabelsRealizer : Realizer inverseRepairLabels := + composition (pair identity repairPairsRealizer) (filterWith inverseLabelTestRealizer) + +lemma polynomial_inverseRepairLabels : PolynomialTime inverseRepairLabelsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_repairPairs) + (polynomial_filterWith polynomial_inverseLabelTest) + +def checkedInverseRepairList (z : RepairData) : List (List ℕ×List ℕ) := + (inverseRepairLabels z).map (fun st => inverseRepairCode (z,st)) + +def checkedInverseRepairListRealizer : Realizer checkedInverseRepairList := + composition (pair identity inverseRepairLabelsRealizer) (mapWith inverseRepairCodeRealizer) + +theorem polynomial_checkedInverseRepairList : PolynomialTime checkedInverseRepairListRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_inverseRepairLabels) + (polynomial_mapWith polynomial_inverseRepairCode) + +theorem checkedInverseRepairList_length (z : RepairData) : + (checkedInverseRepairList z).length≤z.1.2.1.length^2 := by + simpa only [checkedInverseRepairList,List.length_map,inverseRepairLabels,repairPairs_length] + using List.length_filter_le (fun st => inverseLabelTest (z,st)) (repairPairs z) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +theorem mem_checkedInverseRepairList (B : Fin m → Fin n → ℕ) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (z w : SmallProfile small) + (hw : ∀ a,w a≤B a.1.val.1 a.1.val.2) : + profileCode small e w∈checkedInverseRepairList ((cellCatalog small e,profileCode small e z),U) ↔ + ∃ s t : Cells small, + IsDefect (smallView small w false) (smallQ small B w) s.val t.val ∧ + z=repairedProfile small B w s.val t.val := by + simp only [checkedInverseRepairList,List.mem_map,inverseRepairLabels,List.mem_filter] + constructor + · rintro ⟨⟨i,j⟩,⟨hij,htest⟩,hcode⟩ + have hbounds := (mem_cellPairs _ _ i j).mp hij + simp only [profileCode,viewList,List.length_ofFn] at hbounds + let s := e ⟨i,hbounds.1⟩ + let t := e ⟨j,hbounds.2⟩ + have hs : (e.symm s).val=i := by simp only [s,Equiv.symm_apply_apply] + have ht : (e.symm t).val=j := by simp only [t,Equiv.symm_apply_apply] + have hd := (Bool.and_eq_true_iff.mp htest).1 + have hf := of_decide_eq_true (Bool.and_eq_true_iff.mp htest).2 + simp only [inverseLabelInput,hcode] at hd hf + refine ⟨s,t,?_,?_⟩ + · apply (repairLabelTest_iff small e B U hU w (fun a => hw (a,true)) s t).mp + simpa only [hs,ht] using hd + · have he := forwardRepairCode_eq small e B U hU w s t + rw [hs,ht] at he + exact ((profileCode_injective small e) (he.symm.trans hf)).symm + · rintro ⟨s,t,hd,hz⟩ + let st := ((e.symm s).val,(e.symm t).val) + have hc : inverseRepairCode (((cellCatalog small e,profileCode small e z),U),st)= + profileCode small e w := by + rw [inverseRepairCode_eq small e B U hU z s t,hz, + inverseRepairProfile_repaired small B w s.val t.val hw hd] + refine ⟨st,⟨?_,?_⟩,hc⟩ + · apply (mem_cellPairs _ _ _ _).mpr + simpa only [profileCode,viewList,List.length_ofFn] using + And.intro (e.symm s).isLt (e.symm t).isLt + · simp only [inverseLabelTest,inverseLabelInput,hc,Bool.and_eq_true,decide_eq_true_eq] + refine ⟨(repairLabelTest_iff small e B U hU w (fun a => hw (a,true)) s t).mpr hd,?_⟩ + exact (forwardRepairCode_eq small e B U hU w s t).trans (congrArg (profileCode small e) hz.symm) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallLineSumProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallLineSumProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d593f654b483c307addf262448c0791b5abdf747 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallLineSumProgram.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallViewLookupProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums + +namespace OAI + +/-! # Binary row and column sums of the sparse stored view -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial +open scoped BigOperators + +abbrev LineData := ((List (ℕ×ℕ)×List ℕ)×List ℕ)×ℕ + +def lineEntry (row : Bool) (z : LineData×ℕ) : ℕ := + lookupView (z.1.1.1,if row then (z.1.2,z.2) else (z.2,z.1.2)) + +def lineEntryRealizer (row : Bool) : Realizer (lineEntry row) := + composition (pair (composition (composition first first) first) + (choose (constant row) (pair (composition first second) second) + (pair second (composition first second)))) lookupViewRealizer + +lemma polynomial_lineEntry (row : Bool) : PolynomialTime (lineEntryRealizer row) := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_choose (polynomial_constant row) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_second)))) + polynomial_lookupView + +def lineIndices : Realizer (fun z : LineData => List.range z.1.2.length) := + composition (composition (composition first second) listLength) range + +lemma polynomial_lineIndices : PolynomialTime lineIndices := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength) X + intro z + have hw : weight z.1.2≤weight z := by + rcases z with ⟨⟨lookupData,coords⟩,i⟩ + simp only [weight_prod] + omega + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight z.1.2).trans hw + +def lineSum (row : Bool) (z : LineData) : ℕ := + ((List.range z.1.2.length).map (fun i => lineEntry row (z,i))).sum + +def lineSumRealizer (row : Bool) : Realizer (lineSum row) := + composition (composition (pair identity lineIndices) (mapWith (lineEntryRealizer row))) listSum + +theorem polynomial_lineSum (row : Bool) : PolynomialTime (lineSumRealizer row) := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_lineIndices) + (polynomial_mapWith (polynomial_lineEntry row))) polynomial_listSum + +lemma lineSum_eq_sum {n : ℕ} (row : Bool) (z : LineData) (hsize : z.1.2.length=n) + (f : Fin n → ℕ) (hf : ∀ i,lineEntry row (z,i.val)=f i) : + lineSum row z=∑ i,f i := by + unfold lineSum + have he : (List.range z.1.2.length).map (fun i => lineEntry row (z,i))=List.ofFn f := by + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn,hsize] + · intro i hi _ + have hin : i + (marginList row z.1).getD z.2 0) := + composition (pair (composition first (marginListRealizer row)) second) (getDFast 0) + +lemma polynomial_marginValue (row : Bool) : PolynomialTime (marginValueRealizer row) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first (polynomial_marginList row)) polynomial_second) + (polynomial_getDFast 0) + +def lineValueRealizer (row : Bool) : Realizer (fun z : MarginCheckData×ℕ => + lineSum row (lineArgument row z)) := + composition (f := lineArgument row) (g := lineSum row) + (lineArgumentRealizer row) (lineSumRealizer row) + +lemma polynomial_lineValue (row : Bool) : PolynomialTime (lineValueRealizer row) := + polynomial_composition (polynomial_lineArgument row) (polynomial_lineSum row) + +def validMarginAt (row : Bool) (z : MarginCheckData×ℕ) : Bool := + let a := (marginList row z.1).getD z.2 0 + let s := lineSum row (lineArgument row z) + decide (s≤a ∧ (a + simp only [List.getD_eq_getElem?_getD] at h <;> simp [h]) + +lemma polynomial_validMarginAt (row : Bool) : PolynomialTime (validMarginAtRealizer row) := by + unfold validMarginAtRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_lineValue row) + (polynomial_marginValue row)) polynomial_leNat) + (polynomial_choose (polynomial_composition (polynomial_pair (polynomial_marginValue row) + (polynomial_composition polynomial_first polynomial_second)) polynomial_less) + (polynomial_composition (polynomial_pair (polynomial_lineValue row) + (polynomial_marginValue row)) polynomial_natEqual) (polynomial_constant true))) polynomial_boolAnd) + +def marginIndices (row : Bool) : Realizer (fun z : MarginCheckData => + List.range (marginList row z).length) := + composition (composition (marginListRealizer row) listLength) range + +lemma polynomial_marginIndices (row : Bool) : PolynomialTime (marginIndices row) := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_marginList row) polynomial_listLength) X + intro z + have hw : weight (marginList row z)≤weight z := by + rcases z with ⟨⟨lookupData,⟨r,c⟩⟩,U⟩ + cases row <;> simp only [marginList,Bool.false_eq_true,ite_false,ite_true,weight_prod] <;> omega + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight (marginList row z)).trans hw + +def validMargins (row : Bool) (z : MarginCheckData) : Bool := + (List.range (marginList row z).length).all (fun i => validMarginAt row (z,i)) + +def validMarginsRealizer (row : Bool) : Realizer (validMargins row) := + (composition (composition (pair identity (marginIndices row)) + (mapWith (validMarginAtRealizer row))) all).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,validMargins]) + +theorem polynomial_validMargins (row : Bool) : PolynomialTime (validMarginsRealizer row) := by + unfold validMarginsRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_marginIndices row)) + (polynomial_mapWith (polynomial_validMarginAt row))) polynomial_all) + +theorem validMargins_iff (row : Bool) (z : MarginCheckData) : + validMargins row z=true ↔ ∀ i,i<(marginList row z).length → + lineSum row (lineArgument row (z,i))≤(marginList row z).getD i 0 ∧ + ((marginList row z).getD i 0 h.1 (congrArg Subtype.val he),?_⟩ + intro a + have ha := h.2 a.val.1 a.val.2 + have hba := hb a + simp only [transferInt,view_at_cell,q_at_cell,←cell_eq_coordinates] at ha + split_ifs at ha ⊢ <;> omega + · rintro ⟨hne,h⟩ + refine ⟨fun he => hne (Subtype.ext he),?_⟩ + intro i j + by_cases hs : small i j=true + · let a : Cells small := ⟨(i,j),hs⟩ + have ha := h a + have hba := hb a + simp only [cell_eq_coordinates] at ha + dsimp only [a] at ha hba + simp only [smallQ,smallView,transferInt,hs,dite_true] + split_ifs at ha ⊢ <;> omega + · have hns : ¬(i=s.val.1 ∧ j=s.val.2) := by + rintro ⟨rfl,rfl⟩ + exact hs s.property + have hnt : ¬(i=t.val.1 ∧ j=t.val.2) := by + rintro ⟨rfl,rfl⟩ + exact hs t.property + simp only [smallQ,smallView,transferInt,hs,hns,hnt,ite_false] + norm_num + +/-- An allowed profile is detected by one balanced test or by one of +the ordered cell-pair tests. This uses at most quadratically many labels. -/ +theorem pattern_iff_cellSums + (hb : ∀ a : Cells small,z (a,true)≤B a.val.1 a.val.2) : + Pattern small B z ↔ CellSumBalanced small B z ∨ + ∃ s t : Cells small,CellSumDefect small B z s t := by + constructor + · rintro (h|⟨s,t,hs,ht,hd⟩) + · exact Or.inl ((balanced_iff_cellSums small B z hb).mp h) + · exact Or.inr ⟨⟨s,hs⟩,⟨t,ht⟩,(defect_iff_cellSums small B z hb _ _).mp hd⟩ + · rintro (h|⟨s,t,h⟩) + · exact Or.inl ((balanced_iff_cellSums small B z hb).mpr h) + · exact Or.inr ⟨s.val,t.val,s.property,t.property, + (defect_iff_cellSums small B z hb s t).mpr h⟩ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallPatternProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallPatternProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..47e5b428e2984e299cab849496973c0299b73c11 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallPatternProgram.lean @@ -0,0 +1,247 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternArithmetic +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram + +namespace OAI + +/-! # Polynomial tests for the two allowed small-profile patterns -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +abbrev PatternData := (List ℕ×List ℕ)×ℕ +abbrev LabelledPattern := PatternData×(ℕ×ℕ) + +def pairSum (z : PatternData×ℕ) : ℕ := z.1.1.1.getD z.2 0+z.1.1.2.getD z.2 0 + +def pairSumRealizer : Realizer pairSum := + composition (pair + (composition (pair (composition (composition first first) first) second) (getDFast 0)) + (composition (pair (composition (composition first first) second) second) (getDFast 0))) add + +lemma polynomial_pairSum : PolynomialTime pairSumRealizer := by + unfold pairSumRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) (polynomial_getDFast 0))) polynomial_add + +def indexIndicator : Realizer (fun z : ℕ×ℕ => if z.1=z.2 then (1:ℕ) else 0) := + (choose natEqual (constant 1) (constant 0)).congr (by + intro z; simp only [decide_eq_true_eq]) + +lemma polynomial_indexIndicator : PolynomialTime indexIndicator := by + unfold indexIndicator + exact polynomial_congr _ (polynomial_choose polynomial_natEqual + (polynomial_constant 1) (polynomial_constant 0)) + +def patternIndices : Realizer (fun z : PatternData => List.range z.1.1.length) := + composition (composition (composition first first) listLength) range + +lemma polynomial_patternIndices : PolynomialTime patternIndices := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + have hw : weight z.1.1≤weight z := by + rcases z with ⟨⟨xs,ys⟩,U⟩ + simp only [weight_prod] + omega + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight z.1.1).trans hw + +def balancedAt (z : PatternData×ℕ) : Bool := decide (pairSum z=z.1.2) + +def balancedAtRealizer : Realizer balancedAt := + composition (pair pairSumRealizer (composition first second)) natEqual + +lemma polynomial_balancedAt : PolynomialTime balancedAtRealizer := + polynomial_composition (polynomial_pair polynomial_pairSum + (polynomial_composition polynomial_first polynomial_second)) polynomial_natEqual + +def balancedTest (z : PatternData) : Bool := + (List.range z.1.1.length).all (fun i => balancedAt (z,i)) + +def balancedTestRealizer : Realizer balancedTest := + (composition (composition (pair identity patternIndices) (mapWith balancedAtRealizer)) all).congr + (by intro z; simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,balancedTest]) + +lemma polynomial_balancedTest : PolynomialTime balancedTestRealizer := + polynomial_congr _ (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_patternIndices) + (polynomial_mapWith polynomial_balancedAt)) polynomial_all) + +def defectAt (z : LabelledPattern×ℕ) : Bool := + decide (pairSum (z.1.1,z.2)+(if z.2=z.1.2.1 then 1 else 0)= + z.1.1.2+(if z.2=z.1.2.2 then 1 else 0)) + +def defectAtRealizer : Realizer defectAt := + composition (pair + (composition (pair + (composition (pair (composition first first) second) pairSumRealizer) + (composition (pair second (composition (composition first second) first)) indexIndicator)) add) + (composition (pair (composition (composition first first) second) + (composition (pair second (composition (composition first second) second)) indexIndicator)) add)) + natEqual + +lemma polynomial_defectAt : PolynomialTime defectAtRealizer := by + unfold defectAtRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_pairSum) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first)) + polynomial_indexIndicator)) polynomial_add) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_indexIndicator)) polynomial_add)) polynomial_natEqual + +def defectTest (z : LabelledPattern) : Bool := + decide (z.2.1≠z.2.2) && (List.range z.1.1.1.length).all (fun i => defectAt (z,i)) + +def defectTestRealizer : Realizer defectTest := + (composition (pair + (composition (composition second natEqual) boolNot) + (composition (composition (pair identity (composition first patternIndices)) + (mapWith defectAtRealizer)) all)) boolAnd).congr (by + intro z + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,Bool.not_eq_true', + decide_eq_false_iff_not,defectTest,decide_eq_true_eq,List.all_map,Function.comp_def,id_eq]) + +lemma polynomial_defectTest : PolynomialTime defectTestRealizer := by + unfold defectTestRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_natEqual) polynomial_boolNot) + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition polynomial_first polynomial_patternIndices)) + (polynomial_mapWith polynomial_defectAt)) polynomial_all)) polynomial_boolAnd) + +def patternTest (z : PatternData) : Bool := + balancedTest z || (cellPairs (z.1.1,z.1.1)).any (fun st => defectTest (z,st)) + +def patternTestRealizer : Realizer patternTest := + (composition (pair balancedTestRealizer + (composition (composition (pair identity + (composition (pair (composition first first) (composition first first)) cellPairsRealizer)) + (mapWith defectTestRealizer)) any)) boolOr).congr (by + intro z + simp only [Function.comp_apply,List.any_map,Function.comp_def,id_eq,patternTest]) + +theorem polynomial_patternTest : PolynomialTime patternTestRealizer := by + unfold patternTestRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_balancedTest + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_first polynomial_first)) polynomial_cellPairs)) + (polynomial_mapWith polynomial_defectTest)) polynomial_any)) polynomial_boolOr) + +lemma pairSum_ofFn {n : ℕ} (x y : Fin n → ℕ) (U : ℕ) (i : Fin n) : + pairSum (((List.ofFn x,List.ofFn y),U),i.val)=x i+y i := by + simp only [pairSum,List.getD_eq_getElem?_getD,List.getElem?_ofFn] + simp only [i.isLt,dite_true,Option.getD_some] + +theorem balancedTest_ofFn {n : ℕ} (x y : Fin n → ℕ) (U : ℕ) : + balancedTest ((List.ofFn x,List.ofFn y),U)=true ↔ ∀ i,x i+y i=U := by + simp only [balancedTest,List.all_eq_true,List.mem_range,List.length_ofFn,balancedAt, + decide_eq_true_eq] + constructor + · intro h i + simpa only [pairSum_ofFn] using h i.val i.isLt + · intro h i hi + exact (pairSum_ofFn x y U ⟨i,hi⟩).trans (h ⟨i,hi⟩) + +theorem defectTest_ofFn {n : ℕ} (x y : Fin n → ℕ) (U : ℕ) (s t : Fin n) : + defectTest (((List.ofFn x,List.ofFn y),U),(s.val,t.val))=true ↔ + s≠t ∧ ∀ i,x i+y i+(if i=s then 1 else 0)=U+(if i=t then 1 else 0) := by + simp only [defectTest,Bool.and_eq_true,decide_eq_true_eq,List.all_eq_true, + List.mem_range,List.length_ofFn,defectAt] + constructor + · rintro ⟨hne,h⟩ + refine ⟨fun he => hne (congrArg Fin.val he),fun i => ?_⟩ + simpa only [pairSum_ofFn,Fin.ext_iff] using h i.val i.isLt + · rintro ⟨hne,h⟩ + refine ⟨fun he => hne (Fin.ext he),fun i hi => ?_⟩ + rw [show pairSum (((List.ofFn x,List.ofFn y),U),i)=x ⟨i,hi⟩+y ⟨i,hi⟩ from + pairSum_ofFn x y U ⟨i,hi⟩] + simpa only [Fin.ext_iff] using h ⟨i,hi⟩ + +theorem patternTest_ofFn {n : ℕ} (x y : Fin n → ℕ) (U : ℕ) : + patternTest ((List.ofFn x,List.ofFn y),U)=true ↔ + (∀ i,x i+y i=U) ∨ ∃ s t : Fin n,s≠t ∧ + ∀ i,x i+y i+(if i=s then 1 else 0)=U+(if i=t then 1 else 0) := by + simp only [patternTest,Bool.or_eq_true,balancedTest_ofFn,List.any_eq_true] + constructor + · rintro (h|⟨⟨s,t⟩,hst,h⟩) + · exact Or.inl h + · have hb := (mem_cellPairs (List.ofFn x) (List.ofFn x) s t).mp hst + simp only [List.length_ofFn] at hb + exact Or.inr ⟨⟨s,hb.1⟩,⟨t,hb.2⟩,(defectTest_ofFn x y U _ _).mp h⟩ + · rintro (h|⟨s,t,h⟩) + · exact Or.inl h + · refine Or.inr ⟨(s.val,t.val),?_,(defectTest_ofFn x y U s t).mpr h⟩ + apply (mem_cellPairs (List.ofFn x) (List.ofFn x) _ _).mpr + simpa only [List.length_ofFn] using And.intro s.isLt t.isLt + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres ProfilePrograms + +noncomputable section +universe u +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +/-- The binary list test recognizes exactly the manuscript's profile +patterns on the common small-cell box. -/ +theorem patternTest_views (small : I → J → Bool) (B : I → J → ℕ) + {n : ℕ} (e : Fin n ≃ Cells small) (z : SmallProfile small) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) + (hb : ∀ a : Cells small,z (a,true)≤B a.val.1 a.val.2) : + patternTest ((viewList small e z false,viewList small e z true),U)=true ↔ + Pattern small B z := by + rw [viewList,viewList,patternTest_ofFn,pattern_iff_cellSums small B z hb] + constructor + · rintro (h|⟨s,t,hne,h⟩) + · left + intro a + simpa only [Equiv.apply_symm_apply,hU] using h (e.symm a) + · right + refine ⟨e s,e t,fun he => hne (e.injective he),?_⟩ + intro a + have hs : e.symm a=s ↔ a=e s := by + constructor + · intro he; rw [←he,Equiv.apply_symm_apply] + · intro he; rw [he,Equiv.symm_apply_apply] + have ht : e.symm a=t ↔ a=e t := by + constructor + · intro he; rw [←he,Equiv.apply_symm_apply] + · intro he; rw [he,Equiv.symm_apply_apply] + simpa only [Equiv.apply_symm_apply,hU,hs,ht] using h (e.symm a) + · rintro (h|⟨s,t,hne,h⟩) + · left + intro i + simpa only [hU] using h (e i) + · right + refine ⟨e.symm s,e.symm t,fun he => hne (e.symm.injective he),?_⟩ + intro i + have hs : e i=s ↔ i=e.symm s := by + constructor + · intro he; rw [←he,Equiv.symm_apply_apply] + · intro he; rw [he,Equiv.apply_symm_apply] + have ht : e i=t ↔ i=e.symm t := by + constructor + · intro he; rw [←he,Equiv.symm_apply_apply] + · intro he; rw [he,Equiv.apply_symm_apply] + simpa only [hU,hs,ht] using h (e i) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..d763fcf3d09ff519138f319b1ba39680728be797 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileCode.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileValidator + +namespace OAI + +/-! # Literal lists encode exactly the positive physical states -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +def profileCode (z : SmallProfile small) : List ℕ×List ℕ := + (viewList small e z false,viewList small e z true) + +def profileOfCode (v : List ℕ×List ℕ) : SmallProfile small := + fun a => (if a.2 then v.2 else v.1).getD (e.symm a.1).val 0 + +lemma profileOfCode_code (z : SmallProfile small) : + profileOfCode small e (profileCode small e z)=z := by + funext a + rcases a with ⟨a,b⟩ + cases b <;> + simp only [profileOfCode,profileCode,viewList,Bool.false_eq_true,ite_false,ite_true, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,(e.symm a).isLt,dite_true, + Option.getD_some,Fin.eta,Equiv.apply_symm_apply] + +theorem profileCode_injective : Function.Injective (profileCode small e) := by + intro z w h + have hh := congrArg (profileOfCode small e) h + simpa only [profileOfCode_code] using hh + +private lemma ofFn_getD (xs : List ℕ) (h : xs.length=q) : + List.ofFn (fun i : Fin q => xs.getD i.val 0)=xs := by + apply List.ext_getElem + · simpa only [List.length_ofFn] using h.symm + · intro i hi hj + simp only [List.getElem_ofFn,List.getD_eq_getElem?_getD,List.getElem?_eq_getElem hj, + Option.getD_some] + +lemma profileCode_ofCode (v : List ℕ×List ℕ) (hx : v.1.length=q) (hy : v.2.length=q) : + profileCode small e (profileOfCode small e v)=v := by + apply Prod.ext + · simpa only [profileCode,viewList,profileOfCode,Bool.false_eq_true,ite_false, + Equiv.symm_apply_apply] using ofFn_getD v.1 hx + · simpa only [profileCode,viewList,profileOfCode,ite_true, + Equiv.symm_apply_apply] using ofFn_getD v.2 hy + +def codeCheckData (catalog : List (ℕ×ℕ)) (r c : List ℕ) (U : ℕ) + (v : List ℕ×List ℕ) : ProfileCheckData := (((catalog,v),(r,c)),U) + +/-- For arbitrary input lists, the Boolean program succeeds exactly +when those lists encode an actual positive-completion state. -/ +theorem profileTest_code_iff (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (e : Fin q ≃ Cells (paperSmall r c)) + (v : List ℕ×List ℕ) : + profileTest (codeCheckData (cellCatalog (paperSmall r c) e) (List.ofFn r) (List.ofFn c) + ((dimensionAllowance (I := Fin m) (J := Fin n))^20) v)=true ↔ + ∃ x : PaperStates r c,profileCode (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := Fin m) (J := Fin n))^12) x)=v := by + constructor + · intro h + have hx : v.1.length=q := by + have hh := (Bool.and_eq_true_iff.mp h).1 + simpa only [codeCheckData,cellCatalog,List.length_ofFn,decide_eq_true_eq] using hh + have hy : v.2.length=q := by + have hh := (Bool.and_eq_true_iff.mp (Bool.and_eq_true_iff.mp h).2).1 + simpa only [codeCheckData,cellCatalog,List.length_ofFn,decide_eq_true_eq] using hh + let z := profileOfCode (paperSmall r c) e v + have hz : profileCode (paperSmall r c) e z=v := profileCode_ofCode _ _ v hx hy + have hp : ProfileFeasible r c z := by + apply (profileTest_iff r c htotal e z).mp + change profileTest (codeCheckData (cellCatalog (paperSmall r c) e) + (List.ofFn r) (List.ofFn c) ((dimensionAllowance (I := Fin m) (J := Fin n))^20) + (profileCode (paperSmall r c) e z))=true + rwa [hz] + exact ⟨stateOfFeasible r c z hp,hz⟩ + · rintro ⟨x,rfl⟩ + exact (profileTest_iff r c htotal e _).mpr (physicalProfile_feasible r c x) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileEncoding.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..8abf21d1bbc9ae481fafb10d8dff37ad38c45f54 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileEncoding.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallBalancedEncoding +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSupportVariance + +namespace OAI + +/-! # The variance encoding retains exactly the positive physical states -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal SmallContextEnumeration RowMajorEnumeration FiniteExposureVariance + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev VarianceEncoding (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) := + (Fin (Fintype.card (Cells small)) → Fin (U+1)) ⊕ PositiveDefects small B r c L + +noncomputable def encodeProfile (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + VarianceEncoding small B r c L U → Profiles small B + | .inl x => ⟨choiceProfile small B U hB (wordChoices small U x), + Or.inl (choiceProfile_balanced small B U hB _)⟩ + | .inr z => ⟨z.val,Or.inr z.property.1⟩ + +lemma encodeProfile_injective (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + Function.Injective (encodeProfile small B r c L U hB) := by + intro x y he + cases x with + | inl x => + cases y with + | inl y => + apply congrArg Sum.inl + apply (wordChoices small U).injective + apply rawChoice_injective small U + exact congrArg (fun z : Profiles small B => naturalProfile z.val) he + | inr y => + have hp := choiceProfile_balanced small B U hB (wordChoices small U x) + have hxy := congrArg (fun z : Profiles small B => naturalProfile z.val) he + change rawChoice small U (wordChoices small U x)=naturalProfile y.val at hxy + have hb : Balanced small B (naturalProfile y.val) := by rwa [← hxy] + exact False.elim (balanced_not_defect small B _ hb y.property.1) + | inr x => + cases y with + | inl y => + have hp := choiceProfile_balanced small B U hB (wordChoices small U y) + have hxy := congrArg (fun z : Profiles small B => naturalProfile z.val) he + change naturalProfile x.val=rawChoice small U (wordChoices small U y) at hxy + have hb : Balanced small B (naturalProfile x.val) := by rwa [hxy] + exact False.elim (balanced_not_defect small B _ hb x.property.1) + | inr y => + apply congrArg Sum.inr + apply Subtype.ext + exact congrArg (fun z : Profiles small B => z.val) he + +/-- Every omitted physical profile has zero completion weight. -/ +lemma outside_encoding_weight_zero (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (p : Profiles small B) + (hp : p ∉ Set.range (encodeProfile small B r c L U hB)) : + hardMarginal small B r c L (naturalProfile p.val)=0 := by + have hn : ¬0 < hardMarginal small B r c L (naturalProfile p.val) := by + intro hpos + apply hp + rcases p.property with hb|hd + · refine ⟨.inl (balancedWord small B U hB p.val),?_⟩ + apply Subtype.ext + apply naturalProfile_injective small B + exact balancedWord_profile small B U hB p.val hb + · exact ⟨.inr ⟨p.val,hd,hpos⟩,rfl⟩ + exact le_antisymm (le_of_not_gt hn) (hardMarginal_nonnegative _ _ _ _ _ _) + +/-- The completed graph variance proof concerns the literal bounded +physical profiles; the auxiliary encoding drops only zero-mass defects. -/ +theorem encoding_variance_eq (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (H : SmallProfile small → ℝ) : + variance + (Sum.elim (wordWeight small B r c L U) + (fun z : PositiveDefects small B r c L => hardMarginal small B r c L (naturalProfile z.val))) + (Sum.elim (wordObservable small U H) (fun z => H (naturalProfile z.val)))= + variance (fun z : Profiles small B => hardMarginal small B r c L (naturalProfile z.val)) + (fun z => H (naturalProfile z.val)) := by + convert variance_support_embedding (encodeProfile small B r c L U hB) + (encodeProfile_injective small B r c L U hB) + (fun z => hardMarginal small B r c L (naturalProfile z.val)) + (outside_encoding_weight_zero small B r c L U hB) + (fun z => H (naturalProfile z.val)) using 1 + congr 1 <;> funext x <;> cases x <;> rfl + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileFlatCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileFlatCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..2352d12a47f8b71b971e69470b0cad996f6b48f2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileFlatCode.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileCode +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeCandidates + +namespace OAI + +/-! # Flattening the two stored views for coordinate exchanges -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def flattenViews (z : List ℕ×List ℕ) : List ℕ := z.1++z.2 + +def flattenViewsRealizer : Realizer flattenViews := append + +theorem polynomial_flattenViews : PolynomialTime flattenViewsRealizer := polynomial_append + +def splitViews (z : ℕ×List ℕ) : List ℕ×List ℕ := (z.2.take z.1,z.2.drop z.1) + +def splitViewsRealizer : Realizer splitViews := + pair (composition (pair second first) takeFast) (composition (pair second first) dropFast) + +theorem polynomial_splitViews : PolynomialTime splitViewsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_dropFast) + +lemma split_flattenViews (v : List ℕ×List ℕ) : + splitViews (v.1.length,flattenViews v)=v := by + simp only [splitViews,flattenViews,List.take_left,List.drop_left,Prod.mk.eta] + +def codeExchange (z : (List ℕ×List ℕ)×(ℕ×ℕ)) : List ℕ×List ℕ := + splitViews (z.1.1.length,listExchange (flattenViews z.1,z.2)) + +def codeExchangeRealizer : Realizer codeExchange := + composition (pair (composition (composition first first) listLength) + (composition (pair (composition first flattenViewsRealizer) second) listExchangeRealizer)) + splitViewsRealizer + +theorem polynomial_codeExchange : PolynomialTime codeExchangeRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_flattenViews) polynomial_second) + polynomial_listExchange)) polynomial_splitViews + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles ProfilePrograms +open IntegerWeightedTransport + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +def sumViewEquiv : (Fin q⊕Fin q) ≃ Cells small×Bool where + toFun + | .inl i => (e i,false) + | .inr i => (e i,true) + invFun a := if a.2 then .inr (e.symm a.1) else .inl (e.symm a.1) + left_inv a := by cases a <;> simp only [Bool.false_eq_true,ite_false,ite_true,Equiv.symm_apply_apply] + right_inv a := by rcases a with ⟨a,b⟩; cases b <;> simp only [Bool.false_eq_true,ite_false, + ite_true,Equiv.apply_symm_apply] + +def flatViewEquiv : Fin (q+q) ≃ Cells small×Bool := + finSumFinEquiv.symm.trans (sumViewEquiv small e) + +lemma flatten_profileCode (z : SmallProfile small) : + flattenViews (profileCode small e z)=List.ofFn (fun i => z (flatViewEquiv small e i)) := by + rw [List.ofFn_add] + unfold flattenViews profileCode viewList + congr 1 + · apply congrArg List.ofFn + funext i + change z (e i,false)=z (sumViewEquiv small e (finSumFinEquiv.symm (Fin.castAdd q i))) + rw [finSumFinEquiv_symm_apply_castAdd] + rfl + · apply congrArg List.ofFn + funext i + change z (e i,true)=z (sumViewEquiv small e (finSumFinEquiv.symm (Fin.natAdd q i))) + rw [finSumFinEquiv_symm_apply_natAdd] + rfl + +theorem codeExchange_eq (z : SmallProfile small) (i j : Fin (q+q)) : + codeExchange (profileCode small e z,(i.val,j.val))= + profileCode small e (exchangeTarget z (flatViewEquiv small e i) (flatViewEquiv small e j)) := by + have he : exchangeTarget (fun a => z (flatViewEquiv small e a)) i j= + fun a => exchangeTarget z (flatViewEquiv small e i) (flatViewEquiv small e j) + (flatViewEquiv small e a) := by + funext a + simp only [exchangeTarget,(flatViewEquiv small e).injective.eq_iff] + unfold codeExchange + rw [flatten_profileCode,listExchange_ofFn,he,←flatten_profileCode] + simpa only [profileCode,viewList,List.length_ofFn] using + split_flattenViews (profileCode small e + (exchangeTarget z (flatViewEquiv small e i) (flatViewEquiv small e j))) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileRepair.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileRepair.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebfffddc422db42470304292e570289458d2e2b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileRepair.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphVertices +import OAI.Combinatorics.ContingencyTables.Sampling.RepairResiduals + +namespace OAI + +/-! # Literal small-profile repair and its typewise inverse -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +noncomputable def repairedProfile (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) : SmallProfile small := fun a => + if a.2 then B a.1.val.1 a.1.val.2-repairMatrix (smallView small z false) s t a.1.val.1 a.1.val.2 + else repairMatrix (smallView small z false) s t a.1.val.1 a.1.val.2 + +lemma repairMatrix_pointwise (x y : I → J → ℕ) (s t : I×J) (i : I) (j : J) + (h : x i j=y i j) : repairMatrix x s t i j=repairMatrix y s t i j := by + simp only [repairMatrix,transferInt,h] + +lemma repairedProfile_bounded (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hcap : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) : + ∀ a,repairedProfile small B z s t a ≤ B a.1.val.1 a.1.val.2 := by + rintro ⟨a,b⟩ + cases b + · exact hcap a + · exact Nat.sub_le _ _ + +lemma repairedProfile_balanced (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (s t : I×J) + (hcap : ∀ a : Cells small,repairMatrix (smallView small z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2) : + Balanced small B (repairedProfile small B z s t) := by + intro i j + cases hij : small i j + · simp only [smallView,smallQ,hij,Bool.false_eq_true,↓reduceDIte] + · simp only [smallView,smallQ,hij,dite_eq_left,repairedProfile,Bool.false_eq_true,↓reduceIte] + exact (Nat.sub_sub_self (hcap ⟨(i,j),hij⟩)).symm + +/-- Fixed ordered defect labels recover both old views from the literal +repaired profile; this does not forget the column-view complement. -/ +theorem repairedProfile_injective (small : I → J → Bool) (B : I → J → ℕ) + (s t : I×J) (z w : SmallProfile small) + (hz : ∀ a,z a ≤ B a.1.val.1 a.1.val.2) (hw : ∀ a,w a ≤ B a.1.val.1 a.1.val.2) + (hdz : IsDefect (smallView small z false) (smallQ small B z) s t) + (hdw : IsDefect (smallView small w false) (smallQ small B w) s t) + (he : repairedProfile small B z s t=repairedProfile small B w s t) : z=w := by + have hx (a : Cells small) : z (a,false)=w (a,false) := by + have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells small)=a := Subtype.ext (Prod.eta a.val) + have hh := congrArg (fun p : SmallProfile small => (p (a,false):ℤ)) he + change (repairMatrix (smallView small z false) s t a.val.1 a.val.2:ℤ)= + (repairMatrix (smallView small w false) s t a.val.1 a.val.2:ℤ) at hh + rw [repairMatrix_cast hdz,repairMatrix_cast hdw] at hh + simp only [transferInt,smallView,a.property,dite_eq_left] at hh + simp only [heta] at hh + omega + funext a + rcases a with ⟨a,b⟩ + cases b + · exact hx a + · have hdz' := hdz.2 a.val.1 a.val.2 + have hdw' := hdw.2 a.val.1 a.val.2 + have heta : (⟨(a.val.1,a.val.2),a.property⟩ : Cells small)=a := Subtype.ext (Prod.eta a.val) + simp only [smallQ,smallView,a.property,dite_eq_left,transferInt] at hdz' hdw' + simp only [heta,hx a] at hdz' hdw' + have hzb := hz (a,true) + have hwb := hw (a,true) + dsimp only at hzb hwb + omega + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileValidator.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileValidator.lean new file mode 100644 index 0000000000000000000000000000000000000000..be70c2c26fa47feaa4390fa93a9fea2bb21e75c7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProfileValidator.lean @@ -0,0 +1,172 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallMarginSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.SmallBoundsProgram + +namespace OAI + +/-! # A polynomial binary validator for the positive profile space -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev ProfileCheckData := ((List (ℕ×ℕ)×(List ℕ×List ℕ))×(List ℕ×List ℕ))×ℕ + +def profileViews : Realizer (fun z : ProfileCheckData => z.1.1.2) := + composition (composition first first) second + +def profileCatalog : Realizer (fun z : ProfileCheckData => z.1.1.1) := + composition (composition first first) first + +def profileMargins : Realizer (fun z : ProfileCheckData => z.1.2) := + composition first second + +lemma polynomial_profileViews : PolynomialTime profileViews := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + +lemma polynomial_profileCatalog : PolynomialTime profileCatalog := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + +lemma polynomial_profileMargins : PolynomialTime profileMargins := + polynomial_composition polynomial_first polynomial_second + +def profileView (row : Bool) : Realizer (fun z : ProfileCheckData => + if row then z.1.1.2.1 else z.1.1.2.2) := + choose (constant row) (composition profileViews first) (composition profileViews second) + +lemma polynomial_profileView (row : Bool) : PolynomialTime (profileView row) := + polynomial_choose (polynomial_constant row) + (polynomial_composition polynomial_profileViews polynomial_first) + (polynomial_composition polynomial_profileViews polynomial_second) + +def profileBound (row : Bool) : Realizer (fun z : ProfileCheckData => + boundedValues (z.2,if row then z.1.1.2.1 else z.1.1.2.2)) := + composition (pair second (profileView row)) boundedValuesRealizer + +lemma polynomial_profileBound (row : Bool) : PolynomialTime (profileBound row) := + polynomial_composition (polynomial_pair polynomial_second (polynomial_profileView row)) + polynomial_boundedValues + +def profileShape (row : Bool) : Realizer (fun z : ProfileCheckData => + decide ((if row then z.1.1.2.1 else z.1.1.2.2).length=z.1.1.1.length)) := + composition (pair (composition (profileView row) listLength) + (composition profileCatalog listLength)) natEqual + +lemma polynomial_profileShape (row : Bool) : PolynomialTime (profileShape row) := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_profileView row) polynomial_listLength) + (polynomial_composition polynomial_profileCatalog polynomial_listLength)) polynomial_natEqual + +def profilePattern : Realizer (fun z : ProfileCheckData => patternTest (z.1.1.2,z.2)) := + composition (pair profileViews second) patternTestRealizer + +lemma polynomial_profilePattern : PolynomialTime profilePattern := + polynomial_composition (polynomial_pair polynomial_profileViews polynomial_second) + polynomial_patternTest + +def profileColumnView : Realizer (fun z : ProfileCheckData => + complementValues (z.2,z.1.1.2.2)) := + composition (pair second (composition profileViews second)) complementValuesRealizer + +lemma polynomial_profileColumnView : PolynomialTime profileColumnView := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_profileViews polynomial_second)) polynomial_complementValues + +def profileLineData (row : Bool) : Realizer (fun z : ProfileCheckData => + (((z.1.1.1,if row then z.1.1.2.1 else complementValues (z.2,z.1.1.2.2)),z.1.2),z.2)) := + pair (pair (pair profileCatalog + (choose (constant row) (profileView true) profileColumnView)) profileMargins) second + +lemma polynomial_profileLineData (row : Bool) : PolynomialTime (profileLineData row) := + polynomial_pair (polynomial_pair (polynomial_pair polynomial_profileCatalog + (polynomial_choose (polynomial_constant row) (polynomial_profileView true) + polynomial_profileColumnView)) polynomial_profileMargins) polynomial_second + +def profileLineTest (row : Bool) : Realizer (fun z : ProfileCheckData => + validMargins row (((z.1.1.1, + if row then z.1.1.2.1 else complementValues (z.2,z.1.1.2.2)),z.1.2),z.2)) := + composition (profileLineData row) (validMarginsRealizer row) + +lemma polynomial_profileLineTest (row : Bool) : PolynomialTime (profileLineTest row) := + polynomial_composition (polynomial_profileLineData row) (polynomial_validMargins row) + +def profileTest (z : ProfileCheckData) : Bool := + decide (z.1.1.2.1.length=z.1.1.1.length) && + (decide (z.1.1.2.2.length=z.1.1.1.length) && + (boundedValues (z.2,z.1.1.2.1) && + (boundedValues (z.2,z.1.1.2.2) && + (patternTest (z.1.1.2,z.2) && + (validMargins true (((z.1.1.1,z.1.1.2.1),z.1.2),z.2) && + validMargins false (((z.1.1.1,complementValues (z.2,z.1.1.2.2)),z.1.2),z.2)))))) + +def profileTestRealizer : Realizer profileTest := + composition (pair (profileShape true) + (composition (pair (profileShape false) + (composition (pair (profileBound true) + (composition (pair (profileBound false) + (composition (pair profilePattern + (composition (pair (profileLineTest true) (profileLineTest false)) boolAnd)) boolAnd)) + boolAnd)) boolAnd)) boolAnd)) boolAnd + +theorem polynomial_profileTest : PolynomialTime profileTestRealizer := + polynomial_composition (polynomial_pair (polynomial_profileShape true) + (polynomial_composition (polynomial_pair (polynomial_profileShape false) + (polynomial_composition (polynomial_pair (polynomial_profileBound true) + (polynomial_composition (polynomial_pair (polynomial_profileBound false) + (polynomial_composition (polynomial_pair polynomial_profilePattern + (polynomial_composition (polynomial_pair (polynomial_profileLineTest true) + (polynomial_profileLineTest false)) polynomial_boolAnd)) polynomial_boolAnd)) + polynomial_boolAnd)) polynomial_boolAnd)) polynomial_boolAnd)) polynomial_boolAnd + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open PaddedCompletions ProfilePrograms FirstPaperPhysicalMarginal CompletionCounts + +noncomputable section +variable {m n q : ℕ} + +theorem profileTest_iff (r : Fin m → ℕ) (c : Fin n → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (e : Fin q ≃ Cells (paperSmall r c)) + (z : SmallProfile (paperSmall r c)) : + profileTest (((cellCatalog (paperSmall r c) e, + (viewList (paperSmall r c) e z false,viewList (paperSmall r c) e z true)), + (List.ofFn r,List.ofFn c)),(dimensionAllowance (I := Fin m) (J := Fin n))^20)=true ↔ + ProfileFeasible r c z := by + let small := paperSmall r c + let B := stateCapacity r c + let U := (dimensionAllowance (I := Fin m) (J := Fin n))^20 + have hU (a : Cells small) : B a.val.1 a.val.2=U := + stateCapacity_small r c _ _ a.property + have hb : (∀ a,z a≤U) ↔ ∀ a,z a≤B a.1.val.1 a.1.val.2 := by + simp only [hU] + simp only [profileTest,Bool.and_eq_true,cellCatalog,viewList,List.length_ofFn, + decide_true,true_and] + change (boundedValues (U,viewList small e z false)=true ∧ + (boundedValues (U,viewList small e z true)=true ∧ + (patternTest ((viewList small e z false,viewList small e z true),U)=true ∧ + (validMargins true (((cellCatalog small e,viewList small e z false), + (List.ofFn r,List.ofFn c)),U)=true ∧ + validMargins false (((cellCatalog small e,complementValues (U,viewList small e z true)), + (List.ofFn r,List.ofFn c)),U)=true)))) ↔ _ + constructor + · rintro ⟨hx,hy,hp,hr,hc⟩ + have hbound : ∀ a,z a≤U := (boundedValues_views small e z U).mp (by simpa using And.intro hx hy) + apply profileFeasible_of_lineTests r c htotal z (hb.mp hbound) + · exact (patternTest_views small B e z U hU (fun a => hb.mp hbound (a,true))).mp hp + · exact (validRows_iff small e z r c U).mp hr + · exact (validColumns_iff small e B z r c U hU).mp hc + · intro h + have hbound := hb.mpr h.bounded + have hh := (boundedValues_views small e z U).mpr hbound + have hxy := Bool.and_eq_true_iff.mp hh + have hl := profileFeasible_lineTests r c z h + refine ⟨hxy.1,hxy.2,?_,?_,?_⟩ + · exact (patternTest_views small B e z U hU (fun a => h.bounded (a,true))).mpr h.pattern + · exact (validRows_iff small e z r c U).mpr hl.1 + · exact (validColumns_iff small e B z r c U hU).mpr hl.2 + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..612cb86ab9aa639dcdd814a0c6f0e2318033b271 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallProposal.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallChainBudget +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # The manuscript's exact dyadic small-chain proposal -/ + +namespace ContingencyTables + +noncomputable def smallProposal (d : ℕ) : ℝ := 1/(2:ℝ)^(Nat.clog 2 (32*d^2)) + +lemma smallProposal_bounds (d : ℕ) (hd : 1 ≤ d) : + 0 < smallProposal d ∧ 1/(64*(d:ℝ)^2) ≤ smallProposal d ∧ + smallProposal d ≤ 1/(32*(d:ℝ)^2) := by + have hd0 : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hn : 1 < 32*d^2 := by nlinarith + have hlo := Nat.le_pow_clog (by decide : 1 < 2) (32*d^2) + have hp := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hn + have he : 2^Nat.clog 2 (32*d^2) = 2^(Nat.clog 2 (32*d^2)).pred*2 := by + conv_lhs => rw [← Nat.succ_pred_eq_of_pos (Nat.clog_pos (by decide : 1 < 2) hn)] + exact pow_succ _ _ + have hhi : 2^Nat.clog 2 (32*d^2) ≤ 64*d^2 := by rw [he]; omega + have hloR : 32*(d:ℝ)^2 ≤ (2:ℝ)^Nat.clog 2 (32*d^2) := by exact_mod_cast hlo + have hhiR : (2:ℝ)^Nat.clog 2 (32*d^2) ≤ 64*(d:ℝ)^2 := by exact_mod_cast hhi + refine ⟨by unfold smallProposal; positivity,?_,?_⟩ + · exact one_div_le_one_div_of_le (by positivity) hhiR + · exact one_div_le_one_div_of_le (by positivity) hloR + +lemma smallProposal_degree (d : ℕ) (hd : 1 ≤ d) : + ((5*d^2+1:ℕ):ℝ)*smallProposal d ≤ 1/2 := by + have hd0 : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hsq : (1:ℝ) ≤ (d:ℝ)^2 := by exact_mod_cast (show 1 ≤ d^2 by nlinarith) + have hm := mul_le_mul_of_nonneg_left (smallProposal_bounds d hd).2.2 + (show (0:ℝ) ≤ (5*d^2+1:ℕ) by positivity) + apply hm.trans + rw [mul_one_div] + apply (div_le_iff₀ (show (0:ℝ) < 32*(d:ℝ)^2 by positivity)).mpr + push_cast + nlinarith + +lemma smallProposal_poincare_budget (d : ℕ) (hd : 14 ≤ d) : + 2*(770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6)/smallProposal d ≤ (d:ℝ)^160 := by + have hp := smallProposal_bounds d (by omega) + have hd0 : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hrecip : 1/smallProposal d ≤ 64*(d:ℝ)^2 := by + apply (div_le_iff₀ hp.1).mpr + have hh := (div_le_iff₀ (show (0:ℝ) < 64*(d:ℝ)^2 by positivity)).mp hp.2.1 + nlinarith + calc + _ = (2*(770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6))*(1/smallProposal d) := by ring + _ ≤ (2*(770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6))*(64*(d:ℝ)^2) := + mul_le_mul_of_nonneg_left hrecip (by positivity) + _ = 128*(d:ℝ)^2*(770*(d:ℝ)^4*((d^20:ℕ):ℝ)^6) := by ring + _ ≤ _ := small_chain_poincare_constant d hd + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCandidates.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCandidates.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2bea7f7fb0d773ca60be4c8d0f6db0c25ca4915 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCandidates.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.InverseSmallRepair +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphDegree + +namespace OAI + +/-! # Polynomial lists of forward and inverse repair candidates -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open PhysicalCompletionFibres SmallContextFibres FirstPaperProfiles +open IntegerWeightedTransport SmallContextEnumeration RowMajorEnumeration +open SmallContextCoordinates CompletionCounts + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- Candidates are generated by ordered cell pairs, without enumerating +positive defect states. A later feasibility test removes unused pairs. -/ +def localRepairCandidates (small : I → J → Bool) (B : I → J → ℕ) + (v : SmallProfile small) : Finset (SmallProfile small) := + (Finset.univ.image (fun st : Cells small×Cells small => + repairedProfile small B v st.1.val st.2.val)) ∪ + (Finset.univ.image (fun st : Cells small×Cells small => + inverseRepairProfile small B v st.1.val st.2.val)) + +lemma localRepairCandidates_card (small : I → J → Bool) (B : I → J → ℕ) + (v : SmallProfile small) : + (localRepairCandidates small B v).card ≤ 2*(Fintype.card (Cells small))^2 := by + unfold localRepairCandidates + apply (Finset.card_union_le _ _).trans + have h1 := Finset.card_image_le (s := (Finset.univ : Finset (Cells small×Cells small))) + (f := fun st => repairedProfile small B v st.1.val st.2.val) + have h2 := Finset.card_image_le (s := (Finset.univ : Finset (Cells small×Cells small))) + (f := fun st => inverseRepairProfile small B v st.1.val st.2.val) + simp only [Finset.card_univ,Fintype.card_prod] at h1 h2 + nlinarith + +lemma fullNeighbors_local (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (v : SmallProfile (firstPaperSmall r c U)) : + fullNeighbors r c U L B hB v ⊆ + exchangeCandidates v ∪ localRepairCandidates (firstPaperSmall r c U) B v := by + intro w hw + have hs := fullNeighbors_subset r c U L B hB v hw + simp only [Finset.mem_union] at hs ⊢ + rcases hs with he|hr + · exact Or.inl he + · right + simp only [repairNeighbors,Finset.mem_union,Finset.mem_image, + Finset.mem_filter,Finset.mem_univ,true_and] at hr + simp only [localRepairCandidates,Finset.mem_union,Finset.mem_image, + Finset.mem_univ,true_and] + rcases hr with ⟨z,hzv,hzw⟩|⟨z,hzv,hzw⟩ + · left + refine ⟨defectLabels _ B r c L z,?_⟩ + rw [←hzv] + rw [repairWord_profile r c U L B hB z] at hzw + exact hzw + · right + refine ⟨defectLabels _ B r c L z,?_⟩ + rw [repairWord_profile r c U L B hB z] at hzv + rw [←hzv,inverseRepairProfile_repaired _ B _ _ _ + (naturalProfile_bounded z.val) (defectLabels_spec _ B r c L z)] + exact hzw + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCapacity.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCapacity.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a4b14a137dd28e2d213bac8b5de6d2b528bd537 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCapacity.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileRepair +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalContextVariance + +namespace OAI + +/-! # A positive physical defect repairs inside the literal small box -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- Positive hard marginal supplies an actual full completion. Its +preserved residual bounds force each repaired small entry below U. -/ +theorem repair_small_capacity (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (z : SmallProfile (firstPaperSmall r c U)) + (hz : ∀ a,z a ≤ B a.1.val.1 a.1.val.2) (s t : I×J) + (hs : firstPaperSmall r c U s.1 s.2=true) (ht : firstPaperSmall r c U t.1 t.2=true) + (hd : IsDefect (smallView (firstPaperSmall r c U) z false) + (smallQ (firstPaperSmall r c U) B z) s t) + (hf : 0 < hardMarginal (firstPaperSmall r c U) B r c L z) : + ∀ a : Cells (firstPaperSmall r c U), + repairMatrix (smallView (firstPaperSmall r c U) z false) s t a.val.1 a.val.2 ≤ B a.val.1 a.val.2 := by + have hcard : 0 < Fintype.card (CompletionFibre (firstPaperSmall r c U) B r + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) c + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L) z) := by + have h := hf + rw [hardMarginal_eq_fibre_card _ _ _ _ _ z hz] at h + exact_mod_cast h + obtain ⟨Z⟩ := Fintype.card_pos_iff.mp hcard + have hfull := defect_fibre_views Z hs ht hd + intro a + have hcap := repairMatrix_small_capacity r c U hfull hs ht Z.property.1 Z.property.2.1 + a.val.1 a.val.2 a.property + have he : repairMatrix Z.val.val.1 s t a.val.1 a.val.2= + repairMatrix (smallView (firstPaperSmall r c U) z false) s t a.val.1 a.val.2 := by + apply repairMatrix_pointwise + have hx := (Z.property.2.2.1 a.val.1 a.val.2 a.property).1 + simpa only [smallView,a.property,dite_eq_left] using hx + rw [he] at hcap + rw [hB _ _ a.property] + exact Nat.le_of_lt hcap + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCodeProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCodeProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..44b0efef77c348ce2518e460d13d06b025ae9df0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairCodeProgram.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairGeometryProgram + +namespace OAI + +/-! # Forward and inverse repairs on the stored pair of integer lists -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev RepairData := (List (ℕ×ℕ)×(List ℕ×List ℕ))×ℕ +abbrev LabelledRepairData := RepairData×(ℕ×ℕ) + +def repairDataCatalog : Realizer (fun z : LabelledRepairData => z.1.1.1) := + composition (composition first first) first + +def repairDataRows : Realizer (fun z : LabelledRepairData => z.1.1.2.1) := + composition (composition (composition first first) second) first + +lemma polynomial_repairDataCatalog : PolynomialTime repairDataCatalog := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + +lemma polynomial_repairDataRows : PolynomialTime repairDataRows := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first + +def repairDataCaps : Realizer (fun z : LabelledRepairData => + capacityList (z.1.2,z.1.1.2.1)) := + composition (pair (composition first second) repairDataRows) capacityListRealizer + +lemma polynomial_repairDataCaps : PolynomialTime repairDataCaps := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_repairDataRows) + polynomial_capacityList + +def repairDataCross : Realizer (fun z : LabelledRepairData => + crossingIndex (z.1.1.1,z.2)) := + composition (pair repairDataCatalog second) crossingIndexRealizer + +lemma polynomial_repairDataCross : PolynomialTime repairDataCross := + polynomial_composition (polynomial_pair polynomial_repairDataCatalog polynomial_second) + polynomial_crossingIndex + +def forwardRepairCode (z : LabelledRepairData) : List ℕ×List ℕ := + repairedViews (z.1.1.2.1,(capacityList (z.1.2,z.1.1.2.1), + (z.2.2,crossingIndex (z.1.1.1,z.2)))) + +def forwardRepairCodeRealizer : Realizer forwardRepairCode := + composition (pair repairDataRows (pair repairDataCaps + (pair (composition second second) repairDataCross))) repairedViewsRealizer + +theorem polynomial_forwardRepairCode : PolynomialTime forwardRepairCodeRealizer := + polynomial_composition (polynomial_pair polynomial_repairDataRows + (polynomial_pair polynomial_repairDataCaps + (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + polynomial_repairDataCross))) polynomial_repairedViews + +def inverseRepairCode (z : LabelledRepairData) : List ℕ×List ℕ := + backwardViews (z.1.1.2.1,(capacityList (z.1.2,z.1.1.2.1), + (z.2.1,(z.2.2,crossingIndex (z.1.1.1,z.2))))) + +def inverseRepairCodeRealizer : Realizer inverseRepairCode := + composition (pair repairDataRows (pair repairDataCaps + (pair (composition second first) (pair (composition second second) repairDataCross)))) + backwardViewsRealizer + +theorem polynomial_inverseRepairCode : PolynomialTime inverseRepairCodeRealizer := + polynomial_composition (polynomial_pair polynomial_repairDataRows + (polynomial_pair polynomial_repairDataCaps + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + polynomial_repairDataCross)))) polynomial_backwardViews + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +theorem forwardRepairCode_eq (B : Fin m → Fin n → ℕ) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (z : SmallProfile small) + (s t : Cells small) : + forwardRepairCode (((cellCatalog small e,profileCode small e z),U), + ((e.symm s).val,(e.symm t).val))= + profileCode small e (repairedProfile small B z s.val t.val) := by + have hc : capacityList (U,(profileCode small e z).1)= + List.ofFn (fun i => B (e i).val.1 (e i).val.2) := by + simp only [profileCode,viewList,capacityList_ofFn,hU] + unfold forwardRepairCode + rw [hc,crossingIndex_eq] + change repairedViews (viewList small e z false, + (List.ofFn (fun i => B (e i).val.1 (e i).val.2), + ((e.symm t).val,cellIndex small e (t.val.1,s.val.2))))=_ + have ht : cellIndex small e t.val=(e.symm t).val := by + simp only [cellIndex,t.property,dite_true] + rw [←ht] + exact repairedViews_eq small e B z s.val t.val + +theorem inverseRepairCode_eq (B : Fin m → Fin n → ℕ) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (z : SmallProfile small) + (s t : Cells small) : + inverseRepairCode (((cellCatalog small e,profileCode small e z),U), + ((e.symm s).val,(e.symm t).val))= + profileCode small e (inverseRepairProfile small B z s.val t.val) := by + have hc : capacityList (U,(profileCode small e z).1)= + List.ofFn (fun i => B (e i).val.1 (e i).val.2) := by + simp only [profileCode,viewList,capacityList_ofFn,hU] + unfold inverseRepairCode + rw [hc,crossingIndex_eq] + have hs : cellIndex small e s.val=(e.symm s).val := by + simp only [cellIndex,s.property,dite_true] + have ht : cellIndex small e t.val=(e.symm t).val := by + simp only [cellIndex,t.property,dite_true] + rw [←hs,←ht] + exact backwardViews_eq small e B z s.val t.val + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairGeometryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairGeometryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..27e12e51be084135d497b32687e291cfaa726c89 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairGeometryProgram.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileInverseRepairProgram +import OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileCode + +namespace OAI + +/-! # Binary computation of repair crossing cells and capacities -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev RepairGeometry := List (ℕ×ℕ)×(ℕ×ℕ) + +def sourceCell : Realizer (fun z : RepairGeometry => z.1.getD z.2.1 (0,0)) := + composition (pair first (composition second first)) (getDFast (0,0)) + +def targetCell : Realizer (fun z : RepairGeometry => z.1.getD z.2.2 (0,0)) := + composition (pair first (composition second second)) (getDFast (0,0)) + +lemma polynomial_sourceCell : PolynomialTime sourceCell := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast (0,0)) + +lemma polynomial_targetCell : PolynomialTime targetCell := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast (0,0)) + +def crossingIndex (z : RepairGeometry) : ℕ := + z.1.idxOf ((z.1.getD z.2.2 (0,0)).1,(z.1.getD z.2.1 (0,0)).2) + +def crossingIndexRealizer : Realizer crossingIndex := + composition (pair (pair (composition targetCell first) (composition sourceCell second)) first) + cellLookupRealizer + +theorem polynomial_crossingIndex : PolynomialTime crossingIndexRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_targetCell polynomial_first) + (polynomial_composition polynomial_sourceCell polynomial_second)) polynomial_first) + polynomial_cellLookup + +def capacityList (z : ℕ×List ℕ) : List ℕ := z.2.map (fun _ => z.1) + +def capacityListRealizer : Realizer capacityList := mapWith first + +theorem polynomial_capacityList : PolynomialTime capacityListRealizer := + polynomial_mapWith polynomial_first + +lemma capacityList_ofFn {q : ℕ} (U : ℕ) (v : Fin q → ℕ) : + capacityList (U,List.ofFn v)=List.ofFn (fun _ : Fin q => U) := by + simp only [capacityList,List.map_ofFn,Function.comp_def] + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +lemma catalog_getD (i : Fin q) : + (cellCatalog small e).getD i.val (0,0)=((e i).val.1.val,(e i).val.2.val) := by + simp only [cellCatalog,List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt, + dite_true,Option.getD_some,Fin.eta] + +/-- Large crossing cells use the out-of-range index in both the +forward and inverse arithmetic repairs. -/ +theorem crossingIndex_eq (s t : Cells small) : + crossingIndex (cellCatalog small e,((e.symm s).val,(e.symm t).val))= + cellIndex small e (t.val.1,s.val.2) := by + unfold crossingIndex + rw [catalog_getD,catalog_getD] + simp only [Equiv.apply_symm_apply] + exact cellCatalog_index small e (t.val.1,s.val.2) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairListProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairListProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6ba1d30c89e5bf1fba3b0d1aea8da961c71b04e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairListProgram.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallDefectCodeTest + +namespace OAI + +/-! # Polynomial lists of encoded forward and inverse repairs -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def repairRows : Realizer (fun z : RepairData => z.1.2.1) := + composition (composition first second) first + +lemma polynomial_repairRowsData : PolynomialTime repairRows := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first + +def repairPairs (z : RepairData) : List (ℕ×ℕ) := cellPairs (z.1.2.1,z.1.2.1) + +def repairPairsRealizer : Realizer repairPairs := + composition (pair repairRows repairRows) cellPairsRealizer + +lemma polynomial_repairPairs : PolynomialTime repairPairsRealizer := + polynomial_composition (polynomial_pair polynomial_repairRowsData polynomial_repairRowsData) + polynomial_cellPairs + +def forwardRepairLabels (z : RepairData) : List (ℕ×ℕ) := + (repairPairs z).filter (fun st => repairLabelTest (z,st)) + +def forwardRepairLabelsRealizer : Realizer forwardRepairLabels := + composition (pair identity repairPairsRealizer) (filterWith repairLabelTestRealizer) + +lemma polynomial_forwardRepairLabels : PolynomialTime forwardRepairLabelsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_repairPairs) + (polynomial_filterWith polynomial_repairLabelTest) + +def forwardRepairList (z : RepairData) : List (List ℕ×List ℕ) := + (forwardRepairLabels z).map (fun st => forwardRepairCode (z,st)) + +def forwardRepairListRealizer : Realizer forwardRepairList := + composition (pair identity forwardRepairLabelsRealizer) (mapWith forwardRepairCodeRealizer) + +theorem polynomial_forwardRepairList : PolynomialTime forwardRepairListRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_forwardRepairLabels) + (polynomial_mapWith polynomial_forwardRepairCode) + +def inverseRepairList (z : RepairData) : List (List ℕ×List ℕ) := + (repairPairs z).map (fun st => inverseRepairCode (z,st)) + +def inverseRepairListRealizer : Realizer inverseRepairList := + composition (pair identity repairPairsRealizer) (mapWith inverseRepairCodeRealizer) + +theorem polynomial_inverseRepairList : PolynomialTime inverseRepairListRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_repairPairs) + (polynomial_mapWith polynomial_inverseRepairCode) + +lemma repairPairs_length (z : RepairData) : (repairPairs z).length=z.1.2.1.length^2 := by + simp only [repairPairs,cellPairs,List.length_map,List.length_range,pow_two] + +theorem forwardRepairList_length (z : RepairData) : + (forwardRepairList z).length≤z.1.2.1.length^2 := by + simpa only [forwardRepairList,List.length_map,forwardRepairLabels,repairPairs_length] + using List.length_filter_le (fun st => repairLabelTest (z,st)) (repairPairs z) + +theorem inverseRepairList_length (z : RepairData) : + (inverseRepairList z).length=z.1.2.1.length^2 := by + simp only [inverseRepairList,List.length_map,repairPairs_length] + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +theorem mem_forwardRepairList (B : Fin m → Fin n → ℕ) (U : ℕ) + (hU : ∀ a : Cells small,B a.val.1 a.val.2=U) (z : SmallProfile small) + (hb : ∀ a : Cells small,z (a,true)≤B a.val.1 a.val.2) (w : List ℕ×List ℕ) : + w∈forwardRepairList ((cellCatalog small e,profileCode small e z),U) ↔ + ∃ s t : Cells small, + IsDefect (smallView small z false) (smallQ small B z) s.val t.val ∧ + w=profileCode small e (repairedProfile small B z s.val t.val) := by + simp only [forwardRepairList,List.mem_map,forwardRepairLabels,List.mem_filter] + constructor + · rintro ⟨⟨i,j⟩,⟨hij,hd⟩,hw⟩ + have hbounds := (mem_cellPairs _ _ i j).mp hij + simp only [profileCode,viewList,List.length_ofFn] at hbounds + let si : Fin q := ⟨i,hbounds.1⟩ + let ti : Fin q := ⟨j,hbounds.2⟩ + have hs : e.symm (e si)=si := e.symm_apply_apply si + have ht : e.symm (e ti)=ti := e.symm_apply_apply ti + refine ⟨e si,e ti,?_,?_⟩ + · apply (repairLabelTest_iff small e B U hU z hb (e si) (e ti)).mp + simpa only [hs,ht] using hd + · rw [←hw] + simpa only [hs,ht] using forwardRepairCode_eq small e B U hU z (e si) (e ti) + · rintro ⟨s,t,hd,rfl⟩ + refine ⟨((e.symm s).val,(e.symm t).val),⟨?_,?_⟩,?_⟩ + · apply (mem_cellPairs _ _ _ _).mpr + simpa only [profileCode,viewList,List.length_ofFn] using + And.intro (e.symm s).isLt (e.symm t).isLt + · exact (repairLabelTest_iff small e B U hU z hb s t).mpr hd + · exact forwardRepairCode_eq small e B U hU z s t + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0b4b79b7b339b1d7e71552cfad385e5365bdd0a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallRepairWords.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairMass +import OAI.Combinatorics.ContingencyTables.Transport.WordContextVariance + +namespace OAI + +/-! # Actual positive defects repair to the physical transversal words -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres FirstPaperProfiles +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts +open SmallContextEnumeration RowMajorEnumeration + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +def PositiveDefects (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) (L : ℕ) := + {z : BoundedProfile small B // SingleDefect small B (naturalProfile z) ∧ + 0 < hardMarginal small B r c L (naturalProfile z)} + +noncomputable instance positiveDefectsFintype (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : Fintype (PositiveDefects small B r c L) := by + unfold PositiveDefects + infer_instance + +lemma defect_labels_exist (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PositiveDefects small B r c L) : + ∃ st : Cells small×Cells small,IsDefect (smallView small (naturalProfile z.val) false) + (smallQ small B (naturalProfile z.val)) st.1.val st.2.val := by + obtain ⟨s,t,hs,ht,hd⟩ := z.property.1 + exact ⟨(⟨s,hs⟩,⟨t,ht⟩),hd⟩ + +noncomputable def defectLabels (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PositiveDefects small B r c L) : Cells small×Cells small := + Classical.choose (defect_labels_exist small B r c L z) + +lemma defectLabels_spec (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (z : PositiveDefects small B r c L) : + IsDefect (smallView small (naturalProfile z.val) false) (smallQ small B (naturalProfile z.val)) + (defectLabels small B r c L z).1.val (defectLabels small B r c L z).2.val := + Classical.choose_spec (defect_labels_exist small B r c L z) + +noncomputable def repairWord (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + Fin (Fintype.card (Cells (firstPaperSmall r c U))) → Fin (U+1) := fun j => + let st := defectLabels _ B r c L z + let a := enumeration (firstPaperSmall r c U) j + ⟨repairMatrix (smallView (firstPaperSmall r c U) (naturalProfile z.val) false) + st.1.val st.2.val a.val.1 a.val.2,Nat.lt_succ_of_le (by + exact (repair_small_capacity r c U L B hB (naturalProfile z.val) + (naturalProfile_bounded z.val) st.1.val st.2.val st.1.property st.2.property + (defectLabels_spec _ B r c L z) z.property.2 a).trans_eq (hB _ _ a.property))⟩ + +lemma repairWord_profile (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + rawChoice (firstPaperSmall r c U) U + (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z))= + repairedProfile (firstPaperSmall r c U) B (naturalProfile z.val) + (defectLabels _ B r c L z).1.val (defectLabels _ B r c L z).2.val := by + funext p + rcases p with ⟨a,b⟩ + have he : (wordChoices (firstPaperSmall r c U) U (repairWord r c U L B hB z) a).val= + repairMatrix (smallView (firstPaperSmall r c U) (naturalProfile z.val) false) + (defectLabels _ B r c L z).1.val (defectLabels _ B r c L z).2.val a.val.1 a.val.2 := by + change repairMatrix (smallView (firstPaperSmall r c U) (naturalProfile z.val) false) + (defectLabels _ B r c L z).1.val (defectLabels _ B r c L z).2.val + (enumeration (firstPaperSmall r c U) ((enumeration (firstPaperSmall r c U)).symm a)).val.1 + (enumeration (firstPaperSmall r c U) ((enumeration (firstPaperSmall r c U)).symm a)).val.2=_ + rw [Equiv.apply_symm_apply] + cases b + · exact he + · change U-_ = B a.val.1 a.val.2-_ + rw [he,hB _ _ a.property] + +theorem repairWord_weight (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (hcap : ∀ T : ResidualTables (firstPaperSmall r c U) r c + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L),∀ i j,T.val.val i j ≤ B i j) + (z : PositiveDefects (firstPaperSmall r c U) B r c L) : + hardMarginal (firstPaperSmall r c U) B r c L (naturalProfile z.val) ≤ + wordWeight (firstPaperSmall r c U) B r c L U (repairWord r c U L B hB z) := by + unfold wordWeight + rw [repairWord_profile] + exact physical_repair_weight_le r c U L B hB (naturalProfile z.val) (naturalProfile_bounded z.val) + _ _ (defectLabels _ B r c L z).1.property (defectLabels _ B r c L z).2.property + (defectLabels_spec _ B r c L z) hcap z.property.2 + +theorem repairWord_type_injective (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) : + Function.Injective (fun z : PositiveDefects (firstPaperSmall r c U) B r c L => + (defectLabels _ B r c L z,repairWord r c U L B hB z)) := by + intro x y he + have hl := congrArg Prod.fst he + dsimp only at hl + have hr := congrArg (fun a => rawChoice (firstPaperSmall r c U) U + (wordChoices (firstPaperSmall r c U) U a)) (congrArg Prod.snd he) + rw [repairWord_profile,repairWord_profile,hl] at hr + have hdx := defectLabels_spec (firstPaperSmall r c U) B r c L x + rw [hl] at hdx + apply Subtype.ext + apply naturalProfile_injective (firstPaperSmall r c U) B + exact repairedProfile_injective (firstPaperSmall r c U) B _ _ _ _ + (naturalProfile_bounded x.val) (naturalProfile_bounded y.val) hdx + (defectLabels_spec _ B r c L y) hr + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallResidualTotals.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallResidualTotals.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba0526d4c7040c422d76fbfc72af35a0cf956dde --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallResidualTotals.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFeasibility + +namespace OAI + +/-! # Conservation makes the residual-total test redundant -/ + +namespace ContingencyTables.SmallGraphProfiles +open scoped BigOperators Classical +open SmallContextFibres FirstPaperProfiles PaddedCompletions CompletionCounts +open FirstPaperPhysicalMarginal PhysicalCompletionFibres + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma pattern_view_totals (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (hz : Pattern small B z) : + (∑ i,∑ j,smallView small z false i j)=∑ i,∑ j,smallQ small B z i j := by + rcases hz with h|⟨s,t,_,_,h⟩ + · change ∀ i j,smallView small z false i j=smallQ small B z i j at h + simp_rw [h] + · apply Int.natCast_inj.mp + simp only [Nat.cast_sum] + symm + simp_rw [h.2,transferInt] + simp only [Finset.sum_add_distrib,Finset.sum_sub_distrib,ite_and] + simp + +lemma pattern_small_totals (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (hz : Pattern small B z) : + (∑ i,smallRow small (smallView small z false) i)= + ∑ j,smallColumn small B (smallView small z true) j := by + have hrow (i : I) : smallRow small (smallView small z false) i= + ∑ j,smallView small z false i j := by + unfold smallRow + apply Finset.sum_congr rfl + intro j _ + by_cases hs : small i j=true + · simp only [hs,ite_true] + · simp [smallView,hs] + have hcol (j : J) : smallColumn small B (smallView small z true) j= + ∑ i,smallQ small B z i j := by + unfold smallColumn + apply Finset.sum_congr rfl + intro i _ + by_cases hs : small i j=true <;> simp [smallQ,smallView,hs] + simp_rw [hrow,hcol] + exact (pattern_view_totals small B z hz).trans Finset.sum_comm + +lemma padded_residual_totals (small : I → J → Bool) (B : I → J → ℕ) + (z : SmallProfile small) (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (hz : Pattern small B z) + (hr : ∀ i,smallRow small (smallView small z false) i≤r i) + (hc : ∀ j,smallColumn small B (smallView small z true) j≤c j) : + (∑ i,((r i-smallRow small (smallView small z false) i)+rowLargeCount small i*L))= + ∑ j,((c j-smallColumn small B (smallView small z true) j)+columnLargeCount small j*L) := by + have hs := pattern_small_totals small B z hz + have hlarge : (∑ i,rowLargeCount small i)=∑ j,columnLargeCount small j := by + unfold rowLargeCount columnLargeCount + exact Finset.sum_comm + have hrt (i : I) : ((r i-smallRow small (smallView small z false) i:ℕ):ℤ)= + (r i:ℤ)-(smallRow small (smallView small z false) i:ℤ) := Nat.cast_sub (hr i) + have hct (j : J) : ((c j-smallColumn small B (smallView small z true) j:ℕ):ℤ)= + (c j:ℤ)-(smallColumn small B (smallView small z true) j:ℤ) := Nat.cast_sub (hc j) + apply Int.natCast_inj.mp + simp only [Nat.cast_sum,Nat.cast_add,Nat.cast_mul] + simp_rw [hrt,hct] + simp only [Finset.sum_add_distrib,Finset.sum_sub_distrib,←Finset.sum_mul,←Nat.cast_sum] + rw [htotal,hs,hlarge] + +/-- The executable tests need bounds, a local pattern and the row/column +inequalities, with equality on small incident margins. No completion +enumeration or additional residual-total oracle is necessary. -/ +theorem profileFeasible_of_lineTests (r : I → ℕ) (c : J → ℕ) + (htotal : (∑ i,r i)=∑ j,c j) (z : SmallProfile (paperSmall r c)) + (hb : ∀ a,z a ≤ stateCapacity r c a.1.val.1 a.1.val.2) + (hp : Pattern (paperSmall r c) (stateCapacity r c) z) + (hr : ∀ i,smallRow (paperSmall r c) (smallView (paperSmall r c) z false) i≤r i ∧ + (r i<(dimensionAllowance (I := I) (J := J))^20 → + smallRow (paperSmall r c) (smallView (paperSmall r c) z false) i=r i)) + (hc : ∀ j,smallColumn (paperSmall r c) (stateCapacity r c) + (smallView (paperSmall r c) z true) j≤c j ∧ + (c j<(dimensionAllowance (I := I) (J := J))^20 → + smallColumn (paperSmall r c) (stateCapacity r c) + (smallView (paperSmall r c) z true) j=c j)) : + ProfileFeasible r c z := by + refine ⟨hb,hp,⟨fun i => (hr i).1,fun j => (hc j).1⟩,?_,?_,?_⟩ + · intro i hi + have hi' : r i<(dimensionAllowance (I := I) (J := J))^20 := by omega + unfold profileRows + rw [(hr i).2 hi'] + simp [rowLargeCount,paperSmall,firstPaperSmall,hi'] + · intro j hj + have hj' : c j<(dimensionAllowance (I := I) (J := J))^20 := by omega + unfold profileColumns + rw [(hc j).2 hj'] + simp [columnLargeCount,paperSmall,firstPaperSmall,hj'] + · exact padded_residual_totals _ _ z r c _ htotal hp (fun i => (hr i).1) (fun j => (hc j).1) + +lemma profileFeasible_lineTests (r : I → ℕ) (c : J → ℕ) + (z : SmallProfile (paperSmall r c)) (h : ProfileFeasible r c z) : + (∀ i,smallRow (paperSmall r c) (smallView (paperSmall r c) z false) i≤r i ∧ + (r i<(dimensionAllowance (I := I) (J := J))^20 → + smallRow (paperSmall r c) (smallView (paperSmall r c) z false) i=r i)) ∧ + (∀ j,smallColumn (paperSmall r c) (stateCapacity r c) + (smallView (paperSmall r c) z true) j≤c j ∧ + (c j<(dimensionAllowance (I := I) (J := J))^20 → + smallColumn (paperSmall r c) (stateCapacity r c) + (smallView (paperSmall r c) z true) j=c j)) := by + constructor + · intro i + refine ⟨h.residuals.1 i,?_⟩ + intro hi + have hz := h.rows_outside i (by omega) + unfold profileRows at hz + have hb := h.residuals.1 i + omega + · intro j + refine ⟨h.residuals.2 j,?_⟩ + intro hj + have hz := h.columns_outside j (by omega) + unfold profileColumns at hz + have hb := h.residuals.2 j + omega + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallViewLookupProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallViewLookupProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..beb62607e141d6548694fba2729af458c9129f56 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/SmallViewLookupProgram.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram + +namespace OAI + +/-! # Polynomial lookup of the sparse small-cell view -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +abbrev ViewLookupInput := (List (ℕ×ℕ)×List ℕ)×(ℕ×ℕ) + +def lookupView (z : ViewLookupInput) : ℕ := + z.1.2.getD (z.1.1.idxOf z.2) 0 + +def lookupViewRealizer : Realizer lookupView := + composition (pair (composition first second) + (composition (pair second (composition first first)) cellLookupRealizer)) (getDFast 0) + +theorem polynomial_lookupView : PolynomialTime lookupViewRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) polynomial_cellLookup)) + (polynomial_getDFast 0) + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open scoped Classical +open SmallContextCoordinates PhysicalCompletionFibres FirstPaperProfiles ProfilePrograms + +noncomputable section +variable {m n q : ℕ} (small : Fin m → Fin n → Bool) (e : Fin q ≃ Cells small) + +/-- Missing large cells yield zero, exactly as required by `smallView`. -/ +theorem lookupView_eq (z : SmallProfile small) (b : Bool) (i : Fin m) (j : Fin n) : + lookupView ((cellCatalog small e,viewList small e z b),(i.val,j.val))= + smallView small z b i j := by + unfold lookupView + rw [cellCatalog_index small e (i,j)] + by_cases hs : small i j=true + · simp only [cellIndex,dite_eq_left hs,viewList,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,(e.symm ⟨(i,j),hs⟩).isLt,dite_true,Option.getD_some, + smallView] + change z (e (e.symm ⟨(i,j),hs⟩),b)=z (⟨(i,j),hs⟩,b) + rw [Equiv.apply_symm_apply] + · simp only [cellIndex,dite_eq_right hs,viewList,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,lt_self_iff_false,dite_false,Option.getD_none,smallView] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitBoxLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitBoxLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..7682e70faa85e5c4604d027478c0147ee973d383 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitBoxLaw.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxIndex +import OAI.Combinatorics.ContingencyTables.Sampling.UnitIntegerLaw +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLawEmbedding +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # The actual adaptive profile walk embedded in its enumerable box -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] unitStepCounts profileIndex + +/-- Invalid vectors get harmless stationary rows. Every actual profile +row is exactly the computed sampler transition transported to the box. -/ +def unitBoxStep (k : BoxIndex) : IntegerLaw BoxIndex (2^(s)) := + (profileAt r c e k).elim (IntegerLaw.point (2^(s)) k) + (fun x => (unitStepCounts r c e x).push (profileIndex r c e)) + +lemma unitBoxStep_index (x : PaperStates r c) : + unitBoxStep r c e (profileIndex r c e x)= + (unitStepCounts r c e x).push (profileIndex r c e) := by + unfold unitBoxStep + rw [profileAt_index] + rfl + +lemma unitBoxWalk_count (x : PaperStates r c) (N : ℕ) (k : BoxIndex) : + (IntegerLaw.walk (unitBoxStep r c e) (profileIndex r c e x) N).count k= + ((unitWalkCounts r c e x N).push (profileIndex r c e)).count k := + IntegerLaw.walk_push_count (unitStepCounts r c e) + (unitBoxStep r c e) (profileIndex r c e) + (unitBoxStep_index r c e) x N k + +lemma unitBoxWalk_actual_count (x y : PaperStates r c) (N : ℕ) : + (IntegerLaw.walk (unitBoxStep r c e) (profileIndex r c e x) N).count + (profileIndex r c e y)=(unitWalkCounts r c e x N).count y := by + rw [unitBoxWalk_count] + exact IntegerLaw.push_count_injective _ _ (profileIndex_injective r c e) y + +/-- Matrix propagation computes all box masses, including the zero +masses of invalid vectors, without enumerating random histories. -/ +lemma unitBox_iterate (x : PaperStates r c) (N : ℕ) : + IntegerMatrixPrograms.iterate (N, + (List.ofFn (fun target : BoxIndex => List.ofFn (fun source : BoxIndex => + (unitBoxStep r c e source).count target)), + List.ofFn (fun k : BoxIndex => if k=profileIndex r c e x then 1 else 0)))= + List.ofFn (fun k : BoxIndex => + ((unitWalkCounts r c e x N).push (profileIndex r c e)).count k) := by + rw [IntegerMatrixPrograms.iterate_ofFn] + apply congrArg List.ofFn + funext k + exact unitBoxWalk_count r c e x N k + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitFiniteLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitFiniteLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..82aa813cfaea6d5b2a60e32657397beb09b627fb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitFiniteLaw.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitProfileSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallOuter + +namespace OAI + +/-! # The computed all-small walk has the proved uniform sampling law -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms FirstPaperPhysicalMarginal CompletionCounts +open FirstSuccess FairBits CompletionTranslation SmallContextCoordinates ResidualMixture +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +attribute [local irreducible] FirstSuccess.mapLaw + +private lemma mapped_walk_decidableEq_irrel {X Y : Type*} [Fintype X] [Fintype Y] + (dX eX : DecidableEq X) (dY eY : DecidableEq Y) + (K : X → RationalLaw X) (x : X) (n : ℕ) (f : X → Y) : + @mapLaw X Y _ _ dY (@walkLaw X _ dX K x n) f= + @mapLaw X Y _ _ eY (@walkLaw X _ eX K x n) f := by + cases Subsingleton.elim dX eX + cases Subsingleton.elim dY eY + rfl + +lemma unitCodeBitStep_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin s → Bool)) (unitCodeBitStep r c e x)=unitSmallStep r c x := by + have hp := decodedCodeProposal_law r c e htotal x + calc + _ = mapLaw (mapLaw (uniformLaw (α := Fin s → Bool)) (decodedCodeProposal r c e x)) + (fun z => z.getD x) := (mapLaw_comp _ _ _).symm + _ = mapLaw (smallProposalLaw r c x) (fun z => z.getD x) := + congrArg (fun p : RationalLaw (Option (PaperStates r c)) => mapLaw p (fun z => z.getD x)) + hp + _ = _ := by + unfold unitSmallStep proposalStayLaw smallProposalLaw + exact mapLaw_decidableEq_irrel _ _ _ _ + +def flatUnitCodeWalk (x : PaperStates r c) (n : ℕ) (bits : Fin (n*s) → Bool) : PaperStates r c := + wordWalk (unitCodeBitStep r c e) x n (GridBoundary.gridWordEquiv n s bits) + +lemma flatUnitCodeWalk_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (flatUnitCodeWalk r c e x n)= + walkLaw (unitSmallStep r c) x n := by + unfold flatUnitCodeWalk + rw [←map_equiv (GridBoundary.gridWordEquiv n s),uniform_equiv] + change wordWalkLaw _ _ _=_ + rw [wordWalkLaw_eq] + exact congrArg (fun K => walkLaw K x n) (funext (unitCodeBitStep_law r c e htotal)) + +def unitCodeJointDraw (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n : ℕ) (bits : Fin (n*s) → Bool) : PaperStateJoint r c := + let z := flatUnitCodeWalk r c e x n bits + ⟨z,fallback z⟩ + +lemma unitCodeJointDraw_law (htotal : (∑ i,r i)=∑ j,c j) + (fallback : (z : PaperStates r c) → PaperFibre r c z) (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (unitCodeJointDraw r c e fallback x n)= + mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (unitJointDraw r c fallback x n) := by + calc + _ = mapLaw (mapLaw (uniformLaw (α := Fin (n*s) → Bool)) (flatUnitCodeWalk r c e x n)) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c)) := + (mapLaw_comp _ (flatUnitCodeWalk r c e x n) + (fun z => (⟨z,fallback z⟩ : PaperStateJoint r c))).symm + _ = _ := by + rw [flatUnitCodeWalk_law r c e htotal] + exact (mapped_walk_decidableEq_irrel _ _ _ _ _ _ _ _).trans + ((unitJointDraw_law r c fallback x n).symm.trans + (mapLaw_decidableEq_irrel _ _ _ _)) + +def unitCodeOuterDraw (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n M : ℕ) (z₀ : Table r c) + (bits : Fin (M*(n*s)) → Bool) : Table r c := + wordRetry (fun w => stateTrial r c (unitCodeJointDraw r c e fallback x n w)) z₀ M + (GridBoundary.gridWordEquiv M (n*s) bits) + +lemma unitCodeOuterDraw_law (htotal : (∑ i,r i)=∑ j,c j) + (fallback : (z : PaperStates r c) → PaperFibre r c z) + (x : PaperStates r c) (n M : ℕ) (z₀ : Table r c) : + mapLaw (uniformLaw (α := Fin (M*(n*s)) → Bool)) + (unitCodeOuterDraw r c e fallback x n M z₀)= + mapLaw (uniformLaw (α := Fin (M*(n*s)) → Bool)) + (unitOuterDraw r c fallback x n M z₀) := by + unfold unitCodeOuterDraw + rw [←map_equiv (GridBoundary.gridWordEquiv M (n*s)),uniform_equiv] + change wordRetryLaw _ _ _=_ + rw [wordRetryLaw_eq,←retryLaw_map,unitCodeJointDraw_law r c e htotal,unitOuterDraw_law] + exact congrArg (fun p : RationalLaw (PaperStateJoint r c) => + retryLaw p (stateTrial r c) z₀ M) (mapLaw_decidableEq_irrel _ _ _ _) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitGraphEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitGraphEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..3828dee990abdeaf66672d18ebf905bd7f0f7a79 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitGraphEnergy.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain + +namespace OAI + +/-! # Energy of the unit-weight local-proposal chain -/ + +namespace ContingencyTables.MetropolisChain + +open scoped BigOperators Classical +open CommonBasesFPRAS + +noncomputable section +variable {X : Type*} [Fintype X] [Nonempty X] + +lemma unit_chain_energy (Adj : X → X → Prop) (hsym : ∀ x y,Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) (hdegree : ∀ x,(Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D:ℝ)*β ≤ 1/2) (H : X → ℝ) : + (chain (fun _ => 1) (fun _ => by norm_num) Adj hsym β hβ D hdegree hproposal).energy H= + (β/(Fintype.card X:ℝ))*((∑ x,∑ y,if Adj x y then (H x-H y)^2 else 0)/2) := by + unfold chain + rw [FiniteChain.ofMoves_energy] + simp only [move,div_self (one_ne_zero : (1:ℝ)≠0),min_self,mul_one, + normalizer,Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + have hterm (x y : X) : + (1/(Fintype.card X:ℝ))*(if Adj x y then β else 0)*(H x-H y)^2= + (β/(Fintype.card X:ℝ))*(if Adj x y then (H x-H y)^2 else 0) := by + split_ifs <;> ring + simp_rw [hterm,←Finset.mul_sum] + ring + +end +end ContingencyTables.MetropolisChain + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitIntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitIntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5865bf755c4559df3f8416af62fa81a109017b6d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitIntegerLaw.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitFiniteLaw +import OAI.Combinatorics.ContingencyTables.Transport.ListedIntegerLaw + +namespace OAI + +/-! # Integer counts for the all-small sampler's actual random words -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open FirstSuccess FairBits CompletionCounts ResidualMixture SmallContextCoordinates +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +def unitStepCounts (x : PaperStates r c) : IntegerLaw (PaperStates r c) (2^s) := + (IntegerLaw.boolean s).push (unitCodeBitStep r c e x) + +lemma unitStepCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) : + (unitStepCounts r c e x).toRational (by positivity)=unitSmallStep r c x := by + unfold unitStepCounts + rw [IntegerLaw.toRational_push,IntegerLaw.toRational_boolean,unitCodeBitStep_law r c e htotal] + +attribute [local irreducible] unitStepCounts unitSmallStep + +def unitWalkCounts (x : PaperStates r c) (N : ℕ) : + IntegerLaw (PaperStates r c) ((2^s)^N) := IntegerLaw.walk (unitStepCounts r c e) x N + +attribute [local irreducible] unitWalkCounts + +lemma unitWalkCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (N : ℕ) : + (unitWalkCounts r c e x N).toRational (by positivity)=walkLaw (unitSmallStep r c) x N := by + unfold unitWalkCounts + rw [IntegerLaw.toRational_walk _ (by positivity)] + have he : (fun y => (unitStepCounts r c e y).toRational (by positivity))=unitSmallStep r c := by + funext y + exact unitStepCounts_law r c e htotal y + exact congrArg (fun K => walkLaw K x N) he + +def unitTrialCounts (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) (N : ℕ) : + IntegerLaw (Option (Table r c)) ((2^s)^N) := + (unitWalkCounts r c e x N).push (fun y => stateTrial r c ⟨y,allSmallFibre r c hsmall y⟩) + +def unitOuterCounts (hsmall : ∀ i j,paperSmall r c i j=true) + (x : PaperStates r c) (N J : ℕ) (fallback : Table r c) : + IntegerLaw (Table r c) (((2^s)^N)^J) := + (unitTrialCounts r c e hsmall x N).retry fallback J + +lemma unitTrialCounts_law (htotal : ∑ i,r i=∑ j,c j) + (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) (N : ℕ) : + (unitTrialCounts r c e hsmall x N).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (N*s) → Bool)) + (fun bits => stateTrial r c (unitCodeJointDraw r c e (allSmallFibre r c hsmall) x N bits)) := by + unfold unitTrialCounts unitCodeJointDraw + rw [IntegerLaw.toRational_push,unitWalkCounts_law r c e htotal,←flatUnitCodeWalk_law r c e htotal, + mapLaw_comp] + +lemma unitOuterCounts_law (htotal : ∑ i,r i=∑ j,c j) + (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) (N J : ℕ) (fallback : Table r c) : + (unitOuterCounts r c e hsmall x N J fallback).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (J*(N*s)) → Bool)) + (unitCodeOuterDraw r c e (allSmallFibre r c hsmall) x N J fallback) := by + unfold unitOuterCounts unitCodeOuterDraw + rw [IntegerLaw.toRational_retry _ (by positivity),unitTrialCounts_law r c e htotal] + rw [←map_equiv (GridBoundary.gridWordEquiv J (N*s)),uniform_equiv] + rw [retryLaw_map] + exact (wordRetryLaw_eq + (fun bits : Fin (N*s) → Bool => stateTrial r c + (unitCodeJointDraw r c e (allSmallFibre r c hsmall) x N bits)) fallback J).symm + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixEntry.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixEntry.lean new file mode 100644 index 0000000000000000000000000000000000000000..23b6bdcd54dbae823196c22e16125f566d3b55dc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixEntry.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitFiniteLaw + +namespace OAI + +/-! # Integer transition entries for the all-small walk -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +abbrev WordInput := MatrixEntryInput×List Bool + +def wordViews (z : WordInput) : List ℕ×List ℕ := + (codeNeighborProposal (sourceData z.1,z.2)).getD z.1.2.1 + +def wordViewsRealizer : Realizer wordViews := + composition (pair (composition (composition first second) first) + (composition (pair (composition first sourceDataRealizer) second) codeNeighborProposalRealizer)) + FirstSuccessProgram.defaultRealizer + +lemma polynomial_wordViews : PolynomialTime wordViewsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_sourceData) polynomial_second) + polynomial_codeNeighborProposal)) FirstSuccessProgram.polynomial_default + +def wordCount (z : WordInput) : ℕ := if wordViews z=z.1.2.2 then 1 else 0 + +def wordCountRealizer : Realizer wordCount := + (choose (composition (pair wordViewsRealizer + (composition (composition first second) second)) profileCodeEqual) + (constant 1) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq] + rfl) + +lemma polynomial_wordCount : PolynomialTime wordCountRealizer := by + unfold wordCountRealizer + apply polynomial_congr + exact polynomial_choose (polynomial_composition (polynomial_pair polynomial_wordViews + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_profileCodeEqual) (polynomial_constant 1) (polynomial_constant 0) + +def validEntry (z : MatrixEntryInput) : ℕ := + ((booleanWords z.1.2).map (fun w => wordCount (z,w))).sum + +def entryWords (z : MatrixEntryInput) : MatrixEntryInput×List (List Bool) := + (z,booleanWords z.1.2) + +def entryWordsRealizer : Realizer entryWords := + pair identity (composition (f := fun z : MatrixEntryInput => z.1.2) + (g := booleanWords) (composition first second) booleanWordsRealizer) + +def wordSum (z : MatrixEntryInput×List (List Bool)) : ℕ := + (z.2.map (fun w => wordCount (z.1,w))).sum + +def wordSumRealizer : Realizer wordSum := composition (mapWith wordCountRealizer) listSum + +lemma polynomial_wordSum : PolynomialTime wordSumRealizer := + polynomial_composition (polynomial_mapWith polynomial_wordCount) polynomial_listSum + +def validEntryRealizer : Realizer validEntry := + composition (f := entryWords) (g := wordSum) entryWordsRealizer wordSumRealizer + +attribute [local irreducible] wordCount wordViews wordCountRealizer wordViewsRealizer + +def entryMeasure (z : MatrixEntryInput) : ℕ := gridStateCount (z.1.2,2)+weight z + +lemma work_entryWords : WorkBound entryWordsRealizer entryMeasure := by + have hi (z : MatrixEntryInput) : weight z ≤ X.eval (entryMeasure z) := by + simp only [Polynomial.eval_X,entryMeasure] + omega + have hw : WorkBound (composition (f := fun z : MatrixEntryInput => z.1.2) + (g := booleanWords) (composition first second) booleanWordsRealizer) entryMeasure := by + apply work_composition (work_of_polynomial + (polynomial_composition polynomial_first polynomial_second) X hi) work_booleanWords X + intro z + have hh : weight z.1.2 ≤ weight z := (weight_snd z.1).trans (weight_fst z) + simp only [Polynomial.eval_X,entryMeasure,Function.comp_apply] + omega + unfold entryWordsRealizer + exact work_pair (work_of_polynomial polynomial_identity X hi) hw X hi + +lemma work_validEntry : WorkBound validEntryRealizer entryMeasure := by + obtain ⟨p,hp⟩ := work_entryWords + obtain ⟨q,hq⟩ := polynomial_wordSum + refine ⟨p+q.comp p,fun z => ?_⟩ + have h1 := hp z + have h2 := hq (entryWords z) + have h3 := polynomial_eval_monotone q ((Nat.le_add_left _ _).trans h1) + dsimp only at h3 + simp only [Polynomial.eval_add,Polynomial.eval_comp] + unfold validEntryRealizer validEntry + change entryWordsRealizer.cost z+wordSumRealizer.cost (entryWords z)+ + weight (wordSum (entryWords z))≤_ + omega + +def denominator (z : MatrixParameters) : ℕ := BinaryPowerPrograms.power (2,z.2.length) + +def denominatorRealizer : Realizer denominator := + composition (pair (constant 2) (composition second listLength)) BinaryPowerPrograms.powerRealizer + +lemma work_denominator : WorkBound denominatorRealizer (fun z => weight z) := by + unfold denominatorRealizer + apply work_composition (work_of_polynomial (polynomial_pair (polynomial_constant 2) + (polynomial_composition polynomial_second polynomial_listLength)) X (fun _ => by simp)) + BinaryPowerPrograms.work_power (X+9) + intro z + change z.2.length+weight (2:ℕ) ≤ (X+9).eval (weight z) + have htwo : weight (2:ℕ) ≤ 9 := by simpa using weight_nat_numeric 2 + have hl := (list_length_le_weight z.2).trans (weight_snd z) + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat] + omega + +def diagonalEntry (z : MatrixEntryInput) : ℕ := + if z.2.1=z.2.2 then denominator z.1 else 0 + +def diagonalEntryRealizer : Realizer diagonalEntry := + (choose (composition second profileCodeEqual) (composition first denominatorRealizer) + (constant 0)).congr (by intro z; simp only [Function.comp_apply,decide_eq_true_eq]; rfl) + +lemma work_diagonalEntry : WorkBound diagonalEntryRealizer entryMeasure := by + have hi (z : MatrixEntryInput) : weight z ≤ X.eval (entryMeasure z) := by + simp only [Polynomial.eval_X,entryMeasure] + omega + have hd : WorkBound (composition (first (B := (List ℕ×List ℕ)×(List ℕ×List ℕ))) + denominatorRealizer) entryMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_denominator X + intro z + simpa only [Polynomial.eval_X,Function.comp_apply] using (weight_fst z).trans (hi z) + unfold diagonalEntryRealizer + apply work_congr + exact work_choose (work_of_polynomial (polynomial_composition polynomial_second + polynomial_profileCodeEqual) X hi) hd (work_of_polynomial (polynomial_constant 0) X hi) X hi + +def matrixEntry (z : MatrixEntryInput) : ℕ := + if profileTest (sourceData z) then validEntry z else diagonalEntry z + +def matrixEntryRealizer : Realizer matrixEntry := + choose (composition sourceDataRealizer profileTestRealizer) validEntryRealizer diagonalEntryRealizer + +lemma work_matrixEntry : WorkBound matrixEntryRealizer entryMeasure := by + unfold matrixEntryRealizer + exact work_choose (work_of_polynomial (polynomial_composition polynomial_sourceData + polynomial_profileTest) X (fun z => by simp only [Polynomial.eval_X,entryMeasure]; omega)) + work_validEntry work_diagonalEntry X (fun z => by simp only [Polynomial.eval_X,entryMeasure]; omega) + +end ContingencyTables.UnitCountPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..88730f300dd5d2128ffa3ff5557ca38532b5c25f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixLaw.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitBoxLaw +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalSemantics + +namespace OAI + +/-! # The all-small matrix computes its actual finite-word law -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical + +lemma push_push_count {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq B] [DecidableEq C] {Q : ℕ} (p : IntegerLaw A Q) + (f : A → B) (g : B → C) (c : C) : + ((p.push f).push g).count c=(p.push (g ∘ f)).count c := by + calc + _ = ∑ b,(p.push f).count b*(if g b=c then 1 else 0) := by + apply Finset.sum_congr rfl + intro b _ + by_cases h : g b=c <;> simp only [h,ite_true,ite_false,mul_one,mul_zero] + _ = ∑ a,p.count a*(if g (f a)=c then 1 else 0) := sum_push_mul p f _ + _ = _ := by + apply Finset.sum_congr rfl + intro a _ + by_cases h : g (f a)=c <;> simp only [h,Function.comp_apply,ite_true,ite_false,mul_one,mul_zero] + +lemma push_count_sum {A B : Type*} [Fintype A] [Fintype B] [DecidableEq B] + {Q : ℕ} (p : IntegerLaw A Q) (f : A → B) (b : B) : + (p.push f).count b=∑ a,if f a=b then p.count a else 0 := rfl + +lemma boolean_push_count {B : Type*} [Fintype B] [DecidableEq B] (s : ℕ) + (f : (Fin s → Bool) → B) (b : B) : + ((boolean s).push f).count b=∑ bits,if f bits=b then 1 else 0 := rfl + +end ContingencyTables.IntegerLaw + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) (b h : ℕ) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] stateCode stateCodeData profileIndex profileAt matrixInput + UnitCountPrograms.matrixEntry unitStepCounts + +lemma unit_wordViews_actual (htotal : ∑ i,r i=∑ j,c j) (z x : PaperStates r c) + (xs : List Bool) (v : List ℕ×List ℕ) (bits : Fin s → Bool) : + UnitCountPrograms.wordViews ((matrixInput r c e b h z xs,(stateCode r c e x,v)),List.ofFn bits)= + stateCode r c e (unitCodeBitStep r c e x bits) := by + unfold UnitCountPrograms.wordViews + rw [sourceData_input,candidate_stateCodeData,codeProposal_encoded r c e htotal x bits] + cases hp : decodedCodeProposal r c e x bits <;> + simp only [Option.map_none,Option.map_some,Option.getD_none,Option.getD_some,unitCodeBitStep,hp] + +lemma unitStepCounts_push_count (x : PaperStates r c) (j : BoxIndex) : + ((unitStepCounts r c e x).push (profileIndex r c e)).count j= + ∑ bits : Fin s → Bool,if profileIndex r c e (unitCodeBitStep r c e x bits)=j then 1 else 0 := by + unfold unitStepCounts + rw [IntegerLaw.push_push_count] + exact IntegerLaw.boolean_push_count s + (profileIndex r c e ∘ unitCodeBitStep r c e x) j + +lemma unit_wordCount_actual (htotal : ∑ i,r i=∑ j,c j) (z x : PaperStates r c) + (xs : List Bool) (j : BoxIndex) (bits : Fin s → Bool) : + UnitCountPrograms.wordCount + ((matrixInput r c e b h z xs,(stateCode r c e x,boxCode j)),List.ofFn bits)= + if profileIndex r c e (unitCodeBitStep r c e x bits)=j then 1 else 0 := by + unfold UnitCountPrograms.wordCount + rw [unit_wordViews_actual r c e b h htotal z x xs (boxCode j) bits,←boxCode_index r c e] + have he (a b : BoxIndex) : boxCode a=boxCode b ↔ a=b := + (boxCode_injective (m := m) (n := n) (q := q)).eq_iff + simp only [he] + +lemma unit_validEntry_actual (htotal : ∑ i,r i=∑ j,c j) (z x : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (j : BoxIndex) : + UnitCountPrograms.validEntry (matrixInput r c e b h z xs,(stateCode r c e x,boxCode j))= + ((unitStepCounts r c e x).push (profileIndex r c e)).count j := by + unfold UnitCountPrograms.validEntry + have hxs : (matrixInput r c e b h z xs).2=xs := by unfold matrixInput; rfl + rw [hxs] + change ((booleanWords xs).map (fun w => UnitCountPrograms.wordCount + ((matrixInput r c e b h z xs,(stateCode r c e x,boxCode j)),w))).sum=_ + rw [sum_booleanWords xs s hs,unitStepCounts_push_count] + apply Finset.sum_congr rfl + intro bits _ + exact unit_wordCount_actual r c e b h htotal z x xs j bits + +lemma unit_matrixEntry_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (i j : BoxIndex) : + UnitCountPrograms.matrixEntry (matrixInput r c e b h z xs,(boxCode i,boxCode j))= + (unitBoxStep r c e i).count j := by + cases hi : profileAt r c e i with + | none => + have hp := boxCode_test_false r c e htotal z i hi + unfold UnitCountPrograms.matrixEntry + rw [sourceData_input,hp] + simp only [Bool.false_eq_true,ite_false] + unfold UnitCountPrograms.diagonalEntry UnitCountPrograms.denominator + unfold unitBoxStep + rw [hi] + simp only [Option.elim_none,IntegerLaw.point] + unfold matrixInput + rw [BinaryPowerPrograms.power_eq,hs] + have he (a b : BoxIndex) : boxCode a=boxCode b ↔ a=b := + (boxCode_injective (m := m) (n := n) (q := q)).eq_iff + simp only [he,eq_comm] + | some x => + have hix : profileIndex r c e x=i := (profileAt_eq_some r c e i x).mp hi + have hcode : boxCode i=stateCode r c e x := by rw [←hix,boxCode_index] + rw [hcode] + unfold UnitCountPrograms.matrixEntry + rw [sourceData_input] + have hx := (test_candidate_iff r c e htotal z (stateCode r c e x)).mpr ⟨x,rfl⟩ + rw [hx] + simp only [ite_true] + unfold unitBoxStep + rw [hi] + exact unit_validEntry_actual r c e b h htotal z x xs hs j + +lemma unit_profileMatrix_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) : + UnitCountPrograms.profileMatrix (matrixInput r c e b h z xs)= + List.ofFn (fun j : BoxIndex => List.ofFn (fun i : BoxIndex => + (unitBoxStep r c e i).count j)) := by + have hv : profileBoxViews (matrixData (matrixInput r c e b h z xs))= + List.ofFn (boxCode (m := m) (n := n) (q := q)) := by + unfold matrixData matrixInput + exact profileBoxViews_actual r c e z + unfold UnitCountPrograms.profileMatrix + rw [hv,List.map_ofFn] + apply congrArg List.ofFn + funext j + dsimp only [Function.comp_apply] + unfold UnitCountPrograms.matrixColumn + dsimp only [Prod.fst] + rw [hv,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact unit_matrixEntry_actual r c e b h htotal z xs hs i j + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d49abb71c1ddaa6a6261e83434b35ed468ac85fe --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitMatrixProgram.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixEntry + +namespace OAI + +/-! # Constructing the finite transition matrix by deterministic enumeration -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +abbrev MatrixColumnInput := MatrixParameters×(List ℕ×List ℕ) +abbrev MatrixColumnEntryInput := MatrixColumnInput×(List ℕ×List ℕ) + +def columnEntryInput (z : MatrixColumnEntryInput) : MatrixEntryInput := + (z.1.1,(z.2,z.1.2)) + +def columnEntryInputRealizer : Realizer columnEntryInput := + pair (composition first first) (pair second (composition first second)) + +lemma polynomial_columnEntryInput : PolynomialTime columnEntryInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_second)) + +def columnEntry (z : MatrixColumnEntryInput) : ℕ := matrixEntry (columnEntryInput z) + +def columnEntryRealizer : Realizer columnEntry := + composition (f := columnEntryInput) (g := matrixEntry) columnEntryInputRealizer matrixEntryRealizer + +def columnEntryMeasure (z : MatrixColumnEntryInput) : ℕ := + entryMeasure (columnEntryInput z) + +lemma work_columnEntry : WorkBound columnEntryRealizer columnEntryMeasure := by + unfold columnEntryRealizer + apply work_composition (work_of_polynomial polynomial_columnEntryInput X _) work_matrixEntry X + · intro z + simp only [columnEntryMeasure,Polynomial.eval_X] + exact le_rfl + · intro z + have hz : weight z=weight (columnEntryInput z) := by + rcases z with ⟨⟨p,t⟩,s⟩ + simp only [columnEntryInput,weight_prod] + omega + simp only [Polynomial.eval_X,columnEntryMeasure,entryMeasure] + omega + +def matrixColumn (z : MatrixColumnInput) : List ℕ := + (profileBoxViews (matrixData z.1)).map (fun source => columnEntry (z,source)) + +def matrixColumnRealizer : Realizer matrixColumn := + composition (f := fun z : MatrixColumnInput => (z,profileBoxViews (matrixData z.1))) + (g := fun z : MatrixColumnInput×List (List ℕ×List ℕ) => + z.2.map (fun source => columnEntry (z.1,source))) + (pair identity (composition + (f := fun z : MatrixColumnInput => matrixData z.1) (g := profileBoxViews) + (composition (f := fun z : MatrixColumnInput => z.1) (g := matrixData) + first matrixDataRealizer) profileBoxViewsRealizer)) (mapWith columnEntryRealizer) + +def matrixColumnMeasure (z : MatrixColumnInput) : ℕ := + gridStateCount (profileEnumerationData (matrixData z.1))+ + MeasuredMap.listMeasure columnEntryMeasure (z,profileBoxViews (matrixData z.1)) + +lemma work_matrixColumn : WorkBound matrixColumnRealizer matrixColumnMeasure := by + have hin (z : MatrixColumnInput) : weight z ≤ matrixColumnMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := weight_fst (z,profileBoxViews (matrixData z.1)) + simp only [matrixColumnMeasure,MeasuredMap.listMeasure] + omega + have hd : PolynomialTime (composition (first (B := List ℕ×List ℕ)) matrixDataRealizer) := + polynomial_composition polynomial_first polynomial_matrixData + have hv : WorkBound (composition (composition first matrixDataRealizer) profileBoxViewsRealizer) + matrixColumnMeasure := by + apply work_composition (work_of_polynomial hd X (fun z => by simpa using hin z)) + work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z.1) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans + ((weight_fst _).trans (weight_fst z)))) + simp only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + matrixColumnMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := weight_fst (z,profileBoxViews (matrixData z.1)) + omega + unfold matrixColumnRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_columnEntry) X + intro z + simp only [Polynomial.eval_X,matrixColumnMeasure,Function.comp_apply,id_eq] + omega + +def profileMatrix (z : MatrixParameters) : List (List ℕ) := + (profileBoxViews (matrixData z)).map (fun target => matrixColumn (z,target)) + +def profileMatrixRealizer : Realizer profileMatrix := + composition (f := fun z : MatrixParameters => (z,profileBoxViews (matrixData z))) + (g := fun z : MatrixParameters×List (List ℕ×List ℕ) => + z.2.map (fun target => matrixColumn (z.1,target))) + (pair identity (composition (f := matrixData) (g := profileBoxViews) + matrixDataRealizer profileBoxViewsRealizer)) (mapWith matrixColumnRealizer) + +def profileMatrixMeasure (z : MatrixParameters) : ℕ := + gridStateCount (profileEnumerationData (matrixData z))+ + MeasuredMap.listMeasure matrixColumnMeasure (z,profileBoxViews (matrixData z)) + +lemma work_profileMatrix : WorkBound profileMatrixRealizer profileMatrixMeasure := by + have hin (z : MatrixParameters) : weight z ≤ profileMatrixMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z)) := weight_fst (z,profileBoxViews (matrixData z)) + simp only [profileMatrixMeasure,MeasuredMap.listMeasure] + omega + have hv : WorkBound (composition matrixDataRealizer profileBoxViewsRealizer) + profileMatrixMeasure := by + apply work_composition (work_of_polynomial polynomial_matrixData X + (fun z => by simpa using hin z)) work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans (weight_fst z))) + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + profileMatrixMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z)) := weight_fst (z,profileBoxViews (matrixData z)) + omega + unfold profileMatrixRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_matrixColumn) X + intro z + simp only [Polynomial.eval_X,profileMatrixMeasure,Function.comp_apply,id_eq] + omega + +end ContingencyTables.UnitCountPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOriginalVector.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOriginalVector.lean new file mode 100644 index 0000000000000000000000000000000000000000..995f127284adfaca9fd8816c1a7010e9a9f45920 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOriginalVector.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTerminalSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxLaw + +namespace OAI + +/-! # Computing trial counts on every original-table candidate -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +abbrev OptionalTrialInput := WalkCountInput×Option MatrixCode + +def optionalTrialInput (z : OptionalTrialInput) : TrialCountInput := (z.1,z.2.getD []) + +def optionalTrialInputRealizer : Realizer optionalTrialInput := + pair first (composition (pair (constant ([] : MatrixCode)) second) FirstSuccessProgram.defaultRealizer) + +lemma polynomial_optionalTrialInput : PolynomialTime optionalTrialInputRealizer := + polynomial_pair polynomial_first (polynomial_composition + (polynomial_pair (polynomial_constant []) polynomial_second) FirstSuccessProgram.polynomial_default) + +def optionalTrialCount (z : OptionalTrialInput) : ℕ := + if z.2.isSome then trialCount (optionalTrialInput z) else 0 + +def optionalTrialCountRealizer : Realizer optionalTrialCount := + choose (composition second FirstSuccessProgram.isSomeRealizer) + (composition (f := optionalTrialInput) (g := trialCount) + optionalTrialInputRealizer trialCountRealizer) (constant 0) + +def optionalTrialMeasure (z : OptionalTrialInput) : ℕ := + trialCountMeasure (optionalTrialInput z)+weight z + +lemma work_optionalTrialCount : WorkBound optionalTrialCountRealizer optionalTrialMeasure := by + have hi (z : OptionalTrialInput) : weight z ≤ X.eval (optionalTrialMeasure z) := by + simp only [Polynomial.eval_X,optionalTrialMeasure] + omega + have ht : WorkBound (composition optionalTrialInputRealizer trialCountRealizer) + optionalTrialMeasure := by + apply work_composition (work_of_polynomial polynomial_optionalTrialInput X hi) work_trialCount X + intro z + simp only [Polynomial.eval_X,optionalTrialMeasure] + omega + unfold optionalTrialCountRealizer + exact work_choose (work_of_polynomial (polynomial_composition polynomial_second + FirstSuccessProgram.polynomial_isSome) X hi) ht + (work_of_polynomial (polynomial_constant 0) X hi) X hi + +abbrev TrialVectorInput := WalkCountInput×CompletionMargins + +def trialVector (z : TrialVectorInput) : List ℕ := + (originalCandidates z.2).map (fun o => optionalTrialCount (z.1,o)) + +def trialVectorRealizer : Realizer trialVector := + composition (f := fun z : TrialVectorInput => (z.1,originalCandidates z.2)) + (g := fun z : WalkCountInput×List (Option MatrixCode) => + z.2.map (fun o => optionalTrialCount (z.1,o))) + (pair first (composition second originalCandidatesRealizer)) + (mapWith optionalTrialCountRealizer) + +def trialVectorMeasure (z : TrialVectorInput) : ℕ := + originalEnumerationMeasure z.2+ + MeasuredMap.listMeasure optionalTrialMeasure (z.1,originalCandidates z.2)+weight z + +lemma work_trialVector : WorkBound trialVectorRealizer trialVectorMeasure := by + have hi (z : TrialVectorInput) : weight z ≤ X.eval (trialVectorMeasure z) := by + simp only [Polynomial.eval_X,trialVectorMeasure] + omega + have he : WorkBound (composition (second (A := WalkCountInput)) originalCandidatesRealizer) + trialVectorMeasure := by + apply work_composition (work_of_polynomial polynomial_second X hi) work_originalCandidates X + intro z + simp only [Polynomial.eval_X,trialVectorMeasure] + omega + unfold trialVectorRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_first X hi) he X hi) + (MeasuredMap.work_mapWith _ _ work_optionalTrialCount) X + intro z + simp only [Polynomial.eval_X,trialVectorMeasure,Function.comp_apply] + omega + +end ContingencyTables.UnitCountPrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms UnitCountPrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts OriginalTableBox +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (b h : ℕ) (hsmall : ∀ i j,paperSmall r c i j=true) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +attribute [local irreducible] UnitCountPrograms.trialCount unitTrialCounts matrixInput + +lemma unit_trialVector_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) : + UnitCountPrograms.trialVector ((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)), + (List.ofFn r,List.ofFn c))= + List.ofFn (fun k : OriginalTableBox.Index m n (∑ i,r i) => + (OriginalBoxLaw.law r c le_rfl (unitTrialCounts r c e hsmall z N)).count (some k)) := by + unfold UnitCountPrograms.trialVector + rw [candidates_code,List.map_ofFn] + apply congrArg List.ofFn + funext k + rw [OriginalBoxLaw.count_some] + dsimp only [Function.comp_apply] + cases he : tableAt r c k with + | none => rfl + | some T => + simp only [Option.map_some,UnitCountPrograms.optionalTrialCount,Option.isSome_some,ite_true,UnitCountPrograms.optionalTrialInput, + Option.getD_some,Option.elim_some] + exact unit_trialCount_actual r c e b h htotal hsmall z xs hs N T + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOuterVector.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOuterVector.lean new file mode 100644 index 0000000000000000000000000000000000000000..309342ce7f1f1a00ed57a54f52a3a432058accdc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOuterVector.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitOriginalVector +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableIndex +import OAI.Combinatorics.ContingencyTables.Machines.VectorRetryProgram + +namespace OAI + +/-! # Computed first-success counts over the original-table box -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +/-- Walk data and margins; trial markers, denominator, and fallback matrix. -/ +abbrev OuterVectorInput := TrialVectorInput×((List Bool×ℕ)×MatrixCode) + +def outerVectorInput (z : OuterVectorInput) : VectorRetryPrograms.Input := + (z.2.1,(trialVector z.1,originalIndex (z.1.2,z.2.2))) + +def outerVectorInputRealizer : Realizer outerVectorInput := + pair (composition second first) + (pair (composition (f := fun z : OuterVectorInput => z.1) (g := trialVector) + first trialVectorRealizer) + (composition (f := fun z : OuterVectorInput => (z.1.2,z.2.2)) (g := originalIndex) + (pair (composition first second) (composition second second)) originalIndexRealizer)) + +def outerVectorMeasure (z : OuterVectorInput) : ℕ := trialVectorMeasure z.1+weight z + +lemma work_outerVectorInput : WorkBound outerVectorInputRealizer outerVectorMeasure := by + have hi (z : OuterVectorInput) : weight z ≤ X.eval (outerVectorMeasure z) := by + simp only [Polynomial.eval_X,outerVectorMeasure] + omega + have hv : WorkBound (composition (first (B := (List Bool×ℕ)×MatrixCode)) trialVectorRealizer) + outerVectorMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_trialVector X + intro z + simp only [Polynomial.eval_X,outerVectorMeasure] + omega + have hp : PolynomialTime (composition + (f := fun z : OuterVectorInput => (z.1.2,z.2.2)) (g := originalIndex) + (pair (composition first second) (composition second second)) originalIndexRealizer) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_originalIndex + unfold outerVectorInputRealizer + exact work_pair (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) X hi) + (work_pair hv (work_of_polynomial hp X hi) X hi) X hi + +attribute [local irreducible] outerVectorInput + +def outerVector (z : OuterVectorInput) : List ℕ := VectorRetryPrograms.counts (outerVectorInput z) + +def outerVectorRealizer : Realizer outerVector := + composition (f := outerVectorInput) (g := VectorRetryPrograms.counts) + outerVectorInputRealizer VectorRetryPrograms.countsRealizer + +lemma work_outerVector : WorkBound outerVectorRealizer outerVectorMeasure := by + unfold outerVectorRealizer + exact work_then_polynomial work_outerVectorInput VectorRetryPrograms.polynomial_counts + +end ContingencyTables.UnitCountPrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms UnitCountPrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts OriginalTableBox +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (b h : ℕ) (hsmall : ∀ i j,paperSmall r c i j=true) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +attribute [local irreducible] UnitCountPrograms.trialVector unitTrialCounts matrixInput UnitCountPrograms.outerVectorInput + +lemma unit_outerVector_actual (htotal : ∑ i,r i=∑ j,c j) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) (js : List Bool) (fallback : Table r c) : + UnitCountPrograms.outerVector (((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)), + (List.ofFn r,List.ofFn c)),((js,(2^s)^N),matrixCode fallback.val))= + List.ofFn ((OriginalBoxLaw.law r c le_rfl + (unitTrialCounts r c e hsmall z N)).retry + (OriginalTableBox.index r c le_rfl fallback) js.length).count := by + unfold UnitCountPrograms.outerVector UnitCountPrograms.outerVectorInput + rw [unit_trialVector_actual r c e b h hsmall htotal z xs hs N,originalIndex_actual] + exact VectorRetryPrograms.counts_actual _ js _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOutputSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOutputSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..e82f42cba68cbbdc2163c8ac8602a2da1e2127ea --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitOutputSemantics.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedOutputSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallInitialization + +namespace OAI + +/-! # Reconstructing the original table when every cell is small -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open FirstPaperProfiles PaddedCompletions CompletionCounts SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "U" => d^20 +local notation "L" => d^12 + +def unitOutputData (x : PaperStates r c) : OuterTableData := + outputData ((stateCodeData r c e x,L),[]) + +lemma unitOutputEntry (hsmall : ∀ i j,paperSmall r c i j=true) + (x : PaperStates r c) (i : Fin m) (j : Fin n) : + outputEntry (unitOutputData r c e x,(i.val,j.val))= + (allSmallFibre r c hsmall x).val.val.1 i j := by + have he := outputEntry_small (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c L x) + (largeIndices (U,List.ofFn r)) (largeIndices (U,List.ofFn c)) U L [] i j (hsmall i j) + apply he.trans + simpa only [smallView,hsmall i j,dite_true] using + ((allSmallFibre r c hsmall x).property.2.2.1 i j (hsmall i j)).1.symm + +lemma unitOutputSuccess (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) : + outerSuccess (unitOutputData r c e x)=true ↔ + StateJointSuccess r c ⟨x,allSmallFibre r c hsmall x⟩ := by + change (balancedTest (stateCode r c e x,U) && paddingTest (L,[]))=true ↔ _ + simp only [paddingTest,List.all_nil,Bool.and_true] + rw [balancedTest_stateCode] + constructor + · intro h + refine ⟨h,?_⟩ + intro i j hij + rw [hsmall i j] at hij + contradiction + · exact And.left + +lemma unitOutputMatrix (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) + (hx : StateJointSuccess r c ⟨x,allSmallFibre r c hsmall x⟩) : + outputMatrix (prepareOutput ((stateCodeData r c e x,L),[]))= + matrixCode ((originalStateSuccessEquiv r c).symm ⟨⟨x,allSmallFibre r c hsmall x⟩,hx⟩).val := by + change outputMatrix ((List.ofFn r,List.ofFn c),unitOutputData r c e x)=_ + rw [outputMatrix_code] + apply congrArg matrixCode + funext i j + rw [unitOutputEntry r c e hsmall,originalStateSuccessEquiv_symm_entry] + simp only [paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ,true_and,hsmall i j, + Bool.true_eq_false,ite_false,Nat.sub_zero] + +lemma unitOuterTrial (hsmall : ∀ i j,paperSmall r c i j=true) (x : PaperStates r c) : + outerTrial ((stateCodeData r c e x,L),[])= + (stateTrial r c ⟨x,allSmallFibre r c hsmall x⟩).map (fun T => matrixCode T.val) := by + by_cases h : StateJointSuccess r c ⟨x,allSmallFibre r c hsmall x⟩ + · have hp := (unitOutputSuccess r c e hsmall x).mpr h + calc + _ = some (outputMatrix (prepareOutput ((stateCodeData r c e x,L),[]))) := ite_eq_left hp + _ = some (matrixCode ((originalStateSuccessEquiv r c).symm + ⟨⟨x,allSmallFibre r c hsmall x⟩,h⟩).val) := + congrArg some (unitOutputMatrix r c e hsmall x h) + _ = _ := by + simp only [stateTrial,FirstSuccess.partialEquivDraw,dite_eq_left h,Option.map_some] + · have hp : outerSuccess (unitOutputData r c e x)≠true := + fun hp => h ((unitOutputSuccess r c e hsmall x).mp hp) + calc + _ = none := ite_eq_right hp + _ = _ := by + simp only [stateTrial,FirstSuccess.partialEquivDraw,dite_eq_right h,Option.map_none] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f35a4d2abd43f03eccd8736ca9bc788eceeeb704 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileProgram.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileSamplingProgram + +namespace OAI + +/-! # The bounded profile program for the all-small branch -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms Polynomial + +abbrev UnitStepInput := ProfileConfiguration×List Bool + +def unitCandidateInput (z : UnitStepInput) : ProfileStepInput := + (currentParameters z.1,(z.2,[])) +def unitCandidateInputRealizer : Realizer unitCandidateInput := + pair (composition first currentParametersRealizer) (pair second (constant [])) + +theorem polynomial_unitCandidateInput : PolynomialTime unitCandidateInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_currentParameters) + (polynomial_pair polynomial_second (polynomial_constant [])) + +def unitNext (z : UnitStepInput) : List ℕ×List ℕ := + capViews (z.1.1.1.1,stepCandidateViews (unitCandidateInput z)) +def unitNextRealizer : Realizer unitNext := + composition (f := fun z : UnitStepInput => + (z.1.1.1.1,stepCandidateViews (unitCandidateInput z))) (g := capViews) + (pair (composition (composition (composition first first) first) first) + (composition (f := unitCandidateInput) (g := stepCandidateViews) + unitCandidateInputRealizer stepCandidateViewsRealizer)) capViewsRealizer + +theorem polynomial_unitNext : PolynomialTime unitNextRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition polynomial_unitCandidateInput polynomial_stepCandidateViews)) polynomial_capViews + +def unitAdvance (z : List Bool×ProfileConfiguration) : ProfileConfiguration := + (z.2.1,unitNext (z.2,z.1)) +def unitAdvanceRealizer : Realizer unitAdvance := + pair (composition second first) (composition (f := fun z : List Bool×ProfileConfiguration => (z.2,z.1)) + (g := unitNext) (pair second first) unitNextRealizer) + +theorem polynomial_unitAdvance : PolynomialTime unitAdvanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_unitNext) + +lemma unitAdvance_weight (word : List Bool) (z : ProfileConfiguration) (S : ℕ) + (hz : weight z.1≤S) : weight (unitAdvance (word,z))≤20*(S+1)^3 := by + let q := z.1.1.1.1.1.1.length + let U := z.1.1.1.2 + have hq : q≤S := (list_length_le_weight _).trans ((weight_fst z.1.1.1.1.1).trans + ((weight_fst z.1.1.1.1).trans ((weight_fst z.1.1.1).trans ((weight_fst z.1.1).trans ((weight_fst z.1).trans hz))))) + have hU : U.size≤S := (size_le_weight U).trans + ((weight_snd z.1.1.1).trans ((weight_fst z.1.1).trans ((weight_fst z.1).trans hz))) + have hx := capView_weight q U (stepCandidateViews (unitCandidateInput (z,word))).1 + have hy := capView_weight q U (stepCandidateViews (unitCandidateInput (z,word))).2 + change weight (z.1,(capView ((q,U),(stepCandidateViews (unitCandidateInput (z,word))).1), + capView ((q,U),(stepCandidateViews (unitCandidateInput (z,word))).2)))≤20*(S+1)^3 + rw [weight_prod z.1 _,weight_prod (capView ((q,U),(stepCandidateViews (unitCandidateInput (z,word))).1)) + (capView ((q,U),(stepCandidateViews (unitCandidateInput (z,word))).2))] + have hm : q*(4*U.size+2)≤S*(4*S+2) := by gcongr + nlinarith + +def unitProfileWalk (z : ProfileConfiguration×List (List Bool)) : ProfileConfiguration := + z.2.foldl (fun state word => unitAdvance (word,state)) z.1 + +def unitProfileWalkRealizer : Realizer unitProfileWalk := + composition (pair second first) (fold unitAdvanceRealizer) + +lemma unitFold_fixed (words : List (List Bool)) (z : ProfileConfiguration) : + (words.foldl (fun state word => unitAdvance (word,state)) z).1=z.1 := by + induction words generalizing z with + | nil => rfl + | cons w ws ih => exact ih _ + +lemma unitFold_weight (words : List (List Bool)) (z : ProfileConfiguration) (S : ℕ) + (hz : weight z≤S) : + weight (words.foldl (fun state word => unitAdvance (word,state)) z)≤20*(S+1)^3 := by + induction words using List.reverseRecOn with + | nil => + have hpow : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + simpa using hz.trans (by omega : S≤20*(S+1)^3) + | append_singleton words w _ih => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply unitAdvance_weight + rw [unitFold_fixed] + exact (weight_fst z).trans hz + +theorem polynomial_unitProfileWalk : PolynomialTime unitProfileWalkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_unitAdvance (20*(X+1)^3) + intro words z pre post _ + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + exact unitFold_weight pre z (weight (words,z)) (weight_snd (words,z)) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..429c7d23838b2c6e6670cbc7caf04dbd2fa30deb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitProfileSemantics.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitProfileProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.AllSmallBoolean + +namespace OAI + +/-! # Exact finite-word semantics of the all-small profile walk -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] stateCode unitNext capViews codeNeighborProposal +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +def unitCodeBitStep (x : PaperStates r c) (bits : Fin s → Bool) : PaperStates r c := + (decodedCodeProposal r c e x bits).getD x + +lemma unitNext_encoded (htotal : (∑ i,r i)=∑ j,c j) (h : ℕ) + (initial x : PaperStates r c) (bits : Fin s → Bool) : + unitNext (encodedConfiguration r c e h initial x,List.ofFn bits)= + stateCode r c e (unitCodeBitStep r c e x bits) := by + have hp := codeProposal_encoded r c e htotal x bits + simp only [unitNext,unitCandidateInput,currentParameters_encoded,stepCandidateViews,stepProposal] + change capViews (stateCodeData r c e initial, + (codeNeighborProposal (stateCodeData r c e x,List.ofFn bits)).getD (stateCode r c e x))=_ + rw [hp] + cases he : decodedCodeProposal r c e x bits with + | none => + simp only [Option.map_none,Option.getD_none,unitCodeBitStep,he] + exact capViews_stateCode r c e initial x + | some y => + simp only [Option.map_some,Option.getD_some,unitCodeBitStep,he] + exact capViews_stateCode r c e initial y + +lemma unitAdvance_encoded (htotal : (∑ i,r i)=∑ j,c j) (h : ℕ) + (initial x : PaperStates r c) (bits : Fin s → Bool) : + unitAdvance (List.ofFn bits,encodedConfiguration r c e h initial x)= + encodedConfiguration r c e h initial (unitCodeBitStep r c e x bits) := by + apply Prod.ext + · rfl + · + have hn := unitNext_encoded r c e htotal h initial x bits + simpa only [unitAdvance,encodedConfiguration] using hn + +lemma unitProfileWalk_ofFn (htotal : (∑ i,r i)=∑ j,c j) (h : ℕ) + (initial x : PaperStates r c) (steps : ℕ) (bits : Fin steps → Fin s → Bool) : + unitProfileWalk (encodedConfiguration r c e h initial x,List.ofFn (fun i => List.ofFn (bits i)))= + encodedConfiguration r c e h initial (wordWalk (unitCodeBitStep r c e) x steps bits) := by + induction steps with + | zero => rfl + | succ steps ih => + unfold unitProfileWalk at ih ⊢ + rw [List.ofFn_succ',List.concat_eq_append,List.foldl_append] + change unitAdvance (List.ofFn (bits (Fin.last steps)), + (List.ofFn (fun i => List.ofFn ((Fin.init bits) i))).foldl + (fun state word => unitAdvance (word,state)) + (encodedConfiguration r c e h initial x))=_ + rw [ih (Fin.init bits)] + exact unitAdvance_encoded r c e htotal h initial _ _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8451d7fd1a0fdc60f65092d235bf8280b0e4f71 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalProgram.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalProgram + +namespace OAI + +/-! # Deterministic terminal weights for the all-small branch -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +def terminalData (z : TerminalEntryInput) : (ProfileCheckData×ℕ)×MatrixCode := + ((sourceData (terminalSourceInput z),z.1.1.1.1.2),[]) + +def terminalDataRealizer : Realizer terminalData := + pair (pair (composition (f := terminalSourceInput) (g := sourceData) + terminalSourceInputRealizer sourceDataRealizer) + (composition (composition (composition (composition first first) first) first) second)) + (constant []) + +lemma polynomial_terminalData : PolynomialTime terminalDataRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_terminalSourceInput polynomial_sourceData) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + polynomial_second)) (polynomial_constant []) + +def terminalEntry (z : TerminalEntryInput) : ℕ := + successfulWeight (z.2.2,(outerTrial (terminalData z),1)) + +def terminalEntryRealizer : Realizer terminalEntry := + composition (pair (composition second second) + (pair (composition (f := terminalData) (g := outerTrial) + terminalDataRealizer outerTrialRealizer) (constant 1))) successfulWeightRealizer + +lemma polynomial_terminalEntry : PolynomialTime terminalEntryRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_pair (polynomial_composition polynomial_terminalData polynomial_outerTrial) + (polynomial_constant 1))) polynomial_successfulWeight + +def terminalEntryMeasure (z : TerminalEntryInput) : ℕ := weight z + +lemma work_terminalEntry : WorkBound terminalEntryRealizer terminalEntryMeasure := + work_of_polynomial polynomial_terminalEntry X (fun _ => by simp [terminalEntryMeasure]) + +abbrev TerminalColumnInput := MatrixParameters×MatrixCode +abbrev TerminalColumnEntryInput := TerminalColumnInput×(List ℕ×List ℕ) + +def terminalColumnEntryInput (z : TerminalColumnEntryInput) : TerminalEntryInput := + (z.1.1,(z.2,z.1.2)) + +def terminalColumnEntryInputRealizer : Realizer terminalColumnEntryInput := + pair (composition first first) (pair second (composition first second)) + +lemma polynomial_terminalColumnEntryInput : PolynomialTime terminalColumnEntryInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair polynomial_second (polynomial_composition polynomial_first polynomial_second)) + +def terminalColumnEntry (z : TerminalColumnEntryInput) : ℕ := terminalEntry (terminalColumnEntryInput z) + +def terminalColumnEntryRealizer : Realizer terminalColumnEntry := + composition (f := terminalColumnEntryInput) (g := terminalEntry) + terminalColumnEntryInputRealizer terminalEntryRealizer + +def terminalColumnEntryMeasure (z : TerminalColumnEntryInput) : ℕ := + terminalEntryMeasure (terminalColumnEntryInput z)+weight z + +lemma work_terminalColumnEntry : WorkBound terminalColumnEntryRealizer terminalColumnEntryMeasure := by + unfold terminalColumnEntryRealizer + apply work_composition (work_of_polynomial polynomial_terminalColumnEntryInput X + (fun z => by simp only [Polynomial.eval_X,terminalColumnEntryMeasure]; omega)) + work_terminalEntry X + intro z + simp only [Polynomial.eval_X,terminalColumnEntryMeasure] + omega + +def terminalColumn (z : TerminalColumnInput) : List ℕ := + (profileBoxViews (matrixData z.1)).map (fun v => terminalColumnEntry (z,v)) + +def terminalColumnRealizer : Realizer terminalColumn := + composition (f := fun z : TerminalColumnInput => (z,profileBoxViews (matrixData z.1))) + (g := fun z : TerminalColumnInput×List (List ℕ×List ℕ) => + z.2.map (fun v => terminalColumnEntry (z.1,v))) + (pair identity (composition + (f := fun z : TerminalColumnInput => matrixData z.1) (g := profileBoxViews) + (composition (f := fun z : TerminalColumnInput => z.1) (g := matrixData) + first matrixDataRealizer) profileBoxViewsRealizer)) (mapWith terminalColumnEntryRealizer) + +def terminalColumnMeasure (z : TerminalColumnInput) : ℕ := + gridStateCount (profileEnumerationData (matrixData z.1))+ + MeasuredMap.listMeasure terminalColumnEntryMeasure (z,profileBoxViews (matrixData z.1)) + +lemma work_terminalColumn : WorkBound terminalColumnRealizer terminalColumnMeasure := by + have hin (z : TerminalColumnInput) : weight z ≤ terminalColumnMeasure z := by + have hw : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := + weight_fst (z,profileBoxViews (matrixData z.1)) + simp only [terminalColumnMeasure,MeasuredMap.listMeasure] + omega + have hd : PolynomialTime (composition (first (B := MatrixCode)) matrixDataRealizer) := + polynomial_composition polynomial_first polynomial_matrixData + have hv : WorkBound (composition (composition first matrixDataRealizer) profileBoxViewsRealizer) + terminalColumnMeasure := by + apply work_composition (work_of_polynomial hd X (fun z => by simpa using hin z)) + work_profileBoxViews (X+1) + intro z + have hw : weight (matrixData z.1) ≤ weight z := by + unfold matrixData + exact (weight_fst _).trans ((weight_fst _).trans ((weight_fst _).trans + ((weight_fst _).trans (weight_fst z)))) + simp only [Function.comp_apply,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one, + terminalColumnMeasure,MeasuredMap.listMeasure] + have hpair : weight z ≤ weight (z,profileBoxViews (matrixData z.1)) := + weight_fst (z,profileBoxViews (matrixData z.1)) + omega + unfold terminalColumnRealizer + apply work_composition (work_pair (work_of_polynomial polynomial_identity X + (fun z => by simpa using hin z)) hv X (fun z => by simpa using hin z)) + (MeasuredMap.work_mapWith _ _ work_terminalColumnEntry) X + intro z + simp only [Polynomial.eval_X,terminalColumnMeasure,Function.comp_apply,id_eq] + omega + +end ContingencyTables.UnitCountPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0560506052c21e2c443f5832f5d794c45d7507c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTerminalSemantics.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixLaw +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialCountProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitOutputSemantics + +namespace OAI + +/-! # All-small trial counts from the computed matrix and terminal column -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) (b h : ℕ) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "BoxIndex" => ProfileIndex (m := m) (n := n) (q := q) + +attribute [local irreducible] stateCode stateCodeData matrixInput unitWalkCounts unitTrialCounts + UnitCountPrograms.terminalEntry IntegerLaw.push + +lemma successfulWeight_table (o : Option (Table r c)) (T : Table r c) : + successfulWeight (matrixCode T.val,(o.map (fun A => matrixCode A.val),1))= + if o=some T then 1 else 0 := by + cases o with + | none => rfl + | some A => + unfold successfulWeight + simp only [Option.map_some,Option.elim_some,Option.some.injEq] + have he : matrixCode A.val=matrixCode T.val ↔ A=T := by + constructor + · intro he + exact Subtype.ext (matrixCode_injective he) + · rintro rfl + rfl + simp only [he] + +lemma unit_terminalEntry_actual (hsmall : ∀ i j,paperSmall r c i j=true) + (z x : PaperStates r c) (xs : List Bool) (T : Table r c) : + UnitCountPrograms.terminalEntry (matrixInput r c e b h z xs,(stateCode r c e x,matrixCode T.val))= + if stateTrial r c ⟨x,allSmallFibre r c hsmall x⟩=some T then 1 else 0 := by + unfold UnitCountPrograms.terminalEntry UnitCountPrograms.terminalData terminalSourceInput + dsimp only [sourceData,matrixData] + unfold matrixInput + rw [candidate_stateCodeData,unitOuterTrial r c e hsmall x] + exact successfulWeight_table r c _ T + +lemma unit_terminalColumn_ofFn (z : PaperStates r c) (xs : List Bool) (T : Table r c) : + UnitCountPrograms.terminalColumn (matrixInput r c e b h z xs,matrixCode T.val)= + List.ofFn (fun k : BoxIndex => UnitCountPrograms.terminalEntry + (matrixInput r c e b h z xs,(boxCode k,matrixCode T.val))) := by + have hv : profileBoxViews (matrixData (matrixInput r c e b h z xs))=List.ofFn + (boxCode (m := m) (n := n) (q := q)) := by + unfold matrixData matrixInput + exact profileBoxViews_actual r c e z + unfold UnitCountPrograms.terminalColumn + dsimp only [Prod.fst] + rw [hv,List.map_ofFn] + rfl + +lemma unitTrialCounts_count (hsmall : ∀ i j,paperSmall r c i j=true) + (z : PaperStates r c) (N : ℕ) (T : Table r c) : + (unitTrialCounts r c e hsmall z N).count (some T)= + ∑ x,(unitWalkCounts r c e z N).count x* + (if stateTrial r c ⟨x,allSmallFibre r c hsmall x⟩=some T then 1 else 0) := by + unfold unitTrialCounts + rw [IntegerLaw.push_count_sum] + apply Finset.sum_congr rfl + intro x _ + split_ifs <;> simp + +lemma unit_terminal_dot_trial (hsmall : ∀ i j,paperSmall r c i j=true) + (z : PaperStates r c) (xs : List Bool) (N : ℕ) (T : Table r c) : + IntegerMatrixPrograms.dot + (List.ofFn (fun k : BoxIndex => + ((unitWalkCounts r c e z N).push (profileIndex r c e)).count k), + UnitCountPrograms.terminalColumn (matrixInput r c e b h z xs,matrixCode T.val))= + (unitTrialCounts r c e hsmall z N).count (some T) := by + rw [unit_terminalColumn_ofFn r c e b h z xs T,IntegerMatrixPrograms.dot_ofFn,IntegerLaw.sum_push_mul] + change (∑ x,(unitWalkCounts r c e z N).count x* + UnitCountPrograms.terminalEntry + (matrixInput r c e b h z xs,(boxCode (profileIndex r c e x),matrixCode T.val)))=_ + simp_rw [boxCode_index,unit_terminalEntry_actual r c e b h hsmall] + exact (unitTrialCounts_count r c e hsmall z N T).symm + +lemma unit_trialCount_actual (htotal : ∑ i,r i=∑ j,c j) + (hsmall : ∀ i j,paperSmall r c i j=true) (z : PaperStates r c) + (xs : List Bool) (hs : xs.length=s) (N : ℕ) (T : Table r c) : + UnitCountPrograms.trialCount + ((matrixInput r c e b h z xs,(N,(profileIndex r c e z).val)),matrixCode T.val)= + (unitTrialCounts r c e hsmall z N).count (some T) := by + unfold UnitCountPrograms.trialCount UnitCountPrograms.walkCounts UnitCountPrograms.walkCountData + rw [unit_profileMatrix_actual r c e b h htotal z xs hs,IntegerMatrixPrograms.fromPoint_ofFn] + have he : List.ofFn (IntegerPropagation.numerators + (fun i j : BoxIndex => (unitBoxStep r c e i).count j) (profileIndex r c e z) N)= + List.ofFn (fun k : BoxIndex => ((unitWalkCounts r c e z N).push (profileIndex r c e)).count k) := by + apply congrArg List.ofFn + funext k + exact unitBoxWalk_count r c e z N k + rw [he] + exact unit_terminal_dot_trial r c e b h hsmall z xs N T + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f51f5468e3c45247490f22d4bea54abc4a6c1fb7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialCountProgram.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTerminalProgram +import OAI.Combinatorics.ContingencyTables.Transport.IntegerMatrixPoint + +namespace OAI + +/-! # Executed walk-and-terminal integer trial counts -/ + +namespace ContingencyTables.UnitCountPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms Polynomial + +abbrev WalkCountInput := MatrixParameters×(ℕ×ℕ) + +def walkCountData (z : WalkCountInput) : ℕ×(List (List ℕ)×ℕ) := + (z.2.1,(profileMatrix z.1,z.2.2)) + +def walkCountDataRealizer : Realizer walkCountData := + pair (composition second first) + (pair (composition (f := fun z : WalkCountInput => z.1) (g := profileMatrix) + first profileMatrixRealizer) (composition second second)) + +def walkCountMeasure (z : WalkCountInput) : ℕ := + z.2.1+profileMatrixMeasure z.1+weight z + +lemma work_walkCountData : WorkBound walkCountDataRealizer walkCountMeasure := by + have hi (z : WalkCountInput) : weight z ≤ X.eval (walkCountMeasure z) := by + simp only [Polynomial.eval_X,walkCountMeasure] + omega + have hm : WorkBound (composition (first (B := ℕ×ℕ)) profileMatrixRealizer) walkCountMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_profileMatrix X + intro z + simp only [Polynomial.eval_X,walkCountMeasure] + omega + unfold walkCountDataRealizer + exact work_pair (work_of_polynomial (polynomial_composition polynomial_second polynomial_first) X hi) + (work_pair hm (work_of_polynomial + (polynomial_composition polynomial_second polynomial_second) X hi) X hi) X hi + +def walkCounts (z : WalkCountInput) : List ℕ := IntegerMatrixPrograms.fromPoint (walkCountData z) + +def walkCountsRealizer : Realizer walkCounts := + composition (f := walkCountData) (g := IntegerMatrixPrograms.fromPoint) + walkCountDataRealizer IntegerMatrixPrograms.fromPointRealizer + +lemma work_walkCounts : WorkBound walkCountsRealizer walkCountMeasure := by + obtain ⟨p,hp⟩ := work_walkCountData + unfold walkCountsRealizer + apply work_composition ⟨p,hp⟩ IntegerMatrixPrograms.work_fromPoint (X+p) + intro z + have hw := hp z + have hs : weight (profileMatrix z.1,z.2.2) ≤ weight (walkCountData z) := by + exact weight_snd (walkCountData z) + have hn : z.2.1 ≤ walkCountMeasure z := by unfold walkCountMeasure; omega + simp only [Polynomial.eval_add,Polynomial.eval_X] + change z.2.1+weight (profileMatrix z.1,z.2.2) ≤ _ + omega + +abbrev TrialCountInput := WalkCountInput×MatrixCode + +def trialCount (z : TrialCountInput) : ℕ := + IntegerMatrixPrograms.dot (walkCounts z.1,terminalColumn (z.1.1,z.2)) + +def trialCountRealizer : Realizer trialCount := + composition (pair (composition (f := fun z : TrialCountInput => z.1) (g := walkCounts) + first walkCountsRealizer) + (composition (f := fun z : TrialCountInput => (z.1.1,z.2)) (g := terminalColumn) + (pair (composition first first) second) terminalColumnRealizer)) IntegerMatrixPrograms.dotRealizer + +def trialCountMeasure (z : TrialCountInput) : ℕ := + walkCountMeasure z.1+terminalColumnMeasure (z.1.1,z.2)+weight z + +lemma work_trialCount : WorkBound trialCountRealizer trialCountMeasure := by + have hi (z : TrialCountInput) : weight z ≤ X.eval (trialCountMeasure z) := by + simp only [Polynomial.eval_X,trialCountMeasure] + omega + have hw : WorkBound (composition (first (B := MatrixCode)) walkCountsRealizer) trialCountMeasure := by + apply work_composition (work_of_polynomial polynomial_first X hi) work_walkCounts X + intro z + simp only [Polynomial.eval_X,trialCountMeasure] + omega + have ht : WorkBound (composition (pair (composition first first) second) + terminalColumnRealizer) trialCountMeasure := by + apply work_composition (work_of_polynomial (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) X hi) + work_terminalColumn X + intro z + simp only [Polynomial.eval_X,trialCountMeasure,Function.comp_apply] + omega + unfold trialCountRealizer + exact work_then_polynomial (work_pair hw ht X hi) IntegerMatrixPrograms.polynomial_dot + +end ContingencyTables.UnitCountPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2659c14bfb97b77552898c324e4b1ae4eca4c90 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialProgram.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitProfileProgram + +namespace OAI + +/-! # All-small trials and retries use only the stored profile entries -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped DensePrograms + +def unitPackedWords (z : PackedProfileTrial) : List (List Bool) := + wordChunks (z.1.2.1.2,z.2) +def unitPackedWordsRealizer : Realizer unitPackedWords := + composition (f := fun z : PackedProfileTrial => (z.1.2.1.2,z.2)) (g := wordChunks) + (pair (composition (composition (composition first second) first) second) second) wordChunksRealizer + +theorem polynomial_unitPackedWords : PolynomialTime unitPackedWordsRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_second) polynomial_second) polynomial_wordChunks + +def unitPackedState (z : PackedProfileTrial) : ProfileConfiguration := + unitProfileWalk (z.1.1,unitPackedWords z) +def unitPackedStateRealizer : Realizer unitPackedState := + composition (f := fun z : PackedProfileTrial => (z.1.1,unitPackedWords z)) (g := unitProfileWalk) + (pair (composition first first) unitPackedWordsRealizer) unitProfileWalkRealizer + +theorem polynomial_unitPackedState : PolynomialTime unitPackedStateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_unitPackedWords) polynomial_unitProfileWalk + +def unitPackedTrial (z : PackedProfileTrial) : Option MatrixCode := + outerTrial ((currentParameters (unitPackedState z)).1,[]) +def unitPackedTrialRealizer : Realizer unitPackedTrial := + composition (f := fun z : PackedProfileTrial => ((currentParameters (unitPackedState z)).1,[])) + (g := outerTrial) (pair + (composition (f := fun z : PackedProfileTrial => currentParameters (unitPackedState z)) + (g := Prod.fst) (composition (f := unitPackedState) (g := currentParameters) + unitPackedStateRealizer currentParametersRealizer) first) (constant [])) outerTrialRealizer + +theorem polynomial_unitPackedTrial : PolynomialTime unitPackedTrialRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_unitPackedState polynomial_currentParameters) polynomial_first) + (polynomial_constant [])) polynomial_outerTrial + +def unitRetryWidth (z : ProfileRetryData) : ℕ := z.1.1.2.1.1*z.1.1.2.1.2 +def unitRetryWidthRealizer : Realizer unitRetryWidth := + composition (f := fun z : ProfileRetryData => (z.1.1.2.1.1,z.1.1.2.1.2)) + (g := fun t : ℕ×ℕ => t.1*t.2) + (pair (composition (composition (composition (composition first first) second) first) first) + (composition (composition (composition (composition first first) second) first) second)) multiply + +theorem polynomial_unitRetryWidth : PolynomialTime unitRetryWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + polynomial_second)) polynomial_multiply + +def unitRetryWords (z : ProfileRetryData) : List (List Bool) := wordChunks (unitRetryWidth z,z.2) +def unitRetryWordsRealizer : Realizer unitRetryWords := + composition (f := fun z : ProfileRetryData => (unitRetryWidth z,z.2)) (g := wordChunks) + (pair unitRetryWidthRealizer second) wordChunksRealizer + +theorem polynomial_unitRetryWords : PolynomialTime unitRetryWordsRealizer := + polynomial_composition (polynomial_pair polynomial_unitRetryWidth polynomial_second) polynomial_wordChunks + +def unitProfileRetry (z : ProfileRetryData) : MatrixCode := + FirstSuccessProgram.retry unitPackedTrial (z.1,unitRetryWords z) +def unitProfileRetryRealizer : Realizer unitProfileRetry := + composition (f := fun z : ProfileRetryData => (z.1,unitRetryWords z)) + (g := FirstSuccessProgram.retry unitPackedTrial) (pair first unitRetryWordsRealizer) + (FirstSuccessProgram.retryRealizer unitPackedTrialRealizer) + +theorem polynomial_unitProfileRetry : PolynomialTime unitProfileRetryRealizer := + polynomial_composition (polynomial_pair polynomial_first polynomial_unitRetryWords) + (FirstSuccessProgram.polynomial_retry polynomial_unitPackedTrial) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..165ad8a3c8c71869de793c3435dd5971c2fa2c85 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Sampling/UnitTrialSemantics.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitOutputSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.UnitFiniteLaw + +namespace OAI + +/-! # All-small executable trials realize the uniform finite-word law -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms FirstPaperPhysicalMarginal CompletionCounts +open FirstSuccess FairBits SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] unitProfileRetry unitCodeOuterDraw +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +lemma smallProposalBits_pos : 0 matrixCode T.val) := by + unfold unitPackedTrial unitPackedState unitPackedWords + rw [wordChunks_ofFn (smallProposalBits_pos (m := m) (n := n))] + rw [unitProfileWalk_ofFn r c e htotal,currentParameters_encoded] + exact unitOuterTrial r c e hsmall _ + +lemma unitProfileRetry_code (hsmall : ∀ i j,paperSmall r c i j=true) + (htotal : (∑ i,r i)=∑ j,c j) (h : ℕ) (x : PaperStates r c) + (steps attempts f : ℕ) (hsteps : 0 + unitPackedTrial ((encodedConfiguration r c e h x x,((steps,s),f)),List.ofFn word))= + (fun word => (stateTrial r c (unitCodeJointDraw r c e (allSmallFibre r c hsmall) x steps word)).map + (fun T => matrixCode T.val)) := by + funext word + exact unitPackedTrial_ofFn r c e hsmall htotal h x steps f word + rw [he,FirstSuccessProgram.wordRetry_map] + unfold unitCodeOuterDraw + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/AffinePenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/AffinePenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..d45cbc9e71542ba789d8babc428615417c26674a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/AffinePenalty.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWeights +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Topology.Order.Lattice +import Mathlib.Topology.Algebra.Monoid +import Mathlib.Algebra.Order.BigOperators.Group.Finset + +namespace OAI + +/-! +# The softened affine feasibility penalty + +The dense sampler uses the maximum of zero and the negatives of its +normalized affine table entries, minus a fixed slack. This actual penalty +is continuous and convex. Its change bound is proved from the entry +coefficients, including the dependent row and column entries. +-/ + +namespace ContingencyTables.AffinePenalty + +open scoped BigOperators + +variable {I G : Type*} [Fintype I] [Fintype G] + +def affineValue (offset : ℝ) (coeff : I → ℝ) (x : I → ℝ) : ℝ := + offset + ∑ j, coeff j * x j + +theorem affineValue_combine (offset : ℝ) (coeff : I → ℝ) (x y : I → ℝ) + (a b : ℝ) (hab : a + b = 1) : + affineValue offset coeff (a • x + b • y) = + a * affineValue offset coeff x + b * affineValue offset coeff y := by + simp only [affineValue, Pi.add_apply, Pi.smul_apply, smul_eq_mul, + mul_add, Finset.sum_add_distrib] + simp_rw [mul_left_comm (coeff _) a, mul_left_comm (coeff _) b, + ← Finset.mul_sum] + nlinarith [congrArg (fun z => z * offset) hab] + +theorem affineValue_change (offset : ℝ) (coeff : I → ℝ) (x y : I → ℝ) + (c r : ℝ) (hc : 0 ≤ c) (hcoeff : ∀ j, |coeff j| ≤ c) + (hxy : ∀ j, |x j - y j| ≤ r) : + |affineValue offset coeff x - affineValue offset coeff y| ≤ + Fintype.card I * c * r := by + have heq : affineValue offset coeff x - affineValue offset coeff y = + ∑ j, coeff j * (x j - y j) := by + simp [affineValue, mul_sub, Finset.sum_sub_distrib] + rw [heq] + calc + _ ≤ ∑ j, |coeff j * (x j - y j)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ _j : I, c * r := by + apply Finset.sum_le_sum + intro j _ + rw [abs_mul] + exact mul_le_mul (hcoeff j) (hxy j) (abs_nonneg _) hc + _ = _ := by simp; ring + +def component (offset : G → ℝ) (coeff : G → I → ℝ) (slack : ℝ) : + Option G → (I → ℝ) → ℝ + | none, _ => 0 + | some g, x => -affineValue (offset g) (coeff g) x - slack + +noncomputable def penalty (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (x : I → ℝ) : ℝ := + Finset.univ.sup' Finset.univ_nonempty (fun g : Option G => component offset coeff slack g x) + +theorem component_le_penalty (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (x : I → ℝ) (g : Option G) : + component offset coeff slack g x ≤ penalty offset coeff slack x := by + unfold penalty + exact Finset.le_sup' (fun g : Option G => component offset coeff slack g x) (Finset.mem_univ g) + +theorem penalty_nonnegative (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (x : I → ℝ) : 0 ≤ penalty offset coeff slack x := + component_le_penalty offset coeff slack x none + +omit [Fintype G] in +private theorem component_combine (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (g : Option G) (x y : I → ℝ) (a b : ℝ) (hab : a + b = 1) : + component offset coeff slack g (a • x + b • y) = + a * component offset coeff slack g x + b * component offset coeff slack g y := by + cases g with + | none => simp [component] + | some g => + simp only [component, affineValue_combine _ _ _ _ _ _ hab] + nlinarith [congrArg (fun z => z * slack) hab] + +theorem penalty_convex (offset : G → ℝ) (coeff : G → I → ℝ) (slack : ℝ) + (K : Set (I → ℝ)) (hK : Convex ℝ K) : + ConvexOn ℝ K (penalty offset coeff slack) := by + refine ⟨hK, ?_⟩ + intro x _ y _ a b ha hb hab + apply Finset.sup'_le + intro g _ + rw [component_combine offset coeff slack g x y a b hab] + exact add_le_add + (mul_le_mul_of_nonneg_left (component_le_penalty offset coeff slack x g) ha) + (mul_le_mul_of_nonneg_left (component_le_penalty offset coeff slack y g) hb) + +omit [Fintype G] in +private theorem component_change (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (g : Option G) (x y : I → ℝ) (c r : ℝ) + (hc : 0 ≤ c) (hr : 0 ≤ r) (hcoeff : ∀ g j, |coeff g j| ≤ c) + (hxy : ∀ j, |x j - y j| ≤ r) : + |component offset coeff slack g x - component offset coeff slack g y| ≤ + Fintype.card I * c * r := by + cases g with + | none => simp only [component, sub_self, abs_zero]; positivity + | some g => + have heq : component offset coeff slack (some g) x - + component offset coeff slack (some g) y = + -(affineValue (offset g) (coeff g) x - affineValue (offset g) (coeff g) y) := by + simp only [component] + ring + rw [heq, abs_neg] + exact affineValue_change _ _ _ _ c r hc (hcoeff g) hxy + +private theorem penalty_sub_le (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (x y : I → ℝ) (c r : ℝ) + (hc : 0 ≤ c) (hr : 0 ≤ r) (hcoeff : ∀ g j, |coeff g j| ≤ c) + (hxy : ∀ j, |x j - y j| ≤ r) : + penalty offset coeff slack x ≤ penalty offset coeff slack y + Fintype.card I * c * r := by + apply Finset.sup'_le + intro g _ + have h := (abs_le.mp (component_change offset coeff slack g x y c r hc hr hcoeff hxy)).2 + linarith [component_le_penalty offset coeff slack y g] + +theorem penalty_change (offset : G → ℝ) (coeff : G → I → ℝ) + (slack : ℝ) (x y : I → ℝ) (c r : ℝ) + (hc : 0 ≤ c) (hr : 0 ≤ r) (hcoeff : ∀ g j, |coeff g j| ≤ c) + (hxy : ∀ j, |x j - y j| ≤ r) : + |penalty offset coeff slack x - penalty offset coeff slack y| ≤ Fintype.card I * c * r := by + apply abs_le.mpr + constructor + · have h := penalty_sub_le offset coeff slack y x c r hc hr hcoeff + (fun j => by simpa [abs_sub_comm] using hxy j) + linarith + · linarith [penalty_sub_le offset coeff slack x y c r hc hr hcoeff hxy] + +theorem penalty_continuous (offset : G → ℝ) (coeff : G → I → ℝ) (slack : ℝ) : + Continuous (penalty offset coeff slack) := by + apply Continuous.finset_sup'_apply + intro g _ + cases g with + | none => exact continuous_const + | some g => + exact (continuous_const.add (continuous_finsetSum Finset.univ + (fun j _ => continuous_const.mul (continuous_apply j)))).neg.sub continuous_const + +end ContingencyTables.AffinePenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/AuxiliaryRepairMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/AuxiliaryRepairMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..45734616007f76725ff91c672275c5413622e0ea --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/AuxiliaryRepairMass.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ExcessContextDefects +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperChildMass + +namespace OAI + +/-! # Conditional repair bounds the literal auxiliary kernel mass -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open BalancedEnumeration IntegerWeightedTransport FirstPaperProfiles +open FirstPaperContextTransport FirstPaperPhysicalMarginal IntegerBoxTruncation +open PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +lemma rawExcess_injective (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) : + Function.Injective (rawExcess small s hs σ U l e) := by + intro q q' he + apply excessEmbedding_injective _ (auxRoot U l) + funext a + have hh := congrFun he (contextEquiv small s hs e U (.inr a)) + simpa only [rawExcess,assemble,Function.comp_apply,Equiv.symm_apply_apply,Sum.elim_inr] using hh + +abbrev ValidAssignments (U n : ℕ) := + {q : ExcessAssignments (widths (fun _ : Fin n => U)) // ValidExcess _ q} + +noncomputable instance validAssignmentsFintype (U n : ℕ) : Fintype (ValidAssignments U n) := + inferInstanceAs (Fintype {q : ExcessAssignments (widths (fun _ : Fin n => U)) // ValidExcess _ q}) + +lemma finite_injective_sum_le {X Y : Type*} [Fintype X] [Fintype Y] + (j : X → Y) (hj : Function.Injective j) (g : Y → ℝ) (hg : ∀ y, 0 ≤ g y) : + (∑ x, g (j x)) ≤ ∑ y, g y := by + calc + _ = ∑ y ∈ Finset.univ.image j, g y := + (Finset.sum_image (fun x _ y _ he => hj he)).symm + _ ≤ ∑ y, g y := Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ _) + (fun y _ _ => hg y) + +variable [Fintype I] [Fintype J] + +/-- Every truncated auxiliary assignment maps injectively into one +actual conditional defect profile. The hard weights retain all completions. -/ +theorem auxiliary_mass_le_defect_sum (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hl0 : 1 ≤ l) (hlU : l ≤ U) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + auxiliaryKernel Ms (truncate f (bounds (fun _ : Bool => U) Ms) (U+Ms.sum)) (auxRoot U l) ≤ + ∑ t : Later small s, ∑ z : DefectProfiles small B s t.val.val σ l, + hardMarginal small B r c L (naturalProfile z.val) := by + dsimp only + rw [auxiliaryKernel_truncate_eq_valid_sum _ _ _ _ _ (auxRoot_inBox U l hlU) (by + simp only [auxRoot,Fintype.sum_bool,Bool.false_eq_true,↓reduceIte] + omega)] + rw [Finset.sum_subtype (p := ValidExcess (widths (fun _ : Fin n => U))) _ (by simp)] + let j : ValidAssignments U n → (t : Later small s) × DefectProfiles small B s t.val.val σ l := + fun q => ⟨e (excessIndex (fun _ : Fin n => U) q.val), + excessDefectProfile small B s hs σ U l hl0 hlU hB hσ e q.val q.property⟩ + have hj : Function.Injective j := by + intro q q' he + apply Subtype.ext + apply rawExcess_injective small s hs σ U l e + exact congrArg (fun a : (t : Later small s) × DefectProfiles small B s t.val.val σ l => + naturalProfile a.2.val) he + have hg (a : (t : Later small s) × DefectProfiles small B s t.val.val σ l) : + 0 ≤ hardMarginal small B r c L (naturalProfile a.2.val) := by + rw [hardMarginal_eq_fibre_card small B r c L _ (naturalProfile_bounded a.2.val)] + positivity + have hh := finite_injective_sum_le j hj + (fun a => hardMarginal small B r c L (naturalProfile a.2.val)) hg + rw [Fintype.sum_sigma] at hh + exact hh + +/-- Apply the completion-retaining repair injection and sum over actual +later cells. Each repair enters one of the two adjacent children. -/ +theorem auxiliary_mass_le_adjacent (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hl0 : 1 ≤ l) (hlU : l ≤ U) + (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + auxiliaryKernel Ms (truncate f (bounds (fun _ : Bool => U) Ms) (U+Ms.sum)) (auxRoot U l) ≤ + n*max (eliminate Ms f (childProfile U (l-1))) (eliminate Ms f (childProfile U l)) := by + dsimp only + let f := contextHard small B r c L (widths (fun _ : Fin n => U)) + (contextEquiv small s hs e U) (prefixRaw small s σ U) + have hfirst := auxiliary_mass_le_defect_sum small B r c L s hs σ U l hl0 hlU hB hσ e + dsimp only at hfirst + refine hfirst.trans ?_ + have htbound (t : Later small s) : + (∑ z : DefectProfiles small B s t.val.val σ l, hardMarginal small B r c L (naturalProfile z.val)) ≤ + max (eliminate _ f (childProfile U (l-1))) (eliminate _ f (childProfile U l)) := by + have hrepair := conditional_defect_mass_le small B r c L s t.val.val σ l hs + t.val.property t.property hcap + have hk : l-1+(if t.val.val.1=s.1 then 1 else 0) ≤ U := by + split_ifs <;> omega + have he := eliminate_context_eq_balanced_mass small B r c L s hs σ U hB hσ + ⟨l-1+(if t.val.val.1=s.1 then 1 else 0),Nat.lt_succ_of_le hk⟩ e + have hb := hrepair.trans_eq he.symm + by_cases hrow : t.val.val.1=s.1 + · simp only [hrow,↓reduceIte] at hb + have hl : l-1+1=l := by omega + rw [hl] at hb + exact hb.trans (le_max_right _ _) + · simp only [hrow,↓reduceIte,add_zero] at hb + exact hb.trans (le_max_left _ _) + calc + _ ≤ ∑ _t : Later small s, + max (eliminate _ f (childProfile U (l-1))) (eliminate _ f (childProfile U l)) := + Finset.sum_le_sum (fun t _ => htbound t) + _ = _ := by + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + rw [←Fintype.card_congr e,Fintype.card_fin] + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/AxisProposalTest.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/AxisProposalTest.lean new file mode 100644 index 0000000000000000000000000000000000000000..276701fcf771267b6b145088c3642b963ca83c3f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/AxisProposalTest.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.ContingencyTables.Machines.NatListEquality +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisWordProgram + +namespace OAI + +/-! # Testing dense adjacency by the polynomial list of signed directions -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary + +abbrev AxisNumberData := (ℕ×List ℕ)×ℕ + +def axisNumberStep (z : AxisNumberData) : Option (List ℕ) := + axisListStep ((z.1,z.2/2),decide (z.2%2=1)) + +def axisNumberStepRealizer : Realizer axisNumberStep := + composition (pair (pair first (composition (pair second (constant 2)) quotient)) + (composition (pair (composition (pair second (constant 2)) remainder) (constant 1)) natEqual)) + axisListStepRealizer + +theorem polynomial_axisNumberStep : PolynomialTime axisNumberStepRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 2)) + polynomial_quotient)) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 2)) + polynomial_remainder) (polynomial_constant 1)) polynomial_natEqual)) polynomial_axisListStep + +theorem axisNumberStep_eq {q K M : ℕ} (a : Grid (I := Fin q) K) (v : Fin M) : + axisNumberStep ((K,gridNatCode a),v.val)=(axisCodeStep a v).map gridNatCode := by + change axisListStep (((K,gridNatCode a),v.val/2),decide (v.val%2=1))=_ + by_cases hv : v.val NatListEquality.listEqual (xs,z.1.2)) + +def proposalMatchesRealizer : Realizer proposalMatches := + composition (pair identity + (composition (pair (composition first first) second) axisNumberStepRealizer)) + (optionCases (constant false) + (composition (pair second (composition (composition first first) second)) + NatListEquality.listEqualRealizer)) + +lemma polynomial_proposalMatches : PolynomialTime proposalMatchesRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_axisNumberStep)) + (polynomial_optionCases (polynomial_constant false) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) NatListEquality.polynomial_listEqual)) + +def proposalIndices (z : ProposalTestData) : List ℕ := List.range (2*z.1.2.length) + +def proposalIndicesRealizer : Realizer proposalIndices := by + let L : Realizer (fun z : ProposalTestData => z.1.2.length) := + composition (composition first second) listLength + let M := composition (pair (constant 2) L) multiply + exact composition M range + +lemma polynomial_proposalIndices : PolynomialTime proposalIndicesRealizer := by + unfold proposalIndicesRealizer + apply polynomial_boundedRange (polynomial_composition (polynomial_pair (polynomial_constant 2) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength)) polynomial_multiply) (2*Polynomial.X) + intro z + have hl: z.1.2.length ≤ weight z:= + (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + simpa only [Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Function.comp_apply] using + Nat.mul_le_mul_left 2 hl + +def hasProposal (z : ProposalTestData) : Bool := + (proposalIndices z).any (fun i => proposalMatches (z,i)) + +def hasProposalRealizer : Realizer hasProposal := + (composition (composition (pair identity proposalIndicesRealizer) + (mapWith proposalMatchesRealizer)) any).congr (by + intro z + simp only [Function.comp_apply,List.any_map,id_eq,Function.comp_def,hasProposal]) + +theorem polynomial_hasProposal : PolynomialTime hasProposalRealizer := by + unfold hasProposalRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_proposalIndices) + (polynomial_mapWith polynomial_proposalMatches)) polynomial_any + +lemma gridNatCode_injective {q K : ℕ} : Function.Injective (gridNatCode (q := q) (K := K)) := by + intro a b h + have hv:=List.ofFn_injective h + funext i + apply Subtype.ext + have hi:=congrFun hv i + change (corner a i).toNat=(corner b i).toNat at hi + have ha: 0≤corner a i := (a i).property.1 + have hb: 0≤corner b i := (b i).property.1 + change corner a i=corner b i + have hv:=congrArg (fun n : ℕ => (n:ℤ)) hi + simpa only [Int.toNat_of_nonneg ha,Int.toNat_of_nonneg hb] using hv + +theorem hasProposal_code {q K : ℕ} (a b : Grid (I := Fin q) K) : + hasProposal ((K,gridNatCode a),gridNatCode b)=true ↔ Neighbor a b := by + simp only [hasProposal,List.any_eq_true] + constructor + · rintro ⟨v,hv,h⟩ + have hlen : v<2*q := by simpa [proposalIndices,gridNatCode] using hv + rw [proposalMatches,axisNumberStep_eq a (⟨v,by omega⟩ : Fin (2*q))] at h + cases he:axisCodeStep a (⟨v,by omega⟩ : Fin (2*q)) with + | none => simp [he] at h + | some c => + have hc : gridNatCode c=gridNatCode b := + (NatListEquality.listEqual_true _ _).mp (by simpa [he] using h) + have hcb:=gridNatCode_injective hc + subst c + exact axisCodeStep_sound a b _ he + · intro h + obtain ⟨v,hv⟩:=axisCodeStep_exists (le_refl (q*2)) a b h + refine ⟨v.val,?_,?_⟩ + · simpa only [proposalIndices,List.mem_range,gridNatCode,List.length_ofFn,Nat.mul_comm] using v.isLt + · rw [proposalMatches,axisNumberStep_eq a v,hv] + simpa only [Option.map_some,Option.elim_some] using + (NatListEquality.listEqual_true _ _).mpr rfl + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedBox.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed91b7a93485c20dbe37bd4e8766f8b0dc6fca5b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedBox.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerMarginal + +namespace OAI + +/-! +# Fixed-total, finite-box balanced marginal closure + +The display and positivity hypotheses of integer marginalization follow +from the box-valid total slice. Positivity of the marginal permits induction +over every finite family of balanced pairs before the equality limit. +-/ + +namespace ContingencyTables.BalancedBox + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +def InBox (m z : I → ℕ) : Prop := ∀ i, z i ≤ m i + +def PositiveSlice (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) : Prop := + ∀ z, InBox m z → (∑ i, z i)=R → 0 < f z + +def RemovalSlice (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) : Prop := + ∀ z, InBox m z → (∑ i, z i)=R+2 → + OnePositiveDirection (integerRemovalMatrix f z).toBilin' + +omit [Fintype I] [DecidableEq I] in +lemma profile_inBox (m z : I → ℕ) (M a b : ℕ) (hz : InBox m z) (ha : a ≤ M) (hb : b ≤ M) : + InBox (profile m M M) (profile z a b) := by + intro i + rcases i with i | (_ | _) <;> simp only [profile,Sum.elim_inl,Sum.elim_inr,ite_true] + · exact hz i + · exact ha + · exact hb + +omit [DecidableEq I] in +lemma profile_total (z : I → ℕ) (a b : ℕ) : + (∑ i, profile z a b i)=(∑ i, z i)+a+b := by + simp [profile,Fintype.sum_sum_type] + omega + +/-- One balanced pair preserves the exact box-valid integer signature. -/ +theorem marginal_removal_slice (F : ((I ⊕ Bool) → ℕ) → ℝ) (m : I → ℕ) (R M : ℕ) + (hM : 2 ≤ M) (hpos : PositiveSlice F (profile m M M) (R+M)) + (hsig : RemovalSlice F (profile m M M) (R+M)) : + RemovalSlice (marginal F M) m R := by + intro z hz htotal + apply marginal_removal_onePositive F M z hM + · intro j hj + apply hsig _ (profile_inBox m z M j (M-j) hz hj (Nat.sub_le _ _)) + rw [profile_total,htotal] + omega + · intro j hj0 hjM + apply hpos _ (profile_inBox m z M (j-1) (M-1-j) hz (by omega) (by omega)) + rw [profile_total,htotal] + omega + +omit [DecidableEq I] in +/-- The finite sum stays strictly positive on precisely its required total +slice. This is the induction input for the next balanced pair. -/ +theorem marginal_positive_slice (F : ((I ⊕ Bool) → ℕ) → ℝ) (m : I → ℕ) (R M : ℕ) + (hpos : PositiveSlice F (profile m M M) (R+M)) : + PositiveSlice (marginal F M) m R := by + intro z hz htotal + unfold marginal + apply Finset.sum_pos' + · intro j hj + have hjM : j ≤ M := by simpa using Finset.mem_range.mp hj + apply le_of_lt + apply hpos _ (profile_inBox m z M j (M-j) hz hjM (Nat.sub_le _ _)) + rw [profile_total,htotal] + omega + · refine ⟨0,by simp,?_⟩ + apply hpos _ (profile_inBox m z M 0 (M-0) hz (Nat.zero_le _) (by simp)) + rw [profile_total,htotal] + omega + +end ContingencyTables.BalancedBox + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCellFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCellFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..162c05d8f1d7b4859122a99cc937982832cb6671 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCellFibres.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalLargeProfiles +import Mathlib.Logic.Equiv.Prod + +namespace OAI + +/-! # Exact one-cell fibres of the physical balanced profile sum -/ + +namespace ContingencyTables.BalancedCellFibres + +open scoped BigOperators Classical + +variable {C : Type*} [Fintype C] [DecidableEq C] + +abbrev Profiles (M : C → ℕ) := (c : C) → Fin (M c+1) +abbrev Others (M : C → ℕ) (t : C) := (c : {c : C // c≠t}) → Fin (M c.val+1) + +def profile (M : C → ℕ) (a : Profiles M) : C×Bool → ℕ := + fun p => if p.2 then M p.1-(a p.1).val else (a p.1).val + +noncomputable def fibre (M : C → ℕ) (F : (C×Bool → ℕ) → ℝ) + (t : C) (k : Fin (M t+1)) : ℝ := + ∑ a : Profiles M,if a t=k then F (profile M a) else 0 + +noncomputable def join (M : C → ℕ) (t : C) + (k : Fin (M t+1)) (a : Others M t) : Profiles M := + (Equiv.piSplitAt t (fun c => Fin (M c+1))).symm (k,a) + +omit [Fintype C] in +lemma join_at (M : C → ℕ) (t : C) (k : Fin (M t+1)) (a : Others M t) : + join M t k a t=k := by + exact congrArg Prod.fst ((Equiv.piSplitAt t (fun c => Fin (M c+1))).apply_symm_apply (k,a)) + +omit [Fintype C] in +lemma join_other (M : C → ℕ) (t : C) (k : Fin (M t+1)) (a : Others M t) + (c : {c : C // c≠t}) : join M t k a c.val=a c := by + exact congrFun (congrArg Prod.snd + ((Equiv.piSplitAt t (fun c => Fin (M c+1))).apply_symm_apply (k,a))) c + +/-- The fibre has no multiplicity: choosing the retained cell fixes +that coordinate and leaves exactly the independent choices elsewhere. -/ +theorem fibre_eq_sum (M : C → ℕ) (F : (C×Bool → ℕ) → ℝ) + (t : C) (k : Fin (M t+1)) : + fibre M F t k=∑ a : Others M t,F (profile M (join M t k a)) := by + let e := Equiv.piSplitAt t (fun c => Fin (M c+1)) + have he : (∑ a : Profiles M,if a t=k then F (profile M a) else 0)= + ∑ p : Fin (M t+1)×Others M t,if p.1=k then F (profile M (e.symm p)) else 0 := by + apply Fintype.sum_equiv e + intro a + simp only [Equiv.symm_apply_apply] + rfl + unfold fibre + rw [he,Fintype.sum_prod_type,Finset.sum_comm] + simp only [Finset.sum_ite_eq',Finset.mem_univ,ite_true] + rfl + +theorem fibre_nonnegative (M : C → ℕ) (F : (C×Bool → ℕ) → ℝ) + (hF : ∀ z,0 ≤ F z) (t : C) (k : Fin (M t+1)) : 0 ≤ fibre M F t k := by + apply Finset.sum_nonneg + intro a _ + split_ifs + · exact hF _ + · exact le_rfl + +/-- The actual one-cell fibres partition the full physical finite sum. -/ +theorem sum_fibre (M : C → ℕ) (F : (C×Bool → ℕ) → ℝ) (t : C) : + (∑ k : Fin (M t+1),fibre M F t k)=∑ a : Profiles M,F (profile M a) := by + unfold fibre + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp + +end ContingencyTables.BalancedCellFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCompletionMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCompletionMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c72b29976262fdb9e16940093660ffe0299977a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedCompletionMass.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallBalancedEncoding + +namespace OAI + +/-! # Balanced profile/completion pairs inject into padded tables -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal FirstPaperProfiles +open SmallContextFibres SmallContextCoordinates SmallContextEnumeration RowMajorEnumeration +open PaddedCompletions CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] + +lemma balanced_fibre_views_eq (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) + (hz : Balanced small B z) (Z : CompletionFibre small B r rbar c cbar z) : + Z.val.val.1=Z.val.val.2 := by + funext i j + cases hs : small i j with + | false => exact Z.property.2.2.2.1 i j hs + | true => + rw [(Z.property.2.2.1 i j hs).1,(Z.property.2.2.1 i j hs).2] + have h := hz i j + simpa only [smallView,smallQ,hs,dite_eq_left] using h + +noncomputable def balancedFibreTable (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : SmallProfile small) + (hz : Balanced small B z) (Z : CompletionFibre small B r rbar c cbar z) : + Table rbar cbar := + ⟨Z.val.val.1,Z.val.property.1,by + rw [balanced_fibre_views_eq small B r rbar c cbar z hz Z] + exact Z.val.property.2⟩ + +variable [LinearOrder I] [LinearOrder J] + +abbrev BalancedJoint (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) := + (a : Fin (Fintype.card (Cells small)) → Fin (U+1)) × + CompletionFibre small B r (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) (rawChoice small U (wordChoices small U a)) + +noncomputable def balancedJointTable (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (a : BalancedJoint small B r c L U) : + Table (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L) := + balancedFibreTable small B r _ c _ _ (rawChoice_balanced small B U hB _) a.2 + +lemma balancedJointTable_injective (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + Function.Injective (balancedJointTable small B r c L U hB) := by + intro a b hab + apply fibre_projection_injective small B r _ c _ + (fun a => rawChoice small U (wordChoices small U a)) + ((rawChoice_injective small U).comp (wordChoices small U).injective) + (fun a => rawChoice_bounded small B U hB _) + apply Subtype.ext + apply Prod.ext + · exact congrArg Subtype.val hab + · have ha := balanced_fibre_views_eq small B r _ c _ _ (rawChoice_balanced small B U hB _) a.2 + have hb := balanced_fibre_views_eq small B r _ c _ _ (rawChoice_balanced small B U hB _) b.2 + rw [← ha,← hb] + exact congrArg Subtype.val hab + +lemma word_mass_eq_balancedJoint_card (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + (∑ a,wordWeight small B r c L U a)=(Fintype.card (BalancedJoint small B r c L U):ℝ) := by + rw [Fintype.card_sigma,Nat.cast_sum] + apply Finset.sum_congr rfl + intro a _ + exact hardMarginal_eq_fibre_card small B r c L _ (rawChoice_bounded small B U hB _) + +/-- This inequality retains all large-cell multiplicities and counts every +balanced word exactly once. -/ +theorem word_mass_le_padded_count (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) : + (∑ a,wordWeight small B r c L U a) ≤ + (Fintype.card (Table (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)):ℝ) := by + rw [word_mass_eq_balancedJoint_card small B r c L U hB] + exact_mod_cast Fintype.card_le_of_injective _ (balancedJointTable_injective small B r c L U hB) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..06e04ed6faaeb8aaf4d2c19b3a26577c39c0f154 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedEnumeration.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedFamily + +namespace OAI + +/-! +# Balanced elimination as a finite assignment sum + +The recursive integer marginal equals the finite sum over the choices in +all eliminated large-cell pairs. This identifies the signature marginal +with the completion count. +-/ + +namespace ContingencyTables.BalancedEnumeration + +open scoped BigOperators Classical +open BalancedFamily IntegerMarginal BalancedBox + +@[reducible] def Assignments : List ℕ → Type + | [] => PUnit + | M::Ms => Assignments Ms × Fin (M+1) + +@[reducible] instance assignmentsFintype (Ms : List ℕ) : Fintype (Assignments Ms) := by + induction Ms with + | nil => exact inferInstanceAs (Fintype PUnit) + | cons M Ms ih => + letI := ih + exact inferInstanceAs (Fintype (Assignments Ms × Fin (M+1))) + +def embedding {I : Type*} : (Ms : List ℕ) → (I → ℕ) → Assignments Ms → Coordinates I Ms → ℕ + | [],z,_ => z + | M::Ms,z,a => profile (embedding Ms z a.1) a.2.val (M-a.2.val) + +theorem eliminate_eq_sum {I : Type*} (Ms : List ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : + eliminate Ms F z=∑ a : Assignments Ms, F (embedding Ms z a) := by + induction Ms with + | nil => simp only [eliminate,Assignments,embedding,Fintype.sum_unique] + | cons M Ms ih => + change eliminate Ms (marginal F M) z= + ∑ a : Assignments Ms × Fin (M+1), F (profile (embedding Ms z a.1) a.2.val (M-a.2.val)) + rw [ih,Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + unfold marginal + exact (Fin.sum_univ_eq_sum_range (fun j => F (profile (embedding Ms z a) j (M-j))) (M+1)).symm + +lemma embedding_inBox {I : Type*} (Ms : List ℕ) (m : I → ℕ) (z : I → ℕ) + (hz : InBox m z) (a : Assignments Ms) : InBox (bounds m Ms) (embedding Ms z a) := by + induction Ms with + | nil => exact hz + | cons M Ms ih => + apply profile_inBox (bounds m Ms) (embedding Ms z a.1) M a.2.val (M-a.2.val) + · exact ih a.1 + · have ha := a.2.isLt; omega + · exact Nat.sub_le _ _ + +lemma embedding_total {I : Type*} [Fintype I] (Ms : List ℕ) (z : I → ℕ) + (a : Assignments Ms) : + (∑ i, embedding Ms z a i)=(∑ i, z i)+Ms.sum := by + induction Ms with + | nil => simp only [embedding,List.sum_nil,add_zero] + | cons M Ms ih => + change (∑ i, profile (embedding Ms z a.1) a.2.val (M-a.2.val) i)=_ + rw [profile_total,ih] + have ha := a.2.isLt + simp only [List.sum_cons] + omega + +end ContingencyTables.BalancedEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedFamily.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b1fe62f9b77b4934bd5a153207d6ea654aa78e6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedFamily.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedBox +import OAI.Combinatorics.ContingencyTables.Transport.IntegerReflection + +namespace OAI + +/-! +# All finite balanced-pair eliminations + +The coordinates are the retained small coordinates followed by the actual +finite list of large-cell pairs. The recursion performs their finite +balanced sums and proves the total-slice positivity and removal signature +at every step. +-/ + +namespace ContingencyTables.BalancedFamily + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal BalancedBox + +universe u + +@[reducible] def Coordinates (I : Type u) : List ℕ → Type u + | [] => I + | _ :: Ms => Coordinates I Ms ⊕ Bool + +@[reducible] instance coordinatesFintype {I : Type*} [Fintype I] (Ms : List ℕ) : + Fintype (Coordinates I Ms) := by + induction Ms with + | nil => exact inferInstanceAs (Fintype I) + | cons M Ms ih => + letI := ih + exact inferInstanceAs (Fintype (Coordinates I Ms ⊕ Bool)) + +@[reducible] instance coordinatesDecidableEq {I : Type*} [DecidableEq I] (Ms : List ℕ) : + DecidableEq (Coordinates I Ms) := by + induction Ms with + | nil => exact inferInstanceAs (DecidableEq I) + | cons M Ms ih => + letI := ih + exact inferInstanceAs (DecidableEq (Coordinates I Ms ⊕ Bool)) + +def bounds {I : Type*} (m : I → ℕ) : (Ms : List ℕ) → Coordinates I Ms → ℕ + | [] => m + | M :: Ms => profile (bounds m Ms) M M + +noncomputable def eliminate {I : Type*} : (Ms : List ℕ) → + ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → ℝ + | [], F => F + | M :: Ms, F => eliminate Ms (marginal F M) + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- Every actual large-cell pair has width at least two; eliminating all +of them preserves precisely the required box-valid total slice. -/ +theorem eliminate_slices (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) + (hpos : PositiveSlice F (bounds m Ms) (R+Ms.sum)) + (hsig : RemovalSlice F (bounds m Ms) (R+Ms.sum)) : + PositiveSlice (eliminate Ms F) m R ∧ RemovalSlice (eliminate Ms F) m R := by + induction Ms with + | nil => simpa only [List.sum_nil,add_zero,eliminate,bounds] using And.intro hpos hsig + | cons M Ms ih => + have htotal : R+(M::Ms).sum = (R+Ms.sum)+M := by simp only [List.sum_cons]; omega + rw [htotal] at hpos hsig + have hp := marginal_positive_slice F (bounds m Ms) (R+Ms.sum) M hpos + have hs := marginal_removal_slice F (bounds m Ms) (R+Ms.sum) M + (hwidth M (by simp)) hpos hsig + exact ih (marginal F M) (fun N hN => hwidth N (by simp [hN])) hp hs + +omit [DecidableEq I] in +/-- Only the paper's finite box and required total slice are ever read +by a balanced marginal. In particular its zero extension is harmless. -/ +theorem eliminate_congr_slice (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (F f : (Coordinates I Ms → ℕ) → ℝ) + (heq : ∀ x, InBox (bounds m Ms) x → (∑ i, x i)=R+Ms.sum → F x=f x) + (z : I → ℕ) (hz : InBox m z) (htotal : (∑ i, z i)=R) : + eliminate Ms F z=eliminate Ms f z := by + induction Ms with + | nil => exact heq z hz (by simpa using htotal) + | cons M Ms ih => + apply ih (marginal F M) (marginal f M) + intro x hx hxtotal + apply Finset.sum_congr rfl + intro j hj + have hjM : j ≤ M := by simpa using Finset.mem_range.mp hj + apply heq _ (profile_inBox (bounds m Ms) x M j (M-j) hx hjM (Nat.sub_le _ _)) + rw [profile_total,hxtotal] + simp only [List.sum_cons] + omega + +omit [Fintype I] [DecidableEq I] in +theorem eliminate_nonnegative (Ms : List ℕ) (F : (Coordinates I Ms → ℕ) → ℝ) + (hF : ∀ x, 0 ≤ F x) (z : I → ℕ) : 0 ≤ eliminate Ms F z := by + induction Ms with + | nil => exact hF z + | cons M Ms ih => + apply ih (marginal F M) + intro x + apply Finset.sum_nonneg + intro j _ + exact hF (profile x j (M-j)) + +omit [Fintype I] [DecidableEq I] in +/-- Reflection reverses the finite index in every summed large pair and +also reflects every retained coordinate. -/ +theorem eliminate_reflect (Ms : List ℕ) (m : I → ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : + eliminate Ms (fun x => F (IntegerReflection.reflect (bounds m Ms) x)) z = + eliminate Ms F (IntegerReflection.reflect m z) := by + induction Ms with + | nil => rfl + | cons M Ms ih => + have he : marginal (fun x => F (IntegerReflection.reflect (bounds m (M::Ms)) x)) M = + fun x => marginal F M (IntegerReflection.reflect (bounds m Ms) x) := by + funext x + exact IntegerReflection.marginal_reflect F (bounds m Ms) x M + change eliminate Ms (marginal (fun x => F (IntegerReflection.reflect (bounds m (M::Ms)) x)) M) z = _ + rw [he] + exact ih (marginal F M) + +omit [Fintype I] [DecidableEq I] in +/-- All balanced eliminations are finite sums, so their actual values +commute with the equality-softening limit. -/ +theorem eliminate_tendsto {K : Type*} {l : Filter K} (Ms : List ℕ) + (F : K → (Coordinates I Ms → ℕ) → ℝ) (f : (Coordinates I Ms → ℕ) → ℝ) + (hlim : ∀ z, Filter.Tendsto (fun t => F t z) l (nhds (f z))) (z : I → ℕ) : + Filter.Tendsto (fun t => eliminate Ms (F t) z) l (nhds (eliminate Ms f z)) := by + induction Ms with + | nil => exact hlim z + | cons M Ms ih => + apply ih (fun t => marginal (F t) M) (marginal f M) + intro x + unfold marginal + apply tendsto_finsetSum + intro j _ + exact hlim (profile x j (M-j)) + +end ContingencyTables.BalancedFamily + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedJointConstruction.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedJointConstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..f62529201811bbf21b6ad462135fad963992f299 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedJointConstruction.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedCompletionMass + +namespace OAI + +/-! # Recover the unique balanced joint object from its full padded table -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal FirstPaperProfiles +open SmallContextFibres SmallContextCoordinates SmallContextEnumeration RowMajorEnumeration +open PaddedCompletions CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def tableWord (small : I → J → Bool) (U : ℕ) (Y : I → J → ℕ) + (hY : ∀ i j,small i j=true → Y i j ≤ U) : + Fin (Fintype.card (Cells small)) → Fin (U+1) := + (wordChoices small U).symm (fun a => ⟨Y a.val.1 a.val.2,Nat.lt_succ_of_le (hY _ _ a.property)⟩) + +lemma tableWord_false (small : I → J → Bool) (U : ℕ) (Y : I → J → ℕ) + (hY : ∀ i j,small i j=true → Y i j ≤ U) (a : Cells small) : + rawChoice small U (wordChoices small U (tableWord small U Y hY)) (a,false)=Y a.val.1 a.val.2 := by + unfold tableWord + rw [Equiv.apply_symm_apply] + rfl + +lemma tableWord_true (small : I → J → Bool) (U : ℕ) (Y : I → J → ℕ) + (hY : ∀ i j,small i j=true → Y i j ≤ U) (a : Cells small) : + rawChoice small U (wordChoices small U (tableWord small U Y hY)) (a,true)=U-Y a.val.1 a.val.2 := by + unfold tableWord + rw [Equiv.apply_symm_apply] + rfl + +/-- Residual feasibility and the literal small-cell bound suffice to +construct the balanced profile together with every retained large entry. -/ +noncomputable def jointOfTable (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) + (Y : Table (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L)) + (hY : ∀ i j,small i j=true → Y.val i j ≤ U) + (hR : ∀ i,smallRow small Y.val i ≤ r i) + (hC : ∀ j,smallColumnView small Y.val j ≤ c j) + (hlarge : ∀ i j,small i j=false → Y.val i j ≤ B i j) : BalancedJoint small B r c L U := + ⟨tableWord small U Y.val hY, + ⟨⟨(Y.val,Y.val),Y.property⟩,hR,hC,by + intro i j hs + constructor + · exact (tableWord_false small U Y.val hY ⟨(i,j),hs⟩).symm + · rw [tableWord_true,hB i j hs,Nat.sub_sub_self (hY i j hs)] + ,fun _ _ _ => rfl,hlarge⟩⟩ + +lemma jointOfTable_projection (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) + (Y : Table (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L)) + (hY : ∀ i j,small i j=true → Y.val i j ≤ U) + (hR : ∀ i,smallRow small Y.val i ≤ r i) + (hC : ∀ j,smallColumnView small Y.val j ≤ c j) + (hlarge : ∀ i j,small i j=false → Y.val i j ≤ B i j) : + balancedJointTable small B r c L U hB (jointOfTable small B r c L U hB Y hY hR hC hlarge)=Y := by + apply Subtype.ext + rfl + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedPhysicalPartition.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedPhysicalPartition.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f34383e1611625f5a581c30fea22a4c3a19ad60 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedPhysicalPartition.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedCellFibres + +namespace OAI + +/-! # Partitioning actual balanced profiles into small and large cells -/ + +namespace ContingencyTables.BalancedCellFibres + +open scoped BigOperators Classical +open PhysicalLargeProfiles LargePairEnumeration + +variable {C : Type*} + +abbrev SmallProfiles (small : C → Bool) (M : C → ℕ) := + (s : {c : C // small c=true}) → Fin (M s.val+1) + +noncomputable def partition (small : C → Bool) (M : C → ℕ) : + Profiles M ≃ SmallProfiles small M×PhysicalAssignments small M where + toFun a := (fun s => a s.val,fun l => a l.val) + invFun a c := if hs : small c=true then a.1 ⟨c,hs⟩ + else a.2 ⟨c,Bool.eq_false_iff.mpr hs⟩ + left_inv a := by funext c; dsimp only; split_ifs <;> rfl + right_inv a := by + apply Prod.ext + · funext s + simp only [s.property,dite_eq_left] + · funext l + simp only [l.property,Bool.false_eq_true,dite_false] + +def smallDisplay (small : C → Bool) (M : C → ℕ) (a : SmallProfiles small M) : SmallView small → ℕ := + fun p => if p.2 then M p.1.val-(a p.1).val else (a p.1).val + +lemma partition_profile (small : C → Bool) (M : C → ℕ) + (a : SmallProfiles small M×PhysicalAssignments small M) : + profile M ((partition small M).symm a)= + physicalProfile small M (smallDisplay small M a.1) a.2 := by + funext p + rcases p with ⟨c,b⟩ + by_cases hs : small c=true + · simp only [profile,partition,Equiv.coe_fn_symm_mk,physicalProfile,hs,dite_eq_left,smallDisplay] + · simp only [profile,partition,Equiv.coe_fn_symm_mk,physicalProfile,hs,Bool.false_eq_true,dite_false] + +variable [Fintype C] + +/-- This exact finite product split removes all artificial labels and +enumerations from the companion's terminal normalizer. -/ +theorem sum_eq_small_large (small : C → Bool) (M : C → ℕ) + (F : (C×Bool → ℕ) → ℝ) : + (∑ a : Profiles M,F (profile M a))= + ∑ s : SmallProfiles small M,∑ a : PhysicalAssignments small M, + F (physicalProfile small M (smallDisplay small M s) a) := by + have he := Fintype.sum_equiv (partition small M) + (fun a => F (profile M a)) + (fun a => F (physicalProfile small M (smallDisplay small M a.1) a.2)) + (by + intro a + have h := partition_profile small M ((partition small M) a) + simpa only [Equiv.symm_apply_apply] using congrArg F h) + rw [he,Fintype.sum_prod_type] + +end ContingencyTables.BalancedCellFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedSummation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedSummation.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e772cd46746e8ee5cf29d0047b2d42fbd6473af --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BalancedSummation.lean @@ -0,0 +1,315 @@ +import OAI.Combinatorics.ContingencyTables.Transport.QuadraticTransport +import Lean.Elab.Tactic.Omega +import Mathlib.Algebra.BigOperators.Ring.Finset + +namespace OAI + +/-! +# Balanced-pair summation of two-removal forms + +This is the finite unweighted closure step in paper 200-01, +Lemma `lem:pair-summation` (`D'=B`), and paper 200-02, +Lemma `lem:integer-signature`. The hypotheses describe the actual old/fresh +blocks and their adjacent cross entries. Cumulative coefficients are +constructed from those cross entries; no transport or closure conclusion is +assumed. In particular the zero-diagonal capacity-two case is included. +-/ + +namespace ContingencyTables + +open scoped BigOperators +open LinearMap (BilinForm) + +/-- The lower endpoint convention used by the balanced-pair matrices. -/ +theorem sum_pred_second_differences (a : ℕ → ℝ) (n : ℕ) : + (∑ j ∈ Finset.range (n + 1), (2 * a j - a (j - 1) - a (j + 1))) = + a n - a (n + 1) := by + induction n with + | zero => simp; ring + | succ n ih => + rw [Finset.sum_range_succ, ih] + simp only [Nat.add_sub_cancel] + ring + +/-- First moment of the discrete second difference, with exact boundaries. -/ +theorem sum_firstMoment_second_differences (a : ℕ → ℝ) (n : ℕ) : + (∑ j ∈ Finset.range (n + 1), (j : ℝ) * (2 * a j - a (j - 1) - a (j + 1))) = + ((n : ℝ) + 1) * a n - a 0 - (n : ℝ) * a (n + 1) := by + induction n with + | zero => simp + | succ n ih => + rw [Finset.sum_range_succ, ih] + simp only [Nat.add_sub_cancel, Nat.cast_add, Nat.cast_one] + ring + +/-- Second moment of the same difference. -/ +theorem sum_secondMoment_second_differences (a : ℕ → ℝ) (n : ℕ) : + (∑ j ∈ Finset.range (n + 1), (j : ℝ) ^ 2 * (2 * a j - a (j - 1) - a (j + 1))) = + ((n : ℝ) + 1) ^ 2 * a n - (n : ℝ) ^ 2 * a (n + 1) + a 0 - + 2 * ∑ j ∈ Finset.range (n + 1), a j := by + induction n with + | zero => simp; ring + | succ n ih => + have hs : (∑ j ∈ Finset.range (n + 1 + 1), a j) = + (∑ j ∈ Finset.range (n + 1), a j) + a (n + 1) := Finset.sum_range_succ _ _ + rw [Finset.sum_range_succ, ih, hs] + simp only [Nat.add_sub_cancel, Nat.cast_add, Nat.cast_one] + ring + +/-- The exact weighted telescope in equation pair-weighted. The boundary +terms are scalar values, so invalid endpoint matrices are never needed. -/ +theorem sum_weighted_second_differences (a : ℕ → ℝ) (n : ℕ) : + (∑ j ∈ Finset.range (n + 1), (j : ℝ) * ((n : ℝ) - j) * + (2 * a j - a (j - 1) - a (j + 1))) = + 2 * (∑ j ∈ Finset.range (n + 1), a j) - ((n : ℝ) + 1) * (a 0 + a n) := by + calc + _ = (n : ℝ) * (∑ j ∈ Finset.range (n + 1), (j : ℝ) * + (2 * a j - a (j - 1) - a (j + 1))) - + ∑ j ∈ Finset.range (n + 1), (j : ℝ) ^ 2 * + (2 * a j - a (j - 1) - a (j + 1)) := by + rw [Finset.mul_sum, ← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro j _ + ring + _ = _ := by + rw [sum_firstMoment_second_differences, sum_secondMoment_second_differences] + ring + +/-- Summation of the local inequalities with the actual nonnegative +weights. Only interior inequalities are required. -/ +theorem weighted_second_differences_bound (a v : ℕ → ℝ) (n : ℕ) + (ha0 : a 0 = 0) (han : a n = 0) + (hlocal : ∀ j, 0 < j → j < n → + 2 * a j - a (j - 1) - a (j + 1) ≤ -v j) : + 2 * (∑ j ∈ Finset.range (n + 1), a j) ≤ + -(∑ j ∈ Finset.range (n + 1), (j : ℝ) * ((n : ℝ) - j) * v j) := by + have hsum : (∑ j ∈ Finset.range (n + 1), (j : ℝ) * ((n : ℝ) - j) * + (2 * a j - a (j - 1) - a (j + 1))) ≤ + ∑ j ∈ Finset.range (n + 1), (j : ℝ) * ((n : ℝ) - j) * (-v j) := by + apply Finset.sum_le_sum + intro j hj + have hjn : j ≤ n := by simpa using Finset.mem_range.mp hj + by_cases hj0 : j = 0 + · subst j + simp + by_cases hjeq : j = n + · subst j + simp + have hjr : (j : ℝ) ≤ n := by exact_mod_cast hjn + apply mul_le_mul_of_nonneg_left (hlocal j (by omega) (by omega)) + exact mul_nonneg (Nat.cast_nonneg j) (sub_nonneg.mpr hjr) + rw [sum_weighted_second_differences, ha0, han] at hsum + simp only [add_zero, mul_zero, sub_zero, mul_neg, Finset.sum_neg_distrib] at hsum + exact hsum + +section Cumulative + +variable {V : Type*} [AddCommGroup V] [Module ℝ V] + +/-- The partial cross-entry sum in equation pair-cumulative. -/ +def pairCumulative (S : ℕ → V →ₗ[ℝ] ℝ) (v : V) (j : ℕ) : ℝ := + ∑ l ∈ Finset.range j, S (l + 1) v + +lemma pairCumulative_zero (S : ℕ → V →ₗ[ℝ] ℝ) (v : V) : pairCumulative S v 0 = 0 := by + simp [pairCumulative] + +lemma pairCumulative_succ (S : ℕ → V →ₗ[ℝ] ℝ) (v : V) (j : ℕ) : + pairCumulative S v (j + 1) = pairCumulative S v j + S (j + 1) v := by + exact Finset.sum_range_succ _ _ + +/-- The cumulative coefficients, with division by zero harmless at the +endpoints because the corresponding cumulative mass is proved zero. -/ +noncomputable def pairCoefficient (S : ℕ → V →ₗ[ℝ] ℝ) (u : ℕ → ℝ) (v : V) (j : ℕ) : ℝ := + pairCumulative S v j / u j + +lemma pairCoefficient_represents (S : ℕ → V →ₗ[ℝ] ℝ) (u : ℕ → ℝ) + (n : ℕ) (v : V) + (huint : ∀ j, 0 < j → j < n → 0 < u j) + (hbalance : pairCumulative S v n = 0) (hend : S (n + 1) v = 0) + {j : ℕ} (hj : j ≤ n + 1) : + u j * pairCoefficient S u v j = pairCumulative S v j := by + by_cases hj0 : j = 0 + · subst j + simp [pairCoefficient, pairCumulative_zero] + by_cases hjn : j = n + · subst j + simp [pairCoefficient, hbalance] + by_cases hjn1 : j = n + 1 + · subst j + simp [pairCoefficient, pairCumulative_succ, hbalance, hend] + have hu : u j ≠ 0 := ne_of_gt (huint j (by omega) (by omega)) + dsimp [pairCoefficient] + field_simp + +/-- Representation up to the balanced endpoint needs no value outside +that endpoint. This version is used for the `D'=B+1` interior displays. -/ +lemma pairCoefficient_represents_le (S : ℕ → V →ₗ[ℝ] ℝ) (u : ℕ → ℝ) + (n : ℕ) (v : V) + (huint : ∀ j, 0 < j → j < n → 0 < u j) + (hbalance : pairCumulative S v n = 0) {j : ℕ} (hj : j ≤ n) : + u j * pairCoefficient S u v j = pairCumulative S v j := by + by_cases hj0 : j = 0 + · subst j + simp [pairCoefficient, pairCumulative_zero] + by_cases hjn : j = n + · subst j + simp [pairCoefficient, hbalance] + have hu : u j ≠ 0 := ne_of_gt (huint j (by omega) (by omega)) + dsimp [pairCoefficient] + field_simp + +lemma pairCumulative_difference (S : ℕ → V →ₗ[ℝ] ℝ) (v : V) {j : ℕ} (hj : 0 < j) : + pairCumulative S v j - pairCumulative S v (j - 1) = S j v := by + have hh := pairCumulative_succ S v (j - 1) + have hj' : j - 1 + 1 = j := by omega + rw [hj'] at hh + linarith + +end Cumulative + +section Closure + +variable {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] + +/-- Summing the old blocks of the two-removal matrices preserves the +one-positive-direction signature. The cumulative coefficients and common kernel are explicit. -/ +theorem balancedPair_sum_onePositive + (n : ℕ) (hn : 2 ≤ n) + (B : ℕ → BilinForm ℝ W) (old : V →ₗ[ℝ] W) (ea eb : W) + (S : ℕ → V →ₗ[ℝ] ℝ) (u : ℕ → ℝ) + (hsymm : ∀ j ≤ n, ∀ x y, B j x y = B j y x) + (hsig : ∀ j ≤ n, OnePositiveDirection (B j)) + (hu0 : u 0 = 0) (hun : u n = 0) (hun1 : u (n + 1) = 0) + (huint : ∀ j, 0 < j → j < n → 0 < u j) + (hS0 : S 0 = 0) (hSn1 : S (n + 1) = 0) + (haa : ∀ j ≤ n, B j ea ea = u (j - 1)) + (hbb : ∀ j ≤ n, B j eb eb = u (j + 1)) + (hab : ∀ j ≤ n, B j ea eb = u j) + (hha : ∀ j ≤ n, ∀ v, B j (old v) ea = S j v) + (hhb : ∀ j ≤ n, ∀ v, B j (old v) eb = S (j + 1) v) : + OnePositiveDirection (∑ j ∈ Finset.range (n + 1), (B j).compl₁₂ old old) := by + let A : BilinForm ℝ V := ∑ j ∈ Finset.range (n + 1), (B j).compl₁₂ old old + let L : V →ₗ[ℝ] ℝ := ∑ j ∈ Finset.range n, S (j + 1) + have hA (v w : V) : A v w = ∑ j ∈ Finset.range (n + 1), B j (old v) (old w) := by + simp only [A, LinearMap.sum_apply, LinearMap.compl₁₂_apply] + have hu_nonneg {j : ℕ} (hj : j ≤ n + 1) : 0 ≤ u j := by + by_cases hj0 : j = 0 + · simp [hj0, hu0] + by_cases hjn : j = n + · simp [hjn, hun] + by_cases hjn1 : j = n + 1 + · simp [hjn1, hun1] + exact le_of_lt (huint j (by omega) (by omega)) + change OnePositiveDirection A + refine onePositiveDirection_of_kernel A ?_ L ?_ + · intro v w + rw [hA, hA] + apply Finset.sum_congr rfl + intro j hj + exact hsymm j (by simpa using Finset.mem_range.mp hj) _ _ + · intro v hv + have hbalance : pairCumulative S v n = 0 := by + simpa only [L, LinearMap.sum_apply, pairCumulative] using hv + have hend : S (n + 1) v = 0 := by rw [hSn1]; rfl + let g := pairCoefficient S u v + have hrepr {j : ℕ} (hj : j ≤ n + 1) : u j * g j = pairCumulative S v j := + pairCoefficient_represents S u n v huint hbalance hend hj + have hlocal {j : ℕ} (hj : j ≤ n) : + 2 * (u j * g j ^ 2) - (u (j - 1) * g (j - 1) ^ 2) - + (u (j + 1) * g (j + 1) ^ 2) ≤ -B j (old v) (old v) := by + have hleft : B j (old v) ea = u j * g j - u (j - 1) * g (j - 1) := by + rw [hha j hj, hrepr (by omega), hrepr (by omega)] + by_cases hj0 : j = 0 + · subst j + simp [hS0, pairCumulative_zero] + · have hc := pairCumulative_succ S v (j - 1) + have heq : j - 1 + 1 = j := by omega + rw [heq] at hc + linarith + have hright : B j (old v) eb = u (j + 1) * g (j + 1) - u j * g j := by + rw [hhb j hj, hrepr (by omega), hrepr (by omega), pairCumulative_succ] + ring + have hpositive : 0 < u (j - 1) ∨ 0 < u (j + 1) ∨ + (u (j - 1) = 0 ∧ u (j + 1) = 0 ∧ 0 < u j) := by + by_cases hm : 0 < u (j - 1) + · exact Or.inl hm + by_cases hp : 0 < u (j + 1) + · exact Or.inr (Or.inl hp) + have hj0 : 0 < j := by + by_contra h + have hjz : j = 0 := by omega + subst j + exact hp (huint 1 (by omega) (by omega)) + have hjn : j < n := by + by_contra h + have hjeq : j = n := by omega + subst j + exact hm (huint (n - 1) (by omega) (by omega)) + exact Or.inr (Or.inr ⟨le_antisymm (le_of_not_gt hm) (hu_nonneg (by omega)), + le_antisymm (le_of_not_gt hp) (hu_nonneg (by omega)), huint j hj0 hjn⟩) + simpa only [mul_assoc] using pair_step_of_signature (B j) (hsymm j hj) (hsig j hj) (old v) ea eb + (u (j - 1)) (u j) (u (j + 1)) (g (j - 1)) (g j) (g (j + 1)) + (haa j hj) (hbb j hj) (hab j hj) hleft hright + (hu_nonneg (by omega)) (hu_nonneg (by omega)) hpositive + have hsum := Finset.sum_le_sum (s := Finset.range (n + 1)) + (fun j hj => hlocal (by simpa using Finset.mem_range.mp hj)) + rw [sum_pred_second_differences] at hsum + simp only [hun, hun1, zero_mul, sub_self, Finset.sum_neg_distrib] at hsum + rw [hA] + linarith + +/-- The actual weighted pair estimate (`D'=B+1`) used in integer +signed transport. Only the box-valid interior matrices are evaluated. +The coefficients are the explicitly constructed cumulative quotients. -/ +theorem balancedPair_weighted_potential + (n : ℕ) (B : ℕ → BilinForm ℝ W) (old : V →ₗ[ℝ] W) (ea eb : W) + (S : ℕ → V →ₗ[ℝ] ℝ) (u : ℕ → ℝ) (v : V) + (hsymm : ∀ j, 0 < j → j < n → ∀ x y, B j x y = B j y x) + (hsig : ∀ j, 0 < j → j < n → OnePositiveDirection (B j)) + (hu0 : u 0 = 0) (hun : u n = 0) + (huint : ∀ j, 0 < j → j < n → 0 < u j) + (hbalance : pairCumulative S v n = 0) + (haa : ∀ j, 0 < j → j < n → B j ea ea = u (j - 1)) + (hbb : ∀ j, 0 < j → j < n → B j eb eb = u (j + 1)) + (hab : ∀ j, 0 < j → j < n → B j ea eb = u j) + (hha : ∀ j, 0 < j → j < n → B j (old v) ea = S j v) + (hhb : ∀ j, 0 < j → j < n → B j (old v) eb = S (j + 1) v) : + 2 * (∑ j ∈ Finset.range (n + 1), u j * pairCoefficient S u v j ^ 2) ≤ + -(∑ j ∈ Finset.range (n + 1), (j : ℝ) * ((n : ℝ) - j) * B j (old v) (old v)) := by + let g := pairCoefficient S u v + have hrepr {j : ℕ} (hj : j ≤ n) : u j * g j = pairCumulative S v j := + pairCoefficient_represents_le S u n v huint hbalance hj + have hu_nonneg {j : ℕ} (hj : j ≤ n) : 0 ≤ u j := by + by_cases hj0 : j = 0 + · simp [hj0, hu0] + by_cases hjn : j = n + · simp [hjn, hun] + exact le_of_lt (huint j (by omega) (by omega)) + apply weighted_second_differences_bound + (fun j => u j * g j ^ 2) (fun j => B j (old v) (old v)) n + (by simp [hu0]) (by simp [hun]) + intro j hj0 hjn + have hleft : B j (old v) ea = u j * g j - u (j - 1) * g (j - 1) := by + rw [hha j hj0 hjn, hrepr (by omega), hrepr (by omega)] + exact (pairCumulative_difference S v hj0).symm + have hright : B j (old v) eb = u (j + 1) * g (j + 1) - u j * g j := by + rw [hhb j hj0 hjn, hrepr (by omega), hrepr (by omega), pairCumulative_succ] + ring + have hpositive : 0 < u (j - 1) ∨ 0 < u (j + 1) ∨ + (u (j - 1) = 0 ∧ u (j + 1) = 0 ∧ 0 < u j) := by + by_cases hm : 0 < u (j - 1) + · exact Or.inl hm + by_cases hp : 0 < u (j + 1) + · exact Or.inr (Or.inl hp) + exact Or.inr (Or.inr ⟨le_antisymm (le_of_not_gt hm) (hu_nonneg (by omega)), + le_antisymm (le_of_not_gt hp) (hu_nonneg (by omega)), huint j hj0 hjn⟩) + simpa only [mul_assoc] using pair_step_of_signature (B j) (hsymm j hj0 hjn) (hsig j hj0 hjn) + (old v) ea eb (u (j - 1)) (u j) (u (j + 1)) (g (j - 1)) (g j) (g (j + 1)) + (haa j hj0 hjn) (hbb j hj0 hjn) (hab j hj0 hjn) hleft hright + (hu_nonneg (by omega)) (hu_nonneg (by omega)) hpositive + +end Closure + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanCountTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanCountTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..19c0e991e0ed8553d7cbfe9b7ad51ec64382ccd2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanCountTransport.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCount + +namespace OAI + +/-! # A completion-coordinate change in the finite transition count -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical +noncomputable section + +lemma booleanFinish_equiv_count {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq C] {s f Q : ℕ} (p : IntegerLaw A (2^f)) (q : IntegerLaw B Q) + (e : A ≃ B) (M : ℕ) (finish : (Fin s → Bool) → B → C) + (h : ∀ a,p.count a=q.count (e a)*M) (c : C) : + (booleanFinish p (fun bits a => finish bits (e a))).count c= + ∑ bits : Fin s → Bool,∑ b,if finish bits b=c then q.count b*M else 0 := by + rw [booleanFinish_count] + simp_rw [h] + apply Finset.sum_congr rfl + intro bits _ + exact e.sum_comp (fun b : B => if finish bits b=c then q.count b*M else 0) + +end +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd002981d25ebf19ddec3a788283291191dd39b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanEnumeration.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CompletionEnumerationProgram + +namespace OAI + +/-! # Enumerating only the short proposal word -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators Classical + +def digitBool (a : ℕ) : Bool := decide (a=1) + +def digitBoolRealizer : Realizer digitBool := composition (pair identity (constant 1)) natEqual + +lemma polynomial_digitBool : PolynomialTime digitBoolRealizer := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 1)) + polynomial_natEqual + +def booleanWords (xs : List Bool) : List (List Bool) := + (gridWords (xs,2)).map (List.map digitBool) + +def booleanWordsRealizer : Realizer booleanWords := + composition (composition (pair identity (constant 2)) gridWordsRealizer) + (map (map digitBoolRealizer)) + +lemma work_booleanWords : WorkBound booleanWordsRealizer + (fun xs => gridStateCount (xs,2)+weight xs) := by + have hi : WorkBound (pair (identity (A := List Bool)) (constant 2)) + (fun xs => gridStateCount (xs,2)+weight xs) := + work_of_polynomial (polynomial_pair polynomial_identity (polynomial_constant 2)) + Polynomial.X (fun xs => by simp) + have hg : WorkBound (composition (pair (identity (A := List Bool)) (constant 2)) + gridWordsRealizer) (fun xs => gridStateCount (xs,2)+weight xs) := by + apply work_composition hi work_gridWords (Polynomial.X+10) + intro xs + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat,weight_prod,id_eq] + have hc : weight (2:ℕ)≤9 := by simpa using weight_nat_numeric 2 + omega + unfold booleanWordsRealizer + exact work_then_polynomial hg (polynomial_map (polynomial_map polynomial_digitBool)) + +def booleanEnumeration (s : ℕ) : Fin (2^s) ≃ (Fin s → Bool) := + finFunctionFinEquiv.symm.trans (Equiv.piCongrRight (fun _ => finTwoEquiv)) + +lemma booleanWords_of_length (xs : List Bool) (s : ℕ) (hs : xs.length=s) : + booleanWords xs=List.ofFn (fun k => List.ofFn (booleanEnumeration s k)) := by + unfold booleanWords + rw [gridWords_finFunctions xs 1 s hs,List.map_ofFn] + apply congrArg List.ofFn + funext k + dsimp only [Function.comp_apply] + rw [List.map_ofFn] + apply congrArg List.ofFn + funext i + change digitBool ((finFunctionFinEquiv.symm k) i).val= + finTwoEquiv ((finFunctionFinEquiv.symm k) i) + have hb (a : Fin 2) : digitBool a.val=finTwoEquiv a := by + fin_cases a <;> rfl + exact hb _ + +lemma sum_booleanWords (xs : List Bool) (s : ℕ) (hs : xs.length=s) + (w : List Bool → ℕ) : + ((booleanWords xs).map w).sum=∑ bits : Fin s → Bool,w (List.ofFn bits) := by + rw [booleanWords_of_length xs s hs,List.map_ofFn,List.sum_ofFn] + exact (booleanEnumeration s).sum_comp (fun bits => w (List.ofFn bits)) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanIntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanIntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..f53918b39719b2fbf17f08f368a8dc406972e801 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BooleanIntegerLaw.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerEquivLaw +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Independent Boolean words combined with cached integer laws -/ + +namespace ContingencyTables.IntegerLaw +open FirstSuccess FairBits ResidualMixture +open scoped BigOperators Classical +noncomputable section + +def boolean (n : ℕ) : IntegerLaw (Fin n → Bool) (2^n) where + count _ := 1 + total := by simp + +lemma toRational_boolean (n : ℕ) : + (boolean n).toRational (by positivity)=uniformLaw (α := Fin n → Bool) := by + apply RationalLaw.ext + funext x + simp [toRational,boolean,uniformLaw,uniformMass] + +variable {B C : Type*} [Fintype B] [Fintype C] [DecidableEq C] + +/-- A short proposal word and an independently drawn cached completion +reserve their full combined word length. -/ +def booleanFinish {s f : ℕ} (p : IntegerLaw B (2^f)) + (finish : (Fin s → Bool) → B → C) : IntegerLaw C (2^(s+f)) := + (((boolean s).product p).push (fun z => finish z.1 z.2)).rebase (pow_add 2 s f).symm + +lemma toRational_booleanFinish {s f : ℕ} (p : IntegerLaw B (2^f)) + (draw : (Fin f → Bool) → B) (finish : (Fin s → Bool) → B → C) + (hp : p.toRational (by positivity)=mapLaw (uniformLaw (α := Fin f → Bool)) draw) : + (booleanFinish p finish).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (s+f) → Bool)) + (fun bits => finish (splitWordEquiv s f bits).1 (draw (splitWordEquiv s f bits).2)) := by + classical + unfold booleanFinish + rw [toRational_rebase,toRational_push,toRational_product,toRational_boolean,hp] + have he := mapLaw_product (uniformLaw (α := Fin s → Bool)) + (uniformLaw (α := Fin f → Bool)) id draw + rw [mapLaw_id] at he + rw [←he,mapLaw_comp] + have hs := map_equiv (splitWordEquiv s f) + (uniformLaw (α := Fin (s+f) → Bool)) + (fun z => finish z.1 (draw z.2)) + rw [uniform_equiv,←uniform_product] at hs + exact hs + all_goals positivity + +end +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedCellShift.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedCellShift.lean new file mode 100644 index 0000000000000000000000000000000000000000..68ba8cf533bb62cf6f899dba53645e9d77fdfc9a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedCellShift.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Model +import Mathlib.Tactic.SplitIfs + +namespace OAI + +/-! # A literal one-cell lower-bound reduction + +Requiring the selected entry to be at least t is equivalent to subtracting +t from that entry, its incident margins and its capacity. The three guards +are retained explicitly, including for zero margins and structural zeros. +-/ + +namespace ContingencyTables.BoundedCellShift + +open scoped BigOperators + +variable {m n : ℕ} + +def margin (r : Fin m→ℕ) (i₀ : Fin m) (t : ℕ) (i : Fin m) : ℕ := + if i=i₀ then r i-t else r i + +def lower (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) + (i : Fin m) (j : Fin n) : ℕ := + if i=i₀ ∧ j=j₀ then X i j-t else X i j + +def raise (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) + (i : Fin m) (j : Fin n) : ℕ := + X i j+if i=i₀ ∧ j=j₀ then t else 0 + +lemma lower_raise (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) : + lower (raise X i₀ j₀ t) i₀ j₀ t=X := by + funext i j + by_cases hi : i=i₀ <;> by_cases hj : j=j₀ <;> simp [lower,raise,hi,hj] + +lemma raise_lower (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) + (ht : t≤X i₀ j₀) : raise (lower X i₀ j₀ t) i₀ j₀ t=X := by + funext i j + by_cases hi : i=i₀ <;> by_cases hj : j=j₀ + · subst i; subst j + simpa only [raise,lower,ite_true,true_and,add_zero] using Nat.sub_add_cancel ht + all_goals simp [lower,raise,hi,hj] + +lemma raise_row_sum (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) + (t : ℕ) (i : Fin m) : + (∑ j,raise X i₀ j₀ t i j)=(∑ j,X i j)+if i=i₀ then t else 0 := by + by_cases hi : i=i₀ + · subst i + simp [raise,Finset.sum_add_distrib] + · simp [raise,hi] + +lemma raise_column_sum (X : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) + (t : ℕ) (j : Fin n) : + (∑ i,raise X i₀ j₀ t i j)=(∑ i,X i j)+if j=j₀ then t else 0 := by + by_cases hj : j=j₀ + · subst j + simp [raise,Finset.sum_add_distrib] + · simp [raise,hj] + +lemma lower_margins (X : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) (hm : HasMargins X r c) + (ht : t≤X i₀ j₀) : + HasMargins (lower X i₀ j₀ t) (margin r i₀ t) (margin c j₀ t) := by + have he := raise_lower X i₀ j₀ t ht + constructor + · intro i + by_cases hi : i=i₀ + · subst i + have hs := raise_row_sum (lower X i₀ j₀ t) i₀ j₀ t i₀ + rw [he,hm.1 i₀] at hs + simp only [ite_true] at hs + simp only [margin,ite_true] + omega + · have hs := raise_row_sum (lower X i₀ j₀ t) i₀ j₀ t i + rw [he,hm.1 i] at hs + simpa only [margin,hi,ite_false,Nat.add_zero] using hs.symm + · intro j + by_cases hj : j=j₀ + · subst j + have hs := raise_column_sum (lower X i₀ j₀ t) i₀ j₀ t j₀ + rw [he,hm.2 j₀] at hs + simp only [ite_true] at hs + simp only [margin,ite_true] + omega + · have hs := raise_column_sum (lower X i₀ j₀ t) i₀ j₀ t j + rw [he,hm.2 j] at hs + simpa only [margin,hj,ite_false,Nat.add_zero] using hs.symm + +lemma raise_margins (Y : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) + (hr : t≤r i₀) (hc : t≤c j₀) + (hm : HasMargins Y (margin r i₀ t) (margin c j₀ t)) : + HasMargins (raise Y i₀ j₀ t) r c := by + constructor + · intro i + rw [raise_row_sum,hm.1 i] + by_cases hi : i=i₀ + · subst i + simpa [margin] using Nat.sub_add_cancel hr + · simp [margin,hi] + · intro j + rw [raise_column_sum,hm.2 j] + by_cases hj : j=j₀ + · subst j + simpa [margin] using Nat.sub_add_cancel hc + · simp [margin,hj] + +lemma lower_bounds (X b : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) + (t : ℕ) (hb : ∀ i j,X i j≤b i j) : + ∀ i j,lower X i₀ j₀ t i j≤lower b i₀ j₀ t i j := by + intro i j + unfold lower + split_ifs + · exact Nat.sub_le_sub_right (hb i j) t + · exact hb i j + +lemma raise_bounds (Y b : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) + (t : ℕ) (ht : t≤b i₀ j₀) + (hb : ∀ i j,Y i j≤lower b i₀ j₀ t i j) : + ∀ i j,raise Y i₀ j₀ t i j≤b i j := by + intro i j + have h := hb i j + by_cases hi : i=i₀ <;> by_cases hj : j=j₀ + · subst i; subst j + simp only [lower,ite_true,true_and] at h + simp only [raise,ite_true,true_and] + omega + all_goals simpa [raise,lower,hi,hj] using h + +theorem feasible_lower_iff (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (i₀ : Fin m) (j₀ : Fin n) (t : ℕ) : + (∃ X,HasMargins X r c ∧ (∀ i j,X i j≤b i j) ∧ t≤X i₀ j₀) ↔ + t≤r i₀ ∧ t≤c j₀ ∧ t≤b i₀ j₀ ∧ + ∃ Y,HasMargins Y (margin r i₀ t) (margin c j₀ t) ∧ + ∀ i j,Y i j≤lower b i₀ j₀ t i j := by + constructor + · rintro ⟨X,hm,hb,ht⟩ + have hc : X i₀ j₀≤c j₀ := by + rw [←hm.2 j₀] + exact Finset.single_le_sum (f := fun i=>X i j₀) (fun _ _=>Nat.zero_le _) + (Finset.mem_univ i₀) + exact ⟨ht.trans (entry_le_row hm i₀ j₀),ht.trans hc,ht.trans (hb i₀ j₀), + lower X i₀ j₀ t,lower_margins X r c i₀ j₀ t hm ht,lower_bounds X b i₀ j₀ t hb⟩ + · rintro ⟨hr,hc,hb,Y,hm,hy⟩ + refine ⟨raise Y i₀ j₀ t,raise_margins Y r c i₀ j₀ t hr hc hm, + raise_bounds Y b i₀ j₀ t hb hy,?_⟩ + simp only [raise,ite_true,true_and] + omega + +end ContingencyTables.BoundedCellShift + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedOffsetLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedOffsetLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6785a5cf9a7d18cec694866978dc59d62c56fd1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedOffsetLaw.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalProducts +import OAI.Combinatorics.ContingencyTables.Machines.FairBits +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # Actual bounded scaling laws for the dense offsets -/ + +namespace ContingencyTables.FairBits + +open scoped BigOperators +open ResidualMixture FirstSuccess + +def scaledLaw (M k : ℕ) (hM : 0 < M) : RationalLaw (Fin M) where + mass := fun β => outputMass M (2 ^ k) β.val + nonnegative := fun β => outputMass_nonnegative _ _ _ + total := by + rw [Fin.sum_univ_eq_sum_range] + exact outputMass_total hM (pow_pos (by decide) _) + +def uniformIntLaw (M : ℕ) (hM : 0 < M) : RationalLaw (Fin M) where + mass := fun _ => 1 / (M : ℚ) + nonnegative := fun _ => by positivity + total := by + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + exact mul_one_div_cancel (by exact_mod_cast ne_of_gt hM) + +theorem scaledLaw_variation (M k : ℕ) (hM : 0 < M) : + variation (scaledLaw M k hM) (uniformIntLaw M hM) ≤ (M : ℚ) / (2 * (2 : ℚ) ^ k) := by + have h := variation_bound hM (pow_pos (by decide : 0 < 2) k) + change (1 / 2 : ℚ) * (∑ β ∈ Finset.range M, |outputMass M (2 ^ k) β - 1 / (M : ℚ)|) ≤ _ at h + unfold variation + simp only [scaledLaw, uniformIntLaw] + have hs : (∑ β : Fin M, |outputMass M (2 ^ k) β.val - 1 / (M : ℚ)|) = + ∑ β ∈ Finset.range M, |outputMass M (2 ^ k) β - 1 / (M : ℚ)| := + Fin.sum_univ_eq_sum_range (fun β => |outputMass M (2 ^ k) β - 1 / (M : ℚ)|) M + rw [hs] + simpa only [div_eq_mul_inv, mul_comm, Nat.cast_pow, Nat.cast_ofNat, one_mul] using h + +def offsetBitLength (w h d : ℕ) : ℕ := Nat.clog 2 (w + 1) + 4 * (h + d) + +/-- This law is the exact output law of multiplying the finite fair-bit +integer by w and taking the integer quotient. -/ +theorem dense_scaled_offset_variation (w h d : ℕ) (hw : 0 < w) : + variation (scaledLaw w (offsetBitLength w h d) hw) (uniformIntLaw w hw) ≤ + 1 / (2 : ℚ) ^ (4 * (h + d)) := by + apply (scaledLaw_variation w (offsetBitLength w h d) hw).trans + have hpow : w ≤ 2 ^ Nat.clog 2 (w + 1) := + (Nat.le_succ w).trans (Nat.le_pow_clog (by decide) (w + 1)) + have hp : (w : ℚ) ≤ (2 : ℚ) ^ Nat.clog 2 (w + 1) := by exact_mod_cast hpow + unfold offsetBitLength + rw [pow_add] + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + have hm := mul_le_mul_of_nonneg_right hp + (show (0 : ℚ) ≤ 2 ^ (4 * (h + d)) by positivity) + nlinarith [pow_pos (by norm_num : (0 : ℚ) < 2) (4 * (h + d))] + +theorem dense_offset_product_variation (q h d : ℕ) (w : Fin q → ℕ) + (hw : ∀ i, 0 < w i) (hq : q ≤ d) : + variation (piLaw (fun i => scaledLaw (w i) (offsetBitLength (w i) h d) (hw i))) + (piLaw (fun i => uniformIntLaw (w i) (hw i))) ≤ + (d : ℚ) / (2 : ℚ) ^ (4 * (h + d)) := by + calc + _ ≤ ∑ i : Fin q, variation + (scaledLaw (w i) (offsetBitLength (w i) h d) (hw i)) + (uniformIntLaw (w i) (hw i)) := variation_pi _ _ _ + _ ≤ ∑ _i : Fin q, 1 / (2 : ℚ) ^ (4 * (h + d)) := + Finset.sum_le_sum (fun i _ => dense_scaled_offset_variation (w i) h d (hw i)) + _ = (q : ℚ) / (2 : ℚ) ^ (4 * (h + d)) := by simp; ring + _ ≤ _ := div_le_div_of_nonneg_right (by exact_mod_cast hq) (by positivity) + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..f01084c141d7505580b4a78859c7fb0ca81c5f2d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileSemantics.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileWalk +import OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanStep + +namespace OAI + +/-! # The bounded binary loop preserves the physical profile walk -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts +open SmallContextCoordinates FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) + +lemma stateCode_bounded (x : PaperStates r c) (a : Cells (paperSmall r c)) (side : Bool) : + physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) x (a,side)≤d^20 := by + have he := (physicalProfile_feasible r c x).bounded (a,side) + exact he.trans_eq (stateCapacity_small r c _ _ a.property) + +lemma capViews_stateCode (x y : PaperStates r c) : + capViews (stateCodeData r c e x,stateCode r c e y)=stateCode r c e y := by + have hb (side : Bool) : + capView ((q,d^20),viewList (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) y) side)= + viewList (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c (d^12) y) side := by + apply capView_eq + · simp only [viewList,List.length_ofFn] + · intro a ha + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp ha + exact stateCode_bounded r c y (e i) side + simpa only [capViews,stateCodeData,codeCheckData,cellCatalog,List.length_ofFn,stateCode,profileCode] + using Prod.ext (hb false) (hb true) + +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +def encodedConfiguration (initial current : PaperStates r c) : ProfileConfiguration := + (((stateCodeData r c e initial,d^12),(d,h)),stateCode r c e current) + +theorem advanceProfile_encoded (htotal : (∑ i,r i)=∑ j,c j) + (initial x : PaperStates r c) (bits : Fin (s+f) → Bool) : + advanceProfile ((List.ofFn (splitWordEquiv s f bits).1,List.ofFn (splitWordEquiv s f bits).2), + encodedConfiguration r c e h initial x)= + encodedConfiguration r c e h initial (listedBitStep r c e hr hc b h hb x bits) := by + apply Prod.ext + · rfl + · change capViews (stateCodeData r c e initial, + profileStep (encodedStepInput r c e b h x + (splitWordEquiv s f bits).1 (splitWordEquiv s f bits).2))=_ + rw [profileStep_listedBitStep r c e hr hc b h hb htotal] + exact capViews_stateCode r c e initial _ + +theorem profileWalk_ofFn (htotal : (∑ i,r i)=∑ j,c j) + (initial x : PaperStates r c) (steps : ℕ) (bits : Fin steps → Fin (s+f) → Bool) : + profileWalk (encodedConfiguration r c e h initial x, + List.ofFn (fun i => (List.ofFn (splitWordEquiv s f (bits i)).1, + List.ofFn (splitWordEquiv s f (bits i)).2)))= + encodedConfiguration r c e h initial + (wordWalk (listedBitStep r c e hr hc b h hb) x steps bits) := by + induction steps with + | zero => rfl + | succ steps ih => + unfold profileWalk at ih ⊢ + rw [List.ofFn_succ',List.concat_eq_append,List.foldl_append] + change advanceProfile ((List.ofFn (splitWordEquiv s f (bits (Fin.last steps))).1, + List.ofFn (splitWordEquiv s f (bits (Fin.last steps))).2), + (List.ofFn (fun i => (List.ofFn (splitWordEquiv s f ((Fin.init bits) i)).1, + List.ofFn (splitWordEquiv s f ((Fin.init bits) i)).2))).foldl + (fun state word => advanceProfile (word,state)) + (encodedConfiguration r c e h initial x))=_ + rw [ih (Fin.init bits)] + exact advanceProfile_encoded r c e hr hc b h hb htotal initial _ _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd38255eb4accb2bd41ba9250870bf449452c713 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedProfileWalk.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionProgram + +namespace OAI + +/-! # A polynomial loop for the encoded small-profile walk -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def capView (z : (ℕ×ℕ)×List ℕ) : List ℕ := + (z.2.take z.1.1).map (fun a => min a z.1.2) + +def capViewRealizer : Realizer capView := + composition (pair (composition first second) + (composition (pair second (composition first first)) takeFast)) + (mapWith (composition (pair second first) minimum)) + +theorem polynomial_capView : PolynomialTime capViewRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) polynomial_takeFast)) + (polynomial_mapWith (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + polynomial_minimum)) + +lemma capView_weight (q U : ℕ) (xs : List ℕ) : + weight (capView ((q,U),xs))≤q*(4*U.size+2)+1 := by + have hw := weight_map_bound (f := fun a => min a U) (as := xs.take q) (N := 4*U.size+1) + (fun a _ => (weight_nat_le _).trans (by + have hs := Nat.size_le_size (min_le_right a U) + omega)) + change weight (capView ((q,U),xs))≤(xs.take q).length*(4*U.size+2)+1 at hw + exact hw.trans (by + have hl : (xs.take q).length≤q := by simp only [List.length_take]; exact min_le_left _ _ + gcongr) + +lemma capView_eq (q U : ℕ) (xs : List ℕ) (hq : xs.length=q) + (hU : ∀ a∈xs,a≤U) : capView ((q,U),xs)=xs := by + unfold capView + rw [←hq,List.take_length] + calc + xs.map (fun a => min a U)=xs.map id := List.map_congr_left (fun a ha => min_eq_left (hU a ha)) + _ = xs := List.map_id xs + +def capViews (z : ProfileCheckData×(List ℕ×List ℕ)) : List ℕ×List ℕ := + (capView ((z.1.1.1.1.length,z.1.2),z.2.1),capView ((z.1.1.1.1.length,z.1.2),z.2.2)) + +def capBounds (z : ProfileCheckData×(List ℕ×List ℕ)) : ℕ×ℕ := + (z.1.1.1.1.length,z.1.2) + +def capBoundsRealizer : Realizer capBounds := + pair (composition (composition + (f := fun z : ProfileCheckData×(List ℕ×List ℕ) => z.1) + (g := fun z : ProfileCheckData => z.1.1.1) first profileCatalog) listLength) + (composition first second) + +theorem polynomial_capBounds : PolynomialTime capBoundsRealizer := + polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_profileCatalog) polynomial_listLength) + (polynomial_composition polynomial_first polynomial_second) + +def capViewsRealizer : Realizer capViews := + pair (composition (pair capBoundsRealizer (composition second first)) capViewRealizer) + (composition (pair capBoundsRealizer (composition second second)) capViewRealizer) + +theorem polynomial_capViews : PolynomialTime capViewsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair polynomial_capBounds + (polynomial_composition polynomial_second polynomial_first)) polynomial_capView) + (polynomial_composition (polynomial_pair polynomial_capBounds + (polynomial_composition polynomial_second polynomial_second)) polynomial_capView) + +abbrev ProfileConfiguration := ResidualParameters×(List ℕ×List ℕ) +abbrev ProfileWord := List Bool×List Bool + +def currentParameters (z : ProfileConfiguration) : ResidualParameters := + ((candidateData (z.1.1.1,z.2),z.1.1.2),z.1.2) + +def currentParametersRealizer : Realizer currentParameters := + pair (pair (composition (pair (composition (composition first first) first) second) + candidateDataRealizer) (composition (composition first first) second)) + (composition first second) + +theorem polynomial_currentParameters : PolynomialTime currentParametersRealizer := + polynomial_pair (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) polynomial_candidateData) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + (polynomial_composition polynomial_first polynomial_second) + +def boundedNext (z : ProfileConfiguration×ProfileWord) : List ℕ×List ℕ := + capViews (z.1.1.1.1,profileStep (currentParameters z.1,z.2)) + +def boundedNextRealizer : Realizer boundedNext := by + let check : Realizer (fun z : ProfileConfiguration×ProfileWord => z.1.1.1.1) := + composition (composition (composition first first) first) first + let input : Realizer (fun z : ProfileConfiguration×ProfileWord => (currentParameters z.1,z.2)) := + pair (composition first currentParametersRealizer) second + exact composition (pair check (composition input profileStepRealizer)) capViewsRealizer + +theorem polynomial_boundedNext : PolynomialTime boundedNextRealizer := by + unfold boundedNextRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_currentParameters) polynomial_second) + polynomial_profileStep)) polynomial_capViews + +def advanceProfile (z : ProfileWord×ProfileConfiguration) : ProfileConfiguration := + (z.2.1,boundedNext (z.2,z.1)) + +def advanceProfileRealizer : Realizer advanceProfile := + pair (composition second first) (composition + (f := fun z : ProfileWord×ProfileConfiguration => (z.2,z.1)) (g := boundedNext) + (pair second first) boundedNextRealizer) + +theorem polynomial_advanceProfile : PolynomialTime advanceProfileRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_boundedNext) + +lemma advanceProfile_weight (word : ProfileWord) (z : ProfileConfiguration) (S : ℕ) + (hz : weight z.1≤S) : weight (advanceProfile (word,z))≤20*(S+1)^3 := by + let q := z.1.1.1.1.1.1.length + let U := z.1.1.1.2 + have hq : q≤S := (list_length_le_weight _).trans ((weight_fst z.1.1.1.1.1).trans + ((weight_fst z.1.1.1.1).trans ((weight_fst z.1.1.1).trans ((weight_fst z.1.1).trans ((weight_fst z.1).trans hz))))) + have hU : U.size≤S := (size_le_weight U).trans + ((weight_snd z.1.1.1).trans ((weight_fst z.1.1).trans ((weight_fst z.1).trans hz))) + have hx := capView_weight q U (profileStep (currentParameters z,word)).1 + have hy := capView_weight q U (profileStep (currentParameters z,word)).2 + change weight (z.1,(capView ((q,U),(profileStep (currentParameters z,word)).1), + capView ((q,U),(profileStep (currentParameters z,word)).2)))≤20*(S+1)^3 + rw [weight_prod z.1 _,weight_prod (capView ((q,U),(profileStep (currentParameters z,word)).1)) + (capView ((q,U),(profileStep (currentParameters z,word)).2))] + have hm : q*(4*U.size+2)≤S*(4*S+2) := by gcongr + nlinarith + +def profileWalk (z : ProfileConfiguration×List ProfileWord) : ProfileConfiguration := + z.2.foldl (fun state word => advanceProfile (word,state)) z.1 + +def profileWalkRealizer : Realizer profileWalk := + composition (pair second first) (fold advanceProfileRealizer) + +lemma profileFold_fixed (words : List ProfileWord) (z : ProfileConfiguration) : + (words.foldl (fun state word => advanceProfile (word,state)) z).1=z.1 := by + induction words generalizing z with + | nil => rfl + | cons w ws ih => exact ih _ + +lemma profileFold_weight (words : List ProfileWord) (z : ProfileConfiguration) (S : ℕ) + (hz : weight z≤S) : + weight (words.foldl (fun state word => advanceProfile (word,state)) z)≤20*(S+1)^3 := by + induction words using List.reverseRecOn with + | nil => + have hpow : S+1≤(S+1)^3 := Nat.le_self_pow (by decide) _ + simpa using hz.trans (by omega : S≤20*(S+1)^3) + | append_singleton words w _ih => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply advanceProfile_weight + rw [profileFold_fixed] + exact (weight_fst z).trans hz + +theorem polynomial_profileWalk : PolynomialTime profileWalkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advanceProfile (20*(X+1)^3) + intro words z pre post _ + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + exact profileFold_weight pre z (weight (words,z)) (weight_snd (words,z)) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableComplement.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableComplement.lean new file mode 100644 index 0000000000000000000000000000000000000000..55ca1215ec85ee5418bd38f08a90e69764231f77 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableComplement.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Model + +namespace OAI + +/-! # Complementing a bounded table + +The map X ↦ b-X transforms cell minima into maxima. All margin +subtractions are justified by an actual feasible table. +-/ + +namespace ContingencyTables.BoundedTableComplement + +open scoped BigOperators + +variable {m n : ℕ} + +def complement (b X : Fin m→Fin n→ℕ) (i : Fin m) (j : Fin n) : ℕ := b i j-X i j + +def rowTotal (b : Fin m→Fin n→ℕ) (i : Fin m) : ℕ := ∑ j,b i j +def columnTotal (b : Fin m→Fin n→ℕ) (j : Fin n) : ℕ := ∑ i,b i j + +def rows (b : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (i : Fin m) : ℕ := rowTotal b i-r i +def columns (b : Fin m→Fin n→ℕ) (c : Fin n→ℕ) (j : Fin n) : ℕ := columnTotal b j-c j + +lemma complement_bounds (b X : Fin m→Fin n→ℕ) : + ∀ i j,complement b X i j≤b i j := fun _ _=>Nat.sub_le _ _ + +lemma complement_twice (b X : Fin m→Fin n→ℕ) (hb : ∀ i j,X i j≤b i j) : + complement b (complement b X)=X := by + funext i j + exact Nat.sub_sub_self (hb i j) + +lemma complement_margins (b X : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hb : ∀ i j,X i j≤b i j) : + HasMargins (complement b X) (rows b r) (columns b c) := by + constructor + · intro i + have hs : (∑ j,complement b X i j)+(∑ j,X i j)=rowTotal b i := by + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j _ + exact Nat.sub_add_cancel (hb i j) + rw [hm.1 i] at hs + unfold rows + omega + · intro j + have hs : (∑ i,complement b X i j)+(∑ i,X i j)=columnTotal b j := by + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + exact Nat.sub_add_cancel (hb i j) + rw [hm.2 j] at hs + unfold columns + omega + +lemma row_total_ge (b X : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hb : ∀ i j,X i j≤b i j) (i : Fin m) : + r i≤rowTotal b i := by + rw [←hm.1 i] + exact Finset.sum_le_sum (fun j _=>hb i j) + +lemma column_total_ge (b X : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hb : ∀ i j,X i j≤b i j) (j : Fin n) : + c j≤columnTotal b j := by + rw [←hm.2 j] + exact Finset.sum_le_sum (fun i _=>hb i j) + +lemma margins_twice (b X : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hb : ∀ i j,X i j≤b i j) : + rows b (rows b r)=r ∧ columns b (columns b c)=c := by + constructor + · funext i + exact Nat.sub_sub_self (row_total_ge b X r c hm hb i) + · funext j + exact Nat.sub_sub_self (column_total_ge b X r c hm hb j) + +lemma complement_reverse_margins (b X Y : Fin m→Fin n→ℕ) + (r : Fin m→ℕ) (c : Fin n→ℕ) (hx : HasMargins X r c) (hxb : ∀ i j,X i j≤b i j) + (hy : HasMargins Y (rows b r) (columns b c)) (hyb : ∀ i j,Y i j≤b i j) : + HasMargins (complement b Y) r c := by + have h := complement_margins b Y (rows b r) (columns b c) hy hyb + obtain ⟨hr,hc⟩ := margins_twice b X r c hx hxb + rwa [hr,hc] at h + +end ContingencyTables.BoundedTableComplement + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableFeasibility.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableFeasibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..c0d35941b88e8cb5f260e91632a6abaff2751db5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoundedTableFeasibility.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Transport.LayeredTableNetwork +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! # Executed bounded-table feasibility from the cited flow bound + +The test runs the concrete residual algorithm on the literal three-layer +network. It handles zero margins, empty row or column types, and structural +zeros. No bounded-table feasibility oracle is assumed. +-/ + +namespace ContingencyTables.BoundedTableFeasibility + +open LayeredTableNetwork +open scoped BigOperators + +def vertices (m n : ℕ) : Vertex m n ≃ Fin (2+(m+n)) := + (Equiv.sumCongr finTwoEquiv.symm finSumFinEquiv).trans finSumFinEquiv + +variable {m n : ℕ} + +def networkCapacity (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : + PublishedEdmondsKarp.Capacity (2+(m+n)) := + fun u v=>capacity r c b ((vertices m n).symm u) ((vertices m n).symm v) + +def pull (f : PublishedEdmondsKarp.Flow (2+(m+n))) : Vertex m n → Vertex m n → ℤ := + fun u v=>f (vertices m n u) (vertices m n v) + +def push (f : Vertex m n → Vertex m n → ℤ) : PublishedEdmondsKarp.Flow (2+(m+n)) := + fun u v=>f ((vertices m n).symm u) ((vertices m n).symm v) + +lemma source_ne_sink : vertices m n (source : Vertex m n)≠vertices m n sink := by + intro h + have he := (vertices m n).injective h + cases he + +lemma capacity_loop (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (u : Fin (2+(m+n))) : networkCapacity r c b u u=0 := + capacity_diagonal r c b _ + +lemma pull_feasible (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (f : PublishedEdmondsKarp.Flow (2+(m+n))) + (hf : PublishedEdmondsKarp.Feasible (networkCapacity r c b) + (vertices m n source) (vertices m n sink) f) : Feasible r c b (pull f) := by + refine ⟨fun u v=>hf.1 _ _,?_,?_⟩ + · intro u v + simpa only [pull,networkCapacity,Equiv.symm_apply_apply] using hf.2.1 + (vertices m n u) (vertices m n v) + · intro u hs ht + have h := hf.2.2 (vertices m n u) + (fun he=>hs ((vertices m n).injective he)) + (fun he=>ht ((vertices m n).injective he)) + simpa only [pull,(vertices m n).sum_comp] using h + +lemma push_feasible (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (f : Vertex m n → Vertex m n → ℤ) (hf : Feasible r c b f) : + PublishedEdmondsKarp.Feasible (networkCapacity r c b) + (vertices m n source) (vertices m n sink) (push f) := by + refine ⟨fun u v=>hf.1 _ _,fun u v=>hf.2.1 _ _,?_⟩ + intro u hs ht + have h := hf.2.2 ((vertices m n).symm u) + (fun he=>hs ((vertices m n).symm_apply_eq.mp he)) + (fun he=>ht ((vertices m n).symm_apply_eq.mp he)) + simpa only [push,(vertices m n).symm.sum_comp] using h + +lemma pull_value (f : PublishedEdmondsKarp.Flow (2+(m+n))) : + value (pull f)=PublishedEdmondsKarp.value (vertices m n source) f := by + exact (vertices m n).sum_comp (fun v=>f (vertices m n source) v) + +lemma push_value (f : Vertex m n → Vertex m n → ℤ) : + PublishedEdmondsKarp.value (vertices m n source) (push f)=value f := by + simp only [PublishedEdmondsKarp.value,push,Equiv.symm_apply_apply] + exact (vertices m n).symm.sum_comp (fun v=>f source v) + +def computedFlow (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : + Vertex m n → Vertex m n → ℤ := + pull (EdmondsKarpAlgorithm.maxFlow (networkCapacity r c b) + (vertices m n source) (vertices m n sink)) + +def feasibleTest (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : Bool := + decide ((∑ i,r i)=∑ j,c j ∧ value (computedFlow r c b)=∑ i,(r i:ℤ)) + +theorem computedFlow_feasible (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : + Feasible r c b (computedFlow r c b) := + pull_feasible r c b _ (EdmondsKarpAlgorithm.maxFlow_correct hEK + (networkCapacity r c b) (capacity_loop r c b) _ _ source_ne_sink).1 + +theorem feasibleTest_correct (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : + feasibleTest r c b=true ↔ ∃ X,HasMargins X r c ∧ ∀ i j,X i j≤b i j := by + rw [feasibleTest,decide_eq_true_eq] + constructor + · rintro ⟨htotal,hvalue⟩ + exact ⟨decode (computedFlow r c b),decode_boundedTable r c b _ + (computedFlow_feasible hEK r c b) hvalue htotal⟩ + · rintro ⟨X,hm,hb⟩ + refine ⟨totals_equal hm,?_⟩ + have hmax := EdmondsKarpAlgorithm.maxFlow_correct hEK + (networkCapacity r c b) (capacity_loop r c b) + (vertices m n source) (vertices m n sink) source_ne_sink + have hle := hmax.2 (push (tableFlow r c X)) + (push_feasible r c b _ (tableFlow_feasible r c b X hm hb)) + rw [push_value,tableFlow_value,←pull_value] at hle + exact le_antisymm (value_le_total r c b _ (computedFlow_feasible hEK r c b)) hle + +end ContingencyTables.BoundedTableFeasibility + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad3a8d25559ec2e9988c6b5c8cc3899b5b01a7cc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxCompletion.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialSemantics + +namespace OAI + +/-! # Enumerating tables through their free entries -/ + +namespace ContingencyTables.BoxCompletion +open DenseAffine DensePrograms +open scoped BigOperators Classical +noncomputable section + +abbrev Box (m n N : ℕ) := Fin (m*n) → Fin (N+1) + +def freeValues {m n N : ℕ} (z : Box m n N) : Fin m×Fin n → ℕ := + fun ij => (z (finProdFinEquiv ij)).val + +def decode {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (htotal : ∑ i,R i=∑ j,P j) (N : ℕ) (z : Box m n N) : Option (Table R P) := + if hz : ∀ i j,0 ≤ integerTable R P (freeValues z) i j then + some ⟨naturalTable R P (freeValues z),naturalTable_rows R P _ hz, + naturalTable_columns R P _ hz htotal⟩ + else none + +def encode {m n N : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hN : (∑ i,R i)≤N) (X : Table R P) : Box m n N := fun k => + ⟨X.val (some (finProdFinEquiv.symm k).1) (some (finProdFinEquiv.symm k).2), + Nat.lt_succ_of_le ((entry_le_total X.property _ _).trans hN)⟩ + +lemma freeValues_encode {m n N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hN : (∑ i,R i)≤N) (X : Table R P) : + freeValues (encode R P hN X)=fun ij => X.val (some ij.1) (some ij.2) := by + funext ij + simp only [freeValues,encode,Equiv.symm_apply_apply] + +lemma decode_encode {m n N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) + (hN : (∑ i,R i)≤N) (X : Table R P) : + decode R P htotal N (encode R P hN X)=some X := by + have he := integerTable_recover R P X.val X.property.1 X.property.2 + have hz : ∀ i j,0 ≤ integerTable R P (freeValues (encode R P hN X)) i j := by + rw [freeValues_encode,he] + exact fun _ _ => Int.natCast_nonneg _ + rw [decode,dite_eq_left hz] + congr 1 + apply Subtype.ext + funext i j + simp only [naturalTable,freeValues_encode,he,Int.toNat_natCast] + +/-- Each feasible table occurs at exactly one enumerated free vector. -/ +theorem decode_eq_some {m n N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) + (hN : (∑ i,R i)≤N) (z : Box m n N) (X : Table R P) : + decode R P htotal N z=some X ↔ z=encode R P hN X := by + constructor + · intro h + unfold decode at h + split at h + next hz => + have he := Option.some.inj h + funext k + apply Fin.ext + have hv := congrArg (fun Y : Table R P => + Y.val (some (finProdFinEquiv.symm k).1) (some (finProdFinEquiv.symm k).2)) he + simpa only [naturalTable_free,freeValues,Prod.mk.eta, + Equiv.apply_symm_apply,encode] using hv + next hz => cases h + · rintro rfl + exact decode_encode R P htotal hN X + +lemma decode_elim_sum {A : Type*} [Fintype A] (y : Option A) (w : A → ℕ) : + y.elim 0 w=∑ a,if y=some a then w a else 0 := by + cases y <;> simp + +/-- Summing over candidate completions counts each feasible table once, +and gives zero weight to every rejected completion. -/ +theorem sum_decode {m n N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) + (hN : (∑ i,R i)≤N) (w : Table R P → ℕ) : + (∑ z : Box m n N,(decode R P htotal N z).elim 0 w)=∑ X,w X := by + simp_rw [decode_elim_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro X _ + simp_rw [decode_eq_some R P htotal hN] + simp + +/-- The existing executable acceptance test returns the same optional +table as the finite enumeration used in the counting proof. -/ +theorem acceptCompletion_eq {m n N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) (z : Box m n N) : + acceptCompletion ((marginCode R,marginCode P), + matrixCode (fun i j => freeValues z (i,j)))= + (decode R P htotal N z).map tableOutput := by + by_cases hz : ∀ i j,0 ≤ integerTable R P (freeValues z) i j + · have hv := (completionValid_code R P (fun i j => freeValues z (i,j))).mpr hz + simp only [acceptCompletion,hv,ite_true,decode,dite_eq_left hz] + rw [completedMatrix_code] + rfl + · have hv : completionValid ((marginCode R,marginCode P), + matrixCode (fun i j => freeValues z (i,j)))≠true := by + intro h + exact hz ((completionValid_code R P _).mp h) + simp only [acceptCompletion,hv,Bool.false_eq_true,ite_false,decode,dite_eq_right hz, + Option.map_none] + +end +end ContingencyTables.BoxCompletion + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxGeometry.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3edb708bab2a379af7f8773a05512a17fd951fa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/BoxGeometry.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.ContingencyTables.PublishedInputs +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring +import Mathlib.MeasureTheory.Function.LocallyIntegrable +import Mathlib.Analysis.Convex.Basic + +namespace OAI + +/-! +# Finite-box geometry for the conditional conductance argument + +Finite unions of grid boxes remain finite unions of boxes under weighted +Minkowski interpolation, giving the domain hypothesis of Prékopa–Leindler. +-/ + +namespace ContingencyTables.PublishedInputs + +open MeasureTheory + +private theorem scalar_box_interpolation (t a b c d z : ℝ) + (ht : 0 < t) (ht1 : t < 1) (hab : a < b) (hcd : c < d) + (hz : (1 - t) * a + t * c < z ∧ z < (1 - t) * b + t * d) : + ∃ w : ℝ × ℝ, a < w.1 ∧ w.1 < b ∧ c < w.2 ∧ w.2 < d ∧ + z = (1 - t) * w.1 + t * w.2 := by + let D := (1 - t) * (b - a) + t * (d - c) + have hD : 0 < D := add_pos (mul_pos (sub_pos.mpr ht1) (sub_pos.mpr hab)) + (mul_pos ht (sub_pos.mpr hcd)) + let wgt := (z - ((1 - t) * a + t * c)) / D + have hwgt : 0 < wgt := div_pos (sub_pos.mpr hz.1) hD + have hwgt1 : wgt < 1 := by + apply (div_lt_one hD).mpr + dsimp [D] + linarith [hz.2] + refine ⟨(a + wgt * (b - a), c + wgt * (d - c)), ?_, ?_, ?_, ?_, ?_⟩ + · linarith [mul_pos hwgt (sub_pos.mpr hab)] + · nlinarith [mul_pos (sub_pos.mpr hwgt1) (sub_pos.mpr hab)] + · linarith [mul_pos hwgt (sub_pos.mpr hcd)] + · nlinarith [mul_pos (sub_pos.mpr hwgt1) (sub_pos.mpr hcd)] + · dsimp [wgt] + field_simp + dsimp [D] + ring + +private theorem finite_box_union_of_fintype {q : ℕ} {K : Type*} [Fintype K] + (lower upper : K → Point q) : + IsFiniteBoxUnion {x | ∃ k : K, ∀ i, lower k i < x i ∧ x i < upper k i} := by + classical + let e := (Fintype.equivFin K).symm + refine ⟨Fintype.card K, (fun k => lower (e k)), (fun k => upper (e k)), ?_⟩ + ext x + constructor + · rintro ⟨k, hk⟩ + exact ⟨e.symm k, by simpa using hk⟩ + · rintro ⟨k, hk⟩ + exact ⟨e k, hk⟩ + +/-- Interpolation preserves exactly the finite-box class appearing in +Prékopa's published integral inequality. -/ +theorem IsFiniteBoxUnion.interpolate {q : ℕ} {S T : Set (Point q)} + (hS : IsFiniteBoxUnion S) (hT : IsFiniteBoxUnion T) + (t : ℝ) (ht : 0 < t) (ht1 : t < 1) : + IsFiniteBoxUnion (interpolate t S T) := by + classical + obtain ⟨n, l, u, rfl⟩ := hS + obtain ⟨m, l', u', rfl⟩ := hT + let K := {p : Fin n × Fin m // + (∀ i, l p.1 i < u p.1 i) ∧ (∀ i, l' p.2 i < u' p.2 i)} + let lower : K → Point q := fun p i => (1 - t) * l p.val.1 i + t * l' p.val.2 i + let upper : K → Point q := fun p i => (1 - t) * u p.val.1 i + t * u' p.val.2 i + have heq : PublishedInputs.interpolate t {x | ∃ k : Fin n, ∀ i, l k i < x i ∧ x i < u k i} + {x | ∃ k : Fin m, ∀ i, l' k i < x i ∧ x i < u' k i} = + {z | ∃ k : K, ∀ i, lower k i < z i ∧ z i < upper k i} := by + ext z + constructor + · rintro ⟨x, ⟨k, hk⟩, y, ⟨k', hk'⟩, rfl⟩ + let p : K := ⟨(k, k'), + (fun i => (hk i).1.trans (hk i).2), + (fun i => (hk' i).1.trans (hk' i).2)⟩ + refine ⟨p, ?_⟩ + intro i + change (1 - t) * l k i + t * l' k' i < (1 - t) * x i + t * y i ∧ + (1 - t) * x i + t * y i < (1 - t) * u k i + t * u' k' i + constructor + · exact add_lt_add + (mul_lt_mul_of_pos_left (hk i).1 (sub_pos.mpr ht1)) + (mul_lt_mul_of_pos_left (hk' i).1 ht) + · exact add_lt_add + (mul_lt_mul_of_pos_left (hk i).2 (sub_pos.mpr ht1)) + (mul_lt_mul_of_pos_left (hk' i).2 ht) + · rintro ⟨p, hp⟩ + have hw (i : Fin q) := scalar_box_interpolation t + (l p.val.1 i) (u p.val.1 i) (l' p.val.2 i) (u' p.val.2 i) (z i) + ht ht1 (p.property.1 i) (p.property.2 i) (hp i) + choose w hw using hw + refine ⟨(fun i => (w i).1), ⟨p.val.1, ?_⟩, + (fun i => (w i).2), ⟨p.val.2, ?_⟩, ?_⟩ + · exact fun i => ⟨(hw i).1, (hw i).2.1⟩ + · exact fun i => ⟨(hw i).2.2.1, (hw i).2.2.2.1⟩ + · funext i + exact (hw i).2.2.2.2 + rw [heq] + exact finite_box_union_of_fintype lower upper + +theorem IsFiniteBoxUnion.isOpen {q : ℕ} {S : Set (Point q)} + (hS : IsFiniteBoxUnion S) : IsOpen S := by + obtain ⟨n, l, u, rfl⟩ := hS + have heq : {x : Point q | ∃ k : Fin n, ∀ i, l k i < x i ∧ x i < u k i} = + ⋃ k : Fin n, ⋂ i : Fin q, {x : Point q | l k i < x i ∧ x i < u k i} := by + ext x + simp + rw [heq] + apply isOpen_iUnion + intro k + apply isOpen_iInter_of_finite + intro i + exact (isOpen_lt continuous_const (continuous_apply i)).inter + (isOpen_lt (continuous_apply i) continuous_const) + +theorem interpolation_closure_in_box {q : ℕ} {S T : Set (Point q)} + {lower upper : Point q} (hS : closure S ⊆ Set.Icc lower upper) + (hT : closure T ⊆ Set.Icc lower upper) (t : ℝ) (ht : 0 ≤ t) (ht1 : t ≤ 1) : + closure (interpolate t S T) ⊆ Set.Icc lower upper := by + apply isClosed_Icc.closure_subset_iff.mpr + rintro _ ⟨x, hx, y, hy, rfl⟩ + exact convex_Icc lower upper (hS (subset_closure hx)) (hT (subset_closure hy)) + (sub_nonneg.mpr ht1) ht (by ring) + +private theorem weighted_geometric_doubling (a b t : ℝ) (ha : 0 < a) + (hb : 2 * a ≤ b) (ht : 0 ≤ t) : + (2 : ℝ) ^ t * a ≤ a ^ (1 - t) * b ^ t := by + have hab : 0 ≤ 2 * a := by positivity + have hr := Real.rpow_le_rpow hab hb ht + calc + (2 : ℝ) ^ t * a = a ^ (1 - t) * (2 * a) ^ t := by + rw [Real.mul_rpow (by norm_num) ha.le] + have heq := Real.rpow_add ha (1 - t) t + have hexp : (1 - t) + t = 1 := by ring + rw [hexp, Real.rpow_one] at heq + calc + (2 : ℝ) ^ t * a = (2 : ℝ) ^ t * (a ^ (1 - t) * a ^ t) := + congrArg (fun z => (2 : ℝ) ^ t * z) heq + _ = a ^ (1 - t) * ((2 : ℝ) ^ t * a ^ t) := by ring + _ ≤ a ^ (1 - t) * b ^ t := + mul_le_mul_of_nonneg_left hr (Real.rpow_nonneg ha.le _) + +/-- The interpolation shell gains the mass used in the grid-cut proof. +This conditional result depends only on the precisely identified published +integral inequality; finite-box closure and integrability are proved here. -/ +theorem interpolation_shell_gain {q : ℕ} (hPL : FiniteBoxPrekopaLeindler q) + (t : ℝ) (ht : 0 < t) (ht1 : t < 1) + (lower upper : Point q) (S T : Set (Point q)) (ρ : Point q → ℝ) + (hS : IsFiniteBoxUnion S) (hT : IsFiniteBoxUnion T) + (hSc : closure S ⊆ Set.Icc lower upper) + (hTc : closure T ⊆ Set.Icc lower upper) + (hρ : ContinuousOn ρ (Set.Icc lower upper)) + (hpos : ∀ x ∈ Set.Icc lower upper, 0 < ρ x) + (hlc : LogConcaveOn ρ (Set.Icc lower upper)) + (hsub : S ⊆ interpolate t S T) + (hSmass : 0 < ∫ x in S, ρ x) + (hTmass : 2 * (∫ x in S, ρ x) ≤ ∫ x in T, ρ x) : + ((2 : ℝ) ^ t - 1) * (∫ x in S, ρ x) ≤ + ∫ x in (interpolate t S T) \ S, ρ x := by + have hMc := interpolation_closure_in_box hSc hTc t ht.le ht1.le + have hM := hS.interpolate hT t ht ht1 + have hint : IntegrableOn ρ (interpolate t S T) := + hρ.integrableOn_Icc.mono_set (fun _ hx => hMc (subset_closure hx)) + rw [MeasureTheory.setIntegral_sdiff hS.isOpen.measurableSet hint hsub] + have hPL' := density_interpolation hPL t ht ht1 lower upper S T ρ + hS hT hM hSc hTc hMc hρ hpos hlc + have hgain := weighted_geometric_doubling (∫ x in S, ρ x) (∫ x in T, ρ x) + t hSmass hTmass ht.le + nlinarith + +end ContingencyTables.PublishedInputs + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CacheBoxBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CacheBoxBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4f2065fa386b938aeed9c04eb2a53dcc8e03f56 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CacheBoxBounds.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTabulationScalarBounds +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntryRuntime + +namespace OAI + +/-! # The finite boxes controlling one cached transition entry -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms Polynomial + +def completionBoxMeasure (z : CanonicalParameters) : ℕ := + rawBoxMeasure (canonicalCountInput z).1+ + gridStateCount (completionEnumerationData z.1)+weight z + +theorem completionWeightMeasure_polynomial : ∃ p : Polynomial ℕ,∀ z, + completionWeightMeasure z ≤ p.eval (completionBoxMeasure z) := by + obtain ⟨p,hp⟩ := polynomial_canonicalCountInput + obtain ⟨q,hq⟩ := rawTabulationMeasure_polynomial + refine ⟨q+p+2*X,?_⟩ + intro z + let M := completionBoxMeasure z + have hz : weight z ≤ M := by unfold M completionBoxMeasure; omega + have hw : weight (canonicalCountInput z) ≤ p.eval M := + (Nat.le_add_left _ _).trans ((hp z).trans (polynomial_eval_monotone p hz)) + have hb : rawBoxMeasure (canonicalCountInput z).1 ≤ M := by + unfold M completionBoxMeasure; omega + have hr : rawTabulationMeasure (canonicalCountInput z).1 ≤ q.eval M := + (hq (canonicalCountInput z).1).trans (polynomial_eval_monotone q hb) + have hc : gridStateCount (completionEnumerationData z.1)+weight z.1 ≤ M := by + have := weight_fst z + unfold M completionBoxMeasure + omega + change rawTabulationMeasure (canonicalCountInput z).1+weight (canonicalCountInput z)+ + weight z+(gridStateCount (completionEnumerationData z.1)+weight z.1) ≤ _ + change _ ≤ (q+p+2*X).eval M + simp only [eval_add,eval_mul,eval_ofNat,eval_X] + omega + +end ContingencyTables.DensePrograms + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +def matrixEntryBox (z : MatrixEntryInput) : ℕ := + completionBoxMeasure (residualParameters (entryCacheParameters z).1)+ + (entryCacheParameters z).2+gridStateCount (z.1.2,2)+weight z + +def entryResidualParameters (z : MatrixEntryInput) : CanonicalParameters := + residualParameters (entryCacheParameters z).1 + +def entryResidualRealizer : Realizer entryResidualParameters := + composition (f := fun z : MatrixEntryInput => (entryCacheParameters z).1) + (g := residualParameters) + (composition (f := entryCacheParameters) (g := Prod.fst) entryCacheParametersRealizer first) + residualParametersRealizer + +lemma polynomial_entryResidual : PolynomialTime entryResidualRealizer := + polynomial_composition (polynomial_composition polynomial_entryCacheParameters polynomial_first) + polynomial_residualParameters + +/-- Separating binary preparation size from the four enumerated boxes. -/ +theorem matrixEntryBox_bound : ∃ p : Polynomial ℕ,∀ z, + let r := entryResidualParameters z + let a := (canonicalCountInput r).1 + matrixEntryBox z ≤ (4*a.2.1^8)^tabulationDimension a+ + gridStateCount (completionEnumerationData a.1)+ + gridStateCount (completionEnumerationData r.1)+gridStateCount (z.1.2,2)+ + r.2.1+r.2.2+(entryCacheParameters z).2+p.eval (weight z) := by + obtain ⟨p,hp⟩ := polynomial_entryResidual + obtain ⟨q,hq⟩ := polynomial_canonicalCountInput + refine ⟨q.comp p+p+X,?_⟩ + intro z + dsimp only + have hr : weight (entryResidualParameters z) ≤ p.eval (weight z) := + (Nat.le_add_left _ _).trans (hp z) + have ha : weight (canonicalCountInput (entryResidualParameters z)) ≤ + q.eval (p.eval (weight z)) := + (Nat.le_add_left _ _).trans ((hq _).trans (polynomial_eval_monotone q hr)) + have hf := (weight_fst (canonicalCountInput (entryResidualParameters z))).trans ha + change weight (canonicalCountInput (entryResidualParameters z)).1 ≤ + q.eval (p.eval (weight z)) at hf + simp only [eval_add,eval_comp,eval_X] + change (4*((canonicalCountInput (entryResidualParameters z)).1).2.1^8)^ + tabulationDimension (canonicalCountInput (entryResidualParameters z)).1+ + gridStateCount (completionEnumerationData (canonicalCountInput (entryResidualParameters z)).1.1)+ + ((entryResidualParameters z).2.1+(entryResidualParameters z).2.2+ + weight (canonicalCountInput (entryResidualParameters z)).1)+ + gridStateCount (completionEnumerationData (entryResidualParameters z).1)+ + weight (entryResidualParameters z)+(entryCacheParameters z).2+ + gridStateCount (z.1.2,2)+weight z ≤ _ + omega + +theorem matrixEntryMeasure_polynomial : ∃ p : Polynomial ℕ,∀ z, + matrixEntryMeasure z ≤ p.eval (matrixEntryBox z) := by + obtain ⟨p,hp⟩ := polynomial_entryCacheParameters + obtain ⟨q,hq⟩ := completionWeightMeasure_polynomial + refine ⟨q+p+X,?_⟩ + intro z + let M := matrixEntryBox z + have hz : weight z ≤ M := by unfold M matrixEntryBox; omega + have hw : weight (entryCacheParameters z) ≤ p.eval M := + (Nat.le_add_left _ _).trans ((hp z).trans (polynomial_eval_monotone p hz)) + have hc : completionBoxMeasure (residualParameters (entryCacheParameters z).1) ≤ M := by + unfold M matrixEntryBox; omega + have hq' : completionWeightMeasure (residualParameters (entryCacheParameters z).1) ≤ + q.eval M := (hq _).trans (polynomial_eval_monotone q hc) + have hs : (entryCacheParameters z).2+gridStateCount (z.1.2,2)+weight z ≤ M := by + unfold M matrixEntryBox; omega + change (entryCacheParameters z).2+ + completionWeightMeasure (residualParameters (entryCacheParameters z).1)+ + weight (entryCacheParameters z)+gridStateCount (z.1.2,2)+weight z ≤ _ + change _ ≤ (q+p+X).eval M + simp only [eval_add,eval_X] + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalDrawTabulation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalDrawTabulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..538d12ded5a853e59a685f2a1a6561c74eff1735 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalDrawTabulation.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseSuppliedFallback + +namespace OAI + +/-! # Exact dense counts after computed maximal-margin normalization -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical + +def canonicalCountInput (z : CanonicalParameters) : SuppliedTabulation := + ((swapMargins (marginIndices z.1,z.1),z.2), + swapMatrix (marginIndices z.1,GreedyFeasibleTable.listMatrix z.1.1 z.1.2)) + +def canonicalCountInputRealizer : Realizer canonicalCountInput := by + let source : Realizer (fun z : CanonicalParameters => z.1) := first + let indices := composition source marginIndicesRealizer + let margins := composition (pair indices source) swapMarginsRealizer + let fallback := composition source GreedyFeasibleTable.tableRealizer + let precision : Realizer (fun z : CanonicalParameters => z.2) := second + let result := pair (pair margins precision) + (composition (pair indices fallback) swapMatrixRealizer) + exact result + +lemma polynomial_canonicalCountInput : PolynomialTime canonicalCountInputRealizer := by + unfold canonicalCountInputRealizer + exact polynomial_pair + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_marginIndices) polynomial_first) + polynomial_swapMargins) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_marginIndices) + (polynomial_composition polynomial_first GreedyFeasibleTable.polynomial_table)) + polynomial_swapMatrix) + +attribute [local irreducible] canonicalCountInputRealizer suppliedDrawCountsRealizer + +def canonicalDrawCounts : CanonicalParameters → List ℕ := + suppliedDrawCounts ∘ canonicalCountInput + +def canonicalDrawCountsRealizer : Realizer canonicalDrawCounts := by + let result := composition (f := canonicalCountInput) (g := suppliedDrawCounts) + canonicalCountInputRealizer suppliedDrawCountsRealizer + exact result + +def canonicalTabulationMeasure (z : CanonicalParameters) : ℕ := + suppliedTabulationMeasure (canonicalCountInput z)+weight z + +section +attribute [local irreducible] canonicalCountInput suppliedDrawCounts + +theorem work_canonicalDrawCounts : + WorkBound (f := canonicalDrawCounts) canonicalDrawCountsRealizer canonicalTabulationMeasure := by + obtain ⟨p,hp⟩ := polynomial_canonicalCountInput + obtain ⟨q,hq⟩ := work_suppliedDrawCounts + refine ⟨p+q,fun z => ?_⟩ + have h1 := (hp z).trans (polynomial_eval_monotone p + (show weight z≤canonicalTabulationMeasure z from Nat.le_add_left _ _)) + have h2 := (hq (canonicalCountInput z)).trans (polynomial_eval_monotone q + (show suppliedTabulationMeasure (canonicalCountInput z)≤canonicalTabulationMeasure z by + exact Nat.le_add_right _ _)) + dsimp only at h1 h2 + simp only [Polynomial.eval_add] + change canonicalCountInputRealizer.cost z+ + suppliedDrawCountsRealizer.cost (canonicalCountInput z)+ + weight (suppliedDrawCounts (canonicalCountInput z))≤_ + omega +end + +/-- The lookup index uses exactly the same two swaps as the sampler. -/ +def canonicalTableIndex (z : CanonicalParameters×MatrixCode) : ℕ := + tableIndex ((canonicalCountInput z.1).1.1,swapMatrix (marginIndices z.1.1,z.2)) + +def canonicalTableIndexRealizer : Realizer canonicalTableIndex := by + let source : Realizer (fun z : CanonicalParameters×MatrixCode => z.1) := first + let normalized := composition source canonicalCountInputRealizer + let margins := composition (composition normalized first) first + let originals : Realizer (fun z : CanonicalParameters×MatrixCode => z.1.1) := + composition first first + let indices := composition originals marginIndicesRealizer + let query := composition (pair indices second) swapMatrixRealizer + exact composition (pair margins query) tableIndexRealizer + +lemma polynomial_canonicalTableIndex : PolynomialTime canonicalTableIndexRealizer := by + unfold canonicalTableIndexRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_canonicalCountInput) + polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_marginIndices) polynomial_second) polynomial_swapMatrix)) polynomial_tableIndex + +lemma canonicalCountInput_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) (d h : ℕ) : + canonicalCountInput ((marginCode R,marginCode P),(d,h))= + (((marginCode (normalizedMargin R),marginCode (normalizedMargin P)),(d,h)), + tableOutput (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P (canonicalFallback R P htotal))) := by + unfold canonicalCountInput swapMargins marginIndices + rw [←marginPosition_val,←marginPosition_val,marginCode_swap,marginCode_swap, + ←canonicalFallback_output R P htotal,tableOutput_swap] + rfl + +lemma canonicalTableIndex_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) (d h : ℕ) (X : Table R P) : + canonicalTableIndex (((marginCode R,marginCode P),(d,h)),tableOutput X)= + (IndexedTableLaw.index (normalizedMargin R) (normalizedMargin P) + (le_refl (∑ i,normalizedMargin R i)) + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P X)).val := by + unfold canonicalTableIndex + rw [canonicalCountInput_code R P htotal] + simp only [marginIndices,←marginPosition_val] + rw [tableOutput_swap] + exact tableIndex_actual (normalizedMargin R) (normalizedMargin P) _ + +/-- The cached numerator is the count at the transported table, including +all fallback words of the actual normalized dense program. -/ +theorem canonicalDrawCounts_at {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (X : Table R P) : + (canonicalDrawCounts ((marginCode R,marginCode P),(d,h))).getD + (canonicalTableIndex (((marginCode R,marginCode P),(d,h)),tableOutput X)) 0= + (denseDrawCounts (normalizedMargin R) (normalizedMargin P) d hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) + finProdFinEquiv (by rw [normalizedMargin_total,normalizedMargin_total]; exact htotal) h + (canonicalOrigin (m*n) d (by omega)) + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P (canonicalFallback R P htotal))).count + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P X) := by + dsimp only [canonicalDrawCounts,Function.comp_apply] + rw [canonicalCountInput_code R P htotal,canonicalTableIndex_code R P htotal] + have he := suppliedDrawCounts_at (normalizedMargin R) (normalizedMargin P) hd hq + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) + (by rw [normalizedMargin_total,normalizedMargin_total]; exact htotal) h + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P (canonicalFallback R P htotal)) + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P X) + have hi := tableIndex_actual (normalizedMargin R) (normalizedMargin P) + (tableReindex (indexPermutation (marginPosition R)) + (indexPermutation (marginPosition P)) R P X) + dsimp only [normalizedMargin] at he hi ⊢ + rw [hi] at he + exact he + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalIntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalIntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3a316b361a7d6ddf7a3deafae76a075afbd8433 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CanonicalIntegerLaw.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CanonicalDrawTabulation +import OAI.Combinatorics.ContingencyTables.Transport.IntegerEquivLaw + +namespace OAI + +/-! # The exact finite integer law of the normalized Boolean sampler -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits ResidualMixture FirstSuccess +open scoped BigOperators Classical +noncomputable section + +variable {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) +variable (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) +variable (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + +def canonicalCounts : IntegerLaw (Table R P) (2^normalizedDrawBits R P d h) := + let E : Table R P ≃ Table (normalizedMargin R) (normalizedMargin P) := + tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P + (denseDrawCounts (normalizedMargin R) (normalizedMargin P) d hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) finProdFinEquiv + (by rw [normalizedMargin_total,normalizedMargin_total]; exact htotal) h + (canonicalOrigin (m*n) d (by omega)) (E (canonicalFallback R P htotal))).equiv E.symm + +theorem canonicalCounts_law : + (canonicalCounts R P hd hR hP htotal h).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (normalizedDrawBits R P d h) → Bool)) + (normalizedBooleanDraw R P hd hR hP htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal)) := by + let E : Table R P ≃ Table (normalizedMargin R) (normalizedMargin P) := + tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P + let a := canonicalOrigin (m*n) d (show 0 E.symm (draw bits)) + exact (IntegerLaw.toRational_equiv p E.symm (by positivity)).trans + ((congrArg (equivLaw E.symm) hp).trans (mapLaw_equiv_output E.symm _ draw).symm) + +theorem canonicalCounts_computed (hq : m*n≤d) (X : Table R P) : + (canonicalDrawCounts ((marginCode R,marginCode P),(d,h))).getD + (canonicalTableIndex (((marginCode R,marginCode P),(d,h)),tableOutput X)) 0= + (canonicalCounts R P hd hR hP htotal h).count X := + canonicalDrawCounts_at R P hd hq hR hP htotal h X + +/-- A reserved word contributes a power of two for its unused suffix. -/ +def paddedCanonicalCounts (N : ℕ) (hN : normalizedDrawBits R P d h≤N) : + IntegerLaw (Table R P) (2^N) := + ((canonicalCounts R P hd hR hP htotal h).scale + (2^(N-normalizedDrawBits R P d h))).rebase (by rw [←pow_add,Nat.add_sub_of_le hN]) + +theorem paddedCanonicalCounts_law (N : ℕ) (hN : normalizedDrawBits R P d h≤N) : + (paddedCanonicalCounts R P hd hR hP htotal h N hN).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin N → Bool)) + (fun bits => normalizedBooleanDraw R P hd hR hP htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal) + (prefixWord hN bits)) := by + unfold paddedCanonicalCounts + rw [IntegerLaw.toRational_rebase,IntegerLaw.toRational_scale,canonicalCounts_law] + exact (padded_draw_law hN _).symm + all_goals positivity + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ChoiceContextEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ChoiceContextEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa6f7a559e90884d74db02d433f9b3dd237089be --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ChoiceContextEnumeration.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextWeightedEnumeration +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPrefixEnergies +import OAI.Combinatorics.ContingencyTables.Transport.FiniteChoiceFibres + +namespace OAI + +/-! # Literal finite choice fibres equal the transport child sums -/ + +namespace ContingencyTables.SmallContextEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres +open LargePairEnumeration BalancedEnumeration BalancedFamily +open FirstPaperContextTransport FirstPaperPhysicalMarginal ExcessContextProfiles SmallGraphProfiles +open FiniteExposureVariance +open IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +def rawChoice (small : I → J → Bool) (U : ℕ) (x : Cells small → Fin (U+1)) : + SmallProfile small := fun p => if p.2 then U-(x p.1).val else (x p.1).val + +def earlierChoices (small : I → J → Bool) (s : I×J) (U : ℕ) + (x : Cells small → Fin (U+1)) : Earlier small s → Fin (U+1) := fun a => x a.val + +omit [Fintype I] [Fintype J] in +lemma earlierChoices_eq_iff (small : I → J → Bool) (s : I×J) (U : ℕ) + (x : Cells small → Fin (U+1)) (τ : Earlier small s → Fin (U+1)) : + earlierChoices small s U x=τ ↔ ∀ a : Earlier small s,x a.val=τ a := + funext_iff + +def ChoiceContext (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) := + {x : Cells small → Fin (U+1) // earlierChoices small s U x=τ ∧ x ⟨s,hs⟩=k} + +noncomputable instance choiceContextFintype (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) : + Fintype (ChoiceContext small s hs U τ k) := by unfold ChoiceContext; infer_instance + +noncomputable def choiceContextEquiv (small : I → J → Bool) (s : I×J) + (hs : small s.1 s.2=true) (U : ℕ) (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) : + (Later small s → Fin (U+1)) ≃ ChoiceContext small s hs U τ k where + toFun y := ⟨splitChoices small s hs U τ k y,funext (splitChoices_prefix small s hs U τ k y), + splitChoices_special small s hs U τ k y⟩ + invFun x := fun a => x.val a.val + left_inv y := by funext a; exact splitChoices_later small s hs U τ k y a + right_inv x := by + apply Subtype.ext + funext a + obtain ⟨v,rfl⟩ := (cellSplitEquiv small s hs).surjective a + rcases v with p|(_|t) + · exact (splitChoices_prefix small s hs U τ k _ p).trans (congrFun x.property.1 p).symm + · exact (splitChoices_special small s hs U τ k _).trans x.property.2.symm + · exact splitChoices_later small s hs U τ k _ t + +lemma choice_fibre_sum (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (U : ℕ) (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + (F : (Cells small → Fin (U+1)) → ℝ) : + (∑ x,fibreWeight (fibreWeight F (earlierChoices small s U) τ) (fun x => x ⟨s,hs⟩) k x)= + ∑ x : ChoiceContext small s hs U τ k,F x.val := by + exact double_fibre_sum F (earlierChoices small s U) (fun x => x ⟨s,hs⟩) τ k + +omit [Fintype I] [Fintype J] in +lemma prefixChoices_extension (small : I → J → Bool) (s : I×J) (U : ℕ) + (τ : Earlier small s → Fin (U+1)) : + prefixChoices small s (prefixExtension small s U τ) U (prefixExtension_bounded small s U τ)=τ := by + funext a + apply Fin.ext + exact prefixExtension_at small s U τ a + +/-- The child mass and every child moment are the actual finite fibre +sums of balanced physical choices, retaining all large completions. -/ +theorem eliminate_context_eq_choice_fibre (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) + (τ : Earlier small s → Fin (U+1)) (k : Fin (U+1)) + {n : ℕ} (e : Fin n ≃ Later small s) (F : SmallProfile small → ℝ) : + eliminate (widths (fun _ : Fin n => U)) + (fun p => F (assemble small s hs (prefixExtension small s U τ) U e p)) (childProfile U k.val)= + ∑ x,fibreWeight (fibreWeight (fun x => F (rawChoice small U x)) + (earlierChoices small s U) τ) (fun x => x ⟨s,hs⟩) k x := by + rw [eliminate_context_eq_weighted_sum small B s hs _ U hB + (prefixExtension_bounded small s U τ),choice_fibre_sum] + have he := Fintype.sum_equiv + (balancedContextEquiv small B s hs (prefixExtension small s U τ) U hB + (prefixExtension_bounded small s U τ) k) + (fun y => F (rawChoice small U (splitChoices small s hs U τ k y))) + (fun z => F (naturalProfile z.val)) (fun y => by + change F (rawChoice small U (splitChoices small s hs U τ k y))= + F (rawChoice small U (splitChoices small s hs U + (prefixChoices small s (prefixExtension small s U τ) U (prefixExtension_bounded small s U τ)) k y)) + rw [prefixChoices_extension]) + have hc := Fintype.sum_equiv (choiceContextEquiv small s hs U τ k) + (fun y => F (rawChoice small U (splitChoices small s hs U τ k y))) + (fun x => F (rawChoice small U x.val)) (fun _ => rfl) + exact he.symm.trans hc + +end ContingencyTables.SmallContextEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ComplementChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComplementChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..0eeab347f301b0281eba808c58c67598e03a93a2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComplementChain.lean @@ -0,0 +1,296 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ObservableBounds + +namespace OAI + +/-! +# The manuscript's original omission coordinates + +Complementation reverses defect labels and their multipliers. We prove the +actual chain energy, conditional projection, and variance identities before +transferring the variance and observable inequalities back to the original +factorial lift f. The final theorems assume its omission property. +-/ + +namespace ContingencyTables.ComplementChain + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction DegreeCompletion PairedComplement ObservableVariance ObservableBounds + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +omit [Fintype Γ] [DecidableEq Γ] in +lemma plain_complement (gs : List (Γ × Γ)) (S : Set Γ) : + PlainState gs Sᶜ ↔ PlainState gs S := by + unfold PlainState PairSingle + simp only [Set.mem_compl_iff] + constructor <;> intro h p hp <;> have hh := h p hp <;> tauto + +omit [Fintype Γ] [DecidableEq Γ] in +lemma defect_complement (gs : List (Γ × Γ)) (p r : Γ × Γ) (S : Set Γ) : + DefectState gs p r Sᶜ ↔ DefectState gs r p S := by + unfold DefectState PairEmpty PairFull PairSingle + simp only [Set.mem_compl_iff, not_not] + constructor + · rintro ⟨hp,hr,hpr,hep,hfr,hs⟩ + refine ⟨hr,hp,hpr.symm,hfr,hep,?_⟩ + intro t ht htr htp + have h := hs t ht htp htr + tauto + · rintro ⟨hr,hp,hrp,her,hfp,hs⟩ + refine ⟨hp,hr,hrp.symm,hfp,her,?_⟩ + intro t ht htp htr + have h := hs t ht htr htp + tauto + +omit [Fintype Γ] [DecidableEq Γ] in +lemma state_complement (gs : List (Γ × Γ)) (S : Set Γ) : + ChainState gs Sᶜ ↔ ChainState gs S := by + unfold ChainState + rw [plain_complement] + constructor + · rintro (h | ⟨p,r,h⟩) + · exact Or.inl h + · exact Or.inr ⟨r,p,(defect_complement gs p r S).mp h⟩ + · rintro (h | ⟨p,r,h⟩) + · exact Or.inl h + · exact Or.inr ⟨r,p,(defect_complement gs r p S).mpr h⟩ + +omit [Fintype Γ] [DecidableEq Γ] in +lemma adjacent_complement (S T : Set Γ) : ExchangeAdjacent Sᶜ Tᶜ ↔ ExchangeAdjacent S T := by + have hf (S T : Set Γ) (h : ExchangeAdjacent S T) : ExchangeAdjacent Sᶜ Tᶜ := by + obtain ⟨A,a,b,hab,ha,hb,rfl,rfl⟩ := h + let B := (insert a (insert b A))ᶜ + refine ⟨B,b,a,hab.symm,?_,?_,?_,?_⟩ + · simp [B] + · simp [B] + · ext x + simp only [B, Set.mem_compl_iff, Set.mem_insert_iff] + constructor + · intro hx + by_cases hxb : x = b + · exact Or.inl hxb + · exact Or.inr (by tauto) + · intro hx + rcases hx with rfl | hx + · exact not_or.mpr ⟨hab.symm, hb⟩ + · tauto + · ext x + simp only [B, Set.mem_compl_iff, Set.mem_insert_iff] + constructor + · intro hx + by_cases hxa : x = a + · exact Or.inl hxa + · exact Or.inr (by tauto) + · intro hx + rcases hx with rfl | hx + · exact not_or.mpr ⟨hab, ha⟩ + · tauto + exact ⟨fun h => by simpa using hf Sᶜ Tᶜ h, hf S T⟩ + +omit [Fintype Γ] [DecidableEq Γ] in +def complementEquiv : Set Γ ≃ Set Γ where + toFun := compl + invFun := compl + left_inv := compl_compl + right_inv := compl_compl + +omit [Fintype Γ] [DecidableEq Γ] in +def reverseMultiplier (w : (Γ × Γ) → (Γ × Γ) → ℝ) : (Γ × Γ) → (Γ × Γ) → ℝ := + fun p r => w r p + +lemma multiplier_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (S : Set Γ) : + chainMultiplier gs (reverseMultiplier w) Sᶜ = chainMultiplier gs w S := by + by_cases he : ∃ p r, DefectState gs p r S + · obtain ⟨p,r,h⟩ := he + rw [chainMultiplier_defect gs _ Sᶜ ((defect_complement gs r p S).mpr h), + chainMultiplier_defect gs w S h] + rfl + · have hec : ¬ ∃ p r, DefectState gs p r Sᶜ := by + rintro ⟨p,r,h⟩ + exact he ⟨r,p,(defect_complement gs p r S).mp h⟩ + simp only [chainMultiplier, dite_eq_right he, dite_eq_right hec] + +lemma weight_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (S : Set Γ) : + chainWeight gs (reverseMultiplier w) (complementWeight f) Sᶜ = chainWeight gs w f S := by + simp only [chainWeight, multiplier_complement, complementWeight, compl_compl] + +lemma chain_sum_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f J : Set Γ → ℝ) : + (∑ S ∈ chainStates gs, chainWeight gs (reverseMultiplier w) (complementWeight f) S * J S) = + ∑ S ∈ chainStates gs, chainWeight gs w f S * J Sᶜ := by + simp only [chainStates, Finset.sum_filter] + apply Fintype.sum_equiv complementEquiv + intro S + change (if ChainState gs S then _ else 0) = (if ChainState gs Sᶜ then _ else 0) + rw [state_complement] + by_cases h : ChainState gs S + · simp only [ite_eq_left h] + have hw := weight_complement gs w f Sᶜ + simp only [compl_compl] at hw + rw [hw] + simp only [complementEquiv, Equiv.coe_fn_mk, compl_compl] + · simp only [ite_eq_right h] + +lemma total_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f : Set Γ → ℝ) : + chainTotal gs (reverseMultiplier w) (complementWeight f) = chainTotal gs w f := by + simpa only [chainTotal, mul_one] using chain_sum_complement gs w f (fun _ => 1) + +lemma mean_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : + chainMean gs (reverseMultiplier w) (complementWeight f) (complementWeight H) = chainMean gs w f H := by + unfold chainMean + rw [total_complement, chain_sum_complement] + simp only [complementWeight, compl_compl] + +lemma variance_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : + chainVariance gs (reverseMultiplier w) (complementWeight f) (complementWeight H) = + chainVariance gs w f H := by + unfold chainVariance + rw [total_complement, mean_complement, chain_sum_complement] + simp only [complementWeight, compl_compl] + +lemma conductance_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (ST : Set Γ × Set Γ) : + chainConductance gs (reverseMultiplier w) (complementWeight f) (ST.1ᶜ,ST.2ᶜ) = + chainConductance gs w f ST := by + simp only [chainConductance, multiplier_complement, complementWeight, compl_compl] + +lemma energy_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : + restrictedEnergy (chainEdges gs) (chainConductance gs (reverseMultiplier w) (complementWeight f)) + (complementWeight H) ∅ ∅ = + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + have hr (ST : Set Γ × Set Γ) : EdgeRespects ∅ ∅ ST := by simp [EdgeRespects, Respects] + unfold restrictedEnergy + simp only [hr, ite_true, chainEdges, Finset.sum_filter] + congr 1 + let E : (Set Γ × Set Γ) ≃ (Set Γ × Set Γ) := Equiv.prodCongr complementEquiv complementEquiv + apply Fintype.sum_equiv E + intro ST + change (if ChainState gs ST.1 ∧ ChainState gs ST.2 ∧ ExchangeAdjacent ST.1 ST.2 then _ else 0) = + (if ChainState gs ST.1ᶜ ∧ ChainState gs ST.2ᶜ ∧ ExchangeAdjacent ST.1ᶜ ST.2ᶜ then _ else 0) + rw [state_complement, state_complement, adjacent_complement] + by_cases h : ChainState gs ST.1 ∧ ChainState gs ST.2 ∧ ExchangeAdjacent ST.1 ST.2 + · simp only [ite_eq_left h] + have hc := conductance_complement gs w f (ST.1ᶜ,ST.2ᶜ) + simp only [compl_compl] at hc + rw [hc] + rfl + · simp only [ite_eq_right h] + +lemma dirichlet_complement (gs : List (Γ × Γ)) (w : (Γ × Γ) → (Γ × Γ) → ℝ) (f H : Set Γ → ℝ) : + chainDirichlet gs (reverseMultiplier w) (complementWeight f) (complementWeight H) = + chainDirichlet gs w f H := by + unfold chainDirichlet + rw [total_complement, energy_complement] + +lemma plain_mass_complement (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) : + slotTotal gs (complementWeight f) ∅ = slotTotal gs f ∅ := by + exact slotTotal_complement gs f ∅ ∅ (by simp) (by simpa using hgs) (by simpa using hcover) + +lemma defect_mass_complement (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f : Set Γ → ℝ) + (p r : Γ × Γ) (hp : p ∈ gs) (hr : r ∈ gs) (hpr : p ≠ r) : + slotDefect gs (complementWeight f) ∅ p r = slotDefect gs f ∅ r p := by + exact slotDefect_complement gs f ∅ ∅ (by simp) (by simpa using hgs) (by simpa using hcover) p r hp hr hpr + +lemma projection_complement (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) : + observableProjection gs (complementWeight f) (complementWeight H) = + complementWeight (observableProjection gs f H) := by + have hmul : (fun S => complementWeight f S * complementWeight H S) = + complementWeight (fun S => f S * H S) := rfl + funext S + change observableProjection gs (complementWeight f) (complementWeight H) S = + observableProjection gs f H Sᶜ + by_cases he : ∃ p r, DefectState gs p r S + · obtain ⟨p,r,h⟩ := he + have hc : DefectState gs r p Sᶜ := (defect_complement gs r p S).mpr h + rw [observableProjection_defect gs _ _ S h, observableProjection_defect gs f H Sᶜ hc] + unfold defectMean + rw [hmul, defect_mass_complement gs hgs hcover _ p r h.1 h.2.1 h.2.2.1, + defect_mass_complement gs hgs hcover f p r h.1 h.2.1 h.2.2.1] + · have hec : ¬ ∃ p r, DefectState gs p r Sᶜ := by + rintro ⟨p,r,h⟩ + exact he ⟨r,p,(defect_complement gs p r S).mp h⟩ + simp only [observableProjection, dite_eq_right he, dite_eq_right hec, complementWeight] + +lemma slotVariance_complement (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (f H : Set Γ → ℝ) : + slotVariance gs (complementWeight f) (complementWeight H) ∅ = slotVariance gs f H ∅ := by + unfold slotVariance + change slotTotal gs (complementWeight (fun S => f S*(H S)^2)) ∅ - + (slotTotal gs (complementWeight (fun S => f S*H S)) ∅)^2/slotTotal gs (complementWeight f) ∅ = _ + rw [plain_mass_complement gs hgs hcover, plain_mass_complement gs hgs hcover, + plain_mass_complement gs hgs hcover] + +/-- The actual manuscript variance theorem in original omission coordinates. -/ +theorem omission_twoLift_transversal_variance (gs : List (Γ × Γ)) (f g H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (q : ℝ) (hq : 0 ≤ q) + (hf : DegreePositive f gs.length) (hg : DegreePositive g gs.length) + (hsigf : OmissionProperty f gs.length) (hsigg : AdditionProperty g gs.length) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) : + slotVariance gs f H ∅ ≤ (gs.length : ℝ)*(1+8*(gs.length : ℝ)*q^2)* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + have hcard := slots_ground_card gs hgs hcover + have hhalf : Fintype.card Γ - gs.length = gs.length := by omega + have hfc : DegreePositive (complementWeight f) gs.length := by + simpa only [hhalf] using complement_degreePositive f gs.length (by omega) hf + have hgc : DegreePositive (complementWeight g) gs.length := by + simpa only [hhalf] using complement_degreePositive g gs.length (by omega) hg + have hsf : AdditionProperty (complementWeight f) gs.length := by + simpa only [OmissionProperty, hhalf] using hsigf + have hsg : OmissionProperty (complementWeight g) gs.length := by + have hcc : complementWeight (complementWeight g) = g := by funext S; simp [complementWeight] + simpa only [OmissionProperty, hhalf, hcc] using hsigg + have hgood' : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs (complementWeight f) ∅/(4*slotDefect gs (complementWeight f) ∅ p r) ≤ reverseMultiplier w p r := by + intro p hp r hr hpr + rw [plain_mass_complement gs hgs hcover, defect_mass_complement gs hgs hcover f p r hp hr hpr] + exact hgood r hr p hp hpr.symm + have ht := validDegree_twoLift_transversal_variance gs (complementWeight f) (complementWeight g) + (complementWeight H) (reverseMultiplier w) q hq hfc hgc hsf hsg hgs hcover + (fun p r => hw r p) hgood' + (fun S hS => hagree Sᶜ ((plain_complement gs S).mpr hS)) + (fun S hS => hcompare Sᶜ ((state_complement gs S).mpr hS)) + rwa [slotVariance_complement gs hgs hcover f H, energy_complement gs w f H] at ht + +/-- The paper's observable Poincaré theorem for the literal first factorial +lift, assuming its omission property only at the actual subset degree. -/ +theorem omission_observable_poincare (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) + (hf : DegreePositive f gs.length) (hsig : OmissionProperty f gs.length) + (q : ℝ) (hq : 1 ≤ q) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + chainVariance gs w f (observableProjection gs f H) ≤ + observableConstant gs.length q * chainDirichlet gs w f H := by + have hcard := slots_ground_card gs hgs hcover + have hhalf : Fintype.card Γ - gs.length = gs.length := by omega + have hfc : DegreePositive (complementWeight f) gs.length := by + simpa only [hhalf] using complement_degreePositive f gs.length (by omega) hf + have hsf : AdditionProperty (complementWeight f) gs.length := by + simpa only [OmissionProperty, hhalf] using hsig + have hl : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs (complementWeight f) ∅/(4*slotDefect gs (complementWeight f) ∅ p r) ≤ reverseMultiplier w p r := by + intro p hp r hr hpr + rw [plain_mass_complement gs hgs hcover, defect_mass_complement gs hgs hcover f p r hp hr hpr] + exact hlower r hr p hp hpr.symm + have hu : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + reverseMultiplier w p r ≤ 4*slotTotal gs (complementWeight f) ∅/slotDefect gs (complementWeight f) ∅ p r := by + intro p hp r hr hpr + rw [plain_mass_complement gs hgs hcover, defect_mass_complement gs hgs hcover f p r hp hr hpr] + exact hupper r hr p hp hpr.symm + have ht := validDegree_observable_poincare gs hgs hne hcover (reverseMultiplier w) + (fun p r => hw r p) (complementWeight f) (complementWeight H) hfc hsf q hq hl hu + rwa [projection_complement gs hgs hcover, variance_complement, dirichlet_complement] at ht + +end ContingencyTables.ComplementChain + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionChainFlow.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionChainFlow.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fbdc9b9966721dd6d0453fba53a53422a32fc3a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionChainFlow.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionChain + +namespace OAI + +/-! # Exact edge flow of the completion-translation chain -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open CommonBasesFPRAS + +variable {X I J : Type*} [Fintype X] [Nonempty X] [Fintype I] [Fintype J] + +omit [Nonempty X] in +lemma completionMove_flow (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (β : ℝ) (x y : X) : + ((blockCount R P x:ℝ)/MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)))* + completionMove R P Adj β x y = + if Adj x y then β*(acceptedCount R P x y:ℝ)/ + MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)) else 0 := by + have hx : (blockCount R P x:ℝ)≠0 := ne_of_gt (by exact_mod_cast blockCount_pos R P htotal x) + unfold completionMove + split_ifs + · exact div_mul_div_cancel₀' hx _ _ + · exact mul_zero _ + +/-- The flow formula includes the holding terms: those contribute zero +energy. The numerator counts literal acceptable completion translations. -/ +theorem completionChain_energy (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (hsym : ∀ x y,Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x,(Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D:ℝ)*β ≤ 1/2) (H : X → ℝ) : + (completionChain R P htotal Adj hsym β hβ D hdegree hproposal).energy H= + (∑ x,∑ y,if Adj x y then + β*(acceptedCount R P x y:ℝ)*(H x-H y)^2 else 0)/ + (2*MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ))) := by + unfold completionChain + rw [FiniteChain.ofMoves_energy] + simp_rw [completionMove_flow R P htotal Adj β] + have hterm (x y : X) : + (if Adj x y then β*(acceptedCount R P x y:ℝ)/ + MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)) else 0)*(H x-H y)^2 = + (if Adj x y then β*(acceptedCount R P x y:ℝ)*(H x-H y)^2 else 0)/ + MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)) := by + split_ifs <;> ring + simp_rw [hterm,← Finset.sum_div] + ring + +omit [Fintype X] [Nonempty X] in +/-- A half-acceptance estimate yields the min-weight comparison on every +actual edge, with no request for completion-count evaluation. -/ +lemma completionMove_lower (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) (x y : X) + (hxy : Adj x y) + (haccept : (blockCount R P x:ℝ)/2 ≤ acceptedCount R P x y) : + β/2*min 1 ((blockCount R P y:ℝ)/blockCount R P x) ≤ completionMove R P Adj β x y := by + have hx : (0:ℝ) (a.val i j).val + +omit [Fintype I] [Fintype J] in +lemma assignment_supported {small : I → J → Bool} {B : I → J → ℕ} (a : Assignment small B) : + Supported small (assignmentMatrix a) := a.property + +omit [Fintype I] [Fintype J] in +lemma assignment_bounded {small : I → J → Bool} {B : I → J → ℕ} (a : Assignment small B) (i : I) (j : J) : + assignmentMatrix a i j ≤ B i j := Nat.le_of_lt_succ (a.val i j).isLt + +noncomputable def fullPenalty (small : I → J → Bool) (B X Y A : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : ℝ := + penalty cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L)) + viewSlope (smallOffset small B r c) viewSlope (profile small B X Y A) + +def ZeroAssignments (small : I → J → Bool) (B X Y : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) := + {a : Assignment small B // fullPenalty small B X Y (assignmentMatrix a) r c L=0} + +noncomputable instance zeroAssignmentsFintype (small : I → J → Bool) (B X Y : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) : Fintype (ZeroAssignments small B X Y r c L) := by + unfold ZeroAssignments + infer_instance + +/-- The total padded residual mass is at most the original mass plus +one padding unit L for each large cell. -/ +theorem padded_total_le (small : I → J → Bool) (X : I → J → ℕ) (r : I → ℕ) (L : ℕ) : + (∑ i, (r i-smallRow small X i+rowLargeCount small i*L)) ≤ + (∑ i, r i)+(∑ i, rowLargeCount small i)*L := by + rw [Finset.sum_add_distrib,Finset.sum_mul] + exact Nat.add_le_add_right (Finset.sum_le_sum (fun i _ => Nat.sub_le _ _)) _ + +/-- This is the exact reason the paper's formal large capacity excludes +no padded completion. No large-range enumeration is used. -/ +theorem capacity_excludes_none (small : I → J → Bool) (B X : I → J → ℕ) + (r : I → ℕ) (L d C : ℕ) (hcount : (∑ i, rowLargeCount small i) ≤ d) + (hC : (∑ i, r i)+d*L ≤ C) (hB : ∀ i j, small i j=false → B i j=C) : + ∀ i j, small i j=false → + (∑ k, (r k-smallRow small X k+rowLargeCount small k*L)) ≤ B i j := by + intro i j hij + rw [hB i j hij] + exact (padded_total_le small X r L).trans + ((Nat.add_le_add_left (Nat.mul_le_mul_right L hcount) _).trans hC) + +theorem large_count_le_dimension (small : I → J → Bool) : + (∑ i, rowLargeCount small i) ≤ Fintype.card I*Fintype.card J := by + calc + _ ≤ ∑ _ : I, Fintype.card J := by + apply Finset.sum_le_sum + intro i _ + unfold rowLargeCount + calc + _ ≤ ∑ _ : J, (1:ℕ) := by + apply Finset.sum_le_sum + intro j _ + split_ifs <;> omega + _ = Fintype.card J := by simp + _ = _ := by simp + +noncomputable def paperCapacity (small : I → J → Bool) (r : I → ℕ) (d L U : ℕ) : I → J → ℕ := + fun i j => if small i j then U else (∑ k, r k)+d*L+U+2 + +/-- For the manuscript's exact C=N+dL+U+2, the capacity hypothesis of +the count equivalence follows just from the dimension allowance. -/ +theorem paper_capacity_excludes_none (small : I → J → Bool) (X : I → J → ℕ) + (r : I → ℕ) (d L U : ℕ) (hd : Fintype.card I*Fintype.card J ≤ d) : + ∀ i j, small i j=false → + (∑ k, (r k-smallRow small X k+rowLargeCount small k*L)) ≤ paperCapacity small r d L U i j := by + apply capacity_excludes_none small (paperCapacity small r d L U) X r L d + ((∑ k, r k)+d*L+U+2) ((large_count_le_dimension small).trans hd) + · omega + · intro i j hij + simp [paperCapacity,hij] + +def firstPaperSmall (r : I → ℕ) (c : J → ℕ) (U : ℕ) (i : I) (j : J) : Bool := + decide (r i r i-smallRow small X i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B Y j+columnLargeCount small j*L) where + toFun a := ⟨⟨assignmentMatrix a.val, + ((zero_penalty_iff_padded_completion small B X Y (assignmentMatrix a.val) r c L + (assignment_supported a.val) hX hY (fun i j _ => assignment_bounded a.val i j)).mp a.property).2⟩, + assignment_supported a.val⟩ + invFun A := by + have hcap : ∀ i j, A.val.val i j ≤ B i j := by + intro i j + cases hs : small i j + · exact (entry_le_total A.val.property i j).trans (hB i j hs) + · rw [A.property i j hs] + exact Nat.zero_le _ + let a : Assignment small B := ⟨fun i j => ⟨A.val.val i j,Nat.lt_succ_of_le (hcap i j)⟩, + A.property⟩ + refine ⟨a,?_⟩ + exact (zero_penalty_iff_padded_completion small B X Y A.val.val r c L A.property hX hY + (fun i j _ => hcap i j)).mpr ⟨hres,A.val.property⟩ + left_inv a := by + apply Subtype.ext + apply Subtype.ext + funext i j + apply Fin.ext + rfl + right_inv A := by + apply Subtype.ext + apply Subtype.ext + rfl + +/-- The finite hard marginal is exactly the padded completion count; +if an original residual is negative every zero-penalty term vanishes. -/ +theorem hard_count_eq (small : I → J → Bool) (B X Y : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (hX : ∀ i j, small i j=true → X i j ≤ B i j) + (hY : ∀ i j, small i j=true → Y i j ≤ B i j) + (hB : ∀ i j, small i j=false → (∑ k, (r k-smallRow small X k+rowLargeCount small k*L)) ≤ B i j) : + (∑ a : Assignment small B, if fullPenalty small B X Y (assignmentMatrix a) r c L=0 then (1:ℝ) else 0) = + if OriginalResidualsNonnegative small B X Y r c then + (Fintype.card (LargeCompletion small (fun i => r i-smallRow small X i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B Y j+columnLargeCount small j*L)):ℝ) else 0 := by + by_cases hres : OriginalResidualsNonnegative small B X Y r c + · rw [ite_eq_left hres] + calc + _ = (Fintype.card (ZeroAssignments small B X Y r c L):ℝ) := by + rw [Finset.sum_boole,← Fintype.card_subtype] + exact congrArg (fun n : ℕ => (n:ℝ)) (Fintype.card_congr + (α := {a : Assignment small B // fullPenalty small B X Y (assignmentMatrix a) r c L=0}) + (β := ZeroAssignments small B X Y r c L) (Equiv.refl _)) + _ = _ := congrArg (fun n : ℕ => (n:ℝ)) + (Fintype.card_congr (completionEquiv small B X Y r c L hX hY hres hB)) + · rw [ite_eq_right hres] + apply Finset.sum_eq_zero + intro a _ + apply ite_eq_right + intro hz + exact hres ((zero_penalty_iff_padded_completion small B X Y (assignmentMatrix a) r c L + (assignment_supported a) hX hY (fun i j _ => assignment_bounded a i j)).mp hz).1 + +/-- The first manuscript's actual supported padded-completion weight, +with its dimension allowance, padding, threshold and formal capacity. -/ +noncomputable def firstPaperWeight (r : I → ℕ) (c : J → ℕ) (X Y : I → J → ℕ) : ℝ := + let d := dimensionAllowance (I := I) (J := J) + let L := d^12 + let U := d^20 + let small := firstPaperSmall r c U + let B := paperCapacity small r d L U + if OriginalResidualsNonnegative small B X Y r c then + (Fintype.card (LargeCompletion small (fun i => r i-smallRow small X i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B Y j+columnLargeCount small j*L)):ℝ) else 0 + +noncomputable def firstPaperHardSum (r : I → ℕ) (c : J → ℕ) (X Y : I → J → ℕ) : ℝ := + let d := dimensionAllowance (I := I) (J := J) + let L := d^12 + let U := d^20 + let small := firstPaperSmall r c U + let B := paperCapacity small r d L U + ∑ a : Assignment small B, if fullPenalty small B X Y (assignmentMatrix a) r c L=0 then 1 else 0 + +/-- This identifies the actual finite zero-penalty large-assignment sum +with the original supported completion count, on every small profile. -/ +theorem firstPaperHardSum_eq_weight (r : I → ℕ) (c : J → ℕ) (X Y : I → J → ℕ) + (hX : ∀ i j, firstPaperSmall r c (dimensionAllowance (I := I) (J := J)^20) i j=true → + X i j ≤ dimensionAllowance (I := I) (J := J)^20) + (hY : ∀ i j, firstPaperSmall r c (dimensionAllowance (I := I) (J := J)^20) i j=true → + Y i j ≤ dimensionAllowance (I := I) (J := J)^20) : + firstPaperHardSum r c X Y=firstPaperWeight r c X Y := by + apply hard_count_eq + · intro i j hij + simpa only [paperCapacity,hij,ite_true] using hX i j hij + · intro i j hij + simpa only [paperCapacity,hij,ite_true] using hY i j hij + · exact paper_capacity_excludes_none _ X r _ _ _ dimension_le_allowance + +end ContingencyTables.CompletionCounts + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionDecisionReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionDecisionReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d4865c52490bc8f1a0f9a6dfcae38980437cf8d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionDecisionReindex.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.ContingencyTables.Transport.StarReindex +import OAI.Combinatorics.ContingencyTables.Transport.CompletionStepApproximation +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits + +namespace OAI + +/-! # Reindexing the literal completion accept/reject decision -/ + +namespace ContingencyTables.CompletionTranslation +open FirstSuccess FairBits ResidualMixture +open scoped Classical + +variable {X I J I' J' : Type*} [Fintype X] [DecidableEq X] +variable [Fintype I] [Fintype J] [Fintype I'] [Fintype J'] + +omit [Fintype X] [DecidableEq X] in +theorem completionDecision_reindex + (eI : Option I' ≃ Option I) (eJ : Option J' ≃ Option J) + (hI : eI none=none) (hJ : eJ none=none) + (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (x : X) (proposal : Option X) (A : Table (R x) (P x)) : + completionDecision (fun x i => R x (eI i)) (fun x j => P x (eJ j)) x proposal + (tableReindex eI eJ (R x) (P x) A)=completionDecision R P x proposal A := by + cases proposal with + | none => rfl + | some y => + unfold completionDecision + dsimp only + have he := translated_nonnegative_reindex eI eJ hI hJ (R x) (R y) (P x) (P y) A + split_ifs with h₁ h₂ h₂ + · rfl + · exact False.elim (h₂ (he.mp h₁)) + · exact False.elim (h₁ (he.mpr h₂)) + · rfl + +theorem uniform_completionDecision_reindex + (eI : Option I' ≃ Option I) (eJ : Option J' ≃ Option J) + (hI : eI none=none) (hJ : eJ none=none) + (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (x : X) (proposal : Option X) + [Nonempty (Table (R x) (P x))] + [Nonempty (Table (fun i => R x (eI i)) (fun j => P x (eJ j)))] : + mapLaw (uniformLaw (α := Table (fun i => R x (eI i)) (fun j => P x (eJ j)))) + (completionDecision (fun x i => R x (eI i)) (fun x j => P x (eJ j)) x proposal)= + mapLaw (uniformLaw (α := Table (R x) (P x))) (completionDecision R P x proposal) := by + rw [←uniform_equiv (tableReindex eI eJ (R x) (P x)),map_equiv] + congr 1 + funext A + exact completionDecision_reindex eI eJ hI hJ R P x proposal A + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionEnergyComparison.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionEnergyComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..71bbcccae9cf2704bb15be6943966779c4d2dfcb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionEnergyComparison.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionChainFlow + +namespace OAI + +/-! # From literal acceptance counts to weighted graph energy -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open CommonBasesFPRAS + +variable {X I J : Type*} [Fintype X] [Nonempty X] [Fintype I] [Fintype J] + +/-- This is the actual chain energy comparison. The half-acceptance +premise is supplied by the proved reference-star small-entry estimate. -/ +theorem completionChain_energy_lower + (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (hsym : ∀ x y,Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x,(Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D:ℝ)*β ≤ 1/2) + (haccept : ∀ x y,Adj x y → (blockCount R P x:ℝ)/2 ≤ acceptedCount R P x y) + (H : X → ℝ) : + β/(2*MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)))* + ((∑ x,∑ y,if Adj x y then min (blockCount R P x:ℝ) (blockCount R P y:ℝ)* + (H x-H y)^2 else 0)/2) ≤ + (completionChain R P htotal Adj hsym β hβ D hdegree hproposal).energy H := by + let Z := MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)) + have hZ : 0 < Z := MetropolisChain.normalizer_pos _ + (fun z => by exact_mod_cast blockCount_pos R P htotal z) + have hterm (x y : X) : + β/2*(if Adj x y then min (blockCount R P x:ℝ) (blockCount R P y:ℝ)*(H x-H y)^2 else 0) ≤ + if Adj x y then β*(acceptedCount R P x y:ℝ)*(H x-H y)^2 else 0 := by + by_cases hxy : Adj x y + · rw [ite_eq_left hxy,ite_eq_left hxy] + have hm : min (blockCount R P x:ℝ) (blockCount R P y:ℝ)/2 ≤ acceptedCount R P x y := + (div_le_div_of_nonneg_right (min_le_left _ _) (by norm_num)).trans (haccept x y hxy) + have hs := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hm hβ) (sq_nonneg (H x-H y)) + convert hs using 1 + all_goals ring + · rw [ite_eq_right hxy,ite_eq_right hxy,mul_zero] + have hsum := Finset.sum_le_sum (fun x (_ : x ∈ (Finset.univ : Finset X)) => + Finset.sum_le_sum (fun y (_ : y ∈ (Finset.univ : Finset X)) => hterm x y)) + simp_rw [← Finset.mul_sum] at hsum + rw [completionChain_energy] + have hb := div_le_div_of_nonneg_right hsum (show 0 ≤ 2*Z by positivity) + convert hb using 1 + all_goals + dsimp only [Z] + ring + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreEquiv.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreEquiv.lean new file mode 100644 index 0000000000000000000000000000000000000000..af7dfb146260ca857ee55b34e62a1e0583fe6e56 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreEquiv.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalOriginalResiduals +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBlock +import OAI.Combinatorics.ContingencyTables.Transport.TableMarginTransport + +namespace OAI + +/-! +# Entry-preserving completion equivalences + +The finite dense draw is transported to the retained completion fibre by +an equivalence preserving every table entry. +-/ + +namespace ContingencyTables.PhysicalCompletionFibres + +open scoped BigOperators Classical +open LargePairEnumeration PhysicalLargeProfiles RowColumnPenalties +open FirstPaperPhysicalMarginal FirstPaperProfiles PaddedCompletions CompletionCounts + +variable {I J : Type*} [Fintype I] [Fintype J] + +abbrev ZeroPhysical (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) := + {a : PhysicalAssignments (fun a : I×J => small a.1 a.2) (fun a => B a.1 a.2) // + NestedPenaltyApplication.penalty cellLine (smallCoordinate small) + (fullOffset B (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L)) viewSlope + (smallOffset small B r c) viewSlope + (PhysicalLargeProfiles.physicalProfile (fun a : I×J => small a.1 a.2) + (fun a => B a.1 a.2) z a)=0} + +noncomputable def zeroSupportedEquiv (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) : + ZeroPhysical small B r c L z ≃ + ZeroAssignments small B (smallView small z false) (smallView small z true) r c L := + (supportedAssignmentEquiv small B).subtypeEquiv (fun a => by + have h := physicalProfile_supported small B z ((supportedAssignmentEquiv small B) a) + rw [Equiv.symm_apply_apply] at h + change _=0 ↔ fullPenalty small B _ _ _ r c L=0 + rw [h] + rfl) + +noncomputable def fibreLargeEquiv (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) + (hz : ∀ u,z u ≤ B u.1.val.1 u.1.val.2) + (hres : OriginalResidualsNonnegative small B (smallView small z false) (smallView small z true) r c) + (hcap : ∀ i j,small i j=false → + (∑ k,(r k-smallRow small (smallView small z false) k+rowLargeCount small k*L)) ≤ B i j) : + CompletionFibre small B r (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) z ≃ + LargeCompletion small + (fun i => r i-smallRow small (smallView small z false) i+rowLargeCount small i*L) + (fun j => c j-smallColumn small B (smallView small z true) j+columnLargeCount small j*L) := + ((zeroPhysicalEquiv small B r c L z hz).symm.trans + (zeroSupportedEquiv small B r c L z)).trans + (completionEquiv small B (smallView small z false) (smallView small z true) r c L + (fun i j hs => by simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,false)) + (fun i j hs => by simpa only [smallView,hs,dite_eq_left] using hz (⟨(i,j),hs⟩,true)) hres hcap) + +lemma fibreLargeEquiv_apply (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) + (hz : ∀ u,z u ≤ B u.1.val.1 u.1.val.2) + (hres : OriginalResidualsNonnegative small B (smallView small z false) (smallView small z true) r c) + (hcap : ∀ i j,small i j=false → + (∑ k,(r k-smallRow small (smallView small z false) k+rowLargeCount small k*L)) ≤ B i j) + (Z : CompletionFibre small B r (fun i => r i+rowLargeCount small i*L) + c (fun j => c j+columnLargeCount small j*L) z) (i : I) (j : J) : + (fibreLargeEquiv small B r c L z hz hres hcap Z).val.val i j= + if small i j then 0 else Z.val.val.1 i j := by + change (if hs : small i j=true then (0 : Fin (B i j+1)) + else fibreAssignment Z ⟨(i,j),Bool.eq_false_iff.mpr hs⟩).val=_ + by_cases hs : small i j=true + · simp only [hs,dite_eq_left,ite_true,Fin.val_zero] + · simp only [hs] + rfl + +end ContingencyTables.PhysicalCompletionFibres + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open SmallContextFibres + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- Actual retained completion fibre to the fixed-reference dense block. -/ +noncomputable def referenceFibreEquiv (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) : + CompletionFibre (firstPaperSmall r c U) B r + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) c + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L) + (physicalProfile _ B r c L z) ≃ + Table (referenceRows r c U L B i₀ z) (referenceColumns r c U L B j₀ z) := by + refine ((fibreLargeEquiv (firstPaperSmall r c U) B r c L + (physicalProfile _ B r c L z) (naturalProfile_bounded z.val.val) + (physical_original_residuals _ B r c L z hcap) hcap).trans ?_).trans + (tableReindex (Equiv.optionSubtypeNe i₀) (Equiv.optionSubtypeNe j₀) + (fun i : LargeRows r U => residualRows (firstPaperSmall r c U) B r c L z i.val) + (fun j : LargeColumns c U => residualColumns (firstPaperSmall r c U) B r c L z j.val)) + let E := rectangleCompletionEquiv (firstPaperSmall r c U) + (fun i => U ≤ r i) (fun j => U ≤ c j) (firstPaperSmall_false_iff r c U) + (residualRows _ B r c L z) (residualColumns _ B r c L z) + (physical_residual_row_zero r c U L B z hcap) + (physical_residual_column_zero r c U L B z hcap) + exact E.trans (tableFintypeTransport _ _ _ _ _ _) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..405d4f84de1e5c1350c5a275378e893afe45c6ba --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionFibreTransport.lean @@ -0,0 +1,22 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalCompletionFibres + +namespace OAI + +/-! # Changing a retained profile by an equality keeps the literal views -/ + +namespace ContingencyTables.PhysicalCompletionFibres + +variable {I J : Type*} [Fintype I] [Fintype J] +variable {small : I → J → Bool} {B : I → J → ℕ} +variable {r rbar : I → ℕ} {c cbar : J → ℕ} {z w : SmallProfile small} + +def withProfile (h : z=w) (Z : CompletionFibre small B r rbar c cbar z) : + CompletionFibre small B r rbar c cbar w := + ⟨Z.val,by rw [←h]; exact Z.property⟩ + +lemma withProfile_val (h : z=w) (Z : CompletionFibre small B r rbar c cbar z) : + (withProfile h Z).val=Z.val := rfl + +end ContingencyTables.PhysicalCompletionFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionKernelIdentification.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionKernelIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..5469e0cb8d9c377bfa1bc9fe112db4d4ab4b3fee --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionKernelIdentification.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionProposalLaw + +namespace OAI + +/-! # Identifying a complete transition law from its off-diagonal probabilities -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {X : Type*} [Fintype X] [DecidableEq X] + +/-- Normalization determines the remaining holding probability. -/ +theorem law_ext_except (p q : RationalLaw X) (x : X) + (h : ∀ y,y≠x → p.mass y=q.mass y) : p=q := by + apply RationalLaw.ext + funext y + by_cases hy : y=x + · subst y + have hs : (∑ y,(p.mass y-q.mass y))=p.mass x-q.mass x := by + apply Finset.sum_eq_single x + · intro y _ hy + rw [h y hy,sub_self] + · simp + rw [Finset.sum_sub_distrib,p.total,q.total,sub_self] at hs + linarith + · exact h y hy + +end ContingencyTables.FirstSuccess + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section +variable {X I J : Type*} [Fintype X] [Fintype I] [Fintype J] [DecidableEq X] +variable (R : X → Option I → ℕ) (P : X → Option J → ℕ) +variable [∀ x,Nonempty (Table (R x) (P x))] + +omit [∀ x,Nonempty (Table (R x) (P x))] in +/-- Only the proposal distribution at the current state is observed. -/ +lemma completionStepLaw_proposal_at (p q : X → RationalLaw (Option X)) + (draw : (z : X) → RationalLaw (Table (R z) (P z))) (x : X) (h : p x=q x) : + completionStepLaw R P p draw x=completionStepLaw R P q draw x := by + unfold completionStepLaw + rw [h] + +/-- This identifies the actual draw-and-test transition, including holds; +no independent reversibility or stationarity assertion is imposed on it. -/ +theorem uniformCompletionStep_eq (w : X → ℚ) (hw : ∀ y,0 ≤ w y) + (htotal : ∑ y,w y ≤ 1) (x : X) (K : RationalLaw X) + (hK : ∀ y,y≠x → K.mass y=w y*(acceptedCount R P x y:ℚ)/(blockCount R P x:ℚ)) : + completionStepLaw R P (fun _ => proposalLaw w hw htotal) + (fun z => uniformLaw (α := Table (R z) (P z))) x=K := by + apply law_ext_except _ _ x + intro y hy + rw [completionStepLaw_mass_ne R P w hw htotal _ x y hy.symm,uniformAcceptedMass,hK y hy] + ring + +end +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionProposalLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionProposalLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..c85e523ecf921f6e0b1178b5b9c0737bf316d4d0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionProposalLaw.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionStepApproximation +import Mathlib.Algebra.Order.Field.Basic + +namespace OAI + +/-! # The literal proposal, completion draw and acceptance test -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section +variable {X I J : Type*} [Fintype X] [Fintype I] [Fintype J] [DecidableEq X] + +/-- Each feasible neighbor is assigned its prescribed dyadic mass; the +remaining proposal words hold at the present state. -/ +def proposalLaw (w : X → ℚ) (hw : ∀ y,0 ≤ w y) (htotal : ∑ y,w y ≤ 1) : + RationalLaw (Option X) where + mass := fun y => match y with + | none => 1-∑ z,w z + | some z => w z + nonnegative := fun y => by cases y with + | none => exact sub_nonneg.mpr htotal + | some y => exact hw y + total := by rw [Fintype.sum_option]; dsimp only; ring + +omit [Fintype X] in +/-- Only a proposal of y can reach y from a distinct current state x. -/ +lemma completionDecision_eq (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (x y : X) (hne : x≠y) (q : Option X) (a : Table (R x) (P x)) : + completionDecision R P x q a=y ↔ + q=some y ∧ ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j := by + cases q with + | none => simp [completionDecision,hne] + | some z => + by_cases hz : z=y + · subst z + simp only [completionDecision,true_and] + split_ifs <;> simp_all + · simp only [completionDecision,Option.some.injEq,hz,false_and] + split_ifs <;> simp_all + +lemma completionStepLaw_mass_ne (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (w : X → ℚ) (hw : ∀ y,0 ≤ w y) (htotal : ∑ y,w y ≤ 1) + (μ : (x : X) → RationalLaw (Table (R x) (P x))) (x y : X) (hne : x≠y) : + (completionStepLaw R P (fun _ => proposalLaw w hw htotal) μ x).mass y= + w y*∑ a : Table (R x) (P x), + if ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then (μ x).mass a else 0 := by + change (∑ q : Option X,(proposalLaw w hw htotal).mass q * + ∑ a : Table (R x) (P x),if completionDecision R P x q a=y then (μ x).mass a else 0)=_ + simp_rw [completionDecision_eq R P x y hne] + rw [Fintype.sum_option] + simp only [reduceCtorEq,false_and,ite_false,Finset.sum_const_zero,mul_zero,zero_add,Option.some.injEq] + have hh (z : X) : (∑ a : Table (R x) (P x), + if z=y ∧ ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then (μ x).mass a else 0)= + if z=y then ∑ a : Table (R x) (P x), + if ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then (μ x).mass a else 0 else 0 := by + by_cases hz : z=y <;> simp [hz] + simp_rw [hh] + simp [proposalLaw,mul_ite] + +omit [Fintype X] [DecidableEq X] in +/-- The normalized completion indicator is exactly the acceptance count +used in the reversible small kernel. -/ +lemma uniformAcceptedMass (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (x y : X) [Nonempty (Table (R x) (P x))] : + (∑ a : Table (R x) (P x), + if ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then (uniformLaw (α := Table (R x) (P x))).mass a else 0)= + (acceptedCount R P x y:ℚ)/(blockCount R P x:ℚ) := by + simp only [uniformLaw,uniformMass] + calc + _ = (∑ a : Table (R x) (P x), + if ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then (1:ℚ) else 0)/(Fintype.card (Table (R x) (P x)):ℚ) := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp + _ = _ := by + rw [Finset.sum_boole,←Fintype.card_subtype] + rfl + +end +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionStepApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionStepApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fa4c1c5341c44dd48fd574989666a254d8ad051 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/CompletionStepApproximation.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionCounts +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalkApproximation + +namespace OAI + +/-! # Completion replacement in the actual proposal-and-translation step -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +variable {X I J : Type*} [Fintype X] [Fintype I] [Fintype J] [DecidableEq X] + +/-- A proposal is either a hold or a target state. The sampled completion +is discarded after its literal translated-nonnegativity test. -/ +def completionDecision (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (x : X) (proposal : Option X) (a : Table (R x) (P x)) : X := + match proposal with + | none => x + | some y => if ∀ i j,0 ≤ (a.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j then y else x + +def completionStepLaw (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (proposal : X → RationalLaw (Option X)) + (draw : (x : X) → RationalLaw (Table (R x) (P x))) (x : X) : RationalLaw X := + bindLaw (proposal x) (fun y => mapLaw (draw x) (completionDecision R P x y)) + +/-- From a common state only the completion draw changes. Mapping to the +accept/reject decision and averaging over the same proposal cannot enlarge TV. -/ +theorem completionStep_variation (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (proposal : X → RationalLaw (Option X)) + (μ ν : (x : X) → RationalLaw (Table (R x) (P x))) (η : ℚ) + (h : ∀ x,variation (μ x) (ν x) ≤ η) (x : X) : + variation (completionStepLaw R P proposal μ x) (completionStepLaw R P proposal ν x) ≤ η := by + have hv := variation_bind_uniform (proposal x) (proposal x) + (fun y => mapLaw (μ x) (completionDecision R P x y)) + (fun y => mapLaw (ν x) (completionDecision R P x y)) η + (fun y => (variation_map _ _ _).trans (h x)) + simpa only [completionStepLaw,variation,sub_self,abs_zero,Finset.sum_const_zero,zero_div,zero_add] using hv + +/-- The transition draws and the final completion all use fresh bits. The +bound is uniform even though the state supplied to each draw is adaptive. -/ +theorem completionWalk_terminal_variation (R : X → Option I → ℕ) (P : X → Option J → ℕ) + {Y : Type*} [Fintype Y] [DecidableEq Y] + (proposal : X → RationalLaw (Option X)) + (μ ν : (x : X) → RationalLaw (Table (R x) (P x))) + (output : (x : X) → Table (R x) (P x) → Y) (η : ℚ) + (h : ∀ x,variation (μ x) (ν x) ≤ η) (x : X) (n : ℕ) : + variation + (bindLaw (walkLaw (completionStepLaw R P proposal μ) x n) (fun z => mapLaw (μ z) (output z))) + (bindLaw (walkLaw (completionStepLaw R P proposal ν) x n) (fun z => mapLaw (ν z) (output z))) ≤ + (n+1)*η := + walkLaw_terminal_variation _ _ _ _ η + (completionStep_variation R P proposal μ ν η h) + (fun z => (variation_map _ _ _).trans (h z)) x n + +end +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedCompanionInstance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedCompanionInstance.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c612d2c2216979c8edb081a63ce232727b16122 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedCompanionInstance.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ComputedLargeForest +import OAI.Combinatorics.ContingencyTables.Machines.TightenedInputProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalMass + +namespace OAI + +/-! # A literal companion instance from binary bounded margins + +All operational data are read from the executed endpoint, flow, and +maximum-forest programs. The existential endpoint witnesses are used +only in the terminal-mass proof, never to define an executed output. +-/ + +namespace ContingencyTables.ComputedCompanionInstance + +open CompanionFactorialApplication ComputedTableTightening +open scoped BigOperators Classical + +variable {m n : ℕ} + +def baseline (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : ℕ := + ((TightenedInputProgram.baseline (NetworkVertexCode.data r c b)).getD i.val []).getD j.val 0 + +lemma baseline_properties (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) : + HasMargins (baseline r c b) (newRows r c b) (newColumns r c b) ∧ + ∀ i j,baseline r c b i j≤newBounds r c b i j := by + obtain ⟨Y,hcode,hm,hb⟩ := TightenedInputProgram.baseline_correct hEK r c b hne + have he : baseline r c b=Y := by + funext i j + simp only [baseline,hcode,ResidualGraphProgram.natCode, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,j.isLt, + dite_true,Option.getD_some,Fin.eta] + simpa only [he] using And.intro hm hb + +/-- The package consumed by the proved factorial, terminal, and oracle +lemmas. Its forest and baseline are decoded executed values. -/ +noncomputable def instanceData (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2≤W) : + Instance (Fin m) (Fin n) where + small:=ComputedLargeForest.small (newBounds r c b) W + b:=newBounds r c b + T:=ComputedLargeForest.computed (newRows r c b) (newColumns r c b) (newBounds r c b) W + hTG:=(ComputedLargeForest.computed_spec _ _ _ W (by omega)).1 + hT:=(ComputedLargeForest.computed_spec _ _ _ W (by omega)).2.1 + hmax:=(ComputedLargeForest.computed_spec _ _ _ W (by omega)).2.2 + r:=fun i=>(newRows r c b i:ℤ) + c:=fun j=>(newColumns r c b j:ℤ) + X:=fun i j=>(baseline r c b i j:ℤ) + d:=1+m*n + W:=W + hd:=by omega + hcard:=by simp only [Fintype.card_fin]; omega + hW:=hW + hlarge:=by + intro i j hs + have hb : W≤newBounds r c b i j := by + simpa only [ComputedLargeForest.small,decide_eq_false_iff_not,not_lt] using hs + exact ⟨hb,(show 1≤W by omega).trans hb⟩ + hsmall:=by + intro i j hs + simpa only [ComputedLargeForest.small,decide_eq_true_eq] using hs + hX:=by + intro i j + exact ⟨Nat.cast_nonneg _,by exact_mod_cast (baseline_properties hEK r c b hne).2 i j⟩ + hXr:=by + intro i + exact_mod_cast (baseline_properties hEK r c b hne).1.1 i + hXc:=by + intro j + exact_mod_cast (baseline_properties hEK r c b hne).1.2 j + +/-- Tightening preserves the count consumed by the terminal estimator. -/ +theorem original_count (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2≤W) : + CompanionTerminalMass.tableCount (instanceData hEK r c b hne W hW)= + (Fintype.card (BoundedTable r c b):ℝ) := by + unfold CompanionTerminalMass.tableCount + have he := (ComputedTableTightening.count_eq hEK r c b hne).symm + calc + _ = (Fintype.card (BoundedTable (newRows r c b) (newColumns r c b) + (newBounds r c b)):ℝ) := by + apply congrArg (fun k : ℕ=>(k:ℝ)) + exact Fintype.card_congr (Equiv.refl _) + _ = _ := congrArg (fun k : ℕ=>(k:ℝ)) he + +/-- The endpoint assumption in the terminal proof follows from the +executed searches. The witnesses here are mathematical proof data. -/ +noncomputable def endpoints (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (W : ℕ) (hW : 2≤W) : + CompanionTerminalMass.Endpoints (instanceData hEK r c b hne W hW) := by + have hends:=ComputedTableTightening.attained_endpoints hEK r c b hne + let lo : ∀ i j,Fin m→Fin n→ℕ:=fun i j=>Classical.choose (hends.1 i j) + let hi : ∀ i j,Fin m→Fin n→ℕ:=fun i j=>Classical.choose (hends.2 i j) + have hlo (i : Fin m) (j : Fin n) := Classical.choose_spec (hends.1 i j) + have hhi (i : Fin m) (j : Fin n) := Classical.choose_spec (hends.2 i j) + refine { lowerTable:=fun t i j=>(lo t.val.1 t.val.2 i j:ℤ) + upperTable:=fun t i j=>(hi t.val.1 t.val.2 i j:ℤ) + lowerBounds:=?_,upperBounds:=?_,lowerRows:=?_,lowerColumns:=?_, + upperRows:=?_,upperColumns:=?_,lowerAttains:=?_,upperAttains:=?_ } + · intro t i j + exact ⟨Nat.cast_nonneg _,by exact_mod_cast (hlo t.val.1 t.val.2).2.1 i j⟩ + · intro t i j + exact ⟨Nat.cast_nonneg _,by exact_mod_cast (hhi t.val.1 t.val.2).2.1 i j⟩ + · intro t i + change (∑ j,(lo t.val.1 t.val.2 i j:ℤ))=(newRows r c b i:ℤ) + exact_mod_cast (hlo t.val.1 t.val.2).1.1 i + · intro t j + change (∑ i,(lo t.val.1 t.val.2 i j:ℤ))=(newColumns r c b j:ℤ) + exact_mod_cast (hlo t.val.1 t.val.2).1.2 j + · intro t i + change (∑ j,(hi t.val.1 t.val.2 i j:ℤ))=(newRows r c b i:ℤ) + exact_mod_cast (hhi t.val.1 t.val.2).1.1 i + · intro t j + change (∑ i,(hi t.val.1 t.val.2 i j:ℤ))=(newColumns r c b j:ℤ) + exact_mod_cast (hhi t.val.1 t.val.2).1.2 j + · intro t + exact_mod_cast (hlo t.val.1 t.val.2).2.2 + · intro t + exact_mod_cast (hhi t.val.1 t.val.2).2.2 + +end ContingencyTables.ComputedCompanionInstance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedTableTightening.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedTableTightening.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b649b56ce29967733d35a46ccc06c7758a0d499 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ComputedTableTightening.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CellMinimumProgram +import OAI.Combinatorics.ContingencyTables.Transport.TableTightening + +namespace OAI + +/-! # Exact table bijection for the computed attained endpoints + +The endpoint hypotheses of the translation lemma are discharged by the +executed minimum and maximum searches, conditional only on EK1972. +-/ + +namespace ContingencyTables.ComputedTableTightening + +open TableTightening +open scoped Classical + +variable {m n : ℕ} + +def lower (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : ℕ := + CellMinimumProgram.minimum (NetworkVertexCode.data r c b,(i.val,j.val)) +def upper (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : ℕ := + CellMaximumProgram.maximum (NetworkVertexCode.data r c b,(i.val,j.val)) + +variable (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,Feasible r c b X) + +include hEK hne + +lemma lower_le {X : Fin m→Fin n→ℕ} (hX : Feasible r c b X) + (i : Fin m) (j : Fin n) : lower r c b i j≤X i j := by + obtain ⟨Y,_,_,he,hy⟩ := CellMinimumProgram.minimum_correct hEK r c b i j hne + have h := hy X hX.1 hX.2 + simpa only [he,lower] using h + +lemma le_upper {X : Fin m→Fin n→ℕ} (hX : Feasible r c b X) + (i : Fin m) (j : Fin n) : X i j≤upper r c b i j := by + obtain ⟨Y,_,_,he,hy⟩ := CellMaximumProgram.maximum_correct hEK r c b i j hne + have h := hy X hX.1 hX.2 + simpa only [he,upper] using h + +lemma lower_attained (i : Fin m) (j : Fin n) : + ∃ X,Feasible r c b X ∧ X i j=lower r c b i j := by + obtain ⟨X,hm,hb,he,_⟩ := CellMinimumProgram.minimum_correct hEK r c b i j hne + exact ⟨X,⟨hm,hb⟩,he⟩ + +lemma upper_attained (i : Fin m) (j : Fin n) : + ∃ X,Feasible r c b X ∧ X i j=upper r c b i j := by + obtain ⟨X,hm,hb,he,_⟩ := CellMaximumProgram.maximum_correct hEK r c b i j hne + exact ⟨X,⟨hm,hb⟩,he⟩ + +lemma upper_le_bound (i : Fin m) (j : Fin n) : upper r c b i j≤b i j := by + obtain ⟨X,hX,he⟩ := upper_attained hEK r c b hne i j + simpa only [←he] using hX.2 i j + +lemma lower_le_upper (i : Fin m) (j : Fin n) : lower r c b i j≤upper r c b i j := by + obtain ⟨X,hX⟩ := hne + exact (lower_le hEK r c b ⟨X,hX⟩ hX i j).trans + (le_upper hEK r c b ⟨X,hX⟩ hX i j) + +omit hEK hne in +def newRows : Fin m→ℕ := rows r (lower r c b) +omit hEK hne in +def newColumns : Fin n→ℕ := columns c (lower r c b) +omit hEK hne in +def newBounds : Fin m→Fin n→ℕ := bounds (lower r c b) (upper r c b) + +noncomputable def tighten (X : BoundedTable r c b) : + BoundedTable (newRows r c b) (newColumns r c b) (newBounds r c b) := by + have h := subtract_feasible r c b (lower r c b) (upper r c b) + (fun Y hY i j=>lower_le hEK r c b hne hY i j) + (fun Y hY i j=>le_upper hEK r c b hne hY i j) ⟨X.val.property,X.property⟩ + exact ⟨⟨subtract X.val.val (lower r c b),h.1⟩,h.2⟩ + +noncomputable def restore + (Y : BoundedTable (newRows r c b) (newColumns r c b) (newBounds r c b)) : + BoundedTable r c b := by + have h := add_feasible r c b (lower r c b) (upper r c b) hne + (fun X hX i j=>lower_le hEK r c b hne hX i j) + (upper_le_bound hEK r c b hne) ⟨Y.val.property,Y.property⟩ + exact ⟨⟨add Y.val.val (lower r c b),h.1⟩,h.2⟩ + +noncomputable def tighteningEquiv : BoundedTable r c b ≃ + BoundedTable (newRows r c b) (newColumns r c b) (newBounds r c b) where + toFun := tighten hEK r c b hne + invFun := restore hEK r c b hne + left_inv X := by + apply Subtype.ext + apply Subtype.ext + exact add_subtract X.val.val (lower r c b) + (fun i j=>lower_le hEK r c b hne ⟨X.val.property,X.property⟩ i j) + right_inv Y := by + apply Subtype.ext + apply Subtype.ext + exact subtract_add Y.val.val (lower r c b) + +theorem count_eq : Fintype.card (BoundedTable r c b)= + Fintype.card (BoundedTable (newRows r c b) (newColumns r c b) (newBounds r c b)) := + Fintype.card_congr (tighteningEquiv hEK r c b hne) + +theorem attained_endpoints : + (∀ i j,∃ Y,HasMargins Y (newRows r c b) (newColumns r c b) ∧ + (∀ a d,Y a d≤newBounds r c b a d) ∧ Y i j=0) ∧ + (∀ i j,∃ Y,HasMargins Y (newRows r c b) (newColumns r c b) ∧ + (∀ a d,Y a d≤newBounds r c b a d) ∧ Y i j=newBounds r c b i j) := by + have h := endpoints r c b (lower r c b) (upper r c b) + (fun X hX i j=>lower_le hEK r c b hne hX i j) + (fun X hX i j=>le_upper hEK r c b hne hX i j) + (lower_attained hEK r c b hne) (upper_attained hEK r c b hne) + simpa only [TightFeasible,and_assoc,newRows,newColumns,newBounds] using h + +end ContingencyTables.ComputedTableTightening + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextAdjacentTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextAdjacentTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..98c82dc250b179a42b00a0d2b60751a1d8aa654f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextAdjacentTransport.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Transport.AuxiliaryRepairMass +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextBox +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportCoefficient + +namespace OAI + +/-! # Adjacent physical exposure means with the repaired coefficient -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open BalancedEnumeration IntegerWeightedTransport FirstPaperProfiles +open FirstPaperContextTransport FirstPaperPhysicalMarginal IntegerBoxTruncation +open PaddedCompletions CompletionCounts FactorialSignatures + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +def rootDisplay (U l : ℕ) : Bool → ℕ := fun b => if b then U-l+1 else l + +lemma rootDisplay_inBox (U l : ℕ) (hl0 : 1 ≤ l) (hlU : l ≤ U) : + InBox (fun _ : Bool => U) (rootDisplay U l) := by + intro b + cases b + · exact hlU + · change U-l+1 ≤ U + omega + +lemma rootDisplay_total (U l : ℕ) (hlU : l ≤ U) : + (∑ b, rootDisplay U l b)=U+1 := by + simp only [rootDisplay,Fintype.sum_bool,Bool.false_eq_true,↓reduceIte] + omega + +lemma rootDisplay_remove_false (U l : ℕ) (hl0 : 1 ≤ l) (hlU : l ≤ U) : + removeOne (rootDisplay U l) false=childProfile U (l-1) := by + funext b + cases b <;> simp only [removeOne,rootDisplay,childProfile,Bool.false_eq_true,Bool.true_eq_false,↓reduceIte] + omega + +lemma rootDisplay_remove_true (U l : ℕ) : + removeOne (rootDisplay U l) true=childProfile U l := by + funext b + cases b <;> simp [removeOne,rootDisplay,childProfile] + +lemma rootDisplay_remove_two (U l : ℕ) : + removeTwo (rootDisplay U l) false true=auxRoot U l := by + funext b + cases b <;> simp [removeTwo,removeOne,rootDisplay,auxRoot] + +lemma rootDisplay_oneHole_false (F : (Bool → ℕ) → ℝ) (U l : ℕ) + (hl0 : 1 ≤ l) (hlU : l ≤ U) : + oneHole F (rootDisplay U l) false=F (childProfile U (l-1)) := by + rw [oneHole,ite_eq_left (show 0 < rootDisplay U l false by exact hl0), + rootDisplay_remove_false U l hl0 hlU] + +lemma rootDisplay_oneHole_true (F : (Bool → ℕ) → ℝ) (U l : ℕ) : + oneHole F (rootDisplay U l) true=F (childProfile U l) := by + rw [oneHole,ite_eq_left (show 0 < rootDisplay U l true by change 0 < U-l+1; omega), + rootDisplay_remove_true] + +lemma rootDisplay_removal (F : (Bool → ℕ) → ℝ) (U l : ℕ) (hl0 : 1 ≤ l) : + integerRemovalMatrix F (rootDisplay U l) false true=F (auxRoot U l) := by + have hv : ValidPair (rootDisplay U l) false true := by + simp only [ValidPair,rootDisplay,Bool.false_eq_true,Bool.true_eq_false,↓reduceIte] + omega + rw [integerRemovalMatrix,ite_eq_left hv,rootDisplay_remove_two] + +lemma widths_constant_mem (U : ℕ) {n : ℕ} (w : ℕ) + (hw : w ∈ widths (fun _ : Fin n => U)) : w=U := by + induction n with + | zero => exact False.elim (List.not_mem_nil hw) + | succ n ih => + simp only [widths,List.mem_cons] at hw + exact hw.elim id ih + +lemma prefixRaw_inBox (small : I → J → Bool) (s : I×J) (σ : I×J → ℕ) (U : ℕ) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) : + InBox (fun _ : Earlier small s×Bool => U) (prefixRaw small s σ U) := by + rintro ⟨a,b⟩ + cases b + · exact hσ a + · exact Nat.sub_le _ _ + +lemma graphEnergy_nonnegative {C : Type*} [DecidableEq C] + (V : Finset (C → ℕ)) (f H : (C → ℕ) → ℝ) (hf : ∀ x, 0 ≤ f x) : + 0 ≤ integerGraphEnergy V f H := by + unfold integerGraphEnergy + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro e _ + exact mul_nonneg (le_min (hf _) (hf _)) (sq_nonneg _) + +variable [Fintype I] [Fintype J] + +/-- The actual adjacent conditional means satisfy the uniform repaired +transport estimate, with precisely the box-valid leaf exchange energy. -/ +theorem adjacent_context_transport (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hU : 2 ≤ U) (hl0 : 1 ≤ l) (hlU : l ≤ U) + (hB : ∀ i j, small i j=true → B i j=U) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) + (H : (Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) → ℝ) + (hleft : 0 < eliminate (widths (fun _ : Fin n => U)) + (contextHard small B r c L _ (contextEquiv small s hs e U) (prefixRaw small s σ U)) + (childProfile U (l-1))) + (hright : 0 < eliminate (widths (fun _ : Fin n => U)) + (contextHard small B r c L _ (contextEquiv small s hs e U) (prefixRaw small s σ U)) + (childProfile U l)) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let a := eliminate Ms f (childProfile U (l-1)) + let b := eliminate Ms f (childProfile U l) + let E := integerGraphEnergy + ((leafVertices Ms (rootDisplay U l)).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum)) f H + min a b*(eliminate Ms (fun p => f p*H p) (childProfile U (l-1))/a- + eliminate Ms (fun p => f p*H p) (childProfile U l)/b)^2 ≤ + (2+2*n*((U:ℝ)+1)^2)*E := by + dsimp only + have htransport := context_box_transport small B r c L (widths (fun _ : Fin n => U)) + (contextEquiv small s hs e U) (prefixRaw small s σ U) (fun _ => U) + (fun _ => U) (rootDisplay U l) U U (prefixRaw_inBox small s σ U hσ) hlarge + (fun w hw => by rw [widths_constant_mem U w hw]; exact hU) + (fun w hw => le_of_eq (widths_constant_mem U w hw)) + (rootDisplay_inBox U l hl0 hlU) (rootDisplay_total U l hlU) H + (leafVertices _ (rootDisplay U l)) (Finset.Subset.refl _) + (by rw [rootDisplay_oneHole_false _ U l hl0 hlU]; exact hleft) + (by rw [rootDisplay_oneHole_true]; exact hright) + dsimp only at htransport + simp only [rootDisplay_oneHole_false _ U l hl0 hlU,rootDisplay_oneHole_true, + rootDisplay_removal _ U l hl0] at htransport + have haux := auxiliary_mass_le_adjacent small B r c L s hs σ U l hl0 hlU hB hσ e hcap + dsimp only at haux + exact repaired_root_transport _ _ _ n U _ _ hleft hright + (graphEnergy_nonnegative _ _ _ (contextHard_nonnegative small B r c L _ _ _)) haux htransport + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextChildVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextChildVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..35445d4268aac6ce86d2cb19dc36d5fd7ed89119 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextChildVariance.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ContextAdjacentTransport +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance + +namespace OAI + +/-! # Between-child variance for actual physical exposure contexts -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open IntegerWeightedTransport FirstPaperProfiles FirstPaperContextTransport +open FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u + +lemma graphEnergy_mono {C : Type*} [DecidableEq C] + (V W : Finset (C → ℕ)) (f H : (C → ℕ) → ℝ) + (hVW : V ⊆ W) (hf : ∀ x, 0 ≤ f x) : + integerGraphEnergy V f H ≤ integerGraphEnergy W f H := by + unfold integerGraphEnergy + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum_of_subset_of_nonneg + · intro e he + obtain ⟨he,hadj⟩ := Finset.mem_filter.mp he + obtain ⟨hx,hy⟩ := Finset.mem_product.mp he + exact Finset.mem_filter.mpr ⟨Finset.mem_product.mpr ⟨hVW hx,hVW hy⟩,hadj⟩ + · intro e _ _ + exact mul_nonneg (le_min (hf _) (hf _)) (sq_nonneg _) + +noncomputable def contextVertices (U n : ℕ) : + Finset (Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) := + Finset.univ.biUnion (fun l : Fin (U+1) => leafVertices _ (rootDisplay U l.val)) + +lemma leafVertices_subset_context (U n l : ℕ) (hl : l ≤ U) : + leafVertices (widths (fun _ : Fin n => U)) (rootDisplay U l) ⊆ contextVertices U n := by + intro x hx + exact Finset.mem_biUnion.mpr ⟨⟨l,Nat.lt_succ_of_le hl⟩,Finset.mem_univ _,hx⟩ + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- The physical conditional masses and means satisfy the paper's +between-child estimate, allowing arbitrary zero-mass children. -/ +theorem physical_child_variance (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) (hU : 2 ≤ U) + (hB : ∀ i j, small i j=true → B i j=U) + (hlarge : ∀ i j, small i j=false → 2 ≤ B i j) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (hcap : ∀ T : ResidualTables small r c + (fun i => r i+rowLargeCount small i*L) (fun j => c j+columnLargeCount small j*L), + ∀ i j, T.val.val i j ≤ B i j) + (H : (Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) → ℝ) + (hZ : 0 < ∑ j : Fin (U+1), eliminate (widths (fun _ : Fin n => U)) + (contextHard small B r c L _ (contextEquiv small s hs e U) (prefixRaw small s σ U)) + (childProfile U j.val)) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let z := fun j => eliminate Ms f (childProfile U j) + let μ := fun j => eliminate Ms (fun p => f p*H p) (childProfile U j)/z j + let E := integerGraphEnergy ((contextVertices U n).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum)) f H + (∑ j : Fin (U+1), z j.val*(μ j.val- + (∑ k : Fin (U+1),z k.val*μ k.val)/(∑ k : Fin (U+1),z k.val))^2) ≤ + ((U:ℝ)+1)^4*(2+2*n*((U:ℝ)+1)^2)*E := by + dsimp only + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let z := fun j => eliminate Ms f (childProfile U j) + let μ := fun j => eliminate Ms (fun p => f p*H p) (childProfile U j)/z j + let V := (contextVertices U n).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum) + have hf : ∀ x, 0 ≤ f x := contextHard_nonnegative small B r c L Ms _ _ + have hz (j : ℕ) : 0 ≤ z j := eliminate_nonnegative Ms f hf _ + have hE : 0 ≤ integerGraphEnergy V f H := graphEnergy_nonnegative V f H hf + apply child_variance_bound z μ U (2+2*n*((U:ℝ)+1)^2) (integerGraphEnergy V f H) + (fun j _ => hz j) hZ (by positivity) hE + · intro a j b haj hjb hbU + exact context_child_minimum small B r c L Ms (contextEquiv small s hs e U) + (prefixRaw small s σ U) (fun _ => U) U (prefixRaw_inBox small s σ U hσ) hlarge + (fun w hw => by rw [widths_constant_mem U w hw]; exact hU) a j b haj hjb hbU + · intro j hj + by_cases hl : 0 < z j + · by_cases hr : 0 < z (j+1) + · have htransport := adjacent_context_transport small B r c L s hs σ U (j+1) hU + (by omega) (by omega) hB hlarge hσ e hcap H (by simpa only [Nat.add_sub_cancel] using hl) hr + dsimp only at htransport + simp only [Nat.add_sub_cancel] at htransport + have hsub : (leafVertices Ms (rootDisplay U (j+1))).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum) ⊆ V := by + intro x hx + obtain ⟨hx,hbox⟩ := Finset.mem_filter.mp hx + exact Finset.mem_filter.mpr ⟨leafVertices_subset_context U n (j+1) (by omega) hx,hbox⟩ + exact htransport.trans (mul_le_mul_of_nonneg_left (graphEnergy_mono _ V f H hsub hf) (by positivity)) + · have hr0 : z (j+1)=0 := le_antisymm (le_of_not_gt hr) (hz (j+1)) + rw [hr0,min_eq_right (hz j),zero_mul] + positivity + · have hl0 : z j=0 := le_antisymm (le_of_not_gt hl) (hz j) + rw [hl0,min_eq_left (hz (j+1)),zero_mul] + positivity + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..447dd18d8ab1abadd1e20f44d20e5539fd2960fd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphEnergy.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphVertices + +namespace OAI + +/-! # Contextual transport energy embeds in the actual physical graph -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open IntegerWeightedTransport FirstPaperProfiles ExcessContextProfiles +open FirstPaperContextTransport FirstPaperPhysicalMarginal + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +def PhysicalPrefix (small : I → J → Bool) (s : I×J) (σ : I×J → ℕ) + (z : SmallProfile small) : Prop := + ∀ a : Earlier small s, z (a.val,false)=σ a.val.val + +omit [Fintype I] [Fintype J] in +lemma assemble_physicalPrefix (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (x : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) : + PhysicalPrefix small s σ (assemble small s hs σ U e x) := by + intro a + exact assemble_prefix small s hs σ U e x a false + +noncomputable def physicalContextEdges (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) : Finset (SmallProfile small×SmallProfile small) := + ((vertices small B) ×ˢ (vertices small B)).filter + (fun p => IntegerExchangeAdjacent p.1 p.2 ∧ PhysicalPrefix small s σ p.1 ∧ PhysicalPrefix small s σ p.2) + +noncomputable def physicalContextEnergy (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (σ : I×J → ℕ) (f H : SmallProfile small → ℝ) : ℝ := + (∑ p ∈ physicalContextEdges small B s σ, edgeTerm f H p)/2 + +omit [LinearOrder I] [LinearOrder J] in +lemma hardMarginal_nonnegative (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) (z : SmallProfile small) : + 0 ≤ hardMarginal small B r c L z := by + unfold hardMarginal fullHardFamily NestedPenaltyApplication.hardWeight + apply Finset.sum_nonneg + intro a _ + split_ifs <;> norm_num + +/-- The actual conditional variance energy uses physical allowed states +and ordinary exchange edges in its fixed row-major prefix only. -/ +theorem context_graphEnergy_le (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L : ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hU : 1 ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (H : SmallProfile small → ℝ) : + let Ms := widths (fun _ : Fin n => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + integerGraphEnergy ((contextVertices U n).filter + (fun x => InBox (bounds (fun _ : Bool => U) Ms) x ∧ (∑ i, x i)=U+Ms.sum)) + f (fun x => H (assemble small s hs σ U e x)) ≤ + physicalContextEnergy small B s σ (hardMarginal small B r c L) H := by + dsimp only + let V := (contextVertices U n).filter + (fun x => InBox (bounds (fun _ : Bool => U) (widths (fun _ : Fin n => U))) x ∧ + (∑ i, x i)=U+(widths (fun _ : Fin n => U)).sum) + let E := (V ×ˢ V).filter (fun p => IntegerExchangeAdjacent p.1 p.2) + let j : ((Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ)× + (Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ)) → + (SmallProfile small×SmallProfile small) := + fun p => (assemble small s hs σ U e p.1,assemble small s hs σ U e p.2) + have hj : Function.Injective j := by + intro a b he + apply Prod.ext + · exact assemble_injective small s hs σ U e (congrArg Prod.fst he) + · exact assemble_injective small s hs σ U e (congrArg Prod.snd he) + have hmem (x) (hx : x ∈ V) : assemble small s hs σ U e x ∈ vertices small B := by + obtain ⟨hx,hbox,_⟩ := Finset.mem_filter.mp hx + exact context_vertex_mem small B s hs σ U hU hB hσ e x hx hbox + have hsub : E.image j ⊆ physicalContextEdges small B s σ := by + intro p hp + obtain ⟨q,hq,rfl⟩ := Finset.mem_image.mp hp + obtain ⟨hq,hadj⟩ := Finset.mem_filter.mp hq + obtain ⟨hx,hy⟩ := Finset.mem_product.mp hq + apply Finset.mem_filter.mpr + exact ⟨Finset.mem_product.mpr ⟨hmem _ hx,hmem _ hy⟩, + assemble_exchange_adjacent small s hs σ U e _ _ hadj, + assemble_physicalPrefix small s hs σ U e _,assemble_physicalPrefix small s hs σ U e _⟩ + unfold integerGraphEnergy physicalContextEnergy + apply div_le_div_of_nonneg_right _ (by norm_num) + change (∑ p ∈ E, edgeTerm (hardMarginal small B r c L) H (j p)) ≤ _ + calc + _ = ∑ p ∈ E.image j, edgeTerm (hardMarginal small B r c L) H p := + (Finset.sum_image (fun a _ b _ he => hj he)).symm + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg hsub (fun p _ _ => + mul_nonneg (le_min (hardMarginal_nonnegative small B r c L _) + (hardMarginal_nonnegative small B r c L _)) (sq_nonneg _)) + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphMembership.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphMembership.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d3aacfb6531dd76a4a083eee3fbaee4eaa3604c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextGraphMembership.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallGraphProfiles +import OAI.Combinatorics.ContingencyTables.Transport.ContextChildVariance + +namespace OAI + +/-! # Context leaf vertices are actual balanced or single-defect states -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open BalancedEnumeration IntegerWeightedTransport FirstPaperProfiles ExcessContextProfiles FactorialSignatures + +universe u + +lemma pair_total_removeOne {C : Type*} [DecidableEq C] + (D : C×Bool → ℕ) (c a : C) (b : Bool) (hd : 0 < D (c,b)) : + removeOne D (c,b) (a,false)+removeOne D (c,b) (a,true)= + D (a,false)+D (a,true)-(if a=c then 1 else 0) := by + by_cases ha : a=c + · subst a + cases b <;> simp only [removeOne,Prod.mk.injEq,Bool.false_eq_true, + Bool.true_eq_false,↓reduceIte,and_false,Nat.sub_zero] at hd ⊢ <;> omega + · simp only [removeOne,Prod.mk.injEq,ha,false_and,↓reduceIte,Nat.sub_zero] + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +omit [LinearOrder I] [LinearOrder J] in +lemma balanced_of_pair_totals (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j, small i j=true → B i j=U) (z : SmallProfile small) + (hpair : ∀ a : Cells small, z (a,false)+z (a,true)=U) : Balanced small B z := by + intro i j + cases hij : small i j + · simp only [smallView,smallQ,hij,Bool.false_eq_true,↓reduceDIte] + · have hh := hpair ⟨(i,j),hij⟩ + simp only [smallView,smallQ,hij,dite_eq_left,hB i j hij] + omega + +lemma pattern_after_one_removal (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hU : 1 ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (s : I×J) (hs : small s.1 s.2=true) (D : SmallProfile small) + (hpair : ∀ a : Cells small, D (a,false)+D (a,true)=if a=⟨s,hs⟩ then U+1 else U) + (i : SmallView (fun a : I×J => small a.1 a.2)) (hi : 0 < D i) + (hz : ∀ a, removeOne D i a ≤ U) : Pattern small B (removeOne D i) := by + rcases i with ⟨c,b⟩ + by_cases hc : c=⟨s,hs⟩ + · subst c + left + apply balanced_of_pair_totals small B U hB + intro a + have hh := pair_total_removeOne D ⟨s,hs⟩ a b hi + rw [hpair a] at hh + by_cases ha : a=⟨s,hs⟩ + · rw [ite_eq_left ha,ite_eq_left ha] at hh + omega + · rw [ite_eq_right ha,ite_eq_right ha] at hh + omega + · right + have hc' : c.val≠s := fun he => hc (Subtype.ext he) + refine ⟨c.val,s,c.property,hs,?_⟩ + apply defect_of_pair_totals small B U hU hB c.val s c.property hs hc' _ hz + intro a + have hh := pair_total_removeOne D c a b hi + rw [hpair a] at hh + have hp : removeOne D (c,b) (a,false)+removeOne D (c,b) (a,true)= + if a=c then U-1 else if a=⟨s,hs⟩ then U+1 else U := by + by_cases hac : a=c + · have has : a≠⟨s,hs⟩ := fun he => hc (hac.symm.trans he) + rw [ite_eq_right has,ite_eq_left hac] at hh + rw [ite_eq_left hac] + exact hh + · rw [ite_eq_right hac] at hh ⊢ + by_cases has : a=⟨s,hs⟩ + · rw [ite_eq_left has] at hh ⊢ + omega + · rw [ite_eq_right has] at hh ⊢ + omega + simpa only [Subtype.ext_iff] using hp + +lemma assemble_bounded (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) + {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (hv : InBox (bounds (fun _ : Bool => U) (widths (fun _ : Fin n => U))) v) : + ∀ a, assemble small s hs σ U e v a ≤ U := by + rw [bounds_constant] at hv + intro a + obtain ⟨w,rfl⟩ := (contextEquiv small s hs e U).surjective a + rw [assemble_apply] + cases w with + | inl p => + rcases p with ⟨p,b⟩ + cases b + · exact hσ p + · exact Nat.sub_le _ _ + | inr w => exact hv w + +lemma base_pair_total (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hlU : l ≤ U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : Assignments (widths (fun _ : Fin n => U))) (a : Cells small) : + assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (a,false)+ + assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (a,true)= + if a=⟨s,hs⟩ then U+1 else U := by + obtain ⟨v,rfl⟩ := (cellSplitEquiv small s hs).surjective a + rcases v with p|(_|t) + · have hps : p.val≠⟨s,hs⟩ := by + intro he + have h := p.property + rw [he] at h + exact h.ne rfl + change assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (p.val,false)+ + assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (p.val,true)= + if p.val=⟨s,hs⟩ then U+1 else U + simp only [assemble_prefix,Bool.false_eq_true,↓reduceIte,hps] + have hb := hσ p + omega + · change assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (⟨s,hs⟩,false)+ + assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (⟨s,hs⟩,true)= + if (⟨s,hs⟩ : Cells small)=⟨s,hs⟩ then U+1 else U + rw [ite_eq_left rfl] + simp only [assemble_special,embedding_root,rootDisplay,Bool.false_eq_true,↓reduceIte] + omega + · have hts : t.val≠⟨s,hs⟩ := by + intro he + have h := t.property + rw [he] at h + exact h.ne rfl + change assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (t.val,false)+ + assemble small s hs σ U e (embedding _ (rootDisplay U l) q) (t.val,true)= + if t.val=⟨s,hs⟩ then U+1 else U + have hf := assemble_later small s hs σ U e (embedding _ (rootDisplay U l) q) (e.symm t) false + have ht := assemble_later small s hs σ U e (embedding _ (rootDisplay U l) q) (e.symm t) true + simp only [Equiv.apply_symm_apply] at hf ht + rw [hf,ht,ite_eq_right hts] + exact embedding_pair_total (fun _ : Fin n => U) (rootDisplay U l) q (e.symm t) + +/-- Every box-valid transport leaf has exactly an allowed physical +small-graph pattern. No multi-defect vertex enters the local energy. -/ +theorem leaf_pattern (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U l : ℕ) + (hU : 1 ≤ U) (hlU : l ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (x : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (hx : x ∈ leafVertices _ (rootDisplay U l)) + (hbox : InBox (bounds (fun _ : Bool => U) (widths (fun _ : Fin n => U))) x) : + Pattern small B (assemble small s hs σ U e x) := by + obtain ⟨q,_,hx⟩ := Finset.mem_biUnion.mp hx + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hx + have hi' := (Finset.mem_filter.mp hi).2 + have hb := assemble_bounded small s hs σ U hσ e _ hbox + rw [assemble_removeOne] at hb ⊢ + apply pattern_after_one_removal small B U hU hB s hs + (assemble small s hs σ U e (embedding _ (rootDisplay U l) q)) + (base_pair_total small s hs σ U l hlU hσ e q) + (contextEquiv small s hs e U (.inr i)) _ hb + rw [assemble_apply] + exact hi' + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextWeightedEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextWeightedEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..b237ca5a0da3b77e9d1cb0d22f186caed10229ab --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ContextWeightedEnumeration.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.ExcessContextProfiles + +namespace OAI + +/-! # Physical observables in the literal conditional enumeration -/ + +namespace ContingencyTables.SmallContextEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextFibres PhysicalCompletionFibres +open LargePairEnumeration BalancedEnumeration BalancedFamily +open FirstPaperContextTransport FirstPaperPhysicalMarginal ExcessContextProfiles +open IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +/-- Arbitrary physical observables keep exactly the same completion +multiplicity in recursive elimination and in the literal child fibre. -/ +theorem eliminate_context_eq_weighted_sum (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s,σ a.val.val ≤ U) (k : Fin (U+1)) + {n : ℕ} (e : Fin n ≃ Later small s) (F : SmallProfile small → ℝ) : + eliminate (widths (fun _ : Fin n => U)) + (fun p => F (assemble small s hs σ U e p)) (childProfile U k.val)= + ∑ z : BalancedProfiles small B s σ k.val,F (naturalProfile z.val) := by + rw [eliminate_eq_sum] + apply Fintype.sum_equiv (((assignmentEquiv (fun _ : Fin n => U)).trans + (reindexChoices small s e)).trans (balancedContextEquiv small B s hs σ U hB hσ k)) + intro q + unfold assemble + rw [physical_embedding_eq small B s hs σ U hB hσ k e q] + rfl + +end ContingencyTables.SmallContextEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/DegreeCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/DegreeCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..665eb4527e2927cb7bc3500c3915f755ce7d7f90 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/DegreeCompletion.lean @@ -0,0 +1,222 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RecursiveSignedTransport +import OAI.Combinatorics.ContingencyTables.Transport.LaminarSignature + +namespace OAI + +/-! +# Positive completion of a single valid degree + +A fixed-degree weight is extended by the constant weight one on every +other degree. All off-degree signatures are proved, and all coefficient +sums at the original degree are unchanged. This lets the existing general +nonnegative-derivative theorem retain contracted coordinates without +assuming positivity or signatures of the original weight at other degrees. +-/ + +namespace ContingencyTables.DegreeCompletion + +open scoped BigOperators Classical Topology +open CommonBasesFPRAS BinaryContraction RecursiveSignedTransport + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +noncomputable def completeDegree (f : Set Γ → ℝ) (k : ℕ) (A : Set Γ) : ℝ := + if A.ncard = k then f A else 1 + +omit [Fintype Γ] [DecidableEq Γ] in +lemma completeDegree_positive (f : Set Γ → ℝ) (k : ℕ) (hf : DegreePositive f k) : + ∀ A, 0 < completeDegree f k A := by + intro A + unfold completeDegree + split_ifs with h + · exact hf A h + · norm_num + +lemma constant_face_signature (A : Set Γ) : + CommonBasesFPRAS.OnePositive (faceHessian (fun _ : Set Γ => (1 : ℝ)) A).toBilin' := by + let K := twoLevelKernel (fun i : {i // i ∉ A} => i) (fun _ => false) + (fun _ => (0 : ℝ)) (fun _ => (1 : ℝ)) + have heq : faceHessian (fun _ : Set Γ => (1 : ℝ)) A = K := by + ext i j + simp [faceHessian, K, twoLevelKernel] + rw [heq] + apply (signature_iff _ (matrix_bilin_symm _ (by intro i j; simp [K, twoLevelKernel, eq_comm]))).mp + exact twoLevelKernel_onePositive _ _ _ _ (by intro i; norm_num) + (by intro i; norm_num) (by intro i; norm_num) + +lemma completeDegree_face_signature (f : Set Γ → ℝ) (k : ℕ) + (hsig : AdditionProperty f k) (A : Set Γ) : + CommonBasesFPRAS.OnePositive (faceHessian (completeDegree f k) A).toBilin' := by + by_cases hA : A.ncard + 2 = k + · have heq : faceHessian (completeDegree f k) A = faceHessian f A := by + ext i j + by_cases hij : i = j + · simp [faceHessian, hij] + simp only [faceHessian, hij, ite_false, completeDegree] + rw [ite_eq_left ((ncard_union_pair A i j hij).trans hA)] + rw [heq] + exact hsig A hA + · have heq : faceHessian (completeDegree f k) A = faceHessian (fun _ => (1 : ℝ)) A := by + ext i j + by_cases hij : i = j + · simp [faceHessian, hij] + simp only [faceHessian, hij, ite_false, completeDegree] + rw [ite_eq_right (by rw [ncard_union_pair A i j hij]; exact hA)] + rw [heq] + exact constant_face_signature A + +/-- Positive directions are handled by the existing cubic spectral theorem. +The cardinality cutoff of a repeated derivative is established at each step. -/ +lemma positive_derivatives_signature (f : Set Γ → ℝ) (hf : ∀ A, 0 < f A) + (hsig : ∀ A, CommonBasesFPRAS.OnePositive (faceHessian f A).toBilin') + (ds : List (Γ → ℝ)) (hds : ∀ a ∈ ds, ∀ i, 0 < a i) : + FullPositive (coeffDerivs ds f) ds.length ∧ + ∀ A, CommonBasesFPRAS.OnePositive (faceHessian (coeffDerivs ds f) A).toBilin' := by + induction ds with + | nil => + refine ⟨⟨fun A _ => hf A, ?_⟩, hsig⟩ + intro A hA + have hcard : A.ncard ≤ Fintype.card Γ := by simpa using Set.ncard_le_card A + simp only [List.length_nil, Nat.add_zero] at hA + omega + | cons a ds ih => + have ha := hds a List.mem_cons_self + obtain ⟨hp, hs⟩ := ih (fun b hb => hds b (List.mem_cons_of_mem _ hb)) + exact ⟨hp.deriv a ha, derivative_face_signature hp hs a ha⟩ + +/-- The zero coordinates of a direction are reached by an actual positive +perturbation and the proved closedness of the quadratic signature. -/ +lemma nonnegative_derivatives_signature (f : Set Γ → ℝ) (hf : ∀ A, 0 < f A) + (hsig : ∀ A, CommonBasesFPRAS.OnePositive (faceHessian f A).toBilin') + (ds : List (Γ → ℝ)) (hds : ∀ a ∈ ds, ∀ i, 0 ≤ a i) (A : Set Γ) : + CommonBasesFPRAS.OnePositive (faceHessian (coeffDerivs ds f) A).toBilin' := by + let F : ℝ → Matrix {i // i ∉ A} {i // i ∉ A} ℝ := fun t => + faceHessian (coeffDerivs (ds.map (fun a i => a i + t)) f) A + have hzero : F 0 = faceHessian (coeffDerivs ds f) A := by simp [F] + rw [← hzero] + let l := nhdsWithin (0 : ℝ) (Set.Ioi 0) + have : l.NeBot := nhdsWithin_Ioi_neBot (le_refl (0 : ℝ)) + apply onePositive_of_tendsto (l := l) F (F 0) + · intro i j + have hc : Continuous (fun t => F t i j) := by + dsimp [F, faceHessian] + by_cases hij : i = j + · simp only [ite_eq_left hij]; exact continuous_const + · simp only [ite_eq_right hij] + exact continuous_coeffDerivs_perturb ds f _ + exact hc.continuousAt.tendsto.mono_left nhdsWithin_le_nhds + · exact fun t => faceHessian_symm _ A + · have hpos : ∀ᶠ t in l, 0 < t := self_mem_nhdsWithin + filter_upwards [hpos] with t ht + apply (positive_derivatives_signature f hf hsig _ _).2 A + intro b hb i + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hb + exact add_pos_of_nonneg_of_pos (hds a ha i) ht + +/-- All retained-coordinate slot signatures of the completion are proved. +The original input is only the single valid-degree addition property. -/ +theorem completeDegree_hasSlotSignature (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) : + HasSlotSignature (completeDegree f k) := by + intro ps A + apply nonnegative_derivatives_signature _ (completeDegree_positive f k hf) + (completeDegree_face_signature f k hsig) _ _ A + intro a ha i + obtain ⟨p, _, rfl⟩ := List.mem_map.mp ha + exact slotDirection_nonneg _ i + +/-- Every nonzero derivative term adds precisely one new element; no +fresh-pair or disjointness assumption is needed for this congruence. -/ +lemma coeffDerivs_degree_congr (ds : List (Γ → ℝ)) (f g : Set Γ → ℝ) (k : ℕ) + (heq : ∀ S, S.ncard = k → f S = g S) (A : Set Γ) + (hdegree : A.ncard + ds.length = k) : coeffDerivs ds f A = coeffDerivs ds g A := by + induction ds generalizing A with + | nil => exact heq A (by simpa using hdegree) + | cons a ds ih => + change coeffDeriv a (coeffDerivs ds f) A = coeffDeriv a (coeffDerivs ds g) A + unfold coeffDeriv + apply Finset.sum_congr rfl + intro i _ + by_cases hi : i ∈ A + · simp only [ite_eq_left hi] + · simp only [ite_eq_right hi] + congr 1 + apply ih (insert i A) + rw [ncard_insert_eq A i hi] + simp only [List.length_cons] at hdegree + omega + +lemma slotTotal_completeDegree (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) : + slotTotal ps (completeDegree f k) A = slotTotal ps f A := by + apply coeffDerivs_degree_congr _ _ _ k + · intro S hS + simp [completeDegree, hS] + · simpa only [List.length_map] using hdegree + +/-- The full retained-coordinate matrix at its valid degree inherits the +signature, including coordinates of previously contracted pairs. -/ +theorem slot_face_signature_degree (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) (A : Set Γ) + (hdegree : A.ncard + ps.length + 2 = k) : + CommonBasesFPRAS.OnePositive (faceHessian (slotTotal ps f) A).toBilin' := by + have heq : faceHessian (slotTotal ps (completeDegree f k)) A = + faceHessian (slotTotal ps f) A := by + ext i j + by_cases hij : i = j + · simp [faceHessian, hij] + simp only [faceHessian, hij, ite_false] + apply slotTotal_completeDegree + rw [ncard_union_pair A i j hij] + omega + rw [← heq] + exact completeDegree_hasSlotSignature f k hf hsig ps A + +lemma slotDefect_completeDegree (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) (hps : SlotsFresh ps A) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + slotDefect ps (completeDegree f k) A p r = slotDefect ps f A p r := by + have hperm := slots_perm_two hp hr hpr + have hh := (SlotsFresh.perm hperm A).mp hps + have hrA : r.1 ∉ A := fun h => hh.2.2.2.2.1 (Or.inr (Or.inr h)) + have hrB : r.2 ∉ A := fun h => hh.2.2.2.2.2.1 (Or.inr (Or.inr h)) + unfold slotDefect + apply slotTotal_completeDegree + rw [ncard_insert_eq _ r.1 (by simp only [Set.mem_insert_iff, not_or]; exact ⟨hh.2.2.2.1, hrA⟩), + ncard_insert_eq A r.2 hrB] + have hlen := hperm.length_eq + simp only [List.length_cons] at hlen + omega + +/-- Actual two-pair masses satisfy the determinant bound on their valid +cardinality layer; completion disappears from the conclusion. -/ +theorem slotDefect_pair_bound_degree (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) (hps : SlotsFresh ps A) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + 4 * slotDefect ps f A p r * slotDefect ps f A r p ≤ (slotTotal ps f A)^2 := by + have h := slotDefect_pair_bound ps (completeDegree f k) (completeDegree_positive f k hf) + (completeDegree_hasSlotSignature f k hf hsig) A hps p r hp hr hpr + rwa [slotDefect_completeDegree ps f k A hdegree hps p r hp hr hpr, + slotDefect_completeDegree ps f k A hdegree hps r p hr hp hpr.symm, + slotTotal_completeDegree ps f k A hdegree] at h + +/-- Actual three-pair masses satisfy the cross-entry bound, obtained from +full cubic contraction while retaining the contracted pair coordinates. -/ +theorem slotDefect_triple_bound_degree (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) (hps : SlotsFresh ps A) + (p r t : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) + (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : + slotDefect ps f A p r * slotDefect ps f A r t ≤ + slotTotal ps f A * slotDefect ps f A p t := by + have h := slotDefect_triple_bound ps (completeDegree f k) (completeDegree_positive f k hf) + (completeDegree_hasSlotSignature f k hf hsig) A hps p r t hp hr ht hpr hrt hpt + rwa [slotDefect_completeDegree ps f k A hdegree hps p r hp hr hpr, + slotDefect_completeDegree ps f k A hdegree hps r t hr ht hrt, + slotDefect_completeDegree ps f k A hdegree hps p t hp ht hpt, + slotTotal_completeDegree ps f k A hdegree] at h + +end ContingencyTables.DegreeCompletion + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..96d2da51125551a380965b9a2e72bbfa6163dc81 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSBounds.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Machines.DirectedBFSProgram + +namespace OAI + +/-! # Polynomial size of the materialized BFS path store -/ + +namespace ContingencyTables.DirectedBFSBounds + +open MatchingFPRAS.TreeTyped DirectedBFSCode + +def Bounded (P : Store) (B : ℕ) : Prop := ∀ o∈P,weight o≤B + +lemma none_weight : weight (none : Option (List ℕ))≤5 := by decide + +lemma lookup_weight (P : Store) (B : ℕ) (hB : 5≤B) (hP : Bounded P B) (v : ℕ) : + weight (lookup P v)≤B := by + by_cases hv : v + have h := lookup_weight P B hB hP v + simp only [hc] at h + simpa only [roundRow,hc] using h.trans (by omega) + | none => + cases hp : predecessor g P v with + | none => + simpa only [roundRow,hc,hp,Option.bind_none] using none_weight.trans (by omega) + | some u => + cases hu : lookup P u with + | none => + simpa only [roundRow,hc,hp,Option.bind_some,hu,Option.map_none] using + none_weight.trans (by omega) + | some xs => + have h := lookup_weight P B hB hP u + simp only [hu] at h + simp only [roundRow,hc,hp,Option.bind_some,hu,Option.map_some,append_weight] + omega + +lemma round_bounded (g : Graph) (P : Store) (B : ℕ) (hB : 5≤B) + (hP : Bounded P B) : Bounded (round g P) (B+4*g.length+2) := by + intro o ho + obtain ⟨v,hv,rfl⟩ := List.mem_map.mp ho + exact row_weight g P B hB hP v (List.mem_range.mp hv) + +lemma round_length (g : Graph) (P : Store) : (round g P).length=g.length := by + simp [DirectedBFSCode.round] + +lemma fold_bounded (g : Graph) (P : Store) (B : ℕ) (hB : 5≤B) + (hP : Bounded P B) (steps : List ℕ) : + Bounded (steps.foldl (fun P _=>round g P) P) (B+steps.length*(4*g.length+2)) := by + induction steps generalizing P B with + | nil => simpa using hP + | cons a steps ih => + have h := ih (round g P) (B+4*g.length+2) (by omega) (round_bounded g P B hB hP) + have he : B+(a::steps).length*(4*g.length+2)= + B+4*g.length+2+steps.length*(4*g.length+2) := by + simp only [List.length_cons] + ring + rw [List.foldl_cons,he] + exact h + +lemma fold_length_le (g : Graph) (P : Store) (steps : List ℕ) : + (steps.foldl (fun P _=>round g P) P).length≤ max P.length g.length := by + induction steps generalizing P with + | nil => exact le_max_left _ _ + | cons a steps ih => + have h := ih (round g P) + simp only [List.foldl_cons] + exact h.trans (by rw [round_length,max_self]; exact le_max_right _ _) + +lemma store_weight (P : Store) (B : ℕ) (hP : Bounded P B) : + weight P≤P.length*(B+1)+1 := by + have h := weight_map_bound (as:=P) (f:=id) (N:=B) hP + simpa only [List.map_id] using h + +lemma initial_bounded (g : Graph) (s : ℕ) : Bounded (initial g s) (weight s+10) := by + intro o ho + obtain ⟨v,_,rfl⟩ := List.mem_map.mp ho + by_cases h : v=s + · simp only [h,ite_true] + change weight (true,[s])≤weight s+10 + have hb := weight_bool_le true + simp only [weight_prod,weight_cons,weight_nil] + omega + · simpa only [h,ite_false] using none_weight.trans (by omega) + +lemma initial_length (g : Graph) (s : ℕ) : (initial g s).length=g.length := by + simp [initial] + +end ContingencyTables.DirectedBFSBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..580222884b66061cf553c68179af9ad12f33a15d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/DirectedBFSCode.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDirectedBFS +import Mathlib.Data.List.OfFn + +namespace OAI + +/-! # Materialized breadth-first path tables + +Every round reads the preceding path table and writes one table of the +same size. Consequently evaluation does not recursively recompute old +rounds when different vertices ask for their predecessors. +-/ + +namespace ContingencyTables.DirectedBFSCode + +abbrev Graph := List (List Bool) +abbrev Store := List (Option (List ℕ)) + +def adjacent (g : Graph) (u v : ℕ) : Bool := (g.getD u []).getD v false +def lookup (P : Store) (v : ℕ) : Option (List ℕ) := P.getD v none + +def predecessor (g : Graph) (P : Store) (v : ℕ) : Option ℕ := + (List.range g.length).find? (fun u=>(lookup P u).isSome && adjacent g u v) + +def roundRow (g : Graph) (P : Store) (v : ℕ) : Option (List ℕ) := + match lookup P v with + | some xs => some xs + | none => (predecessor g P v).bind (fun u=>(lookup P u).map (fun xs=>xs++[v])) + +def round (g : Graph) (P : Store) : Store := + (List.range g.length).map (roundRow g P) + +def initial (g : Graph) (s : ℕ) : Store := + (List.range g.length).map (fun v=>if v=s then some [s] else none) + +def run (g : Graph) (s : ℕ) : Store := + (List.range g.length).foldl (fun P _=>round g P) (initial g s) + +def search (g : Graph) (s t : ℕ) : Option (List ℕ) := lookup (run g s) t + +def graphCode {n : ℕ} (E : Fin n → Fin n → Bool) : Graph := + List.ofFn (fun u=>List.ofFn (E u)) + +def storeCode {n : ℕ} (P : FiniteDirectedBFS.Paths n) : Store := + List.ofFn (fun u=>(P u).map (List.map Fin.val)) + +lemma range_eq_map (n : ℕ) : List.range n=(List.finRange n).map Fin.val := by + apply List.ext_getElem <;> simp + +lemma adjacent_graphCode {n : ℕ} (E : Fin n → Fin n → Bool) (u v : Fin n) : + adjacent (graphCode E) u.val v.val=E u v := by + simp [adjacent,graphCode,List.getD_eq_getElem?_getD,u.isLt,v.isLt] + +lemma lookup_storeCode {n : ℕ} (P : FiniteDirectedBFS.Paths n) (v : Fin n) : + lookup (storeCode P) v.val=(P v).map (List.map Fin.val) := by + simp [lookup,storeCode,List.getD_eq_getElem?_getD,v.isLt] + +lemma predecessor_code {n : ℕ} (E : Fin n → Fin n → Bool) + (P : FiniteDirectedBFS.Paths n) (v : Fin n) : + predecessor (graphCode E) (storeCode P) v.val= + (FiniteDirectedBFS.predecessor E P v).map Fin.val := by + have hlen : (graphCode E).length=n := by simp [graphCode] + simp only [predecessor,hlen,range_eq_map,List.find?_map] + congr 1 + apply congrArg (fun f=>(List.finRange n).find? f) + funext u + simp only [Function.comp_apply,lookup_storeCode,Option.isSome_map,adjacent_graphCode] + +lemma roundRow_code {n : ℕ} (E : Fin n → Fin n → Bool) + (P : FiniteDirectedBFS.Paths n) (v : Fin n) : + roundRow (graphCode E) (storeCode P) v.val= + (FiniteDirectedBFS.round E P v).map (List.map Fin.val) := by + simp only [roundRow,lookup_storeCode,predecessor_code,FiniteDirectedBFS.round] + cases hp : P v with + | some xs => rfl + | none => + cases hu : FiniteDirectedBFS.predecessor E P v with + | none => rfl + | some u => + simp only [Option.map_some,Option.bind_some,lookup_storeCode] + cases hpu : P u <;> simp [List.map_append] + +lemma round_code {n : ℕ} (E : Fin n → Fin n → Bool) (P : FiniteDirectedBFS.Paths n) : + round (graphCode E) (storeCode P)=storeCode (FiniteDirectedBFS.round E P) := by + simp only [round,graphCode,List.length_ofFn,range_eq_map,List.map_map] + rw [←List.ofFn_eq_map] + unfold storeCode + apply congrArg List.ofFn + funext v + exact roundRow_code E P v + +lemma initial_code {n : ℕ} (E : Fin n → Fin n → Bool) (s : Fin n) : + initial (graphCode E) s.val=storeCode (FiniteDirectedBFS.paths E s 0) := by + simp only [initial,graphCode,List.length_ofFn,range_eq_map,List.map_map] + rw [←List.ofFn_eq_map] + unfold storeCode + apply congrArg List.ofFn + funext v + by_cases h : v=s + · subst v; simp [FiniteDirectedBFS.paths] + · have hv : v.val≠s.val := fun he=>h (Fin.ext he) + simp [Function.comp_apply,FiniteDirectedBFS.paths,h,hv] + +lemma fold_round_code {n : ℕ} (E : Fin n → Fin n → Bool) (s : Fin n) (k : ℕ) : + (List.range k).foldl (fun P _=>round (graphCode E) P) (initial (graphCode E) s.val)= + storeCode (FiniteDirectedBFS.paths E s k) := by + induction k with + | zero => simpa using initial_code E s + | succ k ih => + rw [List.range_succ,List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil,ih,round_code,FiniteDirectedBFS.paths] + +theorem run_code {n : ℕ} (E : Fin n → Fin n → Bool) (s : Fin n) : + run (graphCode E) s.val=storeCode (FiniteDirectedBFS.paths E s n) := by + simpa only [run,graphCode,List.length_ofFn] using fold_round_code E s n + +theorem search_code {n : ℕ} (E : Fin n → Fin n → Bool) (s t : Fin n) : + search (graphCode E) s.val t.val= + (FiniteDirectedBFS.paths E s n t).map (List.map Fin.val) := by + rw [search,run_code,lookup_storeCode] + +end ContingencyTables.DirectedBFSCode + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..a65bb57ae8050d56ffa4e77492f23f8b8da575e7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicAcceptance.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRational +import Mathlib.Data.Fintype.Fin + +namespace OAI + +/-! # Exact finite-bit Metropolis acceptance + +A uniform integer encoded by the allotted fair bits is compared with a +power of two. Extra bits are padding; their number does not change the +acceptance probability. +-/ + +namespace ContingencyTables.FairBits + +open scoped BigOperators + +abbrev acceptDyadic (gap allowance : ℕ) (z : Fin (2 ^ allowance)) : Prop := + z.val < 2 ^ (allowance - gap) + +theorem acceptDyadic_count (gap allowance : ℕ) : + (Finset.univ.filter (acceptDyadic gap allowance)).card = 2 ^ (allowance - gap) := by + change (Finset.univ.filter (fun z : Fin (2 ^ allowance) => z.val < 2 ^ (allowance - gap))).card = _ + rw [Fin.card_filter_val_lt, min_eq_right] + exact Nat.pow_le_pow_right (by decide) (Nat.sub_le _ _) + +theorem acceptDyadic_probability (gap allowance : ℕ) (h : gap ≤ allowance) : + ((Finset.univ.filter (acceptDyadic gap allowance)).card : ℝ) / (2 : ℝ) ^ allowance = + 1 / (2 : ℝ) ^ gap := by + rw [acceptDyadic_count gap allowance, Nat.cast_pow, Nat.cast_ofNat] + have ha : allowance = (allowance - gap) + gap := by omega + have hden : (2 : ℝ) ^ allowance = 2 ^ (allowance - gap) * 2 ^ gap := by + conv_lhs => rw [ha, pow_add] + rw [hden] + simpa only [one_div] using div_mul_cancel_left₀ + (by positivity : (2 : ℝ) ^ (allowance - gap) ≠ 0) ((2 : ℝ) ^ gap) + +theorem dyadic_ratio_min (a b : ℕ) : + min (1 : ℝ) ((1 / (2 : ℝ) ^ b) / (1 / (2 : ℝ) ^ a)) = + 1 / (2 : ℝ) ^ (b - a) := by + by_cases hab : a ≤ b + · have he : b = a + (b - a) := by omega + have hr : ((1 / (2 : ℝ) ^ b) / (1 / (2 : ℝ) ^ a)) = 1 / (2 : ℝ) ^ (b - a) := by + conv_lhs => rw [he, pow_add] + field_simp + rw [hr, min_eq_right] + simpa only [div_one] using one_div_le_one_div_of_le (by norm_num : (0 : ℝ) < 1) + (show (1 : ℝ) ≤ 2 ^ (b - a) from one_le_pow₀ (by norm_num)) + · have hba : b ≤ a := by omega + have he : a = b + (a - b) := by omega + have hr : ((1 / (2 : ℝ) ^ b) / (1 / (2 : ℝ) ^ a)) = (2 : ℝ) ^ (a - b) := by + conv_lhs => rw [he, pow_add] + field_simp + rw [hr, Nat.sub_eq_zero_of_le hba, pow_zero, div_one, min_eq_left] + exact one_le_pow₀ (by norm_num) + +end ContingencyTables.FairBits + +namespace ContingencyTables.GridBoundary + +open scoped Classical + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q K : ℕ} + +theorem dense_acceptance_dyadic (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) K) : + min (1 : ℝ) (denseBinWeight R P d e b / denseBinWeight R P d e a) = + 1 / (2 : ℝ) ^ (denseExponent R P d e b - denseExponent R P d e a) := by + simp only [denseBinWeight_eq_dyadic] + exact FairBits.dyadic_ratio_min _ _ + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicRootBisection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicRootBisection.lean new file mode 100644 index 0000000000000000000000000000000000000000..7242b087e822f8fc32524b7f4423e8b7b49f020a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/DyadicRootBisection.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalRootBisection +import OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction + +namespace OAI + +/-! # Integer implementation of the correction-root bisection + +The two interval endpoints share one dyadic denominator. Every comparison +is an inequality between natural powers and products. This is the literal +integer algorithm to which the rational correction analysis is applied. +-/ + +namespace ContingencyTables.DyadicRootBisection + +open MatchingFPRAS + +abbrev State := (ℕ×ℕ)×ℕ + +def value (z : State) : ℚ×ℚ := ((z.1.1:ℚ)/z.2,(z.1.2:ℚ)/z.2) + +def advance (c : TreeFraction.Fraction) (s : ℕ) (z : State) : State := + if (z.1.1+z.1.2)^s*c.2 ≤ c.1*(2*z.2)^s + then ((z.1.1+z.1.2,2*z.1.2),2*z.2) + else ((2*z.1.1,z.1.1+z.1.2),2*z.2) + +def run (c : TreeFraction.Fraction) (s : ℕ) : ℕ→State + | 0=>((0,8),1) + | n+1=>advance c s (run c s n) + +def output (c : TreeFraction.Fraction) (s n : ℕ) : TreeFraction.Fraction := + let z:=run c s n + TreeFraction.normalize (z.1.1+z.1.2,2*z.2) + +lemma compare_iff (a d p q s : ℕ) (hd : 0 rfl + +lemma run_denominator (c : TreeFraction.Fraction) (s n : ℕ) : + (run c s n).2=2^n := by + induction n with + | zero=>rfl + | succ n ih=>simp only [run,advance_denominator,ih,pow_succ,mul_comm] + +lemma advance_bounds (c : TreeFraction.Fraction) (s : ℕ) (z : State) + (ha : z.1.1≤8*z.2) (hb : z.1.2≤8*z.2) : + (advance c s z).1.1≤8*(advance c s z).2 ∧ + (advance c s z).1.2≤8*(advance c s z).2 := by + unfold advance + split_ifs <;> dsimp only <;> omega + +lemma run_bounds (c : TreeFraction.Fraction) (s n : ℕ) : + (run c s n).1.1≤8*2^n ∧ (run c s n).1.2≤8*2^n := by + induction n with + | zero=>norm_num [run] + | succ n ih=> + have h:=advance_bounds c s (run c s n) + (by simpa only [run_denominator] using ih.1) + (by simpa only [run_denominator] using ih.2) + change (run c s (n+1)).1.1≤8*(run c s (n+1)).2 ∧ + (run c s (n+1)).1.2≤8*(run c s (n+1)).2 at h + simpa only [run_denominator] using h + +lemma value_advance (c : TreeFraction.Fraction) (hc : 0norm_num [run,value,RationalRootBisection.interval] + | succ n ih=> + rw [run,value_advance c hc s _ (by rw [run_denominator]; positivity),ih] + rfl + +theorem output_value (c : TreeFraction.Fraction) (hc : 0 0 + | k+1 => advance c s t (run c s t k) + +def maxFlow (c : Capacity n) (s t : Fin n) : Flow n := run c s t (n^3+1) + +lemma zero_feasible (c : Capacity n) (s t : Fin n) : Feasible c s t 0 := by + refine ⟨?_,?_,?_⟩ + · intro u v; simp + · intro u v + change (0:ℤ)≤(c u v:ℤ) + exact_mod_cast Nat.zero_le (c u v) + · intro u _ _; simp + +lemma run_feasible (c : Capacity n) (s t : Fin n) (hst : s≠t) (k : ℕ) : + Feasible c s t (run c s t k) := by + induction k with + | zero => exact zero_feasible c s t + | succ k ih => + cases hs : step c s t (run c s t k) with + | none => simpa only [run,advance,hs,Option.getD_none] using ih + | some g => + simpa only [run,advance,hs,Option.getD_some] using + step_feasible c s t hst (run c s t k) g ih hs + +lemma run_step (c : Capacity n) (s t : Fin n) (k : ℕ) (g : Flow n) + (h : step c s t (run c s t k)=some g) : run c s t (k+1)=g := by + simp only [run,advance,h,Option.getD_some] + +lemma run_stops (c : Capacity n) (s t : Fin n) (k : ℕ) + (h : step c s t (run c s t k)=none) (j : ℕ) : + run c s t (k+j)=run c s t k := by + induction j with + | zero => simp + | succ j ih => + rw [Nat.add_succ,run,ih,advance,h,Option.getD_none] + +theorem termination (hEK : EdmondsKarp1972Theorem1) + (c : Capacity n) (hc : ∀ u,c u u=0) (s t : Fin n) (hst : s≠t) : + ∃ i≤n^3,step c s t (run c s t i)=none := by + by_contra hn + have hsome : ∀ i≤n^3,∃ g,step c s t (run c s t i)=some g := by + intro i hi + cases hs : step c s t (run c s t i) with + | none => exact False.elim (hn ⟨i,hi,hs⟩) + | some g => exact ⟨g,rfl⟩ + let F : Fin (n^3+2) → Flow n := fun i=>run c s t i.val + have hF : AugmentationTrace c s t F := by + refine ⟨rfl,?_,?_⟩ + · intro i + exact run_feasible c s t hst i.val + · intro i + obtain ⟨g,hg⟩ := hsome i.val (by have hi:=i.isLt; omega) + have he : F i.succ=g := run_step c s t i.val g hg + rw [he] + exact step_augmentation c s t hst (F i.castSucc) g hg + exact no_long_trace hEK c hc s t hst F hF + +theorem maxFlow_correct (hEK : EdmondsKarp1972Theorem1) + (c : Capacity n) (hc : ∀ u,c u u=0) (s t : Fin n) (hst : s≠t) : + IsMaximum c s t (maxFlow c s t) := by + obtain ⟨i,hi,hs⟩ := termination hEK c hc s t hst + have hstop := run_stops c s t i hs (n^3+1-i) + have he : i+(n^3+1-i)=n^3+1 := by omega + rw [he] at hstop + unfold maxFlow + rw [hstop] + exact step_none_maximum c s t (run c s t i) (run_feasible c s t hst i) hs + +end ContingencyTables.EdmondsKarpAlgorithm + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpAugmentation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpAugmentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7189a2e308036568989d0ad341b3851185af51c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpAugmentation.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpDistance +import OAI.Combinatorics.ContingencyTables.Transport.PathAugmentation + +namespace OAI + +/-! # Label monotonicity and critical arcs of a shortest augmentation -/ +namespace ContingencyTables.EdmondsKarpAugmentation +open PublishedEdmondsKarp PathAugmentation EdmondsKarpDistance +open scoped Classical +noncomputable section +variable {n k : ℕ} + +lemma reverse_count_zero (p : Fin (k+1)→Fin n) (hp : Function.Injective p) (i : Fin k) : + arcCount p (p i.succ) (p i.castSucc)=0 := by + apply arcCount_eq_zero + rintro ⟨j,hj,hi⟩ + have h1 := congrArg Fin.val (hp hj) + have h2 := congrArg Fin.val (hp hi) + simp only [Fin.val_castSucc,Fin.val_succ] at h1 h2 + omega + +lemma update_decrease (f : Flow n) (p : Fin (k+1)→Fin n) (a : ℤ) (ha : 0 ≤ a) + (u v : Fin n) (h : update f p a u v < f u v) : + ∃ i : Fin k,p i.castSucc=v ∧ p i.succ=u := by + by_contra hn + have hz : arcCount p v u=0 := arcCount_eq_zero p v u hn + have hc := arcCount_nonneg p u v + have hprod := mul_nonneg ha hc + simp only [update,hz,sub_zero] at h + omega + +lemma update_new_edge (c : Capacity n) (f : Flow n) (p : Fin (k+1)→Fin n) + (a : ℤ) (ha : 0 ≤ a) (u v : Fin n) + (h : 0 < (c u v:ℤ)-update f p a u v) : + 0 < (c u v:ℤ)-f u v ∨ ∃ i : Fin k,p i.castSucc=v ∧ p i.succ=u := by + by_cases hold : 0 < (c u v:ℤ)-f u v + · exact Or.inl hold + · exact Or.inr (update_decrease f p a ha u v (by omega)) + +lemma update_saturates (c : Capacity n) (f : Flow n) (p : Fin (k+1)→Fin n) + (hp : Function.Injective p) (a : ℤ) (i : Fin k) + (ha : a=(c (p i.castSucc) (p i.succ):ℤ)-f (p i.castSucc) (p i.succ)) : + update f p a (p i.castSucc) (p i.succ)=c (p i.castSucc) (p i.succ) := by + rw [update,arcCount_eq_one p hp i,reverse_count_zero p hp i] + omega + +/-- All old distance labels remain valid lower potentials for the new +residual graph, including arcs created by cancellation of flow. -/ +theorem labels_monotone {c : Capacity n} {s t : Fin n} {f g : Flow n} + (h : ShortestAugmentation c s t f g) (v : Fin n) : label c f s v ≤ label c g s v := by + obtain ⟨k,p,a,hp,hshort,ha,_,_,hg⟩ := h + have he : g=update f p a := funext (fun u => funext (hg u)) + apply potential_le_distance (ResidualSearch.edge c g) s (label c f s) + (label_source c f s) (label_le c f s) + intro u v huv + have hres : 0 < (c u v:ℤ)-g u v := of_decide_eq_true huv + rw [he] at hres + rcases update_new_edge c f p a ha.le u v hres with hold|⟨i,hi,hj⟩ + · exact label_edge hold + · have h1 := label_path hp hshort i.castSucc + have h2 := label_path hp hshort i.succ + rw [hi] at h1 + rw [hj] at h2 + simp only [Fin.val_castSucc,Fin.val_succ] at h1 h2 + omega + +/-- A decrease of flow on (u,v) means the augmentation used (v,u). +Consequently u was one distance layer beyond v. -/ +theorem decrease_labels {c : Capacity n} {s t : Fin n} {f g : Flow n} + (h : ShortestAugmentation c s t f g) (u v : Fin n) (hdec : g u v < f u v) : + label c f s u=label c f s v+1 := by + obtain ⟨k,p,a,hp,hshort,ha,_,_,hg⟩ := h + have he : g=update f p a := funext (fun u => funext (hg u)) + rw [he] at hdec + obtain ⟨i,hi,hj⟩ := update_decrease f p a ha.le u v hdec + have h1 := label_path hp hshort i.castSucc + have h2 := label_path hp hshort i.succ + rw [hi] at h1 + rw [hj] at h2 + simp only [Fin.val_castSucc,Fin.val_succ] at h1 h2 + omega + +/-- Each augmentation has an arc which was residual, becomes saturated, +and points from one finite distance layer to the next. -/ +theorem critical_arc {c : Capacity n} {s t : Fin n} {f g : Flow n} + (h : ShortestAugmentation c s t f g) : + ∃ u v : Fin n,f u v < (c u v:ℤ) ∧ g u v=(c u v:ℤ) ∧ + label c f s v=label c f s u+1 ∧ label c f s u < n := by + obtain ⟨k,p,a,hp,hshort,ha,_,⟨i,hsat⟩,hg⟩ := h + have he : g=update f p a := funext (fun u => funext (hg u)) + refine ⟨p i.castSucc,p i.succ,?_,?_,?_,?_⟩ + · have hr := hp.2.2.2 i + omega + · rw [he] + exact update_saturates c f p hp.2.2.1 a i hsat + · rw [label_path hp hshort i.castSucc,label_path hp hshort i.succ] + rfl + · exact label_path_lt hp hshort i.castSucc + +end +end ContingencyTables.EdmondsKarpAugmentation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..c68c4c3bae2abeae5796094d93cb8dace5ccb15f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpBound.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpTrace + +namespace OAI + +/-! +# The shortest-augmentation bound + +Charge an augmentation to a critical directed arc and its previous tail +label. A repeated directed arc has strictly larger label, so the charge +is injective into n×n×n. +-/ +namespace ContingencyTables.EdmondsKarpBound +open PublishedEdmondsKarp EdmondsKarpDistance EdmondsKarpAugmentation EdmondsKarpTrace +open scoped Classical +noncomputable section +variable {n K : ℕ} + +theorem shortest_trace_bound (c : Capacity n) (s t : Fin n) (F : Fin (K+1)→Flow n) + (h : ∀ i : Fin K,ShortestAugmentation c s t (F i.castSucc) (F i.succ)) : K ≤ n^3 := by + choose u v hu using (fun i : Fin K => critical_arc (h i)) + let code : Fin K→Fin n×Fin n×Fin n := fun i => + (u i,v i,⟨label c (F i.castSucc) s (u i),(hu i).2.2.2⟩) + have hordered (i j : Fin K) (hij : i < j) (huv : u i=u j) (hvv : v i=v j) : + label c (F i.castSucc) s (u i) < label c (F j.castSucc) s (u j) := by + have hres : F j.castSucc (u i) (v i) < (c (u i) (v i):ℤ) := by + simpa only [huv,hvv] using (hu j).1 + have hr := repeated_critical h i j hij (u i) (v i) (hu i).2.1 (hu i).2.2.1 hres + rw [←huv] + omega + have hinj : Function.Injective code := by + intro i j he + have huij := congrArg Prod.fst he + have hvij := congrArg (fun p : Fin n×Fin n×Fin n => p.2.1) he + have hdij := congrArg (fun p : Fin n×Fin n×Fin n => p.2.2.val) he + dsimp only [code] at huij hvij hdij + by_contra hne + rcases lt_or_gt_of_ne hne with hij|hji + · exact (ne_of_lt (hordered i j hij huij hvij)) hdij + · exact (ne_of_lt (hordered j i hji huij.symm hvij.symm)) hdij.symm + have hc := Fintype.card_le_of_injective code hinj + simpa only [Fintype.card_fin,Fintype.card_prod,pow_succ,pow_zero,mul_one,one_mul,mul_assoc] using hc + +/-- Edmonds and Karp (1972), Theorem 1, in the exact integral-skew-flow +specialization for the sampling and counting algorithms. -/ +theorem edmondsKarp1972Theorem1 : EdmondsKarp1972Theorem1 := by + intro n c _ s t _ K F hF + exact shortest_trace_bound c s t F hF.2.2 + +end +end ContingencyTables.EdmondsKarpBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpDistance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpDistance.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1cf290757184fc66369c6a17b5eebb40391cbae --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpDistance.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ResidualSearch + +namespace OAI + +/-! # Bounded shortest-path labels for Edmonds--Karp + +An unreachable vertex has label n. Reachable vertices have their actual +shortest distance, at most n-1. These labels are obtained from the already +proved breadth-first search, independently of its deterministic tie rule. +-/ +namespace ContingencyTables.EdmondsKarpDistance +open FiniteDirectedBFS PublishedEdmondsKarp +open scoped Classical +noncomputable section +variable {n : ℕ} + +def distance (E : Fin n→Fin n→Bool) (s v : Fin n) : ℕ := + ((paths E s n v).map (fun xs => xs.length-1)).getD n + +lemma distance_of_some {E : Fin n→Fin n→Bool} {s v : Fin n} {xs : List (Fin n)} + (h : paths E s n v=some xs) : distance E s v=xs.length-1 := by + simp only [distance,h,Option.map_some,Option.getD_some] + +lemma distance_of_none {E : Fin n→Fin n→Bool} {s v : Fin n} + (h : paths E s n v=none) : distance E s v=n := by + simp only [distance,h,Option.map_none,Option.getD_none] + +lemma distance_le (E : Fin n→Fin n→Bool) (s v : Fin n) : distance E s v ≤ n := by + cases h : paths E s n v with + | none => exact (distance_of_none h).le + | some xs => + rw [distance_of_some h] + have hl := paths_length_le h + omega + +lemma distance_lt_of_some {E : Fin n→Fin n→Bool} {s v : Fin n} {xs : List (Fin n)} + (h : paths E s n v=some xs) : distance E s v < n := by + rw [distance_of_some h] + have hl := paths_length_le h + have hp := (paths_sound h).1.length_pos + omega + +lemma distance_source (E : Fin n→Fin n→Bool) (s : Fin n) : distance E s s=0 := by + obtain ⟨xs,hxs⟩ := source_found E s + rw [distance_of_some hxs] + have hshort := paths_shortest hxs [s] Route.start + simp only [List.length_singleton] at hshort + omega + +lemma distance_route {E : Fin n→Fin n→Bool} {s v : Fin n} {xs : List (Fin n)} + (h : Route E s v xs) : distance E s v ≤ xs.length-1 := by + obtain ⟨ys,hys⟩ := route_found h + rw [distance_of_some hys] + exact Nat.sub_le_sub_right (paths_shortest hys xs h) 1 + +lemma distance_edge {E : Fin n→Fin n→Bool} {s u v : Fin n} + (he : E u v=true) : distance E s v ≤ distance E s u+1 := by + cases h : paths E s n u with + | none => + rw [distance_of_none h] + exact (distance_le E s v).trans (Nat.le_succ n) + | some xs => + have hr := (paths_sound h).1 + have hv := distance_route (hr.extend he) + rw [distance_of_some h] + simp only [List.length_append,List.length_singleton] at hv + have hp := hr.length_pos + omega + +lemma route_potential {E : Fin n→Fin n→Bool} {s v : Fin n} {xs : List (Fin n)} + (d : Fin n→ℕ) (hzero : d s=0) + (hedge : ∀ u v,E u v=true → d v ≤ d u+1) + (h : Route E s v xs) : d v ≤ xs.length-1 := by + induction h with + | start => simp only [hzero,List.length_singleton,Nat.sub_self,le_refl] + | @extend u v xs hr huv ih => + have he := hedge u v huv + have hp := hr.length_pos + simp only [List.length_append,List.length_singleton] + omega + +/-- Every bounded potential increasing by at most one on each edge lies +below the shortest-path labels. This also covers unreachable vertices. -/ +lemma potential_le_distance (E : Fin n→Fin n→Bool) (s : Fin n) (d : Fin n→ℕ) + (hzero : d s=0) (hbound : ∀ v,d v ≤ n) + (hedge : ∀ u v,E u v=true → d v ≤ d u+1) (v : Fin n) : + d v ≤ distance E s v := by + cases h : paths E s n v with + | none => simpa only [distance_of_none h] using hbound v + | some xs => + rw [distance_of_some h] + exact route_potential d hzero hedge (paths_sound h).1 + +/-- A unit-Lipschitz sequence attaining its maximal endpoint slope has +unit slope at every intermediate index. -/ +lemma tight_sequence {k : ℕ} (d : Fin (k+1)→ℕ) (hzero : d 0=0) + (hlast : d (Fin.last k)=k) + (hstep : ∀ i : Fin k,d i.succ ≤ d i.castSucc+1) : + ∀ i : Fin (k+1),d i=i.val := by + have hu : ∀ i : Fin (k+1),d i ≤ i.val := by + intro i + refine Fin.induction ?_ (fun j ih => ?_) i + · simpa only [Fin.val_zero,hzero] using (Nat.le_refl 0) + · have hs := hstep j + simp only [Fin.val_succ,Fin.val_castSucc] at * + omega + have hl : ∀ i : Fin (k+1),k ≤ d i+(k-i.val) := by + intro i + refine Fin.reverseInduction ?_ (fun j ih => ?_) i + · simp only [Fin.val_last,hlast,Nat.sub_self,Nat.add_zero,le_refl] + · have hs := hstep j + have hj := j.isLt + simp only [Fin.val_succ,Fin.val_castSucc] at * + omega + intro i + have hupper := hu i + have hlower := hl i + have hi := i.isLt + omega + +def label (c : Capacity n) (f : Flow n) (s v : Fin n) : ℕ := + distance (ResidualSearch.edge c f) s v + +lemma label_le (c : Capacity n) (f : Flow n) (s v : Fin n) : label c f s v ≤ n := + distance_le _ _ _ + +lemma label_source (c : Capacity n) (f : Flow n) (s : Fin n) : label c f s s=0 := + distance_source _ _ + +lemma label_edge {c : Capacity n} {f : Flow n} {s u v : Fin n} + (h : 0 < (c u v:ℤ)-f u v) : label c f s v ≤ label c f s u+1 := + distance_edge (by simpa only [ResidualSearch.edge,decide_eq_true_eq] using h) + +lemma label_target {c : Capacity n} {f : Flow n} {s t : Fin n} {k : ℕ} + {p : Fin (k+1)→Fin n} (hp : ResidualPath c f s t k p) + (hshort : ∀ l q,ResidualPath c f s t l q → k ≤ l) : label c f s t=k := by + have hr := ResidualSearch.route_of_residual c f s t k p hp + obtain ⟨xs,hxs⟩ := route_found hr + obtain ⟨l,q,hq,hres,_⟩ := ResidualSearch.search_shortest c f s t xs hxs + have hkl := hshort l q hres + have hlen : xs.length=l+1 := by rw [hq,List.length_ofFn] + have hshorter := paths_shortest hxs (List.ofFn p) hr + simp only [List.length_ofFn] at hshorter + change distance (ResidualSearch.edge c f) s t=k + rw [distance_of_some hxs] + omega + +/-- Every vertex of a shortest residual augmenting path has its path +index as shortest distance from the source. -/ +theorem label_path {c : Capacity n} {f : Flow n} {s t : Fin n} {k : ℕ} + {p : Fin (k+1)→Fin n} (hp : ResidualPath c f s t k p) + (hshort : ∀ l q,ResidualPath c f s t l q → k ≤ l) (i : Fin (k+1)) : + label c f s (p i)=i.val := by + apply tight_sequence (fun j => label c f s (p j)) + · rw [hp.1,label_source] + · rw [hp.2.1] + exact label_target hp hshort + · intro j + exact label_edge (hp.2.2.2 j) + +lemma label_path_lt {c : Capacity n} {f : Flow n} {s t : Fin n} {k : ℕ} + {p : Fin (k+1)→Fin n} (hp : ResidualPath c f s t k p) + (hshort : ∀ l q,ResidualPath c f s t l q → k ≤ l) (i : Fin (k+1)) : + label c f s (p i) < n := by + rw [label_path hp hshort] + have hcard := Fintype.card_le_of_injective p hp.2.2.1 + simp only [Fintype.card_fin] at hcard + have hi := i.isLt + omega + +end +end ContingencyTables.EdmondsKarpDistance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpTrace.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f3549a9e4570f84f90943f40c500d0738d847bb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EdmondsKarpTrace.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpAugmentation +import Mathlib.Order.Fin.Basic + +namespace OAI + +/-! # Repeated critical arcs strictly increase their distance label -/ +namespace ContingencyTables.EdmondsKarpTrace +open PublishedEdmondsKarp EdmondsKarpDistance EdmondsKarpAugmentation +open scoped Classical +noncomputable section +variable {n K : ℕ} + +lemma descent_between (a : Fin (K+1)→ℤ) (i j : Fin (K+1)) (hij : i ≤ j) + (h : a j < a i) : + ∃ k : Fin K,i ≤ k.castSucc ∧ k.succ ≤ j ∧ a k.succ < a k.castSucc := by + by_contra hn + have hstep (k : Fin K) (hik : i ≤ k.castSucc) (hkj : k.succ ≤ j) : + a k.castSucc ≤ a k.succ := + le_of_not_gt (fun hlt => hn ⟨k,hik,hkj,hlt⟩) + have hm : ∀ u : Fin (K+1),i ≤ u → u ≤ j → a i ≤ a u := by + intro u + refine Fin.induction ?_ (fun k ih => ?_) u + · intro hi _ + change i.val ≤ 0 at hi + have he : i=0 := by + apply Fin.ext + simpa only [Fin.val_zero] using Nat.eq_zero_of_le_zero hi + subst i + exact le_rfl + · intro hi hj' + by_cases hik : i ≤ k.castSucc + · exact (ih hik ((Fin.castSucc_le_succ k).trans hj')).trans (hstep k hik hj') + · have he : i=k.succ := Fin.ext (by + change i.val ≤ k.val+1 at hi + change ¬i.val ≤ k.val at hik + change i.val=k.val+1 + omega) + rw [he] + exact (not_le_of_gt h) (hm j hij le_rfl) + +lemma labels_monotone {c : Capacity n} {s t : Fin n} {F : Fin (K+1)→Flow n} + (h : ∀ i : Fin K,ShortestAugmentation c s t (F i.castSucc) (F i.succ)) (v : Fin n) : + Monotone (fun i => label c (F i) s v) := by + apply Fin.monotone_iff_le_succ.mpr + intro i + exact EdmondsKarpAugmentation.labels_monotone (h i) v + +/-- Once (u,v) is saturated, using it again requires a reverse +augmentation and hence at least two more source-distance layers at u. -/ +theorem repeated_critical {c : Capacity n} {s t : Fin n} {F : Fin (K+1)→Flow n} + (h : ∀ i : Fin K,ShortestAugmentation c s t (F i.castSucc) (F i.succ)) + (i j : Fin K) (hij : i < j) (u v : Fin n) + (hsat : F i.succ u v=(c u v:ℤ)) + (hlevel : label c (F i.castSucc) s v=label c (F i.castSucc) s u+1) + (hres : F j.castSucc u v < (c u v:ℤ)) : + label c (F i.castSucc) s u+2 ≤ label c (F j.castSucc) s u := by + have hisj : i.succ ≤ j.castSucc := by + change i.val+1 ≤ j.val + exact hij + obtain ⟨k,hik,hkj,hdec⟩ := descent_between (fun q => F q u v) i.succ j.castSucc hisj + (by rw [hsat]; exact hres) + have hreverse := decrease_labels (h k) u v hdec + have hfirst := labels_monotone h v ((Fin.castSucc_le_succ i).trans hik) + have hlast := labels_monotone h u ((Fin.castSucc_le_succ k).trans hkj) + dsimp only at hfirst hlast + omega + +end +end ContingencyTables.EdmondsKarpTrace + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualityReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualityReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3eec7f0d99b68473e655b0d9635eb34dd21898d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualityReindex.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ReflectedSlices + +namespace OAI + +/-! +# Equality factors under the actual physical coordinate bijection + +A bijection of coordinates preserves the line totals and unary products. +Consequently the balanced marginal signature applies to the literal +physical factor family after all cell-index bookkeeping has been proved. +-/ + +namespace ContingencyTables.EqualityReindex + +open scoped BigOperators Classical +open ProductIntegerSignature EqualitySoftening BalancedFamily BalancedBox + +variable {C D G : Type*} [Fintype C] [Fintype D] [Fintype G] + +omit [Fintype G] in +lemma lineTotal_reindex (e : C ≃ D) (line : D → G) (z : C → ℕ) (g : G) : + lineTotal (line ∘ e) z g=lineTotal line (z ∘ e.symm) g := by + unfold lineTotal + have h := e.sum_comp (fun d => if line d=g then z (e.symm d) else 0) + simpa only [Function.comp_apply,Equiv.symm_apply_apply] using h + +lemma productWeight_reindex (e : C ≃ D) (line : D → G) + (a : G → ℕ → ℝ) (b : D → ℕ → ℝ) (z : C → ℕ) : + productWeight (line ∘ e) a (fun c => b (e c)) z= + productWeight line a b (z ∘ e.symm) := by + unfold productWeight + simp_rw [lineTotal_reindex] + congr 1 + have h := e.prod_comp (fun d => b d (z (e.symm d))) + simpa only [Function.comp_apply,Equiv.symm_apply_apply] using h + +lemma exactWeight_reindex (e : C ≃ D) (line : D → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : D → ℝ) (z : C → ℕ) : + exactWeight (line ∘ e) root rate offset slope (urate ∘ e) (ell ∘ e) + (uslope ∘ e) (cap ∘ e) z= + exactWeight line root rate offset slope urate ell uslope cap (z ∘ e.symm) := by + unfold exactWeight + exact productWeight_reindex e line (exactLineFactor root rate offset slope) + (unaryFactor urate ell uslope cap) z + +variable {S : Type*} [Fintype S] [DecidableEq S] + +/-- The application needs precisely the raw removal signature of the +actual physical factor marginal, rather than a hypothesis asserting it. -/ +theorem physical_marginal_removal (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : D → ℝ) + (hwidth : ∀ M ∈ Ms, 2≤M) (hrate : ∀ g, 0≤rate g) (hu : ∀ d, 0≤urate d) : + RemovalSlice (eliminate Ms (fun z => + exactWeight line root rate offset slope urate ell uslope cap (z ∘ e.symm))) m R := by + have heq : (fun z => exactWeight line root rate offset slope urate ell uslope cap + (z ∘ e.symm))= + exactWeight (line ∘ e) root rate offset slope (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) := by + funext z + exact (exactWeight_reindex e line root rate offset slope urate ell uslope cap z).symm + rw [heq] + exact exact_marginal_removal Ms m R (line ∘ e) root rate offset slope + (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) hwidth hrate (fun i => hu (e i)) + +/-- Global physical reflection also preserves the proved marginal +signature, and all balanced pairs are reflected along with small views. -/ +theorem physical_marginal_reflected (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : D → ℝ) + (hwidth : ∀ M ∈ Ms, 2≤M) (hrate : ∀ g, 0≤rate g) (hu : ∀ d, 0≤urate d) : + RemovalSlice (fun z => eliminate Ms (fun q => + exactWeight line root rate offset slope urate ell uslope cap (q ∘ e.symm)) + (IntegerReflection.reflect m z)) m R := by + have heq : (fun z => exactWeight line root rate offset slope urate ell uslope cap + (z ∘ e.symm))= + exactWeight (line ∘ e) root rate offset slope (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) := by + funext z + exact (exactWeight_reindex e line root rate offset slope urate ell uslope cap z).symm + rw [heq] + exact ReflectedSlices.reflected_exact_marginal Ms m R (line ∘ e) root rate offset slope + (urate ∘ e) (ell ∘ e) (uslope ∘ e) (cap ∘ e) hwidth hrate (fun i => hu (e i)) + +end ContingencyTables.EqualityReindex + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualitySoftening.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualitySoftening.lean new file mode 100644 index 0000000000000000000000000000000000000000..84226a21f8e250bec9051d38064062038a478c95 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/EqualitySoftening.lean @@ -0,0 +1,149 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedFamily +import OAI.Combinatorics.ContingencyTables.Transport.ScalarPenalty + +namespace OAI + +/-! +# Root penalties and exact nonroot equations + +Root lines carry their actual absolute-deviation penalty. Nonroot lines +carry a positive equality softener; its limit is the exact prescribed-line +indicator. Unary interval penalties include the companion's tree factors. +All balanced large-cell sums are performed before this finite limit. +-/ + +namespace ContingencyTables.EqualitySoftening + +open scoped BigOperators Classical Matrix Topology +open Filter CommonBasesFPRAS FactorialSignatures ProductIntegerSignature +open ScalarPenalty IntegerMarginal BalancedBox BalancedFamily + +variable {C G : Type*} [Fintype C] [Fintype G] + +noncomputable def lineFactor (root : G → Bool) (rate offset slope : G → ℝ) + (L : ℝ) (g : G) (n : ℕ) : ℝ := + factor (if root g then rate g else L) (fun k => |offset g+(k:ℝ)*slope g|) n + +noncomputable def exactLineFactor (root : G → Bool) (rate offset slope : G → ℝ) + (g : G) (n : ℕ) : ℝ := + if root g then factor (rate g) (fun k => |offset g+(k:ℝ)*slope g|) n + else if |offset g+(n:ℝ)*slope g|=0 then 1 else 0 + +/-- A physical affine coordinate, including a reflected tree coordinate. -/ +noncomputable def affineDistance (ell slope cap : ℝ) (n : ℕ) : ℝ := + max 0 (max (-(ell+(n:ℝ)*slope)) (ell+(n:ℝ)*slope-cap)) + +lemma affineDistance_convex (ell slope cap : ℝ) (n : ℕ) (hn : 2 ≤ n) : + 2*affineDistance ell slope cap (n-1) ≤ + affineDistance ell slope cap n+affineDistance ell slope cap (n-2) := by + unfold affineDistance + apply max_convex (fun _ => 0) + (fun k => max (-(ell+(k:ℝ)*slope)) (ell+(k:ℝ)*slope-cap)) n + · simp + · apply max_convex (fun k => -(ell+(k:ℝ)*slope)) + (fun k => ell+(k:ℝ)*slope-cap) n + · have h := affine_midpoint (-ell) (-slope) n hn + convert le_of_eq h using 1 <;> ring + · have h := affine_midpoint (ell-cap) slope n hn + convert le_of_eq h using 1 <;> ring + +noncomputable def unaryFactor (rate ell slope cap : C → ℝ) (i : C) (n : ℕ) : ℝ := + factor (rate i) (affineDistance (ell i) (slope i) (cap i)) n + +noncomputable def softenedWeight (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) : + (C → ℕ) → ℝ := + productWeight line (lineFactor root rate offset slope L) (unaryFactor urate ell uslope cap) + +noncomputable def exactWeight (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) : (C → ℕ) → ℝ := + productWeight line (exactLineFactor root rate offset slope) (unaryFactor urate ell uslope cap) + +lemma softenedWeight_positive (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) (z : C → ℕ) : + 0 < softenedWeight line root rate offset slope urate ell uslope cap L z := by + apply mul_pos <;> apply Finset.prod_pos <;> intro i _ <;> apply factor_positive + +/-- The actual positive factors prove the raw signature; it is not an +assumption about a previously lifted binary weight. -/ +theorem softenedWeight_removal (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) + (hrate : ∀ g, 0 ≤ rate g) (hu : ∀ i, 0 ≤ urate i) (hL : 0 ≤ L) (z : C → ℕ) : + OnePositiveDirection + (integerRemovalMatrix (softenedWeight line root rate offset slope urate ell uslope cap L) z).toBilin' := by + apply product_removal_onePositive line (lineFactor root rate offset slope L) + (unaryFactor urate ell uslope cap) z + · intro g n _; exact factor_positive _ _ _ + · intro i n _; exact factor_positive _ _ _ + · intro g hn + apply abs_factor_logConcave _ _ _ _ _ hn + split_ifs + · exact hrate g + · exact hL + · intro i hn + exact factor_logConcave (urate i) (hu i) _ _ + (affineDistance_convex (ell i) (uslope i) (cap i) _ hn) + +omit [Fintype G] in +lemma lineFactor_tendsto (root : G → Bool) (rate offset slope : G → ℝ) (g : G) (n : ℕ) : + Tendsto (fun L : ℝ => lineFactor root rate offset slope L g n) atTop + (nhds (exactLineFactor root rate offset slope g n)) := by + by_cases hroot : root g + · simp [lineFactor,exactLineFactor,hroot] + · simpa [lineFactor,exactLineFactor,hroot,factor] using + factor_limit |offset g+(n:ℝ)*slope g| (abs_nonneg _) + +theorem softenedWeight_tendsto (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (z : C → ℕ) : + Tendsto (fun L : ℝ => softenedWeight line root rate offset slope urate ell uslope cap L z) atTop + (nhds (exactWeight line root rate offset slope urate ell uslope cap z)) := by + apply Tendsto.mul_const + apply tendsto_finsetProd + intro g _ + exact lineFactor_tendsto root rate offset slope g (lineTotal line z g) + +/-- The exact-equality product itself inherits its finite raw signature. -/ +theorem exactWeight_removal (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) + (hrate : ∀ g, 0 ≤ rate g) (hu : ∀ i, 0 ≤ urate i) (z : C → ℕ) : + OnePositiveDirection + (integerRemovalMatrix (exactWeight line root rate offset slope urate ell uslope cap) z).toBilin' := by + apply removal_signature_limit (l := (atTop : Filter ℝ)) + (fun L => softenedWeight line root rate offset slope urate ell uslope cap L) + (exactWeight line root rate offset slope urate ell uslope cap) z + (softenedWeight_tendsto line root rate offset slope urate ell uslope cap) + filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + exact softenedWeight_removal line root rate offset slope urate ell uslope cap L hrate hu hL z + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- This is the actual finite balanced large-cell marginal with exact +nonroot equations. Positive softening is retained through every sum and +removed only after the last sum. -/ +theorem exact_marginal_removal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (root : G → Bool) (rate offset slope : G → ℝ) + (urate ell uslope cap : Coordinates I Ms → ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) (hrate : ∀ g, 0 ≤ rate g) (hu : ∀ i, 0 ≤ urate i) : + RemovalSlice (eliminate Ms (exactWeight line root rate offset slope urate ell uslope cap)) m R := by + intro z hz htotal + apply removal_signature_limit (l := (atTop : Filter ℝ)) + (fun L => eliminate Ms (softenedWeight line root rate offset slope urate ell uslope cap L)) + (eliminate Ms (exactWeight line root rate offset slope urate ell uslope cap)) z + · intro x + exact eliminate_tendsto Ms _ _ + (softenedWeight_tendsto line root rate offset slope urate ell uslope cap) x + · filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + have hp : PositiveSlice (softenedWeight line root rate offset slope urate ell uslope cap L) + (bounds m Ms) (R+Ms.sum) := by + intro x _ _ + exact softenedWeight_positive line root rate offset slope urate ell uslope cap L x + have hs : RemovalSlice (softenedWeight line root rate offset slope urate ell uslope cap L) + (bounds m Ms) (R+Ms.sum) := by + intro x _ _ + convert softenedWeight_removal line root rate offset slope urate ell uslope cap L hrate hu hL x using 1 + congr 2 <;> exact Subsingleton.elim _ _ + exact (eliminate_slices Ms m R _ hwidth hp hs).2 z hz htotal + +end ContingencyTables.EqualitySoftening + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextDefects.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextDefects.lean new file mode 100644 index 0000000000000000000000000000000000000000..13097f6a10dbdf71bc36263b1d6b2718dc7d4114 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextDefects.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ExcessContextProfiles + +namespace OAI + +/-! # Auxiliary raw profiles satisfy the literal physical defect equation -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open BalancedEnumeration IntegerWeightedTransport FirstPaperProfiles + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +lemma defect_of_pair_totals (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hU : 1 ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (s t : I×J) (hs : small s.1 s.2=true) (ht : small t.1 t.2=true) (hst : s≠t) + (z : SmallProfile small) (hz : ∀ a, z a ≤ U) + (hpair : ∀ a : Cells small, z (a,false)+z (a,true)= + if a.val=s then U-1 else if a.val=t then U+1 else U) : + IsDefect (smallView small z false) (smallQ small B z) s t := by + refine ⟨hst,?_⟩ + intro i j + cases hij : small i j + · have hns : ¬(i=s.1 ∧ j=s.2) := by + rintro ⟨rfl,rfl⟩ + rw [hs] at hij + contradiction + have hnt : ¬(i=t.1 ∧ j=t.2) := by + rintro ⟨rfl,rfl⟩ + rw [ht] at hij + contradiction + simp only [transferInt,smallView,smallQ,hij,Bool.false_eq_true,↓reduceDIte, + hns,hnt,↓reduceIte] + norm_num + · have hp := hpair ⟨(i,j),hij⟩ + have hx := hz (⟨(i,j),hij⟩,false) + have hy := hz (⟨(i,j),hij⟩,true) + dsimp only at hp + by_cases his : i=s.1 ∧ j=s.2 + · have his' : (i,j)=s := Prod.ext his.1 his.2 + have hit : ¬(i=t.1 ∧ j=t.2) := by + intro hit + exact hst (his'.symm.trans (Prod.ext hit.1 hit.2)) + rw [ite_eq_left his'] at hp + simp only [transferInt,smallView,smallQ,hij,dite_eq_left,hB i j hij, + ite_eq_left his,ite_eq_right hit] + omega + · have his' : (i,j)≠s := fun h => his (Prod.ext_iff.mp h) + rw [ite_eq_right his'] at hp + by_cases hit : i=t.1 ∧ j=t.2 + · have hit' : (i,j)=t := Prod.ext hit.1 hit.2 + rw [ite_eq_left hit'] at hp + simp only [transferInt,smallView,smallQ,hij,dite_eq_left,hB i j hij, + ite_eq_right his,ite_eq_left hit] + omega + · have hit' : (i,j)≠t := fun h => hit (Prod.ext_iff.mp h) + rw [ite_eq_right hit'] at hp + simp only [transferInt,smallView,smallQ,hij,dite_eq_left,hB i j hij, + ite_eq_right his,ite_eq_right hit] + omega + +noncomputable def boundedExcess (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U l : ℕ) + (hl : l ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) + (hq : ValidExcess _ q) : BoundedProfile small B := fun a => + ⟨rawExcess small s hs σ U l e q a,by + rw [hB _ _ a.1.property] + exact Nat.lt_succ_of_le (rawExcess_bounded small s hs σ U l hl hσ e q hq a)⟩ + +lemma naturalProfile_boundedExcess (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U l : ℕ) + (hl : l ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) (hq : ValidExcess _ q) : + naturalProfile (boundedExcess small B s hs σ U l hl hB hσ e q hq)= + rawExcess small s hs σ U l e q := rfl + +noncomputable def excessDefectProfile (small : I → J → Bool) (B : I → J → ℕ) + (s : I×J) (hs : small s.1 s.2=true) (σ : I×J → ℕ) (U l : ℕ) + (hl0 : 1 ≤ l) (hlU : l ≤ U) (hB : ∀ i j, small i j=true → B i j=U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) (hq : ValidExcess _ q) : + DefectProfiles small B s (e (excessIndex (fun _ : Fin n => U) q)).val.val σ l := by + let t := e (excessIndex (fun _ : Fin n => U) q) + refine ⟨boundedExcess small B s hs σ U l hlU hB hσ e q hq,?_,?_,?_⟩ + · rw [naturalProfile_boundedExcess] + apply defect_of_pair_totals small B U (by omega) hB s t.val.val hs t.val.property + t.property.ne (rawExcess small s hs σ U l e q) + (rawExcess_bounded small s hs σ U l hlU hσ e q hq) + intro a + have hh := rawExcess_pair_total small s hs σ U l hl0 hlU hσ e q a + simpa only [Subtype.ext_iff] using hh + · intro i j hij hbefore + simp only [naturalProfile_boundedExcess,smallView,hij,dite_eq_left] + have hh := assemble_prefix small s hs σ U e + (excessEmbedding _ (auxRoot U l) q) ⟨⟨(i,j),hij⟩,hbefore⟩ false + exact hh + · simp only [naturalProfile_boundedExcess,smallView,hs,dite_eq_left,rawExcess, + assemble_special,excessEmbedding_root,auxRoot,Bool.false_eq_true,↓reduceIte] + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextProfiles.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextProfiles.lean new file mode 100644 index 0000000000000000000000000000000000000000..892b7d3f3f45a49555ff65b4294d52abf9fef92c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessContextProfiles.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.ExcessPairCoordinates + +namespace OAI + +/-! # Physical defect profiles in the auxiliary context kernel -/ + +namespace ContingencyTables.ExcessContextProfiles + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open BalancedEnumeration IntegerWeightedTransport FirstPaperProfiles + +universe u + +variable {I J : Type u} [LinearOrder I] [LinearOrder J] + +noncomputable def assemble (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) : SmallProfile small := + (Sum.elim (prefixRaw small s σ U) v) ∘ (contextEquiv small s hs e U).symm + +lemma assemble_apply (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (a : (Earlier small s×Bool) ⊕ Coordinates Bool (widths (fun _ : Fin n => U))) : + assemble small s hs σ U e v (contextEquiv small s hs e U a)= + Sum.elim (prefixRaw small s σ U) v a := by + simp only [assemble,Function.comp_apply,Equiv.symm_apply_apply] + +lemma assemble_prefix (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) + (a : Earlier small s) (b : Bool) : + assemble small s hs σ U e v (a.val,b)=if b then U-σ a.val.val else σ a.val.val := by + have h := assemble_apply small s hs σ U e v (.inl (a,b)) + simpa only [contextEquiv_prefix,Sum.elim_inl,prefixRaw] using h + +lemma assemble_special (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) (b : Bool) : + assemble small s hs σ U e v (⟨s,hs⟩,b)= + v ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inl b)) := by + have h := assemble_apply small s hs σ U e v + (.inr ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inl b))) + simpa only [contextEquiv_special,Sum.elim_inr] using h + +lemma assemble_later (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (v : Coordinates Bool (widths (fun _ : Fin n => U)) → ℕ) (i : Fin n) (b : Bool) : + assemble small s hs σ U e v ((e i).val,b)= + v ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inr (i,b))) := by + have h := assemble_apply small s hs σ U e v + (.inr ((coordinateEquiv Bool (fun _ : Fin n => U)).symm (.inr (i,b)))) + simpa only [contextEquiv_later,Sum.elim_inr] using h + +def auxRoot (U l : ℕ) : Bool → ℕ := fun b => if b then U-l else l-1 + +lemma auxRoot_inBox (U l : ℕ) (hl : l ≤ U) : InBox (fun _ => U) (auxRoot U l) := by + intro b + cases b + · exact (Nat.sub_le _ _).trans hl + · exact Nat.sub_le _ _ + +noncomputable def rawExcess (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) : SmallProfile small := + assemble small s hs σ U e (excessEmbedding _ (auxRoot U l) q) + +lemma bounds_constant (U : ℕ) {n : ℕ} : + bounds (fun _ : Bool => U) (widths (fun _ : Fin n => U))=(fun _ => U) := by + induction n with + | zero => rfl + | succ n ih => + funext a + cases a with + | inl a => exact congrFun ih a + | inr b => cases b <;> rfl + +lemma rawExcess_bounded (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hl : l ≤ U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) + (hq : ValidExcess _ q) (a : SmallView (fun a : I×J => small a.1 a.2)) : + rawExcess small s hs σ U l e q a ≤ U := by + have hv := (excessEmbedding_inBox_iff _ _ _ (auxRoot_inBox U l hl) q).mpr hq + obtain ⟨v,rfl⟩ := (contextEquiv small s hs e U).surjective a + unfold rawExcess + rw [assemble_apply] + cases v with + | inl p => + rcases p with ⟨p,b⟩ + cases b + · exact hσ p + · exact Nat.sub_le _ _ + | inr v => + rw [bounds_constant] at hv + exact hv v + +/-- The auxiliary profile has exactly the negative current pair and +one positive later pair required by the manuscript's conditional repair. -/ +lemma rawExcess_pair_total (small : I → J → Bool) (s : I×J) (hs : small s.1 s.2=true) + (σ : I×J → ℕ) (U l : ℕ) (hl0 : 1 ≤ l) (hlU : l ≤ U) + (hσ : ∀ a : Earlier small s, σ a.val.val ≤ U) {n : ℕ} (e : Fin n ≃ Later small s) + (q : ExcessAssignments (widths (fun _ : Fin n => U))) (a : Cells small) : + rawExcess small s hs σ U l e q (a,false)+rawExcess small s hs σ U l e q (a,true)= + if a=⟨s,hs⟩ then U-1 else + if a=(e (excessIndex (fun _ : Fin n => U) q)).val then U+1 else U := by + obtain ⟨v,rfl⟩ := (cellSplitEquiv small s hs).surjective a + rcases v with p|(_|t) + · have hps : p.val≠⟨s,hs⟩ := by + intro he + have h := p.property + rw [he] at h + exact h.ne rfl + have hpt : p.val≠(e (excessIndex (fun _ : Fin n => U) q)).val := by + intro he + have h := p.property + rw [he] at h + exact (h.trans (e (excessIndex (fun _ : Fin n => U) q)).property).ne rfl + change rawExcess small s hs σ U l e q (p.val,false)+rawExcess small s hs σ U l e q (p.val,true)= + if p.val=⟨s,hs⟩ then U-1 else + if p.val=(e (excessIndex (fun _ : Fin n => U) q)).val then U+1 else U + simp only [rawExcess,assemble_prefix,Bool.false_eq_true,↓reduceIte,hps,hpt] + have hb := hσ p + omega + · change rawExcess small s hs σ U l e q (⟨s,hs⟩,false)+rawExcess small s hs σ U l e q (⟨s,hs⟩,true)= + if (⟨s,hs⟩ : Cells small)=⟨s,hs⟩ then U-1 else + if (⟨s,hs⟩ : Cells small)=(e (excessIndex (fun _ : Fin n => U) q)).val then U+1 else U + rw [ite_eq_left rfl] + simp only [rawExcess,assemble_special,excessEmbedding_root,auxRoot,Bool.false_eq_true,↓reduceIte] + omega + · have hts : t.val≠⟨s,hs⟩ := by + intro he + have h := t.property + rw [he] at h + exact h.ne rfl + have hte : t.val=(e (excessIndex (fun _ : Fin n => U) q)).val ↔ + e.symm t=excessIndex (fun _ : Fin n => U) q := by + constructor + · intro he + have he' : t=e (excessIndex (fun _ : Fin n => U) q) := Subtype.ext he + rw [he',Equiv.symm_apply_apply] + · intro he + have hh := congrArg e he + simpa only [Equiv.apply_symm_apply] using congrArg Subtype.val hh + have hh := excessEmbedding_pair_total (fun _ : Fin n => U) (auxRoot U l) q (e.symm t) + change assemble small s hs σ U e (excessEmbedding _ (auxRoot U l) q) (t.val,false)+ + assemble small s hs σ U e (excessEmbedding _ (auxRoot U l) q) (t.val,true)= + if t.val=⟨s,hs⟩ then U-1 else + if t.val=(e (excessIndex (fun _ : Fin n => U) q)).val then U+1 else U + have hf := assemble_later small s hs σ U e (excessEmbedding _ (auxRoot U l) q) (e.symm t) false + have ht := assemble_later small s hs σ U e (excessEmbedding _ (auxRoot U l) q) (e.symm t) true + simp only [Equiv.apply_symm_apply] at hf ht + rw [hf,ht,ite_eq_right hts] + by_cases h : e.symm t=excessIndex (fun _ : Fin n => U) q + · rw [ite_eq_left (hte.mpr h)] + simpa only [h,↓reduceIte] using hh + · rw [ite_eq_right (fun he => h (hte.mp he))] + simpa only [h,↓reduceIte,add_zero] using hh + +end ContingencyTables.ExcessContextProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessPairCoordinates.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessPairCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..f494e5e616f19e2e6dd42229351291ea5278fe4c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ExcessPairCoordinates.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerAuxiliaryEnumeration +import OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration + +namespace OAI + +/-! # The unique excess pair in physical finite coordinates -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open BalancedFamily BalancedEnumeration LargePairEnumeration IntegerMarginal + +lemma coordinateEquiv_symm_root_succ {S : Type*} {n : ℕ} (M : Fin (n+1) → ℕ) (s : S) : + (coordinateEquiv S M).symm.toFun (Sum.inl s)= + Sum.inl ((coordinateEquiv S (fun i => M i.succ)).symm (Sum.inl s)) := rfl + +lemma coordinateEquiv_symm_zero {S : Type*} {n : ℕ} (M : Fin (n+1) → ℕ) (b : Bool) : + (coordinateEquiv S M).symm.toFun (Sum.inr (0,b))=Sum.inr b := rfl + +lemma coordinateEquiv_symm_succ {S : Type*} {n : ℕ} (M : Fin (n+1) → ℕ) + (i : Fin n) (b : Bool) : + (coordinateEquiv S M).symm.toFun (Sum.inr (i.succ,b))= + Sum.inl ((coordinateEquiv S (fun j => M j.succ)).symm (Sum.inr (i,b))) := rfl + +lemma embedding_root {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (q : Assignments (widths M)) (s : S) : + embedding (widths M) z q ((coordinateEquiv S M).symm (.inl s))=z s := by + have h := embedding_coordinate M z ((assignmentEquiv M) q) + ((coordinateEquiv S M).symm (.inl s)) + simpa only [Equiv.symm_apply_apply,Equiv.apply_symm_apply,joinedProfile] using h + +lemma embedding_pair_total {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (q : Assignments (widths M)) (i : Fin n) : + embedding (widths M) z q ((coordinateEquiv S M).symm (.inr (i,false)))+ + embedding (widths M) z q ((coordinateEquiv S M).symm (.inr (i,true)))=M i := by + have hfalse := embedding_coordinate M z ((assignmentEquiv M) q) + ((coordinateEquiv S M).symm (.inr (i,false))) + have htrue := embedding_coordinate M z ((assignmentEquiv M) q) + ((coordinateEquiv S M).symm (.inr (i,true))) + simp only [Equiv.symm_apply_apply,Equiv.apply_symm_apply,joinedProfile, + Bool.false_eq_true,↓reduceIte] at hfalse htrue + rw [hfalse,htrue] + have hb := ((assignmentEquiv M) q i).isLt + omega + +def excessIndex : {n : ℕ} → (M : Fin n → ℕ) → ExcessAssignments (widths M) → Fin n + | 0,_,q => Empty.elim q + | _+1,_,.inl _ => 0 + | _+1,M,.inr q => (excessIndex (fun i => M i.succ) q.1).succ + +lemma excessEmbedding_root {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (q : ExcessAssignments (widths M)) (s : S) : + excessEmbedding (widths M) z q ((coordinateEquiv S M).symm (.inl s))=z s := by + induction n with + | zero => exact Empty.elim q + | succ n ih => + cases q with + | inl q => + change embedding (widths (fun i => M i.succ)) z q.1 + ((coordinateEquiv S (fun i => M i.succ)).symm (.inl s))=z s + exact embedding_root (fun i => M i.succ) z q.1 s + | inr q => + change excessEmbedding (widths (fun i => M i.succ)) z q.1 + ((coordinateEquiv S (fun i => M i.succ)).symm (.inl s))=z s + exact ih (fun i => M i.succ) q.1 + +/-- The raw finite profile recovers the distinguished position by its +pair total; all other pairs have their original total. -/ +lemma excessEmbedding_pair_total {S : Type*} {n : ℕ} (M : Fin n → ℕ) (z : S → ℕ) + (q : ExcessAssignments (widths M)) (i : Fin n) : + excessEmbedding (widths M) z q ((coordinateEquiv S M).symm (.inr (i,false)))+ + excessEmbedding (widths M) z q ((coordinateEquiv S M).symm (.inr (i,true)))= + M i+if i=excessIndex M q then 1 else 0 := by + induction n with + | zero => exact Fin.elim0 i + | succ n ih => + cases q with + | inl q => + refine Fin.cases ?_ (fun j => ?_) i + · change q.2.val+(M 0+1-q.2.val)=M 0+if (0 : Fin (n+1))=0 then 1 else 0 + have hb := q.2.isLt + simp only [↓reduceIte] + omega + · change embedding (widths (fun j => M j.succ)) z q.1 + ((coordinateEquiv S (fun j => M j.succ)).symm (.inr (j,false)))+ + embedding (widths (fun j => M j.succ)) z q.1 + ((coordinateEquiv S (fun j => M j.succ)).symm (.inr (j,true)))=M j.succ+if j.succ=0 then 1 else 0 + rw [embedding_pair_total] + simp only [Fin.succ_ne_zero,↓reduceIte,add_zero] + | inr q => + refine Fin.cases ?_ (fun j => ?_) i + · change q.2.val+(M 0-q.2.val)=M 0+ + if (0 : Fin (n+1))=(excessIndex (fun j => M j.succ) q.1).succ then 1 else 0 + have hb := q.2.isLt + have hn : (0 : Fin (n+1))≠(excessIndex (fun j => M j.succ) q.1).succ := + (Fin.succ_ne_zero _).symm + simp only [hn,↓reduceIte,add_zero] + omega + · change excessEmbedding (widths (fun j => M j.succ)) z q.1 + ((coordinateEquiv S (fun j => M j.succ)).symm (.inr (j,false)))+ + excessEmbedding (widths (fun j => M j.succ)) z q.1 + ((coordinateEquiv S (fun j => M j.succ)).symm (.inr (j,true)))=M j.succ+ + if j.succ=(excessIndex (fun j => M j.succ) q.1).succ then 1 else 0 + rw [ih] + simp only [Fin.succ_inj] + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FactorialSignatures.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FactorialSignatures.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fb805fdeedde6d632ece3f08bf1ae261b1a64ae --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FactorialSignatures.lean @@ -0,0 +1,556 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryContraction + +namespace OAI + +/-! +# Factorial congruence for the two binary lifts + +The integer-to-binary signature transfer in paper 200-02, +Lemma `lem:binary-signatures`. Coordinates with zero remaining copies +are allowed; a single remaining copy gives an invalid repeated removal. +The copy matrix is proved to be dominated by the integer form compressed +to group means. The difference is the nonnegative within-group variance. +-/ + +namespace ContingencyTables.FactorialSignatures + +open scoped BigOperators Classical Matrix +open LinearMap (BilinForm) +open CommonBasesFPRAS + +/-- Domination by a compressed one-positive form preserves the signature. +This is the precise group-mean argument, including forms with no positive direction. -/ +theorem onePositive_of_dominated_compression + {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] + (B : BilinForm ℝ V) (C : BilinForm ℝ W) (L : W →ₗ[ℝ] V) + (hsymm : ∀ x y, C x y = C y x) (hsig : OnePositiveDirection B) + (hdom : ∀ v, C v v ≤ B (L v) (L v)) : OnePositiveDirection C := by + by_cases hpos : ∃ u, 0 < C u u + · obtain ⟨u, hu⟩ := hpos + apply onePositiveDirection_of_kernel C hsymm ((B (L u)).comp L) + intro v hv + exact (hdom v).trans (hsig (L u) (lt_of_lt_of_le hu (hdom u)) (L v) hv) + · intro u hu + exact False.elim (hpos ⟨u, hu⟩) + +variable {G : Type*} [Fintype G] [DecidableEq G] + +abbrev Copies (n : G → ℕ) := (u : G) × Fin (n u) + +noncomputable def groupAverage (n : G → ℕ) : (Copies n → ℝ) →ₗ[ℝ] (G → ℝ) where + toFun x u := (∑ i : Fin (n u), x ⟨u, i⟩) / n u + map_add' x y := by ext u; simp [Finset.sum_add_distrib, add_div] + map_smul' a x := by + ext u + simp only [Pi.smul_apply, smul_eq_mul, ← Finset.mul_sum, mul_div_assoc, RingHom.id_apply] + +def groupIndicator (n : G → ℕ) (u : G) (i : Copies n) : ℝ := if i.1 = u then 1 else 0 + +def groupOuter (n : G → ℕ) (u : G) : Matrix (Copies n) (Copies n) ℝ := + fun i j => groupIndicator n u i * groupIndicator n u j + +noncomputable def withinCoefficient (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) (u : G) : ℝ := + c * H u u / ((n u : ℝ) * (n u - 1 : ℕ)) + +noncomputable def normalizedMatrix (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) : + Matrix (Copies n) (Copies n) ℝ := + fun i j => c * H i.1 j.1 / ((n i.1 : ℝ) * n j.1) + +noncomputable def scaledPullback (n : G → ℕ) (H : Matrix G G ℝ) : + Matrix (Copies n) (Copies n) ℝ := + fun i j => (1 / (n i.1 : ℝ)) * H i.1 j.1 * (1 / (n j.1 : ℝ)) + +/-- Exact normalized copy matrix, including the within-group diagonal correction. -/ +noncomputable def copyMatrix (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) : + Matrix (Copies n) (Copies n) ℝ := + normalizedMatrix n H c + + ∑ u, (withinCoefficient n H c u / n u) • groupOuter n u - + Matrix.diagonal (fun i : Copies n => withinCoefficient n H c i.1) + +lemma grouped_form (n : G → ℕ) (H : Matrix G G ℝ) (x y : Copies n → ℝ) : + (H.submatrix Sigma.fst Sigma.fst).toBilin' x y = + H.toBilin' (fun u => ∑ i : Fin (n u), x ⟨u, i⟩) + (fun u => ∑ i : Fin (n u), y ⟨u, i⟩) := by + simp only [Matrix.toBilin'_apply, Matrix.submatrix_apply, Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro u _ + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro v _ + simp_rw [← Finset.mul_sum] + rw [← Finset.sum_mul, ← Finset.sum_mul] + +lemma groupOuter_form (n : G → ℕ) (u : G) (x y : Copies n → ℝ) : + (groupOuter n u).toBilin' x y = + (∑ i : Fin (n u), x ⟨u, i⟩) * ∑ i : Fin (n u), y ⟨u, i⟩ := by + simp only [Matrix.toBilin'_apply, groupOuter, groupIndicator, Fintype.sum_sigma] + simp [Finset.mul_sum, Finset.sum_mul] + rw [Finset.sum_comm] + +lemma normalized_form (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) (x y : Copies n → ℝ) : + (normalizedMatrix n H c).toBilin' x y = + c * H.toBilin' (groupAverage n x) (groupAverage n y) := by + have heq : normalizedMatrix n H c = c • scaledPullback n H := by + ext i j + simp only [normalizedMatrix, scaledPullback, Matrix.smul_apply, smul_eq_mul, + div_mul_eq_div_div] + ring + rw [heq] + simp only [map_smul, LinearMap.smul_apply, smul_eq_mul] + congr 1 + have hg := grouped_form n H (fun i => x i / n i.1) (fun i => y i / n i.1) + convert hg using 1 + · rw [Matrix.toBilin'_apply, Matrix.toBilin'_apply] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + simp only [Matrix.submatrix_apply, scaledPullback] + ring + · congr 1 <;> ext u <;> simp [groupAverage, Finset.sum_div] + +lemma diagonal_form (n : G → ℕ) (d x : Copies n → ℝ) : + (Matrix.diagonal d).toBilin' x x = ∑ i, d i * x i * x i := by + rw [Matrix.toBilin'_apply] + apply Finset.sum_congr rfl + intro i _ + simp only [Matrix.diagonal_apply, mul_ite, mul_zero, ite_mul, zero_mul, + Finset.sum_ite_eq, Finset.mem_univ, ite_true] + ring + +/-- The factorial copy form equals the integer form on group averages +minus the sum of within-group variances with their actual coefficients. -/ +theorem copyMatrix_form (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) (x : Copies n → ℝ) : + (copyMatrix n H c).toBilin' x x = + c * H.toBilin' (groupAverage n x) (groupAverage n x) - + ∑ u, withinCoefficient n H c u * + ((∑ i : Fin (n u), x ⟨u, i⟩ ^ 2) - + (∑ i : Fin (n u), x ⟨u, i⟩) ^ 2 / n u) := by + simp only [copyMatrix, map_sub, map_add, map_sum, map_smul, + LinearMap.sub_apply, LinearMap.add_apply, LinearMap.sum_apply, + LinearMap.smul_apply, smul_eq_mul, normalized_form, groupOuter_form, + diagonal_form] + simp only [Fintype.sum_sigma] + simp_rw [mul_assoc, ← Finset.mul_sum] + have halg (a b d r : ℝ) : a * (b - d ^ 2 / r) = a * b - a / r * (d * d) := by ring + simp_rw [halg, Finset.sum_sub_distrib, pow_two] + ring + +omit [Fintype G] [DecidableEq G] in +lemma within_variance_nonnegative (n : ℕ) (x : Fin n → ℝ) : + 0 ≤ (∑ i, x i ^ 2) - (∑ i, x i) ^ 2 / n := by + by_cases hn : n = 0 + · subst n + simp + have hnr : (0 : ℝ) < n := by exact_mod_cast Nat.pos_of_ne_zero hn + have hcs := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ (fun _ : Fin n => (1 : ℝ)) x + have hh : (∑ i, x i) ^ 2 ≤ (n : ℝ) * ∑ i, x i ^ 2 := by simpa using hcs + exact sub_nonneg.mpr ((div_le_iff₀ hnr).mpr (by nlinarith [hh])) + +/-- Raw integer signatures imply signatures of the actual copy matrix. +Zero groups are harmless and single-copy groups require no division argument. -/ +theorem copyMatrix_onePositive (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) + (hc : 0 < c) (hH : ∀ u v, H u v = H v u) + (hsig : OnePositiveDirection H.toBilin') (hdiag : ∀ u, 0 ≤ H u u) : + OnePositiveDirection (copyMatrix n H c).toBilin' := by + have hcSig : OnePositiveDirection (c • H.toBilin') := by + intro u hu v hv + simp only [LinearMap.smul_apply, smul_eq_mul] at hu hv ⊢ + have hu' : 0 < H.toBilin' u u := pos_of_mul_pos_right hu hc.le + have hv' : H.toBilin' u v = 0 := (mul_eq_zero.mp hv).resolve_left (ne_of_gt hc) + exact mul_nonpos_of_nonneg_of_nonpos hc.le (hsig u hu' v hv') + have hsymm : ∀ i j, copyMatrix n H c i j = copyMatrix n H c j i := by + intro i j + simp only [copyMatrix, normalizedMatrix, Matrix.sub_apply, Matrix.add_apply, Matrix.sum_apply, + Matrix.smul_apply, smul_eq_mul, Matrix.diagonal_apply, groupOuter] + rw [hH] + simp only [mul_comm (n i.1 : ℝ) (n j.1 : ℝ)] + congr 1 + · congr 1 + apply Finset.sum_congr rfl + intro u _ + ring + · by_cases hij : i = j + · subst j; rfl + · simp [hij, Ne.symm hij] + apply onePositive_of_dominated_compression (c • H.toBilin') _ (groupAverage n) + (fun x y => (matrix_bilin_symm _ hsymm).eq x y) hcSig + intro x + rw [copyMatrix_form] + change _ ≤ c * H.toBilin' (groupAverage n x) (groupAverage n x) + apply sub_le_self + apply Finset.sum_nonneg + intro u _ + apply mul_nonneg _ (within_variance_nonnegative (n u) (fun i => x ⟨u, i⟩)) + exact div_nonneg (mul_nonneg hc.le (hdiag u)) (mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + +omit [Fintype G] [DecidableEq G] in +lemma normalization_identity (n : ℕ) (a : ℝ) (hsmall : n < 2 → a = 0) : + a / ((n : ℝ) * n) + (a / ((n : ℝ) * (n - 1 : ℕ))) / n = + a / ((n : ℝ) * (n - 1 : ℕ)) := by + by_cases hn : 2 ≤ n + · have hn0 : (n : ℝ) ≠ 0 := by exact_mod_cast (show n ≠ 0 by omega) + have hn1 : (n : ℝ) - 1 ≠ 0 := by + have : (2 : ℝ) ≤ n := by exact_mod_cast hn + linarith + have hcast : ((n - 1 : ℕ) : ℝ) = (n : ℝ) - 1 := by + rw [Nat.cast_sub (by omega : 1 ≤ n), Nat.cast_one] + rw [hcast] + field_simp + ring + · rw [hsmall (by omega)] + simp + +/-- The normalization has exactly the zero diagonal and the factorial +removal denominator, including single-copy and empty groups. -/ +theorem copyMatrix_apply (n : G → ℕ) (H : Matrix G G ℝ) (c : ℝ) + (hzero : ∀ u, n u < 2 → H u u = 0) (i j : Copies n) : + copyMatrix n H c i j = if i = j then 0 else + c * H i.1 j.1 / ((n i.1 : ℝ) * + (if i.1 = j.1 then ((n i.1 - 1 : ℕ) : ℝ) else n j.1)) := by + simp only [copyMatrix, normalizedMatrix, Matrix.sub_apply, Matrix.add_apply, Matrix.sum_apply, + Matrix.smul_apply, smul_eq_mul, groupOuter, groupIndicator, Matrix.diagonal_apply] + rw [Finset.sum_eq_single i.1] + · by_cases hg : i.1 = j.1 + · have hn := normalization_identity (n i.1) (c * H i.1 i.1) + (fun h => by rw [hzero i.1 h, mul_zero]) + simp only [hg, ite_true, mul_one, withinCoefficient] at * + rw [hn] + by_cases hij : i = j <;> simp [hij] + · have hij : i ≠ j := fun h => hg (congrArg Sigma.fst h) + simp [hg, Ne.symm hg, hij] + · intro u _ hu + simp [Ne.symm hu] + · simp + +noncomputable def factorialProduct (n : G → ℕ) : ℝ := ∏ u, (n u).factorial + +def removeOne (n : G → ℕ) (u : G) : G → ℕ := fun v => n v - if v = u then 1 else 0 + +def removeTwo (n : G → ℕ) (u v : G) : G → ℕ := removeOne (removeOne n u) v + +omit [DecidableEq G] in +lemma factorialProduct_positive (n : G → ℕ) : 0 < factorialProduct n := by + apply Finset.prod_pos + intro u _ + exact_mod_cast Nat.factorial_pos (n u) + +/-- Removing one labeled copy cancels precisely its coordinate count. -/ +lemma factorialProduct_removeOne (n : G → ℕ) (u : G) (hu : 0 < n u) : + factorialProduct (removeOne n u) = factorialProduct n / n u := by + have hnu : (n u : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hu + apply (eq_div_iff hnu).mpr + unfold factorialProduct + rw [← Finset.mul_prod_erase Finset.univ (fun v => ((removeOne n u v).factorial : ℝ)) + (Finset.mem_univ u), + ← Finset.mul_prod_erase Finset.univ (fun v => ((n v).factorial : ℝ)) (Finset.mem_univ u)] + have hrest : (∏ v ∈ Finset.univ.erase u, ((removeOne n u v).factorial : ℝ)) = + ∏ v ∈ Finset.univ.erase u, ((n v).factorial : ℝ) := by + apply Finset.prod_congr rfl + intro v hv + simp [removeOne, (Finset.mem_erase.mp hv).1] + rw [hrest] + have hfac : (n u : ℝ) * ((n u - 1).factorial : ℝ) = (n u).factorial := by + exact_mod_cast Nat.mul_factorial_pred (Nat.ne_of_gt hu) + simp only [removeOne, ite_true] + calc + _ = ((n u : ℝ) * ((n u - 1).factorial : ℝ)) * + ∏ v ∈ Finset.univ.erase u, ((n v).factorial : ℝ) := by ring + _ = _ := by rw [hfac] + +/-- Two factorial reductions yield the exact cross-group or repeated-group +multiplicity denominator. -/ +theorem factorialProduct_removeTwo (n : G → ℕ) (u v : G) + (hu : 0 < n u) (hv : 0 < n v - if v = u then 1 else 0) : + factorialProduct (removeTwo n u v) = factorialProduct n / + ((n u : ℝ) * (if u = v then ((n u - 1 : ℕ) : ℝ) else n v)) := by + rw [removeTwo, factorialProduct_removeOne _ v hv, factorialProduct_removeOne n u hu] + by_cases huv : u = v + · subst v + simp only [removeOne, ite_true, div_div] + · simp [removeOne, huv, Ne.symm huv, div_div] + + +omit [Fintype G] in +/-- Distinct labeled copies give valid one-per-coordinate or repeated-coordinate removals. -/ +lemma distinct_copy_counts (n : G → ℕ) (i j : Copies n) (hij : i ≠ j) : + 0 < n i.1 ∧ 0 < n j.1 - if j.1 = i.1 then 1 else 0 := by + rcases i with ⟨u, a⟩ + rcases j with ⟨v, b⟩ + have hu : 0 < n u := lt_of_le_of_lt (Nat.zero_le _) a.isLt + have hv : 0 < n v := lt_of_le_of_lt (Nat.zero_le _) b.isLt + refine ⟨hu, ?_⟩ + by_cases huv : u = v + · subst v + have hab : a ≠ b := fun h => hij (congrArg (Sigma.mk u) h) + have hn : 2 ≤ n u := by + by_contra hn + have ha : a.val = 0 := by omega + have hb : b.val = 0 := by omega + exact hab (Fin.ext (ha.trans hb.symm)) + simp only [ite_true] + omega + · simp [Ne.symm huv, hv] + +noncomputable def factorialMatrix (n : G → ℕ) (H : Matrix G G ℝ) (D : ℝ) : + Matrix (Copies n) (Copies n) ℝ := fun i j => if i = j then 0 else + H i.1 j.1 * factorialProduct (removeTwo n i.1 j.1) / D + +/-- Exact factorial congruence with the normalized integer matrix. -/ +theorem factorialMatrix_eq (n : G → ℕ) (H : Matrix G G ℝ) (D : ℝ) + (hzero : ∀ u, n u < 2 → H u u = 0) : + factorialMatrix n H D = copyMatrix n H (factorialProduct n / D) := by + ext i j + rw [copyMatrix_apply n H _ hzero] + by_cases hij : i = j + · simp [factorialMatrix, hij] + obtain ⟨hi, hj⟩ := distinct_copy_counts n i j hij + simp only [factorialMatrix, hij, ite_false] + rw [factorialProduct_removeTwo n i.1 j.1 hi hj] + ring + +/-- The literal factorial weights have the binary signature implied by +their integer two-removal or remaining-capacity addition matrix. -/ +theorem factorialMatrix_onePositive (n : G → ℕ) (H : Matrix G G ℝ) (D : ℝ) + (hD : 0 < D) (hH : ∀ u v, H u v = H v u) + (hsig : OnePositiveDirection H.toBilin') (hdiag : ∀ u, 0 ≤ H u u) + (hzero : ∀ u, n u < 2 → H u u = 0) : + OnePositiveDirection (factorialMatrix n H D).toBilin' := by + rw [factorialMatrix_eq n H D hzero] + exact copyMatrix_onePositive n H _ (div_pos (factorialProduct_positive n) hD) hH hsig hdiag + +def ValidPair (n : G → ℕ) (u v : G) : Prop := + 0 < n u ∧ 0 < n v - if v = u then 1 else 0 + +omit [Fintype G] in +lemma validPair_symm (n : G → ℕ) (u v : G) : ValidPair n u v ↔ ValidPair n v u := by + by_cases huv : u = v + · subst v + rfl + · simp [ValidPair, huv, Ne.symm huv, and_comm] + +omit [Fintype G] in +lemma removeTwo_comm (n : G → ℕ) (u v : G) : removeTwo n u v = removeTwo n v u := by + funext w + dsimp [removeTwo, removeOne] + omega + +noncomputable def integerRemovalMatrix (h : (G → ℕ) → ℝ) (n : G → ℕ) : Matrix G G ℝ := + fun u v => if ValidPair n u v then h (removeTwo n u v) else 0 + +noncomputable def removalLiftMatrix (h : (G → ℕ) → ℝ) (n : G → ℕ) (D : ℝ) : + Matrix (Copies n) (Copies n) ℝ := fun i j => if i = j then 0 else + h (removeTwo n i.1 j.1) * factorialProduct (removeTwo n i.1 j.1) / D + +/-- The actual omission matrix of the first factorial lift, with all +integer invalid-removal entries set to zero. -/ +theorem removalLift_onePositive (h : (G → ℕ) → ℝ) (n : G → ℕ) (D : ℝ) + (hD : 0 < D) (hh : ∀ r, 0 ≤ h r) + (hsig : OnePositiveDirection (integerRemovalMatrix h n).toBilin') : + OnePositiveDirection (removalLiftMatrix h n D).toBilin' := by + have heq : removalLiftMatrix h n D = factorialMatrix n (integerRemovalMatrix h n) D := by + ext i j + by_cases hij : i = j + · simp [removalLiftMatrix, factorialMatrix, hij] + have hv := distinct_copy_counts n i j hij + simp [removalLiftMatrix, factorialMatrix, hij, integerRemovalMatrix, ValidPair, hv] + rw [heq] + apply factorialMatrix_onePositive n _ D hD + · intro u v + simp only [integerRemovalMatrix, validPair_symm n u v, removeTwo_comm n u v] + · exact hsig + · intro u + unfold integerRemovalMatrix + split_ifs <;> simp [hh] + · intro u hu + have hn : ¬ValidPair n u u := by simp [ValidPair]; omega + simp [integerRemovalMatrix, hn] + +def addTwo (r : G → ℕ) (u v : G) : G → ℕ := + fun w => r w + (if w = u then 1 else 0) + (if w = v then 1 else 0) + +noncomputable def integerAdditionMatrix (h : (G → ℕ) → ℝ) (r n : G → ℕ) : Matrix G G ℝ := + fun u v => if ValidPair n u v then h (addTwo r u v) else 0 + +noncomputable def additionLiftMatrix (h : (G → ℕ) → ℝ) (r n : G → ℕ) (D : ℝ) : + Matrix (Copies n) (Copies n) ℝ := fun i j => if i = j then 0 else + h (addTwo r i.1 j.1) * factorialProduct (removeTwo n i.1 j.1) / D + +/-- The actual addition matrix of the complementary factorial lift uses +remaining-capacity factorials, and hence exactly the same congruence. -/ +theorem additionLift_onePositive (h : (G → ℕ) → ℝ) (r n : G → ℕ) (D : ℝ) + (hD : 0 < D) (hh : ∀ a, 0 ≤ h a) + (hsig : OnePositiveDirection (integerAdditionMatrix h r n).toBilin') : + OnePositiveDirection (additionLiftMatrix h r n D).toBilin' := by + have heq : additionLiftMatrix h r n D = factorialMatrix n (integerAdditionMatrix h r n) D := by + ext i j + by_cases hij : i = j + · simp [additionLiftMatrix, factorialMatrix, hij] + have hv := distinct_copy_counts n i j hij + simp [additionLiftMatrix, factorialMatrix, hij, integerAdditionMatrix, ValidPair, hv] + rw [heq] + apply factorialMatrix_onePositive n _ D hD + · intro u v + have heq : addTwo r u v = addTwo r v u := by funext w; dsimp [addTwo]; omega + simp only [integerAdditionMatrix, validPair_symm n u v, heq] + · exact hsig + · intro u + unfold integerAdditionMatrix + split_ifs <;> simp [hh] + · intro u hu + have hn : ¬ValidPair n u u := by simp [ValidPair]; omega + simp [integerAdditionMatrix, hn] + + +noncomputable def cellFactor (b x y : ℕ) : ℝ := + (x.factorial : ℝ) * y.factorial / b.factorial + +noncomputable def complementCellFactor (b x y : ℕ) : ℝ := + ((b - x).factorial : ℝ) * (b - y).factorial / b.factorial + +omit [Fintype G] [DecidableEq G] in +lemma cellFactor_positive (b x y : ℕ) : 0 < cellFactor b x y := by + exact div_pos (mul_pos (by exact_mod_cast Nat.factorial_pos x) + (by exact_mod_cast Nat.factorial_pos y)) (by exact_mod_cast Nat.factorial_pos b) + +omit [Fintype G] [DecidableEq G] in +/-- On transversals, the two cell multipliers agree exactly. -/ +lemma balanced_cell_factors (b x y : ℕ) (h : x + y = b) : + complementCellFactor b x y = cellFactor b x y := by + have hx : b - x = y := by omega + have hy : b - y = x := by omega + simp only [complementCellFactor, cellFactor, hx, hy] + ring + +omit [Fintype G] [DecidableEq G] in +/-- The empty-pair cell contributes `(x+1)(y+1)` to the lift ratio. -/ +lemma empty_cell_factors (b x y : ℕ) (h : x + y + 1 = b) : + complementCellFactor b x y = ((x : ℝ) + 1) * ((y : ℝ) + 1) * cellFactor b x y := by + have hx : b - x = y + 1 := by omega + have hy : b - y = x + 1 := by omega + simp only [complementCellFactor, cellFactor, hx, hy, Nat.factorial_succ, Nat.cast_mul, + Nat.cast_add, Nat.cast_one] + ring + +omit [Fintype G] [DecidableEq G] in +/-- The full-pair cell contributes the reciprocal product `1/(xy)`. -/ +lemma full_cell_factors (b x y : ℕ) (hx : x ≤ b) (hy : y ≤ b) (h : x + y = b + 1) : + complementCellFactor b x y * ((x : ℝ) * y) = cellFactor b x y := by + have hx0 : x ≠ 0 := by omega + have hy0 : y ≠ 0 := by omega + have hbx : b - x = y - 1 := by omega + have hby : b - y = x - 1 := by omega + have hxf : (x : ℝ) * ((x - 1).factorial : ℝ) = x.factorial := by + exact_mod_cast Nat.mul_factorial_pred hx0 + have hyf : (y : ℝ) * ((y - 1).factorial : ℝ) = y.factorial := by + exact_mod_cast Nat.mul_factorial_pred hy0 + simp only [complementCellFactor, cellFactor, hbx, hby] + calc + _ = ((x : ℝ) * ((x - 1).factorial : ℝ)) * + ((y : ℝ) * ((y - 1).factorial : ℝ)) / b.factorial := by ring + _ = _ := by rw [hxf, hyf] + +omit [Fintype G] [DecidableEq G] in +lemma quotient_square_bounds (W A B : ℝ) (hW : 0 < W) + (hA0 : 1 ≤ A) (hB0 : 1 ≤ B) (hA : A ≤ W ^ 2) (hB : B ≤ W ^ 2) : + 1 / W ^ 2 ≤ A / B ∧ A / B ≤ W ^ 2 := by + have hWp : 0 < W ^ 2 := sq_pos_of_pos hW + have hBp : 0 < B := by linarith + constructor + · apply (div_le_div_iff₀ hWp hBp).mpr + nlinarith + · apply (div_le_iff₀ hBp).mpr + nlinarith + +/-- The product ratio when one cell contains the hole, one contains the +full pair, and all remaining cells are balanced. -/ +lemma defect_product_identity (F T : G → ℝ) (a b : G) (hab : a ≠ b) (A B : ℝ) + (ha : T a = A * F a) (hb : T b = F b / B) + (hrest : ∀ u, u ≠ a → u ≠ b → T u = F u) : + (∏ u, T u) = (A / B) * ∏ u, F u := by + have heq : T = fun u => + (if u = a then A else 1) * (if u = b then 1 / B else 1) * F u := by + funext u + by_cases hua : u = a + · subst u + simp [hab, ha] + by_cases hub : u = b + · subst u + simp [Ne.symm hab, hb, div_eq_mul_inv, mul_comm] + · simp [hua, hub, hrest u hua hub] + rw [heq] + simp only [Finset.prod_mul_distrib] + simp [Finset.prod_ite_eq', div_eq_mul_inv, mul_assoc] + +/-- The exact `q = W²` comparison between the two factorial lifts on a +single-hole/single-full defect, after their common positive base weight. -/ +theorem defect_lift_comparison (b x y : G → ℕ) (a d : G) (had : a ≠ d) + (W : ℕ) (hW : 0 < W) (hbW : ∀ u, b u < W) + (hx : ∀ u, x u ≤ b u) (hy : ∀ u, y u ≤ b u) + (ha : x a + y a + 1 = b a) (hd : x d + y d = b d + 1) + (hrest : ∀ u, u ≠ a → u ≠ d → x u + y u = b u) + (h : ℝ) (hh : 0 ≤ h) : + (1 / (W : ℝ) ^ 2) * (h * ∏ u, cellFactor (b u) (x u) (y u)) ≤ + h * ∏ u, complementCellFactor (b u) (x u) (y u) ∧ + (h * ∏ u, complementCellFactor (b u) (x u) (y u)) ≤ + (W : ℝ) ^ 2 * (h * ∏ u, cellFactor (b u) (x u) (y u)) := by + let A : ℝ := ((x a : ℝ) + 1) * ((y a : ℝ) + 1) + let B : ℝ := (x d : ℝ) * y d + have hxd : 1 ≤ x d := by have := hy d; omega + have hyd : 1 ≤ y d := by have := hx d; omega + have hBpos : 0 < B := by + dsimp [B] + exact mul_pos (by exact_mod_cast hxd) (by exact_mod_cast hyd) + have hprod : (∏ u, complementCellFactor (b u) (x u) (y u)) = + (A / B) * ∏ u, cellFactor (b u) (x u) (y u) := by + apply defect_product_identity _ _ a d had A B + · exact empty_cell_factors _ _ _ ha + · exact (eq_div_iff (ne_of_gt hBpos)).mpr (full_cell_factors _ _ _ (hx d) (hy d) hd) + · intro u hua hud + exact balanced_cell_factors _ _ _ (hrest u hua hud) + have hbounds : 1 / (W : ℝ) ^ 2 ≤ A / B ∧ A / B ≤ (W : ℝ) ^ 2 := by + apply quotient_square_bounds _ A B (by exact_mod_cast hW) + · dsimp [A] + have hxa : (0 : ℝ) ≤ x a := Nat.cast_nonneg _ + have hya : (0 : ℝ) ≤ y a := Nat.cast_nonneg _ + nlinarith + · dsimp [B] + have hxd' : (1 : ℝ) ≤ x d := by exact_mod_cast hxd + have hyd' : (1 : ℝ) ≤ y d := by exact_mod_cast hyd + nlinarith + · dsimp [A] + have hxa : (x a : ℝ) + 1 ≤ W := by exact_mod_cast (by have := hx a; have := hbW a; omega : x a + 1 ≤ W) + have hya : (y a : ℝ) + 1 ≤ W := by exact_mod_cast (by have := hy a; have := hbW a; omega : y a + 1 ≤ W) + have hxa0 : 0 ≤ (x a : ℝ) + 1 := by positivity + have hya0 : 0 ≤ (y a : ℝ) + 1 := by positivity + nlinarith + · dsimp [B] + have hxdW : (x d : ℝ) ≤ W := by exact_mod_cast (by have := hx d; have := hbW d; omega : x d ≤ W) + have hydW : (y d : ℝ) ≤ W := by exact_mod_cast (by have := hy d; have := hbW d; omega : y d ≤ W) + have hxd0 : (0 : ℝ) ≤ x d := Nat.cast_nonneg _ + have hyd0 : (0 : ℝ) ≤ y d := Nat.cast_nonneg _ + nlinarith + have hF : 0 ≤ h * ∏ u, cellFactor (b u) (x u) (y u) := + mul_nonneg hh (Finset.prod_nonneg (fun u _ => (cellFactor_positive _ _ _).le)) + rw [hprod] + constructor + · convert mul_le_mul_of_nonneg_right hbounds.1 hF using 1 + ring + · convert mul_le_mul_of_nonneg_right hbounds.2 hF using 1 + ring + + +omit [DecidableEq G] in +/-- Agreement of the actual full factorial multipliers on every balanced profile. -/ +theorem balanced_lift_agreement (b x y : G → ℕ) + (hbalanced : ∀ u, x u + y u = b u) (h : ℝ) : + h * (∏ u, complementCellFactor (b u) (x u) (y u)) = + h * ∏ u, cellFactor (b u) (x u) (y u) := by + congr 1 + apply Finset.prod_congr rfl + intro u _ + exact balanced_cell_factors _ _ _ (hbalanced u) + +end ContingencyTables.FactorialSignatures + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAcceptCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAcceptCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7debd2e10f8122581e90f3941bd0bb4534cb28c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAcceptCounts.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolis +import OAI.Combinatorics.ContingencyTables.Transport.DyadicAcceptance +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPropagation + +namespace OAI + +/-! # Integer transition counts without enumerating acceptance bits -/ + +namespace ContingencyTables.FiniteAcceptCounts +open ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section +variable {α β : Type*} [Fintype α] [DecidableEq α] [Fintype β] [Nonempty β] + +def denominator (K : ℕ) : ℕ := Fintype.card β * 2^K + +def offCount (a : α) (proposal : β → Option α) (gap : α → ℕ) (K : ℕ) (b : α) : ℕ := + if b=a then 0 else + (Finset.univ.filter (fun z => proposal z=some b)).card * 2^(K-gap b) + +def row (a : α) (proposal : β → Option α) (gap : α → ℕ) (K : ℕ) (b : α) : ℕ := + offCount a proposal gap K b + + if b=a then denominator (β := β) K - ∑ x,offCount a proposal gap K x else 0 + +lemma denominator_pos (K : ℕ) : 0 FairBits.acceptDyadic (gap b) K)).mass b := by + rw [finiteAcceptLaw_off_diagonal a b proposal _ hba.symm] + rw [Finset.filter_congr_decidable (Finset.univ : Finset (Fin (2^K))) + (FairBits.acceptDyadic (gap b) K) (fun _ => Classical.propDecidable _)] + rw [FairBits.acceptDyadic_count] + simp only [offCount,ite_eq_right hba,denominator,Nat.cast_mul,Nat.cast_pow, + Nat.cast_ofNat,Fintype.card_fin] + exact (div_mul_div_comm + ((Finset.univ.filter (fun z => proposal z=some b)).card:ℚ) + (Fintype.card β) (2^(K-gap b)) (2^K)).symm + +lemma offCount_sum_le (a : α) (proposal : β → Option α) (gap : α → ℕ) (K : ℕ) : + (∑ b,offCount a proposal gap K b) ≤ denominator (β := β) K := by + let p:=finiteAcceptLaw a proposal (fun b => FairBits.acceptDyadic (gap b) K) + have hQ : (0:ℚ) hb b) + rw [←Finset.sum_div,←Nat.cast_sum,p.total] at hs + exact_mod_cast (div_le_one hQ).mp hs + +lemma row_total (a : α) (proposal : β → Option α) (gap : α → ℕ) (K : ℕ) : + ∑ b,row a proposal gap K b=denominator (β := β) K := by + simp only [row,Finset.sum_add_distrib,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + exact Nat.add_sub_of_le (offCount_sum_le a proposal gap K) + +/-- The diagonal count is recovered from the row total; all other entries +use a proposal count and one binary power, independently of `2^K` coins. -/ +theorem row_kernel (a : α) (proposal : α → β → Option α) (gap : α → α → ℕ) (K : ℕ) : + (IntegerPropagation.kernel (fun a b => row a (proposal a) (gap a) K b) + (denominator (β := β) K) (denominator_pos K) + (fun x => row_total x (proposal x) (gap x) K) a) = + finiteAcceptLaw a (proposal a) (fun b => FairBits.acceptDyadic (gap a b) K) := by + apply RationalLaw.eq_of_off_diagonal _ _ a + intro b hba + change (row a (proposal a) (gap a) K b:ℚ)/denominator (β := β) K=_ + simp only [row,ite_eq_right hba,add_zero] + exact offCount_mass a b (proposal a) (gap a) K hba + +end +end ContingencyTables.FiniteAcceptCounts + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAdaptiveObservable.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAdaptiveObservable.lean new file mode 100644 index 0000000000000000000000000000000000000000..24f48463123618cae6bd50f15cf1938581e3668a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteAdaptiveObservable.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport + +namespace OAI + +/-! # Observable laws under adaptive finite-word calls + +The stored state may include rational estimates and is not assumed +finite. Each fresh word is finite; equality of every conditional call +therefore suffices for equality of the entire executed history. +-/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS +open scoped Classical + +noncomputable section + +variable {X Y U V Z W : Type*} +variable [Fintype X] [Fintype Y] [Fintype U] [Fintype V] + +theorem SameLaw.bind {f : X → Z} {g : Y → Z} (hfg : SameLaw f g) + (F : Z → U → W) (G : Z → V → W) (h : ∀ z,SameLaw (F z) (G z)) : + SameLaw (fun xu : X × U => F (f xu.1) xu.2) + (fun yv : Y × V => G (g yv.1) yv.2) := by + intro phi + rw [uniformAverage_prod,uniformAverage_prod] + have hi (x : X) := h (f x) phi + simp_rw [hi] + exact hfg (fun z => uniformAverage (fun v : V => phi (G z v))) + +def adaptiveRun (step : Z → X → Z) (z : Z) : (N : ℕ) → (Fin N → X) → Z + | 0,_ => z + | N+1,xs => adaptiveRun step (step z (xs 0)) N (Fin.tail xs) + +theorem adaptiveRun_sameLaw (F : Z → X → Z) (G : Z → Y → Z) + (h : ∀ z,SameLaw (F z) (G z)) (z : Z) (N : ℕ) : + SameLaw (adaptiveRun F z N) (adaptiveRun G z N) := by + intro phi + induction N generalizing z with + | zero => simp only [adaptiveRun,uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp only [adaptiveRun,Fin.cons_zero,Fin.tail_cons] + have hi (x : X) := ih (F z x) + simp_rw [hi] + exact h z (fun next => uniformAverage (fun ys : Fin N → Y => + phi (adaptiveRun G next N ys))) + +def appendStep (step : List Z → X → Z) (history : List Z) (x : X) : List Z := + history++[step history x] + +theorem appendStep_sameLaw (F : List Z → X → Z) (G : List Z → Y → Z) + (h : ∀ history,SameLaw (F history) (G history)) (history : List Z) : + SameLaw (appendStep F history) (appendStep G history) := + (h history).map (fun z => history++[z]) + +/-- This transports complete stored histories, hence also every final +estimate and every abort event obtained from that history. -/ +theorem adaptiveHistory_sameLaw (F : List Z → X → Z) (G : List Z → Y → Z) + (h : ∀ history,SameLaw (F history) (G history)) (history : List Z) (N : ℕ) : + SameLaw (adaptiveRun (appendStep F) history N) + (adaptiveRun (appendStep G) history N) := + adaptiveRun_sameLaw _ _ (appendStep_sameLaw F G h) history N + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBiasedAverages.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBiasedAverages.lean new file mode 100644 index 0000000000000000000000000000000000000000..87386af57dcc6738693df9f10a6efbbb3d4e1bd9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBiasedAverages.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentAverages + +namespace OAI + +/-! # Independent finite experiments with an explicitly bounded mean bias -/ + +namespace ContingencyTables.FiniteIndependentAverages + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} [Fintype X] [Nonempty X] + +theorem sampleAverage_absolute_failure (g : X → ℝ) (N : ℕ) (hN : 0 < N) + (r : ℝ) (hr : 0 < r) : + uniformAverage (fun xs : Fin N → X => + if r < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) ≤ + uniformAverage (fun x => (g x-uniformAverage g)^2)/(N*r^2) := by + have hp (xs : Fin N → X) : + (if r < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) ≤ + (sampleAverage g N xs-uniformAverage g)^2/r^2 := by + split_ifs with h + · rw [le_div_iff₀ (sq_pos_of_pos hr)] + simpa only [one_mul,sq_abs] using + (sq_le_sq₀ hr.le (abs_nonneg _)).mpr h.le + · positivity + calc + _ ≤ uniformAverage (fun xs : Fin N → X => + (sampleAverage g N xs-uniformAverage g)^2/r^2) := uniformAverage_mono _ _ hp + _ = _ := by + simp_rw [div_eq_mul_inv] + rw [uniformAverage_mul_const,sampleAverage_secondMoment g N hN] + ring + +lemma bounded_variance (g : X → ℝ) (U : ℝ) + (hg : ∀ x,0 ≤ g x ∧ g x ≤ U) : + uniformAverage (fun x => (g x-uniformAverage g)^2) ≤ U^2 := by + have hm := mean_bounds g 0 U hg + have hU : 0 ≤ U := hm.1.trans hm.2 + have hp (x : X) : (g x-uniformAverage g)^2 ≤ U^2 := by + have habs : |g x-uniformAverage g| ≤ U := abs_le.mpr ⟨by linarith [(hg x).1],by linarith [(hg x).2]⟩ + simpa only [sq_abs] using (sq_le_sq₀ (abs_nonneg _) hU).mpr habs + simpa only [uniformAverage_const] using uniformAverage_mono _ (fun _ : X => U^2) hp + +/-- The target is an exact mathematical mean; the experiment's own mean +may differ, but only by the displayed deterministic bias. -/ +theorem biased_target_failure (g : X → ℝ) (U target delta : ℝ) + (hg : ∀ x,0 ≤ g x ∧ g x ≤ U) (htarget : 0 < target) (hdelta : 0 < delta) + (hbias : |uniformAverage g-target| ≤ delta*target/2) + (N : ℕ) (hN : 0 < N) : + uniformAverage (fun xs : Fin N → X => + if delta*target < |sampleAverage g N xs-target| then (1:ℝ) else 0) ≤ + 4*U^2/(N*(delta*target)^2) := by + have hr : 0 < delta*target/2 := by positivity + have hp (xs : Fin N → X) : + (if delta*target < |sampleAverage g N xs-target| then (1:ℝ) else 0) ≤ + if delta*target/2 < |sampleAverage g N xs-uniformAverage g| then 1 else 0 := by + split_ifs with h h' + · rfl + · exfalso + have hh : |sampleAverage g N xs-target| ≤ + |sampleAverage g N xs-uniformAverage g|+|uniformAverage g-target| := by + simpa only [sub_add_sub_cancel] using abs_add_le + (sampleAverage g N xs-uniformAverage g) (uniformAverage g-target) + have hn := le_of_not_gt h' + linarith + · norm_num + · rfl + have hNR : (0:ℝ) < N := by exact_mod_cast hN + calc + _ ≤ uniformAverage (fun xs : Fin N → X => + if delta*target/2 < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) := + uniformAverage_mono _ _ hp + _ ≤ uniformAverage (fun x => (g x-uniformAverage g)^2)/(N*(delta*target/2)^2) := + sampleAverage_absolute_failure g N hN _ hr + _ ≤ U^2/(N*(delta*target/2)^2) := + div_le_div_of_nonneg_right (bounded_variance g U hg) (by positivity) + _ = _ := by + field_simp [hNR.ne',hdelta.ne',htarget.ne']; ring + +end + +end ContingencyTables.FiniteIndependentAverages + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBoundedProjectedHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBoundedProjectedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..52be756396090bae4a6d432079daa36e1c885ce0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteBoundedProjectedHistory.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteProjectedHistory + +namespace OAI + +/-! # Projected adaptive laws up to the prescribed number of phases -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS +open scoped Classical +noncomputable section + +theorem bounded_projected_foldl_sameLaw {C Z U V : Type*} [Fintype U] [Fintype V] + (F : C→U→C) (G : Z→V→Z) (e : C→Z) (Valid : C→Prop) + (size : C→ℕ) (H : ℕ) + (hsize : ∀ c u,size (F c u)=size c+1) + (hvalid : ∀ c,Valid c→size c e (F c u)) (G (e c))) + (c : C) (hc : Valid c) (N : ℕ) (hN : size c+N≤H) : + SameLaw (fun us : Fin N→U => e ((List.ofFn us).foldl F c)) + (fun vs : Fin N→V => (List.ofFn vs).foldl G (e c)) := by + intro phi + induction N generalizing c phi with + | zero => simp only [List.ofFn_zero,List.foldl_nil,uniformAverage_const] + | succ N ih => + have hlt : size c uniformAverage (fun vs : Fin N→V => + phi ((List.ofFn vs).foldl G z))) + have hl : uniformAverage (fun u : U => uniformAverage (fun us : Fin N→U => + phi (e ((List.ofFn us).foldl F (F c u)))))= + uniformAverage (fun u : U => uniformAverage (fun vs : Fin N→V => + phi ((List.ofFn vs).foldl G (e (F c u))))) := by + apply congrArg uniformAverage + funext u + apply ih (F c u) (hvalid c hc hlt u) + rw [hsize] + omega + exact hl.trans h + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainGraphComparison.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainGraphComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3e126524518307d486d91fe50c452eb68803694 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainGraphComparison.lean @@ -0,0 +1,30 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteChainWeightVariance + +namespace OAI + +/-! # Normalize a weighted graph inequality for its reversible chain -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators +open CommonBasesFPRAS + +variable {X : Type*} [Fintype X] [Nonempty X] + +lemma chain_poincare_of_weighted_graph (C : FiniteChain X) (w H : X → ℝ) + (hw : ∀ x,0 < w x) (hπ : ∀ x,C.π x=w x/(∑ y,w y)) + (E K β : ℝ) (hK : 0 ≤ K) (hβ : 0 < β) + (hv : variance w H ≤ K*E) + (he : β/(2*(∑ x,w x))*E ≤ C.energy H) : + C.variance H ≤ (2*K/β)*C.energy H := by + have hZ : 0 < ∑ x,w x := Finset.sum_pos (fun x _ => hw x) Finset.univ_nonempty + rw [chain_variance_eq C w H hπ] + calc + _ ≤ K*E/(∑ x,w x) := div_le_div_of_nonneg_right hv (le_of_lt hZ) + _ = (2*K/β)*(β/(2*(∑ x,w x))*E) := by + field_simp [ne_of_gt hβ,ne_of_gt hZ] + _ ≤ _ := mul_le_mul_of_nonneg_left he (by positivity) + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainSlowdown.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainSlowdown.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d183594528312cf2959f985f6ed9293795dc07c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainSlowdown.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Exact holding slowdown of finite reversible chains -/ + +namespace ContingencyTables.FiniteChainSlowdown + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} [Fintype X] + +def slow (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) : FiniteChain X where + P x y := a*C.P x y+if x=y then 1-a else 0 + π := C.π + positive := C.positive + normalized := C.normalized + nonnegative x y := by + apply add_nonneg (mul_nonneg ha0 (C.nonnegative x y)) + split_ifs + · linarith + · rfl + stochastic x := by + simp only [Finset.sum_add_distrib,←Finset.mul_sum,C.stochastic,mul_one] + simp + reversible x y := by + by_cases h : x=y + · subst y + rfl + · simp only [h,Ne.symm h,ite_false,add_zero] + nlinarith [C.reversible x y] + lazy x := by + simp only [ite_true] + have hm := mul_le_mul_of_nonneg_left (C.lazy x) ha0 + linarith + +lemma stationary (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) : + (slow C a ha0 ha1).π=C.π := rfl + +lemma mean (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) (f : X → ℝ) : + (slow C a ha0 ha1).mean f=C.mean f := rfl + +lemma variance (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) (f : X → ℝ) : + (slow C a ha0 ha1).variance f=C.variance f := rfl + +/-- Every off-diagonal move and the Dirichlet energy are scaled by the +same holding factor. No irreducibility or nonzero denominator is needed. -/ +theorem energy (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) (f : X → ℝ) : + (slow C a ha0 ha1).energy f=a*C.energy f := by + rw [FiniteChain.energy_eq,FiniteChain.energy_eq,←mul_div_assoc] + congr 1 + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + change C.π x*(a*C.P x y+if x=y then 1-a else 0)*(f x-f y)^2= + a*(C.π x*C.P x y*(f x-f y)^2) + by_cases h : x=y + · subst y + simp + · simp only [h,ite_false,add_zero] + ring + +/-- A holding factor at least one half increases every applicable +variance/energy bound by at most two, including bounds restricted to the +specific observables used by the counting algorithm. -/ +theorem variance_bound (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (ha : 1/2 ≤ a) (K : ℝ) (hK : 0 ≤ K) (f : X → ℝ) + (h : C.variance f ≤ K*C.energy f) : + (slow C a ha0 ha1).variance f ≤ (2*K)*(slow C a ha0 ha1).energy f := by + rw [variance,energy] + have hm := mul_le_mul_of_nonneg_right ha (C.energy_nonneg f) + have hh := mul_le_mul_of_nonneg_left hm hK + nlinarith + +end + +end ContingencyTables.FiniteChainSlowdown + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainWeightVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainWeightVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6cb286aa17c66594acd67080446deeda7c5f134 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChainWeightVariance.lean @@ -0,0 +1,31 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance + +namespace OAI + +/-! # Normalizing a finite weighted variance -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators +open CommonBasesFPRAS + +variable {X : Type*} [Fintype X] + +lemma chain_variance_eq (C : FiniteChain X) (w H : X → ℝ) + (hπ : ∀ x,C.π x=w x/(∑ y,w y)) : + C.variance H=variance w H/(∑ x,w x) := by + have hm : C.mean H=mean w H := by + unfold FiniteChain.mean mean + simp_rw [hπ,div_mul_eq_mul_div] + rw [← Finset.sum_div] + unfold FiniteChain.variance FiniteChain.inner variance + rw [hm] + simp_rw [hπ] + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro x _ + ring + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChoiceFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChoiceFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..45911926bf50339fd8cc843da0993a0d1397c19b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteChoiceFibres.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FinitePartitionVariance + +namespace OAI + +/-! # Finite fibre sums with their literal subtype enumeration -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical + +lemma double_fibreWeight_mul {X C D : Type*} (w H : X → ℝ) + (π : X → C) (ρ : X → D) (c : C) (d : D) (x : X) : + fibreWeight (fibreWeight (fun a => w a*H a) π c) ρ d x= + fibreWeight (fibreWeight w π c) ρ d x*H x := by + rw [fibreWeight_pair,fibreWeight_mul,← fibreWeight_pair] + +theorem double_fibre_sum {X C D : Type*} [Fintype X] + (w : X → ℝ) (π : X → C) (ρ : X → D) (c : C) (d : D) + [Fintype {x : X // π x=c ∧ ρ x=d}] : + (∑ x,fibreWeight (fibreWeight w π c) ρ d x)= + ∑ x : {x : X // π x=c ∧ ρ x=d},w x.val := by + have he (x : X) : fibreWeight (fibreWeight w π c) ρ d x= + if π x=c ∧ ρ x=d then w x else 0 := by + unfold fibreWeight + by_cases hp : π x=c <;> by_cases hρ : ρ x=d <;> + simp only [hp,hρ,↓reduceIte,and_self,false_and,and_false] + calc + _ = ∑ x,if π x=c ∧ ρ x=d then w x else 0 := Finset.sum_congr rfl (fun x _ => he x) + _ = ∑ x ∈ Finset.univ.filter (fun x => π x=c ∧ ρ x=d),w x := (Finset.sum_filter _ _).symm + _ = _ := Finset.sum_subtype _ (by simp) w + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteCorrectionLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteCorrectionLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..9949979f38905e588840f52a9333555aee083441 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteCorrectionLaw.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFiniteSampler +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCorrectionBudget + +namespace OAI + +/-! # Exact residual correction of the initialized finite sampler -/ + +namespace ContingencyTables.FirstSuccess +open ResidualMixture +open scoped BigOperators Classical + +lemma variation_point_le {X : Type*} [Fintype X] (p q : RationalLaw X) (x : X) : + |p.mass x-q.mass x| ≤ variation p q := by + classical + have hm : (∑ y,(p.mass y:ℝ))=∑ y,(q.mass y:ℝ) := by + exact_mod_cast p.total.trans q.total.symm + have h := RealKernelApproximation.distance_event + (fun y => (p.mass y:ℝ)) (fun y => (q.mass y:ℝ)) hm {x} + simp only [Finset.sum_singleton] at h + have hd : RealKernelApproximation.distance (fun y => (p.mass y:ℝ)) + (fun y => (q.mass y:ℝ))=(variation p q:ℝ) := by + simp only [RealKernelApproximation.distance,variation,Rat.cast_div,Rat.cast_sum, + Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat] + rw [hd] at h + exact_mod_cast h + +/-- Total variation at most the square of the rare-branch probability +implies the exact pointwise domination required by residual correction. -/ +theorem residual_from_variation {X : Type*} [Fintype X] [Nonempty X] + (p : RationalLaw X) (delta : ℚ) (hd : 0 < delta) (hd1 : delta ≤ 1) + (hcard : (Fintype.card X:ℚ)*delta ≤ 1) + (herror : variation p (uniformLaw (α := X)) ≤ delta^2) : + ∃ q : RationalLaw X,∀ x,(1-delta)*p.mass x+delta*q.mass x=uniformMass (α := X) := by + apply exact_correction p hd hd1 hcard + intro x + have h := variation_point_le p (uniformLaw (α := X)) x + have hu : (uniformLaw (α := X)).mass x=uniformMass (α := X) := rfl + rw [hu] at h + linarith [(abs_le.mp (h.trans herror)).2] + +end ContingencyTables.FirstSuccess + +namespace ContingencyTables.SmallGraphProfiles +open ResidualMixture FirstSuccess FairBits CompletionCounts +open scoped BigOperators Classical + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "D" => correctionPrecision r c + +/-- The rare correction law for the actual initialized finite experiment. +This establishes its exact probability identity; tabulation and execution +of this law are separate implementation obligations. -/ +theorem initialized_residual_correction (htotal : (∑ i,r i)=∑ j,c j) + (a : GridBoundary.Grid (I := Fin q) (4*d^8)) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin q) (4*d^8))) : + let _ : Nonempty (Table r c) := ⟨GreedyFeasibleTable.reindexed r c htotal⟩ + let p := mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c (2*D)) → Bool)) + (initializedFiniteDraw r c i₀ j₀ e (2*D) htotal a) + ∃ residual : RationalLaw (Table r c),∀ x, + (1-1/(2:ℚ)^D)*p.mass x+(1/(2:ℚ)^D)*residual.mass x=uniformMass (α := Table r c) := by + let : Nonempty (Table r c) := ⟨GreedyFeasibleTable.reindexed r c htotal⟩ + have hd : 1 ≤ d := by unfold dimensionAllowance; omega + have hb : 1 ≤ smallBinaryLength r c := hd.trans (smallBinaryLength_parameters r c).2.1 + have hD : 1 ≤ D := Nat.mul_le_mul (one_le_pow₀ hd) (one_le_pow₀ hb) + apply residual_from_variation + · exact one_div_pos.mpr (pow_pos (by norm_num) _) + · exact (div_le_one (pow_pos (by norm_num) _)).mpr (one_le_pow₀ (by norm_num)) + · exact correction_card_mass r c + · have h := initializedFiniteDraw_variation r c i₀ j₀ e (2*D) (by omega) htotal a hPL hCheeger + have he : (1/(2:ℚ)^D)^2=1/(2:ℚ)^(2*D) := by + rw [div_pow,one_pow,←pow_mul,Nat.mul_comm D 2] + rw [he] + apply (Rat.cast_le (K := ℝ)).mp + simpa only [Rat.cast_div,Rat.cast_pow,Rat.cast_one,Rat.cast_ofNat] using h + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..3bb11e170f00ac5499620a0cc80d5a58547cc5be --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentApproximation.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentLaw +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalkApproximation + +namespace OAI + +/-! # Total variation for state-dependent finite completion laws -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {X : Type*} {Y : X → Type*} [Fintype X] [∀ x,Fintype (Y x)] + +theorem variation_dependentJoint (p q : RationalLaw X) + (K L : (x : X) → RationalLaw (Y x)) : + variation (dependentJointLaw p K) (dependentJointLaw q L) ≤ + variation p q+∑ x,p.mass x*variation (K x) (L x) := by + have hpoint (x : X) (y : Y x) : + |p.mass x*(K x).mass y-q.mass x*(L x).mass y| ≤ + p.mass x*|(K x).mass y-(L x).mass y|+|p.mass x-q.mass x| *(L x).mass y := by + calc + _ = |p.mass x*((K x).mass y-(L x).mass y)+(p.mass x-q.mass x)*(L x).mass y| := by + congr 1 + ring + _ ≤ |p.mass x*((K x).mass y-(L x).mass y)|+|(p.mass x-q.mass x)*(L x).mass y| := + abs_add_le _ _ + _ = _ := by + rw [abs_mul,abs_mul,abs_of_nonneg (p.nonnegative x),abs_of_nonneg ((L x).nonnegative y)] + have hsum := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => + Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => hpoint x y)) + simp only [Finset.sum_add_distrib,←Finset.mul_sum,(L _).total,mul_one] at hsum + unfold variation + change (∑ a : (x : X) × Y x,|p.mass a.1*(K a.1).mass a.2-q.mass a.1*(L a.1).mass a.2|)/2 ≤ _ + rw [Fintype.sum_sigma] + have hh := div_le_div_of_nonneg_right hsum (show (0:ℚ) ≤ 2 by norm_num) + convert hh using 1 + simp only [add_div,Finset.sum_div,mul_div_assoc] + ring + +theorem variation_dependentJoint_uniform (p q : RationalLaw X) + (K L : (x : X) → RationalLaw (Y x)) (η : ℚ) + (hη : ∀ x,variation (K x) (L x) ≤ η) : + variation (dependentJointLaw p K) (dependentJointLaw q L) ≤ variation p q+η := by + calc + _ ≤ variation p q+∑ x,p.mass x*variation (K x) (L x) := variation_dependentJoint p q K L + _ ≤ variation p q+∑ x,p.mass x*η := by + apply add_le_add_right + exact Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hη x) (p.nonnegative x)) + _ = _ := by rw [←Finset.sum_mul,p.total,one_mul] + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5555ac340485e10d84adeb91953770123c489cff --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDependentLaw.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Exact joint laws with a finite state-dependent completion space -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +variable {X : Type*} {Y : X → Type*} [Fintype X] [∀ x,Fintype (Y x)] + +def dependentJointLaw (p : RationalLaw X) (q : (x : X) → RationalLaw (Y x)) : + RationalLaw ((x : X) × Y x) where + mass := fun a => p.mass a.1*(q a.1).mass a.2 + nonnegative := fun a => mul_nonneg (p.nonnegative a.1) ((q a.1).nonnegative a.2) + total := by + rw [Fintype.sum_sigma] + simp only [←Finset.mul_sum,(q _).total,mul_one,p.total] + +variable [Nonempty X] [∀ x,Nonempty (Y x)] + +instance dependentJointNonempty : Nonempty ((x : X) × Y x) := + ⟨⟨Classical.choice ‹Nonempty X›, Classical.choice (inferInstance : Nonempty (Y (Classical.choice ‹Nonempty X›)))⟩⟩ + +/-- A state chosen in proportion to its completion count, followed by a +uniform completion, gives exactly the uniform law on all joint pairs. -/ +theorem dependentJointLaw_uniform (p : RationalLaw X) + (hp : ∀ x,p.mass x=(Fintype.card (Y x):ℚ)/(∑ z : X,(Fintype.card (Y z):ℚ))) : + dependentJointLaw p (fun x => uniformLaw (α := Y x))= + uniformLaw (α := (x : X) × Y x) := by + apply RationalLaw.ext + funext a + have hcard : (Fintype.card (Y a.1):ℚ)≠0 := by + exact_mod_cast (Fintype.card_pos (α := Y a.1)).ne' + change p.mass a.1*(1/(Fintype.card (Y a.1):ℚ))=1/(Fintype.card ((x : X) × Y x):ℚ) + rw [hp,Fintype.card_sigma,Nat.cast_sum] + field_simp + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDeterministicJoint.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDeterministicJoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..02ccd4c7e5af1cddf00ac89ba16d95ae17888d53 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDeterministicJoint.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentLaw +import OAI.Combinatorics.ContingencyTables.Transport.RejectionLaw + +namespace OAI + +/-! # Joint laws with a deterministic second coordinate -/ + +namespace ContingencyTables.FirstSuccess +open scoped BigOperators Classical +open ResidualMixture + +variable {X : Type*} {Y : X → Type*} [Fintype X] [∀ x,Fintype (Y x)] + +lemma mapLaw_deterministicJoint (p : RationalLaw X) (f : (x : X) → Y x) : + mapLaw p (fun x => (⟨x,f x⟩ : Sigma Y))= + dependentJointLaw p (fun x => pointLaw (f x)) := by + apply RationalLaw.ext + funext a + rcases a with ⟨x,y⟩ + change (∑ z,if (⟨z,f z⟩ : Sigma Y)=⟨x,y⟩ then p.mass z else 0)= + p.mass x*(if y=f x then 1 else 0) + rw [Finset.sum_eq_single x] + · by_cases h : f x=y <;> simp [h,eq_comm] + · intro z _ hz + have hn : (⟨z,f z⟩ : Sigma Y)≠⟨x,y⟩ := fun h => hz (congrArg Sigma.fst h) + simp only [hn,ite_false] + · simp + +lemma pointLaw_eq_uniform {A : Type*} [Fintype A] [Subsingleton A] [Nonempty A] (a : A) : + pointLaw a=uniformLaw (α := A) := by + let : Unique A := ⟨⟨a⟩,fun x => Subsingleton.elim x a⟩ + apply RationalLaw.ext + funext x + simp only [pointLaw,uniformLaw,uniformMass,Subsingleton.elim a x,ite_true, + Fintype.card_unique,Nat.cast_one,div_one] + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDirectedBFS.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDirectedBFS.lean new file mode 100644 index 0000000000000000000000000000000000000000..b89cb217672a50fd2c1d7b3fa82aafba78ee47ea --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteDirectedBFS.lean @@ -0,0 +1,281 @@ +import Mathlib.Data.List.FinRange +import Mathlib.Data.List.Chain +import Mathlib.Data.Fintype.Card +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! # Deterministic directed breadth-first search + +Each round retains every discovered path and scans the vertex list for +one predecessor of each undiscovered vertex. There is one stored path +per vertex; the search does not enumerate candidate paths. +-/ + +namespace ContingencyTables.FiniteDirectedBFS + +variable {n : ℕ} + +/-- A directed walk, including its two endpoints. -/ +inductive Route (E : Fin n → Fin n → Bool) (s : Fin n) : + Fin n → List (Fin n) → Prop + | start : Route E s s [s] + | extend {u v xs} : Route E s u xs → E u v=true → Route E s v (xs++[v]) + +namespace Route + +variable {E : Fin n → Fin n → Bool} {s v : Fin n} {xs : List (Fin n)} + +theorem nonempty (h : Route E s v xs) : xs≠[] := by + cases h <;> simp + +theorem length_pos (h : Route E s v xs) : 0 rfl + | @extend u v xs h _ ih => + rw [List.head?_append_of_ne_nil _ h.nonempty] + exact ih + +theorem last (h : Route E s v xs) : xs.getLast?=some v := by + cases h <;> simp + +theorem chain (h : Route E s v xs) : xs.IsChain (fun a b=>E a b=true) := by + induction h with + | start => exact List.IsChain.singleton _ + | @extend u v xs h huv ih => + apply ih.append (List.IsChain.singleton _) + simpa [h.last] using huv + +/-- Every visited vertex has a prefix walk no longer than the whole walk. -/ +theorem routePrefix (h : Route E s v xs) {w : Fin n} (hw : w∈xs) : + ∃ ys, Route E s w ys ∧ ys.length≤xs.length := by + induction h with + | start => + have he : w=s := by simpa using hw + subst w + exact ⟨[s],Route.start,le_rfl⟩ + | @extend u v xs h huv ih => + rcases List.mem_append.mp hw with hw | hw + · obtain ⟨ys,hy,hl⟩ := ih hw + exact ⟨ys,hy,hl.trans (by simp)⟩ + · have he : w=v := by simpa using hw + subst w + exact ⟨xs++[v],h.extend huv,le_rfl⟩ + +end Route + +abbrev Paths (n : ℕ) := Fin n → Option (List (Fin n)) + +def discovered (P : Paths n) (v : Fin n) : Prop := ∃ xs,P v=some xs + +def predecessor (E : Fin n → Fin n → Bool) (P : Paths n) (v : Fin n) : + Option (Fin n) := + (List.finRange n).find? (fun u=> (P u).isSome && E u v) + +def round (E : Fin n → Fin n → Bool) (P : Paths n) (v : Fin n) : + Option (List (Fin n)) := + match P v with + | some xs => some xs + | none => (predecessor E P v).bind (fun u=>(P u).map (fun xs=>xs++[v])) + +def paths (E : Fin n → Fin n → Bool) (s : Fin n) : ℕ → Paths n + | 0 => fun v=>if v=s then some [s] else none + | k+1 => round E (paths E s k) + +lemma predecessor_some {E : Fin n → Fin n → Bool} {P : Paths n} + {v u : Fin n} (h : predecessor E P v=some u) : + discovered P u ∧ E u v=true := by + have hp := List.find?_some h + simp only [Bool.and_eq_true,Option.isSome_iff_exists] at hp + exact hp + +lemma predecessor_none {E : Fin n → Fin n → Bool} {P : Paths n} + {v : Fin n} (h : predecessor E P v=none) : + ∀ u,discovered P u → E u v≠true := by + have hp := List.find?_eq_none.mp h + intro u hu he + have hx := hp u (List.mem_finRange u) + obtain ⟨xs,hxs⟩ := hu + simp [hxs,he] at hx + +lemma round_retains {E : Fin n → Fin n → Bool} {P : Paths n} + {v : Fin n} {xs : List (Fin n)} (h : P v=some xs) : + round E P v=some xs := by simp [round,h] + +lemma round_discovered {E : Fin n → Fin n → Bool} {P : Paths n} {v : Fin n} : + discovered (round E P) v ↔ + discovered P v ∨ ∃ u,discovered P u ∧ E u v=true := by + cases hv : P v with + | some xs => + constructor + · intro _; exact Or.inl ⟨xs,hv⟩ + · intro _; exact ⟨xs,round_retains hv⟩ + | none => + cases hp : predecessor E P v with + | none => + constructor + · rintro ⟨xs,hxs⟩ + simp [round,hv,hp] at hxs + · intro h + rcases h with ⟨xs,hxs⟩ | ⟨u,hu,he⟩ + · simp [hv] at hxs + · exact False.elim (predecessor_none hp u hu he) + | some u => + obtain ⟨⟨xs,hxs⟩,huv⟩ := predecessor_some hp + constructor + · intro _; exact Or.inr ⟨u,⟨xs,hxs⟩,huv⟩ + · intro _; exact ⟨xs++[v],by simp [round,hv,hp,hxs]⟩ + +theorem paths_sound {E : Fin n → Fin n → Bool} {s v : Fin n} + {k : ℕ} {xs : List (Fin n)} (h : paths E s k v=some xs) : + Route E s v xs ∧ xs.length≤k+1 := by + induction k generalizing v xs with + | zero => + simp only [paths] at h + split at h + · rename_i he + subst v + have hx : xs=[s] := by simpa using h.symm + subst xs + exact ⟨Route.start,le_rfl⟩ + · simp at h + | succ k ih => + change round E (paths E s k) v=some xs at h + cases hv : paths E s k v with + | some ys => + have hx : ys=xs := by simpa [round,hv] using h + subst xs + obtain ⟨hr,hl⟩ := ih hv + exact ⟨hr,hl.trans (by omega)⟩ + | none => + cases hp : predecessor E (paths E s k) v with + | none => simp [round,hv,hp] at h + | some u => + obtain ⟨⟨ys,hy⟩,huv⟩ := predecessor_some hp + have hx : ys++[v]=xs := by simpa [round,hv,hp,hy] using h + subst xs + obtain ⟨hr,hl⟩ := ih hy + exact ⟨hr.extend huv,by simpa using Nat.add_le_add_right hl 1⟩ + +theorem route_discovered {E : Fin n → Fin n → Bool} {s v : Fin n} + {xs : List (Fin n)} (h : Route E s v xs) (k : ℕ) + (hl : xs.length≤k+1) : discovered (paths E s k) v := by + induction k generalizing v xs with + | zero => + cases h with + | start => exact ⟨[s],by simp [paths]⟩ + | @extend u v ys hy _ => + have hp := hy.length_pos + simp only [List.length_append,List.length_singleton] at hl + omega + | succ k ih => + change discovered (round E (paths E s k)) v + apply round_discovered.mpr + cases h with + | start => exact Or.inl (ih Route.start (by simp)) + | @extend u v ys hy huv => + exact Or.inr ⟨u,ih hy (by simpa using hl),huv⟩ + +theorem paths_shortest {E : Fin n → Fin n → Bool} {s v : Fin n} + {k : ℕ} {xs : List (Fin n)} (h : paths E s k v=some xs) : + ∀ ys,Route E s v ys → xs.length≤ys.length := by + induction k generalizing v xs with + | zero => + have ⟨_,hl⟩ := paths_sound h + intro ys hy + exact hl.trans (by have hp:=hy.length_pos; omega) + | succ k ih => + cases hv : paths E s k v with + | some ys => + have hx : ys=xs := by simpa [paths,round,hv] using h + subst xs + exact ih hv + | none => + intro ys hy + have hs := (paths_sound h).2 + by_contra hn + have hl : ys.length≤k+1 := by omega + obtain ⟨zs,hz⟩ := route_discovered hy k hl + simp [hv] at hz + +theorem paths_nodup {E : Fin n → Fin n → Bool} {s v : Fin n} + {k : ℕ} {xs : List (Fin n)} (h : paths E s k v=some xs) : xs.Nodup := by + induction k generalizing v xs with + | zero => + have ⟨hr,_⟩ := paths_sound h + cases hr with + | start => simp + | @extend u v ys hy _ => + have hp:=hy.length_pos + have hl := (paths_sound h).2 + simp only [List.length_append,List.length_singleton] at hl + omega + | succ k ih => + cases hv : paths E s k v with + | some ys => + have hx : ys=xs := by simpa [paths,round,hv] using h + subst xs + exact ih hv + | none => + cases hp : predecessor E (paths E s k) v with + | none => simp [paths,round,hv,hp] at h + | some u => + obtain ⟨⟨ys,hy⟩,_⟩ := predecessor_some hp + have hx : ys++[v]=xs := by simpa [paths,round,hv,hp,hy] using h + subst xs + have hnot : v∉ys := by + intro hm + have ⟨hr,hl⟩ := paths_sound hy + obtain ⟨zs,hz,hzl⟩ := hr.routePrefix hm + obtain ⟨ws,hw⟩ := route_discovered hz k (hzl.trans hl) + simp [hv] at hw + apply List.nodup_append.mpr + refine ⟨ih hy,by simp,?_⟩ + intro a ha b hb hab + have hb' : b=v := by simpa using hb + exact hnot (hab.trans hb' ▸ ha) + +theorem paths_length_le {E : Fin n → Fin n → Bool} {s v : Fin n} + {k : ℕ} {xs : List (Fin n)} (h : paths E s k v=some xs) : xs.length≤n := by + simpa using List.Nodup.length_le_card (paths_nodup h) + +/-- Every directed walk is found within n rounds. The proof uses the +short simple path stored by the search, rather than enumerating walks. -/ +theorem route_found {E : Fin n → Fin n → Bool} {s v : Fin n} + {xs : List (Fin n)} (h : Route E s v xs) : + discovered (paths E s n) v := by + obtain ⟨ys,hy⟩ := route_discovered h xs.length (by omega) + exact route_discovered (paths_sound hy).1 n + ((paths_length_le hy).trans (by omega)) + +theorem paths_complete {E : Fin n → Fin n → Bool} {s v : Fin n} : + discovered (paths E s n) v ↔ ∃ xs,Route E s v xs := by + constructor + · rintro ⟨xs,hxs⟩ + exact ⟨xs,(paths_sound hxs).1⟩ + · rintro ⟨xs,hxs⟩ + exact route_found hxs + +/-- The computed reached set contains the source and is closed under +every directed edge. This is the cut certificate used on failure. -/ +theorem source_found (E : Fin n → Fin n → Bool) (s : Fin n) : + discovered (paths E s n) s := route_found Route.start + +theorem reached_closed {E : Fin n → Fin n → Bool} {s u v : Fin n} + (hu : discovered (paths E s n) u) (huv : E u v=true) : + discovered (paths E s n) v := by + obtain ⟨xs,hxs⟩ := hu + exact route_found ((paths_sound hxs).1.extend huv) + +theorem failure_no_route {E : Fin n → Fin n → Bool} {s t : Fin n} + (h : paths E s n t=none) : ¬∃ xs,Route E s t xs := by + intro hr + obtain ⟨xs,hxs⟩ := paths_complete.mpr hr + simp [h] at hxs + +end ContingencyTables.FiniteDirectedBFS + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeDegree.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..099e846c311397907a119b83c98af80bdf8140ea --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeDegree.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLeafEnergy + +namespace OAI + +/-! # A literal finite list of all unit-exchange neighbors -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped Classical +open FactorialSignatures + +variable {C : Type*} [DecidableEq C] + +/-- The ordered pair records the coordinate raised and the coordinate lowered. -/ +def exchangeTarget (X : C → ℕ) (i j : C) : C → ℕ := fun a => + X a+(if a=i then 1 else 0)-(if a=j then 1 else 0) + +lemma adjacent_eq_exchangeTarget {X Y : C → ℕ} (h : IntegerExchangeAdjacent X Y) : + ∃ i j,i≠j ∧ Y=exchangeTarget X i j := by + obtain ⟨D,i,j,hij,hi,hj,rfl,rfl⟩ := h + refine ⟨i,j,hij,?_⟩ + funext a + unfold exchangeTarget removeOne + by_cases hai : a=i + · subst a + simp only [hij,ite_true,ite_false,Nat.sub_zero] + omega + · by_cases haj : a=j + · subst a + simp only [hai,ite_true,ite_false,Nat.sub_zero,Nat.add_zero] + · simp only [hai,haj,ite_false,Nat.sub_zero,Nat.add_zero] + +noncomputable def exchangeCandidates [Fintype C] (X : C → ℕ) : Finset (C → ℕ) := + Finset.univ.image (fun p : C×C => exchangeTarget X p.1 p.2) + +lemma adjacent_mem_candidates [Fintype C] {X Y : C → ℕ} (h : IntegerExchangeAdjacent X Y) : + Y ∈ exchangeCandidates X := by + obtain ⟨i,j,_,rfl⟩ := adjacent_eq_exchangeTarget h + exact Finset.mem_image.mpr ⟨(i,j),Finset.mem_univ _,rfl⟩ + +theorem exchangeCandidates_card_le [Fintype C] (X : C → ℕ) : + (exchangeCandidates X).card ≤ (Fintype.card C)^2 := by + unfold exchangeCandidates + exact (Finset.card_image_le).trans_eq (by simp only [Finset.card_univ,Fintype.card_prod,pow_two]) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeObservables.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeObservables.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b718035263c577e65a1dca5dcada6a1929a5646 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExchangeObservables.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeDegree + +namespace OAI + +/-! # Unit exchanges change each selected coordinate sum by at most two -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open FactorialSignatures + +variable {C : Type*} [Fintype C] [DecidableEq C] + +noncomputable def linearObservable (a : C → ℤ) (z : C → ℕ) : ℤ := ∑ k,a k*(z k:ℤ) + +lemma linearObservable_removeOne (a : C → ℤ) (D : C → ℕ) (i : C) (hi : 0 < D i) : + linearObservable a (removeOne D i)=linearObservable a D-a i := by + have ht (k : C) : (removeOne D i k:ℤ)=(D k:ℤ)-(if k=i then 1 else 0) := by + by_cases hk : k=i + · subst k + simp only [removeOne,ite_true] + omega + · simp only [removeOne,hk,ite_false,Nat.sub_zero,sub_zero] + unfold linearObservable + simp_rw [ht,mul_sub] + rw [Finset.sum_sub_distrib] + simp + +lemma exchange_observable_difference (a : C → ℤ) (X Y : C → ℕ) + (hxy : IntegerExchangeAdjacent X Y) : + ∃ i j,linearObservable a Y-linearObservable a X=a i-a j := by + obtain ⟨D,i,j,_,hi,hj,rfl,rfl⟩ := hxy + refine ⟨i,j,?_⟩ + rw [linearObservable_removeOne a D i hi,linearObservable_removeOne a D j hj] + ring + +theorem exchange_observable_abs_le_two (a : C → ℤ) (ha : ∀ i,|a i| ≤ 1) + (X Y : C → ℕ) (hxy : IntegerExchangeAdjacent X Y) : + |linearObservable a Y-linearObservable a X| ≤ 2 := by + obtain ⟨i,j,he⟩ := exchange_observable_difference a X Y hxy + rw [he] + exact (abs_sub _ _).trans (by linarith [ha i,ha j]) + +theorem exchange_selected_sum_abs_le_two (p : C → Prop) (X Y : C → ℕ) + (hxy : IntegerExchangeAdjacent X Y) : + |((∑ k,if p k then Y k else 0:ℕ):ℤ)-((∑ k,if p k then X k else 0:ℕ):ℤ)| ≤ 2 := by + have ha : ∀ k,|(if p k then 1 else 0:ℤ)| ≤ 1 := by + intro k + split_ifs <;> norm_num + have h := exchange_observable_abs_le_two (fun k => if p k then 1 else 0) ha X Y hxy + simpa only [linearObservable,ite_mul,one_mul,zero_mul,Nat.cast_sum,Nat.cast_ite,Nat.cast_zero] using h + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..1881a0ce92eac0df8946f3eae0bb204f58a10bb5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureBudget.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FinitePrefixVariance + +namespace OAI + +/-! # The finite exposure depth and polynomial coefficient -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped Classical + +theorem variance_le_polynomial_budget {A : Type*} [Fintype A] {q : ℕ} + (w H : (Fin q → A) → ℝ) (hw : ∀ a,0 ≤ w a) (d U : ℕ) (hq : q ≤ d) + (E : ℝ) (hE : 0 ≤ E) + (hb : ∀ k : Fin q,prefixContribution w H k ≤ 4*d*((U:ℝ)+1)^6*E) : + variance w H ≤ 4*(d:ℝ)^2*((U:ℝ)+1)^6*E := by + have hv := variance_le_prefix_budget w H hw (4*d*((U:ℝ)+1)^6*E) hb + have hq' : (q:ℝ) ≤ d := by exact_mod_cast hq + have hcoef : 0 ≤ 4*(d:ℝ)*((U:ℝ)+1)^6 := by positivity + calc + _ ≤ q*(4*d*((U:ℝ)+1)^6*E) := hv + _ ≤ (d:ℝ)*(4*d*((U:ℝ)+1)^6*E) := mul_le_mul_of_nonneg_right hq' (mul_nonneg hcoef hE) + _ = _ := by ring + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..c974e17beb1ab332bf108e6eab383e20c59b4d94 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteExposureVariance.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerChildVariance + +namespace OAI + +/-! # Finite exposure variance with zero-mass children + +The exact variance decomposition uses only finite nonnegative weights. +A child of mass zero has zero moment, so its mean can be set to zero. +This is the algebraic decomposition iterated by the small-slot exposure. +-/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical +open CommonBasesFPRAS + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +noncomputable def mean (w H : X → ℝ) : ℝ := (∑ x, w x*H x)/(∑ x, w x) + +noncomputable def variance (w H : X → ℝ) : ℝ := ∑ x, w x*(H x-mean w H)^2 + +omit [Fintype Y] in +lemma zero_mass_weights (w : X → ℝ) (hw : ∀ x, 0 ≤ w x) (hz : (∑ x, w x)=0) : + ∀ x, w x=0 := by + intro x + exact (Finset.sum_eq_zero_iff_of_nonneg (fun y _ => hw y)).mp hz x (Finset.mem_univ x) + +omit [Fintype Y] in +lemma mean_moment (w H : X → ℝ) (hw : ∀ x, 0 ≤ w x) : + (∑ x, w x)*mean w H=∑ x, w x*H x := by + by_cases hz : (∑ x, w x)=0 + · have h := zero_mass_weights w hw hz + simp only [mean,h,zero_mul,Finset.sum_const_zero] + · unfold mean + field_simp + +omit [Fintype Y] in +lemma mean_second (w H : X → ℝ) : + (∑ x, w x)*(mean w H)^2=(∑ x, w x*H x)^2/(∑ x, w x) := by + by_cases hz : (∑ x, w x)=0 + · simp only [mean,hz,div_zero,zero_mul] + · unfold mean + field_simp + +omit [Fintype Y] in +/-- The second-moment identity also holds at mass zero. -/ +lemma variance_formula (w H : X → ℝ) (hw : ∀ x, 0 ≤ w x) : + variance w H=(∑ x, w x*(H x)^2)-(∑ x, w x*H x)^2/(∑ x, w x) := by + by_cases hz : (∑ x, w x)=0 + · have h := zero_mass_weights w hw hz + simp only [variance,h,zero_mul,Finset.sum_const_zero,zero_pow,ne_eq, + OfNat.ofNat_ne_zero,not_false_eq_true,div_zero,sub_zero] + · exact finite_center_at_mean Finset.univ w H hz + +/-- Exact conditional variance decomposition, allowing arbitrary +zero-mass child fibres and a zero-mass whole space. -/ +theorem variance_split (w H : Y → X → ℝ) (hw : ∀ y x, 0 ≤ w y x) : + variance (fun p : X×Y => w p.2 p.1) (fun p => H p.2 p.1)= + (∑ y, variance (w y) (H y))+ + variance (fun y => ∑ x, w y x) (fun y => mean (w y) (H y)) := by + have hmass : (∑ y, ∑ x, w y x)=(∑ p : X×Y, w p.2 p.1) := by + rw [Fintype.sum_prod_type,Finset.sum_comm] + have hmoment : (∑ y, (∑ x, w y x)*mean (w y) (H y))= + ∑ p : X×Y, w p.2 p.1*H p.2 p.1 := by + simp_rw [mean_moment _ _ (hw _)] + rw [Fintype.sum_prod_type,Finset.sum_comm] + have hsecond : (∑ y, (∑ x, w y x)*(mean (w y) (H y))^2)= + ∑ y, (∑ x, w y x*H y x)^2/(∑ x, w y x) := by + simp_rw [mean_second] + have hsquares : (∑ y, ∑ x, w y x*(H y x)^2)= + ∑ p : X×Y, w p.2 p.1*(H p.2 p.1)^2 := by + rw [Fintype.sum_prod_type,Finset.sum_comm] + rw [variance_formula (fun p : X×Y => w p.2 p.1) (fun p => H p.2 p.1) (fun p => hw p.2 p.1), + variance_formula (fun y : Y => ∑ x, w y x) (fun y => mean (w y) (H y)) + (fun y => Finset.sum_nonneg (fun x _ => hw y x))] + have hchild (y : Y) := variance_formula (w y) (H y) (hw y) + simp_rw [hchild] + rw [Finset.sum_sub_distrib,hmass,hmoment,hsecond,hsquares] + ring + +omit [Fintype X] [Fintype Y] in +/-- A fixed-depth partition uses each nonnegative edge energy at most +once. The same statement applies to profile contexts and directed edges. -/ +theorem sum_context_energy_le {E C : Type*} [Fintype C] + (edges : Finset E) (energy : E → ℝ) (context : E → C) + (eligible : E → Prop) (henergy : ∀ e ∈ edges, 0 ≤ energy e) : + (∑ c : C, ∑ e ∈ edges.filter (fun e => eligible e ∧ context e=c), energy e) ≤ + ∑ e ∈ edges, energy e := by + simp only [Finset.sum_filter] + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro e he + by_cases h : eligible e + · simp only [h,true_and,Finset.sum_ite_eq,Finset.mem_univ,↓reduceIte] + exact le_rfl + · simpa only [h,false_and,↓reduceIte,Finset.sum_const_zero] using henergy e he + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphCutSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphCutSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..90c6192f25c5d920d3b8fb568a856d00f5c328bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphCutSemantics.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphCutProgram + +namespace OAI + +/-! # Exact edge-deletion and cut-metadata computation -/ + +namespace ContingencyTables.FiniteGraphCutProgram + +open SimpleGraph FiniteGraphRootProgram + +lemma keep_eq_true_iff (u v i a : ℕ) : + keep (((u,v),i),a)=true ↔ ¬(i=u ∧ a=v) ∧ ¬(i=v ∧ a=u) := by + unfold keep + split_ifs <;> simp_all + +variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + +lemma deleteRow_graph (u v i : Fin n) : + deleteRow ((graphCode G,(u.val,v.val)),i.val)= + adjacencyRow (G.deleteEdges {s(u,v)}) i := by + unfold deleteRow + rw [graphCode_getD] + unfold adjacencyRow + rw [List.filter_map,List.filter_filter] + congr 1 + apply List.filter_congr + intro a _ + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,Bool.and_eq_true,decide_eq_true_eq,keep_eq_true_iff, + SimpleGraph.deleteEdges_adj,Set.mem_singleton_iff,Sym2.eq_iff,Fin.ext_iff] + tauto + +theorem deleteGraph_graph (u v : Fin n) : + deleteGraph (graphCode G,(u.val,v.val))=graphCode (G.deleteEdges {s(u,v)}) := by + apply List.ext_getElem + · simp only [deleteGraph,List.length_map,indices,List.length_range,graphCode_length] + · intro i hi _ + have hi' : i rfl + +/-- The executed Boolean metadata is the selected root-away cut in the +actual graph, rather than an arbitrary precomputed cut oracle. -/ +theorem cutCode_graph (u v root a : Fin n) : + cutCode (((graphCode G,(u.val,v.val)),root.val),a.val)= + RootedCut.cut G u v root a := by + unfold cutCode + rw [deleteGraph_graph,awayCode_graph,reachableCode_graph] + apply Bool.eq_iff_iff.mpr + simp only [RootedCut.cut,MaximumForest.side,decide_eq_true_eq] + +theorem canonicalCutCode_graph (u v a : Fin n) : + canonicalCutCode ((graphCode G,(u.val,v.val)),a.val)= + RootedCut.cut G u v (FiniteGraphRoots.root G u) a := by + unfold canonicalCutCode + rw [rootCode_eq,cutCode_graph] + +end ContingencyTables.FiniteGraphCutProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphPoincareBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphPoincareBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb7c372972c60b63d656c7a8861264576dc7769f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphPoincareBudget.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRepairVariance + +namespace OAI + +/-! # The source polynomial coefficient for the repaired graph -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical + +lemma graph_poincare_coefficient (d U : ℕ) (hd : 1 ≤ d) (hU : 1 ≤ U) : + ((1+2*(d:ℝ)^2)*4*(d:ℝ)^2*((U:ℝ)+1)^6+2) ≤ 770*(d:ℝ)^4*(U:ℝ)^6 := by + have hd' : (1:ℝ) ≤ d := by exact_mod_cast hd + have hU' : (1:ℝ) ≤ U := by exact_mod_cast hU + have hd2 : (1:ℝ) ≤ (d:ℝ)^2 := by nlinarith + have hd4 : (1:ℝ) ≤ (d:ℝ)^4 := by nlinarith [sq_nonneg ((d:ℝ)^2-1)] + have hU6 : (1:ℝ) ≤ (U:ℝ)^6 := by + have h := pow_le_pow_left₀ (by norm_num : (0:ℝ) ≤ 1) hU' 6 + simpa only [one_pow] using h + have hbig : (1:ℝ) ≤ (d:ℝ)^4*(U:ℝ)^6 := by nlinarith + have hplus : ((U:ℝ)+1)^6 ≤ (2*(U:ℝ))^6 := + pow_le_pow_left₀ (by positivity) (by linarith) 6 + calc + _ ≤ (3*(d:ℝ)^2)*4*(d:ℝ)^2*(2*(U:ℝ))^6+2 := by + have hc : (1+2*(d:ℝ)^2)*4*(d:ℝ)^2 ≤ (3*(d:ℝ)^2)*4*(d:ℝ)^2 := + mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_right (by nlinarith : + 1+2*(d:ℝ)^2 ≤ 3*(d:ℝ)^2) (by norm_num)) (sq_nonneg _) + exact add_le_add (mul_le_mul hc hplus (by positivity) (by positivity)) le_rfl + _ = 768*(d:ℝ)^4*(U:ℝ)^6+2 := by ring + _ ≤ _ := by nlinarith + +theorem variance_repaired_graph_budget {B D T : Type*} [Fintype B] [Fintype D] [Fintype T] + (w : B → ℝ) (v : D → ℝ) (H : B → ℝ) (K : D → ℝ) (R : D → B) (label : D → T) + (hw : ∀ b,0 ≤ w b) (hv : ∀ d,0 ≤ v d) (hdom : ∀ d,v d ≤ w (R d)) + (hinj : Function.Injective (fun d => (label d,R d))) (d U : ℕ) (hd : 1 ≤ d) (hU : 1 ≤ U) + (hT : Fintype.card T ≤ d^2) (E : ℝ) (hE : 0 ≤ E) + (hvar : variance w H ≤ 4*(d:ℝ)^2*((U:ℝ)+1)^6*E) + (hrepair : (∑ x,v x*(K x-H (R x))^2) ≤ E) : + variance (Sum.elim w v) (Sum.elim H K) ≤ 770*(d:ℝ)^4*(U:ℝ)^6*E := by + have hcoef : (1+2*(Fintype.card T:ℝ)) ≤ 1+2*(d:ℝ)^2 := by + have hT' : (Fintype.card T:ℝ) ≤ (d:ℝ)^2 := by exact_mod_cast hT + linarith + have hvar0 : 0 ≤ variance w H := Finset.sum_nonneg (fun b _ => mul_nonneg (hw _) (sq_nonneg _)) + calc + _ ≤ (1+2*(Fintype.card T:ℝ))*variance w H+2*∑ x,v x*(K x-H (R x))^2 := + variance_sum_repair w v H K R label hw hv hdom hinj + _ ≤ (1+2*(d:ℝ)^2)*variance w H+2*E := + add_le_add (mul_le_mul_of_nonneg_right hcoef hvar0) (mul_le_mul_of_nonneg_left hrepair (by norm_num)) + _ ≤ (1+2*(d:ℝ)^2)*(4*(d:ℝ)^2*((U:ℝ)+1)^6*E)+2*E := + add_le_add (mul_le_mul_of_nonneg_left hvar (show 0 ≤ 1+2*(d:ℝ)^2 by positivity)) le_rfl + _ = ((1+2*(d:ℝ)^2)*4*(d:ℝ)^2*((U:ℝ)+1)^6+2)*E := by ring + _ ≤ _ := mul_le_mul_of_nonneg_right (graph_poincare_coefficient d U hd hU) hE + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRootSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRootSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7e958c9f2dc9bcaef79d659bfb5dd1d8e07c760 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRootSemantics.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphRootProgram + +namespace OAI + +/-! # Exact correctness of the finite component-root program + +The stored adjacency list is identified with the given finite graph. +Each list growth round is the proved finite reachability growth, and +the final binary minimum is the least vertex of the actual component. +-/ + +namespace ContingencyTables.FiniteGraphRootProgram + +open MatchingFPRAS.ComputableReach SimpleGraph + +variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + +def adjacencyRow (b : Fin n) : List ℕ := + ((List.finRange n).filter (fun a => decide (G.Adj a b))).map Fin.val + +def graphCode : GraphCode := List.ofFn (adjacencyRow G) + +lemma graphCode_length : (graphCode G).length=n := List.length_ofFn + +lemma graphCode_getD (b : Fin n) : (graphCode G).getD b.val []=adjacencyRow G b := by + simp only [graphCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn,b.isLt,dite_eq_left, + Option.getD_some] + +lemma adjacencyRow_mem (b : Fin n) (a : ℕ) : + a∈adjacencyRow G b ↔ ∃ u : Fin n,u.val=a ∧ G.Adj u b := by + simp only [adjacencyRow,List.mem_map,List.mem_filter,List.mem_finRange,true_and, + decide_eq_true_eq] + constructor + · rintro ⟨u,hu,ha⟩ + exact ⟨u,ha,hu⟩ + · rintro ⟨u,ha,hu⟩ + exact ⟨u,hu,ha⟩ + +lemma grow_mem (s : List ℕ) (b : Fin n) : + b.val∈grow (graphCode G,s) ↔ + b.val∈s ∨ ∃ a : Fin n,a.val∈s ∧ G.Adj a b := by + simp only [grow,indices,List.mem_filter,List.mem_range,graphCode_length,growTest, + Bool.or_eq_true,decide_eq_true_eq,neighborHit,List.any_eq_true,graphCode_getD, + b.isLt,true_and] + constructor + · rintro (h|⟨a,ha,hs⟩) + · exact Or.inl h + · obtain ⟨u,hu,hg⟩ := (adjacencyRow_mem G b a).mp ha + exact Or.inr ⟨u,hu.symm ▸ hs,hg⟩ + · rintro (h|⟨a,ha,hg⟩) + · exact Or.inl h + · exact Or.inr ⟨a.val,(adjacencyRow_mem G b a.val).mpr ⟨a,rfl,hg⟩,ha⟩ + +lemma grow_bound (rows : GraphCode) (s : List ℕ) {a : ℕ} + (ha : a∈grow (rows,s)) : a advance (row,s)) (rows,s)).2= + (fun s => grow (rows,s))^[steps.length] s := by + induction steps generalizing s with + | nil => rfl + | cons row steps ih => + simp only [List.foldl_cons,List.length_cons] + change (steps.foldl (fun s row => advance (row,s)) (rows,grow (rows,s))).2=_ + rw [ih,Function.iterate_succ_apply] + +lemma iterate_mem (v b : Fin n) (k : ℕ) : + b.val∈(fun s => grow (graphCode G,s))^[k] [v.val] ↔ + b∈MatchingFPRAS.ComputableReach.reached G {v} k := by + induction k generalizing b with + | zero => + simp only [Function.iterate_zero_apply,List.mem_singleton, + MatchingFPRAS.ComputableReach.reached,Finset.mem_singleton] + exact Fin.ext_iff.symm + | succ k ih => + rw [Function.iterate_succ_apply',grow_mem, + MatchingFPRAS.ComputableReach.reached_step,mem_grow] + simp only [ih] + +lemma iterate_bound (v : Fin n) (k : ℕ) : + ∀ a∈(fun s => grow (graphCode G,s))^[k] [v.val],a + intro a ha + simp only [Function.iterate_zero_apply,List.mem_singleton] at ha + exact ha ▸ v.isLt + | succ k => + intro a ha + rw [Function.iterate_succ_apply'] at ha + simpa only [graphCode_length] using grow_bound _ _ ha + +lemma reached_eq_iterate (v : Fin n) : + reached (graphCode G,v.val)=(fun s => grow (graphCode G,s))^[n] [v.val] := by + unfold reached run + rw [fold_advance,graphCode_length] + +theorem reached_mem_iff (v b : Fin n) : + b.val∈reached (graphCode G,v.val) ↔ G.Reachable v b := by + rw [reached_eq_iterate,iterate_mem] + simpa only [MatchingFPRAS.ComputableReach.closure,Fintype.card_fin] using mem_closure G v b + +lemma reached_bound (v : Fin n) {a : ℕ} (ha : a∈reached (graphCode G,v.val)) : a min a b) b≤a := by + induction xs generalizing b with + | nil => simp only [List.not_mem_nil] at ha + | cons x xs ih => + simp only [List.mem_cons] at ha + rcases ha with h|ha + · subst x + exact (minimum_fold_le xs (min a b)).trans (min_le_left _ _) + · exact ih (min x b) ha + +lemma le_minimum_fold (xs : List ℕ) (b a : ℕ) (hb : a≤b) + (hs : ∀ x∈xs,a≤x) : a≤xs.foldl (fun b x => min x b) b := by + induction xs generalizing b with + | nil => exact hb + | cons x xs ih => + exact ih (min x b) (le_min (hs x (by simp)) hb) + (fun y hy => hs y (by simp [hy])) + +/-- The executed least root agrees with the explicit mathematical +selector. It does not identify that selector with a quotient choice. -/ +theorem rootCode_eq (v : Fin n) : + rootCode (graphCode G,v.val)=(FiniteGraphRoots.root G v).val := by + unfold rootCode + rw [graphCode_length] + apply le_antisymm + · exact minimum_fold_le_of_mem _ _ _ ((reached_mem_iff G v _).mpr + (FiniteGraphRoots.root_reachable G v)) + · apply le_minimum_fold _ _ _ (FiniteGraphRoots.root G v).isLt.le + intro a ha + let u : Fin n := ⟨a,reached_bound G v ha⟩ + have hr : G.Reachable v u := (reached_mem_iff G v u).mp ha + exact FiniteGraphRoots.root_le G hr + +end ContingencyTables.FiniteGraphRootProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRoots.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRoots.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf9a1d9817a5c33cb94ef69f22c5b8d870d31d65 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGraphRoots.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.MatchingCount.Sampling.Certify + +namespace OAI + +/-! # Explicit least roots of finite graph components + +The selector uses the finite reachability closure, not a choice of a +quotient representative. Its defining closure runs exactly n growth +rounds on Fin n, including disconnected and singleton components. +-/ + +namespace ContingencyTables.FiniteGraphRoots + +open MatchingFPRAS.ComputableReach SimpleGraph + +variable {n : ℕ} (G : SimpleGraph (Fin n)) [DecidableRel G.Adj] + +lemma closure_nonempty (v : Fin n) : (closure G v).Nonempty := + ⟨v,(mem_closure G v v).mpr (Reachable.refl v)⟩ + +/-- The least actual vertex index in the reached component. -/ +def root (v : Fin n) : Fin n := (closure G v).min' (closure_nonempty G v) + +lemma root_mem (v : Fin n) : root G v∈closure G v := + Finset.min'_mem _ _ + +lemma root_reachable (v : Fin n) : G.Reachable v (root G v) := + (mem_closure G v (root G v)).mp (root_mem G v) + +lemma closure_eq {u v : Fin n} (h : G.Reachable u v) : closure G u=closure G v := by + ext a + simp only [mem_closure] + constructor + · intro hu + exact h.symm.trans hu + · intro hv + exact h.trans hv + +lemma root_constant {u v : Fin n} (h : G.Reachable u v) : root G u=root G v := by + apply le_antisymm + · exact Finset.min'_le _ _ ((mem_closure G u (root G v)).mpr + (h.trans (root_reachable G v))) + · exact Finset.min'_le _ _ ((mem_closure G v (root G u)).mpr + (h.symm.trans (root_reachable G u))) + +lemma root_idempotent (v : Fin n) : root G (root G v)=root G v := + (root_constant G (root_reachable G v)).symm + +lemma root_le {u v : Fin n} (h : G.Reachable u v) : root G u≤v := + Finset.min'_le _ v ((mem_closure G u v).mpr h) + +lemma root_eq_self_of_minimal (u : Fin n) + (h : ∀ v,G.Reachable u v → u≤v) : root G u=u := by + apply le_antisymm + · exact root_le G (Reachable.refl u) + · exact h _ (root_reachable G u) + +end ContingencyTables.FiniteGraphRoots + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGridWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGridWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..c91a8446122e893826f9f2f2822b9fe6684399ec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteGridWords.lean @@ -0,0 +1,176 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisSemantics + +namespace OAI + +/-! # Explicit finite-box state enumeration, independent of sampling precision -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators + +abbrev GridEnumerationData := List Bool×ℕ + +def clippedGridPowerInput (z : GridEnumerationData×ℕ) : ℕ×ℕ := + (z.1.2,min z.2 z.1.1.length) + +def clippedGridPowerInputRealizer : Realizer clippedGridPowerInput := + pair (composition first second) + (composition (pair second (composition (composition first first) listLength)) minNat) + +lemma polynomial_clippedGridPowerInput : PolynomialTime clippedGridPowerInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength)) polynomial_minNat) + +def clippedGridPower (z : GridEnumerationData×ℕ) : ℕ := + BinaryPowerPrograms.power (clippedGridPowerInput z) + +def clippedGridPowerRealizer : Realizer clippedGridPower := + composition clippedGridPowerInputRealizer BinaryPowerPrograms.powerRealizer + +lemma polynomial_clippedGridPower : PolynomialTime clippedGridPowerRealizer := by + apply work_composition polynomial_clippedGridPowerInput BinaryPowerPrograms.work_power + (2*Polynomial.X) + intro z + have hl := (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + have hw := (weight_snd z.1).trans (weight_fst z) + have hm := min_le_right z.2 z.1.1.length + simp only [clippedGridPowerInput,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + omega + +abbrev GridCoordinateData := (GridEnumerationData×ℕ)×ℕ + +def gridCoordinate (z : GridCoordinateData) : ℕ := + z.1.2 / clippedGridPower (z.1.1,z.2) % z.1.1.2 + +def gridCoordinateRealizer : Realizer gridCoordinate := + composition (pair + (composition (pair (composition first second) + (composition (pair (composition first first) second) clippedGridPowerRealizer)) quotient) + (composition (composition first first) second)) remainder + +lemma polynomial_gridCoordinate : PolynomialTime gridCoordinateRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_clippedGridPower)) polynomial_quotient) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_remainder + +def gridCoordinateIndices (z : GridEnumerationData×ℕ) : List ℕ := List.range z.1.1.length + +def gridCoordinateIndicesRealizer : Realizer gridCoordinateIndices := + composition (composition (composition first first) listLength) range + +lemma polynomial_gridCoordinateIndices : PolynomialTime gridCoordinateIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_listLength) Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def gridCoordinates (z : GridEnumerationData×ℕ) : List ℕ := + (gridCoordinateIndices z).map (fun i => gridCoordinate (z,i)) + +def gridCoordinatesRealizer : Realizer gridCoordinates := + composition (pair identity gridCoordinateIndicesRealizer) (mapWith gridCoordinateRealizer) + +lemma polynomial_gridCoordinates : PolynomialTime gridCoordinatesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_gridCoordinateIndices) + (polynomial_mapWith polynomial_gridCoordinate) + +def gridStateCount (z : GridEnumerationData) : ℕ := + clippedGridPower (z,z.1.length) + +def gridStateCountRealizer : Realizer gridStateCount := + composition (pair identity (composition first listLength)) clippedGridPowerRealizer + +lemma polynomial_gridStateCount : PolynomialTime gridStateCountRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_listLength)) polynomial_clippedGridPower + +lemma gridStateCount_eq (z : GridEnumerationData) : gridStateCount z=z.2^z.1.length := by + simp [gridStateCount,clippedGridPower,clippedGridPowerInput,BinaryPowerPrograms.power_eq] + +def gridWords (z : GridEnumerationData) : List (List ℕ) := + (List.range (gridStateCount z)).map (fun i => gridCoordinates (z,i)) + +def gridWordsRealizer : Realizer gridWords := + composition (pair identity (composition gridStateCountRealizer range)) + (mapWith gridCoordinatesRealizer) + +/-- State enumeration is polynomial in its output count, not in the +precision or number of fair random words of the sampler. -/ +theorem work_gridWords : WorkBound gridWordsRealizer + (fun z => gridStateCount z+weight z) := by + have hp : WorkBound gridStateCountRealizer (fun z => gridStateCount z+weight z) := + work_of_polynomial polynomial_gridStateCount Polynomial.X (fun z => by simp) + have hr : WorkBound (composition gridStateCountRealizer range) + (fun z => gridStateCount z+weight z) := + work_composition hp range_numeric_work Polynomial.X (fun z => by simp) + unfold gridWordsRealizer + apply work_then_polynomial _ (polynomial_mapWith polynomial_gridCoordinates) + apply work_pair + (work_of_polynomial polynomial_identity Polynomial.X (fun z => by simp)) hr + Polynomial.X (fun z => by simp) + +private lemma map_range_eq_ofFn {A : Type*} (f : ℕ → A) (N : ℕ) : + (List.range N).map f=List.ofFn (fun i : Fin N => f i.val) := by + simpa using (List.ofFn_getElem_eq_map (List.range N) f).symm + +lemma gridCoordinates_eq (z : GridEnumerationData) (x : ℕ) : + gridCoordinates (z,x)=List.ofFn + (fun i : Fin z.1.length => x/z.2^i.val % z.2) := by + rw [gridCoordinates,gridCoordinateIndices,map_range_eq_ofFn] + apply congrArg List.ofFn + funext i + simp [gridCoordinate,clippedGridPower,clippedGridPowerInput, + BinaryPowerPrograms.power_eq] + +def gridDigitEquiv (K : ℕ) : Fin K ≃ Set.Icc (0:ℤ) ((K:ℤ)-1) where + toFun x := ⟨(x.val:ℤ),by + change 0≤(x.val:ℤ) ∧ (x.val:ℤ)≤(K:ℤ)-1 + have hx := x.isLt + omega⟩ + invFun x := ⟨x.val.toNat,by + have hx0 : 0≤x.val := x.property.1 + have hxK : x.val≤(K:ℤ)-1 := x.property.2 + omega⟩ + left_inv x := by ext; simp + right_inv x := by + apply Subtype.ext + have hx0 : 0≤x.val := x.property.1 + dsimp + omega + +def gridEnumeration (q K : ℕ) : Fin (K^q) ≃ Grid (I := Fin q) K := + finFunctionFinEquiv.symm.trans (Equiv.piCongrRight (fun _ => gridDigitEquiv K)) + +lemma gridEnumeration_code (q K : ℕ) (a : Fin (K^q)) : + gridNatCode (gridEnumeration q K a)= + List.ofFn (fun i : Fin q => a.val/K^i.val % K) := by + apply congrArg List.ofFn + funext i + rfl + +/-- Every box state occurs once in this explicit, mixed-radix list. -/ +theorem gridWords_eq (z : GridEnumerationData) : + gridWords z=List.ofFn (fun i => gridNatCode (gridEnumeration z.1.length z.2 i)) := by + unfold gridWords + rw [gridStateCount_eq,map_range_eq_ofFn] + apply congrArg List.ofFn + funext i + rw [gridCoordinates_eq,gridEnumeration_code] + +lemma gridWords_eq_length (xs : List Bool) (K q : ℕ) (hq : xs.length=q) : + gridWords (xs,K)=List.ofFn (fun i => gridNatCode (gridEnumeration q K i)) := by + subst q + exact gridWords_eq (xs,K) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentAverages.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentAverages.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a58e49da8a815ef46c601ec2e55b85fb137a359 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentAverages.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Concentration of averages of actual independent finite experiments -/ + +namespace ContingencyTables.FiniteIndependentAverages + +open CommonBasesFPRAS +open scoped BigOperators + +noncomputable section + +variable {X : Type*} [Fintype X] [Nonempty X] + +def sampleSum (g : X → ℝ) (N : ℕ) (xs : Fin N → X) : ℝ := ∑ i,g (xs i) + +def sampleAverage (g : X → ℝ) (N : ℕ) (xs : Fin N → X) : ℝ := sampleSum g N xs/N + +omit [Fintype X] [Nonempty X] in +lemma sampleSum_cons (g : X → ℝ) (N : ℕ) (x : X) (xs : Fin N → X) : + sampleSum g (N+1) (Fin.cons x xs)=g x+sampleSum g N xs := by + simp only [sampleSum,Fin.sum_univ_succ,Fin.cons_zero,Fin.cons_succ] + +lemma centered_mean (g : X → ℝ) : + uniformAverage (fun x => g x-uniformAverage g)=0 := by + rw [uniformAverage_sub_const,sub_self] + +lemma sampleSum_mean_zero (g : X → ℝ) (hg : uniformAverage g=0) (N : ℕ) : + uniformAverage (sampleSum g N)=0 := by + induction N with + | zero => + change uniformAverage (fun xs : Fin 0 → X => sampleSum g 0 xs)=0 + simp [sampleSum,uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ] + have he (x : X) : uniformAverage (fun xs : Fin N → X => sampleSum g (N+1) (Fin.cons x xs))=g x := by + simp_rw [sampleSum_cons] + rw [uniformAverage_add,uniformAverage_const,ih,add_zero] + simp_rw [he] + exact hg + +/-- Mixed terms vanish because each coordinate is an independent uniform +finite experiment, not because of an assumed concentration oracle. -/ +theorem sampleSum_secondMoment (g : X → ℝ) (hg : uniformAverage g=0) (N : ℕ) : + uniformAverage (fun xs : Fin N → X => (sampleSum g N xs)^2)= + N*uniformAverage (fun x => (g x)^2) := by + induction N with + | zero => simp [sampleSum,uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ] + have he (x : X) : + uniformAverage (fun xs : Fin N → X => (sampleSum g (N+1) (Fin.cons x xs))^2)= + (g x)^2+N*uniformAverage (fun y => (g y)^2) := by + have hfun : (fun xs : Fin N → X => (sampleSum g (N+1) (Fin.cons x xs))^2)= + fun xs => ((g x)^2+(2*g x)*sampleSum g N xs)+(sampleSum g N xs)^2 := by + funext xs + rw [sampleSum_cons] + ring + rw [hfun,uniformAverage_add,uniformAverage_add,uniformAverage_const, + uniformAverage_mul_left,sampleSum_mean_zero g hg N,ih] + ring + simp_rw [he] + rw [uniformAverage_add,uniformAverage_const] + push_cast + ring + +omit [Nonempty X] in +lemma sampleAverage_centered (g : X → ℝ) (N : ℕ) (hN : 0 < N) (xs : Fin N → X) : + sampleAverage g N xs-uniformAverage g= + sampleSum (fun x => g x-uniformAverage g) N xs/N := by + have hNR : (N:ℝ)≠0 := by exact_mod_cast hN.ne' + unfold sampleAverage sampleSum + rw [Finset.sum_sub_distrib] + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + field_simp [hNR] + +theorem sampleAverage_secondMoment (g : X → ℝ) (N : ℕ) (hN : 0 < N) : + uniformAverage (fun xs : Fin N → X => (sampleAverage g N xs-uniformAverage g)^2)= + uniformAverage (fun x => (g x-uniformAverage g)^2)/N := by + have hNR : (N:ℝ)≠0 := by exact_mod_cast hN.ne' + simp_rw [sampleAverage_centered g N hN,div_pow,div_eq_mul_inv] + rw [uniformAverage_mul_const,sampleSum_secondMoment _ (centered_mean g)] + field_simp [hNR] + +/-- A finite Chebyshev bound for the actual independent sample array. -/ +theorem sampleAverage_failure (g : X → ℝ) (N : ℕ) (hN : 0 < N) + (sigma : ℝ) (hsigma : 0 < sigma) (hmean : 0 < uniformAverage g) : + uniformAverage (fun xs : Fin N → X => + if sigma*uniformAverage g < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) ≤ + uniformAverage (fun x => (g x-uniformAverage g)^2)/(N*(sigma*uniformAverage g)^2) := by + have hden : 0 < (sigma*uniformAverage g)^2 := sq_pos_of_pos (mul_pos hsigma hmean) + have hpoint (xs : Fin N → X) : + (if sigma*uniformAverage g < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) ≤ + (sampleAverage g N xs-uniformAverage g)^2/(sigma*uniformAverage g)^2 := by + split_ifs with h + · rw [le_div_iff₀ hden] + have hh := (sq_le_sq₀ (mul_nonneg hsigma.le hmean.le) (abs_nonneg _)).mpr h.le + simpa only [one_mul,sq_abs] using hh + · positivity + have hh := uniformAverage_mono _ _ hpoint + have he : uniformAverage (fun xs : Fin N → X => + (sampleAverage g N xs-uniformAverage g)^2/(sigma*uniformAverage g)^2)= + uniformAverage (fun x => (g x-uniformAverage g)^2)/(N*(sigma*uniformAverage g)^2) := by + simp_rw [div_eq_mul_inv] + rw [uniformAverage_mul_const,sampleAverage_secondMoment g N hN] + ring + exact hh.trans_eq he + +lemma mean_bounds (g : X → ℝ) (L U : ℝ) (hg : ∀ x,L ≤ g x ∧ g x ≤ U) : + L ≤ uniformAverage g ∧ uniformAverage g ≤ U := by + constructor + · simpa only [uniformAverage_const] using uniformAverage_mono (fun _ : X => L) g (fun x => (hg x).1) + · simpa only [uniformAverage_const] using uniformAverage_mono g (fun _ : X => U) (fun x => (hg x).2) + +/-- A bounded positive output gives the same explicit relative-variance +bound on every finite experiment, including a Boolean-word sampler. -/ +theorem bounded_relative_failure (g : X → ℝ) (L U : ℝ) (hL : 0 < L) + (hg : ∀ x,L ≤ g x ∧ g x ≤ U) (N : ℕ) (hN : 0 < N) (sigma : ℝ) (hsigma : 0 < sigma) : + uniformAverage (fun xs : Fin N → X => + if sigma*uniformAverage g < |sampleAverage g N xs-uniformAverage g| then (1:ℝ) else 0) ≤ + U^2/(N*(sigma*L)^2) := by + have hm := mean_bounds g L U hg + have hmean : 0 < uniformAverage g := hL.trans_le hm.1 + have hU : 0 ≤ U := hmean.le.trans hm.2 + have hvar : uniformAverage (fun x => (g x-uniformAverage g)^2) ≤ U^2 := by + have hp (x : X) : (g x-uniformAverage g)^2 ≤ U^2 := by + have hx := hg x + have hnon : 0 ≤ g x := hL.le.trans hx.1 + have habs : |g x-uniformAverage g| ≤ U := abs_le.mpr ⟨by linarith,by linarith⟩ + simpa only [sq_abs] using (sq_le_sq₀ (abs_nonneg _) hU).mpr habs + simpa only [uniformAverage_const] using uniformAverage_mono _ (fun _ : X => U^2) hp + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hden : 0 < N*(sigma*L)^2 := mul_pos hNR (sq_pos_of_pos (mul_pos hsigma hL)) + have hden' : N*(sigma*L)^2 ≤ N*(sigma*uniformAverage g)^2 := by + apply mul_le_mul_of_nonneg_left _ hNR.le + exact (sq_le_sq₀ (mul_nonneg hsigma.le hL.le) (mul_nonneg hsigma.le hmean.le)).mpr + (mul_le_mul_of_nonneg_left hm.1 hsigma.le) + exact (sampleAverage_failure g N hN sigma hsigma hmean).trans + (div_le_div₀ (by positivity) hvar hden hden') + +end + +end ContingencyTables.FiniteIndependentAverages + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentFailures.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentFailures.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dddcdf19266ecf1b0724e4b71cc297bfcd30e25 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteIndependentFailures.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +import Mathlib.Logic.Equiv.Prod + +namespace OAI + +/-! # Coordinate marginals and a union bound for independent finite blocks -/ + +namespace ContingencyTables.FiniteIndependentAverages + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +lemma uniformAverage_coordinate {J : Type*} [Fintype J] {X : J → Type*} + [∀ j,Fintype (X j)] [∀ j,Nonempty (X j)] (i : J) (g : X i → ℝ) : + uniformAverage (fun x : (j : J) → X j => g (x i))=uniformAverage g := by + have he := uniformAverage_equiv (Equiv.piSplitAt i X) (fun x => g x.1) + change uniformAverage (fun x : (j : J) → X j => g (x i))= + uniformAverage (fun x : X i × ((j : {j // j≠i}) → X j.val) => g x.1) at he + rw [he,uniformAverage_prod] + simp_rw [uniformAverage_const] + +lemma uniform_union_bound {X J : Type*} [Fintype X] [Fintype J] + (bad : J → X → Prop) : + uniformAverage (fun x => if ∃ j,bad j x then (1:ℝ) else 0) ≤ + ∑ j,uniformAverage (fun x => if bad j x then (1:ℝ) else 0) := by + rw [←uniformAverage_sum] + apply uniformAverage_mono + intro x + by_cases h : ∃ j,bad j x + · obtain ⟨j,hj⟩ := h + rw [ite_eq_left ⟨j,hj⟩] + calc + 1 = (if bad j x then (1:ℝ) else 0) := by rw [ite_eq_left hj] + _ ≤ ∑ k : J,if bad k x then (1:ℝ) else 0 := + Finset.single_le_sum (f := fun k => if bad k x then (1:ℝ) else 0) + (fun k _ => by split_ifs <;> norm_num) (Finset.mem_univ j) + · rw [ite_eq_right h] + exact Finset.sum_nonneg (fun j _ => by split_ifs <;> norm_num) + +/-- Each block is an actual independently uniform finite experiment. +The event may test a different observable on each block. -/ +theorem independent_union_failure {J : Type*} [Fintype J] {X : J → Type*} + [∀ j,Fintype (X j)] [∀ j,Nonempty (X j)] (bad : (j : J) → X j → Prop) : + uniformAverage (fun draws : (j : J) → X j => + if ∃ j,bad j (draws j) then (1:ℝ) else 0) ≤ + ∑ j,uniformAverage (fun x : X j => if bad j x then (1:ℝ) else 0) := by + apply (uniform_union_bound (fun j (draws : (k : J) → X k) => bad j (draws j))).trans_eq + apply Finset.sum_congr rfl + intro j _ + exact uniformAverage_coordinate j (fun x => if bad j x then (1:ℝ) else 0) + +end + +end ContingencyTables.FiniteIndependentAverages + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawDecidableEq.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawDecidableEq.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a45108ad3d99653433282371a79cc431d3ff12c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawDecidableEq.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FinitePartialDraw + +namespace OAI + +/-! # Explicit decidable equality at finite-law application boundaries -/ + +namespace ContingencyTables.FirstSuccess + +open ResidualMixture + +universe u v + +variable {X : Type u} {Y : Type v} [Fintype X] [Fintype Y] + +/-- The output equality decision only computes the same finite fibres; +it does not change the mapped probability law. Keeping the decisions +explicit avoids reducing a large concrete state type to match instances. -/ +theorem mapLaw_decidableEq_irrel (d e : DecidableEq Y) + (p : RationalLaw X) (f : X → Y) : + @mapLaw X Y _ _ d p f=@mapLaw X Y _ _ e p f := by + cases Subsingleton.elim d e + rfl + +theorem mapLaw_mass_decidableEq_irrel (d e : DecidableEq Y) + (p : RationalLaw X) (f : X → Y) (y : Y) : + (@mapLaw X Y _ _ d p f).mass y=(@mapLaw X Y _ _ e p f).mass y := by + rw [mapLaw_decidableEq_irrel d e] + +end ContingencyTables.FirstSuccess + +namespace ContingencyTables.FairBits + +open ResidualMixture FirstSuccess +open scoped Classical + +universe u + +variable {X : Type u} [Fintype X] + +/-- The actual subset bit draw has its exact dyadic mass with any chosen +output equality decision. The draw and its embedding are unchanged. -/ +theorem subsetBitDraw_mass_decidableEq (d : DecidableEq (Option X)) + (p : X → Prop) (k : ℕ) (h : Fintype.card {x // p x} ≤ 2^k) (x : X) : + (@mapLaw (Fin k → Bool) (Option X) _ _ d + (uniformLaw (α := Fin k → Bool)) (subsetBitDraw p k h)).mass (some x)= + if p x then 1/(2:ℚ)^k else 0 := by + let dX : DecidableEq X := Classical.decEq X + have he := mapLaw_mass_decidableEq_irrel d (@Option.instDecidableEq X dX) + (uniformLaw (α := Fin k → Bool)) (subsetBitDraw p k h) (some x) + exact he.trans (@subsetBitDraw_mass X _ dX p k h x) + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawMoments.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawMoments.lean new file mode 100644 index 0000000000000000000000000000000000000000..b865563424dce933fb5d3527ff4eed7f2db2b609 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawMoments.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentAverages +import OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess + +namespace OAI + +/-! # Expectations of concrete finite-word output laws -/ + +namespace ContingencyTables.FiniteLawMoments + +open CommonBasesFPRAS ResidualMixture FirstSuccess +open scoped BigOperators Classical + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +def expectation (p : RationalLaw X) (g : X → ℝ) : ℝ := ∑ x,(p.mass x:ℝ)*g x + +lemma expectation_map [DecidableEq Y] (p : RationalLaw X) (draw : X → Y) (g : Y → ℝ) : + expectation (mapLaw p draw) g=expectation p (fun x => g (draw x)) := by + unfold expectation mapLaw + simp only [Rat.cast_sum] + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + calc + _ = ∑ y : Y,if draw x=y then (p.mass x:ℝ)*g y else 0 := by + apply Finset.sum_congr rfl + intro y _ + split_ifs <;> simp + _ = _ := by simp + +lemma expectation_uniform [Nonempty X] (g : X → ℝ) : + expectation (uniformLaw (α := X)) g=uniformAverage g := by + unfold expectation uniformLaw uniformMass uniformAverage + simp only [Rat.cast_div,Rat.cast_one,Rat.cast_natCast] + rw [←Finset.mul_sum] + ring + +lemma word_expectation [Nonempty X] [DecidableEq Y] (draw : X → Y) (g : Y → ℝ) : + uniformAverage (fun x => g (draw x))=expectation (mapLaw (uniformLaw (α := X)) draw) g := by + rw [expectation_map,expectation_uniform] + +/-- Bounded real observables may be evaluated after a rational finite +experiment. Their expectation error follows from the actual output TV. -/ +theorem expectation_difference (p q : RationalLaw X) (g : X → ℝ) (U : ℝ) + (hg : ∀ x,|g x| ≤ U) : + |expectation p g-expectation q g| ≤ 2*U*(variation p q:ℝ) := by + have he : expectation p g-expectation q g=∑ x,((p.mass x:ℝ)-(q.mass x:ℝ))*g x := by + unfold expectation + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + rw [he] + calc + _ ≤ ∑ x,|((p.mass x:ℝ)-(q.mass x:ℝ))*g x| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ x,|(p.mass x:ℝ)-(q.mass x:ℝ)| * U := by + apply Finset.sum_le_sum + intro x _ + rw [abs_mul] + exact mul_le_mul_of_nonneg_left (hg x) (abs_nonneg _) + _ = _ := by + rw [←Finset.sum_mul] + simp only [variation,Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat] + ring + +lemma expectation_bounds (p : RationalLaw X) (g : X → ℝ) (L U : ℝ) + (hg : ∀ x,L ≤ g x ∧ g x ≤ U) : L ≤ expectation p g ∧ expectation p g ≤ U := by + have htotal : ∑ x,(p.mass x:ℝ)=1 := by exact_mod_cast p.total + unfold expectation + constructor + · calc + L = ∑ x,(p.mass x:ℝ)*L := by rw [←Finset.sum_mul,htotal,one_mul] + _ ≤ _ := Finset.sum_le_sum (fun x _ => + mul_le_mul_of_nonneg_left (hg x).1 (by exact_mod_cast p.nonnegative x)) + · calc + _ ≤ ∑ x,(p.mass x:ℝ)*U := Finset.sum_le_sum (fun x _ => + mul_le_mul_of_nonneg_left (hg x).2 (by exact_mod_cast p.nonnegative x)) + _ = U := by rw [←Finset.sum_mul,htotal,one_mul] + +end ContingencyTables.FiniteLawMoments + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawRelativeError.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawRelativeError.lean new file mode 100644 index 0000000000000000000000000000000000000000..db4518c43694bb37df692a0fea5c0a0004668974 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteLawRelativeError.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # Passing deterministic relative error through a finite law -/ + +namespace ContingencyTables.FiniteLawMoments + +open ResidualMixture +open scoped BigOperators + +variable {X : Type*} [Fintype X] + +lemma expectation_relative_error (p : RationalLaw X) (f g : X → ℝ) (delta : ℝ) + (herror : ∀ x,|g x-f x| ≤ delta*f x) : + |expectation p g-expectation p f| ≤ delta*expectation p f := by + have he : expectation p g-expectation p f=∑ x,(p.mass x:ℝ)*(g x-f x) := by + unfold expectation + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + rw [he] + calc + _ ≤ ∑ x,|(p.mass x:ℝ)*(g x-f x)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ x,(p.mass x:ℝ)*(delta*f x) := by + apply Finset.sum_le_sum + intro x _ + have hp : (0:ℝ) ≤ p.mass x := by exact_mod_cast p.nonnegative x + rw [abs_mul,abs_of_nonneg hp] + exact mul_le_mul_of_nonneg_left (herror x) hp + _ = _ := by + unfold expectation + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring + +end ContingencyTables.FiniteLawMoments + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMedianConfidence.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMedianConfidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..21373a23defc733f348d6e8b103566b08294df60 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMedianConfidence.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Rational medians with real target intervals -/ + +namespace ContingencyTables.FiniteMedianConfidence + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +/-- Rational thresholds used only in the proof permit direct reuse of +finite median amplification when the intended target is a real number. -/ +theorem median_confidence_real {X : Type*} [Fintype X] [Nonempty X] + (output : X → ℚ) (L L' U' U : ℝ) (hL : L < L') (hU : U' < U) + (delta : ℚ) (hdelta : 0 < delta) + (hbad : uniformAverage (fun x => + if (output x:ℝ) < L' ∨ U' < (output x:ℝ) then (1:ℝ) else 0) ≤ 5/16) : + 1-(delta:ℝ) ≤ uniformAverage (fun xs : Fin (repetitionCount delta) → X => + if L ≤ (rationalMedian (List.ofFn (fun i => output (xs i))):ℝ) ∧ + (rationalMedian (List.ofFn (fun i => output (xs i))):ℝ) ≤ U + then (1:ℝ) else 0) := by + obtain ⟨a,haL,haL'⟩ := exists_rat_btwn hL + obtain ⟨b,hU'b,hbU⟩ := exists_rat_btwn hU + have hab : uniformAverage (fun x => if outsideInterval a b (output x) then (1:ℝ) else 0) ≤ 5/16 := by + apply (uniformAverage_mono _ _ (fun x => ?_)).trans hbad + simp only [outsideInterval,decide_eq_true_eq] + by_cases hn : ¬(a ≤ output x ∧ output x ≤ b) + · have hor : output x < a ∨ b < output x := by + by_cases ha : output x < a + · exact Or.inl ha + · right + by_contra hb + exact hn ⟨le_of_not_gt ha,le_of_not_gt hb⟩ + have ht : (output x:ℝ) < L' ∨ U' < (output x:ℝ) := by + rcases hor with ha|hb + · left + exact lt_trans (by exact_mod_cast ha) haL' + · right + exact lt_trans hU'b (by exact_mod_cast hb) + simp [hn,ht] + · simp only [hn,ite_false] + split_ifs <;> norm_num + have hm := median_confidence output a b delta hdelta hab + apply hm.trans + apply uniformAverage_mono + intro xs + by_cases hg : a ≤ rationalMedian (List.ofFn (fun i => output (xs i))) ∧ + rationalMedian (List.ofFn (fun i => output (xs i))) ≤ b + · have hreal : L ≤ (rationalMedian (List.ofFn (fun i => output (xs i))):ℝ) ∧ + (rationalMedian (List.ofFn (fun i => output (xs i))):ℝ) ≤ U := + ⟨le_trans haL.le (by exact_mod_cast hg.1),le_trans (by exact_mod_cast hg.2) hbU.le⟩ + simp [hg,hreal] + · simp only [hg,ite_false] + split_ifs <;> norm_num + +lemma rationalMedian_mem (l : List ℚ) (hl : 0 < l.length) : rationalMedian l ∈ l := by + have hi : l.length/2 < (l.mergeSort (· ≤ ·)).length := by + rw [List.length_mergeSort] + omega + unfold rationalMedian + rw [List.getD_eq_getElem _ _ hi] + exact List.mem_mergeSort.mp (List.getElem_mem hi) + +end + +end ContingencyTables.FiniteMedianConfidence + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolis.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolis.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8c737cda91663c706e5714728d13624e7a2984a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolis.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalReindex + +namespace OAI + +/-! # Exact finite proposal-and-acceptance experiments -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +noncomputable section + +variable {α β γ : Type*} [Fintype α] [Fintype β] [Fintype γ] +variable [DecidableEq α] [Nonempty β] [Nonempty γ] + +def finiteAcceptStep (a : α) (proposal : β → Option α) (accept : α → γ → Prop) + (z : β × γ) : α := + match proposal z.1 with + | none => a + | some b => if accept b z.2 then b else a + +def finiteAcceptLaw (a : α) (proposal : β → Option α) (accept : α → γ → Prop) : RationalLaw α := + mapLaw (productLaw (uniformLaw (α := β)) (uniformLaw (α := γ))) + (finiteAcceptStep a proposal accept) + +omit [Fintype α] [Fintype β] [Fintype γ] [DecidableEq α] [Nonempty β] [Nonempty γ] in +theorem finiteAcceptStep_eq_iff (a b : α) (proposal : β → Option α) (accept : α → γ → Prop) + (z : β × γ) (hab : a ≠ b) : + finiteAcceptStep a proposal accept z = b ↔ proposal z.1 = some b ∧ accept b z.2 := by + cases hp : proposal z.1 with + | none => simp [finiteAcceptStep, hp, hab] + | some c => + by_cases hcb : c = b + · subst c + simp [finiteAcceptStep, hp, hab] + · by_cases hc : accept c z.2 <;> simp [finiteAcceptStep, hp, hc, hcb, hab] + +/-- The off-diagonal mass is the exact product of the proposal-code and +acceptance-coin frequencies. Both experiments use bounded finite samples. -/ +theorem finiteAcceptLaw_off_diagonal (a b : α) (proposal : β → Option α) + (accept : α → γ → Prop) (hab : a ≠ b) : + (finiteAcceptLaw a proposal accept).mass b = + ((Finset.univ.filter (fun z => proposal z = some b)).card / (Fintype.card β : ℚ)) * + ((Finset.univ.filter (accept b)).card / (Fintype.card γ : ℚ)) := by + change (∑ z : β × γ, if finiteAcceptStep a proposal accept z = b then + uniformMass (α := β) * uniformMass (α := γ) else 0) = _ + simp_rw [finiteAcceptStep_eq_iff a b proposal accept _ hab] + rw [Fintype.sum_prod_type] + have hs : (∑ x : β, ∑ y : γ, if proposal x = some b ∧ accept b y then + uniformMass (α := β) * uniformMass (α := γ) else 0) = + (∑ x : β, if proposal x = some b then uniformMass (α := β) else 0) * + (∑ y : γ, if accept b y then uniformMass (α := γ) else 0) := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + by_cases hx : proposal x = some b <;> by_cases hy : accept b y <;> simp [hx, hy] + rw [hs, ← Finset.sum_filter, ← Finset.sum_filter] + simp only [Finset.sum_const, nsmul_eq_mul, uniformMass] + ring + +omit [Fintype β] [Fintype γ] [Nonempty β] [Nonempty γ] in +/-- Two finite probability laws agreeing off a fixed state agree there +as well. This recovers the rejection/stay probability from normalization. -/ +theorem RationalLaw.eq_of_off_diagonal (p q : RationalLaw α) (a : α) + (h : ∀ b, b ≠ a → p.mass b = q.mass b) : p = q := by + apply RationalLaw.ext + funext b + by_cases hb : b = a + · subst b + have hp := Finset.sum_erase_add (Finset.univ : Finset α) p.mass (Finset.mem_univ a) + have hq := Finset.sum_erase_add (Finset.univ : Finset α) q.mass (Finset.mem_univ a) + have he : (∑ b ∈ Finset.univ.erase a, p.mass b) = ∑ b ∈ Finset.univ.erase a, q.mass b := by + apply Finset.sum_congr rfl + intro b hb + exact h b (Finset.mem_erase.mp hb).1 + rw [p.total] at hp + rw [q.total] at hq + rw [he] at hp + linarith + · exact h b hb + +end + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolisTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolisTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..80723e4e28681771060b55aebfac92d5b485d6e8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteMetropolisTransport.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteAdaptiveObservable + +namespace OAI + +/-! # Exact observable transport of optional proposals and acceptance -/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS +open scoped Classical +noncomputable section + +variable {X P Q U V : Type*} [Fintype P] [Fintype Q] [Fintype U] [Fintype V] + +def proposedMove (start : X) (pick : Option X) (accept : X → U → Bool) (bits : U) : X := + match pick with + | none => start + | some next => if accept next bits then next else start + +/-- The proposed state and fresh acceptance experiment can both be +replaced by experiments with the same observable law. -/ +theorem proposedMove_sameLaw (start : X) (pick : P → Option X) (pick' : Q → Option X) + (accept : X → U → Bool) (accept' : X → V → Bool) + (hp : SameLaw pick pick') (ha : ∀ next,SameLaw (accept next) (accept' next)) : + SameLaw (fun z : P × U => proposedMove start (pick z.1) accept z.2) + (fun z : Q × V => proposedMove start (pick' z.1) accept' z.2) := by + apply hp.bind (fun o u => proposedMove start o accept u) + (fun o v => proposedMove start o accept' v) + intro o + cases o with + | none => exact (ha start).map (fun _ : Bool => start) + | some next => exact (ha next).map (fun flag : Bool => if flag then next else start) + +/-- An independent holding flag is preserved by the replacement. -/ +theorem holding_sameLaw {A B : Type*} [Fintype A] [Fintype B] + (start : X) (f : A → X) (g : B → X) (h : SameLaw f g) : + SameLaw (fun z : (Fin 1 → Bool) × A => if z.1 0 then start else f z.2) + (fun z : (Fin 1 → Bool) × B => if z.1 0 then start else g z.2) := by + have hid : SameLaw (fun b : Fin 1 → Bool => b 0) (fun b : Fin 1 → Bool => b 0) := fun _ => rfl + exact (hid.prod h).map (fun z : Bool × X => if z.1 then start else z.2) + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d4abf45a340c55a93c26414551eb5c34b94ce3a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableReindex.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # Exact finite-observable transports at word and law boundaries -/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS ResidualMixture FirstSuccess +open scoped Classical +noncomputable section + +lemma SameLaw.word_length {a b : ℕ} (h : a=b) {Y Z : Type*} [Fintype Y] + (f : List Bool → Z) (g : Y → Z) + (hf : SameLaw (fun xs : Fin a → Bool => f (List.ofFn xs)) g) : + SameLaw (fun xs : Fin b → Bool => f (List.ofFn xs)) g := by + cases h + exact hf + +lemma SameLaw.of_mapLaw_eq {X Y Z : Type*} [Fintype X] [Nonempty X] + [Fintype Y] [Nonempty Y] [Fintype Z] [DecidableEq Z] + (f : X → Z) (g : Y → Z) + (h : mapLaw (uniformLaw (α := X)) f=mapLaw (uniformLaw (α := Y)) g) : + SameLaw f g := by + intro phi + rw [FiniteLawMoments.word_expectation,FiniteLawMoments.word_expectation,h] + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..f157fa026c3a8fd873b3b2eb9df705b319ab9d41 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteObservableTransport.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Exact transport of finite experiments with rational outputs + +Output values need not form a finite type. Equality against every real +observable is preserved by deterministic postprocessing and by the +independent arrays used in the counting estimator. +-/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS +open scoped Classical + +noncomputable section +variable {X Y U V Z W : Type*} +variable [Fintype X] [Fintype Y] [Fintype U] [Fintype V] + +def SameLaw (f : X → Z) (g : Y → Z) : Prop := + ∀ phi : Z → ℝ,uniformAverage (fun x => phi (f x))=uniformAverage (fun y => phi (g y)) + +lemma SameLaw.map {f : X → Z} {g : Y → Z} (h : SameLaw f g) (F : Z → W) : + SameLaw (fun x => F (f x)) (fun y => F (g y)) := by + intro phi + exact h (fun z => phi (F z)) + +lemma SameLaw.prod {f : X → Z} {g : Y → Z} {a : U → W} {b : V → W} + (hfg : SameLaw f g) (hab : SameLaw a b) : + SameLaw (fun x : X×U => (f x.1,a x.2)) (fun y : Y×V => (g y.1,b y.2)) := by + intro phi + rw [uniformAverage_prod,uniformAverage_prod] + have hinner (x : X) : + uniformAverage (fun u : U => phi (f x,a u))= + uniformAverage (fun v : V => phi (f x,b v)) := + hab (fun w => phi (f x,w)) + simp_rw [hinner] + exact hfg (fun z => uniformAverage (fun v : V => phi (z,b v))) + +lemma SameLaw.independent {f : X → Z} {g : Y → Z} (h : SameLaw f g) (N : ℕ) : + SameLaw (fun xs : Fin N → X => fun i => f (xs i)) + (fun ys : Fin N → Y => fun i => g (ys i)) := by + intro phi + exact uniformAverage_independent_eq f g h N phi + +lemma indexed (N : ℕ) (f : Fin N → X → Z) (g : Fin N → Y → Z) + (h : ∀ i,SameLaw (f i) (g i)) : + SameLaw (fun xs : Fin N → X => fun i => f i (xs i)) + (fun ys : Fin N → Y => fun i => g i (ys i)) := by + intro phi + induction N with + | zero => + have hf (xs : Fin 0 → X) : (fun i => f i (xs i))=(fun i : Fin 0 => Fin.elim0 i) := by + funext i + exact Fin.elim0 i + have hg (ys : Fin 0 → Y) : (fun i => g i (ys i))=(fun i : Fin 0 => Fin.elim0 i) := by + funext i + exact Fin.elim0 i + simp_rw [hf,hg,uniformAverage_const] + | succ N ih => + have hf (x : X) (xs : Fin N → X) : + (fun i => f i ((Fin.cons x xs : Fin (N+1) → X) i))=Fin.cons (f 0 x) (fun i => f i.succ (xs i)) := by + funext i + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + have hg (y : Y) (ys : Fin N → Y) : + (fun i => g i ((Fin.cons y ys : Fin (N+1) → Y) i))=Fin.cons (g 0 y) (fun i => g i.succ (ys i)) := by + funext i + refine Fin.cases ?_ (fun j => ?_) i <;> rfl + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp_rw [hf,hg] + have htail (x : X) := ih (fun i => f i.succ) (fun i => g i.succ) + (fun i => h i.succ) (fun zs => phi (Fin.cons (f 0 x) zs)) + simp_rw [htail] + exact h 0 (fun z => uniformAverage (fun ys : Fin N → Y => + phi (Fin.cons z (fun i => g i.succ (ys i))))) + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePaddedAverage.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePaddedAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..6eb95e4759900a711f184fcc123ceed2c8dac206 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePaddedAverage.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # Observables of a padded and reindexed finite Boolean word -/ + +namespace ContingencyTables.FairBits + +open CommonBasesFPRAS FirstSuccess ResidualMixture FiniteLawMoments +open scoped BigOperators Classical + +noncomputable section + +lemma padded_equiv_average {k N : ℕ} (hk : k ≤ N) {X : Type*} [Fintype X] + (e : (Fin k → Bool) ≃ X) (f : X → ℝ) : + uniformAverage (fun bits : Fin N → Bool => f (e (prefixWord hk bits)))= + uniformAverage f := by + have hp := word_expectation (prefixWord hk) (fun bits => f (e bits)) + rw [prefixWord_uniform,expectation_uniform] at hp + exact hp.trans (uniformAverage_equiv e f) + +end +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartialDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartialDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..9605f0db146bc01d6aea3a2b35f7bf0295288292 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartialDraw.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import OAI.Combinatorics.ContingencyTables.Transport.CompletionKernelIdentification +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts +import Mathlib.Data.Fintype.EquivFin + +namespace OAI + +/-! # One Boolean word per listed proposal, with unused words giving a hold -/ + +namespace ContingencyTables.FairBits + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +variable {X : Type*} [Fintype X] + +/-- A code with no preimage is an explicit hold. -/ +def injectionDraw {k : ℕ} (e : X ↪ Fin (2^k)) (b : Fin (2^k)) : Option X := + if h : ∃ x,e x=b then some (Classical.choose h) else none + +lemma injectionDraw_eq_some {k : ℕ} (e : X ↪ Fin (2^k)) (b : Fin (2^k)) (x : X) : + injectionDraw e b=some x ↔ b=e x := by + by_cases h : ∃ y,e y=b + · simp only [injectionDraw,dite_eq_left h,Option.some.injEq] + constructor + · intro hx + rw [←hx] + exact (Classical.choose_spec h).symm + · intro hx + apply e.injective + exact (Classical.choose_spec h).trans hx + · have hn : b≠e x := by + intro hx + exact h ⟨x,hx.symm⟩ + simp only [injectionDraw,dite_eq_right h,reduceCtorEq,hn] + +/-- Every listed proposal gets exactly one equally likely bit string. -/ +theorem injectionDraw_mass {k : ℕ} (e : X ↪ Fin (2^k)) (x : X) : + (mapLaw (uniformLaw (α := Fin (2^k))) (injectionDraw e)).mass (some x)=1/(2:ℚ)^k := by + simp only [mapLaw,injectionDraw_eq_some,uniformLaw,uniformMass,Fintype.card_fin] + simp + +def proposalEmbedding (k : ℕ) (h : Fintype.card X ≤ 2^k) : X ↪ Fin (2^k) := + Classical.choice (Function.Embedding.nonempty_of_card_le (by simpa using h)) + +def partialBitDraw (k : ℕ) (h : Fintype.card X ≤ 2^k) (bits : Fin k → Bool) : Option X := + injectionDraw (proposalEmbedding k h) (binaryWordEquiv k bits) + +theorem partialBitDraw_mass (k : ℕ) (h : Fintype.card X ≤ 2^k) (x : X) : + (mapLaw (uniformLaw (α := Fin k → Bool)) (partialBitDraw k h)).mass (some x)=1/(2:ℚ)^k := by + unfold partialBitDraw + rw [←map_equiv (binaryWordEquiv k),uniform_equiv] + exact injectionDraw_mass _ x + +variable {S : Type*} [Fintype S] [DecidableEq X] + +lemma optionMap_mass_injective (p : RationalLaw (Option S)) (f : S → X) + (hf : Function.Injective f) (s : S) : + (mapLaw p (Option.map f)).mass (some (f s))=p.mass (some s) := by + simp only [mapLaw,Fintype.sum_option,Option.map_none,Option.map_some, + Option.some.injEq,reduceCtorEq,ite_false,zero_add,hf.eq_iff] + simp + +lemma optionMap_mass_outside (p : RationalLaw (Option S)) (f : S → X) (x : X) + (hx : ∀ s,f s≠x) : (mapLaw p (Option.map f)).mass (some x)=0 := by + simp only [mapLaw,Fintype.sum_option,Option.map_none,Option.map_some, + Option.some.injEq,reduceCtorEq,ite_false,zero_add,hx,Finset.sum_const_zero] + +def subsetBitDraw (p : X → Prop) (k : ℕ) (h : Fintype.card {x // p x} ≤ 2^k) + (bits : Fin k → Bool) : Option X := + (partialBitDraw (X := {x // p x}) k h bits).map Subtype.val + +/-- Distinct listed outcomes each have the advertised dyadic mass. -/ +theorem subsetBitDraw_mass (p : X → Prop) (k : ℕ) + (h : Fintype.card {x // p x} ≤ 2^k) (x : X) : + (mapLaw (uniformLaw (α := Fin k → Bool)) (subsetBitDraw p k h)).mass (some x)= + if p x then 1/(2:ℚ)^k else 0 := by + let : DecidableEq {x // p x} := Classical.decEq _ + change (mapLaw (uniformLaw (α := Fin k → Bool)) + (fun bits => Option.map Subtype.val (partialBitDraw k h bits))).mass (some x)=_ + rw [←mapLaw_comp] + by_cases hx : p x + · rw [ite_eq_left hx] + exact (optionMap_mass_injective _ Subtype.val Subtype.val_injective ⟨x,hx⟩).trans + (partialBitDraw_mass k h ⟨x,hx⟩) + · rw [ite_eq_right hx] + exact optionMap_mass_outside _ Subtype.val x (fun s hs => hx (hs ▸ s.property)) + +end +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartitionVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartitionVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..f13d26e56704bfa92a77865dc7b24bd74bc20d87 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePartitionVariance.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance + +namespace OAI + +/-! # Exact variance decomposition for finite physical prefix partitions -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical + +variable {X C D : Type*} [Fintype X] [Fintype C] [Fintype D] + +noncomputable def fibreWeight (w : X → ℝ) (π : X → C) (c : C) : X → ℝ := + fun x => if π x=c then w x else 0 + +omit [Fintype X] [Fintype C] [Fintype D] in +lemma fibreWeight_mul (w H : X → ℝ) (π : X → C) (c : C) (x : X) : + fibreWeight (fun x => w x*H x) π c x=fibreWeight w π c x*H x := by + simp only [fibreWeight,ite_mul,zero_mul] + +omit [Fintype X] [Fintype C] [Fintype D] in +lemma fibreWeight_nonnegative (w : X → ℝ) (hw : ∀ x,0 ≤ w x) (π : X → C) (c : C) : + ∀ x,0 ≤ fibreWeight w π c x := by + intro x + unfold fibreWeight + split_ifs + · exact hw x + · exact le_rfl + +omit [Fintype D] in +theorem variance_partition (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) (π : X → C) : + variance w H=(∑ c,variance (fibreWeight w π c) H)+ + variance (fun c => ∑ x,fibreWeight w π c x) + (fun c => mean (fibreWeight w π c) H) := by + have hw' : ∀ c x,0 ≤ fibreWeight w π c x := fibreWeight_nonnegative w hw π + have hsplit := variance_split (fibreWeight w π) (fun _ => H) hw' + have he : variance (fun p : X×C => fibreWeight w π p.2 p.1) (fun p => H p.1)=variance w H := by + rw [variance_formula (fun p : X×C => fibreWeight w π p.2 p.1) + (fun p => H p.1) (fun p => hw' p.2 p.1),variance_formula w H hw] + simp only [Fintype.sum_prod_type,fibreWeight,ite_mul,zero_mul, + Finset.sum_ite_eq,Finset.mem_univ,ite_true] + rw [he] at hsplit + exact hsplit + +noncomputable def partitionVariance (w H : X → ℝ) (π : X → C) : ℝ := + ∑ c,variance (fibreWeight w π c) H + +noncomputable def partitionContribution (w H : X → ℝ) (π : X → C) (ρ : X → D) : ℝ := + ∑ c,variance (fun d => ∑ x,fibreWeight (fibreWeight w π c) ρ d x) + (fun d => mean (fibreWeight (fibreWeight w π c) ρ d) H) + +omit [Fintype X] [Fintype C] [Fintype D] in +lemma fibreWeight_pair (w : X → ℝ) (π : X → C) (ρ : X → D) (c : C) (d : D) : + fibreWeight (fibreWeight w π c) ρ d=fibreWeight w (fun x => (π x,ρ x)) (c,d) := by + funext x + unfold fibreWeight + simp only [Prod.mk.injEq] + by_cases hc : π x=c <;> by_cases hd : ρ x=d <;> simp only [hc,hd,↓reduceIte,and_self, + false_and,and_false] + +/-- Refining a physical prefix adds exactly its between-child variance. +All zero fibres are retained and contribute zero. -/ +theorem partition_refinement (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) + (π : X → C) (ρ : X → D) : + partitionVariance w H π=partitionVariance w H (fun x => (π x,ρ x))+ + partitionContribution w H π ρ := by + have h (c : C) := variance_partition (fibreWeight w π c) H + (fibreWeight_nonnegative w hw π c) ρ + unfold partitionVariance partitionContribution + simp_rw [h] + rw [Finset.sum_add_distrib,Fintype.sum_prod_type] + simp_rw [fibreWeight_pair] + +omit [Fintype D] in +lemma partitionVariance_reindex {E : Type*} [Fintype E] (e : C ≃ E) + (w H : X → ℝ) (π : X → C) : + partitionVariance w H (fun x => e (π x))=partitionVariance w H π := by + unfold partitionVariance + symm + apply Fintype.sum_equiv e + intro c + congr 1 + funext x + simp only [fibreWeight,Equiv.apply_eq_iff_eq] + +omit [Fintype C] [Fintype D] in +lemma variance_singleton_fibre (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) (a : X) : + variance (fibreWeight w id a) H=0 := by + rw [variance_formula _ H (fibreWeight_nonnegative w hw id a)] + simp only [fibreWeight,id_eq,ite_mul,zero_mul,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + by_cases hz : w a=0 + · simp only [hz,zero_mul,zero_pow,ne_eq,OfNat.ofNat_ne_zero,not_false_eq_true,div_zero,sub_zero] + · field_simp + ring + +omit [Fintype C] [Fintype D] in +lemma partitionVariance_identity (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) : + partitionVariance w H id=0 := by + unfold partitionVariance + simp only [variance_singleton_fibre w H hw,Finset.sum_const_zero] + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePrefixVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePrefixVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..58483fae285409e910eb17312155dba9aa9a86ae --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FinitePrefixVariance.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FinitePartitionVariance +import Mathlib.Data.Fin.Tuple.Basic + +namespace OAI + +/-! # Variance telescoping for literal finite coordinate prefixes -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical + +def restriction {A : Type*} {q : ℕ} (k : ℕ) (hk : k ≤ q) + (a : Fin q → A) : Fin k → A := fun i => a ⟨i.val,lt_of_lt_of_le i.isLt hk⟩ + +def prefixSnocEquiv (A : Type*) (k : ℕ) : ((Fin k → A)×A) ≃ (Fin (k+1) → A) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _ => A)) + +lemma restriction_snoc {A : Type*} {q k : ℕ} (hk : k < q) (a : Fin q → A) : + prefixSnocEquiv A k (restriction k (Nat.le_of_lt hk) a,a ⟨k,hk⟩)= + restriction (k+1) hk a := by + change Fin.snoc (restriction k (Nat.le_of_lt hk) a) (a ⟨k,hk⟩)=restriction (k+1) hk a + have hi : restriction k (Nat.le_of_lt hk) a=Fin.init (restriction (k+1) hk a) := rfl + rw [hi] + exact Fin.snoc_init_self _ + +variable {A : Type*} [Fintype A] {q : ℕ} + +noncomputable def prefixVariance (w H : (Fin q → A) → ℝ) (k : ℕ) (hk : k ≤ q) : ℝ := + partitionVariance w H (restriction k hk) + +noncomputable def prefixContribution (w H : (Fin q → A) → ℝ) (k : Fin q) : ℝ := + partitionContribution w H (restriction k.val (Nat.le_of_lt k.isLt)) (fun a => a k) + +theorem prefixVariance_step (w H : (Fin q → A) → ℝ) (hw : ∀ a,0 ≤ w a) (k : Fin q) : + prefixVariance w H k.val (Nat.le_of_lt k.isLt)= + prefixVariance w H (k.val+1) k.isLt+prefixContribution w H k := by + have hp := partition_refinement w H hw (restriction k.val (Nat.le_of_lt k.isLt)) (fun a => a k) + have he := partitionVariance_reindex (prefixSnocEquiv A k.val) w H + (fun a => (restriction k.val (Nat.le_of_lt k.isLt) a,a k)) + have hfun : (fun a => prefixSnocEquiv A k.val (restriction k.val (Nat.le_of_lt k.isLt) a,a k))= + restriction (k.val+1) k.isLt := by + funext a + exact restriction_snoc k.isLt a + rw [hfun] at he + rw [← he] at hp + exact hp + +lemma prefixVariance_zero (w H : (Fin q → A) → ℝ) : prefixVariance w H 0 (Nat.zero_le q)=variance w H := by + unfold prefixVariance partitionVariance + rw [Fintype.sum_unique] + congr 1 + funext a + unfold fibreWeight + rw [ite_eq_left (Subsingleton.elim _ _)] + +lemma prefixVariance_final (w H : (Fin q → A) → ℝ) (hw : ∀ a,0 ≤ w a) : + prefixVariance w H q le_rfl=0 := by + change partitionVariance w H id=0 + exact partitionVariance_identity w H hw + +/-- Each physical exposure depth incurs its own budget once. -/ +theorem variance_le_prefix_budget (w H : (Fin q → A) → ℝ) (hw : ∀ a,0 ≤ w a) + (B : ℝ) (hb : ∀ k : Fin q,prefixContribution w H k ≤ B) : + variance w H ≤ q*B := by + have hacc : ∀ k (hk : k ≤ q),variance w H ≤ prefixVariance w H k hk+k*B := by + intro k + induction k with + | zero => + intro hk + rw [prefixVariance_zero] + simp only [Nat.cast_zero,zero_mul,add_zero,le_refl] + | succ k ih => + intro hk + have hkl : k < q := by omega + have hstep := prefixVariance_step w H hw ⟨k,hkl⟩ + have hprevious := ih (Nat.le_of_lt hkl) + have hbound := hb ⟨k,hkl⟩ + dsimp only at hstep hbound + rw [hstep] at hprevious + rw [Nat.cast_succ] + linarith + have h := hacc q le_rfl + rw [prefixVariance_final w H hw,zero_add] at h + exact h + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProductAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProductAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6354dfd95955d78da6d11c7e1aa75801c1146aa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProductAccuracy.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Counting.AnnealingMultipliers +import OAI.Combinatorics.ContingencyTables.Counting.CompanionReferenceAccuracy + +namespace OAI + +/-! # Relative accuracy of the finite product used by the weight oracle -/ + +namespace ContingencyTables.FiniteProductAccuracy + +open scoped BigOperators Classical + +variable {J : Type*} [Fintype J] + +lemma relative_log (x y delta : ℝ) (hy : 0 < y) (hd0 : 0 ≤ delta) (hd : delta ≤ 1/4) + (herr : |x-y| ≤ delta*y) : 0 < x ∧ |Real.log (x/y)| ≤ 4*delta := by + have hh := abs_le.mp herr + have hx : (1-delta)*y ≤ x ∧ x ≤ (1+delta)*y := by constructor <;> nlinarith + have h1 : (1-delta)*(1:ℝ) ≤ 1 ∧ (1:ℝ) ≤ (1+delta)*1 := by constructor <;> nlinarith + have hp := AnnealingMultipliers.relative_ratio hy (by norm_num : (0:ℝ)<1) hd0 hd hx h1 + refine ⟨AnnealingMultipliers.empirical_positive hy hd hx.1,?_⟩ + simpa only [mul_one,one_mul] using hp.2.2.2 + +lemma product_log (x y : J → ℝ) (hy : ∀ j,0 < y j) (delta : ℝ) + (hd0 : 0 ≤ delta) (hd : delta ≤ 1/4) (herr : ∀ j,|x j-y j| ≤ delta*y j) : + 0 < ∏ j,x j ∧ |Real.log ((∏ j,x j)/(∏ j,y j))| ≤ 4*(Fintype.card J:ℝ)*delta := by + have hstep := fun j => relative_log (x j) (y j) delta (hy j) hd0 hd (herr j) + refine ⟨Finset.prod_pos (fun j _ => (hstep j).1),?_⟩ + rw [←Finset.prod_div_distrib,Real.log_prod (fun j _ => div_ne_zero (hstep j).1.ne' (hy j).ne')] + calc + _ ≤ ∑ j,|Real.log (x j/y j)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ _j : J,4*delta := Finset.sum_le_sum (fun j _ => (hstep j).2) + _ = _ := by simp; ring + +/-- The source has j+1 factors, each observed to the same tolerance. +This scalar budget is sufficient for its requested relative interval. -/ +theorem product_relative (x y : J → ℝ) (hy : ∀ j,0 < y j) (epsilon : ℝ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) + (herr : ∀ j,|x j-y j| ≤ (epsilon/(200*(Fintype.card J:ℝ)))*y j) + (hcard : 0 < Fintype.card J) : + (1-epsilon/4)*(∏ j,y j) ≤ ∏ j,x j ∧ + (∏ j,x j) ≤ (1+epsilon/4)*(∏ j,y j) := by + have hc : (0:ℝ) < Fintype.card J := by exact_mod_cast hcard + have hc1 : (1:ℝ) ≤ Fintype.card J := by exact_mod_cast hcard + have hd0 : 0 ≤ epsilon/(200*(Fintype.card J:ℝ)) := by positivity + have hd : epsilon/(200*(Fintype.card J:ℝ)) ≤ 1/4 := by + rw [div_le_iff₀ (by positivity : (0:ℝ)<200*(Fintype.card J:ℝ))] + linarith + have hh := product_log x y hy _ hd0 hd herr + have hb : 4*(Fintype.card J:ℝ)*(epsilon/(200*(Fintype.card J:ℝ)))=epsilon/50 := by + field_simp [hc.ne'] + ring + have ht := Finset.prod_pos (s := Finset.univ) (fun j _ => hy j) + have hr := CompanionReferenceAccuracy.relative_of_log_error epsilon + ((∏ j,x j)/(∏ j,y j)) he0 he1 (div_pos hh.1 ht) (hh.2.trans_eq hb) + exact ⟨(le_div_iff₀ ht).mp hr.1,(div_le_iff₀ ht).mp hr.2⟩ + +end ContingencyTables.FiniteProductAccuracy + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProjectedHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProjectedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..a46263b4443ded90c26024f39bfc67cdcd8b1cdf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProjectedHistory.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedHistory + +namespace OAI + +/-! # Adaptive histories observed through a projection -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS +open scoped Classical +noncomputable section + +/-- Intermediate representations may vary as long as their projected next-step +law agrees and the representation invariant is preserved. -/ +theorem projected_foldl_sameLaw {C Z U V : Type*} [Fintype U] [Fintype V] + (F : C→U→C) (G : Z→V→Z) (e : C→Z) (Valid : C→Prop) + (hvalid : ∀ c,Valid c→∀ u,Valid (F c u)) + (hstep : ∀ c,Valid c→SameLaw (fun u => e (F c u)) (G (e c))) + (c : C) (hc : Valid c) (N : ℕ) : + SameLaw (fun us : Fin N→U => e ((List.ofFn us).foldl F c)) + (fun vs : Fin N→V => (List.ofFn vs).foldl G (e c)) := by + intro phi + induction N generalizing c phi with + | zero => simp only [List.ofFn_zero,List.foldl_nil,uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp only [List.ofFn_cons,List.foldl_cons] + have h := hstep c hc (fun z => uniformAverage (fun vs : Fin N→V => + phi ((List.ofFn vs).foldl G z))) + have hl : uniformAverage (fun u : U => uniformAverage (fun us : Fin N→U => + phi (e ((List.ofFn us).foldl F (F c u)))))= + uniformAverage (fun u : U => uniformAverage (fun vs : Fin N→V => + phi ((List.ofFn vs).foldl G (e (F c u))))) := by + apply congrArg uniformAverage + funext u + exact ih (F c u) (hvalid c hc u) phi + exact hl.trans h + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProposalStay.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProposalStay.lean new file mode 100644 index 0000000000000000000000000000000000000000..9945ea84d79ca307f66a0b6663a7c10d2216e517 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteProposalStay.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionProposalLaw + +namespace OAI + +/-! # A finite proposal with unused words held at the current state -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section +variable {X : Type*} [Fintype X] [DecidableEq X] + +def proposalStayLaw (w : X → ℚ) (hw : ∀ y,0 ≤ w y) + (htotal : ∑ y,w y ≤ 1) (x : X) : RationalLaw X := + mapLaw (proposalLaw w hw htotal) (fun y => y.getD x) + +lemma proposalStayLaw_mass (w : X → ℚ) (hw : ∀ y,0 ≤ w y) + (htotal : ∑ y,w y ≤ 1) (x y : X) : + (proposalStayLaw w hw htotal x).mass y= + w y+if x=y then 1-∑ z,w z else 0 := by + change (∑ z : Option X,if z.getD x=y then (proposalLaw w hw htotal).mass z else 0)=_ + rw [Fintype.sum_option] + simp only [Option.getD_none,Option.getD_some,proposalLaw] + rw [Finset.sum_ite_eq'] + simp only [Finset.mem_univ,ite_true] + ring + +end +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRationalThreshold.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRationalThreshold.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc75dad30b76130e2bbd75863f298c8239150e0d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRationalThreshold.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import OAI.Combinatorics.ContingencyTables.Machines.FairBits +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # A bounded dyadic comparison with a rational acceptance probability -/ + +namespace ContingencyTables.FairBits + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +def rationalThreshold (k : ℕ) (q : ℚ) : ℕ := ⌊(2:ℚ)^k*q⌋₊ + +def rationalThresholdMass (k : ℕ) (q : ℚ) : ℚ := rationalThreshold k q/(2:ℚ)^k + +abbrev rationalThresholdAccept (k : ℕ) (q : ℚ) (bits : Fin k → Bool) : Prop := + (binaryWordEquiv k bits).val < rationalThreshold k q + +lemma rationalThreshold_le (k : ℕ) (q : ℚ) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) : + rationalThreshold k q ≤ 2^k := by + have h := Nat.floor_le (mul_nonneg (by positivity : (0:ℚ) ≤ 2^k) hq0) + have h' : (rationalThreshold k q:ℚ) ≤ (2:ℚ)^k := by + change (⌊(2:ℚ)^k*q⌋₊:ℚ) ≤ (2:ℚ)^k + exact h.trans (by nlinarith [pow_pos (by norm_num : (0:ℚ)<2) k]) + exact_mod_cast h' + +lemma rationalThreshold_count (k : ℕ) (q : ℚ) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) : + (Finset.univ.filter (fun z : Fin (2^k) => z.val < rationalThreshold k q)).card= + rationalThreshold k q := by + rw [Fin.card_filter_val_lt,min_eq_right (rationalThreshold_le k q hq0 hq1)] + +/-- The finite coin always rounds downward and loses less than one +code word, including the exact endpoint probabilities zero and one. -/ +theorem rationalThreshold_error (k : ℕ) (q : ℚ) (hq : 0 ≤ q) : + 0 ≤ rationalThresholdMass k q ∧ rationalThresholdMass k q ≤ q ∧ + q-rationalThresholdMass k q < 1/(2:ℚ)^k := by + have hp : (0:ℚ)<2^k := by positivity + have hlo := Nat.floor_le (mul_nonneg hp.le hq) + have hhi := Nat.lt_floor_add_one ((2:ℚ)^k*q) + change 0 ≤ (⌊(2:ℚ)^k*q⌋₊:ℚ)/(2:ℚ)^k ∧ + (⌊(2:ℚ)^k*q⌋₊:ℚ)/(2:ℚ)^k ≤ q ∧ + q-(⌊(2:ℚ)^k*q⌋₊:ℚ)/(2:ℚ)^k < 1/(2:ℚ)^k + refine ⟨by positivity,?_,?_⟩ + · exact (div_le_iff₀ hp).mpr (by simpa only [mul_comm] using hlo) + · rw [sub_div' hp.ne',div_lt_div_iff_of_pos_right hp] + nlinarith + +/-- An actual k-bit input realizes the stated rounded probability. -/ +theorem rationalThreshold_expectation (k : ℕ) (q : ℚ) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) : + uniformAverage (fun bits : Fin k → Bool => + if rationalThresholdAccept k q bits then (1:ℝ) else 0)= + (rationalThresholdMass k q:ℝ) := by + have he := uniformAverage_equiv (binaryWordEquiv k) + (fun z : Fin (2^k) => if z.val < rationalThreshold k q then (1:ℝ) else 0) + simp only [rationalThresholdAccept] + rw [he] + unfold uniformAverage + rw [←Finset.sum_filter] + simp only [Finset.sum_const,nsmul_eq_mul,mul_one,rationalThreshold_count k q hq0 hq1, + Fintype.card_fin,rationalThresholdMass,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat, + Nat.cast_pow,Nat.cast_ofNat] + +end + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRecordedHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRecordedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8abc54a9e36c8e32992b51d88e746fef2bac735 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRecordedHistory.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedHistory +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrajectory + +namespace OAI + +/-! # The fixed-capacity recorder stores the chronological word history -/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS FirstSuccess RealKernelApproximation +open CompanionBooleanPhase CompanionPhaseTrajectory + +lemma traceStates_snoc {X U : Type*} (F : X → U → X) (us : List U) (c : X) (u : U) : + traceStates F c (us++[u])= + traceStates F c us++[F (us.foldl F c) u] := by + induction us generalizing c with + | nil => rfl + | cons a us ih => + change c::traceStates F (F c a) (us++[u])= + c::(traceStates F (F c a) us++[F (us.foldl F (F c a)) u]) + rw [ih] + +def recorded {X : Type*} {k : ℕ} (F : X → (Fin k → Bool) → X) (N : ℕ) (c : X) + (n : ℕ) (words : Fin n → Fin k → Bool) : PathState X N := + wordWalk (fun a bits => pathPut a (F (pathRead a) bits)) (pathInitial N c) n words + +lemma recorded_position {X : Type*} {k : ℕ} (F : X → (Fin k → Bool) → X) + (N : ℕ) (c : X) (n : ℕ) (hn : n ≤ N) (words : Fin n → Fin k → Bool) : + (recorded F N c n words).1.val=n := by + induction n with + | zero => rfl + | succ n ih => + change (pathPut (recorded F N c n (Fin.init words)) + (F (pathRead (recorded F N c n (Fin.init words))) (words (Fin.last n)))).1.val=n+1 + rw [position_put] + · rw [ih (by omega)] + · rw [ih (by omega)] + omega + +lemma recorded_read {X : Type*} {k : ℕ} (F : X → (Fin k → Bool) → X) + (N : ℕ) (c : X) (n : ℕ) (words : Fin n → Fin k → Bool) : + pathRead (recorded F N c n words)=(List.ofFn words).foldl F c := by + induction n with + | zero => rfl + | succ n ih => + change pathRead (pathPut (recorded F N c n (Fin.init words)) + (F (pathRead (recorded F N c n (Fin.init words))) (words (Fin.last n))))=_ + rw [read_put,ih,List.ofFn_succ',List.concat_eq_append,List.foldl_append] + rfl + +theorem recorded_prefix {X : Type*} {k : ℕ} (F : X → (Fin k → Bool) → X) + (N : ℕ) (c : X) (n : ℕ) (hn : n ≤ N) (words : Fin n → Fin k → Bool) : + historyPrefix (recorded F N c n words)=traceStates F c (List.ofFn words) := by + induction n with + | zero => exact prefix_initial N c + | succ n ih => + change historyPrefix (pathPut (recorded F N c n (Fin.init words)) + (F (pathRead (recorded F N c n (Fin.init words))) (words (Fin.last n))))=_ + rw [prefix_put] + · rw [ih (by omega),recorded_read,List.ofFn_succ',List.concat_eq_append,traceStates_snoc] + rfl + · rw [recorded_position F N c n (by omega)] + omega + +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairDegree.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a4d73a3a38e140187e46033ec090255eca86811 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairDegree.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSymmetricEnergy + +namespace OAI + +/-! # The finite list of designated and inverse repair neighbors -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped Classical + +variable {X D T : Type*} [Fintype D] [Fintype T] + +omit [Fintype T] in +/-- If the source encoding is injective there is at most one outgoing +repair at a fixed state. -/ +theorem outgoing_repair_card_le (x y : D → X) (hx : Function.Injective x) (v : X) : + ((Finset.univ.filter (fun d => x d=v)).image y).card ≤ 1 := by + have hsmall : (Finset.univ.filter (fun d => x d=v)).card ≤ 1 := by + apply Finset.card_le_one.mpr + intro a ha b hb + exact hx ((Finset.mem_filter.mp ha).2.trans (Finset.mem_filter.mp hb).2.symm) + exact Finset.card_image_le.trans hsmall + +/-- The ordered defect type and repaired profile identify the source. +Consequently a fixed target has at most one inverse repair of each type. -/ +theorem incoming_repair_card_le (x y : D → X) (label : D → T) + (h : Function.Injective (fun d => (label d,y d))) (v : X) : + ((Finset.univ.filter (fun d => y d=v)).image x).card ≤ Fintype.card T := by + let S := {d : D // y d=v} + have hlabel : Function.Injective (fun d : S => label d.val) := by + intro a b he + apply Subtype.ext + exact h (Prod.ext he (a.property.trans b.property.symm)) + have hcard : Fintype.card S ≤ Fintype.card T := Fintype.card_le_of_injective _ hlabel + have he : (Finset.univ.filter (fun d => y d=v)).card=Fintype.card S := by + symm + exact Fintype.card_subtype _ + exact Finset.card_image_le.trans (he.le.trans hcard) + +noncomputable def repairNeighbors (x y : D → X) (v : X) : Finset X := + ((Finset.univ.filter (fun d => x d=v)).image y) ∪ + ((Finset.univ.filter (fun d => y d=v)).image x) + +omit [Fintype T] in +lemma mem_repairNeighbors_forward (x y : D → X) (v : X) (d : D) (h : x d=v) : + y d ∈ repairNeighbors x y v := by + unfold repairNeighbors + exact Finset.mem_union_left _ + (Finset.mem_image.mpr ⟨d,Finset.mem_filter.mpr ⟨Finset.mem_univ _,h⟩,rfl⟩) + +omit [Fintype T] in +lemma mem_repairNeighbors_reverse (x y : D → X) (v : X) (d : D) (h : y d=v) : + x d ∈ repairNeighbors x y v := by + unfold repairNeighbors + exact Finset.mem_union_right _ + (Finset.mem_image.mpr ⟨d,Finset.mem_filter.mpr ⟨Finset.mem_univ _,h⟩,rfl⟩) + +theorem repairNeighbors_card_le (x y : D → X) (hx : Function.Injective x) (label : D → T) + (h : Function.Injective (fun d => (label d,y d))) (v : X) : + (repairNeighbors x y v).card ≤ 1+Fintype.card T := by + exact (Finset.card_union_le _ _).trans + (Nat.add_le_add (outgoing_repair_card_le x y hx v) (incoming_repair_card_le x y label h v)) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9bbf67b3b8d54ce587bacf47e9fef5907ac31c3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteRepairVariance.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance +import OAI.Combinatorics.ContingencyTables.Transport.AuxiliaryRepairMass + +namespace OAI + +/-! # Finite variance extension along completion-retaining repairs -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical +open CommonBasesFPRAS + +variable {X : Type*} [Fintype X] + +lemma variance_le_center (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) (a : ℝ) : + variance w H ≤ ∑ x,w x*(H x-a)^2 := by + by_cases hz : 0 < ∑ x,w x + · exact finite_center_min Finset.univ w H a hz + · have hz' : (∑ x,w x)=0 := + le_antisymm (le_of_not_gt hz) (Finset.sum_nonneg (fun x _ => hw x)) + have hzero := zero_mass_weights w hw hz' + simp only [variance,hzero,zero_mul,Finset.sum_const_zero,le_refl] + +omit [Fintype X] in +lemma square_repair_split (x y a : ℝ) : (x-a)^2 ≤ 2*(x-y)^2+2*(y-a)^2 := by + nlinarith [sq_nonneg (x-2*y+a)] + +omit [Fintype X] in +lemma repair_center_mass {B D T : Type*} [Fintype B] [Fintype D] [Fintype T] + (w : B → ℝ) (v : D → ℝ) (H : B → ℝ) (R : D → B) (label : D → T) + (hw : ∀ b,0 ≤ w b) (hdom : ∀ d,v d ≤ w (R d)) + (hinj : Function.Injective (fun d => (label d,R d))) (a : ℝ) : + (∑ d,v d*(H (R d)-a)^2) ≤ Fintype.card T*∑ b,w b*(H b-a)^2 := by + calc + _ ≤ ∑ d,w (R d)*(H (R d)-a)^2 := + Finset.sum_le_sum (fun d _ => mul_le_mul_of_nonneg_right (hdom d) (sq_nonneg _)) + _ ≤ ∑ p : T×B,w p.2*(H p.2-a)^2 := + ExcessContextProfiles.finite_injective_sum_le (fun d => (label d,R d)) hinj + (fun p => w p.2*(H p.2-a)^2) (fun p => mul_nonneg (hw _) (sq_nonneg _)) + _ = _ := by + rw [Fintype.sum_prod_type] + simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + +omit [Fintype X] in +/-- The actual typewise repair injection extends a transversal variance +bound to all states, charging each defect-to-repair difference once. -/ +theorem variance_sum_repair {B D T : Type*} [Fintype B] [Fintype D] [Fintype T] + (w : B → ℝ) (v : D → ℝ) (H : B → ℝ) (K : D → ℝ) + (R : D → B) (label : D → T) (hw : ∀ b,0 ≤ w b) (hv : ∀ d,0 ≤ v d) + (hdom : ∀ d,v d ≤ w (R d)) (hinj : Function.Injective (fun d => (label d,R d))) : + variance (Sum.elim w v) (Sum.elim H K) ≤ + (1+2*(Fintype.card T:ℝ))*variance w H+2*∑ d,v d*(K d-H (R d))^2 := by + have hcenter := variance_le_center (Sum.elim w v) (Sum.elim H K) + (fun x => Sum.rec hw hv x) (mean w H) + have hdefect : (∑ d,v d*(K d-mean w H)^2) ≤ + 2*(∑ d,v d*(K d-H (R d))^2)+2*(∑ d,v d*(H (R d)-mean w H)^2) := by + calc + _ ≤ ∑ d,v d*(2*(K d-H (R d))^2+2*(H (R d)-mean w H)^2) := + Finset.sum_le_sum (fun d _ => mul_le_mul_of_nonneg_left + (square_repair_split (K d) (H (R d)) (mean w H)) (hv d)) + _ = _ := by + have he (d : D) : v d*(2*(K d-H (R d))^2+2*(H (R d)-mean w H)^2)= + 2*(v d*(K d-H (R d))^2)+2*(v d*(H (R d)-mean w H)^2) := by ring + simp_rw [he] + rw [Finset.sum_add_distrib,← Finset.mul_sum,← Finset.mul_sum] + have hmass := repair_center_mass w v H R label hw hdom hinj (mean w H) + change (∑ d,v d*(H (R d)-mean w H)^2) ≤ Fintype.card T*variance w H at hmass + rw [Fintype.sum_sum_type] at hcenter + change variance (Sum.elim w v) (Sum.elim H K) ≤ variance w H+(∑ d,v d*(K d-mean w H)^2) at hcenter + nlinarith + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSameLawSupport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSameLawSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cdab36173601ac41b9143d46afd0fd6f836739a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSameLawSupport.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport + +namespace OAI + +/-! # Pointwise support transfer for finite uniform experiments -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section + +theorem SameLaw.property {X Y Z : Type*} [Fintype X] [Fintype Y] + {f : X→Z} {g : Y→Z} (h : SameLaw f g) (P : Z→Prop) + (hg : ∀ y,P (g y)) (x : X) : P (f x) := by + by_contra hx + let bad : Z→ℝ := fun z => if P z then 0 else 1 + have he := h bad + have hz : uniformAverage (fun y => bad (g y))=0 := by + simp only [bad,hg,ite_true,uniformAverage,Finset.sum_const_zero,zero_div] + rw [hz] at he + have hnonneg (t : X) : 0 ≤ bad (f t) := by + dsimp only [bad] + split_ifs <;> norm_num + have hsum : (∑ t : X,bad (f t))=0 := by + rcases (div_eq_zero_iff).mp he with he'|he' + · exact he' + · have hc : Fintype.card X≠0 := by + let : Nonempty X := ⟨x⟩ + exact Fintype.card_ne_zero + exact False.elim (hc (by exact_mod_cast he')) + have hb := Finset.single_le_sum (fun t _ => hnonneg t) (Finset.mem_univ x) + rw [hsum] at hb + simp only [bad,hx,ite_false] at hb + norm_num at hb + +theorem SameLaw.exists_preimage {X Y Z : Type*} [Fintype X] [Fintype Y] + {f : X→Z} {g : Y→Z} (h : SameLaw f g) (x : X) : ∃ y,g y=f x := + h.property (fun z => ∃ y,g y=z) (fun y => ⟨y,rfl⟩) x + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteScaledDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteScaledDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..446778e46377d8598e9dcfe6551db858c8415c11 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteScaledDraw.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk +import OAI.Combinatorics.ContingencyTables.Transport.BoundedOffsetLaw + +namespace OAI + +/-! # The bounded quotient draw is realized by an actual Boolean word -/ + +namespace ContingencyTables.FairBits + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +def scaledInteger (M k : ℕ) (hM : 0 < M) (z : Fin (2 ^ k)) : Fin M := + ⟨M * z.val / 2 ^ k, by + rw [← scale_eq_div] + exact scale_lt hM (pow_pos (by decide) k) z.isLt⟩ + +theorem scaledIntegerLaw_eq (M k : ℕ) (hM : 0 < M) : + mapLaw (uniformLaw (α := Fin (2 ^ k))) (scaledInteger M k hM) = scaledLaw M k hM := by + apply RationalLaw.ext + funext β + rw [uniform_map_mass] + change (∑ z : Fin (2 ^ k), if scaledInteger M k hM z = β then (1 : ℚ) else 0) / + Fintype.card (Fin (2 ^ k)) = outputMass M (2 ^ k) β.val + simp only [scaledInteger, Fin.ext_iff, ← scale_eq_div, Fintype.card_fin] + rw [Fin.sum_univ_eq_sum_range (fun z : ℕ => + if scale M (2 ^ k) z = β.val then (1 : ℚ) else 0) (2 ^ k)] + unfold outputMass fiber + rw [← Finset.sum_filter] + simp + +def scaledBitInteger (M k : ℕ) (hM : 0 < M) (bits : Fin k → Bool) : Fin M := + scaledInteger M k hM (binaryWordEquiv k bits) + +/-- The exact law of the finite Boolean quotient operation is the law +used in the dense offset error estimate and the tabulation formula. -/ +theorem scaledBitIntegerLaw_eq (M k : ℕ) (hM : 0 < M) : + mapLaw (uniformLaw (α := Fin k → Bool)) (scaledBitInteger M k hM) = scaledLaw M k hM := by + unfold scaledBitInteger + rw [← map_equiv (binaryWordEquiv k), uniform_equiv] + exact scaledIntegerLaw_eq M k hM + +end + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c3013134f1609efddd64ece46dcace028170998 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportEnergy.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSymmetricEnergy + +namespace OAI + +/-! # Restricting a finite weighted graph to its positive states -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical + +variable {X Y : Type*} [Fintype X] + +omit [Fintype X] in +lemma pairTerm_eq_zero_left (f H : Y → ℝ) (hf : ∀ y,0 ≤ f y) (a b : Y) + (ha : f a=0) : pairTerm f H (a,b)=0 := by + simp only [pairTerm,ha,min_eq_left (hf b),zero_mul] + +omit [Fintype X] in +lemma pairTerm_eq_zero_right (f H : Y → ℝ) (hf : ∀ y,0 ≤ f y) (a b : Y) + (hb : f b=0) : pairTerm f H (a,b)=0 := by + simp only [pairTerm,hb,min_eq_right (hf a),zero_mul] + +/-- Only endpoints with nonzero weight need to occur in the embedding. +The ambient graph may still contain zero-weight vertices. -/ +theorem symmetricEnergy_restrict (E : Finset (Y×Y)) (f H : Y → ℝ) + (hf : ∀ y,0 ≤ f y) (i : X → Y) (hi : Function.Injective i) + (hsupport : ∀ p ∈ E,(f p.1≠0 → ∃ x,i x=p.1) ∧ (f p.2≠0 → ∃ x,i x=p.2)) : + symmetricEnergy E f H= + (∑ x,∑ y,if (i x,i y) ∈ E then + min (f (i x)) (f (i y))*(H (i x)-H (i y))^2 else 0)/2 := by + let j : X×X → Y×Y := fun p => (i p.1,i p.2) + let S := (Finset.univ : Finset (X×X)).filter (fun p => j p ∈ E) + have hj : Function.Injective j := by + intro a b h + exact Prod.ext (hi (congrArg Prod.fst h)) (hi (congrArg Prod.snd h)) + have hsub : S.image j ⊆ E := by + intro p hp + obtain ⟨q,hq,rfl⟩ := Finset.mem_image.mp hp + exact (Finset.mem_filter.mp hq).2 + have hz (p : Y×Y) (hp : p ∈ E) (hn : p ∉ S.image j) : pairTerm f H p=0 := by + by_cases h₁ : f p.1=0 + · exact pairTerm_eq_zero_left f H hf p.1 p.2 h₁ + by_cases h₂ : f p.2=0 + · exact pairTerm_eq_zero_right f H hf p.1 p.2 h₂ + obtain ⟨x,hx⟩ := (hsupport p hp).1 h₁ + obtain ⟨y,hy⟩ := (hsupport p hp).2 h₂ + have he : j (x,y)=p := Prod.ext hx hy + exact False.elim (hn (Finset.mem_image.mpr ⟨(x,y), + Finset.mem_filter.mpr ⟨Finset.mem_univ _,by rw [he]; exact hp⟩,he⟩)) + unfold symmetricEnergy + rw [← Finset.sum_subset hsub hz,Finset.sum_image (fun a _ b _ h => hj h)] + dsimp only [S] + rw [Finset.sum_filter,Fintype.sum_prod_type] + rfl + +theorem symmetricEnergy_restrict_observable (E : Finset (Y×Y)) (f H : Y → ℝ) + (hf : ∀ y,0 ≤ f y) (i : X → Y) (hi : Function.Injective i) + (hsupport : ∀ p ∈ E,(f p.1≠0 → ∃ x,i x=p.1) ∧ (f p.2≠0 → ∃ x,i x=p.2)) + (h : X → ℝ) (hh : ∀ x,H (i x)=h x) : + symmetricEnergy E f H= + (∑ x,∑ y,if (i x,i y) ∈ E then + min (f (i x)) (f (i y))*(h x-h y)^2 else 0)/2 := by + rw [symmetricEnergy_restrict E f H hf i hi hsupport] + simp_rw [hh] + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba3fbd782b350f520d68549a54c318a1e35dce2c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSupportVariance.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance + +namespace OAI + +/-! # Removing zero-weight states preserves finite weighted variance -/ + +namespace ContingencyTables.FiniteExposureVariance + +open scoped BigOperators Classical + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +/-- An injective encoding may omit only states of weight zero. -/ +theorem sum_support_embedding (e : X → Y) (he : Function.Injective e) + (w : Y → ℝ) (hw : ∀ y ∉ Set.range e,w y=0) (H : Y → ℝ) : + (∑ x,w (e x)*H (e x))=∑ y,w y*H y := by + apply Fintype.sum_of_injective e he _ _ + · intro y hy + rw [hw y hy,zero_mul] + · intro x + rfl + +theorem mean_support_embedding (e : X → Y) (he : Function.Injective e) + (w : Y → ℝ) (hw : ∀ y ∉ Set.range e,w y=0) (H : Y → ℝ) : + mean (fun x => w (e x)) (fun x => H (e x))=mean w H := by + have hm : (∑ x,w (e x))=∑ y,w y := + Fintype.sum_of_injective e he _ _ hw (fun _ => rfl) + unfold mean + rw [sum_support_embedding e he w hw H,hm] + +theorem variance_support_embedding (e : X → Y) (he : Function.Injective e) + (w : Y → ℝ) (hw : ∀ y ∉ Set.range e,w y=0) (H : Y → ℝ) : + variance (fun x => w (e x)) (fun x => H (e x))=variance w H := by + unfold variance + rw [mean_support_embedding e he w hw H] + exact sum_support_embedding e he w hw (fun y => (H y-mean w H)^2) + +omit [Fintype Y] in +/-- In particular, restriction to the strictly positive support does not +change any weighted variance, including the empty-support case. -/ +theorem variance_positive_support (w H : X → ℝ) (hw : ∀ x,0 ≤ w x) : + variance (fun x : {x // 0 < w x} => w x.val) + (fun x => H x.val)=variance w H := by + apply variance_support_embedding Subtype.val Subtype.val_injective w + intro x hx + have hn : ¬0 < w x := by + intro hp + exact hx ⟨⟨x,hp⟩,rfl⟩ + exact le_antisymm (le_of_not_gt hn) (hw x) + +end ContingencyTables.FiniteExposureVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSymmetricEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSymmetricEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..691d38763cf4cd585ad3801710984223ba0b16bf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteSymmetricEnergy.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLeafEnergy + +namespace OAI + +/-! # Repair edges are charged once in a symmetric physical graph -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical + +noncomputable def pairTerm {X : Type*} (f H : X → ℝ) (p : X×X) : ℝ := + min (f p.1) (f p.2)*(H p.1-H p.2)^2 + +noncomputable def symmetricEnergy {X : Type*} (E : Finset (X×X)) (f H : X → ℝ) : ℝ := + (∑ p ∈ E,pairTerm f H p)/2 + +lemma pairTerm_nonnegative {X : Type*} (f H : X → ℝ) (hf : ∀ x,0 ≤ f x) (p : X×X) : + 0 ≤ pairTerm f H p := mul_nonneg (le_min (hf _) (hf _)) (sq_nonneg _) + +lemma pairTerm_reverse {X : Type*} (f H : X → ℝ) (x y : X) : + pairTerm f H (y,x)=pairTerm f H (x,y) := by + unfold pairTerm + rw [min_comm] + congr 1 + ring + +theorem symmetricEnergy_mono {X : Type*} (E F : Finset (X×X)) (hEF : E ⊆ F) + (f H : X → ℝ) (hf : ∀ x,0 ≤ f x) : symmetricEnergy E f H ≤ symmetricEnergy F f H := by + unfold symmetricEnergy + apply div_le_div_of_nonneg_right _ (by norm_num) + exact Finset.sum_le_sum_of_subset_of_nonneg hEF (fun p _ _ => pairTerm_nonnegative f H hf p) + +/-- Distinct defects give distinct unoriented repair edges. Both directed +copies together use twice their weight and hence cancel the energy's half. -/ +theorem repair_energy_le {X D : Type*} [Fintype D] (E : Finset (X×X)) + (f H : X → ℝ) (hf : ∀ x,0 ≤ f x) (x y : D → X) + (hx : Function.Injective x) (hxy : ∀ d e,x d≠y e) + (hforward : ∀ d,(x d,y d) ∈ E) (hreverse : ∀ d,(y d,x d) ∈ E) : + (∑ d,pairTerm f H (x d,y d)) ≤ symmetricEnergy E f H := by + let a := fun d => (x d,y d) + let b := fun d => (y d,x d) + let A := Finset.univ.image a + let B := Finset.univ.image b + have ha : Function.Injective a := fun d e he => hx (congrArg Prod.fst he) + have hb : Function.Injective b := fun d e he => hx (congrArg Prod.snd he) + have hdis : Disjoint A B := by + apply Finset.disjoint_left.mpr + intro p hp hq + obtain ⟨d,_,hd⟩ := Finset.mem_image.mp hp + obtain ⟨e,_,he⟩ := Finset.mem_image.mp hq + exact hxy d e (congrArg Prod.fst (hd.trans he.symm)) + have hsub : A ∪ B ⊆ E := by + intro p hp + rcases Finset.mem_union.mp hp with hp|hp + · obtain ⟨d,_,rfl⟩ := Finset.mem_image.mp hp + exact hforward d + · obtain ⟨d,_,rfl⟩ := Finset.mem_image.mp hp + exact hreverse d + have hA : (∑ p ∈ A,pairTerm f H p)=∑ d,pairTerm f H (x d,y d) := + Finset.sum_image (fun d _ e _ he => ha he) + have hB : (∑ p ∈ B,pairTerm f H p)=∑ d,pairTerm f H (x d,y d) := by + rw [Finset.sum_image (fun d _ e _ he => hb he)] + apply Finset.sum_congr rfl + intro d _ + exact pairTerm_reverse f H (x d) (y d) + have hs : 2*(∑ d,pairTerm f H (x d,y d)) ≤ ∑ p ∈ E,pairTerm f H p := by + calc + _ = ∑ p ∈ A ∪ B,pairTerm f H p := by rw [Finset.sum_union hdis,hA,hB]; ring + _ ≤ _ := Finset.sum_le_sum_of_subset_of_nonneg hsub (fun p _ _ => pairTerm_nonnegative f H hf p) + unfold symmetricEnergy + linarith + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteUniformHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteUniformHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..caf0519ae8c99299201921de6266695b1679cf6d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FiniteUniformHistory.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Exact independent-word law of a finite adaptive-history experiment -/ + +namespace ContingencyTables.FiniteUniformHistory + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section +variable {X : Type*} [Fintype X] [Nonempty X] + +def kernel (_ : List X) (_ : X) : ℝ := 1/Fintype.card X + +lemma kernel_nonneg (h : List X) (x : X) : 0 ≤ kernel h x := by + unfold kernel + positivity + +lemma kernel_mass (h : List X) : ∑ x,kernel h x=1 := by + have hx : (Fintype.card X:ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + simp only [kernel,Finset.sum_const,Finset.card_univ,nsmul_eq_mul] + field_simp [hx] + +lemma expectation (N : ℕ) (h : List X) (f : List X → ℝ) : + FiniteExperiment.expect kernel N h f= + uniformAverage (fun xs : Fin N → X => f (h++List.ofFn xs)) := by + induction N generalizing h with + | zero => simp only [FiniteExperiment.expect,List.ofFn_zero,List.append_nil,uniformAverage_const] + | succ N ih => + simp only [FiniteExperiment.expect,ih] + rw [uniformAverage_fin_succ] + have he : (fun x : X => uniformAverage + (fun xs : Fin N → X => f ((h++[x])++List.ofFn xs)))= + (fun x : X => uniformAverage + (fun xs : Fin N → X => f (h++List.ofFn (Fin.cons x xs)))) := by + funext x + congr 1 + funext xs + simp only [List.ofFn_succ,Fin.cons_zero,Fin.cons_succ,List.append_assoc,List.singleton_append] + rw [←he] + let g : X → ℝ := fun x => uniformAverage + (fun xs : Fin N → X => f ((h++[x])++List.ofFn xs)) + change (∑ x,kernel h x*g x)=uniformAverage g + unfold kernel uniformAverage + rw [←Finset.mul_sum] + ring + +/-- A history-dependent success predicate is evaluated on genuinely +independent finite words; only its conditional one-step loss is assumed. -/ +theorem good_probability (Good : List X → Prop) (N : ℕ) (e : ℝ) (he : 0 ≤ e) + (hstep : ∀ h,Good h → h.length if Good (h++[x]) then (1:ℝ) else 0)) + (hzero : Good []) : + 1-(N:ℝ)*e ≤ uniformAverage (fun xs : Fin N → X => + if Good (List.ofFn xs) then (1:ℝ) else 0) := by + have hs (h : List X) (hh : Good h) (hlen : h.length simp + simp_rw [heq] + rw [←Finset.sum_div] + exact hprob + have hp := FiniteExperiment.good_probability_bounded kernel Good kernel_nonneg + (fun h => (kernel_mass h).le) N e he hs hzero + rw [expectation] at hp + simpa only [List.nil_append] using hp + +end +end ContingencyTables.FiniteUniformHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FirstSuccess.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FirstSuccess.lean new file mode 100644 index 0000000000000000000000000000000000000000..7aa2a4173b6ca15fbf686d2bfc8ae831190f7450 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FirstSuccess.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ResidualMixture +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.Order.Ring.Abs + +namespace OAI + +/-! +# First-success law and finite-law error bounds + +The bounded outer sampler repeats independent trials and uses a fixed +feasible fallback. Its geometric output law has a stationary uniform-mixture +specialization. Total-variation bounds are preserved by deterministic output +maps. +-/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {α β : Type*} [Fintype α] [Fintype β] + +def variation (p q : RationalLaw α) : ℚ := + (∑ x, |p.mass x - q.mass x|) / 2 + +lemma variation_nonnegative (p q : RationalLaw α) : 0 ≤ variation p q := + div_nonneg (Finset.sum_nonneg fun _ _ => abs_nonneg _) (by norm_num) + +lemma geometric_balance (f : ℚ) (J : ℕ) : + (1 - f) * (∑ j ∈ Finset.range J, f ^ j) + f ^ J = 1 := by + induction J with + | zero => simp + | succ J ih => + rw [Finset.sum_range_succ, pow_succ] + nlinarith [ih] + +/-- The exact first-success-or-fallback mass from the manuscript. -/ +def outputMass [DecidableEq α] (g : α → ℚ) (f : ℚ) (J : ℕ) (fallback z : α) : ℚ := + g z * (∑ j ∈ Finset.range J, f ^ j) + if z = fallback then f ^ J else 0 + +omit [Fintype α] in +lemma outputMass_nonnegative [DecidableEq α] (g : α → ℚ) (f : ℚ) (J : ℕ) + (fallback z : α) (hg : ∀ z, 0 ≤ g z) (hf : 0 ≤ f) : + 0 ≤ outputMass g f J fallback z := by + apply add_nonneg + · exact mul_nonneg (hg z) (Finset.sum_nonneg fun _ _ => pow_nonneg hf _) + · split_ifs <;> positivity + +lemma outputMass_total [DecidableEq α] (g : α → ℚ) (f : ℚ) (J : ℕ) + (fallback : α) (htotal : (∑ z, g z) + f = 1) : + ∑ z, outputMass g f J fallback z = 1 := by + simp only [outputMass, Finset.sum_add_distrib, ← Finset.sum_mul, + Finset.sum_ite_eq', Finset.mem_univ, ite_true] + have hsum : (∑ z, g z) = 1 - f := by linarith + rw [hsum] + exact geometric_balance f J + +def outputLaw [DecidableEq α] (g : α → ℚ) (f : ℚ) (J : ℕ) + (fallback : α) (hg : ∀ z, 0 ≤ g z) (hf : 0 ≤ f) + (htotal : (∑ z, g z) + f = 1) : RationalLaw α where + mass := outputMass g f J fallback + nonnegative := fun z => outputMass_nonnegative g f J fallback z hg hf + total := outputMass_total g f J fallback htotal + +variable [Nonempty α] + +def uniformLaw : RationalLaw α where + mass := fun _ => uniformMass (α := α) + nonnegative := fun _ => uniformMass_pos.le + total := uniformMass_total + +omit [Nonempty α] in +/-- Successful stationary pairs have equal mass; the repeated-trial law +is exactly a uniform law mixed with the fallback, without conditioning on +the implemented approximate trial's success. -/ +theorem stationary_output_mass [DecidableEq α] (s : ℚ) (J : ℕ) (fallback z : α) : + outputMass (fun _ => s * uniformMass (α := α)) (1 - s) J fallback z = + (1 - (1 - s) ^ J) * uniformMass (α := α) + + if z = fallback then (1 - s) ^ J else 0 := by + have hgeom := geometric_balance (1 - s) J + have hgeom' : s * (∑ j ∈ Finset.range J, (1 - s) ^ j) = 1 - (1 - s) ^ J := by + nlinarith [hgeom] + dsimp [outputMass] + rw [mul_assoc, mul_comm (uniformMass (α := α)), ← mul_assoc, hgeom'] + +omit [Nonempty α] in +lemma point_mass_variation [DecidableEq α] (p : RationalLaw α) (fallback : α) : + (∑ z, |(if z = fallback then (1 : ℚ) else 0) - p.mass z|) / 2 ≤ 1 := by + have hsum : (∑ z, |(if z = fallback then (1 : ℚ) else 0) - p.mass z|) ≤ 2 := by + calc + _ ≤ ∑ z, ((if z = fallback then (1 : ℚ) else 0) + p.mass z) := by + apply Finset.sum_le_sum + intro z _ + have hi : (0 : ℚ) ≤ if z = fallback then 1 else 0 := by split_ifs <;> norm_num + calc + _ ≤ |if z = fallback then (1 : ℚ) else 0| + |p.mass z| := abs_sub _ _ + _ = _ := by rw [abs_of_nonneg hi, abs_of_nonneg (p.nonnegative z)] + _ = 2 := by simp [Finset.sum_add_distrib, p.total]; norm_num + linarith + +/-- The stationary repeated-trial error is at most the probability that +all trials fail. No error term is divided by a success probability. -/ +theorem stationary_variation [DecidableEq α] (s : ℚ) (_hs0 : 0 ≤ s) (hs1 : s ≤ 1) + (J : ℕ) (fallback : α) : + (∑ z, |outputMass (fun _ => s * uniformMass (α := α)) (1 - s) J fallback z - + uniformMass (α := α)|) / 2 ≤ (1 - s) ^ J := by + have hf : 0 ≤ (1 - s) ^ J := pow_nonneg (sub_nonneg.mpr hs1) _ + have hpoint := point_mass_variation (uniformLaw (α := α)) fallback + have hterm (z : α) : + |outputMass (fun _ => s * uniformMass (α := α)) (1 - s) J fallback z - + uniformMass (α := α)| = + (1 - s) ^ J * |(if z = fallback then (1 : ℚ) else 0) - uniformMass (α := α)| := by + rw [stationary_output_mass] + have heq : (1 - (1 - s) ^ J) * uniformMass (α := α) + + (if z = fallback then (1 - s) ^ J else 0) - uniformMass (α := α) = + (1 - s) ^ J * ((if z = fallback then 1 else 0) - uniformMass (α := α)) := by + split_ifs <;> ring + rw [heq, abs_mul, abs_of_nonneg hf] + simp_rw [hterm] + rw [← Finset.mul_sum] + change (1 - s) ^ J * (∑ z, |(if z = fallback then 1 else 0) - uniformMass (α := α)|) / 2 ≤ _ + change (∑ z, |(if z = fallback then 1 else 0) - uniformMass (α := α)|) / 2 ≤ 1 at hpoint + nlinarith [mul_le_mul_of_nonneg_left hpoint hf] + +omit [Nonempty α] in +def mapLaw [DecidableEq β] (p : RationalLaw α) (f : α → β) : RationalLaw β where + mass := fun y => ∑ x, if f x = y then p.mass x else 0 + nonnegative := fun y => Finset.sum_nonneg fun x _ => by + split_ifs + · exact p.nonnegative x + · rfl + total := by + rw [Finset.sum_comm] + simpa using p.total + +omit [Nonempty α] in +/-- Deterministic postprocessing contracts total variation, as used for +the map selecting the first successful trial and unpadding its table. -/ +theorem variation_map [DecidableEq β] (p q : RationalLaw α) (f : α → β) : + variation (mapLaw p f) (mapLaw q f) ≤ variation p q := by + unfold variation + apply div_le_div_of_nonneg_right _ (by norm_num) + calc + _ = ∑ y, |∑ x, if f x = y then p.mass x - q.mass x else 0| := by + apply Finset.sum_congr rfl + intro y _ + congr 1 + simp only [mapLaw, ← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro x _ + split_ifs <;> simp + _ ≤ ∑ y, ∑ x, |if f x = y then p.mass x - q.mass x else 0| := by + apply Finset.sum_le_sum + intro y _ + exact Finset.abs_sum_le_sum_abs _ _ + _ = ∑ x, |p.mass x - q.mass x| := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp only [abs_ite, abs_zero] + simp + +omit [Nonempty α] in +def productLaw (p : RationalLaw α) (q : RationalLaw β) : RationalLaw (α × β) where + mass := fun z => p.mass z.1 * q.mass z.2 + nonnegative := fun z => mul_nonneg (p.nonnegative z.1) (q.nonnegative z.2) + total := by + simp only [Fintype.sum_prod_type, ← Finset.mul_sum, q.total, mul_one, p.total] + +omit [Nonempty α] in +/-- Independent trials accumulate their errors additively, before the +deterministic first-success map is applied. -/ +theorem variation_product (p q : RationalLaw α) (r s : RationalLaw β) : + variation (productLaw p r) (productLaw q s) ≤ variation p q + variation r s := by + have hpoint (a : α) (b : β) : |p.mass a * r.mass b - q.mass a * s.mass b| ≤ + p.mass a * |r.mass b - s.mass b| + |p.mass a - q.mass a| * s.mass b := by + calc + _ = |p.mass a * (r.mass b - s.mass b) + (p.mass a - q.mass a) * s.mass b| := by + congr 1 + ring + _ ≤ |p.mass a * (r.mass b - s.mass b)| + |(p.mass a - q.mass a) * s.mass b| := + abs_add_le _ _ + _ = _ := by + rw [abs_mul, abs_mul, abs_of_nonneg (p.nonnegative a), abs_of_nonneg (s.nonnegative b)] + have hsum : (∑ a, ∑ b, |p.mass a * r.mass b - q.mass a * s.mass b|) ≤ + (∑ a, |p.mass a - q.mass a|) + (∑ b, |r.mass b - s.mass b|) := by + calc + _ ≤ ∑ a, ∑ b, (p.mass a * |r.mass b - s.mass b| + + |p.mass a - q.mass a| * s.mass b) := by + apply Finset.sum_le_sum + intro a _ + exact Finset.sum_le_sum fun b _ => hpoint a b + _ = _ := by + simp only [Finset.sum_add_distrib, ← Finset.mul_sum, ← Finset.sum_mul, + p.total, s.total, one_mul, mul_one] + ring + unfold variation + simp only [productLaw, Fintype.sum_prod_type] + linarith + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowClamp.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowClamp.lean new file mode 100644 index 0000000000000000000000000000000000000000..137cfb29816d1ab5b4a03cb84f4f636e1eb774a4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowClamp.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PublishedEdmondsKarp +import OAI.Combinatorics.ContingencyTables.Machines.SignedPairProgram + +namespace OAI + +/-! # Binary flow magnitudes and a harmless total-domain clamp + +Skew symmetry bounds a feasible entry between its two directed +capacities. The executed list program clamps normalized entries to this +interval. This is the identity on every valid flow and bounds every +stored value even on unrelated raw program inputs. +-/ + +namespace ContingencyTables.FlowClamp + +open MatchingFPRAS.TreeTyped SignedPairProgram PublishedEdmondsKarp + +lemma feasible_lower {n : ℕ} (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (u v : Fin n) : -(c v u:ℤ)≤f u v := by + have h := hf.2.1 v u + have hs := hf.1 u v + omega + +lemma residual_bounds {n : ℕ} (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (u v : Fin n) : + 0≤(c u v:ℤ)-f u v ∧ (c u v:ℤ)-f u v≤c u v+c v u := by + have hl := feasible_lower c s t f hf u v + have hu := hf.2.1 u v + constructor <;> omega + +def clamp (z : (ℕ×ℕ)×Signed) : Signed := + (min z.1.1 (z.2.1-z.2.2),min z.1.2 (z.2.2-z.2.1)) + +def clampRealizer : Realizer clamp := by + let A : Realizer (fun z : (ℕ×ℕ)×Signed=>z.1.1) := composition first first + let B : Realizer (fun z : (ℕ×ℕ)×Signed=>z.1.2) := composition first second + let N : Realizer (fun z : (ℕ×ℕ)×Signed=>SignedPairProgram.normalize z.2) := + composition second normalizeRealizer + exact pair (composition (pair A (composition N first)) minimum) + (composition (pair B (composition N second)) minimum) + +theorem polynomial_clamp : PolynomialTime clampRealizer := by + unfold clampRealizer + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition + (polynomial_composition polynomial_second polynomial_normalize) polynomial_first)) + polynomial_minimum + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition + (polynomial_composition polynomial_second polynomial_normalize) polynomial_second)) + polynomial_minimum + +theorem clamp_bounds (limits : ℕ×ℕ) (z : Signed) : + (clamp (limits,z)).1≤limits.1 ∧ (clamp (limits,z)).2≤limits.2 := + ⟨min_le_left _ _,min_le_left _ _⟩ + +theorem clamp_eq_normalize (limits : ℕ×ℕ) (z : Signed) + (hl : -(limits.2:ℤ)≤SignedPairProgram.value z) (hu : SignedPairProgram.value z≤limits.1) : + clamp (limits,z)=SignedPairProgram.normalize z := by + apply Prod.ext + · change min limits.1 (z.1-z.2)=z.1-z.2 + apply min_eq_right + unfold SignedPairProgram.value at hu + omega + · change min limits.2 (z.2-z.1)=z.2-z.1 + apply min_eq_right + unfold SignedPairProgram.value at hl + omega + +theorem clamp_feasible {n : ℕ} (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (u v : Fin n) (z : Signed) (hz : SignedPairProgram.value z=f u v) : + clamp ((c u v,c v u),z)=ForestAffineProgram.signedParts (f u v) := by + rw [clamp_eq_normalize _ z (by rw [hz];exact feasible_lower c s t f hf u v) + (by rw [hz];exact hf.2.1 u v),SignedPairProgram.normalize_eq,hz] + +end ContingencyTables.FlowClamp + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowMatrixBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowMatrixBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..73486facce8b0698f8c6848607a2080e1a1be63d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/FlowMatrixBounds.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FlowMatrixProgram + +namespace OAI + +/-! # Binary-size bounds for materialized flow updates -/ + +namespace ContingencyTables.FlowMatrixBounds + +open MatchingFPRAS.TreeTyped ResidualGraphProgram FlowEntryProgram FlowMatrixProgram + +lemma getD_weight {α : Type} [Codec α] (xs : List α) (d : α) + (hd : weight d≤ weight xs) (i : ℕ) : weight (xs.getD i d)≤ weight xs := by + by_cases hi : i< xs.length + · have he : xs.getD i d=xs[i] := by simp [List.getD_eq_getElem?_getD,hi] + rw [he] + exact weight_mem (List.getElem_mem hi) + · simpa [List.getD_eq_getElem?_getD,hi] using hd + +lemma capacityEntry_weight (C : NatMatrix) (u v : ℕ) : + weight (capacityEntry (C,(u,v)))≤ weight C := by + have hr : weight (C.getD u [])≤ weight C := + getD_weight C [] (by + rw [weight_nil] + have hp := weight_pos C + omega) u + have he : weight ((C.getD u []).getD v 0)≤ weight (C.getD u []) := + getD_weight (C.getD u []) 0 (by + change 1≤ weight (C.getD u []) + exact weight_pos _) v + exact he.trans hr + +lemma updateCell_weight (z : EntryInput) : + weight (updateCell z)≤8*weight z.1.1.1+3 := by + have hb := updateCell_bounds z + have h1 := weight_nat_small hb.1 + have h2 := weight_nat_small hb.2 + have hc1 := capacityEntry_weight z.1.1.1 z.2.1 z.2.2 + have hc2 := capacityEntry_weight z.1.1.1 z.2.2 z.2.1 + change weight ((updateCell z).1,(updateCell z).2)≤_ + rw [weight_prod] + change weight (updateCell z).1≤4*weight (capacityEntry (z.1.1.1,(z.2.1,z.2.2)))+1 at h1 + change weight (updateCell z).2≤ + 4*weight (capacityEntry (z.1.1.1,(z.2.2,z.2.1)))+1 at h2 + omega + +lemma updateRow_weight (z : FlowEntryProgram.UpdateData×ℕ) : + weight (updateRow z)≤ z.1.1.1.length*(8*weight z.1.1.1+4)+1 := by + have h := weight_map_bound (as:=List.range z.1.1.1.length) + (f:=fun v=>updateCell (z.1,(z.2,v))) (N:=8*weight z.1.1.1+3) + (fun v _=>updateCell_weight (z.1,(z.2,v))) + simpa only [updateRow,List.length_range] using h + +lemma updateMatrix_weight (z : FlowEntryProgram.UpdateData) : + weight (updateMatrix z)≤ z.1.1.length*(z.1.1.length*(8*weight z.1.1+4)+2)+1 := by + have h := weight_map_bound (as:=List.range z.1.1.length) + (f:=fun u=>updateRow (z,u)) (N:=z.1.1.length*(8*weight z.1.1+4)+1) + (fun u _=>updateRow_weight (z,u)) + simpa only [updateMatrix,List.length_range] using h + +def matrixBound (C : NatMatrix) : ℕ := C.length*(C.length*(8*weight C+4)+2)+1 + +lemma augment_weight (z : Data×List ℕ) : weight (augment z)≤ matrixBound z.1.1 := by + exact updateMatrix_weight (prepareAugment z) + +lemma advance_weight (z : Data×(ℕ×ℕ)) : + weight (advance z)≤ max (weight z.1.2) (matrixBound z.1.1) := by + cases hs : ResidualGraphProgram.search z with + | none => simpa only [advance,hs] using le_max_left (weight z.1.2) (matrixBound z.1.1) + | some xs => + simpa only [advance,hs] using (augment_weight (z.1,xs)).trans + (le_max_right (weight z.1.2) (matrixBound z.1.1)) + +lemma matrixBound_le {S : ℕ} (C : NatMatrix) (h : weight C≤ S) : + matrixBound C≤8*S^3+4*S^2+2*S+1 := by + have hn : C.length≤ S := (list_length_le_weight C).trans h + have h1 := Nat.mul_le_mul hn (show 8*weight C+4≤8*S+4 by omega) + have h2 := Nat.mul_le_mul hn (show C.length*(8*weight C+4)+2≤ S*(8*S+4)+2 by omega) + unfold matrixBound + nlinarith + +end ContingencyTables.FlowMatrixBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..faf32e361b2e740db5bd14389ea4c8030d692c95 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionCounts.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionUnique + +namespace OAI + +/-! +# Multiplicity-one forest-coordinate sums + +The finite coordinates are the actual tree cells of the row/column +forest, with physical intervals [-10 d b,10 d b]. A solution of the +nonroot equations contributes exactly once, with its original weight. +-/ + +namespace ContingencyTables.GraphCompletionCounts + +open scoped BigOperators Classical +open SimpleGraph +open ForestCapacity GraphIntegralCompletion GraphCompletionUnique + +variable {I J : Type*} [Fintype I] [Fintype J] + +abbrev TreeCell (T : SimpleGraph (I⊕J)) := + {a : I×J // T.Adj (.inl a.1) (.inr a.2)} + +abbrev TreeIndex (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) := + (e : TreeCell T) → Fin (20*d*b e.val.1 e.val.2+1) + +noncomputable def physical (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) + (a : TreeIndex T d b) (i : I) (j : J) : ℤ := + if h : T.Adj (.inl i) (.inr j) then + -((10*d*b i j:ℕ):ℤ)+(a ⟨(i,j),h⟩).val else 0 + +omit [Fintype I] [Fintype J] in +lemma physical_supported (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) + (a : TreeIndex T d b) (i : I) (j : J) (h : ¬T.Adj (.inl i) (.inr j)) : + physical T d b a i j=0 := by simp only [physical,h,not_false_eq_true,dite_eq_right] + +omit [Fintype I] [Fintype J] in +lemma physical_injective (T : SimpleGraph (I⊕J)) (d : ℕ) (b : I → J → ℕ) : + Function.Injective (physical T d b) := by + intro a a' h + funext e + apply Fin.ext + have he := congrFun (congrFun h e.val.1) e.val.2 + simp only [physical,e.property,dite_eq_left] at he + exact_mod_cast (add_left_cancel he : ((a e).val:ℤ)=((a' e).val:ℤ)) + +def NonrootMargins (T : SimpleGraph (I⊕J)) (r : I → ℤ) (c : J → ℤ) + (z : I → J → ℤ) : Prop := + (∀ i, Sum.inl i≠componentRoot T (.inl i) → (∑ j, z i j)=r i) ∧ + (∀ j, Sum.inr j≠componentRoot T (.inr j) → (∑ i, z i j)=c j) + +noncomputable def solutionIndex (T : SimpleGraph (I⊕J)) (r : I → ℤ) (c : J → ℤ) + (d : ℕ) (b : I → J → ℕ) + (hbox : ∀ i j, T.Adj (.inl i) (.inr j) → + -((10*d*b i j:ℕ):ℤ)≤tableCompletion T r c i j ∧ + tableCompletion T r c i j≤(10*d*b i j:ℕ)) : TreeIndex T d b := fun e => + ⟨(tableCompletion T r c e.val.1 e.val.2+(10*d*b e.val.1 e.val.2:ℕ)).toNat,by + have h := hbox e.val.1 e.val.2 e.property + have hz : 0≤tableCompletion T r c e.val.1 e.val.2+(10*d*b e.val.1 e.val.2:ℕ) := by omega + have hle : (tableCompletion T r c e.val.1 e.val.2+(10*d*b e.val.1 e.val.2:ℕ)).toNat≤ + 20*d*b e.val.1 e.val.2 := by + exact_mod_cast (show ((tableCompletion T r c e.val.1 e.val.2+ + (10*d*b e.val.1 e.val.2:ℕ)).toNat:ℤ)≤(20*d*b e.val.1 e.val.2:ℕ) by + rw [Int.toNat_of_nonneg hz] + push_cast at h ⊢ + nlinarith) + omega⟩ + +lemma physical_solutionIndex (T : SimpleGraph (I⊕J)) (r : I → ℤ) (c : J → ℤ) + (d : ℕ) (b : I → J → ℕ) + (hbox : ∀ i j, T.Adj (.inl i) (.inr j) → + -((10*d*b i j:ℕ):ℤ)≤tableCompletion T r c i j ∧ + tableCompletion T r c i j≤(10*d*b i j:ℕ)) : + physical T d b (solutionIndex T r c d b hbox)=tableCompletion T r c := by + funext i j + by_cases h : T.Adj (.inl i) (.inr j) + · have hz : 0≤tableCompletion T r c i j+(10*d*b i j:ℕ) := by + have hb := hbox i j h + omega + simp only [physical,h,dite_eq_left,solutionIndex,Int.toNat_of_nonneg hz] + omega + · simp only [physical,h,not_false_eq_true,dite_eq_right,tableCompletion_supported T r c i j h] + +/-- The actual tree intervals contain the unique completion, so the +finite equality-indicator sum has multiplicity exactly one. -/ +theorem weighted_completion_sum (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (r : I → ℤ) (c : J → ℤ) (d : ℕ) (b : I → J → ℕ) + (hbox : ∀ i j, T.Adj (.inl i) (.inr j) → + -((10*d*b i j:ℕ):ℤ)≤tableCompletion T r c i j ∧ + tableCompletion T r c i j≤(10*d*b i j:ℕ)) + (weight : (I → J → ℤ) → ℝ) : + (∑ a : TreeIndex T d b, if NonrootMargins T r c (physical T d b a) + then weight (physical T d b a) else 0)=weight (tableCompletion T r c) := by + let a₀ := solutionIndex T r c d b hbox + have ha₀ : physical T d b a₀=tableCompletion T r c := physical_solutionIndex T r c d b hbox + have hsol : NonrootMargins T r c (tableCompletion T r c) := + ⟨tableCompletion_row small T hTG r c,tableCompletion_column small T hTG r c⟩ + rw [Finset.sum_eq_single a₀] + · simp only [ha₀,hsol,ite_true] + · intro a _ hne + by_cases ha : NonrootMargins T r c (physical T d b a) + · have he := tableCompletion_unique small T hTG hT r c (physical T d b a) + (physical_supported T d b a) ha.1 ha.2 + have haa : a=a₀ := physical_injective T d b (he.trans ha₀.symm) + exact (hne haa).elim + · simp only [ha,ite_false] + · simp + +end ContingencyTables.GraphCompletionCounts + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionUnique.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionUnique.lean new file mode 100644 index 0000000000000000000000000000000000000000..353ede7d8bd2cb6f815fdd7e21df1acb607ad4d6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphCompletionUnique.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Transport.GraphIntegralCompletion + +namespace OAI + +/-! +# Uniqueness of the actual forest completion + +A homogeneous real table supported on an acyclic row/column graph, +with zero sums at every nonroot vertex, vanishes. The proof constructs +an actual root-away deletion cut for each tree cell and isolates that +cell in the signed margin sum. Thus the integral root-path construction +is the unique integral completion, without a leaf-order encoding input. +-/ + +namespace ContingencyTables.GraphCompletionUnique + +open scoped BigOperators Classical +open SimpleGraph +open MaximumForest ForestCut ForestCapacity GraphIntegralCompletion + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- This is the nonsingular forest-incidence assertion needed by the +companion's tree-coordinate sum, over the reals as well as the integers. -/ +theorem zero_of_nonroot_sums (T : SimpleGraph (I⊕J)) + (hT : T.IsAcyclic) (z : I → J → ℝ) + (hsupport : ∀ i j, ¬T.Adj (.inl i) (.inr j) → z i j=0) + (hr : ∀ i, Sum.inl i≠componentRoot T (.inl i) → (∑ j, z i j)=0) + (hc : ∀ j, Sum.inr j≠componentRoot T (.inr j) → (∑ i, z i j)=0) : + ∀ i j, z i j=0 := by + intro i₀ j₀ + by_cases ht : T.Adj (.inl i₀) (.inr j₀) + · let t : Sym2 (I⊕J) := s(Sum.inl i₀,Sum.inr j₀) + let D := T.deleteEdges {t} + let root := componentRoot T (.inl i₀) + have hrootReach : T.Reachable root (.inl i₀) := + (componentRoot_reachable T (.inl i₀)).symm + obtain ⟨r,hrr,hrootSide,hcross⟩ := exists_root_avoiding_side T hT ht root hrootReach + let rowU : I → Bool := fun i => side D r (.inl i) + let colU : J → Bool := fun j => side D r (.inr j) + have hcross' : rowU i₀≠colU j₀ := hcross + have hrootRoot : componentRoot T root=root := componentRoot_idempotent T (.inl i₀) + have hnonroot : ∀ v : I⊕J, side D r v=true → v≠componentRoot T v := by + intro v hv he + have hrv : D.Reachable r v := by simpa only [side,decide_eq_true_eq] using hv + have hcomp := hrr.trans (hrv.mono (T.deleteEdges_le {t})) + have hsame : componentRoot T v=root := by + rw [← componentRoot_constant T hcomp,hrootRoot] + have hvroot : v=root := he.trans hsame + have hbad : side D r root=true := by simpa only [hvroot] using hv + exact Bool.false_ne_true (hrootSide.symm.trans hbad) + let f : I×J → ℝ := fun a => cutTerm (fun _ _ => false) rowU colU 0 0 z 0 a.1 a.2 + have hsum : (∑ a, f a)=0 := by + rw [Fintype.sum_prod_type] + apply cut_sum_zero + · intro i hi + simpa only [rowDifference,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero] + using hr i (hnonroot (.inl i) hi) + · intro j hj + simpa only [columnDifference,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero] + using hc j (hnonroot (.inr j) hj) + have hother : ∀ a : I×J, a≠(i₀,j₀) → f a=0 := by + rintro ⟨i,j⟩ hne + by_cases hij : T.Adj (.inl i) (.inr j) + · have he : rowU i=colU j := side_eq_of_tree_edge T t r hij + (fun h => hne (cell_edge_injective h)) + simp [f,cutTerm,he] + · simp [f,cutTerm,hsupport i j hij] + have hisolate : (∑ a, f a)=f (i₀,j₀) := by + apply Finset.sum_eq_single (i₀,j₀) + · intro a _ hne + exact hother a hne + · simp + rw [hisolate] at hsum + have habs : |f (i₀,j₀)|=|z i₀ j₀| := by + simp only [f,cutTerm,Bool.false_eq_true,ite_false,Pi.zero_apply,sub_zero, + abs_mul,abs_indicator_sub hcross',one_mul] + rw [hsum,abs_zero] at habs + exact abs_eq_zero.mp habs.symm + · exact hsupport i₀ j₀ ht + +/-- The explicit integral root-path solution has no hidden multiplicity: +every integral table supported on the tree and satisfying its nonroot +margin equations equals that solution. -/ +theorem tableCompletion_unique (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (hT : T.IsAcyclic) + (r : I → ℤ) (c : J → ℤ) (z : I → J → ℤ) + (hsupport : ∀ i j, ¬T.Adj (.inl i) (.inr j) → z i j=0) + (hr : ∀ i, Sum.inl i≠componentRoot T (.inl i) → (∑ j, z i j)=r i) + (hc : ∀ j, Sum.inr j≠componentRoot T (.inr j) → (∑ i, z i j)=c j) : + z=tableCompletion T r c := by + let δ : I → J → ℝ := fun i j => (z i j:ℝ)-tableCompletion T r c i j + have hz := zero_of_nonroot_sums T hT δ (by + intro i j hij + simp only [δ,hsupport i j hij,Int.cast_zero,tableCompletion_supported T r c i j hij,sub_self]) + (by + intro i hi + have h := tableCompletion_row small T hTG r c i hi + dsimp [δ] + rw [Finset.sum_sub_distrib,← Int.cast_sum,← Int.cast_sum,hr i hi,h,sub_self]) + (by + intro j hj + have h := tableCompletion_column small T hTG r c j hj + dsimp [δ] + rw [Finset.sum_sub_distrib,← Int.cast_sum,← Int.cast_sum,hc j hj,h,sub_self]) + funext i j + have he : (z i j:ℝ)=(tableCompletion T r c i j:ℝ) := sub_eq_zero.mp (hz i j) + exact_mod_cast he + +theorem exists_unique_integral_completion (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hTG : T≤cellGraph small) (hT : T.IsAcyclic) (r : I → ℤ) (c : J → ℤ) : + ∃! z : I → J → ℤ, + (∀ i j, ¬T.Adj (.inl i) (.inr j) → z i j=0) ∧ + (∀ i, Sum.inl i≠componentRoot T (.inl i) → (∑ j, z i j)=r i) ∧ + (∀ j, Sum.inr j≠componentRoot T (.inr j) → (∑ i, z i j)=c j) := by + refine ⟨tableCompletion T r c, + ⟨tableCompletion_supported T r c,tableCompletion_row small T hTG r c, + tableCompletion_column small T hTG r c⟩,?_⟩ + intro z hz + exact tableCompletion_unique small T hTG hT r c z hz.1 hz.2.1 hz.2.2 + +end ContingencyTables.GraphCompletionUnique + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphIntegralCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphIntegralCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa8c3b790dc4a91d37f79399d8a94886ef1032cb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/GraphIntegralCompletion.lean @@ -0,0 +1,208 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestCapacity + +namespace OAI + +/-! +# Integral completion of actual graph incidence equations + +Integral root-path flows give an explicit solution of every nonroot +incidence equation. This works directly on the finite row/column graph, +including disconnected components and singleton components. +-/ + +namespace ContingencyTables.GraphIntegralCompletion + +open scoped BigOperators Classical +open SimpleGraph + +variable {V : Type*} [Fintype V] + +omit [Fintype V] in +noncomputable def edgeFlow (u v a b : V) : ℤ := + (if u=a ∧ v=b then 1 else 0)-(if u=b ∧ v=a then 1 else 0) + +omit [Fintype V] in +lemma edgeFlow_skew (u v a b : V) : edgeFlow u v a b= -edgeFlow u v b a := by + unfold edgeFlow + ring + +omit [Fintype V] in +lemma edgeFlow_nonadj (G : SimpleGraph V) {u v a b : V} + (h : G.Adj u v) (hab : ¬G.Adj a b) : edgeFlow u v a b=0 := by + have hf : ¬(u=a ∧ v=b) := by rintro ⟨rfl,rfl⟩; exact hab h + have hr : ¬(u=b ∧ v=a) := by rintro ⟨rfl,rfl⟩; exact hab h.symm + simp only [edgeFlow,hf,hr,ite_false,sub_self] + +lemma edgeFlow_sum (u v a : V) : + (∑ b, edgeFlow u v a b)=(if u=a then (1:ℤ) else 0)-(if v=a then 1 else 0) := by + simp [edgeFlow,Finset.sum_sub_distrib,ite_and] + +omit [Fintype V] in +noncomputable def walkFlow {G : SimpleGraph V} {u v : V} (p : G.Walk u v) (a b : V) : ℤ := + (p.darts.map (fun d => edgeFlow d.fst d.snd a b)).sum + +omit [Fintype V] in +@[simp] lemma walkFlow_nil (G : SimpleGraph V) (u a b : V) : + walkFlow (Walk.nil : G.Walk u u) a b=0 := rfl + +omit [Fintype V] in +lemma walkFlow_cons {G : SimpleGraph V} {u v w : V} (h : G.Adj u v) + (p : G.Walk v w) (a b : V) : + walkFlow (Walk.cons h p) a b=edgeFlow u v a b+walkFlow p a b := by + simp only [walkFlow,Walk.darts_cons,List.map_cons,List.sum_cons] + +omit [Fintype V] in +lemma walkFlow_skew {G : SimpleGraph V} {u v : V} (p : G.Walk u v) (a b : V) : + walkFlow p a b= -walkFlow p b a := by + induction p with + | nil => simp only [walkFlow_nil,neg_zero] + | cons h p ih => rw [walkFlow_cons,walkFlow_cons,edgeFlow_skew,ih]; ring + +omit [Fintype V] in +lemma walkFlow_supported {G : SimpleGraph V} {u v : V} (p : G.Walk u v) + (a b : V) (hab : ¬G.Adj a b) : walkFlow p a b=0 := by + induction p with + | nil => rfl + | cons h p ih => rw [walkFlow_cons,edgeFlow_nonadj G h hab,ih,zero_add] + +lemma walkFlow_sum {G : SimpleGraph V} {u v : V} (p : G.Walk u v) (a : V) : + (∑ b, walkFlow p a b)=(if u=a then (1:ℤ) else 0)-(if v=a then 1 else 0) := by + induction p with + | nil => simp + | cons h p ih => + simp_rw [walkFlow_cons] + rw [Finset.sum_add_distrib,edgeFlow_sum,ih] + ring + +omit [Fintype V] in +noncomputable def componentRoot (G : SimpleGraph V) (v : V) : V := + Classical.choose (G.connectedComponentMk v).exists_rep + +omit [Fintype V] in +lemma componentRoot_component (G : SimpleGraph V) (v : V) : + G.connectedComponentMk (componentRoot G v)=G.connectedComponentMk v := + Classical.choose_spec (G.connectedComponentMk v).exists_rep + +omit [Fintype V] in +lemma componentRoot_reachable (G : SimpleGraph V) (v : V) : + G.Reachable v (componentRoot G v) := + ConnectedComponent.exact (componentRoot_component G v).symm + +omit [Fintype V] in +lemma componentRoot_constant (G : SimpleGraph V) {u v : V} (h : G.Reachable u v) : + componentRoot G u=componentRoot G v := by + exact congrArg (fun C : G.ConnectedComponent => Classical.choose C.exists_rep) + (ConnectedComponent.sound h) + +omit [Fintype V] in +lemma componentRoot_idempotent (G : SimpleGraph V) (v : V) : + componentRoot G (componentRoot G v)=componentRoot G v := + (componentRoot_constant G (componentRoot_reachable G v)).symm + +omit [Fintype V] in +noncomputable def rootPath (G : SimpleGraph V) (v : V) : G.Walk v (componentRoot G v) := + Classical.choice (componentRoot_reachable G v) + +noncomputable def completionFlow (G : SimpleGraph V) (r : V → ℤ) (a b : V) : ℤ := + ∑ v, r v*walkFlow (rootPath G v) a b + +lemma completionFlow_skew (G : SimpleGraph V) (r : V → ℤ) (a b : V) : + completionFlow G r a b= -completionFlow G r b a := by + unfold completionFlow + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro v _ + rw [walkFlow_skew,mul_neg] + +lemma completionFlow_supported (G : SimpleGraph V) (r : V → ℤ) + (a b : V) (hab : ¬G.Adj a b) : completionFlow G r a b=0 := by + unfold completionFlow + apply Finset.sum_eq_zero + intro v _ + rw [walkFlow_supported _ a b hab,mul_zero] + +/-- Every prescribed integral nonroot divergence is satisfied exactly. +The chosen roots are the only vertices where a discrepancy can remain. -/ +theorem completionFlow_divergence (G : SimpleGraph V) (r : V → ℤ) + (a : V) (ha : a≠componentRoot G a) : (∑ b, completionFlow G r a b)=r a := by + have hroot : ∀ v, componentRoot G v≠a := by + intro v hv + have h := componentRoot_idempotent G v + rw [hv] at h + exact ha h.symm + unfold completionFlow + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum,walkFlow_sum,mul_sub,Finset.sum_sub_distrib] + simp [hroot,eq_comm] + +variable {I J : Type*} [Fintype I] [Fintype J] + +omit [Fintype V] [Fintype I] [Fintype J] in +noncomputable def tableFlow (z : I → J → ℤ) : I⊕J → I⊕J → ℤ + | .inl i,.inr j => z i j + | .inr j,.inl i => -z i j + | _,_ => 0 + +omit [Fintype V] [Fintype I] [Fintype J] in +lemma tableFlow_skew (z : I → J → ℤ) (a b : I⊕J) : + tableFlow z a b= -tableFlow z b a := by + cases a <;> cases b <;> simp [tableFlow] + +omit [Fintype V] in +lemma tableFlow_row (z : I → J → ℤ) (i : I) : + (∑ v, tableFlow z (.inl i) v)=∑ j, z i j := by + simp [Fintype.sum_sum_type,tableFlow] + +omit [Fintype V] in +lemma tableFlow_column (z : I → J → ℤ) (j : J) : + (∑ v, tableFlow z (.inr j) v)= -(∑ i, z i j) := by + simp [Fintype.sum_sum_type,tableFlow,Finset.sum_neg_distrib] + +omit [Fintype V] in +noncomputable def tableCompletion (T : SimpleGraph (I⊕J)) (r : I → ℤ) (c : J → ℤ) + (i : I) (j : J) : ℤ := + completionFlow T (Sum.elim r (fun j => -c j)) (.inl i) (.inr j) + +omit [Fintype V] in +lemma tableCompletion_supported (T : SimpleGraph (I⊕J)) (r : I → ℤ) (c : J → ℤ) + (i : I) (j : J) (h : ¬T.Adj (.inl i) (.inr j)) : tableCompletion T r c i j=0 := + completionFlow_supported T _ _ _ h + +omit [Fintype V] in +lemma tableCompletion_row (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) (i : I) + (hi : Sum.inl i≠componentRoot T (.inl i)) : (∑ j, tableCompletion T r c i j)=r i := by + have hs := completionFlow_divergence T (Sum.elim r (fun j => -c j)) (.inl i) hi + rw [Fintype.sum_sum_type] at hs + have hzero : (∑ i', completionFlow T (Sum.elim r (fun j => -c j)) (.inl i) (.inl i'))=0 := by + apply Finset.sum_eq_zero + intro i' _ + apply completionFlow_supported + intro h + exact hT h + simpa only [hzero,zero_add,Sum.elim_inl,tableCompletion] using hs + +omit [Fintype V] in +lemma tableCompletion_column (small : I → J → Bool) (T : SimpleGraph (I⊕J)) + (hT : T≤ForestCapacity.cellGraph small) (r : I → ℤ) (c : J → ℤ) (j : J) + (hj : Sum.inr j≠componentRoot T (.inr j)) : (∑ i, tableCompletion T r c i j)=c j := by + have hs := completionFlow_divergence T (Sum.elim r (fun j => -c j)) (.inr j) hj + rw [Fintype.sum_sum_type] at hs + have hzero : (∑ j', completionFlow T (Sum.elim r (fun j => -c j)) (.inr j) (.inr j'))=0 := by + apply Finset.sum_eq_zero + intro j' _ + apply completionFlow_supported + intro h + exact hT h + have hskew : (∑ i, completionFlow T (Sum.elim r (fun j => -c j)) (.inr j) (.inl i))= + -(∑ i, tableCompletion T r c i j) := by + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + exact completionFlow_skew T _ _ _ + simp only [hzero,add_zero,Sum.elim_inr,hskew,neg_inj] at hs + exact hs + +end ContingencyTables.GraphIntegralCompletion + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/HardZeroTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/HardZeroTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..4599181764cb7380512c59cb51b27b1d6743bc5f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/HardZeroTransport.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RecursiveSignedTransport + +namespace OAI + +/-! +# Finite softened-weight transport limits + +The explicit root coefficient has only the two endpoint masses in its +weight-dependent denominators. All puncture masses and edge energies are +finite sums of continuous functions of weights. Thus the actual proved +one-hole transport survives zero internal weights when the two limiting +endpoint masses are positive. +-/ + +namespace ContingencyTables.HardZeroTransport + +open scoped BigOperators Classical Matrix Topology +open CommonBasesFPRAS BinaryContraction RecursiveSignedTransport +open Filter + +variable {Γ K : Type*} [Fintype Γ] [DecidableEq Γ] {l : Filter K} + +omit [DecidableEq Γ] in +lemma coeffDerivs_tendsto (as : List (Γ → ℝ)) (F : K → Set Γ → ℝ) (f : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) (A : Set Γ) : + Tendsto (fun t => coeffDerivs as (F t) A) l (nhds (coeffDerivs as f A)) := by + induction as generalizing A with + | nil => exact hlim A + | cons a as ih => + change Tendsto (fun t => ∑ i, if i ∈ A then 0 else a i*coeffDerivs as (F t) (insert i A)) l _ + apply tendsto_finsetSum + intro i _ + by_cases hi : i ∈ A + · simpa only [hi,ite_true] using (tendsto_const_nhds : Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + · simpa only [hi,ite_false] using (tendsto_const_nhds.mul (ih (insert i A))) + +lemma slotTotal_tendsto (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) (A : Set Γ) : + Tendsto (fun t => slotTotal ps (F t) A) l (nhds (slotTotal ps f A)) := + coeffDerivs_tendsto (ps.map pairDirection) F f hlim A + +lemma slotTotal_weighted_tendsto (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f H : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) (A : Set Γ) : + Tendsto (fun t => slotTotal ps (fun S => F t S*H S) A) l + (nhds (slotTotal ps (fun S => f S*H S) A)) := + slotTotal_tendsto ps _ _ (fun S => (hlim S).mul_const (H S)) A + +private lemma list_sum_tendsto {A : Type*} (xs : List A) (u : K → A → ℝ) (v : A → ℝ) + (hu : ∀ a, Tendsto (fun t => u t a) l (nhds (v a))) : + Tendsto (fun t => (xs.map (u t)).sum) l (nhds ((xs.map v).sum)) := by + induction xs with + | nil => simpa using (tendsto_const_nhds : Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + | cons a xs ih => simpa only [List.map_cons,List.sum_cons] using (hu a).add ih + +lemma rootCoefficient_tendsto (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hsp : slotTotal ps f (insert p A) ≠ 0) (hsd : slotTotal ps f (insert d A) ≠ 0) + (hW : ∀ i, W i ≠ 0) : + Tendsto (fun t => rootCoefficient ps (F t) A p d W) l (nhds (rootCoefficient ps f A p d W)) := by + have hp := slotTotal_tendsto ps F f hlim (insert p A) + have hd := slotTotal_tendsto ps F f hlim (insert d A) + have hs := list_sum_tendsto (slotPunctures ps) + (fun t x => slotTotal x.2 (F t) (insert p (insert d A))/W x.1.1) + (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1) + (fun x => (slotTotal_tendsto x.2 F f hlim _).div_const _) + unfold rootCoefficient + exact ((tendsto_const_nhds.div (hp.mul_const (W p)) (mul_ne_zero hsp (hW p))).add + (tendsto_const_nhds.div (hd.mul_const (W d)) (mul_ne_zero hsd (hW d)))).add + ((tendsto_const_nhds.div (hp.mul hd) (mul_ne_zero hsp hsd)).mul hs) + +omit [Fintype Γ] [DecidableEq Γ] in +lemma slotGraphEnergy_tendsto {I : Type*} [Fintype I] + (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f H : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) + (A : Set Γ) (e : I → Γ) (W : Γ → ℝ) : + Tendsto (fun t => slotGraphEnergy ps (F t) H A e W) l (nhds (slotGraphEnergy ps f H A e W)) := by + unfold slotGraphEnergy + apply Tendsto.div_const + apply tendsto_finsetSum + intro ST _ + unfold slotEdgeEnergy + exact (((hlim ST.1).const_mul _).min ((hlim ST.2).const_mul _)).mul_const _ + +/-- The original finite transport inequality at nonnegative limiting +weights. Only the two actual endpoint masses need to stay positive. -/ +theorem transport_graph_bound_degree_limit + [l.NeBot] + (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f H : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (k : ℕ) + (hsoft : ∀ᶠ t in l, DegreePositive (F t) k ∧ AdditionProperty (F t) k) + (hdegree : A.ncard+ps.length+1=k) (hpd : p≠d) (hpA : p∉A) (hdA : d∉A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p∈ps, W p.1=W p.2) + (hsp : 0 < slotTotal ps f (insert p A)) (hsd : 0 < slotTotal ps f (insert d A)) : + (slotTotal ps (fun S => f S*H S) (insert p A)/slotTotal ps f (insert p A) - + slotTotal ps (fun S => f S*H S) (insert d A)/slotTotal ps f (insert d A))^2 ≤ + rootCoefficient ps f A p d W * slotGraphEnergy ps f H A (rootEmbedding p d) W := by + have hp := slotTotal_tendsto ps F f hlim (insert p A) + have hd := slotTotal_tendsto ps F f hlim (insert d A) + have hpn := slotTotal_weighted_tendsto ps F f H hlim (insert p A) + have hdn := slotTotal_weighted_tendsto ps F f H hlim (insert d A) + have hc := rootCoefficient_tendsto ps F f hlim A p d W (ne_of_gt hsp) (ne_of_gt hsd) + (fun i => ne_of_gt (hW i)) + have he := slotGraphEnergy_tendsto ps F f H hlim A (rootEmbedding p d) W + apply le_of_tendsto_of_tendsto (((hpn.div hp (ne_of_gt hsp)).sub (hdn.div hd (ne_of_gt hsd))).pow 2) (hc.mul he) + filter_upwards [hsoft] with t ht + exact transport_graph_bound_degree ps (F t) H A p d W k ht.1 ht.2 hdegree + hpd hpA hdA hps hW hw + +/-- Hard-zero transport in the manuscript's original omission convention, +obtained from the actual positive softened lifts and finite limits. -/ +theorem one_hole_transport_limit + [l.NeBot] + (ps : List (Γ × Γ)) (F : K → Set Γ → ℝ) (f H : Set Γ → ℝ) + (hlim : ∀ S, Tendsto (fun t => F t S) l (nhds (f S))) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (k : ℕ) (hk : k ≤ Fintype.card Γ) + (hsoft : ∀ᶠ t in l, DegreePositive (F t) k ∧ OmissionProperty (F t) k) + (hdegree : A.ncard+ps.length+1=Fintype.card Γ-k) + (hpd : p≠d) (hpA : p∉A) (hdA : d∉A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p∈ps, W p.1=W p.2) + (hsp : 0 < slotTotal ps (complementWeight f) (insert p A)) + (hsd : 0 < slotTotal ps (complementWeight f) (insert d A)) : + let fc := complementWeight f + let Hc := complementWeight H + (slotTotal ps (fun S => fc S*Hc S) (insert p A)/slotTotal ps fc (insert p A) - + slotTotal ps (fun S => fc S*Hc S) (insert d A)/slotTotal ps fc (insert d A))^2 ≤ + rootCoefficient ps fc A p d W * slotGraphEnergy ps fc Hc A (rootEmbedding p d) W := by + apply transport_graph_bound_degree_limit ps (fun t => complementWeight (F t)) + (complementWeight f) (complementWeight H) (fun S => hlim Sᶜ) A p d W (Fintype.card Γ-k) + · filter_upwards [hsoft] with t ht + exact ⟨complement_degreePositive (F t) k hk ht.1,ht.2⟩ + · exact hdegree + · exact hpd + · exact hpA + · exact hdA + · exact hps + · exact hW + · exact hw + · exact hsp + · exact hsd + +end ContingencyTables.HardZeroTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IndexedTableLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IndexedTableLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..21078fa0d056162d8fef1e1fad761baeb89f297b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IndexedTableLaw.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoxCompletion +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw + +namespace OAI + +/-! # Embedding accepted-table laws into the computed completion list -/ + +namespace ContingencyTables.IndexedTableLaw +open scoped BigOperators Classical +noncomputable section +variable {m n N Q : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + +abbrev Index (m n N : ℕ) := Fin ((N+1)^(m*n)) + +def index (hN : (∑ i,R i)≤N) (X : Table R P) : Index m n N := + finFunctionFinEquiv (BoxCompletion.encode R P hN X) + +def tableAt (htotal : ∑ i,R i=∑ j,P j) (k : Index m n N) : Option (Table R P) := + BoxCompletion.decode R P htotal N (finFunctionFinEquiv.symm k) + +lemma tableAt_eq_some (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (k : Index m n N) (X : Table R P) : + tableAt R P htotal k=some X ↔ index R P hN X=k := by + rw [tableAt,BoxCompletion.decode_eq_some R P htotal hN] + constructor + · intro h + have he := congrArg finFunctionFinEquiv h + simpa only [Equiv.apply_symm_apply,index] using he.symm + · intro h + rw [←h,index,Equiv.symm_apply_apply] + +lemma tableAt_index (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (X : Table R P) : tableAt R P htotal (index R P hN X)=some X := + (tableAt_eq_some R P htotal hN _ X).mpr rfl + +lemma index_eq_iff (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (X Y : Table R P) : index R P hN X=index R P hN Y ↔ X=Y := by + constructor + · intro h + have he := congrArg (tableAt R P htotal) h + rw [tableAt_index,tableAt_index] at he + exact Option.some.inj he + · rintro rfl + rfl + +def law (hN : (∑ i,R i)≤N) (p : IntegerLaw (Option (Table R P)) Q) : + IntegerLaw (Option (Index m n N)) Q := + p.push (Option.map (index R P hN)) + +lemma count_none (hN : (∑ i,R i)≤N) (p : IntegerLaw (Option (Table R P)) Q) : + (law R P hN p).count none=p.count none := by + simp [law,IntegerLaw.push,Fintype.sum_option] + +/-- Invalid completions have zero count; every valid completion has +exactly the count of its unique feasible table. -/ +lemma count_some (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (p : IntegerLaw (Option (Table R P)) Q) (k : Index m n N) : + (law R P hN p).count (some k)= + (tableAt R P htotal k).elim 0 (fun X => p.count (some X)) := by + simp only [law,IntegerLaw.push,Fintype.sum_option,Option.map_none,reduceCtorEq, + ite_false,zero_add,Option.map_some,Option.some.injEq] + simp_rw [←tableAt_eq_some R P htotal hN] + cases tableAt R P htotal k <;> simp + +lemma count_index (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (p : IntegerLaw (Option (Table R P)) Q) (X : Table R P) : + (law R P hN p).count (some (index R P hN X))=p.count (some X) := by + rw [count_some R P htotal,tableAt_index] + rfl + +/-- Embedding tables into the explicit finite candidate list commutes +with every bounded first-success retry. -/ +theorem retry_count_index (htotal : ∑ i,R i=∑ j,P j) (hN : (∑ i,R i)≤N) + (p : IntegerLaw (Option (Table R P)) Q) (fallback X : Table R P) (J : ℕ) : + ((law R P hN p).retry (index R P hN fallback) J).count (index R P hN X)= + (p.retry fallback J).count X := by + change IntegerLaw.retryCount (law R P hN p) (index R P hN fallback) J (index R P hN X)= + IntegerLaw.retryCount p fallback J X + induction J with + | zero => simp only [IntegerLaw.retryCount,index_eq_iff R P htotal] + | succ J ih => + rw [IntegerLaw.retryCount,IntegerLaw.retryCount,count_index R P htotal,count_none,ih] + +end +end ContingencyTables.IndexedTableLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialDefectChoices.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialDefectChoices.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e7622628c9a513b542a7051711a823e46dbe64b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialDefectChoices.lean @@ -0,0 +1,278 @@ +import OAI.Combinatorics.ContingencyTables.Transport.InitialTransversals + +namespace OAI + +/-! +# Actual remaining label choices for an initial defect + +The hole and full pair are removed before the remaining row labels are +chosen. This gives the finite combinatorial space underlying the exact +local initialization brackets, including two removed labels in one cell. +-/ + +namespace ContingencyTables.InitialDefectChoices + +open scoped BigOperators Classical +open CommonBasesFPRAS TwoLiftStates +open InitialTransversals (Copy) + +variable {C : Type*} [Fintype C] (b : C → ℕ) (p q : Copy b) + +@[reducible] def Local (c : C) := + {k : Fin (b c) // (⟨c,k⟩:Copy b)≠p ∧ (⟨c,k⟩:Copy b)≠q} + +noncomputable def encode (S : (c : C) → Finset (Local b p q c)) : Set (Copy b×Bool) := + fun a => if a.1=q then True else if h : a.1≠p ∧ a.1≠q then + if a.2 then (⟨a.1.2,h⟩:Local b p q a.1.1)∉S a.1.1 + else (⟨a.1.2,h⟩:Local b p q a.1.1)∈S a.1.1 + else False + +omit [Fintype C] in +lemma encode_full (S : (c : C) → Finset (Local b p q c)) (t : Bool) : + (q,t)∈encode b p q S := by + change (if q=q then True else _) + simp + +omit [Fintype C] in +lemma encode_hole (hpq : p≠q) (S : (c : C) → Finset (Local b p q c)) (t : Bool) : + (p,t)∉encode b p q S := by + change ¬(if p=q then True else if h : p≠p ∧ p≠q then _ else False) + simp [hpq] + +omit [Fintype C] in +lemma encode_false (S : (c : C) → Finset (Local b p q c)) (a : Copy b) + (ha : a≠p ∧ a≠q) : + (a,false)∈encode b p q S ↔ (⟨a.2,ha⟩:Local b p q a.1)∈S a.1 := by + change (if a=q then True else if h : a≠p ∧ a≠q then _ else False)↔_ + simp [ha] + +omit [Fintype C] in +lemma encode_true (S : (c : C) → Finset (Local b p q c)) (a : Copy b) + (ha : a≠p ∧ a≠q) : + (a,true)∈encode b p q S ↔ (⟨a.2,ha⟩:Local b p q a.1)∉S a.1 := by + change (if a=q then True else if h : a≠p ∧ a≠q then _ else False)↔_ + simp [ha] + +lemma encode_defect (hpq : p≠q) (S : (c : C) → Finset (Local b p q c)) : + DefectState pairs (TwoLiftStates.pair p) (TwoLiftStates.pair q) (encode b p q S) := by + refine ⟨pair_mem p,pair_mem q,(fun h => hpq (pair_injective h)),?_,?_,?_⟩ + · exact ⟨encode_hole b p q hpq S false,encode_hole b p q hpq S true⟩ + · exact ⟨encode_full b p q S false,encode_full b p q S true⟩ + · intro t ht htp htq + obtain ⟨a,_,rfl⟩ := List.mem_map.mp (show t∈Finset.univ.toList.map TwoLiftStates.pair from ht) + have ha : a≠p ∧ a≠q := ⟨fun h => htp (congrArg TwoLiftStates.pair h), + fun h => htq (congrArg TwoLiftStates.pair h)⟩ + by_cases hs : (⟨a.2,ha⟩:Local b p q a.1)∈S a.1 + · exact Or.inl ⟨(encode_false b p q S a ha).mpr hs, + fun h => (encode_true b p q S a ha).mp h hs⟩ + · exact Or.inr ⟨(encode_true b p q S a ha).mpr hs, + fun h => hs ((encode_false b p q S a ha).mp h)⟩ + +noncomputable def defectEquivChoices (hpq : p≠q) : + {S : Set (Copy b×Bool) // DefectState pairs (TwoLiftStates.pair p) (TwoLiftStates.pair q) S} ≃ + ((c : C) → Finset (Local b p q c)) where + toFun S c := Finset.univ.filter (fun k => ((⟨c,k.val⟩,false):Copy b×Bool)∈S.val) + invFun S := ⟨encode b p q S,encode_defect b p q hpq S⟩ + left_inv S := by + apply Subtype.ext + ext ⟨a,t⟩ + let R : (c : C) → Finset (Local b p q c) := + fun c => Finset.univ.filter (fun k => ((⟨c,k.val⟩,false):Copy b×Bool)∈S.val) + change (a,t)∈encode b p q R ↔ (a,t)∈S.val + by_cases hap : a=p + · subst a + have he := S.property.2.2.2.1 + cases t <;> simp only [TwoLiftStates.pair,PairEmpty] at he + · exact iff_of_false (encode_hole b p q hpq R false) he.1 + · exact iff_of_false (encode_hole b p q hpq R true) he.2 + · by_cases haq : a=q + · subst a + have hf := S.property.2.2.2.2.1 + cases t <;> simp only [TwoLiftStates.pair,PairFull] at hf + · exact iff_of_true (encode_full b p q R false) hf.1 + · exact iff_of_true (encode_full b p q R true) hf.2 + · have ha : a≠p ∧ a≠q := ⟨hap,haq⟩ + have hs := S.property.2.2.2.2.2 (TwoLiftStates.pair a) (pair_mem a) + (fun h => hap (pair_injective h)) (fun h => haq (pair_injective h)) + cases t + · rw [encode_false b p q R a ha] + simp [R] + · rw [encode_true b p q R a ha] + dsimp only [R] + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + rcases hs with ⟨hf,ht⟩|⟨ht,hf⟩ <;> + simp only [TwoLiftStates.pair] at hf ht <;> tauto + right_inv S := by + funext c + ext k + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + exact encode_false b p q S ⟨c,k.val⟩ k.property + +omit [Fintype C] in +lemma fiber_eq_sum (c : C) (a : Copy b) : + (∑ k : Fin (b c), if (⟨c,k⟩:Copy b)=a then (1:ℕ) else 0)= + if a.1=c then 1 else 0 := by + rcases a with ⟨a,k⟩ + by_cases ha : a=c + · subst a + simp + · have hn (k' : Fin (b c)) : (⟨c,k'⟩:Copy b)≠⟨a,k⟩ := + fun h => ha (congrArg Sigma.fst h).symm + simp [ha,hn] + +omit [Fintype C] in +/-- There are exactly b-u-v remaining labels in each cell. This proof +uses distinct physical labels, so the coinciding-cell case is included. -/ +theorem local_card_balance (hpq : p≠q) (c : C) : + Fintype.card (Local b p q c)+(if p.1=c then 1 else 0)+(if q.1=c then 1 else 0)=b c := by + have ht (k : Fin (b c)) : + (if (⟨c,k⟩:Copy b)≠p ∧ (⟨c,k⟩:Copy b)≠q then (1:ℕ) else 0)+ + (if (⟨c,k⟩:Copy b)=p then 1 else 0)+ + (if (⟨c,k⟩:Copy b)=q then 1 else 0)=1 := by + by_cases hp : (⟨c,k⟩:Copy b)=p + · have hq : (⟨c,k⟩:Copy b)≠q := fun h => hpq (hp.symm.trans h) + simp [hp,hpq] + · by_cases hq : (⟨c,k⟩:Copy b)=q <;> simp [hp,hq,Ne.symm hpq] + have hs := Finset.sum_congr (s₁ := Finset.univ) rfl (fun k _ => ht k) + rw [Finset.sum_add_distrib,Finset.sum_add_distrib,fiber_eq_sum,fiber_eq_sum] at hs + have he : (∑ k : Fin (b c), if (⟨c,k⟩:Copy b)≠p ∧ (⟨c,k⟩:Copy b)≠q then (1:ℕ) else 0)= + Fintype.card (Local b p q c) := by + rw [Fintype.card_subtype] + simp + rw [he] at hs + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,smul_eq_mul,mul_one] at hs + exact hs + +omit [Fintype C] in +lemma local_card (hpq : p≠q) (c : C) : + Fintype.card (Local b p q c)=b c-(if p.1=c then 1 else 0)-(if q.1=c then 1 else 0) := by + have h := local_card_balance b p q hpq c + omega + +noncomputable def chosen (S : (c : C) → Finset (Local b p q c)) (c : C) : Finset (Fin (b c)) := + (S c).map ⟨Subtype.val,Subtype.val_injective⟩ + +omit [Fintype C] in +lemma chosen_ne (S : (c : C) → Finset (Local b p q c)) (c : C) (k : Fin (b c)) + (hk : k∈chosen b p q S c) : (⟨c,k⟩:Copy b)≠p ∧ (⟨c,k⟩:Copy b)≠q := by + obtain ⟨a,ha,rfl⟩ := Finset.mem_map.mp hk + exact a.property + +omit [Fintype C] in +lemma encode_row (S : (c : C) → Finset (Local b p q c)) (a : Copy b) : + (a,false)∈encode b p q S ↔ a=q ∨ a.2∈chosen b p q S a.1 := by + by_cases haq : a=q + · exact iff_of_true (haq ▸ encode_full b p q S false) (Or.inl haq) + · by_cases hap : a=p + · subst a + have hn : p.2∉chosen b p q S p.1 := fun h => (chosen_ne b p q S _ _ h).1 rfl + exact iff_of_false (encode_hole b p q haq S false) (by simp [haq,hn]) + · rw [encode_false b p q S a ⟨hap,haq⟩] + simp only [haq,false_or,chosen,Finset.mem_map] + constructor + · intro h + exact ⟨⟨a.2,hap,haq⟩,h,rfl⟩ + · rintro ⟨k,hk,he⟩ + have he' : k=⟨a.2,hap,haq⟩ := Subtype.ext he + rwa [he'] at hk + +lemma row_count (_hpq : p≠q) (S : (c : C) → Finset (Local b p q c)) (c : C) : + viewCount (InitialTransversals.cell b) (encode b p q S) c false= + (S c).card+(if q.1=c then 1 else 0) := by + unfold viewCount + rw [Fintype.sum_sigma] + have hi (x : C) : + (∑ k : Fin (b x), if InitialTransversals.cell b ⟨x,k⟩=c ∧ + ((⟨x,k⟩,false):Copy b×Bool)∈encode b p q S then (1:ℕ) else 0)= + if x=c then (S c).card+(if q.1=c then 1 else 0) else 0 := by + by_cases hx : x=c + · subst x + simp only [InitialTransversals.cell,true_and,encode_row] + have he (k : Fin (b c)) : + (if (⟨c,k⟩:Copy b)=q ∨ k∈chosen b p q S c then (1:ℕ) else 0)= + (if k∈chosen b p q S c then 1 else 0)+(if (⟨c,k⟩:Copy b)=q then 1 else 0) := by + by_cases hq : (⟨c,k⟩:Copy b)=q + · have hn : k∉chosen b p q S c := fun h => (chosen_ne b p q S c k h).2 hq + simp [hq,hn] + · by_cases hk : k∈chosen b p q S c <;> simp [hq,hk] + simp_rw [he] + rw [Finset.sum_add_distrib,fiber_eq_sum] + simp only [Finset.sum_boole,Finset.filter_mem_eq_inter,Finset.univ_inter] + rw [chosen,Finset.card_map] + simp + · simp [hx] + calc + _ = ∑ x : C, if x=c then (S c).card+(if q.1=c then 1 else 0) else 0 := + Finset.sum_congr rfl (fun x _ => hi x) + _ = _ := by simp + +lemma column_count (hpq : p≠q) (S : (c : C) → Finset (Local b p q c)) (c : C) : + viewCount (InitialTransversals.cell b) (encode b p q S) c true= + Fintype.card (Local b p q c)-(S c).card+(if q.1=c then 1 else 0) := by + have h := defect_counts (InitialTransversals.cell b) (encode b p q S) p q + (encode_defect b p q hpq S) c + rw [row_count b p q hpq,InitialTransversals.width_cell] at h + have hc := local_card_balance b p q hpq c + have hS := Finset.card_le_univ (S c) + simp only [InitialTransversals.cell] at h + omega + +noncomputable def localWeight (c : C) (S : Finset (Local b p q c)) : ℝ := + (((S.card+(if q.1=c then 1 else 0)).factorial:ℝ)* + ((Fintype.card (Local b p q c)-S.card+(if q.1=c then 1 else 0)).factorial:ℝ))/(b c).factorial + +omit [Fintype C] in +lemma sum_localWeight (hpq : p≠q) (c : C) : + (∑ S : Finset (Local b p q c),localWeight b p q c S)= + InitializationBrackets.bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0) := by + have h := Finset.sum_powerset_apply_card + (fun k => (((k+(if q.1=c then 1 else 0)).factorial:ℝ)* + ((Fintype.card (Local b p q c)-k+(if q.1=c then 1 else 0)).factorial:ℝ))/(b c).factorial) + (x := (Finset.univ : Finset (Local b p q c))) + simpa [localWeight,InitializationBrackets.bracket,local_card b p q hpq, + nsmul_eq_mul,Finset.sum_div,mul_div_assoc,mul_assoc] using h + +lemma firstLift_encode (hpq : p≠q) (M : ℝ) (S : (c : C) → Finset (Local b p q c)) : + LabelledFactorial.firstLift (group (InitialTransversals.cell b)) (fun _ => M) + (InitialTransversals.denominator b) (encode b p q S)=M*∏ c,localWeight b p q c (S c) := by + unfold LabelledFactorial.firstLift FactorialSignatures.factorialProduct InitialTransversals.denominator + rw [Fintype.prod_prod_type] + simp only [Fintype.prod_bool,groupCount_eq_viewCount,row_count b p q hpq,column_count b p q hpq] + unfold localWeight + rw [Finset.prod_div_distrib] + have he : (∏ c, ((Fintype.card (Local b p q c)-(S c).card+(if q.1=c then 1 else 0)).factorial:ℝ)* + (((S c).card+(if q.1=c then 1 else 0)).factorial:ℝ))= + ∏ c, (((S c).card+(if q.1=c then 1 else 0)).factorial:ℝ)* + ((Fintype.card (Local b p q c)-(S c).card+(if q.1=c then 1 else 0)).factorial:ℝ) := by + apply Finset.prod_congr rfl + intro c _ + exact mul_comm _ _ + rw [he] + ring + +/-- The source bracket product is the actual finite defect normalizer, +with no assumption about where its missing and full labels lie. -/ +theorem slotDefect_constant (hpq : p≠q) (M : ℝ) : + slotDefect pairs (LabelledFactorial.firstLift (group (InitialTransversals.cell b)) + (fun _ => M) (InitialTransversals.denominator b)) ∅ (TwoLiftStates.pair p) (TwoLiftStates.pair q)= + M*∏ c,InitializationBrackets.bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0) := by + rw [slotDefect_eq_defect_sum pairs PairedLabels.fresh PairedLabels.cover _ + (TwoLiftStates.pair p) (TwoLiftStates.pair q) (pair_mem p) (pair_mem q) + (fun h => hpq (pair_injective h))] + rw [Finset.sum_subtype (p := DefectState pairs (TwoLiftStates.pair p) (TwoLiftStates.pair q)) _ + (by intro S; simp)] + calc + _ = ∑ S : ((c : C) → Finset (Local b p q c)),M*∏ c,localWeight b p q c (S c) := by + apply Fintype.sum_equiv (defectEquivChoices b p q hpq) + intro S + have h := firstLift_encode b p q hpq M ((defectEquivChoices b p q hpq) S) + have he : encode b p q ((defectEquivChoices b p q hpq) S)=S.val := + congrArg Subtype.val ((defectEquivChoices b p q hpq).symm_apply_apply S) + rwa [he] at h + _ = _ := by + rw [← Finset.mul_sum,← Fintype.prod_sum] + simp_rw [sum_localWeight b p q hpq] + +end ContingencyTables.InitialDefectChoices + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialFactorialLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialFactorialLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..edb29b2968c22ab1f7aa1f9907ab4f46bf1a5e13 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialFactorialLaw.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityMixture +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmStart + +namespace OAI + +/-! # Independent initial cell choices give the literal companion law + +The finite rational law is the product of the uniform-size subset laws. +Encoding a choice as its paired transversal yields exactly the initial +law of the companion's factorial lift, with its actual free-completion +normalizer cancelled. +-/ + +namespace ContingencyTables.InitialFactorialLaw + +open CommonBasesFPRAS ResidualMixture FirstSuccess TwoLiftStates LabelledFactorial +open InitialTransversals FixedCardinalityMixture CompanionFactorialApplication +open scoped BigOperators Classical +noncomputable section + +variable {C : Type*} [Fintype C] (b : C → ℕ) + +def choiceLaw : RationalLaw ((c : C) → Finset (Fin (b c))) where + mass S := ∏ c,(localLaw (b c)).mass (S c) + nonnegative S := Finset.prod_nonneg (fun c _ => (localLaw (b c)).nonnegative (S c)) + total := by + rw [←Fintype.prod_sum] + simp only [(localLaw _).total,Finset.prod_const_one] + +theorem choiceLaw_mass_cast (S : (c : C) → Finset (Fin (b c))) : + ((choiceLaw b).mass S:ℝ)= + (∏ c,InitialLocalChoices.localWeight (b c) 0 0 (S c))/(∏ c,((b c:ℝ)+1)) := by + change ((∏ c,(localLaw (b c)).mass (S c):ℚ):ℝ)=_ + rw [Rat.cast_prod] + simp_rw [localLaw_mass_cast] + exact Finset.prod_div_distrib + (fun c : C => InitialLocalChoices.localWeight (b c) 0 0 (S c)) + (fun c : C => (b c:ℝ)+1) + +def plainLaw : RationalLaw {S : Set (Copy b×Bool) // PlainState pairs S} := + equivLaw (plainEquivChoices b).symm (choiceLaw b) + +theorem plainLaw_mass_cast (S : {S : Set (Copy b×Bool) // PlainState pairs S}) : + ((plainLaw b).mass S:ℝ)= + (∏ c,InitialLocalChoices.localWeight (b c) 0 0 ((plainEquivChoices b S) c))/ + (∏ c,((b c:ℝ)+1)) := + choiceLaw_mass_cast b (plainEquivChoices b S) + +theorem plainLaw_lift (M : ℝ) (hM : 0 M) (InitialTransversals.denominator b) S.val/ + (M*∏ c,((b c:ℝ)+1)) := by + let choices := plainEquivChoices b S + have he : encode b choices=S.val := + congrArg Subtype.val ((plainEquivChoices b).symm_apply_apply S) + rw [←he,firstLift_encode,plainLaw_mass_cast] + exact (mul_div_mul_left _ _ (ne_of_gt hM)).symm + +variable {I J : Type*} [Fintype I] [Fintype J] + +def companionLaw (A : Instance I J) : + RationalLaw {S : Set (Labels A×Bool) // PlainState pairs S} := + plainLaw (fun s : SmallCell A => A.b s.val.1 s.val.2) + +/-- No abstract initialization hypothesis: the rational product law is +the actual phase-zero law of the given bounded-table instance. -/ +theorem companionLaw_mass (A : Instance I J) + (S : {S : Set (Labels A×Bool) // PlainState pairs S}) : + ((companionLaw A).mass S:ℝ)=CompanionWarmStart.law A 0 S.val := by + have hM : 0 A.b s.val.1 s.val.2) + (CompanionInitialization.freeTotal A) hM S + have hf : f A 0=firstLift (group (labelCell A)) + (fun _ => CompanionInitialization.freeTotal A) + (CompanionFactorialApplication.denominator A) := by + funext T + unfold f firstLift + rw [CompanionInitialization.h_zero] + change ((plainLaw _).mass S:ℝ)=_ + unfold CompanionWarmStart.law CompanionWarmStart.total CompanionAnnealing.weight + simp only [Nat.cast_zero,zero_div] + rw [CompanionInitialization.total_zero,hf,CompanionInitialization.denominator_eq] + exact h + +end +end ContingencyTables.InitialFactorialLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialTransversals.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialTransversals.lean new file mode 100644 index 0000000000000000000000000000000000000000..7af9e4f411a59ea53132aca5fc8ea7781a4a55b4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/InitialTransversals.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PairedLabels +import OAI.Combinatorics.ContingencyTables.Machines.InitialLocalChoices + +namespace OAI + +/-! +# The initial transversal sum is an actual finite row-label choice sum + +For every cell, a choice of row labels gives exactly one paired +transversal. Its factorial weight is the local factorial weight used in +the evaluated initialization brackets. +-/ + +namespace ContingencyTables.InitialTransversals + +open scoped BigOperators Classical +open Nat +open CommonBasesFPRAS TwoLiftStates LabelledFactorial InitialLocalChoices + +variable {C : Type*} [Fintype C] (b : C → ℕ) + +abbrev Copy := Σ c, Fin (b c) + +@[reducible] def cell (p : Copy b) : C := p.1 + +@[reducible] noncomputable def encode (S : (c : C) → Finset (Fin (b c))) : Set (Copy b×Bool) := + fun p => if p.2 then p.1.2∉S p.1.1 else p.1.2∈S p.1.1 + +omit [Fintype C] in +@[simp] lemma encode_false (S : (c : C) → Finset (Fin (b c))) (p : Copy b) : + (p,false)∈encode b S ↔ p.2∈S p.1 := Iff.rfl + +omit [Fintype C] in +@[simp] lemma encode_true (S : (c : C) → Finset (Fin (b c))) (p : Copy b) : + (p,true)∈encode b S ↔ p.2∉S p.1 := Iff.rfl + +lemma encode_plain (S : (c : C) → Finset (Fin (b c))) : PlainState pairs (encode b S) := by + intro p hp + obtain ⟨a,rfl⟩ : ∃ a, TwoLiftStates.pair a=p := by simpa [pairs] using hp + by_cases hs : a.2∈S a.1 + · exact Or.inl (by simp [TwoLiftStates.pair,hs]) + · exact Or.inr (by simp [TwoLiftStates.pair,hs]) + +noncomputable def plainEquivChoices : + {S : Set (Copy b×Bool) // PlainState pairs S} ≃ ((c : C) → Finset (Fin (b c))) where + toFun S c := Finset.univ.filter (fun k => ((⟨c,k⟩,false):Copy b×Bool)∈S.val) + invFun S := ⟨encode b S,encode_plain b S⟩ + left_inv S := by + apply Subtype.ext + ext ⟨⟨c,k⟩,t⟩ + have h := S.property (TwoLiftStates.pair (⟨c,k⟩:Copy b)) (pair_mem (⟨c,k⟩:Copy b)) + cases t + · simp + · simp only [encode_true,Finset.mem_filter,Finset.mem_univ,true_and] + change (¬((⟨c,k⟩,false):Copy b×Bool)∈S.val)↔((⟨c,k⟩,true):Copy b×Bool)∈S.val + rcases h with ⟨ha,hb⟩|⟨ha,hb⟩ <;> simp [TwoLiftStates.pair] at ha hb ⊢ <;> tauto + right_inv S := by + funext c + ext k + simp + +lemma width_cell (c : C) : width (cell b) c=b c := by + rw [width_eq_sum,Fintype.sum_sigma] + have hinner (x : C) : + (∑ k : Fin (b x), if cell b ⟨x,k⟩=c then 1 else 0)= + if x=c then b x else 0 := by + by_cases hx : x=c + · subst x + simp + · simp [hx] + convert (show (∑ x : C, if x=c then b x else 0)=b c by simp) using 1 + apply Finset.sum_congr rfl + intro x _ + exact hinner x + +lemma row_count (S : (c : C) → Finset (Fin (b c))) (c : C) : + viewCount (cell b) (encode b S) c false=(S c).card := by + unfold viewCount + rw [Fintype.sum_sigma] + have hinner (x : C) : + (∑ k : Fin (b x), if cell b ⟨x,k⟩=c ∧ ((⟨x,k⟩,false):Copy b×Bool)∈encode b S then 1 else 0)= + if x=c then (S c).card else 0 := by + by_cases hx : x=c + · subst x + simp only [cell,true_and,encode_false] + simp + · simp [hx] + convert (show (∑ x : C, if x=c then (S c).card else 0)=(S c).card by simp) using 1 + apply Finset.sum_congr rfl + intro x _ + exact hinner x + +lemma column_count (S : (c : C) → Finset (Fin (b c))) (c : C) : + viewCount (cell b) (encode b S) c true=b c-(S c).card := by + have h := plain_counts (cell b) (encode b S) (encode_plain b S) c + rw [row_count,width_cell] at h + omega + +noncomputable def denominator : ℝ := ∏ c, ((b c)!:ℝ) + +lemma firstLift_encode (M : ℝ) (S : (c : C) → Finset (Fin (b c))) : + firstLift (group (cell b)) (fun _ => M) (denominator b) (encode b S)= + M*∏ c, localWeight (b c) 0 0 (S c) := by + unfold firstLift FactorialSignatures.factorialProduct denominator + rw [Fintype.prod_prod_type] + simp only [Fintype.prod_bool,groupCount_eq_viewCount,row_count,column_count] + simp only [localWeight,Nat.sub_zero,Nat.add_zero] + rw [Finset.prod_div_distrib] + have he : (∏ c, ((b c-(S c).card)!:ℝ)*((S c).card !:ℝ))= + ∏ c, ((S c).card !:ℝ)*((b c-(S c).card)!:ℝ) := by + apply Finset.prod_congr rfl + intro c _ + exact mul_comm _ _ + rw [he] + ring + +/-- The actual paired-transversal total at a constant raw completion +count M is exactly the manuscript's M*product(b+1). -/ +theorem slotTotal_constant (M : ℝ) : + slotTotal pairs (firstLift (group (cell b)) (fun _ => M) (denominator b)) ∅= + M*∏ c, ((b c:ℝ)+1) := by + rw [slotTotal_eq_plain_sum pairs PairedLabels.fresh PairedLabels.cover] + rw [Finset.sum_subtype (p := PlainState (pairs : List ((Copy b×Bool)×(Copy b×Bool)))) _ + (by intro S; simp)] + calc + _ = ∑ S : ((c : C) → Finset (Fin (b c))), M*∏ c, localWeight (b c) 0 0 (S c) := by + apply Fintype.sum_equiv (plainEquivChoices b) + intro S + have h := firstLift_encode b M ((plainEquivChoices b) S) + have he : encode b ((plainEquivChoices b) S)=S.val := + congrArg Subtype.val ((plainEquivChoices b).symm_apply_apply S) + rwa [he] at h + _ = _ := by + rw [← Finset.mul_sum] + have he := sum_independent_choices b (fun _ => 0) (fun _ => 0) + simp only [Nat.sub_zero] at he + rw [he] + simp_rw [InitializationBrackets.bracket_neither] + +end ContingencyTables.InitialTransversals + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerAuxiliaryEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerAuxiliaryEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..567682cebb54c33fca5d3ff4ed7e0ecde5039d05 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerAuxiliaryEnumeration.lean @@ -0,0 +1,182 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTruncatedTransport + +namespace OAI + +/-! # The auxiliary kernel enumerates exactly one excess ordinary pair + +The finite assignment carries its excess-pair position. Its raw full +profile recovers the position and every choice uniquely. Box truncation +removes exactly the two inadmissible endpoints of that excess pair. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open BalancedFamily BalancedEnumeration IntegerMarginal BalancedBox +open IntegerBoxTruncation + +/-- One distinguished ordinary pair has occupancy U+1. -/ +@[reducible] def ExcessAssignments : List ℕ → Type + | [] => Empty + | U::Ms => (Assignments Ms × Fin (U+2)) ⊕ (ExcessAssignments Ms × Fin (U+1)) + +@[reducible] instance excessAssignmentsFintype (Ms : List ℕ) : Fintype (ExcessAssignments Ms) := by + induction Ms with + | nil => exact inferInstanceAs (Fintype Empty) + | cons U Ms ih => + letI := ih + exact inferInstanceAs (Fintype ((Assignments Ms × Fin (U+2)) ⊕ + (ExcessAssignments Ms × Fin (U+1)))) + +def excessEmbedding {I : Type*} : (Ms : List ℕ) → (I → ℕ) → + ExcessAssignments Ms → Coordinates I Ms → ℕ + | [],_,a => Empty.elim a + | U::Ms,z,.inl a => profile (embedding Ms z a.1) a.2.val (U+1-a.2.val) + | U::Ms,z,.inr a => profile (excessEmbedding Ms z a.1) a.2.val (U-a.2.val) + +def ValidExcess : (Ms : List ℕ) → ExcessAssignments Ms → Prop + | [],a => Empty.elim a + | U::_,.inl a => 0 < a.2.val ∧ a.2.val ≤ U + | _::Ms,.inr a => ValidExcess Ms a.1 + +/-- Exact finite expansion of the actual recursive auxiliary kernel. -/ +theorem auxiliaryKernel_eq_excess_sum {I : Type*} (Ms : List ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : + auxiliaryKernel Ms F z=∑ a : ExcessAssignments Ms, F (excessEmbedding Ms z a) := by + induction Ms with + | nil => simp only [auxiliaryKernel,ExcessAssignments,Finset.univ_eq_empty,Finset.sum_empty] + | cons U Ms ih => + change marginal (exposedFamily Ms F) (U+1) z+auxiliaryKernel Ms (marginal F U) z= + ∑ a : (Assignments Ms × Fin (U+2)) ⊕ (ExcessAssignments Ms × Fin (U+1)), + F (excessEmbedding (U::Ms) z a) + rw [Fintype.sum_sum_type] + congr 1 + · unfold marginal exposedFamily + simp_rw [eliminate_eq_sum,expose_embedding] + rw [Finset.sum_comm,Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + exact (Fin.sum_univ_eq_sum_range + (fun j => F (profile (embedding Ms z a) j (U+1-j))) (U+2)).symm + · rw [ih,Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + unfold marginal + exact (Fin.sum_univ_eq_sum_range + (fun j => F (profile (excessEmbedding Ms z a) j (U-j))) (U+1)).symm + +lemma excessEmbedding_injective {I : Type*} (Ms : List ℕ) (z : I → ℕ) : + Function.Injective (excessEmbedding Ms z) := by + induction Ms with + | nil => intro a; exact Empty.elim a + | cons U Ms ih => + intro a b he + cases a with + | inl a => + cases b with + | inl b => + have hj := congrFun he (.inr false) + change a.2.val=b.2.val at hj + have ho : embedding Ms z a.1=embedding Ms z b.1 := by + funext i + exact congrFun he (.inl i) + exact congrArg Sum.inl (Prod.ext (embedding_injective Ms z ho) (Fin.ext hj)) + | inr b => + have hj := congrFun he (.inr false) + have hk := congrFun he (.inr true) + change a.2.val=b.2.val at hj + change U+1-a.2.val=U-b.2.val at hk + have ha := a.2.isLt + have hb := b.2.isLt + omega + | inr a => + cases b with + | inl b => + have hj := congrFun he (.inr false) + have hk := congrFun he (.inr true) + change a.2.val=b.2.val at hj + change U-a.2.val=U+1-b.2.val at hk + have ha := a.2.isLt + have hb := b.2.isLt + omega + | inr b => + have hj := congrFun he (.inr false) + change a.2.val=b.2.val at hj + have ho : excessEmbedding Ms z a.1=excessEmbedding Ms z b.1 := by + funext i + exact congrFun he (.inl i) + exact congrArg Sum.inr (Prod.ext (ih ho) (Fin.ext hj)) + +lemma excessEmbedding_total {I : Type*} [Fintype I] (Ms : List ℕ) + (z : I → ℕ) (a : ExcessAssignments Ms) : + (∑ i, excessEmbedding Ms z a i)=(∑ i, z i)+Ms.sum+1 := by + induction Ms with + | nil => exact Empty.elim a + | cons U Ms ih => + cases a with + | inl a => + change (∑ i, profile (embedding Ms z a.1) a.2.val (U+1-a.2.val) i)=_ + rw [profile_total,embedding_total] + have ha := a.2.isLt + simp only [List.sum_cons] + omega + | inr a => + change (∑ i, profile (excessEmbedding Ms z a.1) a.2.val (U-a.2.val) i)=_ + rw [profile_total,ih] + have ha := a.2.isLt + simp only [List.sum_cons] + omega + +lemma excessEmbedding_inBox_iff {I : Type*} (Ms : List ℕ) (m z : I → ℕ) + (hz : InBox m z) (a : ExcessAssignments Ms) : + InBox (bounds m Ms) (excessEmbedding Ms z a) ↔ ValidExcess Ms a := by + induction Ms with + | nil => exact Empty.elim a + | cons U Ms ih => + cases a with + | inl a => + constructor + · intro h + have ha := h (.inr false) + have hb := h (.inr true) + change a.2.val ≤ U at ha + change U+1-a.2.val ≤ U at hb + change 0 < a.2.val ∧ a.2.val ≤ U + omega + · intro h + apply profile_inBox (bounds m Ms) (embedding Ms z a.1) U a.2.val (U+1-a.2.val) + · exact embedding_inBox Ms m z hz a.1 + · exact h.2 + · have ha := h.1 + omega + | inr a => + constructor + · intro h + apply (ih a.1).mp + intro i + exact h (.inl i) + · intro h + apply profile_inBox (bounds m Ms) (excessEmbedding Ms z a.1) U a.2.val (U-a.2.val) + · exact (ih a.1).mpr h + · have ha := a.2.isLt + omega + · exact Nat.sub_le _ _ + +/-- The zero-extended auxiliary count includes precisely the admissible +single-excess-pair profiles, each once. -/ +theorem auxiliaryKernel_truncate_eq_valid_sum {I : Type*} [Fintype I] + (Ms : List ℕ) (F : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) + (hz : InBox m z) (htotal : (∑ i, z i)+1=R) : + auxiliaryKernel Ms (truncate F (bounds m Ms) (R+Ms.sum)) z= + ∑ a ∈ Finset.univ.filter (ValidExcess Ms), F (excessEmbedding Ms z a) := by + rw [auxiliaryKernel_eq_excess_sum,Finset.sum_filter] + apply Finset.sum_congr rfl + intro a _ + have ht : (∑ i, excessEmbedding Ms z a i)=R+Ms.sum := by + rw [excessEmbedding_total] + omega + simp only [truncate,ht,excessEmbedding_inBox_iff Ms m z hz a,and_true] + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerBoxTruncation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerBoxTruncation.lean new file mode 100644 index 0000000000000000000000000000000000000000..77308fe982f96ec24dd1a100f80cb80ae0b2ced5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerBoxTruncation.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedBox +import OAI.Combinatorics.ContingencyTables.Transport.ProductIntegerSignature + +namespace OAI + +/-! +# The actual finite-box fixed-total weight + +Truncating the positive product outside its box and required total leaves +every valid two-removal matrix entry unchanged at a box-valid display two +above that total. The balancing development therefore applies to the +paper's literal zero-extended weight. +-/ + +namespace ContingencyTables.IntegerBoxTruncation + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures ProductIntegerSignature BalancedBox + +variable {I : Type*} [Fintype I] + +noncomputable def truncate (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) (z : I → ℕ) : ℝ := + if InBox m z ∧ (∑ i, z i)=R then f z else 0 + +omit [Fintype I] in +lemma removal_inBox (m z : I → ℕ) (hz : InBox m z) (i j : I) : InBox m (removeTwo z i j) := by + intro k + apply le_trans _ (hz k) + unfold removeTwo removeOne + omega + +lemma removal_total (z : I → ℕ) (i j : I) (hv : ValidPair z i j) : + (∑ k, removeTwo z i j k)+2=∑ k, z k := by + have h := lineTotal_removeTwo (fun _ : I => ()) z i j hv () + simp only [lineTotal,ite_true] at h + omega + +/-- Exact equality of the actual truncated and product integer matrices. -/ +theorem removal_truncate_eq (f : (I → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) + (hz : InBox m z) (ht : (∑ i, z i)=R+2) : + integerRemovalMatrix (truncate f m R) z = integerRemovalMatrix f z := by + ext i j + unfold integerRemovalMatrix + split_ifs with hv + · have hb := removal_inBox m z hz i j + have htotal := removal_total z i j hv + have he : (∑ k, removeTwo z i j k)=R := by omega + simp [truncate,hb,he] + · rfl + +/-- Positivity on the actual slice is unchanged by literal zero extension. -/ +theorem truncate_positive_slice (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) + (hpos : PositiveSlice f m R) : PositiveSlice (truncate f m R) m R := by + intro z hz ht + have hb : InBox m z ∧ (∑ i, z i)=R := ⟨hz,ht⟩ + simpa only [truncate,ite_eq_left hb] using hpos z hz ht + +/-- The actual integer signature is unchanged by the box/total indicator. -/ +theorem truncate_removal_slice (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) + (hsig : RemovalSlice f m R) : RemovalSlice (truncate f m R) m R := by + intro z hz ht + rw [removal_truncate_eq f m z R hz ht] + exact hsig z hz ht + +end ContingencyTables.IntegerBoxTruncation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildLogConcavity.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildLogConcavity.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cb7f9ae727641a3b3008deab30d5157dbdbbb12 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildLogConcavity.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportLimit +import OAI.Combinatorics.ContingencyTables.Transport.PositiveSequenceMinimum + +namespace OAI + +/-! # Conditional child masses have no internal valley + +The actual two-coordinate removal form gives the local log-concavity +inequality. The endpoint-minimum property passes to the hard-zero limit. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Topology Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal BalancedBox Filter + +def childProfile (U k : ℕ) : Bool → ℕ := fun b => if b then U-k else k + +lemma bool_diagonal_product (A : Matrix Bool Bool ℝ) + (hsymm : ∀ i j, A i j=A j i) (hsig : OnePositiveDirection A.toBilin') + (haa : 0 < A false false) : A false false*A true true ≤ (A false true)^2 := by + let ea : Bool → ℝ := Pi.single false 1 + let eb : Bool → ℝ := Pi.single true 1 + have ha : 0 < A.toBilin' ea ea := by + simpa [ea,Matrix.toBilin'_apply] using haa + have hp := (le_div_iff₀ ha).mp + (positive_projection A.toBilin' (fun x y => (matrix_bilin_symm A hsymm).eq x y) hsig ea eb ha) + simpa [ea,eb,Matrix.toBilin'_apply,mul_comm] using hp + +lemma childProfile_inBox (U k : ℕ) (hk : k ≤ U) : + InBox (fun _ : Bool => U) (childProfile U k) := by + intro b + cases b + · exact hk + · exact Nat.sub_le _ _ + +lemma childProfile_total (U k : ℕ) (hk : k ≤ U) : (∑ b, childProfile U k b)=U := by + simp only [Fintype.sum_bool,childProfile,Bool.false_eq_true,↓reduceIte] + omega + +theorem child_logConcave (f : (Bool → ℕ) → ℝ) (U : ℕ) + (hp : PositiveSlice f (fun _ => U) U) (hs : RemovalSlice f (fun _ => U) U) + (k : ℕ) (hk : k+2 ≤ U) : + f (childProfile U k)*f (childProfile U (k+2)) ≤ (f (childProfile U (k+1)))^2 := by + let D : Bool → ℕ := fun b => if b then U-k else k+2 + have hDbox : InBox (fun _ : Bool => U) D := by + intro b + cases b + · exact hk + · exact Nat.sub_le _ _ + have hDsum : (∑ b, D b)=U+2 := by + simp only [D,Fintype.sum_bool,Bool.false_eq_true,↓reduceIte] + omega + have hsig := hs D hDbox hDsum + have haa : integerRemovalMatrix f D false false=f (childProfile U k) := by + have hv : ValidPair D false false := by simp [ValidPair,D] + rw [integerRemovalMatrix,ite_eq_left hv] + congr 1 + funext b + cases b <;> simp [removeTwo,removeOne,D,childProfile] + have hbb : integerRemovalMatrix f D true true=f (childProfile U (k+2)) := by + have hv : ValidPair D true true := by simp [ValidPair,D]; omega + rw [integerRemovalMatrix,ite_eq_left hv] + congr 1 + funext b + cases b + · simp [removeTwo,removeOne,D,childProfile] + · simp [removeTwo,removeOne,D,childProfile] + omega + have hab : integerRemovalMatrix f D false true=f (childProfile U (k+1)) := by + have hv : ValidPair D false true := by simp [ValidPair,D]; omega + rw [integerRemovalMatrix,ite_eq_left hv] + congr 1 + funext b + cases b + · simp [removeTwo,removeOne,D,childProfile] + · simp [removeTwo,removeOne,D,childProfile] + omega + have hpos : 0 < integerRemovalMatrix f D false false := by + rw [haa] + exact hp _ (childProfile_inBox U k (by omega)) (childProfile_total U k (by omega)) + have hdet := bool_diagonal_product _ (integerRemoval_symm f D) hsig hpos + rwa [haa,hbb,hab] at hdet + +theorem child_minimum (f : (Bool → ℕ) → ℝ) (U : ℕ) + (hp : PositiveSlice f (fun _ => U) U) (hs : RemovalSlice f (fun _ => U) U) + (a j b : ℕ) (haj : a ≤ j) (hjb : j ≤ b) (hbU : b ≤ U) : + min (f (childProfile U a)) (f (childProfile U b)) ≤ f (childProfile U j) := by + apply positive_sequence_minimum (fun k => f (childProfile U k)) U a j b + · intro k hk + exact hp _ (childProfile_inBox U k hk) (childProfile_total U k hk) + · exact child_logConcave f U hp hs + · exact haj + · exact hjb + · exact hbU + +/-- Every mass between two positive hard children is at least the +smaller endpoint mass, including when other children have zero weight. -/ +theorem child_minimum_limit {K : Type*} {l : Filter K} [l.NeBot] + (F : K → (Bool → ℕ) → ℝ) (f : (Bool → ℕ) → ℝ) (U : ℕ) + (hlim : ∀ z, Tendsto (fun t => F t z) l (nhds (f z))) + (hsoft : ∀ᶠ t in l, PositiveSlice (F t) (fun _ => U) U ∧ + RemovalSlice (F t) (fun _ => U) U) + (a j b : ℕ) (haj : a ≤ j) (hjb : j ≤ b) (hbU : b ≤ U) : + min (f (childProfile U a)) (f (childProfile U b)) ≤ f (childProfile U j) := by + apply le_of_tendsto_of_tendsto ((hlim _).min (hlim _)) (hlim _) + filter_upwards [hsoft] with t ht + exact child_minimum (F t) U ht.1 ht.2 a j b haj hjb hbU + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..59ea82a92dd65b089b060b3c5a5c19bf23287a86 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerChildVariance.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerChildLogConcavity + +namespace OAI + +/-! # Between-child variance from raw integer transport + +The no-valley bound for child masses turns adjacent transport into a +bound on every pair of child means. Finite Cauchy--Schwarz and the exact +weighted pair formula then bound the between-child variance. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open CommonBasesFPRAS + +lemma range_difference_sum (H : ℕ → ℝ) (a n : ℕ) : + (∑ j ∈ Finset.range n, (H (a+j)-H (a+j+1)))=H a-H (a+n) := by + induction n with + | zero => simp + | succ n ih => rw [Finset.sum_range_succ,ih]; simp only [Nat.add_succ]; ring + +lemma path_square (H : ℕ → ℝ) (a n : ℕ) : + (H a-H (a+n))^2 ≤ (n:ℝ)*∑ j ∈ Finset.range n, (H (a+j)-H (a+j+1))^2 := by + have h := Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul (Finset.range n) + (r := fun j => H (a+j)-H (a+j+1)) (f := fun _ => (1:ℝ)) + (g := fun j => (H (a+j)-H (a+j+1))^2) + (fun _ _ => zero_le_one) (fun _ _ => sq_nonneg _) (fun _ _ => by simp) + simpa only [range_difference_sum,Finset.sum_const,Finset.card_range,nsmul_eq_mul,mul_one] using h + +lemma minimum_pair_coefficient (x y Z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) + (hZ : 0 < Z) (hxZ : x ≤ Z) (hyZ : y ≤ Z) : x*y/Z ≤ min x y := by + apply le_min + · apply (div_le_iff₀ hZ).mpr + exact mul_le_mul_of_nonneg_left hyZ hx + · apply (div_le_iff₀ hZ).mpr + simpa only [mul_comm] using mul_le_mul_of_nonneg_left hxZ hy + +lemma child_pair_path_bound (z H : ℕ → ℝ) (U a b : ℕ) (Z A E : ℝ) + (hz : ∀ j ≤ U, 0 ≤ z j) (hZ : 0 < Z) (hzZ : ∀ j ≤ U, z j ≤ Z) + (hA : 0 ≤ A) (hE : 0 ≤ E) + (hminimum : ∀ a j b, a ≤ j → j ≤ b → b ≤ U → min (z a) (z b) ≤ z j) + (hadj : ∀ j, j < U → min (z j) (z (j+1))*(H j-H (j+1))^2 ≤ A*E) + (ha : a ≤ U) (hb : b ≤ U) : + z a*z b/Z*(H a-H b)^2 ≤ (U:ℝ)^2*A*E := by + wlog hab : a ≤ b generalizing a b + · have h := this b a hb ha (by omega) + have hsq : (H b-H a)^2=(H a-H b)^2 := by ring + simpa only [mul_comm (z b) (z a),hsq] using h + have hmin : 0 ≤ min (z a) (z b) := le_min (hz a ha) (hz b hb) + have hn : b-a ≤ U := by omega + have hpath := path_square H a (b-a) + rw [Nat.add_sub_of_le hab] at hpath + have hcoef := minimum_pair_coefficient (z a) (z b) Z (hz a ha) (hz b hb) + hZ (hzZ a ha) (hzZ b hb) + have hsteps : ∑ j ∈ Finset.range (b-a), + min (z a) (z b)*(H (a+j)-H (a+j+1))^2 ≤ (b-a:ℕ)* (A*E) := by + calc + _ ≤ ∑ _j ∈ Finset.range (b-a), A*E := by + apply Finset.sum_le_sum + intro j hj + have hjn := Finset.mem_range.mp hj + have hjU : a+j < U := by omega + have hm : min (z a) (z b) ≤ min (z (a+j)) (z (a+j+1)) := by + apply le_min + · exact hminimum a (a+j) b (by omega) (by omega) hb + · exact hminimum a (a+j+1) b (by omega) (by omega) hb + exact (mul_le_mul_of_nonneg_right hm (sq_nonneg _)).trans (hadj (a+j) hjU) + _ = _ := by simp + have hnreal : (b-a:ℕ) ≤ (U:ℝ) := by exact_mod_cast hn + have hAE : 0 ≤ A*E := mul_nonneg hA hE + calc + _ ≤ min (z a) (z b)*(H a-H b)^2 := mul_le_mul_of_nonneg_right hcoef (sq_nonneg _) + _ ≤ min (z a) (z b)*((b-a:ℕ)* + ∑ j ∈ Finset.range (b-a), (H (a+j)-H (a+j+1))^2) := + mul_le_mul_of_nonneg_left hpath hmin + _ = (b-a:ℕ)*(∑ j ∈ Finset.range (b-a), + min (z a) (z b)*(H (a+j)-H (a+j+1))^2) := by rw [←Finset.mul_sum]; ring + _ ≤ (b-a:ℕ)*((b-a:ℕ)*(A*E)) := + mul_le_mul_of_nonneg_left hsteps (Nat.cast_nonneg _) + _ ≤ (U:ℝ)*((U:ℝ)*(A*E)) := by + gcongr + _ = _ := by ring + +lemma finite_pair_square {X : Type*} [Fintype X] (w H : X → ℝ) : + (∑ x, ∑ y, w x*w y*(H x-H y)^2)= + 2*(∑ x, w x)*(∑ x, w x*(H x)^2)-2*(∑ x, w x*H x)^2 := by + have he (x y : X) : w x*w y*(H x-H y)^2= + (w x*(H x)^2)*w y+w x*(w y*(H y)^2)-2*((w x*H x)*(w y*H y)) := by ring + have hinner (x : X) : (∑ y, w x*w y*(H x-H y)^2)= + (w x*(H x)^2)*(∑ y, w y)+w x*(∑ y, w y*(H y)^2)- + 2*((w x*H x)*(∑ y, w y*H y)) := by + simp_rw [he,Finset.sum_sub_distrib,Finset.sum_add_distrib,←Finset.mul_sum] + simp_rw [hinner,Finset.sum_sub_distrib,Finset.sum_add_distrib,←Finset.mul_sum,←Finset.sum_mul] + ring + +/-- Exact unnormalized weighted variance pair formula. -/ +lemma finite_weighted_variance_pair {X : Type*} [Fintype X] (w H : X → ℝ) + (hZ : 0 < ∑ x, w x) : + (∑ x, w x*(H x-(∑ y, w y*H y)/(∑ y, w y))^2)= + (∑ x, ∑ y, w x*w y/(∑ k, w k)*(H x-H y)^2)/2 := by + have hc := finite_center_at_mean Finset.univ w H (ne_of_gt hZ) + rw [hc] + have he : (∑ x, ∑ y, w x*w y/(∑ k, w k)*(H x-H y)^2)= + (∑ x, ∑ y, w x*w y*(H x-H y)^2)/(∑ k, w k) := by + simp_rw [div_mul_eq_mul_div,←Finset.sum_div] + rw [he,finite_pair_square] + field_simp + +/-- The paper's between-child estimate, including zero-mass children. -/ +theorem child_variance_bound (z H : ℕ → ℝ) (U : ℕ) (A E : ℝ) + (hz : ∀ j ≤ U, 0 ≤ z j) (hZ : 0 < ∑ j : Fin (U+1), z j.val) + (hA : 0 ≤ A) (hE : 0 ≤ E) + (hminimum : ∀ a j b, a ≤ j → j ≤ b → b ≤ U → min (z a) (z b) ≤ z j) + (hadj : ∀ j, j < U → min (z j) (z (j+1))*(H j-H (j+1))^2 ≤ A*E) : + (∑ j : Fin (U+1), z j.val*(H j.val- + (∑ k : Fin (U+1), z k.val*H k.val)/(∑ k : Fin (U+1), z k.val))^2) ≤ + ((U:ℝ)+1)^4*A*E := by + have hzZ (j : ℕ) (hj : j ≤ U) : z j ≤ ∑ k : Fin (U+1), z k.val := by + exact Finset.single_le_sum (fun k _ => hz k.val (by omega)) + (Finset.mem_univ (⟨j,by omega⟩ : Fin (U+1))) + rw [finite_weighted_variance_pair _ _ hZ] + have hp (a b : Fin (U+1)) := child_pair_path_bound z H U a.val b.val _ A E hz hZ hzZ + hA hE hminimum hadj (by omega) (by omega) + have hsum := Finset.sum_le_sum (s := Finset.univ) (fun a _ => + Finset.sum_le_sum (s := Finset.univ) (fun b _ => hp a b)) + have hsum' : (∑ a : Fin (U+1), ∑ b : Fin (U+1), + z a.val*z b.val/(∑ k : Fin (U+1), z k.val)*(H a.val-H b.val)^2) ≤ + ((U:ℝ)+1)^2*(U:ℝ)^2*A*E := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul, + Nat.cast_add,Nat.cast_one] at hsum + convert hsum using 1; ring + have hAE : 0 ≤ A*E := mul_nonneg hA hE + have hU : 0 ≤ (U:ℝ) := Nat.cast_nonneg _ + have hpow : ((U:ℝ)+1)^2*(U:ℝ)^2 ≤ ((U:ℝ)+1)^4 := by + have hsq : (U:ℝ)^2 ≤ ((U:ℝ)+1)^2 := by nlinarith + convert mul_le_mul_of_nonneg_left hsq (sq_nonneg ((U:ℝ)+1)) using 1; ring + have hb := mul_le_mul_of_nonneg_right hpow hAE + nlinarith + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerContextSlices.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerContextSlices.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e500cca26354975e91637c9b3633dd95baa3339 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerContextSlices.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerSliceRestriction + +namespace OAI + +/-! # A fixed context after a physical coordinate bijection -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open BalancedBox + +variable {C D S : Type*} [Fintype C] [Fintype D] [Fintype S] + [DecidableEq C] [DecidableEq D] [DecidableEq S] + +theorem context_slices (e : (C ⊕ D) ≃ S) (f : (S → ℕ) → ℝ) + (mC c : C → ℕ) (mD : D → ℕ) (R : ℕ) (hc : InBox mC c) + (hp : PositiveSlice f ((Sum.elim mC mD) ∘ e.symm) ((∑ i, c i)+R)) + (hs : RemovalSlice f ((Sum.elim mC mD) ∘ e.symm) ((∑ i, c i)+R)) : + PositiveSlice (fun x => f ((Sum.elim c x) ∘ e.symm)) mD R ∧ + RemovalSlice (fun x => f ((Sum.elim c x) ∘ e.symm)) mD R := by + have hpr := positiveSlice_reindex e f _ _ hp + have hsr := removalSlice_reindex e f _ _ hs + have hm : ((Sum.elim mC mD) ∘ e.symm) ∘ e=Sum.elim mC mD := by + funext t + simp only [Function.comp_apply,Equiv.symm_apply_apply] + rw [hm] at hpr hsr + exact ⟨positiveSlice_fixed (fun x => f (x ∘ e.symm)) mC c mD R hc hpr, + removalSlice_fixed (fun x => f (x ∘ e.symm)) mC c mD R hc hsr⟩ + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerCorrectionKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerCorrectionKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b9ce4e8918861f2c35f8e26d6f3e1e344cac7b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerCorrectionKernel.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerRecursiveFlow + +namespace OAI + +/-! # The literal sum of future-slot correction kernels + +Each summand gives exactly one unexposed ordinary pair occupancy M+1, +with multiplier a(M+1-a); every other pair is summed at its ordinary +balance. The coordinate changes below preserve complete configurations. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open BalancedFamily BalancedEnumeration IntegerMarginal + +universe u + +def exposePullback {I : Type u} (Ms : List ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) : + (Coordinates (I ⊕ Bool) Ms → ℕ) → ℝ := + fun x => F (x ∘ (exposeEquiv (I := I) Ms).symm) + +lemma exposed_profile {I : Type u} (Ms : List ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (a b : ℕ) : + exposedFamily Ms F (profile z a b) = + eliminate Ms (fun x => F (profile x a b)) z := by + unfold exposedFamily + simp only [eliminate_eq_sum] + apply Finset.sum_congr rfl + intro v _ + rw [expose_embedding] + +lemma expose_pair {I : Type u} (Ms : List ℕ) (V : ℕ) + (x : Coordinates (I ⊕ Bool) Ms → ℕ) (a b : ℕ) : + (profile x a b) ∘ (exposeEquiv (I := I) (V::Ms)).symm = + (profile (x ∘ (exposeEquiv (I := I) Ms).symm) a b) ∘ swapPairs := by + funext t + rcases t with (i | c) | c <;> rfl + +lemma exposed_double_profile {I : Type u} (Ms : List ℕ) (V : ℕ) + (F : (((Coordinates I Ms ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) + (z : I → ℕ) (j k a b : ℕ) : + exposedFamily Ms (exposePullback (V::Ms) F) (profile (profile z j k) a b) = + eliminate Ms (fun x => F (profile (profile x a b) j k)) z := by + unfold exposedFamily exposePullback + simp only [eliminate_eq_sum] + apply Finset.sum_congr rfl + intro v _ + change F ((embedding Ms (profile (profile z j k) a b) v ∘ + (exposeEquiv (I := I ⊕ Bool) Ms).symm) ∘ + (exposeEquiv (I := I) (V::Ms)).symm) = _ + have he := expose_embedding Ms (profile z j k) a b v + change embedding Ms (profile (profile z j k) a b) v ∘ + (exposeEquiv (I := I ⊕ Bool) Ms).symm = _ at he + rw [he, expose_pair] + have he' := expose_embedding Ms z j k v + change embedding Ms (profile z j k) v ∘ (exposeEquiv (I := I) Ms).symm = _ at he' + rw [he'] + exact congrArg F (profile_swap (embedding Ms z v) a b j k) + +lemma eliminate_sum {I : Type u} {A : Type*} (Ms : List ℕ) (s : Finset A) + (F : A → (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : + eliminate Ms (fun x => ∑ a ∈ s, F a x) z = + ∑ a ∈ s, eliminate Ms (F a) z := by + simp only [eliminate_eq_sum] + rw [Finset.sum_comm] + +lemma eliminate_mul {I : Type u} (Ms : List ℕ) (r : ℝ) + (F : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : + eliminate Ms (fun x => r*F x) z = r*eliminate Ms F z := by + simp only [eliminate_eq_sum, Finset.mul_sum] + +/-- The same current and future profiles occur on both sides, including +the complete fixed-domain sum over every other ordinary slot. -/ +lemma weighted_exposed_commute {I : Type u} (Ms : List ℕ) (U V : ℕ) + (F : (((Coordinates I Ms ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) : + weightedFuture (exposedFamily Ms (marginal F U)) (V+1) z = + marginal (weightedFuture (exposedFamily Ms (exposePullback (V::Ms) F)) (V+1)) U z := by + unfold weightedFuture + conv_lhs => tactic => simp_rw [exposed_profile, marginal, eliminate_sum, Finset.mul_sum] + unfold marginal + rw [Finset.sum_comm] + simp_rw [exposed_double_profile] + +lemma pullback_marginal {I : Type u} (Ms : List ℕ) (V : ℕ) + (F : (((Coordinates I Ms ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) : + marginal (exposePullback (V::Ms) F) V = + exposePullback Ms (marginal (fun x => F (x ∘ swapPairs)) V) := by + funext x + unfold marginal exposePullback + apply Finset.sum_congr rfl + intro j _ + rw [expose_pair] + +lemma marginal_swap_commute {J : Type u} (F : (((J ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) + (U V : ℕ) : + marginal (marginal F U) V = marginal (marginal (fun x => F (x ∘ swapPairs)) V) U := by + funext z + unfold marginal + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro j _ + apply Finset.sum_congr rfl + intro a _ + exact congrArg F (profile_swap z a (V-a) j (U-j)).symm + +noncomputable def correctionKernel {I : Type u} : (Ms : List ℕ) → + ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → ℝ + | [], _ => fun _ => 0 + | U::Ms, F => fun z => weightedFuture (exposedFamily Ms F) (U+1) z + + correctionKernel Ms (marginal F U) z + +theorem correctionKernel_nonnegative {I : Type u} (Ms : List ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (hF : ∀ x, 0 ≤ F x) (z : I → ℕ) : + 0 ≤ correctionKernel Ms F z := by + induction Ms with + | nil => exact le_rfl + | cons U Ms ih => + apply add_nonneg + · apply weightedFuture_nonnegative + intro x + exact eliminate_nonnegative Ms _ (fun p => hF _) x + · apply ih + intro x + exact Finset.sum_nonneg (fun j _ => hF _) + +/-- Summing the currently exposed pair commutes with the literal sum +of all the other future corrections. -/ +theorem correctionKernel_current_commute : ∀ (Ms : List ℕ) {I : Type u} + (U : ℕ) (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ), + correctionKernel Ms (marginal F U) = + marginal (correctionKernel Ms (exposePullback Ms F)) U := by + intro Ms + induction Ms with + | nil => intro I U F; funext z; simp [correctionKernel, marginal] + | cons V Ms ih => + intro I U F + funext z + change weightedFuture (exposedFamily Ms (marginal F U)) (V+1) z + + correctionKernel Ms (marginal (marginal F U) V) z = + ∑ j ∈ Finset.range (U+1), + (weightedFuture (exposedFamily Ms (exposePullback (V::Ms) F)) (V+1) + (profile z j (U-j)) + + correctionKernel Ms (marginal (exposePullback (V::Ms) F) V) (profile z j (U-j))) + rw [Finset.sum_add_distrib, weighted_exposed_commute, marginal_swap_commute] + have ht := congrFun (ih U (marginal (fun x => F (x ∘ swapPairs)) V)) z + rw [← pullback_marginal] at ht + rw [ht] + rfl + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerEquivLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerEquivLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..17f6d1408bce74877cdf7eb7ce0f9f475e2eb4ea --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerEquivLaw.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw +import OAI.Combinatorics.ContingencyTables.Transport.RationalReindex + +namespace OAI + +/-! # Integer laws under bijective coordinate changes -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators +variable {A B : Type*} [Fintype A] [Fintype B] {Q : ℕ} + +/-- A coordinate permutation leaves the common denominator unchanged. -/ +def equiv (p : IntegerLaw A Q) (e : A ≃ B) : IntegerLaw B Q where + count b := p.count (e.symm b) + total := (e.symm.sum_comp p.count).trans p.total + +@[simp] lemma equiv_count (p : IntegerLaw A Q) (e : A ≃ B) (b : B) : + (p.equiv e).count b=p.count (e.symm b) := rfl + +lemma toRational_equiv (p : IntegerLaw A Q) (e : A ≃ B) (hQ : 0 (K x).count y) x n + total := IntegerPropagation.numerators_total _ Q (fun x => (K x).total) x n + +lemma toRational_walk [DecidableEq A] (K : A → IntegerLaw A Q) (hQ : 0 (K x).toRational hQ) x n := by + apply ResidualMixture.RationalLaw.ext + funext y + have hK : IntegerPropagation.kernel (fun x y => (K x).count y) Q hQ + (fun x => (K x).total)=(fun x => (K x).toRational hQ) := by + funext a + apply ResidualMixture.RationalLaw.ext + rfl + have he := IntegerPropagation.numerators_walkLaw (fun x y => (K x).count y) + Q hQ (fun x => (K x).total) x n y + rw [hK] at he + simpa only [toRational,walk,Nat.cast_pow] using + he + +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerExchangeArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerExchangeArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..06a8f5ba50e2799c26af9fbfa60fbc44dbe0d18b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerExchangeArithmetic.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeDegree + +namespace OAI + +/-! # Arithmetic recognition of unit-exchange edges -/ + +namespace ContingencyTables.IntegerWeightedTransport +open FactorialSignatures + +variable {C : Type*} [DecidableEq C] + +lemma exchangeTarget_adjacent (X : C → ℕ) (i j : C) + (hij : i≠j) (hj : 0 X a+if a=i then 1 else 0 + refine ⟨D,i,j,hij,?_,?_,?_,?_⟩ + · simp only [D,ite_true] + omega + · simpa only [D,Ne.symm hij,ite_false,Nat.add_zero] using hj + · funext a + simp only [D,removeOne] + split_ifs <;> omega + · rfl + +/-- The test quantifies only over two coordinates, never over profiles. -/ +theorem adjacent_iff_arithmetic (X Y : C → ℕ) : + IntegerExchangeAdjacent X Y ↔ + ∃ i j,i≠j ∧ 0 Equiv.refl _ + | _::Ms => (Equiv.sumCongr (exposeEquiv (I := I) Ms) (Equiv.refl Bool)).trans swapPairs + +lemma expose_embedding {I : Type*} (Ms : List ℕ) (z : I → ℕ) (a b : ℕ) + (u : Assignments Ms) : + (fun t => embedding Ms (profile z a b) u ((exposeEquiv (I := I) Ms).symm t)) = + profile (embedding Ms z u) a b := by + induction Ms with + | nil => rfl + | cons M Ms ih => + funext t + rcases t with (i | c) | c + · change embedding Ms (profile z a b) u.1 ((exposeEquiv (I := I) Ms).symm (.inl i)) = + embedding Ms z u.1 i + exact congrFun (ih u.1) (.inl i) + · cases c <;> rfl + · change embedding Ms (profile z a b) u.1 ((exposeEquiv (I := I) Ms).symm (.inr c)) = _ + exact congrFun (ih u.1) (.inr c) + +noncomputable def exposedFamily {I : Type*} (Ms : List ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) : ((I ⊕ Bool) → ℕ) → ℝ := + eliminate Ms (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + +/-- The literal child family sums back to its actual parent; the domain +is the same Cartesian product of all remaining balanced profiles. -/ +theorem exposed_marginal {I : Type*} (Ms : List ℕ) (U : ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) : + marginal (exposedFamily Ms F) U = eliminate (U::Ms) F := by + funext z + change (∑ j ∈ Finset.range (U+1), exposedFamily Ms F (profile z j (U-j))) = + eliminate Ms (marginal F U) z + simp only [exposedFamily, eliminate_eq_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + unfold marginal + apply Finset.sum_congr rfl + intro j _ + rw [expose_embedding] + + +lemma expose_bounds {I : Type*} (Ms : List ℕ) (m : I → ℕ) (U : ℕ) : + (fun t => bounds (profile m U U) Ms ((exposeEquiv (I := I) Ms).symm t)) = + profile (bounds m Ms) U U := by + induction Ms with + | nil => rfl + | cons M Ms ih => + funext t + rcases t with (i | c) | c + · change bounds (profile m U U) Ms ((exposeEquiv (I := I) Ms).symm (.inl i)) = bounds m Ms i + exact congrFun ih (.inl i) + · cases c <;> rfl + · change bounds (profile m U U) Ms ((exposeEquiv (I := I) Ms).symm (.inr c)) = _ + exact congrFun ih (.inr c) + + +lemma expose_bounds_forward {I : Type*} (Ms : List ℕ) (m : I → ℕ) (U : ℕ) : + (profile (bounds m Ms) U U) ∘ exposeEquiv (I := I) Ms = bounds (profile m U U) Ms := by + funext t + have he := congrFun (expose_bounds Ms m U) (exposeEquiv (I := I) Ms t) + simpa only [Equiv.symm_apply_apply, Function.comp_apply] using he.symm + +/-- Remaining balanced marginalization supplies the exposed child +family's positivity and signature on the exact required total slice. -/ +theorem exposed_slices {I : Type*} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (U : ℕ) (m : I → ℕ) (R : ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) + (hpos : BalancedBox.PositiveSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum)) + (hsig : BalancedBox.RemovalSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum)) : + BalancedBox.PositiveSlice (exposedFamily Ms F) (profile m U U) (R+U) ∧ + BalancedBox.RemovalSlice (exposedFamily Ms F) (profile m U U) (R+U) := by + apply eliminate_slices Ms (profile m U U) (R+U) _ hwidth + · have hp := positiveSlice_reindex (exposeEquiv (I := I) Ms) F (profile (bounds m Ms) U U) + (R+U+Ms.sum) hpos + rw [expose_bounds_forward] at hp + exact hp + · have hs := removalSlice_reindex (exposeEquiv (I := I) Ms) F (profile (bounds m Ms) U U) + (R+U+Ms.sum) hsig + rw [expose_bounds_forward] at hs + exact hs + + +theorem expose_source_positive {I : Type*} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (U : ℕ) (m : I → ℕ) (R : ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) + (hpos : BalancedBox.PositiveSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum)) : + BalancedBox.PositiveSlice (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (bounds (profile m U U) Ms) (R+U+Ms.sum) := by + have hp := positiveSlice_reindex (exposeEquiv (I := I) Ms) F (profile (bounds m Ms) U U) + (R+U+Ms.sum) hpos + rw [expose_bounds_forward] at hp + exact hp + +theorem eliminate_positive {I : Type*} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (m : I → ℕ) (R : ℕ) (F : (Coordinates I Ms → ℕ) → ℝ) + (hpos : BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum)) : + BalancedBox.PositiveSlice (eliminate Ms F) m R := by + induction Ms with + | nil => simpa only [List.sum_nil, add_zero, eliminate, bounds] using hpos + | cons U Ms ih => + apply ih (marginal F U) + apply BalancedBox.marginal_positive_slice F (bounds m Ms) (R+Ms.sum) U + rw [show R+Ms.sum+U=R+(U::Ms).sum by simp only [List.sum_cons]; omega] + exact hpos + +theorem exposed_positive {I : Type*} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (U : ℕ) (m : I → ℕ) (R : ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) + (hpos : BalancedBox.PositiveSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum)) : + BalancedBox.PositiveSlice (exposedFamily Ms F) (profile m U U) (R+U) := + eliminate_positive Ms (profile m U U) (R+U) _ (expose_source_positive Ms U m R F hpos) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab8a28bd3920f691182c6f5324716aeb66083d3b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureKernel.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerFutureSquare + +namespace OAI + +/-! +# The weighted future-slot kernel + +Weights a(M-a) are used inside the finite box 0≤a≤M. The common +nonnegative kernel identifies the integer transport's future correction +matrix. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def weightedFuture (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) : ℝ := + ∑ a ∈ Finset.range (M+1), (a:ℝ)*((M:ℝ)-a)*F (profile z a (M-a)) + +omit [Fintype I] [DecidableEq I] in +lemma weightedFuture_nonnegative (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) + (hF : ∀ p, 0 ≤ F p) (z : I → ℕ) : 0 ≤ weightedFuture F M z := by + apply Finset.sum_nonneg + intro a ha + have haM : a ≤ M := by have := Finset.mem_range.mp ha; omega + have haR : (a:ℝ) ≤ M := by exact_mod_cast haM + exact mul_nonneg (mul_nonneg (Nat.cast_nonneg _) (sub_nonneg.mpr haR)) (hF _) + +omit [Fintype I] in +/-- Weighted future matrices are the old block of the literal common +kernel. This is an equality, with no one-positive-direction hypothesis. -/ +theorem weightedFuture_matrix (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) : + integerRemovalMatrix (weightedFuture F M) z = + ∑ a ∈ Finset.range (M+1), ((a:ℝ)*((M:ℝ)-a)) • + (pairMatrix F M z a).submatrix Sum.inl Sum.inl := by + ext i j + simp only [Matrix.sum_apply, Matrix.smul_apply, smul_eq_mul, + Matrix.submatrix_apply, pairMatrix_old, integerRemovalMatrix, weightedFuture] + split_ifs <;> simp + +/-- The scalar correction Q_t is exactly the weighted two-old-hole sum. -/ +theorem weightedFuture_form (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) + (z : I → ℕ) (h : I → ℝ) : + (integerRemovalMatrix (weightedFuture F M) z).toBilin' h h = + ∑ a ∈ Finset.range (M+1), (a:ℝ)*((M:ℝ)-a)* + (pairMatrix F M z a).toBilin' (old h) (old h) := by + rw [weightedFuture_matrix] + simp only [map_sum, map_smul, LinearMap.sum_apply, LinearMap.smul_apply, smul_eq_mul] + apply Finset.sum_congr rfl + intro a _ + rw [old_old] + +/-- Applying the square identity to the manuscript's weighted future +kernel proves monotonicity for that kernel itself. -/ +theorem weighted_future_monotone + (F : (((I ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) (n : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) (hF : ∀ p, 0 ≤ F p) : + (integerRemovalMatrix (marginal (weightedFuture F M) (n+2)) z).toBilin' h h ≤ + ∑ j ∈ Finset.range (n+3), (pairMatrix (weightedFuture F M) (n+2) z j).toBilin' + (extendCoefficients h (g j) (g (j+1))) (extendCoefficients h (g j) (g (j+1))) := + future_form_monotone (weightedFuture F M) z n h g (weightedFuture_nonnegative F M hF) + +/-- Exchange the current and future pairs, leaving all old coordinates +fixed. This makes the common summation domain explicit. -/ +def swapPairs : ((I ⊕ Bool) ⊕ Bool) ≃ ((I ⊕ Bool) ⊕ Bool) where + toFun + | .inl (.inl i) => .inl (.inl i) + | .inl (.inr b) => .inr b + | .inr b => .inl (.inr b) + invFun + | .inl (.inl i) => .inl (.inl i) + | .inl (.inr b) => .inr b + | .inr b => .inl (.inr b) + left_inv x := by rcases x with (i | b) | b <;> rfl + right_inv x := by rcases x with (i | b) | b <;> rfl + +omit [Fintype I] [DecidableEq I] in +lemma profile_swap (z : I → ℕ) (j k a b : ℕ) : + (fun t => profile (profile z a b) j k (swapPairs t)) = + profile (profile z j k) a b := by + funext t + rcases t with (i | c) | c <;> rfl + +omit [Fintype I] [DecidableEq I] in +/-- The weighted future sum and the current balanced sum commute on +one fixed set of complete configurations. -/ +theorem weightedFuture_marginal_commute + (F : (((I ⊕ Bool) ⊕ Bool) → ℕ) → ℝ) (U M : ℕ) (z : I → ℕ) : + marginal (weightedFuture F M) U z = + weightedFuture (marginal (fun v => F (fun t => v (swapPairs t))) U) M z := by + unfold marginal weightedFuture + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro j _ + dsimp only + rw [profile_swap] + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureSquare.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureSquare.lean new file mode 100644 index 0000000000000000000000000000000000000000..0446d9d8fa340bfa51eb8bff927c10f741be1646 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerFutureSquare.lean @@ -0,0 +1,248 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerWeightedTransport + +namespace OAI + +/-! # The integer transport recursion's future square identity + +The three new--new removal entries partition by the same resulting pair. +Their coefficients give an exact nonnegative square, without a signature +assumption on the weighted future form. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +lemma sum_range_shift (n s : ℕ) (f : ℕ → ℝ) : + (∑ j ∈ Finset.range (n+s), if s ≤ j then f (j-s) else 0) = + ∑ k ∈ Finset.range n, f k := by + rw [Nat.add_comm n s, Finset.sum_range_add] + have hz : (∑ j ∈ Finset.range s, if s ≤ j then f (j-s) else 0) = 0 := by + apply Finset.sum_eq_zero + intro j hj + simp [show ¬s ≤ j by have := Finset.mem_range.mp hj; omega] + rw [hz, zero_add] + apply Finset.sum_congr rfl + intro j _ + simp + +lemma sum_range_truncate (n s : ℕ) (f : ℕ → ℝ) : + (∑ j ∈ Finset.range (n+s), if j < n then f j else 0) = + ∑ k ∈ Finset.range n, f k := by + rw [Finset.sum_range_add] + have hz : (∑ j ∈ Finset.range s, if n+j < n then f (n+j) else 0) = 0 := by + apply Finset.sum_eq_zero + intro j _ + simp + rw [hz, add_zero] + apply Finset.sum_congr rfl + intro j hj + simp [Finset.mem_range.mp hj] + +lemma sum_middle_shift (n : ℕ) (f : ℕ → ℝ) : + (∑ j ∈ Finset.range (n+3), if 1 ≤ j ∧ j ≤ n+1 then f (j-1) else 0) = + ∑ k ∈ Finset.range (n+1), f k := by + rw [show n+3 = (n+2)+1 by omega, Finset.sum_range_succ] + simp only [show ¬(1 ≤ n+2 ∧ n+2 ≤ n+1) by omega, ite_false, add_zero] + convert sum_range_shift (n+1) 1 f using 1 + apply Finset.sum_congr rfl + intro j hj + have hjn := Finset.mem_range.mp hj + simp [show j ≤ n+1 by omega] + +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] in +lemma future_aa (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n j : ℕ) : + pairMatrix F (n+2) z j (.inr false) (.inr false) = + if 2 ≤ j then F (profile z (j-2) (n+2-j)) else 0 := by + have hv : ValidPair (profile z j (n+2-j)) (.inr false) (.inr false) ↔ 2 ≤ j := by + simp [ValidPair, profile]; omega + unfold IntegerMarginal.pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeAA] + +omit [Fintype I] in +lemma future_bb (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n j : ℕ) : + pairMatrix F (n+2) z j (.inr true) (.inr true) = + if j ≤ n then F (profile z j (n-j)) else 0 := by + have hv : ValidPair (profile z j (n+2-j)) (.inr true) (.inr true) ↔ j ≤ n := by + simp [ValidPair, profile]; omega + unfold IntegerMarginal.pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeBB] + split_ifs <;> congr 1 + congr 1 + omega + +omit [Fintype I] in +lemma future_ab (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n j : ℕ) : + pairMatrix F (n+2) z j (.inr false) (.inr true) = + if 1 ≤ j ∧ j ≤ n+1 then F (profile z (j-1) (n+1-j)) else 0 := by + have hv : ValidPair (profile z j (n+2-j)) (.inr false) (.inr true) ↔ + 1 ≤ j ∧ j ≤ n+1 := by + simp [ValidPair, profile]; omega + unfold IntegerMarginal.pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeAB] + split_ifs <;> congr 1 + congr 1 + omega + +omit [Fintype I] in +/-- The exact new--new part of the future correction: two diagonal +removals and the mixed removal of the same integer pair form a square. -/ +theorem future_new_square + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n : ℕ) (g : ℕ → ℝ) : + (∑ j ∈ Finset.range (n+3), + (pairMatrix F (n+2) z j (.inr false) (.inr false) * g j ^ 2 - + 2 * pairMatrix F (n+2) z j (.inr false) (.inr true) * g j * g (j+1) + + pairMatrix F (n+2) z j (.inr true) (.inr true) * g (j+1) ^ 2)) = + ∑ k ∈ Finset.range (n+1), F (profile z k (n-k)) * (g (k+2)-g (k+1)) ^ 2 := by + have haa : (∑ j ∈ Finset.range (n+3), + pairMatrix F (n+2) z j (.inr false) (.inr false) * g j ^ 2) = + ∑ k ∈ Finset.range (n+1), F (profile z k (n-k)) * g (k+2) ^ 2 := by + convert sum_range_shift (n+1) 2 (fun k => F (profile z k (n-k)) * g (k+2)^2) using 1 + apply Finset.sum_congr rfl + intro j _ + rw [future_aa] + split_ifs with hj + · rw [show j-2+2 = j by omega, show n-(j-2) = n+2-j by omega] + · simp + have hbb : (∑ j ∈ Finset.range (n+3), + pairMatrix F (n+2) z j (.inr true) (.inr true) * g (j+1) ^ 2) = + ∑ k ∈ Finset.range (n+1), F (profile z k (n-k)) * g (k+1) ^ 2 := by + convert sum_range_truncate (n+1) 2 (fun k => F (profile z k (n-k)) * g (k+1)^2) using 1 + apply Finset.sum_congr rfl + intro j _ + rw [future_bb] + by_cases hj : j ≤ n + · simp [hj, show j < n+1 by omega] + · simp [hj, show ¬j < n+1 by omega] + have hab : (∑ j ∈ Finset.range (n+3), + 2 * pairMatrix F (n+2) z j (.inr false) (.inr true) * g j * g (j+1)) = + ∑ k ∈ Finset.range (n+1), 2 * F (profile z k (n-k)) * g (k+1) * g (k+2) := by + convert sum_middle_shift n (fun k => 2 * F (profile z k (n-k)) * g (k+1) * g (k+2)) using 1 + apply Finset.sum_congr rfl + intro j _ + rw [future_ab] + split_ifs with hj + · rw [show j-1+1 = j by omega, show j-1+2 = j+1 by omega, + show n-(j-1) = n+1-j by omega] + · simp + rw [Finset.sum_add_distrib, Finset.sum_sub_distrib, haa, hab, hbb, + ← Finset.sum_sub_distrib, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro k _ + ring + +omit [Fintype I] in +/-- Every kernel entry has the same complete configuration; positivity +alone makes the future correction nonnegative. -/ +theorem future_new_nonnegative + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n : ℕ) (g : ℕ → ℝ) + (hF : ∀ p, 0 ≤ F p) : + 0 ≤ ∑ j ∈ Finset.range (n+3), + (pairMatrix F (n+2) z j (.inr false) (.inr false) * g j ^ 2 - + 2 * pairMatrix F (n+2) z j (.inr false) (.inr true) * g j * g (j+1) + + pairMatrix F (n+2) z j (.inr true) (.inr true) * g (j+1) ^ 2) := by + rw [future_new_square] + exact Finset.sum_nonneg (fun k _ => mul_nonneg (hF _) (sq_nonneg _)) + + +/-- The two mixed old--new sums telescope, including both invalid +endpoint removals. -/ +theorem future_mixed_cancel + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (M : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) : + (∑ j ∈ Finset.range (M+1), + ((pairMatrix F M z j).toBilin' (old h) (Pi.single (.inr false) 1) * g j - + (pairMatrix F M z j).toBilin' (old h) (Pi.single (.inr true) 1) * g (j+1))) = 0 := by + calc + _ = ∑ j ∈ Finset.range (M+1), (cross F M z j h * g j - + cross F M z (j+1) h * g (j+1)) := by + apply Finset.sum_congr rfl + intro j hj + have hjM : j ≤ M := by have := Finset.mem_range.mp hj; omega + rw [cross_a F M z j hjM, cross_b F M z j hjM] + _ = cross F M z 0 h * g 0 - cross F M z (M+1) h * g (M+1) := + Finset.sum_range_sub' (fun j => cross F M z j h * g j) (M+1) + _ = 0 := by simp [cross] + +/-- Old--old entries partition the parent's balanced marginal exactly. -/ +theorem future_old_sum + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (M : ℕ) (h : I → ℝ) : + (∑ j ∈ Finset.range (M+1), (pairMatrix F M z j).toBilin' (old h) (old h)) = + (integerRemovalMatrix (marginal F M) z).toBilin' h h := by + rw [marginal_old_block] + simp only [LinearMap.sum_apply, LinearMap.compl₁₂_apply] + + +noncomputable def extendCoefficients (h : I → ℝ) (a b : ℝ) : I ⊕ Bool → ℝ := + old h + a • Pi.single (.inr false) 1 - b • Pi.single (.inr true) 1 + + +omit [Fintype I] in +@[simp] lemma extendCoefficients_inl (h : I → ℝ) (a b : ℝ) (i : I) : + extendCoefficients h a b (.inl i) = h i := by + simp [extendCoefficients, old] + +omit [Fintype I] in +@[simp] lemma extendCoefficients_a (h : I → ℝ) (a b : ℝ) : + extendCoefficients h a b (.inr false) = a := by + simp [extendCoefficients, old] + +omit [Fintype I] in +@[simp] lemma extendCoefficients_b (h : I → ℝ) (a b : ℝ) : + extendCoefficients h a b (.inr true) = -b := by + simp [extendCoefficients, old] + +lemma extended_quadratic (B : Matrix (I ⊕ Bool) (I ⊕ Bool) ℝ) + (hB : ∀ i j, B i j = B j i) (h : I → ℝ) (a b : ℝ) : + B.toBilin' (extendCoefficients h a b) (extendCoefficients h a b) = + B.toBilin' (old h) (old h) + + 2 * (B.toBilin' (old h) (Pi.single (.inr false) 1) * a - + B.toBilin' (old h) (Pi.single (.inr true) 1) * b) + + (B (.inr false) (.inr false) * a^2 - + 2 * B (.inr false) (.inr true) * a * b + B (.inr true) (.inr true) * b^2) := by + have hs := matrix_bilin_symm B hB + unfold extendCoefficients + simp only [LinearMap.BilinForm.add_left, LinearMap.BilinForm.add_right, + LinearMap.BilinForm.sub_left, LinearMap.BilinForm.sub_right, + LinearMap.BilinForm.smul_left, LinearMap.BilinForm.smul_right] + rw [hs.eq (Pi.single (.inr false) 1) (old h), + hs.eq (Pi.single (.inr true) 1) (old h)] + simp only [Matrix.toBilin'_single] + rw [hB (.inr true) (.inr false)] + ring + +/-- Equation future-square of the first manuscript for actual integer +removal matrices. The parent is the balanced raw marginal. -/ +theorem future_square_identity + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) : + (∑ j ∈ Finset.range (n+3), + (pairMatrix F (n+2) z j).toBilin' + (extendCoefficients h (g j) (g (j+1))) (extendCoefficients h (g j) (g (j+1)))) - + (integerRemovalMatrix (marginal F (n+2)) z).toBilin' h h = + ∑ k ∈ Finset.range (n+1), F (profile z k (n-k)) * (g (k+2)-g (k+1))^2 := by + simp_rw [extended_quadratic (pairMatrix F (n+2) z _) (integerRemoval_symm F _) h] + rw [Finset.sum_add_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, + future_mixed_cancel, mul_zero, add_zero] + rw [show n+3 = (n+2)+1 by omega, future_old_sum] + rw [show n+2+1 = n+3 by omega, future_new_square] + ring + +/-- Processing an ordinary integer pair can only increase a future form. +No signature assertion about the weighted future kernel is required. -/ +theorem future_form_monotone + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (n : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) (hF : ∀ p, 0 ≤ F p) : + (integerRemovalMatrix (marginal F (n+2)) z).toBilin' h h ≤ + ∑ j ∈ Finset.range (n+3), (pairMatrix F (n+2) z j).toBilin' + (extendCoefficients h (g j) (g (j+1))) (extendCoefficients h (g j) (g (j+1))) := by + apply sub_nonneg.mp + rw [future_square_identity] + exact Finset.sum_nonneg (fun k _ => mul_nonneg (hF _) (sq_nonneg _)) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerGraphTruncation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerGraphTruncation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba4365efb471ffdaea3d8f1596a4356ed4e5066f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerGraphTruncation.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTruncatedTransport + +namespace OAI + +/-! # The zero-extended energy is the actual box-restricted graph energy -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open IntegerBoxTruncation BalancedBox + +variable {C : Type*} [Fintype C] [DecidableEq C] + +theorem graphEnergy_truncate (V : Finset (C → ℕ)) (f H : (C → ℕ) → ℝ) + (m : C → ℕ) (R : ℕ) (hf : ∀ x, 0 ≤ f x) : + integerGraphEnergy V (truncate f m R) H= + integerGraphEnergy (V.filter (fun x => InBox m x ∧ (∑ i, x i)=R)) f H := by + unfold integerGraphEnergy + rw [←Finset.filter_product,Finset.filter_filter] + simp only [Finset.sum_filter] + congr 1 + apply Finset.sum_congr rfl + intro e _ + by_cases ha : IntegerExchangeAdjacent e.1 e.2 + · by_cases hx : InBox m e.1 ∧ (∑ i, e.1 i)=R + · by_cases hy : InBox m e.2 ∧ (∑ i, e.2 i)=R + · simp only [ha,hx,hy,↓reduceIte,and_self,edgeTerm,truncate] + · simp [ha,hx,hy,edgeTerm,truncate,min_eq_right (hf e.1)] + · by_cases hy : InBox m e.2 ∧ (∑ i, e.2 i)=R + · simp [ha,hx,hy,edgeTerm,truncate,min_eq_left (hf e.2)] + · simp [ha,hx,hy,edgeTerm,truncate] + · simp only [ha,and_false,↓reduceIte] + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..a20150114d3646ac04bb407841d4754ec1c4bcef --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLaw.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPropagation +import OAI.Combinatorics.ContingencyTables.Transport.RationalProducts + +namespace OAI + +/-! # Integer counts for the finite stages of law tabulation -/ + +namespace ContingencyTables +open scoped BigOperators + +/-- Counts of equally likely slots. The denominator is explicit so that +composition can reserve ignored bits without enumerating them. -/ +structure IntegerLaw (A : Type*) [Fintype A] (Q : ℕ) where + count : A → ℕ + total : ∑ a,count a=Q + +namespace IntegerLaw +open ResidualMixture FirstSuccess +open scoped Classical +noncomputable section +variable {A B : Type*} [Fintype A] [Fintype B] {Q P : ℕ} + +def toRational (p : IntegerLaw A Q) (hQ : 0 hQ i))= + piLaw (fun i => (p i).toRational (hQ i)) := by + apply RationalLaw.ext + funext x + change ((∏ i,(p i).count (x i):ℕ):ℚ)/(∏ i,Q i)=∏ i,((p i).count (x i):ℚ)/Q i + rw [Nat.cast_prod,Finset.prod_div_distrib,Nat.cast_prod] + +def point [DecidableEq A] (Q : ℕ) (a : A) : IntegerLaw A Q where + count b := if b=a then Q else 0 + total := by simp + +def push [DecidableEq B] (p : IntegerLaw A Q) (f : A → B) : IntegerLaw B Q where + count b := ∑ a,if f a=b then p.count a else 0 + total := by + rw [Finset.sum_comm] + simpa using p.total + +def bind (p : IntegerLaw A Q) (K : A → IntegerLaw B P) : IntegerLaw B (Q*P) where + count b := ∑ a,p.count a*(K a).count b + total := by + rw [Finset.sum_comm] + simp only [←Finset.mul_sum,(K _).total,←Finset.sum_mul,p.total] + +def product (p : IntegerLaw A Q) (q : IntegerLaw B P) : IntegerLaw (A×B) (Q*P) where + count x := p.count x.1*q.count x.2 + total := by + rw [Fintype.sum_prod_type] + simp only [←Finset.mul_sum,q.total,←Finset.sum_mul,p.total] + +theorem toRational_product (p : IntegerLaw A Q) (q : IntegerLaw B P) + (hQ : 0 simp + +theorem toRational_bind (p : IntegerLaw A Q) (K : A → IntegerLaw B P) + (hQ : 0 (K a).toRational hP) := by + apply RationalLaw.ext + funext b + change ((∑ a,p.count a*(K a).count b:ℕ):ℚ)/((Q*P:ℕ):ℚ)= + ∑ a,((p.count a:ℚ)/Q)*(((K a).count b:ℚ)/P) + rw [Nat.cast_sum,Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + push_cast + exact (div_mul_div_comm (p.count a:ℚ) Q ((K a).count b) P).symm + +theorem toRational_point [DecidableEq A] (Q : ℕ) (hQ : 0 if a=fallback then 1 else 0 + | N+1,a => p.count (some a)*Q^N+p.count none*retryCount p fallback N a + +lemma retryCount_total (p : IntegerLaw (Option A) Q) (fallback : A) (N : ℕ) : + ∑ a,retryCount p fallback N a=Q^N := by + induction N with + | zero => simp [retryCount] + | succ N ih => + have ht:=p.total + rw [Fintype.sum_option] at ht + simp only [retryCount,Finset.sum_add_distrib,←Finset.sum_mul,←Finset.mul_sum,ih] + rw [←add_mul,add_comm,ht,pow_succ'] + +def retry (p : IntegerLaw (Option A) Q) (fallback : A) (N : ℕ) : IntegerLaw A (Q^N) := + ⟨retryCount p fallback N,retryCount_total p fallback N⟩ + +/-- First-success sums are evaluated in integers with a reserved common +denominator. No division by the acceptance probability occurs. -/ +theorem toRational_retry (p : IntegerLaw (Option A) Q) (hQ : 0 simp [retry,toRational,retryCount,retryLaw,pointLaw] + | succ N ih => + rw [retryLaw,retryStep_mass] + simp only [successMass,failureMass,id_eq,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + simp only [retry,toRational,retryCount,Nat.cast_add,Nat.cast_mul,Nat.cast_pow] at ih ⊢ + rw [←ih] + rw [pow_succ] + field_simp [show (Q:ℚ)≠0 by exact_mod_cast hQ.ne'] + +end +end IntegerLaw +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLawEmbedding.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLawEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc1180f473dcdb8307ff549b704fb624f9fca3ac --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLawEmbedding.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerEquivLaw + +namespace OAI + +/-! # Propagating a finite law inside a larger executable state box -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical +noncomputable section + +variable {A B : Type*} [Fintype A] [Fintype B] [DecidableEq A] [DecidableEq B] +variable {Q : ℕ} + +lemma push_count_injective (p : IntegerLaw A Q) (f : A → B) + (hf : Function.Injective f) (a : A) : (p.push f).count (f a)=p.count a := by + change (∑ x,if f x=f a then p.count x else 0)=_ + simp only [hf.eq_iff,Finset.sum_ite_eq',Finset.mem_univ,ite_true] + +/-- A transition matrix may contain unused box states. Starting in the +embedded state set gives exactly the pushed-forward original walk. -/ +theorem walk_push_count (K : A → IntegerLaw A Q) (L : B → IntegerLaw B Q) + (f : A → B) (hf : ∀ x,L (f x)=(K x).push f) (start : A) (N : ℕ) (b : B) : + (walk L (f start) N).count b=((walk K start N).push f).count b := by + induction N generalizing b with + | zero => + change (if b=f start then 1 else 0)=∑ a,if f a=b then (if a=start then 1 else 0) else 0 + have he (a : A) : (if f a=b then (if a=start then 1 else 0) else 0)= + if a=start then (if f start=b then 1 else 0) else 0 := by + by_cases h : a=start <;> simp [h] + simp_rw [he] + simp [eq_comm] + | succ N ih => + change (∑ y,(walk L (f start) N).count y*(L y).count b)= + ∑ a,if f a=b then (∑ x,(walk K start N).count x*(K x).count a) else 0 + simp_rw [ih] + change (∑ y,(∑ x,if f x=y then (walk K start N).count x else 0)*(L y).count b)=_ + simp_rw [Finset.sum_mul,ite_mul,zero_mul] + rw [Finset.sum_comm] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + simp_rw [hf] + change (∑ x,(walk K start N).count x*(∑ a,if f a=b then (K x).count a else 0))=_ + simp_rw [Finset.mul_sum,mul_ite,mul_zero] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp + +end +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafEnergy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..84e8b64c5c033d7c0e3c549f2f7a9095e927e2e6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafEnergy.lean @@ -0,0 +1,261 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerRecursiveFlow + +namespace OAI + +/-! # The actual leaf energy as a finite sum of complete displays -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open FactorialSignatures BalancedFamily BalancedEnumeration IntegerMarginal + +universe u + +noncomputable def leafClique {C : Type*} [Fintype C] [DecidableEq C] + (F H : (C → ℕ) → ℝ) (z : C → ℕ) : ℝ := + SignedTransport.cliqueEnergy (oneHole F z) (fun _ => 1) (fun i => H (removeOne z i)) + +lemma oneHole_reindex {C D : Type*} [DecidableEq C] [DecidableEq D] + (e : C ≃ D) (F : (D → ℕ) → ℝ) (z : C → ℕ) (i : C) : + oneHole (fun x => F (x ∘ e.symm)) z i = oneHole F (z ∘ e.symm) (e i) := by + unfold oneHole + simp only [Function.comp_apply, Equiv.symm_apply_apply, removeOne_reindex] + +lemma leafClique_reindex {C D : Type*} [Fintype C] [Fintype D] + [DecidableEq C] [DecidableEq D] (e : C ≃ D) (F H : (D → ℕ) → ℝ) (z : C → ℕ) : + leafClique (fun x => F (x ∘ e.symm)) (fun x => H (x ∘ e.symm)) z = + leafClique F H (z ∘ e.symm) := by + unfold leafClique SignedTransport.cliqueEnergy + simp only [one_mul, oneHole_reindex, removeOne_reindex] + congr 1 + calc + _ = ∑ i : C, ∑ j : D, + min (oneHole F (z ∘ e.symm) (e i)) (oneHole F (z ∘ e.symm) j) * + (H (removeOne (z ∘ e.symm) (e i))-H (removeOne (z ∘ e.symm) j))^2 := by + apply Finset.sum_congr rfl + intro i _ + exact e.sum_comp (fun j : D => + min (oneHole F (z ∘ e.symm) (e i)) (oneHole F (z ∘ e.symm) j) * + (H (removeOne (z ∘ e.symm) (e i))-H (removeOne (z ∘ e.symm) j))^2) + _ = _ := e.sum_comp (fun i : D => ∑ j : D, + min (oneHole F (z ∘ e.symm) i) (oneHole F (z ∘ e.symm) j) * + (H (removeOne (z ∘ e.symm) i)-H (removeOne (z ∘ e.symm) j))^2) + +noncomputable def leafEnergySum {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) : ℝ := + ∑ a : Assignments Ms, leafClique F H (embedding Ms z a) + +/-- Every recursive leaf is exactly its literal full display, counted +once in the Cartesian product of the ordinary balanced profiles. -/ +theorem recursiveEnergy_eq_leafEnergySum : ∀ (Ms : List ℕ) {I : Type u} + [Fintype I] [DecidableEq I] (F H : (Coordinates I Ms → ℕ) → ℝ) + (z : I → ℕ) (h : I → ℝ), + recursiveEnergy Ms F H z h=leafEnergySum Ms F H z := by + intro Ms + induction Ms with + | nil => + intro I _ _ F H z h + simp only [recursiveEnergy, leafEnergySum, Assignments, embedding, Fintype.sum_unique, leafClique] + | cons U Ms ih => + intro I _ _ F H z h + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + change (∑ j : Fin (U+1), recursiveEnergy Ms + (fun x => F (x ∘ (exposeEquiv (I := I) Ms).symm)) + (fun x => H (x ∘ (exposeEquiv (I := I) Ms).symm)) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1)))) = _ + simp_rw [ih] + unfold leafEnergySum + simp_rw [leafClique_reindex] + have he (j : Fin (U+1)) (a : Assignments Ms) : + embedding Ms (profile z j.val (U-j.val)) a ∘ (exposeEquiv (I := I) Ms).symm = + profile (embedding Ms z a) j.val (U-j.val) := + expose_embedding Ms z j.val (U-j.val) a + simp_rw [he] + rw [Finset.sum_comm] + change (∑ a : Assignments Ms, ∑ j : Fin (U+1), + leafClique F H (profile (embedding Ms z a) j.val (U-j.val))) = + ∑ a : Assignments Ms × Fin (U+1), leafClique F H (embedding (U::Ms) z a) + rw [Fintype.sum_prod_type] + rfl + +lemma embedding_injective {I : Type u} (Ms : List ℕ) (z : I → ℕ) : + Function.Injective (embedding Ms z) := by + induction Ms with + | nil => intro a b _; exact Subsingleton.elim _ _ + | cons U Ms ih => + intro a b hab + apply Prod.ext + · apply ih + funext i + exact congrFun hab (.inl i) + · apply Fin.ext + exact congrFun hab (.inr false) + +/-- Distinct valid holes recover their full display by the coordinate +maximum. This is the reason different leaf cliques share no edges. -/ +lemma max_removeOne {C : Type*} [DecidableEq C] (z : C → ℕ) (i j : C) + (hij : i ≠ j) : + (fun k => max (removeOne z i k) (removeOne z j k))=z := by + funext k + unfold removeOne + by_cases hki : k=i + · subst k + simp only [hij, ↓reduceIte, Nat.sub_zero] + exact max_eq_right (Nat.sub_le _ _) + · by_cases hkj : k=j + · subst k + simp only [hki, ↓reduceIte, Nat.sub_zero] + exact max_eq_left (Nat.sub_le _ _) + · simp only [hki,hkj,↓reduceIte,Nat.sub_zero,max_self] + +lemma removeOne_injective_valid {C : Type*} [DecidableEq C] (z : C → ℕ) + (i j : C) (hi : 0 < z i) (he : removeOne z i=removeOne z j) : i=j := by + by_contra hij + have h := congrFun he i + simp only [removeOne, hij, ↓reduceIte, Nat.sub_zero] at h + omega + +def leafEdgeCodes {I : Type u} [Fintype I] [DecidableEq I] (Ms : List ℕ) (z : I → ℕ) : + Finset (Assignments Ms × Coordinates I Ms × Coordinates I Ms) := + Finset.univ.filter (fun e => 0 < embedding Ms z e.1 e.2.1 ∧ + 0 < embedding Ms z e.1 e.2.2 ∧ e.2.1 ≠ e.2.2) + +def leafEdgeState {I : Type u} [DecidableEq I] (Ms : List ℕ) (z : I → ℕ) + (e : Assignments Ms × Coordinates I Ms × Coordinates I Ms) : + (Coordinates I Ms → ℕ) × (Coordinates I Ms → ℕ) := + (removeOne (embedding Ms z e.1) e.2.1, removeOne (embedding Ms z e.1) e.2.2) + +/-- An oriented exchange edge determines its display, then its branch +assignment, then its two hole coordinates. -/ +theorem leafEdgeState_injective {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (z : I → ℕ) : + Set.InjOn (leafEdgeState Ms z) (leafEdgeCodes Ms z) := by + intro a ha b hb he + obtain ⟨hai,haj,haij⟩ := (Finset.mem_filter.mp ha).2 + obtain ⟨hbi,hbj,hbij⟩ := (Finset.mem_filter.mp hb).2 + have hd : embedding Ms z a.1=embedding Ms z b.1 := by + calc + _ = fun k => max ((leafEdgeState Ms z a).1 k) ((leafEdgeState Ms z a).2 k) := + (max_removeOne _ _ _ haij).symm + _ = fun k => max ((leafEdgeState Ms z b).1 k) ((leafEdgeState Ms z b).2 k) := by rw [he] + _ = _ := max_removeOne _ _ _ hbij + have hab := embedding_injective Ms z hd + apply Prod.ext hab + apply Prod.ext + · apply removeOne_injective_valid (embedding Ms z a.1) _ _ hai + have ht := congrArg Prod.fst he + change removeOne (embedding Ms z a.1) a.2.1=removeOne (embedding Ms z b.1) b.2.1 at ht + simpa only [←hab] using ht + · apply removeOne_injective_valid (embedding Ms z a.1) _ _ haj + have ht := congrArg Prod.snd he + change removeOne (embedding Ms z a.1) a.2.2=removeOne (embedding Ms z b.1) b.2.2 at ht + simpa only [←hab] using ht + +noncomputable def leafEdges {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (z : I → ℕ) : + Finset ((Coordinates I Ms → ℕ) × (Coordinates I Ms → ℕ)) := + (leafEdgeCodes Ms z).image (leafEdgeState Ms z) + +noncomputable def edgeTerm {C : Type*} (F H : (C → ℕ) → ℝ) + (e : (C → ℕ) × (C → ℕ)) : ℝ := + min (F e.1) (F e.2) * (H e.1-H e.2)^2 + +lemma leafClique_eq_valid_sum {C : Type*} [Fintype C] [DecidableEq C] + (F H : (C → ℕ) → ℝ) (z : C → ℕ) (hF : ∀ x, 0 ≤ F x) : + leafClique F H z = (∑ i, ∑ j, + if 0 < z i ∧ 0 < z j ∧ i ≠ j then + edgeTerm F H (removeOne z i,removeOne z j) else 0)/2 := by + unfold leafClique SignedTransport.cliqueEnergy + congr 1 + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + simp only [one_mul] + by_cases hij : i=j + · subst j + simp + · by_cases hi : 0 < z i + · by_cases hj : 0 < z j + · simp [oneHole,edgeTerm,hi,hj,hij] + · simp only [oneHole,hi,hj,↓reduceIte,and_false,false_and, + min_eq_right (hF _),zero_mul] + · have hj := oneHole_nonnegative F hF z j + simp only [oneHole,hi,↓reduceIte] at hj ⊢ + rw [min_eq_left hj] + simp + +/-- Complete leaf cliques have disjoint oriented edges. The resulting +energy is exactly the ordinary minimum-endpoint graph sum. -/ +theorem leafEnergySum_eq_edges {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) + (hF : ∀ x, 0 ≤ F x) : + leafEnergySum Ms F H z = (∑ e ∈ leafEdges Ms z, edgeTerm F H e)/2 := by + unfold leafEnergySum + simp_rw [leafClique_eq_valid_sum F H _ hF] + rw [← Finset.sum_div] + congr 1 + rw [leafEdges, Finset.sum_image (leafEdgeState_injective Ms z)] + unfold leafEdgeCodes + rw [Finset.sum_filter] + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + rw [Fintype.sum_prod_type] + rfl + +def IntegerExchangeAdjacent {C : Type*} [DecidableEq C] (X Y : C → ℕ) : Prop := + ∃ (D : C → ℕ) (i j : C), i ≠ j ∧ 0 < D i ∧ 0 < D j ∧ + X=removeOne D i ∧ Y=removeOne D j + +noncomputable def integerGraphEnergy {C : Type*} [DecidableEq C] + (V : Finset (C → ℕ)) (F H : (C → ℕ) → ℝ) : ℝ := + (∑ e ∈ (V ×ˢ V).filter (fun e => IntegerExchangeAdjacent e.1 e.2), edgeTerm F H e)/2 + +noncomputable def leafVertices {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (z : I → ℕ) : Finset (Coordinates I Ms → ℕ) := + Finset.univ.biUnion (fun a : Assignments Ms => + (Finset.univ.filter (fun i => 0 < embedding Ms z a i)).image + (fun i => removeOne (embedding Ms z a) i)) + +lemma leafEdges_states_adjacent {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (z : I → ℕ) (e : (Coordinates I Ms → ℕ) × (Coordinates I Ms → ℕ)) + (he : e ∈ leafEdges Ms z) : + e.1 ∈ leafVertices Ms z ∧ e.2 ∈ leafVertices Ms z ∧ IntegerExchangeAdjacent e.1 e.2 := by + obtain ⟨a,ha,rfl⟩ := Finset.mem_image.mp he + obtain ⟨hi,hj,hij⟩ := (Finset.mem_filter.mp ha).2 + have hv (i : Coordinates I Ms) (h : 0 < embedding Ms z a.1 i) : + removeOne (embedding Ms z a.1) i ∈ leafVertices Ms z := by + apply Finset.mem_biUnion.mpr + refine ⟨a.1,Finset.mem_univ _,?_⟩ + exact Finset.mem_image.mpr ⟨i,Finset.mem_filter.mpr ⟨Finset.mem_univ _,h⟩,rfl⟩ + exact ⟨hv _ hi,hv _ hj,embedding Ms z a.1,a.2.1,a.2.2,hij,hi,hj,rfl,rfl⟩ + +/-- The full exchange graph may contain further edges; their energies +are nonnegative. Every leaf edge occurs once in this graph. -/ +theorem leafEnergySum_le_graphEnergy {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) + (hF : ∀ x, 0 ≤ F x) (V : Finset (Coordinates I Ms → ℕ)) + (hV : leafVertices Ms z ⊆ V) : + leafEnergySum Ms F H z ≤ integerGraphEnergy V F H := by + rw [leafEnergySum_eq_edges Ms F H z hF] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum_of_subset_of_nonneg + · intro e he + obtain ⟨hx,hy,hadj⟩ := leafEdges_states_adjacent Ms z e he + exact Finset.mem_filter.mpr ⟨Finset.mem_product.mpr ⟨hV hx,hV hy⟩,hadj⟩ + · intro e _ _ + exact mul_nonneg (le_min (hF _) (hF _)) (sq_nonneg _) + +theorem recursiveEnergy_le_graphEnergy {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ) + (hF : ∀ x, 0 ≤ F x) (V : Finset (Coordinates I Ms → ℕ)) + (hV : leafVertices Ms z ⊆ V) : + recursiveEnergy Ms F H z h ≤ integerGraphEnergy V F H := by + rw [recursiveEnergy_eq_leafEnergySum] + exact leafEnergySum_le_graphEnergy Ms F H z hF V hV + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b0cefd7421602a40b56a605a8711e2ccf2ffd32 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerLeafTransport.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPairRecursion +import OAI.Combinatorics.ContingencyTables.Transport.SignedTransport + +namespace OAI + +/-! # Integer leaf cliques, allowing invalid holes of zero weight -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open SignedTransport + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- The leaf-clique estimate for raw masses. Invalid removals may have +zero mass; no artificial positive weight is assigned to those vertices. -/ +theorem raw_leaf_transport (m h H : I → ℝ) (hm : ∀ i, 0 ≤ m i) + (hbalance : ∑ i, m i * h i = 0) : + (∑ i, m i * h i * H i) ^ 2 ≤ + (∑ i, m i * h i ^ 2) * cliqueEnergy m (fun _ => 1) H := by + cases isEmpty_or_nonempty I with + | inl he => simp [cliqueEnergy] + | inr hn => + obtain ⟨hub, _, hhub⟩ := Finset.exists_max_image Finset.univ m Finset.univ_nonempty + have hdemand : (∑ i, m i * h i * (H i-H hub)) = ∑ i, m i * h i * H i := by + simp only [mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul, hbalance, + zero_mul, sub_zero] + have hcs : (∑ i, m i * h i * (H i-H hub)) ^ 2 ≤ + (∑ i, m i * h i ^ 2) * ∑ i, m i * (H i-H hub) ^ 2 := by + apply Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul Finset.univ + · intro i _ + exact mul_nonneg (hm i) (sq_nonneg _) + · intro i _ + exact mul_nonneg (hm i) (sq_nonneg _) + · intro i _ + exact le_of_eq (by ring) + have hstar : (∑ i, m i * (H i-H hub) ^ 2) ≤ cliqueEnergy m (fun _ => 1) H := by + have hs := star_energy_le + (fun i j => min (m i) (m j) * (H i-H j)^2) + (fun i j => mul_nonneg (le_min (hm i) (hm j)) (sq_nonneg _)) + (by intro i j; rw [min_comm]; ring) (by intro i; simp) hub + simp_rw [min_eq_left (hhub _ (Finset.mem_univ _))] at hs + simpa only [cliqueEnergy, one_mul] using hs + rw [hdemand] at hcs + exact hcs.trans (mul_le_mul_of_nonneg_left hstar + (Finset.sum_nonneg (fun i _ => mul_nonneg (hm i) (sq_nonneg _)))) + +/-- Instantiation at the actual one-removal weights of an integer display. -/ +theorem integer_leaf_transport (F : (I → ℕ) → ℝ) (z : I → ℕ) + (h H : I → ℝ) (hF : ∀ p, 0 ≤ F p) + (hbalance : ∑ i, oneHole F z i * h i = 0) : + (∑ i, oneHole F z i * h i * H i)^2 ≤ + holePotential F z h * cliqueEnergy (oneHole F z) (fun _ => 1) H := by + exact raw_leaf_transport (oneHole F z) h H + (fun i => by unfold oneHole; split_ifs; exact hF _; exact le_rfl) hbalance + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMarginal.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4a497884a0c6f0abd382883b78eda2b522132c0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMarginal.lean @@ -0,0 +1,258 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedSummation +import OAI.Combinatorics.ContingencyTables.Transport.FactorialSignatures + +namespace OAI + +/-! +# Balanced marginalization of actual integer two-removal matrices + +The new pair is summed subject to its exact total M. We identify every +old, fresh and cross entry with the balanced summation theorem; thus the +signature of the marginal is derived from signatures of the actual unsummed +integer matrices, rather than assumed for a binary encoding. +-/ + +namespace ContingencyTables.IntegerMarginal + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures +open LinearMap (BilinForm) + +variable {I : Type*} [Fintype I] [DecidableEq I] + +def profile (z : I → ℕ) (a b : ℕ) : I ⊕ Bool → ℕ := + Sum.elim z (fun t => if t then b else a) + +noncomputable def marginal (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) : ℝ := + ∑ j ∈ Finset.range (M + 1), F (profile z j (M-j)) + +omit [Fintype I] in +lemma profile_removeOld (z : I → ℕ) (a b : ℕ) (i k : I) : + removeTwo (profile z a b) (.inl i) (.inl k) = profile (removeTwo z i k) a b := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + +omit [Fintype I] in +lemma profile_removeAA (z : I → ℕ) (a b : ℕ) : + removeTwo (profile z a b) (.inr false) (.inr false) = profile z (a-2) b := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + omega + +omit [Fintype I] in +lemma profile_removeBB (z : I → ℕ) (a b : ℕ) : + removeTwo (profile z a b) (.inr true) (.inr true) = profile z a (b-2) := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + omega + +omit [Fintype I] in +lemma profile_removeAB (z : I → ℕ) (a b : ℕ) : + removeTwo (profile z a b) (.inr false) (.inr true) = profile z (a-1) (b-1) := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + +omit [Fintype I] in +lemma profile_removeOldA (z : I → ℕ) (a b : ℕ) (i : I) : + removeTwo (profile z a b) (.inl i) (.inr false) = profile (removeOne z i) (a-1) b := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + +omit [Fintype I] in +lemma profile_removeOldB (z : I → ℕ) (a b : ℕ) (i : I) : + removeTwo (profile z a b) (.inl i) (.inr true) = profile (removeOne z i) a (b-1) := by + funext t + rcases t with i | (_ | _) <;> simp [profile,removeTwo,removeOne] + +noncomputable def old : (I → ℝ) →ₗ[ℝ] (I ⊕ Bool → ℝ) where + toFun v := Sum.elim v (fun _ => 0) + map_add' _ _ := by ext t; cases t <;> simp + map_smul' _ _ := by ext t; cases t <;> simp + +noncomputable def pairMatrix (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) : Matrix (I ⊕ Bool) (I ⊕ Bool) ℝ := + integerRemovalMatrix F (profile z j (M-j)) + +noncomputable def innerWeight (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) : ℝ := + if 0 < j ∧ j < M then F (profile z (j-1) (M-1-j)) else 0 + +noncomputable def cross (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) : (I → ℝ) →ₗ[ℝ] ℝ := + if 0 < j ∧ j ≤ M then + (pairMatrix F M z j).toBilin' |>.flip (Pi.single (.inr false) 1) |>.comp old + else 0 + +omit [Fintype I] in +lemma integerRemoval_symm (F : (I → ℕ) → ℝ) (z : I → ℕ) (i k : I) : + integerRemovalMatrix F z i k = integerRemovalMatrix F z k i := by + simp only [integerRemovalMatrix, validPair_symm z i k, removeTwo_comm z i k] + +omit [Fintype I] in +lemma pairMatrix_aa (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (hj : j ≤ M) : + pairMatrix F M z j (.inr false) (.inr false) = innerWeight F M z (j-1) := by + have hv : ValidPair (profile z j (M-j)) (.inr false) (.inr false) ↔ 2 ≤ j := by + simp [ValidPair,profile]; omega + unfold pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeAA] + unfold innerWeight + by_cases h : 2 ≤ j + · rw [ite_eq_left h, ite_eq_left (by omega)] + congr 1 + congr 1; omega + · rw [ite_eq_right h, ite_eq_right (by omega)] + +omit [Fintype I] in +lemma pairMatrix_bb (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (hj : j ≤ M) : + pairMatrix F M z j (.inr true) (.inr true) = innerWeight F M z (j+1) := by + have hv : ValidPair (profile z j (M-j)) (.inr true) (.inr true) ↔ j+2 ≤ M := by + simp [ValidPair,profile]; omega + unfold pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeBB] + unfold innerWeight + by_cases h : j+2 ≤ M + · rw [ite_eq_left h, ite_eq_left (by omega)] + congr 1 + congr 1; omega + · rw [ite_eq_right h, ite_eq_right (by omega)] + +omit [Fintype I] in +lemma pairMatrix_ab (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (_hj : j ≤ M) : + pairMatrix F M z j (.inr false) (.inr true) = innerWeight F M z j := by + have hv : ValidPair (profile z j (M-j)) (.inr false) (.inr true) ↔ 0 < j ∧ j < M := by + simp [ValidPair,profile] + unfold pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeAB] + unfold innerWeight + split_ifs + · congr 1; congr 1; omega + · rfl + +lemma old_single (B : Matrix (I ⊕ Bool) (I ⊕ Bool) ℝ) (v : I → ℝ) (t : Bool) : + B.toBilin' (old v) (Pi.single (.inr t) 1) = ∑ i, v i * B (.inl i) (.inr t) := by + simp [Matrix.toBilin'_apply, old, Fintype.sum_sum_type, Pi.single_apply] + +lemma old_old (B : Matrix (I ⊕ Bool) (I ⊕ Bool) ℝ) (v w : I → ℝ) : + B.toBilin' (old v) (old w) = (B.submatrix Sum.inl Sum.inl).toBilin' v w := by + simp [Matrix.toBilin'_apply, old, Fintype.sum_sum_type] + +lemma cross_a (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (hj : j ≤ M) (v : I → ℝ) : + (pairMatrix F M z j).toBilin' (old v) (Pi.single (.inr false) 1) = cross F M z j v := by + unfold cross + by_cases h : 0 < j + · rw [ite_eq_left ⟨h,hj⟩]; rfl + · rw [ite_eq_right (by omega)] + rw [old_single] + apply Finset.sum_eq_zero + intro i _ + have hv : ¬ValidPair (profile z j (M-j)) (.inl i) (.inr false) := by + simp [ValidPair,profile]; omega + simp [pairMatrix,integerRemovalMatrix,hv] + +lemma cross_b (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (hj : j ≤ M) (v : I → ℝ) : + (pairMatrix F M z j).toBilin' (old v) (Pi.single (.inr true) 1) = cross F M z (j+1) v := by + unfold cross + by_cases h : j < M + · rw [ite_eq_left (by omega)] + change _ = (pairMatrix F M z (j+1)).toBilin' (old v) (Pi.single (.inr false) 1) + rw [old_single,old_single] + apply Finset.sum_congr rfl + intro i _ + congr 1 + have hv : ValidPair (profile z j (M-j)) (.inl i) (.inr true) ↔ 0 < z i := by + simp [ValidPair,profile]; omega + have hv' : ValidPair (profile z (j+1) (M-(j+1))) (.inl i) (.inr false) ↔ 0 < z i := by + simp [ValidPair,profile] + unfold pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl,if_congr hv' rfl rfl,profile_removeOldB,profile_removeOldA] + simp only [Nat.add_sub_cancel,Nat.sub_sub] + · rw [ite_eq_right (by omega),old_single] + apply Finset.sum_eq_zero + intro i _ + have hv : ¬ValidPair (profile z j (M-j)) (.inl i) (.inr true) := by + simp [ValidPair,profile]; omega + simp [pairMatrix,integerRemovalMatrix,hv] + +omit [Fintype I] in +lemma pairMatrix_old (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) + (j : ℕ) (i k : I) : + pairMatrix F M z j (.inl i) (.inl k) = + if ValidPair z i k then F (profile (removeTwo z i k) j (M-j)) else 0 := by + have hv : ValidPair (profile z j (M-j)) (.inl i) (.inl k) ↔ ValidPair z i k := by + simp [ValidPair,profile] + unfold pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl,profile_removeOld] + +omit [Fintype I] in +lemma marginal_old_matrix (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) : + integerRemovalMatrix (marginal F M) z = + ∑ j ∈ Finset.range (M+1), (pairMatrix F M z j).submatrix Sum.inl Sum.inl := by + ext i k + simp only [Matrix.sum_apply,Matrix.submatrix_apply,pairMatrix_old,integerRemovalMatrix,marginal] + split_ifs <;> simp + +lemma marginal_old_block (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) : + (integerRemovalMatrix (marginal F M) z).toBilin' = + ∑ j ∈ Finset.range (M+1), (pairMatrix F M z j).toBilin'.compl₁₂ old old := by + rw [marginal_old_matrix] + simp only [map_sum] + apply Finset.sum_congr rfl + intro j _ + apply LinearMap.ext + intro v + apply LinearMap.ext + intro w + exact (old_old _ v w).symm + +/-- Exact balanced marginal closure for the paper's raw integer matrices. -/ +theorem marginal_removal_onePositive + (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) (hM : 2 ≤ M) + (hsig : ∀ j ≤ M, OnePositiveDirection (integerRemovalMatrix F (profile z j (M-j))).toBilin') + (hpos : ∀ j, 0 < j → j < M → 0 < F (profile z (j-1) (M-1-j))) : + OnePositiveDirection (integerRemovalMatrix (marginal F M) z).toBilin' := by + rw [marginal_old_block] + apply balancedPair_sum_onePositive M hM + (fun j => (pairMatrix F M z j).toBilin') old + (Pi.single (.inr false) 1) (Pi.single (.inr true) 1) (cross F M z) (innerWeight F M z) + · intro j _ x y + exact (matrix_bilin_symm _ (integerRemoval_symm _ _)).eq x y + · exact hsig + · simp [innerWeight] + · simp [innerWeight] + · simp [innerWeight] + · intro j hj0 hjM; simp [innerWeight,hj0,hjM,hpos j hj0 hjM] + · simp [cross] + · simp [cross] + · intro j hj; simpa using pairMatrix_aa F M z j hj + · intro j hj; simpa using pairMatrix_bb F M z j hj + · intro j hj; simpa using pairMatrix_ab F M z j hj + · exact cross_a F M z + · exact cross_b F M z + +/-- Equality-softening limits preserve the actual raw integer signature. +Only the finitely many displayed matrix entries are used. -/ +theorem removal_signature_limit {K : Type*} {l : Filter K} [l.NeBot] + (F : K → (I → ℕ) → ℝ) (f : (I → ℕ) → ℝ) (z : I → ℕ) + (hlim : ∀ n, Filter.Tendsto (fun t => F t n) l (nhds (f n))) + (hsig : ∀ᶠ t in l, OnePositiveDirection (integerRemovalMatrix (F t) z).toBilin') : + OnePositiveDirection (integerRemovalMatrix f z).toBilin' := by + apply (BinaryContraction.signature_iff _ (matrix_bilin_symm _ (integerRemoval_symm _ _))).mpr + apply onePositive_of_tendsto (l := l) (fun t => integerRemovalMatrix (F t) z) (integerRemovalMatrix f z) + · intro i j + by_cases h : ValidPair z i j + · simpa only [integerRemovalMatrix,h,ite_true] using hlim (removeTwo z i j) + · simpa only [integerRemovalMatrix,h,ite_false] using + (tendsto_const_nhds : Filter.Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + · intro t + exact integerRemoval_symm _ _ + · filter_upwards [hsig] with t ht + exact (BinaryContraction.signature_iff _ (matrix_bilin_symm _ (integerRemoval_symm _ _))).mp ht + +end ContingencyTables.IntegerMarginal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMatrixPoint.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMatrixPoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0684605f6b9980848067634bd55298fe03ecf45 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerMatrixPoint.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # Propagating an executable point mass through an integer matrix -/ + +namespace ContingencyTables.IntegerMatrixPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +def pointEntry (z : ℕ×ℕ) : ℕ := if z.2=z.1 then 1 else 0 + +def pointEntryRealizer : Realizer pointEntry := + (choose (composition (pair second first) natEqual) (constant 1) (constant 0)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq] + rfl) + +lemma polynomial_pointEntry : PolynomialTime pointEntryRealizer := by + unfold pointEntryRealizer + apply polynomial_congr + exact polynomial_choose (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) polynomial_natEqual) + (polynomial_constant 1) (polynomial_constant 0) + +def pointVector (z : List (List ℕ)×ℕ) : List ℕ := + (List.range z.1.length).map (fun j => pointEntry (z.2,j)) + +def pointVectorRealizer : Realizer pointVector := + composition (pair second (composition (composition first listLength) range)) + (mapWith pointEntryRealizer) + +lemma polynomial_pointVector : PolynomialTime pointVectorRealizer := by + unfold pointVectorRealizer + apply polynomial_composition _ (polynomial_mapWith polynomial_pointEntry) + apply polynomial_pair polynomial_second + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def fromPoint (z : ℕ×(List (List ℕ)×ℕ)) : List ℕ := + iterate (z.1,(z.2.1,pointVector z.2)) + +def fromPointInputRealizer : Realizer (fun z : ℕ×(List (List ℕ)×ℕ) => + (z.1,(z.2.1,pointVector z.2))) := + pair first (pair (composition second first) (composition second pointVectorRealizer)) + +def fromPointRealizer : Realizer fromPoint := + composition fromPointInputRealizer iterateRealizer + +lemma polynomial_fromPointInput : PolynomialTime fromPointInputRealizer := + polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_pointVector)) + +lemma work_fromPoint : WorkBound fromPointRealizer (fun z => z.1+weight z.2) := by + have hi : WorkBound fromPointInputRealizer (fun z => z.1+weight z.2) := + work_of_polynomial polynomial_fromPointInput (4*X+2) (by + intro z + have hn := weight_nat_numeric z.1 + rw [←Prod.eta z,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + omega) + obtain ⟨p,hp⟩ := hi + unfold fromPointRealizer + apply work_composition ⟨p,hp⟩ work_iterate (X+p) + intro z + have hz := hp z + dsimp only at hz + simp only [Polynomial.eval_add,Polynomial.eval_X] + change z.1+weight (z.2.1,pointVector z.2) ≤ _ + have hw : weight (z.2.1,pointVector z.2) ≤ weight (z.1,(z.2.1,pointVector z.2)) := + weight_snd (z.1,(z.2.1,pointVector z.2)) + omega + +lemma pointVector_ofFn {n : ℕ} (B : Fin n → Fin n → ℕ) (start : Fin n) : + pointVector (List.ofFn (fun j => List.ofFn (fun i => B i j)),start.val)= + List.ofFn (fun i : Fin n => if i=start then 1 else 0) := by + unfold pointVector + rw [List.length_ofFn] + apply List.ext_getElem + · simp + · intro i hi hj + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,pointEntry,Fin.ext_iff] + + +lemma fromPoint_ofFn {n : ℕ} (B : Fin n → Fin n → ℕ) (start : Fin n) (N : ℕ) : + fromPoint (N,(List.ofFn (fun j => List.ofFn (fun i => B i j)),start.val))= + List.ofFn (IntegerPropagation.numerators B start N) := by + unfold fromPoint + rw [pointVector_ofFn,iterate_ofFn] + +end ContingencyTables.IntegerMatrixPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPairRecursion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPairRecursion.lean new file mode 100644 index 0000000000000000000000000000000000000000..7df52f46429d6e9f2fea1a473a5e83a98245d463 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPairRecursion.lean @@ -0,0 +1,237 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerFutureSquare + +namespace OAI + +/-! # Balanced coefficients and the actual integer child potentials -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def oneHole (F : (I → ℕ) → ℝ) (z : I → ℕ) (i : I) : ℝ := + if 0 < z i then F (removeOne z i) else 0 + +omit [Fintype I] in +lemma profile_removeOne_old (z : I → ℕ) (a b : ℕ) (i : I) : + removeOne (profile z a b) (.inl i) = profile (removeOne z i) a b := by + funext t + rcases t with k | (_ | _) <;> simp [profile, removeOne] + +omit [Fintype I] in +lemma profile_removeOne_a (z : I → ℕ) (a b : ℕ) : + removeOne (profile z a b) (.inr false) = profile z (a-1) b := by + funext t + rcases t with k | (_ | _) <;> simp [profile, removeOne] + +omit [Fintype I] in +lemma profile_removeOne_b (z : I → ℕ) (a b : ℕ) : + removeOne (profile z a b) (.inr true) = profile z a (b-1) := by + funext t + rcases t with k | (_ | _) <;> simp [profile, removeOne] + +omit [Fintype I] in +lemma old_hole_sum (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (U : ℕ) (i : I) : + (∑ j ∈ Finset.range (U+1), oneHole F (profile z j (U-j)) (.inl i)) = + oneHole (marginal F U) z i := by + simp only [oneHole, profile_removeOne_old] + change (∑ j ∈ Finset.range (U+1), if 0 < z i then + F (profile (removeOne z i) j (U-j)) else 0) = + if 0 < z i then marginal F U (removeOne z i) else 0 + by_cases hp : 0 < z i <;> simp [hp, marginal] + +omit [Fintype I] in +lemma child_hole_a (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (U j : ℕ) (hj : j ≤ U) : + oneHole F (profile z j (U-j)) (.inr false) = innerWeight F (U+1) z j := by + unfold oneHole + rw [profile_removeOne_a] + change (if 0 < j then F (profile z (j-1) (U-j)) else 0) = _ + unfold innerWeight + by_cases hp : 0 < j + · rw [ite_eq_left hp, ite_eq_left (by omega)] + congr 1 + · rw [ite_eq_right hp, ite_eq_right (by omega)] + +omit [Fintype I] in +lemma child_hole_b (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (U j : ℕ) (hj : j ≤ U) : + oneHole F (profile z j (U-j)) (.inr true) = innerWeight F (U+1) z (j+1) := by + unfold oneHole + rw [profile_removeOne_b] + change (if 0 < U-j then F (profile z j (U-j-1)) else 0) = _ + unfold innerWeight + by_cases hp : j < U + · rw [ite_eq_left (by omega), ite_eq_left (by omega)] + simp only [Nat.add_sub_cancel] + congr 1 + · rw [ite_eq_right (by omega), ite_eq_right (by omega)] + +lemma child_old_signed_mass (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (U j : ℕ) (hj : j ≤ U) (h : I → ℝ) : + (∑ i, oneHole F (profile z j (U-j)) (.inl i) * h i) = cross F (U+1) z (j+1) h := by + rw [← cross_a F (U+1) z (j+1) (by omega), old_single] + apply Finset.sum_congr rfl + intro i _ + have hv : ValidPair (profile z (j+1) (U+1-(j+1))) (.inl i) (.inr false) ↔ 0 < z i := by + simp [ValidPair, profile] + unfold IntegerMarginal.pairMatrix integerRemovalMatrix + rw [if_congr hv rfl rfl, profile_removeOldA] + unfold oneHole + rw [profile_removeOne_old] + simp only [Nat.add_sub_cancel, Nat.add_sub_add_right] + change (if 0 < z i then F (profile (removeOne z i) j (U-j)) else 0) * h i = + h i * (if 0 < z i then F (profile (removeOne z i) j (U-j)) else 0) + exact mul_comm _ _ + +/-- The cumulative coefficients balance every integer child, including +zero-capacity endpoint removals. -/ +theorem integer_child_balance + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (U j : ℕ) (hj : j ≤ U) + (h : I → ℝ) + (hpos : ∀ k, 0 < k → k < U+1 → 0 < innerWeight F (U+1) z k) + (hbal : pairCumulative (cross F (U+1) z) h (U+1) = 0) : + let g := pairCoefficient (cross F (U+1) z) (innerWeight F (U+1) z) h + ∑ i : I ⊕ Bool, oneHole F (profile z j (U-j)) i * + extendCoefficients h (g j) (g (j+1)) i = 0 := by + dsimp only + simp only [Fintype.sum_sum_type, Fintype.sum_bool, extendCoefficients_inl, + extendCoefficients_a, extendCoefficients_b, mul_neg] + rw [child_old_signed_mass F z U j hj, child_hole_a F z U j hj, child_hole_b F z U j hj] + rw [pairCoefficient_represents_le _ _ (U+1) h hpos hbal (by omega), + pairCoefficient_represents_le _ _ (U+1) h hpos hbal (by omega)] + rw [pairCumulative_succ] + ring + + +noncomputable def holePotential (F : (I → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ) : ℝ := + ∑ i, oneHole F z i * h i ^ 2 + +lemma child_potential (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (U j : ℕ) (hj : j ≤ U) (h : I → ℝ) (g : ℕ → ℝ) : + holePotential F (profile z j (U-j)) (extendCoefficients h (g j) (g (j+1))) = + (∑ i, oneHole F (profile z j (U-j)) (.inl i) * h i ^ 2) + + (innerWeight F (U+1) z j * g j ^ 2 + innerWeight F (U+1) z (j+1) * g (j+1) ^ 2) := by + simp only [holePotential, Fintype.sum_sum_type, Fintype.sum_bool, + extendCoefficients_inl, extendCoefficients_a, extendCoefficients_b, neg_sq] + rw [child_hole_a F z U j hj, child_hole_b F z U j hj] + ring + +/-- The old potential partitions and the two fresh-hole contributions +have identical sums, including both invalid endpoint holes. -/ +theorem integer_potential_increment + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (U : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) : + (∑ j ∈ Finset.range (U+1), + holePotential F (profile z j (U-j)) (extendCoefficients h (g j) (g (j+1)))) = + holePotential (marginal F U) z h + + 2 * ∑ j ∈ Finset.range (U+2), innerWeight F (U+1) z j * g j ^ 2 := by + have hold : (∑ j ∈ Finset.range (U+1), + ∑ i, oneHole F (profile z j (U-j)) (.inl i) * h i ^ 2) = + holePotential (marginal F U) z h := by + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul, old_hole_sum] + rfl + have hshift := Finset.sum_range_sub' + (fun j => innerWeight F (U+1) z j * g j ^ 2) (U+1) + rw [Finset.sum_sub_distrib] at hshift + have hz0 : innerWeight F (U+1) z 0 = 0 := by simp [innerWeight] + have hzM : innerWeight F (U+1) z (U+1) = 0 := by simp [innerWeight] + rw [hz0, hzM, zero_mul, zero_mul, sub_self] at hshift + have hend : (∑ j ∈ Finset.range (U+2), innerWeight F (U+1) z j * g j ^ 2) = + ∑ j ∈ Finset.range (U+1), innerWeight F (U+1) z j * g j ^ 2 := by + rw [show U+2 = (U+1)+1 by omega, Finset.sum_range_succ] + simp [innerWeight] + calc + _ = (∑ j ∈ Finset.range (U+1), + ((∑ i, oneHole F (profile z j (U-j)) (.inl i) * h i ^ 2) + + (innerWeight F (U+1) z j * g j ^ 2 + innerWeight F (U+1) z (j+1) * g (j+1) ^ 2))) := by + apply Finset.sum_congr rfl + intro j hj + exact child_potential F z U j (by have := Finset.mem_range.mp hj; omega) h g + _ = _ := by + rw [Finset.sum_add_distrib, Finset.sum_add_distrib, hold, hend] + linarith + +/-- A split is controlled by the actual D'=U+1 integer removal forms. +These are precisely the interior signatures available in the manuscript. -/ +theorem integer_split_potential_bound + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (U : ℕ) (h : I → ℝ) + (hsig : ∀ j, 0 < j → j < U+1 → + OnePositiveDirection (integerRemovalMatrix F (profile z j (U+1-j))).toBilin') + (hpos : ∀ j, 0 < j → j < U+1 → 0 < F (profile z (j-1) (U-j))) + (hbalance : pairCumulative (cross F (U+1) z) h (U+1) = 0) : + let g := pairCoefficient (cross F (U+1) z) (innerWeight F (U+1) z) h + (∑ j ∈ Finset.range (U+1), + holePotential F (profile z j (U-j)) (extendCoefficients h (g j) (g (j+1)))) ≤ + holePotential (marginal F U) z h - + ∑ j ∈ Finset.range (U+2), (j:ℝ)*(((U+1:ℕ):ℝ)-(j:ℝ)) * + (pairMatrix F (U+1) z j).toBilin' (old h) (old h) := by + dsimp only + rw [integer_potential_increment] + have hp := weighted_pair_potential F (U+1) z h hsig (by + intro j hj0 hjU + simpa only [Nat.add_sub_cancel] using hpos j hj0 hjU) hbalance + linarith + + +noncomputable def holeLinear (G : (I → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ) : ℝ := + ∑ i, oneHole G z i * h i + +/-- Equal resulting one-hole states cancel across adjacent branches. +The numerator family G may already include the arbitrary test function H. -/ +theorem integer_demand_conservation + (G : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (U : ℕ) + (h : I → ℝ) (g : ℕ → ℝ) : + (∑ j ∈ Finset.range (U+1), + holeLinear G (profile z j (U-j)) (extendCoefficients h (g j) (g (j+1)))) = + holeLinear (marginal G U) z h := by + have hold : (∑ j ∈ Finset.range (U+1), + ∑ i, oneHole G (profile z j (U-j)) (.inl i) * h i) = + holeLinear (marginal G U) z h := by + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul, old_hole_sum] + rfl + have hshift := Finset.sum_range_sub' + (fun j => innerWeight G (U+1) z j * g j) (U+1) + rw [Finset.sum_sub_distrib] at hshift + have hzero0 : innerWeight G (U+1) z 0 = 0 := by simp [innerWeight] + have hzeroM : innerWeight G (U+1) z (U+1) = 0 := by simp [innerWeight] + rw [hzero0, hzeroM, zero_mul, zero_mul, sub_self] at hshift + calc + _ = ∑ j ∈ Finset.range (U+1), + ((∑ i, oneHole G (profile z j (U-j)) (.inl i) * h i) + + (innerWeight G (U+1) z j * g j - innerWeight G (U+1) z (j+1) * g (j+1))) := by + apply Finset.sum_congr rfl + intro j hj + have hjU : j ≤ U := by have := Finset.mem_range.mp hj; omega + simp only [holeLinear, Fintype.sum_sum_type, Fintype.sum_bool, + extendCoefficients_inl, extendCoefficients_a, extendCoefficients_b, mul_neg] + rw [child_hole_a G z U j hjU, child_hole_b G z U j hjU] + ring + _ = _ := by + rw [Finset.sum_add_distrib, Finset.sum_sub_distrib, hold, hshift, add_zero] + +/-- Parent balance is exactly the zero cumulative cross mass required +by the weighted pair theorem. -/ +theorem cumulative_eq_parent_demand + (F : ((I ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (U : ℕ) (h : I → ℝ) : + pairCumulative (cross F (U+1) z) h (U+1) = + holeLinear (marginal F U) z h := by + unfold pairCumulative + calc + _ = ∑ j ∈ Finset.range (U+1), ∑ i, oneHole F (profile z j (U-j)) (.inl i) * h i := by + apply Finset.sum_congr rfl + intro j hj + exact (child_old_signed_mass F z U j (by have := Finset.mem_range.mp hj; omega) h).symm + _ = _ := by + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul, old_hole_sum] + rfl + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPropagation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPropagation.lean new file mode 100644 index 0000000000000000000000000000000000000000..662353db0610eaa981960fcd6c68686df7804706 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPropagation.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums + +namespace OAI + +/-! # Integer propagation tabulates adaptive finite laws without random tapes -/ + +namespace ContingencyTables.IntegerPropagation +open ResidualMixture FirstSuccess +open scoped BigOperators Classical + +variable {A : Type*} [Fintype A] [DecidableEq A] +variable (B : A → A → ℕ) (Q : ℕ) + +def numerators (start : A) : ℕ → A → ℕ + | 0,y => if y=start then 1 else 0 + | n+1,y => ∑ x,numerators start n x*B x y + +lemma numerators_total (hrow : ∀ x,∑ y,B x y=Q) (start : A) (n : ℕ) : + ∑ y,numerators B start n y=Q^n := by + induction n with + | zero => simp [numerators] + | succ n ih => + simp only [numerators] + rw [Finset.sum_comm] + simp_rw [←Finset.mul_sum,hrow] + rw [←Finset.sum_mul,ih,pow_succ] + +lemma numerator_le (hrow : ∀ x,∑ y,B x y=Q) (start : A) (n : ℕ) (y : A) : + numerators B start n y≤Q^n := by + rw [←numerators_total B Q hrow start n] + exact Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ y) + +/-- One row of a dyadic transition table, viewed as an exact rational law. -/ +def kernel (hQ : 0 simp [numerators,walkLaw,pointLaw] + | succ n ih => + simp only [numerators,Nat.cast_sum,Nat.cast_mul,walkLaw,bindLaw,kernel,pow_succ] + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro x _ + rw [←ih x] + exact (div_mul_div_comm _ _ _ _).symm + +end ContingencyTables.IntegerPropagation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPushTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPushTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..9daabce0321e347d7fcccd144aa2d0dce21f7698 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerPushTransport.lean @@ -0,0 +1,24 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerEquivLaw + +namespace OAI + +/-! # Count transport through a completion-coordinate bijection -/ + +namespace ContingencyTables.IntegerLaw +open scoped BigOperators Classical +noncomputable section + +lemma push_equiv_count {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq C] {P Q : ℕ} (p : IntegerLaw A P) (q : IntegerLaw B Q) + (e : A ≃ B) (M : ℕ) (finish : B → C) + (h : ∀ a,p.count a=q.count (e a)*M) (c : C) : + (p.push (fun a => finish (e a))).count c= + ∑ b,if finish b=c then q.count b*M else 0 := by + change (∑ a,if finish (e a)=c then p.count a else 0)=_ + simp_rw [h] + exact e.sum_comp (fun b : B => if finish b=c then q.count b*M else 0) + +end +end ContingencyTables.IntegerLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursiveFlow.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursiveFlow.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa9e3f319f3a5f4d93046eeb8cabaf12ba37fea1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursiveFlow.lean @@ -0,0 +1,259 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerExposure +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPairRecursion +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLeafTransport + +namespace OAI + +/-! # The actual recursive signed integer demands + +Every node exposes an ordinary balanced pair, computes the cumulative +coefficients from its actual remaining marginal, and retains the old +coefficients. The numerator can include any test function on complete +configurations. Its total leaf demand is exactly its root demand. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical +open BalancedFamily BalancedEnumeration IntegerMarginal + +universe u + +noncomputable def recursivePotential : {I : Type u} → [Fintype I] → [DecidableEq I] → + (Ms : List ℕ) → ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → (I → ℝ) → ℝ + | _, _, _, [], F, z, h => holePotential F z h + | I, _, _, U::Ms, F, z, h => + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + ∑ j : Fin (U+1), recursivePotential Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1))) + +noncomputable def recursiveDemand : {I : Type u} → [Fintype I] → [DecidableEq I] → + (Ms : List ℕ) → ((Coordinates I Ms → ℕ) → ℝ) → + ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → (I → ℝ) → ℝ + | _, _, _, [], _, G, z, h => holeLinear G z h + | I, _, _, U::Ms, F, G, z, h => + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + ∑ j : Fin (U+1), recursiveDemand Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (fun x => G (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1))) + +/-- All auxiliary ordinary negative-pair divergences cancel in the +actual recursion. No limit of recursive coefficients is needed. -/ +theorem recursiveDemand_eq : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F G : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ), + recursiveDemand Ms F G z h = holeLinear (eliminate Ms G) z h := by + intro Ms + induction Ms with + | nil => intro I _ _ F G z h; rfl + | cons U Ms ih => + intro I _ _ F G z h + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + change (∑ j : Fin (U+1), recursiveDemand Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (fun x => G (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1)))) = _ + simp_rw [ih] + change (∑ j : Fin (U+1), holeLinear (exposedFamily Ms G) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1)))) = _ + rw [Fin.sum_univ_eq_sum_range (fun j => holeLinear (exposedFamily Ms G) + (profile z j (U-j)) (extendCoefficients h (g j) (g (j+1)))) (U+1)] + rw [integer_demand_conservation, exposed_marginal] + +theorem recursivePotential_nonnegative : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ), + (∀ p, 0≤F p) → 0≤recursivePotential Ms F z h := by + intro Ms + induction Ms with + | nil => + intro I _ _ F z h hF + apply Finset.sum_nonneg + intro i _ + apply mul_nonneg _ (sq_nonneg _) + unfold oneHole + split_ifs + · exact hF _ + · exact le_rfl + | cons U Ms ih => + intro I _ _ F z h hF + apply Finset.sum_nonneg + intro j _ + exact ih _ _ _ (fun p => hF _) + + +noncomputable def recursiveEnergy : {I : Type u} → [Fintype I] → [DecidableEq I] → + (Ms : List ℕ) → ((Coordinates I Ms → ℕ) → ℝ) → + ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → (I → ℝ) → ℝ + | _, _, _, [], F, H, z, _ => + SignedTransport.cliqueEnergy (oneHole F z) (fun _ => 1) (fun i => H (FactorialSignatures.removeOne z i)) + | I, _, _, U::Ms, F, H, z, h => + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + ∑ j : Fin (U+1), recursiveEnergy Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (fun x => H (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1))) + +lemma oneHole_nonnegative {I : Type*} [DecidableEq I] (F : (I → ℕ) → ℝ) + (hF : ∀ p, 0≤F p) (z : I → ℕ) (i : I) : 0≤oneHole F z i := by + unfold oneHole + split_ifs + · exact hF _ + · exact le_rfl + +lemma oneHole_mul {I : Type*} [DecidableEq I] (F H : (I → ℕ) → ℝ) + (z : I → ℕ) (i : I) : + oneHole (fun p => F p*H p) z i = oneHole F z i * H (FactorialSignatures.removeOne z i) := by + unfold oneHole + split_ifs <;> simp + +theorem recursiveEnergy_nonnegative : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ), + (∀ p, 0≤F p) → 0≤recursiveEnergy Ms F H z h := by + intro Ms + induction Ms with + | nil => + intro I _ _ F H z h hF + change 0≤SignedTransport.cliqueEnergy (oneHole F z) (fun _ => 1) + (fun i => H (FactorialSignatures.removeOne z i)) + unfold SignedTransport.cliqueEnergy + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro i _ + apply Finset.sum_nonneg + intro j _ + exact mul_nonneg (le_min (by simpa using oneHole_nonnegative F hF z i) + (by simpa using oneHole_nonnegative F hF z j)) (sq_nonneg _) + | cons U Ms ih => + intro I _ _ F H z h hF + apply Finset.sum_nonneg + intro j _ + exact ih _ _ _ _ (fun p => hF _) + + +noncomputable def recursivelyBalanced : {I : Type u} → [Fintype I] → [DecidableEq I] → + (Ms : List ℕ) → ((Coordinates I Ms → ℕ) → ℝ) → (I → ℕ) → (I → ℝ) → Prop + | _, _, _, [], F, z, h => holeLinear F z h = 0 + | I, _, _, U::Ms, F, z, h => + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + ∀ j : Fin (U+1), recursivelyBalanced Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1))) + +/-- Positivity only on the valid box and degree supplies every cumulative +coefficient denominator and propagates root balance to all actual leaves. -/ +theorem recursivelyBalanced_of_slice : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) (h : I → ℝ), + BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum) → + BalancedBox.InBox m z → (∑ i, z i)=R+1 → + holeLinear (eliminate Ms F) z h=0 → recursivelyBalanced Ms F z h := by + intro Ms + induction Ms with + | nil => intro I _ _ F m z R h _ _ _ hb; exact hb + | cons U Ms ih => + intro I _ _ F m z R h hpos hz htotal hbalance + have hp : BalancedBox.PositiveSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum) := by + rw [show R+U+Ms.sum=R+(U::Ms).sum by simp only [List.sum_cons]; omega] + exact hpos + let f := exposedFamily Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + have hfpos := exposed_positive Ms U m R F hp + have hinner : ∀ k, 0 < k → k < U+1 → 0 < innerWeight f (U+1) z k := by + intro k hk0 hkU + rw [innerWeight, ite_eq_left ⟨hk0,hkU⟩] + apply hfpos + · apply BalancedBox.profile_inBox m z U (k-1) (U+1-1-k) hz <;> omega + · rw [BalancedBox.profile_total, htotal] + omega + have hcum : pairCumulative (cross f (U+1) z) h (U+1)=0 := by + rw [cumulative_eq_parent_demand] + change holeLinear (marginal (exposedFamily Ms F) U) z h=0 + rw [exposed_marginal] + exact hbalance + change ∀ j : Fin (U+1), recursivelyBalanced Ms + (fun x => F (fun t => x ((exposeEquiv (I := I) Ms).symm t))) + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1))) + intro j + apply ih _ (profile m U U) _ (R+U) _ (expose_source_positive Ms U m R F hp) + · exact BalancedBox.profile_inBox m z U j.val (U-j.val) hz (by omega) (Nat.sub_le _ _) + · rw [BalancedBox.profile_total, htotal] + have hj := j.isLt + omega + · change holeLinear f (profile z j.val (U-j.val)) + (extendCoefficients h (g j.val) (g (j.val+1)))=0 + exact integer_child_balance f z U j.val (by have := j.isLt; omega) h hinner hcum + +/-- The full actual recursive signed demands satisfy the leaf energy +comparison once their recursively proved balances are supplied. -/ +theorem recursive_signed_transport : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ), + (∀ p, 0≤F p) → recursivelyBalanced Ms F z h → + (recursiveDemand Ms F (fun p => F p*H p) z h)^2 ≤ + recursivePotential Ms F z h * recursiveEnergy Ms F H z h := by + intro Ms + induction Ms with + | nil => + intro I _ _ F H z h hF hbal + have ht := integer_leaf_transport F z h + (fun i => H (FactorialSignatures.removeOne z i)) hF hbal + change (holeLinear (fun p => F p*H p) z h)^2 ≤ holePotential F z h * + SignedTransport.cliqueEnergy (oneHole F z) (fun _ => 1) + (fun i => H (FactorialSignatures.removeOne z i)) + have he : holeLinear (fun p => F p*H p) z h = + ∑ i, oneHole F z i * h i * H (FactorialSignatures.removeOne z i) := by + unfold holeLinear + simp_rw [oneHole_mul] + apply Finset.sum_congr rfl + intro i _ + ring + rw [he] + exact ht + | cons U Ms ih => + intro I _ _ F H z h hF hbal + change (∑ j : Fin (U+1), recursiveDemand Ms _ _ _ _)^2 ≤ + (∑ j : Fin (U+1), recursivePotential Ms _ _ _) * + (∑ j : Fin (U+1), recursiveEnergy Ms _ _ _ _) + apply Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul Finset.univ + · intro j _ + exact recursivePotential_nonnegative Ms _ _ _ (fun p => hF _) + · intro j _ + exact recursiveEnergy_nonnegative Ms _ _ _ _ (fun p => hF _) + · intro j _ + exact ih _ _ _ _ (fun p => hF _) (hbal j) + +/-- The recursively accumulated clique energy is independent of all +signed coefficients; only the actual display and weight family matter. -/ +theorem recursiveEnergy_independent : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F H : (Coordinates I Ms → ℕ) → ℝ) (z : I → ℕ) (h h' : I → ℝ), + recursiveEnergy Ms F H z h = recursiveEnergy Ms F H z h' := by + intro Ms + induction Ms with + | nil => intro I _ _ F H z h h'; rfl + | cons U Ms ih => + intro I _ _ F H z h h' + apply Finset.sum_congr rfl + intro j _ + exact ih _ _ _ _ _ + +/-- The full recursive comparison with all balances discharged from +the literal softened slice, expressed solely using the root numerator. -/ +theorem integer_recursive_transport_of_slice {I : Type u} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (F H : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) + (R : ℕ) (h : I → ℝ) (hF : ∀ p, 0 ≤ F p) + (hpos : BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum)) + (hz : BalancedBox.InBox m z) (htotal : (∑ i, z i)=R+1) + (hbalance : holeLinear (eliminate Ms F) z h=0) : + (holeLinear (eliminate Ms (fun p => F p*H p)) z h)^2 ≤ + recursivePotential Ms F z h * recursiveEnergy Ms F H z h := by + rw [← recursiveDemand_eq Ms F (fun p => F p*H p) z h] + exact recursive_signed_transport Ms F H z h hF + (recursivelyBalanced_of_slice Ms F m z R h hpos hz htotal hbalance) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursivePotential.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursivePotential.lean new file mode 100644 index 0000000000000000000000000000000000000000..9171f31c9d4355bd282be112a6b9614ace17ef0f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerRecursivePotential.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerCorrectionKernel + +namespace OAI + +/-! # Telescoping the actual raw integer recursion + +The literal future kernel commutation and nonnegative square identity +control every future correction after a split. No signature property of +the weighted correction kernel is used. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures BalancedFamily BalancedEnumeration IntegerMarginal + +universe u + +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma correction_future_lower (Ms : List ℕ) (U : ℕ) (hU : 2 ≤ U) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) + (h : I → ℝ) (g : ℕ → ℝ) (hF : ∀ x, 0 ≤ F x) : + (integerRemovalMatrix (correctionKernel Ms (marginal F U)) z).toBilin' h h ≤ + ∑ j : Fin (U+1), + (integerRemovalMatrix (correctionKernel Ms (exposePullback Ms F)) + (profile z j.val (U-j.val))).toBilin' + (extendCoefficients h (g j.val) (g (j.val+1))) + (extendCoefficients h (g j.val) (g (j.val+1))) := by + rw [correctionKernel_current_commute] + rw [Fin.sum_univ_eq_sum_range (fun j => + (integerRemovalMatrix (correctionKernel Ms (exposePullback Ms F)) + (profile z j (U-j))).toBilin' + (extendCoefficients h (g j) (g (j+1))) + (extendCoefficients h (g j) (g (j+1)))) (U+1)] + have ht := future_form_monotone (correctionKernel Ms (exposePullback Ms F)) z + (U-2) h g (correctionKernel_nonnegative Ms _ (fun x => hF _)) + simpa only [show U-2+2=U by omega, show U-2+3=U+1 by omega, IntegerMarginal.pairMatrix] using ht + +omit [Fintype I] in +lemma integerRemovalMatrix_add (F G : (I → ℕ) → ℝ) (z : I → ℕ) : + integerRemovalMatrix (fun x => F x+G x) z = + integerRemovalMatrix F z + integerRemovalMatrix G z := by + ext i j + simp only [integerRemovalMatrix, Matrix.add_apply] + split_ifs <;> simp + +lemma correction_form_cons (Ms : List ℕ) (U : ℕ) + (F : ((Coordinates I Ms ⊕ Bool) → ℕ) → ℝ) (z : I → ℕ) (h : I → ℝ) : + (integerRemovalMatrix (correctionKernel (U::Ms) F) z).toBilin' h h = + (integerRemovalMatrix (weightedFuture (exposedFamily Ms F) (U+1)) z).toBilin' h h + + (integerRemovalMatrix (correctionKernel Ms (marginal F U)) z).toBilin' h h := by + rw [correctionKernel, integerRemovalMatrix_add] + simp only [map_add, LinearMap.add_apply] + +/-- The entire leaf potential is bounded by the root potential minus +the sum of the actual root future forms. All recursive hypotheses are +derived from the original valid total slice. -/ +theorem recursivePotential_bound : ∀ (Ms : List ℕ) {I : Type u} [Fintype I] [DecidableEq I] + (F : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) (h : I → ℝ), + (∀ U ∈ Ms, 2 ≤ U) → (∀ x, 0 ≤ F x) → + BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum) → + BalancedBox.RemovalSlice F (bounds m Ms) (R+Ms.sum) → + BalancedBox.InBox m z → (∑ i, z i)=R+1 → + holeLinear (eliminate Ms F) z h=0 → + recursivePotential Ms F z h ≤ holePotential (eliminate Ms F) z h - + (integerRemovalMatrix (correctionKernel Ms F) z).toBilin' h h := by + intro Ms + induction Ms with + | nil => + intro I _ _ F m z R h _ _ _ _ _ _ _ + change holePotential F z h ≤ holePotential F z h - + (integerRemovalMatrix (fun _ => 0) z).toBilin' h h + have hz : integerRemovalMatrix (fun _ : I → ℕ => (0:ℝ)) z=0 := by + ext i j + simp [integerRemovalMatrix] + rw [hz] + simp + | cons U Ms ih => + intro I _ _ F m z R h hwidth hF hpos hsig hz htotal hbalance + have hU := hwidth U (by simp) + have htail : ∀ V ∈ Ms, 2 ≤ V := fun V hV => hwidth V (by simp [hV]) + have hp : BalancedBox.PositiveSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum) := by + rw [show R+U+Ms.sum=R+(U::Ms).sum by simp only [List.sum_cons]; omega] + exact hpos + have hs : BalancedBox.RemovalSlice F (profile (bounds m Ms) U U) (R+U+Ms.sum) := by + rw [show R+U+Ms.sum=R+(U::Ms).sum by simp only [List.sum_cons]; omega] + exact hsig + let f := exposedFamily Ms F + let G := exposePullback Ms F + let g := pairCoefficient (cross f (U+1) z) (innerWeight f (U+1) z) h + obtain ⟨hfpos,hfsig⟩ := exposed_slices Ms U m R F htail hp hs + have hinner : ∀ k, 0 < k → k < U+1 → 0 < innerWeight f (U+1) z k := by + intro k hk0 hkU + rw [innerWeight, ite_eq_left ⟨hk0,hkU⟩] + apply hfpos + · apply BalancedBox.profile_inBox m z U (k-1) (U+1-1-k) hz <;> omega + · rw [BalancedBox.profile_total, htotal] + omega + have hcum : pairCumulative (cross f (U+1) z) h (U+1)=0 := by + rw [cumulative_eq_parent_demand] + change holeLinear (marginal (exposedFamily Ms F) U) z h=0 + rw [exposed_marginal] + exact hbalance + have hGpos := expose_source_positive Ms U m R F hp + have hGsig : BalancedBox.RemovalSlice G (bounds (profile m U U) Ms) (R+U+Ms.sum) := by + have ht := removalSlice_reindex (exposeEquiv (I := I) Ms) F + (profile (bounds m Ms) U U) (R+U+Ms.sum) hs + rw [expose_bounds_forward] at ht + exact ht + have hleaves : (∑ j : Fin (U+1), recursivePotential Ms G + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1)))) ≤ + ∑ j : Fin (U+1), (holePotential f (profile z j.val (U-j.val)) + (extendCoefficients h (g j.val) (g (j.val+1))) - + (integerRemovalMatrix (correctionKernel Ms G) (profile z j.val (U-j.val))).toBilin' + (extendCoefficients h (g j.val) (g (j.val+1))) + (extendCoefficients h (g j.val) (g (j.val+1)))) := by + apply Finset.sum_le_sum + intro j _ + apply ih G (profile m U U) _ (R+U) _ htail (fun x => hF _) hGpos hGsig + · exact BalancedBox.profile_inBox m z U j.val (U-j.val) hz + (by have := j.isLt; omega) (Nat.sub_le _ _) + · rw [BalancedBox.profile_total, htotal] + have hj := j.isLt + omega + · exact integer_child_balance f z U j.val (by have := j.isLt; omega) h hinner hcum + have hsplit := integer_split_potential_bound f z U h (by + intro j hj0 hjU + apply hfsig + · exact BalancedBox.profile_inBox m z U j (U+1-j) hz (by omega) (by omega) + · rw [BalancedBox.profile_total, htotal] + omega) (by + intro j hj0 hjU + apply hfpos + · exact BalancedBox.profile_inBox m z U (j-1) (U-j) hz (by omega) (Nat.sub_le _ _) + · rw [BalancedBox.profile_total, htotal] + omega) hcum + change (∑ j ∈ Finset.range (U+1), holePotential f (profile z j (U-j)) + (extendCoefficients h (g j) (g (j+1)))) ≤ _ at hsplit + rw [← weightedFuture_form, exposed_marginal] at hsplit + rw [← Fin.sum_univ_eq_sum_range (fun j => holePotential f (profile z j (U-j)) + (extendCoefficients h (g j) (g (j+1)))) (U+1)] at hsplit + have hfuture := correction_future_lower Ms U hU F z h g hF + rw [Finset.sum_sub_distrib] at hleaves + change (∑ j : Fin (U+1), recursivePotential Ms G + (profile z j.val (U-j.val)) (extendCoefficients h (g j.val) (g (j.val+1)))) ≤ _ + rw [correction_form_cons] + linarith + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerReflection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerReflection.lean new file mode 100644 index 0000000000000000000000000000000000000000..87370e1c638d097b7f17f45d83ca82f6076229a9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerReflection.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerMarginal + +namespace OAI + +/-! +# Actual box reflection and integer addition signatures + +Reflection of every coordinate converts a valid two-addition entry into a +two-removal entry. A balanced summed pair is reflected by reversing its +finite index, so the same marginal closure applies to additions. +-/ + +namespace ContingencyTables.IntegerReflection + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +def reflect (N z : I → ℕ) : I → ℕ := fun i => N i-z i + +omit [Fintype I] in +lemma reflect_removeTwo (N r n : I → ℕ) (hr : ∀ i, r i+n i=N i) + (i j : I) (hv : ValidPair n i j) : + reflect N (removeTwo n i j) = addTwo r i j := by + funext k + have hk := hr k + have hi := hv.1 + have hj := hv.2 + by_cases hij : i=j + · subst j + have hn : 2 ≤ n i := by simp at hj; omega + by_cases hki : k=i + · subst k + simp only [reflect,removeTwo,removeOne,addTwo,ite_true] + omega + · simp [reflect,removeTwo,removeOne,addTwo,hki] + omega + · have hj0 : 0 < n j := by simpa [Ne.symm hij] using hj + by_cases hki : k=i + · subst k + simp only [reflect,removeTwo,removeOne,addTwo,ite_true,hij,ite_false] + omega + · by_cases hkj : k=j + · subst k + simp only [reflect,removeTwo,removeOne,addTwo,ite_true,Ne.symm hij,ite_false] + omega + · simp only [reflect,removeTwo,removeOne,addTwo,hki,hkj,ite_false,Nat.sub_zero,add_zero] + omega + +omit [Fintype I] in +/-- Exact matrix identity, including all invalid pair entries. -/ +theorem addition_eq_reflected_removal (h : (I → ℕ) → ℝ) (N r n : I → ℕ) + (hr : ∀ i, r i+n i=N i) : + integerAdditionMatrix h r n = integerRemovalMatrix (fun z => h (reflect N z)) n := by + ext i j + unfold integerAdditionMatrix integerRemovalMatrix + split_ifs with hv + · dsimp only + rw [reflect_removeTwo N r n hr i j hv] + · rfl + +/-- The addition signature follows from the raw removal signature of +its globally reflected weight, without a binary-lift assumption. -/ +theorem addition_onePositive_of_reflection (h : (I → ℕ) → ℝ) (N r n : I → ℕ) + (hr : ∀ i, r i+n i=N i) + (hsig : OnePositiveDirection (integerRemovalMatrix (fun z => h (reflect N z)) n).toBilin') : + OnePositiveDirection (integerAdditionMatrix h r n).toBilin' := by + rw [addition_eq_reflected_removal h N r n hr] + exact hsig + +omit [Fintype I] [DecidableEq I] in +lemma reflect_profile (N z : I → ℕ) (M j : ℕ) (hj : j ≤ M) : + reflect (profile N M M) (profile z j (M-j)) = profile (reflect N z) (M-j) j := by + funext t + rcases t with i | (_ | _) <;> simp [reflect,profile] + omega + +omit [Fintype I] [DecidableEq I] in +/-- Reflection commutes with actual balanced marginalization by reversal +of the finite summation index. -/ +theorem marginal_reflect (F : ((I ⊕ Bool) → ℕ) → ℝ) (N z : I → ℕ) (M : ℕ) : + marginal (fun x => F (reflect (profile N M M) x)) M z = + marginal F M (reflect N z) := by + unfold marginal + calc + _ = ∑ j ∈ Finset.range (M+1), F (profile (reflect N z) (M-j) j) := by + apply Finset.sum_congr rfl + intro j hj + dsimp only + rw [reflect_profile N z M j (by simpa using Finset.mem_range.mp hj)] + _ = _ := by + have hh := Finset.sum_range_reflect + (fun j => F (profile (reflect N z) j (M-j))) (M+1) + convert hh using 1 + apply Finset.sum_congr rfl + intro j hj + have hjM : j ≤ M := by simpa using Finset.mem_range.mp hj + congr 1 + congr 1; omega + +end ContingencyTables.IntegerReflection + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerResidualCorrection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerResidualCorrection.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dfac79e1bd41cff600074be54963aa47a4c8669 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerResidualCorrection.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw + +namespace OAI + +/-! # Integer realization of the exact residual correction law -/ + +namespace ContingencyTables.IntegerResidualCorrection +open ResidualMixture +open scoped BigOperators Classical +noncomputable section + +variable {A : Type*} [Fintype A] [Nonempty A] {Q : ℕ} + +def count (p : IntegerLaw A Q) (T : ℕ) (a : A) : ℕ := + (residualNumerator Q T (fun x => (p.count x : ℤ)) a).toNat + +lemma cast_count (p : IntegerLaw A Q) (T : ℕ) (hQ : 0 (p.count x : ℤ)) a := by + apply Int.toNat_of_nonneg + apply residualNumerator_nonnegative + · exact_mod_cast hQ + · exact_mod_cast hT + · simpa only [IntegerLaw.toRational,Int.cast_natCast] using hdom + +/-- The finite integer weights sum to `|A|*Q`; all truncations are exact +because the ordinary law is pointwise dominated by the uniform law. -/ +def law (p : IntegerLaw A Q) (T : ℕ) (hQ : 0 (p.count x:ℤ)) ht + +lemma denominator_pos (hQ : 0 (z:ℚ)) (cast_count p T hQ hT hdom a) + simp only [Int.cast_natCast] at hc + change (count p T a:ℚ)/(Fintype.card A*Q:ℕ)=_ + rw [hc,Nat.cast_mul] + exact residualNumerator_quotient (Q:ℤ) (T:ℤ) (fun x => (p.count x:ℤ)) + (by exact_mod_cast hQ.ne') (by exact_mod_cast hT.ne') a + +/-- The ordinary branch and the explicit integer-weight branch have +exactly uniform combined mass, before physical execution is compiled. -/ +theorem mixture_exact (p : IntegerLaw A Q) (T : ℕ) (hQ : 0 if b then -(1/t) else 1/s + +lemma root_potential (s t : ℝ) (hs : 0 fun _ => 0 + | U::Ms, F => fun z => marginal (exposedFamily Ms F) (U+1) z + + auxiliaryKernel Ms (marginal F U) z + +theorem auxiliaryKernel_nonnegative {I : Type u} (Ms : List ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (hF : ∀ x, 0 ≤ F x) (z : I → ℕ) : + 0 ≤ auxiliaryKernel Ms F z := by + induction Ms with + | nil => exact le_rfl + | cons U Ms ih => + apply add_nonneg + · apply Finset.sum_nonneg + intro j _ + exact eliminate_nonnegative Ms _ (fun x => hF _) _ + · exact ih _ (fun x => Finset.sum_nonneg (fun j _ => hF _)) + +lemma weightedFuture_upper {I : Type u} (F : ((I ⊕ Bool) → ℕ) → ℝ) + (M W : ℕ) (hM : M ≤ W+1) (hF : ∀ x, 0 ≤ F x) (z : I → ℕ) : + weightedFuture F M z ≤ ((W:ℝ)+1)^2 * marginal F M z := by + unfold weightedFuture marginal + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro a ha + have haM : a ≤ M := by have := Finset.mem_range.mp ha; omega + have haR : (a:ℝ) ≤ M := by exact_mod_cast haM + have hMR : (M:ℝ) ≤ (W:ℝ)+1 := by exact_mod_cast hM + apply mul_le_mul_of_nonneg_right _ (hF _) + calc + _ ≤ ((W:ℝ)+1)*((W:ℝ)+1) := + mul_le_mul (haR.trans hMR) (by linarith) (by linarith) (by positivity) + _ = _ := by ring + +theorem correctionKernel_upper {I : Type u} (Ms : List ℕ) + (F : (Coordinates I Ms → ℕ) → ℝ) (W : ℕ) + (hwidth : ∀ U ∈ Ms, U ≤ W) (hF : ∀ x, 0 ≤ F x) (z : I → ℕ) : + correctionKernel Ms F z ≤ ((W:ℝ)+1)^2 * auxiliaryKernel Ms F z := by + induction Ms with + | nil => simp [correctionKernel,auxiliaryKernel] + | cons U Ms ih => + have hcur := weightedFuture_upper (exposedFamily Ms F) (U+1) W + (by have := hwidth U (by simp); omega) + (fun x => eliminate_nonnegative Ms _ (fun p => hF _) _) z + have htail := ih (marginal F U) (fun V hV => hwidth V (by simp [hV])) + (fun x => Finset.sum_nonneg (fun j _ => hF _)) + change _+_ ≤ ((W:ℝ)+1)^2 * (_+_) + linarith + +lemma removal_nonnegative {C : Type*} [DecidableEq C] (F : (C → ℕ) → ℝ) + (hF : ∀ x, 0 ≤ F x) (z : C → ℕ) (i j : C) : + 0 ≤ integerRemovalMatrix F z i j := by + unfold integerRemovalMatrix + split_ifs + · exact hF _ + · exact le_rfl + +lemma correction_offdiagonal_upper (Ms : List ℕ) + (F : (Coordinates Bool Ms → ℕ) → ℝ) (W : ℕ) + (hwidth : ∀ U ∈ Ms, U ≤ W) (hF : ∀ x, 0 ≤ F x) (z : Bool → ℕ) : + integerRemovalMatrix (correctionKernel Ms F) z false true ≤ + ((W:ℝ)+1)^2 * integerRemovalMatrix (auxiliaryKernel Ms F) z false true := by + unfold integerRemovalMatrix + split_ifs + · exact correctionKernel_upper Ms F W hwidth hF _ + · simp + +lemma root_balance (f : (Bool → ℕ) → ℝ) (z : Bool → ℕ) + (hs : 0 < oneHole f z false) (ht : 0 < oneHole f z true) : + holeLinear f z (rootCoefficients (oneHole f z false) (oneHole f z true))=0 := by + simp only [holeLinear,Fintype.sum_bool,rootCoefficients,Bool.false_eq_true,↓reduceIte] + field_simp [ne_of_gt hs,ne_of_gt ht] + ring + +lemma root_holePotential (f : (Bool → ℕ) → ℝ) (z : Bool → ℕ) + (hs : 0 < oneHole f z false) (ht : 0 < oneHole f z true) : + holePotential f z (rootCoefficients (oneHole f z false) (oneHole f z true)) = + 1/oneHole f z false+1/oneHole f z true := by + simpa only [holePotential,Fintype.sum_bool,rootCoefficients, + Bool.false_eq_true,↓reduceIte] using root_potential _ _ hs ht + +/-- The root potential estimate for the actual integer recursion. The +only weight-dependent denominators are its two positive endpoint masses. -/ +theorem recursive_root_potential (Ms : List ℕ) + (F : (Coordinates Bool Ms → ℕ) → ℝ) (m z : Bool → ℕ) (R W : ℕ) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hF : ∀ x, 0 ≤ F x) + (hpos : BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum)) + (hsig : BalancedBox.RemovalSlice F (bounds m Ms) (R+Ms.sum)) + (hz : BalancedBox.InBox m z) (htotal : (∑ i, z i)=R+1) + (hs : 0 < oneHole (eliminate Ms F) z false) + (ht : 0 < oneHole (eliminate Ms F) z true) : + let s := oneHole (eliminate Ms F) z false + let t := oneHole (eliminate Ms F) z true + let c := integerRemovalMatrix (auxiliaryKernel Ms F) z false true + recursivePotential Ms F z (rootCoefficients s t) ≤ + 1/s+1/t+2*((W:ℝ)+1)^2*c/(s*t) := by + dsimp only + have hp := recursivePotential_bound Ms F m z R + (rootCoefficients _ _) hlower hF hpos hsig hz htotal (root_balance _ _ hs ht) + rw [root_holePotential _ _ hs ht] at hp + have hq := root_future_bound (integerRemovalMatrix (correctionKernel Ms F) z) + (oneHole (eliminate Ms F) z false) (oneHole (eliminate Ms F) z true) + (((W:ℝ)+1)^2) (integerRemovalMatrix (auxiliaryKernel Ms F) z false true) + hs ht (integerRemoval_symm _ _ _ _) + (removal_nonnegative _ (correctionKernel_nonnegative Ms F hF) _ _ _) + (removal_nonnegative _ (correctionKernel_nonnegative Ms F hF) _ _ _) + (correction_offdiagonal_upper Ms F W hupper hF z) + linarith + +/-- The softened integer transport on the actual exchange graph. All +recursive coefficients and future forms have been eliminated. -/ +theorem integer_root_graph_transport (Ms : List ℕ) + (F H : (Coordinates Bool Ms → ℕ) → ℝ) (m z : Bool → ℕ) (R W : ℕ) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hF : ∀ x, 0 ≤ F x) + (hpos : BalancedBox.PositiveSlice F (bounds m Ms) (R+Ms.sum)) + (hsig : BalancedBox.RemovalSlice F (bounds m Ms) (R+Ms.sum)) + (hz : BalancedBox.InBox m z) (htotal : (∑ i, z i)=R+1) + (hs : 0 < oneHole (eliminate Ms F) z false) + (ht : 0 < oneHole (eliminate Ms F) z true) + (V : Finset (Coordinates Bool Ms → ℕ)) (hV : leafVertices Ms z ⊆ V) : + let s := oneHole (eliminate Ms F) z false + let t := oneHole (eliminate Ms F) z true + let c := integerRemovalMatrix (auxiliaryKernel Ms F) z false true + (holeLinear (eliminate Ms (fun p => F p*H p)) z (rootCoefficients s t))^2 ≤ + (1/s+1/t+2*((W:ℝ)+1)^2*c/(s*t)) * integerGraphEnergy V F H := by + dsimp only + have hp := recursive_root_potential Ms F m z R W hlower hupper hF hpos hsig hz htotal hs ht + have hb := integer_recursive_transport_of_slice Ms F H m z R (rootCoefficients _ _) + hF hpos hz htotal (root_balance _ _ hs ht) + have he := recursiveEnergy_le_graphEnergy Ms F H z (rootCoefficients + (oneHole (eliminate Ms F) z false) (oneHole (eliminate Ms F) z true)) hF V hV + have hpn := recursivePotential_nonnegative Ms F z (rootCoefficients + (oneHole (eliminate Ms F) z false) (oneHole (eliminate Ms F) z true)) hF + have hen := recursiveEnergy_nonnegative Ms F H z (rootCoefficients + (oneHole (eliminate Ms F) z false) (oneHole (eliminate Ms F) z true)) hF + exact hb.trans ((mul_le_mul_of_nonneg_right hp hen).trans + (mul_le_mul_of_nonneg_left he (hpn.trans hp))) + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..17ad5efc814196aecc439fc06baeb86c2a421e75 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceReindex.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedBox + +namespace OAI + +/-! # Raw integer removal slices under coordinate bijections -/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal BalancedBox BinaryContraction + +variable {C D : Type*} [Fintype C] [Fintype D] [DecidableEq C] [DecidableEq D] + +omit [Fintype C] [Fintype D] in +lemma removeOne_reindex (e : C ≃ D) (z : C → ℕ) (i : C) : + (removeOne z i) ∘ e.symm = removeOne (z ∘ e.symm) (e i) := by + funext d + simp only [Function.comp_apply, removeOne] + by_cases hd : d = e i + · subst d + simp + · have hi : e.symm d ≠ i := by + intro hi + apply hd + simpa only [Equiv.apply_symm_apply] using congrArg e hi + simp only [hd, hi, ↓reduceIte] + +omit [Fintype C] [Fintype D] in +lemma removeTwo_reindex (e : C ≃ D) (z : C → ℕ) (i j : C) : + (removeTwo z i j) ∘ e.symm = removeTwo (z ∘ e.symm) (e i) (e j) := by + simp only [removeTwo, removeOne_reindex] + +omit [Fintype C] [Fintype D] in +lemma removalMatrix_reindex (e : C ≃ D) (F : (D → ℕ) → ℝ) (z : C → ℕ) : + integerRemovalMatrix (fun x => F (x ∘ e.symm)) z = + (integerRemovalMatrix F (z ∘ e.symm)).submatrix e e := by + ext i j + have hv : ValidPair (z ∘ e.symm) (e i) (e j) ↔ ValidPair z i j := by + simp [ValidPair] + change (if ValidPair z i j then F (removeTwo z i j ∘ e.symm) else 0) = + if ValidPair (z ∘ e.symm) (e i) (e j) then + F (removeTwo (z ∘ e.symm) (e i) (e j)) else 0 + simp only [hv, removeTwo_reindex] + +lemma removalSignature_reindex (e : C ≃ D) (F : (D → ℕ) → ℝ) (z : C → ℕ) + (hs : OnePositiveDirection (integerRemovalMatrix F (z ∘ e.symm)).toBilin') : + OnePositiveDirection (integerRemovalMatrix (fun x => F (x ∘ e.symm)) z).toBilin' := by + rw [removalMatrix_reindex] + apply (signature_iff _ (matrix_bilin_symm _ (by + intro i j + exact integerRemoval_symm F (z ∘ e.symm) (e i) (e j)))).mpr + apply onePositive_submatrix + exact (signature_iff _ (matrix_bilin_symm _ (integerRemoval_symm F _))).mp hs + +omit [DecidableEq C] [DecidableEq D] in +lemma positiveSlice_reindex (e : C ≃ D) (F : (D → ℕ) → ℝ) (m : D → ℕ) (R : ℕ) + (hF : PositiveSlice F m R) : + PositiveSlice (fun x => F (x ∘ e.symm)) (m ∘ e) R := by + intro z hz ht + apply hF + · intro d + simpa only [Function.comp_apply, Equiv.apply_symm_apply] using hz (e.symm d) + · have he := e.sum_comp (fun d => z (e.symm d)) + simp only [Equiv.symm_apply_apply] at he + exact he.symm.trans ht + +lemma removalSlice_reindex (e : C ≃ D) (F : (D → ℕ) → ℝ) (m : D → ℕ) (R : ℕ) + (hF : RemovalSlice F m R) : + RemovalSlice (fun x => F (x ∘ e.symm)) (m ∘ e) R := by + intro z hz ht + apply removalSignature_reindex + apply hF + · intro d + simpa only [Function.comp_apply, Equiv.apply_symm_apply] using hz (e.symm d) + · have he := e.sum_comp (fun d => z (e.symm d)) + simp only [Equiv.symm_apply_apply] at he + exact he.symm.trans ht + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceRestriction.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ead3faa40fa92024a61455f446523879237871d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerSliceRestriction.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerSliceReindex + +namespace OAI + +/-! # Restricting fixed prefix coordinates + +A context is fixed before the signed transport starts. Its coordinates +are removed from the transport index set, so leaf cliques cannot move a +hole into that prefix. The remaining removal form is a principal block. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal BalancedBox BinaryContraction + +variable {C D : Type*} [Fintype C] [Fintype D] [DecidableEq C] [DecidableEq D] + +omit [Fintype C] [Fintype D] in +lemma removeOne_fixed (c : C → ℕ) (z : D → ℕ) (i : D) : + removeOne (Sum.elim c z) (.inr i) = Sum.elim c (removeOne z i) := by + funext t + rcases t with t | t <;> simp [removeOne] + +omit [Fintype C] [Fintype D] in +lemma removeTwo_fixed (c : C → ℕ) (z : D → ℕ) (i j : D) : + removeTwo (Sum.elim c z) (.inr i) (.inr j) = Sum.elim c (removeTwo z i j) := by + simp only [removeTwo, removeOne_fixed] + +omit [Fintype C] [Fintype D] in +lemma removalMatrix_fixed (F : ((C ⊕ D) → ℕ) → ℝ) (c : C → ℕ) (z : D → ℕ) : + integerRemovalMatrix (fun x => F (Sum.elim c x)) z = + (integerRemovalMatrix F (Sum.elim c z)).submatrix Sum.inr Sum.inr := by + ext i j + change (if ValidPair z i j then F (Sum.elim c (removeTwo z i j)) else 0) = + if ValidPair (Sum.elim c z) (.inr i) (.inr j) then + F (removeTwo (Sum.elim c z) (.inr i) (.inr j)) else 0 + simp only [ValidPair, Sum.elim_inr, Sum.inr.injEq, removeTwo_fixed] + split_ifs <;> rfl + +lemma removalSignature_fixed (F : ((C ⊕ D) → ℕ) → ℝ) (c : C → ℕ) (z : D → ℕ) + (hs : OnePositiveDirection (integerRemovalMatrix F (Sum.elim c z)).toBilin') : + OnePositiveDirection (integerRemovalMatrix (fun x => F (Sum.elim c x)) z).toBilin' := by + rw [removalMatrix_fixed] + apply (signature_iff _ (matrix_bilin_symm _ (by + intro i j + exact integerRemoval_symm F (Sum.elim c z) (.inr i) (.inr j)))).mpr + apply onePositive_submatrix + exact (signature_iff _ (matrix_bilin_symm _ (integerRemoval_symm F _))).mp hs + +omit [DecidableEq C] [DecidableEq D] in +theorem positiveSlice_fixed (F : ((C ⊕ D) → ℕ) → ℝ) (mC c : C → ℕ) (mD : D → ℕ) + (R : ℕ) (hc : InBox mC c) + (hp : PositiveSlice F (Sum.elim mC mD) ((∑ i, c i)+R)) : + PositiveSlice (fun x => F (Sum.elim c x)) mD R := by + intro z hz ht + apply hp + · intro t + rcases t with i | i + · exact hc i + · exact hz i + · simp only [Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr, ht] + +theorem removalSlice_fixed (F : ((C ⊕ D) → ℕ) → ℝ) (mC c : C → ℕ) (mD : D → ℕ) + (R : ℕ) (hc : InBox mC c) + (hs : RemovalSlice F (Sum.elim mC mD) ((∑ i, c i)+R)) : + RemovalSlice (fun x => F (Sum.elim c x)) mD R := by + intro z hz ht + apply removalSignature_fixed + apply hs + · intro t + rcases t with i | i + · exact hc i + · exact hz i + · simp only [Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr, ht] + omega + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportCoefficient.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportCoefficient.lean new file mode 100644 index 0000000000000000000000000000000000000000..75dbb1bad21f9d9fd63757317a7238d1ac7a2c84 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportCoefficient.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerRootTransport + +namespace OAI + +/-! # Eliminating the actual auxiliary-defect coefficient + +Conditional repair bounds each auxiliary defect fibre by one endpoint +child. The elementary reciprocal calculation below converts their sum +into the manuscript's uniform adjacent-mean transport constant. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +lemma root_coefficient_bound (s t K c d : ℝ) (hs : 0 < s) (ht : 0 < t) + (hK : 0 ≤ K) (hc : c ≤ d*max s t) : + min s t*(1/s+1/t+K*c/(s*t)) ≤ 2+K*d := by + wlog hst : s ≤ t generalizing s t + · have h := this t s ht hs (by simpa only [max_comm] using hc) (le_of_not_ge hst) + simpa only [min_comm,mul_comm t s,add_comm (1/t) (1/s)] using h + rw [min_eq_left hst,max_eq_right hst] at * + have he : s*(1/s+1/t+K*c/(s*t))=1+s/t+K*(c/t) := by + field_simp + rw [he] + have hst' : s/t ≤ 1 := (div_le_one ht).mpr hst + have hc' : c/t ≤ d := (div_le_iff₀ ht).mpr hc + have hkc := mul_le_mul_of_nonneg_left hc' hK + linarith + +/-- The hard root transport and the proved repair domination give the +uniform adjacent-mean estimate used in exposure variance. -/ +theorem repaired_root_transport (s t c d W E Δ : ℝ) + (hs : 0 < s) (ht : 0 < t) (hE : 0 ≤ E) + (hc : c ≤ d*max s t) + (htransport : Δ^2 ≤ (1/s+1/t+2*(W+1)^2*c/(s*t))*E) : + min s t*Δ^2 ≤ (2+2*d*(W+1)^2)*E := by + have hcoef := root_coefficient_bound s t (2*(W+1)^2) c d hs ht (by positivity) hc + calc + _ ≤ min s t*((1/s+1/t+2*(W+1)^2*c/(s*t))*E) := + mul_le_mul_of_nonneg_left htransport (le_min hs.le ht.le) + _ = (min s t*(1/s+1/t+2*(W+1)^2*c/(s*t)))*E := by ring + _ ≤ (2+(2*(W+1)^2)*d)*E := mul_le_mul_of_nonneg_right hcoef hE + _ = _ := by ring + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLevels.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLevels.lean new file mode 100644 index 0000000000000000000000000000000000000000..8957667f17b62c2e1aeec101817dc2b4c29191e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLevels.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPairRecursion + +namespace OAI + +/-! # Summing the actual integer-branch recursion by exposure level + +The branches are the U+1 balanced profiles of each ordinary slot. +Local potential increments and future-form monotonicity telescope to the +root bound used before the softened limit. No positivity of future forms +or signature property of their weighted sums is assumed. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical + +abbrev BranchPath (U k : ℕ) := Fin k → Fin (U+1) + +noncomputable def levelSum {U k : ℕ} (f : BranchPath U k → ℝ) : ℝ := ∑ s, f s + +lemma levelSum_succ {U k : ℕ} (f : BranchPath U (k+1) → ℝ) : + levelSum f = ∑ s : BranchPath U k, ∑ j : Fin (U+1), + f (Fin.snoc (α := fun _ : Fin (k+1) => Fin (U+1)) s j) := by + unfold levelSum + rw [← (Fin.snocEquiv (fun _ : Fin (k+1) => Fin (U+1))).sum_comp] + rw [Fintype.sum_prod_type, Finset.sum_comm] + rfl + +/-- A future slot's total quadratic form increases up to the level at +which that slot is processed. -/ +theorem level_future_lower (U : ℕ) + (Q : ∀ k, BranchPath U k → ℕ → ℝ) + (hfuture : ∀ k t, k < t → ∀ s : BranchPath U k, + Q k s t ≤ ∑ j : Fin (U+1), + Q (k+1) (Fin.snoc (α := fun _ : Fin (k+1) => Fin (U+1)) s j) t) + (k t : ℕ) (hkt : k ≤ t) : + levelSum (fun s => Q 0 s t) ≤ levelSum (fun s => Q k s t) := by + induction k with + | zero => exact le_rfl + | succ k ih => + apply (ih (by omega)).trans + rw [levelSum_succ] + apply Finset.sum_le_sum + intro s _ + exact hfuture k t (by omega) s + +/-- The sum of all leaf potentials is at most the root potential minus +the root's future corrections. This is the manuscript's recursion-level +telescoping step for U+1 ordinary integer branches. -/ +theorem integer_leaf_potential_bound (U : ℕ) + (P : ∀ k, BranchPath U k → ℝ) (Q : ∀ k, BranchPath U k → ℕ → ℝ) + (hsplit : ∀ k, ∀ s : BranchPath U k, + (∑ j : Fin (U+1), P (k+1) + (Fin.snoc (α := fun _ : Fin (k+1) => Fin (U+1)) s j)) ≤ P k s - Q k s k) + (hfuture : ∀ k t, k < t → ∀ s : BranchPath U k, + Q k s t ≤ ∑ j : Fin (U+1), + Q (k+1) (Fin.snoc (α := fun _ : Fin (k+1) => Fin (U+1)) s j) t) + (n : ℕ) : + levelSum (P n) ≤ levelSum (P 0) - + ∑ t ∈ Finset.range n, levelSum (fun s => Q 0 s t) := by + induction n with + | zero => simp [levelSum] + | succ n ih => + have hs : levelSum (P (n+1)) ≤ levelSum (P n) - levelSum (fun s => Q n s n) := by + rw [levelSum_succ] + unfold levelSum + rw [← Finset.sum_sub_distrib] + exact Finset.sum_le_sum (fun s _ => hsplit n s) + have hq := level_future_lower U Q hfuture n n le_rfl + rw [Finset.sum_range_succ] + linarith + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLimit.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLimit.lean new file mode 100644 index 0000000000000000000000000000000000000000..5167ec91fc4b371bc76ebcbed334e1bed3e88eef --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTransportLimit.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerRootTransport + +namespace OAI + +/-! # The hard-zero limit of the actual integer transport + +The final bound contains only finite marginal and auxiliary defect sums, +minimum-endpoint graph energies, and the two positive endpoint masses. +Thus no limit of recursively defined coefficients is needed. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Topology +open FactorialSignatures BalancedFamily BalancedEnumeration IntegerMarginal Filter + +universe u + +variable {K : Type*} {l : Filter K} + +lemma auxiliaryKernel_tendsto {I : Type u} (Ms : List ℕ) + (F : K → (Coordinates I Ms → ℕ) → ℝ) (f : (Coordinates I Ms → ℕ) → ℝ) + (hlim : ∀ x, Tendsto (fun t => F t x) l (nhds (f x))) (z : I → ℕ) : + Tendsto (fun t => auxiliaryKernel Ms (F t) z) l (nhds (auxiliaryKernel Ms f z)) := by + induction Ms with + | nil => exact tendsto_const_nhds + | cons U Ms ih => + apply Tendsto.add + · unfold marginal + apply tendsto_finsetSum + intro j _ + exact eliminate_tendsto Ms _ _ (fun x => hlim _) _ + · apply ih + intro x + unfold marginal + apply tendsto_finsetSum + intro j _ + exact hlim _ + +lemma removal_tendsto {C : Type*} [DecidableEq C] + (F : K → (C → ℕ) → ℝ) (f : (C → ℕ) → ℝ) + (hlim : ∀ x, Tendsto (fun t => F t x) l (nhds (f x))) (z : C → ℕ) (i j : C) : + Tendsto (fun t => integerRemovalMatrix (F t) z i j) l + (nhds (integerRemovalMatrix f z i j)) := by + by_cases hv : ValidPair z i j + · simpa only [integerRemovalMatrix,hv,↓reduceIte] using hlim (removeTwo z i j) + · simpa only [integerRemovalMatrix,hv,↓reduceIte] using + (tendsto_const_nhds : Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + +lemma oneHole_tendsto {C : Type*} [DecidableEq C] + (F : K → (C → ℕ) → ℝ) (f : (C → ℕ) → ℝ) + (hlim : ∀ x, Tendsto (fun t => F t x) l (nhds (f x))) (z : C → ℕ) (i : C) : + Tendsto (fun t => oneHole (F t) z i) l (nhds (oneHole f z i)) := by + by_cases hi : 0 < z i + · simpa only [oneHole,hi,↓reduceIte] using hlim (removeOne z i) + · simpa only [oneHole,hi,↓reduceIte] using + (tendsto_const_nhds : Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + +lemma integerGraphEnergy_tendsto {C : Type*} [DecidableEq C] + (V : Finset (C → ℕ)) (F : K → (C → ℕ) → ℝ) (f H : (C → ℕ) → ℝ) + (hlim : ∀ x, Tendsto (fun t => F t x) l (nhds (f x))) : + Tendsto (fun t => integerGraphEnergy V (F t) H) l (nhds (integerGraphEnergy V f H)) := by + unfold integerGraphEnergy + apply Tendsto.div_const + apply tendsto_finsetSum + intro e _ + exact ((hlim e.1).min (hlim e.2)).mul_const _ + +lemma root_linear_eq (g : (Bool → ℕ) → ℝ) (z : Bool → ℕ) (s t : ℝ) : + holeLinear g z (rootCoefficients s t) = oneHole g z false/s-oneHole g z true/t := by + simp only [holeLinear,Fintype.sum_bool,rootCoefficients,Bool.false_eq_true,↓reduceIte] + ring + +/-- The original raw integer transport survives arbitrary hard zeros. +Only its two endpoint marginal masses must remain positive. -/ +theorem integer_root_graph_transport_limit [l.NeBot] (Ms : List ℕ) + (F : K → (Coordinates Bool Ms → ℕ) → ℝ) (f H : (Coordinates Bool Ms → ℕ) → ℝ) + (hlim : ∀ x, Tendsto (fun t => F t x) l (nhds (f x))) + (m z : Bool → ℕ) (R W : ℕ) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hsoft : ∀ᶠ t in l, (∀ x, 0 ≤ F t x) ∧ + BalancedBox.PositiveSlice (F t) (bounds m Ms) (R+Ms.sum) ∧ + BalancedBox.RemovalSlice (F t) (bounds m Ms) (R+Ms.sum)) + (hz : BalancedBox.InBox m z) (htotal : (∑ i, z i)=R+1) + (hs : 0 < oneHole (eliminate Ms f) z false) + (ht : 0 < oneHole (eliminate Ms f) z true) + (V : Finset (Coordinates Bool Ms → ℕ)) (hV : leafVertices Ms z ⊆ V) : + let s := oneHole (eliminate Ms f) z false + let t := oneHole (eliminate Ms f) z true + let c := integerRemovalMatrix (auxiliaryKernel Ms f) z false true + (oneHole (eliminate Ms (fun p => f p*H p)) z false/s - + oneHole (eliminate Ms (fun p => f p*H p)) z true/t)^2 ≤ + (1/s+1/t+2*((W:ℝ)+1)^2*c/(s*t)) * integerGraphEnergy V f H := by + dsimp only + have hmarg := eliminate_tendsto Ms F f hlim + have hnum := eliminate_tendsto Ms (fun t p => F t p*H p) (fun p => f p*H p) + (fun p => (hlim p).mul_const (H p)) + have hsm := oneHole_tendsto _ _ hmarg z false + have htm := oneHole_tendsto _ _ hmarg z true + have hsn := oneHole_tendsto _ _ hnum z false + have htn := oneHole_tendsto _ _ hnum z true + have hc := removal_tendsto _ _ (auxiliaryKernel_tendsto Ms F f hlim) z false true + have he := integerGraphEnergy_tendsto V F f H hlim + have hleft := ((hsn.div hsm (ne_of_gt hs)).sub (htn.div htm (ne_of_gt ht))).pow 2 + have h1 : Tendsto (fun _ : K => (1:ℝ)) l (nhds 1) := tendsto_const_nhds + have hright := (((h1.div hsm (ne_of_gt hs)).add + (h1.div htm (ne_of_gt ht))).add + ((hc.const_mul (2*((W:ℝ)+1)^2)).div (hsm.mul htm) (mul_ne_zero (ne_of_gt hs) (ne_of_gt ht)))).mul he + apply le_of_tendsto_of_tendsto hleft hright + have hspos : ∀ᶠ t in l, 0 < oneHole (eliminate Ms (F t)) z false := + hsm.eventually (lt_mem_nhds hs) + have htpos : ∀ᶠ t in l, 0 < oneHole (eliminate Ms (F t)) z true := + htm.eventually (lt_mem_nhds ht) + filter_upwards [hsoft,hspos,htpos] with t hf hsp htp + have hb := integer_root_graph_transport Ms (F t) H m z R W hlower hupper + hf.1 hf.2.1 hf.2.2 hz htotal hsp htp V hV + simpa only [root_linear_eq, Pi.div_apply] using hb + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTruncatedTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTruncatedTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..af5a1eb54a155614ee09bce860afafc829d71ece --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerTruncatedTransport.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportLimit +import OAI.Combinatorics.ContingencyTables.Transport.IntegerBoxTruncation + +namespace OAI + +/-! # Raw transport with the literal box and degree zero extension + +Excess-pair auxiliary sums may visit profiles outside the original box. +Their zero extension is therefore retained in the auxiliary count and +energy. Balanced endpoint masses and numerators are unchanged. +-/ + +namespace ContingencyTables.IntegerBoxTruncation + +open scoped BigOperators Classical Topology +open BalancedFamily BalancedBox FactorialSignatures IntegerWeightedTransport +open ProductIntegerSignature + +variable {C : Type*} [Fintype C] + +lemma truncate_nonnegative (f : (C → ℕ) → ℝ) (m : C → ℕ) (R : ℕ) + (hf : ∀ x, 0 ≤ f x) (x : C → ℕ) : 0 ≤ truncate f m R x := by + unfold truncate + split_ifs + · exact hf x + · exact le_rfl + +lemma truncate_mul (f H : (C → ℕ) → ℝ) (m : C → ℕ) (R : ℕ) : + (fun x => truncate f m R x*H x)=truncate (fun x => f x*H x) m R := by + funext x + unfold truncate + split_ifs <;> simp + +lemma truncate_tendsto {K : Type*} {l : Filter K} + (F : K → (C → ℕ) → ℝ) (f : (C → ℕ) → ℝ) (m : C → ℕ) (R : ℕ) + (hlim : ∀ x, Filter.Tendsto (fun t => F t x) l (nhds (f x))) (x : C → ℕ) : + Filter.Tendsto (fun t => truncate (F t) m R x) l (nhds (truncate f m R x)) := by + by_cases hx : InBox m x ∧ (∑ i, x i)=R + · simpa only [truncate,hx,and_self,↓reduceIte] using hlim x + · simpa only [truncate,hx,and_self,↓reduceIte] using + (tendsto_const_nhds : Filter.Tendsto (fun _ : K => (0:ℝ)) l (nhds 0)) + +lemma eliminate_truncate {I : Type*} [Fintype I] + (Ms : List ℕ) (f : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) + (hz : InBox m z) (htotal : (∑ i, z i)=R) : + eliminate Ms (truncate f (bounds m Ms) (R+Ms.sum)) z=eliminate Ms f z := by + apply eliminate_congr_slice Ms m R _ f _ z hz htotal + intro x hx ht + simp only [truncate,hx,ht,↓reduceIte,and_self] + +lemma active_removeOne_sum {I : Type*} [Fintype I] [DecidableEq I] + (z : I → ℕ) (i : I) (hi : 0 < z i) : + (∑ j, removeOne z i j)+1=∑ j, z j := by + have he : (∑ j, z j)=(∑ j, (removeOne z i j+if j=i then 1 else 0)) := by + apply Finset.sum_congr rfl + intro j _ + unfold removeOne + by_cases hj : j=i + · subst j + simp only [↓reduceIte] + omega + · simp only [hj,↓reduceIte,Nat.sub_zero,Nat.add_zero] + rw [Finset.sum_add_distrib] at he + simpa only [Finset.sum_ite_eq',Finset.mem_univ,↓reduceIte] using he.symm + +lemma active_truncate_removal {I : Type*} [Fintype I] [DecidableEq I] + (f : (I → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) + (hz : InBox m z) (htotal : (∑ i, z i)=R+2) : + integerRemovalMatrix (truncate f m R) z=integerRemovalMatrix f z := by + ext i j + unfold integerRemovalMatrix + split_ifs with hv + · have hb : InBox m (removeTwo z i j) := by + intro k + apply le_trans _ (hz k) + unfold removeTwo removeOne + omega + have hi : 0 < z i := hv.1 + have hj : 0 < removeOne z i j := by + simpa only [removeOne] using hv.2 + have h1 := active_removeOne_sum z i hi + have h2 := active_removeOne_sum (removeOne z i) j hj + have ht : (∑ k, removeTwo z i j k)=R := by + unfold removeTwo + omega + simp only [truncate,hb,ht,and_self,↓reduceIte] + · rfl + +lemma truncate_all_slices {I : Type*} [Fintype I] [DecidableEq I] + (f : (I → ℕ) → ℝ) (m : I → ℕ) (R : ℕ) + (hf : ∀ x, 0 ≤ f x) (hp : PositiveSlice f m R) (hs : RemovalSlice f m R) : + (∀ x, 0 ≤ truncate f m R x) ∧ PositiveSlice (truncate f m R) m R ∧ + RemovalSlice (truncate f m R) m R := by + refine ⟨truncate_nonnegative f m R hf,?_,?_⟩ + · intro z hz ht + simpa only [truncate,hz,ht,and_self,↓reduceIte] using hp z hz ht + · intro z hz ht + rw [active_truncate_removal f m z R hz ht] + exact hs z hz ht + +lemma oneHole_eliminate_truncate {I : Type*} [Fintype I] [DecidableEq I] + (Ms : List ℕ) (f : (Coordinates I Ms → ℕ) → ℝ) (m z : I → ℕ) (R : ℕ) + (hz : InBox m z) (htotal : (∑ i, z i)=R+1) (i : I) : + oneHole (eliminate Ms (truncate f (bounds m Ms) (R+Ms.sum))) z i= + oneHole (eliminate Ms f) z i := by + by_cases hi : 0 < z i + · simp only [oneHole,hi,↓reduceIte] + apply eliminate_truncate Ms f m (removeOne z i) R + · intro j + apply le_trans _ (hz j) + unfold removeOne + omega + · have h := active_removeOne_sum z i hi + omega + · simp only [oneHole,hi,↓reduceIte] + +end ContingencyTables.IntegerBoxTruncation + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Topology +open BalancedFamily BalancedBox IntegerBoxTruncation FactorialSignatures + +/-- Transport for the literal zero-extended weight. Its endpoint masses +and weighted means are still the original physical balanced sums. -/ +theorem integer_box_root_transport_limit {K : Type*} {l : Filter K} [l.NeBot] + (Ms : List ℕ) (F : K → (Coordinates Bool Ms → ℕ) → ℝ) + (f H : (Coordinates Bool Ms → ℕ) → ℝ) + (hlim : ∀ x, Filter.Tendsto (fun t => F t x) l (nhds (f x))) + (m z : Bool → ℕ) (R W : ℕ) + (hlower : ∀ U ∈ Ms, 2 ≤ U) (hupper : ∀ U ∈ Ms, U ≤ W) + (hsoft : ∀ᶠ t in l, (∀ x, 0 ≤ F t x) ∧ + PositiveSlice (F t) (bounds m Ms) (R+Ms.sum) ∧ + RemovalSlice (F t) (bounds m Ms) (R+Ms.sum)) + (hz : InBox m z) (htotal : (∑ i, z i)=R+1) + (hs : 0 < oneHole (eliminate Ms f) z false) + (ht : 0 < oneHole (eliminate Ms f) z true) + (V : Finset (Coordinates Bool Ms → ℕ)) (hV : leafVertices Ms z ⊆ V) : + let g := truncate f (bounds m Ms) (R+Ms.sum) + let s := oneHole (eliminate Ms f) z false + let t := oneHole (eliminate Ms f) z true + let c := integerRemovalMatrix (auxiliaryKernel Ms g) z false true + (oneHole (eliminate Ms (fun p => f p*H p)) z false/s- + oneHole (eliminate Ms (fun p => f p*H p)) z true/t)^2 ≤ + (1/s+1/t+2*((W:ℝ)+1)^2*c/(s*t))*integerGraphEnergy V g H := by + dsimp only + let M := bounds m Ms + let D := R+Ms.sum + have hF : ∀ᶠ t in l, (∀ x, 0 ≤ truncate (F t) M D x) ∧ + PositiveSlice (truncate (F t) M D) M D ∧ + RemovalSlice (truncate (F t) M D) M D := by + filter_upwards [hsoft] with t ht + exact truncate_all_slices (F t) M D ht.1 ht.2.1 ht.2.2 + have hs' : 0 < oneHole (eliminate Ms (truncate f M D)) z false := by + simpa only [M,D,oneHole_eliminate_truncate Ms f m z R hz htotal] using hs + have ht' : 0 < oneHole (eliminate Ms (truncate f M D)) z true := by + simpa only [M,D,oneHole_eliminate_truncate Ms f m z R hz htotal] using ht + have h := integer_root_graph_transport_limit Ms (fun t => truncate (F t) M D) + (truncate f M D) H (truncate_tendsto F f M D hlim) m z R W hlower hupper hF + hz htotal hs' ht' V hV + dsimp only at h + rw [truncate_mul] at h + simpa only [M,D,oneHole_eliminate_truncate Ms _ m z R hz htotal] using h + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerWeightedTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerWeightedTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..a20fab1674405c460f2b9819ea6d35f69f9c0e40 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/IntegerWeightedTransport.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerMarginal + +namespace OAI + +/-! +# The actual weighted integer pair estimate + +For first-paper transport the pair display has total B+1 and capacity B, +so only the interior matrices are valid. The potential identity uses +exactly those matrices and the actual cumulative cross entries; it never +assumes an endpoint matrix signature. +-/ + +namespace ContingencyTables.IntegerWeightedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures IntegerMarginal + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- The D'=B+1 weighted estimate for the actual raw integer removal forms. +The required balance is the zero total signed cross flow at the pair. -/ +theorem weighted_pair_potential + (F : ((I ⊕ Bool) → ℕ) → ℝ) (M : ℕ) (z : I → ℕ) (v : I → ℝ) + (hsig : ∀ j, 0 < j → j < M → + OnePositiveDirection (integerRemovalMatrix F (profile z j (M-j))).toBilin') + (hpos : ∀ j, 0 < j → j < M → 0 < F (profile z (j-1) (M-1-j))) + (hbalance : pairCumulative (cross F M z) v M = 0) : + 2*(∑ j ∈ Finset.range (M+1), innerWeight F M z j * + pairCoefficient (cross F M z) (innerWeight F M z) v j ^ 2) ≤ + -(∑ j ∈ Finset.range (M+1), (j:ℝ)*((M:ℝ)-j)* + (pairMatrix F M z j).toBilin' (old v) (old v)) := by + apply balancedPair_weighted_potential M (fun j => (pairMatrix F M z j).toBilin') old + (Pi.single (.inr false) 1) (Pi.single (.inr true) 1) (cross F M z) (innerWeight F M z) v + · intro j _ _ x y + exact (matrix_bilin_symm _ (integerRemoval_symm _ _)).eq x y + · exact hsig + · simp [innerWeight] + · simp [innerWeight] + · intro j hj0 hjM + have ht : 0 < j ∧ j < M := ⟨hj0,hjM⟩ + simpa only [innerWeight,ite_eq_left ht] using hpos j hj0 hjM + · exact hbalance + · intro j _ hjM; simpa using pairMatrix_aa F M z j hjM.le + · intro j _ hjM; simpa using pairMatrix_bb F M z j hjM.le + · intro j _ hjM; simpa using pairMatrix_ab F M z j hjM.le + · intro j _ hjM; exact cross_a F M z j hjM.le v + · intro j _ hjM; exact cross_b F M z j hjM.le v + +end ContingencyTables.IntegerWeightedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/LabelledFactorial.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/LabelledFactorial.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed90b28bdbee893cf27f428b025da70771201552 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/LabelledFactorial.lean @@ -0,0 +1,208 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FactorialSignatures + +namespace OAI + +/-! +# Literal subset factorial lifts and their conditioned copy displays + +A display is the actual subtype of available labelled elements. Its group +fibres are reindexed by Fin of their exact cardinalities. Removing or adding +actual labels changes the group counts by the exact integer updates, so the +conditioned subset matrices are congruent to the proved factorial copy +matrices. No binary-lift signature is assumed. +-/ + +namespace ContingencyTables.LabelledFactorial + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS BinaryContraction FactorialSignatures + +variable {I G : Type*} [Fintype I] [Fintype G] + +noncomputable def groupCount (group : I → G) (S : Set I) : G → ℕ := + fun u => (Finset.univ.filter (fun i => i ∈ S ∧ group i = u)).card + +omit [Fintype G] in +lemma groupCount_insert (group : I → G) (S : Set I) (i : I) (hi : i ∉ S) : + groupCount group (insert i S) = fun u => groupCount group S u + if u = group i then 1 else 0 := by + funext u + have heq : Finset.univ.filter (fun j => j ∈ insert i S ∧ group j = u) = + if group i = u then insert i (Finset.univ.filter (fun j => j ∈ S ∧ group j = u)) + else Finset.univ.filter (fun j => j ∈ S ∧ group j = u) := by + ext j + by_cases h : group i = u + · simp only [h, ite_true, Finset.mem_filter, Finset.mem_univ, true_and, + Set.mem_insert_iff, Finset.mem_insert] + constructor + · rintro ⟨hji | hjS, hjg⟩ + · exact Or.inl hji + · exact Or.inr ⟨hjS,hjg⟩ + · rintro (rfl | ⟨hjS,hjg⟩) + · exact ⟨Or.inl rfl,h⟩ + · exact ⟨Or.inr hjS,hjg⟩ + · simp only [h, ite_false, Finset.mem_filter, Finset.mem_univ, true_and, Set.mem_insert_iff] + constructor + · rintro ⟨rfl | hjS,hjg⟩ + · exact (h hjg).elim + · exact ⟨hjS,hjg⟩ + · rintro ⟨hjS,hjg⟩; exact ⟨Or.inr hjS,hjg⟩ + unfold groupCount + have hc := congrArg Finset.card heq + convert hc.trans ?_ using 1 + · congr 1; ext j; simp + · by_cases h : group i = u + · simp only [h, ite_true] + apply Finset.card_insert_of_notMem + simp [hi] + · simp [h, Ne.symm h] + +omit [Fintype G] in +lemma groupCount_remove (group : I → G) (S : Set I) (i : I) (hi : i ∈ S) : + groupCount group (S \ {i}) = removeOne (groupCount group S) (group i) := by + funext u + have heq : Finset.univ.filter (fun j => j ∈ S \ {i} ∧ group j = u) = + (Finset.univ.filter (fun j => j ∈ S ∧ group j = u)).erase i := by + ext j; simp; tauto + unfold groupCount removeOne + have hc := congrArg Finset.card heq + convert hc.trans ?_ using 1 + · congr 1; ext j; simp + · by_cases h : group i = u + · rw [Finset.card_erase_of_mem (by simp [hi,h])] + simp [h] + · rw [Finset.erase_eq_of_notMem (by simp [h])] + simp [Ne.symm h] + +omit [Fintype G] in +lemma groupCount_removeTwo (group : I → G) (S : Set I) (i j : I) + (hi : i ∈ S) (hj : j ∈ S) (hij : i ≠ j) : + groupCount group (S \ {i,j}) = removeTwo (groupCount group S) (group i) (group j) := by + have heq : S \ {i,j} = (S \ {i}) \ {j} := by ext x; simp; tauto + rw [heq, groupCount_remove group _ j (by simp [hj,hij.symm]), groupCount_remove group S i hi] + rfl + +omit [Fintype G] in +lemma groupCount_addTwo (group : I → G) (S : Set I) (i j : I) + (hi : i ∉ S) (hj : j ∉ S) (hij : i ≠ j) : + groupCount group (S ∪ {i,j}) = addTwo (groupCount group S) (group i) (group j) := by + have heq : S ∪ {i,j} = insert j (insert i S) := by ext x; simp; tauto + rw [heq, groupCount_insert group _ j (by simp [hj,hij.symm]), groupCount_insert group S i hi] + funext u + rfl + +omit [Fintype G] in +lemma fibre_card (group : I → G) (S : Set I) (u : G) : + Fintype.card {i : {i // i ∈ S} // group i.val = u} = groupCount group S u := by + let E : {i : {i // i ∈ S} // group i.val = u} ≃ + {i : I // i ∈ Finset.univ.filter (fun i => i ∈ S ∧ group i = u)} := + { toFun := fun i => ⟨i.val.val, by simp [i.val.property,i.property]⟩ + invFun := fun i => ⟨⟨i.val, by simpa using (Finset.mem_filter.mp i.property).2.1⟩, + (Finset.mem_filter.mp i.property).2.2⟩ + left_inv := fun i => rfl + right_inv := fun i => rfl } + exact (Fintype.card_congr E).trans (Fintype.card_coe _) + +/-- The actual finite display, reindexed fibre by fibre by its exact copy count. -/ +noncomputable def displayCopyEquiv (group : I → G) (S : Set I) : + {i // i ∈ S} ≃ Copies (groupCount group S) := + (Equiv.sigmaFiberEquiv (fun i : {i // i ∈ S} => group i.val)).symm.trans + (Equiv.sigmaCongrRight (fun u => Fintype.equivFinOfCardEq (fibre_card group S u))) + +omit [Fintype G] in +lemma displayCopyEquiv_group (group : I → G) (S : Set I) (i : {i // i ∈ S}) : + (displayCopyEquiv group S i).1 = group i.val := rfl + +lemma groupCount_total (group : I → G) (S : Set I) : + ∑ u, groupCount group S u = S.ncard := by + have h := Fintype.card_congr (displayCopyEquiv group S) + simp only [Copies, Fintype.card_sigma, Fintype.card_fin] at h + have hc : Fintype.card {i // i ∈ S} = S.ncard := by + exact Set.fintypeCard_eq_ncard S + omega + +noncomputable def firstLift (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (S : Set I) : ℝ := + h (groupCount group S) * factorialProduct (groupCount group S) / D + +noncomputable def secondLift (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (S : Set I) : ℝ := + h (groupCount group S) * factorialProduct (groupCount group Sᶜ) / D + +/-- Every entry of the literal subset omission matrix equals the copy +matrix entry at the canonical labels of the available display. -/ +theorem firstLift_omission_matrix (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (A : Set I) : + faceHessian (complementWeight (firstLift group h D)) A = + (removalLiftMatrix h (groupCount group Aᶜ) D).submatrix + (displayCopyEquiv group Aᶜ) (displayCopyEquiv group Aᶜ) := by + ext i j + by_cases hij : i = j + · simp [faceHessian, removalLiftMatrix, Matrix.submatrix_apply, hij] + have he : displayCopyEquiv group Aᶜ i ≠ displayCopyEquiv group Aᶜ j := + fun h => hij ((displayCopyEquiv group Aᶜ).injective h) + have hs : (A ∪ {i.val,j.val})ᶜ = Aᶜ \ {i.val,j.val} := by ext x; simp; tauto + have hval : i.val ≠ j.val := fun h => hij (Subtype.ext h) + simp only [faceHessian, hij, ite_false, Matrix.submatrix_apply, removalLiftMatrix, he, + complementWeight, firstLift, displayCopyEquiv_group] + rw [hs, groupCount_removeTwo group Aᶜ i.val j.val i.property j.property hval] + +/-- The literal second-lift addition matrix has the exact remaining-capacity +factorials of the canonical copy matrix. -/ +theorem secondLift_addition_matrix (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (A : Set I) : + faceHessian (secondLift group h D) A = + (additionLiftMatrix h (groupCount group A) (groupCount group Aᶜ) D).submatrix + (displayCopyEquiv group Aᶜ) (displayCopyEquiv group Aᶜ) := by + ext i j + by_cases hij : i = j + · simp [faceHessian, additionLiftMatrix, Matrix.submatrix_apply, hij] + have he : displayCopyEquiv group Aᶜ i ≠ displayCopyEquiv group Aᶜ j := + fun h => hij ((displayCopyEquiv group Aᶜ).injective h) + have hs : (A ∪ {i.val,j.val})ᶜ = Aᶜ \ {i.val,j.val} := by ext x; simp; tauto + have hval : i.val ≠ j.val := fun h => hij (Subtype.ext h) + simp only [faceHessian, hij, ite_false, Matrix.submatrix_apply, additionLiftMatrix, he, + secondLift, displayCopyEquiv_group] + rw [hs, groupCount_removeTwo group Aᶜ i.val j.val i.property j.property hval, + groupCount_addTwo group A i.val j.val i.property j.property hval] + +/-- Integer removal signatures imply the omission property of the literal +first factorial lift, through the proved exact copy-display congruence. -/ +theorem firstLift_omission (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (k : ℕ) + (hD : 0 < D) (hh : ∀ n, 0 ≤ h n) + (hsig : ∀ A : Set I, A.ncard + 2 = Fintype.card I - k → + OnePositiveDirection (integerRemovalMatrix h (groupCount group Aᶜ)).toBilin') : + OmissionProperty (firstLift group h D) k := by + intro A hA + rw [firstLift_omission_matrix] + apply onePositive_reindex (displayCopyEquiv group Aᶜ) + have hs := removalLift_onePositive h (groupCount group Aᶜ) D hD hh (hsig A hA) + have hm := (signature_iff _ (matrix_bilin_symm _ (show ∀ i j, + removalLiftMatrix h (groupCount group Aᶜ) D i j = + removalLiftMatrix h (groupCount group Aᶜ) D j i from by + intro i j + simp only [removalLiftMatrix, eq_comm, removeTwo_comm]))).mp hs + convert hm using 1 + congr 2; exact Subsingleton.elim _ _ + +/-- Integer addition signatures imply the addition property of the literal +complementary-factorial lift. -/ +theorem secondLift_addition (group : I → G) (h : (G → ℕ) → ℝ) (D : ℝ) (k : ℕ) + (hD : 0 < D) (hh : ∀ n, 0 ≤ h n) + (hsig : ∀ A : Set I, A.ncard + 2 = k → + OnePositiveDirection (integerAdditionMatrix h (groupCount group A) (groupCount group Aᶜ)).toBilin') : + AdditionProperty (secondLift group h D) k := by + intro A hA + rw [secondLift_addition_matrix] + apply onePositive_reindex (displayCopyEquiv group Aᶜ) + have hs := additionLift_onePositive h (groupCount group A) (groupCount group Aᶜ) D hD hh (hsig A hA) + have hsymm : ∀ i j, additionLiftMatrix h (groupCount group A) (groupCount group Aᶜ) D i j = + additionLiftMatrix h (groupCount group A) (groupCount group Aᶜ) D j i := by + intro i j + have ha : addTwo (groupCount group A) i.1 j.1 = addTwo (groupCount group A) j.1 i.1 := by + funext u + unfold addTwo + omega + simp only [additionLiftMatrix, eq_comm, removeTwo_comm, ha] + have hm := (signature_iff _ (matrix_bilin_symm _ hsymm)).mp hs + convert hm using 1 + congr 2; exact Subsingleton.elim _ _ + +end ContingencyTables.LabelledFactorial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/LaminarSignature.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/LaminarSignature.lean new file mode 100644 index 0000000000000000000000000000000000000000..f069f200d9b4966656117b4d0a73a8317a6d5fc1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/LaminarSignature.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.ContingencyTables.Transport.QuadraticTransport +import Mathlib.LinearAlgebra.Matrix.BilinearForm + +namespace OAI + +/-! +# The two-level laminar kernel in contingency-table weights + +The factor groups in the sampling paper's laminar-signature lemma are line +coordinate sets, with one nested small-slot subset in each line. Row and +column coordinates belong to separate lines. The normalized kernel +decomposition gives the quadratic one-positive-direction property. +-/ + +namespace ContingencyTables + +open scoped BigOperators +open LinearMap (BilinForm) + +section TwoLevel + +variable {I G : Type*} [Fintype I] [DecidableEq I] [Fintype G] [DecidableEq G] + +/-- The normalized two-removal kernel: line factors and the nested small +coordinate factor are the only factors shared by two distinct indices. -/ +def twoLevelKernel (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) : + Matrix I I ℝ := fun i j => + if line i = line j then + γ (line i) * (if inner i = true ∧ inner j = true then δ (line i) else 1) + else 1 + +/-- Indicator of one line-coordinate group. -/ +def lineVector (line : I → G) (g : G) (i : I) : ℝ := + if line i = g then 1 else 0 + +/-- Indicator of the small-coordinate subgroup of one line. -/ +def innerVector (line : I → G) (inner : I → Bool) (g : G) (i : I) : ℝ := + if line i = g ∧ inner i = true then 1 else 0 + +/-- The rank-one matrix associated with a vector. -/ +def outerMatrix (v : I → ℝ) : Matrix I I ℝ := fun i j => v i * v j + +/-- The linear sum of the coordinates weighted by `v`. -/ +def vectorSum (v : I → ℝ) : (I → ℝ) →ₗ[ℝ] ℝ := + ∑ i, v i • LinearMap.proj i + +omit [DecidableEq I] in +lemma vectorSum_apply (v x : I → ℝ) : vectorSum v x = ∑ i, v i * x i := by + simp [vectorSum] + +lemma outerMatrix_form (v x y : I → ℝ) : + (outerMatrix v).toBilin' x y = vectorSum v x * vectorSum v y := by + rw [Matrix.toBilin'_apply, vectorSum_apply, vectorSum_apply] + simp only [outerMatrix] + have hprod (i j : I) : x i * (v i * v j) * y j = (v i * x i) * (v j * y j) := by + ring + simp_rw [hprod, ← Finset.mul_sum] + rw [← Finset.sum_mul] + +omit [Fintype I] [DecidableEq I] in +/-- The precise rank-one-minus-blocks identity for the line/inner family. -/ +theorem twoLevelKernel_decomposition (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) : + twoLevelKernel line inner γ δ = + outerMatrix (fun _ : I => 1) - + ∑ g, ((1 - γ g) • outerMatrix (lineVector line g) + + (γ g * (1 - δ g)) • outerMatrix (innerVector line inner g)) := by + ext i j + simp only [Matrix.sub_apply, Matrix.sum_apply, Matrix.add_apply, Matrix.smul_apply, + smul_eq_mul, outerMatrix] + rw [Finset.sum_eq_single (line i)] + · by_cases hline : line i = line j + · by_cases hi : inner i = true <;> by_cases hj : inner j = true <;> + simp [twoLevelKernel, lineVector, innerVector, hline, hi, hj] + all_goals ring + · have hline' : line j ≠ line i := Ne.symm hline + simp [twoLevelKernel, lineVector, innerVector, hline, hline'] + · intro g _ hg + have hg' : line i ≠ g := Ne.symm hg + simp [lineVector, innerVector, hg'] + · simp + +/-- The corresponding bilinear decomposition makes the squares explicit +when both arguments are equal. -/ +theorem twoLevelKernel_form (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) + (x y : I → ℝ) : + (twoLevelKernel line inner γ δ).toBilin' x y = + vectorSum (fun _ : I => 1) x * vectorSum (fun _ : I => 1) y - + ∑ g, ((1 - γ g) * (vectorSum (lineVector line g) x * vectorSum (lineVector line g) y) + + (γ g * (1 - δ g)) * + (vectorSum (innerVector line inner g) x * vectorSum (innerVector line inner g) y)) := by + rw [twoLevelKernel_decomposition] + simp only [map_sub, map_sum, map_add, map_smul, LinearMap.sub_apply, + LinearMap.sum_apply, LinearMap.add_apply, LinearMap.smul_apply, smul_eq_mul, + outerMatrix_form] + +/-- The line/inner two-removal kernel has positive inertia at most one in +quadratic-form language. Its proof uses the actual matrix decomposition. -/ +theorem twoLevelKernel_onePositive (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) + (hγ0 : ∀ g, 0 ≤ γ g) (hγ1 : ∀ g, γ g ≤ 1) (hδ1 : ∀ g, δ g ≤ 1) : + OnePositiveDirection (twoLevelKernel line inner γ δ).toBilin' := by + refine onePositiveDirection_of_kernel _ ?_ (vectorSum (fun _ : I => 1)) ?_ + · intro x y + rw [twoLevelKernel_form, twoLevelKernel_form] + congr 1 + · ring + · apply Finset.sum_congr rfl + intro g _ + ring + · intro v hv + rw [twoLevelKernel_form, hv, zero_mul, zero_sub] + apply neg_nonpos.mpr + apply Finset.sum_nonneg + intro g _ + apply add_nonneg + · exact mul_nonneg (sub_nonneg.mpr (hγ1 g)) (mul_self_nonneg _) + · exact mul_nonneg (mul_nonneg (hγ0 g) (sub_nonneg.mpr (hδ1 g))) (mul_self_nonneg _) + +/-- The bilinear kernel is symmetric even before positivity assumptions. -/ +lemma twoLevelKernel_form_symm (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) + (x y : I → ℝ) : + (twoLevelKernel line inner γ δ).toBilin' x y = + (twoLevelKernel line inner γ δ).toBilin' y x := by + rw [twoLevelKernel_form, twoLevelKernel_form] + congr 1 + · ring + · apply Finset.sum_congr rfl + intro g _ + ring + +/-- The normalized kernel is nonpositive on the zero-sum hyperplane. -/ +theorem twoLevelKernel_nonpositive (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) + (hγ0 : ∀ g, 0 ≤ γ g) (hγ1 : ∀ g, γ g ≤ 1) (hδ1 : ∀ g, δ g ≤ 1) + (v : I → ℝ) (hv : vectorSum (fun _ : I => 1) v = 0) : + (twoLevelKernel line inner γ δ).toBilin' v v ≤ 0 := by + rw [twoLevelKernel_form, hv, zero_mul, zero_sub] + apply neg_nonpos.mpr + apply Finset.sum_nonneg + intro g _ + apply add_nonneg + · exact mul_nonneg (sub_nonneg.mpr (hγ1 g)) (mul_self_nonneg _) + · exact mul_nonneg (mul_nonneg (hγ0 g) (sub_nonneg.mpr (hδ1 g))) (mul_self_nonneg _) + +def scaledMatrix (K : Matrix I I ℝ) (α : I → ℝ) : Matrix I I ℝ := + fun i j => α i * K i j * α j + +/-- Undo diagonal normalization and subtract the entries corresponding to +invalid repeated removals. Zero scale coordinates also restore zero rows. -/ +def weightedCorrection (K : Matrix I I ℝ) (W : ℝ) (α κ : I → ℝ) : Matrix I I ℝ := + W • scaledMatrix K α - Matrix.diagonal κ + +lemma scaledMatrix_form (K : Matrix I I ℝ) (α x y : I → ℝ) : + (scaledMatrix K α).toBilin' x y = + K.toBilin' (fun i => α i * x i) (fun i => α i * y i) := by + rw [Matrix.toBilin'_apply, Matrix.toBilin'_apply] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + dsimp [scaledMatrix] + ring + +lemma diagonalMatrix_form (κ x y : I → ℝ) : + (Matrix.diagonal κ).toBilin' x y = ∑ i, κ i * x i * y i := by + rw [Matrix.toBilin'_apply] + apply Finset.sum_congr rfl + intro i _ + simp only [Matrix.diagonal_apply, mul_ite, mul_zero, ite_mul, zero_mul, + Finset.sum_ite_eq, Finset.mem_univ, ite_true] + ring + +/-- The exact quadratic effect of scaling and invalid-diagonal removal. -/ +theorem weightedCorrection_form (K : Matrix I I ℝ) (W : ℝ) (α κ x y : I → ℝ) : + (weightedCorrection K W α κ).toBilin' x y = + W * K.toBilin' (fun i => α i * x i) (fun i => α i * y i) - + ∑ i, κ i * x i * y i := by + simp only [weightedCorrection, map_sub, map_smul, LinearMap.sub_apply, + LinearMap.smul_apply, smul_eq_mul, scaledMatrix_form, diagonalMatrix_form] + +/-- This includes the full unsummed two-removal signature: positive scalar +and diagonal congruence, invalid diagonals removed, zero rows restored. -/ +theorem correctedTwoLevel_onePositive (line : I → G) (inner : I → Bool) (γ δ : G → ℝ) + (W : ℝ) (α κ : I → ℝ) + (hγ0 : ∀ g, 0 ≤ γ g) (hγ1 : ∀ g, γ g ≤ 1) (hδ1 : ∀ g, δ g ≤ 1) + (hW : 0 ≤ W) (hκ : ∀ i, 0 ≤ κ i) : + OnePositiveDirection (weightedCorrection (twoLevelKernel line inner γ δ) W α κ).toBilin' := by + refine onePositiveDirection_of_kernel _ ?_ (vectorSum α) ?_ + · intro x y + rw [weightedCorrection_form, weightedCorrection_form, + twoLevelKernel_form_symm line inner γ δ] + congr 1 + apply Finset.sum_congr rfl + intro i _ + ring + · intro v hv + have hsum : vectorSum (fun _ : I => 1) (fun i => α i * v i) = 0 := by + simpa only [vectorSum_apply, one_mul] using hv + have hK := twoLevelKernel_nonpositive line inner γ δ hγ0 hγ1 hδ1 + (fun i => α i * v i) hsum + have hnegative := mul_nonpos_of_nonneg_of_nonpos hW hK + have hdiagonal : 0 ≤ ∑ i, κ i * v i * v i := by + apply Finset.sum_nonneg + intro i _ + have h := mul_nonneg (hκ i) (mul_self_nonneg (v i)) + nlinarith + rw [weightedCorrection_form] + linarith + +end TwoLevel + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/LayeredTableNetwork.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/LayeredTableNetwork.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bee4cd87e5e00968314225858af9932d9abc6bf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/LayeredTableNetwork.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.ContingencyTables.Model +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpAlgorithm +import Mathlib.Data.Fintype.Sum +import Mathlib.Tactic.Positivity + +namespace OAI + +/-! # The source-row-column-sink network for bounded tables + +The only nonzero capacities are the three layers prescribed in the +manuscript. Both antiparallel orientations are stored as one skew flow. +-/ + +namespace ContingencyTables.LayeredTableNetwork + +open scoped BigOperators + +abbrev Vertex (m n : ℕ) := Bool ⊕ (Fin m ⊕ Fin n) + +variable {m n : ℕ} + +def source : Vertex m n := Sum.inl false +def sink : Vertex m n := Sum.inl true +def row (i : Fin m) : Vertex m n := Sum.inr (Sum.inl i) +def column (j : Fin n) : Vertex m n := Sum.inr (Sum.inr j) + +def capacity (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) : + Vertex m n → Vertex m n → ℕ + | .inl false,.inr (.inl i) => r i + | .inr (.inl i),.inr (.inr j) => b i j + | .inr (.inr j),.inl true => c j + | _,_ => 0 + +def Feasible (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (f : Vertex m n → Vertex m n → ℤ) : Prop := + (∀ u v,f u v= -f v u) ∧ + (∀ u v,f u v≤capacity r c b u v) ∧ + ∀ u,u≠source → u≠sink → (∑ v,f u v)=0 + +def value (f : Vertex m n → Vertex m n → ℤ) : ℤ := ∑ v,f source v + +def tableFlow (r : Fin m → ℕ) (c : Fin n → ℕ) (X : Fin m → Fin n → ℕ) : + Vertex m n → Vertex m n → ℤ + | .inl false,.inr (.inl i) => r i + | .inr (.inl i),.inl false => -(r i:ℤ) + | .inr (.inl i),.inr (.inr j) => X i j + | .inr (.inr j),.inr (.inl i) => -(X i j:ℤ) + | .inr (.inr j),.inl true => c j + | .inl true,.inr (.inr j) => -(c j:ℤ) + | _,_ => 0 + +lemma capacity_diagonal (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (v : Vertex m n) : capacity r c b v v=0 := by + rcases v with a | (i | j) + · cases a <;> rfl + · rfl + · rfl + +lemma tableFlow_skew (r : Fin m → ℕ) (c : Fin n → ℕ) (X : Fin m → Fin n → ℕ) : + ∀ u v,tableFlow r c X u v= -tableFlow r c X v u := by + rintro (a | i | j) (d | k | l) + all_goals (try cases a) <;> (try cases d) <;> simp [tableFlow] + +theorem tableFlow_feasible (r : Fin m → ℕ) (c : Fin n → ℕ) + (b X : Fin m → Fin n → ℕ) (hm : HasMargins X r c) (hb : ∀ i j,X i j≤b i j) : + Feasible r c b (tableFlow r c X) := by + refine ⟨tableFlow_skew r c X,?_,?_⟩ + · rintro (a | i | j) (d | k | l) + all_goals (try cases a) <;> (try cases d) <;> simp [tableFlow,capacity] + all_goals exact_mod_cast hb _ _ + · rintro (a | i | j) hs ht + · cases a + · exact False.elim (hs rfl) + · exact False.elim (ht rfl) + · have h : (∑ j,(X i j:ℤ))=(r i:ℤ) := by exact_mod_cast hm.1 i + simp [Fintype.sum_sum_type,tableFlow,h] + · have h : (∑ i,(X i j:ℤ))=(c j:ℤ) := by exact_mod_cast hm.2 j + simp [Fintype.sum_sum_type,tableFlow,h] + +theorem tableFlow_value (r : Fin m → ℕ) (c : Fin n → ℕ) + (X : Fin m → Fin n → ℕ) : value (tableFlow r c X)=∑ i,(r i:ℤ) := by + simp [value,source,tableFlow,Fintype.sum_sum_type] + +lemma zero_of_no_capacity (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (u v : Vertex m n) + (huv : capacity r c b u v=0) (hvu : capacity r c b v u=0) : f u v=0 := by + have h1 := hf.2.1 u v + have h2 := hf.2.1 v u + rw [huv] at h1 + rw [hvu] at h2 + have hs := hf.1 u v + omega + +lemma row_column_nonnegative (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (i : Fin m) (j : Fin n) : 0≤f (row i) (column j) := by + have h := hf.2.1 (column j) (row i) + have hs := hf.1 (row i) (column j) + change f (column j) (row i)≤(0:ℤ) at h + omega + +lemma source_value (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) : value f=∑ i,f source (row i) := by + have hss : f source source=0 := by have h:=hf.1 source source; omega + have hst : f source sink=0 := zero_of_no_capacity r c b f hf _ _ rfl rfl + have hsc : ∀ j,f source (column j)=0 := fun j=> + zero_of_no_capacity r c b f hf _ _ rfl rfl + simp only [source,sink,column] at hss hst hsc + simp [value,source,row,Fintype.sum_sum_type,hss,hst,hsc] + +theorem value_le_total (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) : value f≤∑ i,(r i:ℤ) := by + rw [source_value r c b f hf] + exact Finset.sum_le_sum (fun i _=>hf.2.1 source (row i)) + +lemma row_balance (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (i : Fin m) : + (∑ j,f (row i) (column j))=f source (row i) := by + have hr : ∀ k,f (row i) (row k)=0 := fun k=> + zero_of_no_capacity r c b f hf _ _ rfl rfl + have ht : f (row i) sink=0 := zero_of_no_capacity r c b f hf _ _ rfl rfl + have hs := hf.1 (row i) source + have h := hf.2.2 (row i) (by simp [row,source]) (by simp [row,sink]) + have he : (∑ v,f (row i) v)=f (row i) source+(∑ j,f (row i) (column j)) := by + simp only [row,sink] at hr ht + simp [Fintype.sum_sum_type,source,row,column,hr,ht] + rw [he] at h + omega + +lemma column_balance (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (j : Fin n) : + (∑ i,f (row i) (column j))=f (column j) sink := by + have hc : ∀ k,f (column j) (column k)=0 := fun k=> + zero_of_no_capacity r c b f hf _ _ rfl rfl + have hs : f (column j) source=0 := zero_of_no_capacity r c b f hf _ _ rfl rfl + have hneg : ∀ i,f (column j) (row i)= -f (row i) (column j) := + fun i=>hf.1 _ _ + have h := hf.2.2 (column j) (by simp [column,source]) (by simp [column,sink]) + have he : (∑ v,f (column j) v)=f (column j) sink-(∑ i,f (row i) (column j)) := by + simp only [row,column,source] at hc hs hneg + simp [Fintype.sum_sum_type,sink,row,column,hc,hs,hneg,sub_eq_add_neg] + rw [he] at h + omega + +lemma saturation {q : ℕ} (f g : Fin q → ℤ) (hfg : ∀ i,f i≤g i) + (hs : (∑ i,f i)=∑ i,g i) : ∀ i,f i=g i := by + have hsum : (∑ i,(g i-f i))=0 := by + rw [Finset.sum_sub_distrib,hs] + omega + have hz := (Finset.sum_eq_zero_iff_of_nonneg (fun i _=>sub_nonneg.mpr (hfg i))).mp hsum + intro i + have hi := hz i (Finset.mem_univ i) + omega + +lemma source_saturated (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (hv : value f=∑ i,(r i:ℤ)) : + ∀ i,f source (row i)=r i := by + apply saturation + · intro i + exact hf.2.1 source (row i) + · simpa only [source_value r c b f hf] using hv + +lemma column_saturated (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (hv : value f=∑ i,(r i:ℤ)) + (htotal : (∑ i,r i)=∑ j,c j) : + ∀ j,f (column j) sink=c j := by + apply saturation + · intro j + exact hf.2.1 (column j) sink + · calc + (∑ j,f (column j) sink) = ∑ j,∑ i,f (row i) (column j) := by + apply Finset.sum_congr rfl + intro j _ + exact (column_balance r c b f hf j).symm + _ = ∑ i,∑ j,f (row i) (column j) := Finset.sum_comm + _ = ∑ i,(r i:ℤ) := by + apply Finset.sum_congr rfl + intro i _ + exact (row_balance r c b f hf i).trans (source_saturated r c b f hf hv i) + _ = ∑ j,(c j:ℤ) := by exact_mod_cast htotal + +def decode (f : Vertex m n → Vertex m n → ℤ) (i : Fin m) (j : Fin n) : ℕ := + (f (row i) (column j)).toNat + +theorem decode_boundedTable (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (f : Vertex m n → Vertex m n → ℤ) + (hf : Feasible r c b f) (hv : value f=∑ i,(r i:ℤ)) + (htotal : (∑ i,r i)=∑ j,c j) : + HasMargins (decode f) r c ∧ ∀ i j,decode f i j≤b i j := by + have hd : ∀ i j,(decode f i j:ℤ)=f (row i) (column j) := fun i j=> + Int.toNat_of_nonneg (row_column_nonnegative r c b f hf i j) + refine ⟨⟨?_,?_⟩,?_⟩ + · intro i + have he : (∑ j,(decode f i j:ℤ))=(r i:ℤ) := by + simp only [hd] + exact (row_balance r c b f hf i).trans (source_saturated r c b f hf hv i) + exact_mod_cast he + · intro j + have he : (∑ i,(decode f i j:ℤ))=(c j:ℤ) := by + simp only [hd] + exact (column_balance r c b f hf j).trans + (column_saturated r c b f hf hv htotal j) + exact_mod_cast he + · intro i j + have he := hf.2.1 (row i) (column j) + change f (row i) (column j)≤(b i j:ℤ) at he + rw [←hd] at he + exact_mod_cast he + +end ContingencyTables.LayeredTableNetwork + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/LineUnarySignature.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/LineUnarySignature.lean new file mode 100644 index 0000000000000000000000000000000000000000..99093ed18e8825a8e50365326accd5e589a2b741 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/LineUnarySignature.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Transport.LaminarSignature + +namespace OAI + +/-! +# The line and unary factors of the bounded-table application + +The bounded-table signature argument uses disjoint row/column line factors +and unary tree penalties. Factoring the product after two removals expresses +unary factors as nonnegative diagonal corrections of the line kernel. +-/ + +namespace ContingencyTables + +open scoped BigOperators + +section Products + +variable {A : Type*} [Fintype A] [DecidableEq A] + +def productTwoUpdates (a₀ a₁ a₂ : A → ℝ) (i j : A) : ℝ := + ∏ k, if k = i then (if k = j then a₂ k else a₁ k) + else (if k = j then a₁ k else a₀ k) + +/-- Exact factorization of the actual product after two coordinate changes, +including a repeated change of the same coordinate. -/ +theorem productTwoUpdates_factor (a₀ a₁ a₂ : A → ℝ) + (h₀ : ∀ k, a₀ k ≠ 0) (h₁ : ∀ k, a₁ k ≠ 0) (i j : A) : + productTwoUpdates a₀ a₁ a₂ i j = + (∏ k, a₀ k) * (a₁ i / a₀ i) * (a₁ j / a₀ j) * + (if i = j then a₀ i * a₂ i / (a₁ i) ^ 2 else 1) := by + have hterm (k : A) : + (if k = i then (if k = j then a₂ k else a₁ k) + else (if k = j then a₁ k else a₀ k)) = + a₀ k * (if k = i then a₁ k / a₀ k else 1) * + (if k = j then a₁ k / a₀ k else 1) * + (if k = i ∧ i = j then a₀ k * a₂ k / (a₁ k) ^ 2 else 1) := by + by_cases hi : k = i + · subst k + by_cases hij : i = j + · subst j + simp only [ite_true, and_self] + field_simp [h₀ i, h₁ i] + · simp only [ite_true, hij, ite_false, and_false, mul_one] + field_simp [h₀ i] + · by_cases hj : k = j + · subst k + simp only [hi, ite_false, ite_true, false_and, mul_one] + field_simp [h₀ j] + · simp [hi, hj] + unfold productTwoUpdates + simp_rw [hterm, Finset.prod_mul_distrib] + have hlast : (∏ k, if k = i ∧ i = j then a₀ k * a₂ k / (a₁ k) ^ 2 else 1) = + if i = j then a₀ i * a₂ i / (a₁ i) ^ 2 else 1 := by + by_cases h : i = j <;> simp [h] + rw [hlast] + simp only [Finset.prod_ite_eq', Finset.mem_univ, ite_true] + +end Products + +section LineUnary + +variable {I G : Type*} [Fintype I] [DecidableEq I] [Fintype G] [DecidableEq G] + +/-- Values of every line factor and every unary factor after zero, one, +and two removals give exactly this two-removal matrix. -/ +def lineUnaryRemoval (line : I → G) (a₀ a₁ a₂ : G → ℝ) (b₀ b₁ b₂ : I → ℝ) : + Matrix I I ℝ := fun i j => + productTwoUpdates a₀ a₁ a₂ (line i) (line j) * productTwoUpdates b₀ b₁ b₂ i j + +theorem lineUnaryRemoval_factor (line : I → G) (a₀ a₁ a₂ : G → ℝ) (b₀ b₁ b₂ : I → ℝ) + (ha₀ : ∀ g, a₀ g ≠ 0) (ha₁ : ∀ g, a₁ g ≠ 0) + (hb₀ : ∀ i, b₀ i ≠ 0) (hb₁ : ∀ i, b₁ i ≠ 0) (i j : I) : + lineUnaryRemoval line a₀ a₁ a₂ b₀ b₁ b₂ i j = + ((∏ g, a₀ g) * ∏ k, b₀ k) * + ((a₁ (line i) / a₀ (line i)) * (b₁ i / b₀ i)) * + ((a₁ (line j) / a₀ (line j)) * (b₁ j / b₀ j)) * + (if line i = line j then a₀ (line i) * a₂ (line i) / (a₁ (line i)) ^ 2 else 1) * + (if i = j then b₀ i * b₂ i / (b₁ i) ^ 2 else 1) := by + rw [lineUnaryRemoval, productTwoUpdates_factor a₀ a₁ a₂ ha₀ ha₁, + productTwoUpdates_factor b₀ b₁ b₂ hb₀ hb₁] + ring + +omit [Fintype I] [Fintype G] in +private theorem normalized_line_unary_correction (line : I → G) (W : ℝ) + (α : I → ℝ) (γ : G → ℝ) (δ : I → ℝ) : + (fun i j => W * α i * α j * (if line i = line j then γ (line i) else 1) * + (if i = j then δ i else 1)) = + weightedCorrection (twoLevelKernel line (fun _ => false) γ (fun _ => 1)) W α + (fun i => W * α i ^ 2 * γ (line i) * (1 - δ i)) := by + ext i j + by_cases hij : i = j + · subst j + simp only [weightedCorrection, scaledMatrix, twoLevelKernel, Matrix.sub_apply, + Matrix.smul_apply, smul_eq_mul, Matrix.diagonal_apply, ite_true, + Bool.false_eq_true, false_and, ite_false, mul_one] + ring + · by_cases hline : line i = line j <;> + simp [weightedCorrection, scaledMatrix, twoLevelKernel, hij, hline] <;> ring + +/-- The actual line/unary two-removal matrix has the required signature +when each factor satisfies its scalar log-concavity inequality. -/ +theorem lineUnaryRemoval_onePositive (line : I → G) + (a₀ a₁ a₂ : G → ℝ) (b₀ b₁ b₂ : I → ℝ) + (ha₀ : ∀ g, 0 < a₀ g) (ha₁ : ∀ g, 0 < a₁ g) (ha₂ : ∀ g, 0 ≤ a₂ g) + (hb₀ : ∀ i, 0 < b₀ i) (hb₁ : ∀ i, 0 < b₁ i) + (halc : ∀ g, a₀ g * a₂ g ≤ (a₁ g) ^ 2) + (hblc : ∀ i, b₀ i * b₂ i ≤ (b₁ i) ^ 2) : + OnePositiveDirection (lineUnaryRemoval line a₀ a₁ a₂ b₀ b₁ b₂).toBilin' := by + let W := (∏ g, a₀ g) * ∏ i, b₀ i + let α : I → ℝ := fun i => (a₁ (line i) / a₀ (line i)) * (b₁ i / b₀ i) + let γ : G → ℝ := fun g => a₀ g * a₂ g / (a₁ g) ^ 2 + let δ : I → ℝ := fun i => b₀ i * b₂ i / (b₁ i) ^ 2 + let K := twoLevelKernel line (fun _ => false) γ (fun _ => 1) + let κ : I → ℝ := fun i => W * α i ^ 2 * γ (line i) * (1 - δ i) + have hW : 0 ≤ W := mul_nonneg + (Finset.prod_nonneg fun g _ => (ha₀ g).le) (Finset.prod_nonneg fun i _ => (hb₀ i).le) + have hγ₀ (g : G) : 0 ≤ γ g := + div_nonneg (mul_nonneg (ha₀ g).le (ha₂ g)) (sq_nonneg _) + have hγ₁ (g : G) : γ g ≤ 1 := by + exact (div_le_one (sq_pos_of_pos (ha₁ g))).mpr (halc g) + have hδ₁ (i : I) : δ i ≤ 1 := by + exact (div_le_one (sq_pos_of_pos (hb₁ i))).mpr (hblc i) + have hκ (i : I) : 0 ≤ κ i := + mul_nonneg (mul_nonneg (mul_nonneg hW (sq_nonneg _)) (hγ₀ _)) + (sub_nonneg.mpr (hδ₁ i)) + have heq : lineUnaryRemoval line a₀ a₁ a₂ b₀ b₁ b₂ = weightedCorrection K W α κ := by + rw [← normalized_line_unary_correction line W α γ δ] + ext i j + exact lineUnaryRemoval_factor line a₀ a₁ a₂ b₀ b₁ b₂ + (fun g => ne_of_gt (ha₀ g)) (fun g => ne_of_gt (ha₁ g)) + (fun i => ne_of_gt (hb₀ i)) (fun i => ne_of_gt (hb₁ i)) i j + rw [heq] + exact correctedTwoLevel_onePositive line (fun _ => false) γ (fun _ => 1) + W α κ hγ₀ hγ₁ (fun _ => le_refl _) hW hκ + +end LineUnary + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListBitProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListBitProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fff867bc73443efa3f6d1e289ff2a41aa324e3f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListBitProposal.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawDecidableEq +import Mathlib.Data.List.Nodup + +namespace OAI + +/-! # Dyadic proposals from an explicit list without repeated entries -/ + +namespace ContingencyTables.FairBits +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +variable {X : Type*} [Fintype X] [DecidableEq X] + +/-- Read a binary index; every index beyond the list gives a hold. -/ +def listBitDraw (xs : List X) (k : ℕ) (bits : Fin k → Bool) : Option X := + xs[(binaryWordEquiv k bits).val]? + +omit [Fintype X] [DecidableEq X] in +lemma listIndex_eq_iff (xs : List X) (hn : xs.Nodup) (k : ℕ) + (hlen : xs.length ≤ 2^k) (i : ℕ) (hi : i xs[b.val]?)).mass (some x)= + if x∈xs then 1/(2:ℚ)^k else 0 := by + by_cases hx : x∈xs + · obtain ⟨i,hi,hix⟩ := List.mem_iff_getElem.mp hx + have he (b : Fin (2^k)) : xs[b.val]?=some x ↔ b=⟨i,hi.trans_le hlen⟩ := by + rw [←hix] + exact listIndex_eq_iff xs hn k hlen i hi b + simp only [mapLaw,uniformLaw,uniformMass,Fintype.card_fin,he,ite_eq_left hx] + simp + · have he (b : Fin (2^k)) : xs[b.val]?≠some x := by + intro hb + obtain ⟨hb,hval⟩ := List.getElem?_eq_some_iff.mp hb + exact hx (List.mem_iff_getElem.mpr ⟨b.val,hb,hval⟩) + simp only [mapLaw,he,ite_false,Finset.sum_const_zero,ite_eq_right hx] + +/-- This implementation has exactly the same masses as a uniform +injection into the dyadic code space, with no search for that injection. -/ +theorem listBitDraw_mass (xs : List X) (hn : xs.Nodup) (k : ℕ) + (hlen : xs.length ≤ 2^k) (x : X) : + (mapLaw (uniformLaw (α := Fin k → Bool)) (listBitDraw xs k)).mass (some x)= + if x∈xs then 1/(2:ℚ)^k else 0 := by + have he := map_equiv (binaryWordEquiv k) + (uniformLaw (α := Fin k → Bool)) (fun b : Fin (2^k) => xs[b.val]?) + rw [uniform_equiv] at he + change (mapLaw (uniformLaw (α := Fin k → Bool)) + (fun bits => xs[(binaryWordEquiv k bits).val]?)).mass (some x)=_ + rw [←he] + exact listIndex_mass xs hn k hlen x + +theorem listBitDraw_mass_decidableEq (d : DecidableEq (Option X)) + (xs : List X) (hn : xs.Nodup) (k : ℕ) (hlen : xs.length ≤ 2^k) (x : X) : + (@mapLaw (Fin k → Bool) (Option X) _ _ d + (uniformLaw (α := Fin k → Bool)) (listBitDraw xs k)).mass (some x)= + if x∈xs then 1/(2:ℚ)^k else 0 := by + have he := mapLaw_mass_decidableEq_irrel d (@Option.instDecidableEq X inferInstance) + (uniformLaw (α := Fin k → Bool)) (listBitDraw xs k) (some x) + exact he.trans (listBitDraw_mass xs hn k hlen x) + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..afdcaa1501a402744f703062654d00b9769b964d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanDraw.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanStep + +namespace OAI + +/-! # Literal finite-word outer sampling with the computed dense draw -/ + +namespace ContingencyTables.SmallGraphProfiles +open ResidualMixture FirstSuccess CompletionTranslation CompletionCounts FairBits +open ProfilePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +def listedFlatWalk (x : PaperStates r c) (n : ℕ) + (bits : Fin (n*(s+f)) → Bool) : PaperStates r c := + wordWalk (listedBitStep r c e hr hc b h hb) x n + (GridBoundary.gridWordEquiv n (s+f) bits) + +theorem listedFlatWalk_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (listedFlatWalk r c e hr hc b h hb x n)= + walkLaw (listedSmallKernel r c hr hc b h hb) x n := by + unfold listedFlatWalk + rw [←map_equiv (GridBoundary.gridWordEquiv n (s+f)),uniform_equiv] + change wordWalkLaw _ _ _=_ + rw [wordWalkLaw_eq] + exact congrArg (fun K => walkLaw K x n) + (funext (listedBitStep_law r c e hr hc b h hb htotal)) + +def listedJointDraw (x : PaperStates r c) (n : ℕ) + (bits : Fin (n*(s+f)+f) → Bool) : PaperStateJoint r c := + let draws := splitWordEquiv (n*(s+f)) f bits + let z := listedFlatWalk r c e hr hc b h hb x n draws.1 + ⟨z,listedPaddedDraw r c hr hc b h hb z draws.2⟩ + +/-- The terminal completion uses fresh bits at the adaptively obtained +state, with exactly the joint law used in the error proof. -/ +theorem listedJointDraw_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*(s+f)+f) → Bool)) + (listedJointDraw r c e hr hc b h hb x n)= + listedJointLaw r c hr hc b h hb x n := by + let E := splitWordEquiv (n*(s+f)) f + let F := fun ab : (Fin (n*(s+f)) → Bool) × (Fin f → Bool) => + let z := listedFlatWalk r c e hr hc b h hb x n ab.1 + (⟨z,listedPaddedDraw r c hr hc b h hb z ab.2⟩ : PaperStateJoint r c) + have he := map_equiv E (uniformLaw (α := Fin (n*(s+f)+f) → Bool)) F + rw [uniform_equiv,←uniform_product] at he + calc + _ = mapLaw (productLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (uniformLaw (α := Fin f → Bool))) F := he.symm + _ = dependentJointLaw + (mapLaw (uniformLaw (α := Fin (n*(s+f)) → Bool)) + (listedFlatWalk r c e hr hc b h hb x n)) + (fun z => mapLaw (uniformLaw (α := Fin f → Bool)) + (listedPaddedDraw r c hr hc b h hb z)) := + mapLaw_dependent_product (A := Fin (n*(s+f)) → Bool) (B := Fin f → Bool) + (X := PaperStates r c) (Y := PaperFibre r c) + (uniformLaw (α := Fin (n*(s+f)) → Bool)) (uniformLaw (α := Fin f → Bool)) + (listedFlatWalk r c e hr hc b h hb x n) + (fun z => listedPaddedDraw r c hr hc b h hb z) + _ = _ := by rw [listedFlatWalk_law r c e hr hc b h hb htotal]; rfl + +def listedOuterDraw (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) + (bits : Fin (J₀*(n*(s+f)+f)) → Bool) : Table r c := + wordRetry (fun bitword => stateTrial r c + (listedJointDraw r c e hr hc b h hb x n bitword)) z₀ J₀ + (GridBoundary.gridWordEquiv J₀ (n*(s+f)+f) bits) + +/-- All trial words are independent and failed trials return the fixed +feasible fallback. In particular, every bit word returns a feasible table. -/ +theorem listedOuterDraw_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) : + mapLaw (uniformLaw (α := Fin (J₀*(n*(s+f)+f)) → Bool)) + (listedOuterDraw r c e hr hc b h hb x n J₀ z₀)= + retryLaw (listedJointLaw r c hr hc b h hb x n) + (stateTrial r c) z₀ J₀ := by + unfold listedOuterDraw + rw [←map_equiv (GridBoundary.gridWordEquiv J₀ (n*(s+f)+f)),uniform_equiv] + change wordRetryLaw _ _ _=_ + rw [wordRetryLaw_eq,←retryLaw_map,listedJointDraw_law r c e hr hc b h hb htotal] + + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..8136a2d01d09009d9d4ac97bc666651d9dfc80b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedBooleanStep.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Transport.WordCompletionStep +import OAI.Combinatorics.ContingencyTables.Transport.ListedKernelAccuracy +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk + +namespace OAI + +/-! # The computed binary outer step has the proved mixing kernel -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts +open ResidualMixture FirstSuccess FairBits CompletionTranslation SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "i₀" => largeOptionEquiv r (d^20) hr none +local notation "j₀" => largeOptionEquiv c (d^20) hc none +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +def listedBlockDraw (x : PaperStates r c) (word : Fin f → Bool) : Table (R x) (P x) := + paperReferenceEquiv r c i₀ j₀ x (listedPaddedDraw r c hr hc b h hb x word) + +lemma listedBlockDraw_law (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin f → Bool)) (listedBlockDraw r c hr hc b h hb x)= + listedReferenceLaw r c hr hc b h hb x := by + exact mapLaw_equiv_output (paperReferenceEquiv r c i₀ j₀ x) _ _ + +def listedBitStep (x : PaperStates r c) (bits : Fin (s+f) → Bool) : PaperStates r c := + wordCompletionStep R P (decodedCodeProposal r c e) (listedBlockDraw r c hr hc b h hb) x bits + +attribute [local irreducible] FirstSuccess.mapLaw completionStepLaw + +theorem listedBitStep_law (htotal : (∑ i,r i)=∑ j,c j) (x : PaperStates r c) : + mapLaw (uniformLaw (α := Fin (s+f) → Bool)) (listedBitStep r c e hr hc b h hb x)= + listedSmallKernel r c hr hc b h hb x := by + have he := wordCompletionStep_law R P (decodedCodeProposal r c e) + (listedBlockDraw r c hr hc b h hb) x + have hp := funext (decodedCodeProposal_law r c e htotal) + have hd := funext (listedBlockDraw_law r c hr hc b h hb) + have hP := congrArg (fun prop : PaperStates r c → RationalLaw (Option (PaperStates r c)) => + completionStepLaw R P prop + (fun x => mapLaw (uniformLaw (α := Fin f → Bool)) (listedBlockDraw r c hr hc b h hb x)) x) hp + have hD := congrArg (fun draw : (x : PaperStates r c) → RationalLaw (Table (R x) (P x)) => + completionStepLaw R P (smallProposalLaw r c) draw x) hd + have hq := funext (fun y : PaperStates r c => + mapLaw_decidableEq_irrel (@Option.instDecidableEq (PaperStates r c) inferInstance) + (inferInstance : DecidableEq (Option (PaperStates r c))) + (uniformLaw (α := Fin s → Bool)) (decodedCodeProposal r c e y)) + have hQ := congrArg (fun prop : PaperStates r c → RationalLaw (Option (PaperStates r c)) => + completionStepLaw R P prop + (fun x => mapLaw (uniformLaw (α := Fin f → Bool)) (listedBlockDraw r c hr hc b h hb x)) x) hq + exact he.trans (hQ.trans (hP.trans hD)) + +theorem profileStep_listedBitStep (htotal : (∑ i,r i)=∑ j,c j) + (x : PaperStates r c) (bits : Fin (s+f) → Bool) : + profileStep (encodedStepInput r c e b h x (splitWordEquiv s f bits).1 (splitWordEquiv s f bits).2)= + stateCode r c e (listedBitStep r c e hr hc b h hb x bits) := by + rw [profileStep_encoded r c e hr hc b h hb htotal] + rw [listed_completionDecision r c hr hc] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..41a543fcf0469bf1310e98f2416326444a343fa6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedCompletion.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TableMarginTransport +import OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginReference +import OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreEquiv +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBounds + +namespace OAI + +/-! # Entry-preserving completion coordinates in computed list order -/ + +namespace ContingencyTables.SmallGraphProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open DensePrograms +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} +variable (r : Fin m → ℕ) (c : Fin n → ℕ) (U L : ℕ) (B : Fin m → Fin n → ℕ) +variable (hr : 0 < (ProfilePrograms.largeIndices (U,List.ofFn r)).length) +variable (hc : 0 < (ProfilePrograms.largeIndices (U,List.ofFn c)).length) + +def listedReferenceIndex (r : Fin m → ℕ) (U : ℕ) + (hr : 0 < (ProfilePrograms.largeIndices (U,List.ofFn r)).length) : + Option (Fin ((ProfilePrograms.largeIndices (U,List.ofFn r)).length-1)) ≃ + Option {i : LargeRows r U // i≠largeOptionEquiv r U hr none} := + (largeOptionEquiv r U hr).trans (Equiv.optionSubtypeNe (largeOptionEquiv r U hr none)).symm + +lemma listedReference_row + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + (fun i => referenceRows r c U L B (largeOptionEquiv r U hr none) z + (listedReferenceIndex r U hr i))=listedRows r c U L B hr z := by + funext i + simp only [referenceRows,listedReferenceIndex,Equiv.trans_apply,Equiv.apply_symm_apply,listedRows] + +lemma listedReference_column + (z : PhysicalStates (firstPaperSmall r c U) B r c L) : + (fun j => referenceColumns r c U L B (largeOptionEquiv c U hc none) z + (listedReferenceIndex c U hc j))=listedColumns r c U L B hc z := by + funext j + simp only [referenceColumns,listedReferenceIndex,Equiv.trans_apply,Equiv.apply_symm_apply,listedColumns] + +def listedFibreEquiv (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k)≤B i j) : + CompletionFibre (firstPaperSmall r c U) B r + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) c + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L) + (physicalProfile _ B r c L z) ≃ Table (listedRows r c U L B hr z) (listedColumns r c U L B hc z) := by + let i₀ := largeOptionEquiv r U hr none + let j₀ := largeOptionEquiv c U hc none + have E := (referenceFibreEquiv r c U L B i₀ j₀ z hcap).trans + (tableReindex (listedReferenceIndex r U hr) (listedReferenceIndex c U hc) + (referenceRows r c U L B i₀ z) (referenceColumns r c U L B j₀ z)) + exact E.trans (tableMarginTransport _ _ _ _ + (listedReference_row r c U L B hr z) (listedReference_column r c U L B hc z)) + +lemma listedFibreEquiv_entry (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k)≤B i j) + (A : CompletionFibre (firstPaperSmall r c U) B r + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) c + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L) + (physicalProfile _ B r c L z)) (i) (j) : + (listedFibreEquiv r c U L B hr hc z hcap A).val i j= + (referenceFibreEquiv r c U L B (largeOptionEquiv r U hr none) + (largeOptionEquiv c U hc none) z hcap A).val + (listedReferenceIndex r U hr i) (listedReferenceIndex c U hc j) := rfl + +theorem listed_totals (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k)≤B i j) : + (∑ i,listedRows r c U L B hr z i)=∑ j,listedColumns r c U L B hc z j := by + have h := reference_totals r c U L B (largeOptionEquiv r U hr none) + (largeOptionEquiv c U hc none) z hcap + rw [←(listedReferenceIndex r U hr).sum_comp + (referenceRows r c U L B (largeOptionEquiv r U hr none) z), + ←(listedReferenceIndex c U hc).sum_comp + (referenceColumns r c U L B (largeOptionEquiv c U hc none) z)] at h + simpa only [listedReference_row,listedReference_column] using h + +include hc in +theorem listed_row_padding (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (i : Option (Fin ((ProfilePrograms.largeIndices (U,List.ofFn r)).length-1))) : + L≤listedRows r c U L B hr z i := + large_row_padding r c U L B z (largeOptionEquiv r U hr i) (largeOptionEquiv c U hc none) + +include hr in +theorem listed_column_padding (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (j : Option (Fin ((ProfilePrograms.largeIndices (U,List.ofFn c)).length-1))) : + L≤listedColumns r c U L B hc z j := + large_column_padding r c U L B z (largeOptionEquiv r U hr none) (largeOptionEquiv c U hc j) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..0645a315e33c9fadd592d50961b2611a465534e2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseDraw.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedCompletion +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceDrawBounds +import OAI.Combinatorics.ContingencyTables.Machines.ResidualDenseProgram + +namespace OAI + +/-! # A canonical dense draw in the actual retained completion fibre -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open CompletionCounts PaddedCompletions ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} +variable (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) + +abbrev largeTailCount {m : ℕ} (r : Fin m → ℕ) (V : ℕ) : ℕ := + (largeIndices (V,List.ofFn r)).length-1 + +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "U" => d^20 +local notation "L" => d^12 +local notation "R" => listedRows r c U L (stateCapacity r c) hr +local notation "P" => listedColumns r c U L (stateCapacity r c) hc +local notation "nr" => largeTailCount r U +local notation "nc" => largeTailCount c U + +lemma largeIndices_length_le {m : ℕ} (r : Fin m → ℕ) (V : ℕ) : + (largeIndices (V,List.ofFn r)).length ≤ m := by + have h := Fintype.card_congr (largeIndexEquiv r V) + rw [Fintype.card_fin] at h + rw [h] + exact (Fintype.card_subtype_le _).trans_eq (Fintype.card_fin m) + +include hr hc in +lemma listed_dimensions : + Fintype.card (Option (Fin nr)) ≤ d ∧ + Fintype.card (Option (Fin nc)) ≤ d ∧ Fintype.card (Fin nr×Fin nc) ≤ d := by + have hm := largeIndices_length_le r U + have hn := largeIndices_length_le c U + simp only [Fintype.card_option,Fintype.card_fin,Fintype.card_prod,largeTailCount] + have hmul := Nat.mul_le_mul ((Nat.sub_le (largeIndices (U,List.ofFn r)).length 1).trans hm) + ((Nat.sub_le (largeIndices (U,List.ofFn c)).length 1).trans hn) + have hd := dimension_le_allowance (I := Fin m) (J := Fin n) + simp only [Fintype.card_fin] at hd + have hdr : m ≤ d := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hdc : n ≤ d := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + exact ⟨by omega,by omega,hmul.trans hd⟩ + +include hr hc in +lemma listed_dimension_fourteen : 14 ≤ d := + reference_dimension_fourteen r c U (largeOptionEquiv r U hr none) (largeOptionEquiv c U hc none) + +abbrev paperListedEquiv (z : PaperStates r c) : PaperFibre r c z ≃ Table (R z) (P z) := + listedFibreEquiv r c U L (stateCapacity r c) hr hc z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z) + +lemma listed_paper_totals (z : PaperStates r c) : (∑ i,R z i)=∑ j,P z j := + listed_totals r c U L (stateCapacity r c) hr hc z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z) + +lemma listed_row_bound (z : PaperStates r c) (i : Option (Fin nr)) : R z i ≤ stateBound r c := by + have h := reference_row_le_stateBound r c (largeOptionEquiv r U hr none) z + (listedReferenceIndex r U hr i) + have he := congrFun (listedReference_row r c U L (stateCapacity r c) hr z) i + exact he ▸ h + +abbrev listedDrawBits (h : ℕ) (z : PaperStates r c) := normalizedDrawBits (R z) (P z) d h + +def listedDenseDraw (h : ℕ) (z : PaperStates r c) + (bits : Fin (listedDrawBits r c hr hc h z) → Bool) : PaperFibre r c z := + (paperListedEquiv r c hr hc z).symm + (normalizedBooleanDraw (R z) (P z) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c U L (stateCapacity r c) hr hc z) + (listed_column_padding r c U L (stateCapacity r c) hr hc z) + (listed_paper_totals r c hr hc z) h + (canonicalOrigin (nr*nc) d (by have := listed_dimension_fourteen r c hr hc; omega)) + (canonicalFallback (R z) (P z) (listed_paper_totals r c hr hc z)) bits) + +theorem listedDrawBits_le (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (z : PaperStates r c) : listedDrawBits r c hr hc h z ≤ 25*(d+b+h+1)^62 := by + apply normalizedDrawBits_polynomial (R z) (P z) d (stateBound r c) b h + · simpa only [Fintype.card_prod,Fintype.card_fin] using (listed_dimensions r c hr hc).2.2 + · exact listed_row_bound r c hr z + · exact hb + +theorem listedDenseDraw_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (nr*nc)) + (hCheeger : PublishedInputs.FiniteCheeger (GridBoundary.Grid (I := Fin (nr*nc)) (4*d^8))) + (h : ℕ) (z : PaperStates r c) : + (variation (mapLaw (uniformLaw (α := Fin (listedDrawBits r c hr hc h z) → Bool)) + (listedDenseDraw r c hr hc h z)) (uniformLaw (α := PaperFibre r c z)):ℝ) ≤ (2:ℝ)^(-(h:ℝ)) := by + let E : PaperFibre r c z ≃ Table (R z) (P z) := paperListedEquiv r c hr hc z + let fb := canonicalFallback (R z) (P z) (listed_paper_totals r c hr hc z) + let : Nonempty (Table (R z) (P z)) := ⟨fb⟩ + have hv := canonicalDenseDraw_variation (R z) (P z) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c U L (stateCapacity r c) hr hc z) + (listed_column_padding r c U L (stateCapacity r c) hr hc z) + (listed_dimensions r c hr hc).1 (listed_dimensions r c hr hc).2.1 + (listed_dimensions r c hr hc).2.2 (listed_paper_totals r c hr hc z) hPL hCheeger h + unfold listedDenseDraw + rw [mapLaw_equiv_output] + change (variation (equivLaw E.symm _) (uniformLaw (α := PaperFibre r c z)):ℝ) ≤ _ + rw [←uniform_equiv E.symm,variation_equiv] + exact hv + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseProgramSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseProgramSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f9ff2b633bdc1eea82bde04fe68451cec9f1a09 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedDenseProgramSemantics.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedDenseDraw + +namespace OAI + +/-! # The binary residual call implements the actual completion draw -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates FirstPaperProfiles CompletionCounts +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (e : Fin q ≃ Cells (paperSmall r c)) + +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc + +theorem residualParameters_code (h : ℕ) (z : PaperStates r c) : + residualParameters ((stateCodeData r c e z,d^12),(d,h))= + ((marginCode (R z),marginCode (P z)),(d,h)) := by + apply Prod.ext + · apply Prod.ext + · exact (listedRows_code r c (d^20) (d^12) (stateCapacity r c) hr e z).symm + · exact (listedColumns_code r c (d^20) (d^12) (stateCapacity r c) hc e + (fun a => stateCapacity_small r c _ _ a.property) z).symm + · rfl + +/-- On every word, the polynomial binary call returns precisely the +matrix of a genuine completion, in the computed large-rectangle order. -/ +theorem residualDenseDraw_code (h : ℕ) (z : PaperStates r c) + (bits : Fin (listedDrawBits r c hr hc h z) → Bool) : + residualDenseDraw (((stateCodeData r c e z,d^12),(d,h)),List.ofFn bits)= + tableOutput (paperListedEquiv r c hr hc z (listedDenseDraw r c hr hc h z bits)) := by + unfold residualDenseDraw + rw [residualParameters_code] + have he := canonicalDenseDraw_eq (R z) (P z) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc z) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc z) + (listed_paper_totals r c hr hc z) h bits + refine he.trans ?_ + simp only [listedDenseDraw,Equiv.apply_symm_apply] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedIntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedIntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6339d0e3dac23a5c0462f83f4bf68ddf4436ca74 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedIntegerLaw.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CanonicalIntegerLaw +import OAI.Combinatorics.ContingencyTables.Transport.BooleanIntegerLaw +import OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanDraw + +namespace OAI + +/-! # Integer transition counts for the actual outer-profile walk -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open CompletionCounts SmallContextCoordinates ResidualMixture FirstSuccess FairBits CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) +local notation "f" => 25*(d+b+h+1)^62 + +def listedCompletionCounts (x : PaperStates r c) : IntegerLaw (PaperFibre r c x) (2^f) := + (paddedCanonicalCounts (R x) (P x) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_paper_totals r c hr hc x) h f (listedDrawBits_le r c hr hc b h hb x)).equiv + (paperListedEquiv r c hr hc x).symm + +lemma listedCompletionCounts_law (x : PaperStates r c) : + (listedCompletionCounts r c hr hc b h hb x).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin f → Bool)) (listedPaddedDraw r c hr hc b h hb x) := by + unfold listedCompletionCounts + rw [IntegerLaw.toRational_equiv,paddedCanonicalCounts_law] + unfold listedPaddedDraw listedDenseDraw + rw [mapLaw_equiv_output] + +/-- Completion counts are cached once per state; only the short proposal +word is enumerated to form this finite transition matrix. -/ +def listedStepCounts (x : PaperStates r c) : IntegerLaw (PaperStates r c) (2^(s+f)) := + IntegerLaw.booleanFinish (listedCompletionCounts r c hr hc b h hb x) + (fun word A => completionDecision R P x (decodedCodeProposal r c e x word) + (paperListedEquiv r c hr hc x A)) + +lemma listedStepCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) : + (listedStepCounts r c e hr hc b h hb x).toRational (by positivity)= + listedSmallKernel r c hr hc b h hb x := by + unfold listedStepCounts + rw [IntegerLaw.toRational_booleanFinish _ _ _ + (listedCompletionCounts_law r c hr hc b h hb x)] + have he : (fun bits : Fin (s+f) → Bool => + completionDecision R P x (decodedCodeProposal r c e x (splitWordEquiv s f bits).1) + (paperListedEquiv r c hr hc x + (listedPaddedDraw r c hr hc b h hb x (splitWordEquiv s f bits).2)))= + listedBitStep r c e hr hc b h hb x := by + funext bits + rw [listed_completionDecision r c hr hc] + rfl + rw [he] + exact listedBitStep_law r c e hr hc b h hb htotal x + +attribute [local irreducible] listedStepCounts listedSmallKernel + +/-- The complete adaptive walk is an integer matrix power. -/ +def listedWalkCounts (x : PaperStates r c) (N : ℕ) : + IntegerLaw (PaperStates r c) ((2^(s+f))^N) := + IntegerLaw.walk (listedStepCounts r c e hr hc b h hb) x N + +attribute [local irreducible] listedWalkCounts + +lemma listedWalkCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (N : ℕ) : + (listedWalkCounts r c e hr hc b h hb x N).toRational (by positivity)= + walkLaw (listedSmallKernel r c hr hc b h hb) x N := by + unfold listedWalkCounts + rw [IntegerLaw.toRational_walk] + congr 1 + funext y + exact listedStepCounts_law r c e hr hc b h hb htotal y + +/-- Each final table count sums over the reached profile and its fresh +terminal completion; failed outer trials retain their exact numerator. -/ +def listedTrialCounts (x : PaperStates r c) (N : ℕ) : + IntegerLaw (Option (Table r c)) ((2^(s+f))^N*2^f) := + (listedWalkCounts r c e hr hc b h hb x N).bind + (fun y => (listedCompletionCounts r c hr hc b h hb y).push + (fun A => stateTrial r c ⟨y,A⟩)) + +lemma listedTrialCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (N : ℕ) : + (listedTrialCounts r c e hr hc b h hb x N).toRational (by positivity)= + mapLaw (listedJointLaw r c hr hc b h hb x N) (stateTrial r c) := by + unfold listedTrialCounts + rw [IntegerLaw.toRational_bind _ _ (by positivity) (by positivity), + listedWalkCounts_law r c e hr hc b h hb htotal] + have hf (y : PaperStates r c) : + ((listedCompletionCounts r c hr hc b h hb y).push + (fun A => stateTrial r c ⟨y,A⟩)).toRational (by positivity)= + mapLaw (listedFibreLaw r c hr hc b h hb y) (fun A => stateTrial r c ⟨y,A⟩) := by + rw [IntegerLaw.toRational_push] + exact congrArg (fun p => mapLaw p (fun A => stateTrial r c ⟨y,A⟩)) + (listedCompletionCounts_law r c hr hc b h hb y) + have hk := funext hf + rw [hk] + apply RationalLaw.ext + funext T + simp only [mapLaw,listedJointLaw,listedFibreLaw,dependentJointLaw,bindLaw, + Fintype.sum_sigma,Finset.mul_sum,mul_ite,mul_zero] + +def listedOuterCounts (x : PaperStates r c) (N J : ℕ) (fallback : Table r c) : + IntegerLaw (Table r c) (((2^(s+f))^N*2^f)^J) := + (listedTrialCounts r c e hr hc b h hb x N).retry fallback J + +lemma listedOuterCounts_law (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) + (N J : ℕ) (fallback : Table r c) : + (listedOuterCounts r c e hr hc b h hb x N J fallback).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (J*(N*(s+f)+f)) → Bool)) + (listedOuterDraw r c e hr hc b h hb x N J fallback) := by + unfold listedOuterCounts + rw [IntegerLaw.toRational_retry _ (by positivity), + listedTrialCounts_law r c e hr hc b h hb htotal, + retryLaw_map,listedOuterDraw_law r c e hr hc b h hb htotal] + rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedKernelAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedKernelAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..72578dd46ae39c9f9bf780222ba7b9aaaffa897a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedKernelAccuracy.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedReservedDraw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperImplementedLaw + +namespace OAI + +/-! # Mixing with the computed, canonically initialized completion draw -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open ResidualMixture FirstSuccess FairBits CompletionTranslation CompletionCounts +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "i₀" => largeOptionEquiv r (d^20) hr none +local notation "j₀" => largeOptionEquiv c (d^20) hc none +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +def listedFibreLaw (z : PaperStates r c) : RationalLaw (PaperFibre r c z) := + mapLaw (uniformLaw (α := Fin (25*(d+b+h+1)^62) → Bool)) (listedPaddedDraw r c hr hc b h hb z) + +def listedReferenceLaw (z : PaperStates r c) : RationalLaw (Table (R z) (P z)) := + equivLaw (paperReferenceEquiv r c i₀ j₀ z) (listedFibreLaw r c hr hc b h hb z) + +def listedSmallKernel (z : PaperStates r c) : RationalLaw (PaperStates r c) := + completionStepLaw R P (smallProposalLaw r c) (listedReferenceLaw r c hr hc b h hb) z + +def listedJointLaw (x : PaperStates r c) (steps : ℕ) : RationalLaw (PaperStateJoint r c) := + dependentJointLaw (walkLaw (listedSmallKernel r c hr hc b h hb) x steps) + (listedFibreLaw r c hr hc b h hb) + +variable (hPL : PublishedInputs.FiniteBoxPrekopaLeindler + (largeTailCount r ((dimensionAllowance (I := Fin m) (J := Fin n))^20)* + largeTailCount c ((dimensionAllowance (I := Fin m) (J := Fin n))^20))) +variable (hCheeger : PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin (largeTailCount r ((dimensionAllowance (I := Fin m) (J := Fin n))^20)* + largeTailCount c ((dimensionAllowance (I := Fin m) (J := Fin n))^20))) + (4*(dimensionAllowance (I := Fin m) (J := Fin n))^8))) + +include hPL hCheeger + + +theorem listedFibreLaw_variation (z : PaperStates r c) : + variation (listedFibreLaw r c hr hc b h hb z) (uniformLaw (α := PaperFibre r c z)) ≤ 1/(2:ℚ)^h := by + have ht := @listedDenseDraw_variation m n r c hr hc + hPL hCheeger h z + rw [←listedPaddedDraw_law r c hr hc b h hb z] at ht + change (variation (listedFibreLaw r c hr hc b h hb z) + (uniformLaw (α := PaperFibre r c z)):ℝ) ≤ _ at ht + rw [←dyadicError_cast] at ht + exact (Rat.cast_le (K := ℝ)).mp ht + +theorem listedReferenceLaw_variation (z : PaperStates r c) : + variation (listedReferenceLaw r c hr hc b h hb z) (idealReferenceLaw r c i₀ j₀ z) ≤ 1/(2:ℚ)^h := by + unfold listedReferenceLaw idealReferenceLaw + rw [variation_equiv] + exact listedFibreLaw_variation r c hr hc b h hb hPL hCheeger z + +variable [Nonempty (PaperStates r c)] + +theorem listedSmallKernel_variation (x : PaperStates r c) : + variation (listedSmallKernel r c hr hc b h hb x) (smallTransitionLaw r c i₀ j₀ x) ≤ 1/(2:ℚ)^h := by + rw [←smallIdealStep_eq r c i₀ j₀] + apply completionStep_variation + intro z + exact listedReferenceLaw_variation r c hr hc b h hb hPL hCheeger z + +/-- The implemented draw incurs one dyadic error per transition and +one more for the independent terminal completion. -/ +theorem listedJointLaw_variation (x : PaperStates r c) (steps : ℕ) : + (variation (listedJointLaw r c hr hc b h hb x steps) (stationaryJointLaw r c i₀ j₀):ℝ) ≤ + ((steps:ℝ)+1)/(2:ℝ)^h+ + ((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(steps:ℝ)/(d:ℝ)^160) := by + have hj := variation_dependentJoint_uniform + (walkLaw (listedSmallKernel r c hr hc b h hb) x steps) (smallStationaryLaw r c i₀ j₀) + (listedFibreLaw r c hr hc b h hb) (fun z => uniformLaw (α := PaperFibre r c z)) (1/(2:ℚ)^h) + (listedFibreLaw_variation r c hr hc b h hb hPL hCheeger) + have hw := walkLaw_variation (listedSmallKernel r c hr hc b h hb) + (smallTransitionLaw r c i₀ j₀) (1/(2:ℚ)^h) + (listedSmallKernel_variation r c hr hc b h hb hPL hCheeger) x steps + have ht := variation_triangle + (walkLaw (listedSmallKernel r c hr hc b h hb) x steps) + (smallWalkLaw r c i₀ j₀ x steps) (smallStationaryLaw r c i₀ j₀) + have he : variation (listedJointLaw r c hr hc b h hb x steps) + (stationaryJointLaw r c i₀ j₀) ≤ + ((steps:ℚ)+1)*(1/(2:ℚ)^h)+ + variation (smallWalkLaw r c i₀ j₀ x steps) (smallStationaryLaw r c i₀ j₀) := by + change variation (walkLaw (listedSmallKernel r c hr hc b h hb) x steps) + (smallWalkLaw r c i₀ j₀ x steps) ≤ _ at hw + change variation (listedJointLaw r c hr hc b h hb x steps) + (stationaryJointLaw r c i₀ j₀) ≤ _ at hj + linarith + have heR := (Rat.cast_le (K := ℝ)).mpr he + simp only [Rat.cast_add,Rat.cast_natCast,Rat.cast_one,Rat.cast_div, + Rat.cast_pow,Rat.cast_ofNat,mul_one_div] at heR + exact heR.trans (add_le_add_right (smallWalkLaw_variation r c i₀ j₀ x steps) _) + +/-- This is the manuscript's three-term bound for the actual finite +completion subroutine, ideal mixing, and first-success fallback. -/ +theorem listedOuterLaw_variation [Nonempty (Table r c)] + (htotal : ∑ i,r i=∑ j,c j) (x : PaperStates r c) (n J₀ : ℕ) (z₀ : Table r c) : + (variation (retryLaw (listedJointLaw r c hr hc b h hb x n) + (stateTrial r c) z₀ J₀) (uniformLaw (α := Table r c)):ℝ) ≤ + Real.exp (-(J₀:ℝ)/(2*(1+(d:ℝ)^2)))+ + (J₀:ℝ)*(((n:ℝ)+1)/(2:ℝ)^h+ + ((stateBound r c+1:ℕ):ℝ)^(2*d)*Real.exp (-(n:ℝ)/(d:ℝ)^160)) := by + have hretry := retryLaw_variation (listedJointLaw r c hr hc b h hb x n) + (stationaryJointLaw r c i₀ j₀) (stateTrial r c) z₀ J₀ + have ht := variation_triangle + (retryLaw (listedJointLaw r c hr hc b h hb x n) (stateTrial r c) z₀ J₀) + (retryLaw (stationaryJointLaw r c i₀ j₀) (stateTrial r c) z₀ J₀) (uniformLaw (α := Table r c)) + have hrR := (Rat.cast_le (K := ℝ)).mpr hretry + have htR := (Rat.cast_le (K := ℝ)).mpr ht + simp only [Rat.cast_add,Rat.cast_mul,Rat.cast_natCast] at hrR htR + have hj := mul_le_mul_of_nonneg_left + (listedJointLaw_variation r c hr hc b h hb hPL hCheeger x n) + (show (0:ℝ) ≤ J₀ by positivity) + have hi := ideal_outer_variation r c i₀ j₀ htotal z₀ J₀ + linarith + + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedOutputSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedOutputSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef7edf41b151eefdf039b470842d883f0c5bf3ad --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedOutputSemantics.lean @@ -0,0 +1,170 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OuterMatrixSemantics +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionEntries +import OAI.Combinatorics.ContingencyTables.Transport.StateSuccessEntries +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealRejection + +namespace OAI + +/-! # Executable output entries for actual retained completion fibres -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open FirstPaperProfiles PaddedCompletions CompletionCounts SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] referenceFibreEquiv listedFibreEquiv +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "U" => d^20 +local notation "L" => d^12 + +lemma paperListedEquiv_entry (x : PaperStates r c) (A : PaperFibre r c x) + (i : Option (Fin ((largeIndices (U,List.ofFn r)).length-1))) + (j : Option (Fin ((largeIndices (U,List.ofFn c)).length-1))) : + (paperListedEquiv r c hr hc x A).val i j= + A.val.val.1 (largeOptionEquiv r U hr i).val (largeOptionEquiv c U hc j).val := by + rw [listedFibreEquiv_entry,referenceFibreEquiv_entry] + simp only [listedReferenceIndex,Equiv.trans_apply,Equiv.apply_symm_apply] + +lemma listedPaddingTest (x : PaperStates r c) (A : PaperFibre r c x) : + paddingTest (L,tableOutput (paperListedEquiv r c hr hc x A))=true ↔ + ∀ i j,paperSmall r c i j=false → L≤A.val.val.1 i j := by + rw [paddingTest_tableOutput] + simp_rw [paperListedEquiv_entry] + constructor + · intro h i j hij + obtain ⟨hi,hj⟩ := (firstPaperSmall_false_iff r c U i j).mp hij + obtain ⟨a,ha⟩ := (largeOptionEquiv r U hr).surjective ⟨i,hi⟩ + obtain ⟨b,hb⟩ := (largeOptionEquiv c U hc).surjective ⟨j,hj⟩ + simpa only [ha,hb] using h a b + · intro h i j + exact h _ _ ((firstPaperSmall_false_iff r c U _ _).mpr + ⟨(largeOptionEquiv r U hr i).property,(largeOptionEquiv c U hc j).property⟩) + +def actualOutputData (x : PaperStates r c) (A : PaperFibre r c x) : OuterTableData := + outputData ((stateCodeData r c e x,L),tableOutput (paperListedEquiv r c hr hc x A)) + +lemma actualOutputData_eq (x : PaperStates r c) (A : PaperFibre r c x) : + actualOutputData r c e hr hc x A= + (((cellCatalog (paperSmall r c) e,stateCode r c e x), + (largeIndices (U,List.ofFn r),largeIndices (U,List.ofFn c))), + ((U,L),tableOutput (paperListedEquiv r c hr hc x A))) := rfl + +lemma actualOutputEntry_large (x : PaperStates r c) (A : PaperFibre r c x) + (i : Option (Fin ((largeIndices (U,List.ofFn r)).length-1))) + (j : Option (Fin ((largeIndices (U,List.ofFn c)).length-1))) : + outputEntry (actualOutputData r c e hr hc x A, + ((largeOptionEquiv r U hr i).val.val,(largeOptionEquiv c U hc j).val.val))= + A.val.val.1 (largeOptionEquiv r U hr i).val (largeOptionEquiv c U hc j).val-L := by + have hs : paperSmall r c (largeOptionEquiv r U hr i).val (largeOptionEquiv c U hc j).val=false := + (firstPaperSmall_false_iff r c U _ _).mpr + ⟨(largeOptionEquiv r U hr i).property,(largeOptionEquiv c U hc j).property⟩ + have hnot := (mem_cellCatalog (paperSmall r c) e + ((largeOptionEquiv r U hr i).val,(largeOptionEquiv c U hc j).val)).not.mpr + (by simp only [hs,Bool.false_eq_true,not_false_eq_true]) + have hpos := List.idxOf_eq_length hnot + have hbad : ¬outputCellPosition (actualOutputData r c e hr hc x A, + ((largeOptionEquiv r U hr i).val.val,(largeOptionEquiv c U hc j).val.val))< + (actualOutputData r c e hr hc x A).1.1.1.length := by + change ¬(cellCatalog (paperSmall r c) e).idxOf + ((largeOptionEquiv r U hr i).val.val,(largeOptionEquiv c U hc j).val.val)< + (cellCatalog (paperSmall r c) e).length + rw [hpos] + exact Nat.lt_irrefl _ + have hlarge : outputEntry (actualOutputData r c e hr hc x A, + ((largeOptionEquiv r U hr i).val.val,(largeOptionEquiv c U hc j).val.val))= + outputLargeEntry (actualOutputData r c e hr hc x A, + ((largeOptionEquiv r U hr i).val.val,(largeOptionEquiv c U hc j).val.val)) := ite_eq_right hbad + rw [hlarge] + change matrixEntry (tableOutput (paperListedEquiv r c hr hc x A), + ((largeIndices (U,List.ofFn r)).idxOf (largeOptionEquiv r U hr i).val.val, + (largeIndices (U,List.ofFn c)).idxOf (largeOptionEquiv c U hc j).val.val))-L=_ + rw [largeOption_index,largeOption_index,tableOutput_entry,paperListedEquiv_entry] + +lemma actualOutputEntry_small (x : PaperStates r c) (A : PaperFibre r c x) + (i : Fin m) (j : Fin n) (hs : paperSmall r c i j=true) : + outputEntry (actualOutputData r c e hr hc x A,(i.val,j.val))=A.val.val.1 i j := by + rw [actualOutputData_eq] + have he := outputEntry_small (paperSmall r c) e + (physicalProfile (paperSmall r c) (stateCapacity r c) r c L x) + (largeIndices (U,List.ofFn r)) (largeIndices (U,List.ofFn c)) U L + (tableOutput (paperListedEquiv r c hr hc x A)) i j hs + exact he.trans (by + simpa only [smallView,hs,dite_true] using (A.property.2.2.1 i j hs).1.symm) + +lemma actualOutputEntry (x : PaperStates r c) (A : PaperFibre r c x) + (i : Fin m) (j : Fin n) : + outputEntry (actualOutputData r c e hr hc x A,(i.val,j.val))= + A.val.val.1 i j-largePadding (paperLarge r c) L i j := by + cases hs : paperSmall r c i j with + | true => + simpa only [paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ,true_and,hs, + Bool.true_eq_false,ite_false,Nat.sub_zero] using + actualOutputEntry_small r c e hr hc x A i j hs + | false => + obtain ⟨hi,hj⟩ := (firstPaperSmall_false_iff r c U i j).mp hs + obtain ⟨a,ha⟩ := (largeOptionEquiv r U hr).surjective ⟨i,hi⟩ + obtain ⟨b,hb⟩ := (largeOptionEquiv c U hc).surjective ⟨j,hj⟩ + simpa only [ha,hb,paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ,true_and, + hs,ite_true] using actualOutputEntry_large r c e hr hc x A a b + +lemma balancedTest_stateCode (x : PaperStates r c) : + balancedTest (stateCode r c e x,U)=true ↔ + Balanced (paperSmall r c) (stateCapacity r c) + (physicalProfile (paperSmall r c) (stateCapacity r c) r c L x) := by + rw [stateCode,profileCode,viewList,viewList,balancedTest_ofFn, + balanced_iff_cellSums (paperSmall r c) (stateCapacity r c) _ + (fun a => (physicalProfile_feasible r c x).bounded (a,true))] + constructor + · intro h a + simpa only [Equiv.apply_symm_apply,stateCapacity_small r c _ _ a.property] using h (e.symm a) + · intro h i + simpa only [stateCapacity_small r c _ _ (e i).property] using h (e i) + +lemma actualOutputSuccess (x : PaperStates r c) (A : PaperFibre r c x) : + outerSuccess (actualOutputData r c e hr hc x A)=true ↔ + StateJointSuccess r c ⟨x,A⟩ := by + rw [actualOutputData_eq] + change (balancedTest (stateCode r c e x,U) && + paddingTest (L,tableOutput (paperListedEquiv r c hr hc x A)))=true ↔ _ + rw [Bool.and_eq_true,balancedTest_stateCode,listedPaddingTest] + rfl + +lemma actualOutputMatrix (a : SuccessfulStateJoint r c) : + outputMatrix (prepareOutput ((stateCodeData r c e a.val.1,L), + tableOutput (paperListedEquiv r c hr hc a.val.1 a.val.2)))= + matrixCode ((originalStateSuccessEquiv r c).symm a).val := by + change outputMatrix ((List.ofFn r,List.ofFn c), + actualOutputData r c e hr hc a.val.1 a.val.2)=_ + rw [outputMatrix_code] + apply congrArg matrixCode + funext i j + rw [actualOutputEntry,originalStateSuccessEquiv_symm_entry] + +lemma actualOuterTrial (x : PaperStates r c) (A : PaperFibre r c x) : + outerTrial ((stateCodeData r c e x,L),tableOutput (paperListedEquiv r c hr hc x A))= + (stateTrial r c ⟨x,A⟩).map (fun T => matrixCode T.val) := by + by_cases h : StateJointSuccess r c ⟨x,A⟩ + · have hp := (actualOutputSuccess r c e hr hc x A).mpr h + calc + _ = some (outputMatrix (prepareOutput ((stateCodeData r c e x,L), + tableOutput (paperListedEquiv r c hr hc x A)))) := ite_eq_left hp + _ = some (matrixCode ((originalStateSuccessEquiv r c).symm ⟨⟨x,A⟩,h⟩).val) := + congrArg some (actualOutputMatrix r c e hr hc ⟨⟨x,A⟩,h⟩) + _ = _ := by + simp only [stateTrial,FirstSuccess.partialEquivDraw,dite_eq_left h,Option.map_some] + · have hp : outerSuccess (actualOutputData r c e hr hc x A)≠true := + fun hp => h ((actualOutputSuccess r c e hr hc x A).mp hp) + calc + _ = none := ite_eq_right hp + _ = _ := by + simp only [stateTrial,FirstSuccess.partialEquivDraw,dite_eq_right h,Option.map_none] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReferenceDecision.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReferenceDecision.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0e9df63654af839b71de6130843144bed297ce9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReferenceDecision.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedDenseDraw +import OAI.Combinatorics.ContingencyTables.Transport.CompletionDecisionReindex + +namespace OAI + +/-! # The computed large rectangle implements the reference decision -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts +open CompletionTranslation +open scoped BigOperators Classical + +noncomputable section +attribute [local irreducible] referenceFibreEquiv listedFibreEquiv +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "i₀" => largeOptionEquiv r (d^20) hr none +local notation "j₀" => largeOptionEquiv c (d^20) hc none +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "R₀" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P₀" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +lemma listedReferenceIndex_none (v : Fin m → ℕ) (V : ℕ) + (hv : 0 < (largeIndices (V,List.ofFn v)).length) : + listedReferenceIndex v V hv none=none := + Equiv.optionSubtypeNe_symm_self _ + +lemma listed_between (x y : PaperStates r c) (i) (j) : + between (R x) (R y) (P x) (P y) i j= + between (R₀ x) (R₀ y) (P₀ x) (P₀ y) + (listedReferenceIndex r (d^20) hr i) (listedReferenceIndex c (d^20) hc j) := by + have he := between_reindex (listedReferenceIndex r (d^20) hr) + (listedReferenceIndex c (d^20) hc) + (listedReferenceIndex_none r _ hr) (listedReferenceIndex_none c _ hc) + (R₀ x) (R₀ y) (P₀ x) (P₀ y) i j + simpa only [listedReference_row,listedReference_column] using he + +lemma listed_translated_nonnegative (x y : PaperStates r c) (A : PaperFibre r c x) : + (∀ i j,0 ≤ ((paperListedEquiv r c hr hc x A).val i j:ℤ)+ + between (R x) (R y) (P x) (P y) i j) ↔ + ∀ i j,0 ≤ ((paperReferenceEquiv r c i₀ j₀ x A).val i j:ℤ)+ + between (R₀ x) (R₀ y) (P₀ x) (P₀ y) i j := by + have he (i) (j) : (paperListedEquiv r c hr hc x A).val i j= + (paperReferenceEquiv r c i₀ j₀ x A).val + (listedReferenceIndex r (d^20) hr i) (listedReferenceIndex c (d^20) hc j) := + @listedFibreEquiv_entry m n r c (d^20) (d^12) (stateCapacity r c) hr hc x + (physical_paper_capacity (paperSmall r c) r c d (d^12) (d^20) + dimension_le_allowance x) A i j + simp only [he,listed_between] + constructor + · intro h i j + obtain ⟨i,rfl⟩ := (listedReferenceIndex r (d^20) hr).surjective i + obtain ⟨j,rfl⟩ := (listedReferenceIndex c (d^20) hc).surjective j + exact h i j + · intro h i j + exact h _ _ + +theorem listed_completionDecision (x : PaperStates r c) (proposal : Option (PaperStates r c)) + (A : PaperFibre r c x) : + completionDecision R P x proposal (paperListedEquiv r c hr hc x A)= + completionDecision R₀ P₀ x proposal (paperReferenceEquiv r c i₀ j₀ x A) := by + cases proposal with + | none => rfl + | some y => + unfold completionDecision + dsimp only + have he := listed_translated_nonnegative r c hr hc x y A + split_ifs with h₁ h₂ h₂ + · rfl + · exact False.elim (h₂ (he.mp h₁)) + · exact False.elim (h₁ (he.mpr h₂)) + · rfl + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReservedDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReservedDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..00a665a337b3dc0ab63df1853b7f43aefb03e66c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedReservedDraw.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedDenseProgramSemantics +import OAI.Combinatorics.ContingencyTables.Dense.DenseReservedWord + +namespace OAI + +/-! # A common fixed word for all computed residual completion draws -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped + +def reservedResidualDraw (z : ResidualDrawData) : DensePrograms.MatrixCode := + DensePrograms.reservedCanonicalDraw (residualParameters z.1,z.2) + +def reservedResidualDrawRealizer : Realizer reservedResidualDraw := + composition (pair (composition first residualParametersRealizer) second) + DensePrograms.reservedCanonicalDrawRealizer + +theorem polynomial_reservedResidualDraw : PolynomialTime reservedResidualDrawRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_residualParameters) polynomial_second) + DensePrograms.polynomial_reservedCanonicalDraw + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (hr : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0 < (largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc + +def listedPaddedDraw (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (z : PaperStates r c) (bits : Fin (25*(d+b+h+1)^62) → Bool) : PaperFibre r c z := + listedDenseDraw r c hr hc h z (prefixWord (listedDrawBits_le r c hr hc b h hb z) bits) + +theorem listedPaddedDraw_law (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (z : PaperStates r c) : + mapLaw (uniformLaw (α := Fin (25*(d+b+h+1)^62) → Bool)) (listedPaddedDraw r c hr hc b h hb z)= + mapLaw (uniformLaw (α := Fin (listedDrawBits r c hr hc h z) → Bool)) + (listedDenseDraw r c hr hc h z) := + padded_draw_law (listedDrawBits_le r c hr hc b h hb z) (listedDenseDraw r c hr hc h z) + +theorem listedPaddedDraw_code (e : Fin q ≃ Cells (paperSmall r c)) + (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (z : PaperStates r c) (bits : Fin (25*(d+b+h+1)^62) → Bool) : + reservedResidualDraw (((stateCodeData r c e z,d^12),(d,h)),List.ofFn bits)= + tableOutput (paperListedEquiv r c hr hc z (listedPaddedDraw r c hr hc b h hb z bits)) := by + have he := residualDenseDraw_code r c hr hc e h z + (prefixWord (listedDrawBits_le r c hr hc b h hb z) bits) + unfold residualDenseDraw at he + rw [residualParameters_code r c hr hc e] at he + unfold reservedResidualDraw reservedCanonicalDraw + rw [residualParameters_code r c hr hc e] + rw [canonicalBitCount_code (R z) (P z) + (by have := listed_dimension_fourteen r c hr hc; omega) (listed_paper_totals r c hr hc z), + take_ofFn_prefix (listedDrawBits_le r c hr hc b h hb z)] + dsimp only [listedPaddedDraw] + exact he + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedScheduledSampler.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedScheduledSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..de2e0ec583899c780a31d0c9f2e0e6e3f6fb8d11 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ListedScheduledSampler.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanDraw +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFiniteSampler + +namespace OAI + +/-! # Accuracy of the fully computed listed sampler schedule -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts FirstPaperPhysicalMarginal +open ResidualMixture FirstSuccess FairBits SmallContextCoordinates +open scoped BigOperators Classical + +noncomputable section +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "b" => smallBinaryLength r c + +variable (hPL : PublishedInputs.FiniteBoxPrekopaLeindler + (largeTailCount r ((dimensionAllowance (I := Fin m) (J := Fin n))^20)* + largeTailCount c ((dimensionAllowance (I := Fin m) (J := Fin n))^20))) +variable (hCheeger : PublishedInputs.FiniteCheeger + (GridBoundary.Grid (I := Fin (largeTailCount r ((dimensionAllowance (I := Fin m) (J := Fin n))^20)* + largeTailCount c ((dimensionAllowance (I := Fin m) (J := Fin n))^20))) + (4*(dimensionAllowance (I := Fin m) (J := Fin n))^8))) + +include hPL hCheeger + +/-- The executable, canonically initialized completion subroutine satisfies +exactly the three-error budget from the manuscript. -/ +theorem listedScheduledDraw_accuracy (htotal : (∑ i,r i)=∑ j,c j) + (x : PaperStates r c) (fallback : Table r c) (k : ℕ) (hk : 1≤k) : + let _ : Nonempty (Table r c) := ⟨fallback⟩ + (variation (mapLaw (uniformLaw (α := Fin (finiteSamplerBits r c k) → Bool)) + (listedOuterDraw r c e hr hc b (outerAccuracy d b k) (smallBinaryLength_parameters r c).1 + x (outerSteps d b k) (outerTrials d k) fallback)) + (uniformLaw (α := Table r c)):ℝ)≤1/(2:ℝ)^k := by + let : Nonempty (Table r c) := ⟨fallback⟩ + let : Nonempty (PaperStates r c) := ⟨x⟩ + dsimp only + rw [listedOuterDraw_law r c e hr hc b (outerAccuracy d b k) + (smallBinaryLength_parameters r c).1 htotal] + have hv := listedOuterLaw_variation r c hr hc b (outerAccuracy d b k) + (smallBinaryLength_parameters r c).1 hPL hCheeger htotal x + (outerSteps d b k) (outerTrials d k) fallback + have he := outer_total_error d b k (stateBound r c) + (listed_dimension_fourteen r c hr hc) (smallBinaryLength_parameters r c).2.1 hk + (smallBinaryLength_parameters r c).2.2 + apply hv.trans + convert he using 1 + push_cast + ring + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredFold.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..5280ce28faa2b1612cc7261af323e3b781d5c8e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredFold.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure + +namespace OAI + +/-! # List folds with the cost of each cached computation accounted for -/ + +namespace ContingencyTables.MeasuredFold +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +variable {A B : Type} [Codec A] [Codec B] + +/-- The loop cost is polynomial in one common external measure whenever +each reached call and each stored accumulator satisfy such a bound. -/ +lemma work_fold {f : A×B → B} (F : Realizer f) (measure : List A×B → ℕ) + (p q : Polynomial ℕ) + (hinput : ∀ z,weight z ≤ measure z) + (hcall : ∀ (as : List A) (b : B) pre a post,as=pre++a::post → + F.cost (a,pre.foldl (fun z c => f (c,z)) b) ≤ p.eval (measure (as,b))) + (hstate : ∀ (as : List A) (b : B) pre post,as=pre++post → + weight (pre.foldl (fun z a => f (a,z)) b) ≤ q.eval (measure (as,b))) : + WorkBound (fold F) measure := by + refine ⟨X*(p+14*X+34)+10+q,?_⟩ + rintro ⟨as,b⟩ + let S := measure (as,b) + have hs : weight as ≤ S := by + have hi := hinput (as,b) + rw [weight_prod] at hi + exact le_trans (by omega : weight as≤1+weight as+weight b) hi + have hc := Fold.cost_prefix_bound (f := f) F.cost as b (p.eval S) S hs + (hcall as b) + have hout := hstate as b as [] (by simp) + have hlen : as.length ≤ S := (list_length_le_weight as).trans hs + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + change Fold.cost f F.cost as b+weight (as.foldl (fun z a => f (a,z)) b) ≤ _ + change _ ≤ S*(p.eval S+14*S+34)+10+q.eval S + have hm := Nat.mul_le_mul_right (p.eval S+14*S+34) hlen + change _ ≤ q.eval S at hout + omega + +end ContingencyTables.MeasuredFold + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredMap.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..eee3f70e22a44a741a69197c06446e256933774e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/MeasuredMap.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Transport.MeasuredFold + +namespace OAI + +/-! # Costs for mapping cached computations over a finite list -/ + +namespace ContingencyTables.MeasuredMap +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +variable {A B C : Type} [Codec A] [Codec B] [Codec C] + +/-- The map accumulator adds linear copying overhead to one call of the +underlying computation. Its cost may use an external finite-box measure. -/ +lemma mapStep_cost {f : A×B → C} (F : Realizer f) (a : A) (b : B) (cs : List C) : + (mapStepRealizer F).cost (b,(a,cs)) ≤ + F.cost (a,b)+500*(weight a+weight b+weight cs+weight (f (a,b))+1) := by + simp only [mapStepRealizer,composition,pair,first,second,listCons,Function.comp_apply] + simp only [weight,encode_prod,MatchingFPRAS.TreeFunction.size_cons] + omega + +def listMeasure (μ : A×B → ℕ) (z : A×List B) : ℕ := + weight z+(z.2.map (fun b => μ (z.1,b))).sum + +def foldMeasure (μ : A×B → ℕ) (z : List B×(A×List C)) : ℕ := + weight z+(z.1.map (fun b => μ (z.2.1,b))).sum + +private lemma measure_entry (μ : A×B → ℕ) (as : List B) (a : A) (cs : List C) + (b : B) (hb : b∈as) : μ (a,b) ≤ foldMeasure μ (as,(a,cs)) := by + have h := List.single_le_sum (fun _ _ => Nat.zero_le _) (μ (a,b)) + (List.mem_map.mpr ⟨b,hb,rfl⟩ : μ (a,b)∈as.map (fun b => μ (a,b))) + exact h.trans (Nat.le_add_left _ _) + +/-- Mapping a finite list costs a polynomial in its encoded size and +in the sum of the work measures of its individual cached computations. -/ +lemma work_mapWith {f : A×B → C} (F : Realizer f) (μ : A×B → ℕ) + (hF : WorkBound F μ) : WorkBound (mapWith F) (listMeasure μ) := by + obtain ⟨p,hp⟩ := hF + let q : Polynomial ℕ := 2*X+X*(p+1)+2 + have hstate (as : List B) (a : A) (cs : List C) (pre post : List B) + (he : as=pre++post) : + weight (pre.foldl (fun z b => mapStep f (b,z)) (a,cs)) ≤ + q.eval (foldMeasure μ (as,(a,cs))) := by + let S := foldMeasure μ (as,(a,cs)) + have hi : weight (as,(a,cs)) ≤ S := Nat.le_add_right _ _ + have hbs : weight as ≤ S := by rw [weight_prod] at hi; omega + have ha : weight a ≤ S := by simp only [weight_prod] at hi; omega + have hc : weight cs ≤ S := by simp only [weight_prod] at hi; omega + have hl : pre.length ≤ S := (list_length_le_weight pre).trans ((weight_prefix he).trans hbs) + have hm := weight_map_bound (as := pre) (f := fun b => f (a,b)) (N := p.eval S) (by + intro b hb + have hμ := measure_entry μ as a cs b (by rw [he]; exact List.mem_append_left _ hb) + have ht := polynomial_eval_monotone p hμ + have hf := hp (a,b) + change p.eval (μ (a,b)) ≤ p.eval S at ht + omega) + rw [mapStep_fold,weight_prod] + have happ := weight_append (pre.map (fun b => f (a,b))).reverse cs + rw [weight_reverse] at happ + change _ ≤ q.eval S + simp only [q,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X, + Polynomial.eval_ofNat,Polynomial.eval_one] + have hlm := Nat.mul_le_mul_right (p.eval S+1) hl + omega + have hfold : WorkBound (fold (mapStepRealizer F)) (foldMeasure μ) := by + apply MeasuredFold.work_fold _ _ (p+500*(2*X+q+p+1)) q + · intro z + exact Nat.le_add_right _ _ + · rintro as ⟨a,cs⟩ pre b post he + let S := foldMeasure μ (as,(a,cs)) + have hz := hstate as a cs pre (b::post) he + have hi : weight (as,(a,cs)) ≤ S := Nat.le_add_right _ _ + have ha : weight a ≤ S := by simp only [weight_prod] at hi; omega + have hb : weight b ≤ S := (weight_mem (show b∈as by rw [he]; simp)).trans (by + simp only [weight_prod] at hi; omega) + have hμ := measure_entry μ as a cs b (by rw [he]; simp) + have ht := polynomial_eval_monotone p hμ + have hf := hp (a,b) + change p.eval (μ (a,b)) ≤ p.eval S at ht + rw [mapStep_fold] at hz ⊢ + have hcs : weight ((pre.map (fun b => f (a,b))).reverse++cs) ≤ q.eval S := by + rw [weight_prod] at hz + exact (Nat.le_add_left _ _).trans hz + have hm := mapStep_cost F a b ((pre.map (fun b => f (a,b))).reverse++cs) + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X,Polynomial.eval_one] + change _ ≤ p.eval S+500*(2*S+q.eval S+p.eval S+1) + apply hm.trans + have hcost : F.cost (a,b) ≤ p.eval S := (Nat.le_add_right _ _).trans (hf.trans ht) + have hout : weight (f (a,b)) ≤ p.eval S := (Nat.le_add_left _ _).trans (hf.trans ht) + omega + · rintro as ⟨a,cs⟩ pre post he + exact hstate as a cs pre post he + unfold mapWith + apply work_congr + apply work_then_polynomial _ (polynomial_composition polynomial_second polynomial_reverse) + have hi : WorkBound (pair (second (A := A)) (pair first (constant ([] : List C)))) + (listMeasure μ) := + work_of_polynomial + (polynomial_pair polynomial_second (polynomial_pair polynomial_first (polynomial_constant []))) X + (fun z => by simp only [Polynomial.eval_X,listMeasure]; omega) + apply work_composition hi hfold (X+2) + rintro ⟨a,bs⟩ + simp only [foldMeasure,listMeasure,weight_prod,weight_nil,Polynomial.eval_add, + Polynomial.eval_X,Polynomial.eval_ofNat] + omega + +end ContingencyTables.MeasuredMap + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/MetropolisChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/MetropolisChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..b732474573c2ab8e24b8b77edf16b0fca5926409 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/MetropolisChain.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Dense.PublishedCheeger + +namespace OAI + +/-! +# Finite weighted Metropolis chain + +The holding probability, stationary law, and cut flow are proved from +positive weights, symmetric proposals, and the proposal-degree bound. +Only the final Poincaré consequence uses the explicit published Cheeger input. +-/ + +namespace ContingencyTables.MetropolisChain + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} [Fintype X] [Nonempty X] + +def normalizer (w : X → ℝ) : ℝ := ∑ x, w x + +theorem normalizer_pos (w : X → ℝ) (hw : ∀ x, 0 < w x) : 0 < normalizer w := by + exact Finset.sum_pos (fun x _ => hw x) Finset.univ_nonempty + +def move (w : X → ℝ) (Adj : X → X → Prop) (β : ℝ) (x y : X) : ℝ := + if Adj x y then β * min 1 (w y / w x) else 0 + +private theorem accept_mass (a b : ℝ) (ha : 0 < a) : + a * min 1 (b / a) = min a b := by + rw [mul_min_of_nonneg _ _ ha.le, mul_one, mul_div_cancel₀ _ (ne_of_gt ha)] + +omit [Fintype X] [Nonempty X] in +theorem move_nonnegative (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) (x y : X) : + 0 ≤ move w Adj β x y := by + unfold move + split_ifs + · exact mul_nonneg hβ (le_min (by norm_num) (div_nonneg (hw y).le (hw x).le)) + · exact le_rfl + +omit [Nonempty X] in +theorem move_reversible (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (hsym : ∀ x y, Adj x y ↔ Adj y x) + (β : ℝ) (x y : X) : + (w x / normalizer w) * move w Adj β x y = + (w y / normalizer w) * move w Adj β y x := by + unfold move + by_cases h : Adj x y + · rw [ite_eq_left h, ite_eq_left ((hsym x y).mp h)] + have hx := accept_mass (w x) (w y) (hw x) + have hy := accept_mass (w y) (w x) (hw y) + calc + _ = β * (w x * min 1 (w y / w x)) / normalizer w := by ring + _ = β * min (w x) (w y) / normalizer w := by rw [hx] + _ = β * (w y * min 1 (w x / w y)) / normalizer w := by rw [hy, min_comm] + _ = _ := by ring + · simp only [h, (hsym x y).not.mp h, ite_false, mul_zero] + +omit [Nonempty X] in +theorem move_row_bound (w : X → ℝ) (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) + (D : ℕ) (hdegree : ∀ x, (Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D : ℝ) * β ≤ 1 / 2) (x : X) : ∑ y, move w Adj β x y ≤ 1 / 2 := by + calc + _ ≤ ∑ y : X, if Adj x y then β else 0 := by + apply Finset.sum_le_sum + intro y _ + unfold move + split_ifs + · exact (mul_le_mul_of_nonneg_left (min_le_left _ _) hβ).trans_eq (mul_one β) + · exact le_rfl + _ = ((Finset.univ.filter (Adj x)).card : ℝ) * β := by + rw [← Finset.sum_filter] + simp + _ ≤ (D : ℝ) * β := mul_le_mul_of_nonneg_right (by exact_mod_cast hdegree x) hβ + _ ≤ 1 / 2 := hproposal + +def chain (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (hsym : ∀ x y, Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x, (Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D : ℝ) * β ≤ 1 / 2) : FiniteChain X := + FiniteChain.ofMoves (fun x => w x / normalizer w) (move w Adj β) + (fun x => div_pos (hw x) (normalizer_pos w hw)) + (by rw [← Finset.sum_div]; exact div_self (ne_of_gt (normalizer_pos w hw))) + (move_nonnegative w hw Adj β hβ) + (move_row_bound w Adj β hβ D hdegree hproposal) + (move_reversible w hw Adj hsym β) + +theorem chain_flow (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (hsym : ∀ x y, Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x, (Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D : ℝ) * β ≤ 1 / 2) (x y : X) (hxy : x ≠ y) : + let C := chain w hw Adj hsym β hβ D hdegree hproposal + C.π x * C.P x y = if Adj x y then β * min (w x) (w y) / normalizer w else 0 := by + change (w x / normalizer w) * (move w Adj β x y + if x = y then _ else 0) = _ + rw [ite_eq_right hxy, add_zero] + unfold move + split_ifs + · have hx := accept_mass (w x) (w y) (hw x) + calc + _ = β * (w x * min 1 (w y / w x)) / normalizer w := by ring + _ = _ := by rw [hx] + · exact mul_zero _ + +theorem chain_cut_flow (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (hsym : ∀ x y, Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x, (Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D : ℝ) * β ≤ 1 / 2) (S : Finset X) : + let C := chain w hw Adj hsym β hβ D hdegree hproposal + (∑ x ∈ S, ∑ y ∈ Sᶜ, C.π x * C.P x y) = + (β / normalizer w) * (∑ x ∈ S, ∑ y ∈ Sᶜ, if Adj x y then min (w x) (w y) else 0) := by + dsimp only + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x hx + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y hy + have hxy : x ≠ y := fun h => (Finset.mem_compl.mp hy) (h ▸ hx) + rw [chain_flow w hw Adj hsym β hβ D hdegree hproposal x y hxy] + split_ifs <;> ring + +theorem poincare_of_weighted_cut (w : X → ℝ) (hw : ∀ x, 0 < w x) + (Adj : X → X → Prop) (hsym : ∀ x y, Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x, (Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D : ℝ) * β ≤ 1 / 2) + (hCheeger : PublishedInputs.FiniteCheeger X) (κ : ℝ) (hκ : 0 < κ) + (hcut : ∀ S : Finset X, + κ * min (∑ x ∈ S, w x) (∑ x ∈ Sᶜ, w x) ≤ + β * (∑ x ∈ S, ∑ y ∈ Sᶜ, if Adj x y then min (w x) (w y) else 0)) : + ∀ f : X → ℝ, + (chain w hw Adj hsym β hβ D hdegree hproposal).variance f ≤ + (2 / κ ^ 2) * (chain w hw Adj hsym β hβ D hdegree hproposal).energy f := by + apply hCheeger _ κ hκ + intro S + rw [chain_cut_flow] + change κ * min (∑ x ∈ S, w x / normalizer w) (∑ x ∈ Sᶜ, w x / normalizer w) ≤ _ + rw [← Finset.sum_div, ← Finset.sum_div, min_div_div_right (normalizer_pos w hw).le] + have hz := normalizer_pos w hw + have h := div_le_div_of_nonneg_right (hcut S) hz.le + convert h using 1 <;> ring + +end + +end ContingencyTables.MetropolisChain + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedPenaltyApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedPenaltyApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..c334eb8373339d2a53bd5f5b0e0d68fcf34de01d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedPenaltyApplication.lean @@ -0,0 +1,215 @@ +import OAI.Combinatorics.ContingencyTables.Transport.NestedProductSignature +import OAI.Combinatorics.ContingencyTables.Transport.ScalarPenalty +import OAI.Combinatorics.ContingencyTables.Transport.BalancedFamily +import OAI.Combinatorics.ContingencyTables.Transport.IntegerBoxTruncation +import OAI.Combinatorics.ContingencyTables.Transport.SliceFactorial +import OAI.Combinatorics.ContingencyTables.Transport.HardZeroTransport + +namespace OAI + +/-! +# The first paper's actual positive penalties and hard equality limit + +Full row/column deviations give absolute affine line factors; the nested +small-slot residual constraints give positive-part affine factors. Their +product is exactly 2^(-L D). Balanced large-slot sums retain their proved +signature, and their finite limit is the exact zero-penalty indicator sum. +-/ + +namespace ContingencyTables.NestedPenaltyApplication + +open scoped BigOperators Classical Matrix Topology +open Filter CommonBasesFPRAS FactorialSignatures ProductIntegerSignature +open NestedProductSignature ScalarPenalty IntegerMarginal BalancedBox BalancedFamily + +variable {C G : Type*} [Fintype C] [Fintype G] + +noncomputable def penalty (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : ℝ := + (∑ g, |offset g+(lineTotal line z g:ℝ)*slope g|)+ + ∑ g, max (smallOffset g+(smallTotal line inner z g:ℝ)*smallSlope g) 0 + +noncomputable def softWeight (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) : (C → ℕ) → ℝ := + nestedWeight line inner + (fun g => factor L (fun n => |offset g+(n:ℝ)*slope g|)) + (fun g => factor L (fun n => max (smallOffset g+(n:ℝ)*smallSlope g) 0)) + +noncomputable def hardWeight (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : ℝ := + if penalty line inner offset slope smallOffset smallSlope z=0 then 1 else 0 + +lemma penalty_nonnegative (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : + 0 ≤ penalty line inner offset slope smallOffset smallSlope z := by + apply add_nonneg <;> apply Finset.sum_nonneg + · intro g _; exact abs_nonneg _ + · intro g _; exact le_max_right _ _ + +private lemma prod_pow (L : ℝ) (p : G → ℝ) : + (∏ g, (2:ℝ)^(-L*p g))=(2:ℝ)^(-L*∑ g, p g) := by + rw [← Real.rpow_sum_of_pos (by norm_num : (0:ℝ)<2)] + congr 1 + rw [Finset.mul_sum] + +/-- This is the manuscript's literal exponential of the full deviation +plus the small residual violation penalty, with eta=2^(-L). -/ +theorem softWeight_eq (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (z : C → ℕ) : + softWeight line inner offset slope smallOffset smallSlope L z = + (2:ℝ)^(-L*penalty line inner offset slope smallOffset smallSlope z) := by + unfold softWeight nestedWeight factor penalty + rw [prod_pow,prod_pow,← Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + ring + +lemma softWeight_positive (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (z : C → ℕ) : + 0 < softWeight line inner offset slope smallOffset smallSlope L z := by + rw [softWeight_eq] + exact Real.rpow_pos_of_pos (by norm_num) _ + +theorem softWeight_removal (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0 ≤ L) (z : C → ℕ) : + OnePositiveDirection + (integerRemovalMatrix (softWeight line inner offset slope smallOffset smallSlope L) z).toBilin' := by + apply nested_product_removal_onePositive line inner + · intro g n _; exact factor_positive _ _ _ + · intro g n _; exact factor_positive _ _ _ + · intro g hn; exact abs_factor_logConcave L (offset g) (slope g) hL _ hn + · intro g hn; exact positivePart_factor_logConcave L (smallOffset g) (smallSlope g) hL _ hn + +theorem softWeight_tendsto (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : + Tendsto (fun L : ℝ => softWeight line inner offset slope smallOffset smallSlope L z) atTop + (nhds (hardWeight line inner offset slope smallOffset smallSlope z)) := by + simp_rw [softWeight_eq] + exact factor_limit _ (penalty_nonnegative line inner offset slope smallOffset smallSlope z) + +variable {I : Type*} [Fintype I] + +/-- The actual softened marginal is positive before the hard limit and +has the raw integer removal signature on every required display. -/ +theorem softened_marginal_slices (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0 ≤ L) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + PositiveSlice (eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L)) m R ∧ + RemovalSlice (eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L)) m R := by + apply eliminate_slices Ms m R _ hwidth + · intro z _ _; exact softWeight_positive line inner offset slope smallOffset smallSlope L z + · intro z _ _ + convert softWeight_removal line inner offset slope smallOffset smallSlope L hL z using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +/-- The first paper's hard-zero finite marginal inherits its actual raw +signature. This proves the required input to factorial omission lifting. -/ +theorem hard_marginal_removal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + RemovalSlice (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) m R := by + intro z hz htotal + apply removal_signature_limit (l := (atTop : Filter ℝ)) + (fun L => eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L)) + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) z + · intro x + exact eliminate_tendsto Ms _ _ (softWeight_tendsto line inner offset slope smallOffset smallSlope) x + · filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + exact (softened_marginal_slices Ms m R line inner offset slope smallOffset smallSlope L hL hwidth).2 + z hz htotal + +/-- Zero extension outside the box and full total gives precisely the +same actual softened marginal on its required state slice. -/ +theorem truncate_softened_marginal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) + (z : I → ℕ) (hz : InBox m z) (htotal : (∑ i, z i)=R) : + eliminate Ms + (IntegerBoxTruncation.truncate + (softWeight line inner offset slope smallOffset smallSlope L) (bounds m Ms) (R+Ms.sum)) z = + eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L) z := by + apply eliminate_congr_slice Ms m R _ _ _ z hz htotal + intro x hx ht + exact ite_eq_left ⟨hx,ht⟩ + +/-- The actual softened factorial lift now has both required properties +by the integer proofs above; neither binary property is assumed. -/ +theorem softened_firstLift_data {L : Type*} [Fintype L] (group : L → I) + (Ms : List ℕ) (R : ℕ) (D : ℝ) (hD : 0 < D) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (a : ℝ) (ha : 0 ≤ a) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + let f := LabelledFactorial.firstLift group + (eliminate Ms (softWeight line inner offset slope smallOffset smallSlope a)) D + BinaryContraction.DegreePositive f R ∧ BinaryContraction.OmissionProperty f R := by + have hs := softened_marginal_slices Ms (LabelledFactorial.groupCount group Set.univ) R + line inner offset slope smallOffset smallSlope a ha hwidth + exact ⟨SliceFactorial.firstLift_degreePositive group _ D R hD hs.1, + SliceFactorial.firstLift_omission_slice group _ D R hD + (fun z => eliminate_nonnegative Ms _ + (fun x => (softWeight_positive line inner offset slope smallOffset smallSlope a x).le) z) hs.2⟩ + +/-- These are the literal subset weights consumed by endpoint-positive +hard-zero transport, with no positivity requirement on internal limits. -/ +theorem firstLift_limit {L : Type*} [Fintype L] (group : L → I) + (Ms : List ℕ) (D : ℝ) (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (S : Set L) : + Tendsto (fun a : ℝ => LabelledFactorial.firstLift group + (eliminate Ms (softWeight line inner offset slope smallOffset smallSlope a)) D S) atTop + (nhds (LabelledFactorial.firstLift group + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) D S)) := by + apply SliceFactorial.firstLift_tendsto + intro z + exact eliminate_tendsto Ms _ _ + (softWeight_tendsto line inner offset slope smallOffset smallSlope) z + +/-- Actual first-paper hard transport. The positive softened factorial +properties are proved above from the explicit deviation penalties. Only +the two hard limiting endpoint masses are required to be positive. -/ +theorem hard_firstLift_transport {L : Type*} [Fintype L] + (group : L → I) (Ms : List ℕ) (R : ℕ) (D : ℝ) (hD : 0 < D) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (hwidth : ∀ M ∈ Ms, 2 ≤ M) + (ps : List (L × L)) (H : Set L → ℝ) (A : Set L) (p d : L) (W : L → ℝ) + (hR : R ≤ Fintype.card L) (hdegree : A.ncard+ps.length+1=Fintype.card L-R) + (hpd : p≠d) (hpA : p∉A) (hdA : d∉A) + (hps : CommonBasesFPRAS.SlotsFresh ps (A ∪ Set.range (CommonBasesFPRAS.rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ a∈ps, W a.1=W a.2) + (hsp : 0 < CommonBasesFPRAS.slotTotal ps + (BinaryContraction.complementWeight (LabelledFactorial.firstLift group + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) D)) (insert p A)) + (hsd : 0 < CommonBasesFPRAS.slotTotal ps + (BinaryContraction.complementWeight (LabelledFactorial.firstLift group + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) D)) (insert d A)) : + let f := BinaryContraction.complementWeight (LabelledFactorial.firstLift group + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) D) + let Hc := BinaryContraction.complementWeight H + (CommonBasesFPRAS.slotTotal ps (fun S => f S*Hc S) (insert p A)/ + CommonBasesFPRAS.slotTotal ps f (insert p A)- + CommonBasesFPRAS.slotTotal ps (fun S => f S*Hc S) (insert d A)/ + CommonBasesFPRAS.slotTotal ps f (insert d A))^2 ≤ + CommonBasesFPRAS.rootCoefficient ps f A p d W* + CommonBasesFPRAS.slotGraphEnergy ps f Hc A (CommonBasesFPRAS.rootEmbedding p d) W := by + apply HardZeroTransport.one_hole_transport_limit (l := (atTop : Filter ℝ)) ps + (fun a => LabelledFactorial.firstLift group + (eliminate Ms (softWeight line inner offset slope smallOffset smallSlope a)) D) + (LabelledFactorial.firstLift group + (eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope)) D) H + (firstLift_limit group Ms D line inner offset slope smallOffset smallSlope) + A p d W R hR + · filter_upwards [eventually_ge_atTop (0:ℝ)] with a ha + exact softened_firstLift_data group Ms R D hD line inner offset slope smallOffset smallSlope a ha hwidth + · exact hdegree + · exact hpd + · exact hpA + · exact hdA + · exact hps + · exact hW + · exact hw + · exact hsp + · exact hsd + +end ContingencyTables.NestedPenaltyApplication + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedProductSignature.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedProductSignature.lean new file mode 100644 index 0000000000000000000000000000000000000000..172ec92cfd05701fbaf1817947851beadb8df87b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedProductSignature.lean @@ -0,0 +1,248 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ProductIntegerSignature + +namespace OAI + +/-! +# The first paper's actual line and small-slot subgroup product + +Each small-slot subgroup is contained in a disjoint line group. The literal +product after two removals is factored into the two-level kernel. Zero +integer counts are masked and invalid repeated removals subtract a +nonnegative diagonal. +-/ + +namespace ContingencyTables.NestedProductSignature + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures ProductIntegerSignature + +variable {I G : Type*} [Fintype I] [Fintype G] + +def unitExtension (c : G → ℝ) : Option G → ℝ := fun o => o.elim 1 c + +def subgroup (line : I → G) (inner : I → Bool) (i : I) : Option G := + if inner i then some (line i) else none + +noncomputable def nestedRemoval (line : I → G) (inner : I → Bool) + (a₀ a₁ a₂ c₀ c₁ c₂ : G → ℝ) : Matrix I I ℝ := fun i j => + productTwoUpdates a₀ a₁ a₂ (line i) (line j) * + productTwoUpdates (unitExtension c₀) (unitExtension c₁) (unitExtension c₂) + (subgroup line inner i) (subgroup line inner j) + +omit [Fintype I] in +lemma nestedRemoval_factor (line : I → G) (inner : I → Bool) + (a₀ a₁ a₂ c₀ c₁ c₂ : G → ℝ) + (ha₀ : ∀ g, a₀ g ≠ 0) (ha₁ : ∀ g, a₁ g ≠ 0) + (hc₀ : ∀ g, c₀ g ≠ 0) (hc₁ : ∀ g, c₁ g ≠ 0) (i j : I) : + nestedRemoval line inner a₀ a₁ a₂ c₀ c₁ c₂ i j = + ((∏ g, a₀ g) * ∏ g, c₀ g) * + ((a₁ (line i)/a₀ (line i)) * (if inner i then c₁ (line i)/c₀ (line i) else 1)) * + ((a₁ (line j)/a₀ (line j)) * (if inner j then c₁ (line j)/c₀ (line j) else 1)) * + twoLevelKernel line inner + (fun g => a₀ g*a₂ g/(a₁ g)^2) (fun g => c₀ g*c₂ g/(c₁ g)^2) i j := by + have hce₀ : ∀ g, unitExtension c₀ g ≠ 0 := by intro g; cases g <;> simp [unitExtension,hc₀] + have hce₁ : ∀ g, unitExtension c₁ g ≠ 0 := by intro g; cases g <;> simp [unitExtension,hc₁] + unfold nestedRemoval + rw [productTwoUpdates_factor _ _ _ ha₀ ha₁,productTwoUpdates_factor _ _ _ hce₀ hce₁] + simp only [Fintype.prod_option,unitExtension,Option.elim_none,Option.elim_some,one_mul] + cases hi : inner i <;> cases hj : inner j <;> by_cases hline : line i=line j <;> + simp [subgroup,hi,hj,hline,twoLevelKernel] <;> ring + +/-- Signature of the literal nested product update matrix. -/ +theorem nestedRemoval_onePositive (line : I → G) (inner : I → Bool) + (a₀ a₁ a₂ c₀ c₁ c₂ : G → ℝ) + (ha₀ : ∀ g, 0 < a₀ g) (ha₁ : ∀ g, 0 < a₁ g) (ha₂ : ∀ g, 0 ≤ a₂ g) + (hc₀ : ∀ g, 0 < c₀ g) (hc₁ : ∀ g, 0 < c₁ g) + (halc : ∀ g, a₀ g*a₂ g ≤ (a₁ g)^2) + (hclc : ∀ g, c₀ g*c₂ g ≤ (c₁ g)^2) : + OnePositiveDirection (nestedRemoval line inner a₀ a₁ a₂ c₀ c₁ c₂).toBilin' := by + let W := (∏ g, a₀ g) * ∏ g, c₀ g + let α : I → ℝ := fun i => (a₁ (line i)/a₀ (line i)) * + (if inner i then c₁ (line i)/c₀ (line i) else 1) + let γ : G → ℝ := fun g => a₀ g*a₂ g/(a₁ g)^2 + let δ : G → ℝ := fun g => c₀ g*c₂ g/(c₁ g)^2 + have he : nestedRemoval line inner a₀ a₁ a₂ c₀ c₁ c₂ = + weightedCorrection (twoLevelKernel line inner γ δ) W α (fun _ => 0) := by + ext i j + rw [nestedRemoval_factor line inner a₀ a₁ a₂ c₀ c₁ c₂ + (fun g => ne_of_gt (ha₀ g)) (fun g => ne_of_gt (ha₁ g)) + (fun g => ne_of_gt (hc₀ g)) (fun g => ne_of_gt (hc₁ g))] + simp only [weightedCorrection,Matrix.sub_apply,Matrix.smul_apply,smul_eq_mul, + scaledMatrix,Matrix.diagonal_apply,ite_self,sub_zero] + ring + rw [he] + exact correctedTwoLevel_onePositive line inner γ δ W α (fun _ => 0) + (fun g => div_nonneg (mul_nonneg (ha₀ g).le (ha₂ g)) (sq_nonneg _)) + (fun g => (div_le_one (sq_pos_of_pos (ha₁ g))).mpr (halc g)) + (fun g => (div_le_one (sq_pos_of_pos (hc₁ g))).mpr (hclc g)) + (mul_nonneg (Finset.prod_nonneg fun g _ => (ha₀ g).le) + (Finset.prod_nonneg fun g _ => (hc₀ g).le)) (fun _ => le_rfl) + +noncomputable def smallTotal (line : I → G) (inner : I → Bool) (z : I → ℕ) (g : G) : ℕ := + lineTotal (fun i => (line i,inner i)) z (g,true) + +noncomputable def nestedWeight (line : I → G) (inner : I → Bool) + (a c : G → ℕ → ℝ) (z : I → ℕ) : ℝ := + (∏ g, a g (lineTotal line z g)) * ∏ g, c g (smallTotal line inner z g) + +omit [Fintype G] in +lemma smallTotal_removeTwo (line : I → G) (inner : I → Bool) (z : I → ℕ) + (i j : I) (hv : ValidPair z i j) (g : G) : + smallTotal line inner (removeTwo z i j) g + + (if subgroup line inner i=some g then 1 else 0) + + (if subgroup line inner j=some g then 1 else 0) = smallTotal line inner z g := by + have h := lineTotal_removeTwo (fun k => (line k,inner k)) z i j hv (g,true) + cases hi : inner i <;> cases hj : inner j <;> + simpa [smallTotal,subgroup,hi,hj,Prod.mk.injEq] using h + +/-- Exact literal nested product at every valid integer two-removal entry. -/ +theorem nestedWeight_removeTwo (line : I → G) (inner : I → Bool) (a c : G → ℕ → ℝ) + (z : I → ℕ) (i j : I) (hv : ValidPair z i j) : + nestedWeight line inner a c (removeTwo z i j) = + nestedRemoval line inner + (fun g => a g (lineTotal line z g)) (fun g => a g (lineTotal line z g-1)) + (fun g => if 2 ≤ lineTotal line z g then a g (lineTotal line z g-2) else 0) + (fun g => c g (smallTotal line inner z g)) (fun g => c g (smallTotal line inner z g-1)) + (fun g => if 2 ≤ smallTotal line inner z g then c g (smallTotal line inner z g-2) else 0) i j := by + unfold nestedWeight nestedRemoval productTwoUpdates + congr 1 + · apply Finset.prod_congr rfl + intro g _ + have ht := lineTotal_removeTwo line z i j hv g + by_cases hi : g=line i + · by_cases hj : g=line j + · have hn : 2 ≤ lineTotal line z g := by simp only [hi.symm,hj.symm,ite_true] at ht; omega + have he : lineTotal line (removeTwo z i j) g=lineTotal line z g-2 := by + simp only [hi.symm,hj.symm,ite_true] at ht; omega + simp only [ite_eq_left hi,ite_eq_left hj,ite_eq_left hn,he] + · have he : lineTotal line (removeTwo z i j) g=lineTotal line z g-1 := by + simp only [hi.symm,ite_true,Ne.symm hj,ite_false] at ht; omega + simp only [ite_eq_left hi,ite_eq_right hj,he] + · by_cases hj : g=line j + · have he : lineTotal line (removeTwo z i j) g=lineTotal line z g-1 := by + simp only [Ne.symm hi,ite_false,hj.symm,ite_true] at ht; omega + simp only [ite_eq_right hi,ite_eq_left hj,he] + · have he : lineTotal line (removeTwo z i j) g=lineTotal line z g := by + simp only [Ne.symm hi,Ne.symm hj,ite_false,add_zero] at ht; exact ht + simp only [ite_eq_right hi,ite_eq_right hj,he] + · rw [Fintype.prod_option] + simp only [unitExtension,Option.elim_none,ite_self,one_mul] + apply Finset.prod_congr rfl + intro g _ + have ht := smallTotal_removeTwo line inner z i j hv g + by_cases hi : some g=subgroup line inner i + · by_cases hj : some g=subgroup line inner j + · have hn : 2 ≤ smallTotal line inner z g := by simp only [hi.symm,hj.symm,ite_true] at ht; omega + have he : smallTotal line inner (removeTwo z i j) g=smallTotal line inner z g-2 := by + simp only [hi.symm,hj.symm,ite_true] at ht; omega + simp only [ite_eq_left hi,ite_eq_left hj,Option.elim_some,ite_eq_left hn,he] + · have he : smallTotal line inner (removeTwo z i j) g=smallTotal line inner z g-1 := by + simp only [hi.symm,ite_true,Ne.symm hj,ite_false] at ht; omega + simp only [ite_eq_left hi,ite_eq_right hj,Option.elim_some,he] + · by_cases hj : some g=subgroup line inner j + · have he : smallTotal line inner (removeTwo z i j) g=smallTotal line inner z g-1 := by + simp only [Ne.symm hi,ite_false,hj.symm,ite_true] at ht; omega + simp only [ite_eq_right hi,ite_eq_left hj,Option.elim_some,he] + · have he : smallTotal line inner (removeTwo z i j) g=smallTotal line inner z g := by + simp only [Ne.symm hi,Ne.symm hj,ite_false,add_zero] at ht; exact ht + simp only [ite_eq_right hi,ite_eq_right hj,Option.elim_some,he] + +omit [Fintype I] in +private lemma masked_correction (h : (I → ℕ) → ℝ) (z : I → ℕ) (H : Matrix I I ℝ) + (hentry : ∀ i j, ValidPair z i j → h (removeTwo z i j)=H i j) : + integerRemovalMatrix h z = scaledMatrix H (activeMask z) - + Matrix.diagonal (fun i => if z i=1 then H i i else 0) := by + ext i j + simp only [Matrix.sub_apply,Matrix.diagonal_apply,integerRemovalMatrix,scaledMatrix,activeMask] + by_cases hv : ValidPair z i j + · have hi : 0 < z i := hv.1 + have hj : 0 < z j := by have := hv.2; omega + rw [ite_eq_left hv,hentry i j hv] + simp only [hi,hj,ite_true,one_mul,mul_one] + by_cases hij : i=j + · subst j + have hn : z i ≠ 1 := by have := hv.2; simp at this; omega + simp [hn] + · simp [hij] + · rw [ite_eq_right hv] + by_cases hi : 0 < z i + · by_cases hj : 0 < z j + · have hij : i=j := by by_contra h; exact hv ⟨hi,by simpa [Ne.symm h] using hj⟩ + subst j + have hn : z i=1 := by simp [ValidPair] at hv; omega + simp [hn] + · by_cases hij : i=j + · subst j + have hn : z i=0 := by omega + simp [hn] + · simp [hj,hij] + · by_cases hij : i=j + · subst j + have hn : z i=0 := by omega + simp [hn] + · simp [hi,hij] + +private lemma updates_nonnegative {A : Type*} [Fintype A] [DecidableEq A] + (a₀ a₁ a₂ : A → ℝ) (ha₀ : ∀ k, 0 ≤ a₀ k) (ha₁ : ∀ k, 0 ≤ a₁ k) (ha₂ : ∀ k, 0 ≤ a₂ k) + (i j : A) : 0 ≤ productTwoUpdates a₀ a₁ a₂ i j := by + apply Finset.prod_nonneg + intro k _ + split_ifs <;> first | exact ha₀ k | exact ha₁ k | exact ha₂ k + +/-- The exact integer two-removal signature for the first paper's full +line penalties and nested small-slot subset penalties. -/ +theorem nested_product_removal_onePositive (line : I → G) (inner : I → Bool) + (a c : G → ℕ → ℝ) (z : I → ℕ) + (ha : ∀ g n, n ≤ lineTotal line z g → 0 < a g n) + (hc : ∀ g n, n ≤ smallTotal line inner z g → 0 < c g n) + (halc : ∀ g, 2 ≤ lineTotal line z g → + a g (lineTotal line z g)*a g (lineTotal line z g-2) ≤ a g (lineTotal line z g-1)^2) + (hclc : ∀ g, 2 ≤ smallTotal line inner z g → + c g (smallTotal line inner z g)*c g (smallTotal line inner z g-2) ≤ + c g (smallTotal line inner z g-1)^2) : + OnePositiveDirection (integerRemovalMatrix (nestedWeight line inner a c) z).toBilin' := by + let a₀ := fun g => a g (lineTotal line z g) + let a₁ := fun g => a g (lineTotal line z g-1) + let a₂ := fun g => if 2 ≤ lineTotal line z g then a g (lineTotal line z g-2) else 0 + let c₀ := fun g => c g (smallTotal line inner z g) + let c₁ := fun g => c g (smallTotal line inner z g-1) + let c₂ := fun g => if 2 ≤ smallTotal line inner z g then c g (smallTotal line inner z g-2) else 0 + let H := nestedRemoval line inner a₀ a₁ a₂ c₀ c₁ c₂ + have ha₀ : ∀ g, 0 < a₀ g := fun g => ha g _ le_rfl + have ha₁ : ∀ g, 0 < a₁ g := fun g => ha g _ (Nat.sub_le _ _) + have ha₂ : ∀ g, 0 ≤ a₂ g := by intro g; dsimp [a₂]; split_ifs; exact (ha g _ (Nat.sub_le _ _)).le; exact le_rfl + have hc₀ : ∀ g, 0 < c₀ g := fun g => hc g _ le_rfl + have hc₁ : ∀ g, 0 < c₁ g := fun g => hc g _ (Nat.sub_le _ _) + have hc₂ : ∀ g, 0 ≤ c₂ g := by intro g; dsimp [c₂]; split_ifs; exact (hc g _ (Nat.sub_le _ _)).le; exact le_rfl + have hH : OnePositiveDirection H.toBilin' := nestedRemoval_onePositive line inner a₀ a₁ a₂ c₀ c₁ c₂ + ha₀ ha₁ ha₂ hc₀ hc₁ + (fun g => by dsimp [a₀,a₁,a₂]; split_ifs with h; exact halc g h; simp [sq_nonneg]) + (fun g => by dsimp [c₀,c₁,c₂]; split_ifs with h; exact hclc g h; simp [sq_nonneg]) + have hHdiag (i : I) : 0 ≤ H i i := by + apply mul_nonneg + · exact updates_nonnegative a₀ a₁ a₂ (fun g => (ha₀ g).le) (fun g => (ha₁ g).le) ha₂ _ _ + · apply updates_nonnegative + · intro g; cases g <;> simp [unitExtension,(hc₀ _).le] + · intro g; cases g <;> simp [unitExtension,(hc₁ _).le] + · intro g; cases g <;> simp [unitExtension,hc₂] + have hsig : OnePositiveDirection (scaledMatrix H (activeMask z)).toBilin' := by + intro x hx y hxy + rw [scaledMatrix_form] at hx hxy ⊢ + exact hH _ hx _ hxy + apply onePositive_of_dominated_compression (scaledMatrix H (activeMask z)).toBilin' + (integerRemovalMatrix (nestedWeight line inner a c) z).toBilin' LinearMap.id + · exact fun x y => (matrix_bilin_symm _ (fun i j => by + simp only [integerRemovalMatrix,validPair_symm z i j,removeTwo_comm z i j])).eq x y + · exact hsig + · intro v + rw [masked_correction _ z H (nestedWeight_removeTwo line inner a c z)] + simp only [map_sub,LinearMap.sub_apply,diagonalMatrix_form,LinearMap.id_apply] + apply sub_le_self + apply Finset.sum_nonneg + intro i _ + have hκ : 0 ≤ if z i=1 then H i i else 0 := by split_ifs; exact hHdiag i; exact le_rfl + nlinarith [mul_nonneg hκ (sq_nonneg (v i))] + +end ContingencyTables.NestedProductSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..25cd006b9e19eacdd0bd5b0e678b8d0a0d3db57a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/NestedReindex.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EqualityReindex +import OAI.Combinatorics.ContingencyTables.Transport.NestedPenaltyApplication +import OAI.Combinatorics.ContingencyTables.Transport.ReflectedNested + +namespace OAI + +/-! # Physical coordinate reindexing of the first paper's nested penalties -/ + +namespace ContingencyTables.NestedReindex + +open scoped BigOperators Classical +open ProductIntegerSignature NestedProductSignature NestedPenaltyApplication +open BalancedFamily BalancedBox EqualityReindex + +variable {C D G : Type*} [Fintype C] [Fintype D] [Fintype G] + +omit [Fintype G] in +lemma smallTotal_reindex (e : C ≃ D) (line : D → G) (inner : D → Bool) + (z : C → ℕ) (g : G) : + smallTotal (line ∘ e) (inner ∘ e) z g=smallTotal line inner (z ∘ e.symm) g := by + exact lineTotal_reindex e (fun d => (line d,inner d)) z (g,true) + +lemma penalty_reindex (e : C ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : + penalty (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope z= + penalty line inner offset slope smallOffset smallSlope (z ∘ e.symm) := by + unfold penalty + simp_rw [lineTotal_reindex,smallTotal_reindex] + +lemma hardWeight_reindex (e : C ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (z : C → ℕ) : + hardWeight (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope z= + hardWeight line inner offset slope smallOffset smallSlope (z ∘ e.symm) := by + unfold hardWeight + rw [penalty_reindex] + +lemma softWeight_reindex (e : C ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (z : C → ℕ) : + softWeight (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope L z= + softWeight line inner offset slope smallOffset smallSlope L (z ∘ e.symm) := by + rw [softWeight_eq,softWeight_eq,penalty_reindex] + +variable {S : Type*} [Fintype S] [DecidableEq S] + +omit [Fintype S] in +/-- Box congruence with the ambient equality decision used by the actual +physical view type. -/ +lemma removal_congr_box (f h : (S → ℕ) → ℝ) (m z : S → ℕ) (hz : InBox m z) + (heq : ∀ x, InBox m x → f x=h x) : + FactorialSignatures.integerRemovalMatrix f z=FactorialSignatures.integerRemovalMatrix h z := by + have hd : (inferInstance : DecidableEq S)=Classical.decEq S := Subsingleton.elim _ _ + cases hd + ext i j + unfold FactorialSignatures.integerRemovalMatrix + split_ifs with hv + · exact heq _ (IntegerBoxTruncation.removal_inBox m z hz i j) + · rfl + +theorem physical_soft_marginal_slices (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0≤L) + (hwidth : ∀ M ∈ Ms, 2≤M) : + PositiveSlice (eliminate Ms (fun z => + softWeight line inner offset slope smallOffset smallSlope L (z ∘ e.symm))) m R ∧ + RemovalSlice (eliminate Ms (fun z => + softWeight line inner offset slope smallOffset smallSlope L (z ∘ e.symm))) m R := by + have hd : (inferInstance : DecidableEq S)=Classical.decEq S := Subsingleton.elim _ _ + cases hd + have heq : (fun z => softWeight line inner offset slope smallOffset smallSlope L + (z ∘ e.symm))=softWeight (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope L := by + funext z + exact (softWeight_reindex e line inner offset slope smallOffset smallSlope L z).symm + rw [heq] + exact softened_marginal_slices Ms m R (line ∘ e) (inner ∘ e) + offset slope smallOffset smallSlope L hL hwidth + +theorem physical_hard_marginal_removal (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (hwidth : ∀ M ∈ Ms, 2≤M) : + RemovalSlice (eliminate Ms (fun z => + hardWeight line inner offset slope smallOffset smallSlope (z ∘ e.symm))) m R := by + have hd : (inferInstance : DecidableEq S)=Classical.decEq S := Subsingleton.elim _ _ + cases hd + have heq : (fun z => hardWeight line inner offset slope smallOffset smallSlope + (z ∘ e.symm))=hardWeight (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope := by + funext z + exact (hardWeight_reindex e line inner offset slope smallOffset smallSlope z).symm + rw [heq] + exact hard_marginal_removal Ms m R (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope hwidth + +theorem physical_hard_marginal_reflected (Ms : List ℕ) (m : S → ℕ) (R : ℕ) + (e : Coordinates S Ms ≃ D) (line : D → G) (inner : D → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (hwidth : ∀ M ∈ Ms, 2≤M) : + RemovalSlice (fun z => eliminate Ms (fun q => + hardWeight line inner offset slope smallOffset smallSlope (q ∘ e.symm)) + (IntegerReflection.reflect m z)) m R := by + have hd : (inferInstance : DecidableEq S)=Classical.decEq S := Subsingleton.elim _ _ + cases hd + have heq : (fun z => hardWeight line inner offset slope smallOffset smallSlope + (z ∘ e.symm))=hardWeight (line ∘ e) (inner ∘ e) offset slope smallOffset smallSlope := by + funext z + exact (hardWeight_reindex e line inner offset slope smallOffset smallSlope z).symm + rw [heq] + exact ReflectedNested.reflected_hard_marginal Ms m R (line ∘ e) (inner ∘ e) + offset slope smallOffset smallSlope hwidth + +end ContingencyTables.NestedReindex + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/NetworkVertexCode.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/NetworkVertexCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..51017de3c877abdbf85b950ab8a2564f499e4575 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/NetworkVertexCode.lean @@ -0,0 +1,99 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedTableFeasibility +import OAI.Combinatorics.ContingencyTables.Machines.ResidualGraphProgram + +namespace OAI + +/-! # Explicit source/row/column/sink indices for the executed network -/ + +namespace ContingencyTables.NetworkVertexCode + +open LayeredTableNetwork ResidualGraphProgram + +variable {m n : ℕ} + +/-- Source and sink occupy zero and one, then rows and columns. -/ +def index : Vertex m n→ℕ + | .inl false => 0 + | .inl true => 1 + | .inr (.inl i) => 2+i.val + | .inr (.inr j) => 2+m+j.val + +def tag : Vertex m n→ℕ + | .inl false => 0 + | .inl true => 1 + | .inr (.inl _) => 2 + | .inr (.inr _) => 3 + +def kind (m k : ℕ) : ℕ := + if k=0 then 0 else if k=1 then 1 else if k<2+m then 2 else 3 + +lemma kind_index (v : Vertex m n) : kind m (index v)=tag v := by + rcases v with a | (i | j) + · cases a <;> rfl + · have h0 : 2+i.val≠0 := by omega + have h1 : 2+i.val≠1 := by omega + have h2 : 2+i.val<2+m := by have hi := i.isLt; omega + simp only [index,tag,kind,h0,h1,h2,ite_false,ite_true] + · have h0 : 2+m+j.val≠0 := by omega + have h1 : 2+m+j.val≠1 := by omega + have h2 : ¬2+m+j.val<2+m := by omega + simp only [index,tag,kind,h0,h1,h2,ite_false] + +lemma index_vertices (v : Vertex m n) : + (BoundedTableFeasibility.vertices m n v).val=index v := by + rcases v with a | (i | j) + · cases a <;> rfl + · simp [BoundedTableFeasibility.vertices,index,finSumFinEquiv_apply_left, + finSumFinEquiv_apply_right] + · simp [BoundedTableFeasibility.vertices,index, + finSumFinEquiv_apply_right,Nat.add_assoc] + +abbrev Input := (List ℕ×List ℕ)×NatMatrix + +def entry (z : Input×(ℕ×ℕ)) : ℕ := + let ku := kind z.1.1.1.length z.2.1 + let kv := kind z.1.1.1.length z.2.2 + if ku=0 ∧ kv=2 then z.1.1.1.getD (z.2.2-2) 0 + else if ku=2 ∧ kv=3 then capacityEntry (z.1.2,(z.2.1-2,z.2.2-(2+z.1.1.1.length))) + else if ku=3 ∧ kv=1 then z.1.1.2.getD (z.2.1-(2+z.1.1.1.length)) 0 + else 0 + +def data (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : Input := + ((List.ofFn r,List.ofFn c),natCode b) + +lemma entry_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (u v : Vertex m n) : + entry (data r c b,(index u,index v))=capacity r c b u v := by + have he : (data r c b).1.1.length=m := by simp [data] + have hcol (k : ℕ) : 2+(m+k)-(2+m)=k := by omega + simp only [entry,he,kind_index] + rcases u with a | (i | j) <;> rcases v with d | (k | l) + all_goals (try cases a) <;> (try cases d) + all_goals simp [tag,index,data,capacity,capacityEntry,natCode, + List.getD_eq_getElem?_getD, + Nat.add_assoc,hcol] + +def vertexCount (z : Input) : ℕ := 2+(z.1.1.length+z.1.2.length) + +def matrix (z : Input) : NatMatrix := + (List.range (vertexCount z)).map (fun u=> + (List.range (vertexCount z)).map (fun v=>entry (z,(u,v)))) + +lemma matrix_code (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + matrix (data r c b)=natCode (BoundedTableFeasibility.networkCapacity r c b) := by + have hn : vertexCount (data r c b)=2+(m+n) := by simp [vertexCount,data] + simp only [matrix,hn,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn,natCode] + apply congrArg List.ofFn + funext u + apply congrArg List.ofFn + funext v + have hu : u.val=index ((BoundedTableFeasibility.vertices m n).symm u) := by + rw [←index_vertices,Equiv.apply_symm_apply] + have hv : v.val=index ((BoundedTableFeasibility.vertices m n).symm v) := by + rw [←index_vertices,Equiv.apply_symm_apply] + simp only [Function.comp_apply,hu,hv] + exact entry_code r c b _ _ + +end ContingencyTables.NetworkVertexCode + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5992732fa1fdcf71ca3b70c6a82500e70130590 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableBounds.lean @@ -0,0 +1,190 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ObservableVariance + +namespace OAI + +/-! +# Observable and trace bounds on the actual valid-degree chain + +Positive completion is used only to instantiate the existing finite-chain +constructor. All its state weights, conductances, and conditional projections +are proved equal to the original valid-degree quantities. +-/ + +namespace ContingencyTables.ObservableBounds + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction DegreeCompletion ObservableVariance + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +/-- The manuscript's observable constant. -/ +def observableConstant (p q : ℝ) : ℝ := + 10*p^4*(9*(p*(1+8*p*q^2))+2*(8+32*p*q^3)) + +lemma observableConstant_lower (p q : ℝ) (hp : 1 ≤ p) (hq : 1 ≤ q) : + 338*p^5 ≤ observableConstant p q := by + have hp0 : 0 ≤ p := by linarith + have hq0 : 0 ≤ q := by linarith + have hq2 : 1 ≤ q^2 := by nlinarith + have hprod : 1 ≤ p*q^2 := hp.trans (by nlinarith [mul_le_mul_of_nonneg_left hq2 hp0]) + have hbig : 81*p ≤ 9*(p*(1+8*p*q^2)) := by nlinarith + have htail : 0 ≤ 2*(8+32*p*q^3) := by positivity + have hi : (338/10 : ℝ)*p ≤ 9*(p*(1+8*p*q^2))+2*(8+32*p*q^3) := by nlinarith + calc + 338*p^5 = 10*p^4*((338/10 : ℝ)*p) := by ring + _ ≤ observableConstant p q := mul_le_mul_of_nonneg_left hi (by positivity) + +/-- A sharper direct consequence of the existing proved projection bound. +The finite defect-type count is retained until its last numerical estimate. -/ +theorem observable_poincare_sharp (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) (hf : ∀ S, 0 < f S) + (hsig : HasSlotSignature f) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + chainVariance gs w f (observableProjection gs f H) ≤ + 338*(gs.length:ℝ)^5*chainDirichlet gs w f H := by + have hΛ := chainTotal_pos gs hgs hcover w f hf hw + have hm := finite_center_min (chainStates gs) (chainWeight gs w f) + (observableProjection gs f H) (plainMean gs f H) hΛ + have hb := projection_center_bound gs hgs hcover w hw f H hf hsig hlower hupper + let n : ℝ := gs.length + let D := restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ + have hD : 0 ≤ D := restrictedEnergy_nonneg _ _ _ _ _ (by + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + have hn : 1 ≤ n := by + dsimp only [n] + exact_mod_cast List.length_pos_iff.mpr hne + have hn0 : 0 < n := lt_of_lt_of_le zero_lt_one hn + have hcard : ((defectTypes gs).card:ℝ) ≤ n^2 := by + dsimp only [n] + exact_mod_cast (show (defectTypes gs).card ≤ gs.length^2 by simpa [pow_two] using defectTypes_card_le gs) + have hc : n*(1+8*n)+4*((defectTypes gs).card:ℝ)*(8+32*n) ≤ 169*n^3 := by + have hn2 : n ≤ n^2 := by nlinarith + have hn3 : n^2 ≤ n^3 := by nlinarith [mul_le_mul_of_nonneg_left hn2 hn0.le] + have hh := mul_le_mul_of_nonneg_right hcard (show 0 ≤ 4*(8+32*n) by positivity) + nlinarith + have hbound := (hm.trans hb).trans (mul_le_mul_of_nonneg_right hc hD) + change chainVariance gs w f (observableProjection gs f H) ≤ 338*n^5*(D/(2*n^2*chainTotal gs w f)) + unfold chainVariance chainMean + apply (div_le_iff₀ hΛ).mpr + have he : 338*n^5*(D/(2*n^2*chainTotal gs w f))*chainTotal gs w f = 169*n^3*D := by + field_simp + ; ring + rw [he] + exact hbound + +lemma slotDefect_completion_mul (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (k : ℕ) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) (hps : SlotsFresh ps A) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + slotDefect ps (fun S => completeDegree f k S * H S) A p r = + slotDefect ps (fun S => f S * H S) A p r := by + have heq : completeDegree (fun S => completeDegree f k S * H S) k = + completeDegree (fun S => f S * H S) k := by + funext S + unfold completeDegree + split_ifs with h + · simp [h] + · rfl + rw [← slotDefect_completeDegree ps (fun S => completeDegree f k S * H S) k A hdegree hps p r hp hr hpr, + heq, slotDefect_completeDegree ps (fun S => f S * H S) k A hdegree hps p r hp hr hpr] + +lemma observableProjection_completion (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (hgs : SlotsFresh gs ∅) (S : Set Γ) : + observableProjection gs (completeDegree f gs.length) H S = observableProjection gs f H S := by + by_cases he : ∃ p r, DefectState gs p r S + · obtain ⟨p,r,hpr⟩ := he + rw [observableProjection_defect gs _ H S hpr, observableProjection_defect gs f H S hpr] + unfold defectMean + rw [slotDefect_completion_mul gs f H gs.length ∅ (by simp) hgs p r hpr.1 hpr.2.1 hpr.2.2.1, + slotDefect_completeDegree gs f gs.length ∅ (by simp) hgs p r hpr.1 hpr.2.1 hpr.2.2.1] + · simp only [observableProjection, dite_eq_right he] + +lemma chainTotal_completion (gs : List (Γ × Γ)) (f : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : chainTotal gs w (completeDegree f gs.length) = chainTotal gs w f := by + unfold chainTotal chainWeight + apply Finset.sum_congr rfl + intro S hS + have hd := ((Finset.mem_filter.mp hS).2).ncard hgs hcover + simp only [completeDegree, hd, ite_true] + +lemma chainMean_completion (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : chainMean gs w (completeDegree f gs.length) H = chainMean gs w f H := by + unfold chainMean + rw [chainTotal_completion gs f w hgs hcover] + congr 1 + apply Finset.sum_congr rfl + intro S hS + have hd := ((Finset.mem_filter.mp hS).2).ncard hgs hcover + simp only [chainWeight, completeDegree, hd, ite_true] + +lemma chainVariance_completion (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : + chainVariance gs w (completeDegree f gs.length) H = chainVariance gs w f H := by + unfold chainVariance + rw [chainTotal_completion gs f w hgs hcover, chainMean_completion gs f H w hgs hcover] + congr 1 + apply Finset.sum_congr rfl + intro S hS + have hd := ((Finset.mem_filter.mp hS).2).ncard hgs hcover + simp only [chainWeight, completeDegree, hd, ite_true] + +lemma chainDirichlet_completion (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) : + chainDirichlet gs w (completeDegree f gs.length) H = chainDirichlet gs w f H := by + unfold chainDirichlet + rw [chainTotal_completion gs f w hgs hcover, restrictedEnergy_completeDegree gs f H w hgs hcover ∅ ∅] + +/-- Observable Poincaré on the original valid-degree weights, with the exact +manuscript constant. Off-degree positivity is absent from its assumptions. -/ +theorem validDegree_observable_poincare (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (hw : ∀ p r, 0 < w p r) (f H : Set Γ → ℝ) + (hf : DegreePositive f gs.length) (hsig : AdditionProperty f gs.length) + (q : ℝ) (hq : 1 ≤ q) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) : + chainVariance gs w f (observableProjection gs f H) ≤ + observableConstant gs.length q * chainDirichlet gs w f H := by + let F := completeDegree f gs.length + have hF := completeDegree_positive f gs.length hf + have hsF := completeDegree_hasSlotSignature f gs.length hf hsig + have hlower' : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs F ∅/(4*slotDefect gs F ∅ p r) ≤ w p r := by + intro p hp r hr hpr + dsimp [F] + rw [slotTotal_completeDegree gs f gs.length ∅ (by simp), + slotDefect_completeDegree gs f gs.length ∅ (by simp) hgs p r hp hr hpr] + exact hlower p hp r hr hpr + have hupper' : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs F ∅/slotDefect gs F ∅ p r := by + intro p hp r hr hpr + dsimp [F] + rw [slotTotal_completeDegree gs f gs.length ∅ (by simp), + slotDefect_completeDegree gs f gs.length ∅ (by simp) hgs p r hp hr hpr] + exact hupper p hp r hr hpr + have ht := observable_poincare_sharp gs hgs hne hcover w hw F H hF hsF hlower' hupper' + have hproj : observableProjection gs F H = observableProjection gs f H := + funext (observableProjection_completion gs f H hgs) + rw [hproj, chainVariance_completion gs f _ w hgs hcover, + chainDirichlet_completion gs f H w hgs hcover] at ht + have hD : 0 ≤ chainDirichlet gs w f H := by + rw [← chainDirichlet_completion gs f H w hgs hcover] + unfold chainDirichlet + apply div_nonneg + · exact restrictedEnergy_nonneg _ _ _ _ _ (by + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hF _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hF _).le)) + · exact mul_nonneg (mul_nonneg (by norm_num) (sq_nonneg _)) + (chainTotal_pos gs hgs hcover w F hF hw).le + exact ht.trans (mul_le_mul_of_nonneg_right + (observableConstant_lower gs.length q (by exact_mod_cast List.length_pos_iff.mpr hne) hq) hD) + +end ContingencyTables.ObservableBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableTrajectory.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableTrajectory.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d9f808604dc6aea7c79567fd3bdae09bdb0ae12 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableTrajectory.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TraceBounds + +namespace OAI + +/-! +# Warm trajectory averages of the paper's class observables + +The dual estimate is derived from the proved original-coordinate observable +Poincaré inequality. The existing finite-chain covariance and warm moment +lemmas then give the paper's 2UKobs Var/N mean-square bound. Completion is +absent from the observable mean, variance, and warm-start law. +-/ + +namespace ContingencyTables.ObservableTrajectory + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction DegreeCompletion ObservableVariance ObservableBounds ComplementChain + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +/-- Dual observable bound for the genuine omission-lift chain. -/ +theorem omission_chain_dual (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) + (hf : DegreePositive f gs.length) (hsig : OmissionProperty f gs.length) + (q : ℝ) (hq : 1 ≤ q) (hG : ClassObservable gs G) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (H : ChainIndex gs → ℝ) : + let C := metropolisChain gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf) + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + (C.inner g H)^2 ≤ observableConstant gs.length q*C.inner g g*C.energy H := by + let F := completeDegree f gs.length + have hF := completeDegree_positive f gs.length hf + let C := metropolisChain gs hgs hne hcover w F hw hF + let a := chainMean gs w f G + let g := fun S : ChainIndex gs => G S.val-a + let H' := extendChainFun gs H + let QH := fun S : ChainIndex gs => observableProjection gs F H' S.val + have hext : (fun S : ChainIndex gs => H' S.val) = H := by + funext S + exact extendChainFun_apply gs H S + have hmean : C.mean g = 0 := by + have hm := metropolisChain_mean gs hgs hne hcover w F G hw hF + rw [chainMean_completion gs f G w hgs hcover] at hm + change C.mean (fun S => G S.val-a) = 0 + change C.mean (fun S : ChainIndex gs => G S.val) = a at hm + rw [← hm] + exact C.centered_mean _ + have hpair : C.inner g H = C.inner g QH := by + rw [← hext] + change C.inner (fun S => G S.val-a) (fun S => H' S.val) = + C.inner (fun S => G S.val-a) (fun S => observableProjection gs F H' S.val) + dsimp only [C] + rw [metropolisChain_inner gs hgs hne hcover w F (fun S => G S-a) H' hw hF, + metropolisChain_inner gs hgs hne hcover w F (fun S => G S-a) (observableProjection gs F H') hw hF] + exact congrArg (fun t => t/chainTotal gs w F) + (chain_pairing_projection gs hgs hcover w F (fun S => G S-a) H' hF (hG.sub_const a)) + have hbound : C.variance QH ≤ observableConstant gs.length q*C.energy H := by + change (metropolisChain gs hgs hne hcover w F hw hF).variance + (fun S => observableProjection gs F H' S.val) ≤ _ + rw [metropolisChain_variance] + have hb := omission_observable_poincare gs hgs hne hcover w hw f H' hf hsig q hq hlower hupper + have hproj : observableProjection gs F H' = observableProjection gs f H' := + funext (observableProjection_completion gs f H' hgs) + rw [hproj, chainVariance_completion gs f _ w hgs hcover] + rw [← chainDirichlet_completion gs f H' w hgs hcover, + ← metropolisChain_energy gs hgs hne hcover w F H' hw hF, hext] at hb + exact hb + dsimp only + rw [hpair, ← C.inner_center_right g QH hmean (C.mean QH)] + calc + _ ≤ C.inner g g*C.variance QH := C.inner_cauchy _ _ + _ ≤ C.inner g g*(observableConstant gs.length q*C.energy H) := + mul_le_mul_of_nonneg_left hbound (C.inner_nonneg g) + _ = _ := by ring + +/-- The manuscript's trajectory mean-square estimate, using its original +conditional class observable, stationary variance, and warm-start density. -/ +theorem omission_chain_timeAverage (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f G : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) + (hf : DegreePositive f gs.length) (hsig : OmissionProperty f gs.length) + (q : ℝ) (hq : 1 ≤ q) (hG : ClassObservable gs G) + (hlower : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (U : ℝ) (hU : 0 ≤ U) (ν : ChainIndex gs → ℝ) + (hwarm : ∀ S, ν S ≤ U*chainWeight gs w f S.val/chainTotal gs w f) + (N : ℕ) (hN : 0 < N) : + let C := metropolisChain gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf) + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + (∑ S, ν S*C.squareMoment g N S)/(N:ℝ)^2 ≤ + 2*U*observableConstant gs.length q*chainVariance gs w f G/N := by + let F := completeDegree f gs.length + have hF := completeDegree_positive f gs.length hf + let C := metropolisChain gs hgs hne hcover w F hw hF + let g := fun S : ChainIndex gs => G S.val-chainMean gs w f G + have hi : C.inner g g = chainVariance gs w f G := by + rw [← chainVariance_completion gs f G w hgs hcover, + ← metropolisChain_variance gs hgs hne hcover w F G hw hF] + unfold FiniteChain.variance + rw [metropolisChain_mean, chainMean_completion gs f G w hgs hcover] + have hK : 0 ≤ observableConstant gs.length q := by + unfold observableConstant + have hq0 : 0 ≤ q := by linarith + positivity + have hwarm' : ∀ S, ν S ≤ U*C.π S := by + intro S + change ν S ≤ U*(chainWeight gs w F S.val/chainTotal gs w F) + rw [chainTotal_completion gs f w hgs hcover] + have hd := S.property.ncard hgs hcover + simpa only [chainWeight, F, completeDegree, hd, ite_true, mul_div_assoc] using hwarm S + have h := C.warm_squareMoment_bound g (observableConstant gs.length q) U hK hU + (omission_chain_dual gs hgs hne hcover w f G hw hf hsig q hq hG hlower hupper) ν hwarm' N hN + rw [hi] at h + exact h + +end ContingencyTables.ObservableTrajectory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..d26ea10565228f856399b6199ee280921ca28ff4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ObservableVariance.lean @@ -0,0 +1,444 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PairedComplement + +namespace OAI + +/-! +# Two-lift transversal variance + +The adaptive signed-transport proof from paper 200-02, with its comparison +factor q². The transport weight has addition signatures in complementary +coordinates; the other lift has addition signatures in the original +coordinates. Complement identities, rather than an interchange of those +two signature roles, supply the defect score inequalities. +-/ + +namespace ContingencyTables.ObservableVariance + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction RecursiveSignedTransport DegreeCompletion PairedComplement + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +lemma choiceVertices_plain_node (gs ps : List (Γ × Γ)) (A B : Set Γ) + (hnode : VarianceNode gs ps A B) (S : Set Γ) (hS : S ∈ choiceVertices ps A) : + PlainState gs S := by + have hfresh := hnode.2.1.mono Set.subset_union_left + have hs := (mem_choiceVertices_iff ps A S hfresh).mp hS + have hdis : Disjoint B S := choiceVertices_excluded ps A B S hnode.1 + (fun r hr => by + have h := hnode.2.1.elements_fresh r hr + exact ⟨fun hx => h.1 (Or.inr hx), fun hx => h.2 (Or.inr hx)⟩) hS + intro r hr + by_cases hm : r ∈ ps + · exact hs.2.2 r hm + · exact hnode.2.2.2.single ⟨hs.1, hdis⟩ r hr hm + +lemma choiceVertices_defect_node (gs ps : List (Γ × Γ)) (A B : Set Γ) + (hnode : VarianceNode gs ps A B) (p r : Γ × Γ) + (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) + (S : Set Γ) (hS : S ∈ choiceVertices ((ps.erase p).erase r) (insert r.1 (insert r.2 A))) : + DefectState gs p r S := by + let qs := (ps.erase p).erase r + have hperm : ps.Perm (p::r::qs) := slots_perm_two hp hr hpr + have hh := (SlotsFresh.perm hperm (A ∪ B)).mp hnode.2.1 + have hq : SlotsFresh qs (insert r.1 (insert r.2 A)) := by + apply hh.2.2.2.2.2.2.mono + intro x hx + simp only [Set.mem_insert_iff, Set.mem_union] at hx ⊢ + tauto + have hs := (mem_choiceVertices_iff qs _ S hq).mp hS + have hB : Disjoint B S := choiceVertices_excluded qs _ B S + (by + apply Set.disjoint_insert_left.mpr + refine ⟨fun hx => hh.2.2.2.2.1 (Or.inr (Or.inr (Or.inr hx))), ?_⟩ + apply Set.disjoint_insert_left.mpr + exact ⟨fun hx => hh.2.2.2.2.2.1 (Or.inr (Or.inr (Or.inr hx))), hnode.1⟩) + (fun t ht => by + have h := hh.2.2.2.2.2.2.elements_fresh t ht + exact ⟨fun hx => h.1 (Or.inr (Or.inr (Or.inr (Or.inr (Or.inr hx))))), + fun hx => h.2 (Or.inr (Or.inr (Or.inr (Or.inr (Or.inr hx)))))⟩) hS + have hep : PairEmpty p S := by + have hn (x : Γ) (hxA : x ∉ A) (hxr₁ : x ≠ r.1) (hxr₂ : x ≠ r.2) + (hxq : x ∉ pairSupport qs) : x ∉ S := by + intro hx + have := hs.2.1 hx + simp only [Set.mem_union, Set.mem_insert_iff] at this + tauto + have hr₁ := hh.2.2.2.2.1 + have hr₂ := hh.2.2.2.2.2.1 + have hqd := hh.2.2.2.2.2.2.support_disjoint + constructor + · apply hn p.1 (fun h => hh.2.1 (Or.inl h)) + · intro h; exact hr₁ (Or.inl h.symm) + · intro h; exact hr₂ (Or.inl h.symm) + · intro h; exact Set.disjoint_left.mp hqd h (Or.inr (Or.inr (Or.inl rfl))) + · apply hn p.2 (fun h => hh.2.2.1 (Or.inl h)) + · intro h; exact hr₁ (Or.inr (Or.inl h.symm)) + · intro h; exact hr₂ (Or.inr (Or.inl h.symm)) + · intro h; exact Set.disjoint_left.mp hqd h (Or.inr (Or.inr (Or.inr (Or.inl rfl)))) + refine ⟨hnode.2.2.1 p hp, hnode.2.2.1 r hr, hpr, hep, + ⟨hs.1 (Or.inl rfl), hs.1 (Or.inr (Or.inl rfl))⟩, ?_⟩ + intro t ht htp htr + by_cases hm : t ∈ ps + · exact hs.2.2 t ((List.mem_erase_of_ne htr).mpr ((List.mem_erase_of_ne htp).mpr hm)) + · exact hnode.2.2.2.single ⟨fun x hx => hs.1 (Or.inr (Or.inr hx)), hB⟩ t ht hm + +lemma slotTotal_node_agreement (gs ps : List (Γ × Γ)) (f g : Set Γ → ℝ) + (hagree : ∀ S, PlainState gs S → f S = g S) (A B : Set Γ) + (hnode : VarianceNode gs ps A B) : slotTotal ps f A = slotTotal ps g A := by + have hfr := hnode.2.1.mono Set.subset_union_left + rw [slotTotal_eq_choice_sum ps A f hfr, slotTotal_eq_choice_sum ps A g hfr] + exact Finset.sum_congr rfl (fun S hS => hagree S (choiceVertices_plain_node gs ps A B hnode S hS)) + +lemma slotDefect_node_comparison (gs ps : List (Γ × Γ)) (f g : Set Γ → ℝ) (q : ℝ) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) (A B : Set Γ) + (hnode : VarianceNode gs ps A B) (p r : Γ × Γ) + (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + slotDefect ps f A p r ≤ q*slotDefect ps g A p r := by + let qs := (ps.erase p).erase r + have hh := (SlotsFresh.perm (slots_perm_two hp hr hpr) (A ∪ B)).mp hnode.2.1 + have hq : SlotsFresh qs (insert r.1 (insert r.2 A)) := by + apply hh.2.2.2.2.2.2.mono + intro x hx + simp only [Set.mem_insert_iff, Set.mem_union] at hx ⊢ + tauto + unfold slotDefect + rw [slotTotal_eq_choice_sum qs _ f hq, slotTotal_eq_choice_sum qs _ g hq, Finset.mul_sum] + apply Finset.sum_le_sum + intro S hS + exact hcompare S (Or.inr ⟨p, r, choiceVertices_defect_node gs ps A B hnode p r hp hr hpr S hS⟩) + +lemma complement_global_pair_bound (ps : List (Γ × Γ)) (g : Set Γ → ℝ) + (hg : ∀ S, 0 < g S) (hsig : HasSlotSignature (complementWeight g)) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + 4 * slotDefect ps g A p r * slotDefect ps g A r p ≤ (slotTotal ps g A)^2 := by + have hh := complement_defect_pair ps (complementWeight g) (B.ncard + ps.length) + (fun S _ => hg Sᶜ) (fun S _ => hsig [] S) A B hAB hps hcover rfl p r hp hr hpr + have hcc : complementWeight (complementWeight g) = g := by + funext S + simp [complementWeight] + rwa [hcc] at hh + +lemma complement_global_triple_bound (ps : List (Γ × Γ)) (g : Set Γ → ℝ) + (hg : ∀ S, 0 < g S) (hsig : HasSlotSignature (complementWeight g)) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) + (p r t : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) + (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : + slotDefect ps g A p r * slotDefect ps g A r t ≤ slotTotal ps g A * slotDefect ps g A p t := by + have hh := complement_defect_triple ps (complementWeight g) (B.ncard + ps.length) + (fun S _ => hg Sᶜ) (fun S _ => hsig [] S) A B hAB hps hcover rfl p r t hp hr ht hpr hrt hpt + have hcc : complementWeight (complementWeight g) = g := by + funext S + simp [complementWeight] + rwa [hcc] at hh + +/-- The sink is proved from the second lift's two- and three-pair inequalities; +its raw signature is in the complementary coordinates. -/ +lemma twoLift_scores_sink (gs ps : List (Γ × Γ)) (g : Set Γ → ℝ) + (hg : ∀ S, 0 < g S) (hsig : HasSlotSignature (complementWeight g)) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) + (A B : Set Γ) (hnode : VarianceNode gs ps A B) (hne : ps ≠ []) : + ∃ p ∈ ps, ∀ r ∈ ps, p ≠ r → + slotDefect ps g A r p * slotDefect gs g ∅ p r ≤ slotTotal ps g A * slotTotal gs g ∅ := by + let J := {p : Γ × Γ // p ∈ ps} + have : Nonempty J := by + obtain ⟨p,hp⟩ := List.exists_mem_of_ne_nil ps hne + exact ⟨⟨p,hp⟩⟩ + have hne' : ∀ p r : J, p ≠ r → p.val ≠ r.val := fun p r h he => h (Subtype.ext he) + have hglobal : VarianceNode gs gs ∅ ∅ := ⟨by simp, by simpa using hgs, + fun _ => id, fun r hr hn => False.elim (hn hr)⟩ + have hpfr := hnode.2.1.mono Set.subset_union_left + obtain ⟨p,hp⟩ := coefficient_scores_sink + (fun p r : J => slotDefect ps g A r.val p.val) + (fun p r : J => slotDefect gs g ∅ r.val p.val) + (slotTotal ps g A) (slotTotal gs g ∅) + (slotTotal_pos ps g hg A hpfr) (slotTotal_pos gs g hg ∅ hgs) + (fun p r h => (slotDefect_pos ps g hg A hpfr r p r.property p.property (hne' r p h.symm)).le) + (fun p r h => (slotDefect_pos gs g hg ∅ hgs r p (hnode.2.2.1 r r.property) + (hnode.2.2.1 p p.property) (hne' r p h.symm)).le) + (fun p r h => complement_global_pair_bound ps g hg hsig A B hnode.1 hnode.2.1 + (PairedComplement.VarianceNode.cover hnode hcover) r p r.property p.property (hne' r p h.symm)) + (fun p r h => complement_global_pair_bound gs g hg hsig ∅ ∅ hglobal.1 hglobal.2.1 + (PairedComplement.VarianceNode.cover hglobal hcover) r p (hnode.2.2.1 r r.property) (hnode.2.2.1 p p.property) (hne' r p h.symm)) + (fun p r t h₁ h₂ h₃ => by + simpa only [mul_comm] using complement_global_triple_bound ps g hg hsig A B hnode.1 hnode.2.1 + (PairedComplement.VarianceNode.cover hnode hcover) t r p t.property r.property p.property + (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) + (fun p r t h₁ h₂ h₃ => by + simpa only [mul_comm] using complement_global_triple_bound gs g hg hsig ∅ ∅ hglobal.1 hglobal.2.1 + (PairedComplement.VarianceNode.cover hglobal hcover) t r p (hnode.2.2.1 t t.property) (hnode.2.2.1 r r.property) + (hnode.2.2.1 p p.property) (hne' t r h₂.symm) (hne' r p h₁.symm) (hne' t p h₃.symm)) + refine ⟨p.val,p.property,?_⟩ + intro r hr hpr + exact hp ⟨r,hr⟩ (fun h => hpr (congrArg Subtype.val h)) + +/-- One transport split costs at most 1+8s q². -/ +theorem transport_node_variance_twoLift (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (q : ℝ) + (hf : ∀ S, 0 < f S) (hSig : HasSlotSignature f) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hWp : W p = 1) (hWd : W d = 1) + (hsink : ∀ x ∈ slotPunctures ps, + slotTotal x.2 f (insert p (insert d A))/W x.1.1 ≤ + 4*q^2*(slotTotal ps f (insert p A)+slotTotal ps f (insert d A))) : + let sp := slotTotal ps f (insert p A) + let sd := slotTotal ps f (insert d A) + sp*sd/(sp+sd) * + (slotTotal ps (fun S => f S*H S) (insert p A)/sp - + slotTotal ps (fun S => f S*H S) (insert d A)/sd)^2 ≤ + (1+8*(ps.length : ℝ)*q^2)*slotGraphEnergy ps f H A (rootEmbedding p d) W := by + let sp := slotTotal ps f (insert p A) + let sd := slotTotal ps f (insert d A) + have hp : 0 < sp := slotTotal_pos ps f hf _ (hps.mono (by + intro x hx; rcases hx with rfl | hx + · exact Or.inr ⟨false,rfl⟩ + · exact Or.inl hx)) + have hd : 0 < sd := slotTotal_pos ps f hf _ (hps.mono (by + intro x hx; rcases hx with rfl | hx + · exact Or.inr ⟨true,rfl⟩ + · exact Or.inl hx)) + have hpd' : 0 < sp*sd/(sp+sd) := div_pos (mul_pos hp hd) (add_pos hp hd) + have hsum := list_sum_map_le_const (slotPunctures ps) + (fun x => slotTotal x.2 f (insert p (insert d A))/W x.1.1) (4*q^2*(sp+sd)) hsink + rw [slotPunctures_length] at hsum + have hcoef : sp*sd/(sp+sd)*rootCoefficient ps f A p d W ≤ 1+8*(ps.length : ℝ)*q^2 := by + unfold rootCoefficient + change sp*sd/(sp+sd)*(1/(sp*W p)+1/(sd*W d)+2/(sp*sd)*_) ≤ _ + rw [hWp,hWd,mul_one,mul_one] + have heq (s : ℝ) : sp*sd/(sp+sd)*(1/sp+1/sd+2/(sp*sd)*s) = 1+2/(sp+sd)*s := by + field_simp + ; ring + rw [heq] + have hh := mul_le_mul_of_nonneg_left hsum (show 0 ≤ 2/(sp+sd) by positivity) + have heq' : 2/(sp+sd)*((ps.length : ℝ)*(4*q^2*(sp+sd))) = 8*(ps.length : ℝ)*q^2 := by + field_simp + ; ring + rw [heq'] at hh + linarith + have hE : 0 ≤ slotGraphEnergy ps f H A (rootEmbedding p d) W := by + unfold slotGraphEnergy + apply div_nonneg _ (by norm_num) + apply Finset.sum_nonneg + intro ST hST + unfold slotEdgeEnergy + apply mul_nonneg _ (sq_nonneg _) + apply le_min + · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le + · exact mul_nonneg (missingMultiplier_nonneg ps _ W (fun i => (hW i).le) _ ) (hf _).le + have ht := mul_le_mul_of_nonneg_left + (transport_graph_bound ps f H A p d W hf hSig hpd hpA hdA hps hW hw) hpd'.le + dsimp only + exact ht.trans (by rw [← mul_assoc]; exact mul_le_mul_of_nonneg_right hcoef hE) + +lemma twoLift_variance_node (gs ps : List (Γ × Γ)) (f g H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (q : ℝ) (hq : 0 ≤ q) + (hf : ∀ S, 0 < f S) (hg : ∀ S, 0 < g S) + (hsigf : HasSlotSignature f) (hsigg : HasSlotSignature (complementWeight g)) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) + (A B : Set Γ) (hnode : VarianceNode gs ps A B) (hne : ps ≠ []) : + ∃ p qs, ps.Perm (p::qs) ∧ SlotsFresh (p::qs) A ∧ + VarianceNode gs qs (insert p.1 A) (insert p.2 B) ∧ + VarianceNode gs qs (insert p.2 A) (insert p.1 B) ∧ + slotVariance (p::qs) f H A - slotVariance qs f H (insert p.1 A) - + slotVariance qs f H (insert p.2 A) ≤ + (1+8*(gs.length : ℝ)*q^2)*restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + obtain ⟨p,hp,hsink⟩ := twoLift_scores_sink gs ps g hg hsigg hgs hcover A B hnode hne + let qs := ps.erase p + have hperm : ps.Perm (p::qs) := List.perm_cons_erase hp + have hnode' := hnode.perm hperm + have hfr := hnode'.2.1 + have hfrA : SlotsFresh (p::qs) A := hfr.mono Set.subset_union_left + have hps : SlotsFresh qs (A ∪ Set.range (rootEmbedding p.1 p.2)) := + hfrA.2.2.2.mono (by + intro x hx + rcases hx with hx | ⟨i,rfl⟩ + · exact Or.inr (Or.inr hx) + · cases i <;> simp [rootEmbedding]) + let W := pairMultiplier qs (w p) + have hW : ∀ x, 0 < W x := pairMultiplier_pos qs (w p) (hw p) + have hws : ∀ r ∈ qs, W r.1 = W r.2 := by + intro r hr + dsimp only [W] + rw [pairMultiplier_on hps _ r hr r.1 (Or.inl rfl), pairMultiplier_on hps _ r hr r.2 (Or.inr rfl)] + have hWp : W p.1 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨false,rfl⟩) + have hWd : W p.2 = 1 := pairMultiplier_fresh hps _ _ (Or.inr ⟨true,rfl⟩) + have hglobal : VarianceNode gs gs ∅ ∅ := ⟨by simp, by simpa using hgs, + fun _ => id, fun r hr hn => False.elim (hn hr)⟩ + have hz : slotTotal ps g A = slotTotal ps f A := (slotTotal_node_agreement gs ps f g hagree A B hnode).symm + have hC : slotTotal gs g ∅ = slotTotal gs f ∅ := (slotTotal_node_agreement gs gs f g hagree ∅ ∅ hglobal).symm + have hsink' : ∀ x ∈ slotPunctures qs, + slotTotal x.2 f (insert p.1 (insert p.2 A))/W x.1.1 ≤ + 4*q^2*(slotTotal qs f (insert p.1 A)+slotTotal qs f (insert p.2 A)) := by + intro x hx + have hxq : x.1 ∈ qs := (slotPunctures_perm qs x hx).mem_iff.mpr List.mem_cons_self + have hxp : p ≠ x.1 := hfr.pair_ne_of_mem hxq + have hxps : x.1 ∈ ps := hperm.mem_iff.mpr (List.mem_cons_of_mem _ hxq) + have hpG := hnode.2.2.1 p hp + have hxG := hnode.2.2.1 x.1 hxps + have hcpos := slotDefect_pos gs f hf ∅ hgs p x.1 hpG hxG hxp + have hzpos := slotTotal_pos ps f hf A (hnode.2.1.mono Set.subset_union_left) + have hs := hsink x.1 hxps hxp + rw [hz,hC] at hs + have hm := mul_le_mul + (slotDefect_node_comparison gs ps f g q hcompare A B hnode x.1 p hxps hp hxp.symm) + (slotDefect_node_comparison gs gs f g q hcompare ∅ ∅ hglobal p x.1 hpG hxG hxp) + hcpos.le (mul_nonneg hq (slotDefect_pos ps g hg A (hnode.2.1.mono Set.subset_union_left) + x.1 p hxps hp hxp.symm).le) + have hs' : slotDefect ps f A x.1 p * slotDefect gs f ∅ p x.1 ≤ + q^2*(slotTotal ps f A * slotTotal gs f ∅) := by + calc + _ ≤ (q*slotDefect ps g A x.1 p)*(q*slotDefect gs g ∅ p x.1) := hm + _ = q^2*(slotDefect ps g A x.1 p*slotDefect gs g ∅ p x.1) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_left hs (sq_nonneg q) + rw [slotDefect_perm hperm,slotDefect_puncture qs p A f hfrA x hx] at hs' + have hg := (div_le_iff₀ (mul_pos (by norm_num : (0:ℝ)<4) hcpos)).mp (hgood p hpG x.1 hxG hxp) + have hgz := mul_le_mul_of_nonneg_left hg (mul_nonneg (sq_nonneg q) hzpos.le) + have hbound : slotTotal x.2 f (insert p.1 (insert p.2 A)) ≤ + 4*q^2*slotTotal ps f A*w p x.1 := by + apply (mul_le_mul_iff_of_pos_right hcpos).mp + nlinarith + change slotTotal x.2 f (insert p.1 (insert p.2 A))/pairMultiplier qs (w p) x.1.1 ≤ _ + rw [pairMultiplier_on hps _ x.1 hxq x.1.1 (Or.inl rfl)] + apply (div_le_iff₀ (hw p x.1)).mpr + rw [slotTotal_perm hperm f,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] at hbound + exact hbound + have ht := transport_node_variance_twoLift qs f H A p.1 p.2 W q hf hsigf + hfrA.1 hfrA.2.1 hfrA.2.2.1 hps hW hws hWp hWd hsink' + have he := variance_energy_identification gs qs A B p w f H hw hf + hnode'.2.2.1 hnode'.1 hfr hnode'.2.2.2 + have hqle : qs.length ≤ gs.length := by + have hnodup := (hnode.2.1.nodup).erase p + exact List.Subperm.length_le (List.subperm_of_subset hnodup (fun r hr => hnode'.2.2.1 r (List.mem_cons_of_mem _ hr))) + have hqleR : (qs.length : ℝ) ≤ gs.length := by exact_mod_cast hqle + have hcoef : 1+8*(qs.length:ℝ)*q^2 ≤ 1+8*(gs.length:ℝ)*q^2 := by + nlinarith [mul_le_mul_of_nonneg_right hqleR (sq_nonneg q)] + have hepos : 0 ≤ restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + apply restrictedEnergy_nonneg + intro ST _ + exact le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + have hfinal := ht.trans ((mul_le_mul_of_nonneg_left he + (by positivity : (0:ℝ) ≤ 1+8*(qs.length:ℝ)*q^2)).trans + (mul_le_mul_of_nonneg_right hcoef hepos)) + refine ⟨p,qs,hperm,hfrA,hnode'.children.1,hnode'.children.2,?_⟩ + rw [slotVariance_split qs f H hf A p hfrA,slotTotal_cons p qs f A hfrA.1 hfrA.2.1 hfrA.2.2.1] + linarith + +/-- Actual adaptive variance bound with the paper's Cp=p(1+8p q²). +No variance, sink, or transport estimate is an input to this theorem. -/ +theorem twoLift_transversal_variance (gs : List (Γ × Γ)) (f g H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (q : ℝ) (hq : 0 ≤ q) + (hf : ∀ S, 0 < f S) (hg : ∀ S, 0 < g S) + (hsigf : HasSlotSignature f) (hsigg : HasSlotSignature (complementWeight g)) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) : + slotVariance gs f H ∅ ≤ (gs.length : ℝ)*(1+8*(gs.length : ℝ)*q^2)* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + apply adaptive_variance_bound f H hf (chainEdges gs) (chainConductance gs w f) + (fun ST _ => le_min (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le) + (mul_nonneg (chainMultiplier_pos gs w hw _).le (hf _).le)) + (1+8*(gs.length:ℝ)*q^2) (by positivity) (VarianceNode gs) + (fun ps A B hnode hne => twoLift_variance_node gs ps f g H w q hq hf hg hsigf hsigg + hgs hcover hw hgood hagree hcompare A B hnode hne) + exact ⟨by simp,by simpa using hgs,fun _ => id,fun r hr hn => False.elim (hn hr)⟩ + +lemma slotVariance_completeDegree (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (k : ℕ) + (A : Set Γ) (hdegree : A.ncard + ps.length = k) : + slotVariance ps (completeDegree f k) H A = slotVariance ps f H A := by + have hs (h : Set Γ → ℝ) : slotTotal ps (fun S => completeDegree f k S * h S) A = + slotTotal ps (fun S => f S * h S) A := by + apply coeffDerivs_degree_congr _ _ _ k + · intro S hS + simp [completeDegree, hS] + · simpa only [List.length_map] using hdegree + unfold slotVariance + rw [hs, hs, slotTotal_completeDegree ps f k A hdegree] + +lemma restrictedEnergy_completeDegree (gs : List (Γ × Γ)) (f H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (hgs : SlotsFresh gs ∅) + (hcover : pairSupport gs = Set.univ) (A B : Set Γ) : + restrictedEnergy (chainEdges gs) (chainConductance gs w (completeDegree f gs.length)) H A B = + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H A B := by + unfold restrictedEnergy + congr 1 + apply Finset.sum_congr rfl + intro ST hST + have hh := (Finset.mem_filter.mp hST).2 + have hs := hh.1.ncard hgs hcover + have ht := hh.2.1.ncard hgs hcover + simp only [chainConductance, completeDegree, hs, ht, ite_true] + +/-- Completion is eliminated from the genuine fixed-degree variance bound. +Only the transport lift's addition signature and the other lift's omission +signature in these encoded coordinates are assumed. -/ +theorem validDegree_twoLift_transversal_variance (gs : List (Γ × Γ)) (f g H : Set Γ → ℝ) + (w : (Γ × Γ) → (Γ × Γ) → ℝ) (q : ℝ) (hq : 0 ≤ q) + (hf : DegreePositive f gs.length) (hg : DegreePositive g gs.length) + (hsigf : AdditionProperty f gs.length) (hsigg : OmissionProperty g gs.length) + (hgs : SlotsFresh gs ∅) (hcover : pairSupport gs = Set.univ) + (hw : ∀ p r, 0 < w p r) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs f ∅ / (4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) : + slotVariance gs f H ∅ ≤ (gs.length : ℝ)*(1+8*(gs.length : ℝ)*q^2)* + restrictedEnergy (chainEdges gs) (chainConductance gs w f) H ∅ ∅ := by + let F := completeDegree f gs.length + let G := complementWeight (completeDegree (complementWeight g) (Fintype.card Γ - gs.length)) + have hk : gs.length ≤ Fintype.card Γ := by + have hc := slots_ground_card gs hgs hcover + omega + have hgc := complement_degreePositive g gs.length hk hg + have hF : ∀ S, 0 < F S := completeDegree_positive f gs.length hf + have hG : ∀ S, 0 < G S := fun S => completeDegree_positive _ _ hgc Sᶜ + have hFsig := completeDegree_hasSlotSignature f gs.length hf hsigf + have hGsig : HasSlotSignature (complementWeight G) := by + have heq : complementWeight G = completeDegree (complementWeight g) (Fintype.card Γ - gs.length) := by + funext S + simp [G, complementWeight] + rw [heq] + exact completeDegree_hasSlotSignature _ _ hgc hsigg + have hF_eq (S : Set Γ) (hS : S.ncard = gs.length) : F S = f S := by + simp [F, completeDegree, hS] + have hG_eq (S : Set Γ) (hS : S.ncard = gs.length) : G S = g S := by + have hc := S.ncard_add_ncard_compl + simp only [Nat.card_eq_fintype_card] at hc + have hSc : Sᶜ.ncard = Fintype.card Γ - gs.length := by omega + simp [G, complementWeight, completeDegree, hSc] + have hgood' : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → + slotTotal gs F ∅ / (4*slotDefect gs F ∅ p r) ≤ w p r := by + intro p hp r hr hpr + dsimp only [F] + rw [slotTotal_completeDegree gs f gs.length ∅ (by simp), + slotDefect_completeDegree gs f gs.length ∅ (by simp) hgs p r hp hr hpr] + exact hgood p hp r hr hpr + have hagree' : ∀ S, PlainState gs S → F S = G S := by + intro S hS + rw [hF_eq S (hS.ncard hgs hcover), hG_eq S (hS.ncard hgs hcover)] + exact hagree S hS + have hcompare' : ∀ S, ChainState gs S → F S ≤ q*G S := by + intro S hS + rw [hF_eq S (hS.ncard hgs hcover), hG_eq S (hS.ncard hgs hcover)] + exact hcompare S hS + have ht := twoLift_transversal_variance gs F G H w q hq hF hG hFsig hGsig + hgs hcover hw hgood' hagree' hcompare' + rwa [slotVariance_completeDegree gs f H gs.length ∅ (by simp), + restrictedEnergy_completeDegree gs f H w hgs hcover ∅ ∅] at ht + +end ContingencyTables.ObservableVariance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedComplement.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedComplement.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc21b8164695e36f3329231e4ea873893a7913e8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedComplement.lean @@ -0,0 +1,183 @@ +import OAI.Combinatorics.ContingencyTables.Transport.DegreeCompletion + +namespace OAI + +/-! +# Complementation of paired conditional masses + +Complementing a transversal assignment swaps its fixed inclusions and +exclusions and reverses the empty/full defect labels. These are identities +of the actual finite coefficient sums, used to keep the omission and +addition roles of the two factorial lifts separate. +-/ + +namespace ContingencyTables.PairedComplement + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction DegreeCompletion + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +lemma paired_children (ps : List (Γ × Γ)) (A B : Set Γ) (p : Γ × Γ) + (hAB : Disjoint A B) (hps : SlotsFresh (p::ps) (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport (p::ps) = Set.univ) : + Disjoint (insert p.1 A) (insert p.2 B) ∧ + SlotsFresh ps (insert p.1 A ∪ insert p.2 B) ∧ + insert p.1 A ∪ insert p.2 B ∪ pairSupport ps = Set.univ := by + obtain ⟨hp, ha, hb, ht⟩ := hps + refine ⟨?_, ht.mono ?_, ?_⟩ + · simp only [Set.disjoint_insert_left, Set.disjoint_insert_right, Set.mem_insert_iff, + not_or] + exact ⟨⟨hp.symm, fun h => hb (Or.inl h)⟩, fun h => ha (Or.inr h), hAB⟩ + · intro x hx + simp only [Set.mem_union, Set.mem_insert_iff] at hx ⊢ + tauto + · rw [← hcover, pairSupport_cons] + ext x + simp only [Set.mem_union, Set.mem_insert_iff] + tauto + +/-- Exact complement identity for a residual paired choice sum. -/ +theorem slotTotal_complement (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) : + slotTotal ps (complementWeight f) A = slotTotal ps f B := by + induction ps generalizing A B with + | nil => + have hcompl : Aᶜ = B := by + ext x + have hx : x ∈ A ∪ B := by + have h := Set.mem_univ x + rw [← hcover] at h + simpa using h + constructor + · intro ha + exact hx.resolve_left ha + · intro hb ha + exact Set.disjoint_left.mp hAB ha hb + simp only [slotTotal_nil, complementWeight, hcompl] + | cons p ps ih => + have hA := hps.mono Set.subset_union_left + have hB := hps.mono Set.subset_union_right + obtain ⟨hd₁, hf₁, hc₁⟩ := paired_children ps A B p hAB hps hcover + have hswap : SlotsFresh ((p.2,p.1)::ps) (A ∪ B) := by + refine ⟨hps.1.symm, hps.2.2.1, hps.2.1, ?_⟩ + convert hps.2.2.2 using 1 + ext x + simp only [Set.mem_insert_iff] + tauto + have hcovswap : A ∪ B ∪ pairSupport ((p.2,p.1)::ps) = Set.univ := by + rw [← hcover, pairSupport_cons, pairSupport_cons] + ext x + simp only [Set.mem_union, Set.mem_insert_iff] + tauto + obtain ⟨hd₂, hf₂, hc₂⟩ := paired_children ps A B (p.2,p.1) hAB hswap hcovswap + rw [slotTotal_cons p ps _ A hA.1 hA.2.1 hA.2.2.1, + slotTotal_cons p ps _ B hB.1 hB.2.1 hB.2.2.1, + ih _ _ hd₁ hf₁ hc₁, ih _ _ hd₂ hf₂ hc₂, add_comm] + +omit [Fintype Γ] in +lemma VarianceNode.cover {gs ps : List (Γ × Γ)} {A B : Set Γ} + (hnode : VarianceNode gs ps A B) (hcover : pairSupport gs = Set.univ) : + A ∪ B ∪ pairSupport ps = Set.univ := by + apply Set.eq_univ_of_forall + intro x + have hx : x ∈ pairSupport gs := hcover ▸ Set.mem_univ x + obtain ⟨r, hr, hx⟩ := hx + by_cases hm : r ∈ ps + · exact Or.inr ⟨r, hm, hx⟩ + · rcases hnode.2.2.2 r hr hm with h | h + · rcases hx with rfl | rfl + · exact Or.inl (Or.inl h.1) + · exact Or.inl (Or.inr h.2) + · rcases hx with rfl | rfl + · exact Or.inl (Or.inr h.2) + · exact Or.inl (Or.inl h.1) + +omit [Fintype Γ] [DecidableEq Γ] in +lemma VarianceNode.complement {gs ps : List (Γ × Γ)} {A B : Set Γ} + (hnode : VarianceNode gs ps A B) : VarianceNode gs ps B A := by + refine ⟨hnode.1.symm, ?_, hnode.2.2.1, ?_⟩ + · simpa only [Set.union_comm] using hnode.2.1 + · intro r hr hn + rcases hnode.2.2.2 r hr hn with h | h + · exact Or.inr ⟨h.2, h.1⟩ + · exact Or.inl ⟨h.2, h.1⟩ + +/-- Complementation reverses the two distinguished defect labels. -/ +theorem slotDefect_complement (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + slotDefect ps (complementWeight f) A p r = slotDefect ps f B r p := by + let qs := (ps.erase p).erase r + have hperm : ps.Perm (p::r::qs) := slots_perm_two hp hr hpr + have hh := (SlotsFresh.perm hperm (A ∪ B)).mp hps + have hcov : A ∪ B ∪ pairSupport (p::r::qs) = Set.univ := by + rwa [← pairSupport_perm hperm] + have hfr : SlotsFresh qs ((insert r.1 (insert r.2 A)) ∪ insert p.1 (insert p.2 B)) := by + apply hh.2.2.2.2.2.2.mono + intro x hx + simp only [Set.mem_union, Set.mem_insert_iff] at hx ⊢ + tauto + have hab : Disjoint (insert r.1 (insert r.2 A)) (insert p.1 (insert p.2 B)) := by + have hp₁ : p.1 ∉ A ∪ B := hh.2.1 + have hp₂ : p.2 ∉ A ∪ B := hh.2.2.1 + have hr₁ := hh.2.2.2.2.1 + have hr₂ := hh.2.2.2.2.2.1 + simp only [Set.mem_insert_iff, Set.mem_union, not_or] at hp₁ hp₂ hr₁ hr₂ + apply Set.disjoint_left.mpr + intro x hx hy + simp only [Set.mem_insert_iff] at hx hy + rcases hx with rfl | rfl | hx + · tauto + · tauto + · rcases hy with rfl | rfl | hy + · tauto + · tauto + · exact Set.disjoint_left.mp hAB hx hy + have hc : insert r.1 (insert r.2 A) ∪ insert p.1 (insert p.2 B) ∪ pairSupport qs = Set.univ := by + rw [← hcov, pairSupport_cons, pairSupport_cons] + ext x + simp only [Set.mem_union, Set.mem_insert_iff] + tauto + unfold slotDefect + rw [List.erase_comm r p] + exact slotTotal_complement qs f _ _ hab hfr hc + +/-- The complementary second lift satisfies the same oriented defect +inequalities, although its raw signature role is omission rather than addition. -/ +theorem complement_defect_pair (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) + (hdegree : B.ncard + ps.length = k) + (p r : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (hpr : p ≠ r) : + 4 * slotDefect ps (complementWeight f) A p r * + slotDefect ps (complementWeight f) A r p ≤ (slotTotal ps (complementWeight f) A)^2 := by + rw [slotDefect_complement ps f A B hAB hps hcover p r hp hr hpr, + slotDefect_complement ps f A B hAB hps hcover r p hr hp hpr.symm, + slotTotal_complement ps f A B hAB hps hcover] + exact slotDefect_pair_bound_degree ps f k hf hsig B hdegree + (hps.mono Set.subset_union_right) r p hr hp hpr.symm + +/-- Reversing all defect labels preserves the three-pair cross-entry bound. -/ +theorem complement_defect_triple (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hsig : AdditionProperty f k) + (A B : Set Γ) (hAB : Disjoint A B) (hps : SlotsFresh ps (A ∪ B)) + (hcover : A ∪ B ∪ pairSupport ps = Set.univ) + (hdegree : B.ncard + ps.length = k) + (p r t : Γ × Γ) (hp : p ∈ ps) (hr : r ∈ ps) (ht : t ∈ ps) + (hpr : p ≠ r) (hrt : r ≠ t) (hpt : p ≠ t) : + slotDefect ps (complementWeight f) A p r * slotDefect ps (complementWeight f) A r t ≤ + slotTotal ps (complementWeight f) A * slotDefect ps (complementWeight f) A p t := by + rw [slotDefect_complement ps f A B hAB hps hcover p r hp hr hpr, + slotDefect_complement ps f A B hAB hps hcover r t hr ht hrt, + slotDefect_complement ps f A B hAB hps hcover p t hp ht hpt, + slotTotal_complement ps f A B hAB hps hcover] + simpa only [mul_comm] using slotDefect_triple_bound_degree ps f k hf hsig B hdegree + (hps.mono Set.subset_union_right) t r p ht hr hp hrt.symm hpr.symm hpt.symm + +end ContingencyTables.PairedComplement + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedLabels.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b235818197a8a41c118ffc210622897c59246a7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedLabels.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TwoLiftStates + +namespace OAI + +/-! # The actual doubled labels form disjoint covering slots -/ + +namespace ContingencyTables.PairedLabels + +open scoped BigOperators Classical +open CommonBasesFPRAS TwoLiftStates + +variable {P : Type*} + +private lemma mapped_fresh (l : List P) (hl : l.Nodup) (B : Set (P×Bool)) + (hB : ∀ p ∈ l, ∀ b, (p,b)∉B) : SlotsFresh (l.map pair) B := by + induction l generalizing B with + | nil => trivial + | cons p l ih => + have hd := List.nodup_cons.mp hl + refine ⟨?_,hB p (by simp) false,hB p (by simp) true,?_⟩ + · intro he + exact Bool.false_ne_true (congrArg Prod.snd he) + · apply ih hd.2 + intro q hq b hm + rcases hm with he|he|hm + · have hqp : q=p := congrArg Prod.fst he + exact hd.1 (hqp ▸ hq) + · have hqp : q=p := congrArg Prod.fst he + exact hd.1 (hqp ▸ hq) + · exact hB q (by simp [hq]) b hm + +variable [Fintype P] + +theorem fresh : SlotsFresh (pairs : List ((P×Bool)×(P×Bool))) ∅ := + mapped_fresh Finset.univ.toList (Finset.nodup_toList _) _ (by intro p hp b; exact Set.notMem_empty _) + +theorem cover : pairSupport (pairs : List ((P×Bool)×(P×Bool)))=Set.univ := by + apply Set.eq_univ_of_forall + rintro ⟨p,b⟩ + refine ⟨pair p,pair_mem p,?_⟩ + cases b + · exact Or.inl rfl + · exact Or.inr rfl + +@[simp] theorem length : (pairs : List ((P×Bool)×(P×Bool))).length=Fintype.card P := by + simp [pairs] + +end ContingencyTables.PairedLabels + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedProfileSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedProfileSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..9987dee20bd3ee842a671e7be2a1f2bbe2f8ac65 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PairedProfileSemantics.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PairedProfileProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedInitial +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWeightOracle + +namespace OAI + +/-! # The computed paired counts are the manuscript's literal profile -/ + +namespace ContingencyTables.PairedProfileSemantics + +open PairedProfileProgram CanonicalInitialEncoding InitialTransversals +open CompanionArithmeticProposal CompanionFactorialApplication +open scoped BigOperators Classical + +noncomputable section + +variable {q : ℕ} (b : Fin q → ℕ) + +def cellRows (S : Set (Copy b × Bool)) : List (List ℕ) := + List.ofFn (fun i => interleave (List.ofFn (fun k : Fin (b i) => + (if (⟨i,k⟩,false) ∈ S then 1 else 0, + if (⟨i,k⟩,true) ∈ S then 1 else 0)))) + +lemma cellRows_lengths (S : Set (Copy b × Bool)) : + (cellRows b S).map List.length=(List.ofFn b).map width := by + simp only [cellRows,List.map_ofFn,Function.comp_def,interleave_length,List.length_ofFn,width] + +lemma cellRows_flatten (S : Set (Copy b × Bool)) : + (cellRows b S).flatten=encodeSet (coordinateEquiv b) S := by + rw [encodeSet_eq_map] + simp only [cellRows,interleave_flatMap,pairOrder,copyOrder,List.sigma,List.product, + List.ofFn_eq_map,List.flatten_eq_flatMap,List.flatMap_map,List.map_flatMap, + List.flatMap_assoc,List.map_map] + apply List.flatMap_congr + intro i _ + simp only [id_eq,Function.comp_def] + apply List.flatMap_congr + intro k _ + rfl + +lemma rows_encode (S : Set (Copy b × Bool)) : + rows (List.ofFn b,encodeSet (coordinateEquiv b) S)=cellRows b S := by + rw [rows,←cellRows_lengths b S,←cellRows_flatten b S] + exact NaturalBlockProgram.blocks_flatten _ + +lemma counts_cellRow (S : Set (Copy b × Bool)) (i : Fin q) : + counts (interleave (List.ofFn (fun k : Fin (b i) => + (if (⟨i,k⟩,false) ∈ S then 1 else 0, + if (⟨i,k⟩,true) ∈ S then 1 else 0))))= + ((∑ k : Fin (b i), if (⟨i,k⟩,false) ∈ S then 1 else 0), + (∑ k : Fin (b i), if (⟨i,k⟩,true) ∈ S then 1 else 0)) := by + simp only [counts,sideCount,sideEntries_interleave,List.map_ofFn,Function.comp_def,ite_false,ite_true, + Bool.false_eq_true,List.sum_ofFn] + congr 1 <;> apply Finset.sum_congr rfl <;> intro k _ <;> split_ifs <;> simp_all + +theorem profileRows_encode (S : Set (Copy b × Bool)) : + profileRows (List.ofFn b,encodeSet (coordinateEquiv b) S)=List.ofFn (fun i => + ((∑ k : Fin (b i), if (⟨i,k⟩,false) ∈ S then 1 else 0), + (∑ k : Fin (b i), if (⟨i,k⟩,true) ∈ S then 1 else 0))) := by + rw [profileRows,rows_encode] + simp only [cellRows,List.map_ofFn] + apply congrArg List.ofFn + funext i + exact counts_cellRow b S i + +lemma copy_viewCount (S : Set (Copy b × Bool)) (i : Fin q) (side : Bool) : + TwoLiftStates.viewCount (fun p : Copy b => p.1) S i side= + ∑ k : Fin (b i), if (⟨i,k⟩,side) ∈ S then 1 else 0 := by + unfold TwoLiftStates.viewCount + rw [Fintype.sum_sigma] + calc + _=∑ x : Fin q, if x=i then + (∑ k : Fin (b x), if (⟨x,k⟩,side) ∈ S then 1 else 0) else 0 := by + apply Finset.sum_congr rfl + intro x _ + by_cases hx : x=i + · subst x + simp + · simp [hx] + _=_ := by simp + +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +lemma physical_profile_reindex (S : Set (Labels A × Bool)) (s : SmallCell A) (side : Bool) : + CompanionWeightOracle.profile A S (s,side)= + TwoLiftStates.viewCount (fun p : Copy (CompanionComputedInitial.capacities A) => p.1) + ((CompanionComputedInitial.pairOrder A).symm ⁻¹' S) + (CompanionComputedInitial.cellOrder A s) side := by + rw [CompanionWeightOracle.profile,TwoLiftStates.groupCount_eq_viewCount] + unfold TwoLiftStates.viewCount + exact Fintype.sum_equiv (CompanionComputedInitial.copyOrder A) _ _ (fun p => by + have he : (CompanionComputedInitial.copyOrder A p).1= + CompanionComputedInitial.cellOrder A p.1 := rfl + simp only [Set.mem_preimage,CompanionComputedInitial.pairOrder,Equiv.prodCongr_symm, + Equiv.prodCongr_apply,Prod.map_apply, + Equiv.refl_symm,Equiv.refl_apply,Equiv.symm_apply_apply, + he,Equiv.apply_eq_iff_eq,CompanionFactorialApplication.labelCell] + split_ifs <;> simp_all) + +/-- The executed rows use the catalog's actual order, with one pair of +counts per retained physical cell. -/ +theorem profileRows_physical (S : Set (Labels A × Bool)) : + profileRows (List.ofFn (CompanionComputedInitial.capacities A), + encodeSet (CompanionComputedInitial.coordinateOrder A) S)= + List.ofFn (fun i => + (CompanionWeightOracle.profile A S ((CompanionComputedInitial.cellOrder A).symm i,false), + CompanionWeightOracle.profile A S ((CompanionComputedInitial.cellOrder A).symm i,true))) := by + rw [CompanionComputedInitial.encodeSet_reindex,profileRows_encode] + apply congrArg List.ofFn + funext i + apply Prod.ext + · change _=CompanionWeightOracle.profile A S ((CompanionComputedInitial.cellOrder A).symm i,false) + exact ((physical_profile_reindex A S _ false).trans + (by rw [Equiv.apply_symm_apply,copy_viewCount])).symm + · change _=CompanionWeightOracle.profile A S ((CompanionComputedInitial.cellOrder A).symm i,true) + exact ((physical_profile_reindex A S _ true).trans + (by rw [Equiv.apply_symm_apply,copy_viewCount])).symm + +end +end ContingencyTables.PairedProfileSemantics + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PathAugmentation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PathAugmentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c79d0b6b52f19f06be63468e2928a1107586af8a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PathAugmentation.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.ContingencyTables.Transport.PublishedEdmondsKarp +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! # Integral augmentation along a simple path + +The identities here prove conservation and capacity preservation for the +literal forward-minus-reverse update in the published-input interface. +-/ + +namespace ContingencyTables.PathAugmentation + +open PublishedEdmondsKarp +open scoped BigOperators + +variable {n k : ℕ} + +def arcCount (p : Fin (k+1) → Fin n) (u v : Fin n) : ℤ := + ∑ i : Fin k,if p i.castSucc=u ∧ p i.succ=v then 1 else 0 + +def update (f : Flow n) (p : Fin (k+1) → Fin n) (a : ℤ) : Flow n := + fun u v=>f u v+a*(arcCount p u v-arcCount p v u) + +lemma arcCount_nonneg (p : Fin (k+1) → Fin n) (u v : Fin n) : + 0≤arcCount p u v := by + apply Finset.sum_nonneg + intro i _ + split <;> omega + +lemma arcCount_eq_zero (p : Fin (k+1) → Fin n) (u v : Fin n) + (h : ¬∃ i : Fin k,p i.castSucc=u ∧ p i.succ=v) : arcCount p u v=0 := by + apply Finset.sum_eq_zero + intro i _ + exact ite_eq_right (fun hi=>h ⟨i,hi⟩) + +lemma arcCount_eq_one (p : Fin (k+1) → Fin n) (hp : Function.Injective p) + (i : Fin k) : arcCount p (p i.castSucc) (p i.succ)=1 := by + unfold arcCount + rw [Finset.sum_eq_single i] + · simp + · intro j _ hji + apply ite_eq_right + intro h + exact hji (Fin.castSucc_inj.mp (hp h.1)) + · simp + +lemma arcCount_le_one (p : Fin (k+1) → Fin n) (hp : Function.Injective p) + (u v : Fin n) : arcCount p u v≤1 := by + by_cases h : ∃ i : Fin k,p i.castSucc=u ∧ p i.succ=v + · obtain ⟨i,rfl,rfl⟩ := h + exact (arcCount_eq_one p hp i).le + · rw [arcCount_eq_zero p u v h] + omega + +lemma row_arcCount (p : Fin (k+1) → Fin n) (u : Fin n) : + (∑ v,arcCount p u v)=∑ i : Fin k,if p i.castSucc=u then (1:ℤ) else 0 := by + unfold arcCount + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + by_cases h : p i.castSucc=u + · simp [h] + · simp [h] + +lemma column_arcCount (p : Fin (k+1) → Fin n) (u : Fin n) : + (∑ v,arcCount p v u)=∑ i : Fin k,if p i.succ=u then (1:ℤ) else 0 := by + unfold arcCount + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + by_cases h : p i.succ=u + · simp [h] + · simp [h] + +lemma path_divergence (p : Fin (k+1) → Fin n) (u : Fin n) : + (∑ v : Fin n,(arcCount p u v-arcCount p v u))= + (if p 0=u then (1:ℤ) else 0)-(if p (Fin.last k)=u then 1 else 0) := by + have he : (∑ v : Fin n,(arcCount p u v-arcCount p v u))= + (∑ v : Fin n,arcCount p u v)-(∑ v : Fin n,arcCount p v u) := + Finset.sum_sub_distrib (fun v : Fin n=>arcCount p u v) (fun v : Fin n=>arcCount p v u) + have h1 := Fin.sum_univ_castSucc (fun i : Fin (k+1)=>if p i=u then (1:ℤ) else 0) + have h2 := Fin.sum_univ_succ (fun i : Fin (k+1)=>if p i=u then (1:ℤ) else 0) + rw [row_arcCount,column_arcCount] at he + omega + +lemma update_skew (f : Flow n) (hf : ∀ u v,f u v= -f v u) + (p : Fin (k+1) → Fin n) (a : ℤ) : + ∀ u v,update f p a u v= -update f p a v u := by + intro u v + unfold update + rw [hf u v] + ring + +lemma update_capacity (c : Capacity n) (f : Flow n) + (hf : ∀ u v,f u v≤c u v) (p : Fin (k+1) → Fin n) + (hp : Function.Injective p) (a : ℤ) (ha : 0≤a) + (hres : ∀ i : Fin k,a≤(c (p i.castSucc) (p i.succ):ℤ)-f (p i.castSucc) (p i.succ)) : + ∀ u v,update f p a u v≤c u v := by + intro u v + have hr := arcCount_nonneg p v u + by_cases he : ∃ i : Fin k,p i.castSucc=u ∧ p i.succ=v + · obtain ⟨i,rfl,rfl⟩ := he + rw [update,arcCount_eq_one p hp i] + have h := hres i + have hn := mul_nonneg ha hr + nlinarith + · rw [update,arcCount_eq_zero p u v he] + have h := hf u v + have hn := mul_nonneg ha hr + nlinarith + +lemma update_sum (f : Flow n) (p : Fin (k+1) → Fin n) (a : ℤ) (u : Fin n) : + (∑ v,update f p a u v)=(∑ v,f u v)+ + a*((if p 0=u then (1:ℤ) else 0)-(if p (Fin.last k)=u then 1 else 0)) := by + simp only [update,Finset.sum_add_distrib,←Finset.mul_sum] + exact congrArg (fun z : ℤ=>(∑ v,f u v)+a*z) (path_divergence p u) + +theorem update_feasible (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (p : Fin (k+1) → Fin n) + (hp : ResidualPath c f s t k p) (a : ℤ) (ha : 0≤a) + (hres : ∀ i : Fin k,a≤(c (p i.castSucc) (p i.succ):ℤ)-f (p i.castSucc) (p i.succ)) : + Feasible c s t (update f p a) := by + refine ⟨update_skew f hf.1 p a,update_capacity c f hf.2.1 p hp.2.2.1 a ha hres,?_⟩ + intro u hus hut + rw [update_sum,hp.1,hp.2.1,hf.2.2 u hus hut] + simp [Ne.symm hus,Ne.symm hut] + +theorem update_value (c : Capacity n) (s t : Fin n) (hst : s≠t) + (f : Flow n) (p : Fin (k+1) → Fin n) + (hp : ResidualPath c f s t k p) (a : ℤ) : + value s (update f p a)=value s f+a := by + unfold value + rw [update_sum,hp.1,hp.2.1] + simp [Ne.symm hst] + +end ContingencyTables.PathAugmentation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceInterpolation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceInterpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..58d72e1761953a5bc12fd3abfcd5927c98208b23 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceInterpolation.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerChildLogConcavity + +namespace OAI + +/-! # Finite log-concave interpolation for the terminal tree marginal + +The scalar statement used in the contamination estimate follows from +the actual adjacent two-removal inequality. No continuous extension of +the integer marginal is assumed. +-/ + +namespace ContingencyTables + +open scoped BigOperators + +private lemma decreasing_increments_average (g : ℕ → ℝ) (N : ℕ) + (hc : ∀ k, k+2 ≤ N → g k+g (k+2) ≤ 2*g (k+1)) + (n : ℕ) (hn : n+1 ≤ N) : + (n:ℝ)*(g (n+1)-g n) ≤ g n-g 0 := by + induction n with + | zero => simp + | succ n ih => + have ha := ih (by omega) + have hd : g (n+2)-g (n+1) ≤ g (n+1)-g n := by + linarith [hc n (by omega)] + have hm := mul_le_mul_of_nonneg_left hd + (show (0:ℝ) ≤ (n:ℝ)+1 by positivity) + push_cast at hm ⊢ + nlinarith + +/-- A finite sequence with decreasing adjacent increments lies above +each secant joining its first point to a later point. -/ +theorem discrete_secant (g : ℕ → ℝ) (N : ℕ) + (hc : ∀ k, k+2 ≤ N → g k+g (k+2) ≤ 2*g (k+1)) + (n : ℕ) (hn : n ≤ N) (k : ℕ) (hk : k ≤ n) : + (k:ℝ)*(g n-g 0) ≤ (n:ℝ)*(g k-g 0) := by + induction n with + | zero => + have hk0 : k=0 := by omega + simp [hk0] + | succ n ih => + by_cases hkn : k ≤ n + · by_cases hn0 : n=0 + · have hk0 : k=0 := by omega + simp [hk0] + · have hi := ih (by omega) hkn + have ha := decreasing_increments_average g N hc n (by omega) + have hi' := mul_le_mul_of_nonneg_left hi + (show (0:ℝ) ≤ (n:ℝ)+1 by positivity) + have ha' := mul_le_mul_of_nonneg_left ha (Nat.cast_nonneg k : (0:ℝ) ≤ k) + have hnR : (0:ℝ) < n := by exact_mod_cast Nat.pos_of_ne_zero hn0 + push_cast at hi' ⊢ + nlinarith + · have hke : k=n+1 := by omega + simp only [hke] + exact le_rfl + +/-- Adjacent log-concavity gives the exact finite logarithmic secant +inequality used for each positive tree-coordinate marginal. -/ +theorem positive_sequence_log_secant (a : ℕ → ℝ) (N : ℕ) + (hp : ∀ k, k ≤ N → 0 < a k) + (hc : ∀ k, k+2 ≤ N → a k*a (k+2) ≤ (a (k+1))^2) + (k : ℕ) (hk : k ≤ N) : + (k:ℝ)*(Real.log (a N)-Real.log (a 0)) ≤ + (N:ℝ)*(Real.log (a k)-Real.log (a 0)) := by + apply discrete_secant (fun j => Real.log (a j)) N _ N le_rfl k hk + intro j hj + have h0 := hp j (by omega) + have h1 := hp (j+1) (by omega) + have h2 := hp (j+2) hj + have hh := Real.log_le_log (mul_pos h0 h2) (hc j hj) + rw [Real.log_mul h0.ne' h2.ne',Real.log_pow] at hh + simpa only [Nat.cast_ofNat] using hh + +/-- A positive log-concave sequence whose far endpoint has mass at +least one and whose first mass is at most 2^K loses at most a factor +two over the first N/K integer positions. -/ +theorem positive_sequence_half_window (a : ℕ → ℝ) (N K : ℕ) + (hK : 1 ≤ K) (hN : 0 < N) + (hp : ∀ k, k ≤ N → 0 < a k) + (hc : ∀ k, k+2 ≤ N → a k*a (k+2) ≤ (a (k+1))^2) + (hend : 1 ≤ a N) (hfirst : a 0 ≤ (2:ℝ)^K) + (r : ℕ) (hr : r*K ≤ N) : a 0/2 ≤ a r := by + have hrN : r ≤ N := by nlinarith + have h0 := hp 0 (Nat.zero_le N) + have hr0 := hp r hrN + have hlog := positive_sequence_log_secant a N hp hc r hrN + have hlogend : 0 ≤ Real.log (a N) := Real.log_nonneg hend + have hlogfirst : Real.log (a 0) ≤ (K:ℝ)*Real.log 2 := by + have hh := Real.log_le_log h0 hfirst + simpa only [Real.log_pow] using hh + have htwo : 0 ≤ Real.log (2:ℝ) := Real.log_nonneg (by norm_num) + have hrK : (r:ℝ)*K ≤ N := by exact_mod_cast hr + have hrR : (0:ℝ) ≤ r := Nat.cast_nonneg r + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hm := mul_le_mul_of_nonneg_left hlogfirst hrR + have hsum := mul_le_mul_of_nonneg_right hrK htwo + have hloghalf : Real.log (a 0)-Real.log 2 ≤ Real.log (a r) := by + nlinarith [mul_nonneg hrR hlogend] + rw [← Real.log_div h0.ne' (by norm_num : (2:ℝ) ≠ 0)] at hloghalf + exact (Real.log_le_log_iff (div_pos h0 (by norm_num)) hr0).mp hloghalf + +/-- A half-height interpolation window contains enough distinct integer +positions to give the source's normalized exterior point-mass bound. -/ +theorem half_window_mass_bound (a : ℕ → ℝ) (U k N K b : ℕ) + (hK : 0 < K) (hb : 0 < b) (hbN : b ≤ N) (hkN : k+N ≤ U) + (ha : ∀ j,j ≤ U → 0 ≤ a j) + (hC : 0 < ∑ j ∈ Finset.range (U+1),a j) + (hwindow : ∀ r,r*K ≤ N → a k/2 ≤ a (k+r)) : + a k/(∑ j ∈ Finset.range (U+1),a j) ≤ (2*K:ℝ)/b := by + let q := N/K+1 + have hkU : k ≤ U := by omega + have hak : 0 ≤ a k := ha k hkU + have hsubset : (Finset.range q).image (fun r => k+r) ⊆ Finset.range (U+1) := by + intro j hj + obtain ⟨r,hr,rfl⟩ := Finset.mem_image.mp hj + have hrq : r ≤ N/K := by have := Finset.mem_range.mp hr; dsimp only [q] at this; omega + have hrN : r ≤ N := hrq.trans (Nat.div_le_self _ _) + exact Finset.mem_range.mpr (by omega) + have hsum : (∑ r ∈ Finset.range q,a (k+r)) ≤ ∑ j ∈ Finset.range (U+1),a j := by + rw [← Finset.sum_image (fun r _ s _ hrs => Nat.add_left_cancel hrs)] + exact Finset.sum_le_sum_of_subset_of_nonneg hsubset + (fun j hj _ => ha j (by have := Finset.mem_range.mp hj; omega)) + have hheight : (q:ℝ)*(a k/2) ≤ ∑ r ∈ Finset.range q,a (k+r) := by + calc + _ = ∑ _r ∈ Finset.range q,a k/2 := by simp + _ ≤ _ := by + apply Finset.sum_le_sum + intro r hr + apply hwindow + have hrq : r ≤ N/K := by have := Finset.mem_range.mp hr; dsimp only [q] at this; omega + exact (Nat.mul_le_mul_right K hrq).trans (Nat.div_mul_le_self _ _) + have hcountNat : b ≤ K*q := hbN.trans (Nat.lt_mul_div_succ N hK).le + have hcount : (b:ℝ) ≤ (K:ℝ)*(q:ℝ) := by exact_mod_cast hcountNat + have hmass := hheight.trans hsum + have hm1 := mul_le_mul_of_nonneg_right hcount (div_nonneg hak (by norm_num : (0:ℝ) ≤ 2)) + have hm2 := mul_le_mul_of_nonneg_left hmass (Nat.cast_nonneg K : (0:ℝ) ≤ K) + have hbR : (0:ℝ) < b := by exact_mod_cast hb + rw [div_le_div_iff₀ hC hbR] + nlinarith + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceMinimum.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceMinimum.lean new file mode 100644 index 0000000000000000000000000000000000000000..af931ccb783e9bffdb4463e2acd3d3f4043dec6b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PositiveSequenceMinimum.lean @@ -0,0 +1,70 @@ +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Linarith +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! # Endpoint minimum for a positive finite log-concave sequence + +This is the finite inequality needed by the conditional-variance paths. +After one strict decrease, the local product inequality forces every +subsequent step to decrease, so there can be no valley between endpoints. +-/ + +namespace ContingencyTables + +lemma positive_sequence_drop (a : ℕ → ℝ) (N k : ℕ) + (hpos : ∀ i, i ≤ N → 0 < a i) + (hlog : ∀ i, i+2 ≤ N → a i*a (i+2) ≤ (a (i+1))^2) + (hk : k+2 ≤ N) (hdrop : a (k+1) intro _; exact le_rfl + | succ n hin ih => + intro hnj + exact (ih (by omega)).trans (hstep n hin (by omega)) + exact hleft (hm j hij le_rfl) + obtain ⟨r,hir,hrj,hdrop⟩ := hex + have hdecrease : ∀ n, r ≤ n → n+1 ≤ N → a (n+1) intro _; exact hdrop + | succ n hrn ih => + intro hnN + exact positive_sequence_drop a N n hpos hlog (by omega) (ih (by omega)) + have hm : ∀ n, j ≤ n → n ≤ k → a n ≤ a j := by + intro n hjn + induction n,hjn using Nat.le_induction with + | base => intro _; exact le_rfl + | succ n hjn ih => + intro hnk + exact (hdecrease n (by omega) (by omega)).le.trans (ih (by omega)) + exact (min_le_right _ _).trans (hm k hjk le_rfl) + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PowerOfTwoApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PowerOfTwoApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ddad3ddd326fe901fdc5355e74362115ef2011eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PowerOfTwoApproximation.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalRootBisection +import Mathlib.Data.Rat.Floor + +namespace OAI + +/-! # A bounded rational approximation to the evaluator's power of two -/ + +namespace ContingencyTables.PowerOfTwoApproximation + +open RationalRootBisection + +noncomputable section + +def numerator (beta : ℚ) (s : ℕ) : ℤ := ⌊(s:ℚ)*beta⌋ + +def rounded (beta : ℚ) (s : ℕ) : ℝ := (numerator beta s:ℝ)/s + +def approximation (beta : ℚ) (s n : ℕ) : ℚ := midpoint ((2:ℚ)^numerator beta s) s n + +lemma rounded_bounds (beta : ℚ) (s : ℕ) (hs : 0 < s) : + rounded beta s ≤ (beta:ℝ) ∧ (beta:ℝ)-rounded beta s ≤ 1/(s:ℝ) := by + have hsR : (0:ℝ) < s := by exact_mod_cast hs + have hlow : (numerator beta s:ℚ) ≤ (s:ℚ)*beta := Int.floor_le _ + have hhigh : (s:ℚ)*beta < (numerator beta s:ℚ)+1 := Int.lt_floor_add_one _ + have hl : (numerator beta s:ℝ) ≤ (s:ℝ)*(beta:ℝ) := by exact_mod_cast hlow + have hu : (s:ℝ)*(beta:ℝ) < (numerator beta s:ℝ)+1 := by exact_mod_cast hhigh + constructor + · exact (div_le_iff₀ hsR).mpr (by simpa only [mul_comm] using hl) + · unfold rounded + apply (le_div_iff₀ hsR).mpr + have he : ((beta:ℝ)-(numerator beta s:ℝ)/(s:ℝ))*(s:ℝ)= + (s:ℝ)*(beta:ℝ)-(numerator beta s:ℝ) := by field_simp + rw [he] + linarith + +lemma rounded_power_root (beta : ℚ) (s : ℕ) (hs : 0 < s) : + ((2:ℝ)^rounded beta s)^s=(((2:ℚ)^numerator beta s:ℚ):ℝ) := by + have hsR : (s:ℝ)≠0 := by exact_mod_cast hs.ne' + rw [←Real.rpow_mul_natCast (by norm_num : (0:ℝ) ≤ 2)] + unfold rounded + rw [div_mul_cancel₀ _ hsR,Real.rpow_intCast] + exact (Rat.cast_zpow _ _).symm + +/-- Rounding downward loses at most 1/s in relative value. The proof uses +only the tangent bound for exp and log 2 ≤ 1. -/ +lemma rounded_power_error (beta : ℚ) (s : ℕ) (hs : 0 < s) : + 0 ≤ (2:ℝ)^(beta:ℝ)-(2:ℝ)^rounded beta s ∧ + (2:ℝ)^(beta:ℝ)-(2:ℝ)^rounded beta s ≤ (2:ℝ)^(beta:ℝ)/(s:ℝ) := by + have hb := rounded_bounds beta s hs + have hT : 0 < (2:ℝ)^(beta:ℝ) := Real.rpow_pos_of_pos (by norm_num) _ + have hlog : Real.log 2 ≤ 1 := by + linarith [Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ)<2)] + have hd : rounded beta s-(beta:ℝ) ≤ 0 := by linarith [hb.1] + have hmul := mul_le_mul_of_nonpos_right hlog hd + have he := Real.add_one_le_exp (Real.log 2*(rounded beta s-(beta:ℝ))) + have hlower : 1-1/(s:ℝ) ≤ (2:ℝ)^rounded beta s/(2:ℝ)^(beta:ℝ) := by + rw [←Real.rpow_sub (by norm_num : (0:ℝ)<2),Real.rpow_def_of_pos (by norm_num : (0:ℝ)<2)] + linarith [hb.2] + have hprod := (le_div_iff₀ hT).mp hlower + constructor + · exact sub_nonneg.mpr (Real.rpow_le_rpow_of_exponent_le (by norm_num) hb.1) + · calc + _ ≤ (2:ℝ)^(beta:ℝ)-(1-1/(s:ℝ))*(2:ℝ)^(beta:ℝ) := by linarith + _ = _ := by ring + +/-- The only non-rational quantity in the proof is the target. The +returned value is the midpoint of a fixed number of rational comparisons. -/ +theorem approximation_error (beta : ℚ) (hlo : -2 ≤ beta) (hhi : beta ≤ 2) + (s n : ℕ) (hs : 0 < s) (sigma : ℝ) + (hbudget : 1/(s:ℝ)+32/(2:ℝ)^n ≤ sigma) : + |(approximation beta s n:ℝ)-(2:ℝ)^(beta:ℝ)| ≤ sigma*(2:ℝ)^(beta:ℝ) := by + have hb := rounded_bounds beta s hs + have hp := rounded_power_error beta s hs + have ht0 : 0 ≤ (2:ℝ)^rounded beta s := (Real.rpow_pos_of_pos (by norm_num) _).le + have ht8 : (2:ℝ)^rounded beta s ≤ 8 := by + have hr : rounded beta s ≤ 2 := hb.1.trans (by exact_mod_cast hhi) + have hh := Real.rpow_le_rpow_of_exponent_le (by norm_num : (1:ℝ) ≤ 2) hr + norm_num at hh + linarith + have hT : (1/4:ℝ) ≤ (2:ℝ)^(beta:ℝ) := by + have hh := Real.rpow_le_rpow_of_exponent_le (by norm_num : (1:ℝ) ≤ 2) + (show (-2:ℝ) ≤ (beta:ℝ) by exact_mod_cast hlo) + norm_num at hh + exact hh + have he := midpoint_error ((2:ℚ)^numerator beta s) s hs ((2:ℝ)^rounded beta s) + ht0 ht8 (rounded_power_root beta s hs) n + have hscale : 8/(2:ℝ)^n ≤ (32/(2:ℝ)^n)*(2:ℝ)^(beta:ℝ) := by + have hh := mul_le_mul_of_nonneg_left hT (show (0:ℝ) ≤ 32/(2:ℝ)^n by positivity) + convert hh using 1; ring + have htpos : 0 ≤ (2:ℝ)^(beta:ℝ) := (Real.rpow_pos_of_pos (by norm_num) _).le + calc + _ ≤ |(approximation beta s n:ℝ)-(2:ℝ)^rounded beta s|+ + |(2:ℝ)^rounded beta s-(2:ℝ)^(beta:ℝ)| := by + simpa only [sub_add_sub_cancel] using abs_add_le + ((approximation beta s n:ℝ)-(2:ℝ)^rounded beta s) + ((2:ℝ)^rounded beta s-(2:ℝ)^(beta:ℝ)) + _ ≤ 8/(2:ℝ)^n+(2:ℝ)^(beta:ℝ)/(s:ℝ) := by + exact add_le_add he (by rw [abs_of_nonpos (by linarith [hp.1])]; linarith [hp.2]) + _ ≤ (32/(2:ℝ)^n)*(2:ℝ)^(beta:ℝ)+(2:ℝ)^(beta:ℝ)/(s:ℝ) := add_le_add hscale le_rfl + _ = (1/(s:ℝ)+32/(2:ℝ)^n)*(2:ℝ)^(beta:ℝ) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_right hbudget htpos + +def rootDegree (sigma : ℚ) : ℕ := ⌈128/sigma⌉₊ + +def depth (sigma : ℚ) : ℕ := Nat.clog 2 (rootDegree sigma) + +def approximate (beta sigma : ℚ) : ℚ := approximation beta (rootDegree sigma) (depth sigma) + +lemma degree_positive (sigma : ℚ) (hsigma : 0 < sigma) : 0 < rootDegree sigma := by + have h := Nat.le_ceil (128/sigma:ℚ) + have hp : (0:ℚ) < 128/sigma := by positivity + have hc : (0:ℚ) < rootDegree sigma := lt_of_lt_of_le hp h + exact_mod_cast hc + +lemma degree_le (sigma : ℚ) (hsigma : 0 < sigma) : + (rootDegree sigma:ℚ) ≤ 128/sigma+1 := by + exact (Nat.ceil_lt_add_one (by positivity : (0:ℚ) ≤ 128/sigma)).le + +lemma error_budget (sigma : ℚ) (hsigma : 0 < sigma) : + 1/(rootDegree sigma:ℝ)+32/(2:ℝ)^depth sigma ≤ (sigma:ℝ) := by + have hs := degree_positive sigma hsigma + have hsR : (0:ℝ) < rootDegree sigma := by exact_mod_cast hs + have hsigmaR : (0:ℝ) < sigma := by exact_mod_cast hsigma + have hceil : (128:ℝ)/(sigma:ℝ) ≤ rootDegree sigma := by + have hh := Nat.le_ceil (128/sigma:ℚ) + exact_mod_cast hh + have hpow : (rootDegree sigma:ℝ) ≤ (2:ℝ)^depth sigma := by + exact_mod_cast Nat.le_pow_clog (by decide : 1 < 2) (rootDegree sigma) + have hrec : 1/(rootDegree sigma:ℝ) ≤ (sigma:ℝ)/128 := by + rw [div_le_div_iff₀ hsR (by norm_num : (0:ℝ)<128)] + have hh := (div_le_iff₀ hsigmaR).mp hceil + nlinarith + have hrec' : 32/(2:ℝ)^depth sigma ≤ (sigma:ℝ)/4 := by + apply (div_le_div_of_nonneg_left (by norm_num : (0:ℝ) ≤ 32) hsR hpow).trans + rw [div_le_div_iff₀ hsR (by norm_num : (0:ℝ)<4)] + have hh := (div_le_iff₀ hsigmaR).mp hceil + nlinarith + linarith + +theorem approximate_error (beta sigma : ℚ) (hlo : -2 ≤ beta) (hhi : beta ≤ 2) + (hsigma : 0 < sigma) : + |(approximate beta sigma:ℝ)-(2:ℝ)^(beta:ℝ)| ≤ (sigma:ℝ)*(2:ℝ)^(beta:ℝ) := + approximation_error beta hlo hhi _ _ (degree_positive sigma hsigma) _ (error_budget sigma hsigma) + +theorem approximate_positive (beta sigma : ℚ) (hlo : -2 ≤ beta) (hhi : beta ≤ 2) + (hsigma : 0 < sigma) (hsigma1 : sigma < 1) : 0 < approximate beta sigma := by + have he := approximate_error beta sigma hlo hhi hsigma + have hT : 0 < (2:ℝ)^(beta:ℝ) := Real.rpow_pos_of_pos (by norm_num) _ + have hl := (abs_le.mp he).1 + have hsigmaR : (sigma:ℝ) < 1 := by exact_mod_cast hsigma1 + have hpos : (0:ℝ) < approximate beta sigma := by nlinarith + exact_mod_cast hpos + +end + +end ContingencyTables.PowerOfTwoApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ProductIntegerSignature.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ProductIntegerSignature.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c116114dce4860fd9e7c6f0e1c600dd8805779c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ProductIntegerSignature.lean @@ -0,0 +1,168 @@ +import OAI.Combinatorics.ContingencyTables.Transport.LineUnarySignature +import OAI.Combinatorics.ContingencyTables.Transport.FactorialSignatures + +namespace OAI + +/-! +# Raw integer signatures of the actual line and unary product + +The line groups are disjoint. Integer counts at zero are masked; a repeated +removal from a count below two uses a zero second-update factor. This +identifies the actual integer matrix, including its box boundaries, with a +congruence of the proved line/unary update matrix. +-/ + +namespace ContingencyTables.ProductIntegerSignature + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures + +variable {I G : Type*} [Fintype I] [Fintype G] + +noncomputable def lineTotal (line : I → G) (z : I → ℕ) (g : G) : ℕ := + ∑ i, if line i = g then z i else 0 + +noncomputable def productWeight (line : I → G) (a : G → ℕ → ℝ) (b : I → ℕ → ℝ) + (z : I → ℕ) : ℝ := (∏ g, a g (lineTotal line z g)) * ∏ i, b i (z i) + +omit [Fintype G] in +lemma lineTotal_removeOne (line : I → G) (z : I → ℕ) (i : I) (hi : 0 < z i) (g : G) : + lineTotal line (removeOne z i) g + (if line i = g then 1 else 0) = lineTotal line z g := by + have h1 := Finset.sum_erase_add (s := Finset.univ) (a := i) + (fun k => if line k = g then z k else 0) (Finset.mem_univ i) + have h2 := Finset.sum_erase_add (s := Finset.univ) (a := i) + (fun k => if line k = g then removeOne z i k else 0) (Finset.mem_univ i) + have he : (∑ k ∈ Finset.univ.erase i, if line k = g then removeOne z i k else 0) = + ∑ k ∈ Finset.univ.erase i, if line k = g then z k else 0 := by + apply Finset.sum_congr rfl + intro k hk + simp [removeOne,(Finset.mem_erase.mp hk).1] + rw [he] at h2 + have hepi : removeOne z i i = z i-1 := by simp [removeOne] + rw [hepi] at h2 + unfold lineTotal + by_cases hg : line i = g <;> simp only [hg,ite_true,ite_false] at h1 h2 ⊢ <;> omega + +omit [Fintype G] in +lemma lineTotal_removeTwo (line : I → G) (z : I → ℕ) (i j : I) + (hvalid : ValidPair z i j) (g : G) : + lineTotal line (removeTwo z i j) g + (if line i = g then 1 else 0) + + (if line j = g then 1 else 0) = lineTotal line z g := by + have hj : 0 < removeOne z i j := hvalid.2 + have h1 := lineTotal_removeOne line z i hvalid.1 g + have h2 := lineTotal_removeOne line (removeOne z i) j hj g + change lineTotal line (removeOne (removeOne z i) j) g + _ + _ = _ + omega + +/-- Literal product values after a valid integer removal coincide with +all line and unary update products. -/ +theorem productWeight_removeTwo (line : I → G) (a : G → ℕ → ℝ) (b : I → ℕ → ℝ) + (z : I → ℕ) (i j : I) (hvalid : ValidPair z i j) : + productWeight line a b (removeTwo z i j) = + lineUnaryRemoval line + (fun g => a g (lineTotal line z g)) + (fun g => a g (lineTotal line z g-1)) + (fun g => if 2 ≤ lineTotal line z g then a g (lineTotal line z g-2) else 0) + (fun k => b k (z k)) (fun k => b k (z k-1)) + (fun k => if 2 ≤ z k then b k (z k-2) else 0) i j := by + unfold productWeight lineUnaryRemoval productTwoUpdates + congr 1 + · apply Finset.prod_congr rfl + intro g _ + have ht := lineTotal_removeTwo line z i j hvalid g + by_cases hi : g = line i + · by_cases hj : g = line j + · have hn : 2 ≤ lineTotal line z g := by simp only [hi.symm,hj.symm,ite_true] at ht; omega + have he : lineTotal line (removeTwo z i j) g = lineTotal line z g-2 := by + simp only [hi.symm,hj.symm,ite_true] at ht; omega + simp only [ite_eq_left hi,ite_eq_left hj,ite_eq_left hn,he] + · have he : lineTotal line (removeTwo z i j) g = lineTotal line z g-1 := by + simp only [hi.symm,ite_true,Ne.symm hj,ite_false] at ht; omega + simp only [ite_eq_left hi,ite_eq_right hj,he] + · by_cases hj : g = line j + · have he : lineTotal line (removeTwo z i j) g = lineTotal line z g-1 := by + simp only [Ne.symm hi,ite_false,hj.symm,ite_true] at ht; omega + simp only [ite_eq_right hi,ite_eq_left hj,he] + · have he : lineTotal line (removeTwo z i j) g = lineTotal line z g := by + simp only [Ne.symm hi,Ne.symm hj,ite_false,add_zero] at ht; exact ht + simp only [ite_eq_right hi,ite_eq_right hj,he] + · apply Finset.prod_congr rfl + intro k _ + by_cases hi : k = i + · by_cases hj : k = j + · have hn : 2 ≤ z k := by subst i; subst j; simp [ValidPair] at hvalid; omega + have he : removeTwo z i j k = z k-2 := by simp [removeTwo,removeOne,hi.symm.trans hj,hi,Nat.sub_sub] + simp only [ite_eq_left hi,ite_eq_left hj,ite_eq_left hn,he] + · have he : removeTwo z i j k = z k-1 := by + simp only [removeTwo,removeOne,ite_eq_left hi,ite_eq_right hj,Nat.sub_zero] + simp only [ite_eq_left hi,ite_eq_right hj,he] + · by_cases hj : k = j + · have he : removeTwo z i j k = z k-1 := by + simp only [removeTwo,removeOne,ite_eq_right hi,ite_eq_left hj,Nat.sub_zero] + simp only [ite_eq_right hi,ite_eq_left hj,he] + · simp only [removeTwo,removeOne,ite_eq_right hi,ite_eq_right hj,Nat.sub_zero] + +noncomputable def activeMask (z : I → ℕ) : I → ℝ := fun i => if 0 < z i then 1 else 0 + +/-- The raw matrix is exactly the line/unary matrix with inactive integer +coordinates set to zero. Invalid repeated removals are also zero. -/ +theorem integerRemoval_product_matrix (line : I → G) (a : G → ℕ → ℝ) (b : I → ℕ → ℝ) + (z : I → ℕ) : + integerRemovalMatrix (productWeight line a b) z = + scaledMatrix (lineUnaryRemoval line + (fun g => a g (lineTotal line z g)) + (fun g => a g (lineTotal line z g-1)) + (fun g => if 2 ≤ lineTotal line z g then a g (lineTotal line z g-2) else 0) + (fun k => b k (z k)) (fun k => b k (z k-1)) + (fun k => if 2 ≤ z k then b k (z k-2) else 0)) (activeMask z) := by + ext i j + unfold integerRemovalMatrix scaledMatrix activeMask + by_cases hv : ValidPair z i j + · have hi : 0 < z i := hv.1 + have hj : 0 < z j := by dsimp [ValidPair] at hv; omega + simp only [hv,ite_true,hi,hj,one_mul,mul_one] + exact productWeight_removeTwo line a b z i j hv + · rw [ite_eq_right hv] + by_cases hi : 0 < z i + · by_cases hj : 0 < z j + · have hij : i = j := by by_contra h; exact hv ⟨hi,by simp [Ne.symm h,hj]⟩ + subst j + have hn : ¬2 ≤ z i := by simp [ValidPair] at hv; omega + simp only [hi,ite_true,one_mul,mul_one,lineUnaryRemoval] + have hz : productTwoUpdates (fun k => b k (z k)) (fun k => b k (z k-1)) + (fun k => if 2 ≤ z k then b k (z k-2) else 0) i i = 0 := by + apply Finset.prod_eq_zero (Finset.mem_univ i) + simp [hn] + rw [hz,mul_zero] + · simp [hj] + · simp [hi] + +/-- Log-concavity of the actual scalar sequences gives the integer +signature required by factorial lifting and balanced marginalization. -/ +theorem product_removal_onePositive (line : I → G) (a : G → ℕ → ℝ) (b : I → ℕ → ℝ) + (z : I → ℕ) + (ha : ∀ g n, n ≤ lineTotal line z g → 0 < a g n) + (hb : ∀ i n, n ≤ z i → 0 < b i n) + (halc : ∀ g, 2 ≤ lineTotal line z g → + a g (lineTotal line z g) * a g (lineTotal line z g-2) ≤ a g (lineTotal line z g-1)^2) + (hblc : ∀ i, 2 ≤ z i → b i (z i) * b i (z i-2) ≤ b i (z i-1)^2) : + OnePositiveDirection (integerRemovalMatrix (productWeight line a b) z).toBilin' := by + rw [integerRemoval_product_matrix] + have hs := lineUnaryRemoval_onePositive line + (fun g => a g (lineTotal line z g)) + (fun g => a g (lineTotal line z g-1)) + (fun g => if 2 ≤ lineTotal line z g then a g (lineTotal line z g-2) else 0) + (fun i => b i (z i)) (fun i => b i (z i-1)) + (fun i => if 2 ≤ z i then b i (z i-2) else 0) + (fun g => ha g _ le_rfl) (fun g => ha g _ (Nat.sub_le _ _)) + (fun g => by split_ifs; exact (ha g _ (Nat.sub_le _ _)).le; exact le_rfl) + (fun i => hb i _ le_rfl) (fun i => hb i _ (Nat.sub_le _ _)) + (fun g => by split_ifs with h; exact halc g h; simp [sq_nonneg]) + (fun i => by split_ifs with h; exact hblc i h; simp [sq_nonneg]) + intro x hx y hxy + rw [scaledMatrix_form] at hx hxy ⊢ + exact hs _ hx _ hxy + +end ContingencyTables.ProductIntegerSignature + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/PublishedEdmondsKarp.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/PublishedEdmondsKarp.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d2e95d65013382379f8acc691ca9676864f914c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/PublishedEdmondsKarp.lean @@ -0,0 +1,88 @@ +import Mathlib.Data.Finset.Basic +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fin.Basic +import Mathlib.Algebra.BigOperators.Fin + +namespace OAI + +/-! +# Shortest-augmenting-path bound + +The finite integral-network specialization of Edmonds and Karp, +*Theoretical Improvements in Algorithmic Efficiency for Network Flow +Problems*, J. ACM 19(2) (1972), 248–264, Theorem 1 (printed page 251). +The bound (n³−n)/4 implies the n³ bound for shortest residual augmentations. + +Primary text: +https://web.eecs.umich.edu/~pettie/matching/Edmonds-Karp-network-flow.pdf +-/ + +namespace ContingencyTables.PublishedEdmondsKarp + +open scoped BigOperators + +abbrev Flow (n : ℕ) := Fin n → Fin n → ℤ +abbrev Capacity (n : ℕ) := Fin n → Fin n → ℕ + +/-- Skew flows combine the two antiparallel directions. The upper +capacity bound and skew symmetry give both directed residual bounds. -/ +def Feasible {n : ℕ} (c : Capacity n) (s t : Fin n) (f : Flow n) : Prop := + (∀ u v, f u v= -f v u) ∧ + (∀ u v, f u v≤c u v) ∧ + (∀ u, u≠s → u≠t → (∑ v, f u v)=0) + +def value {n : ℕ} (s : Fin n) (f : Flow n) : ℤ := ∑ v, f s v + +def IsMaximum {n : ℕ} (c : Capacity n) (s t : Fin n) (f : Flow n) : Prop := + Feasible c s t f ∧ ∀ g, Feasible c s t g → value s g≤value s f + +/-- A directed residual path with k arcs and no repeated vertices. -/ +def ResidualPath {n : ℕ} (c : Capacity n) (f : Flow n) (s t : Fin n) + (k : ℕ) (p : Fin (k+1) → Fin n) : Prop := + p 0=s ∧ p (Fin.last k)=t ∧ Function.Injective p ∧ + ∀ i : Fin k, 0<(c (p i.castSucc) (p i.succ):ℤ)-f (p i.castSucc) (p i.succ) + +/-- An actual saturating augmentation along a shortest residual path. +The bottleneck is positive, bounded by every residual capacity, and +attained by an arc. The displayed update adds it forward and subtracts +it backward on precisely the traversed arcs. -/ +def ShortestAugmentation {n : ℕ} (c : Capacity n) (s t : Fin n) + (f g : Flow n) : Prop := + ∃ (k : ℕ) (p : Fin (k+1) → Fin n) (a : ℤ), + ResidualPath c f s t k p ∧ + (∀ (l : ℕ) (q : Fin (l+1) → Fin n), ResidualPath c f s t l q → k≤l) ∧ + 0 mul_nonneg (ha g) (sq_nonneg _)) + +end Forms + +/-- Exact scalar expansion behind the balanced-pair telescoping +inequality. The two mixed entries are expressed as discrete differences +of the cumulative coefficients. -/ +theorem pair_expansion (v um u up gm g gp : ℝ) : + v + 2 * g * ((u * g - um * gm) - (up * gp - u * g)) + + (um - 2 * u + up) * g ^ 2 - + (um * (g - gm) ^ 2 + up * (g - gp) ^ 2) = + v + 2 * u * g ^ 2 - um * gm ^ 2 - up * gp ^ 2 := by + ring + +/-- Once the local projection estimate is available, the exact +expansion gives equation pair-one in 200-01 and integer-telescoping +in 200-02. The hypothesis is a local quadratic estimate, not a claim +that the whole manuscript has been proved. -/ +theorem pair_telescoping_step (v um u up gm g gp : ℝ) + (hprojection : + v + 2 * g * ((u * g - um * gm) - (up * gp - u * g)) + + (um - 2 * u + up) * g ^ 2 ≤ + um * (g - gm) ^ 2 + up * (g - gp) ^ 2) : + 2 * u * g ^ 2 - um * gm ^ 2 - up * gp ^ 2 ≤ -v := by + have h := sub_nonpos.mpr hprojection + rw [pair_expansion] at h + linarith + +section PairProjection + +variable {V : Type*} [AddCommGroup V] [Module ℝ V] + +/-- The local inequality follows from the signature even when either or +both of the fresh diagonal entries vanish. This includes the capacity-two +boundary case in both manuscripts. -/ +theorem pair_step_of_signature (B : BilinForm ℝ V) + (hsymm : ∀ x y, B x y = B y x) (hsig : OnePositiveDirection B) + (h ea eb : V) (um u up gm g gp : ℝ) + (haa : B ea ea = um) (hbb : B eb eb = up) (hab : B ea eb = u) + (hha : B h ea = u * g - um * gm) + (hhb : B h eb = up * gp - u * g) + (hum : 0 ≤ um) (hup : 0 ≤ up) + (hpositive : 0 < um ∨ 0 < up ∨ (um = 0 ∧ up = 0 ∧ 0 < u)) : + 2 * u * g ^ 2 - um * gm ^ 2 - up * gp ^ 2 ≤ -B h h := by + let v := h + g • ea - g • eb + have hba : B eb ea = u := by rw [hsymm, hab] + have hv_a : B v ea = um * (g - gm) := by + dsimp [v] + simp only [LinearMap.BilinForm.sub_left, LinearMap.BilinForm.add_left, + LinearMap.BilinForm.smul_left, haa, hba, hha] + ring + have hv_b : B v eb = up * (gp - g) := by + dsimp [v] + simp only [LinearMap.BilinForm.sub_left, LinearMap.BilinForm.add_left, + LinearMap.BilinForm.smul_left, hab, hbb, hhb] + ring + have hvv : B v v = B h h + + 2 * g * ((u * g - um * gm) - (up * gp - u * g)) + + (um - 2 * u + up) * g ^ 2 := by + have hah : B ea h = u * g - um * gm := by rw [hsymm, hha] + have hbh : B eb h = up * gp - u * g := by rw [hsymm, hhb] + dsimp [v] + simp only [LinearMap.BilinForm.sub_left, LinearMap.BilinForm.sub_right, + LinearMap.BilinForm.add_left, LinearMap.BilinForm.add_right, + LinearMap.BilinForm.smul_left, LinearMap.BilinForm.smul_right, + haa, hbb, hab, hba, hha, hhb, hah, hbh] + ring + have hbound : B v v ≤ um * (g - gm) ^ 2 + up * (g - gp) ^ 2 := by + rcases hpositive with ha | hb | ⟨ha, hb, hu⟩ + · have hh := positive_projection B hsymm hsig ea v (by rwa [haa]) + rw [hsymm ea v, hv_a, haa] at hh + have heq : (um * (g - gm)) ^ 2 / um = um * (g - gm) ^ 2 := by + field_simp + rw [heq] at hh + exact hh.trans (le_add_of_nonneg_right (mul_nonneg hup (sq_nonneg _))) + · have hh := positive_projection B hsymm hsig eb v (by rwa [hbb]) + rw [hsymm eb v, hv_b, hbb] at hh + have heq : (up * (gp - g)) ^ 2 / up = up * (g - gp) ^ 2 := by + field_simp + ring + rw [heq] at hh + exact hh.trans (le_add_of_nonneg_left (mul_nonneg hum (sq_nonneg _))) + · have hsum : B (ea + eb) (ea + eb) = 2 * u := by + simp only [LinearMap.BilinForm.add_left, LinearMap.BilinForm.add_right, + haa, hbb, hab, hba, ha, hb] + ring + have horth : B (ea + eb) v = 0 := by + rw [hsymm, LinearMap.BilinForm.add_right, hv_a, hv_b, ha, hb] + ring + have hh := hsig (ea + eb) (by rw [hsum]; linarith) v horth + simpa only [ha, hb, zero_mul, zero_add] using hh + rw [hvv] at hbound + exact pair_telescoping_step _ _ _ _ _ _ _ hbound + +end PairProjection + +/-- The scalar second differences telescope with their actual boundary +terms. No absent endpoint matrix is needed. -/ +theorem sum_second_differences (a : ℕ → ℝ) (n : ℕ) : + (∑ j ∈ range n, (2 * a (j + 1) - a j - a (j + 2))) = + a 1 - a 0 + a n - a (n + 1) := by + induction n with + | zero => simp + | succ n ih => + rw [sum_range_succ, ih] + ring + +/-- The endpoint convention in the unweighted balanced-pair summation +makes the scalar second differences have zero total. -/ +theorem sum_second_differences_zero (a : ℕ → ℝ) (n : ℕ) + (h0 : a 0 = 0) (h1 : a 1 = 0) (hn : a n = 0) (hn1 : a (n + 1) = 0) : + (∑ j ∈ range n, (2 * a (j + 1) - a j - a (j + 2))) = 0 := by + rw [sum_second_differences, h0, h1, hn, hn1] + ring + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainCast.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainCast.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f2a4dbd2c900fb7800a2ed8d67316d6bdb98e53 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainCast.lean @@ -0,0 +1,31 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks +import OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain + +namespace OAI + +/-! # Independent rational walks agree with their real finite kernels -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture CommonBasesFPRAS + +variable {X : Type*} [Fintype X] [DecidableEq X] + +theorem walkLaw_cast_kernel (K : X → RationalLaw X) (C : FiniteChain X) + (hK : ∀ x y,((K x).mass y:ℝ)=C.P x y) (n : ℕ) (x y : X) : + ((walkLaw K x n).mass y:ℝ)=(C.kernel.power n).P x y := by + induction n generalizing y with + | zero => + simp only [walkLaw,pointLaw,FiniteKernel.power,FiniteKernel.identity] + by_cases hxy : x=y + · subst y; simp + · simp [hxy,Ne.symm hxy] + | succ n ih => + change ((∑ z,(walkLaw K x n).mass z*(K z).mass y:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,ih,hK, + FiniteKernel.power,FiniteKernel.comp,FiniteChain.kernel] + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a17da246a09712d017a0163d9058a61b3276e08 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalChainMixing.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalChainCast +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentApproximation + +namespace OAI + +/-! # A real pointwise mixing bound for the corresponding rational walk -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture CommonBasesFPRAS + +variable {X : Type*} [Fintype X] [DecidableEq X] + +theorem rationalWalk_variation (K : X → RationalLaw X) (C : FiniteChain X) + (hK : ∀ x y,((K x).mass y:ℝ)=C.P x y) (π : RationalLaw X) + (hπ : ∀ y,(π.mass y:ℝ)=C.π y) (x : X) (n : ℕ) (δ : ℝ) (hδ : 0 ≤ δ) + (hpoint : ∀ y,|C.iterate n (C.pointDensity y) x-1| ≤ δ) : + (variation (walkLaw K x n) π:ℝ) ≤ δ := by + have hp (y : X) : |(C.kernel.power n).P x y-C.π y| ≤ C.π y*δ := by + have hh := hpoint y + rw [←C.kernel_power_density] at hh + calc + _ = C.π y*|(C.kernel.power n).P x y/C.π y-1| := by + calc + _ = |C.π y*((C.kernel.power n).P x y/C.π y-1)| := by + congr 1 + field_simp [(C.positive y).ne'] + _ = _ := by rw [abs_mul,abs_of_pos (C.positive y)] + _ ≤ _ := mul_le_mul_of_nonneg_left hh (C.positive y).le + have hs := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => hp y) + rw [←Finset.sum_mul,C.normalized,one_mul] at hs + unfold variation + simp only [Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat, + walkLaw_cast_kernel K C hK,hπ] + linarith + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalMapProducts.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalMapProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd4dd3f3b061cbc9d92b276e790e854932fa0387 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalMapProducts.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalProducts +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset + +namespace OAI + +/-! # Independent finite coordinate maps and uniform product laws -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +noncomputable section + +theorem mapLaw_id {A : Type*} [Fintype A] [DecidableEq A] (p : RationalLaw A) : mapLaw p id = p := by + apply RationalLaw.ext + funext y + simp [mapLaw] + +theorem mapLaw_comp {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] [DecidableEq B] [DecidableEq C] + (p : RationalLaw A) (f : A → B) (g : B → C) : + mapLaw (mapLaw p f) g = mapLaw p (fun x => g (f x)) := by + apply RationalLaw.ext + funext z + change (∑ y, if g y = z then ∑ x, if f x = y then p.mass x else 0 else 0) = _ + calc + _ = ∑ y, ∑ x, if f x = y then (if g y = z then p.mass x else 0) else 0 := by + apply Finset.sum_congr rfl + intro y _ + by_cases hy : g y = z <;> simp [hy] + _ = _ := by rw [Finset.sum_comm]; simp [mapLaw] + +theorem mapLaw_product {A B C D : Type*} [Fintype A] [Fintype B] [Fintype C] [Fintype D] + [DecidableEq C] [DecidableEq D] [DecidableEq (C × D)] + (p : RationalLaw A) (q : RationalLaw B) (f : A → C) (g : B → D) : + mapLaw (productLaw p q) (fun z => (f z.1, g z.2)) = productLaw (mapLaw p f) (mapLaw q g) := by + apply RationalLaw.ext + funext z + change (∑ x : A × B, if (f x.1, g x.2) = z then p.mass x.1 * q.mass x.2 else 0) = + (∑ x, if f x = z.1 then p.mass x else 0) * (∑ y, if g y = z.2 then q.mass y else 0) + rw [Fintype.sum_prod_type, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + by_cases hx : f x = z.1 <;> by_cases hy : g y = z.2 <;> simp [Prod.ext_iff, hx, hy] + +theorem mapLaw_equiv_output {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq B] [DecidableEq C] + (e : B ≃ C) (p : RationalLaw A) (f : A → B) : + mapLaw p (fun x => e (f x)) = equivLaw e (mapLaw p f) := by + apply RationalLaw.ext + funext y + change (∑ x, if e (f x) = y then p.mass x else 0) = + ∑ x, if f x = e.symm y then p.mass x else 0 + simp only [← Equiv.eq_symm_apply] + +variable {n : ℕ} {α β : Fin n → Type*} [∀ i, Fintype (α i)] [∀ i, Fintype (β i)] + +theorem pi_mapLaw [∀ i, DecidableEq (β i)] [DecidableEq (∀ i, β i)] (p : ∀ i, RationalLaw (α i)) (f : ∀ i, α i → β i) : + mapLaw (piLaw p) (fun x i => f i (x i)) = piLaw (fun i => mapLaw (p i) (f i)) := by + apply RationalLaw.ext + funext y + change (∑ x : ∀ i, α i, if (fun i => f i (x i)) = y then ∏ i, (p i).mass (x i) else 0) = + ∏ i, ∑ x : α i, if f i x = y i then (p i).mass x else 0 + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro x _ + rw [Fintype.prod_ite_zero] + congr 1 + exact propext funext_iff + +omit [∀ i, Fintype (β i)] in +theorem pi_uniformLaw [∀ i, Nonempty (α i)] : + piLaw (fun i => uniformLaw (α := α i)) = uniformLaw (α := ∀ i, α i) := by + apply RationalLaw.ext + funext x + change (∏ i, (1 : ℚ) / Fintype.card (α i)) = 1 / Fintype.card (∀ i, α i) + rw [Finset.prod_div_distrib, Finset.prod_const_one, ← Nat.cast_prod, Fintype.card_pi] + +end + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalProducts.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2e789240fabde1caa1e6616b7d4349b8da52fee --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalProducts.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Algebra.Order.BigOperators.GroupWithZero.Finset + +namespace OAI + +/-! # Finite product laws for the independent bounded offset draws -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +def piLaw {n : ℕ} {α : Fin n → Type*} [∀ i, Fintype (α i)] + (p : ∀ i, RationalLaw (α i)) : RationalLaw (∀ i, α i) where + mass := fun x => ∏ i, (p i).mass (x i) + nonnegative := fun x => Finset.prod_nonneg (fun i _ => (p i).nonnegative (x i)) + total := by + rw [← Fintype.prod_sum] + simp only [(p _).total, Finset.prod_const_one] + +theorem variation_pi_succ {n : ℕ} (α : Fin (n + 1) → Type*) [∀ i, Fintype (α i)] + (p q : ∀ i, RationalLaw (α i)) : + variation (piLaw p) (piLaw q) = + variation (productLaw (p 0) (piLaw (fun i : Fin n => p i.succ))) + (productLaw (q 0) (piLaw (fun i : Fin n => q i.succ))) := by + unfold variation + congr 1 + apply Fintype.sum_equiv (Fin.consEquiv α).symm + intro x + change |(∏ i, (p i).mass (x i)) - (∏ i, (q i).mass (x i))| = + |(p 0).mass (x 0) * (∏ i : Fin n, (p i.succ).mass (x i.succ)) - + (q 0).mass (x 0) * (∏ i : Fin n, (q i.succ).mass (x i.succ))| + rw [Fin.prod_univ_succ, Fin.prod_univ_succ] + +/-- Errors in independent coordinate draws add before any success test +or deterministic table completion is applied. -/ +theorem variation_pi {n : ℕ} (α : Fin n → Type*) [∀ i, Fintype (α i)] + (p q : ∀ i, RationalLaw (α i)) : + variation (piLaw p) (piLaw q) ≤ ∑ i, variation (p i) (q i) := by + induction n with + | zero => simp [variation, piLaw] + | succ n ih => + have hi := ih (fun i : Fin n => α i.succ) + (fun i : Fin n => p i.succ) (fun i : Fin n => q i.succ) + calc + _ = _ := variation_pi_succ α p q + _ ≤ variation (p 0) (q 0) + + variation (piLaw (fun i : Fin n => p i.succ)) (piLaw (fun i : Fin n => q i.succ)) := + variation_product _ _ _ _ + _ ≤ variation (p 0) (q 0) + ∑ i : Fin n, variation (p i.succ) (q i.succ) := + add_le_add le_rfl hi + _ = _ := (Fin.sum_univ_succ (fun i => variation (p i) (q i))).symm + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f4c23220f414c69d3349306974d763777cd72fd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalReindex.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess + +namespace OAI + +/-! # Finite rational laws transported through bijections -/ + +namespace ContingencyTables.ResidualMixture + +variable {α : Type*} [Fintype α] + +@[ext] theorem RationalLaw.ext {p q : RationalLaw α} (h : p.mass = q.mass) : p = q := by + cases p + cases q + cases h + rfl + +end ContingencyTables.ResidualMixture + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {α β : Type*} [Fintype α] [Fintype β] + +def equivLaw (e : α ≃ β) (p : RationalLaw α) : RationalLaw β where + mass := fun y => p.mass (e.symm y) + nonnegative := fun y => p.nonnegative (e.symm y) + total := by + have h := Fintype.sum_equiv e p.mass (fun y => p.mass (e.symm y)) (fun x => by simp) + rw [← h, p.total] + +theorem variation_equiv (e : α ≃ β) (p q : RationalLaw α) : + variation (equivLaw e p) (equivLaw e q) = variation p q := by + unfold variation equivLaw + congr 1 + symm + apply Fintype.sum_equiv e + intro x + simp + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalRootBisection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalRootBisection.lean new file mode 100644 index 0000000000000000000000000000000000000000..14911e17b8462a92276354cefc2160cd7c27f2ca --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalRootBisection.lean @@ -0,0 +1,89 @@ +import Mathlib.Analysis.SpecialFunctions.Pow.Real +import Mathlib.Data.Rat.Cast.Order +import Mathlib.Tactic + +namespace OAI + +/-! # Fixed-depth rational bisection for the correction power of two -/ + +namespace ContingencyTables.RationalRootBisection + +noncomputable section + +/-- Every branch compares exact rational powers. The loop count is the +explicit depth, independent of the comparison outcomes. -/ +def interval (c : ℚ) (s : ℕ) : ℕ → ℚ × ℚ + | 0 => (0,8) + | n+1 => + let ab := interval c s n + let m := (ab.1+ab.2)/2 + if m^s ≤ c then (m,ab.2) else (ab.1,m) + +def midpoint (c : ℚ) (s n : ℕ) : ℚ := + ((interval c s n).1+(interval c s n).2)/2 + +/-- The target is used only in correctness, never by the algorithm. -/ +theorem interval_contains (c : ℚ) (s : ℕ) (hs : 0 < s) (t : ℝ) + (ht : 0 ≤ t) (ht8 : t ≤ 8) (hroot : t^s=(c:ℝ)) (n : ℕ) : + 0 ≤ ((interval c s n).1:ℝ) ∧ ((interval c s n).1:ℝ) ≤ t ∧ + t ≤ ((interval c s n).2:ℝ) ∧ ((interval c s n).2:ℝ) ≤ 8 := by + induction n with + | zero => simpa only [interval,Rat.cast_zero,Rat.cast_ofNat] using ⟨le_refl 0,ht,ht8,le_refl 8⟩ + | succ n ih => + let ab := interval c s n + let m : ℚ := (ab.1+ab.2)/2 + have hm0 : (0:ℝ) ≤ m := by + dsimp only [m] + push_cast + change 0 ≤ (((interval c s n).1:ℝ)+((interval c s n).2:ℝ))/2 + linarith [ih.1,ih.2.1,ih.2.2.1] + have hml : ((ab.1:ℚ):ℝ) ≤ m := by + dsimp only [m,ab] + push_cast + linarith [ih.2.1,ih.2.2.1] + have hmu : (m:ℝ) ≤ ab.2 := by + dsimp only [m,ab] + push_cast + linarith [ih.2.1,ih.2.2.1] + change 0 ≤ ((if m^s ≤ c then (m,ab.2) else (ab.1,m)).1:ℝ) ∧ + ((if m^s ≤ c then (m,ab.2) else (ab.1,m)).1:ℝ) ≤ t ∧ + t ≤ ((if m^s ≤ c then (m,ab.2) else (ab.1,m)).2:ℝ) ∧ + ((if m^s ≤ c then (m,ab.2) else (ab.1,m)).2:ℝ) ≤ 8 + by_cases h : m^s ≤ c + · simp only [h,ite_true] + have hp : (m:ℝ)^s ≤ t^s := by rw [hroot]; exact_mod_cast h + exact ⟨hm0,le_of_pow_le_pow_left₀ hs.ne' ht hp,ih.2.2.1,ih.2.2.2⟩ + · simp only [h,ite_false] + have hp : t^s < (m:ℝ)^s := by rw [hroot]; exact_mod_cast (lt_of_not_ge h) + exact ⟨ih.1,ih.2.1,(lt_of_pow_lt_pow_left₀ s hm0 hp).le,hmu.trans ih.2.2.2⟩ + +lemma interval_width (c : ℚ) (s n : ℕ) : + (interval c s n).2-(interval c s n).1=8/(2:ℚ)^n := by + induction n with + | zero => norm_num [interval] + | succ n ih => + simp only [interval,pow_succ] + split_ifs <;> dsimp only + all_goals + have hn : (2:ℚ)^n≠0 := pow_ne_zero _ (by norm_num) + field_simp [hn] at ih ⊢ + nlinarith + +/-- A fixed depth yields an absolute error certificate for every rational +power comparison path. -/ +theorem midpoint_error (c : ℚ) (s : ℕ) (hs : 0 < s) (t : ℝ) + (ht : 0 ≤ t) (ht8 : t ≤ 8) (hroot : t^s=(c:ℝ)) (n : ℕ) : + |(midpoint c s n:ℝ)-t| ≤ 8/(2:ℝ)^n := by + have hb := interval_contains c s hs t ht ht8 hroot n + have hw : ((interval c s n).2:ℝ)-((interval c s n).1:ℝ)=8/(2:ℝ)^n := by + have hh := congrArg (fun q : ℚ => (q:ℝ)) (interval_width c s n) + simpa only [Rat.cast_sub,Rat.cast_div,Rat.cast_ofNat,Rat.cast_pow] using hh + unfold midpoint + push_cast + exact abs_le.mpr ⟨by linarith [hb.2.1,hb.2.2.1],by linarith [hb.2.1,hb.2.2.1]⟩ + +end + +end ContingencyTables.RationalRootBisection + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalkApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalkApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbc5a4ce8a94a06713122ed64fae7731ea9a0a25 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalkApproximation.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks + +namespace OAI + +/-! # Adaptive completion errors add once per actual transition -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {α β : Type*} [Fintype α] [Fintype β] + +theorem variation_bind_two (p q : RationalLaw α) (K L : α → RationalLaw β) : + variation (bindLaw p K) (bindLaw q L) ≤ + variation p q+∑ x,p.mass x*variation (K x) (L x) := by + have hpoint (x : α) (y : β) : + |p.mass x*(K x).mass y-q.mass x*(L x).mass y| ≤ + p.mass x*|(K x).mass y-(L x).mass y|+|p.mass x-q.mass x| *(L x).mass y := by + calc + _ = |p.mass x*((K x).mass y-(L x).mass y)+(p.mass x-q.mass x)*(L x).mass y| := by + congr 1 + ring + _ ≤ |p.mass x*((K x).mass y-(L x).mass y)|+|(p.mass x-q.mass x)*(L x).mass y| := + abs_add_le _ _ + _ = _ := by + rw [abs_mul,abs_mul,abs_of_nonneg (p.nonnegative x),abs_of_nonneg ((L x).nonnegative y)] + have hsum : + (∑ y,|∑ x,(p.mass x*(K x).mass y-q.mass x*(L x).mass y)|) ≤ + (∑ x,|p.mass x-q.mass x|)+∑ x,p.mass x*(∑ y,|(K x).mass y-(L x).mass y|) := by + calc + _ ≤ ∑ y,∑ x,|p.mass x*(K x).mass y-q.mass x*(L x).mass y| := + Finset.sum_le_sum (fun y _ => Finset.abs_sum_le_sum_abs _ _) + _ ≤ ∑ y,∑ x,(p.mass x*|(K x).mass y-(L x).mass y|+ + |p.mass x-q.mass x| *(L x).mass y) := + Finset.sum_le_sum (fun y _ => Finset.sum_le_sum (fun x _ => hpoint x y)) + _ = _ := by + rw [Finset.sum_comm] + simp only [Finset.sum_add_distrib,← Finset.mul_sum,(L _).total,mul_one] + ring + unfold variation + change (∑ y,|(∑ x,p.mass x*(K x).mass y)-(∑ x,q.mass x*(L x).mass y)|)/2 ≤ _ + simp_rw [← Finset.sum_sub_distrib] + have hh := div_le_div_of_nonneg_right hsum (show (0:ℚ) ≤ 2 by norm_num) + convert hh using 1 + simp only [add_div,Finset.sum_div,mul_div_assoc] + +theorem variation_bind_uniform (p q : RationalLaw α) (K L : α → RationalLaw β) + (η : ℚ) (hη : ∀ x,variation (K x) (L x) ≤ η) : + variation (bindLaw p K) (bindLaw q L) ≤ variation p q+η := by + calc + _ ≤ variation p q+∑ x,p.mass x*variation (K x) (L x) := variation_bind_two p q K L + _ ≤ variation p q+∑ x,p.mass x*η := by + apply add_le_add_right + exact Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hη x) (p.nonnegative x)) + _ = _ := by rw [← Finset.sum_mul,p.total,one_mul] + +variable [DecidableEq α] + +/-- The common state may depend on earlier randomness. Only the uniform +one-step bound is used; the approximating chain need not be reversible. -/ +theorem walkLaw_variation (K L : α → RationalLaw α) (η : ℚ) + (hη : ∀ x,variation (K x) (L x) ≤ η) (a : α) (n : ℕ) : + variation (walkLaw K a n) (walkLaw L a n) ≤ n*η := by + induction n with + | zero => simp [walkLaw,variation] + | succ n ih => + change variation (bindLaw (walkLaw K a n) K) (bindLaw (walkLaw L a n) L) ≤ _ + calc + _ ≤ variation (walkLaw K a n) (walkLaw L a n)+η := variation_bind_uniform _ _ K L η hη + _ ≤ (n:ℚ)*η+η := add_le_add_left ih η + _ = _ := by push_cast; ring + +theorem walkLaw_terminal_variation (K L : α → RationalLaw α) + (F G : α → RationalLaw β) (η : ℚ) + (hη : ∀ x,variation (K x) (L x) ≤ η) + (hterminal : ∀ x,variation (F x) (G x) ≤ η) (a : α) (n : ℕ) : + variation (bindLaw (walkLaw K a n) F) (bindLaw (walkLaw L a n) G) ≤ (n+1)*η := by + calc + _ ≤ variation (walkLaw K a n) (walkLaw L a n)+η := variation_bind_uniform _ _ F G η hterminal + _ ≤ (n:ℚ)*η+η := add_le_add_left (walkLaw_variation K L η hη a n) η + _ = _ := by ring + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalks.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalks.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa28876f690709707e48e4f3e8a38b5f5d9eeda --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RationalWalks.lean @@ -0,0 +1,31 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalReindex +import OAI.Combinatorics.ContingencyTables.Transport.RejectionLaw + +namespace OAI + +/-! # Independent composition of finite rational transition experiments -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators +open ResidualMixture + +variable {α β : Type*} [Fintype α] [Fintype β] + +def bindLaw (p : RationalLaw α) (K : α → RationalLaw β) : RationalLaw β where + mass := fun y => ∑ x, p.mass x * (K x).mass y + nonnegative := fun y => Finset.sum_nonneg fun x _ => mul_nonneg (p.nonnegative x) ((K x).nonnegative y) + total := by + rw [Finset.sum_comm] + simp only [← Finset.mul_sum, (K _).total, mul_one, p.total] + +variable [DecidableEq α] + +/-- Each transition uses a fresh independent finite experiment. -/ +def walkLaw (K : α → RationalLaw α) (a : α) : ℕ → RationalLaw α + | 0 => pointLaw a + | n + 1 => bindLaw (walkLaw K a n) K + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RawSmallChoiceProperties.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RawSmallChoiceProperties.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b4c3ee5cfae17375b421d1b7f3734e71c910f80 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RawSmallChoiceProperties.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ChoiceContextEnumeration + +namespace OAI + +/-! # Balanced words are literal bounded physical transversal profiles -/ + +namespace ContingencyTables.SmallContextEnumeration + +open scoped Classical +open SmallContextCoordinates SmallContextFibres SmallGraphProfiles + +universe u + +variable {I J : Type u} + +lemma rawChoice_bounded (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (x : Cells small → Fin (U+1)) : + ∀ a,rawChoice small U x a ≤ B a.1.val.1 a.1.val.2 := + naturalProfile_bounded (choiceProfile small B U hB x) + +lemma rawChoice_balanced (small : I → J → Bool) (B : I → J → ℕ) (U : ℕ) + (hB : ∀ i j,small i j=true → B i j=U) (x : Cells small → Fin (U+1)) : + Balanced small B (rawChoice small U x) := choiceProfile_balanced small B U hB x + +lemma rawChoice_injective (small : I → J → Bool) (U : ℕ) : Function.Injective (rawChoice small U) := by + intro x y he + funext a + exact Fin.ext (congrFun he (a,false)) + +end ContingencyTables.SmallContextEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RealCompletion.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7f6534238172a368fb64cd0c98ffe444a7dc8d8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealCompletion.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAffine +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.FieldSimp + +namespace OAI + +/-! +# Real completions with prescribed lower bounds + +The dense geometric argument needs one strictly feasible normalized table. +Residual nonnegative real margins are completed by a rank-one table; this +is enough for the analytic interior-point argument and makes no algorithmic +claim about integral flow preprocessing. +-/ + +namespace ContingencyTables + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem real_table_exists (r : I → ℝ) (c : J → ℝ) + (hr : ∀ i, 0 ≤ r i) (hc : ∀ j, 0 ≤ c j) + (htotal : ∑ i, r i = ∑ j, c j) : + ∃ X : I → J → ℝ, (∀ i j, 0 ≤ X i j) ∧ + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) := by + by_cases hzero : ∑ i, r i = 0 + · have hr₀ (i : I) : r i = 0 := by + have h := Finset.single_le_sum (fun a _ => hr a) (Finset.mem_univ i) + linarith [hr i] + have hc₀ (j : J) : c j = 0 := by + have h := Finset.single_le_sum (fun a _ => hc a) (Finset.mem_univ j) + rw [← htotal, hzero] at h + linarith [hc j] + exact ⟨fun _ _ => 0, by simp, by simp [hr₀], by simp [hc₀]⟩ + · have hN : 0 < ∑ i, r i := lt_of_le_of_ne + (Finset.sum_nonneg fun i _ => hr i) (Ne.symm hzero) + refine ⟨fun i j => r i * c j / (∑ i, r i), ?_, ?_, ?_⟩ + · intro i j + exact div_nonneg (mul_nonneg (hr i) (hc j)) hN.le + · intro i + rw [← Finset.sum_div, ← Finset.mul_sum, ← htotal] + field_simp + · intro j + rw [← Finset.sum_div, ← Finset.sum_mul] + field_simp + +theorem lower_bounded_real_table (r : I → ℝ) (c : J → ℝ) (lower : I → J → ℝ) + (htotal : ∑ i, r i = ∑ j, c j) + (hrow : ∀ i, ∑ j, lower i j ≤ r i) (hcol : ∀ j, ∑ i, lower i j ≤ c j) : + ∃ X : I → J → ℝ, (∀ i j, lower i j ≤ X i j) ∧ + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) := by + let r₀ : I → ℝ := fun i => r i - ∑ j, lower i j + let c₀ : J → ℝ := fun j => c j - ∑ i, lower i j + have ht : ∑ i, r₀ i = ∑ j, c₀ j := by + simp only [r₀, c₀, Finset.sum_sub_distrib, htotal] + rw [Finset.sum_comm (f := lower)] + obtain ⟨Y, hY, hR, hC⟩ := real_table_exists r₀ c₀ + (fun i => sub_nonneg.mpr (hrow i)) (fun j => sub_nonneg.mpr (hcol j)) ht + refine ⟨fun i j => lower i j + Y i j, ?_, ?_, ?_⟩ + · intro i j + linarith [hY i j] + · intro i + rw [Finset.sum_add_distrib, hR] + dsimp [r₀] + ring + · intro j + rw [Finset.sum_add_distrib, hC] + dsimp [c₀] + ring + +/-- Assigning `min(rᵢ,cⱼ)/(2d)` to every cell leaves nonnegative residual +margins whenever each dimension is at most `d`. -/ +theorem strict_real_completion (r : I → ℝ) (c : J → ℝ) (d : ℝ) + (hd : 0 < d) (hr : ∀ i, 0 ≤ r i) (hc : ∀ j, 0 ≤ c j) + (hrows : (Fintype.card I : ℝ) ≤ d) (hcols : (Fintype.card J : ℝ) ≤ d) + (htotal : ∑ i, r i = ∑ j, c j) : + ∃ X : I → J → ℝ, (∀ i j, min (r i) (c j) / (2 * d) ≤ X i j) ∧ + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) := by + apply lower_bounded_real_table r c (fun i j => min (r i) (c j) / (2 * d)) htotal + · intro i + calc + (∑ j, min (r i) (c j) / (2 * d)) ≤ ∑ _j : J, r i / (2 * d) := by + apply Finset.sum_le_sum + intro j _ + exact div_le_div_of_nonneg_right (min_le_left _ _) (by positivity) + _ = Fintype.card J * (r i / (2 * d)) := by simp + _ ≤ d * (r i / (2 * d)) := mul_le_mul_of_nonneg_right hcols + (div_nonneg (hr i) (by positivity)) + _ ≤ r i := by + rw [← mul_div_assoc] + apply (div_le_iff₀ (show 0 < 2 * d by positivity)).mpr + nlinarith [hr i] + · intro j + calc + (∑ i, min (r i) (c j) / (2 * d)) ≤ ∑ _i : I, c j / (2 * d) := by + apply Finset.sum_le_sum + intro i _ + exact div_le_div_of_nonneg_right (min_le_right _ _) (by positivity) + _ = Fintype.card I * (c j / (2 * d)) := by simp + _ ≤ d * (c j / (2 * d)) := mul_le_mul_of_nonneg_right hrows + (div_nonneg (hc j) (by positivity)) + _ ≤ c j := by + rw [← mul_div_assoc] + apply (div_le_iff₀ (show 0 < 2 * d by positivity)).mpr + nlinarith [hc j] + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RealKernelApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealKernelApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b3e6811fdaadc55de653c2c01c419dc84a645db --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealKernelApproximation.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks +import OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain + +namespace OAI + +/-! # Accumulating rational implementation errors against a real kernel + +The exact companion weights may be real. The implemented probabilities +are rational; comparison takes place after their canonical real cast. +-/ + +namespace ContingencyTables.RealKernelApproximation +open scoped BigOperators Classical +open CommonBasesFPRAS ResidualMixture FirstSuccess + +noncomputable section +variable {X Y : Type*} [Fintype X] [Fintype Y] + +def distance (p q : X → ℝ) : ℝ := (∑ x,|p x-q x|)/2 + +lemma distance_nonneg (p q : X → ℝ) : 0 ≤ distance p q := + div_nonneg (Finset.sum_nonneg fun _ _ => abs_nonneg _) (by norm_num) + +lemma distance_triangle (p q r : X → ℝ) : distance p r ≤ distance p q+distance q r := by + have h := Finset.sum_le_sum (fun x (_ : x∈Finset.univ) => abs_sub_le (p x) (q x) (r x)) + simp only [Finset.sum_add_distrib] at h + unfold distance + linarith + +lemma distance_event (p q : X → ℝ) (hmass : ∑ x,p x=∑ x,q x) (S : Finset X) : + |(∑ x∈S,p x)-(∑ x∈S,q x)| ≤ distance p q := by + have hz : (∑ x ∈ S, (p x-q x))+(∑ x ∈ Sᶜ, (p x-q x))=0 := by + rw [Finset.sum_add_sum_compl,Finset.sum_sub_distrib,hmass,sub_self] + have hc : (∑ x ∈ Sᶜ, (p x-q x))= -(∑ x ∈ S, (p x-q x)) := by linarith + have ha := Finset.abs_sum_le_sum_abs (fun x => p x-q x) S + have hb := Finset.abs_sum_le_sum_abs (fun x => p x-q x) Sᶜ + rw [hc,abs_neg] at hb + have hs := add_le_add ha hb + rw [Finset.sum_add_sum_compl] at hs + rw [←Finset.sum_sub_distrib] + unfold distance + linarith + +lemma distance_push (K : FiniteKernel X Y) (p q : X → ℝ) : + distance (K.push p) (K.push q) ≤ distance p q := by + have hp (y : Y) : |K.push p y-K.push q y| ≤ ∑ x, |p x-q x| * K.P x y := by + unfold FiniteKernel.push + rw [←Finset.sum_sub_distrib] + have h := Finset.abs_sum_le_sum_abs + (fun x => p x*K.P x y-q x*K.P x y) Finset.univ + simpa only [←sub_mul,abs_mul,abs_of_nonneg (K.nonnegative _ _)] using h + have hs := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => hp y) + have ht : (∑ y,∑ x, |p x-q x| * K.P x y) ≤ ∑ x,|p x-q x| := by + rw [Finset.sum_comm] + simp only [←Finset.mul_sum] + exact Finset.sum_le_sum (fun x _ => by + simpa only [mul_one] using mul_le_mul_of_nonneg_left (K.substochastic x) (abs_nonneg (p x-q x))) + unfold distance + exact div_le_div_of_nonneg_right (hs.trans ht) (by norm_num) + +lemma distance_push_rows (K L : FiniteKernel X Y) (p : X → ℝ) + (hp : ∀ x,0 ≤ p x) : + distance (K.push p) (L.push p) ≤ ∑ x,p x*distance (K.P x) (L.P x) := by + have hb (y : Y) : |K.push p y-L.push p y| ≤ ∑ x,p x*|K.P x y-L.P x y| := by + unfold FiniteKernel.push + rw [←Finset.sum_sub_distrib] + have h := Finset.abs_sum_le_sum_abs + (fun x => p x*K.P x y-p x*L.P x y) Finset.univ + simpa only [←mul_sub,abs_mul,abs_of_nonneg (hp _)] using h + have hs := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => hb y) + rw [Finset.sum_comm] at hs + simp only [←Finset.mul_sum] at hs + unfold distance + simpa only [Finset.sum_div,mul_div_assoc] using + div_le_div_of_nonneg_right hs (by norm_num : (0:ℝ)≤2) + +lemma distance_push_two (K L : FiniteKernel X Y) (p q : X → ℝ) + (hp : ∀ x,0 ≤ p x) (hmass : ∑ x,p x=1) (η : ℝ) + (hη : ∀ x,distance (K.P x) (L.P x) ≤ η) : + distance (K.push p) (L.push q) ≤ distance p q+η := by + have hr : distance (K.push p) (L.push p) ≤ η := by + calc + _ ≤ ∑ x,p x*distance (K.P x) (L.P x) := distance_push_rows K L p hp + _ ≤ ∑ x,p x*η := Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hη x) (hp x)) + _ = η := by rw [←Finset.sum_mul,hmass,one_mul] + have ht := distance_triangle (K.push p) (L.push p) (L.push q) + have hc := distance_push L p q + linarith + +def rationalKernel (K : X → RationalLaw Y) : FiniteKernel X Y where + P x y := ((K x).mass y:ℝ) + nonnegative x y := by exact_mod_cast (K x).nonnegative y + substochastic x := by + have h := congrArg (fun z : ℚ => (z:ℝ)) (K x).total + simpa only [Rat.cast_sum,Rat.cast_one] using h.le + +lemma rationalKernel_push (K : X → RationalLaw Y) (p : RationalLaw X) : + (rationalKernel K).push (fun x => (p.mass x:ℝ))= + fun y => ((bindLaw p K).mass y:ℝ) := by + funext y + simp only [rationalKernel,FiniteKernel.push,bindLaw,Rat.cast_sum,Rat.cast_mul] + +variable [DecidableEq X] + +/-- Each realized step may use fresh approximate oracle calls. A uniform +real row error adds once per actual step against the exact real chain. -/ +theorem walk_distance (Q : X → RationalLaw X) (K : FiniteKernel X X) + (η : ℝ) (hη : ∀ x,distance ((rationalKernel Q).P x) (K.P x) ≤ η) + (x : X) (n : ℕ) : + distance (fun y => ((walkLaw Q x n).mass y:ℝ)) ((K.power n).P x) ≤ n*η := by + induction n with + | zero => + simp only [walkLaw,FiniteKernel.power,Nat.cast_zero,zero_mul,distance] + apply le_of_eq + apply div_eq_zero_iff.mpr + left + apply Finset.sum_eq_zero + intro y _ + by_cases h : x=y + · subst y; simp [pointLaw,FiniteKernel.identity] + · simp [pointLaw,FiniteKernel.identity,h,Ne.symm h] + | succ n ih => + have hm : (∑ y,((walkLaw Q x n).mass y:ℝ))=1 := by + exact_mod_cast (walkLaw Q x n).total + have ht := distance_push_two (rationalKernel Q) K + (fun y => ((walkLaw Q x n).mass y:ℝ)) ((K.power n).P x) + (fun y => by exact_mod_cast (walkLaw Q x n).nonnegative y) hm η hη + rw [rationalKernel_push] at ht + change distance (fun y => ((walkLaw Q x (n+1)).mass y:ℝ)) ((K.power (n+1)).P x) ≤ _ at ht + exact ht.trans (by push_cast; linarith) + +end +end ContingencyTables.RealKernelApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RealPathApproximation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealPathApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee989b4adaa2138038907cc5e7b5c8dc45f6ca00 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RealPathApproximation.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation + +namespace OAI + +/-! # Keeping an entire finite history during real-kernel comparison -/ + +namespace ContingencyTables.RealKernelApproximation +open scoped BigOperators Classical +open CommonBasesFPRAS ResidualMixture FirstSuccess + +noncomputable section +variable {X Y A B : Type*} [Fintype X] [Fintype Y] [Fintype A] [Fintype B] + +def mapKernel (f : X → Y) : FiniteKernel X Y where + P x y := if f x=y then 1 else 0 + nonnegative x y := by split_ifs <;> norm_num + substochastic x := by simp + +lemma rational_map_push [DecidableEq Y] (p : RationalLaw X) (f : X → Y) : + (fun y => ((mapLaw p f).mass y:ℝ))=(mapKernel f).push (fun x => (p.mass x:ℝ)) := by + funext y + simp only [mapLaw,FiniteKernel.push,mapKernel,Rat.cast_sum,apply_ite,Rat.cast_zero, + mul_one,mul_zero] + +/-- `a` can contain the entire past. Only `read a` is used for the next +random transition; `put a` retains every coordinate needed afterward. -/ +def liftKernel (K : FiniteKernel X Y) (read : A → X) (put : A → Y → B) : FiniteKernel A B where + P a b := (mapKernel (put a)).push (K.P (read a)) b + nonnegative a b := (mapKernel (put a)).push_nonneg _ (K.nonnegative (read a)) b + substochastic a := ((mapKernel (put a)).push_mass_le _ (K.nonnegative (read a))).trans + (K.substochastic (read a)) + +def liftRational [DecidableEq B] (Q : X → RationalLaw Y) + (read : A → X) (put : A → Y → B) (a : A) : RationalLaw B := mapLaw (Q (read a)) (put a) + +omit [Fintype X] [Fintype A] in +/-- Recording extra coordinates never increases one transition's error. -/ +theorem lifted_row_distance [DecidableEq B] (Q : X → RationalLaw Y) + (K : FiniteKernel X Y) (read : A → X) (put : A → Y → B) (a : A) : + distance ((rationalKernel (liftRational Q read put)).P a) + ((liftKernel K read put).P a) ≤ distance ((rationalKernel Q).P (read a)) (K.P (read a)) := by + change distance (fun b => ((mapLaw (Q (read a)) (put a)).mass b:ℝ)) + ((mapKernel (put a)).push (K.P (read a))) ≤ _ + rw [rational_map_push] + exact distance_push (mapKernel (put a)) _ _ + +/-- The joint-history version of the accumulated transition bound. The +recorded state may be a fixed-length vector of every visited state. -/ +theorem lifted_walk_distance [DecidableEq A] (Q : X → RationalLaw X) + (K : FiniteKernel X X) (read : A → X) (put : A → X → A) + (η : ℝ) (hη : ∀ x,distance ((rationalKernel Q).P x) (K.P x) ≤ η) + (a : A) (n : ℕ) : + distance (fun b => ((walkLaw (liftRational Q read put) a n).mass b:ℝ)) + (((liftKernel K read put).power n).P a) ≤ n*η := by + apply walk_distance + intro b + exact (lifted_row_distance Q K read put b).trans (hη (read b)) + +/-- The first coordinate records which entries of the vector have been +written. Saturation keeps the state space finite even after the horizon. -/ +abbrev PathState (X : Type*) (N : ℕ) := Fin (N+1) × (Fin (N+1) → X) + +def nextPosition {N : ℕ} (i : Fin (N+1)) : Fin (N+1) := + ⟨min (i.val+1) N,Nat.lt_succ_of_le (min_le_right _ _)⟩ + +def pathRead {N : ℕ} (a : PathState X N) : X := a.2 a.1 + +def pathPut {N : ℕ} (a : PathState X N) (x : X) : PathState X N := + (nextPosition a.1,Function.update a.2 (nextPosition a.1) x) + +def pathInitial (N : ℕ) (x : X) : PathState X N := (0,fun _ => x) + +/-- Error for the entire recorded path, hence also for any event defined +from all the empirical observations, is at most one row error per step. -/ +theorem path_distance (Q : X → RationalLaw X) (K : FiniteKernel X X) + (η : ℝ) (hη : ∀ x,distance ((rationalKernel Q).P x) (K.P x) ≤ η) + (N n : ℕ) (x : X) : + distance (fun a => ((walkLaw (liftRational Q pathRead pathPut) (pathInitial N x) n).mass a:ℝ)) + (((liftKernel K pathRead pathPut).power n).P (pathInitial N x)) ≤ n*η := + lifted_walk_distance Q K pathRead pathPut η hη (pathInitial N x) n + +end +end ContingencyTables.RealKernelApproximation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RectangleCompletions.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RectangleCompletions.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9a87da271429ef20e048b8395630f13c4276196 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RectangleCompletions.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionCounts + +namespace OAI + +/-! # Supported completions are tables on the actual large rectangle -/ + +namespace ContingencyTables.CompletionCounts + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma sum_subtype_eq_of_zero {K : Type*} [Fintype K] (p : K → Prop) + (f : K → ℕ) (hf : ∀ k,¬p k → f k=0) : + (∑ k : {k // p k},f k.val)=∑ k,f k := by + calc + _ = ∑ k ∈ Finset.univ.filter p,f k := (Finset.sum_subtype _ (by simp) f).symm + _ = ∑ k,f k := by + rw [Finset.sum_filter] + apply Finset.sum_congr rfl + intro k _ + by_cases hk : p k + · rw [ite_eq_left hk] + · rw [ite_eq_right hk,hf k hk] + +noncomputable def rectangleRestrict (small : I → J → Bool) + (p : I → Prop) (q : J → Prop) + (hrect : ∀ i j,small i j=false ↔ p i ∧ q j) + (R : I → ℕ) (C : J → ℕ) (A : LargeCompletion small R C) : + Table (fun i : {i // p i} => R i.val) (fun j : {j // q j} => C j.val) := by + refine ⟨fun i j => A.val.val i.val j.val,?_,?_⟩ + · intro i + rw [sum_subtype_eq_of_zero q (A.val.val i.val)] + · exact A.val.property.1 i.val + · intro j hj + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hj ((hrect i.val j).mp hs).2 + · intro j + rw [sum_subtype_eq_of_zero p (fun i => A.val.val i j.val)] + · exact A.val.property.2 j.val + · intro i hi + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hi ((hrect i j.val).mp hs).1 + +noncomputable def rectangleExtend (small : I → J → Bool) + (p : I → Prop) (q : J → Prop) + (hrect : ∀ i j,small i j=false ↔ p i ∧ q j) + (R : I → ℕ) (C : J → ℕ) + (hR : ∀ i,¬p i → R i=0) (hC : ∀ j,¬q j → C j=0) + (A : Table (fun i : {i // p i} => R i.val) (fun j : {j // q j} => C j.val)) : + LargeCompletion small R C := by + let F : I → J → ℕ := fun i j => if hi : p i then if hj : q j then A.val ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0 + have hzero (i : I) (j : J) (hs : small i j=true) : F i j=0 := by + dsimp only [F] + split_ifs with hi hj + · have hh := (hrect i j).mpr ⟨hi,hj⟩ + rw [hs] at hh + contradiction + · rfl + · rfl + refine ⟨⟨F,?_,?_⟩,hzero⟩ + · intro i + by_cases hi : p i + · rw [← sum_subtype_eq_of_zero q (F i) (by + intro j hj; simp [F,hi,hj])] + convert A.property.1 ⟨i,hi⟩ using 1 + apply Finset.sum_congr rfl + intro j _ + simp only [F,dite_eq_left hi,dite_eq_left j.property] + · simp [F,hi,hR i hi] + · intro j + by_cases hj : q j + · rw [← sum_subtype_eq_of_zero p (fun i => F i j) (by + intro i hi; simp [F,hi])] + convert A.property.2 ⟨j,hj⟩ using 1 + apply Finset.sum_congr rfl + intro i _ + simp only [F,dite_eq_left i.property,dite_eq_left hj] + · have hz : ∀ i,F i j=0 := by intro i; dsimp only [F]; split_ifs <;> simp_all + simp only [hz,Finset.sum_const_zero,hC j hj] + +noncomputable def rectangleCompletionEquiv (small : I → J → Bool) + (p : I → Prop) (q : J → Prop) + (hrect : ∀ i j,small i j=false ↔ p i ∧ q j) + (R : I → ℕ) (C : J → ℕ) + (hR : ∀ i,¬p i → R i=0) (hC : ∀ j,¬q j → C j=0) : + LargeCompletion small R C ≃ + Table (fun i : {i // p i} => R i.val) (fun j : {j // q j} => C j.val) where + toFun := rectangleRestrict small p q hrect R C + invFun := rectangleExtend small p q hrect R C hR hC + left_inv A := by + apply Subtype.ext + apply Subtype.ext + funext i j + change (if hi : p i then if hj : q j then A.val.val i j else 0 else 0)=A.val.val i j + split_ifs with hi hj + · rfl + · symm + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hj ((hrect i j).mp hs).2 + · symm + apply A.property + apply Bool.eq_true_of_ne_false + intro hs + exact hi ((hrect i j).mp hs).1 + right_inv A := by + apply Subtype.ext + funext i j + change (if hi : p i.val then if hj : q j.val then A.val ⟨i.val,hi⟩ ⟨j.val,hj⟩ else 0 else 0)=A.val i j + simp only [dite_eq_left i.property,dite_eq_left j.property] + +end ContingencyTables.CompletionCounts + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RecursiveSignedTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RecursiveSignedTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..904f3412bc55d238c3cfd4174f72d37377b725b8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RecursiveSignedTransport.lean @@ -0,0 +1,507 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryContraction + +namespace OAI + +/-! +# Recursive signed transport for fixed-degree weights + +The recursive transport construction of the bounded-table counting paper +uses positivity at the valid subset degree. Signatures after pair summation +follow from that degree's addition property and full cubic contraction. +-/ + +namespace ContingencyTables.RecursiveSignedTransport + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS BinaryContraction + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +lemma slotTotal_degree_positive (ps : List (Γ × Γ)) (f : Set Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (A : Set Γ) + (hdegree : A.ncard + ps.length = k) (hslots : SlotsFresh ps A) : + 0 < slotTotal ps f A := by + induction ps generalizing A with + | nil => exact hf A (by simpa using hdegree) + | cons p ps ih => + obtain ⟨hp, ha, hb, ht⟩ := hslots + rw [slotTotal_cons p ps f A hp ha hb] + apply add_pos + · apply ih (insert p.1 A) + · rw [ncard_insert_eq A p.1 ha] + simp only [List.length_cons] at hdegree + omega + · exact ht.mono (by intro x hx; rcases hx with rfl | hx <;> simp_all) + · apply ih (insert p.2 A) + · rw [ncard_insert_eq A p.2 hb] + simp only [List.length_cons] at hdegree + omega + · exact ht.mono (Set.subset_insert _ _) + +omit [DecidableEq Γ] in +lemma embedded_union_card {κ : Type*} (A : Set Γ) (e : κ → Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) (U : Set κ) : + (A ∪ e '' U).ncard = A.ncard + U.ncard := by + have hd : Disjoint A (e '' U) := by + apply Set.disjoint_left.mpr + rintro x hx ⟨i, _, rfl⟩ + exact heA i hx + rw [Set.ncard_union_eq hd, Set.ncard_image_of_injective U he] + +/-- The exact signature needed by the recursion, obtained after summing +fresh pairs only on the valid residual degree. -/ +theorem slot_pair_signature (ps : List (Γ × Γ)) : + ∀ {κ : Type*} [Fintype κ] [DecidableEq κ] [Nonempty κ] + (f : Set Γ → ℝ) (k : ℕ) (A : Set Γ) (e : κ → Γ), + DegreePositive f k → AdditionProperty f k → + A.ncard + ps.length + 2 = k → Function.Injective e → + (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + CommonBasesFPRAS.OnePositive (pairMatrix (slotTotal ps f) A e).toBilin' := by + induction ps with + | nil => + intro κ _ _ _ f k A e hf hsig hdegree he heA _ + let e' : κ → {i // i ∉ A} := fun i => ⟨e i, heA i⟩ + have heq : pairMatrix f A e = (faceHessian f A).submatrix e' e' := by + ext i j + by_cases hij : i = j + · subst j + simp [pairMatrix, faceHessian] + have hne : e' i ≠ e' j := fun h => hij (he (congrArg Subtype.val h)) + simp only [pairMatrix, hij, ite_false, Matrix.submatrix_apply, faceHessian, hne] + congr 1 + ext x + simp [e'] + change CommonBasesFPRAS.OnePositive (pairMatrix f A e).toBilin' + rw [heq] + exact onePositive_submatrix _ (hsig A (by simpa using hdegree)) e' + | cons p ps ih => + intro κ _ _ _ f k A e hf hsig hdegree he heA hslots + obtain ⟨hp, ha, hb, ht⟩ := hslots + let J := κ ⊕ Bool + let E : J → Γ := splitEmbedding e p.1 p.2 + have hE : Function.Injective E := + splitEmbedding_injective e p.1 p.2 he hp + (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h)) + have hEA : ∀ i, E i ∉ A := by + intro i + cases i with + | inl i => exact heA i + | inr b => cases b <;> simp only [E, splitEmbedding] <;> tauto + have htail : SlotsFresh ps (A ∪ Set.range E) := by + apply ht.mono + rintro x (hx | ⟨i, rfl⟩) + · exact Or.inr (Or.inr (Or.inl hx)) + · cases i with + | inl i => exact Or.inr (Or.inr (Or.inr ⟨i, rfl⟩)) + | inr b => cases b <;> simp [E, splitEmbedding] + let g : Set J → ℝ := fun U => slotTotal ps f (A ∪ E '' U) + have hJ : 3 ≤ Fintype.card J := by + have hκ : 0 < Fintype.card κ := Fintype.card_pos + simp only [J, Fintype.card_sum, Fintype.card_bool] + omega + have hgpos : DegreePositive g 3 := by + intro U hU + apply slotTotal_degree_positive ps f k hf + · rw [embedded_union_card A E hE hEA U, hU] + simp only [List.length_cons] at hdegree + omega + · exact htail.mono (Set.union_subset_union_right A (Set.image_subset_range _ _)) + have hgsig : AdditionProperty g 3 := by + intro U hU + let C : Set Γ := A ∪ E '' U + let v : {i : J // i ∉ U} → Γ := fun i => E i.val + have hUcard : U.ncard = 1 := by omega + have hCcard : C.ncard = A.ncard + 1 := by + rw [embedded_union_card A E hE hEA U, hUcard] + have hcardU := card_outside U + have : Nonempty {i : J // i ∉ U} := Fintype.card_pos_iff.mp (by omega) + have hv : Function.Injective v := fun i j h => Subtype.ext (hE h) + have hvC : ∀ i, v i ∉ C := by + intro i + rintro (hiA | ⟨j, hj, hji⟩) + · exact hEA i.val hiA + · exact i.property ((hE hji) ▸ hj) + have hcontexts : C ∪ Set.range v ⊆ A ∪ Set.range E := by + rintro x ((hx | ⟨i, _, rfl⟩) | ⟨i, rfl⟩) + · exact Or.inl hx + · exact Or.inr ⟨i, rfl⟩ + · exact Or.inr ⟨i.val, rfl⟩ + have hsigU := ih f k C v hf hsig (by + rw [hCcard] + simp only [List.length_cons] at hdegree + omega) hv hvC (htail.mono hcontexts) + have heq : faceHessian g U = pairMatrix (slotTotal ps f) C v := by + ext i j + by_cases hij : i = j + · subst j + simp [faceHessian, pairMatrix] + simp only [faceHessian, pairMatrix, hij, ite_false, g] + congr 1 + ext x + simp [C, v] + rw [heq] + exact hsigU + let pa : {i : J // i ∉ (∅ : Set J)} := ⟨Sum.inr false, Set.notMem_empty _⟩ + let pb : {i : J // i ∉ (∅ : Set J)} := ⟨Sum.inr true, Set.notMem_empty _⟩ + have hfull := fixedDegree_pair_contraction g 3 hJ hgpos hgsig ∅ (by simp) pa pb + have hsymm : ∀ i j, + (faceCubic g ∅ pa + faceCubic g ∅ pb) i j = + (faceCubic g ∅ pa + faceCubic g ∅ pb) j i := by + intro i j + simp only [Matrix.add_apply, faceCubic_symm] + have hfull' : CommonBasesFPRAS.OnePositive + (faceCubic g ∅ pa + faceCubic g ∅ pb).toBilin' := by + apply (signature_iff _ (matrix_bilin_symm _ hsymm)).mp + convert hfull using 1 + congr 2 + exact Subsingleton.elim _ _ + let old : κ → {i : J // i ∉ (∅ : Set J)} := + fun i => ⟨Sum.inl i, Set.notMem_empty _⟩ + have heq : (faceCubic g ∅ pa + faceCubic g ∅ pb).submatrix old old = + pairMatrix (slotTotal (p :: ps) f) A e := by + rw [pairMatrix_parent ps f A e p hp ha hb] + ext i j + by_cases hij : i = j + · subst j + simp [Matrix.submatrix_apply, faceCubic, pairMatrix] + have hij' : old i ≠ old j := by + intro h + exact hij (Sum.inl_injective (congrArg Subtype.val h)) + simp [Matrix.submatrix_apply, Matrix.add_apply, faceCubic, pairMatrix, hij, + hij', pa, pb, old, g, E, splitEmbedding, Set.image_insert_eq, Set.insert_comm, add_comm] + rw [← heq] + exact onePositive_submatrix _ hfull' old + + +lemma slot_split_signature_degree {κ : Type*} [Fintype κ] [DecidableEq κ] [Nonempty κ] + (f : Set Γ → ℝ) (k : ℕ) (hf : DegreePositive f k) (hsig : AdditionProperty f k) + (ps : List (Γ × Γ)) (A : Set Γ) (e : κ → Γ) (p : Γ × Γ) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) + (hslots : SlotsFresh (p :: ps) (A ∪ Set.range e)) + (hdegree : A.ncard + ps.length + 2 = k) : + CommonBasesFPRAS.OnePositive (splitMatrix (pairMatrix (slotTotal ps f) A e) + (fun i => slotTotal ps f (insert (e i) (insert p.2 A))) + (fun i => slotTotal ps f (insert (e i) (insert p.1 A))) + (slotTotal ps f (insert p.1 (insert p.2 A)))).toBilin' := by + obtain ⟨hp, ha, hb, ht⟩ := hslots + rw [← pairMatrix_split] + apply slot_pair_signature ps f k A _ hf hsig hdegree + (splitEmbedding_injective e p.1 p.2 he hp + (fun h => ha (Or.inr h)) (fun h => hb (Or.inr h))) + · intro i + cases i with + | inl i => exact heA i + | inr b => cases b <;> simp only [splitEmbedding] <;> tauto + · apply ht.mono + rintro x (hx | ⟨i, rfl⟩) + · exact Or.inr (Or.inr (Or.inl hx)) + · cases i with + | inl i => exact Or.inr (Or.inr (Or.inr ⟨i, rfl⟩)) + | inr b => cases b <;> simp [splitEmbedding] + +/-- The full recursive signed transport bound. Every mass and signature +is supplied by the proved exact-degree lemmas above, and all future-slot +corrections telescope through the actual binary recursion. -/ +theorem transport_linear_bound_degree (ps : List (Γ × Γ)) : + ∀ {κ : Type*} [Fintype κ] [DecidableEq κ] [Nonempty κ] + (f H : Set Γ → ℝ) (A : Set Γ) (e : κ → Γ) (h : κ → ℝ) (W : Γ → ℝ) (k : ℕ), + DegreePositive f k → AdditionProperty f k → + A.ncard + ps.length + 1 = k → Function.Injective e → + (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + (∀ i, 0 < W i) → (∀ p ∈ ps, W p.1 = W p.2) → + (∑ i, slotTotal ps f (insert (e i) A)*h i = 0) → + 2*transportDemand ps f H A e h ≤ + transportPotential ps f A e h W - transportCorrection ps f A e h W + + transportEnergy ps f H A e W := by + induction ps with + | nil => + intro κ _ _ _ f H A e h W k hf _ hdegree _ heA _ hW _ hbal + have hb : ∑ i, f (insert (e i) A)*h i = 0 := hbal + have hl := clique_linear_bound (fun i => f (insert (e i) A)) (fun i => W (e i)) h + (fun i => H (insert (e i) A)) (fun i => hf _ (by + rw [ncard_insert_eq A (e i) (heA i)] + simpa using hdegree)) (fun i => hW _) hb + simpa [transportDemand, transportPotential, transportCorrection, slotPunctures, + slotTotal, coeffDerivs, transportEnergy_nil, mul_comm, mul_left_comm, mul_assoc] using hl + | cons p ps ih => + intro κ _ _ _ f H A e h W k hf hSig hdegree he heA hFresh hW hw hbal + obtain ⟨hab,ha,hb,ht⟩ := hFresh + have hFresh' : SlotsFresh (p::ps) (A ∪ Set.range e) := ⟨hab,ha,hb,ht⟩ + obtain ⟨hfa,hfb⟩ := slotsFresh_child e A p ps hFresh' + let sa : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.2 A)) + let sb : κ → ℝ := fun i => slotTotal ps f (insert (e i) (insert p.1 A)) + let u : ℝ := slotTotal ps f (insert p.1 (insert p.2 A)) + let X : ℝ := ∑ i, h i*sa i + let c : ℝ := -X/u + have hpa : p.1 ∉ A := fun h => ha (Or.inl h) + have hpb : p.2 ∉ A := fun h => hb (Or.inl h) + have hdegA : (insert p.2 A).ncard + ps.length + 1 = k := by + rw [ncard_insert_eq A p.2 hpb] + simp only [List.length_cons] at hdegree + omega + have hdegB : (insert p.1 A).ncard + ps.length + 1 = k := by + rw [ncard_insert_eq A p.1 hpa] + simp only [List.length_cons] at hdegree + omega + have hu : 0 < u := slotTotal_degree_positive ps f k hf _ (by + rw [ncard_insert_eq _ p.1 (by simpa using And.intro hab hpa), + ncard_insert_eq A p.2 hpb] + simp only [List.length_cons] at hdegree + omega) + (ht.mono (Set.insert_subset_insert (Set.insert_subset_insert Set.subset_union_left))) + have hb0 : (∑ i, (sa i+sb i)*h i) = 0 := by + simpa only [slotTotal_parent ps f A e p hab ha hb] using hbal + have hXb : (∑ i, h i*sb i) = -X := by + simp only [add_mul, Finset.sum_add_distrib] at hb0 + have ha' : (∑ i, sa i*h i) = X := by dsimp [X]; apply Finset.sum_congr rfl; intro i _; ring + have hb' : (∑ i, sb i*h i) = ∑ i, h i*sb i := by apply Finset.sum_congr rfl; intro i _; ring + rw [ha',hb'] at hb0 + linarith + have hcB : -c = -(∑ i, h i*sb i)/u := by rw [hXb]; dsimp [c]; ring + have hba : ∑ i, slotTotal ps f (insert (appendPoint e p.1 i) (insert p.2 A)) * + extendVector h c i = 0 := by + have hc := child_balance sa h u (ne_of_gt hu) + simp only [Fintype.sum_option, extendVector] at hc + simpa only [Fintype.sum_option, extendVector, appendPoint, sa, u, c, X] using hc + have hbb : ∑ i, slotTotal ps f (insert (appendPoint e p.2 i) (insert p.1 A)) * + extendVector h (-c) i = 0 := by + rw [hcB] + have hc := child_balance sb h u (ne_of_gt hu) + simp only [Fintype.sum_option, extendVector] at hc + simpa only [Fintype.sum_option, extendVector, appendPoint, u, sb, Set.insert_comm p.2 p.1] using hc + have hwa := hw p (List.mem_cons_self ..) + have hwt : ∀ p ∈ ps, W p.1 = W p.2 := fun q hq => hw q (List.mem_cons_of_mem _ hq) + have hla := ih f H (insert p.2 A) (appendPoint e p.1) (extendVector h c) W k + hf hSig hdegA (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hab (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa hW hwt hba + have hlb := ih f H (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W k + hf hSig hdegB (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hab.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb hW hwt hbb + have hsplit := split_bound (pairMatrix (slotTotal ps f) A e) sa sb h u hu + (pairMatrix_symm _ A e) (slot_split_signature_degree f k hf hSig ps A e p he heA hFresh' (by + simp only [List.length_cons] at hdegree + omega)) hb0 + have hcost : 2*X^2/(u*W p.1) ≤ + -(pairMatrix (slotTotal ps f) A e).toBilin' h h / W p.1 := by + simpa only [X, div_div] using div_le_div_of_nonneg_right hsplit (hW p.1).le + have hpot := transportPotential_split ps f A e p h X u W hab ha hb rfl + (ne_of_gt hu) hwa (ne_of_gt (hW p.1)) + have hcN : X/u = -c := by dsimp [c]; ring + rw [hcN] at hpot + change transportPotential ps f (insert p.2 A) (appendPoint e p.1) (extendVector h c) W + + transportPotential ps f (insert p.1 A) (appendPoint e p.2) (extendVector h (-c)) W = _ at hpot + rw [← transportDemand_split ps f H A e p h c hab ha hb, + transportEnergy_cons, transportCorrection_split ps f A e p h c W hab ha hb] + rw [neg_div] at hcost + linarith + + +theorem transport_squared_bound_degree {ι : Type*} [Fintype ι] [DecidableEq ι] [Nonempty ι] (ps : List (Γ × Γ)) + (f H : Set Γ → ℝ) (A : Set Γ) (e : ι → Γ) (h : ι → ℝ) (W : Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hSig : AdditionProperty f k) + (hdegree : A.ncard + ps.length + 1 = k) (he : Function.Injective e) + (heA : ∀ i, e i ∉ A) (hps : SlotsFresh ps (A ∪ Set.range e)) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hbal : ∑ i, slotTotal ps f (insert (e i) A)*h i = 0) + (hC : 0 < transportPotential ps f A e h W - transportCorrection ps f A e h W) : + (transportDemand ps f H A e h)^2 ≤ + (transportPotential ps f A e h W - transportCorrection ps f A e h W) * + transportEnergy ps f H A e W := by + apply squared_le_of_linear_scalings _ _ _ hC + intro t + have hbal' : ∑ i, slotTotal ps f (insert (e i) A)*(t • h) i = 0 := by + simp only [Pi.smul_apply, smul_eq_mul] + simp_rw [mul_left_comm _ t, ← Finset.mul_sum, hbal, mul_zero] + have ht := transport_linear_bound_degree ps f H A e (t • h) W k hf hSig hdegree he heA hps hW hw hbal' + rw [transportDemand_smul,transportPotential_smul,transportCorrection_smul] at ht + nlinarith + + +lemma rootCoefficient_degree_pos (ps : List (Γ × Γ)) (f : Set Γ → ℝ) + (k : ℕ) (hf : DegreePositive f k) (A : Set Γ) (p d : Γ) (W : Γ → ℝ) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hdegree : A.ncard + ps.length + 1 = k) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) (hW : ∀ i, 0 < W i) : + 0 < rootCoefficient ps f A p d W := by + have hfp : SlotsFresh ps (insert p A) := hps.mono (by + rintro x (rfl | hx) + · exact Or.inr ⟨false, rfl⟩ + · exact Or.inl hx) + have hfd : SlotsFresh ps (insert d A) := hps.mono (by + rintro x (rfl | hx) + · exact Or.inr ⟨true, rfl⟩ + · exact Or.inl hx) + have hp := slotTotal_degree_positive ps f k hf (insert p A) (by + rw [ncard_insert_eq A p hpA] + omega) hfp + have hd := slotTotal_degree_positive ps f k hf (insert d A) (by + rw [ncard_insert_eq A d hdA] + omega) hfd + unfold rootCoefficient + apply add_pos_of_pos_of_nonneg + · exact add_pos (one_div_pos.mpr (mul_pos hp (hW p))) + (one_div_pos.mpr (mul_pos hd (hW d))) + · apply mul_nonneg (div_nonneg (by norm_num) (mul_pos hp hd).le) + apply List.sum_nonneg + intro x hx + obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hx + apply div_nonneg _ (hW _).le + have hperm := slotPunctures_perm ps y hy + have hlen := hperm.length_eq + simp only [List.length_cons] at hlen + have hfr := (SlotsFresh.perm hperm _).mp hps + apply (slotTotal_degree_positive y.2 f k hf _ ?_ ?_).le + · rw [ncard_insert_eq _ p (by simpa using And.intro hpd hpA), + ncard_insert_eq A d hdA] + omega + · apply hfr.2.2.2.mono + rintro x (rfl | rfl | hx) + · exact Or.inr (Or.inr (Or.inr ⟨false, rfl⟩)) + · exact Or.inr (Or.inr (Or.inr ⟨true, rfl⟩)) + · exact Or.inr (Or.inr (Or.inl hx)) + +/-- The paper's root transport coefficient and weighted mean difference, +with fixed-degree positivity and addition signatures only. For one-hole +states this is applied to the complement-set weight. -/ +theorem transport_root_bound_degree (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hSig : AdditionProperty f k) + (hdegree : A.ncard + ps.length + 1 = k) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : + (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - + slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ + rootCoefficient ps f A p d W * transportEnergy ps f H A (rootEmbedding p d) W := by + have heA : ∀ i, rootEmbedding p d i ∉ A := by + intro i + cases i <;> assumption + have hfresh : ∀ i, SlotsFresh ps (insert (rootEmbedding p d i) A) := by + intro i + apply hps.mono + rintro x (rfl | hx) + · exact Or.inr ⟨i, rfl⟩ + · exact Or.inl hx + have hsp := slotTotal_degree_positive ps f k hf (insert p A) (by + rw [ncard_insert_eq A p hpA] + omega) (hfresh false) + have hsd := slotTotal_degree_positive ps f k hf (insert d A) (by + rw [ncard_insert_eq A d hdA] + omega) (hfresh true) + let h := rootDemand (slotTotal ps f (insert p A)) (slotTotal ps f (insert d A)) + have hbal : ∑ i, slotTotal ps f (insert (rootEmbedding p d i) A)*h i = 0 := by + simp [h, rootDemand, rootEmbedding, ne_of_gt hsp, ne_of_gt hsd] + have hcoef : transportPotential ps f A (rootEmbedding p d) h W - + transportCorrection ps f A (rootEmbedding p d) h W = rootCoefficient ps f A p d W := by + dsimp [h] + rw [rootPotential ps f A p d W (ne_of_gt hsp) (ne_of_gt hsd), rootCorrection] + simp only [rootCoefficient, sub_neg_eq_add] + have ht := transport_squared_bound_degree ps f H A (rootEmbedding p d) h W k hf hSig + hdegree (rootEmbedding_injective p d hpd) heA hps hW hw hbal (by + rw [hcoef] + exact rootCoefficient_degree_pos ps f k hf A p d W hpd hpA hdA hdegree hps hW) + rw [hcoef] at ht + simpa [transportDemand, h, rootDemand, rootEmbedding, Fintype.sum_bool, div_eq_mul_inv, + mul_comm, sub_eq_add_neg, add_comm] using ht + + +lemma slotVertices_degree (ps : List (Γ × Γ)) : + ∀ {κ : Type*} [Fintype κ] [DecidableEq κ] (A : Set Γ) (e : κ → Γ), + Function.Injective e → (∀ i, e i ∉ A) → SlotsFresh ps (A ∪ Set.range e) → + ∀ S ∈ slotVertices ps A e, S.ncard = A.ncard + ps.length + 1 := by + induction ps with + | nil => + intro κ _ _ A e he heA _ S hS + rw [slotVertices] at hS + obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hS + rw [ncard_insert_eq A (e i) (heA i)] + rfl + | cons p ps ih => + intro κ _ _ A e he heA hslots S hS + obtain ⟨hp, ha, hb, ht⟩ := hslots + have hslots' : SlotsFresh (p :: ps) (A ∪ Set.range e) := ⟨hp, ha, hb, ht⟩ + obtain ⟨hfa, hfb⟩ := slotsFresh_child e A p ps hslots' + rw [slotVertices] at hS + rcases Finset.mem_union.mp hS with hS | hS + · have h := ih (insert p.2 A) (appendPoint e p.1) + (appendPoint_injective e p.1 he (fun h => ha (Or.inr h))) + (appendPoint_fresh e A p.1 p.2 heA hp (fun h => ha (Or.inl h)) + (fun h => hb (Or.inr h))) hfa S hS + rw [ncard_insert_eq A p.2 (fun h => hb (Or.inl h))] at h + simp only [List.length_cons] + omega + · have h := ih (insert p.1 A) (appendPoint e p.2) + (appendPoint_injective e p.2 he (fun h => hb (Or.inr h))) + (appendPoint_fresh e A p.2 p.1 heA hp.symm (fun h => hb (Or.inl h)) + (fun h => ha (Or.inr h))) hfb S hS + rw [ncard_insert_eq A p.1 (fun h => ha (Or.inl h))] at h + simp only [List.length_cons] + omega + +lemma transportEnergy_le_graphEnergy_degree {κ : Type*} [Fintype κ] [DecidableEq κ] + (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) (A : Set Γ) (e : κ → Γ) (W : Γ → ℝ) + (k : ℕ) (hf : DegreePositive f k) (hdegree : A.ncard + ps.length + 1 = k) + (he : Function.Injective e) (heA : ∀ i, e i ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range e)) (hw : ∀ p ∈ ps, W p.1 = W p.2) + (hW : ∀ i, 0 ≤ W i) : + transportEnergy ps f H A e W ≤ slotGraphEnergy ps f H A e W := by + rw [transportEnergy_eq_sum ps f H A e W he heA hps hw] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum_of_subset_of_nonneg + · intro ST hST + apply Finset.mem_filter.mpr + exact ⟨Finset.mem_product.mpr (transportEdges_states ps A e ST hST), + transportEdges_adjacent ps A e he heA hps ST hST⟩ + · intro ST hST _ + obtain ⟨hs, ht⟩ := Finset.mem_product.mp (Finset.mem_filter.mp hST).1 + have hsdeg : ST.1.ncard = k := (slotVertices_degree ps A e he heA hps ST.1 hs).trans hdegree + have htdeg : ST.2.ncard = k := (slotVertices_degree ps A e he heA hps ST.2 ht).trans hdegree + apply mul_nonneg _ (sq_nonneg _) + exact le_min (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.1) (hf _ hsdeg).le) + (mul_nonneg (missingMultiplier_nonneg ps e W hW ST.2) (hf _ htdeg).le) + +/-- Full one-hole transport on the actual exchange graph with the exact +minimum-endpoint conductances and unordered-edge convention. -/ +theorem transport_graph_bound_degree (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (k : ℕ) + (hf : DegreePositive f k) (hSig : AdditionProperty f k) + (hdegree : A.ncard + ps.length + 1 = k) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : + (slotTotal ps (fun S => f S*H S) (insert p A) / slotTotal ps f (insert p A) - + slotTotal ps (fun S => f S*H S) (insert d A) / slotTotal ps f (insert d A))^2 ≤ + rootCoefficient ps f A p d W * slotGraphEnergy ps f H A (rootEmbedding p d) W := by + apply (transport_root_bound_degree ps f H A p d W k hf hSig hdegree hpd hpA hdA hps hW hw).trans + apply mul_le_mul_of_nonneg_left _ + (rootCoefficient_degree_pos ps f k hf A p d W hpd hpA hdA hdegree hps hW).le + apply transportEnergy_le_graphEnergy_degree ps f H A (rootEmbedding p d) W k hf hdegree + (rootEmbedding_injective p d hpd) _ hps hw (fun i => (hW i).le) + intro i + cases i <;> assumption + + +/-- The one-hole statement in the paper's omission convention. An encoded +set is the complement of the original table-lift state, so the multiplier +marks its unique hole slot. -/ +theorem one_hole_transport (ps : List (Γ × Γ)) (f H : Set Γ → ℝ) + (A : Set Γ) (p d : Γ) (W : Γ → ℝ) (k : ℕ) + (hk : k ≤ Fintype.card Γ) (hf : DegreePositive f k) (hSig : OmissionProperty f k) + (hdegree : A.ncard + ps.length + 1 = Fintype.card Γ - k) + (hpd : p ≠ d) (hpA : p ∉ A) (hdA : d ∉ A) + (hps : SlotsFresh ps (A ∪ Set.range (rootEmbedding p d))) + (hW : ∀ i, 0 < W i) (hw : ∀ p ∈ ps, W p.1 = W p.2) : + let fc := complementWeight f + let Hc := complementWeight H + (slotTotal ps (fun S => fc S * Hc S) (insert p A) / slotTotal ps fc (insert p A) - + slotTotal ps (fun S => fc S * Hc S) (insert d A) / slotTotal ps fc (insert d A)) ^ 2 ≤ + rootCoefficient ps fc A p d W * slotGraphEnergy ps fc Hc A (rootEmbedding p d) W := by + exact transport_graph_bound_degree ps (complementWeight f) (complementWeight H) A p d W + (Fintype.card Γ - k) (complement_degreePositive f k hk hf) hSig hdegree + hpd hpA hdA hps hW hw + +end ContingencyTables.RecursiveSignedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBlock.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBlock.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba2abb096ad576653139bce381a2603d94d614a3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBlock.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalResidualMargins +import OAI.Combinatorics.ContingencyTables.Transport.TableReindex +import Mathlib.Logic.Equiv.Option + +namespace OAI + +/-! # Fixed reference row and column for the physical completion blocks -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev LargeRows (r : I → ℕ) (U : ℕ) := {i // U ≤ r i} +abbrev LargeColumns (c : J → ℕ) (U : ℕ) := {j // U ≤ c j} + +noncomputable def referenceRows (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (i : Option {i : LargeRows r U // i ≠ i₀}) : ℕ := + residualRows (firstPaperSmall r c U) B r c L z ((Equiv.optionSubtypeNe i₀) i).val + +noncomputable def referenceColumns (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (j₀ : LargeColumns c U) (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (j : Option {j : LargeColumns c U // j ≠ j₀}) : ℕ := + residualColumns (firstPaperSmall r c U) B r c L z ((Equiv.optionSubtypeNe j₀) j).val + +lemma reference_totals (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) : + (∑ i,referenceRows r c U L B i₀ z i)=∑ j,referenceColumns r c U L B j₀ z j := by + unfold referenceRows referenceColumns + rw [(Equiv.optionSubtypeNe i₀).sum_comp + (fun i : LargeRows r U => residualRows (firstPaperSmall r c U) B r c L z i.val), + (Equiv.optionSubtypeNe j₀).sum_comp + (fun j : LargeColumns c U => residualColumns (firstPaperSmall r c U) B r c L z j.val)] + have hr : (∑ i : LargeRows r U,residualRows (firstPaperSmall r c U) B r c L z i.val)= + ∑ i,residualRows (firstPaperSmall r c U) B r c L z i := by + convert sum_subtype_eq_of_zero (fun i => U ≤ r i) + (residualRows (firstPaperSmall r c U) B r c L z) + (physical_residual_row_zero r c U L B z hcap) using 1 + congr 2 + exact Subsingleton.elim _ _ + have hc : (∑ j : LargeColumns c U,residualColumns (firstPaperSmall r c U) B r c L z j.val)= + ∑ j,residualColumns (firstPaperSmall r c U) B r c L z j := by + convert sum_subtype_eq_of_zero (fun j => U ≤ c j) + (residualColumns (firstPaperSmall r c U) B r c L z) + (physical_residual_column_zero r c U L B z hcap) using 1 + congr 2 + exact Subsingleton.elim _ _ + rw [hr,hc] + exact physical_residual_totals _ B r c L z hcap + +/-- A single pair of reference indices, fixed independently of the state, +reindexes every actual completion block and retains its exact count. -/ +theorem physical_weight_reference_block (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k) ≤ B i j) : + hardMarginal (firstPaperSmall r c U) B r c L (physicalProfile _ B r c L z)= + (Fintype.card (Table (referenceRows r c U L B i₀ z) (referenceColumns r c U L B j₀ z)):ℝ) := by + rw [physical_weight_rectangle r c U L B z hcap] + convert congrArg (fun n : ℕ => (n:ℝ)) (Fintype.card_congr + (tableReindex (Equiv.optionSubtypeNe i₀) (Equiv.optionSubtypeNe j₀) + (fun i : LargeRows r U => residualRows (firstPaperSmall r c U) B r c L z i.val) + (fun j : LargeColumns c U => residualColumns (firstPaperSmall r c U) B r c L z j.val))) using 1 + all_goals congr 3 + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd0a5dae5326ba11a09ddf2bfa8a8e5f5111fdf2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionBounds.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBlock + +namespace OAI + +/-! # Padding and dimension bounds for the actual reference completion block -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma large_row_padding (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (i : LargeRows r U) (j : LargeColumns c U) : + L ≤ residualRows (firstPaperSmall r c U) B r c L z i.val := by + have hs := (firstPaperSmall_false_iff r c U i.val j.val).mpr ⟨i.property,j.property⟩ + have hh := Finset.single_le_sum + (f := fun j' => if firstPaperSmall r c U i.val j' then 0 else 1) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ j.val) + have hc : 1 ≤ rowLargeCount (firstPaperSmall r c U) i.val := by + simpa only [rowLargeCount,hs,Bool.false_eq_true,ite_false] using hh + unfold residualRows + nlinarith + +lemma large_column_padding (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (i : LargeRows r U) (j : LargeColumns c U) : + L ≤ residualColumns (firstPaperSmall r c U) B r c L z j.val := by + have hs := (firstPaperSmall_false_iff r c U i.val j.val).mpr ⟨i.property,j.property⟩ + have hh := Finset.single_le_sum + (f := fun i' => if firstPaperSmall r c U i' j.val then 0 else 1) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ i.val) + have hc : 1 ≤ columnLargeCount (firstPaperSmall r c U) j.val := by + simpa only [columnLargeCount,hs,Bool.false_eq_true,ite_false] using hh + unfold residualColumns + nlinarith + +lemma reference_row_padding (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (i : Option {i : LargeRows r U // i≠i₀}) : L ≤ referenceRows r c U L B i₀ z i := + large_row_padding r c U L B z ((Equiv.optionSubtypeNe i₀) i) j₀ + +lemma reference_column_padding (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (j : Option {j : LargeColumns c U // j≠j₀}) : L ≤ referenceColumns r c U L B j₀ z j := + large_column_padding r c U L B z i₀ ((Equiv.optionSubtypeNe j₀) j) + +lemma reference_block_dimensions (r : I → ℕ) (c : J → ℕ) (U : ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) : + Fintype.card (Option {i : LargeRows r U // i≠i₀}) ≤ dimensionAllowance (I := I) (J := J) ∧ + Fintype.card (Option {j : LargeColumns c U // j≠j₀}) ≤ dimensionAllowance (I := I) (J := J) ∧ + Fintype.card {i : LargeRows r U // i≠i₀}+Fintype.card {j : LargeColumns c U // j≠j₀}+1 ≤ + dimensionAllowance (I := I) (J := J) := by + have hri := Fintype.card_congr (Equiv.optionSubtypeNe i₀) + have hcj := Fintype.card_congr (Equiv.optionSubtypeNe j₀) + have hr : Fintype.card (LargeRows r U) ≤ Fintype.card I := Fintype.card_subtype_le _ + have hc : Fintype.card (LargeColumns c U) ≤ Fintype.card J := Fintype.card_subtype_le _ + rw [Fintype.card_option] at hri hcj + simp only [Fintype.card_option] + unfold dimensionAllowance + constructor + · nlinarith + constructor <;> nlinarith + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionEntries.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionEntries.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c0c8baf7f1449309f75a7ffde473f9f5664bf2c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceCompletionEntries.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreEquiv + +namespace OAI + +/-! # Literal matrix entries of the completion coordinate equivalences -/ + +namespace ContingencyTables.SmallGraphProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open FirstPaperProfiles SmallContextCoordinates SmallContextFibres +open scoped BigOperators Classical + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +theorem referenceFibreEquiv_entry (r : I → ℕ) (c : J → ℕ) (U L : ℕ) (B : I → J → ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (z : PhysicalStates (firstPaperSmall r c U) B r c L) + (hcap : ∀ i j,firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c L z k)≤B i j) + (A : CompletionFibre (firstPaperSmall r c U) B r + (fun i => r i+rowLargeCount (firstPaperSmall r c U) i*L) c + (fun j => c j+columnLargeCount (firstPaperSmall r c U) j*L) + (physicalProfile _ B r c L z)) + (i : Option {i : LargeRows r U // i≠i₀}) (j : Option {j : LargeColumns c U // j≠j₀}) : + (referenceFibreEquiv r c U L B i₀ j₀ z hcap A).val i j= + A.val.val.1 ((Equiv.optionSubtypeNe i₀ i).val) ((Equiv.optionSubtypeNe j₀ j).val) := by + change (fibreLargeEquiv (firstPaperSmall r c U) B r c L + (physicalProfile _ B r c L z) (naturalProfile_bounded z.val.val) + (physical_original_residuals _ B r c L z hcap) hcap A).val.val + (Equiv.optionSubtypeNe i₀ i).val (Equiv.optionSubtypeNe j₀ j).val=_ + have he := fibreLargeEquiv_apply (firstPaperSmall r c U) B r c L + (physicalProfile _ B r c L z) (naturalProfile_bounded z.val.val) + (physical_original_residuals _ B r c L z hcap) hcap A + (Equiv.optionSubtypeNe i₀ i).val (Equiv.optionSubtypeNe j₀ j).val + have hs : firstPaperSmall r c U (Equiv.optionSubtypeNe i₀ i).val + (Equiv.optionSubtypeNe j₀ j).val=false := + (firstPaperSmall_false_iff r c U _ _).mpr + ⟨(Equiv.optionSubtypeNe i₀ i).property,(Equiv.optionSubtypeNe j₀ j).property⟩ + simpa only [hs,Bool.false_eq_true,ite_false,rectangleCompletionEquiv,rectangleRestrict] using he + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceDrawBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceDrawBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..58f9fce78dd13ecdd4a7f7a5287166b17999d94d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceDrawBounds.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallMixing + +namespace OAI + +/-! # Uniform size bounds for the state-dependent dense completion call -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma reference_free_dimension (r : I → ℕ) (c : J → ℕ) (U : ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) : + Fintype.card ({i : LargeRows r U // i≠i₀} × {j : LargeColumns c U // j≠j₀}) ≤ + dimensionAllowance (I := I) (J := J) := by + have hr : Fintype.card {i : LargeRows r U // i≠i₀} ≤ Fintype.card I := + (Fintype.card_subtype_le _).trans (Fintype.card_subtype_le _) + have hc : Fintype.card {j : LargeColumns c U // j≠j₀} ≤ Fintype.card J := + (Fintype.card_subtype_le _).trans (Fintype.card_subtype_le _) + rw [Fintype.card_prod] + exact (Nat.mul_le_mul hr hc).trans dimension_le_allowance + +omit [LinearOrder I] [LinearOrder J] in +lemma reference_dimension_fourteen (r : I → ℕ) (c : J → ℕ) (U : ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) : + 14 ≤ dimensionAllowance (I := I) (J := J) := by + have hr : 0 < Fintype.card I := Fintype.card_pos_iff.mpr ⟨i₀.val⟩ + have hc : 0 < Fintype.card J := Fintype.card_pos_iff.mpr ⟨j₀.val⟩ + unfold dimensionAllowance + nlinarith + +lemma reference_row_le_stateBound (r : I → ℕ) (c : J → ℕ) + (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) + (z : PaperStates r c) (i : Option {i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀}) : + referenceRows r c _ _ (stateCapacity r c) i₀ z i ≤ stateBound r c := by + let k := ((Equiv.optionSubtypeNe i₀) i).val + have hr : r k ≤ ∑ a,r a := Finset.single_le_sum (f := r) (fun _ _ => Nat.zero_le _) (Finset.mem_univ k) + have hcount : rowLargeCount (paperSmall r c) k ≤ Fintype.card J := by + unfold rowLargeCount + calc + _ ≤ ∑ _j : J,(1:ℕ) := Finset.sum_le_sum (fun j _ => by split_ifs <;> omega) + _ = _ := by simp + have hdim : Fintype.card J ≤ dimensionAllowance (I := I) (J := J) := by + unfold dimensionAllowance + nlinarith + have hm := Nat.mul_le_mul_right ((dimensionAllowance (I := I) (J := J))^12) (hcount.trans hdim) + have hs := Nat.sub_le (r k) + (smallRow (paperSmall r c) (FirstPaperProfiles.smallView (paperSmall r c) + (physicalProfile _ (stateCapacity r c) r c _ z) false) k) + unfold referenceRows residualRows stateBound + change r k-_+rowLargeCount (paperSmall r c) k*((dimensionAllowance (I := I) (J := J))^12) ≤ _ + omega + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceEdgeAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceEdgeAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..8626f28bfa5cb812133a9e2d230ba391cf60763f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceEdgeAcceptance.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalEdgeMargins +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBounds +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCompletionAcceptance +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionCounts + +namespace OAI + +/-! # Half of every physical completion block accepts an adjacent translation -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open CompletionTranslation + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +omit [LinearOrder I] [LinearOrder J] in +lemma reference_dimension_ge_fourteen (r : I → ℕ) (c : J → ℕ) (U : ℕ) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) : + 14 ≤ dimensionAllowance (I := I) (J := J) := by + have hi : 0 < Fintype.card I := Fintype.card_pos_iff.mpr ⟨i₀.val⟩ + have hj : 0 < Fintype.card J := Fintype.card_pos_iff.mpr ⟨j₀.val⟩ + unfold dimensionAllowance + nlinarith + +theorem reference_edge_acceptance (r : I → ℕ) (c : J → ℕ) (U : ℕ) + (B : I → J → ℕ) + (hB : ∀ i j,firstPaperSmall r c U i j=true → B i j=U) + (i₀ : LargeRows r U) (j₀ : LargeColumns c U) + (hcap : ∀ z : PhysicalStates (firstPaperSmall r c U) B r c + ((dimensionAllowance (I := I) (J := J))^12),∀ i j, + firstPaperSmall r c U i j=false → + (∑ k,residualRows (firstPaperSmall r c U) B r c _ z k) ≤ B i j) + (x y : PhysicalStates (firstPaperSmall r c U) B r c + ((dimensionAllowance (I := I) (J := J))^12)) + (hxy : physicalAdjacent r c U _ B hB x y) : + (blockCount (referenceRows r c U _ B i₀) (referenceColumns r c U _ B j₀) x:ℝ)/2 ≤ + acceptedCount (referenceRows r c U _ B i₀) (referenceColumns r c U _ B j₀) x y := by + let d := dimensionAllowance (I := I) (J := J) + let R := referenceRows r c U (d^12) B i₀ + let P := referenceColumns r c U (d^12) B j₀ + have hm := physical_edge_residual_margins r c U (d^12) B hB hcap x y hxy + have hr (i) : |(R y i:ℤ)-R x i| ≤ 2 := hm.1 ((Equiv.optionSubtypeNe i₀) i).val + have hp (j) : |(P y j:ℤ)-P x j| ≤ 2 := hm.2 ((Equiv.optionSubtypeNe j₀) j).val + have hd := reference_block_dimensions r c U i₀ j₀ + have hD (i j) : |between (R x) (R y) (P x) (P y) i j| ≤ (10*d:ℕ) := by + have hs := star_abs_le (fun i => (R y i:ℤ)-R x i) + (fun j => (P y j:ℤ)-P x j) 2 (by norm_num) hr hp i j + have hc : (Fintype.card {j : LargeColumns c U // j≠j₀}:ℤ)+1 ≤ d := by + exact_mod_cast (show Fintype.card {j : LargeColumns c U // j≠j₀}+1 ≤ d by + simpa only [Fintype.card_option] using hd.2.1) + change |star _ _ i j| ≤ _ + push_cast + nlinarith + exact reference_acceptance_half (R x) (P x) (between (R x) (R y) (P x) (P y)) + (reference_totals r c U (d^12) B i₀ j₀ x (hcap x)) (fun _ _ => rfl) + d (reference_dimension_ge_fourteen r c U i₀ j₀) hd.1 hd.2.1 hd.2.2 + (reference_row_padding r c U (d^12) B i₀ j₀ x) + (reference_column_padding r c U (d^12) B i₀ j₀ x) hD + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceFiniteDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceFiniteDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..4aa5ce9332f428820fa21a5a6c782ef057aaa541 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReferenceFiniteDraw.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperJointLaw +import OAI.Combinatorics.ContingencyTables.Transport.ReferenceDrawBounds +import OAI.Combinatorics.ContingencyTables.Dense.DenseMaximalReindex +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding + +namespace OAI + +/-! # A finite Boolean draw of the actual state-dependent completion fibre -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal CompletionCounts PaddedCompletions +open ResidualMixture FirstSuccess GridBoundary FairBits + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] +variable (r : I → ℕ) (c : J → ℕ) +variable (i₀ : LargeRows r ((dimensionAllowance (I := I) (J := J))^20)) +variable (j₀ : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20)) +variable {q : ℕ} +variable (e : ({i : LargeRows r ((dimensionAllowance (I := I) (J := J))^20) // i≠i₀} × + {j : LargeColumns c ((dimensionAllowance (I := I) (J := J))^20) // j≠j₀}) ≃ Fin q) + +local notation "d" => dimensionAllowance (I := I) (J := J) +local notation "R" => referenceRows r c (d^20) (d^12) (stateCapacity r c) i₀ +local notation "P" => referenceColumns r c (d^20) (d^12) (stateCapacity r c) j₀ + +abbrev paperReferenceEquiv (z : PaperStates r c) : PaperFibre r c z ≃ Table (R z) (P z) := + referenceFibreEquiv r c _ _ (stateCapacity r c) i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z) + +abbrev completionDrawBits (h : ℕ) (z : PaperStates r c) := + reindexedDrawBits (R z) (P z) d e h + +def completionBooleanDraw (h : ℕ) (a : Grid (I := Fin q) (4*d^8)) + (z : PaperStates r c) (fallback : PaperFibre r c z) + (bits : Fin (completionDrawBits r c i₀ j₀ e h z) → Bool) : PaperFibre r c z := + (paperReferenceEquiv r c i₀ j₀ z).symm + (reindexedBooleanDraw (R z) (P z) d (reference_dimension_fourteen r c _ i₀ j₀) + (reference_row_padding r c _ _ _ i₀ j₀ z) + (reference_column_padding r c _ _ _ i₀ j₀ z) e + (reference_totals r c _ _ _ i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z)) h a + (paperReferenceEquiv r c i₀ j₀ z fallback) bits) + +/-- The output is a genuine completion of the current retained profile +on every bit word; the distance bound is uniform in that state. -/ +theorem completionBooleanDraw_variation + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4*d^8))) + (h : ℕ) (a : Grid (I := Fin q) (4*d^8)) + (z : PaperStates r c) (fallback : PaperFibre r c z) : + (variation (mapLaw (uniformLaw (α := Fin (completionDrawBits r c i₀ j₀ e h z) → Bool)) + (completionBooleanDraw r c i₀ j₀ e h a z fallback)) + (uniformLaw (α := PaperFibre r c z)):ℝ) ≤ (2:ℝ)^(-(h:ℝ)) := by + let E := paperReferenceEquiv r c i₀ j₀ z + let : Nonempty (Table (R z) (P z)) := ⟨E fallback⟩ + have hh := reindexedBooleanDraw_variation (R z) (P z) d + (reference_dimension_fourteen r c _ i₀ j₀) + (reference_row_padding r c _ _ _ i₀ j₀ z) + (reference_column_padding r c _ _ _ i₀ j₀ z) + (reference_block_dimensions r c _ i₀ j₀).1 + (reference_block_dimensions r c _ i₀ j₀).2.1 + (reference_free_dimension r c _ i₀ j₀) + (reference_totals r c _ _ _ i₀ j₀ z + (physical_paper_capacity _ r c _ _ _ dimension_le_allowance z)) + e hPL hCheeger h a (E fallback) + unfold completionBooleanDraw + rw [mapLaw_equiv_output] + change (variation (equivLaw E.symm _) (uniformLaw (α := PaperFibre r c z)):ℝ) ≤ _ + rw [←uniform_equiv E.symm,variation_equiv] + exact hh + +lemma completionDrawBits_le (b h : ℕ) + (hb : Nat.clog 2 (stateBound r c+2) ≤ b) (z : PaperStates r c) : + completionDrawBits r c i₀ j₀ e h z ≤ 25*(d+b+h+1)^62 := by + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + rw [←hc] + exact reference_free_dimension r c _ i₀ j₀ + exact reindexedDrawBits_polynomial (R z) (P z) d (stateBound r c) b h e hq + (reference_row_le_stateBound r c i₀ z) hb + +/-- One common reserved word works at every state, despite the different +residual margins and quotient lengths. -/ +def completionPaddedDraw (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (a : Grid (I := Fin q) (4*d^8)) (z : PaperStates r c) (fallback : PaperFibre r c z) + (bits : Fin (25*(d+b+h+1)^62) → Bool) : PaperFibre r c z := + completionBooleanDraw r c i₀ j₀ e h a z fallback + (prefixWord (completionDrawBits_le r c i₀ j₀ e b h hb z) bits) + +theorem completionPaddedDraw_law (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2) ≤ b) + (a : Grid (I := Fin q) (4*d^8)) (z : PaperStates r c) (fallback : PaperFibre r c z) : + mapLaw (uniformLaw (α := Fin (25*(d+b+h+1)^62) → Bool)) + (completionPaddedDraw r c i₀ j₀ e b h hb a z fallback)= + mapLaw (uniformLaw (α := Fin (completionDrawBits r c i₀ j₀ e h z) → Bool)) + (completionBooleanDraw r c i₀ j₀ e h a z fallback) := by + unfold completionPaddedDraw + exact padded_draw_law (completionDrawBits_le r c i₀ j₀ e b h hb z) + (completionBooleanDraw r c i₀ j₀ e h a z fallback) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedNested.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedNested.lean new file mode 100644 index 0000000000000000000000000000000000000000..32cbe839fb3399d298a8ab40919178f9a8459732 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedNested.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ReflectedSlices +import OAI.Combinatorics.ContingencyTables.Transport.NestedPenaltyApplication + +namespace OAI + +/-! +# Both literal factorial lifts of the first paper's nested marginal + +Reflection changes the affine offsets and signs in the full-line and +small-subset penalties. The same actual positive nested factors therefore +prove the complementary lift's addition property, including its hard limit. +-/ + +namespace ContingencyTables.ReflectedNested + +open scoped BigOperators Classical Matrix Topology +open Filter CommonBasesFPRAS FactorialSignatures ProductIntegerSignature +open NestedProductSignature NestedPenaltyApplication IntegerReflection +open BalancedBox BalancedFamily LabelledFactorial ReflectedSlices + +variable {C G : Type*} [Fintype C] [Fintype G] + +omit [Fintype G] in +lemma smallTotal_reflect_add (line : C → G) (inner : C → Bool) (m z : C → ℕ) + (hz : InBox m z) (g : G) : + smallTotal line inner (reflect m z) g+smallTotal line inner z g=smallTotal line inner m g := + lineTotal_reflect_add (fun i => (line i,inner i)) m z hz (g,true) + +theorem softWeight_reflect (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (m z : C → ℕ) (hz : InBox m z) : + softWeight line inner offset slope smallOffset smallSlope L (reflect m z) = + softWeight line inner + (fun g => offset g+(lineTotal line m g:ℝ)*slope g) (fun g => -slope g) + (fun g => smallOffset g+(smallTotal line inner m g:ℝ)*smallSlope g) + (fun g => -smallSlope g) L z := by + unfold softWeight nestedWeight ScalarPenalty.factor + congr 1 + · apply Finset.prod_congr rfl + intro g _ + dsimp only + rw [affine_reflect (offset g) (slope g) _ _ _ (lineTotal_reflect_add line m z hz g)] + · apply Finset.prod_congr rfl + intro g _ + dsimp only + rw [affine_reflect (smallOffset g) (smallSlope g) _ _ _ (smallTotal_reflect_add line inner m z hz g)] + +theorem reflected_soft_removal (line : C → G) (inner : C → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0 ≤ L) + (m z : C → ℕ) (hz : InBox m z) : + OnePositiveDirection (integerRemovalMatrix + (fun x => softWeight line inner offset slope smallOffset smallSlope L (reflect m x)) z).toBilin' := by + rw [removal_congr_box _ _ m z hz (fun x hx => softWeight_reflect line inner offset slope smallOffset smallSlope L m x hx)] + exact softWeight_removal line inner + (fun g => offset g+(lineTotal line m g:ℝ)*slope g) (fun g => -slope g) + (fun g => smallOffset g+(smallTotal line inner m g:ℝ)*smallSlope g) + (fun g => -smallSlope g) L hL z + +variable {I : Type*} [Fintype I] + +theorem reflected_soft_marginal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0 ≤ L) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + RemovalSlice (fun z => eliminate Ms + (softWeight line inner offset slope smallOffset smallSlope L) (reflect m z)) m R := by + let F := softWeight line inner offset slope smallOffset smallSlope L + have hp : PositiveSlice (fun x => F (reflect (bounds m Ms) x)) (bounds m Ms) (R+Ms.sum) := by + intro x _ _ + exact softWeight_positive line inner offset slope smallOffset smallSlope L _ + have hs : RemovalSlice (fun x => F (reflect (bounds m Ms) x)) (bounds m Ms) (R+Ms.sum) := by + intro x hx _ + convert reflected_soft_removal line inner offset slope smallOffset smallSlope L hL (bounds m Ms) x hx using 1 + congr 2 <;> exact Subsingleton.elim _ _ + have h := (eliminate_slices Ms m R _ hwidth hp hs).2 + have he : eliminate Ms (fun x => F (reflect (bounds m Ms) x)) = + fun z => eliminate Ms F (reflect m z) := by + funext z + exact eliminate_reflect Ms m F z + rwa [he] at h + +theorem reflected_hard_marginal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + RemovalSlice (fun z => eliminate Ms + (hardWeight line inner offset slope smallOffset smallSlope) (reflect m z)) m R := by + intro z hz ht + apply IntegerMarginal.removal_signature_limit (l := (atTop : Filter ℝ)) + (fun L x => eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L) (reflect m x)) + (fun x => eliminate Ms (hardWeight line inner offset slope smallOffset smallSlope) (reflect m x)) z + · intro x + exact eliminate_tendsto Ms _ _ + (softWeight_tendsto line inner offset slope smallOffset smallSlope) (reflect m x) + · filter_upwards [eventually_ge_atTop (0:ℝ)] with L hL + exact reflected_soft_marginal Ms m R line inner offset slope smallOffset smallSlope L hL hwidth z hz ht + +/-- Both actual positive factorial lifts have their original manuscript +degree and signature conventions, derived from the explicit penalties. -/ +theorem softened_twoLift_data {A : Type*} [Fintype A] (group : A → I) + (Ms : List ℕ) (R : ℕ) (hR : R ≤ Fintype.card A) (D : ℝ) (hD : 0 < D) + (line : Coordinates I Ms → G) (inner : Coordinates I Ms → Bool) + (offset slope smallOffset smallSlope : G → ℝ) (L : ℝ) (hL : 0 ≤ L) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) : + let h := eliminate Ms (softWeight line inner offset slope smallOffset smallSlope L) + BinaryContraction.DegreePositive (firstLift group h D) R ∧ + BinaryContraction.OmissionProperty (firstLift group h D) R ∧ + BinaryContraction.AdditionProperty (secondLift group h D) R := by + have hf := softened_firstLift_data group Ms R D hD line inner offset slope smallOffset smallSlope L hL hwidth + refine ⟨hf.1,hf.2,?_⟩ + apply secondLift_addition_reflected_slice group _ D R hR hD + · intro z + exact eliminate_nonnegative Ms _ (fun x => (softWeight_positive line inner offset slope smallOffset smallSlope L x).le) z + · exact reflected_soft_marginal Ms (groupCount group Set.univ) (Fintype.card A-R) + line inner offset slope smallOffset smallSlope L hL hwidth + +end ContingencyTables.ReflectedNested + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedSlices.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedSlices.lean new file mode 100644 index 0000000000000000000000000000000000000000..90235319fc2f77369c7c406d1a575dcc08c01ed8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ReflectedSlices.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EqualitySoftening +import OAI.Combinatorics.ContingencyTables.Transport.SliceFactorial +import OAI.Combinatorics.ContingencyTables.Transport.IntegerBoxTruncation + +namespace OAI + +/-! +# Reflected actual penalties and the complementary factorial lift + +Reflecting a physical box changes affine offsets and reverses their +slopes. The root/equality and unary interval factors therefore have the +same proved scalar signatures. All finite balanced pairs are reflected +as well, before transferring the resulting addition signature to labels. +-/ + +namespace ContingencyTables.ReflectedSlices + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures ProductIntegerSignature +open IntegerReflection EqualitySoftening BalancedBox BalancedFamily LabelledFactorial + +variable {C G : Type*} [Fintype C] [Fintype G] + +omit [Fintype G] in +lemma lineTotal_reflect_add (line : C → G) (m z : C → ℕ) (hz : InBox m z) (g : G) : + lineTotal line (reflect m z) g+lineTotal line z g=lineTotal line m g := by + unfold lineTotal reflect + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + by_cases hi : line i=g + · simp only [hi,ite_true] + exact Nat.sub_add_cancel (hz i) + · simp only [hi,ite_false,add_zero] + +lemma affine_reflect (a slope : ℝ) (M r n : ℕ) (h : r+n=M) : + a+(r:ℝ)*slope=(a+(M:ℝ)*slope)+(n:ℝ)*(-slope) := by + have hh : (r:ℝ)+(n:ℝ)=M := by exact_mod_cast h + rw [← hh] + ring + +theorem softenedWeight_reflect (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) + (m z : C → ℕ) (hz : InBox m z) : + softenedWeight line root rate offset slope urate ell uslope cap L (reflect m z) = + softenedWeight line root rate + (fun g => offset g+(lineTotal line m g:ℝ)*slope g) (fun g => -slope g) + urate (fun i => ell i+(m i:ℝ)*uslope i) (fun i => -uslope i) cap L z := by + unfold softenedWeight productWeight + congr 1 + · apply Finset.prod_congr rfl + intro g _ + unfold lineFactor ScalarPenalty.factor + dsimp only + rw [affine_reflect (offset g) (slope g) _ _ _ (lineTotal_reflect_add line m z hz g)] + · apply Finset.prod_congr rfl + intro i _ + unfold unaryFactor ScalarPenalty.factor affineDistance reflect + dsimp only + rw [affine_reflect (ell i) (uslope i) (m i) (m i-z i) (z i) (Nat.sub_add_cancel (hz i))] + +omit [Fintype G] [Fintype C] in +lemma removal_congr_box (f h : (C → ℕ) → ℝ) (m z : C → ℕ) (hz : InBox m z) + (heq : ∀ x, InBox m x → f x=h x) : integerRemovalMatrix f z=integerRemovalMatrix h z := by + ext i j + unfold integerRemovalMatrix + split_ifs with hv + · exact heq _ (IntegerBoxTruncation.removal_inBox m z hz i j) + · rfl + +/-- The original globally reflected positive weight has its raw removal +signature throughout the physical box, from explicit reflected factors. -/ +theorem reflected_softened_removal (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) + (hrate : ∀ g, 0 ≤ rate g) (hu : ∀ i, 0 ≤ urate i) (hL : 0 ≤ L) + (m z : C → ℕ) (hz : InBox m z) : + OnePositiveDirection (integerRemovalMatrix + (fun x => softenedWeight line root rate offset slope urate ell uslope cap L (reflect m x)) z).toBilin' := by + rw [removal_congr_box _ _ m z hz (fun x hx => softenedWeight_reflect line root rate offset slope + urate ell uslope cap L m x hx)] + exact softenedWeight_removal line root rate + (fun g => offset g+(lineTotal line m g:ℝ)*slope g) (fun g => -slope g) + urate (fun i => ell i+(m i:ℝ)*uslope i) (fun i => -uslope i) cap L hrate hu hL z + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- The companion's actual positive finite marginal has the reflected +removal signature needed for its two-addition matrix. -/ +theorem reflected_softened_marginal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (root : G → Bool) (rate offset slope : G → ℝ) + (urate ell uslope cap : Coordinates I Ms → ℝ) (L : ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) (hrate : ∀ g, 0 ≤ rate g) + (hu : ∀ i, 0 ≤ urate i) (hL : 0 ≤ L) : + RemovalSlice + (fun z => eliminate Ms (softenedWeight line root rate offset slope urate ell uslope cap L) + (reflect m z)) m R := by + let F := softenedWeight line root rate offset slope urate ell uslope cap L + have hp : PositiveSlice (fun x => F (reflect (bounds m Ms) x)) (bounds m Ms) (R+Ms.sum) := by + intro x _ _ + exact softenedWeight_positive line root rate offset slope urate ell uslope cap L _ + have hs : RemovalSlice (fun x => F (reflect (bounds m Ms) x)) (bounds m Ms) (R+Ms.sum) := by + intro x hx _ + convert reflected_softened_removal line root rate offset slope urate ell uslope cap L + hrate hu hL (bounds m Ms) x hx using 1 + congr 2 <;> exact Subsingleton.elim _ _ + have h := (eliminate_slices Ms m R _ hwidth hp hs).2 + have he : eliminate Ms (fun x => F (reflect (bounds m Ms) x)) = + fun z => eliminate Ms F (reflect m z) := by + funext z + exact eliminate_reflect Ms m F z + rwa [he] at h + +/-- The reflected addition input survives the nonroot-equality limit +after all balanced large-cell sums, exactly as the removal input does. -/ +theorem reflected_exact_marginal (Ms : List ℕ) (m : I → ℕ) (R : ℕ) + (line : Coordinates I Ms → G) (root : G → Bool) (rate offset slope : G → ℝ) + (urate ell uslope cap : Coordinates I Ms → ℝ) + (hwidth : ∀ M ∈ Ms, 2 ≤ M) (hrate : ∀ g, 0 ≤ rate g) (hu : ∀ i, 0 ≤ urate i) : + RemovalSlice + (fun z => eliminate Ms (exactWeight line root rate offset slope urate ell uslope cap) + (reflect m z)) m R := by + intro z hz ht + apply IntegerMarginal.removal_signature_limit (l := (Filter.atTop : Filter ℝ)) + (fun L x => eliminate Ms (softenedWeight line root rate offset slope urate ell uslope cap L) + (reflect m x)) + (fun x => eliminate Ms (exactWeight line root rate offset slope urate ell uslope cap) + (reflect m x)) z + · intro x + exact eliminate_tendsto Ms _ _ + (softenedWeight_tendsto line root rate offset slope urate ell uslope cap) (reflect m x) + · filter_upwards [Filter.eventually_ge_atTop (0:ℝ)] with L hL + exact reflected_softened_marginal Ms m R line root rate offset slope urate ell uslope cap L + hwidth hrate hu hL z hz ht + +variable {A : Type*} [Fintype A] + +omit [Fintype I] [DecidableEq I] [Fintype G] [Fintype C] in +lemma groupCount_complement (group : A → C) (S : Set A) (c : C) : + groupCount group S c+groupCount group Sᶜ c=groupCount group Set.univ c := by + unfold groupCount + simp_rw [Finset.card_filter] + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro a _ + by_cases hg : group a=c <;> by_cases hs : a∈S <;> simp [hg,hs] + +omit [Fintype I] [DecidableEq I] [Fintype G] in +/-- The actual reflected raw slice proves the addition property of the +literal complementary-factorial lift in the original coordinates. -/ +theorem secondLift_addition_reflected_slice (group : A → C) (h : (C → ℕ) → ℝ) + (D : ℝ) (R : ℕ) (hR : R ≤ Fintype.card A) (hD : 0 < D) (hh : ∀ z, 0 ≤ h z) + (hsig : RemovalSlice (fun z => h (reflect (groupCount group Set.univ) z)) + (groupCount group Set.univ) (Fintype.card A-R)) : + BinaryContraction.AdditionProperty (secondLift group h D) R := by + apply secondLift_addition group h D R hD hh + intro S hS + apply addition_onePositive_of_reflection h (groupCount group Set.univ) + (groupCount group S) (groupCount group Sᶜ) (groupCount_complement group S) + apply hsig _ (SliceFactorial.groupCount_inBox group Sᶜ) + rw [groupCount_total] + have hc := Set.ncard_add_ncard_compl S + simp only [Nat.card_eq_fintype_card] at hc + omega + +end ContingencyTables.ReflectedSlices + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RejectionLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RejectionLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f53eb0c637dcc714fc415b68786a0f5e6e0c572 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RejectionLaw.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess + +namespace OAI + +/-! # Exact finite repeated-trial laws and their approximation error -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +noncomputable section + +variable {α β : Type*} [Fintype α] [Fintype β] [DecidableEq β] + +theorem variation_self (p : RationalLaw α) : variation p p = 0 := by + simp [variation] + +theorem variation_triangle (p q r : RationalLaw α) : + variation p r ≤ variation p q + variation q r := by + have hsum : (∑ x, |p.mass x - r.mass x|) ≤ + (∑ x, |p.mass x - q.mass x|) + ∑ x, |q.mass x - r.mass x| := by + rw [← Finset.sum_add_distrib] + exact Finset.sum_le_sum fun x _ => abs_sub_le (p.mass x) (q.mass x) (r.mass x) + unfold variation + linarith + +def pointLaw (z : β) : RationalLaw β where + mass := fun y => if y = z then 1 else 0 + nonnegative := fun y => by split_ifs <;> norm_num + total := by simp + +def retryStep (p : RationalLaw α) (f : α → Option β) (tail : RationalLaw β) : RationalLaw β := + mapLaw (productLaw p tail) (fun z => (f z.1).getD z.2) + +def retryLaw (p : RationalLaw α) (f : α → Option β) (fallback : β) : ℕ → RationalLaw β + | 0 => pointLaw fallback + | n + 1 => retryStep p f (retryLaw p f fallback n) + +def successMass (p : RationalLaw α) (f : α → Option β) (z : β) : ℚ := + ∑ x, if f x = some z then p.mass x else 0 + +def failureMass (p : RationalLaw α) (f : α → Option β) : ℚ := + ∑ x, if f x = none then p.mass x else 0 + +theorem success_failure_total (p : RationalLaw α) (f : α → Option β) : + (∑ z, successMass p f z) + failureMass p f = 1 := by + unfold successMass failureMass + rw [Finset.sum_comm, ← Finset.sum_add_distrib] + calc + _ = ∑ x, p.mass x := by + apply Finset.sum_congr rfl + intro x _ + cases f x <;> simp + _ = 1 := p.total + +theorem retryStep_mass (p : RationalLaw α) (f : α → Option β) + (tail : RationalLaw β) (z : β) : + (retryStep p f tail).mass z = successMass p f z + failureMass p f * tail.mass z := by + change (∑ x : α × β, if (f x.1).getD x.2 = z then p.mass x.1 * tail.mass x.2 else 0) = _ + rw [Fintype.sum_prod_type] + unfold successMass failureMass + rw [Finset.sum_mul, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + cases hfx : f x with + | none => simp [hfx] + | some y => + by_cases hy : y = z + · subst y + simp only [hfx, Option.getD_some, ite_true, ite_false, + reduceCtorEq, zero_mul, add_zero] + rw [← Finset.mul_sum, tail.total, mul_one] + · simp [hfx, hy] + +omit [Fintype β] in +theorem outputMass_succ (g : β → ℚ) (f : ℚ) (n : ℕ) (fallback z : β) : + outputMass g f (n + 1) fallback z = g z + f * outputMass g f n fallback z := by + have h := geometric_balance f n + have hg := congrArg (fun x : ℚ => g z * x) h + unfold outputMass + rw [Finset.sum_range_succ, pow_succ] + split_ifs <;> nlinarith [hg] + +/-- The law of finitely many independent trials, each of which can either +return a value or fail, is the geometric first-success law. -/ +theorem retryLaw_mass (p : RationalLaw α) (f : α → Option β) + (fallback z : β) (n : ℕ) : + (retryLaw p f fallback n).mass z = + outputMass (successMass p f) (failureMass p f) n fallback z := by + induction n with + | zero => simp [retryLaw, pointLaw, outputMass] + | succ n ih => + rw [retryLaw, retryStep_mass, ih, outputMass_succ] + +/-- Approximate independent trials incur their error before the success +test. Rejection never divides that error by a success probability. -/ +theorem retryLaw_variation (p q : RationalLaw α) (f : α → Option β) + (fallback : β) (n : ℕ) : + variation (retryLaw p f fallback n) (retryLaw q f fallback n) ≤ + (n : ℚ) * variation p q := by + induction n with + | zero => simp [retryLaw, variation_self] + | succ n ih => + calc + _ ≤ variation p q + variation (retryLaw p f fallback n) (retryLaw q f fallback n) := + (variation_map (productLaw p (retryLaw p f fallback n)) + (productLaw q (retryLaw q f fallback n)) _).trans (variation_product _ _ _ _) + _ ≤ variation p q + (n : ℚ) * variation p q := add_le_add le_rfl ih + _ = _ := by push_cast; ring + +end + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualAugmentation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualAugmentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..11a616a51e8b2fe4a1103ca92fd4f33c3d6f3eef --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualAugmentation.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ResidualSearch +import OAI.Combinatorics.ContingencyTables.Transport.PathAugmentation +import Mathlib.Data.List.MinMax + +namespace OAI + +/-! # Executed bottleneck and residual augmentation + +The program takes the actual BFS path list, scans its residual capacities +for a minimum, and adds the resulting skew path flow. No path or amount +is chosen through a mathematical existence proof. +-/ + +namespace ContingencyTables.ResidualAugmentation + +open PublishedEdmondsKarp +open scoped BigOperators + +variable {n : ℕ} + +def arcs : List (Fin n) → List (Fin n×Fin n) + | [] => [] + | [_] => [] + | u::v::xs => (u,v)::arcs (v::xs) + +def bottleneck (c : Capacity n) (f : Flow n) (xs : List (Fin n)) : ℤ := + ((arcs xs).map (fun uv=>(c uv.1 uv.2:ℤ)-f uv.1 uv.2)).min?.getD 0 + +def listUpdate (f : Flow n) (xs : List (Fin n)) (a : ℤ) : Flow n := + fun u v=>f u v+a*((((arcs xs).map (fun uv=>if uv=(u,v) then (1:ℤ) else 0)).sum)- + (((arcs xs).map (fun uv=>if uv=(v,u) then (1:ℤ) else 0)).sum)) + +def step (c : Capacity n) (s t : Fin n) (f : Flow n) : Option (Flow n) := + (ResidualSearch.search c f s t).map (fun xs=>listUpdate f xs (bottleneck c f xs)) + +lemma arcs_ofFn (k : ℕ) (p : Fin (k+1) → Fin n) : + arcs (List.ofFn p)=List.ofFn (fun i : Fin k=>(p i.castSucc,p i.succ)) := by + induction k with + | zero => simp [List.ofFn_succ,arcs] + | succ k ih => + rw [List.ofFn_succ (f:=p)] + rw [List.ofFn_succ (f:=fun i : Fin (k+1)=>p i.succ)] + rw [arcs] + have h := ih (fun i : Fin (k+1)=>p i.succ) + rw [List.ofFn_succ] at h + rw [h,List.ofFn_succ] + rfl + +lemma listUpdate_ofFn (f : Flow n) (k : ℕ) (p : Fin (k+1) → Fin n) (a : ℤ) : + listUpdate f (List.ofFn p) a=PathAugmentation.update f p a := by + funext u v + simp only [listUpdate,arcs_ofFn,List.map_ofFn,Function.comp_apply,Fin.sum_ofFn, + PathAugmentation.update,PathAugmentation.arcCount,Prod.mk.injEq] + +lemma bottleneck_ofFn (c : Capacity n) (f : Flow n) (k : ℕ) + (p : Fin (k+1) → Fin n) : + bottleneck c f (List.ofFn p)= + (List.ofFn (fun i : Fin k=>(c (p i.castSucc) (p i.succ):ℤ)- + f (p i.castSucc) (p i.succ))).min?.getD 0 := by + simp only [bottleneck,arcs_ofFn,List.map_ofFn,Function.comp_def] + +lemma bottleneck_spec (c : Capacity n) (s t : Fin n) (hst : s≠t) (f : Flow n) + (k : ℕ) (p : Fin (k+1) → Fin n) (hp : ResidualPath c f s t k p) : + 0(c (p i.castSucc) (p i.succ):ℤ)- + f (p i.castSucc) (p i.succ) + rw [bottleneck_ofFn] + change 0<(List.ofFn r).min?.getD 0 ∧ + (∀ i,(List.ofFn r).min?.getD 0≤r i) ∧ ∃ i,(List.ofFn r).min?.getD 0=r i + cases hm : (List.ofFn r).min? with + | none => + have hz : k=0 := List.ofFn_eq_nil_iff.mp (List.min?_eq_none_iff.mp hm) + exact False.elim (hk hz) + | some a => + have ha := List.min?_eq_some_iff.mp hm + obtain ⟨i,hi⟩ := List.mem_ofFn.mp ha.1 + simp only [Option.getD_some] + refine ⟨?_,?_,⟨i,hi.symm⟩⟩ + · rw [←hi] + exact hp.2.2.2 i + · intro j + exact ha.2 (r j) (List.mem_ofFn.mpr ⟨j,rfl⟩) + +theorem step_augmentation (c : Capacity n) (s t : Fin n) (hst : s≠t) + (f g : Flow n) (h : step c s t f=some g) : ShortestAugmentation c s t f g := by + obtain ⟨xs,hxs,hg⟩ := Option.map_eq_some_iff.mp h + obtain ⟨k,p,hp,hr,hshort⟩ := ResidualSearch.search_shortest c f s t xs hxs + subst xs + have hb := bottleneck_spec c s t hst f k p hr + refine ⟨k,p,bottleneck c f (List.ofFn p),hr,hshort,hb.1,hb.2.1,hb.2.2,?_⟩ + intro u v + rw [←hg,listUpdate_ofFn] + rfl + +theorem step_feasible (c : Capacity n) (s t : Fin n) (hst : s≠t) + (f g : Flow n) (hf : Feasible c s t f) (h : step c s t f=some g) : + Feasible c s t g := by + obtain ⟨k,p,a,hp,_,ha,hr,_,hu⟩ := step_augmentation c s t hst f g h + have he : g=PathAugmentation.update f p a := funext (fun u=>funext (hu u)) + rw [he] + exact PathAugmentation.update_feasible c s t f hf p hp a ha.le hr + +theorem step_none_maximum (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (h : step c s t f=none) : IsMaximum c s t f := by + apply ResidualSearch.failure_maximum c s t f hf + exact Option.map_eq_none_iff.mp h + +end ContingencyTables.ResidualAugmentation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualBoxScale.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualBoxScale.lean new file mode 100644 index 0000000000000000000000000000000000000000..07322b582c7e20d51a0528a662a072cf27925c0f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualBoxScale.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ResidualEnumerationBounds +import OAI.Combinatorics.ContingencyTables.Transport.CacheBoxBounds + +namespace OAI + +/-! # One scale for all boxes in the rare exact correction -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] profilePaddedMargins + +def exactBoxScale {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : ℕ := + 2^(40*((dimensionAllowance (I := Fin m) (J := Fin n))^3*smallBinaryLength r c)) + +variable {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +local notation "dim" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "bits" => smallBinaryLength r c + +private lemma normalized_base_bound (b l s : ℕ) (hb : 1 ≤ b) + (hl : l ≤ 2^b) (hs : s+1 ≤ 2^(4*b)) : l*s+1 ≤ 2^(6*b) := by + have hm := Nat.mul_le_mul hl (show s ≤ 2^(4*b) by omega) + have he : (2:ℕ)^b*2^(4*b)=2^(5*b) := by + calc + _ = 2^(b+4*b) := (pow_add 2 b (4*b)).symm + _ = _ := congrArg (fun k : ℕ => (2:ℕ)^k) (by omega) + rw [he] at hm + have hp : 1 ≤ (2:ℕ)^(5*b) := one_le_pow₀ (by decide) + calc + _ ≤ 2*2^(5*b) := by omega + _ = 2^(5*b+1) := by rw [pow_succ]; omega + _ ≤ 2^(6*b) := Nat.pow_le_pow_right (by decide) (by omega) + +lemma exactBoxScale_pos : 1 ≤ exactBoxScale r c := by + exact one_le_pow₀ (by decide) + +lemma normalized_profile_completion_count (v : ProfileCheckData) + (hr : v.1.2.1=List.ofFn r) (hc : v.1.2.2=List.ofFn c) (h : ℕ) : + gridStateCount (completionEnumerationData + (canonicalCountInput (residualParameters ((v,dim^12),(dim,h)))).1.1) ≤ + exactBoxScale r c := by + let R := profilePaddedMargins true (v,dim^12) + let C := profilePaddedMargins false (v,dim^12) + have hd : 1 ≤ dim := by unfold dimensionAllowance; omega + have hb : 1 ≤ bits := hd.trans (smallBinaryLength_parameters r c).2.1 + have hdb : dim ≤ 2^bits := by + have h1 : dim ≤ bits := (smallBinaryLength_parameters r c).2.1 + exact h1.trans (Nat.le_of_lt (Nat.lt_two_pow_self)) + have hR : R.length ≤ dim := by + have ht := profilePaddedMargins_length true (v,dim^12) + simp only [hr,ite_true,List.length_ofFn] at ht + have hm : m ≤ dim := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + exact ht.trans hm + have hC : C.length ≤ dim := by + have ht := profilePaddedMargins_length false (v,dim^12) + simp only [Bool.false_eq_true,ite_false,hc,List.length_ofFn] at ht + have hn : n ≤ dim := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + exact ht.trans hn + have hsum : R.sum+1 ≤ 2^(4*bits) := arbitrary_profile_margin_sum r c v hr hc + have hbase : R.length*R.sum+1 ≤ 2^(6*bits) := + normalized_base_bound bits R.length R.sum hb (hR.trans hdb) hsum + have hn := canonicalCompletion_count_le (residualParameters ((v,dim^12),(dim,h))) + change _ ≤ (R.length*R.sum+1)^(R.length*C.length) at hn + have hprod : R.length*C.length ≤ dim^2 := by simpa only [pow_two] using Nat.mul_le_mul hR hC + have h23 : dim^2 ≤ dim^3 := Nat.pow_le_pow_right hd (by decide) + calc + _ ≤ (R.length*R.sum+1)^(R.length*C.length) := hn + _ ≤ (2^(6*bits))^(dim^2) := + (Nat.pow_le_pow_left hbase _).trans (Nat.pow_le_pow_right (by positivity) hprod) + _ = 2^((6*bits)*dim^2) := (pow_mul _ _ _).symm + _ ≤ exactBoxScale r c := Nat.pow_le_pow_right (by decide) (by nlinarith) + +lemma normalized_profile_dense_grid (v : ProfileCheckData) + (hr : v.1.2.1=List.ofFn r) (hc : v.1.2.2=List.ofFn c) (h : ℕ) : + let z := (canonicalCountInput (residualParameters ((v,dim^12),(dim,h)))).1 + (4*z.2.1^8)^tabulationDimension z ≤ exactBoxScale r c := by + let z := (canonicalCountInput (residualParameters ((v,dim^12),(dim,h)))).1 + have hd : 1 ≤ dim := by unfold dimensionAllowance; omega + have hb : 1 ≤ bits := hd.trans (smallBinaryLength_parameters r c).2.1 + have hr' := profilePaddedMargins_length true (v,dim^12) + have hc' := profilePaddedMargins_length false (v,dim^12) + simp only [hr,ite_true,List.length_ofFn] at hr' + simp only [Bool.false_eq_true,ite_false,hc,List.length_ofFn] at hc' + have hm : m ≤ dim := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hn : n ≤ dim := by unfold dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hq : tabulationDimension z ≤ dim^2 := by + unfold tabulationDimension z canonicalCountInput swapMargins residualParameters + simp only [swapZeroList_length,List.length_tail] + simpa only [pow_two] using Nat.mul_le_mul + ((Nat.sub_le _ _).trans (hr'.trans hm)) ((Nat.sub_le _ _).trans (hc'.trans hn)) + have hbase : 4*dim^8 ≤ 2^(10*dim) := by + have hdim : dim ≤ 2^dim := Nat.le_of_lt (Nat.lt_two_pow_self) + calc + _ ≤ 4*(2^dim)^8 := Nat.mul_le_mul_left 4 (Nat.pow_le_pow_left hdim 8) + _ = 2^(dim*8+2) := by rw [←pow_mul,pow_add]; norm_num; ring + _ ≤ 2^(10*dim) := Nat.pow_le_pow_right (by decide) (by omega) + change (4*dim^8)^tabulationDimension z ≤ exactBoxScale r c + calc + _ ≤ (2^(10*dim))^(dim^2) := + (Nat.pow_le_pow_left hbase _).trans (Nat.pow_le_pow_right (by positivity) hq) + _ = 2^((10*dim)*dim^2) := (pow_mul _ _ _).symm + _ ≤ exactBoxScale r c := Nat.pow_le_pow_right (by decide) (by + have hbits : dim^3 ≤ dim^3*bits := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (dim^3) hb + nlinarith) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualEnumerationBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualEnumerationBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..40e3905f5f6a77274a85af61e845b946b776260e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualEnumerationBounds.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.PaddedEnumerationBounds +import OAI.Combinatorics.ContingencyTables.Sampling.ExactBoxBounds +import OAI.Combinatorics.ContingencyTables.Transport.CanonicalDrawTabulation + +namespace OAI + +/-! # The completion boxes used at arbitrary enumerated profiles -/ + +namespace ContingencyTables.ProfilePrograms +open DensePrograms + +lemma completionEnumeration_count (z : CompletionMargins) : + gridStateCount (completionEnumerationData z)= + (z.1.sum+1)^(z.1.tail.length*z.2.tail.length) := by + rw [gridStateCount_eq] + simp only [completionEnumerationData,List.length_map,zeroGrid,cellPairs,List.length_range] + +lemma completionEnumeration_count_le (z : CompletionMargins) (m n N : ℕ) + (hr : z.1.length ≤ m) (hc : z.2.length ≤ n) (hN : z.1.sum ≤ N) : + gridStateCount (completionEnumerationData z) ≤ (N+1)^(m*n) := by + rw [completionEnumeration_count] + have hr' : z.1.tail.length ≤ m := by simp only [List.length_tail]; omega + have hc' : z.2.tail.length ≤ n := by simp only [List.length_tail]; omega + exact (Nat.pow_le_pow_left (Nat.add_le_add_right hN 1) _).trans + (Nat.pow_le_pow_right (by omega) (Nat.mul_le_mul hr' hc')) + +lemma swapZeroList_length {A : Type} [MatchingFPRAS.TreeTyped.Codec A] [Inhabited A] + (i : ℕ) (as : List A) : (DensePrograms.swapZeroList (i,as)).length=as.length := by + simp only [swapZeroList,swapZeroIndices,List.length_map,List.length_range] + +lemma swapZeroList_sum_le (i : ℕ) (as : List ℕ) : + (DensePrograms.swapZeroList (i,as)).sum ≤ as.length*as.sum := by + have h := list_sum_le_length_mul (DensePrograms.swapZeroList (i,as)) as.sum (by + intro a ha + rw [swapZeroList] at ha + obtain ⟨j,_,rfl⟩ := List.mem_map.mp ha + exact list_getD_le_sum as (swapZeroIndex (i,j))) + simpa only [swapZeroList_length] using h + +lemma normalizedCompletion_count_le (z : CompletionMargins) (ij : ℕ×ℕ) : + gridStateCount (completionEnumerationData (swapMargins (ij,z))) ≤ + (z.1.length*z.1.sum+1)^(z.1.length*z.2.length) := by + apply completionEnumeration_count_le + · simp only [swapMargins,swapZeroList_length,le_refl] + · simp only [swapMargins,swapZeroList_length,le_refl] + · exact swapZeroList_sum_le ij.1 z.1 + +lemma canonicalCompletion_count_le (z : CanonicalParameters) : + gridStateCount (completionEnumerationData (canonicalCountInput z).1.1) ≤ + (z.1.1.length*z.1.1.sum+1)^(z.1.1.length*z.1.2.length) := by + exact normalizedCompletion_count_le z.1 (DensePrograms.marginIndices z.1) + +private def profilePaddingData (row : Bool) (z : ProfileCheckData×ℕ) : PaddingData := + let view := if row then z.1.1.1.2.1 else complementValues (z.1.2,z.1.1.1.2.2) + let line : MarginCheckData := (((z.1.1.1.1,view),z.1.1.2),z.1.2) + (line,z.2) + +lemma profilePaddedMargins_length (row : Bool) (z : ProfileCheckData×ℕ) : + (profilePaddedMargins row z).length ≤ + (if row then z.1.1.2.1 else z.1.1.2.2).length := by + exact largePaddedMargins_length row (profilePaddingData row z) + +lemma profilePaddedMargins_sum (row : Bool) (z : ProfileCheckData×ℕ) : + (profilePaddedMargins row z).sum ≤ + (if row then z.1.1.2.1 else z.1.1.2.2).length* + ((if row then z.1.1.2.1 else z.1.1.2.2).sum+ + (if !row then z.1.1.2.1 else z.1.1.2.2).length*z.2) := by + exact largePaddedMargins_sum row (profilePaddingData row z) + +lemma profilePaddedMargins_sum_ofFn {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (v : ProfileCheckData) (hr : v.1.2.1=List.ofFn r) (hc : v.1.2.2=List.ofFn c) (pad : ℕ) : + (profilePaddedMargins true (v,pad)).sum+1 ≤ m*((List.ofFn r).sum+n*pad)+1 := by + have hsum := profilePaddedMargins_sum true (v,pad) + simp only [hr,hc,List.length_ofFn,ite_true,Bool.not_true,Bool.false_eq_true,ite_false] at hsum + exact Nat.add_le_add_right hsum 1 + +/-- This bound is independent of the values in the two proposed small +views. In particular it applies before the validity test accepts them. -/ +lemma profileCompletion_count (z : ProfileCheckData×ℕ) : + gridStateCount (completionEnumerationData + (profilePaddedMargins true z,profilePaddedMargins false z)) ≤ + (z.1.1.2.1.length*(z.1.1.2.1.sum+z.1.1.2.2.length*z.2)+1)^ + (z.1.1.2.1.length*z.1.1.2.2.length) := by + apply completionEnumeration_count_le + · simpa using profilePaddedMargins_length true z + · simpa using profilePaddedMargins_length false z + · simpa using profilePaddedMargins_sum true z + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms CompletionCounts +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] profilePaddedMargins + +private lemma padded_base_bound (d b N m n : ℕ) (hd : 1 ≤ d) (hb : 1 ≤ b) + (hm : m ≤ d) (hn : n ≤ d) (hN : N+1 ≤ 2^b) (hD : d^20+1 ≤ 2^b) : + m*(N+n*d^12)+1 ≤ 2^(4*b) := by + have hd20 : d ≤ d^20 := Nat.le_self_pow (by decide) d + have hmP : m ≤ 2^b := hm.trans (hd20.trans (by omega)) + have hd14 : d^14 ≤ d^20 := Nat.pow_le_pow_right hd (by decide) + have hpad : m*n*d^12 ≤ 2^b := by + calc + _ ≤ d*d*d^12 := Nat.mul_le_mul_right _ (Nat.mul_le_mul hm hn) + _ = d^14 := by ring + _ ≤ 2^b := hd14.trans (by omega) + have hprod : m*N ≤ (2^b)^2 := by + simpa only [pow_two] using Nat.mul_le_mul hmP (show N ≤ 2^b by omega) + have hP : 1 ≤ 2^b := one_le_pow₀ (by decide) + have hP2 : 2^b ≤ (2^b)^2 := Nat.le_self_pow (by decide) _ + calc + _ ≤ 4*(2^b)^2 := by nlinarith + _ = 2^(2*b+2) := by rw [show 2*b=b*2 by omega,pow_add,pow_mul]; norm_num; ring + _ ≤ 2^(4*b) := Nat.pow_le_pow_right (by decide) (by omega) + +/-- All profile proposals have a singly exponential completion box, +including proposals rejected by the chain's validity test. -/ +lemma arbitrary_profile_margin_sum {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (v : ProfileCheckData) + (hr : v.1.2.1=List.ofFn r) (hc : v.1.2.2=List.ofFn c) : + let dim := dimensionAllowance (I := Fin m) (J := Fin n) + (profilePaddedMargins true (v,dim^12)).sum+1 ≤ 2^(4*smallBinaryLength r c) := by + dsimp only + let dim := dimensionAllowance (I := Fin m) (J := Fin n) + let bits := smallBinaryLength r c + have hd : 1 ≤ dim := by unfold dim dimensionAllowance; omega + have hm : m ≤ dim := by unfold dim dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hn : n ≤ dim := by unfold dim dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hb : 1 ≤ bits := hd.trans (smallBinaryLength_parameters r c).2.1 + have hN : (∑ i,r i)+1 ≤ 2^bits := + (show (∑ i,r i)+1 ≤ stateBound r c+1 by unfold stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hD : dim^20+1 ≤ 2^bits := + (show dim^20+1 ≤ stateBound r c+1 by unfold dim stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hbase := padded_base_bound dim bits (∑ i,r i) m n hd hb hm hn hN hD + have hsum := profilePaddedMargins_sum_ofFn r c v hr hc (dim^12) + rw [List.sum_ofFn] at hsum + exact hsum.trans hbase + +lemma arbitrary_profile_completion_count {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (v : ProfileCheckData) + (hr : v.1.2.1=List.ofFn r) (hc : v.1.2.2=List.ofFn c) : + let dim := dimensionAllowance (I := Fin m) (J := Fin n) + gridStateCount (completionEnumerationData + (profilePaddedMargins true (v,dim^12),profilePaddedMargins false (v,dim^12))) ≤ + 2^(4*(dim^2*smallBinaryLength r c)) := by + dsimp only + let dim := dimensionAllowance (I := Fin m) (J := Fin n) + let bits := smallBinaryLength r c + have hd : 1 ≤ dim := by unfold dim dimensionAllowance; omega + have hm : m ≤ dim := by unfold dim dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hn : n ≤ dim := by unfold dim dimensionAllowance; simp only [Fintype.card_fin]; nlinarith + have hb : 1 ≤ bits := hd.trans (smallBinaryLength_parameters r c).2.1 + have hN : (∑ i,r i)+1 ≤ 2^bits := + (show (∑ i,r i)+1 ≤ stateBound r c+1 by unfold stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hD : dim^20+1 ≤ 2^bits := + (show dim^20+1 ≤ stateBound r c+1 by unfold dim stateBound; omega).trans + (smallBinaryLength_parameters r c).2.2 + have hbase := padded_base_bound dim bits (∑ i,r i) m n hd hb hm hn hN hD + have hcount := profileCompletion_count (v,dim^12) + simp only [hr,hc,List.length_ofFn,List.sum_ofFn] at hcount + calc + _ ≤ (m*((∑ i,r i)+n*dim^12)+1)^(m*n) := hcount + _ ≤ (2^(4*bits))^(m*n) := Nat.pow_le_pow_left hbase _ + _ = 2^((4*bits)*(m*n)) := (pow_mul _ _ _).symm + _ ≤ 2^(4*(dim^2*bits)) := Nat.pow_le_pow_right (by decide) (by + have hh : m*n ≤ dim^2 := by simpa only [pow_two] using Nat.mul_le_mul hm hn + nlinarith) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualSearch.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..b44ccbe67a6568f88c301ba7489cb75937c6ce40 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ResidualSearch.lean @@ -0,0 +1,158 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDirectedBFS +import OAI.Combinatorics.ContingencyTables.Transport.PublishedEdmondsKarp +import Mathlib.Data.List.ChainOfFn +import Mathlib.Data.List.OfFn +import Mathlib.Algebra.Order.BigOperators.Group.Finset + +namespace OAI + +/-! # The computed residual search and its maximum-flow certificate + +The search itself is the deterministic directed BFS. Success supplies +the precise shortest simple residual path required by the published +augmentation bound; failure supplies a saturated cut, hence maximality. +-/ + +namespace ContingencyTables.ResidualSearch + +open FiniteDirectedBFS PublishedEdmondsKarp +open scoped BigOperators + +variable {n : ℕ} + +def edge (c : Capacity n) (f : Flow n) (u v : Fin n) : Bool := + decide (0<(c u v:ℤ)-f u v) + +def search (c : Capacity n) (f : Flow n) (s t : Fin n) : Option (List (Fin n)) := + paths (edge c f) s n t + +lemma route_of_fin (E : Fin n → Fin n → Bool) (k : ℕ) + (p : Fin (k+1) → Fin n) + (hp : ∀ i : Fin k,E (p i.castSucc) (p i.succ)=true) : + Route E (p 0) (p (Fin.last k)) (List.ofFn p) := by + induction k with + | zero => simpa [List.ofFn_succ] using (Route.start (E:=E) (s:=p 0)) + | succ k ih => + let q : Fin (k+1) → Fin n := fun i=>p i.castSucc + have hq : ∀ i : Fin k,E (q i.castSucc) (q i.succ)=true := by + intro i + exact hp i.castSucc + have hr := ih q hq + have he : E (q (Fin.last k)) (p (Fin.last (k+1)))=true := + hp (Fin.last k) + simpa only [List.ofFn_succ_last,q,Fin.castSucc_zero] using hr.extend he + +lemma route_of_residual (c : Capacity n) (f : Flow n) (s t : Fin n) + (k : ℕ) (p : Fin (k+1) → Fin n) (hp : ResidualPath c f s t k p) : + Route (edge c f) s t (List.ofFn p) := by + have h := route_of_fin (edge c f) k p (fun i=>by simpa [edge] using hp.2.2.2 i) + simpa only [hp.1,hp.2.1] using h + +theorem search_shortest (c : Capacity n) (f : Flow n) (s t : Fin n) + (xs : List (Fin n)) (hs : search c f s t=some xs) : + ∃ (k : ℕ) (p : Fin (k+1) → Fin n), + xs=List.ofFn p ∧ ResidualPath c f s t k p ∧ + ∀ (l : ℕ) (q : Fin (l+1) → Fin n), ResidualPath c f s t l q → k≤l := by + have hr := (paths_sound hs).1 + have hn := paths_nodup hs + cases xs with + | nil => exact False.elim (hr.nonempty rfl) + | cons a ys => + let p : Fin (ys.length+1) → Fin n := Fin.cons a ys.get + have he : List.ofFn p=a::ys := by simp [p] + have hhead : p 0=s := by simpa [←he,List.ofFn_succ] using hr.head + have hlast : p (Fin.last ys.length)=t := by + have hh := hr.last + rw [←he,List.getLast?_eq_some_getLast (by simp)] at hh + simpa only [List.getLast_ofFn_succ,Option.some.injEq] using hh + have hinj : Function.Injective p := List.nodup_ofFn.mp (he.symm ▸ hn) + have hchain := List.isChain_ofFn.mp (he.symm ▸ hr.chain) + have hres : ResidualPath c f s t ys.length p := by + refine ⟨hhead,hlast,hinj,?_⟩ + intro i + have hc := hchain i.val (by omega) + change edge c f (p i.castSucc) (p i.succ)=true at hc + exact of_decide_eq_true hc + refine ⟨ys.length,p,he.symm,hres,?_⟩ + intro l q hq + have hle := paths_shortest hs (List.ofFn q) (route_of_residual c f s t l q hq) + simpa using hle + +def reached (c : Capacity n) (f : Flow n) (s : Fin n) : Finset (Fin n) := + Finset.univ.filter (fun v=>(paths (edge c f) s n v).isSome) + +lemma mem_reached (c : Capacity n) (f : Flow n) (s v : Fin n) : + v∈reached c f s ↔ discovered (paths (edge c f) s n) v := by + simp [reached,discovered,Option.isSome_iff_exists] + +lemma source_reached (c : Capacity n) (f : Flow n) (s : Fin n) : + s∈reached c f s := (mem_reached c f s s).mpr (source_found _ _) + +lemma target_not_reached (c : Capacity n) (f : Flow n) (s t : Fin n) + (h : search c f s t=none) : t∉reached c f s := by + rw [mem_reached] + rintro ⟨xs,hxs⟩ + simp [search] at h + simp [h] at hxs + +lemma cut_saturated (c : Capacity n) (f : Flow n) (s : Fin n) + (hcap : ∀ u v,f u v≤c u v) {u v : Fin n} + (hu : u∈reached c f s) (hv : v∉reached c f s) : f u v=c u v := by + have hno : ¬0<(c u v:ℤ)-f u v := by + intro hp + have he : edge c f u v=true := by simpa [edge] using hp + exact hv ((mem_reached c f s v).mpr + (reached_closed ((mem_reached c f s u).mp hu) he)) + have hc := hcap u v + omega + +lemma sum_internal_zero (f : Flow n) (hf : ∀ u v,f u v= -f v u) + (S : Finset (Fin n)) : (∑ u∈S,∑ v∈S,f u v)=0 := by + have hn : (∑ u∈S,∑ v∈S,f u v)= -(∑ u∈S,∑ v∈S,f u v) := by + calc + _ = ∑ v∈S,∑ u∈S,f u v := Finset.sum_comm + _ = ∑ v∈S,∑ u∈S,-f v u := by + apply Finset.sum_congr rfl + intro v _ + exact Finset.sum_congr rfl (fun u _=>hf u v) + _ = _ := by simp + omega + +lemma value_eq_cut (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (S : Finset (Fin n)) (hs : s∈S) (ht : t∉S) : + value s f=∑ u∈S,∑ v∈Sᶜ,f u v := by + have hb : (∑ u∈S,∑ v,f u v)=value s f := by + apply Finset.sum_eq_single s + · intro u hu hus + exact hf.2.2 u hus (fun hut=>ht (hut ▸ hu)) + · exact fun h=>False.elim (h hs) + have hc : (∑ u∈S,∑ v,f u v)= + (∑ u∈S,∑ v∈S,f u v)+(∑ u∈S,∑ v∈Sᶜ,f u v) := by + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro u _ + exact (Finset.sum_add_sum_compl S (f u)).symm + rw [sum_internal_zero f hf.1,zero_add] at hc + exact hb.symm.trans hc + +/-- Failure of the actual finite BFS implies maximum flow. No +max-flow/min-cut result is included in the published input. -/ +theorem failure_maximum (c : Capacity n) (s t : Fin n) (f : Flow n) + (hf : Feasible c s t f) (h : search c f s t=none) : IsMaximum c s t f := by + refine ⟨hf,?_⟩ + intro g hg + let S := reached c f s + have hs : s∈S := source_reached c f s + have ht : t∉S := target_not_reached c f s t h + rw [value_eq_cut c s t g hg S hs ht,value_eq_cut c s t f hf S hs ht] + apply Finset.sum_le_sum + intro u hu + apply Finset.sum_le_sum + intro v hv + have hv' : v∉S := by simpa using hv + have he : f u v=c u v := cut_saturated c f s hf.2.1 hu hv' + simpa only [he] using hg.2.1 u v + +end ContingencyTables.ResidualSearch + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RowColumnPenalties.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowColumnPenalties.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e66f3c38f9f354a145b197b44ec406bf2e22804 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowColumnPenalties.lean @@ -0,0 +1,225 @@ +import OAI.Combinatorics.ContingencyTables.Transport.NestedPenaltyApplication +import OAI.Combinatorics.ContingencyTables.Model + +namespace OAI + +/-! +# Literal doubled row and column penalties + +The false coordinate of a cell is its row value x. Its true coordinate +is y, with physical column value q=B-y. Thus row and column factor groups +are disjoint, while their small-cell subsets are nested inside them. +Offsets below are the actual full margins and capacity sums of the paper. +-/ + +namespace ContingencyTables.RowColumnPenalties + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS ProductIntegerSignature NestedProductSignature +open NestedPenaltyApplication BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +def cellLine (u : (I × J) × Bool) : I ⊕ J := if u.2 then .inr u.1.2 else .inl u.1.1 + +def smallCoordinate (small : I → J → Bool) (u : (I × J) × Bool) : Bool := small u.1.1 u.1.2 + +def rowView (z : ((I × J) × Bool) → ℕ) (i : I) (j : J) : ℕ := z ((i,j),false) +def columnView (B : I → J → ℕ) (z : ((I × J) × Bool) → ℕ) (i : I) (j : J) : ℕ := + B i j-z ((i,j),true) + +noncomputable def columnCapacity (B : I → J → ℕ) (j : J) : ℕ := ∑ i, B i j +noncomputable def smallColumnCapacity (small : I → J → Bool) (B : I → J → ℕ) (j : J) : ℕ := + ∑ i, if small i j then B i j else 0 + +noncomputable def fullOffset (B : I → J → ℕ) (rbar : I → ℕ) (cbar : J → ℕ) : I ⊕ J → ℝ := + Sum.elim (fun i => -(rbar i:ℝ)) (fun j => (columnCapacity B j:ℝ)-cbar j) + +def viewSlope : I ⊕ J → ℝ := Sum.elim (fun _ => 1) (fun _ => -1) + +noncomputable def smallOffset (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) : I ⊕ J → ℝ := + Sum.elim (fun i => -(r i:ℝ)) (fun j => (smallColumnCapacity small B j:ℝ)-c j) + +lemma lineTotal_row (z : ((I × J) × Bool) → ℕ) (i : I) : + lineTotal cellLine z (.inl i)=∑ j, rowView z i j := by + simp [lineTotal,cellLine,Fintype.sum_prod_type,rowView] + rw [Finset.sum_comm] + simp + +lemma lineTotal_column (z : ((I × J) × Bool) → ℕ) (j : J) : + lineTotal cellLine z (.inr j)=∑ i, z ((i,j),true) := by + simp [lineTotal,cellLine,Fintype.sum_prod_type] + +lemma smallTotal_row (small : I → J → Bool) (z : ((I × J) × Bool) → ℕ) (i : I) : + smallTotal cellLine (smallCoordinate small) z (.inl i)= + ∑ j, if small i j then rowView z i j else 0 := by + simp [smallTotal,lineTotal,cellLine,smallCoordinate,Fintype.sum_prod_type,rowView, + ite_and] + +lemma smallTotal_column (small : I → J → Bool) (z : ((I × J) × Bool) → ℕ) (j : J) : + smallTotal cellLine (smallCoordinate small) z (.inr j)= + ∑ i, if small i j then z ((i,j),true) else 0 := by + simp [smallTotal,lineTotal,cellLine,smallCoordinate,Fintype.sum_prod_type, + ite_and] + +omit [Fintype J] in +lemma columnViews_add (B : I → J → ℕ) (z : ((I × J) × Bool) → ℕ) + (hz : InBox (fun u => B u.1.1 u.1.2) z) (j : J) : + (∑ i, columnView B z i j)+(∑ i, z ((i,j),true))=columnCapacity B j := by + unfold columnView columnCapacity + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + exact Nat.sub_add_cancel (hz ((i,j),true)) + +omit [Fintype J] in +lemma smallColumnViews_add (small : I → J → Bool) (B : I → J → ℕ) + (z : ((I × J) × Bool) → ℕ) (hz : InBox (fun u => B u.1.1 u.1.2) z) (j : J) : + (∑ i, if small i j then columnView B z i j else 0)+ + (∑ i, if small i j then z ((i,j),true) else 0)=smallColumnCapacity small B j := by + unfold columnView smallColumnCapacity + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i _ + cases hs : small i j + · simp + · simp only [ite_true] + exact Nat.sub_add_cancel (hz ((i,j),true)) + +lemma full_affine_row (B : I → J → ℕ) (rbar : I → ℕ) (cbar : J → ℕ) + (z : ((I × J) × Bool) → ℕ) (i : I) : + fullOffset B rbar cbar (.inl i)+(lineTotal cellLine z (.inl i):ℝ)*viewSlope (I := I) (J := J) (.inl i) = + ((∑ j, rowView z i j):ℝ)-rbar i := by + rw [lineTotal_row] + simp [fullOffset,viewSlope] + ring + +lemma full_affine_column (B : I → J → ℕ) (rbar : I → ℕ) (cbar : J → ℕ) + (z : ((I × J) × Bool) → ℕ) (hz : InBox (fun u => B u.1.1 u.1.2) z) (j : J) : + fullOffset B rbar cbar (.inr j)+(lineTotal cellLine z (.inr j):ℝ)*viewSlope (I := I) (J := J) (.inr j) = + ((∑ i, columnView B z i j):ℝ)-cbar j := by + have h : ((∑ i, columnView B z i j):ℝ)+((∑ i, z ((i,j),true)):ℝ)=columnCapacity B j := by + exact_mod_cast columnViews_add B z hz j + rw [lineTotal_column] + simp only [fullOffset,viewSlope,Sum.elim_inr,mul_neg_one] + push_cast + linarith + +lemma small_affine_row (small : I → J → Bool) (B : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) + (z : ((I × J) × Bool) → ℕ) (i : I) : + smallOffset small B r c (.inl i)+ + (smallTotal cellLine (smallCoordinate small) z (.inl i):ℝ)*viewSlope (I := I) (J := J) (.inl i) = + ((∑ j, if small i j then rowView z i j else 0):ℝ)-r i := by + rw [smallTotal_row] + simp [smallOffset,viewSlope] + ring + +lemma small_affine_column (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (z : ((I × J) × Bool) → ℕ) + (hz : InBox (fun u => B u.1.1 u.1.2) z) (j : J) : + smallOffset small B r c (.inr j)+ + (smallTotal cellLine (smallCoordinate small) z (.inr j):ℝ)*viewSlope (I := I) (J := J) (.inr j) = + ((∑ i, if small i j then columnView B z i j else 0):ℝ)-c j := by + have h : ((∑ i, if small i j then columnView B z i j else 0):ℝ)+ + ((∑ i, if small i j then z ((i,j),true) else 0):ℝ)=smallColumnCapacity small B j := by + exact_mod_cast smallColumnViews_add small B z hz j + rw [smallTotal_column] + simp only [smallOffset,viewSlope,Sum.elim_inr,mul_neg_one] + push_cast + linarith + +/-- This is exactly the manuscript's full row/column deviation plus its +small residual violation penalty, on the actual doubled physical box. -/ +theorem penalty_eq (small : I → J → Bool) (B : I → J → ℕ) + (r cR : I → ℕ) (c cC : J → ℕ) (z : ((I × J) × Bool) → ℕ) + (hz : InBox (fun u => B u.1.1 u.1.2) z) : + penalty cellLine (smallCoordinate small) (fullOffset B cR cC) viewSlope + (smallOffset small B r c) viewSlope z = + (∑ i, |((∑ j, rowView z i j):ℝ)-cR i|)+ + (∑ j, |((∑ i, columnView B z i j):ℝ)-cC j|)+ + (∑ i, max (((∑ j, if small i j then rowView z i j else 0):ℝ)-r i) 0)+ + (∑ j, max (((∑ i, if small i j then columnView B z i j else 0):ℝ)-c j) 0) := by + unfold penalty + rw [Fintype.sum_sum_type,Fintype.sum_sum_type] + simp_rw [full_affine_row,full_affine_column B cR cC z hz, + small_affine_row,small_affine_column small B r c z hz] + ring + +def FullConditions (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : ((I × J) × Bool) → ℕ) : Prop := + (∀ i, ∑ j, rowView z i j=rbar i) ∧ + (∀ j, ∑ i, columnView B z i j=cbar j) ∧ + (∀ i, (∑ j, if small i j then rowView z i j else 0) ≤ r i) ∧ + (∀ j, (∑ i, if small i j then columnView B z i j else 0) ≤ c j) + +/-- Zero penalty means precisely the enlarged full margins and +nonnegative original residuals, even for unbalanced defect profiles. -/ +theorem penalty_zero_iff (small : I → J → Bool) (B : I → J → ℕ) + (r rbar : I → ℕ) (c cbar : J → ℕ) (z : ((I × J) × Bool) → ℕ) + (hz : InBox (fun u => B u.1.1 u.1.2) z) : + penalty cellLine (smallCoordinate small) (fullOffset B rbar cbar) viewSlope + (smallOffset small B r c) viewSlope z=0 ↔ FullConditions small B r rbar c cbar z := by + rw [penalty_eq small B r rbar c cbar z hz] + let a : I → ℝ := fun i => |((∑ j, rowView z i j):ℝ)-rbar i| + let b : J → ℝ := fun j => |((∑ i, columnView B z i j):ℝ)-cbar j| + let e : I → ℝ := fun i => max (((∑ j, if small i j then rowView z i j else 0):ℝ)-r i) 0 + let f : J → ℝ := fun j => max (((∑ i, if small i j then columnView B z i j else 0):ℝ)-c j) 0 + have ha : ∀ i, 0 ≤ a i := fun _ => abs_nonneg _ + have hb : ∀ j, 0 ≤ b j := fun _ => abs_nonneg _ + have he : ∀ i, 0 ≤ e i := fun _ => le_max_right _ _ + have hf : ∀ j, 0 ≤ f j := fun _ => le_max_right _ _ + change (∑ i, a i)+(∑ j, b j)+(∑ i, e i)+(∑ j, f j)=0 ↔ _ + constructor + · intro hzero + have hsa : 0 ≤ ∑ i, a i := Finset.sum_nonneg (fun i _ => ha i) + have hsb : 0 ≤ ∑ j, b j := Finset.sum_nonneg (fun j _ => hb j) + have hse : 0 ≤ ∑ i, e i := Finset.sum_nonneg (fun i _ => he i) + have hsf : 0 ≤ ∑ j, f j := Finset.sum_nonneg (fun j _ => hf j) + refine ⟨?_,?_,?_,?_⟩ + · intro i + have hi := Finset.single_le_sum (fun k _ => ha k) (Finset.mem_univ i) + have hzabs : a i=0 := by linarith [ha i] + have hiReal := sub_eq_zero.mp (abs_eq_zero.mp hzabs) + exact_mod_cast hiReal + · intro j + have hj := Finset.single_le_sum (fun k _ => hb k) (Finset.mem_univ j) + have hzabs : b j=0 := by linarith [hb j] + have hjReal := sub_eq_zero.mp (abs_eq_zero.mp hzabs) + exact_mod_cast hjReal + · intro i + have hi := Finset.single_le_sum (fun k _ => he k) (Finset.mem_univ i) + have ht : (((∑ j, if small i j then rowView z i j else 0):ℝ)-r i) ≤ 0 := by + have hm := le_max_left (((∑ j, if small i j then rowView z i j else 0):ℝ)-r i) 0 + change _ ≤ e i at hm + linarith + exact_mod_cast (sub_nonpos.mp ht) + · intro j + have hj := Finset.single_le_sum (fun k _ => hf k) (Finset.mem_univ j) + have ht : (((∑ i, if small i j then columnView B z i j else 0):ℝ)-c j) ≤ 0 := by + have hm := le_max_left (((∑ i, if small i j then columnView B z i j else 0):ℝ)-c j) 0 + change _ ≤ f j at hm + linarith + exact_mod_cast (sub_nonpos.mp ht) + · rintro ⟨hr,hc,hsr,hsc⟩ + have haz : ∀ i, a i=0 := by + intro i + have hh : ((∑ j, rowView z i j):ℝ)=rbar i := by exact_mod_cast hr i + exact abs_eq_zero.mpr (sub_eq_zero.mpr hh) + have hbz : ∀ j, b j=0 := by + intro j + have hh : ((∑ i, columnView B z i j):ℝ)=cbar j := by exact_mod_cast hc j + exact abs_eq_zero.mpr (sub_eq_zero.mpr hh) + have hez : ∀ i, e i=0 := by + intro i + apply max_eq_right + exact sub_nonpos.mpr (by exact_mod_cast hsr i) + have hfz : ∀ j, f j=0 := by + intro j + apply max_eq_right + exact sub_nonpos.mpr (by exact_mod_cast hsc j) + simp only [haz,hbz,hez,hfz,Finset.sum_const_zero,add_zero] + +end ContingencyTables.RowColumnPenalties + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorEnumeration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8c471ceeba1cc2800b4ab70ed2cd2a2fc9f0163 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorEnumeration.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCoordinates +import Mathlib.Data.Prod.Lex +import Mathlib.Data.Fintype.Sort + +namespace OAI + +/-! # Increasing enumeration of the actual finite small cells -/ + +namespace ContingencyTables.RowMajorEnumeration + +open scoped Classical +open SmallContextCoordinates + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev LexCells (small : I → J → Bool) := + {a : I×ₗJ // small (ofLex a).1 (ofLex a).2=true} + +noncomputable def lexCellEquiv (small : I → J → Bool) : LexCells small ≃ Cells small where + toFun a := ⟨ofLex a.val,a.property⟩ + invFun a := ⟨toLex a.val,a.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +noncomputable def enumeration (small : I → J → Bool) : Fin (Fintype.card (Cells small)) ≃ Cells small := + (monoEquivOfFin (LexCells small) (Fintype.card_congr (lexCellEquiv small))).toEquiv.trans + (lexCellEquiv small) + +lemma enumeration_before_iff (small : I → J → Bool) + (a b : Fin (Fintype.card (Cells small))) : + RowMajorBefore (enumeration small a).val (enumeration small b).val ↔ a a.val) Subtype.val_injective).trans_eq + (Fintype.card_prod I J) + +end ContingencyTables.RowMajorEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorPrefixFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorPrefixFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd6f7534b5cc089a9ec70afe5c7f97f5bc15a644 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/RowMajorPrefixFibres.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ChoiceContextEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.FinitePrefixVariance +import OAI.Combinatorics.ContingencyTables.Transport.RowMajorEnumeration + +namespace OAI + +/-! # Row-major word prefixes are the literal physical exposure contexts -/ + +namespace ContingencyTables.RowMajorEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily +open ExcessContextProfiles SmallGraphProfiles FiniteExposureVariance IntegerWeightedTransport + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def wordChoices (small : I → J → Bool) (U : ℕ) : + (Fin (Fintype.card (Cells small)) → Fin (U+1)) ≃ (Cells small → Fin (U+1)) where + toFun a := a ∘ (enumeration small).symm + invFun a := a ∘ enumeration small + left_inv a := by funext i; exact congrArg a ((enumeration small).symm_apply_apply i) + right_inv a := by funext i; exact congrArg a ((enumeration small).apply_symm_apply i) + +noncomputable def earlierWordChoices (small : I → J → Bool) (U : ℕ) + (k : Fin (Fintype.card (Cells small))) : + (Fin k.val → Fin (U+1)) ≃ (Earlier small (enumeration small k).val → Fin (U+1)) where + toFun a := a ∘ (earlierEnumeration small k).symm + invFun a := a ∘ earlierEnumeration small k + left_inv a := by funext i; exact congrArg a ((earlierEnumeration small k).symm_apply_apply i) + right_inv a := by funext i; exact congrArg a ((earlierEnumeration small k).apply_symm_apply i) + +lemma earlierEnumeration_cell (small : I → J → Bool) (k : Fin (Fintype.card (Cells small))) + (j : Fin k.val) : + (earlierEnumeration small k j).val=enumeration small ⟨j.val,lt_trans j.isLt k.isLt⟩ := rfl + +lemma wordChoices_prefix (small : I → J → Bool) (U : ℕ) (k : Fin (Fintype.card (Cells small))) + (a : Fin (Fintype.card (Cells small)) → Fin (U+1)) : + earlierChoices small (enumeration small k).val U (wordChoices small U a)= + earlierWordChoices small U k (restriction k.val (Nat.le_of_lt k.isLt) a) := by + funext b + obtain ⟨j,rfl⟩ := (earlierEnumeration small k).surjective b + change a ((enumeration small).symm (earlierEnumeration small k j).val)= + restriction k.val (Nat.le_of_lt k.isLt) a ((earlierEnumeration small k).symm (earlierEnumeration small k j)) + rw [earlierEnumeration_cell,Equiv.symm_apply_apply,Equiv.symm_apply_apply] + rfl + +lemma wordChoices_current (small : I → J → Bool) (U : ℕ) (k : Fin (Fintype.card (Cells small))) + (a : Fin (Fintype.card (Cells small)) → Fin (U+1)) : + wordChoices small U a (enumeration small k)=a k := by + exact congrArg a ((enumeration small).symm_apply_apply k) + +lemma word_fibre_sum (small : I → J → Bool) (U : ℕ) (k : Fin (Fintype.card (Cells small))) + (τ : Fin k.val → Fin (U+1)) (j : Fin (U+1)) (F : (Cells small → Fin (U+1)) → ℝ) : + (∑ a,fibreWeight (fibreWeight (fun a => F (wordChoices small U a)) + (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j a)= + ∑ x,fibreWeight (fibreWeight F (earlierChoices small (enumeration small k).val U) + (earlierWordChoices small U k τ)) (fun x => x (enumeration small k)) j x := by + apply Fintype.sum_equiv (wordChoices small U) + intro a + have hp : earlierChoices small (enumeration small k).val U (wordChoices small U a)= + earlierWordChoices small U k τ ↔ restriction k.val (Nat.le_of_lt k.isLt) a=τ := by + rw [wordChoices_prefix] + exact (earlierWordChoices small U k).apply_eq_iff_eq + unfold fibreWeight + dsimp only + have hc : wordChoices small U a (enumeration small k)=j ↔ a k=j := by + rw [wordChoices_current] + by_cases hj : a k=j + · rw [ite_eq_left hj,ite_eq_left (hc.mpr hj)] + by_cases hτ : restriction k.val (Nat.le_of_lt k.isLt) a=τ + · rw [ite_eq_left hτ,ite_eq_left (hp.mpr hτ)] + · rw [ite_eq_right hτ,ite_eq_right (fun h => hτ (hp.mp h))] + · rw [ite_eq_right hj,ite_eq_right (fun h => hj (hc.mp h))] + +/-- Both zeroth and first moments in the finite prefix variance are +exactly the moments used by the proved physical transport inequality. -/ +theorem eliminate_context_eq_word_fibre (small : I → J → Bool) (B : I → J → ℕ) + (U : ℕ) (hB : ∀ i j,small i j=true → B i j=U) + (k : Fin (Fintype.card (Cells small))) (τ : Fin k.val → Fin (U+1)) (j : Fin (U+1)) + (F : SmallProfile small → ℝ) : + let s := (enumeration small k).val + let hs := (enumeration small k).property + let σ := prefixExtension small s U (earlierWordChoices small U k τ) + let e := laterEnumeration small k + eliminate (widths (fun _ : Fin (Fintype.card (Cells small)-k.val-1) => U)) + (fun p => F (assemble small s hs σ U e p)) (childProfile U j.val)= + ∑ a,fibreWeight (fibreWeight (fun a => F (rawChoice small U (wordChoices small U a))) + (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j a := by + dsimp only + rw [eliminate_context_eq_choice_fibre small B _ _ U hB] + exact (word_fibre_sum small U k τ j (fun x => F (rawChoice small U x))).symm + +end ContingencyTables.RowMajorEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/ScalarPenalty.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/ScalarPenalty.lean new file mode 100644 index 0000000000000000000000000000000000000000..7660c203e31729b0b3292e9b9c190adc61cf1bba --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/ScalarPenalty.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ProductIntegerSignature +import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics + +namespace OAI + +/-! +# The actual positive scalar softening factors + +Absolute affine deviations, positive parts and interval distances have +convex integer exponents. Their powers of two are positive log-concave +sequences, supplying the concrete line and unary factors of both papers. +-/ + +namespace ContingencyTables.ScalarPenalty + +open scoped BigOperators + +noncomputable def factor (A : ℝ) (p : ℕ → ℝ) (n : ℕ) : ℝ := (2:ℝ)^(-A*p n) + +lemma factor_positive (A : ℝ) (p : ℕ → ℝ) (n : ℕ) : 0 < factor A p n := + Real.rpow_pos_of_pos (by norm_num) _ + +/-- Convex discrete exponents give the exact scalar log-concavity test. -/ +theorem factor_logConcave (A : ℝ) (hA : 0 ≤ A) (p : ℕ → ℝ) (n : ℕ) + (hp : 2*p (n-1) ≤ p n+p (n-2)) : + factor A p n * factor A p (n-2) ≤ (factor A p (n-1))^2 := by + unfold factor + rw [pow_two,← Real.rpow_add (by norm_num : (0:ℝ)<2), + ← Real.rpow_add (by norm_num : (0:ℝ)<2)] + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + nlinarith [mul_le_mul_of_nonneg_left hp hA] + +lemma affine_midpoint (a b : ℝ) (n : ℕ) (hn : 2 ≤ n) : + 2*(a+((n-1:ℕ):ℝ)*b) = (a+(n:ℝ)*b)+(a+((n-2:ℕ):ℝ)*b) := by + rw [Nat.cast_sub (by omega : 1 ≤ n),Nat.cast_sub hn] + norm_num + ring + +lemma abs_affine_convex (a b : ℝ) (n : ℕ) (hn : 2 ≤ n) : + 2*|a+((n-1:ℕ):ℝ)*b| ≤ |a+(n:ℝ)*b|+|a+((n-2:ℕ):ℝ)*b| := by + have h := abs_add_le (a+(n:ℝ)*b) (a+((n-2:ℕ):ℝ)*b) + rw [← affine_midpoint a b n hn,abs_mul] at h + norm_num at h + exact h + +lemma max_convex (p q : ℕ → ℝ) (n : ℕ) + (hp : 2*p (n-1) ≤ p n+p (n-2)) (hq : 2*q (n-1) ≤ q n+q (n-2)) : + 2*max (p (n-1)) (q (n-1)) ≤ max (p n) (q n)+max (p (n-2)) (q (n-2)) := by + by_cases h : p (n-1) ≤ q (n-1) + · rw [max_eq_right h] + linarith [le_max_right (p n) (q n),le_max_right (p (n-2)) (q (n-2))] + · rw [max_eq_left (le_of_not_ge h)] + linarith [le_max_left (p n) (q n),le_max_left (p (n-2)) (q (n-2))] + +/-- The row and column absolute-deviation softeners used in both papers. -/ +theorem abs_factor_logConcave (A a b : ℝ) (hA : 0 ≤ A) (n : ℕ) (hn : 2 ≤ n) : + factor A (fun k => |a+(k:ℝ)*b|) n * factor A (fun k => |a+(k:ℝ)*b|) (n-2) ≤ + (factor A (fun k => |a+(k:ℝ)*b|) (n-1))^2 := + factor_logConcave A hA _ n (abs_affine_convex a b n hn) + +/-- Positive-part small-slot penalties of the first paper. -/ +theorem positivePart_factor_logConcave (A a b : ℝ) (hA : 0 ≤ A) (n : ℕ) (hn : 2 ≤ n) : + factor A (fun k => max (a+(k:ℝ)*b) 0) n * factor A (fun k => max (a+(k:ℝ)*b) 0) (n-2) ≤ + (factor A (fun k => max (a+(k:ℝ)*b) 0) (n-1))^2 := by + apply factor_logConcave A hA + exact max_convex (fun k => a+(k:ℝ)*b) (fun _ => 0) n + (le_of_eq (affine_midpoint a b n hn)) (by simp) + +/-- Distance from a physical value ell+n to [0,b]. This formula applies +to the companion's unary tree penalties. -/ +noncomputable def intervalDistance (ell b : ℝ) (n : ℕ) : ℝ := + max 0 (max (-(ell+(n:ℝ))) (ell+(n:ℝ)-b)) + +lemma intervalDistance_convex (ell b : ℝ) (n : ℕ) (hn : 2 ≤ n) : + 2*intervalDistance ell b (n-1) ≤ intervalDistance ell b n+intervalDistance ell b (n-2) := by + unfold intervalDistance + apply max_convex (fun _ => 0) (fun k => max (-(ell+(k:ℝ))) (ell+(k:ℝ)-b)) n + · simp + · apply max_convex (fun k => -(ell+(k:ℝ))) (fun k => ell+(k:ℝ)-b) n + · have h := affine_midpoint (-ell) (-1) n hn + convert le_of_eq h using 1 <;> ring + · have h := affine_midpoint (ell-b) 1 n hn + convert le_of_eq h using 1 <;> ring + +/-- Unary distance softeners are positive and satisfy the exact integer +second-difference inequality needed by the product signature. -/ +theorem interval_factor_logConcave (A ell b : ℝ) (hA : 0 ≤ A) (n : ℕ) (hn : 2 ≤ n) : + factor A (intervalDistance ell b) n * factor A (intervalDistance ell b) (n-2) ≤ + (factor A (intervalDistance ell b) (n-1))^2 := + factor_logConcave A hA _ n (intervalDistance_convex ell b n hn) + +/-- The positive equality softener tends to its exact equality indicator. +This is the actual finite limiting operation used after marginalization. -/ +theorem factor_limit (D : ℝ) (hD : 0 ≤ D) : + Filter.Tendsto (fun A : ℝ => (2:ℝ)^(-A*D)) Filter.atTop + (nhds (if D=0 then 1 else 0)) := by + by_cases hzero : D=0 + · simp [hzero] + · have hpos : 0 < D := lt_of_le_of_ne hD (Ne.symm hzero) + let b : ℝ := (2:ℝ)^(-D) + have hb₀ : 0 < b := Real.rpow_pos_of_pos (by norm_num) _ + have hb₁ : b < 1 := Real.rpow_lt_one_of_one_lt_of_neg (by norm_num) (neg_lt_zero.mpr hpos) + have hlim := tendsto_rpow_atTop_of_base_lt_one b (by linarith) hb₁ + rw [ite_eq_right hzero] + convert hlim using 1 + funext A + dsimp [b] + rw [← Real.rpow_mul (by norm_num : (0:ℝ)≤2)] + congr 1 + ring + +/-- Products of positive scalar log-concave sequences remain log-concave. -/ +theorem mul_logConcave (a b : ℕ → ℝ) (n : ℕ) + (ha : a n*a (n-2) ≤ (a (n-1))^2) + (hb : b n*b (n-2) ≤ (b (n-1))^2) + (hapos : 0 ≤ a n*a (n-2)) (hbpos : 0 ≤ b n*b (n-2)) : + (a n*b n)*(a (n-2)*b (n-2)) ≤ (a (n-1)*b (n-1))^2 := by + have hh := mul_le_mul ha hb hbpos (hapos.trans ha) + convert hh using 1 <;> ring + +end ContingencyTables.ScalarPenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedMarginTranslation.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedMarginTranslation.lean new file mode 100644 index 0000000000000000000000000000000000000000..d09f5ab8b2d959ce3b21a616d82a5e990e2f4486 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedMarginTranslation.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallEntries + +namespace OAI + +/-! # The literal reference-row/reference-column completion translation -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +def star (R : Option I → ℤ) (P : Option J → ℤ) : Option I → Option J → ℤ + | some _,some _ => 0 + | some i,none => R (some i) + | none,some j => P (some j) + | none,none => R none-∑ j,P (some j) + +omit [Fintype I] in +lemma star_rows (R : Option I → ℤ) (P : Option J → ℤ) (i : Option I) : + (∑ j,star R P i j)=R i := by + cases i <;> simp only [Fintype.sum_option,star,Finset.sum_const_zero] <;> ring + +lemma star_columns (R : Option I → ℤ) (P : Option J → ℤ) + (htotal : (∑ i,R i)=∑ j,P j) (j : Option J) : (∑ i,star R P i j)=P j := by + cases j with + | none => + simp only [Fintype.sum_option] at htotal + simp only [Fintype.sum_option,star] + omega + | some j => simp only [Fintype.sum_option,star,Finset.sum_const_zero,add_zero] + +omit [Fintype I] in +lemma star_neg (R : Option I → ℤ) (P : Option J → ℤ) : + star (fun i => -R i) (fun j => -P j)=fun i j => -star R P i j := by + funext i j + cases i <;> cases j <;> simp only [star,Finset.sum_neg_distrib] <;> ring + +def between (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) : Option I → Option J → ℤ := + star (fun i => (R₁ i:ℤ)-R₀ i) (fun j => (P₁ j:ℤ)-P₀ j) + +omit [Fintype I] in +lemma between_rows (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) (i : Option I) : + (∑ j,between R₀ R₁ P₀ P₁ i j)=(R₁ i:ℤ)-R₀ i := star_rows _ _ i + +lemma between_columns (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) + (h₀ : (∑ i,R₀ i)=∑ j,P₀ j) (h₁ : (∑ i,R₁ i)=∑ j,P₁ j) (j : Option J) : + (∑ i,between R₀ R₁ P₀ P₁ i j)=(P₁ j:ℤ)-P₀ j := by + apply star_columns + simp only [Finset.sum_sub_distrib,← Nat.cast_sum,h₀,h₁] + +omit [Fintype I] in +lemma between_reverse (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) : + between R₁ R₀ P₁ P₀=fun i j => -between R₀ R₁ P₀ P₁ i j := by + have hR : (fun i => (R₀ i:ℤ)-R₁ i)=fun i => -((R₁ i:ℤ)-R₀ i) := by funext i; ring + have hP : (fun j => (P₀ j:ℤ)-P₁ j)=fun j => -((P₁ j:ℤ)-P₀ j) := by funext j; ring + unfold between + rw [hR,hP,star_neg] + +omit [Fintype I] in +lemma star_abs_le (R : Option I → ℤ) (P : Option J → ℤ) (M : ℤ) + (hM : 0 ≤ M) (hR : ∀ i,|R i| ≤ M) (hP : ∀ j,|P j| ≤ M) + (i : Option I) (j : Option J) : + |star R P i j| ≤ M*((Fintype.card J:ℤ)+1) := by + have hsum : |∑ j : J,P (some j)| ≤ (Fintype.card J:ℤ)*M := by + calc + _ ≤ ∑ j : J,|P (some j)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ _j : J,M := Finset.sum_le_sum (fun j _ => hP (some j)) + _ = _ := by simp + have hsingle : M ≤ M*((Fintype.card J:ℤ)+1) := by + nlinarith [mul_nonneg hM (Int.natCast_nonneg (Fintype.card J))] + cases i with + | some i => + cases j with + | some j => simpa only [star,abs_zero] using (mul_nonneg hM (by positivity : 0 ≤ (Fintype.card J:ℤ)+1)) + | none => exact (hR (some i)).trans hsingle + | none => + cases j with + | some j => exact (hP (some j)).trans hsingle + | none => + calc + _ ≤ |R none|+|∑ j : J,P (some j)| := abs_sub _ _ + _ ≤ M+(Fintype.card J:ℤ)*M := add_le_add (hR none) hsum + _ = _ := by ring + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..bef383cd6b71855b1dd94b53e201337497499c23 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/SignedTransport.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ContingencyTables.Transport.QuadraticTransport +import Mathlib.Algebra.Order.BigOperators.Ring.Finset + +namespace OAI + +/-! +# Signed transport at a leaf and at a paired split + +The signed-clique inequality, local potential increment and future quadratic +conservation give the counting paper's fixed-degree transport estimate. +Positivity of weights at unrelated degrees is unnecessary. +-/ + +namespace ContingencyTables.SignedTransport + +open scoped BigOperators +open LinearMap (BilinForm) + +section Clique + +variable {I : Type*} [Fintype I] [DecidableEq I] + +/-- The unordered complete exchange energy, expressed as half the ordered +sum, with the manuscript's minimum-endpoint conductance. -/ +noncomputable def cliqueEnergy (m W H : I → ℝ) : ℝ := + (∑ i, ∑ j, min (W i * m i) (W j * m j) * (H i - H j) ^ 2) / 2 + +/-- A star uses each unordered edge once, so its energy is at most the +complete unordered exchange energy. -/ +lemma star_energy_le (E : I → I → ℝ) + (hE : ∀ i j, 0 ≤ E i j) (hsymm : ∀ i j, E i j = E j i) + (hdiag : ∀ i, E i i = 0) (hub : I) : + ∑ i, E i hub ≤ (∑ i, ∑ j, E i j) / 2 := by + have hrest : (∑ i ∈ Finset.univ.erase hub, E i hub) ≤ + ∑ i ∈ Finset.univ.erase hub, ∑ j, E i j := by + apply Finset.sum_le_sum + intro i _ + exact Finset.single_le_sum (fun j _ => hE i j) (Finset.mem_univ hub) + rw [Finset.sum_erase (f := fun i => E i hub) _ (hdiag hub)] at hrest + have htotal := Finset.sum_erase_add Finset.univ (fun i => ∑ j, E i j) + (Finset.mem_univ hub) + have hrow : (∑ j, E hub j) = ∑ j, E j hub := by simp_rw [hsymm hub] + rw [hrow] at htotal + linarith + +/-- A balanced signed demand on the leaf clique has energy controlled by +its potential. This proves the squared inequality directly by weighted +Cauchy--Schwarz and the hub construction. -/ +theorem leaf_signed_transport [Nonempty I] (m W h H : I → ℝ) + (hm : ∀ i, 0 < m i) (hW : ∀ i, 0 < W i) + (hbalance : ∑ i, m i * h i = 0) : + (∑ i, m i * h i * H i) ^ 2 ≤ + (∑ i, m i * h i ^ 2 / W i) * cliqueEnergy m W H := by + obtain ⟨hub, _, hhub⟩ := Finset.exists_max_image Finset.univ + (fun i => W i * m i) Finset.univ_nonempty + have hdemand : (∑ i, m i * h i * (H i - H hub)) = ∑ i, m i * h i * H i := by + simp only [mul_sub, Finset.sum_sub_distrib, ← Finset.sum_mul, hbalance, + zero_mul, sub_zero] + have hcs : (∑ i, m i * h i * (H i - H hub)) ^ 2 ≤ + (∑ i, m i * h i ^ 2 / W i) * + ∑ i, W i * m i * (H i - H hub) ^ 2 := by + apply Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul Finset.univ + · intro i _ + exact div_nonneg (mul_nonneg (hm i).le (sq_nonneg _)) (hW i).le + · intro i _ + exact mul_nonneg (mul_pos (hW i) (hm i)).le (sq_nonneg _) + · intro i _ + have hw : W i ≠ 0 := ne_of_gt (hW i) + apply le_of_eq + field_simp + have hstar : (∑ i, W i * m i * (H i - H hub) ^ 2) ≤ cliqueEnergy m W H := by + have he := star_energy_le + (fun i j => min (W i * m i) (W j * m j) * (H i - H j) ^ 2) + (fun i j => mul_nonneg + (le_min (mul_pos (hW i) (hm i)).le (mul_pos (hW j) (hm j)).le) (sq_nonneg _)) + (by intro i j; rw [min_comm]; ring) (by intro i; simp) hub + simp_rw [min_eq_left (hhub _ (Finset.mem_univ _))] at he + exact he + rw [hdemand] at hcs + apply hcs.trans + apply mul_le_mul_of_nonneg_left hstar + exact Finset.sum_nonneg fun i _ => + div_nonneg (mul_nonneg (hm i).le (sq_nonneg _)) (hW i).le + +end Clique + +section Split + +variable {V : Type*} [AddCommGroup V] [Module ℝ V] + +/-- The exact Schur inequality for a paired binary split. The fresh +coordinates have zero diagonals and positive mixed entry. -/ +theorem split_signed_cost (B : BilinForm ℝ V) + (hsymm : ∀ x y, B x y = B y x) (hsig : OnePositiveDirection B) + (h ea eb : V) (u X : ℝ) (hu : 0 < u) + (haa : B ea ea = 0) (hbb : B eb eb = 0) (hab : B ea eb = u) + (hha : B h ea = -X) (hhb : B h eb = X) : + 2 * X ^ 2 / u ≤ -B h h := by + have hleft : B h ea = u * (-X / u) - 0 * 0 := by + rw [hha] + field_simp + ring + have hright : B h eb = 0 * 0 - u * (-X / u) := by + rw [hhb] + field_simp + ring + have hh := pair_step_of_signature B hsymm hsig h ea eb 0 u 0 0 (-X / u) 0 + haa hbb hab hleft hright (by rfl) (by rfl) (Or.inr (Or.inr ⟨rfl, rfl, hu⟩)) + have heq : 2 * u * (-X / u) ^ 2 - 0 * 0 ^ 2 - 0 * 0 ^ 2 = 2 * X ^ 2 / u := by + field_simp + ring + rwa [heq] at hh + +/-- Child coefficients of opposite signs preserve the future quadratic +form. This is the cancellation that lets each later slot be charged only +its root defect mass. -/ +theorem future_form_conservation (Ba Bb : BilinForm ℝ V) + (haSymm : ∀ x y, Ba x y = Ba y x) (hbSymm : ∀ x y, Bb x y = Bb y x) + (h ea eb : V) (c parent : ℝ) + (hold : Ba h h + Bb h h = parent) + (hcross : Ba h ea = Bb h eb) (haa : Ba ea ea = 0) (hbb : Bb eb eb = 0) : + Ba (h + c • ea) (h + c • ea) + Bb (h - c • eb) (h - c • eb) = parent := by + have hah : Ba ea h = Ba h ea := haSymm ea h + have hbh : Bb eb h = Bb h eb := hbSymm eb h + simp only [LinearMap.BilinForm.add_left, LinearMap.BilinForm.add_right, + LinearMap.BilinForm.sub_left, LinearMap.BilinForm.sub_right, + LinearMap.BilinForm.smul_left, LinearMap.BilinForm.smul_right, + haa, hbb, hah, hbh, hcross] + linarith [hold] + +end Split + +section SplitPotential + +variable {I : Type*} [Fintype I] + +/-- Splitting old masses and assigning the fresh-hole coefficients gives +exactly the manuscript's potential increment `2 X²/(u Wt)`. -/ +theorem split_potential_increment (sa sb h W : I → ℝ) (u X Wt : ℝ) + (hu : u ≠ 0) (hWt : Wt ≠ 0) : + ((∑ i, sa i * h i ^ 2 / W i) + u * (-X / u) ^ 2 / Wt) + + ((∑ i, sb i * h i ^ 2 / W i) + u * (X / u) ^ 2 / Wt) = + (∑ i, (sa i + sb i) * h i ^ 2 / W i) + 2 * X ^ 2 / (u * Wt) := by + simp only [add_mul, add_div, Finset.sum_add_distrib] + field_simp + ring + +/-- The new-hole coefficients balance the two child signed demands. -/ +theorem split_child_balance (sa sb h : I → ℝ) (u : ℝ) (hu : u ≠ 0) + (hbalance : ∑ i, (sa i + sb i) * h i = 0) : + let X := ∑ i, sa i * h i + (∑ i, sa i * h i) + u * (-X / u) = 0 ∧ + (∑ i, sb i * h i) + u * (X / u) = 0 := by + dsimp + simp only [add_mul, Finset.sum_add_distrib] at hbalance + constructor + · field_simp + ring + · field_simp + linarith [hbalance] + +end SplitPotential + +end ContingencyTables.SignedTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/SliceFactorial.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/SliceFactorial.lean new file mode 100644 index 0000000000000000000000000000000000000000..65b0d2578b93df90de456588d13987c350149810 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/SliceFactorial.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Transport.LabelledFactorial +import OAI.Combinatorics.ContingencyTables.Transport.BalancedBox + +namespace OAI + +/-! +# Actual fixed-total signatures give the labelled factorial properties + +Every subset count is in its true label-capacity box and its total is the +subset's cardinality. These identities connect the proved integer slice +signatures to the first factorial lift, without any binary-signature input. +-/ + +namespace ContingencyTables.SliceFactorial + +open scoped BigOperators Classical Matrix Topology +open CommonBasesFPRAS BinaryContraction FactorialSignatures LabelledFactorial BalancedBox + +variable {L C : Type*} [Fintype L] [Fintype C] + +omit [Fintype C] in +lemma groupCount_inBox (group : L → C) (S : Set L) : + InBox (groupCount group Set.univ) (groupCount group S) := by + intro c + apply Finset.card_le_card + intro i hi + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Set.mem_univ] at hi ⊢ + exact hi.2 + +/-- Positivity of the proved actual total-slice marginal gives positivity +of the literal labelled factorial lift on exactly that subset degree. -/ +theorem firstLift_degreePositive (group : L → C) (h : (C → ℕ) → ℝ) (D : ℝ) (R : ℕ) + (hD : 0 < D) (hpos : PositiveSlice h (groupCount group Set.univ) R) : + DegreePositive (firstLift group h D) R := by + intro S hS + apply div_pos _ hD + apply mul_pos _ (factorialProduct_positive _) + apply hpos _ (groupCount_inBox group S) + rw [groupCount_total,hS] + +/-- The exact box-valid raw removal signature implies the omission +property of the manuscript's first lift at its original degree. -/ +theorem firstLift_omission_slice (group : L → C) (h : (C → ℕ) → ℝ) (D : ℝ) (R : ℕ) + (hD : 0 < D) (hh : ∀ z, 0 ≤ h z) + (hsig : RemovalSlice h (groupCount group Set.univ) R) : + OmissionProperty (firstLift group h D) R := by + apply firstLift_omission group h D R hD hh + intro A hA + apply hsig _ (groupCount_inBox group Aᶜ) + rw [groupCount_total] + have hc := Set.ncard_add_ncard_compl A + simp only [Nat.card_eq_fintype_card] at hc + omega + +/-- Pointwise limits of actual integer marginals pass directly to their +literal subset factorial displays. -/ +theorem firstLift_tendsto {K : Type*} {l : Filter K} + (group : L → C) (F : K → (C → ℕ) → ℝ) (h : (C → ℕ) → ℝ) (D : ℝ) + (hlim : ∀ z, Filter.Tendsto (fun t => F t z) l (nhds (h z))) (S : Set L) : + Filter.Tendsto (fun t => firstLift group (F t) D S) l (nhds (firstLift group h D S)) := + ((hlim (groupCount group S)).mul_const (factorialProduct (groupCount group S))).div_const D + +end ContingencyTables.SliceFactorial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/SoftWeightUpper.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/SoftWeightUpper.lean new file mode 100644 index 0000000000000000000000000000000000000000..d02993b5d31f5f38154279c7db72da150d72e1a3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/SoftWeightUpper.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.ContingencyTables.Transport.EqualitySoftening +import OAI.Combinatorics.ContingencyTables.Transport.BalancedEnumeration + +namespace OAI + +/-! # Uniform upper mass of the positive physical softening family -/ + +namespace ContingencyTables.EqualitySoftening + +open scoped BigOperators Classical +open ScalarPenalty ProductIntegerSignature BalancedFamily BalancedEnumeration + +lemma factor_le_one (A : ℝ) (p : ℕ → ℝ) (hA : 0 ≤ A) (n : ℕ) (hp : 0 ≤ p n) : + factor A p n ≤ 1 := by + unfold factor + calc + (2:ℝ)^(-A*p n) ≤ (2:ℝ)^(0:ℝ) := Real.rpow_le_rpow_of_exponent_le (by norm_num) + (mul_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr hA) hp) + _ = 1 := by norm_num + +variable {C G : Type*} [Fintype C] [Fintype G] + +/-- Every actual line/unary soft factor lies in (0,1], even before +the exact nonroot equations are imposed. -/ +theorem softenedWeight_le_one (line : C → G) (root : G → Bool) + (rate offset slope : G → ℝ) (urate ell uslope cap : C → ℝ) (L : ℝ) + (hrate : ∀ g,0 ≤ rate g) (hu : ∀ i,0 ≤ urate i) (hL : 0 ≤ L) (z : C → ℕ) : + softenedWeight line root rate offset slope urate ell uslope cap L z ≤ 1 := by + have hl (g : G) : lineFactor root rate offset slope L g (lineTotal line z g) ≤ 1 := by + apply factor_le_one + · split_ifs + · exact hrate g + · exact hL + · exact abs_nonneg _ + have hun (i : C) : unaryFactor urate ell uslope cap i (z i) ≤ 1 := + factor_le_one _ _ (hu i) _ (le_max_left _ _) + have hprodL : (∏ g,lineFactor root rate offset slope L g (lineTotal line z g)) ≤ 1 := by + calc + _ ≤ ∏ _g : G,(1:ℝ) := Finset.prod_le_prod₀ (fun _ _ => (factor_positive _ _ _).le) (fun g _ => hl g) + _ = _ := by simp + have hprodU : (∏ i,unaryFactor urate ell uslope cap i (z i)) ≤ 1 := by + calc + _ ≤ ∏ _i : C,(1:ℝ) := Finset.prod_le_prod₀ (fun _ _ => (factor_positive _ _ _).le) (fun i _ => hun i) + _ = _ := by simp + have hnonneg : 0 ≤ ∏ i,unaryFactor urate ell uslope cap i (z i) := + Finset.prod_nonneg (fun _ _ => (factor_positive _ _ _).le) + unfold softenedWeight productWeight + exact (mul_le_mul_of_nonneg_right hprodL hnonneg).trans + (by simpa only [one_mul] using hprodU) + + +end ContingencyTables.EqualitySoftening + +namespace ContingencyTables.BalancedEnumeration + +open scoped BigOperators Classical +open BalancedFamily + +/-- The positive softened marginal is bounded by its finite number of +physical balanced assignments, uniformly in the softening parameter. -/ +theorem eliminate_le_card {S : Type*} (Ms : List ℕ) + (F : (Coordinates S Ms → ℕ) → ℝ) (hF : ∀ z,F z ≤ 1) (z : S → ℕ) : + eliminate Ms F z ≤ (Fintype.card (Assignments Ms):ℝ) := by + rw [eliminate_eq_sum] + calc + _ ≤ ∑ _a : Assignments Ms,(1:ℝ) := Finset.sum_le_sum (fun a _ => hF (embedding Ms z a)) + _ = _ := by simp + +end ContingencyTables.BalancedEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/StarReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/StarReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..65608baffa28080a1d350ef4137657f9ba8830ec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/StarReindex.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Transport.SignedMarginTranslation +import OAI.Combinatorics.ContingencyTables.Transport.TableReindex + +namespace OAI + +/-! # The completion shift is invariant under computed tail indexing -/ + +namespace ContingencyTables.CompletionTranslation +open scoped BigOperators + +variable {I J I' J' : Type*} [Fintype I] [Fintype J] [Fintype I'] [Fintype J'] + +lemma sum_some_reindex (e : Option I' ≃ Option I) (he : e none=none) (f : Option I → ℤ) : + (∑ i,f (e (some i)))=∑ i,f (some i) := by + have h := e.sum_comp f + simp only [Fintype.sum_option,he] at h + exact add_left_cancel h + +omit [Fintype I] [Fintype I'] in +lemma reindex_some_ne_none (e : Option I' ≃ Option I) (he : e none=none) (i : I') : + e (some i)≠none := by + intro h + have h' := e.injective (h.trans he.symm) + cases h' + +omit [Fintype I] [Fintype I'] in +theorem star_reindex (eI : Option I' ≃ Option I) (eJ : Option J' ≃ Option J) + (hI : eI none=none) (hJ : eJ none=none) (R : Option I → ℤ) (P : Option J → ℤ) + (i : Option I') (j : Option J') : + star (fun i => R (eI i)) (fun j => P (eJ j)) i j=star R P (eI i) (eJ j) := by + cases i with + | none => + cases j with + | none => + simp only [star,hI,hJ] + rw [sum_some_reindex eJ hJ] + | some j => + rcases h : eJ (some j) with _|j' + · exact False.elim (reindex_some_ne_none eJ hJ j h) + · simp only [star,hI,h] + | some i => + rcases h : eI (some i) with _|i' + · exact False.elim (reindex_some_ne_none eI hI i h) + · cases j with + | none => simp only [star,h,hJ] + | some j => + rcases h' : eJ (some j) with _|j' + · exact False.elim (reindex_some_ne_none eJ hJ j h') + · rfl + +omit [Fintype I] [Fintype I'] in +theorem between_reindex (eI : Option I' ≃ Option I) (eJ : Option J' ≃ Option J) + (hI : eI none=none) (hJ : eJ none=none) + (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) + (i : Option I') (j : Option J') : + between (fun i => R₀ (eI i)) (fun i => R₁ (eI i)) + (fun j => P₀ (eJ j)) (fun j => P₁ (eJ j)) i j= + between R₀ R₁ P₀ P₁ (eI i) (eJ j) := + star_reindex eI eJ hI hJ (fun i => (R₁ i:ℤ)-R₀ i) (fun j => (P₁ j:ℤ)-P₀ j) i j + +theorem translated_nonnegative_reindex (eI : Option I' ≃ Option I) (eJ : Option J' ≃ Option J) + (hI : eI none=none) (hJ : eJ none=none) + (R₀ R₁ : Option I → ℕ) (P₀ P₁ : Option J → ℕ) (X : Table R₀ P₀) : + (∀ i j,0 ≤ (((tableReindex eI eJ R₀ P₀) X).val i j:ℤ)+ + between (fun i => R₀ (eI i)) (fun i => R₁ (eI i)) + (fun j => P₀ (eJ j)) (fun j => P₁ (eJ j)) i j) ↔ + ∀ i j,0 ≤ (X.val i j:ℤ)+between R₀ R₁ P₀ P₁ i j := by + change (∀ i j,0 ≤ (X.val (eI i) (eJ j):ℤ)+ + between (fun i => R₀ (eI i)) (fun i => R₁ (eI i)) + (fun j => P₀ (eJ j)) (fun j => P₁ (eJ j)) i j) ↔ _ + simp only [between_reindex eI eJ hI hJ] + constructor + · intro h i j + simpa only [Equiv.apply_symm_apply] using h (eI.symm i) (eJ.symm j) + · intro h i j + exact h (eI i) (eJ j) + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/StateSuccessEntries.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/StateSuccessEntries.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed03cb382a713a91b49f870e02b36911fabfa35f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/StateSuccessEntries.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessEvent + +namespace OAI + +/-! # The successful state-to-table map removes precisely the large padding -/ + +namespace ContingencyTables.SmallGraphProfiles +open PhysicalCompletionFibres FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts +open scoped BigOperators Classical + +noncomputable section +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +lemma originalStateSuccessEquiv_symm_entry (r : I → ℕ) (c : J → ℕ) + (a : SuccessfulStateJoint r c) (i : I) (j : J) : + ((originalStateSuccessEquiv r c).symm a).val i j= + a.val.2.val.val.1 i j- + largePadding (paperLarge r c) ((dimensionAllowance (I := I) (J := J))^12) i j := by + change (unpadSuccessfulJoint r c ((successStateEquiv r c).symm a)).val i j=_ + rw [unpadSuccessfulJoint_val] + apply congrArg (fun t : ℕ => t-_) + exact congrArg (fun t => t.val.1 i j) + (balancedJointFromState_projection r c a.val a.property.1) + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/SuccessfulJointBijection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/SuccessfulJointBijection.lean new file mode 100644 index 0000000000000000000000000000000000000000..f47220a8f41617c037f16414836dda76944dc3f6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/SuccessfulJointBijection.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.OriginalBalancedJoint +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessRatio + +namespace OAI + +/-! # The literal successful balanced pairs are exactly the original tables -/ + +namespace ContingencyTables.SmallGraphProfiles + +open scoped BigOperators Classical +open PhysicalCompletionFibres FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +abbrev PaperJoint (r : I → ℕ) (c : J → ℕ) := + BalancedJoint (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + +noncomputable def jointTable (r : I → ℕ) (c : J → ℕ) (a : PaperJoint r c) := + balancedJointTable (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + (stateCapacity_small r c) a + +abbrev SuccessfulJoint (r : I → ℕ) (c : J → ℕ) := + {a : PaperJoint r c // ∀ i j,paperSmall r c i j=false → + (dimensionAllowance (I := I) (J := J))^12 ≤ (jointTable r c a).val i j} + +noncomputable def originalSuccessfulJoint (r : I → ℕ) (c : J → ℕ) (X : Table r c) : + SuccessfulJoint r c := by + refine ⟨paperOriginalJoint r c X,?_⟩ + intro i j hs + unfold jointTable + rw [paperOriginalJoint_projection] + simp only [paddedOriginal,hs,Bool.false_eq_true,ite_false] + omega + +noncomputable def unpadSuccessfulJoint (r : I → ℕ) (c : J → ℕ) + (a : SuccessfulJoint r c) : Table r c := by + let L := (dimensionAllowance (I := I) (J := J))^12 + let P := largePadding (paperLarge r c) L + let Y := jointTable r c a.val + have hm : HasMargins Y.val (paddedRows r P) (paddedColumns c P) := by + dsimp only [P,paperLarge] + rw [large_padding_rows,large_padding_columns] + exact Y.property + exact unpadTable P ⟨Y.val,hm⟩ (by + intro i j + cases hs : paperSmall r c i j with + | false => simpa only [P,paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ, + true_and,hs,ite_true] using a.property i j hs + | true => simp [P,paperLarge,largePadding,hs]) + +lemma unpadSuccessfulJoint_val (r : I → ℕ) (c : J → ℕ) (a : SuccessfulJoint r c) (i : I) (j : J) : + (unpadSuccessfulJoint r c a).val i j=(jointTable r c a.val).val i j- + largePadding (paperLarge r c) ((dimensionAllowance (I := I) (J := J))^12) i j := rfl + +/-- Each success produces exactly one original table, and every original +table has exactly one successful state/completion preimage. -/ +noncomputable def successfulJointEquiv (r : I → ℕ) (c : J → ℕ) : + Table r c ≃ SuccessfulJoint r c where + toFun := originalSuccessfulJoint r c + invFun := unpadSuccessfulJoint r c + left_inv X := by + apply Subtype.ext + funext i j + rw [unpadSuccessfulJoint_val] + change (jointTable r c (paperOriginalJoint r c X)).val i j-_=X.val i j + unfold jointTable + rw [paperOriginalJoint_projection] + cases hs : paperSmall r c i j <;> simp [paddedOriginal,paperLarge,largePadding,hs] + right_inv a := by + apply Subtype.ext + apply balancedJointTable_injective (paperSmall r c) (stateCapacity r c) r c + ((dimensionAllowance (I := I) (J := J))^12) ((dimensionAllowance (I := I) (J := J))^20) + (stateCapacity_small r c) + change jointTable r c (paperOriginalJoint r c (unpadSuccessfulJoint r c a))=jointTable r c a.val + unfold jointTable at ⊢ + rw [paperOriginalJoint_projection] + apply Subtype.ext + funext i j + change (unpadSuccessfulJoint r c a).val i j+ + (if paperSmall r c i j then 0 else (dimensionAllowance (I := I) (J := J))^12)=_ + rw [unpadSuccessfulJoint_val] + cases hs : paperSmall r c i j with + | false => + have ha := a.property i j hs + simpa only [paperLarge,largePadding,Finset.mem_filter,Finset.mem_univ,true_and, + hs,ite_true,Bool.false_eq_true,ite_false,jointTable] using Nat.sub_add_cancel ha + | true => simp [paperLarge,largePadding,hs,jointTable] + +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TableMarginTransport.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableMarginTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..34a21c3be7b73db074af502fd6b228fb1de891e4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableMarginTransport.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TableReindex + +namespace OAI + +/-! # Changing equal margin descriptions without changing entries -/ + +namespace ContingencyTables +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Enumeration instances affect the proofs of the margins, never the entries. -/ +def tableFintypeTransport (fi fi' : Fintype I) (fj fj' : Fintype J) + (r : I → ℕ) (c : J → ℕ) : @Table I J fi fj r c ≃ @Table I J fi' fj' r c where + toFun X := ⟨X.val,by + cases Subsingleton.elim fi fi' + cases Subsingleton.elim fj fj' + exact X.property⟩ + invFun X := ⟨X.val,by + cases Subsingleton.elim fi fi' + cases Subsingleton.elim fj fj' + exact X.property⟩ + left_inv X := rfl + right_inv X := rfl + +def tableMarginTransport (r r' : I → ℕ) (c c' : J → ℕ) + (hr : r=r') (hc : c=c') : Table r c ≃ Table r' c' where + toFun X := ⟨X.val,by rw [←hr,←hc]; exact X.property⟩ + invFun X := ⟨X.val,by rw [hr,hc]; exact X.property⟩ + left_inv X := rfl + right_inv X := rfl + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TableReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..787c6a9882e6700b5502fd804a4e1d2dbe4a7fcb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableReindex.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.ContingencyTables.Model +import Mathlib.Algebra.BigOperators.Group.Finset.Pi + +namespace OAI + +/-! # Relabeling a rectangular completion, preserving every table -/ + +namespace ContingencyTables + +open scoped BigOperators + +variable {I J I' J' : Type*} [Fintype I] [Fintype J] [Fintype I'] [Fintype J'] + +def tableReindex (eI : I' ≃ I) (eJ : J' ≃ J) (r : I → ℕ) (c : J → ℕ) : + Table r c ≃ Table (fun i => r (eI i)) (fun j => c (eJ j)) where + toFun X := ⟨fun i j => X.val (eI i) (eJ j), + fun i => (eJ.sum_comp (X.val (eI i))).trans (X.property.1 (eI i)), + fun j => (eI.sum_comp (fun i => X.val i (eJ j))).trans (X.property.2 (eJ j))⟩ + invFun X := ⟨fun i j => X.val (eI.symm i) (eJ.symm j),by + constructor + · intro i + rw [eJ.symm.sum_comp] + simpa only [Equiv.apply_symm_apply] using X.property.1 (eI.symm i) + · intro j + exact (eI.symm.sum_comp (fun i => X.val i (eJ.symm j))).trans (by + simpa only [Equiv.apply_symm_apply] using X.property.2 (eJ.symm j))⟩ + left_inv X := by + apply Subtype.ext + funext i j + simp only [Equiv.apply_symm_apply] + right_inv X := by + apply Subtype.ext + funext i j + simp only [Equiv.symm_apply_apply] + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TableTightening.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableTightening.lean new file mode 100644 index 0000000000000000000000000000000000000000..c56e509e1157cf8cff515811922e79d8e0dd2061 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TableTightening.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Model + +namespace OAI + +/-! # Simultaneous tightening and translation by attained cell minima + +The hypotheses here are exactly the extremum properties proved for the +executed searches. The maps preserve all tables, with explicit inverse +addition and with both endpoints of every translated interval attained. +-/ + +namespace ContingencyTables.TableTightening + +open scoped BigOperators + +variable {m n : ℕ} + +def subtract (X l : Fin m→Fin n→ℕ) (i : Fin m) (j : Fin n) : ℕ := X i j-l i j +def add (Y l : Fin m→Fin n→ℕ) (i : Fin m) (j : Fin n) : ℕ := Y i j+l i j + +def rows (r : Fin m→ℕ) (l : Fin m→Fin n→ℕ) (i : Fin m) : ℕ := r i-∑ j,l i j +def columns (c : Fin n→ℕ) (l : Fin m→Fin n→ℕ) (j : Fin n) : ℕ := c j-∑ i,l i j + +def bounds (l u : Fin m→Fin n→ℕ) (i : Fin m) (j : Fin n) : ℕ := u i j-l i j + +lemma add_subtract (X l : Fin m→Fin n→ℕ) (hl : ∀ i j,l i j≤X i j) : + add (subtract X l) l=X := by + funext i j + exact Nat.sub_add_cancel (hl i j) + +lemma subtract_add (Y l : Fin m→Fin n→ℕ) : subtract (add Y l) l=Y := by + funext i j + exact Nat.add_sub_cancel _ _ + +lemma subtract_margins (X l : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hl : ∀ i j,l i j≤X i j) : + HasMargins (subtract X l) (rows r l) (columns c l) := by + constructor + · intro i + have he : (∑ j,subtract X l i j)+(∑ j,l i j)=r i := by + rw [←Finset.sum_add_distrib,←hm.1 i] + apply Finset.sum_congr rfl + intro j _ + exact Nat.sub_add_cancel (hl i j) + unfold rows + omega + · intro j + have he : (∑ i,subtract X l i j)+(∑ i,l i j)=c j := by + rw [←Finset.sum_add_distrib,←hm.2 j] + apply Finset.sum_congr rfl + intro i _ + exact Nat.sub_add_cancel (hl i j) + unfold columns + omega + +lemma lower_sums (X l : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hm : HasMargins X r c) (hl : ∀ i j,l i j≤X i j) : + (∀ i,(∑ j,l i j)≤r i) ∧ (∀ j,(∑ i,l i j)≤c j) := by + constructor + · intro i + rw [←hm.1 i] + exact Finset.sum_le_sum (fun j _=>hl i j) + · intro j + rw [←hm.2 j] + exact Finset.sum_le_sum (fun i _=>hl i j) + +lemma add_margins (Y l : Fin m→Fin n→ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) + (hr : ∀ i,(∑ j,l i j)≤r i) (hc : ∀ j,(∑ i,l i j)≤c j) + (hm : HasMargins Y (rows r l) (columns c l)) : HasMargins (add Y l) r c := by + constructor + · intro i + simpa only [add,Finset.sum_add_distrib,hm.1 i,rows] using Nat.sub_add_cancel (hr i) + · intro j + simpa only [add,Finset.sum_add_distrib,hm.2 j,columns] using Nat.sub_add_cancel (hc j) + +variable (r : Fin m→ℕ) (c : Fin n→ℕ) (b l u : Fin m→Fin n→ℕ) + +def Feasible (X : Fin m→Fin n→ℕ) : Prop := HasMargins X r c ∧ ∀ i j,X i j≤b i j + +def TightFeasible (Y : Fin m→Fin n→ℕ) : Prop := + HasMargins Y (rows r l) (columns c l) ∧ ∀ i j,Y i j≤bounds l u i j + +/-- A feasible table lies in every attained coordinate interval. -/ +theorem subtract_feasible (hl : ∀ X,Feasible r c b X→∀ i j,l i j≤X i j) + (hu : ∀ X,Feasible r c b X→∀ i j,X i j≤u i j) + {X : Fin m→Fin n→ℕ} (hX : Feasible r c b X) : + TightFeasible r c l u (subtract X l) := by + refine ⟨subtract_margins X l r c hX.1 (hl X hX),?_⟩ + intro i j + exact Nat.sub_le_sub_right (hu X hX i j) (l i j) + +theorem add_feasible (hne : ∃ X,Feasible r c b X) + (hl : ∀ X,Feasible r c b X→∀ i j,l i j≤X i j) + (hu : ∀ i j,u i j≤b i j) + {Y : Fin m→Fin n→ℕ} (hY : TightFeasible r c l u Y) : + Feasible r c b (add Y l) := by + obtain ⟨X,hX⟩ := hne + have hs := lower_sums X l r c hX.1 (hl X hX) + refine ⟨add_margins Y l r c hs.1 hs.2 hY.1,?_⟩ + intro i j + have hlo := (hl X hX i j).trans (hX.2 i j) + have hbound := hY.2 i j + change Y i j≤u i j-l i j at hbound + change Y i j+l i j≤b i j + have hup := hu i j + omega + +/-- Both translated endpoints are actual table entries, including when +an interval has width zero. -/ +theorem endpoints (hl : ∀ X,Feasible r c b X→∀ i j,l i j≤X i j) + (hu : ∀ X,Feasible r c b X→∀ i j,X i j≤u i j) + (hlo : ∀ i j,∃ X,Feasible r c b X ∧ X i j=l i j) + (hup : ∀ i j,∃ X,Feasible r c b X ∧ X i j=u i j) : + (∀ i j,∃ Y,TightFeasible r c l u Y ∧ Y i j=0) ∧ + (∀ i j,∃ Y,TightFeasible r c l u Y ∧ Y i j=bounds l u i j) := by + constructor + · intro i j + obtain ⟨X,hX,he⟩ := hlo i j + refine ⟨subtract X l,subtract_feasible r c b l u hl hu hX,?_⟩ + simp only [subtract,he,Nat.sub_self] + · intro i j + obtain ⟨X,hX,he⟩ := hup i j + refine ⟨subtract X l,subtract_feasible r c b l u hl hu hX,?_⟩ + simp only [subtract,he,bounds] + +end ContingencyTables.TableTightening + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationMeasureBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationMeasureBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfdf98e257415f73465bd92337725ded3d1f5b48 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationMeasureBounds.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Machines.EnumerationPointBounds +import OAI.Combinatorics.ContingencyTables.Sampling.PaddedEnumerationBounds +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixProgram +import OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixProgram + +namespace OAI + +/-! # Bounding the nested measures of the executed profile tabulation -/ + +namespace ContingencyTables.MeasuredMap +open MatchingFPRAS MatchingFPRAS.TreeTyped + +lemma listMeasure_le {A B : Type} [Codec A] [Codec B] (μ : A×B → ℕ) + (a : A) (bs : List B) (M : ℕ) (h : ∀ b∈bs,μ (a,b) ≤ M) : + listMeasure μ (a,bs) ≤ weight (a,bs)+bs.length*M := by + have hs := ProfilePrograms.list_sum_le_length_mul + (bs.map (fun b => μ (a,b))) M (by + intro n hn + obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hn + exact h b hb) + simpa only [listMeasure,List.length_map] using Nat.add_le_add_left hs (weight (a,bs)) + +lemma listMeasure_mono {A B : Type} [Codec A] [Codec B] (μ ν : A×B → ℕ) + (a : A) (bs : List B) (h : ∀ b∈bs,μ (a,b) ≤ ν (a,b)) : + listMeasure μ (a,bs) ≤ listMeasure ν (a,bs) := by + have hs : (bs.map (fun b => μ (a,b))).sum ≤ (bs.map (fun b => ν (a,b))).sum := by + induction bs with + | nil => simp + | cons b bs ih => + simp only [List.map_cons,List.sum_cons] + exact Nat.add_le_add (h b (by simp)) + (ih (by intro c hc; exact h c (by simp [hc]))) + exact Nat.add_le_add_left hs _ + +end ContingencyTables.MeasuredMap + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +lemma list_weight_bound {A : Type} [Codec A] (as : List A) (W : ℕ) + (h : ∀ a∈as,weight a ≤ W) : weight as ≤ as.length*(W+1)+1 := by + simpa only [List.map_id,id_eq] using weight_map_bound (f := id) (as := as) h + +/-- The two loops over the profile box cost a polynomial in its +cardinality and the uniform measure of a single transition entry. -/ +lemma profileMatrixMeasure_le (z : MatrixParameters) (W M : ℕ) + (hz : weight z ≤ W) + (hv : ∀ v∈profileBoxViews (matrixData z),weight v ≤ W) + (he : ∀ u∈profileBoxViews (matrixData z),∀ v∈profileBoxViews (matrixData z), + matrixEntryMeasure (z,(u,v)) ≤ M) : + let N := gridStateCount (profileEnumerationData (matrixData z)) + profileMatrixMeasure z ≤ (N+1)^2*(M+3*W+7) := by + let vs := profileBoxViews (matrixData z) + let N := gridStateCount (profileEnumerationData (matrixData z)) + have hlen : vs.length=N := profileBoxViews_length _ + have hvs : weight vs ≤ N*(W+1)+1 := by + simpa only [hlen] using list_weight_bound vs W hv + have hc (v : List ℕ×List ℕ) (hv' : v∈vs) : + matrixColumnMeasure (z,v) ≤ (N+1)*(M+2*W+4) := by + have hpair : weight ((z,v),vs) ≤ (N+1)*(2*W+3) := by + have hw := hv v hv' + simp only [weight_prod] + nlinarith + have hsum := MeasuredMap.listMeasure_le columnEntryMeasure (z,v) vs M (by + intro u hu + exact he u hu v hv') + have hh : matrixColumnMeasure (z,v) ≤ N+(N+1)*(2*W+3)+N*M := by + unfold matrixColumnMeasure + change N+MeasuredMap.listMeasure columnEntryMeasure ( (z,v),vs) ≤ _ + rw [hlen] at hsum + omega + exact hh.trans (by nlinarith) + have hout : weight (z,vs) ≤ (N+1)*(W+2) := by + simp only [weight_prod] + nlinarith + have hs := MeasuredMap.listMeasure_le matrixColumnMeasure z vs + ((N+1)*(M+2*W+4)) hc + rw [hlen] at hs + have hm : profileMatrixMeasure z ≤ + N+(N+1)*(W+2)+N*((N+1)*(M+2*W+4)) := by + unfold profileMatrixMeasure + change N+MeasuredMap.listMeasure matrixColumnMeasure (z,vs) ≤ _ + omega + have h1 : N ≤ (N+1)^2 := by nlinarith + have h2 : N+1 ≤ (N+1)^2 := Nat.le_self_pow (by decide) _ + have h3 : N*(N+1) ≤ (N+1)^2 := by nlinarith + calc + _ ≤ N+(N+1)*(W+2)+N*((N+1)*(M+2*W+4)) := hm + _ ≤ (N+1)^2+(N+1)^2*(W+2)+(N+1)^2*(M+2*W+4) := by + exact Nat.add_le_add (Nat.add_le_add h1 (Nat.mul_le_mul_right _ h2)) + (by rw [←Nat.mul_assoc]; exact Nat.mul_le_mul_right _ h3) + _ = (N+1)^2*(M+3*W+7) := by ring + +lemma unitMatrixMeasure_le (z : MatrixParameters) : + UnitCountPrograms.profileMatrixMeasure z ≤ profileMatrixMeasure z := by + unfold UnitCountPrograms.profileMatrixMeasure profileMatrixMeasure + apply Nat.add_le_add_left + apply MeasuredMap.listMeasure_mono + intro v _ + unfold UnitCountPrograms.matrixColumnMeasure matrixColumnMeasure + apply Nat.add_le_add_left + apply MeasuredMap.listMeasure_mono + intro u _ + change UnitCountPrograms.entryMeasure (columnEntryInput ((z,v),u)) ≤ + matrixEntryMeasure (columnEntryInput ((z,v),u)) + unfold UnitCountPrograms.entryMeasure matrixEntryMeasure + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationPreparationBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationPreparationBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee0b8bd10a7d7f5693f19f3d6a29b4e926a73980 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TabulationPreparationBounds.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileVectorMeasureBounds +import OAI.Combinatorics.ContingencyTables.Machines.ScheduledScalarBounds + +namespace OAI + +/-! # Polynomial binary sizes before finite tabulation begins -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +theorem tabulation_preparation_polynomial : ∃ p : Polynomial ℕ,∀ z, + let M := p.eval (scheduledCountInputMeasure z) + weight (scheduledOuterInput z) ≤ M ∧ + parameterDimension z+parameterAccuracy z+parameterCompletionWidth z ≤ M ∧ + (∀ v∈profileBoxViews (initialCheck z.1),weight v ≤ M) ∧ + (∀ o∈originalCandidates z.1,weight o ≤ M ∧ weight (o.getD []) ≤ M) ∧ + (∀ u∈profileBoxViews (initialCheck z.1),∀ v∈profileBoxViews (initialCheck z.1), + weight (scheduledMatrixParameters z,(u,v)) ≤ M) := by + obtain ⟨a,ha⟩ := work_scheduledOuterInput + obtain ⟨b,hb⟩ := schedule_numeric_polynomial + obtain ⟨c,hc⟩ := polynomial_initialCheck + obtain ⟨v,hv⟩ := profileBoxViews_point_polynomial + obtain ⟨o,ho⟩ := originalCandidates_point_polynomial + obtain ⟨t,ht⟩ := polynomial_optionalTrialInput + let w := a+b+v.comp c+o+X+1 + let g := w+t.comp (1+2*w)+2+3*w + refine ⟨g,?_⟩ + intro z + let K := scheduledCountInputMeasure z + have hz : weight z ≤ K := by unfold K scheduledCountInputMeasure; omega + have hmargin : weight z.1 ≤ K := (weight_fst z).trans hz + have houter : weight (scheduledOuterInput z) ≤ a.eval K := + (Nat.le_add_left _ _).trans (ha z) + have hnum : parameterDimension z+parameterAccuracy z+parameterCompletionWidth z ≤ b.eval K := hb z + have hcheck : weight (initialCheck z.1) ≤ c.eval K := + (Nat.le_add_left _ _).trans ((hc z.1).trans (polynomial_eval_monotone c hmargin)) + have hview (u : List ℕ×List ℕ) (hu : u∈profileBoxViews (initialCheck z.1)) : + weight u ≤ (v.comp c).eval K := by + rw [eval_comp] + exact (hv _ u hu).trans (polynomial_eval_monotone v hcheck) + have horig (u : Option MatrixCode) (hu : u∈originalCandidates z.1) : + weight u ≤ o.eval K := (ho _ u hu).trans (polynomial_eval_monotone o hmargin) + have hwa : a.eval K ≤ w.eval K := by simp only [w,eval_add,eval_one,eval_X]; omega + have hwb : b.eval K ≤ w.eval K := by simp only [w,eval_add,eval_one,eval_X]; omega + have hwv : (v.comp c).eval K ≤ w.eval K := by simp only [w,eval_add,eval_one,eval_X]; omega + have hwo : o.eval K ≤ w.eval K := by simp only [w,eval_add,eval_one,eval_X]; omega + have hwg : w.eval K ≤ g.eval K := by simp only [g,eval_add,eval_mul,eval_ofNat]; omega + have hwalk : weight (scheduledWalkInput z) ≤ w.eval K := by + have hp : (scheduledOuterInput z).1.1=scheduledWalkInput z := rfl + rw [←hp] + exact ((weight_fst _).trans (weight_fst _)).trans (houter.trans hwa) + refine ⟨(houter.trans hwa).trans hwg,(hnum.trans hwb).trans hwg, + (fun u hu => ((hview u hu).trans hwv).trans hwg),?_,?_⟩ + · intro u hu + have hou : weight u ≤ w.eval K := (horig u hu).trans hwo + refine ⟨hou.trans hwg,?_⟩ + have hi : weight (scheduledWalkInput z,u) ≤ (1+2*w).eval K := by + simp only [weight_prod,eval_add,eval_one,eval_mul,eval_ofNat] + omega + have hdef : weight (u.getD []) ≤ t.eval ((1+2*w).eval K) := + (weight_snd (optionalTrialInput (scheduledWalkInput z,u))).trans + ((Nat.le_add_left _ _).trans ((ht _).trans (polynomial_eval_monotone t hi))) + apply hdef.trans + change t.eval ((1+2*w).eval K) ≤ g.eval K + simp only [g,eval_add,eval_comp,eval_mul,eval_ofNat,eval_one] + omega + · intro u hu v' hv' + have hu' := (hview u hu).trans hwv + have hv'' := (hview v' hv').trans hwv + have hm : weight (scheduledMatrixParameters z) ≤ w.eval K := by + have hp : (scheduledWalkInput z).1=scheduledMatrixParameters z := rfl + rw [←hp] + exact (weight_fst _).trans hwalk + change weight (scheduledMatrixParameters z,(u,v')) ≤ g.eval K + simp only [weight_prod,g,eval_add,eval_mul,eval_ofNat] + omega + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TerminalMassCover.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TerminalMassCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a0fc9ac1e068ee65165d7c9582001b1697e3420 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TerminalMassCover.lean @@ -0,0 +1,71 @@ +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity + +namespace OAI + +/-! # Finite mass accounting for the terminal far and near regions -/ + +namespace ContingencyTables.TerminalMassCover + +open scoped BigOperators Classical + +variable {X C : Type*} [Fintype X] [Fintype C] + +/-- A finite union estimate retaining the feasible unit summands exactly. +The application proves the cover from the original root and tree penalties. -/ +theorem mass_le_cover (w : X → ℝ) (feasible far : X → Prop) (near : C → X → Prop) + (hw : ∀ x,0 ≤ w x) (hunit : ∀ x,feasible x → w x=1) + (hcover : ∀ x,0 < w x → ¬feasible x → far x ∨ ∃ c,near c x) : + (∑ x,w x) ≤ (∑ x,if feasible x then (1:ℝ) else 0)+ + (∑ x,if far x then w x else 0)+∑ c,∑ x,if near c x then w x else 0 := by + rw [Finset.sum_comm] + rw [← Finset.sum_add_distrib,← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro x _ + have hn : 0 ≤ ∑ c,if near c x then w x else 0 := by + apply Finset.sum_nonneg + intro c _ + split_ifs <;> first | exact hw x | exact le_rfl + have hf : 0 ≤ if far x then w x else 0 := by + split_ifs <;> first | exact hw x | exact le_rfl + by_cases hx : feasible x + · simp only [hx,ite_true] + calc + w x = 1 := hunit x hx + _ ≤ 1+(if far x then w x else 0)+(∑ c,if near c x then w x else 0) := by linarith + · simp only [hx,ite_false,zero_add] + by_cases hp : 0 < w x + · rcases hcover x hp hx with hf'|⟨c,hc⟩ + · rw [ite_eq_left hf'] + linarith + · have hs := Finset.single_le_sum + (f := fun c => if near c x then w x else 0) + (fun c _ => by split_ifs <;> first | exact hw x | exact le_rfl) + (Finset.mem_univ c) + simp only [hc,ite_true] at hs + linarith + · have hz : w x=0 := le_antisymm (le_of_not_gt hp) (hw x) + simp only [hz,ite_self,Finset.sum_const_zero,zero_add,le_refl] + +/-- The manuscript's final conversion from a small fraction of the +normalizer to a relative error against the exact table count. -/ +theorem relative_count_bound (Z M epsilon : ℝ) (hZ : 0 ≤ Z) + (he : 0 < epsilon) (he1 : epsilon < 1) (hZM : Z ≤ M) + (hbad : M ≤ Z+(epsilon/64)*M) : + Z ≤ M ∧ M ≤ (1+epsilon/32)*Z := by + refine ⟨hZM,?_⟩ + have hM : 0 ≤ M := hZ.trans hZM + have hscaled : (1-epsilon/64)*M ≤ Z := by linarith + have hfactor : 0 ≤ 1+epsilon/32 := by positivity + have hh := mul_le_mul_of_nonneg_left hscaled hfactor + have hcoef : 1 ≤ (1+epsilon/32)*(1-epsilon/64) := by + nlinarith [mul_nonneg he.le (sub_nonneg.mpr he1.le)] + have hmono := mul_le_mul_of_nonneg_right hcoef hM + nlinarith + +end ContingencyTables.TerminalMassCover + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TraceBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TraceBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..de219bfadd4f6232680df00fd8a0b966f9fbd877 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TraceBounds.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ComplementChain + +namespace OAI + +/-! +# Trace mixing for the actual omission-lift Metropolis chain + +The finite-chain constructor receives the proved positive completion. +Its state weights equal the original valid-degree weights, and the +transversal trace has the original normalized factorial-lift law. +The trace Poincaré bound uses the proved manuscript-coordinate variance +bound, followed by the existing harmonic-extension and spectral arguments. +-/ + +namespace ContingencyTables.TraceBounds + +open scoped BigOperators Classical +open CommonBasesFPRAS BinaryContraction DegreeCompletion ObservableVariance ObservableBounds ComplementChain RecursiveSignedTransport + +variable {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + +lemma completed_trace_pi (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) (hf : DegreePositive f gs.length) + (S : PlainIndex gs) : + (metropolisTrace gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf)).π S = f S.val.val / slotTotal gs f ∅ := by + rw [metropolisTrace_pi, slotTotal_completeDegree gs f gs.length ∅ (by simp)] + simp only [completeDegree, S.property.ncard hgs hcover, ite_true] + +/-- Exact inverse-gap bound 2p²Cp from the actual two-lift variance theorem. -/ +theorem omission_trace_poincare (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) + (hf : DegreePositive f gs.length) (hg : DegreePositive g gs.length) + (hsigf : OmissionProperty f gs.length) (hsigg : AdditionProperty g gs.length) + (q : ℝ) (hq : 0 ≤ q) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) + (h : PlainIndex gs → ℝ) : + let T := metropolisTrace gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf) + T.variance h ≤ (2*(gs.length:ℝ)^2*((gs.length:ℝ)*(1+8*(gs.length:ℝ)*q^2)))*T.energy h := by + let F := completeDegree f gs.length + have hF := completeDegree_positive f gs.length hf + let := plainIndex_nonempty gs hgs hcover + let C := metropolisChain gs hgs hne hcover w F hw hF + let Q := metropolisKilled gs hgs hne hcover w F hw hF + let H := C.harmonicExtension (plainPredicate gs) Q h + let J := extendChainFun gs H + have hJ (S : ChainIndex gs) : J S.val = H S := extendChainFun_apply gs H S + have hh (S : PlainIndex gs) : J S.val.val = h S := by + rw [hJ] + exact C.harmonicExtension_inside (plainPredicate gs) Q h S + have hvar := metropolisTrace_variance gs hgs hne hcover w F hw hF J + have hefun : (fun S : PlainIndex gs => J S.val.val) = h := funext hh + rw [hefun, slotVariance_completeDegree gs f J gs.length ∅ (by simp), + slotTotal_completeDegree gs f gs.length ∅ (by simp)] at hvar + have hv := omission_twoLift_transversal_variance gs f g J w q hq hf hg hsigf hsigg + hgs hcover hw hgood hagree hcompare + have hz : 0 < slotTotal gs f ∅ := slotTotal_degree_positive gs f gs.length hf ∅ (by simp) hgs + have henergy : restrictedEnergy (chainEdges gs) (chainConductance gs w f) J ∅ ∅ = + (2*(gs.length:ℝ)^2*slotTotal gs f ∅)*(metropolisTrace gs hgs hne hcover w F hw hF).energy h := by + have hc := metropolisChain_energy gs hgs hne hcover w F J hw hF + have hfJn : (fun S : ChainIndex gs => J S.val) = H := funext hJ + rw [hfJn] at hc + change C.energy (C.harmonicExtension (plainPredicate gs) Q h) = _ at hc + rw [C.traceChain_energy (plainPredicate gs) Q (by intro _ _; rfl)] at hc + change C.insideMass (plainPredicate gs)*(metropolisTrace gs hgs hne hcover w F hw hF).energy h = _ at hc + rw [metropolis_insideMass gs hgs hne hcover w F hw hF] at hc + unfold chainDirichlet at hc + rw [restrictedEnergy_completeDegree gs f J w hgs hcover ∅ ∅, + slotTotal_completeDegree gs f gs.length ∅ (by simp)] at hc + have hΛ := chainTotal_pos gs hgs hcover w F hF hw + have hn : (0:ℝ) < gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + field_simp [ne_of_gt hn] at hc + nlinarith + rw [henergy] at hv + dsimp only + rw [hvar] + apply (div_le_iff₀ hz).mpr + nlinarith + +lemma trace_constant_le_observable (p q : ℝ) (hp : 1 ≤ p) (hq : 1 ≤ q) : + 2*p^2*(p*(1+8*p*q^2)) ≤ observableConstant p q := by + have hp0 : 0 ≤ p := by linarith + have hq0 : 0 ≤ q := by linarith + have hcoef : 2*p^2 ≤ 90*p^4 := by + have hp2 : 1 ≤ p^2 := by nlinarith + have hp4 : p^2 ≤ p^4 := by nlinarith [sq_nonneg (p^2-1)] + nlinarith + have hc : 0 ≤ p*(1+8*p*q^2) := by positivity + have ht : 0 ≤ 10*p^4*(2*(8+32*p*q^3)) := by positivity + calc + _ ≤ 90*p^4*(p*(1+8*p*q^2)) := mul_le_mul_of_nonneg_right hcoef hc + _ ≤ observableConstant p q := by unfold observableConstant; nlinarith + +/-- Pointwise relative mixing of the actual transversal trace with Kobs. +The lower bound m applies to the original normalized lift masses. -/ +theorem omission_trace_relative_mixing (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f g : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) + (hf : DegreePositive f gs.length) (hg : DegreePositive g gs.length) + (hsigf : OmissionProperty f gs.length) (hsigg : AdditionProperty g gs.length) + (q : ℝ) (hq : 1 ≤ q) + (hgood : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → slotTotal gs f ∅/(4*slotDefect gs f ∅ p r) ≤ w p r) + (hagree : ∀ S, PlainState gs S → f S = g S) + (hcompare : ∀ S, ChainState gs S → f S ≤ q*g S) + (m : ℝ) (hm : 0 < m) (hmin : ∀ S : PlainIndex gs, m ≤ f S.val.val/slotTotal gs f ∅) + (s : ℕ) (x y : PlainIndex gs) : + let T := metropolisTrace gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf) + |(T.kernel.power s).P x y/(f y.val.val/slotTotal gs f ∅)-1| ≤ + Real.exp (-(s:ℝ)/observableConstant gs.length q)/m := by + let T := metropolisTrace gs hgs hne hcover w (completeDegree f gs.length) hw + (completeDegree_positive f gs.length hf) + have hp : (1:ℝ) ≤ gs.length := by exact_mod_cast List.length_pos_iff.mpr hne + have hK : 1 ≤ observableConstant gs.length q := by + have hpow : (1:ℝ) ≤ (gs.length:ℝ)^5 := one_le_pow₀ hp + have hlow := observableConstant_lower gs.length q hp hq + nlinarith + have hπ : ∀ S, m ≤ T.π S := by + intro S + rw [completed_trace_pi gs hgs hne hcover w f hw hf S] + exact hmin S + have hP : ∀ h, T.variance h ≤ observableConstant gs.length q*T.energy h := by + intro h + exact (omission_trace_poincare gs hgs hne hcover w f g hw hf hg hsigf hsigg q + (by linarith) hgood hagree hcompare h).trans + (mul_le_mul_of_nonneg_right (trace_constant_le_observable gs.length q hp hq) (T.energy_nonneg h)) + have ht := T.kernel_point_mixing (observableConstant gs.length q) m hK hm hπ hP s x y + rwa [completed_trace_pi gs hgs hne hcover w f hw hf y] at ht + +/-- A U-warm trace start costs at most 5p²U original-chain steps per +return, with the exact original normalized transversal law. -/ +theorem omission_trace_returnCost (gs : List (Γ × Γ)) (hgs : SlotsFresh gs ∅) (hne : gs ≠ []) + (hcover : pairSupport gs = Set.univ) (w : (Γ × Γ) → (Γ × Γ) → ℝ) + (f : Set Γ → ℝ) (hw : ∀ p r, 0 < w p r) (hf : DegreePositive f gs.length) + (hupper : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs f ∅/slotDefect gs f ∅ p r) + (U : ℝ) (hU : 0 ≤ U) (ν : PlainIndex gs → ℝ) + (hwarm : ∀ S, ν S ≤ U*(f S.val.val/slotTotal gs f ∅)) : + let F := completeDegree f gs.length + let hF := completeDegree_positive f gs.length hf + let C := metropolisChain gs hgs hne hcover w F hw hF + let Q := metropolisKilled gs hgs hne hcover w F hw hF + (∑ S, ν S*C.returnCost (plainPredicate gs) Q S) ≤ 5*(gs.length:ℝ)^2*U := by + let F := completeDegree f gs.length + have hF := completeDegree_positive f gs.length hf + let C := metropolisChain gs hgs hne hcover w F hw hF + let Q := metropolisKilled gs hgs hne hcover w F hw hF + let := plainIndex_nonempty gs hgs hcover + have hwarm' : ∀ S, ν S ≤ U*(metropolisTrace gs hgs hne hcover w F hw hF).π S := by + intro S + rw [completed_trace_pi gs hgs hne hcover w f hw hf S] + exact hwarm S + have hr := C.warm_returnCost (plainPredicate gs) Q (by intro _ _; rfl) ν U hwarm' + have hu : ∀ p ∈ gs, ∀ r ∈ gs, p ≠ r → w p r ≤ 4*slotTotal gs F ∅/slotDefect gs F ∅ p r := by + intro p hp r hr hpr + dsimp only [F] + rw [slotTotal_completeDegree gs f gs.length ∅ (by simp), + slotDefect_completeDegree gs f gs.length ∅ (by simp) hgs p r hp hr hpr] + exact hupper p hp r hr hpr + have htotal := chainTotal_le gs hgs hne hcover w F hF hu + have hz := slotTotal_pos gs F hF ∅ hgs + have hΛ := chainTotal_pos gs hgs hcover w F hF hw + rw [metropolis_insideMass gs hgs hne hcover w F hw hF] at hr + have heq : U/(slotTotal gs F ∅/chainTotal gs w F) = U*chainTotal gs w F/slotTotal gs F ∅ := by + field_simp + have hbound : U/(slotTotal gs F ∅/chainTotal gs w F) ≤ 5*(gs.length:ℝ)^2*U := by + rw [heq] + apply (div_le_iff₀ hz).mpr + nlinarith [mul_le_mul_of_nonneg_left htotal hU] + exact hr.trans hbound + +end ContingencyTables.TraceBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..7355457719b63051c36f42df3066d0aee5eadaa7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionAcceptance.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletions +import OAI.Combinatorics.ContingencyTables.Sampling.Padding + +namespace OAI + +/-! # Acceptance probability of the literal reference-row translation -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] + +def referencePosition : Option I ⊕ J → Option I × Option J := + Sum.elim (fun i => (i,none)) (fun j => (none,some j)) + +abbrev ReferenceGood (R : Option I → ℕ) (P : Option J → ℕ) (t : ℕ) := + {X : Table R P // ¬∃ k : Option I ⊕ J, + X.val (referencePosition k).1 (referencePosition k).2 < t} + +lemma reference_good_nonnegative + (R : Option I → ℕ) (P : Option J → ℕ) (D : Option I → Option J → ℤ) + (hzero : ∀ i j,D (some i) (some j)=0) (t : ℕ) + (hbound : ∀ i j,|D i j| ≤ (t:ℤ)) (X : ReferenceGood R P t) : + ∀ i j,0 ≤ (X.val.val i j:ℤ)+D i j := by + have hcell (k : Option I ⊕ J) : + 0 ≤ (X.val.val (referencePosition k).1 (referencePosition k).2:ℤ)+ + D (referencePosition k).1 (referencePosition k).2 := by + have hn : t ≤ X.val.val (referencePosition k).1 (referencePosition k).2 := + Nat.le_of_not_gt (fun h => X.property ⟨k,h⟩) + have hn' : (t:ℤ) ≤ X.val.val (referencePosition k).1 (referencePosition k).2 := by exact_mod_cast hn + have hl := (abs_le.mp (hbound (referencePosition k).1 (referencePosition k).2)).1 + omega + intro i j + cases j with + | none => exact hcell (.inl i) + | some j => + cases i with + | none => exact hcell (.inr j) + | some i => rw [hzero i j,add_zero]; positivity + +lemma reference_good_card_le + (R : Option I → ℕ) (P : Option J → ℕ) (D : Option I → Option J → ℤ) + (hzero : ∀ i j,D (some i) (some j)=0) (t : ℕ) + (hbound : ∀ i j,|D i j| ≤ (t:ℤ)) : + Fintype.card (ReferenceGood R P t) ≤ Fintype.card (Accepted R P D) := by + let embed : ReferenceGood R P t → Accepted R P D := + fun X => ⟨X.val,reference_good_nonnegative R P D hzero t hbound X⟩ + apply Fintype.card_le_of_injective embed + intro X Y h + apply Subtype.ext + exact congrArg (fun Z : Accepted R P D => Z.val) h + +lemma reference_cell_fraction + (R : Option I → ℕ) (P : Option J → ℕ) + (htotal : (∑ i,R i)=∑ j,P j) + (a₀ d t : ℕ) (hd : 0 < d) + (hrows : Fintype.card (Option I) ≤ d) (hcols : Fintype.card (Option J) ≤ d) + (hrow : ∀ i,a₀ ≤ R i) (hcol : ∀ j,a₀ ≤ P j) + (ha₀ : 4*d ≤ a₀) (ht : 2*t ≤ a₀) (k : Option I ⊕ J) : + (Fintype.card {X : Table R P // X.val (referencePosition k).1 (referencePosition k).2 < t}:ℝ)/ + Fintype.card (Table R P) ≤ 4*t*(d:ℝ)^3/a₀ := by + simpa only [Fintype.card_eq_nat_card] using + small_entry_probability htotal (referencePosition k).1 (referencePosition k).2 + a₀ d t hd hrows hcols (hrow _) (hcol _) ha₀ ht + +lemma reference_good_fraction + (R : Option I → ℕ) (P : Option J → ℕ) + (htotal : (∑ i,R i)=∑ j,P j) + (a₀ d t : ℕ) (hd : 0 < d) + (hrows : Fintype.card (Option I) ≤ d) (hcols : Fintype.card (Option J) ≤ d) + (hrow : ∀ i,a₀ ≤ R i) (hcol : ∀ j,a₀ ≤ P j) + (ha₀ : 4*d ≤ a₀) (ht : 2*t ≤ a₀) : + 1-(Fintype.card I+Fintype.card J+1:ℕ)*(4*t*(d:ℝ)^3/a₀) ≤ + (Fintype.card (ReferenceGood R P t):ℝ)/Fintype.card (Table R P) := by + have hcard : (0:ℝ) < Fintype.card (Table R P) := by + exact_mod_cast Fintype.card_pos_iff.mpr (table_nonempty R P htotal) + have hfrac := fraction_not_exists + (fun (k : Option I ⊕ J) (X : Table R P) => + X.val (referencePosition k).1 (referencePosition k).2 < t) + (4*t*(d:ℝ)^3/a₀) hcard (fun k => by + simpa only [Fintype.card_eq_nat_card] using reference_cell_fraction R P htotal a₀ d t hd hrows hcols hrow hcol ha₀ ht k) + have hcK : Fintype.card (Option I ⊕ J)=Fintype.card I+Fintype.card J+1 := by + rw [Fintype.card_sum,Fintype.card_option] + omega + rw [hcK] at hfrac + simpa only [Fintype.card_eq_nat_card] using hfrac + +/-- The reference row and reference column contain only |I|+|J|+1 +possibly changed entries. No completion outside those entries can reject. -/ +theorem reference_acceptance + (R : Option I → ℕ) (P : Option J → ℕ) (D : Option I → Option J → ℤ) + (htotal : (∑ i,R i)=∑ j,P j) + (hzero : ∀ i j,D (some i) (some j)=0) + (a₀ d t : ℕ) (hd : 0 < d) + (hrows : Fintype.card (Option I) ≤ d) (hcols : Fintype.card (Option J) ≤ d) + (hrow : ∀ i,a₀ ≤ R i) (hcol : ∀ j,a₀ ≤ P j) + (ha₀ : 4*d ≤ a₀) (ht : 2*t ≤ a₀) + (hbound : ∀ i j,|D i j| ≤ (t:ℤ)) : + 1-(Fintype.card I+Fintype.card J+1:ℕ)*(4*t*(d:ℝ)^3/a₀) ≤ + (Fintype.card (Accepted R P D):ℝ)/Fintype.card (Table R P) := by + have hcount : (Fintype.card (ReferenceGood R P t):ℝ) ≤ Fintype.card (Accepted R P D) := by + exact_mod_cast reference_good_card_le R P D hzero t hbound + exact (reference_good_fraction R P htotal a₀ d t hd hrows hcols hrow hcol ha₀ ht).trans + (div_le_div_of_nonneg_right hcount (Nat.cast_nonneg _)) + +/-- Applying the previous estimate to the actual signed star only needs +bounds on the changes to its row and column margins. -/ +theorem star_acceptance + (R : Option I → ℕ) (P : Option J → ℕ) + (δR : Option I → ℤ) (δP : Option J → ℤ) + (htotal : (∑ i,R i)=∑ j,P j) + (a₀ d M t : ℕ) (hd : 0 < d) + (hrows : Fintype.card (Option I) ≤ d) (hcols : Fintype.card (Option J) ≤ d) + (hrow : ∀ i,a₀ ≤ R i) (hcol : ∀ j,a₀ ≤ P j) + (ha₀ : 4*d ≤ a₀) (ht : 2*t ≤ a₀) + (hR : ∀ i,|δR i| ≤ (M:ℤ)) (hP : ∀ j,|δP j| ≤ (M:ℤ)) + (hscale : M*(Fintype.card J+1) ≤ t) : + 1-(Fintype.card I+Fintype.card J+1:ℕ)*(4*t*(d:ℝ)^3/a₀) ≤ + (Fintype.card (Accepted R P (star δR δP)):ℝ)/Fintype.card (Table R P) := by + apply reference_acceptance R P (star δR δP) htotal (fun _ _ => rfl) + a₀ d t hd hrows hcols hrow hcol ha₀ ht + intro i j + exact (star_abs_le δR δP M (by positivity) hR hP i j).trans (by exact_mod_cast hscale) + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4c3f28f7d7b46a9ebc9e2e10f58cecb48e3d04c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionChain.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionCounts +import OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain + +namespace OAI + +/-! # The ideal chain draws an actual uniform completion then translates it -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical +open CommonBasesFPRAS + +variable {X I J : Type*} [Fintype X] [Nonempty X] [Fintype I] [Fintype J] + +noncomputable def completionMove (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (Adj : X → X → Prop) (β : ℝ) (x y : X) : ℝ := + if Adj x y then β*(acceptedCount R P x y:ℝ)/(blockCount R P x:ℝ) else 0 + +omit [Fintype X] [Nonempty X] in +lemma completionMove_nonnegative (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) (x y : X) : + 0 ≤ completionMove R P Adj β x y := by + unfold completionMove + split_ifs + · exact div_nonneg (mul_nonneg hβ (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + · exact le_rfl + +omit [Fintype X] [Nonempty X] in +lemma completionMove_le_proposal (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) (x y : X) : + completionMove R P Adj β x y ≤ if Adj x y then β else 0 := by + unfold completionMove + split_ifs + · have hf : (0:ℝ) < blockCount R P x := by exact_mod_cast blockCount_pos R P htotal x + have hc : (acceptedCount R P x y:ℝ) ≤ blockCount R P x := by exact_mod_cast acceptedCount_le R P x y + apply (div_le_iff₀ hf).mpr + exact mul_le_mul_of_nonneg_left hc hβ + · exact le_rfl + +omit [Nonempty X] in +lemma completionMove_row (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x,(Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D:ℝ)*β ≤ 1/2) (x : X) : ∑ y,completionMove R P Adj β x y ≤ 1/2 := by + calc + _ ≤ ∑ y,if Adj x y then β else 0 := + Finset.sum_le_sum (fun y _ => completionMove_le_proposal R P htotal Adj β hβ x y) + _ = ((Finset.univ.filter (Adj x)).card:ℝ)*β := by rw [← Finset.sum_filter]; simp + _ ≤ (D:ℝ)*β := mul_le_mul_of_nonneg_right (by exact_mod_cast hdegree x) hβ + _ ≤ _ := hproposal + +omit [Nonempty X] in +lemma completionMove_reversible (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (hsym : ∀ x y,Adj x y ↔ Adj y x) (β : ℝ) (x y : X) : + ((blockCount R P x:ℝ)/MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)))* + completionMove R P Adj β x y= + ((blockCount R P y:ℝ)/MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ)))* + completionMove R P Adj β y x := by + have hx : (blockCount R P x:ℝ)≠0 := ne_of_gt (by exact_mod_cast blockCount_pos R P htotal x) + have hy : (blockCount R P y:ℝ)≠0 := ne_of_gt (by exact_mod_cast blockCount_pos R P htotal y) + unfold completionMove + by_cases ha : Adj x y + · rw [ite_eq_left ha,ite_eq_left ((hsym x y).mp ha),acceptedCount_symmetric R P htotal x y] + exact (div_mul_div_cancel₀' hx _ _).trans (div_mul_div_cancel₀' hy _ _).symm + · rw [ite_eq_right ha,ite_eq_right ((hsym x y).not.mp ha)] + simp only [mul_zero] + +noncomputable def completionChain (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) + (Adj : X → X → Prop) (hsym : ∀ x y,Adj x y ↔ Adj y x) + (β : ℝ) (hβ : 0 ≤ β) (D : ℕ) + (hdegree : ∀ x,(Finset.univ.filter (Adj x)).card ≤ D) + (hproposal : (D:ℝ)*β ≤ 1/2) : FiniteChain X := + FiniteChain.ofMoves + (fun x => (blockCount R P x:ℝ)/MetropolisChain.normalizer (fun z => (blockCount R P z:ℝ))) + (completionMove R P Adj β) + (fun x => div_pos (by exact_mod_cast blockCount_pos R P htotal x) + (MetropolisChain.normalizer_pos _ (fun z => by exact_mod_cast blockCount_pos R P htotal z))) + (by rw [← Finset.sum_div]; exact div_self (ne_of_gt + (MetropolisChain.normalizer_pos _ (fun z => by exact_mod_cast blockCount_pos R P htotal z)))) + (completionMove_nonnegative R P Adj β hβ) + (completionMove_row R P htotal Adj β hβ D hdegree hproposal) + (completionMove_reversible R P htotal Adj hsym β) + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dce227d0959ae2343dcf9f146269338c7ba7c40 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletionCounts.lean @@ -0,0 +1,42 @@ +import OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletions + +namespace OAI + +/-! # Symmetric accepted counts for the literal completion adjustment -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators Classical + +variable {X I J : Type*} [Fintype I] [Fintype J] + +noncomputable def blockCount (R : X → Option I → ℕ) (P : X → Option J → ℕ) (x : X) : ℕ := + Fintype.card (Table (R x) (P x)) + +noncomputable def acceptedCount (R : X → Option I → ℕ) (P : X → Option J → ℕ) (x y : X) : ℕ := + Fintype.card (Accepted (R x) (P x) (between (R x) (R y) (P x) (P y))) + +lemma blockCount_pos (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) (x : X) : 0 < blockCount R P x := + Fintype.card_pos_iff.mpr (table_nonempty (R x) (P x) (htotal x)) + +lemma acceptedCount_le (R : X → Option I → ℕ) (P : X → Option J → ℕ) (x y : X) : + acceptedCount R P x y ≤ blockCount R P x := + Fintype.card_subtype_le _ + +/-- Reversibility uses the cardinality of actual accepted translations, +not a Metropolis weight-ratio oracle. -/ +theorem acceptedCount_symmetric (R : X → Option I → ℕ) (P : X → Option J → ℕ) + (htotal : ∀ x,(∑ i,R x i)=∑ j,P x j) (x y : X) : + acceptedCount R P x y=acceptedCount R P y x := by + have he := accepted_card_symmetric (R x) (R y) (P x) (P y) + (between (R x) (R y) (P x) (P y)) + (between_rows (R x) (R y) (P x) (P y)) + (between_columns (R x) (R y) (P x) (P y) (htotal x) (htotal y)) + unfold acceptedCount + rw [between_reverse (R x) (R y) (P x) (P y)] + exact he + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletions.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletions.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e9085197eb4c5ecc8632c1cf650400f3525dceb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslatedCompletions.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Transport.SignedMarginTranslation + +namespace OAI + +/-! # Accepted completion translations are exact finite bijections -/ + +namespace ContingencyTables.CompletionTranslation + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +def Accepted (R : I → ℕ) (P : J → ℕ) (D : I → J → ℤ) := + {X : Table R P // ∀ i j,0 ≤ (X.val i j:ℤ)+D i j} + +noncomputable instance acceptedFintype (R : I → ℕ) (P : J → ℕ) (D : I → J → ℤ) : + Fintype (Accepted R P D) := by + unfold Accepted + classical + infer_instance + +def translate (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₀ P₀ D) : Table R₁ P₁ := by + refine ⟨fun i j => ((X.val.val i j:ℤ)+D i j).toNat,?_,?_⟩ + · intro i + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [Int.toNat_of_nonneg (X.property _ _)] + rw [Finset.sum_add_distrib,← Nat.cast_sum,X.val.property.1,hR] + ring + · intro j + apply Int.natCast_inj.mp + rw [Nat.cast_sum] + simp_rw [Int.toNat_of_nonneg (X.property _ _)] + rw [Finset.sum_add_distrib,← Nat.cast_sum,X.val.property.2,hP] + ring + +lemma translate_cast (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₀ P₀ D) (i : I) (j : J) : + ((translate R₀ R₁ P₀ P₁ D hR hP X).val i j:ℤ)=(X.val.val i j:ℤ)+D i j := + Int.toNat_of_nonneg (X.property i j) + +omit [Fintype I] in +lemma reverse_rows (R₀ R₁ : I → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) (i : I) : + (∑ j,-D i j)=(R₀ i:ℤ)-R₁ i := by + rw [Finset.sum_neg_distrib,hR] + ring + +omit [Fintype J] in +lemma reverse_columns (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (j : J) : + (∑ i,-D i j)=(P₀ j:ℤ)-P₁ j := by + rw [Finset.sum_neg_distrib,hP] + ring + +def forward (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₀ P₀ D) : + Accepted R₁ P₁ (fun i j => -D i j) := by + refine ⟨translate R₀ R₁ P₀ P₁ D hR hP X,?_⟩ + intro i j + rw [translate_cast] + dsimp only + omega + +lemma forward_cast (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₀ P₀ D) (i : I) (j : J) : + ((forward R₀ R₁ P₀ P₁ D hR hP X).val.val i j:ℤ)=(X.val.val i j:ℤ)+D i j := + translate_cast R₀ R₁ P₀ P₁ D hR hP X i j + +def backward (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₁ P₁ (fun i j => -D i j)) : + Accepted R₀ P₀ D := by + refine ⟨translate R₁ R₀ P₁ P₀ (fun i j => -D i j) + (reverse_rows R₀ R₁ D hR) (reverse_columns P₀ P₁ D hP) X,?_⟩ + intro i j + rw [translate_cast] + omega + +lemma backward_cast (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) (X : Accepted R₁ P₁ (fun i j => -D i j)) + (i : I) (j : J) : + ((backward R₀ R₁ P₀ P₁ D hR hP X).val.val i j:ℤ)=(X.val.val i j:ℤ)-D i j := by + change ((translate R₁ R₀ P₁ P₀ (fun i j => -D i j) + (reverse_rows R₀ R₁ D hR) (reverse_columns P₀ P₁ D hP) X).val i j:ℤ)=_ + rw [translate_cast] + rfl + +def acceptedEquiv (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) : + Accepted R₀ P₀ D ≃ Accepted R₁ P₁ (fun i j => -D i j) where + toFun := forward R₀ R₁ P₀ P₁ D hR hP + invFun := backward R₀ R₁ P₀ P₁ D hR hP + left_inv X := by + apply Subtype.ext + apply Subtype.ext + funext i j + apply Int.natCast_inj.mp + change ((backward R₀ R₁ P₀ P₁ D hR hP (forward R₀ R₁ P₀ P₁ D hR hP X)).val.val i j:ℤ)=_ + rw [backward_cast,forward_cast] + ring + right_inv X := by + apply Subtype.ext + apply Subtype.ext + funext i j + apply Int.natCast_inj.mp + change ((forward R₀ R₁ P₀ P₁ D hR hP (backward R₀ R₁ P₀ P₁ D hR hP X)).val.val i j:ℤ)=_ + rw [forward_cast,backward_cast] + ring + +theorem accepted_card_symmetric (R₀ R₁ : I → ℕ) (P₀ P₁ : J → ℕ) (D : I → J → ℤ) + (hR : ∀ i,(∑ j,D i j)=(R₁ i:ℤ)-R₀ i) + (hP : ∀ j,(∑ i,D i j)=(P₁ j:ℤ)-P₀ j) : + Fintype.card (Accepted R₀ P₀ D)=Fintype.card (Accepted R₁ P₁ (fun i j => -D i j)) := + Fintype.card_congr (acceptedEquiv R₀ R₁ P₀ P₁ D hR hP) + +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslationDecisionSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslationDecisionSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..3453478fc35f2d8f33324620b9bace7143787e74 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TranslationDecisionSemantics.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.ContingencyTables.Machines.TranslationDecisionProgram + +namespace OAI + +/-! # Exact semantics of the full translated-nonnegativity test -/ + +namespace ContingencyTables.DensePrograms +open ProfilePrograms CompletionTranslation +open scoped BigOperators + +theorem translationValid_code {m n : ℕ} + (R₀ R₁ : Option (Fin m) → ℕ) (P₀ P₁ : Option (Fin n) → ℕ) + (X : Table R₀ P₀) : + translationValid (((marginCode R₀,marginCode P₀),(marginCode R₁,marginCode P₁)), + tableOutput X)=true ↔ + ∀ i j,0 ≤ (X.val i j:ℤ)+between R₀ R₁ P₀ P₁ i j := by + rw [translationValid,List.all_eq_true] + constructor + · intro h i j + apply (translatedCell_code R₀ R₁ P₀ P₁ X i j).mp + apply h (optionIndex i,optionIndex j) + apply (mem_cellPairs _ _ _ _).mpr + simpa only [marginCode,List.length_cons,List.length_ofFn] using + And.intro (optionIndex_lt i) (optionIndex_lt j) + · intro h a ha + have hab := (mem_cellPairs _ _ _ _).mp ha + have hi : a.1 < m+1 := by + simpa only [marginCode,List.length_cons,List.length_ofFn] using hab.1 + have hj : a.2 < n+1 := by + simpa only [marginCode,List.length_cons,List.length_ofFn] using hab.2 + have he := (translatedCell_code R₀ R₁ P₀ P₁ X + (finSuccEquiv m ⟨a.1,hi⟩) (finSuccEquiv n ⟨a.2,hj⟩)).mpr (h _ _) + simpa only [optionIndex_finSucc] using he + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TransversalCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TransversalCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4facae8a757b1dc2c636d5654ea947915d8f893 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TransversalCount.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Transport.InitialTransversals +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialization + +namespace OAI + +/-! +# Exact binomial/factorial cancellation in a transversal normalizer + +Every small integer profile has a product of binomial numbers of label +preimages. Its factorial lift contributes the inverse product, so the +actual transversal normalizer is exactly the raw integer-profile sum. +-/ + +namespace ContingencyTables.TransversalCount + +open scoped BigOperators Classical +open CommonBasesFPRAS TwoLiftStates LabelledFactorial InitialTransversals InitialLocalChoices + +variable {C : Type*} [Fintype C] (b : C → ℕ) + +@[reducible] def Profile := (c : C) → Fin (b c+1) + +noncomputable def cardAt (c : C) (S : Finset (Fin (b c))) : Fin (b c+1) := + ⟨S.card,by have h := Finset.card_le_univ S; simpa using Nat.lt_succ_of_le h⟩ + +noncomputable def cardProfile (S : (c : C) → Finset (Fin (b c))) : Profile b := + fun c => cardAt b c (S c) + +noncomputable def display (x : Profile b) : C×Bool → ℕ := + fun u => if u.2 then b u.1-(x u.1).val else (x u.1).val + +omit [Fintype C] in +lemma local_fiber (c : C) (x : Fin (b c+1)) : + (∑ S : Finset (Fin (b c)), if cardAt b c S=x then InitialLocalChoices.localWeight (b c) 0 0 S else 0)=1 := by + have hx : x.val≤b c := by have := x.isLt; omega + have h := Finset.sum_powerset_apply_card + (fun k => if k=x.val then ((k.factorial:ℝ)*((b c-k).factorial:ℝ))/(b c).factorial else 0) + (x := (Finset.univ : Finset (Fin (b c)))) + have he : (∑ S : Finset (Fin (b c)), if S.card=x.val then + ((S.card.factorial:ℝ)*((b c-S.card).factorial:ℝ))/(b c).factorial else 0)= + ((b c).choose x.val:ℝ)*((x.val.factorial:ℝ)*((b c-x.val).factorial:ℝ))/(b c).factorial := by + simpa [nsmul_eq_mul,mul_ite,mul_div_assoc,Finset.mem_range,show x.val h (display b (cardProfile b S))) + (InitialTransversals.denominator b) (InitialTransversals.encode b S) := by + unfold firstLift + rw [count_encode] + _ = _ := InitialTransversals.firstLift_encode b _ S + +/-- The literal factorial lift's transversal normalizer is the original +integer-profile count, for arbitrary raw h and arbitrary capacities. -/ +theorem slotTotal_eq_profiles (h : (C×Bool → ℕ) → ℝ) : + slotTotal pairs (firstLift (group (cell b)) h (InitialTransversals.denominator b)) ∅= + ∑ x : Profile b,h (display b x) := by + rw [slotTotal_eq_plain_sum pairs PairedLabels.fresh PairedLabels.cover] + rw [Finset.sum_subtype (p := PlainState (pairs : List ((Copy b×Bool)×(Copy b×Bool)))) _ + (by intro S; simp)] + calc + _ = ∑ S : ((c : C) → Finset (Fin (b c))),h (display b (cardProfile b S))* + ∏ c,InitialLocalChoices.localWeight (b c) 0 0 (S c) := by + apply Fintype.sum_equiv (plainEquivChoices b) + intro S + have ht := firstLift_encode b h ((plainEquivChoices b) S) + have he : InitialTransversals.encode b ((plainEquivChoices b) S)=S.val := + congrArg Subtype.val ((plainEquivChoices b).symm_apply_apply S) + rwa [he] at ht + _ = _ := choices_sum b (fun x => h (display b x)) + +end ContingencyTables.TransversalCount + +namespace ContingencyTables.CompanionTransversalCount + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionInitialization TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Exact binomial/factorial cancellation for the manuscript's literal +softened completion count, including the terminal annealing parameter. -/ +theorem total_eq_raw_profiles (A : Instance I J) (alpha : ℝ) : + slotTotal pairs (f A alpha) ∅= + ∑ x : TransversalCount.Profile (fun s : SmallCell A => A.b s.val.1 s.val.2), + h A alpha (TransversalCount.display (fun s : SmallCell A => A.b s.val.1 s.val.2) x) := by + unfold f + rw [denominator_eq] + convert TransversalCount.slotTotal_eq_profiles + (fun s : SmallCell A => A.b s.val.1 s.val.2) (h A alpha) using 1 + congr 1 + all_goals + congr 1 + ext + simp + +end ContingencyTables.CompanionTransversalCount + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/TwoLiftStates.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/TwoLiftStates.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f0949cc7aa3d330c55dc8953760b5f2cf29e8a1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/TwoLiftStates.lean @@ -0,0 +1,276 @@ +import OAI.Combinatorics.ContingencyTables.Transport.LabelledFactorial + +namespace OAI + +/-! +# Actual paired states and the two factorial weights + +Every physical cell contains an arbitrary finite bundle of paired labels. +The plain and one-hole/one-full predicates imply the exact cell count +identities. Thus the literal subset lifts agree on plain states and obey +the manuscript's W² comparison on every actual chain state. +-/ + +namespace ContingencyTables.TwoLiftStates + +open scoped BigOperators Classical Matrix +open CommonBasesFPRAS FactorialSignatures LabelledFactorial + +variable {P C : Type*} [Fintype P] [Fintype C] + +def group (cell : P → C) (i : P × Bool) : C × Bool := (cell i.1,i.2) + +def pair (p : P) : (P × Bool) × (P × Bool) := ((p,false),(p,true)) + +noncomputable def pairs : List ((P × Bool) × (P × Bool)) := + Finset.univ.toList.map pair + +noncomputable def width (cell : P → C) (c : C) : ℕ := + (Finset.univ.filter (fun p => cell p=c)).card + +noncomputable def viewCount (cell : P → C) (S : Set (P × Bool)) (c : C) (t : Bool) : ℕ := + ∑ p, if cell p=c ∧ (p,t) ∈ S then 1 else 0 + +noncomputable def occupancy (S : Set (P × Bool)) (p : P) : ℕ := + (if (p,false) ∈ S then 1 else 0) + (if (p,true) ∈ S then 1 else 0) + +lemma pair_mem (p : P) : pair p ∈ (pairs : List ((P × Bool) × (P × Bool))) := by + simp [pairs] + +omit [Fintype P] in +lemma pair_injective : Function.Injective (pair : P → (P × Bool) × (P × Bool)) := by + intro p q h + exact congrArg (fun x => x.1.1) h + +omit [Fintype C] in +lemma groupCount_eq_viewCount (cell : P → C) (S : Set (P × Bool)) (c : C) (t : Bool) : + groupCount (group cell) S (c,t) = viewCount cell S c t := by + unfold groupCount viewCount + rw [Finset.card_filter] + simp only [Fintype.sum_prod_type,group,Prod.mk.injEq,Fintype.sum_bool] + apply Finset.sum_congr rfl + intro p _ + cases t <;> simp [and_comm] + +omit [Fintype C] in +lemma width_eq_sum (cell : P → C) (c : C) : + width cell c = ∑ p, if cell p=c then 1 else 0 := Finset.card_filter _ _ + +omit [Fintype C] in +lemma viewCount_compl (cell : P → C) (S : Set (P × Bool)) (c : C) (t : Bool) : + viewCount cell S c t + viewCount cell Sᶜ c t = width cell c := by + rw [width_eq_sum] + unfold viewCount + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro p _ + by_cases hc : cell p=c <;> by_cases hs : (p,t) ∈ S <;> simp [hc,hs] + +omit [Fintype C] in +lemma viewCount_le_width (cell : P → C) (S : Set (P × Bool)) (c : C) (t : Bool) : + viewCount cell S c t ≤ width cell c := by + have := viewCount_compl cell S c t + omega + +omit [Fintype C] in +lemma viewCounts_eq_occupancy (cell : P → C) (S : Set (P × Bool)) (c : C) : + viewCount cell S c false + viewCount cell S c true = + ∑ p, if cell p=c then occupancy S p else 0 := by + unfold viewCount occupancy + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro p _ + by_cases hc : cell p=c <;> simp [hc] + +omit [Fintype P] in +lemma occupancy_single (S : Set (P × Bool)) (p : P) (h : PairSingle (pair p) S) : + occupancy S p = 1 := by + rcases h with ⟨ha,hb⟩ | ⟨ha,hb⟩ <;> simp [occupancy,pair] at ha hb ⊢ <;> simp [ha,hb] + +omit [Fintype P] in +lemma occupancy_empty (S : Set (P × Bool)) (p : P) (h : PairEmpty (pair p) S) : + occupancy S p = 0 := by + rcases h with ⟨ha,hb⟩ + simp [pair] at ha hb + simp [occupancy,ha,hb] + +omit [Fintype P] in +lemma occupancy_full (S : Set (P × Bool)) (p : P) (h : PairFull (pair p) S) : + occupancy S p = 2 := by + rcases h with ⟨ha,hb⟩ + simp [pair] at ha hb + simp [occupancy,ha,hb] + +omit [Fintype C] in +/-- Every actual plain state is balanced in every physical cell. -/ +theorem plain_counts (cell : P → C) (S : Set (P × Bool)) + (hS : PlainState pairs S) (c : C) : + viewCount cell S c false + viewCount cell S c true = width cell c := by + rw [viewCounts_eq_occupancy,width_eq_sum] + apply Finset.sum_congr rfl + intro p _ + rw [occupancy_single S p (hS _ (pair_mem p))] + +lemma defect_occupancy (S : Set (P × Bool)) (p q : P) + (hS : DefectState pairs (pair p) (pair q) S) (k : P) : + occupancy S k + (if k=p then 1 else 0) = 1 + (if k=q then 1 else 0) := by + have hpq : p ≠ q := fun h => hS.2.2.1 (congrArg pair h) + by_cases hkp : k=p + · subst k + rw [occupancy_empty S p hS.2.2.2.1] + simp [hpq] + · by_cases hkq : k=q + · subst k + rw [occupancy_full S q hS.2.2.2.2.1] + simp [hkp] + · rw [occupancy_single S k (hS.2.2.2.2.2 _ (pair_mem k) + (fun h => hkp (pair_injective h)) (fun h => hkq (pair_injective h)))] + simp [hkp,hkq] + +omit [Fintype C] in +/-- Cell occupancies of an actual defect have exactly one unit missing at +its hole and one unit extra at its full pair, including coinciding cells. -/ +theorem defect_counts (cell : P → C) (S : Set (P × Bool)) (p q : P) + (hS : DefectState pairs (pair p) (pair q) S) (c : C) : + viewCount cell S c false + viewCount cell S c true + (if cell p=c then 1 else 0) = + width cell c + (if cell q=c then 1 else 0) := by + have hs : (∑ k, if cell k=c then occupancy S k + (if k=p then 1 else 0) else 0) = + ∑ k, if cell k=c then 1 + (if k=q then 1 else 0) else 0 := by + apply Finset.sum_congr rfl + intro k _ + rw [defect_occupancy S p q hS k] + have hd (u v : P → ℕ) : (∑ k, if cell k=c then u k+v k else 0) = + (∑ k, if cell k=c then u k else 0)+(∑ k, if cell k=c then v k else 0) := by + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro k _ + split_ifs <;> rfl + rw [hd,hd] at hs + have he (a : P) : (∑ k, if cell k=c then (if k=a then (1:ℕ) else 0) else 0) = + if cell a=c then 1 else 0 := by + calc + _ = ∑ k, if k=a then (if cell k=c then 1 else 0) else 0 := by + apply Finset.sum_congr rfl; intro k _; split_ifs <;> rfl + _ = _ := by simp + rw [he p,he q,← width_eq_sum,← viewCounts_eq_occupancy] at hs + exact hs + +noncomputable def denominator (cell : P → C) : ℝ := ∏ c, ((width cell c).factorial : ℝ) + +lemma firstLift_eq_cells (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) (S : Set (P × Bool)) : + firstLift (group cell) h (denominator cell) S = + h (groupCount (group cell) S) * + ∏ c, cellFactor (width cell c) (viewCount cell S c false) (viewCount cell S c true) := by + unfold firstLift factorialProduct denominator cellFactor + simp only [Fintype.prod_prod_type,Fintype.prod_bool,groupCount_eq_viewCount] + simp only [Finset.prod_div_distrib,Finset.prod_mul_distrib] + ring + +lemma secondLift_eq_cells (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) (S : Set (P × Bool)) : + secondLift (group cell) h (denominator cell) S = + h (groupCount (group cell) S) * + ∏ c, complementCellFactor (width cell c) (viewCount cell S c false) (viewCount cell S c true) := by + have he (c : C) (t : Bool) : groupCount (group cell) Sᶜ (c,t) = + width cell c - viewCount cell S c t := by + rw [groupCount_eq_viewCount] + have := viewCount_compl cell S c t + omega + unfold secondLift factorialProduct denominator complementCellFactor + simp only [Fintype.prod_prod_type,Fintype.prod_bool,he] + simp only [Finset.prod_div_distrib,Finset.prod_mul_distrib] + ring + +/-- Exact agreement of the two literal subset lifts on every plain state. -/ +theorem plain_lifts_agree (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) + (S : Set (P × Bool)) (hS : PlainState pairs S) : + secondLift (group cell) h (denominator cell) S = firstLift (group cell) h (denominator cell) S := by + rw [firstLift_eq_cells,secondLift_eq_cells] + exact balanced_lift_agreement _ _ _ (plain_counts cell S hS) _ + +/-- The paper's exact W² comparison on every actual defect state. -/ +theorem defect_lifts_compare (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) + (S : Set (P × Bool)) (hS : ∃ p q, DefectState pairs (pair p) (pair q) S) + (W : ℕ) (hW : 0 < W) (hbW : ∀ c, width cell c < W) + (hh : 0 ≤ h (groupCount (group cell) S)) : + (1/(W:ℝ)^2) * firstLift (group cell) h (denominator cell) S ≤ + secondLift (group cell) h (denominator cell) S ∧ + secondLift (group cell) h (denominator cell) S ≤ + (W:ℝ)^2 * firstLift (group cell) h (denominator cell) S := by + obtain ⟨p,q,hS⟩ := hS + rw [firstLift_eq_cells,secondLift_eq_cells] + by_cases hpq : cell p=cell q + · have hbal (c : C) : viewCount cell S c false + viewCount cell S c true = width cell c := by + have ht := defect_counts cell S p q hS c + rw [hpq] at ht + omega + rw [balanced_lift_agreement _ _ _ hbal] + have hf : 0 ≤ h (groupCount (group cell) S) * + ∏ c, cellFactor (width cell c) (viewCount cell S c false) (viewCount cell S c true) := + mul_nonneg hh (Finset.prod_nonneg fun _ _ => (cellFactor_positive _ _ _).le) + have hWr : (1:ℝ) ≤ W := by exact_mod_cast hW + have hsq : (1:ℝ) ≤ (W:ℝ)^2 := by nlinarith + constructor + · exact mul_le_of_le_one_left hf ((div_le_one (by positivity)).mpr hsq) + · exact le_mul_of_one_le_left hf hsq + · apply defect_lift_comparison _ _ _ (cell p) (cell q) hpq W hW hbW + (fun c => viewCount_le_width cell S c false) (fun c => viewCount_le_width cell S c true) + · have ht := defect_counts cell S p q hS (cell p) + simpa [hpq,Ne.symm hpq] using ht + · have ht := defect_counts cell S p q hS (cell q) + simpa [hpq] using ht + · intro c hcp hcq + have ht := defect_counts cell S p q hS c + simpa [Ne.symm hcp,Ne.symm hcq] using ht + · exact hh + +lemma denominator_positive (cell : P → C) : 0 < denominator cell := by + apply Finset.prod_pos + intro c _ + exact_mod_cast Nat.factorial_pos (width cell c) + +lemma firstLift_nonnegative (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) + (S : Set (P × Bool)) (hh : 0 ≤ h (groupCount (group cell) S)) : + 0 ≤ firstLift (group cell) h (denominator cell) S := by + rw [firstLift_eq_cells] + exact mul_nonneg hh (Finset.prod_nonneg fun _ _ => (cellFactor_positive _ _ _).le) + +/-- Both inequalities hold on every actual chain state, with no extra +assumption about which cells contain the hole and full pair. -/ +theorem chain_lifts_compare (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) + (S : Set (P × Bool)) (hS : ChainState pairs S) + (W : ℕ) (hW : 0 < W) (hbW : ∀ c, width cell c < W) + (hh : 0 ≤ h (groupCount (group cell) S)) : + (1/(W:ℝ)^2) * firstLift (group cell) h (denominator cell) S ≤ + secondLift (group cell) h (denominator cell) S ∧ + secondLift (group cell) h (denominator cell) S ≤ + (W:ℝ)^2 * firstLift (group cell) h (denominator cell) S := by + rcases hS with hS | ⟨p,q,hS⟩ + · rw [plain_lifts_agree cell h S hS] + have hf := firstLift_nonnegative cell h S hh + have hWr : (1:ℝ) ≤ W := by exact_mod_cast hW + have hsq : (1:ℝ) ≤ (W:ℝ)^2 := by nlinarith + constructor + · exact mul_le_of_le_one_left hf ((div_le_one (by positivity)).mpr hsq) + · exact le_mul_of_one_le_left hf hsq + · obtain ⟨a,_,rfl⟩ := List.mem_map.mp (show p ∈ Finset.univ.toList.map pair from hS.1) + obtain ⟨b,_,rfl⟩ := List.mem_map.mp (show q ∈ Finset.univ.toList.map pair from hS.2.1) + exact defect_lifts_compare cell h S ⟨a,b,hS⟩ W hW hbW hh + +/-- The pointwise comparison used by the actual original-chain variance +argument is supplied by the factorial state counts. -/ +theorem firstLift_le_square_secondLift (cell : P → C) (h : ((C × Bool) → ℕ) → ℝ) + (S : Set (P × Bool)) (hS : ChainState pairs S) + (W : ℕ) (hW : 0 < W) (hbW : ∀ c, width cell c < W) + (hh : 0 ≤ h (groupCount (group cell) S)) : + firstLift (group cell) h (denominator cell) S ≤ + (W:ℝ)^2 * secondLift (group cell) h (denominator cell) S := by + have hl := (chain_lifts_compare cell h S hS W hW hbW hh).1 + have hp : (0:ℝ) < (W:ℝ)^2 := sq_pos_of_pos (by exact_mod_cast hW) + have hdiv : firstLift (group cell) h (denominator cell) S/(W:ℝ)^2 ≤ + secondLift (group cell) h (denominator cell) S := by + simpa only [one_div,div_eq_mul_inv,mul_comm,mul_one,one_mul] using hl + simpa only [mul_comm] using (div_le_iff₀ hp).mp hdiv + +end ContingencyTables.TwoLiftStates + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/UnaryMarkers.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/UnaryMarkers.lean new file mode 100644 index 0000000000000000000000000000000000000000..64d802893eb6c96dd233c0186d4862a5c76039d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/UnaryMarkers.lean @@ -0,0 +1,24 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram + +namespace OAI + +/-! # Constructing the bounded unary loop markers used in tabulation -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def unaryMarkers (n : ℕ) : List Bool := (List.range n).map (fun _ => false) + +def unaryMarkersRealizer : Realizer unaryMarkers := + composition range (map (constant false)) + +lemma unaryMarkers_length (n : ℕ) : (unaryMarkers n).length=n := by + simp only [unaryMarkers,List.length_map,List.length_range] + +/-- Unary markers are charged by the actual requested loop length. -/ +lemma work_unaryMarkers : WorkBound unaryMarkersRealizer id := + work_then_polynomial range_numeric_work (polynomial_map (polynomial_constant false)) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/UniformPartialRejection.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/UniformPartialRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4323507b46fdff4cb8d7fa2c1f7ff4c7e303821 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/UniformPartialRejection.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RejectionLaw +import Mathlib.Algebra.Order.Field.Basic +import Mathlib.Analysis.SpecialFunctions.Exp + +namespace OAI + +/-! # Rejecting a uniform finite object through an explicit successful bijection -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +noncomputable section +variable {S A : Type*} [Fintype S] [Fintype A] [Nonempty S] [Nonempty A] +variable (p : S → Prop) (e : A ≃ {s // p s}) + +def partialEquivDraw (s : S) : Option A := + if h : p s then some (e.symm ⟨s,h⟩) else none + +omit [Fintype S] [Fintype A] [Nonempty S] [Nonempty A] in +lemma partialEquivDraw_eq_some (s : S) (a : A) : + partialEquivDraw p e s=some a ↔ s=(e a).val := by + constructor + · intro h + unfold partialEquivDraw at h + split_ifs at h with hs + · have hh := congrArg (fun a => (e a).val) (Option.some.inj h) + simpa only [Equiv.apply_symm_apply] using hh + · intro h + subst s + simp [partialEquivDraw,(e a).property] + +omit [Fintype A] [Nonempty A] in +lemma partialEquiv_success_mass (a : A) : + successMass (uniformLaw (α := S)) (partialEquivDraw p e) a=uniformMass (α := S) := by + unfold successMass + simp only [partialEquivDraw_eq_some,uniformLaw] + simp + +omit [Nonempty A] in +lemma partialEquiv_failure_mass : + failureMass (uniformLaw (α := S)) (partialEquivDraw p e)= + 1-(Fintype.card A:ℚ)/(Fintype.card S:ℚ) := by + have ht := success_failure_total (uniformLaw (α := S)) (partialEquivDraw p e) + simp only [partialEquiv_success_mass,Finset.sum_const,Finset.card_univ,nsmul_eq_mul] at ht + unfold uniformMass at ht + rw [mul_one_div] at ht + linarith + +/-- The bound applies before any approximate law is introduced, so later +TV errors can be accumulated without conditioning on success. -/ +theorem uniform_partial_retry_variation (fallback : A) (n : ℕ) : + variation (retryLaw (uniformLaw (α := S)) (partialEquivDraw p e) fallback n) + (uniformLaw (α := A)) ≤ (1-(Fintype.card A:ℚ)/(Fintype.card S:ℚ))^n := by + let s : ℚ := (Fintype.card A:ℚ)/(Fintype.card S:ℚ) + have hs0 : 0 ≤ s := by dsimp only [s]; positivity + have hc : Fintype.card A ≤ Fintype.card S := + Fintype.card_le_of_injective (fun a => (e a).val) + (Subtype.val_injective.comp e.injective) + have hs1 : s ≤ 1 := by + apply (div_le_one (by exact_mod_cast Fintype.card_pos (α := S))).mpr + exact_mod_cast hc + have he (a : A) : successMass (uniformLaw (α := S)) (partialEquivDraw p e) a= + s*uniformMass (α := A) := by + rw [partialEquiv_success_mass] + dsimp only [s,uniformMass] + have hn : (Fintype.card A:ℚ)≠0 := by exact_mod_cast (Fintype.card_pos (α := A)).ne' + field_simp [hn] + unfold variation + simp only [retryLaw_mass,outputMass] + simp_rw [he,partialEquiv_failure_mass] + exact stationary_variation s hs0 hs1 n fallback + +/-- A lower success bound gives the usual exponential failure tail. -/ +theorem uniform_partial_retry_exp (fallback : A) (n : ℕ) (K : ℝ) + (hs : 1/K ≤ (Fintype.card A:ℝ)/(Fintype.card S:ℝ)) : + (variation (retryLaw (uniformLaw (α := S)) (partialEquivDraw p e) fallback n) + (uniformLaw (α := A)):ℝ) ≤ Real.exp (-(n:ℝ)/K) := by + have hv := uniform_partial_retry_variation p e fallback n + have hc : Fintype.card A ≤ Fintype.card S := + Fintype.card_le_of_injective (fun a => (e a).val) + (Subtype.val_injective.comp e.injective) + have hj : (0:ℝ) < Fintype.card S := by exact_mod_cast Fintype.card_pos (α := S) + have hn : 0 ≤ 1-(Fintype.card A:ℝ)/(Fintype.card S:ℝ) := by + have hh := (div_le_one hj).mpr (show (Fintype.card A:ℝ) ≤ Fintype.card S by exact_mod_cast hc) + linarith + have hv' : (variation (retryLaw (uniformLaw (α := S)) (partialEquivDraw p e) fallback n) + (uniformLaw (α := A)):ℝ) ≤ (1-(Fintype.card A:ℝ)/(Fintype.card S:ℝ))^n := by + simpa only [Rat.cast_pow,Rat.cast_sub,Rat.cast_one,Rat.cast_div,Rat.cast_natCast] using + (Rat.cast_le (K := ℝ)).mpr hv + apply hv'.trans + calc + _ ≤ (Real.exp (-((Fintype.card A:ℝ)/(Fintype.card S:ℝ))))^n := by + apply pow_le_pow_left₀ hn + linarith [Real.add_one_le_exp (-((Fintype.card A:ℝ)/(Fintype.card S:ℝ)))] + _ = Real.exp (-(n:ℝ)*((Fintype.card A:ℝ)/(Fintype.card S:ℝ))) := by + rw [←Real.exp_nat_mul] + congr 1 + ring + _ ≤ _ := by + apply Real.exp_le_exp.mpr + have hh := mul_le_mul_of_nonneg_left hs (show (0:ℝ) ≤ n by positivity) + rw [mul_one_div] at hh + rw [neg_div] + nlinarith + +end +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/WarmKernelIteration.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/WarmKernelIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1c093d09b2fac690dea0d1882ea0ded3f41a1ce --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/WarmKernelIteration.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation + +namespace OAI + +/-! # Repeating an implementation bound averaged under the exact warm law -/ + +namespace ContingencyTables.WarmKernelIteration + +open CommonBasesFPRAS RealKernelApproximation +open scoped BigOperators Classical + +noncomputable section +variable {X : Type*} [Fintype X] + +/-- At every replacement step the reference distribution remains warm. +No warmness assumption is imposed on the implemented distribution. -/ +theorem power_distance (C : FiniteChain X) (K : FiniteKernel X X) + (nu : X → ℝ) (hnu : ∀ x,0≤nu x) (hmass : ∑ x,nu x≤1) + (U e : ℝ) (hwarm : ∀ x,nu x≤U*C.π x) + (hstep : ∀ rho : X → ℝ,(∀ x,0≤rho x) → (∑ x,rho x≤1) → + (∀ x,rho x≤U*C.π x) → distance (K.push rho) (C.kernel.push rho)≤e) + (n : ℕ) : + distance ((K.power n).push nu) ((C.kernel.power n).push nu)≤n*e := by + induction n with + | zero => simp [FiniteKernel.power,FiniteKernel.push_identity,distance] + | succ n ih => + let p := (K.power n).push nu + let q := (C.kernel.power n).push nu + have hq0 : ∀ x,0≤q x := (C.kernel.power n).push_nonneg nu hnu + have hq1 : ∑ x,q x≤1 := by + dsimp only [q] + rw [C.power_push_mass] + exact hmass + have hqwarm : ∀ x,q x≤U*C.π x := C.power_warm n nu U hwarm + have ht := distance_triangle (K.push p) (K.push q) (C.kernel.push q) + have hc := distance_push K p q + have hs := hstep q hq0 hq1 hqwarm + rw [FiniteKernel.power_push_succ,FiniteKernel.power_push_succ] + change distance (K.push p) (C.kernel.push q)≤_ + have hh : distance (K.push p) (C.kernel.push q)≤distance p q+e := by linarith + exact hh.trans (by dsimp only [p,q]; push_cast; linarith) + +/-- A uniform relative row estimate gives the corresponding total +variation estimate for every normalized incoming distribution. -/ +theorem mixing_distance (C : FiniteChain X) (nu : X → ℝ) + (hnu : ∀ x,0≤nu x) (hmass : ∑ x,nu x=1) (n : ℕ) (e : ℝ) + (hmix : ∀ x y,|((C.kernel.power n).P x y)/C.π y-1|≤e) : + distance ((C.kernel.power n).push nu) C.π≤e/2 := by + have hpoint (x y : X) : |(C.kernel.power n).P x y-C.π y|≤e*C.π y := by + have he : (((C.kernel.power n).P x y)/C.π y-1)*C.π y= + (C.kernel.power n).P x y-C.π y := by + field_simp [(C.positive y).ne'] + rw [←he,abs_mul,abs_of_pos (C.positive y)] + exact mul_le_mul_of_nonneg_right (hmix x y) (C.positive y).le + have hmixpoint (y : X) : |(C.kernel.power n).push nu y-C.π y|≤e*C.π y := by + have he : (C.kernel.power n).push nu y-C.π y= + ∑ x,nu x*((C.kernel.power n).P x y-C.π y) := by + simp only [FiniteKernel.push,mul_sub,Finset.sum_sub_distrib,←Finset.sum_mul,hmass,one_mul] + rw [he] + calc + _ ≤ ∑ x,|nu x*((C.kernel.power n).P x y-C.π y)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ x,nu x*(e*C.π y) := by + apply Finset.sum_le_sum + intro x _ + rw [abs_mul,abs_of_nonneg (hnu x)] + exact mul_le_mul_of_nonneg_left (hpoint x y) (hnu x) + _ = _ := by rw [←Finset.sum_mul,hmass,one_mul] + unfold distance + apply div_le_div_of_nonneg_right _ (by norm_num) + calc + _ ≤ ∑ y,e*C.π y := Finset.sum_le_sum (fun y _ => hmixpoint y) + _ = e := by rw [←Finset.mul_sum,C.normalized,mul_one] + +end +end ContingencyTables.WarmKernelIteration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/WeightedCellFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/WeightedCellFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..93bd687f35e405ae50ba2fc4fc50155aef0705f5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/WeightedCellFibres.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedCellFibres + +namespace OAI + +/-! # Exact weighted summation over one physical cell's fibres -/ + +namespace ContingencyTables.BalancedCellFibres + +open scoped BigOperators Classical + +variable {C : Type*} [Fintype C] [DecidableEq C] + +theorem weighted_fibre_sum (M : C → ℕ) (F : (C×Bool → ℕ) → ℝ) + (t : C) (g : Fin (M t+1) → ℝ) : + (∑ k : Fin (M t+1),fibre M F t k*g k)= + ∑ a : Profiles M,F (profile M a)*g (a t) := by + unfold fibre + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp [ite_mul] + +end ContingencyTables.BalancedCellFibres + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/WordCompletionStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/WordCompletionStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e5fbc51211cdebcceaf87eb76d9d79f97cf4316 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/WordCompletionStep.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CompletionStepApproximation +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # Independent finite words for a proposal and its completion test -/ + +namespace ContingencyTables.CompletionTranslation +open FirstSuccess FairBits +open scoped Classical +noncomputable section +variable {X I J : Type*} [Fintype X] [DecidableEq X] [Fintype I] [Fintype J] +variable {s f : ℕ} (R : X → Option I → ℕ) (P : X → Option J → ℕ) +variable (proposal : X → (Fin s → Bool) → Option X) +variable (draw : (x : X) → (Fin f → Bool) → Table (R x) (P x)) + +def wordCompletionStep (x : X) (bits : Fin (s+f) → Bool) : X := + let parts := splitWordEquiv s f bits + completionDecision R P x (proposal x parts.1) (draw x parts.2) + +theorem wordCompletionStep_law (x : X) : + mapLaw (uniformLaw (α := Fin (s+f) → Bool)) (wordCompletionStep R P proposal draw x)= + completionStepLaw R P + (fun x => mapLaw (uniformLaw (α := Fin s → Bool)) (proposal x)) + (fun x => mapLaw (uniformLaw (α := Fin f → Bool)) (draw x)) x := by + let finish := fun y word => completionDecision R P x y (draw x word) + let F := fun ab : (Fin s → Bool)×(Fin f → Bool) => finish (proposal x ab.1) ab.2 + have he := map_equiv (splitWordEquiv s f) (uniformLaw (α := Fin (s+f) → Bool)) F + rw [uniform_equiv,←uniform_product] at he + calc + _ = mapLaw (productLaw (uniformLaw (α := Fin s → Bool)) + (uniformLaw (α := Fin f → Bool))) F := he.symm + _ = _ := by + rw [mapLaw_product_finish] + unfold completionStepLaw + congr 1 + funext y + exact (mapLaw_comp (uniformLaw (α := Fin f → Bool)) (draw x) + (completionDecision R P x y)).symm + +end +end ContingencyTables.CompletionTranslation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Transport/WordContextVariance.lean b/lean/OAI/Combinatorics/ContingencyTables/Transport/WordContextVariance.lean new file mode 100644 index 0000000000000000000000000000000000000000..b76b4cc44d839be0520cda642ff9c7f795e4ab06 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Transport/WordContextVariance.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RowMajorPrefixFibres +import OAI.Combinatorics.ContingencyTables.Sampling.PhysicalContextVariance + +namespace OAI + +/-! # Physical transport bounds the literal word-prefix child variance -/ + +namespace ContingencyTables.RowMajorEnumeration + +open scoped BigOperators Classical +open SmallContextCoordinates SmallContextEnumeration SmallContextFibres +open PhysicalCompletionFibres LargePairEnumeration BalancedFamily BalancedBox +open ExcessContextProfiles SmallGraphProfiles FiniteExposureVariance IntegerWeightedTransport +open FirstPaperContextTransport FirstPaperPhysicalMarginal PaddedCompletions CompletionCounts + +universe u + +variable {I J : Type u} [Fintype I] [Fintype J] [LinearOrder I] [LinearOrder J] + +noncomputable def wordWeight (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (a : Fin (Fintype.card (Cells small)) → Fin (U+1)) : ℝ := + hardMarginal small B r c L (rawChoice small U (wordChoices small U a)) + +noncomputable def wordObservable (small : I → J → Bool) (U : ℕ) (H : SmallProfile small → ℝ) + (a : Fin (Fintype.card (Cells small)) → Fin (U+1)) : ℝ := + H (rawChoice small U (wordChoices small U a)) + +theorem word_context_variance (small : I → J → Bool) (B : I → J → ℕ) + (r : I → ℕ) (c : J → ℕ) (L U : ℕ) + (hU : 2 ≤ U) (hB : ∀ i j,small i j=true → B i j=U) + (hlarge : ∀ i j,small i j=false → 2 ≤ B i j) + (hcap : ∀ T : ResidualTables small r c (fun i => r i+rowLargeCount small i*L) + (fun j => c j+columnLargeCount small j*L),∀ i j,T.val.val i j ≤ B i j) + (k : Fin (Fintype.card (Cells small))) (τ : Fin k.val → Fin (U+1)) + (H : SmallProfile small → ℝ) : + let w := wordWeight small B r c L U + let G := wordObservable small U H + let cw := fun j : Fin (U+1) => fibreWeight + (fibreWeight w (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j + let σ := prefixExtension small (enumeration small k).val U (earlierWordChoices small U k τ) + variance (fun j => ∑ a,cw j a) (fun j => mean (cw j) G) ≤ + ((U:ℝ)+1)^4*(2+2*((Fintype.card (Cells small)-k.val-1:ℕ):ℝ)*((U:ℝ)+1)^2)* + physicalContextEnergy small B (enumeration small k).val σ (hardMarginal small B r c L) H := by + dsimp only + let s := (enumeration small k).val + let hs := (enumeration small k).property + let σ := prefixExtension small s U (earlierWordChoices small U k τ) + let e := laterEnumeration small k + let Ms := widths (fun _ : Fin (Fintype.card (Cells small)-k.val-1) => U) + let f := contextHard small B r c L Ms (contextEquiv small s hs e U) (prefixRaw small s σ U) + let cw := fun j : Fin (U+1) => fibreWeight + (fibreWeight (wordWeight small B r c L U) (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j + have hz (j : Fin (U+1)) : (∑ a,cw j a)=eliminate Ms f (childProfile U j.val) := by + exact (eliminate_context_eq_word_fibre small B U hB k τ j (hardMarginal small B r c L)).symm + have hm (j : Fin (U+1)) : (∑ a,cw j a*wordObservable small U H a)= + eliminate Ms (fun p => f p*H (assemble small s hs σ U e p)) (childProfile U j.val) := by + have h := eliminate_context_eq_word_fibre small B U hB k τ j + (fun x => hardMarginal small B r c L x*H x) + calc + _ = ∑ a,fibreWeight (fibreWeight + (fun a => wordWeight small B r c L U a*wordObservable small U H a) + (restriction k.val (Nat.le_of_lt k.isLt)) τ) (fun a => a k) j a := by + apply Finset.sum_congr rfl + intro a _ + exact (double_fibreWeight_mul _ _ _ _ _ _ a).symm + _ = _ := h.symm + have hμ (j : Fin (U+1)) : mean (cw j) (wordObservable small U H)= + eliminate Ms (fun p => f p*H (assemble small s hs σ U e p)) (childProfile U j.val)/ + eliminate Ms f (childProfile U j.val) := by + unfold mean + rw [hm,hz] + change variance (fun j => ∑ a,cw j a) (fun j => mean (cw j) (wordObservable small U H)) ≤ _ + simp_rw [hz,hμ] + exact physical_context_variance small B r c L s hs σ U hU hB hlarge + (prefixExtension_bounded small s U (earlierWordChoices small U k τ)) e hcap H + +end ContingencyTables.RowMajorEnumeration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/UnconditionalMain.lean b/lean/OAI/Combinatorics/ContingencyTables/UnconditionalMain.lean new file mode 100644 index 0000000000000000000000000000000000000000..088d181b4e2cd032a8477807e460707c985cd1d9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/UnconditionalMain.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingMachine +import OAI.Combinatorics.ContingencyTables.Sampling.ExactSamplingMachine +import OAI.Combinatorics.ContingencyTables.Counting.CountingMainMachine +import OAI.Combinatorics.ContingencyTables.Dense.FiniteBoxPrekopa +import OAI.Combinatorics.ContingencyTables.Dense.FiniteCheegerProof +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpBound + +namespace OAI + +/-! # Sampling and counting contingency tables with arbitrary margins + +The finite-box Prékopa–Leindler inequality, finite Cheeger inequality +and Edmonds–Karp bound yield sampling and counting algorithms with +uniform polynomial bit-cost guarantees. +-/ +namespace ContingencyTables + +/-- Paper 200-01: an almost-uniform sampler with polynomial cost on every execution. -/ +theorem boundedSampling : Algorithms.BoundedSamplingStatement := + SmallGraphProfiles.boundedSampling_conditional + PublishedInputs.finiteBoxPrekopaLeindler (fun _ _ => CheegerProof.finiteCheeger) + +/-- Paper 200-01: exact uniform sampling in expected polynomial bit time. -/ +theorem exactSampling : Algorithms.ExactSamplingStatement := + SmallGraphProfiles.exactSampling_conditional + PublishedInputs.finiteBoxPrekopaLeindler (fun _ _ => CheegerProof.finiteCheeger) + +/-- Paper 200-02: the cell-bounded counting FPRAS with a public fair-bit machine. -/ +theorem counting : Algorithms.CountingStatement := + CountingExecutedMachine.counting_conditional EdmondsKarpBound.edmondsKarp1972Theorem1 + PublishedInputs.finiteBoxPrekopaLeindler (fun _ _ => CheegerProof.finiteCheeger) + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdaptedFamily.lean b/lean/OAI/Combinatorics/Crossing/AdaptedFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..275bb0ecff7695d1e4e532786a2a559b3c07179d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdaptedFamily.lean @@ -0,0 +1,77 @@ +import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas +import Mathlib.LinearAlgebra.Dimension.Free +import Mathlib.LinearAlgebra.Basis.VectorSpace +import Mathlib.Algebra.BigOperators.Group.Finset.Pi +import Mathlib.Basic.Real.Basic +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module Submodule +open scoped BigOperators +variable {W : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + +theorem exists_adapted_family (E : ℕ → Submodule ℝ W) (hE : Monotone E) (hzero : E 0 = ⊥) + (h : ℕ) : + ∃ (v : Fin (finrank ℝ (E h)) → W) (d : Fin (finrank ℝ (E h)) → ℕ), + LinearIndependent ℝ v ∧ span ℝ (Set.range v) = E h ∧ + (∀ i, d i < h ∧ v i ∈ E (d i+1)) ∧ + (∑ i, d i) = ∑ e ∈ Finset.range h, e * (finrank ℝ (E (e+1)) - finrank ℝ (E e)) := by + classical + induction h with + | zero => + have hd : finrank ℝ (E 0) = 0 := by simp [hzero] + rw [hd] + refine ⟨Fin.elim0, Fin.elim0, linearIndependent_empty_type, ?_, ?_, ?_⟩ + · simp [hzero] + · intro i + exact Fin.elim0 i + · simp + | succ h ih => + obtain ⟨v, d, hli, hspan, hmem, hsum⟩ := ih + obtain ⟨C, hdisj, hsup⟩ := IsModularLattice.exists_disjoint_and_sup_eq (hE (Nat.le_succ h)) + have hCle : C ≤ E (h+1) := by rw [← hsup]; exact le_sup_right + have hdim : finrank ℝ (E h) + finrank ℝ C = finrank ℝ (E (h+1)) := by + have hh := Submodule.finrank_sup_add_finrank_inf_eq (E h) C + rw [hsup, hdisj.eq_bot, finrank_bot, add_zero] at hh + exact hh.symm + have hCdim : finrank ℝ C = finrank ℝ (E (h+1)) - finrank ℝ (E h) := by omega + let b := finBasis ℝ C + let w : Fin (finrank ℝ C) → W := fun i => C.subtype (b i) + have hwli : LinearIndependent ℝ w := b.linearIndependent.map' C.subtype (Submodule.ker_subtype C) + have hwspan : span ℝ (Set.range w) = C := by + change span ℝ (Set.range (C.subtype ∘ b)) = C + rw [Set.range_comp, Submodule.span_image, b.span_eq, Submodule.map_subtype_top] + let v' := Sum.elim v w + let d' := Sum.elim d (fun _ : Fin (finrank ℝ C) => h) + have hv' : LinearIndependent ℝ v' := + hli.sum_type hwli (by rwa [hspan, hwspan]) + let e : Fin (finrank ℝ (E (h+1))) ≃ + (Fin (finrank ℝ (E h)) ⊕ Fin (finrank ℝ C)) := + Fintype.equivOfCardEq (by simp [hdim]) + refine ⟨v' ∘ e, d' ∘ e, hv'.comp e e.injective, ?_, ?_, ?_⟩ + · rw [Set.range_comp, e.surjective.range_eq, Set.image_univ] + change span ℝ (Set.range (Sum.elim v w)) = E (h+1) + rw [Set.Sum.elim_range, span_union, hspan, hwspan, hsup] + · intro i + change d' (e i) < h+1 ∧ v' (e i) ∈ E (d' (e i)+1) + cases he : e i with + | inl j => + change d j < h+1 ∧ v j ∈ E (d j+1) + exact ⟨(hmem j).1.trans (Nat.lt_succ_self h), (hmem j).2⟩ + | inr j => + change h < h+1 ∧ w j ∈ E (h+1) + exact ⟨Nat.lt_succ_self h, hCle (b j).property⟩ + · change (∑ i, d' (e i)) = _ + rw [e.sum_comp, Fintype.sum_sum_type, Finset.sum_range_succ] + change (∑ i, d i) + (∑ _ : Fin (finrank ℝ C), h) = _ + rw [hsum] + simp [hCdim, Nat.mul_comm] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdditiveBlockRelation.lean b/lean/OAI/Combinatorics/Crossing/AdditiveBlockRelation.lean new file mode 100644 index 0000000000000000000000000000000000000000..929cd9dc2c8dbae2636cff0701a286849a077af9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdditiveBlockRelation.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.CyclePairing +import OAI.Combinatorics.Crossing.FourCyclePairing + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem fourCycle_pairing_zero (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (i k i₀ : Fin m) (p p' q q' : Fin n) : + edgePairing C.cycleIntersectionMatrix (walkEdgeChain (fourCycleWalk i i₀ p p')) + (walkEdgeChain (fourCycleWalk k i₀ q q'))=0 := by + by_cases hi : i=i₀ + · subst i + have hz : walkEdgeChain (fourCycleWalk i₀ i₀ p p')=0 := by rw [fourCycleWalk_chain]; abel + rw [hz] + simp [edgePairing] + by_cases hk : k=i₀ + · subst k + have hz : walkEdgeChain (fourCycleWalk i₀ i₀ q q')=0 := by rw [fourCycleWalk_chain]; abel + rw [hz] + simp [edgePairing] + by_cases hp : p=p' + · subst p' + have hz : walkEdgeChain (fourCycleWalk i i₀ p p)=0 := by rw [fourCycleWalk_chain]; abel + rw [hz] + simp [edgePairing] + by_cases hq : q=q' + · subst q' + have hz : walkEdgeChain (fourCycleWalk k i₀ q q)=0 := by rw [fourCycleWalk_chain]; abel + rw [hz] + simp [edgePairing] + exact C.lemma3_1 hnorm hstraight htrans _ _ + (fourCycleWalk_isCycle i i₀ p p' hi hp) (fourCycleWalk_isCycle k i₀ q q' hk hq) + +theorem lemma3_2 (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (i k i₀ : Fin m) : + ∃ r c : Fin n → ℝ, ∀ p q, + blockRectangle C.cycleIntersectionMatrix i k i₀ p q=r p+c q := by + cases n with + | zero => exact ⟨0,0,fun p => Fin.elim0 p⟩ + | succ n => + apply rectangle_additive (blockRectangle C.cycleIntersectionMatrix i k i₀) 0 0 + intro p p' q q' + rw [← fourCycle_pairing_rectangle] + exact C.fourCycle_pairing_zero hnorm hstraight htrans i k i₀ p p' q q' + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryDrawing.lean b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a927a91a56ffce982ef8bb15b107a9ee0b89dab --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryDrawing.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.AdjacentSurgeryRoutes + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def adjacentSurgeryDrawing (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : ContinuousDrawing m n := + D'.toContinuousDrawing.replaceTwoEdges p.1 q.1 + (adjacentSurgeryRouteP Kp Kq hm hadj) (adjacentSurgeryRouteQ Kp Kq hm hadj) + (adjacentSurgeryRouteP_injective Kp Kq hm hadj hemb) + (adjacentSurgeryRouteQ_injective Kp Kq hm hadj hemb) + (adjacentSurgeryRouteP_avoids_vertices Kp Kq hm hadj hv hemb) + (adjacentSurgeryRouteQ_avoids_vertices Kp Kq hm hadj hv hemb) + +theorem adjacentSurgeryDrawing_vertex (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).vertex=D'.vertex := rfl + +theorem adjacentSurgeryDrawing_first (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge p.1=adjacentSurgeryRouteP Kp Kq hm hadj := + ContinuousDrawing.replaceTwoRoutes_first _ _ _ _ _ + +theorem adjacentSurgeryDrawing_second (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge q.1=adjacentSurgeryRouteQ Kp Kq hm hadj := + ContinuousDrawing.replaceTwoRoutes_second _ _ _ (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) _ _ + +theorem adjacentSurgeryDrawing_other (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e=D'.edge e := + ContinuousDrawing.replaceTwoRoutes_other _ _ _ _ _ _ hep heq + +theorem adjacentSurgeryRouteP_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) : + HasFiniteAffineCover (adjacentSurgeryRouteP Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteP + split + · exact (reconnectedBackwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + · exact (reconnectedForwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + +theorem adjacentSurgeryRouteQ_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) : + HasFiniteAffineCover (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteQ + split + · exact (reconnectedForwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + · exact (reconnectedBackwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryPointRemoval.lean b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryPointRemoval.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf38d44225310882de6286efc8a59d0e7b639610 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryPointRemoval.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.AdjacentSurgeryDrawing +import OAI.Combinatorics.Crossing.PolygonalParametrizationCover + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e : BipartiteEdge m n) : HasFiniteAffineCover ((adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e) := by + classical + by_cases hep : e=p.1 + · subst e + rw [adjacentSurgeryDrawing_first] + exact adjacentSurgeryRouteP_hasFiniteAffineCover Kp Kq hm hadj + by_cases heq : e=q.1 + · subst e + rw [adjacentSurgeryDrawing_second Kp Kq hm hpq] + exact adjacentSurgeryRouteQ_hasFiniteAffineCover Kp Kq hm hadj + · rw [adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq] + exact (P e).hasFiniteAffineCover + +theorem adjacentSurgeryRoutes_avoid_crossing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∉ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∧ + x ∉ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + have ha := reconnected_paths_avoid_crossing Kp Kq hm hpq x hxp hxq + constructor + · unfold adjacentSurgeryRouteP + split + · exact ha.2 + · exact ha.1 + · unfold adjacentSurgeryRouteQ + split + · exact ha.1 + · exact ha.2 + +theorem adjacentSurgeryDrawing_avoids_crossing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) + (hother : ∀ e, e ≠ p.1 → e ≠ q.1 → x ∉ Set.range (D'.edge e)) : + ∀ e, x ∉ Set.range ((adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e) := by + have ha := adjacentSurgeryRoutes_avoid_crossing Kp Kq hm hpq hadj x hxp hxq + intro e + classical + by_cases hep : e=p.1 + · subst e + rw [adjacentSurgeryDrawing_first] + exact ha.1 + by_cases heq : e=q.1 + · subst e + rw [adjacentSurgeryDrawing_second Kp Kq hm hpq] + exact ha.2 + · rw [adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq] + exact hother e hep heq + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryRoutes.lean b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryRoutes.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b81efbe2bb3ac43c9beb4b353ab9bd52c9b9e97 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdjacentSurgeryRoutes.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.ReplaceDrawingEdges +import OAI.Combinatorics.Crossing.ReconnectedPointRemoval + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def adjacentSurgeryRouteP (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) : + Path (D'.vertex (.inl p.1.1)) (D'.vertex (.inr p.1.2)) := by + classical + exact if h : p.1.1=q.1.1 then (reconnectedBackwardPath Kp Kq hm).cast + (congrArg (fun i => D'.vertex (.inl i)) h) rfl + else (reconnectedForwardPath Kp Kq hm).cast rfl + (congrArg (fun j => D'.vertex (.inr j)) (hadj.resolve_left h)) + +def adjacentSurgeryRouteQ (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) : + Path (D'.vertex (.inl q.1.1)) (D'.vertex (.inr q.1.2)) := by + classical + exact if h : p.1.1=q.1.1 then (reconnectedForwardPath Kp Kq hm).cast + (congrArg (fun i => D'.vertex (.inl i)) h.symm) rfl + else (reconnectedBackwardPath Kp Kq hm).cast rfl + (congrArg (fun j => D'.vertex (.inr j)) (hadj.resolve_left h).symm) + +theorem adjacentSurgeryRouteP_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (adjacentSurgeryRouteP Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteP + split + · exact reconnectedBackwardPath_injective Kp Kq hm hemb + · exact reconnectedForwardPath_injective Kp Kq hm hemb + +theorem adjacentSurgeryRouteQ_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteQ + split + · exact reconnectedForwardPath_injective Kp Kq hm hemb + · exact reconnectedBackwardPath_injective Kp Kq hm hemb + +theorem adjacentSurgeryRouteP_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : BipartiteVertex m n) : + adjacentSurgeryRouteP Kp Kq hm hadj t ≠ D'.vertex j := by + unfold adjacentSurgeryRouteP + split + · exact reconnectedBackwardPath_interior_avoids_vertices Kp Kq hm hv hemb t ht j + · exact reconnectedForwardPath_interior_avoids_vertices Kp Kq hm hv hemb t ht j + +theorem adjacentSurgeryRouteQ_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : BipartiteVertex m n) : + adjacentSurgeryRouteQ Kp Kq hm hadj t ≠ D'.vertex j := by + unfold adjacentSurgeryRouteQ + split + · exact reconnectedForwardPath_interior_avoids_vertices Kp Kq hm hv hemb t ht j + · exact reconnectedBackwardPath_interior_avoids_vertices Kp Kq hm hv hemb t ht j + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AdmissibleAdjacentSurgery.lean b/lean/OAI/Combinatorics/Crossing/AdmissibleAdjacentSurgery.lean new file mode 100644 index 0000000000000000000000000000000000000000..f82c1e853d818e82e743024f588a99931f8d0585 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AdmissibleAdjacentSurgery.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.Crossing.SurgeryFiniteDrawing + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_admissible_adjacent_surgery (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (p q : C.InnerIndex) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + ∃ A : AdmissibleDrawing m n, (∀ e, HasFiniteAffineCover (A.edge e)) ∧ + crossingCount A < crossingCount (E.assembledAdmissible v hvinj hv hdet) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + obtain ⟨P,hmark,hport⟩ := E.exists_assembled_port_subdivision v hvinj hv hdet + obtain ⟨Kp⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport p + obtain ⟨Kq⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport q + have hemb := crossingSurgeryGraph_embedding C P hmark hport p q hm hcross + let B := E.adjacentSurgeryFiniteDrawing v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq + obtain ⟨A,hpoly,hcount⟩ := finite_intersection_normalization B + exact ⟨A,hpoly,hcount.trans_lt + (E.adjacentSurgeryFiniteDrawing_count_lt v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq)⟩ + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AffineIntervalRestriction.lean b/lean/OAI/Combinatorics/Crossing/AffineIntervalRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..26d873dd928c09597e9336a5a9a0cc700b446d2d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AffineIntervalRestriction.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.FiniteAffineCover +import OAI.Combinatorics.Crossing.PathSubarc + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem intervalSegment_interpolate (a b u v t : unitInterval) : + intervalSegment (intervalSegment a b u) (intervalSegment a b v) t= + intervalSegment a b (intervalSegment u v t) := by + apply Subtype.ext + dsimp [intervalSegment] + ring + +theorem segmentPoint_interpolate (a b : Plane) (u v t : ℝ) : + segmentPoint (segmentPoint a b u) (segmentPoint a b v) t= + segmentPoint a b ((1-t)*u+t*v) := by + ext <;> dsimp [segmentPoint] <;> ring + +theorem path_affine_restrict {a b : Plane} (γ : Path a b) (l r : unitInterval) (hlr : l < r) + (haff : ∀ t : unitInterval, γ (intervalSegment l r t)=segmentPoint (γ l) (γ r) t.val) + (u v : unitInterval) (hu : l ≤ u ∧ u ≤ r) (hv : l ≤ v ∧ v ≤ r) (t : unitInterval) : + γ (intervalSegment u v t)=segmentPoint (γ u) (γ v) t.val := by + obtain ⟨u',rfl⟩ := intervalSegment_surjective_interval l r hlr u hu + obtain ⟨v',rfl⟩ := intervalSegment_surjective_interval l r hlr v hv + rw [intervalSegment_interpolate,haff,haff,haff,segmentPoint_interpolate] + rfl + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AffinePathHalves.lean b/lean/OAI/Combinatorics/Crossing/AffinePathHalves.lean new file mode 100644 index 0000000000000000000000000000000000000000..ccca0416a9308169614c47445b7e6f14c7b96c3e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AffinePathHalves.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.IntervalSegments +import Mathlib.Tactic.Ring + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def intervalLeft (t : unitInterval) : unitInterval := ⟨t.val/2,by constructor <;> linarith [t.property.1,t.property.2]⟩ +def intervalRight (t : unitInterval) : unitInterval := ⟨(1+t.val)/2,by constructor <;> linarith [t.property.1,t.property.2]⟩ + +theorem intervalLeft_strictMono : StrictMono intervalLeft := by + intro s t hst + change s.val/2 < t.val/2 + exact div_lt_div_of_pos_right hst (by norm_num) + +theorem intervalRight_strictMono : StrictMono intervalRight := by + intro s t hst + change (1+s.val)/2 < (1+t.val)/2 + have hh : s.val < t.val := hst + linarith + +theorem intervalSegment_left (a b t : unitInterval) : + intervalSegment (intervalLeft a) (intervalLeft b) t=intervalLeft (intervalSegment a b t) := by + apply Subtype.ext + change (1-t.val)*(a.val/2)+t.val*(b.val/2)=((1-t.val)*a.val+t.val*b.val)/2 + ring + +theorem intervalSegment_right (a b t : unitInterval) : + intervalSegment (intervalRight a) (intervalRight b) t=intervalRight (intervalSegment a b t) := by + apply Subtype.ext + change (1-t.val)*((1+a.val)/2)+t.val*((1+b.val)/2)=(1+((1-t.val)*a.val+t.val*b.val))/2 + ring + +theorem path_trans_intervalLeft {a b c : Plane} (γ : Path a b) (η : Path b c) (t : unitInterval) : + (γ.trans η) (intervalLeft t)=γ t := by + rw [← (γ.trans η).extend_extends' (intervalLeft t)] + rw [Path.extend_trans_of_le_half γ η (show (intervalLeft t).val ≤ 1/2 by + change t.val/2 ≤ 1/2 + linarith [t.property.2])] + have he : 2*(intervalLeft t).val=t.val := by change 2*(t.val/2)=t.val; ring + rw [he,γ.extend_extends'] + +theorem path_trans_intervalRight {a b c : Plane} (γ : Path a b) (η : Path b c) (t : unitInterval) : + (γ.trans η) (intervalRight t)=η t := by + rw [← (γ.trans η).extend_extends' (intervalRight t)] + rw [Path.extend_trans_of_half_le γ η (show 1/2 ≤ (intervalRight t).val by + change 1/2 ≤ (1+t.val)/2 + linarith [t.property.1])] + have he : 2*(intervalRight t).val-1=t.val := by change 2*((1+t.val)/2)-1=t.val; ring + rw [he,η.extend_extends'] + +theorem intervalSegment_zero_one (t : unitInterval) : intervalSegment 0 1 t=t := by + apply Subtype.ext + change (1-t.val)*0+t.val*1=t.val + ring + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AffineSideEvents.lean b/lean/OAI/Combinatorics/Crossing/AffineSideEvents.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a6fa81b0606ef2454904b819fd144b10d260c12 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AffineSideEvents.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.StepEvents +import Mathlib.Tactic.FieldSimp + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +def positiveIndicator (x : ℝ) : ℝ := if 0 < x then 1 else 0 + +def slopeSign (b : ℝ) : ℝ := if 0 < b then 1 else -1 + +def sideBefore (b : ℝ) : ℝ := if 0 < b then 0 else 1 + +def sideAfter (b : ℝ) : ℝ := if 0 < b then 1 else 0 + +theorem sideAfter_sub_before (b : ℝ) : sideAfter b-sideBefore b = slopeSign b := by + unfold sideAfter sideBefore slopeSign + split_ifs <;> norm_num + +theorem positiveIndicator_factor (b r t : ℝ) (hb : b ≠ 0) (ht : t ≠ r) : + positiveIndicator (b*(t-r)) = stepAt r (sideBefore b) (sideAfter b) t := by + rcases lt_or_gt_of_ne hb with hb | hb + · by_cases htr : t sideBefore (b i)) (fun i => sideAfter (b i)) hr h0 h1 + have he : ∀ i : Fin n, stepEvent r (fun i => sideBefore (b i)) (fun i => sideAfter (b i)) i = + if 0 change (_ : ℝ) < _ <;> norm_num [mid]) + obtain ⟨ab,hab,ha,hb⟩ := hScov z + have hlo : ab.1 ≤ t i.castSucc := by + by_contra hn + obtain ⟨j,hj⟩ := hleft ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact lt_of_not_ge hn,by rw [hj]; exact ha.trans_lt hz.2⟩ + have hhi : t i.succ ≤ ab.2 := by + by_contra hn + obtain ⟨j,hj⟩ := hright ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact hz.1.trans_le hb,by rw [hj]; exact lt_of_not_ge hn⟩ + have hle : t i.castSucc ≤ t i.succ := ht.monotone (by change i.val ≤ i.val+1; omega) + exact path_affine_restrict γ ab.1 ab.2 (hSlt ab hab) (hSaff ab hab) + (t i.castSucc) (t i.succ) ⟨hlo,hle.trans hhi⟩ ⟨hlo.trans hle,hhi⟩ u + refine ⟨{pieces:=k,knot:=t,increasing:=ht,first:=h0,last:=h1,affine:=haff},?_⟩ + intro u hu + change u ∈ Set.range t + rw [hR] + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem (Finset.mem_union_right _ hu)) + +theorem exists_marked_polygonal_subdivision {m n : ℕ} (D : AdmissibleDrawing m n) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) : + ∃ P : ∀ e, PolygonalParametrization (D.edge e), + ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot := by + classical + have hex (e : BipartiteEdge m n) := (hpoly e).refine (marked_parameters_finite D.toFiniteIntersectionDrawing e).toFinset + choose P hP using hex + exact ⟨P,fun e t ht => hP e (by simpa using ht)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AlternatingPaths.lean b/lean/OAI/Combinatorics/Crossing/AlternatingPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c83aaecd7810b5de290c35e854690255a652ee9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AlternatingPaths.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.Crossing.FinitePathChain + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def alternatingPath (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) : (n : ℕ) → Path (a 0) (b n) + | 0 => p 0 + | n+1 => ((alternatingPath a b p q n).trans (q n)).trans (p (n+1)) + +theorem alternatingPath_range_iff (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) : (n : ℕ) → ∀ x, + x ∈ Set.range (alternatingPath a b p q n) ↔ + (∃ i, i ≤ n ∧ x ∈ Set.range (p i)) ∨ (∃ i, i < n ∧ x ∈ Set.range (q i)) + | 0, x => by + constructor + · intro h + exact Or.inl ⟨0,le_rfl,h⟩ + · rintro (⟨i,hi,h⟩ | ⟨i,hi,h⟩) + · have he : i=0 := by omega + subst i + exact h + · omega + | n+1, x => by + rw [alternatingPath,Path.trans_range,Path.trans_range,Set.mem_union,Set.mem_union, + alternatingPath_range_iff a b p q n] + constructor + · intro hx + rcases hx with hx | hx + · rcases hx with hx | hx + · rcases hx with ⟨i,hi,h⟩ | ⟨i,hi,h⟩ + · exact Or.inl ⟨i,by omega,h⟩ + · exact Or.inr ⟨i,by omega,h⟩ + · exact Or.inr ⟨n,by omega,hx⟩ + · exact Or.inl ⟨n+1,le_rfl,hx⟩ + · rintro (⟨i,hi,h⟩ | ⟨i,hi,h⟩) + · by_cases he : i=n+1 + · subst i + exact Or.inr h + · exact Or.inl (Or.inl (Or.inl ⟨i,by omega,h⟩)) + · by_cases he : i=n + · subst i + exact Or.inl (Or.inr h) + · exact Or.inl (Or.inl (Or.inr ⟨i,by omega,h⟩)) + +theorem alternatingPath_injective (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) : (n : ℕ) → + (∀ i, i ≤ n → Function.Injective (p i)) → (∀ i, i < n → Function.Injective (q i)) → + (∀ i j, i ≤ n → j ≤ n → i ≠ j → Disjoint (Set.range (p i)) (Set.range (p j))) → + (∀ i j, i < n → j < n → i ≠ j → Disjoint (Set.range (q i)) (Set.range (q j))) → + (∀ i j, i ≤ n → j < n → ∀ x, x ∈ Set.range (p i) → x ∈ Set.range (q j) → + (i=j ∧ x=b j) ∨ (i=j+1 ∧ x=a (j+1))) → + Function.Injective (alternatingPath a b p q n) + | 0, hp, _, _, _, _ => hp 0 le_rfl + | n+1, hp, hq, hpp, hqq, hpq => by + have hprev : Function.Injective (alternatingPath a b p q n) := + alternatingPath_injective a b p q n (fun i hi => hp i (by omega)) + (fun i hi => hq i (by omega)) (fun i j hi hj => hpp i j (by omega) (by omega)) + (fun i j hi hj => hqq i j (by omega) (by omega)) + (fun i j hi hj => hpq i j (by omega) (by omega)) + have hfirst : Function.Injective ((alternatingPath a b p q n).trans (q n)) := by + apply path_trans_injective _ _ hprev (hq n (by omega)) + intro x hx hy + rcases (alternatingPath_range_iff a b p q n x).mp hx with ⟨i,hi,hh⟩ | ⟨i,hi,hh⟩ + · rcases hpq i n (by omega) (by omega) x hh hy with ⟨he,hx⟩ | ⟨he,hx⟩ + · exact hx + · omega + · exact False.elim (Set.disjoint_left.mp (hqq i n (by omega) (by omega) (by omega)) hh hy) + apply path_trans_injective _ _ hfirst (hp (n+1) le_rfl) + intro x hx hy + rw [Path.trans_range] at hx + rcases hx with hx | hx + · rcases (alternatingPath_range_iff a b p q n x).mp hx with ⟨i,hi,hh⟩ | ⟨i,hi,hh⟩ + · exact False.elim (Set.disjoint_left.mp (hpp i (n+1) (by omega) le_rfl (by omega)) hh hy) + · rcases hpq (n+1) i le_rfl (by omega) x hy hh with ⟨he,hx⟩ | ⟨he,hx⟩ <;> omega + · rcases hpq (n+1) n le_rfl (by omega) x hy hx with ⟨he,hx⟩ | ⟨he,hx⟩ + · omega + · exact hx + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ArcRangeMinimality.lean b/lean/OAI/Combinatorics/Crossing/ArcRangeMinimality.lean new file mode 100644 index 0000000000000000000000000000000000000000..24a260fa0926a41a225a44966025222dcfd49282 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ArcRangeMinimality.lean @@ -0,0 +1,23 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Topology.Connected.Basic +import Mathlib.Topology.Order.IntermediateValue +import Mathlib.Topology.Separation.Hausdorff + +namespace OAI + +namespace Zarankiewicz + +theorem path_range_eq_of_subset {a b : Plane} (γ δ : Path a b) + (hγ : Function.Injective γ) (hsub : Set.range δ ⊆ Set.range γ) : + Set.range δ=Set.range γ := by + apply Set.Subset.antisymm hsub + rintro x ⟨t,rfl⟩ + have hc : IsPreconnected (γ ⁻¹' Set.range δ) := + (isPreconnected_range δ.continuous).preimage_of_isClosedMap hγ γ.continuous.isClosedMap hsub + have h0 : (0 : unitInterval) ∈ γ ⁻¹' Set.range δ := ⟨0,δ.source.trans γ.source.symm⟩ + have h1 : (1 : unitInterval) ∈ γ ⁻¹' Set.range δ := ⟨1,δ.target.trans γ.target.symm⟩ + exact hc.Icc_subset h0 h1 t.property + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledAdmissibleDrawing.lean b/lean/OAI/Combinatorics/Crossing/AssembledAdmissibleDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..625925d165c14abc35665b8c86de38141c14af3e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledAdmissibleDrawing.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.Crossing.CrossingDiskNeighborhood +import OAI.Combinatorics.Crossing.ProperSegmentCrossing +import OAI.Combinatorics.Crossing.ProperCrossingLocality + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem crossingChord_meeting_proper (C : DrawingPassages D) (p q : C.InnerIndex) + (hpq : p ≠ q) (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) + (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ C.crossingDisk p ∧ + ProperCrossing + (openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p))) + (openSegmentTrace (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) x := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have hst : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val = + segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val := by + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs.trans ht.symm + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property hst + refine ⟨?_,?_⟩ + · rw [← hs] + exact C.crossingChord_interior_in_disk p s hsi + · apply properCrossing_openSegments _ _ _ _ x hd + · exact ⟨s.val,hsi,by simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs⟩ + · exact ⟨t.val,hti,by simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht⟩ + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem assembled_crossings_proper (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f : BipartiteEdge m n) (hef : e ≠ f) (x : Plane) + (hx : x ∈ edgeInterior (E.assembledDrawing v hvinj hv) e) + (hy : x ∈ edgeInterior (E.assembledDrawing v hvinj hv) f) : + ProperCrossing (edgeInterior (E.assembledDrawing v hvinj hv) e) + (edgeInterior (E.assembledDrawing v hvinj hv) f) x := by + obtain ⟨s,hs,he⟩ := hx + obtain ⟨t,ht,hf⟩ := hy + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) ⟨s,he⟩ ⟨t,hf⟩ + have hpq : p ≠ q := fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨hxin,hproper⟩ := C.crossingChord_meeting_proper p q hpq x hxp hxq + apply properCrossing_of_local_eq _ _ _ _ x hproper (C.crossingDisk p) (C.crossingDisk_isOpen p) hxin + · intro z hz + simpa only [hp] using (E.assembled_trace_in_crossingDisk v hvinj hv p z hz).symm + · intro z hz + have hzq : z ∈ C.crossingDisk q := by + change squaredLength (z-(C.innerMark q).val) < C.radius^2 + rw [← hm] + exact hz + simpa only [hq] using (E.assembled_trace_in_crossingDisk v hvinj hv q z hzq).symm + +def assembledAdmissible (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : AdmissibleDrawing m n where + toContinuousDrawing := E.assembledDrawing v hvinj hv + crossings_finite := E.assembled_crossings_finite v hvinj hv hdet + crossings_proper := E.assembled_crossings_proper v hvinj hv hdet + no_triples := E.assembled_no_triples v hvinj hv hdet + +theorem assembled_crossingCount_le (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + crossingCount (E.assembledAdmissible v hvinj hv hdet) ≤ finiteCrossingCount D := by + have h := Set.ncard_le_ncard (E.assembled_crossings_subset v hvinj hv hdet) C.chordCrossings_finite + have hcount : crossingCount (E.assembledAdmissible v hvinj hv hdet)= + (crossingPoints (E.assembledDrawing v hvinj hv)).ncard := by + rw [Set.ncard_eq_toFinset_card _ (E.assembled_crossings_finite v hvinj hv hdet)] + rfl + rw [hcount] + exact h.trans C.chordCrossings_ncard_le + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledContinuousDrawing.lean b/lean/OAI/Combinatorics/Crossing/AssembledContinuousDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..424645b194e8034bec6f6777c575d06ef0d98243 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledContinuousDrawing.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.AssembledEdge + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem vertex_spoke_vertex_eq (C : DrawingPassages D) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (j k : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) + (hk : v k ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : k=j := by + by_contra hkj + have hd := C.disks_disjoint _ _ (C.vertexMark_injective.ne (Ne.symm hkj)) + exact Set.disjoint_left.mp hd (C.vertex_spoke_range_in_disk v hv j p hk) (hv k).le + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem middlePath_avoids_vertices (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (e : BipartiteEdge m n) + (j : BipartiteVertex m n) : v j ∉ Set.range (E.middlePath e) := by + intro hx + rcases (E.middlePath_range_iff e (v j)).mp hx with ⟨i,hi,⟨t,ht⟩⟩ | ⟨p,hp,hx⟩ + · exact E.avoids_new_vertices v hv i t j ht + · exact Set.disjoint_left.mp (C.crossingChord_avoids_vertex_disks p j) hx (hv j).le + +theorem assembledEdge_vertex_eq (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (e : BipartiteEdge m n) + (j : BipartiteVertex m n) (hj : v j ∈ Set.range (E.assembledEdge v e)) : + j=.inl e.1 ∨ j=.inr e.2 := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at hj + rcases hj with (hj | hj) | hj + · exact Or.inl (C.vertex_spoke_vertex_eq v hv _ j (C.startPortAt e) hj) + · exact False.elim (E.middlePath_avoids_vertices v hv e j hj) + · rw [endSpoke_range] at hj + exact Or.inr (C.vertex_spoke_vertex_eq v hv _ j (C.endPortAt e) hj) + +theorem assembledEdge_interior_avoids_vertices (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) + (j : BipartiteVertex m n) : E.assembledEdge v e t ≠ v j := by + intro he + rcases E.assembledEdge_vertex_eq v hv e j ⟨t,he⟩ with rfl | rfl + · have hh := E.assembledEdge_injective v hv e (he.trans (E.assembledEdge v e).source.symm) + exact ht.1.ne hh.symm + · have hh := E.assembledEdge_injective v hv e (he.trans (E.assembledEdge v e).target.symm) + exact ht.2.ne hh + +def assembledDrawing (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (hvinj : Function.Injective v) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) : + ContinuousDrawing m n where + vertex := v + vertex_injective := hvinj + edge := E.assembledEdge v + edge_injective := E.assembledEdge_injective v hv + interior_avoids_vertices := E.assembledEdge_interior_avoids_vertices v hv + +theorem exists_assembledDrawing (D : FiniteIntersectionDrawing m n) : + ∃ (C : DrawingPassages D) (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2), + ∀ e, Function.Injective ((E.assembledDrawing v hvinj hv).edge e) := by + obtain ⟨C⟩ := nonempty_drawingPassages D + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨C,E,v,hvinj,hv,E.assembledEdge_injective v hv⟩ + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledCrossings.lean b/lean/OAI/Combinatorics/Crossing/AssembledCrossings.lean new file mode 100644 index 0000000000000000000000000000000000000000..f45ca63a7af048dd722cdc27332f66a74bf065dd --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledCrossings.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.Crossing.MiddleEdgeIncidence +import OAI.Combinatorics.Crossing.CrossingDiskCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem vertex_spokes_meeting (C : DrawingPassages D) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (j k : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) (q : C.PortsAt (C.vertexMark k)) + (hpq : p.val ≠ q.val) (x : Plane) + (hx : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) + (hy : x ∈ Set.range (Path.segment (v k) (C.portPoint q.val))) : x=v j := by + by_cases hjk : j=k + · subst k + exact spokes_meet_only_at_center _ _ _ (hdet j p q (fun he => hpq (congrArg Subtype.val he))) + (by simpa only [Path.range_segment] using hx) (by simpa only [Path.range_segment] using hy) + · exact False.elim (Set.disjoint_left.mp (C.vertex_spokes_disjoint_of_vertices_ne v hv j k hjk p q) hx hy) + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem assembled_spoke_meeting (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e : BipartiteEdge m n) (j : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) + (hep : e ≠ p.val.1.1) (x : Plane) (hx : x ∈ Set.range (E.assembledEdge v e)) + (hy : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : x=v j := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at hx + rcases hx with (hx | hx) | hx + · exact C.vertex_spokes_meeting v hv hdet j _ p (C.startPortAt e) + (fun he => hep (congrArg (fun r : C.Port => r.1.1) he).symm) x hy hx + · exact False.elim (hep (E.middle_spoke_edge_eq v hv e j p x hx hy)) + · rw [endSpoke_range] at hx + exact C.vertex_spokes_meeting v hv hdet j _ p (C.endPortAt e) + (fun he => hep (congrArg (fun r : C.Port => r.1.1) he).symm) x hy hx + +theorem assembled_meeting_chords (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f : BipartiteEdge m n) (hef : e ≠ f) (x : Plane) + (havoid : ∀ j, x ≠ v j) (hx : x ∈ Set.range (E.assembledEdge v e)) + (hy : x ∈ Set.range (E.assembledEdge v f)) : + ∃ p q : C.InnerIndex, p.1=e ∧ q.1=f ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q) := by + have hm (a b : BipartiteEdge m n) (hab : a ≠ b) + (ha : x ∈ Set.range (E.assembledEdge v a)) (hb : x ∈ Set.range (E.assembledEdge v b)) : + x ∈ Set.range (E.middlePath a) := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at ha + rcases ha with (ha | ha) | ha + · exact False.elim (havoid _ (E.assembled_spoke_meeting v hv hdet b _ (C.startPortAt a) + (Ne.symm hab) x hb ha)) + · exact ha + · rw [endSpoke_range] at ha + exact False.elim (havoid _ (E.assembled_spoke_meeting v hv hdet b _ (C.endPortAt a) + (Ne.symm hab) x hb ha)) + exact E.middle_middle_meeting_chords e f hef x (hm e f hef hx hy) (hm f e (Ne.symm hef) hy hx) + +theorem assembled_crossings_subset (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + crossingPoints (E.assembledDrawing v hvinj hv) ⊆ C.chordCrossings := by + rintro x ⟨e,f,hef,⟨s,hs,he⟩,⟨t,ht,hf⟩⟩ + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) + ⟨s,he⟩ ⟨t,hf⟩ + exact ⟨p,q,(fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq))),hxp,hxq⟩ + +theorem assembled_crossings_finite (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + (crossingPoints (E.assembledDrawing v hvinj hv)).Finite := + C.chordCrossings_finite.subset (E.assembled_crossings_subset v hvinj hv hdet) + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledEdge.lean b/lean/OAI/Combinatorics/Crossing/AssembledEdge.lean new file mode 100644 index 0000000000000000000000000000000000000000..14e28b4ec054b3990598a864306f02eb2bc3e733 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledEdge.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.MiddleSpokeMeeting + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +def startSpoke (C : DrawingPassages D) (v : BipartiteVertex m n → Plane) (e : BipartiteEdge m n) : + Path (v (.inl e.1)) (C.arcStart (C.firstArc e)) := Path.segment _ _ + +def endSpoke (C : DrawingPassages D) (v : BipartiteVertex m n → Plane) (e : BipartiteEdge m n) : + Path (C.arcEnd (C.lastArc e)) (v (.inr e.2)) := (Path.segment _ _).symm + +def assembledEdge (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (e : BipartiteEdge m n) : Path (v (.inl e.1)) (v (.inr e.2)) := + ((startSpoke C v e).trans (E.anchoredMiddle e)).trans (endSpoke C v e) + +theorem startSpoke_injective (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (e : BipartiteEdge m n) : + Function.Injective (startSpoke C v e) := C.vertex_spoke_injective v hv _ (C.startPortAt e) + +theorem endSpoke_range (v : BipartiteVertex m n → Plane) (e : BipartiteEdge m n) : + Set.range (endSpoke C v e)=Set.range (Path.segment (v (.inr e.2)) (C.portPoint (C.endPortAt e).val)) := by + exact Path.symm_range _ + +theorem endSpoke_injective (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (e : BipartiteEdge m n) : + Function.Injective (endSpoke C v e) := by + intro s t he + have hh := C.vertex_spoke_injective v hv _ (C.endPortAt e) he + have hval := congrArg Subtype.val hh + apply Subtype.ext + change 1-s.val=1-t.val at hval + linarith + +theorem assembledEdge_injective (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (e : BipartiteEdge m n) : + Function.Injective (E.assembledEdge v e) := by + have hfirst : Function.Injective ((startSpoke C v e).trans (E.anchoredMiddle e)) := by + apply path_trans_injective _ _ (startSpoke_injective v hv e) (E.anchoredMiddle_injective e) + intro x hx hy + exact E.middle_spoke_meeting v hv e _ (C.startPortAt e) x hy hx + apply path_trans_injective _ _ hfirst (endSpoke_injective v hv e) + intro x hx hy + rw [Path.trans_range] at hx + rw [endSpoke_range] at hy + rcases hx with hx | hx + · have hd := C.vertex_spokes_disjoint_of_vertices_ne v hv (.inl e.1) (.inr e.2) + (by simp) (C.startPortAt e) (C.endPortAt e) + exact False.elim (Set.disjoint_left.mp hd hx hy) + · exact E.middle_spoke_meeting v hv e _ (C.endPortAt e) x hx hy + +theorem assembledEdge_range_iff (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (e : BipartiteEdge m n) (x : Plane) : + x ∈ Set.range (E.assembledEdge v e) ↔ + (x ∈ Set.range (startSpoke C v e) ∨ + (∃ i : C.ArcIndex, i.1=e ∧ x ∈ Set.range (E.chain i).path) ∨ + (∃ p : C.InnerIndex, p.1=e ∧ x ∈ Set.range (C.crossingChord p))) ∨ + x ∈ Set.range (endSpoke C v e) := by + simp only [assembledEdge,Path.trans_range,Set.mem_union,anchoredMiddle_range,E.middlePath_range_iff] + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledNoTriples.lean b/lean/OAI/Combinatorics/Crossing/AssembledNoTriples.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2257f3bfb7f66523617dba4046e76bab8f25d67 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledNoTriples.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.Crossing.AssembledCrossings + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem assembled_no_triples (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f g : BipartiteEdge m n) (hef : e ≠ f) (heg : e ≠ g) (hfg : f ≠ g) : + edgeInterior (E.assembledDrawing v hvinj hv) e ∩ + edgeInterior (E.assembledDrawing v hvinj hv) f ∩ + edgeInterior (E.assembledDrawing v hvinj hv) g=∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + rintro x ⟨⟨⟨s,hs,he⟩,⟨t,ht,hf⟩⟩,⟨u,hu,hg⟩⟩ + have ha : ∀ j, x ≠ v j := fun j heq => + E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq) + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x ha ⟨s,he⟩ ⟨t,hf⟩ + obtain ⟨r,z,hr,hz,hxr,hxz⟩ := E.assembled_meeting_chords v hv hdet e g heg x ha ⟨s,he⟩ ⟨u,hg⟩ + apply C.innerMark_no_triples p q z + · intro heq + exact hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + · intro heq + exact heg (hp.symm.trans ((congrArg Sigma.fst heq).trans hz)) + · intro heq + exact hfg (hq.symm.trans ((congrArg Sigma.fst heq).trans hz)) + · exact C.chord_meeting_marks_eq p q hxp hxq + · exact C.chord_meeting_marks_eq p z hxp hxz + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AssembledPortIncidence.lean b/lean/OAI/Combinatorics/Crossing/AssembledPortIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..34f792baec936f4a551f6c2fe446281714e8adc7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AssembledPortIncidence.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.AssembledCrossings + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem portPoint_mem_exterior (E : PolygonalExterior C) (p : C.Port) : + C.portPoint p ∈ Set.range (E.chain p.1).path := by + rcases p with ⟨i,b⟩ + cases b + · exact ⟨0,(E.chain i).path.source⟩ + · exact ⟨1,(E.chain i).path.target⟩ + +theorem assembled_port_mem_range (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (p : C.Port) : C.portPoint p ∈ Set.range (E.assembledEdge v p.1.1) := by + apply (E.assembledEdge_range_iff v p.1.1 (C.portPoint p)).mpr + exact Or.inl (Or.inr (Or.inl ⟨p.1,rfl,E.portPoint_mem_exterior p⟩)) + +theorem assembled_exterior_edge_eq (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (i : C.ArcIndex) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hy : x ∈ Set.range (E.chain i).path) : e=i.1 := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at hx + rcases hx with (hx | hx) | hx + · obtain ⟨s,hs⟩ := hy + obtain ⟨t,ht⟩ := hx + have hh := E.exterior_spoke_meeting_parameters v hv i _ (C.startPortAt e) s t (hs.trans ht.symm) + rcases hh.2 with ⟨_,he⟩ | ⟨_,he⟩ + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact E.middle_exterior_edge_eq e i x hx hy + · rw [endSpoke_range] at hx + obtain ⟨s,hs⟩ := hy + obtain ⟨t,ht⟩ := hx + have hh := E.exterior_spoke_meeting_parameters v hv i _ (C.endPortAt e) s t (hs.trans ht.symm) + rcases hh.2 with ⟨_,he⟩ | ⟨_,he⟩ + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + +theorem assembled_port_unique_edge (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (p : C.Port) + (hp : C.portPoint p ∈ Set.range (E.assembledEdge v e)) : e=p.1.1 := + E.assembled_exterior_edge_eq v hv e p.1 (C.portPoint p) hp (E.portPoint_mem_exterior p) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisAdmissibility.lean b/lean/OAI/Combinatorics/Crossing/AxisAdmissibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..87db4437348765bc5f9e0679b1764bc767fdbfe8 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisAdmissibility.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.Crossing.AxisFiniteCrossings +import OAI.Combinatorics.Crossing.AxisGenericPositions +import OAI.Combinatorics.Crossing.RowCrossingCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem axisContinuousDrawing_meeting_independent (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) (e f : BipartiteEdge m n) (hef : e ≠ f) + (x : Plane) (hx : x ∈ edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e) + (hy : x ∈ edgeInterior (axisContinuousDrawing a b hai hbi ha hb) f) : e.1 ≠ f.1 ∧ e.2 ≠ f.2 := by + rw [axisContinuousDrawing_interior] at hx hy + obtain ⟨t,ht,he⟩ := hx + obtain ⟨u,hu,hf⟩ := hy + have hmeet : axisSegmentPoint (a e.1) (b e.2) t=axisSegmentPoint (a f.1) (b f.2) u := he.trans hf.symm + constructor + · intro hfirst + rw [hfirst] at hmeet + have hh := axisSegmentPoint_same_vertical (a f.1) (b e.2) (b f.2) t u (ha f.1) ht.1 hmeet + exact hef (Prod.ext hfirst (hbi hh)) + · intro hsecond + rw [hsecond] at hmeet + have hh := axisSegmentPoint_same_horizontal (a e.1) (a f.1) (b f.2) t u (hb f.2) ht.2 hmeet + exact hef (Prod.ext (hai hh) hsecond) + +theorem axisContinuousDrawing_line_equation (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) (e : BipartiteEdge m n) (x : Plane) + (hx : x ∈ edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e) : + a e.1*x.1+b e.2*x.2=a e.1*b e.2 := by + rw [axisContinuousDrawing_interior] at hx + obtain ⟨t,ht,he⟩ := hx + rw [← he] + exact axisSegmentPoint_line_equation _ _ _ + +def axisAdmissibleDrawing (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) + (hgeneric : ∀ e f g : BipartiteEdge m n, AxisIndependentTriple e f g → + axisConcurrency (a e.1) (b e.2) (a f.1) (b f.2) (a g.1) (b g.2) ≠ 0) : AdmissibleDrawing m n where + toContinuousDrawing := axisContinuousDrawing a b hai hbi ha hb + crossings_finite := axisContinuousDrawing_crossings_finite a b hai hbi ha hb + crossings_proper := axisContinuousDrawing_crossings_proper a b hai hbi ha hb + no_triples := by + intro e f g hef heg hfg + apply Set.eq_empty_iff_forall_notMem.mpr + rintro x ⟨⟨he,hf⟩,hg⟩ + have h₀ := axisContinuousDrawing_meeting_independent a b hai hbi ha hb e f hef x he hf + have h₁ := axisContinuousDrawing_meeting_independent a b hai hbi ha hb e g heg x he hg + have h₂ := axisContinuousDrawing_meeting_independent a b hai hbi ha hb f g hfg x hf hg + exact hgeneric e f g ⟨h₀.1,h₁.1,h₂.1,h₀.2,h₁.2,h₂.2⟩ + (axisConcurrency_zero_of_meeting _ _ _ _ _ _ x + (axisContinuousDrawing_line_equation a b hai hbi ha hb e x he) + (axisContinuousDrawing_line_equation a b hai hbi ha hb f x hf) + (axisContinuousDrawing_line_equation a b hai hbi ha hb g x hg)) + +theorem axisAdmissibleDrawing_noAdjacent (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) + (hgeneric : ∀ e f g : BipartiteEdge m n, AxisIndependentTriple e f g → + axisConcurrency (a e.1) (b e.2) (a f.1) (b f.2) (a g.1) (b g.2) ≠ 0) : + NoAdjacentCrossings (axisAdmissibleDrawing a b hai hbi ha hb hgeneric) := by + intro e f hef hadj + apply Set.eq_empty_iff_forall_notMem.mpr + rintro x ⟨hx,hy⟩ + have hh := axisContinuousDrawing_meeting_independent a b hai hbi ha hb e f hef x hx hy + exact hadj.elim hh.1 hh.2 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisConcurrency.lean b/lean/OAI/Combinatorics/Crossing/AxisConcurrency.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c20538c7a839c4228d1ef22393b45771e5dae7e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisConcurrency.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.AxisSegments +import OAI.Combinatorics.Crossing.GenericPolynomialBox + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open MvPolynomial +variable {m n : ℕ} + +def axisConcurrency (a b c d e f : ℝ) : ℝ := + a*d*e*f+b*c*d*e+a*b*c*f-a*b*d*e-b*c*e*f-a*c*d*f + +theorem axisSegmentPoint_line_equation (a b t : ℝ) : + a*(axisSegmentPoint a b t).1+b*(axisSegmentPoint a b t).2=a*b := by + rw [axisSegmentPoint_coordinates] + ring + +theorem axisConcurrency_zero_of_meeting (a b c d e f : ℝ) (z : Plane) + (h₀ : a*z.1+b*z.2=a*b) (h₁ : c*z.1+d*z.2=c*d) (h₂ : e*z.1+f*z.2=e*f) : + axisConcurrency a b c d e f=0 := by + unfold axisConcurrency + linear_combination -(c*f-d*e)*h₀-(b*e-a*f)*h₁-(a*d-b*c)*h₂ + +def axisConcurrencyPolynomial (e f g : BipartiteEdge m n) : MvPolynomial (BipartiteVertex m n) ℝ := + let a := X (Sum.inl e.1); let b := X (Sum.inr e.2) + let c := X (Sum.inl f.1); let d := X (Sum.inr f.2) + let u := X (Sum.inl g.1); let v := X (Sum.inr g.2) + a*d*u*v+b*c*d*u+a*b*c*v-a*b*d*u-b*c*u*v-a*c*d*v + +theorem axisConcurrencyPolynomial_eval (e f g : BipartiteEdge m n) (x : BipartiteVertex m n → ℝ) : + eval x (axisConcurrencyPolynomial e f g)= + axisConcurrency (x (Sum.inl e.1)) (x (Sum.inr e.2)) (x (Sum.inl f.1)) (x (Sum.inr f.2)) + (x (Sum.inl g.1)) (x (Sum.inr g.2)) := by + simp [axisConcurrencyPolynomial,axisConcurrency] + +theorem axisConcurrencyPolynomial_ne_zero (e f g : BipartiteEdge m n) + (hef : e.1 ≠ f.1) (hgf : g.1 ≠ f.1) (hfe : f.2 ≠ e.2) (hge : g.2 ≠ e.2) : + axisConcurrencyPolynomial e f g ≠ 0 := by + let x : BipartiteVertex m n → ℝ + | .inl i => if i=f.1 then 0 else 1 + | .inr p => if p=e.2 then 0 else 1 + intro h + have hh := congrArg (eval x) h + rw [axisConcurrencyPolynomial_eval] at hh + norm_num [x,axisConcurrency,hef,hgf,hfe,hge] at hh + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisContinuousDrawing.lean b/lean/OAI/Combinatorics/Crossing/AxisContinuousDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f4b5f454afc656f07dacc5637915a7da85d3cf7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisContinuousDrawing.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.AxisSegments +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def axisVertex (a : Fin m → ℝ) (b : Fin n → ℝ) : BipartiteVertex m n → Plane + | .inl i => (0,a i) + | .inr p => (b p,0) + +theorem axisVertex_injective (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) (ha : ∀ i, a i ≠ 0) : + Function.Injective (axisVertex a b) := by + rintro (i|p) (k|q) he + · exact congrArg Sum.inl (hai (congrArg Prod.snd he)) + · exact False.elim (ha i (congrArg Prod.snd he)) + · exact False.elim (ha k (congrArg Prod.snd he).symm) + · exact congrArg Sum.inr (hbi (congrArg Prod.fst he)) + +def axisContinuousDrawing (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) : ContinuousDrawing m n where + vertex := axisVertex a b + vertex_injective := axisVertex_injective a b hai hbi ha + edge e := Path.segment (0,a e.1) (b e.2,0) + edge_injective := by + intro e t u he + apply Subtype.ext + apply axisSegmentPoint_injective (a e.1) (b e.2) (hb e.2) + change AffineMap.lineMap (0,a e.1) (b e.2,0) t.val = AffineMap.lineMap (0,a e.1) (b e.2,0) u.val at he + simpa only [AffineMap.lineMap_apply_module,axisSegmentPoint,segmentPoint] using he + interior_avoids_vertices := by + intro e t ht j he + have hh := axisSegmentPoint_interior_off_axes (a e.1) (b e.2) t.val (ha e.1) (hb e.2) ⟨ht.1,ht.2⟩ + have hv : axisSegmentPoint (a e.1) (b e.2) t.val=axisVertex a b j := by + change AffineMap.lineMap (0,a e.1) (b e.2,0) t.val = axisVertex a b j at he + simpa only [AffineMap.lineMap_apply_module,axisSegmentPoint,segmentPoint] using he + rcases j with i | p + · exact hh.1 (congrArg Prod.fst hv) + · exact hh.2 (congrArg Prod.snd hv) + +theorem axisContinuousDrawing_interior (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) (e : BipartiteEdge m n) : + edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e=openSegmentTrace (0,a e.1) (b e.2,0) := by + ext x + constructor + · rintro ⟨t,ht,he⟩ + refine ⟨t.val,⟨ht.1,ht.2⟩,?_⟩ + change AffineMap.lineMap (0,a e.1) (b e.2,0) t.val = x at he + simpa only [AffineMap.lineMap_apply_module,segmentPoint] using he + · rintro ⟨t,ht,he⟩ + refine ⟨⟨t,⟨ht.1.le,ht.2.le⟩⟩,⟨ht.1,ht.2⟩,?_⟩ + change AffineMap.lineMap (0,a e.1) (b e.2,0) t = x + simpa only [AffineMap.lineMap_apply_module,segmentPoint] using he + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisCrossingOrder.lean b/lean/OAI/Combinatorics/Crossing/AxisCrossingOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..47ce148dca663629c05a8db6d8fe0a204f52f63f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisCrossingOrder.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.Crossing.BalancedAxisDrawing +import OAI.Combinatorics.Crossing.BalancedRayPairs + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem positive_scaled_eq_sign (a b t u : ℝ) (ht : 0 < t) (hu : 0 < u) (he : t*a=u*b) : + (0 < a ↔ 0 < b) := by + have hh : (0 < t*a ↔ 0 < a) := mul_pos_iff_of_pos_left ht + have hh' : (0 < u*b ↔ 0 < b) := mul_pos_iff_of_pos_left hu + rw [he] at hh + exact hh.symm.trans hh' + +theorem axis_meeting_abs_order (a b c d t u : ℝ) + (ha : 0 < |a|) (hd : 0 < |d|) (hac : |a| < |c|) + (ht : t ∈ Set.Ioo (0 : ℝ) 1) (hu : u ∈ Set.Ioo (0 : ℝ) 1) + (he : axisSegmentPoint a b t=axisSegmentPoint c d u) : |d| < |b| := by + have hx := congrArg (fun z : Plane => |z.1|) he + have hy := congrArg (fun z : Plane => |z.2|) he + simp only [axisSegmentPoint_coordinates,abs_mul,abs_of_pos ht.1,abs_of_pos hu.1, + abs_of_pos (sub_pos.mpr ht.2),abs_of_pos (sub_pos.mpr hu.2)] at hx hy + have htu : t < u := by + by_contra hnot + have hgap := mul_pos (sub_pos.mpr hac) (sub_pos.mpr hu.2) + have hdiff := mul_nonneg (sub_nonneg.mpr (le_of_not_gt hnot)) ha.le + nlinarith + have hgap := mul_pos (sub_pos.mpr htu) hd + have htb : t*(|b|-|d|) > 0 := by nlinarith [hx] + exact sub_pos.mp ((mul_pos_iff_of_pos_left ht.1).mp htb) + +namespace BalancedAxisRealization +variable {m n : ℕ} (R : BalancedAxisRealization m n) + +theorem meeting_same_rays (i k : Fin m) (p q : Fin n) (x : Plane) + (hx : x ∈ edgeInterior R.drawing.toContinuousDrawing (i,p)) + (hy : x ∈ edgeInterior R.drawing.toContinuousDrawing (k,q)) : + (i.val < m/2 ↔ k.val < m/2) ∧ (p.val < n/2 ↔ q.val < n/2) := by + rw [R.drawing_edgeInterior] at hx hy + obtain ⟨t,ht,he⟩ := hx + obtain ⟨u,hu,hf⟩ := hy + have hmeet : axisSegmentPoint (R.vertical i) (R.horizontal p) t= + axisSegmentPoint (R.vertical k) (R.horizontal q) u := he.trans hf.symm + have hcoordx := congrArg Prod.fst hmeet + have hcoordy := congrArg Prod.snd hmeet + simp only [axisSegmentPoint_coordinates] at hcoordx hcoordy + have hposx := positive_scaled_eq_sign _ _ _ _ ht.1 hu.1 hcoordx + have hposy := positive_scaled_eq_sign _ _ _ _ (sub_pos.mpr ht.2) (sub_pos.mpr hu.2) hcoordy + exact ⟨(axisInterval_sign m i _ (R.vertical_interval i)).1.symm.trans + (hposy.trans (axisInterval_sign m k _ (R.vertical_interval k)).1), + (axisInterval_sign n p _ (R.horizontal_interval p)).1.symm.trans + (hposx.trans (axisInterval_sign n q _ (R.horizontal_interval q)).1)⟩ + +theorem meeting_reverse_horizontal_order (i k : Fin m) (p q : Fin n) (hik : i < k) (x : Plane) + (hx : x ∈ edgeInterior R.drawing.toContinuousDrawing (i,p)) + (hy : x ∈ edgeInterior R.drawing.toContinuousDrawing (k,q)) : q < p := by + rw [R.drawing_edgeInterior] at hx hy + obtain ⟨t,ht,he⟩ := hx + obtain ⟨u,hu,hf⟩ := hy + have hmeet : axisSegmentPoint (R.vertical i) (R.horizontal p) t= + axisSegmentPoint (R.vertical k) (R.horizontal q) u := he.trans hf.symm + have hh := axis_meeting_abs_order _ _ _ _ t u (abs_pos.mpr (R.vertical_ne_zero i)) + (abs_pos.mpr (R.horizontal_ne_zero q)) (R.vertical_abs_strictMono hik) ht hu hmeet + by_contra hnot + have hle := R.horizontal_abs_strictMono.monotone (le_of_not_gt hnot) + exact not_lt_of_ge hle hh + +theorem meeting_balanced_pairs (i k : Fin m) (p q : Fin n) (hik : i < k) (x : Plane) + (hx : x ∈ edgeInterior R.drawing.toContinuousDrawing (i,p)) + (hy : x ∈ edgeInterior R.drawing.toContinuousDrawing (k,q)) : + (i,k) ∈ balancedRayPairs m ∧ (q,p) ∈ balancedRayPairs n := by + obtain ⟨hvert,hhor⟩ := R.meeting_same_rays i k p q x hx hy + exact ⟨(mem_balancedRayPairs m i k).mpr ⟨hik,hvert⟩, + (mem_balancedRayPairs n q p).mpr ⟨R.meeting_reverse_horizontal_order i k p q hik x hx hy,hhor.symm⟩⟩ + +end BalancedAxisRealization +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisFiniteCrossings.lean b/lean/OAI/Combinatorics/Crossing/AxisFiniteCrossings.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc448c234df183e5165371c45477637ed04244ab --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisFiniteCrossings.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.AxisContinuousDrawing +import Mathlib.Data.Set.Finite.Lattice + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem axis_open_intersection_subsingleton (a b c d : ℝ) (ha : a ≠ 0) (hb : b ≠ 0) + (hne : (a,b) ≠ (c,d)) : + (openSegmentTrace (0,a) (b,0) ∩ openSegmentTrace (0,c) (d,0)).Subsingleton := by + rintro x ⟨⟨t,ht,he⟩,⟨u,hu,hf⟩⟩ y ⟨⟨t',ht',he'⟩,⟨u',hu',hf'⟩⟩ + have hmeet : axisSegmentPoint a b t=axisSegmentPoint c d u := he.trans hf.symm + have hdet := axisSegmentPoint_meeting_det a b c d t u ha hb hne hmeet + have hh := segment_intersection_parameters_unique (0,a) (b,0) (0,c) (d,0) hdet t u t' u' + (he.trans hf.symm) (he'.trans hf'.symm) + exact he.symm.trans ((congrArg (segmentPoint (0,a) (b,0)) hh.1).trans he') + +theorem axis_intercept_pair_ne (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) (e f : BipartiteEdge m n) (hef : e ≠ f) : + (a e.1,b e.2) ≠ (a f.1,b f.2) := by + intro he + exact hef (Prod.ext (hai (congrArg Prod.fst he)) (hbi (congrArg Prod.snd he))) + +theorem axisContinuousDrawing_pair_subsingleton (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) (e f : BipartiteEdge m n) (hef : e ≠ f) : + (edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e ∩ + edgeInterior (axisContinuousDrawing a b hai hbi ha hb) f).Subsingleton := by + rw [axisContinuousDrawing_interior,axisContinuousDrawing_interior] + exact axis_open_intersection_subsingleton _ _ _ _ (ha e.1) (hb e.2) (axis_intercept_pair_ne a b hai hbi e f hef) + +theorem axisContinuousDrawing_crossings_finite (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) : + (crossingPoints (axisContinuousDrawing a b hai hbi ha hb)).Finite := by + classical + let D := axisContinuousDrawing a b hai hbi ha hb + let S := fun e f : BipartiteEdge m n => if e=f then (∅ : Set Plane) else edgeInterior D e ∩ edgeInterior D f + have hfinite (e f : BipartiteEdge m n) : (S e f).Finite := by + dsimp only [S] + split_ifs with hef + · exact Set.finite_empty + · exact (axisContinuousDrawing_pair_subsingleton a b hai hbi ha hb e f hef).finite + apply (Set.finite_iUnion fun e => Set.finite_iUnion (hfinite e)).subset + rintro x ⟨e,f,hef,hxe,hxf⟩ + refine Set.mem_iUnion.mpr ⟨e,Set.mem_iUnion.mpr ⟨f,?_⟩⟩ + simpa only [S,ite_eq_right hef] using (show x ∈ edgeInterior D e ∩ edgeInterior D f from ⟨hxe,hxf⟩) + +theorem axisContinuousDrawing_crossings_proper (a : Fin m → ℝ) (b : Fin n → ℝ) + (hai : Function.Injective a) (hbi : Function.Injective b) + (ha : ∀ i, a i ≠ 0) (hb : ∀ p, b p ≠ 0) (e f : BipartiteEdge m n) (hef : e ≠ f) + (x : Plane) (hx : x ∈ edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e) + (hy : x ∈ edgeInterior (axisContinuousDrawing a b hai hbi ha hb) f) : + ProperCrossing (edgeInterior (axisContinuousDrawing a b hai hbi ha hb) e) + (edgeInterior (axisContinuousDrawing a b hai hbi ha hb) f) x := by + rw [axisContinuousDrawing_interior] at hx hy ⊢ + rw [axisContinuousDrawing_interior] + exact axisSegmentPoint_meeting_proper _ _ _ _ (ha e.1) (hb e.2) + (axis_intercept_pair_ne a b hai hbi e f hef) x hx hy + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisGenericPositions.lean b/lean/OAI/Combinatorics/Crossing/AxisGenericPositions.lean new file mode 100644 index 0000000000000000000000000000000000000000..40358bcbdc44b5302300ee635637d24fdf1ac965 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisGenericPositions.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.Crossing.AxisConcurrency + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def AxisIndependentTriple (e f g : BipartiteEdge m n) : Prop := + e.1 ≠ f.1 ∧ e.1 ≠ g.1 ∧ f.1 ≠ g.1 ∧ e.2 ≠ f.2 ∧ e.2 ≠ g.2 ∧ f.2 ≠ g.2 + +theorem exists_axis_generic_positions (lo hi : BipartiteVertex m n → ℝ) + (hinterval : ∀ j, lo j < hi j) : + ∃ x : BipartiteVertex m n → ℝ, (∀ j, x j ∈ Set.Ioo (lo j) (hi j)) ∧ + ∀ e f g : BipartiteEdge m n, AxisIndependentTriple e f g → + axisConcurrency (x (Sum.inl e.1)) (x (Sum.inr e.2)) (x (Sum.inl f.1)) (x (Sum.inr f.2)) + (x (Sum.inl g.1)) (x (Sum.inr g.2)) ≠ 0 := by + classical + let P : (BipartiteEdge m n × BipartiteEdge m n × BipartiteEdge m n) → MvPolynomial (BipartiteVertex m n) ℝ := + fun t => if AxisIndependentTriple t.1 t.2.1 t.2.2 then axisConcurrencyPolynomial t.1 t.2.1 t.2.2 else 1 + have hP : ∀ t, P t ≠ 0 := by + intro t + dsimp only [P] + split_ifs with h + · exact axisConcurrencyPolynomial_ne_zero _ _ _ h.1 (Ne.symm h.2.2.1) + (Ne.symm h.2.2.2.1) (Ne.symm h.2.2.2.2.1) + · exact one_ne_zero + obtain ⟨x,hx,havoid⟩ := exists_box_avoiding_polynomials P hP lo hi hinterval + refine ⟨x,hx,?_⟩ + intro e f g htriple + have hh := havoid (e,f,g) + simpa only [P,ite_eq_left htriple,axisConcurrencyPolynomial_eval] using hh + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/AxisSegments.lean b/lean/OAI/Combinatorics/Crossing/AxisSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf562850696cf14402e04624402e283904cfe33f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/AxisSegments.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.ProperSegmentCrossing + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def axisSegmentPoint (a b t : ℝ) : Plane := segmentPoint (0,a) (b,0) t + +theorem axisSegmentPoint_coordinates (a b t : ℝ) : axisSegmentPoint a b t=(t*b,(1-t)*a) := by + ext <;> simp [axisSegmentPoint,segmentPoint] + +theorem axisSegmentPoint_injective (a b : ℝ) (hb : b ≠ 0) : Function.Injective (axisSegmentPoint a b) := by + intro t u htu + have hx := congrArg Prod.fst htu + simp only [axisSegmentPoint_coordinates] at hx + exact mul_right_cancel₀ hb hx + +theorem axisSegmentPoint_interior_off_axes (a b t : ℝ) (ha : a ≠ 0) (hb : b ≠ 0) + (ht : t ∈ Set.Ioo (0 : ℝ) 1) : + (axisSegmentPoint a b t).1 ≠ 0 ∧ (axisSegmentPoint a b t).2 ≠ 0 := by + rw [axisSegmentPoint_coordinates] + exact ⟨mul_ne_zero (ne_of_gt ht.1) hb,mul_ne_zero (ne_of_gt (sub_pos.mpr ht.2)) ha⟩ + +theorem axisSegmentPoint_same_vertical (a b d t u : ℝ) (ha : a ≠ 0) + (ht : 0 < t) (h : axisSegmentPoint a b t=axisSegmentPoint a d u) : b=d := by + have hx := congrArg Prod.fst h + have hy := congrArg Prod.snd h + simp only [axisSegmentPoint_coordinates] at hx hy + have htu : t=u := by have hh := mul_right_cancel₀ ha hy; linarith + rw [← htu] at hx + exact mul_left_cancel₀ (ne_of_gt ht) hx + +theorem axisSegmentPoint_same_horizontal (a c b t u : ℝ) (hb : b ≠ 0) + (ht : t < 1) (h : axisSegmentPoint a b t=axisSegmentPoint c b u) : a=c := by + have hx := congrArg Prod.fst h + have hy := congrArg Prod.snd h + simp only [axisSegmentPoint_coordinates] at hx hy + have htu : t=u := mul_right_cancel₀ hb hx + rw [← htu] at hy + exact mul_left_cancel₀ (ne_of_gt (sub_pos.mpr ht)) hy + +theorem axisSegmentPoint_meeting_det (a b c d t u : ℝ) (ha : a ≠ 0) (hb : b ≠ 0) + (hne : (a,b) ≠ (c,d)) (h : axisSegmentPoint a b t=axisSegmentPoint c d u) : + det2 ((b,0)-(0,a)) ((d,0)-(0,c)) ≠ 0 := by + intro hz + have hx := congrArg Prod.fst h + have hy := congrArg Prod.snd h + simp only [axisSegmentPoint_coordinates] at hx hy + have hz' : a*d-b*c=0 := by + dsimp [det2] at hz + nlinarith [hz] + have hac : (a-c)*b=0 := by linear_combination b*hy+a*hx+u*hz' + have he : a=c := sub_eq_zero.mp ((mul_eq_zero.mp hac).resolve_right hb) + have hbd : a*(d-b)=0 := by rw [← he] at hz'; nlinarith [hz'] + have he' : b=d := (sub_eq_zero.mp ((mul_eq_zero.mp hbd).resolve_left ha)).symm + exact hne (Prod.ext he he') + +theorem axisSegmentPoint_meeting_proper (a b c d : ℝ) (ha : a ≠ 0) (hb : b ≠ 0) + (hne : (a,b) ≠ (c,d)) (x : Plane) + (hx : x ∈ openSegmentTrace (0,a) (b,0)) (hy : x ∈ openSegmentTrace (0,c) (d,0)) : + ProperCrossing (openSegmentTrace (0,a) (b,0)) (openSegmentTrace (0,c) (d,0)) x := by + obtain ⟨t,ht,he⟩ := hx + obtain ⟨u,hu,hf⟩ := hy + have hmeet : axisSegmentPoint a b t=axisSegmentPoint c d u := he.trans hf.symm + exact properCrossing_openSegments _ _ _ _ _ (axisSegmentPoint_meeting_det a b c d t u ha hb hne hmeet) + ⟨t,ht,he⟩ ⟨u,hu,hf⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BalancedAxisCrossingCount.lean b/lean/OAI/Combinatorics/Crossing/BalancedAxisCrossingCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..082697a2916a1b04e9b2b1a731f56a9d0a04c49e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BalancedAxisCrossingCount.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.Crossing.AxisCrossingOrder +import OAI.Combinatorics.Crossing.EvenCrossingLowerBound + +namespace OAI + +noncomputable section +namespace Zarankiewicz.BalancedAxisRealization +open scoped BigOperators Finset +variable {m n : ℕ} (R : BalancedAxisRealization m n) + +def crossingCandidates (_R : BalancedAxisRealization m n) : Finset ((Fin m × Fin m) × (Fin n × Fin n)) := + balancedRayPairs m ×ˢ balancedRayPairs n + +def candidateCrossings (v : (Fin m × Fin m) × (Fin n × Fin n)) : Finset Plane := + pairCrossings R.drawing (v.1.1,v.2.2) (v.1.2,v.2.1) + +theorem pairCrossings_card_le_one (e f : BipartiteEdge m n) : (pairCrossings R.drawing e f).card ≤ 1 := by + classical + by_cases hef : e=f + · subst f + simp [pairCrossings_self] + · apply Finset.card_le_one.mpr + intro x hx y hy + have hsub := axisContinuousDrawing_pair_subsingleton R.vertical R.horizontal R.vertical_injective + R.horizontal_injective R.vertical_ne_zero R.horizontal_ne_zero e f hef + exact hsub (Finset.mem_filter.mp hx).2.2 (Finset.mem_filter.mp hy).2.2 + +theorem crossings_covered_by_candidates : + R.drawing.crossings_finite.toFinset ⊆ R.crossingCandidates.biUnion R.candidateCrossings := by + classical + intro x hx + have hcross : x ∈ crossingPoints R.drawing.toContinuousDrawing := by simpa using hx + obtain ⟨e,f,hef,he,hf⟩ := hcross + have hind := axisContinuousDrawing_meeting_independent R.vertical R.horizontal R.vertical_injective + R.horizontal_injective R.vertical_ne_zero R.horizontal_ne_zero e f hef x he hf + rcases lt_or_gt_of_ne hind.1 with hlt | hgt + · have hc := R.meeting_balanced_pairs e.1 f.1 e.2 f.2 hlt x he hf + apply Finset.mem_biUnion.mpr + refine ⟨((e.1,f.1),(f.2,e.2)),Finset.mem_product.mpr hc,?_⟩ + apply Finset.mem_filter.mpr + exact ⟨hx,hef,he,hf⟩ + · have hc := R.meeting_balanced_pairs f.1 e.1 f.2 e.2 hgt x hf he + apply Finset.mem_biUnion.mpr + refine ⟨((f.1,e.1),(e.2,f.2)),Finset.mem_product.mpr hc,?_⟩ + apply Finset.mem_filter.mpr + exact ⟨hx,Ne.symm hef,hf,he⟩ + +theorem crossingCount_le : crossingCount R.drawing ≤ axisPairs m*axisPairs n := by + classical + calc + crossingCount R.drawing ≤ (R.crossingCandidates.biUnion R.candidateCrossings).card := + Finset.card_le_card R.crossings_covered_by_candidates + _ ≤ ∑ v ∈ R.crossingCandidates, (R.candidateCrossings v).card := Finset.card_biUnion_le + _ ≤ ∑ _v ∈ R.crossingCandidates, 1 := by + apply Finset.sum_le_sum + intro v hv + exact R.pairCrossings_card_le_one _ _ + _ = R.crossingCandidates.card := by simp + _ = axisPairs m*axisPairs n := by + rw [crossingCandidates,Finset.card_product,balancedRayPairs_card,balancedRayPairs_card] + +theorem crossingCount_eq : crossingCount R.drawing=axisPairs m*axisPairs n := + Nat.le_antisymm R.crossingCount_le (crossing_lower_bound m n R.drawing) + +end Zarankiewicz.BalancedAxisRealization + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BalancedAxisDrawing.lean b/lean/OAI/Combinatorics/Crossing/BalancedAxisDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..2aa578db44ffd781544909148b466d8f501c6cd2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BalancedAxisDrawing.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.Crossing.AxisAdmissibility +import OAI.Combinatorics.Crossing.BalancedAxisIntervals + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +structure BalancedAxisRealization (m n : ℕ) where + vertical : Fin m → ℝ + horizontal : Fin n → ℝ + vertical_interval : ∀ i, vertical i ∈ Set.Ioo (axisIntervalLo m i) (axisIntervalHi m i) + horizontal_interval : ∀ p, horizontal p ∈ Set.Ioo (axisIntervalLo n p) (axisIntervalHi n p) + generic : ∀ e f g : BipartiteEdge m n, AxisIndependentTriple e f g → + axisConcurrency (vertical e.1) (horizontal e.2) (vertical f.1) (horizontal f.2) + (vertical g.1) (horizontal g.2) ≠ 0 + +theorem nonempty_balancedAxisRealization (m n : ℕ) : Nonempty (BalancedAxisRealization m n) := by + let lo : BipartiteVertex m n → ℝ + | .inl i => axisIntervalLo m i + | .inr p => axisIntervalLo n p + let hi : BipartiteVertex m n → ℝ + | .inl i => axisIntervalHi m i + | .inr p => axisIntervalHi n p + have hinterval : ∀ j, lo j < hi j := by + rintro (i|p) + · exact axisInterval_nonempty m i + · exact axisInterval_nonempty n p + obtain ⟨x,hx,hgeneric⟩ := exists_axis_generic_positions lo hi hinterval + exact ⟨⟨fun i => x (Sum.inl i),fun p => x (Sum.inr p),fun i => hx (Sum.inl i), + fun p => hx (Sum.inr p),hgeneric⟩⟩ + +namespace BalancedAxisRealization +variable {m n : ℕ} (R : BalancedAxisRealization m n) + +theorem vertical_injective : Function.Injective R.vertical := axisInterval_injective m _ R.vertical_interval +theorem horizontal_injective : Function.Injective R.horizontal := axisInterval_injective n _ R.horizontal_interval +theorem vertical_ne_zero (i : Fin m) : R.vertical i ≠ 0 := axisInterval_ne_zero m i _ (R.vertical_interval i) +theorem horizontal_ne_zero (p : Fin n) : R.horizontal p ≠ 0 := axisInterval_ne_zero n p _ (R.horizontal_interval p) +theorem vertical_abs_strictMono : StrictMono (fun i => |R.vertical i|) := axisInterval_abs_strictMono m _ R.vertical_interval +theorem horizontal_abs_strictMono : StrictMono (fun p => |R.horizontal p|) := axisInterval_abs_strictMono n _ R.horizontal_interval + +def drawing : AdmissibleDrawing m n := + axisAdmissibleDrawing R.vertical R.horizontal R.vertical_injective R.horizontal_injective + R.vertical_ne_zero R.horizontal_ne_zero R.generic + +theorem drawing_noAdjacent : NoAdjacentCrossings R.drawing := + axisAdmissibleDrawing_noAdjacent _ _ _ _ _ _ _ + +theorem drawing_vertex_left (i : Fin m) : R.drawing.vertex (Sum.inl i)=(0,R.vertical i) := rfl +theorem drawing_vertex_right (p : Fin n) : R.drawing.vertex (Sum.inr p)=(R.horizontal p,0) := rfl +theorem drawing_edge (e : BipartiteEdge m n) : + R.drawing.edge e=Path.segment (0,R.vertical e.1) (R.horizontal e.2,0) := rfl + +theorem drawing_edgeInterior (e : BipartiteEdge m n) : + edgeInterior R.drawing.toContinuousDrawing e=openSegmentTrace (0,R.vertical e.1) (R.horizontal e.2,0) := + axisContinuousDrawing_interior R.vertical R.horizontal R.vertical_injective R.horizontal_injective + R.vertical_ne_zero R.horizontal_ne_zero e + +end BalancedAxisRealization + +theorem exists_axis_admissible (m n : ℕ) : Nonempty (AdmissibleDrawing m n) := by + obtain ⟨R⟩ := nonempty_balancedAxisRealization m n + exact ⟨R.drawing⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BalancedAxisIntervals.lean b/lean/OAI/Combinatorics/Crossing/BalancedAxisIntervals.lean new file mode 100644 index 0000000000000000000000000000000000000000..670786928b8f788dcefbce023e362292c714fed2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BalancedAxisIntervals.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.AxisGenericPositions + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def axisIntervalLo (r : ℕ) (i : Fin r) : ℝ := if i.val < r/2 then 2*(i.val : ℝ)+1 else -(2*(i.val : ℝ)+2) +def axisIntervalHi (r : ℕ) (i : Fin r) : ℝ := if i.val < r/2 then 2*(i.val : ℝ)+2 else -(2*(i.val : ℝ)+1) + +theorem axisInterval_nonempty (r : ℕ) (i : Fin r) : axisIntervalLo r i < axisIntervalHi r i := by + unfold axisIntervalLo axisIntervalHi + split_ifs <;> linarith + +theorem axisInterval_abs_bounds (r : ℕ) (i : Fin r) (x : ℝ) + (hx : x ∈ Set.Ioo (axisIntervalLo r i) (axisIntervalHi r i)) : + 2*(i.val : ℝ)+1 < |x| ∧ |x| < 2*(i.val : ℝ)+2 := by + have hi : 0 ≤ (i.val : ℝ) := Nat.cast_nonneg _ + by_cases h : i.val < r/2 + · simp only [axisIntervalLo,axisIntervalHi,ite_eq_left h,Set.mem_Ioo] at hx + rw [abs_of_pos (by linarith [hx.1])] + exact hx + · simp only [axisIntervalLo,axisIntervalHi,ite_eq_right h,Set.mem_Ioo] at hx + rw [abs_of_neg (by linarith [hx.2])] + constructor <;> linarith [hx.1,hx.2] + +theorem axisInterval_sign (r : ℕ) (i : Fin r) (x : ℝ) + (hx : x ∈ Set.Ioo (axisIntervalLo r i) (axisIntervalHi r i)) : + (0 < x ↔ i.val < r/2) ∧ (x < 0 ↔ r/2 ≤ i.val) := by + have hi : 0 ≤ (i.val : ℝ) := Nat.cast_nonneg _ + by_cases h : i.val < r/2 + · simp only [axisIntervalLo,axisIntervalHi,ite_eq_left h,Set.mem_Ioo] at hx + have hp : 0 < x := by linarith [hx.1] + simp [hp,h,not_lt_of_ge hp.le,Nat.not_le.mpr h] + · simp only [axisIntervalLo,axisIntervalHi,ite_eq_right h,Set.mem_Ioo] at hx + have hn : x < 0 := by linarith [hx.2] + simp [hn,h,not_lt_of_ge hn.le,Nat.le_of_not_gt h] + +theorem axisInterval_ne_zero (r : ℕ) (i : Fin r) (x : ℝ) + (hx : x ∈ Set.Ioo (axisIntervalLo r i) (axisIntervalHi r i)) : x ≠ 0 := by + have hh := (axisInterval_abs_bounds r i x hx).1 + intro he + rw [he,abs_zero] at hh + have hi : 0 ≤ (i.val : ℝ) := Nat.cast_nonneg _ + linarith + +theorem axisInterval_abs_strictMono (r : ℕ) (x : Fin r → ℝ) + (hx : ∀ i, x i ∈ Set.Ioo (axisIntervalLo r i) (axisIntervalHi r i)) : + StrictMono (fun i => |x i|) := by + intro i k hik + have hi := (axisInterval_abs_bounds r i (x i) (hx i)).2 + have hk := (axisInterval_abs_bounds r k (x k) (hx k)).1 + have hik' : (i.val : ℝ)+1 ≤ (k.val : ℝ) := by exact_mod_cast (Nat.succ_le_of_lt hik) + linarith + +theorem axisInterval_injective (r : ℕ) (x : Fin r → ℝ) + (hx : ∀ i, x i ∈ Set.Ioo (axisIntervalLo r i) (axisIntervalHi r i)) : Function.Injective x := by + intro i k hik + exact (axisInterval_abs_strictMono r x hx).injective (congrArg abs hik) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BalancedRayPairs.lean b/lean/OAI/Combinatorics/Crossing/BalancedRayPairs.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b3af68225840d43f34bba70c5b3334a3fe22ccb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BalancedRayPairs.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.Crossing.FloorArithmetic +import Mathlib.Data.Finset.Prod +import Mathlib.Order.Interval.Finset.Fin + +namespace OAI + +namespace Zarankiewicz +open scoped Finset + +def positiveRayIndices (r : ℕ) : Finset (Fin r) := Finset.univ.filter (fun i => i.val < r/2) +def negativeRayIndices (r : ℕ) : Finset (Fin r) := Finset.univ.filter (fun i => ¬ i.val < r/2) + +def balancedRayPairs (r : ℕ) : Finset (Fin r × Fin r) := + ((positiveRayIndices r ×ˢ positiveRayIndices r).filter (fun p => p.1 < p.2)) ∪ + ((negativeRayIndices r ×ˢ negativeRayIndices r).filter (fun p => p.1 < p.2)) + +theorem mem_balancedRayPairs (r : ℕ) (i k : Fin r) : + (i,k) ∈ balancedRayPairs r ↔ i < k ∧ (i.val < r/2 ↔ k.val < r/2) := by + simp only [balancedRayPairs,positiveRayIndices,negativeRayIndices,Finset.mem_union, + Finset.mem_filter,Finset.mem_product,Finset.mem_univ,true_and] + tauto + +theorem positiveRayIndices_card (r : ℕ) : (positiveRayIndices r).card=r/2 := by + cases r with + | zero => simp [positiveRayIndices] + | succ r => + let c : Fin (r+1) := ⟨(r+1)/2,by omega⟩ + have he : positiveRayIndices (r+1)=Finset.Iio c := by + ext i + simp only [positiveRayIndices,Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_Iio] + rfl + rw [he,Fin.card_Iio] + +theorem negativeRayIndices_card (r : ℕ) : (negativeRayIndices r).card=r-r/2 := by + have hh := Finset.card_filter_add_card_filter_not (s := Finset.univ) (fun i : Fin r => i.val < r/2) + change (positiveRayIndices r).card+(negativeRayIndices r).card=Finset.univ.card at hh + rw [positiveRayIndices_card,Finset.card_univ,Fintype.card_fin] at hh + omega + +theorem twice_choose_two (s : ℕ) : 2*s.choose 2=s*(s-1) := by + induction s with + | zero => simp + | succ s ih => + rw [Nat.choose_succ_succ,Nat.choose_one_right,Nat.add_sub_cancel] + have hh : s*(s-1)+2*s=(s+1)*s := by + cases s with + | zero => simp + | succ s => simp only [Nat.add_sub_cancel]; ring + nlinarith + +theorem balanced_choose_two (r : ℕ) : (r/2).choose 2+(r-r/2).choose 2=axisPairs r := by + have hr : r=2*(r/2) ∨ r=2*(r/2)+1 := by omega + rcases hr with hr | hr + · generalize r/2=s at hr + subst r + rw [show 2*s-s=s by omega,axisPairs_even] + have hh := twice_choose_two s + omega + · generalize r/2=s at hr + subst r + rw [show 2*s+1-s=s+1 by omega,axisPairs_odd, + Nat.choose_succ_succ,Nat.choose_one_right] + have hh := twice_choose_two s + cases s with + | zero => simp + | succ s => simp only [Nat.add_sub_cancel] at hh; nlinarith + +theorem balancedRayPairs_card (r : ℕ) : (balancedRayPairs r).card=axisPairs r := by + have hd : Disjoint + ((positiveRayIndices r ×ˢ positiveRayIndices r).filter (fun p => p.1 < p.2)) + ((negativeRayIndices r ×ˢ negativeRayIndices r).filter (fun p => p.1 < p.2)) := by + apply Finset.disjoint_left.mpr + rintro ⟨i,k⟩ hp hn + simp only [Finset.mem_filter,Finset.mem_product,positiveRayIndices,negativeRayIndices, + Finset.mem_univ,true_and] at hp hn + exact hn.1.1 hp.1.1 + rw [balancedRayPairs,Finset.card_union_of_disjoint hd,Finset.card_product_filter_lt, + Finset.card_product_filter_lt,positiveRayIndices_card,negativeRayIndices_card,balanced_choose_two] + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BipartiteDartGeometry.lean b/lean/OAI/Combinatorics/Crossing/BipartiteDartGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..e78336d30bc3da79b148f09d36c68b97fe15daac --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BipartiteDartGeometry.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.FourCycles +import OAI.Combinatorics.Crossing.DrawnEdgeChains + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def forwardBipartiteDart (e : BipartiteEdge m n) : (completeBipartite m n).Dart := + ⟨(Sum.inl e.1,Sum.inr e.2),by simp [completeBipartite,completeBipartiteGraph]⟩ + +def backwardBipartiteDart (e : BipartiteEdge m n) : (completeBipartite m n).Dart := + (forwardBipartiteDart e).symm + +def bipartiteDartEdge (d : (completeBipartite m n).Dart) : BipartiteEdge m n := by + rcases d with ⟨⟨u,v⟩,h⟩ + rcases u with i | p <;> rcases v with k | q + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + · exact (i,q) + · exact (k,p) + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + +def bipartiteDartSign (d : (completeBipartite m n).Dart) : ℝ := + match d.fst with + | .inl _ => 1 + | .inr _ => -1 + +theorem bipartiteDart_cases (d : (completeBipartite m n).Dart) : + (∃ e, d=forwardBipartiteDart e) ∨ (∃ e, d=backwardBipartiteDart e) := by + rcases d with ⟨⟨u,v⟩,h⟩ + rcases u with i | p <;> rcases v with k | q + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + · exact Or.inl ⟨(i,q),rfl⟩ + · exact Or.inr ⟨(k,p),rfl⟩ + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + +theorem bipartiteDart_source_incident (d : (completeBipartite m n).Dart) : + d.fst=Sum.inl (bipartiteDartEdge d).1 ∨ d.fst=Sum.inr (bipartiteDartEdge d).2 := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact Or.inl rfl + · exact Or.inr rfl + +theorem bipartiteDart_target_incident (d : (completeBipartite m n).Dart) : + d.snd=Sum.inl (bipartiteDartEdge d).1 ∨ d.snd=Sum.inr (bipartiteDartEdge d).2 := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact Or.inr rfl + · exact Or.inl rfl + +def dartSourceIncident (d : (completeBipartite m n).Dart) : IncidentEdges d.fst := + ⟨bipartiteDartEdge d,bipartiteDart_source_incident d⟩ + +def dartTargetIncident (d : (completeBipartite m n).Dart) : IncidentEdges d.snd := + ⟨bipartiteDartEdge d,bipartiteDart_target_incident d⟩ + +theorem bipartiteDartEdge_symm (d : (completeBipartite m n).Dart) : + bipartiteDartEdge d.symm=bipartiteDartEdge d := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> rfl + +theorem bipartiteDartSign_symm (d : (completeBipartite m n).Dart) : + bipartiteDartSign d.symm= -bipartiteDartSign d := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · rfl + · norm_num [bipartiteDartSign,backwardBipartiteDart,forwardBipartiteDart,SimpleGraph.Dart.symm] + +theorem orientedEdgeStep_dart (d : (completeBipartite m n).Dart) : + orientedEdgeStep d.fst d.snd=bipartiteDartSign d • Pi.single (bipartiteDartEdge d) 1 := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> + simp [orientedEdgeStep,bipartiteDartSign,bipartiteDartEdge,forwardBipartiteDart, + backwardBipartiteDart,SimpleGraph.Dart.symm] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/Bivariate.lean b/lean/OAI/Combinatorics/Crossing/Bivariate.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f37bbc240206b798883de3d33696e367c3b91b7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/Bivariate.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.Crossing.Interpolation +import Mathlib.LinearAlgebra.Finsupp.Defs +import Mathlib.Tactic.Ring + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule + +abbrev BiPoly := PolynomialModule ℝ (PolynomialModule ℝ ℝ) + +def biCoeff (p : BiPoly) (a b : ℕ) : ℝ := (p.coeff a).coeff b + +def biEval (u v : ℝ) : BiPoly →ₗ[ℝ] ℝ := (eval v).comp (eval u) + +def BiBounded (r s : ℕ) (p : BiPoly) : Prop := + Bounded r p ∧ ∀ a, Bounded s (p.coeff a) + +def flattenBi : BiPoly ≃ₗ[ℝ] (ℕ × ℕ →₀ ℝ) := + ((coeffLinearEquiv ℝ ℝ).trans + (Finsupp.mapRange.linearEquiv (coeffLinearEquiv ℝ ℝ))).trans + (Finsupp.curryLinearEquiv ℝ).symm + +theorem flattenBi_apply (p : BiPoly) (a b : ℕ) : flattenBi p (a,b) = biCoeff p a b := rfl + +def swapBi : BiPoly ≃ₗ[ℝ] BiPoly := + (flattenBi.trans (Finsupp.mapDomain.linearEquiv ℝ ℝ (Equiv.prodComm ℕ ℕ))).trans + flattenBi.symm + +theorem biCoeff_swap (p : BiPoly) (a b : ℕ) : biCoeff (swapBi p) a b = biCoeff p b a := by + rw [← flattenBi_apply] + change flattenBi (flattenBi.symm _) (a,b) = _ + rw [LinearEquiv.apply_symm_apply] + exact Finsupp.mapDomain_equiv_apply (flattenBi p) (a,b) + +theorem bi_ext {p q : BiPoly} (h : ∀ a b, biCoeff p a b = biCoeff q a b) : p = q := by + apply PolynomialModule.ext + apply Finsupp.ext + intro a + apply PolynomialModule.ext + apply Finsupp.ext + exact h a + +theorem swapBi_swapBi (p : BiPoly) : swapBi (swapBi p) = p := by + apply bi_ext + intro a b + rw [biCoeff_swap, biCoeff_swap] + +theorem swapBi_single (a b : ℕ) (c : ℝ) : + swapBi (single ℝ a (single ℝ b c)) = single ℝ b (single ℝ a c) := by + apply bi_ext + intro i j + rw [biCoeff_swap] + simp [biCoeff, Finsupp.single_apply] + split_ifs <;> simp_all + +theorem biEval_swap (p : BiPoly) (u v : ℝ) : biEval u v (swapBi p) = biEval v u p := by + induction p using PolynomialModule.induction_linear with + | zero => simp + | add p q hp hq => simp only [map_add, hp, hq] + | single a q => + induction q using PolynomialModule.induction_linear with + | zero => simp + | add p q hp hq => simp only [single_add, map_add, hp, hq] + | single b c => + rw [swapBi_single] + simp [biEval, eval_single, smul_eq_mul] + ring + +theorem biBounded_swap {r s : ℕ} {p : BiPoly} (hp : BiBounded r s p) : + BiBounded s r (swapBi p) := by + constructor + · intro a ha + apply PolynomialModule.ext + apply Finsupp.ext + intro b + change biCoeff (swapBi p) a b = 0 + rw [biCoeff_swap] + exact hp.2 b a ha + · intro a b hb + change biCoeff (swapBi p) a b = 0 + rw [biCoeff_swap] + simp [biCoeff, hp.1 b hb] + +def boundedSpace (k : ℕ) : Submodule ℝ (PolynomialModule ℝ ℝ) where + carrier := {p | Bounded k p} + zero_mem' := bounded_zero k + add_mem' := bounded_add + smul_mem' := by + intro c p hp n hn + change c • p.coeff n = 0 + rw [hp n hn, smul_zero] + +theorem coefficients_of_mulRoot {W : Type*} [AddCommGroup W] [Module ℝ W] + (Z : Submodule ℝ W) (t : ℝ) (k : ℕ) (q : PolynomialModule ℝ W) + (hq : Bounded k q) (hc : ∀ n, (mulRoot t q).coeff n ∈ Z) : + ∀ n, q.coeff n ∈ Z := by + have aux : ∀ d n, k-n = d → q.coeff n ∈ Z := by + intro d + induction d with + | zero => + intro n hn + rw [hq n (by omega)] + exact Z.zero_mem + | succ d ih => + intro n hn + have hh := Z.add_mem (hc (n+1)) (Z.smul_mem t (ih (n+1) (by omega))) + simpa only [mulRoot_coeff_succ, sub_add_cancel] using hh + intro n + exact aux (k-n) n rfl + +theorem bi_factor_row (r s : ℕ) (p : BiPoly) (hp : BiBounded (r+1) s p) + (t : ℝ) (hz : eval t p = 0) : + ∃ q : BiPoly, BiBounded r s q ∧ mulRoot t q = p := by + obtain ⟨q, hq, he⟩ := exists_mulRoot_of_eval_zero t r p hp.1 hz + refine ⟨q, ⟨hq, ?_⟩, he⟩ + apply coefficients_of_mulRoot (boundedSpace s) t r q hq + intro n + rw [he] + exact hp.2 n + +theorem biEval_mulRoot (t u v : ℝ) (p : BiPoly) : + biEval u v (mulRoot t p) = (u-t) * biEval u v p := by + change eval v (eval u (mulRoot t p)) = _ + rw [eval_mulRoot, _root_.map_smul] + rfl + +theorem bounded_eval_outer {r s : ℕ} {p : BiPoly} (hp : BiBounded r s p) (u : ℝ) : + Bounded s (eval u p) := by + change eval u p ∈ boundedSpace s + change p.coeff.sum (fun a c => u^a • c) ∈ boundedSpace s + apply Submodule.sum_mem + intro a ha + exact (boundedSpace s).smul_mem (u^a) (hp.2 a) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BivariateCoefficients.lean b/lean/OAI/Combinatorics/Crossing/BivariateCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..38c46597400ff4808ca96b81f6869caa6f504c1c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BivariateCoefficients.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.Crossing.TwoTriangleUnisolvence +import Mathlib.LinearAlgebra.Matrix.NonsingularInverse + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module +open scoped BigOperators + +abbrev BiExponent (s : ℕ) := Fin s × Fin s + +def biOfCoeffs (s : ℕ) (c : BiExponent s → ℝ) : BiPoly := + ∑ a : Fin s, single ℝ a.val (∑ b : Fin s, single ℝ b.val (c (a,b))) + +theorem biCoeff_biOfCoeffs (s : ℕ) (c : BiExponent s → ℝ) (a b : Fin s) : + biCoeff (biOfCoeffs s c) a.val b.val = c (a,b) := by + simp [biCoeff, biOfCoeffs, coeff_sum, Finsupp.finsetSum_apply, Finsupp.single_apply, Fin.val_inj] + +theorem biOfCoeffs_injective (s : ℕ) : Function.Injective (biOfCoeffs s) := by + intro c d h + funext ab + have hh := congrArg (fun p => biCoeff p ab.1.val ab.2.val) h + simpa only [biCoeff_biOfCoeffs] using hh + +theorem biOfCoeffs_bounded (s : ℕ) (c : BiExponent s → ℝ) : + BiBounded s s (biOfCoeffs s c) := by + constructor + · apply bounded_sum + intro a ha + exact bounded_single a.isLt _ + · intro n k hk + simp only [biOfCoeffs, coeff_sum, Finsupp.finsetSum_apply, coeff_single, + Finsupp.single_apply] + apply Finset.sum_eq_zero + intro a ha + split_ifs with hna + · simp only [coeff_sum, Finsupp.finsetSum_apply, coeff_single, Finsupp.single_apply] + apply Finset.sum_eq_zero + intro b hb + rw [ite_eq_right (by omega)] + · rfl + +theorem biEval_biOfCoeffs (s : ℕ) (c : BiExponent s → ℝ) (u v : ℝ) : + biEval u v (biOfCoeffs s c) = ∑ a : Fin s, ∑ b : Fin s, + (u^a.val * v^b.val) * c (a,b) := by + simp [biOfCoeffs, biEval, eval_single, smul_eq_mul, Finset.mul_sum, mul_assoc] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/BoundaryCollar.lean b/lean/OAI/Combinatorics/Crossing/BoundaryCollar.lean new file mode 100644 index 0000000000000000000000000000000000000000..a359d8667dc5b6a70e32df42387baa710e9f95ad --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/BoundaryCollar.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.Crossing.RadialExterior +import Mathlib.Analysis.Normed.Module.Convex + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem exists_radial_tip_collar (z x : Plane) (r : ℝ) (hr : 0 < r) + (hx : squaredLength (x-z)=r^2) (U : Set Plane) (hU : IsOpen U) (hxu : x ∈ U) : + ∃ α ρ : ℝ, 0 < α ∧ 0 < ρ ∧ + segment ℝ x (x+α • (x-z)) ⊆ U ∩ insert x {y | r^2 < squaredLength (y-z)} ∧ + (∀ y, dist y x < ρ → r^2 < squaredLength (y-z) → + segment ℝ (x+α • (x-z)) y ⊆ U ∩ {p | r^2 < squaredLength (p-z)}) := by + obtain ⟨ε,hε,hball⟩ := Metric.isOpen_iff.mp hU x hxu + have hmove : Continuous (fun α : ℝ => x+α • (x-z)) := by fun_prop + have hevent : ∀ᶠ α : ℝ in 𝓝 0, x+α • (x-z) ∈ Metric.ball x ε := + hmove.continuousAt.preimage_mem_nhds (by simpa using Metric.ball_mem_nhds x hε) + obtain ⟨δ,hδ,hd⟩ := Metric.eventually_nhds_iff.mp hevent + let α := δ/2 + have hα : 0 < α := by dsimp [α]; positivity + have htip : x+α • (x-z) ∈ Metric.ball x ε := hd (by + rw [Real.dist_eq,sub_zero,abs_of_pos hα] + dsimp [α] + linarith) + have hdpos : 0 < dot2 (x-z) ((x+α • (x-z))-x) := by + rw [radial_tip_dot,hx] + exact mul_pos hα (sq_pos_of_pos hr) + have hdot : Continuous (fun y : Plane => dot2 (y-z) ((x+α • (x-z))-y)) := by + unfold dot2 + fun_prop + have hev : ∀ᶠ y : Plane in 𝓝 x, 0 < dot2 (y-z) ((x+α • (x-z))-y) := + continuousAt_const.eventually_lt hdot.continuousAt hdpos + obtain ⟨σ,hσ,hσdot⟩ := Metric.eventually_nhds_iff.mp hev + refine ⟨α,min ε σ,hα,lt_min hε hσ,?_,?_⟩ + · apply Set.subset_inter + · exact ((convex_ball x ε).segment_subset (Metric.mem_ball_self hε) htip).trans hball + · exact radial_spur_exterior z x r α hx hr hα + · intro y hy hout + apply Set.subset_inter + · exact ((convex_ball x ε).segment_subset htip (hy.trans_le (min_le_left _ _))).trans hball + · rw [segment_symm] + exact exterior_segment_of_dot z y (x+α • (x-z)) r hout + (hσdot (hy.trans_le (min_le_right _ _))).le + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ChainPieceInteriors.lean b/lean/OAI/Combinatorics/Crossing/ChainPieceInteriors.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7e33ee854903e53a335ed851a11698b2c29d0ea --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ChainPieceInteriors.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.Crossing.MinimumChainVertexPieces +import OAI.Combinatorics.Crossing.OpenSegmentEndpoints +import OAI.Combinatorics.Crossing.DrawingRangeCrossings + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem drawing_chain_piece_open_subset_interior {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) : + openSegmentTrace (P.vertices i) (P.vertices (i+1)) ⊆ edgeInterior D e := by + intro x hx + have hseg := openSegmentTrace_subset_segment _ _ hx + have hne := openSegmentTrace_ne_endpoints _ _ + (P.minimum_vertices_ne hmin i (i+1) (by omega) (by omega)) x hx + apply edgeInterior_of_range_not_vertices D e x (P.inside i hi hseg) + intro j hj + have hvertex : D.vertex j ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := hj ▸ hseg + rcases drawing_chain_piece_vertex D e P hmin i hi j hvertex with ⟨he,hii⟩ | ⟨he,hii⟩ + · apply hne.1 + calc + x = D.vertex j := hj + _ = D.vertex (.inl e.1) := congrArg D.vertex he + _ = P.vertices i := by simpa only [hii] using P.first.symm + · apply hne.2 + calc + x = D.vertex j := hj + _ = D.vertex (.inr e.2) := congrArg D.vertex he + _ = P.vertices (i+1) := by simpa only [hii] using P.last.symm + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ChainTracePieces.lean b/lean/OAI/Combinatorics/Crossing/ChainTracePieces.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8ffddc9c500a46336bfe50bfcb92b84ff754802 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ChainTracePieces.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.Crossing.ReducedPolygonalPresentation +import OAI.Combinatorics.Crossing.GraphWalkTrace + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem PolygonalChain.piece_subset_path_range {O : Set Plane} {a b : Plane} + (P : PolygonalChain O a b) (i : ℕ) (hi : i < P.pieces) : + segment ℝ (P.vertices i) (P.vertices (i+1)) ⊆ Set.range P.path := by + exact polygonalArcPath_piece_subset_range P.vertices P.pieces i hi + +theorem drawing_chain_range_eq {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) : + Set.range P.path=Set.range (D.edge e) := + path_range_eq_of_subset (D.edge e) P.path (D.edge_injective e) P.path_range_subset + +theorem drawing_chain_pieces_pos {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) : + 0 < P.pieces := by + apply P.pieces_pos_of_ne + intro h + cases D.vertex_injective h + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ChordEdgeIntersections.lean b/lean/OAI/Combinatorics/Crossing/ChordEdgeIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..5155851e37638b312ad9985cf9243825cc519ea8 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ChordEdgeIntersections.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.StraightChainTransversality +import OAI.Combinatorics.Crossing.UniformCrossTypeGeometry + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_chord_edge_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → + (∀ j (a b : IncidentEdges j) e, + (V.chordChain j a b).Transverse (C.shiftedEdgeChain e ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).pieces=0) ∧ + (∀ j (a b : IncidentEdges j) e, + (V.trackChain e).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).pieces (C.shiftedChordChain j a b ε).pieces=0) := by + obtain ⟨δ,hδ,hh⟩ := C.exists_cross_type_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall + obtain ⟨hTC,hTChord,hChordT,hChordC,hChordChord,hOther⟩ := hh ε hε hsmall + constructor + · intro j a b e + have hconn (k : BipartiteVertex m n) (f : IncidentEdges k) : + (V.chordChain j a b).Transverse (C.connectorChain k f ε) := by + apply PolygonalChain.transverse_single_single + exact segmentPairTransverse_of_not_meet _ _ _ _ (hChordC j k a b f) + have hmid : (V.chordChain j a b).Transverse (C.shiftedTrackChain e ε) := by + apply PolygonalChain.transverse_single_left + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hChordT j a b e i) + have hzconn (k : BipartiteVertex m n) (f : IncidentEdges k) : + polygonIntersection (V.chordChain j a b).vertices (C.connectorChain k f ε).vertices 1 1=0 := by + rw [VertexTruncation.chordChain,connectorChain,PolygonalChain.intersection_single_single] + exact segmentCrossingSign_eq_zero_of_not_meet _ _ _ _ (hChordC j k a b f) + have hzmid : polygonIntersection (V.chordChain j a b).vertices + (shiftedTrack (V.vertices e) (V.pieces e) ε) 1 (V.pieces e)=0 := by + apply (C.shiftedTrackChain e ε).intersection_single_left_zero + intro i + exact hChordT j a b e i + constructor + · change (V.chordChain j a b).Transverse + (((C.connectorChain (Sum.inl e.1) (V.leftIncident e) ε).join (C.shiftedTrackChain e ε)).join + (C.connectorChain (Sum.inr e.2) (V.rightIncident e) ε).reverse) + apply PolygonalChain.transverse_join_right + · exact PolygonalChain.transverse_join_right _ _ _ (hconn _ _) hmid + · exact (V.chordChain j a b).transverse_reverse_right _ (hconn _ _) + · change polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices 1 _=0 + rw [C.shiftedEdgeChain_intersection_right,hzconn,hzconn,hzmid] + norm_num + · intro j a b e + constructor + · apply PolygonalChain.transverse_single_right + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hTChord j a b e i) + · apply PolygonalChain.intersection_single_right_zero + intro i + exact hTChord j a b e i + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ChordExteriorSeparation.lean b/lean/OAI/Combinatorics/Crossing/ChordExteriorSeparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc574c17a62a068c00a36c922119895abc4151c3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ChordExteriorSeparation.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.TrackChordSeparation +import OAI.Combinatorics.Crossing.ConnectorOtherDisks +import OAI.Combinatorics.Crossing.ShiftedTrackDisks + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem round_chord_exterior_disjoint (z a b c d : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hout : segment ℝ c d ⊆ {x | r^2 < squaredLength (x-z)}) : ¬ ClosedSegmentsMeet a b c d := by + intro hh + obtain ⟨x,hx,hy⟩ := (closedSegmentsMeet_iff_nonempty_inter _ _ _ _).mp hh + have hle := round_chord_subset_closed_disk z a b r ha hb hx + have hlt : r^2 < squaredLength (x-z) := hout hy + change squaredLength (x-z) ≤ r^2 at hle + exact not_lt_of_ge hle hlt + +namespace TruncatedSpokeCoordinates +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem different_vertex_chords_disjoint (j k : BipartiteVertex m n) (hjk : j ≠ k) + (a b : IncidentEdges j) (c d : IncidentEdges k) (ε : ℝ) + (hc : |V.spokeScale k c*ε|≤1) (hd : |V.spokeScale k d*ε|≤1) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε) := by + apply not_closedSegmentsMeet_of_disjoint + exact (V.disks_disjoint j k hjk).mono + (round_chord_subset_closed_disk _ _ _ _ (V.spokePort_circle j a) (V.spokePort_circle j b)) + (round_chord_subset_closed_disk _ _ _ _ (C.shiftedPort_circle k c ε hc) (C.shiftedPort_circle k d ε hd)) + +theorem chord_connector_disjoint_all_passages (j : BipartiteVertex m n) (a b f : IncidentEdges j) + (ε : ℝ) (hne : ε ≠ 0) (hsmall : |V.spokeScale j f*ε|<1) + (ha : V.spokePort j a ≠ C.shiftedPort j f ε) (hb : V.spokePort j b ≠ C.shiftedPort j f ε) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + rintro ⟨s,hs,t,ht,he⟩ + have hx : segmentPoint (V.spokePort j a) (V.spokePort j b) s ∈ segment ℝ (V.spokePort j a) (V.spokePort j b) := by + rw [← Path.range_segment] + exact ⟨⟨s,hs⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint]⟩ + have hinside := round_chord_subset_closed_disk (D.vertex j) _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) hx + by_cases htp : 0 linarith + +theorem chordEndpointPairing_reverse_left (a b c d : ℝ) : + chordEndpointPairing b a c d = -chordEndpointPairing a b c d := by + unfold chordEndpointPairing + ring + +theorem chordEndpointPairing_swap (a b c d : ℝ) : + chordEndpointPairing c d a b = -chordEndpointPairing a b c d := by + unfold chordEndpointPairing + rw [orderSign_swap c a,orderSign_swap c b,orderSign_swap d a,orderSign_swap d b] + ring + +theorem circle_chords_separated (a b c d : ℝ) (hab : a norm_num <;> linarith + · have hcb : c norm_num <;> linarith + · have hdb : d norm_num <;> linarith + · have hca : c norm_num <;> linarith + · have had' : a norm_num <;> linarith + · have hbd' : b norm_num <;> linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ChordTransversality.lean b/lean/OAI/Combinatorics/Crossing/ChordTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..974cf90abeb5340df29f3bf4808bad8386675e68 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ChordTransversality.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.CircleChords +import OAI.Combinatorics.Crossing.SegmentContinuity + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segmentPairTransverse_of_noncollinear_endpoints (a b c d : Plane) + (ha : orient2 c d a ≠ 0) (hb : orient2 c d b ≠ 0) + (hc : orient2 a b c ≠ 0) (hd : orient2 a b d ≠ 0) : + SegmentPairTransverse a b c d := by + intro t ht u hu he + have hdet : det2 (b-a) (d-c) ≠ 0 := by + intro hz + have hdiff := orient2_difference a b c d + have heq : orient2 a b c=orient2 a b d := by linarith + have hh := congrArg (orient2 a b) he + rw [orient2_self_segment,orient2_segment,← heq] at hh + apply hc + nlinarith + have ht0 : t ≠ 0 := by + intro h + subst t + rw [segmentPoint_zero] at he + exact ha (by rw [he,orient2_self_segment]) + have ht1 : t ≠ 1 := by + intro h + subst t + rw [segmentPoint_one] at he + exact hb (by rw [he,orient2_self_segment]) + have hu0 : u ≠ 0 := by + intro h + subst u + rw [segmentPoint_zero] at he + exact hc (by rw [← he,orient2_self_segment]) + have hu1 : u ≠ 1 := by + intro h + subst u + rw [segmentPoint_one] at he + exact hd (by rw [← he,orient2_self_segment]) + exact ⟨hdet,⟨lt_of_le_of_ne ht.1 ht0.symm,lt_of_le_of_ne ht.2 ht1⟩, + ⟨lt_of_le_of_ne hu.1 hu0.symm,lt_of_le_of_ne hu.2 hu1⟩⟩ + +theorem circle_orient_ne_zero (a b c : ℝ) (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) : + orient2 (circlePoint a) (circlePoint b) (circlePoint c) ≠ 0 := by + rw [circle_orient_formula] + apply div_ne_zero + · exact mul_ne_zero (mul_ne_zero (mul_ne_zero (by norm_num) (sub_ne_zero.mpr hab.symm)) + (sub_ne_zero.mpr hac.symm)) (sub_ne_zero.mpr hbc.symm) + · exact mul_ne_zero (mul_ne_zero (ne_of_gt (circle_denominator_pos a)) + (ne_of_gt (circle_denominator_pos b))) (ne_of_gt (circle_denominator_pos c)) + +theorem circle_chords_transverse (a b c d : ℝ) + (hab : a ≠ b) (hcd : c ≠ d) (hac : a ≠ c) (had : a ≠ d) (hbc : b ≠ c) (hbd : b ≠ d) : + SegmentPairTransverse (circlePoint a) (circlePoint b) (circlePoint c) (circlePoint d) := by + exact segmentPairTransverse_of_noncollinear_endpoints _ _ _ _ + (circle_orient_ne_zero c d a hcd hac.symm had.symm) + (circle_orient_ne_zero c d b hcd hbc.symm hbd.symm) + (circle_orient_ne_zero a b c hab hac hbc) + (circle_orient_ne_zero a b d hab had hbd) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CircleChords.lean b/lean/OAI/Combinatorics/Crossing/CircleChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9e1fa66c31db4239287284ca398b1405e72ec0b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CircleChords.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.SegmentSides + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def circlePoint (t : ℝ) : Plane := ((1-t^2)/(1+t^2), 2*t/(1+t^2)) + +theorem circle_denominator_pos (t : ℝ) : 0 < 1+t^2 := by nlinarith [sq_nonneg t] + +theorem circlePoint_on_unit_circle (t : ℝ) : (circlePoint t).1^2+(circlePoint t).2^2 = 1 := by + have h := ne_of_gt (circle_denominator_pos t) + dsimp [circlePoint] + field_simp + ring + +theorem circlePoint_parameter (t : ℝ) : (circlePoint t).2/(1+(circlePoint t).1) = t := by + have h := ne_of_gt (circle_denominator_pos t) + have hden : 1+(circlePoint t).1 = 2/(1+t^2) := by + dsimp [circlePoint] + field_simp + ring + rw [hden] + dsimp [circlePoint] + field_simp + +theorem circlePoint_injective : Function.Injective circlePoint := by + intro a b hab + have hh := congrArg (fun z : Plane => z.2/(1+z.1)) hab + simpa only [circlePoint_parameter] using hh + +theorem circle_orient_formula (a b c : ℝ) : + orient2 (circlePoint a) (circlePoint b) (circlePoint c) = + 4*(b-a)*(c-a)*(c-b)/((1+a^2)*(1+b^2)*(1+c^2)) := by + have ha := ne_of_gt (circle_denominator_pos a) + have hb := ne_of_gt (circle_denominator_pos b) + have hc := ne_of_gt (circle_denominator_pos c) + dsimp [orient2,det2,circlePoint] + field_simp + ring + +theorem circle_orient_pos (a b c : ℝ) (hab : a dsimp [segmentPoint,circleOffset,circleTangentOffset,rotateQuarter] <;> ring + +theorem circleConnector_outside (u : Plane) (hu : squaredLength u=1) + (δ : ℝ) (hδ : |δ|≤1) (t : ℝ) (ht : t ∈ Set.Icc (0 : ℝ) 1) : + 1 ≤ squaredLength (segmentPoint (circleOffset u δ) (circleTangentOffset u δ) t) := by + have hnon : 0 ≤ 1-δ^2 := by have hh := abs_le.mp hδ; nlinarith + have hs := Real.sq_sqrt hnon + have hs0 := Real.sqrt_nonneg (1-δ^2) + have hs1 : Real.sqrt (1-δ^2) ≤ 1 := by nlinarith [sq_nonneg δ] + have hA : Real.sqrt (1-δ^2) ≤ (1-t)*Real.sqrt (1-δ^2)+t := by + have hmul := mul_nonneg ht.1 (sub_nonneg.mpr hs1) + nlinarith + rw [circleConnector_parameterization,squaredLength_radial u hu] + nlinarith + +theorem circleConnector_strictly_outside (u : Plane) (hu : squaredLength u=1) + (δ : ℝ) (hδ : |δ|<1) (hne : δ ≠ 0) (t : ℝ) (ht : 0 dsimp [similarityPoint,circleOffset,rotateQuarter] <;> ring + +theorem rotated_parallel_det_ne_zero (d w : Plane) (hd : d ≠ 0) (hw : w ≠ 0) + (hpar : det2 d w=0) : det2 d (rotateQuarter w) ≠ 0 := by + have hp := vector_parallel_of_det_zero d w hd hpar + have hc : dot2 d w/squaredLength d ≠ 0 := by + intro h + rw [h,zero_smul] at hp + exact hw hp + have he : det2 d (rotateQuarter w)=(dot2 d w/squaredLength d)*squaredLength d := by + conv_lhs => rw [hp] + dsimp [det2,rotateQuarter,squaredLength] + ring + rw [he] + exact mul_ne_zero hc (ne_of_gt (squaredLength_pos d hd)) + +def circleTrackScale (d w : Plane) : ℝ := (det2 d (rotateQuarter w))⁻¹ + +theorem circleTrackScale_ne_zero (d w : Plane) (hd : d ≠ 0) (hw : w ≠ 0) + (hpar : det2 d w=0) : circleTrackScale d w ≠ 0 := + inv_ne_zero (rotated_parallel_det_ne_zero d w hd hw hpar) + +theorem circleOffset_track_level (o u v d : Plane) (hd : d ≠ 0) + (hw : similarityPoint o u v-o ≠ 0) + (hpar : det2 d (similarityPoint o u v-o)=0) (ε : ℝ) : + det2 d (similarityPoint o u (circleOffset v (circleTrackScale d (similarityPoint o u v-o)*ε))- + similarityPoint o u v)=ε := by + let w := similarityPoint o u v-o + let δ := circleTrackScale d w*ε + have he : similarityPoint o u (circleOffset v δ)-similarityPoint o u v = + (Real.sqrt (1-δ^2)-1) • w+δ • rotateQuarter w := by + have hh := similarity_circleOffset o u v δ + calc + _ = (similarityPoint o u (circleOffset v δ)-o)-(similarityPoint o u v-o) := by abel + _ = Real.sqrt (1-δ^2) • w+δ • rotateQuarter w-w := by rw [hh] + _ = _ := by rw [sub_smul,one_smul]; abel + change det2 d (similarityPoint o u (circleOffset v δ)-similarityPoint o u v)=ε + rw [he,det2_add_right,det2_smul_right,det2_smul_right,hpar,mul_zero,zero_add] + have hn := rotated_parallel_det_ne_zero d w hd hw hpar + dsimp [δ,circleTrackScale] + field_simp + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CircleOffsetParameter.lean b/lean/OAI/Combinatorics/Crossing/CircleOffsetParameter.lean new file mode 100644 index 0000000000000000000000000000000000000000..af62d24a6955d6dab32647da8427dae99914869a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CircleOffsetParameter.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.CircleOffset +import OAI.Combinatorics.Crossing.CircleDeterminantOrder +import Mathlib.Tactic.FunProp + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +def offsetParameter (a δ : ℝ) : ℝ := + (circleOffset (circlePoint a) δ).2/(1+(circleOffset (circlePoint a) δ).1) + +theorem continuous_circleOffset (u : Plane) : Continuous (circleOffset u) := by + change Continuous (fun δ : ℝ => Real.sqrt (1-δ^2) • u+δ • rotateQuarter u) + fun_prop + +@[simp] theorem offsetParameter_zero (a : ℝ) : offsetParameter a 0=a := by + simp only [offsetParameter,circleOffset_zero,circlePoint_parameter] + +theorem continuousAt_offsetParameter_zero (a : ℝ) : ContinuousAt (offsetParameter a) 0 := by + apply ContinuousAt.div + · exact (continuous_circleOffset (circlePoint a)).continuousAt.snd + · exact continuousAt_const.add (continuous_circleOffset (circlePoint a)).continuousAt.fst + · rw [circleOffset_zero,circlePoint_one_add_x] + exact div_ne_zero (by norm_num) (ne_of_gt (circle_denominator_pos a)) + +theorem exists_circle_offset_parameter_radius (a ε : ℝ) (hε : 0<ε) : + ∃ ρ : ℝ, 0<ρ ∧ ∀ δ : ℝ, |δ|<ρ → + circlePoint (offsetParameter a δ)=circleOffset (circlePoint a) δ ∧ + |offsetParameter a δ-a|<ε ∧ + (0<δ → a linarith)) + have hsmall : ∀ᶠ δ : ℝ in 𝓝 0, |δ|<1 := by + apply Metric.eventually_nhds_iff.mpr + exact ⟨1,by norm_num,by intro delta; simp [Real.dist_eq]⟩ + have hcut : ∀ᶠ δ : ℝ in 𝓝 0, (circleOffset (circlePoint a) δ).1 ≠ -1 := + (continuous_circleOffset (circlePoint a)).continuousAt.fst.eventually_ne + (by simpa using circlePoint_avoids_cut a) + have hprodcont : ContinuousAt (fun δ : ℝ => 1+a*offsetParameter a δ) 0 := + continuousAt_const.add (continuousAt_const.mul hp) + have hprod : ∀ᶠ δ : ℝ in 𝓝 0, 0<1+a*offsetParameter a δ := + continuousAt_const.eventually_lt hprodcont (by rw [offsetParameter_zero]; nlinarith [sq_nonneg a]) + have hevent : ∀ᶠ δ : ℝ in 𝓝 0, + circlePoint (offsetParameter a δ)=circleOffset (circlePoint a) δ ∧ + |offsetParameter a δ-a|<ε ∧ + (0<δ → a hh (by simpa [Real.dist_eq] using hδ)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CircleParameterChart.lean b/lean/OAI/Combinatorics/Crossing/CircleParameterChart.lean new file mode 100644 index 0000000000000000000000000000000000000000..50c81c58b0d23be9c485c5b809298b7b52d17e36 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CircleParameterChart.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.Crossing.CircleChords + +namespace OAI + +namespace Zarankiewicz + +theorem circlePoint_one_add_x (t : ℝ) : 1+(circlePoint t).1 = 2/(1+t^2) := by + have h := ne_of_gt (circle_denominator_pos t) + dsimp [circlePoint] + field_simp + ring + +theorem circlePoint_avoids_cut (t : ℝ) : (circlePoint t).1 ≠ -1 := by + have hh : 0 < 1+(circlePoint t).1 := by + rw [circlePoint_one_add_x] + exact div_pos (by norm_num) (circle_denominator_pos t) + linarith + +theorem circlePoint_surjective_away_cut (z : Plane) (hz : z.1^2+z.2^2 = 1) (hcut : z.1 ≠ -1) : + circlePoint (z.2/(1+z.1)) = z := by + have hx : 0 < 1+z.1 := by + have hy := sq_nonneg z.2 + have hnonneg : 0 ≤ 1+z.1 := by nlinarith + rcases hnonneg.eq_or_lt with he | he + · exfalso + apply hcut + linarith + · exact he + have hxn := ne_of_gt hx + have hden : 1+(z.2/(1+z.1))^2 = 2/(1+z.1) := by + field_simp + nlinarith + apply Prod.ext + · change (1-(z.2/(1+z.1))^2)/(1+(z.2/(1+z.1))^2) = z.1 + rw [hden] + field_simp + nlinarith [congrArg (fun t : ℝ => (1+z.1)*t) hz] + · change (2*(z.2/(1+z.1)))/(1+(z.2/(1+z.1))^2) = z.2 + rw [hden] + field_simp + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ClosedPolygonIntersection.lean b/lean/OAI/Combinatorics/Crossing/ClosedPolygonIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..89e9b7d901cc9cb01e0ba7e9f1e98072d6de41bb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ClosedPolygonIntersection.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.TransversePolygonIntersection +import OAI.Combinatorics.Crossing.PolygonTransversalityStability + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem closed_polygon_intersection_zero (v w : ℕ → Plane) (n m : ℕ) + (hc : v n=v 0) (hd : w m=w 0) + (ht : ∀ i : Fin n, ∀ j : Fin m, + SegmentPairTransverse (v i.val) (v (i.val+1)) (w j.val) (w (j.val+1))) : + polygonIntersection v w n m = 0 := by + by_cases hm : 1 (Fin.elim0 i : Plane)) (fun i : Fin 0 => (Fin.elim0 i : Plane)) + (fun i : Fin 0 => (Fin.elim0 i : Plane)) (fun i => Fin.elim0 i) + m (fun i => w i.val) (fun _ => ε) (fun _ => hε) + let w' := periodicPolygon m hm0 p + have hclose : w' m=w' 0 := periodicPolygon_closed m hm0 p + have hw' (j : Fin m) : w' (j.val+1) ≠ w' j.val := hinj.ne (cyclicIndex_succ_ne m hm j) + obtain ⟨htrans,heq⟩ := hstable w' (periodicPolygon_near m hm0 w hd p ε hnear) + have hzero := polygon_intersection_zero_transverse v w' n m hc hclose hw' + (fun i j => segmentPairTransverse_swap _ _ _ _ (htrans j i)) + have hrev := polygonIntersection_swap v w' n m + rw [hzero,neg_zero,heq] at hrev + rw [polygonIntersection_swap v w n m] at hrev + exact neg_eq_zero.mp hrev + · have hm' : m=0 ∨ m=1 := by omega + rcases hm' with rfl | rfl + · simp [polygonIntersection] + · have hz : polygonIntersection w v 1 n = 0 := by + simp only [polygonIntersection,Finset.sum_range_one] + rw [hd] + simp only [segmentCrossingSign_self_left,Finset.sum_const_zero] + rw [polygonIntersection_swap v w n 1] at hz + exact neg_eq_zero.mp hz + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CollinearSegmentUnion.lean b/lean/OAI/Combinatorics/Crossing/CollinearSegmentUnion.lean new file mode 100644 index 0000000000000000000000000000000000000000..474920fdbc960b08906e41c6b8252a54b6882e62 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CollinearSegmentUnion.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.Crossing.ParallelDirection +import Mathlib.Analysis.Convex.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem collinear_segment_subset_union (a b c : Plane) (hac : a ≠ c) + (h : det2 (b-a) (c-b)=0) : + segment ℝ a c ⊆ segment ℝ a b ∪ segment ℝ b c := by + have hd : det2 (c-a) (b-a)=0 := by + have he : det2 (c-a) (b-a) = -det2 (b-a) (c-b) := by dsimp [det2]; ring + rw [he,h,neg_zero] + have hp := vector_parallel_of_det_zero (c-a) (b-a) (sub_ne_zero.mpr (Ne.symm hac)) hd + have hb : b ∈ Set.range (AffineMap.lineMap a c : ℝ → Plane) := by + refine ⟨dot2 (c-a) (b-a)/squaredLength (c-a),?_⟩ + rw [AffineMap.lineMap_apply] + change (dot2 (c-a) (b-a)/squaredLength (c-a)) • (c-a)+a=b + rw [← hp,sub_add_cancel] + intro x hx + rw [← insert_endpoints_openSegment] at hx + rcases hx with hxa | hxc | hxo + · subst x + exact Or.inl (left_mem_segment ℝ a b) + · subst x + exact Or.inr (right_mem_segment ℝ b c) + · rcases openSegment_subset_union a c hb hxo with hxb | hx' + · subst x + exact Or.inl (right_mem_segment ℝ a b) + · exact hx'.elim (fun hh => Or.inl (openSegment_subset_segment ℝ a b hh)) + (fun hh => Or.inr (openSegment_subset_segment ℝ b c hh)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CompactCorridors.lean b/lean/OAI/Combinatorics/Crossing/CompactCorridors.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ce6158681b5e0d5bb89a3fb4d609c69e603e782 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CompactCorridors.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.Crossing.MarkedCurveDisks +import Mathlib.Topology.Separation.Regular + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem finite_compact_corridors {ι : Type*} [Fintype ι] [DecidableEq ι] + (K O : ι → Set Plane) (hK : ∀ i, IsCompact (K i)) + (hd : ∀ i j, i ≠ j → Disjoint (K i) (K j)) + (hO : ∀ i, IsOpen (O i)) (hKO : ∀ i, K i ⊆ O i) : + ∃ U : ι → Set Plane, (∀ i, IsOpen (U i)) ∧ (∀ i, K i ⊆ U i) ∧ + (∀ i, U i ⊆ O i) ∧ (∀ i j, i ≠ j → Disjoint (U i) (U j)) := by + have hex (i j : ι) : ∃ A B : Set Plane, IsOpen A ∧ IsOpen B ∧ K i ⊆ A ∧ K j ⊆ B ∧ + (i ≠ j → Disjoint A B) := by + by_cases he : i=j + · exact ⟨Set.univ,Set.univ,isOpen_univ,isOpen_univ,Set.subset_univ _,Set.subset_univ _,fun hn => False.elim (hn he)⟩ + · obtain ⟨A,B,hA,hB,hi,hj,hab⟩ := normal_separation (hK i).isClosed (hK j).isClosed (hd i j he) + exact ⟨A,B,hA,hB,hi,hj,fun _ => hab⟩ + choose A B hA hB hKA hKB hAB using hex + let U : ι → Set Plane := fun i => O i ∩ ⋂ j, A i j ∩ B j i + refine ⟨U,?_,?_,?_,?_⟩ + · intro i + exact (hO i).inter (isOpen_iInter_of_finite (fun j => (hA i j).inter (hB j i))) + · intro i x hx + exact ⟨hKO i hx,Set.mem_iInter.mpr (fun j => ⟨hKA i j hx,hKB j i hx⟩)⟩ + · intro i x hx + exact hx.1 + · intro i j hij + apply Set.disjoint_left.mpr + intro x hx hy + exact Set.disjoint_left.mp (hAB i j hij) + (Set.mem_iInter.mp hx.2 j).1 (Set.mem_iInter.mp hy.2 i).2 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ConeIntersection.lean b/lean/OAI/Combinatorics/Crossing/ConeIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b83b4accc17a1c68d9e68e27e932a29b1ab43f6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ConeIntersection.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.Crossing.TriangleOrientations + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +theorem polygon_intersection_zero_of_cone (v w : ℕ → Plane) (n m : ℕ) + (hv : v n = v 0) (hw : w m = w 0) (o : Plane) + (ha : ∀ i ∈ Finset.range n, orient2 o (v i) (v (i+1)) ≠ 0) + (hp : ∀ i ∈ Finset.range n, ∀ j ∈ Finset.range m, + TriangleSegmentPosition o (v i) (v (i+1)) (w j) (w (j+1))) : + polygonIntersection v w n m = 0 := by + unfold polygonIntersection + calc + _ = ∑ j ∈ Finset.range m, ∑ i ∈ Finset.range n, + segmentCrossingSign (v i) (v (i+1)) (w j) (w (j+1)) := Finset.sum_comm + _ = ∑ j ∈ Finset.range m, ∑ i ∈ Finset.range n, + triangleSegmentIntersection o (v i) (v (i+1)) (w j) (w (j+1)) := by + apply Finset.sum_congr rfl + intro j hj + exact (polygon_cone_cancellation v n hv o _ _).symm + _ = ∑ i ∈ Finset.range n, ∑ j ∈ Finset.range m, + triangleSegmentIntersection o (v i) (v (i+1)) (w j) (w (j+1)) := Finset.sum_comm + _ = 0 := by + apply Finset.sum_eq_zero + intro i hi + exact triangle_closed_walk_intersection_zero o _ _ (ha i hi) w m hw (hp i hi) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ConnectorOtherDisks.lean b/lean/OAI/Combinatorics/Crossing/ConnectorOtherDisks.lean new file mode 100644 index 0000000000000000000000000000000000000000..71ca555fdc0676b9c0ba12ba87d3d72433791c95 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ConnectorOtherDisks.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.ConnectorSupportingLines +import OAI.Combinatorics.Crossing.MovingDiskClearance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped Topology +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem exists_connector_other_disks_radius : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j k, j ≠ k → ∀ f : IncidentEdges j, + segment ℝ (C.shiftedPort j f ε) (C.tangentPort j f ε) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex k)} := by + classical + let Pair := Σ j : BipartiteVertex m n, Σ k : {k : BipartiteVertex m n // j ≠ k}, IncidentEdges j + have hstart (b : Pair) : segment ℝ (C.shiftedPort b.1 b.2.2 0) (C.tangentPort b.1 b.2.2 0) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex b.2.1.val)} := by + rw [C.shiftedPort_zero,C.tangentPort_zero,segment_same] + intro x hx + have he : x=V.spokePort b.1 b.2.2 := hx + subst x + change V.radius^2 < squaredLength (V.spokePort b.1 b.2.2-D.vertex b.2.1.val) + by_contra hh + have hj : V.spokePort b.1 b.2.2 ∈ closedRoundDisk (D.vertex b.1) V.radius := by + change squaredLength (V.spokePort b.1 b.2.2-D.vertex b.1) ≤ V.radius^2 + rw [V.spokePort_circle] + have hk : V.spokePort b.1 b.2.2 ∈ closedRoundDisk (D.vertex b.2.1.val) V.radius := not_lt.mp hh + exact Set.disjoint_left.mp (V.disks_disjoint b.1 b.2.1.val b.2.1.property) hj hk + have hevent (b : Pair) := eventually_moving_segment_outside_disk + (C.shiftedPort b.1 b.2.2) (C.tangentPort b.1 b.2.2) + (C.continuous_shiftedPort b.1 b.2.2) (C.continuous_tangentPort b.1 b.2.2) + (D.vertex b.2.1.val) V.radius (hstart b) + have hex (b : Pair) := Metric.eventually_nhds_iff.mp (hevent b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j k hjk f + exact hprop ⟨j,⟨k,hjk⟩,f⟩ (by simpa [Real.dist_eq] using hε.trans (hbound ⟨j,⟨k,hjk⟩,f⟩ (Finset.mem_univ _))) + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ConnectorSupportingLines.lean b/lean/OAI/Combinatorics/Crossing/ConnectorSupportingLines.lean new file mode 100644 index 0000000000000000000000000000000000000000..05b8cfc19647f46e2ffa86a16de762e47d945a22 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ConnectorSupportingLines.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.SpokePieceIsolation +import OAI.Combinatorics.Crossing.SpokeEndpointSeparation + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem det2_segmentPoint_sub (d p a b : Plane) (t : ℝ) : + det2 d (segmentPoint a b t-p)=(1-t)*det2 d (a-p)+t*det2 d (b-p) := by + dsimp [det2,segmentPoint] + ring + +theorem segment_line_level_zero (a b p : Plane) (hp : p=a ∨ p=b) (t : ℝ) : + det2 (b-a) (segmentPoint a b t-p)=0 := by + rcases hp with rfl | rfl <;> dsimp [det2,segmentPoint] <;> ring + +namespace VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +theorem spokePort_is_piece_endpoint (j : BipartiteVertex m n) (e : IncidentEdges j) : + V.spokePort j e=V.vertices e.val (V.spokeIndex j e) ∨ + V.spokePort j e=V.vertices e.val (V.spokeIndex j e+1) := by + unfold spokePort drawingSpokePort spokeIndex + split_ifs + · exact Or.inl (V.vertices_first e.val).symm + · right + have hp := V.pieces_pos e.val + rw [show V.pieces e.val-1+1=V.pieces e.val by omega] + exact (V.vertices_last e.val).symm + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem continuous_tangentPort (j : BipartiteVertex m n) (e : IncidentEdges j) : + Continuous (C.tangentPort j e) := by + change Continuous (fun ε : ℝ => V.spokePort j e+ε • normalShift (V.spokeDirection j e)) + fun_prop + +theorem tangentPort_zero (j : BipartiteVertex m n) (e : IncidentEdges j) : + C.tangentPort j e 0=V.spokePort j e := by simp [tangentPort] + +theorem tangentPort_level (j : BipartiteVertex m n) (e : IncidentEdges j) (ε : ℝ) : + det2 (V.spokeDirection j e) (C.tangentPort j e ε-V.spokePort j e)=ε := by + simp only [tangentPort,add_sub_cancel_left,det2_smul_right, + det2_normalShift _ (V.spokeDirection_ne_zero j e),mul_one] + +theorem connector_level (j : BipartiteVertex m n) (e : IncidentEdges j) (ε t : ℝ) : + det2 (V.spokeDirection j e) + (segmentPoint (C.shiftedPort j e ε) (C.tangentPort j e ε) t-V.spokePort j e)=ε := by + rw [det2_segmentPoint_sub,C.shiftedPort_level,C.tangentPort_level] + ring + +theorem connector_avoids_incident_piece (j : BipartiteVertex m n) (e : IncidentEdges j) + (ε : ℝ) (hε : ε ≠ 0) : + ¬ ClosedSegmentsMeet (V.vertices e.val (V.spokeIndex j e)) + (V.vertices e.val (V.spokeIndex j e+1)) (C.shiftedPort j e ε) (C.tangentPort j e ε) := by + rintro ⟨s,hs,t,ht,he⟩ + have hzero := segment_line_level_zero (V.vertices e.val (V.spokeIndex j e)) + (V.vertices e.val (V.spokeIndex j e+1)) (V.spokePort j e) (V.spokePort_is_piece_endpoint j e) s + change det2 (V.spokeDirection j e) + (segmentPoint (V.vertices e.val (V.spokeIndex j e)) (V.vertices e.val (V.spokeIndex j e+1)) s-V.spokePort j e)=0 at hzero + rw [he,C.connector_level] at hzero + exact hε hzero + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ConnectorTrackAvoidance.lean b/lean/OAI/Combinatorics/Crossing/ConnectorTrackAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..425c10264d9a3ec4b35d9732bab9e5c1778322d6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ConnectorTrackAvoidance.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.ConnectorSupportingLines + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped Topology +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_nonincident_connector_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j (f : IncidentEdges j) e (i : Fin (V.pieces e)), + ¬ (e=f.val ∧ i.val=V.spokeIndex j f) → + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + classical + let Bad := Σ j : BipartiteVertex m n, Σ f : IncidentEdges j, Σ e : BipartiteEdge m n, + {i : Fin (V.pieces e) // ¬ (e=f.val ∧ i.val=V.spokeIndex j f)} + have hnot (b : Bad) : ¬ ClosedSegmentsMeet + (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) + (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) := by + rintro ⟨s,hs,t,ht,he⟩ + have he0 : segmentPoint (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) t=V.spokePort b.1 b.2.1 := by + unfold segmentPoint + rw [← add_smul] + simp + rw [he0] at he + have hx : V.spokePort b.1 b.2.1 ∈ + segment ℝ (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) := by + rw [← Path.range_segment] + refine ⟨⟨s,hs⟩,?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + exact b.2.2.2.property (V.spokePort_piece_unique hnorm b.1 b.2.1 b.2.2.1 b.2.2.2.val hx) + have hevent (b : Bad) := eventually_moving_disjoint_segments + (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) + (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) (C.shiftedPort b.1 b.2.1) (C.tangentPort b.1 b.2.1) + (C.continuous_shiftedPort b.1 b.2.1).continuousAt (C.continuous_tangentPort b.1 b.2.1).continuousAt + (C.shiftedPort_zero b.1 b.2.1) (C.tangentPort_zero b.1 b.2.1) (hnot b) + have hex (b : Bad) := Metric.eventually_nhds_iff.mp (hevent b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j f e i hi + exact hprop ⟨j,f,e,⟨i,hi⟩⟩ (by simpa [Real.dist_eq] using hε.trans (hbound ⟨j,f,e,⟨i,hi⟩⟩ (Finset.mem_univ _))) + +theorem exists_all_connector_track_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j (f : IncidentEdges j) e (i : Fin (V.pieces e)), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + obtain ⟨δ,hδ,hh⟩ := C.exists_nonincident_connector_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall j f e i + by_cases hi : e=f.val ∧ i.val=V.spokeIndex j f + · rcases hi with ⟨rfl,hi⟩ + simpa only [hi] using C.connector_avoids_incident_piece j f ε hε + · exact hh ε hsmall j f e i hi + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ConstructAdjacentSurgery.lean b/lean/OAI/Combinatorics/Crossing/ConstructAdjacentSurgery.lean new file mode 100644 index 0000000000000000000000000000000000000000..a879c9f5b57fa9239bdfa626bed13f143cab2a99 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ConstructAdjacentSurgery.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.AdjacentSurgeryPointRemoval +import OAI.Combinatorics.Crossing.ExtraDrawingSubdivision +import OAI.Combinatorics.Crossing.CrossingDiskOwners + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_adjacentSurgery_continuousDrawing (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (p q : C.InnerIndex) (hpq : p ≠ q) (hadj : p.1.1=q.1.1 ∨ p.1.2=q.1.2) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + ∃ A : ContinuousDrawing m n, A.vertex=v ∧ + (∀ e, HasFiniteAffineCover (A.edge e)) ∧ + (∀ e, x ∉ Set.range (A.edge e)) ∧ + (∀ e, e ≠ p.1 → e ≠ q.1 → ∀ t, A.edge e t=E.assembledEdge v e t) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + obtain ⟨P,hmark,hport⟩ := E.exists_assembled_port_subdivision v hvinj hv hdet + obtain ⟨Kp⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport p + obtain ⟨Kq⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport q + have hemb := crossingSurgeryGraph_embedding C P hmark hport p q hm hcross + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + refine ⟨A,rfl,adjacentSurgeryDrawing_hasFiniteAffineCover Kp Kq hm hpq hadj hv hemb,?_,?_⟩ + · apply adjacentSurgeryDrawing_avoids_crossing Kp Kq hm hpq hadj hv hemb x hxp hxq + intro e hep heq hx + exact Set.disjoint_left.mp (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + hx (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1 + · intro e hep heq t + exact congrArg (fun γ => γ t) (adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingCoordinates.lean b/lean/OAI/Combinatorics/Crossing/CrossingCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ae7c1838cfbfde354b8cf239e14ff1f5ddba39b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingCoordinates.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.Crossing.PlanarDeterminant +import Mathlib.Tactic.FunProp +import Mathlib.Topology.Homeomorph.Defs + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def crossingCoordinates (o u v x : Plane) : Plane := + (det2 (x-o) v/det2 u v,det2 u (x-o)/det2 u v) + +def crossingCoordinateInverse (o u v s : Plane) : Plane := o+s.1 • u+s.2 • v + +theorem crossingCoordinates_left_inverse (o u v : Plane) (h : det2 u v ≠ 0) (x : Plane) : + crossingCoordinateInverse o u v (crossingCoordinates o u v x)=x := by + have hc := mul_inv_cancel₀ h + apply Prod.ext + · dsimp [crossingCoordinateInverse,crossingCoordinates,det2] at * + simp only [div_eq_mul_inv] + linear_combination (x.1-o.1)*hc + · dsimp [crossingCoordinateInverse,crossingCoordinates,det2] at * + simp only [div_eq_mul_inv] + linear_combination (x.2-o.2)*hc + +theorem crossingCoordinates_right_inverse (o u v : Plane) (h : det2 u v ≠ 0) (s : Plane) : + crossingCoordinates o u v (crossingCoordinateInverse o u v s)=s := by + have hc := mul_inv_cancel₀ h + apply Prod.ext + · dsimp [crossingCoordinateInverse,crossingCoordinates,det2] at * + simp only [div_eq_mul_inv] + linear_combination s.1*hc + · dsimp [crossingCoordinateInverse,crossingCoordinates,det2] at * + simp only [div_eq_mul_inv] + linear_combination s.2*hc + +theorem crossingCoordinates_continuous (o u v : Plane) : Continuous (crossingCoordinates o u v) := by + unfold crossingCoordinates det2 + fun_prop + +theorem crossingCoordinateInverse_continuous (o u v : Plane) : Continuous (crossingCoordinateInverse o u v) := by + unfold crossingCoordinateInverse + fun_prop + +def crossingCoordinateHomeomorph (o u v : Plane) (h : det2 u v ≠ 0) : Plane ≃ₜ Plane where + toFun := crossingCoordinates o u v + invFun := crossingCoordinateInverse o u v + left_inv := crossingCoordinates_left_inverse o u v h + right_inv := crossingCoordinates_right_inverse o u v h + continuous_toFun := crossingCoordinates_continuous o u v + continuous_invFun := crossingCoordinateInverse_continuous o u v + +def crossingCoordinateChart (o u v : Plane) (h : det2 u v ≠ 0) + (U : Set Plane) (hU : IsOpen U) : OpenPartialHomeomorph Plane Plane where + toFun := crossingCoordinates o u v + invFun := crossingCoordinateInverse o u v + source := crossingCoordinates o u v ⁻¹' U + target := U + map_source' := fun {_} hx => hx + map_target' := fun {s} hs => by + change crossingCoordinates o u v (crossingCoordinateInverse o u v s) ∈ U + rw [crossingCoordinates_right_inverse o u v h] + exact hs + left_inv' := fun {x} _ => crossingCoordinates_left_inverse o u v h x + right_inv' := fun {s} _ => crossingCoordinates_right_inverse o u v h s + continuousOn_toFun := (crossingCoordinates_continuous o u v).continuousOn + continuousOn_invFun := (crossingCoordinateInverse_continuous o u v).continuousOn + open_source := hU.preimage (crossingCoordinates_continuous o u v) + open_target := hU + +@[simp] theorem crossingCoordinates_origin (o u v : Plane) : crossingCoordinates o u v o=(0,0) := by + simp [crossingCoordinates] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingCutWalks.lean b/lean/OAI/Combinatorics/Crossing/CrossingCutWalks.lean new file mode 100644 index 0000000000000000000000000000000000000000..455fa71226d6eacadbd4e794515cf29aa5510d10 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingCutWalks.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.CrossingPortClearance +import OAI.Combinatorics.Crossing.DrawingWalkCutTraces +import OAI.Combinatorics.Crossing.ExteriorSegmentGraph + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem crossing_cut_traces_disjoint (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (p : C.InnerIndex) (i j : Fin ((P p.1).pieces+1)) + (hi : (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p)) + (hj : (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p)) : + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take i.val))) (C.crossingDisk p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop j.val))) (C.crossingDisk p) := by + have hki : (drawingEdgeWalk P p.1).getVert i.val=E.assembledEdge v p.1 ((P p.1).knot i) := + (drawingEdgeWalk_getVert P p.1 i.val (by omega)).trans ((P p.1).vertices_at i) + have hkj : (drawingEdgeWalk P p.1).getVert j.val=E.assembledEdge v p.1 ((P p.1).knot j) := + (drawingEdgeWalk_getVert P p.1 j.val (by omega)).trans ((P p.1).vertices_at j) + have hu := hki.symm.trans hi + have hw := hkj.symm.trans hj + constructor + · apply Set.disjoint_left.mpr + intro x hx hxin + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P p.1 i hx + exact E.assembled_crossing_port_clearance v hv p _ _ hu hw t (Or.inl ht.2) (he.symm ▸ hxin) + · apply Set.disjoint_left.mpr + intro x hx hxin + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P p.1 j hx + exact E.assembled_crossing_port_clearance v hv p _ _ hu hw t (Or.inr ht.1) (he.symm ▸ hxin) + +theorem exists_exterior_crossing_cuts (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p : C.InnerIndex) : + ∃ i j : Fin ((P p.1).pieces+1), i < j ∧ + (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p) ∧ + (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take i.val))) (C.crossingDisk p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop j.val))) (C.crossingDisk p) := by + obtain ⟨i,j,hij,hi,hj⟩ := E.crossing_port_walk_indices v hvinj hv hdet P hport p + exact ⟨i,j,hij,hi,hj,E.crossing_cut_traces_disjoint v hvinj hv hdet P p i j hi hj⟩ + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingDiskCount.lean b/lean/OAI/Combinatorics/Crossing/CrossingDiskCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9d7c6a41102f32c1d6d29fce76a8c601ace1f89 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingDiskCount.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.CrossingDiskUniqueness +import Mathlib.Data.Set.Card + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +open scoped Classical +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +def chordCrossingOrigin (C : DrawingPassages D) (x : Plane) : Plane := + if hx : x ∈ C.chordCrossings then (C.chord_crossing_original_mark hx).choose.val else 0 + +theorem chordCrossingOrigin_mapsTo (C : DrawingPassages D) : + Set.MapsTo C.chordCrossingOrigin C.chordCrossings (crossingPoints D.toContinuousDrawing) := by + intro x hx + have hh := (C.chord_crossing_original_mark hx).choose_spec.1 + simpa only [chordCrossingOrigin,dite_eq_left hx] using hh + +theorem chordCrossingOrigin_injOn (C : DrawingPassages D) : + Set.InjOn C.chordCrossingOrigin C.chordCrossings := by + intro x hx y hy he + let w : DrawingMark D := (C.chord_crossing_original_mark hx).choose + let v : DrawingMark D := (C.chord_crossing_original_mark hy).choose + have hwx : x ∈ C.chordCrossingsAt w := (C.chord_crossing_original_mark hx).choose_spec.2 + have hvy : y ∈ C.chordCrossingsAt v := (C.chord_crossing_original_mark hy).choose_spec.2 + have hvw : w=v := by + apply Subtype.ext + simpa only [chordCrossingOrigin,dite_eq_left hx,dite_eq_left hy] using he + rw [← hvw] at hvy + exact (C.chordCrossingsAt_subsingleton w) hwx hvy + +theorem chordCrossings_finite (C : DrawingPassages D) : C.chordCrossings.Finite := + Set.Finite.of_injOn C.chordCrossingOrigin_mapsTo C.chordCrossingOrigin_injOn D.crossings_finite + +theorem chordCrossings_ncard_le (C : DrawingPassages D) : + C.chordCrossings.ncard ≤ finiteCrossingCount D := by + calc + C.chordCrossings.ncard ≤ (crossingPoints D.toContinuousDrawing).ncard := + Set.ncard_le_ncard_of_injOn C.chordCrossingOrigin C.chordCrossingOrigin_mapsTo + C.chordCrossingOrigin_injOn D.crossings_finite + _ = finiteCrossingCount D := Set.ncard_eq_toFinset_card _ D.crossings_finite + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingDiskIncidence.lean b/lean/OAI/Combinatorics/Crossing/CrossingDiskIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..2428ba8acd801fc40a1dea197fd07c28907431e6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingDiskIncidence.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.Crossing.InnerDrawingPassages + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem innerIndex_eq_of_edge_mark (C : DrawingPassages D) (p q : C.InnerIndex) + (he : p.1=q.1) (hm : C.innerMark p=C.innerMark q) : p=q := by + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + change e=f at he + subst f + congr 1 + apply Subtype.ext + exact (C.increasing e).injective (D.edge_injective e (congrArg Subtype.val hm)) + +theorem incomingPort_injective (C : DrawingPassages D) : Function.Injective C.incomingPort := by + intro p q he + apply C.innerIndex_eq_of_edge_mark p q (congrArg (fun x : C.Port => x.1.1) he) + have hh := congrArg C.portMark he + simpa only [C.incomingPort_mark] using hh + +theorem outgoingPort_injective (C : DrawingPassages D) : Function.Injective C.outgoingPort := by + intro p q he + apply C.innerIndex_eq_of_edge_mark p q (congrArg (fun x : C.Port => x.1.1) he) + have hh := congrArg C.portMark he + simpa only [C.outgoingPort_mark] using hh + +theorem incomingPort_ne_outgoingPort (C : DrawingPassages D) (p q : C.InnerIndex) : + C.incomingPort p ≠ C.outgoingPort q := by + intro he + have hh : true=false := congrArg Prod.snd he + cases hh + +theorem incomingPoint_on_circle (C : DrawingPassages D) (p : C.InnerIndex) : + squaredLength (C.portPoint (C.incomingPort p)-(C.innerMark p).val)=C.radius^2 := by + simpa only [C.incomingPort_mark] using C.portPoint_on_circle (C.incomingPort p) + +theorem outgoingPoint_on_circle (C : DrawingPassages D) (p : C.InnerIndex) : + squaredLength (C.portPoint (C.outgoingPort p)-(C.innerMark p).val)=C.radius^2 := by + simpa only [C.outgoingPort_mark] using C.portPoint_on_circle (C.outgoingPort p) + +theorem crossing_chords_transverse_at_mark (C : DrawingPassages D) (p q : C.InnerIndex) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + SegmentPairTransverse (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) := by + apply round_circle_chords_transverse (C.innerMark p).val _ _ _ _ C.radius + · exact C.incomingPoint_on_circle p + · exact C.outgoingPoint_on_circle p + · simpa only [hm] using C.incomingPoint_on_circle q + · simpa only [hm] using C.outgoingPoint_on_circle q + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p p) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort q q) + · exact C.portPoint_injective.ne (C.incomingPort_injective.ne hpq) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p q) + · exact C.portPoint_injective.ne (Ne.symm (C.incomingPort_ne_outgoingPort q p)) + · exact C.portPoint_injective.ne (C.outgoingPort_injective.ne hpq) + +theorem innerMark_no_triples (C : DrawingPassages D) (p q r : C.InnerIndex) + (hpq : p ≠ q) (hpr : p ≠ r) (hqr : q ≠ r) + (hpqM : C.innerMark p=C.innerMark q) (hprM : C.innerMark p=C.innerMark r) : False := by + have heq : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hpqM) + have her : p.1 ≠ r.1 := fun he => hpr (C.innerIndex_eq_of_edge_mark p r he hprM) + have hqrM : C.innerMark q=C.innerMark r := hpqM.symm.trans hprM + have hfr : q.1 ≠ r.1 := fun he => hqr (C.innerIndex_eq_of_edge_mark q r he hqrM) + have hp : (C.innerMark p).val ∈ edgeInterior D.toContinuousDrawing p.1 := + ⟨C.node p.1 p.2.val,C.inner_parameter_interior p,rfl⟩ + have hq : (C.innerMark p).val ∈ edgeInterior D.toContinuousDrawing q.1 := by + rw [hpqM] + exact ⟨C.node q.1 q.2.val,C.inner_parameter_interior q,rfl⟩ + have hr : (C.innerMark p).val ∈ edgeInterior D.toContinuousDrawing r.1 := by + rw [hprM] + exact ⟨C.node r.1 r.2.val,C.inner_parameter_interior r,rfl⟩ + have hmem : (C.innerMark p).val ∈ edgeInterior D.toContinuousDrawing p.1 ∩ + edgeInterior D.toContinuousDrawing q.1 ∩ edgeInterior D.toContinuousDrawing r.1 := ⟨⟨hp,hq⟩,hr⟩ + rw [D.no_triples p.1 q.1 r.1 heq her hfr] at hmem + exact hmem + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingDiskNeighborhood.lean b/lean/OAI/Combinatorics/Crossing/CrossingDiskNeighborhood.lean new file mode 100644 index 0000000000000000000000000000000000000000..43c1f03ddd37e472e5e0d0ddbf423461ab909332 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingDiskNeighborhood.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.Crossing.AssembledNoTriples + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +def crossingDisk (C : DrawingPassages D) (p : C.InnerIndex) : Set Plane := + {x | squaredLength (x-(C.innerMark p).val) < C.radius^2} + +theorem crossingDisk_isOpen (C : DrawingPassages D) (p : C.InnerIndex) : IsOpen (C.crossingDisk p) := by + apply isOpen_lt _ continuous_const + unfold squaredLength + fun_prop + +theorem crossingDisk_subset_closed (C : DrawingPassages D) (p : C.InnerIndex) : + C.crossingDisk p ⊆ closedRoundDisk (C.innerMark p).val C.radius := by + intro x hx + exact (show squaredLength (x-(C.innerMark p).val) < C.radius^2 from hx).le + +theorem crossingDisk_disjoint_vertex_disk (C : DrawingPassages D) (p : C.InnerIndex) + (j : BipartiteVertex m n) : + Disjoint (C.crossingDisk p) (closedRoundDisk (D.vertex j) C.radius) := by + have hn : C.innerMark p ≠ C.vertexMark j := by + intro he + exact crossing_not_vertex D (C.innerMark p).val (C.innerMark_is_crossing p) j (congrArg Subtype.val he) + exact (C.disks_disjoint _ _ hn).mono (C.crossingDisk_subset_closed p) Set.Subset.rfl + +theorem crossingChord_openTrace_iff (C : DrawingPassages D) (p : C.InnerIndex) + (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ Set.range (C.crossingChord p) ↔ + x ∈ openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := by + constructor + · rintro ⟨t,ht⟩ + have ht0 : t ≠ 0 := by + intro he + subst t + rw [Path.source] at ht + change squaredLength (x-(C.innerMark p).val) < C.radius^2 at hx + rw [← ht,C.incomingPoint_on_circle] at hx + exact lt_irrefl _ hx + have ht1 : t ≠ 1 := by + intro he + subst t + rw [Path.target] at ht + change squaredLength (x-(C.innerMark p).val) < C.radius^2 at hx + rw [← ht,C.outgoingPoint_on_circle] at hx + exact lt_irrefl _ hx + refine ⟨t.val,⟨?_,?_⟩,?_⟩ + · exact lt_of_le_of_ne t.property.1 (fun he => ht0 (Subtype.ext he.symm)) + · exact lt_of_le_of_ne t.property.2 (fun he => ht1 (Subtype.ext he)) + · simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + · rintro ⟨t,ht,he⟩ + refine ⟨⟨t,ht.1.le,ht.2.le⟩,?_⟩ + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem assembled_range_in_crossingDisk (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ Set.range (E.assembledEdge v p.1) ↔ x ∈ Set.range (C.crossingChord p) := by + constructor + · intro he + rcases (E.assembledEdge_range_iff v p.1 x).mp he with (he | ⟨i,hi,he⟩ | ⟨q,hq,he⟩) | he + · exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hx (C.vertex_spoke_range_in_disk v hv _ (C.startPortAt p.1) he)) + · obtain ⟨t,rfl⟩ := he + exact False.elim (hx.not_ge (E.outside_open_disks i t (C.innerMark p))) + · have hm : C.innerMark q=C.innerMark p := by + by_contra hn + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.crossingChord_range_subset_disk q he) (C.crossingDisk_subset_closed p hx) + have hqp := C.innerIndex_eq_of_edge_mark q p hq hm + exact hqp ▸ he + · rw [endSpoke_range] at he + exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hx (C.vertex_spoke_range_in_disk v hv _ (C.endPortAt p.1) he)) + · intro he + apply (E.assembledEdge_range_iff v p.1 x).mpr + exact Or.inl (Or.inr (Or.inr ⟨p,rfl,he⟩)) + +theorem assembled_trace_in_crossingDisk (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ edgeInterior (E.assembledDrawing v hvinj hv) p.1 ↔ + x ∈ openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := by + have havoid : ∀ j, x ≠ v j := by + intro j he + exact Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p j) hx (he.symm ▸ (hv j).le) + rw [← C.crossingChord_openTrace_iff p x hx,← E.assembled_range_in_crossingDisk v hv p x hx] + constructor + · rintro ⟨t,ht,he⟩ + exact ⟨t,he⟩ + · rintro ⟨t,he⟩ + have ht0 : t ≠ 0 := by + intro ht + subst t + rw [Path.source] at he + exact havoid _ he.symm + have ht1 : t ≠ 1 := by + intro ht + subst t + rw [Path.target] at he + exact havoid _ he.symm + exact ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,he⟩ + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingDiskOwners.lean b/lean/OAI/Combinatorics/Crossing/CrossingDiskOwners.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad10b1b6050094896dcfbd7e0bf53ec66c49a004 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingDiskOwners.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.OrderedCrossingPorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_in_crossingDisk_chord (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (p : C.InnerIndex) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hxin : x ∈ C.crossingDisk p) : + ∃ r : C.InnerIndex, r.1=e ∧ C.innerMark r=C.innerMark p ∧ x ∈ Set.range (C.crossingChord r) := by + rcases (E.assembledEdge_range_iff v e x).mp hx with (hx | ⟨i,hi,hx⟩ | ⟨r,hr,hx⟩) | hx + · exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hxin (C.vertex_spoke_range_in_disk v hv _ (C.startPortAt e) hx)) + · obtain ⟨t,rfl⟩ := hx + exact False.elim (hxin.not_ge (E.outside_open_disks i t (C.innerMark p))) + · refine ⟨r,hr,?_,hx⟩ + by_contra hn + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.crossingChord_range_subset_disk r hx) (C.crossingDisk_subset_closed p hxin) + · rw [endSpoke_range] at hx + exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hxin (C.vertex_spoke_range_in_disk v hv _ (C.endPortAt e) hx)) + +theorem assembled_crossingDisk_owner (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : BipartiteEdge m n) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hxin : x ∈ C.crossingDisk p) : e=p.1 ∨ e=q.1 := by + obtain ⟨r,hr,hrm,hxr⟩ := E.assembled_in_crossingDisk_chord v hv e p x hx hxin + rcases C.innerIndex_at_mark_pair p q r hpq hm hrm.symm with rfl | rfl + · exact Or.inl hr.symm + · exact Or.inr hr.symm + +theorem assembled_other_edge_avoids_crossingDisk (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) : + Disjoint (Set.range (E.assembledEdge v e)) (C.crossingDisk p) := by + apply Set.disjoint_left.mpr + intro x hx hxin + rcases E.assembled_crossingDisk_owner v hv p q hpq hm e x hx hxin with h | h + · exact hep h + · exact heq h + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingDiskUniqueness.lean b/lean/OAI/Combinatorics/Crossing/CrossingDiskUniqueness.lean new file mode 100644 index 0000000000000000000000000000000000000000..012e3371f7abd4865ec3d077c45101d72ce8f8e3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingDiskUniqueness.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.DiskFillingContainment +import OAI.Combinatorics.Crossing.SegmentIntersectionUnique + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem innerIndex_at_mark_pair (C : DrawingPassages D) (p q r : C.InnerIndex) + (hpq : p ≠ q) (hpqM : C.innerMark p=C.innerMark q) (hprM : C.innerMark p=C.innerMark r) : + r=p ∨ r=q := by + by_cases hrp : r=p + · exact Or.inl hrp + by_cases hrq : r=q + · exact Or.inr hrq + exact False.elim (C.innerMark_no_triples p q r hpq (Ne.symm hrp) (Ne.symm hrq) hpqM hprM) + +def chordCrossingsAt (C : DrawingPassages D) (w : DrawingMark D) : Set Plane := + {x | ∃ p q : C.InnerIndex, p ≠ q ∧ C.innerMark p=w ∧ C.innerMark q=w ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q)} + +theorem chordCrossingsAt_subsingleton (C : DrawingPassages D) (w : DrawingMark D) : + (C.chordCrossingsAt w).Subsingleton := by + rintro x ⟨p,q,hpq,hp,hq,hxp,hxq⟩ y ⟨r,s,hrs,hr,hs,hyr,hys⟩ + have hpm : C.innerMark p=C.innerMark q := hp.trans hq.symm + have hrpair := C.innerIndex_at_mark_pair p q r hpq hpm (hp.trans hr.symm) + have hspair := C.innerIndex_at_mark_pair p q s hpq hpm (hp.trans hs.symm) + have hunique := transverse_segment_intersection_subsingleton _ _ _ _ + (C.crossing_chords_transverse_at_mark p q hpq hpm) + rcases hrpair with rfl | rfl <;> rcases hspair with rfl | rfl + · exact False.elim (hrs rfl) + · exact hunique ⟨hxp,hxq⟩ ⟨hyr,hys⟩ + · exact hunique ⟨hxp,hxq⟩ ⟨hys,hyr⟩ + · exact False.elim (hrs rfl) + +theorem chord_meeting_marks_eq (C : DrawingPassages D) (p q : C.InnerIndex) {x : Plane} + (hp : x ∈ Set.range (C.crossingChord p)) (hq : x ∈ Set.range (C.crossingChord q)) : + C.innerMark p=C.innerMark q := by + by_contra h + exact Set.disjoint_left.mp (C.crossingChords_disjoint_of_marks_ne p q h) hp hq + +def chordCrossings (C : DrawingPassages D) : Set Plane := + {x | ∃ p q : C.InnerIndex, p ≠ q ∧ x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q)} + +theorem chord_crossing_original_mark (C : DrawingPassages D) {x : Plane} (hx : x ∈ C.chordCrossings) : + ∃ w : DrawingMark D, w.val ∈ crossingPoints D.toContinuousDrawing ∧ x ∈ C.chordCrossingsAt w := by + obtain ⟨p,q,hpq,hp,hq⟩ := hx + refine ⟨C.innerMark p,C.innerMark_is_crossing p,p,q,hpq,rfl,?_,hp,hq⟩ + exact (C.chord_meeting_marks_eq p q hp hq).symm + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingIncidence.lean b/lean/OAI/Combinatorics/Crossing/CrossingIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fdcb827153aa57ae47ee53c5d880f5b0c914a41 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingIncidence.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Algebra.BigOperators.Group.Finset.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators Classical +variable {m n : ℕ} + +theorem crossingCount_attainment (D₀ : AdmissibleDrawing m n) : + ∃ D : AdmissibleDrawing m n, crossingCount D = ordinaryCrossingNumber m n := by + exact csInf_mem (show (Set.range (@crossingCount m n)).Nonempty from + ⟨crossingCount D₀, D₀, rfl⟩) + +theorem ordinaryCrossingNumber_le_count (D : AdmissibleDrawing m n) : + ordinaryCrossingNumber m n ≤ crossingCount D := + csInf_le' ⟨D, rfl⟩ + +theorem crossing_incident_iff (D : AdmissibleDrawing m n) (x : Plane) + (e f : BipartiteEdge m n) (hef : e ≠ f) + (he : x ∈ edgeInterior D.toContinuousDrawing e) + (hf : x ∈ edgeInterior D.toContinuousDrawing f) (g : BipartiteEdge m n) : + x ∈ edgeInterior D.toContinuousDrawing g ↔ g = e ∨ g = f := by + constructor + · intro hg + by_contra hh + have hge : e ≠ g := by tauto + have hgf : f ≠ g := by tauto + have hmem : x ∈ edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f ∩ + edgeInterior D.toContinuousDrawing g := ⟨⟨he,hf⟩,hg⟩ + rw [D.no_triples e f g hef hge hgf] at hmem + exact hmem + · rintro (rfl | rfl) <;> assumption + +theorem crossing_two_edges (D : AdmissibleDrawing m n) (x : Plane) + (hx : x ∈ crossingPoints D.toContinuousDrawing) : + ∃ e f : BipartiteEdge m n, e ≠ f ∧ + ∀ g, x ∈ edgeInterior D.toContinuousDrawing g ↔ g = e ∨ g = f := by + obtain ⟨e,f,hef,he,hf⟩ := hx + exact ⟨e,f,hef,crossing_incident_iff D x e f hef he hf⟩ + +def pairCrossings (D : AdmissibleDrawing m n) (e f : BipartiteEdge m n) : Finset Plane := + D.crossings_finite.toFinset.filter (fun x => e ≠ f ∧ + x ∈ edgeInterior D.toContinuousDrawing e ∧ x ∈ edgeInterior D.toContinuousDrawing f) + +theorem pairCrossings_self (D : AdmissibleDrawing m n) (e : BipartiteEdge m n) : + pairCrossings D e e = ∅ := by + simp [pairCrossings] + +theorem pairCrossings_comm (D : AdmissibleDrawing m n) (e f : BipartiteEdge m n) : + pairCrossings D e f = pairCrossings D f e := by + ext x + simp only [pairCrossings, Finset.mem_filter] + tauto + +theorem crossing_ordered_incidence (D : AdmissibleDrawing m n) (x : Plane) + (hx : x ∈ crossingPoints D.toContinuousDrawing) : + (∑ e : BipartiteEdge m n, ∑ f : BipartiteEdge m n, + if e ≠ f ∧ x ∈ edgeInterior D.toContinuousDrawing e ∧ + x ∈ edgeInterior D.toContinuousDrawing f then (1 : ℕ) else 0) = 2 := by + classical + obtain ⟨e,f,hef,hinc⟩ := crossing_two_edges D x hx + simp_rw [hinc] + have hp : ∀ a b : BipartiteEdge m n, + (a ≠ b ∧ (a = e ∨ a = f) ∧ (b = e ∨ b = f)) ↔ + ((a = e ∧ b = f) ∨ (a = f ∧ b = e)) := by + intro a b + constructor + · rintro ⟨hab, rfl | rfl, rfl | rfl⟩ <;> tauto + · rintro (⟨rfl,rfl⟩ | ⟨rfl,rfl⟩) <;> tauto + simp_rw [hp] + have hi : ∀ a b : BipartiteEdge m n, + (if (a = e ∧ b = f) ∨ (a = f ∧ b = e) then (1 : ℕ) else 0) = + (if a = e ∧ b = f then 1 else 0) + (if a = f ∧ b = e then 1 else 0) := by + intro a b + split_ifs <;> simp_all + simp_rw [hi, Finset.sum_add_distrib] + simp [ite_and] + +theorem sum_pairCrossings_card (D : AdmissibleDrawing m n) : + (∑ e : BipartiteEdge m n, ∑ f : BipartiteEdge m n, (pairCrossings D e f).card) = + 2 * crossingCount D := by + classical + simp only [pairCrossings, Finset.card_filter] + rw [Finset.sum_comm] + conv_lhs => arg 2; ext f; rw [Finset.sum_comm] + rw [Finset.sum_comm] + have he : ∀ x ∈ D.crossings_finite.toFinset, + (∑ f : BipartiteEdge m n, ∑ e : BipartiteEdge m n, + if e ≠ f ∧ x ∈ edgeInterior D.toContinuousDrawing e ∧ + x ∈ edgeInterior D.toContinuousDrawing f then (1 : ℕ) else 0) = 2 := by + intro x hx + rw [Finset.sum_comm] + exact crossing_ordered_incidence D x (by simpa using hx) + simp_rw [Finset.sum_congr rfl he] + simp [crossingCount, Nat.mul_comm] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingPortClearance.lean b/lean/OAI/Combinatorics/Crossing/CrossingPortClearance.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdd0e55803c209bdc5295c2e6e0176d974a76cc9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingPortClearance.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.OrderedCrossingPorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem crossingChord_parameter_interior (C : DrawingPassages D.toFiniteIntersectionDrawing) (p : C.InnerIndex) + (t : unitInterval) (ht : C.crossingChord p t ∈ C.crossingDisk p) : + t ∈ Set.Ioo (0 : unitInterval) 1 := by + have ht0 : t ≠ 0 := by + intro he + subst t + change squaredLength (C.crossingChord p 0-(C.innerMark p).val) < C.radius^2 at ht + rw [Path.source,C.incomingPoint_on_circle] at ht + exact lt_irrefl _ ht + have ht1 : t ≠ 1 := by + intro he + subst t + change squaredLength (C.crossingChord p 1-(C.innerMark p).val) < C.radius^2 at ht + rw [Path.target,C.outgoingPoint_on_circle] at ht + exact lt_irrefl _ ht + exact ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_crossing_disk_parameter_between (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (u w : unitInterval) + (hu : E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p)) + (hw : E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p)) + (t : unitInterval) (ht : E.assembledEdge v p.1 t ∈ C.crossingDisk p) : u < t ∧ t < w := by + obtain ⟨f,hf,he⟩ := E.assembledEdge_contains_chord v p + have h0 : f 0=u := E.assembledEdge_injective v hv p.1 + (((he 0).trans (C.crossingChord p).source).trans hu.symm) + have h1 : f 1=w := E.assembledEdge_injective v hv p.1 + (((he 1).trans (C.crossingChord p).target).trans hw.symm) + have hmem : E.assembledEdge v p.1 t ∈ Set.range (C.crossingChord p) := + (E.assembled_range_in_crossingDisk v hv p _ ht).mp ⟨t,rfl⟩ + obtain ⟨s,hs⟩ := hmem + have hsint := C.crossingChord_parameter_interior p s (hs.symm ▸ ht) + have hst : f s=t := E.assembledEdge_injective v hv p.1 ((he s).trans hs) + exact ⟨by simpa only [h0,hst] using hf hsint.1,by simpa only [h1,hst] using hf hsint.2⟩ + +theorem assembled_crossing_port_clearance (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (u w : unitInterval) + (hu : E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p)) + (hw : E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p)) + (t : unitInterval) (ht : t ≤ u ∨ w ≤ t) : E.assembledEdge v p.1 t ∉ C.crossingDisk p := by + intro hmem + have hbetween := E.assembled_crossing_disk_parameter_between v hv p u w hu hw t hmem + rcases ht with ht | ht + · exact hbetween.1.not_ge ht + · exact hbetween.2.not_ge ht + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingReconnection.lean b/lean/OAI/Combinatorics/Crossing/CrossingReconnection.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0b1c68e86c6233095c5a06d3199267e3fa2a2ab --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingReconnection.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.Crossing.SegmentCrossingCoordinates +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem crossingCoordinates_affine (o u v a b : Plane) (t : ℝ) : + crossingCoordinates o u v (segmentPoint a b t)= + segmentPoint (crossingCoordinates o u v a) (crossingCoordinates o u v b) t := by + apply Prod.ext <;> dsimp [crossingCoordinates,segmentPoint,det2] <;> + simp only [div_eq_mul_inv] <;> ring + +theorem convex_combination_pos (a b t : ℝ) (ha : 0 < a) (hb : 0 < b) + (ht : t ∈ Set.Icc (0 : ℝ) 1) : 0 < (1-t)*a+t*b := by + have hm : 0 < min a b := lt_min ha hb + have hl := mul_le_mul_of_nonneg_left (min_le_left a b) (sub_nonneg.mpr ht.2) + have hr := mul_le_mul_of_nonneg_left (min_le_right a b) ht.1 + nlinarith + +theorem crossing_reconnections_disjoint (a b c d : Plane) (h : SegmentsCrossProperly a b c d) : + Disjoint (segment ℝ c b) (segment ℝ a d) := by + obtain ⟨hd,s,hs,t,ht,hst⟩ := h + let o := segmentPoint a b s + let F := crossingCoordinates o (b-a) (d-c) + have hFa : F a=(-s,0) := by + have he := crossingCoordinates_first_segment a b c d o s 0 hd rfl + simpa only [segmentPoint_zero,zero_sub] using he + have hFb : F b=(1-s,0) := by + have he := crossingCoordinates_first_segment a b c d o s 1 hd rfl + simpa only [segmentPoint_one] using he + have hFc : F c=(0,-t) := by + have he := crossingCoordinates_second_segment a b c d o t 0 hd hst + simpa only [segmentPoint_zero,zero_sub] using he + have hFd : F d=(0,1-t) := by + have he := crossingCoordinates_second_segment a b c d o t 1 hd hst + simpa only [segmentPoint_one] using he + apply Set.disjoint_left.mpr + intro x hleft hright + rw [← Path.range_segment] at hleft hright + obtain ⟨u,hu⟩ := hleft + obtain ⟨v,hv⟩ := hright + have hu' : segmentPoint c b u.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hu + have hv' : segmentPoint a d v.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hv + have hleftF : F x=segmentPoint (0,-t) (1-s,0) u.val := by + rw [← hu'] + exact (crossingCoordinates_affine o (b-a) (d-c) c b u.val).trans (by + change segmentPoint (F c) (F b) u.val=_ + rw [hFc,hFb]) + have hrightF : F x=segmentPoint (-s,0) (0,1-t) v.val := by + rw [← hv'] + exact (crossingCoordinates_affine o (b-a) (d-c) a d v.val).trans (by + change segmentPoint (F a) (F d) v.val=_ + rw [hFa,hFd]) + have hl : 0 < (F x).1-(F x).2 := by + rw [hleftF] + have hh := convex_combination_pos t (1-s) u.val ht.1 (sub_pos.mpr hs.2) u.property + dsimp [segmentPoint] + nlinarith + have hr : (F x).1-(F x).2 < 0 := by + rw [hrightF] + have hh := convex_combination_pos s (1-t) v.val hs.1 (sub_pos.mpr ht.2) v.property + dsimp [segmentPoint] + nlinarith + exact hl.not_ge hr.le + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CrossingSurgeryGraph.lean b/lean/OAI/Combinatorics/Crossing/CrossingSurgeryGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..7549bc2a6929d2cbb7e452148af67e23f642db12 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CrossingSurgeryGraph.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.SegmentAugmentation +import OAI.Combinatorics.Crossing.ReconnectionChords +import OAI.Combinatorics.Crossing.SubdivisionPointEndpoints +import OAI.Combinatorics.Crossing.ExteriorSegmentGraph + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + +def crossingSurgeryGraph (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) : SimpleGraph Plane := + segmentAugmentedGraph (exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p)) + (C.reconnectionStart p q) (C.reconnectionEnd p q) (C.reconnection_endpoints_ne p q) + +theorem crossingSurgeryGraph_embedding (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) + (hmark : ∀ e t, D'.edge e t ∈ drawingMarks D'.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (hport : ∀ e t, D'.edge e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p q : C.InnerIndex) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) : + StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id := by + have hemb := drawingSubdivisionGraph_embedding P hmark + have houtEmb : StraightEdgeEmbedding + (exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p)) id := by + refine ⟨hemb.1,?_⟩ + intro a b c d hab hcd x hx hy + exact hemb.2 a b c d hab.1 hcd.1 x hx hy + apply segmentAugmentedGraph_embedding _ _ _ _ houtEmb (C.crossingDisk p) + · intro x y hxy + exact hxy.2 + · exact C.reconnection_open_in_disk p q hm + · exact C.reconnection_chords_disjoint p q hcross + · intro i x y hxy + constructor + · apply drawingSubdivisionGraph_point_endpoint P _ ?_ x y hxy.1 + intro e t ht + apply hport e t + cases i + · exact ⟨C.incomingPort q,ht.symm⟩ + · exact ⟨C.incomingPort p,ht.symm⟩ + · apply drawingSubdivisionGraph_point_endpoint P _ ?_ x y hxy.1 + intro e t ht + apply hport e t + cases i + · exact ⟨C.outgoingPort p,ht.symm⟩ + · exact ⟨C.outgoingPort q,ht.symm⟩ + +theorem exterior_le_crossingSurgeryGraph (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) : + exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p) ≤ crossingSurgeryGraph C P p q := + le_segmentAugmentedGraph _ _ _ _ + +theorem crossingSurgeryGraph_reconnection_adj (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) (i : Bool) : + (crossingSurgeryGraph C P p q).Adj (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := + segmentAugmentedGraph_added_adj _ _ _ _ i + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CurveDiskIsolation.lean b/lean/OAI/Combinatorics/Crossing/CurveDiskIsolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..add4a3445938b3ecec692aad8175b227f370e9c6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CurveDiskIsolation.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.ParameterNeighborhoods +import OAI.Combinatorics.Crossing.MarkedCurveDisks + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem finite_injective_curve_disk_isolation {E M : Type*} + [Fintype E] [Fintype M] [DecidableEq M] + (γ : E → unitInterval → Plane) (hc : ∀ e, Continuous (γ e)) + (hi : ∀ e, Function.Injective (γ e)) (mark : M → Plane) (hm : Function.Injective mark) : + ∃ δ : E → ℝ, ∃ r : ℝ, (∀ e, 0 < δ e) ∧ 0 < r ∧ + (∀ k l, k ≠ l → Disjoint (closedRoundDisk (mark k) r) (closedRoundDisk (mark l) r)) ∧ + (∀ e k t, γ e t ∈ closedRoundDisk (mark k) r → + ∃ u : unitInterval, γ e u=mark k ∧ t ∈ parameterNeighborhood u (δ e)) ∧ + (∀ e u v, γ e u ∈ Set.range mark → γ e v ∈ Set.range mark → u ≠ v → + Disjoint (closure (parameterNeighborhood u (δ e))) + (closure (parameterNeighborhood v (δ e)))) := by + have hfinite (e : E) : ((γ e) ⁻¹' Set.range mark).Finite := + Set.Finite.preimage (hi e).injOn (Set.finite_range mark) + have hex (e : E) : ∃ δ : ℝ, 0 < δ ∧ + ∀ u v, γ e u ∈ Set.range mark → γ e v ∈ Set.range mark → u ≠ v → + Disjoint (closure (parameterNeighborhood u δ)) (closure (parameterNeighborhood v δ)) := by + let S := (γ e) ⁻¹' Set.range mark + let : Fintype S := (hfinite e).fintype + let : DecidableEq S := Classical.decEq _ + obtain ⟨δ,hδ,_,hd⟩ := finite_parameter_neighborhoods (fun t : S => t.val) Subtype.val_injective + refine ⟨δ,hδ,?_⟩ + intro u v hu hv huv + exact hd ⟨u,hu⟩ ⟨v,hv⟩ (fun he => huv (congrArg Subtype.val he)) + choose δ hδ hseparate using hex + let O : E → M → Set unitInterval := fun e k => + {t | ∃ u, γ e u=mark k ∧ t ∈ parameterNeighborhood u (δ e)} + have hO (e : E) (k : M) : IsOpen (O e k) := by + apply isOpen_iff_mem_nhds.mpr + rintro t ⟨u,hu,ht⟩ + exact Filter.mem_of_superset ((parameterNeighborhood_open u (δ e)).mem_nhds ht) + (fun s hs => ⟨u,hu,hs⟩) + obtain ⟨r,hr,hdisks,hvisits⟩ := finite_curve_mark_isolation γ hc mark hm O hO (by + intro e k t ht + exact ⟨t,ht,by simpa [parameterNeighborhood] using hδ e⟩) + exact ⟨δ,r,hδ,hr,hdisks,hvisits,hseparate⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CutTraceSeparation.lean b/lean/OAI/Combinatorics/Crossing/CutTraceSeparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..73ef68a8aacd92039983d253d67ea2d0dcd4d7c1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CutTraceSeparation.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.Crossing.CutVertexAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.ExteriorCrossingCut +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {r : C.InnerIndex} + +theorem first_parameter_point (K : ExteriorCrossingCut C P r) : + D'.edge r.1 ((P r.1).knot K.first)=C.portPoint (C.incomingPort r) := + ((drawingEdgeWalk_getVert P r.1 K.first.val (by have h := K.first.isLt; omega)).trans + ((P r.1).vertices_at K.first)).symm.trans K.first_point + +theorem last_parameter_point (K : ExteriorCrossingCut C P r) : + D'.edge r.1 ((P r.1).knot K.last)=C.portPoint (C.outgoingPort r) := + ((drawingEdgeWalk_getVert P r.1 K.last.val (by have h := K.last.isLt; omega)).trans + ((P r.1).vertices_at K.last)).symm.trans K.last_point + +theorem prefix_subset_edge (K : ExteriorCrossingCut C P r) : + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) ⊆ Set.range (D'.edge r.1) := by + intro x hx + obtain ⟨t,_,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + exact ⟨t,he⟩ + +theorem suffix_subset_edge (K : ExteriorCrossingCut C P r) : + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) ⊆ Set.range (D'.edge r.1) := by + intro x hx + obtain ⟨t,_,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hx + exact ⟨t,he⟩ + +theorem incoming_not_suffix (K : ExteriorCrossingCut C P r) : + C.portPoint (C.incomingPort r) ∉ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) := by + intro hx + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hx + have heq := D'.edge_injective r.1 (he.trans K.first_parameter_point.symm) + exact ((P r.1).increasing K.ordered).not_ge (heq ▸ ht.1) + +theorem outgoing_not_prefix (K : ExteriorCrossingCut C P r) : + C.portPoint (C.outgoingPort r) ∉ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) := by + intro hx + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + have heq := D'.edge_injective r.1 (he.trans K.last_parameter_point.symm) + exact ((P r.1).increasing K.ordered).not_ge (heq ▸ ht.2) + +theorem prefix_suffix_disjoint (K : ExteriorCrossingCut C P r) : + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val))) := by + apply Set.disjoint_left.mpr + intro x hx hy + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + obtain ⟨u,hu,hf⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hy + have heq := D'.edge_injective r.1 (he.trans hf.symm) + exact ((P r.1).increasing K.ordered).not_ge (hu.1.trans (heq ▸ ht.2)) + +end Zarankiewicz.ExteriorCrossingCut + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CutVertexAvoidance.lean b/lean/OAI/Combinatorics/Crossing/CutVertexAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..9de61f501fa49f66ab51a5680a161dcbaa91a0e1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CutVertexAvoidance.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.ExteriorCrossingCut + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + +theorem drawing_edge_vertex_parameter (D : ContinuousDrawing m n) (e : BipartiteEdge m n) + (t : unitInterval) (v : BipartiteVertex m n) (he : D.edge e t=D.vertex v) : + (t=0 ∧ v=.inl e.1) ∨ (t=1 ∧ v=.inr e.2) := by + by_cases ht0 : t=0 + · subst t + exact Or.inl ⟨rfl,(D.vertex_injective ((D.edge e).source.symm.trans he)).symm⟩ + by_cases ht1 : t=1 + · subst t + exact Or.inr ⟨rfl,(D.vertex_injective ((D.edge e).target.symm.trans he)).symm⟩ + exact False.elim (D.interior_avoids_vertices e t + ⟨lt_of_le_of_ne t.property.1 (Ne.symm ht0),lt_of_le_of_ne t.property.2 ht1⟩ v he) + +namespace ExteriorCrossingCut +variable {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {r : C.InnerIndex} + +theorem first_parameter_lt_one (K : ExteriorCrossingCut C P r) : (P r.1).knot K.first < 1 := by + rw [← (P r.1).last] + exact (P r.1).increasing (K.ordered.trans_le (Fin.le_last _)) + +theorem last_parameter_pos (K : ExteriorCrossingCut C P r) : 0 < (P r.1).knot K.last := by + rw [← (P r.1).first] + exact (P r.1).increasing ((Fin.zero_le K.first).trans_lt K.ordered) + +theorem prefix_vertex_eq (K : ExteriorCrossingCut C P r) (v : BipartiteVertex m n) + (hv : D'.vertex v ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val))) : + v=.inl r.1.1 := by + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hv + rcases drawing_edge_vertex_parameter D'.toContinuousDrawing r.1 t v he with ⟨_,hv⟩ | ⟨ht1,_⟩ + · exact hv + · exact False.elim ((ht1 ▸ ht.2).not_gt K.first_parameter_lt_one) + +theorem suffix_vertex_eq (K : ExteriorCrossingCut C P r) (v : BipartiteVertex m n) + (hv : D'.vertex v ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val))) : + v=.inr r.1.2 := by + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hv + rcases drawing_edge_vertex_parameter D'.toContinuousDrawing r.1 t v he with ⟨ht0,_⟩ | ⟨_,hv⟩ + · exact False.elim ((ht0 ▸ ht.1).not_gt K.last_parameter_pos) + · exact hv + +end ExteriorCrossingCut +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CycleBlockIntersections.lean b/lean/OAI/Combinatorics/Crossing/CycleBlockIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..b71038d1f922f4ff45375bda81535f2ec491acc4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CycleBlockIntersections.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.Crossing.DartCyclePaths +import OAI.Combinatorics.Crossing.DartPairIntersections +import OAI.Combinatorics.Crossing.VertexChordIntersections + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +namespace PolygonalChain +variable {O T : Set Plane} {a b c d e f : Plane} + +theorem intersection_join_join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (S : PolygonalChain T e f) : + polygonIntersection (P.join Q).vertices (R.join S).vertices (P.join Q).pieces (R.join S).pieces= + polygonIntersection P.vertices R.vertices P.pieces R.pieces+ + polygonIntersection P.vertices S.vertices P.pieces S.pieces+ + polygonIntersection Q.vertices R.vertices Q.pieces R.pieces+ + polygonIntersection Q.vertices S.vertices Q.pieces S.pieces := by + rw [intersection_join_left,intersection_join_right,intersection_join_right] + ring + +theorem transverse_join_join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (S : PolygonalChain T e f) + (hPR : P.Transverse R) (hPS : P.Transverse S) (hQR : Q.Transverse R) (hQS : Q.Transverse S) : + (P.join Q).Transverse (R.join S) := + P.transverse_join_left Q (R.join S) + (R.transverse_join_right S P hPR hPS) (R.transverse_join_right S Q hQR hQS) + +end PolygonalChain +namespace TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def passageIntersection (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (i j : ℕ) (ε : ℝ) : ℝ := + polygonIntersection (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i)).vertices + (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε).vertices 1 1 + +theorem exists_cycle_block_radius (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + ∀ (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ), + bipartiteDartEdge (d (i+1)) ≠ bipartiteDartEdge (d i) → + bipartiteDartEdge (f (j+1)) ≠ bipartiteDartEdge (f j) → + (V.dartCycleBlock d hd i).Transverse (C.shiftedCycleBlock f hf ε j) ∧ + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces= + bipartiteDartSign (d i)*bipartiteDartSign (f j)* + V.signedIntersection (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j))+ + C.passageIntersection d f hd hf i j ε := by + obtain ⟨δ₀,hδ₀,h₀⟩ := C.exists_dart_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,h₁,-,-⟩ := C.exists_vertex_chord_chain_radius hnorm + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hs d f hd hf i j hdi hfj + obtain ⟨hdd,hcd,hdc⟩ := h₀ ε hε (hs.trans_le (min_le_left _ _)) + have hcc := h₁ ε hε (hs.trans_le (min_le_right _ _)) + (d i).snd (f j).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) + (dartTargetIncident (f j)) (dartPassageNext f hf j) + (dartPassage_ne d hd i hdi) (dartPassage_ne f hf j hfj) + obtain ⟨hDD,hDI⟩ := hdd (d i) (f j) + obtain ⟨hCD,hCI⟩ := hcd (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) (f j) + obtain ⟨hDC,hIC⟩ := hdc (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) (d i) + constructor + · exact PolygonalChain.transverse_join_join _ _ _ _ hDD hDC hCD hcc + · change polygonIntersection + ((V.dartTrackChain (d i)).join (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i))).vertices + ((C.shiftedDartChain (f j) ε).join (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε)).vertices + ((V.dartTrackChain (d i)).join (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i))).pieces + ((C.shiftedDartChain (f j) ε).join (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε)).pieces=_ + rw [PolygonalChain.intersection_join_join,hDI,hIC,hCI,add_zero,add_zero] + rfl + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CycleEndpointSum.lean b/lean/OAI/Combinatorics/Crossing/CycleEndpointSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..73d8aa448d3f63f9dbe5555b7fa22bf2d7c9676a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CycleEndpointSum.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.EndpointFlagPairing +import OAI.Combinatorics.Crossing.CyclicSumArithmetic +import OAI.Combinatorics.Crossing.RectangleAlgebra + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem passage_sum_eq_endpoint_sum (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) : + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, C.passagePairing d f hd hf i j)= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + bipartiteDartSign (d i)*bipartiteDartSign (f j)* + C.edgeEndpointPairing (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j)) := by + have hTS := double_sum_cycle_shift_right d f N K hK + (fun a b => C.flagPairing (dartTargetFlag a) (dartSourceFlag b)) + have hST := double_sum_cycle_shift_left d f N K hN + (fun a b => C.flagPairing (dartSourceFlag a) (dartTargetFlag b)) + have hSS₀ := double_sum_cycle_shift_right (fun i => d (i+1)) f N K hK + (fun a b => C.flagPairing (dartSourceFlag a) (dartSourceFlag b)) + have hSS₁ := double_sum_cycle_shift_left d f N K hN + (fun a b => C.flagPairing (dartSourceFlag a) (dartSourceFlag b)) + simp_rw [C.passagePairing_flags,← C.dart_endpoint_pairing] + simp only [Finset.sum_add_distrib,Finset.sum_sub_distrib] + rw [hTS,hST,hSS₀,hSS₁] + +def cycleIntersectionMatrix : Matrix (BipartiteEdge m n) (BipartiteEdge m n) ℝ := + fun e f => V.signedIntersection e f+C.edgeEndpointPairing e f + +theorem closed_cycle_matrix_sum (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) + (hdi : ∀ i, i < N → bipartiteDartEdge (d (i+1)) ≠ bipartiteDartEdge (d i)) + (hfj : ∀ j, j < K → bipartiteDartEdge (f (j+1)) ≠ bipartiteDartEdge (f j)) : + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + bipartiteDartSign (d i)*bipartiteDartSign (f j)* + C.cycleIntersectionMatrix (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j))=0 := by + have hh := C.closed_cycle_averaged_sum hnorm hstraight htrans d f hd hf N K hN hK hdi hfj + simp only [Finset.sum_add_distrib] at hh + rw [C.passage_sum_eq_endpoint_sum d f hd hf N K hN hK] at hh + simpa only [cycleIntersectionMatrix,mul_add,Finset.sum_add_distrib] using hh + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CycleMatrixBlocks.lean b/lean/OAI/Combinatorics/Crossing/CycleMatrixBlocks.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9bdefcacd16c6ebd1b2c8c17ddf3023ab0835e6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CycleMatrixBlocks.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.Crossing.AdditiveBlockRelation +import OAI.Combinatorics.Crossing.DetectorCrossingBound + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def leftHalfOrder (i : Fin m) : Matrix (Fin n) (Fin n) ℝ := fun p q => + orderSign (C.node (Sum.inl i) (V.leftIncident (i,p))) (C.node (Sum.inl i) (V.leftIncident (i,q)))/2 + +def rightHalfOrder (p : Fin n) : Matrix (Fin m) (Fin m) ℝ := fun i k => + orderSign (C.node (Sum.inr p) (V.rightIncident (i,p))) (C.node (Sum.inr p) (V.rightIncident (k,p)))/2 + +theorem flagPairing_left_block (i k : Fin m) (p q : Fin n) : + C.flagPairing (dartSourceFlag (forwardBipartiteDart (i,p))) + (dartSourceFlag (forwardBipartiteDart (k,q)))=if i=k then C.leftHalfOrder i p q else 0 := by + by_cases h : i=k + · subst k + change (if h : (Sum.inl i : BipartiteVertex m n)=Sum.inl i then + orderSign (C.node (Sum.inl i) (V.leftIncident (i,p))) + (C.node (Sum.inl i) (incidentCast h (V.leftIncident (i,q))))/2 else 0)=_ + rw [dite_eq_left rfl,incidentCast_refl,ite_eq_left rfl] + rfl + · have hn : (Sum.inl k : BipartiteVertex m n) ≠ Sum.inl i := fun he => h (Sum.inl.inj he).symm + simp only [flagPairing,dartSourceFlag,forwardBipartiteDart,ite_eq_right h] + exact dite_eq_right hn + +theorem flagPairing_right_block (i k : Fin m) (p q : Fin n) : + C.flagPairing (dartTargetFlag (forwardBipartiteDart (i,p))) + (dartTargetFlag (forwardBipartiteDart (k,q)))=if p=q then C.rightHalfOrder p i k else 0 := by + by_cases h : p=q + · subst q + change (if h : (Sum.inr p : BipartiteVertex m n)=Sum.inr p then + orderSign (C.node (Sum.inr p) (V.rightIncident (i,p))) + (C.node (Sum.inr p) (incidentCast h (V.rightIncident (k,p))))/2 else 0)=_ + rw [dite_eq_left rfl,incidentCast_refl,ite_eq_left rfl] + rfl + · have hn : (Sum.inr q : BipartiteVertex m n) ≠ Sum.inr p := fun he => h (Sum.inr.inj he).symm + simp only [flagPairing,dartTargetFlag,forwardBipartiteDart,ite_eq_right h] + exact dite_eq_right hn + +theorem cycleIntersectionMatrix_entry (i k : Fin m) (p q : Fin n) : + C.cycleIntersectionMatrix (i,p) (k,q)=V.signedIntersection (i,p) (k,q)+ + (if i=k then C.leftHalfOrder i p q else 0)+(if p=q then C.rightHalfOrder p i k else 0) := by + rw [cycleIntersectionMatrix,edgeEndpointPairing,C.flagPairing_left_block,C.flagPairing_right_block] + ring + +theorem cycleIntersectionMatrix_diagonal_block (hnorm : NoAdjacentCrossings D) (i : Fin m) : + edgeBlock C.cycleIntersectionMatrix i i=C.leftHalfOrder i := by + ext p q + rw [edgeBlock,C.cycleIntersectionMatrix_entry,V.signedIntersection_adjacent_zero hnorm (i,p) (i,q) (Or.inl rfl),ite_eq_left rfl] + have hz : C.rightHalfOrder p i i=0 := by simp [rightHalfOrder,orderSign] + rw [hz] + simp + +theorem cycleIntersectionMatrix_offDiagonal_block (i k : Fin m) (hik : i ≠ k) : + edgeBlock C.cycleIntersectionMatrix i k=V.intersectionBlock i k+ + Matrix.diagonal (fun p => C.rightHalfOrder p i k) := by + ext p q + rw [edgeBlock,C.cycleIntersectionMatrix_entry,ite_eq_right hik] + simp only [Matrix.add_apply,VertexTruncation.intersectionBlock,Matrix.diagonal_apply,add_zero] + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CyclePairing.lean b/lean/OAI/Combinatorics/Crossing/CyclePairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..65ffc2aecfe6f0a774fdb5565ad6a9220bd3cf02 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CyclePairing.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.Crossing.CycleEndpointSum +import OAI.Combinatorics.Crossing.WalkVectorSum + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem lemma3_1 (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + {u v : BipartiteVertex m n} (p : (completeBipartite m n).Walk u u) + (q : (completeBipartite m n).Walk v v) (hp : p.IsCycle) (hq : q.IsCycle) : + edgePairing C.cycleIntersectionMatrix (walkEdgeChain p) (walkEdgeChain q)=0 := by + have hpl : 0 < p.length := by have := hp.three_le_length; omega + have hql : 0 < q.length := by have := hq.three_le_length; omega + rw [edgePairing_walk_dart_sum _ p q hpl hql] + exact C.closed_cycle_matrix_sum hnorm hstraight htrans + (cyclicWalkDart p hpl) (cyclicWalkDart q hql) + (cyclicWalkDart_seam p hpl) (cyclicWalkDart_seam q hql) p.length q.length + (cyclicWalkDart_period p hpl) (cyclicWalkDart_period q hql) + (fun i _ => cyclicWalkDart_next_edge_ne p hp i) (fun j _ => cyclicWalkDart_next_edge_ne q hq j) + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CyclicSumArithmetic.lean b/lean/OAI/Combinatorics/Crossing/CyclicSumArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f3539955c9c7be9c6547db6f053c4a3d570a772 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CyclicSumArithmetic.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.Crossing.FourCycles +import Mathlib.Algebra.BigOperators.Group.Finset.Basic + +namespace OAI + +namespace Zarankiewicz +open scoped BigOperators + +theorem sum_range_cycle_succ {A : Type*} [AddCommGroup A] (f : ℕ → A) (N : ℕ) + (hN : f N=f 0) : (∑ i ∈ Finset.range N, f (i+1))=∑ i ∈ Finset.range N, f i := by + apply add_right_cancel (b := f 0) + calc + _ = ∑ i ∈ Finset.range (N+1), f i := (Finset.sum_range_succ' f N).symm + _ = _ := by rw [Finset.sum_range_succ,hN] + +theorem double_sum_cycle_shift_right {A B : Type*} (d : ℕ → A) (f : ℕ → B) + (N K : ℕ) (hK : f K=f 0) (H : A → B → ℝ) : + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, H (d i) (f (j+1)))= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, H (d i) (f j) := by + apply Finset.sum_congr rfl + intro i hi + exact sum_range_cycle_succ (fun j => H (d i) (f j)) K (congrArg (H (d i)) hK) + +theorem double_sum_cycle_shift_left {A B : Type*} (d : ℕ → A) (f : ℕ → B) + (N K : ℕ) (hN : d N=d 0) (H : A → B → ℝ) : + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, H (d (i+1)) (f j))= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, H (d i) (f j) := + sum_range_cycle_succ (fun i => ∑ j ∈ Finset.range K, H (d i) (f j)) N + (congrArg (fun a => ∑ j ∈ Finset.range K, H a (f j)) hN) + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/CyclicWalkDarts.lean b/lean/OAI/Combinatorics/Crossing/CyclicWalkDarts.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ad528a7c9a8d8f92fd73bddaf06a72d0557de59 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/CyclicWalkDarts.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.BipartiteDartGeometry +import OAI.Combinatorics.Crossing.PeriodicPolygon + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open SimpleGraph +variable {m n : ℕ} {u v : BipartiteVertex m n} + +def walkDart (p : (completeBipartite m n).Walk u v) (i : Fin p.length) : + (completeBipartite m n).Dart := + ⟨(p.getVert i.val,p.getVert (i.val+1)),p.adj_getVert_succ i.isLt⟩ + +theorem walkDart_eq_getElem (p : (completeBipartite m n).Walk u v) (i : Fin p.length) : + walkDart p i=p.darts[i.val]'(by simp) := + (Walk.darts_getElem_eq_getVert _ _).symm + +def cyclicWalkDart (p : (completeBipartite m n).Walk u u) (hp : 0 < p.length) (i : ℕ) : + (completeBipartite m n).Dart := walkDart p (cyclicIndex p.length hp i) + +theorem cyclicWalkDart_period (p : (completeBipartite m n).Walk u u) (hp : 0 < p.length) : + cyclicWalkDart p hp p.length=cyclicWalkDart p hp 0 := + congrArg (walkDart p) (cyclicIndex_period _ _) + +theorem cyclicWalkDart_seam (p : (completeBipartite m n).Walk u u) (hp : 0 < p.length) (i : ℕ) : + (cyclicWalkDart p hp i).snd=(cyclicWalkDart p hp (i+1)).fst := by + change p.getVert (i%p.length+1)=p.getVert ((i+1)%p.length) + have hi := Nat.mod_lt i hp + have he : (i+1)%p.length=(i%p.length+1)%p.length := by simp only [Nat.add_mod,Nat.mod_mod] + rw [he] + by_cases hlast : i%p.length+1=p.length + · rw [hlast,Nat.mod_self,p.getVert_length,p.getVert_zero] + · rw [Nat.mod_eq_of_lt (by omega : i%p.length+1 bipartiteDartEdge (walkDart p i)) := by + intro i j hij + change bipartiteDartEdge (walkDart p i)=bipartiteDartEdge (walkDart p j) at hij + apply Fin.ext + have hd : (walkDart p i).edge=(walkDart p j).edge := by + rw [bipartiteDart_unoriented,bipartiteDart_unoriented,hij] + have he : p.edges[i.val]'(by simp)=p.edges[j.val]'(by simp) := by + simpa only [Walk.getElem_edges,walkDart,Dart.edge] using hd + exact hp.edges_nodup.getElem_inj_iff.mp he + +theorem cyclicWalkDart_next_edge_ne (p : (completeBipartite m n).Walk u u) (hp : p.IsCycle) + (i : ℕ) : + bipartiteDartEdge (cyclicWalkDart p (by have := hp.three_le_length; omega) (i+1)) ≠ + bipartiteDartEdge (cyclicWalkDart p (by have := hp.three_le_length; omega) i) := by + intro he + have hn : 1 < p.length := by have := hp.three_le_length; omega + have hh := walkDart_edge_injective p hp.isTrail he + have hv := congrArg Fin.val hh + change (i+1)%p.length=i%p.length at hv + have hi := Nat.mod_lt i (by omega : 0 < p.length) + have hadd : (i+1)%p.length=(i%p.length+1)%p.length := by simp only [Nat.add_mod,Nat.mod_mod] + rw [hadd] at hv + by_cases hlast : i%p.length+1=p.length + · rw [hlast,Nat.mod_self] at hv + omega + · rw [Nat.mod_eq_of_lt (by omega : i%p.length+1 V.spokePort a.fst (dartSourceIncident a)) hN.symm) + +def graphCycleChain {u : BipartiteVertex m n} (p : (completeBipartite m n).Walk u u) + (hp : 0 < p.length) : PolygonalChain Set.univ + (V.dartCycleVertex (cyclicWalkDart p hp) 0) (V.dartCycleVertex (cyclicWalkDart p hp) 0) := + V.dartCycleChain (cyclicWalkDart p hp) (cyclicWalkDart_seam p hp) p.length (cyclicWalkDart_period p hp) + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : ContinuousDrawing m n} {V : VertexTruncation D} (C : TruncatedSpokeCoordinates V) + +theorem shiftedPort_cast {j k : BipartiteVertex m n} (h : j=k) (e : IncidentEdges j) (ε : ℝ) : + C.shiftedPort k (incidentCast h e) ε=C.shiftedPort j e ε := by subst k; rfl + +def shiftedCycleVertex (d : ℕ → (completeBipartite m n).Dart) (ε : ℝ) (i : ℕ) : Plane := + C.shiftedPort (d i).fst (dartSourceIncident (d i)) ε + +def shiftedCycleBlock (d : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (ε : ℝ) (i : ℕ) : + PolygonalChain Set.univ (C.shiftedCycleVertex d ε i) (C.shiftedCycleVertex d ε (i+1)) := + ((C.shiftedDartChain (d i) ε).join + (C.shiftedChordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) ε)).castEndpoints + rfl (C.shiftedPort_cast (hd i).symm _ ε).symm + +def shiftedCycleChain (d : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (N : ℕ) (hN : d N=d 0) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedCycleVertex d ε 0) (C.shiftedCycleVertex d ε 0) := + (finitePolygonalChain Set.univ (C.shiftedCycleVertex d ε) (Set.mem_univ _) (C.shiftedCycleBlock d hd ε) N).castEndpoints + rfl (congrArg (fun a : (completeBipartite m n).Dart => C.shiftedPort a.fst (dartSourceIncident a) ε) hN.symm) + +def shiftedGraphCycleChain {u : BipartiteVertex m n} (p : (completeBipartite m n).Walk u u) + (hp : 0 < p.length) (ε : ℝ) : PolygonalChain Set.univ + (C.shiftedCycleVertex (cyclicWalkDart p hp) ε 0) (C.shiftedCycleVertex (cyclicWalkDart p hp) ε 0) := + C.shiftedCycleChain (cyclicWalkDart p hp) (cyclicWalkDart_seam p hp) p.length (cyclicWalkDart_period p hp) ε + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DartPairIntersections.lean b/lean/OAI/Combinatorics/Crossing/DartPairIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3f0eaa5e9205e67c971c17584ec4cf9fbd5c314 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DartPairIntersections.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.Crossing.DartPathRealizations +import OAI.Combinatorics.Crossing.ShiftedEdgeIntersections +import OAI.Combinatorics.Crossing.ChordEdgeIntersections + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem dart_pair_intersection {ε : ℝ} (a b : (completeBipartite m n).Dart) + (h : ∀ e f, (V.trackChain e).Transverse (C.shiftedEdgeChain f ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).pieces=V.signedIntersection e f) : + (V.dartTrackChain a).Transverse (C.shiftedDartChain b ε) ∧ + polygonIntersection (V.dartTrackChain a).vertices (C.shiftedDartChain b ε).vertices + (V.dartTrackChain a).pieces (C.shiftedDartChain b ε).pieces= + bipartiteDartSign a*bipartiteDartSign b*V.signedIntersection (bipartiteDartEdge a) (bipartiteDartEdge b) := by + rcases bipartiteDart_cases a with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> + rcases bipartiteDart_cases b with ⟨f,rfl⟩ | ⟨f,rfl⟩ + · obtain ⟨hT,hI⟩ := h e f + refine ⟨hT,?_⟩ + change polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).pieces=1*1*V.signedIntersection e f + simpa only [one_mul] using hI + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).transverse_reverse_right _ hT,?_⟩ + change polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).reverse.vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).reverse.pieces=1*(-1)*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_right,hI] + ring + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).transverse_reverse_left _ hT,?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).reverse.pieces (C.shiftedEdgeChain f ε).pieces=(-1)*1*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_left,hI] + ring + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).reverse.transverse_reverse_right _ + ((V.trackChain e).transverse_reverse_left _ hT),?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedEdgeChain f ε).reverse.vertices + (V.trackChain e).reverse.pieces (C.shiftedEdgeChain f ε).reverse.pieces=(-1)*(-1)*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_left,PolygonalChain.intersection_reverse_right,hI] + ring + +theorem chord_dart_intersection {ε : ℝ} (j : BipartiteVertex m n) (a b : IncidentEdges j) + (d : (completeBipartite m n).Dart) + (h : ∀ e, (V.chordChain j a b).Transverse (C.shiftedEdgeChain e ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).pieces=0) : + (V.chordChain j a b).Transverse (C.shiftedDartChain d ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedDartChain d ε).vertices + (V.chordChain j a b).pieces (C.shiftedDartChain d ε).pieces=0 := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact h e + · obtain ⟨hT,hI⟩ := h e + refine ⟨(V.chordChain j a b).transverse_reverse_right _ hT,?_⟩ + change polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).reverse.vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).reverse.pieces=0 + rw [PolygonalChain.intersection_reverse_right,hI,neg_zero] + +theorem dart_chord_intersection {ε : ℝ} (j : BipartiteVertex m n) (a b : IncidentEdges j) + (d : (completeBipartite m n).Dart) + (h : ∀ e, (V.trackChain e).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).pieces (C.shiftedChordChain j a b ε).pieces=0) : + (V.dartTrackChain d).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.dartTrackChain d).vertices (C.shiftedChordChain j a b ε).vertices + (V.dartTrackChain d).pieces (C.shiftedChordChain j a b ε).pieces=0 := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact h e + · obtain ⟨hT,hI⟩ := h e + refine ⟨(V.trackChain e).transverse_reverse_left _ hT,?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).reverse.pieces (C.shiftedChordChain j a b ε).pieces=0 + rw [PolygonalChain.intersection_reverse_left,hI,neg_zero] + +theorem exists_dart_intersection_radius (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + (∀ a b : (completeBipartite m n).Dart, + (V.dartTrackChain a).Transverse (C.shiftedDartChain b ε) ∧ + polygonIntersection (V.dartTrackChain a).vertices (C.shiftedDartChain b ε).vertices + (V.dartTrackChain a).pieces (C.shiftedDartChain b ε).pieces= + bipartiteDartSign a*bipartiteDartSign b*V.signedIntersection (bipartiteDartEdge a) (bipartiteDartEdge b)) ∧ + (∀ j (a b : IncidentEdges j) d, + (V.chordChain j a b).Transverse (C.shiftedDartChain d ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedDartChain d ε).vertices + (V.chordChain j a b).pieces (C.shiftedDartChain d ε).pieces=0) ∧ + (∀ j (a b : IncidentEdges j) d, + (V.dartTrackChain d).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.dartTrackChain d).vertices (C.shiftedChordChain j a b ε).vertices + (V.dartTrackChain d).pieces (C.shiftedChordChain j a b ε).pieces=0) := by + obtain ⟨δ₀,hδ₀,h₀⟩ := C.exists_complete_edge_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,h₁⟩ := C.exists_chord_edge_radius hnorm + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hs + have he := h₀ ε hε (hs.trans_le (min_le_left _ _)) + obtain ⟨hcd,hdc⟩ := h₁ ε hε (hs.trans_le (min_le_right _ _)) + exact ⟨fun a b => C.dart_pair_intersection a b he, + fun j a b d => C.chord_dart_intersection j a b d (hcd j a b), + fun j a b d => C.dart_chord_intersection j a b d (hdc j a b)⟩ + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DartPathRealizations.lean b/lean/OAI/Combinatorics/Crossing/DartPathRealizations.lean new file mode 100644 index 0000000000000000000000000000000000000000..08d23e7864b4317799c8d15df4f7cf2949a83059 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DartPathRealizations.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.BipartiteDartGeometry +import OAI.Combinatorics.Crossing.PolygonalEndpointCasts + +namespace OAI + +noncomputable section +namespace Zarankiewicz +namespace VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +def dartTrackChain (d : (completeBipartite m n).Dart) : + PolygonalChain Set.univ (V.spokePort d.fst (dartSourceIncident d)) + (V.spokePort d.snd (dartTargetIncident d)) := by + rcases d with ⟨⟨u,v⟩,h⟩ + rcases u with i | p <;> rcases v with k | q + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + · exact (V.trackChain (i,q)).castEndpoints + (by simp [spokePort,drawingSpokePort,dartSourceIncident,bipartiteDartEdge,startPort]) + (by simp [spokePort,drawingSpokePort,dartTargetIncident,bipartiteDartEdge,endPort]) + · exact (V.trackChain (k,p)).reverse.castEndpoints + (by simp [spokePort,drawingSpokePort,dartSourceIncident,bipartiteDartEdge,endPort]) + (by simp [spokePort,drawingSpokePort,dartTargetIncident,bipartiteDartEdge,startPort]) + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + +theorem dartTrackChain_forward_vertices (e : BipartiteEdge m n) : + (V.dartTrackChain (forwardBipartiteDart e)).vertices=V.vertices e := rfl + +theorem dartTrackChain_backward_vertices (e : BipartiteEdge m n) : + (V.dartTrackChain (backwardBipartiteDart e)).vertices=reversedSequence (V.vertices e) (V.pieces e) := rfl + +theorem dartTrackChain_pieces (d : (completeBipartite m n).Dart) : + (V.dartTrackChain d).pieces=V.pieces (bipartiteDartEdge d) := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> rfl + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +def shiftedDartChain (d : (completeBipartite m n).Dart) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort d.fst (dartSourceIncident d) ε) + (C.shiftedPort d.snd (dartTargetIncident d) ε) := by + rcases d with ⟨⟨u,v⟩,h⟩ + rcases u with i | p <;> rcases v with k | q + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + · exact (C.shiftedEdgeChain (i,q) ε).castEndpoints rfl rfl + · exact (C.shiftedEdgeChain (k,p) ε).reverse.castEndpoints rfl rfl + · exact False.elim (by simp [completeBipartite,completeBipartiteGraph] at h) + +theorem shiftedDartChain_forward_vertices (e : BipartiteEdge m n) (ε : ℝ) : + (C.shiftedDartChain (forwardBipartiteDart e) ε).vertices=(C.shiftedEdgeChain e ε).vertices := rfl + +theorem shiftedDartChain_backward_vertices (e : BipartiteEdge m n) (ε : ℝ) : + (C.shiftedDartChain (backwardBipartiteDart e) ε).vertices= + reversedSequence (C.shiftedEdgeChain e ε).vertices (C.shiftedEdgeChain e ε).pieces := rfl + +theorem shiftedDartChain_pieces (d : (completeBipartite m n).Dart) (ε : ℝ) : + (C.shiftedDartChain d ε).pieces=(C.shiftedEdgeChain (bipartiteDartEdge d) ε).pieces := by + rcases bipartiteDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> rfl + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DegreeCounting.lean b/lean/OAI/Combinatorics/Crossing/DegreeCounting.lean new file mode 100644 index 0000000000000000000000000000000000000000..08138cd105c684bae63f689d52d0ed23256c89c7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DegreeCounting.lean @@ -0,0 +1,56 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.Nat.Basic +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring +import Mathlib.Tactic.NormNum +import Lean.Elab.Tactic.Omega + +namespace OAI + +namespace Zarankiewicz +open scoped BigOperators + +theorem triangular_degree_sum (ell : ℕ → ℕ) (m : ℕ) : + (∑ h ∈ Finset.range m, ∑ e ∈ Finset.range (h+1), e * ell e) = + ∑ e ∈ Finset.range m, e * (m-e) * ell e := by + induction m with + | zero => simp + | succ m ih => + rw [Finset.sum_range_succ, ih, Finset.sum_range_succ, Finset.sum_range_succ] + simp only [Nat.add_sub_cancel_left, mul_one] + have hc : ∀ e ∈ Finset.range m, + e * (m+1-e) * ell e = e * (m-e) * ell e + e * ell e := by + intro e he + have ht : m+1-e = (m-e)+1 := by have := Finset.mem_range.mp he; omega + rw [ht] + ring + simp_rw [Finset.sum_congr rfl hc, Finset.sum_add_distrib] + omega + +theorem parabola_le_floor (m e : ℕ) (he : e ≤ m) : e * (m-e) ≤ m*m/4 := by + have hm : ((m-e : ℕ) : ℤ) + (e : ℤ) = (m : ℤ) := by + exact_mod_cast Nat.sub_add_cancel he + have hz : (4 : ℤ) * (e : ℤ) * ((m-e : ℕ) : ℤ) ≤ (m : ℤ) * (m : ℤ) := by + nlinarith [sq_nonneg ((e : ℤ) - ((m-e : ℕ) : ℤ))] + have hn : 4 * e * (m-e) ≤ m*m := by exact_mod_cast hz + apply (Nat.le_div_iff_mul_le (by omega)).mpr + nlinarith + +theorem total_degree_cost_le (ell : ℕ → ℕ) (m N : ℕ) + (hell : ∑ e ∈ Finset.range m, ell e ≤ N) : + (∑ h ∈ Finset.range m, ∑ e ∈ Finset.range (h+1), e * ell e) ≤ (m*m/4) * N := by + rw [triangular_degree_sum] + calc + (∑ e ∈ Finset.range m, e * (m-e) * ell e) ≤ + ∑ e ∈ Finset.range m, (m*m/4) * ell e := by + apply Finset.sum_le_sum + intro e he + exact Nat.mul_le_mul_right (ell e) (parabola_le_floor m e (Nat.le_of_lt (Finset.mem_range.mp he))) + _ = (m*m/4) * ∑ e ∈ Finset.range m, ell e := (Finset.mul_sum ..).symm + _ ≤ (m*m/4) * N := Nat.mul_le_mul_left _ hell + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DeletionCount.lean b/lean/OAI/Combinatorics/Crossing/DeletionCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..198aae7c636153dfe8755aaa699990c06ea9f5e5 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DeletionCount.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.Crossing.DrawingDeletion + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators Classical +variable {m n : ℕ} + +theorem delete_crossing_finset (D : AdmissibleDrawing m (n+1)) (v : Fin (n+1)) : + (deleteRightVertex D v).crossings_finite.toFinset = + D.crossings_finite.toFinset.filter + (fun x => x ∈ crossingPoints (deleteRightVertex D v).toContinuousDrawing) := by + ext x + simp only [Finset.mem_filter, Set.Finite.mem_toFinset] + exact ⟨fun h => ⟨restrict_crossingPoints_subset D.toContinuousDrawing _ h,h⟩, And.right⟩ + +theorem sum_delete_crossingCount (D : AdmissibleDrawing m (n+1)) + (hnorm : NoAdjacentCrossings D) : + (∑ v : Fin (n+1), crossingCount (deleteRightVertex D v)) = ((n+1)-2)*crossingCount D := by + simp only [crossingCount, delete_crossing_finset, Finset.card_filter] + rw [Finset.sum_comm] + have he : ∀ x ∈ D.crossings_finite.toFinset, + (∑ v : Fin (n+1), if x ∈ crossingPoints (deleteRightVertex D v).toContinuousDrawing + then (1 : ℕ) else 0) = (n+1)-2 := by + intro x hx + exact crossing_deletion_multiplicity D hnorm x (by simpa using hx) + rw [Finset.sum_congr rfl he] + simp [Nat.mul_comm] + +theorem even_deletion_floor (s : ℕ) : + (2*s)*axisPairs (2*s-1) = (2*s-2)*axisPairs (2*s) := by + cases s with + | zero => simp + | succ s => + have h₁ : 2*(s+1)-1 = 2*s+1 := by omega + have h₂ : 2*(s+1)-2 = 2*s := by omega + rw [h₁, h₂, axisPairs_odd, axisPairs_even, Nat.add_sub_cancel] + ring + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DetectorAnnihilation.lean b/lean/OAI/Combinatorics/Crossing/DetectorAnnihilation.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ce33c1d9aba6dca954ed838b49374688fc2bf4f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DetectorAnnihilation.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.RankDetector + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +theorem detectorAtom_entry_split (s : ℕ) (node : ι → ℝ) (p q : ι) (ab cd : BiExponent s) : + detectorAtom s node p q ab cd = + (node p^(ab.1.val+cd.1.val+1) / derivativeAtNode node p) * + (node q^(ab.2.val+cd.2.val) / derivativeAtNode node q) - + (node p^(ab.1.val+cd.1.val) / derivativeAtNode node p) * + (node q^(ab.2.val+cd.2.val+1) / derivativeAtNode node q) := by + rw [detectorAtom_entry] + simp only [pow_succ, div_eq_mul_inv, mul_inv_rev] + ring + +theorem detectorAtom_row_sum (s : ℕ) (node : ι → ℝ) (hn : Function.Injective node) + (hcard : Fintype.card ι = 2*s+1) (p : ι) : ∑ q, detectorAtom s node p q = 0 := by + funext ab cd + simp only [Matrix.sum_apply, Matrix.zero_apply, detectorAtom_entry_split, + Finset.sum_sub_distrib, ← Finset.mul_sum] + have hb := ab.2.isLt + have hd := cd.2.isLt + rw [node_power_moment node hn _ (by omega), node_power_moment node hn _ (by omega)] + ring + +theorem detectorAtom_column_sum (s : ℕ) (node : ι → ℝ) (hn : Function.Injective node) + (hcard : Fintype.card ι = 2*s+1) (q : ι) : ∑ p, detectorAtom s node p q = 0 := by + funext ab cd + simp only [Matrix.sum_apply, Matrix.zero_apply, detectorAtom_entry_split, + Finset.sum_sub_distrib, ← Finset.sum_mul] + have ha := ab.1.isLt + have hc := cd.1.isLt + rw [node_power_moment node hn _ (by omega), node_power_moment node hn _ (by omega)] + ring + +theorem rankDetector_additive (s : ℕ) (node : ι → ℝ) (hn : Function.Injective node) + (hcard : Fintype.card ι = 2*s+1) (r c : ι → ℝ) : + rankDetector s node (fun p q => r p+c q) = 0 := by + change (∑ p, ∑ q, (r p+c q) • detectorAtom s node p q) = 0 + simp only [add_smul, Finset.sum_add_distrib] + have hr : (∑ p, ∑ q, r p • detectorAtom s node p q) = 0 := by + simp only [← Finset.smul_sum, detectorAtom_row_sum s node hn hcard, smul_zero, Finset.sum_const_zero] + have hc : (∑ p, ∑ q, c q • detectorAtom s node p q) = 0 := by + rw [Finset.sum_comm] + simp only [← Finset.smul_sum, detectorAtom_column_sum s node hn hcard, smul_zero, + Finset.sum_const_zero] + rw [hr, hc, add_zero] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DetectorCrossingBound.lean b/lean/OAI/Combinatorics/Crossing/DetectorCrossingBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f962a4b64341ffbe99313c5a677620eae59540b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DetectorCrossingBound.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.Crossing.TruncatedSignedIntersections +import OAI.Combinatorics.Crossing.DetectorRank + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + +def intersectionBlock (i k : Fin m) : Matrix (Fin n) (Fin n) ℝ := + fun p q => V.signedIntersection (i,p) (k,q) + +theorem detector_rank_le_rowCrossingCount (s : ℕ) (node : Fin n → ℝ) (i k : Fin m) : + (rankDetector s node (V.intersectionBlock i k)).rank ≤ rowCrossingCount D i k := by + classical + apply (rankDetector_support_bound s node (V.intersectionBlock i k)).trans + rw [Finset.card_filter,Fintype.sum_prod_type] + unfold rowCrossingCount + apply Finset.sum_le_sum + intro p hp + apply Finset.sum_le_sum + intro q hq + by_cases hh : p ≠ q ∧ V.intersectionBlock i k p q ≠ 0 + · rw [ite_eq_left hh] + exact V.pairCrossings_pos_of_signedIntersection_ne_zero (i,p) (k,q) hh.2 + · rw [ite_eq_right hh] + exact Nat.zero_le _ + +theorem ordered_detector_rank_le_twice_crossings (hnorm : NoAdjacentCrossings D) + (s : ℕ) (node : Fin n → ℝ) : + (∑ i : Fin m, ∑ k ∈ Finset.univ.erase i, (rankDetector s node (V.intersectionBlock i k)).rank) ≤ + 2*crossingCount D := by + rw [← sum_offDiagonal_rowCrossingCount D hnorm] + apply Finset.sum_le_sum + intro i hi + apply Finset.sum_le_sum + intro k hk + exact V.detector_rank_le_rowCrossingCount s node i k + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DetectorRank.lean b/lean/OAI/Combinatorics/Crossing/DetectorRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..92d29775d19e97ee9ba02da16cc96d46a29614da --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DetectorRank.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.RankDetector +import OAI.Combinatorics.Crossing.MatrixRankBounds +import Mathlib.Data.Matrix.Basis + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +theorem detectorAtom_rank_le_one + {ι : Type*} [Fintype ι] [DecidableEq ι] + (s : ℕ) (node : ι → ℝ) (p q : ι) : + (detectorAtom s node p q).rank ≤ 1 := + (matrix_rank_smul_le _ _).trans (Matrix.rank_vecMulVec_le _ _) + +theorem detectorAtom_rank_one (s : ℕ) (hs : 0 < s) (node : ι → ℝ) + (hn : Function.Injective node) {p q : ι} (hpq : p ≠ q) : + (detectorAtom s node p q).rank = 1 := by + have hw := detectorWeight_ne_zero node hn hpq + have hne : detectorAtom s node p q ≠ 0 := by + intro hz + have he := congrArg (fun A : Matrix (BiExponent s) (BiExponent s) ℝ => + A (⟨0,hs⟩,⟨0,hs⟩) (⟨0,hs⟩,⟨0,hs⟩)) hz + apply hw + simpa [detectorAtom, detectorVector, Matrix.vecMulVec_apply] using he + have hr0 := (matrix_rank_eq_zero_iff (detectorAtom s node p q)).not.mpr hne + have hr1 := detectorAtom_rank_le_one s node p q + omega + +theorem rankDetector_single (s : ℕ) (node : ι → ℝ) (p q : ι) (c : ℝ) : + rankDetector s node (Matrix.single p q c) = c • detectorAtom s node p q := by + change (∑ i, ∑ j, Matrix.single p q c i j • detectorAtom s node i j) = _ + simp [Matrix.single_apply, ite_and] + +theorem rankDetector_support_bound (s : ℕ) (node : ι → ℝ) (H : Matrix ι ι ℝ) : + (rankDetector s node H).rank ≤ + (Finset.univ.filter (fun pq : ι × ι => pq.1 ≠ pq.2 ∧ H pq.1 pq.2 ≠ 0)).card := by + let S := Finset.univ.filter (fun pq : ι × ι => pq.1 ≠ pq.2 ∧ H pq.1 pq.2 ≠ 0) + have he : rankDetector s node H = ∑ pq ∈ S, H pq.1 pq.2 • detectorAtom s node pq.1 pq.2 := by + change (∑ p, ∑ q, H p q • detectorAtom s node p q) = _ + rw [← Fintype.sum_prod_type (fun pq : ι × ι => H pq.1 pq.2 • detectorAtom s node pq.1 pq.2)] + symm + apply Finset.sum_subset (Finset.filter_subset _ _) + intro pq hpq hnot + have hnot' : ¬(pq.1 ≠ pq.2 ∧ H pq.1 pq.2 ≠ 0) := by simpa [S] using hnot + by_cases heq : pq.1 = pq.2 + · simp [heq, detectorAtom_self] + · have hz : H pq.1 pq.2 = 0 := by tauto + rw [hz, zero_smul] + rw [he] + calc + _ ≤ ∑ pq ∈ S, (H pq.1 pq.2 • detectorAtom s node pq.1 pq.2).rank := matrix_rank_sum_le S _ + _ ≤ ∑ _pq ∈ S, 1 := by + apply Finset.sum_le_sum + intro pq hpq + exact (matrix_rank_smul_le _ _).trans (detectorAtom_rank_le_one s node pq.1 pq.2) + _ = _ := by simp [S] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DetectorRelabeling.lean b/lean/OAI/Combinatorics/Crossing/DetectorRelabeling.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1aa55edcbd5d5a599fc644e49a6c2c077a80bc7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DetectorRelabeling.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.RankDetector +import Mathlib.Data.Finset.Sort + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators +variable {ι κ : Type*} [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + +theorem nodePolynomial_equiv + {ι κ : Type*} [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + (node : ι → ℝ) (e : κ ≃ ι) : + nodePolynomial (node ∘ e) = nodePolynomial node := by + exact e.prod_comp (fun i => Polynomial.X-Polynomial.C (node i)) + +theorem derivativeAtNode_equiv (node : ι → ℝ) (e : κ ≃ ι) (p : κ) : + derivativeAtNode (node ∘ e) p = derivativeAtNode node (e p) := by + simp only [derivativeAtNode, nodePolynomial_equiv, Function.comp_apply] + +theorem detectorAtom_equiv (s : ℕ) (node : ι → ℝ) (e : κ ≃ ι) (p q : κ) : + detectorAtom s (node ∘ e) p q = detectorAtom s node (e p) (e q) := by + unfold detectorAtom detectorWeight + rw [derivativeAtNode_equiv, derivativeAtNode_equiv] + rfl + +theorem rankDetector_equiv (s : ℕ) (node : ι → ℝ) (e : κ ≃ ι) (H : Matrix ι ι ℝ) : + rankDetector s (node ∘ e) (H.submatrix e e) = rankDetector s node H := by + change (∑ p, ∑ q, H (e p) (e q) • detectorAtom s (node ∘ e) p q) = _ + simp only [detectorAtom_equiv] + calc + _ = ∑ p : κ, ∑ q : ι, H (e p) q • detectorAtom s node (e p) q := by + apply Finset.sum_congr rfl + intro p hp + exact e.sum_comp (fun q => H (e p) q • detectorAtom s node (e p) q) + _ = _ := e.sum_comp (fun p => ∑ q, H p q • detectorAtom s node p q) + +def halfOrderMatrix (α : Type*) [LinearOrder α] : Matrix α α ℝ := + fun p q => if p < q then (1/2 : ℝ) else if q < p then -1/2 else 0 + +theorem halfOrderMatrix_orderIso + {ι κ : Type*} [Fintype ι] [DecidableEq ι] [Fintype κ] [DecidableEq κ] + [LinearOrder ι] [LinearOrder κ] (e : κ ≃o ι) : + (halfOrderMatrix ι).submatrix e e = halfOrderMatrix κ := by + funext p q + simp [halfOrderMatrix] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DiskFillingContainment.lean b/lean/OAI/Combinatorics/Crossing/DiskFillingContainment.lean new file mode 100644 index 0000000000000000000000000000000000000000..b899899a72ff0ff4c1d9f868ed5170ceb7113153 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DiskFillingContainment.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.CrossingDiskIncidence +import OAI.Combinatorics.Crossing.DrawingVertexPlacement + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem round_chord_in_disk (z a b : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (t : ℝ) (ht : t ∈ Set.Icc (0 : ℝ) 1) : + squaredLength (segmentPoint a b t-z) ≤ r^2 := by + have he : squaredLength (segmentPoint a b t-z)= + (1-t)*squaredLength (a-z)+t*squaredLength (b-z)-t*(1-t)*squaredLength (b-a) := by + dsimp [squaredLength,segmentPoint] + ring + have hnon : 0 ≤ t*(1-t)*squaredLength (b-a) := by + apply mul_nonneg (mul_nonneg ht.1 (sub_nonneg.mpr ht.2)) + dsimp [squaredLength] + positivity + rw [he,ha,hb] + linarith + +namespace DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem crossingChord_range_subset_disk (C : DrawingPassages D) (p : C.InnerIndex) : + Set.range (C.crossingChord p) ⊆ closedRoundDisk (C.innerMark p).val C.radius := by + rintro x ⟨t,rfl⟩ + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) ≤ C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_disk _ _ _ _ (C.incomingPoint_on_circle p) (C.outgoingPoint_on_circle p) t.val t.property + +theorem crossingChord_interior_in_disk (C : DrawingPassages D) (p : C.InnerIndex) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : + squaredLength (C.crossingChord p t-(C.innerMark p).val) < C.radius^2 := by + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) < C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_open_disk _ _ _ _ (C.incomingPoint_on_circle p) (C.outgoingPoint_on_circle p) + (C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p p)) t.val ht + +theorem crossingChords_disjoint_of_marks_ne (C : DrawingPassages D) (p q : C.InnerIndex) + (hm : C.innerMark p ≠ C.innerMark q) : + Disjoint (Set.range (C.crossingChord p)) (Set.range (C.crossingChord q)) := + (C.disks_disjoint _ _ hm).mono (C.crossingChord_range_subset_disk p) (C.crossingChord_range_subset_disk q) + +theorem portPoint_outside_other_disk (C : DrawingPassages D) (p : C.Port) (x : DrawingMark D) + (hx : C.portMark p ≠ x) : C.radius^2 < squaredLength (C.portPoint p-x.val) := by + apply lt_of_not_ge + intro hh + have hp : C.portPoint p ∈ closedRoundDisk (C.portMark p).val C.radius := (C.portPoint_on_circle p).le + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hx) hp hh + +theorem portPoint_outside_open_disks (C : DrawingPassages D) (p : C.Port) (x : DrawingMark D) : + C.radius^2 ≤ squaredLength (C.portPoint p-x.val) := by + by_cases he : C.portMark p=x + · have hp := C.portPoint_on_circle p + rw [he] at hp + exact hp.ge + · exact (C.portPoint_outside_other_disk p x he).le + +theorem crossingChord_avoids_vertex_disks (C : DrawingPassages D) (p : C.InnerIndex) + (v : BipartiteVertex m n) : + Disjoint (Set.range (C.crossingChord p)) (closedRoundDisk (D.vertex v) C.radius) := by + have hn : C.innerMark p ≠ C.vertexMark v := by + intro he + exact crossing_not_vertex D (C.innerMark p).val (C.innerMark_is_crossing p) v (congrArg Subtype.val he) + exact (C.disks_disjoint _ _ hn).mono (C.crossingChord_range_subset_disk p) Set.Subset.rfl + +end DrawingPassages +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DiskPassage.lean b/lean/OAI/Combinatorics/Crossing/DiskPassage.lean new file mode 100644 index 0000000000000000000000000000000000000000..a06fa2d4184c33d4c7c8b6ca1760365319ef0413 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DiskPassage.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.Crossing.SublevelExtrema +import OAI.Combinatorics.Crossing.RoundDiskVisits + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +structure DiskPassage {a b : Plane} (γ : Path a b) (z : Plane) (r : ℝ) (τ : unitInterval) where + enter : unitInterval + leave : unitInterval + enter_le_mark : enter ≤ τ + mark_le_leave : τ ≤ leave + enter_mem : γ enter ∈ closedRoundDisk z r + leave_mem : γ leave ∈ closedRoundDisk z r + all_visits : ∀ t, γ t ∈ closedRoundDisk z r → enter ≤ t ∧ t ≤ leave + enter_boundary : 0 < enter → squaredLength (γ enter-z)=r^2 + leave_boundary : leave < 1 → squaredLength (γ leave-z)=r^2 + strict_enter : 0 < τ → enter < τ + strict_leave : τ < 1 → τ < leave + +theorem nonempty_diskPassage {a b : Plane} (γ : Path a b) (z : Plane) (r : ℝ) + (τ : unitInterval) (hτ : squaredLength (γ τ-z) < r^2) : + Nonempty (DiskPassage γ z r τ) := by + obtain ⟨u,v,hu,hv,huτ,hτv,hfu,hfv,hall,hbu,hbv,hsu,hsv⟩ := sublevel_passage_extrema + (fun t => squaredLength (γ.extend t-z)) (continuous_path_squared_distance γ z) (r^2) τ.val τ.property + (by simpa using hτ) + let u' : unitInterval := ⟨u,hu⟩ + let v' : unitInterval := ⟨v,hv⟩ + have heu : γ.extend u=γ u' := γ.extend_extends' u' + have hev : γ.extend v=γ v' := γ.extend_extends' v' + rw [heu] at hfu hbu + rw [hev] at hfv hbv + exact ⟨{ + enter := u' + leave := v' + enter_le_mark := huτ + mark_le_leave := hτv + enter_mem := hfu + leave_mem := hfv + all_visits := fun t ht => hall t.val t.property (by simpa [closedRoundDisk] using ht) + enter_boundary := hbu + leave_boundary := hbv + strict_enter := hsu + strict_leave := hsv }⟩ + +namespace DiskPassage +variable {a b z : Plane} {γ : Path a b} {r : ℝ} {τ : unitInterval} + +theorem enter_lt_leave (P : DiskPassage γ z r τ) : P.enter < P.leave := by + by_cases ht : τ=0 + · exact P.enter_le_mark.trans_lt (P.strict_leave (by rw [ht]; exact zero_lt_one)) + · exact (P.strict_enter (lt_of_le_of_ne (show 0 ≤ τ from τ.property.1) (Ne.symm ht))).trans_le P.mark_le_leave + +theorem enter_at_source (P : DiskPassage γ z r τ) (ht : τ=0) : P.enter=0 := by + apply le_antisymm + · exact P.enter_le_mark.trans_eq ht + · exact P.enter.property.1 + +theorem leave_at_target (P : DiskPassage γ z r τ) (ht : τ=1) : P.leave=1 := by + apply le_antisymm + · exact P.leave.property.2 + · exact ht.symm.trans_le P.mark_le_leave + +theorem enter_pos_of_source_outside (P : DiskPassage γ z r τ) + (h : a ∉ closedRoundDisk z r) : 0 < P.enter := by + apply lt_of_le_of_ne (show 0 ≤ P.enter from P.enter.property.1) + intro he + have hh := P.enter_mem + rw [← he] at hh + exact h (by simpa using hh) + +theorem leave_lt_one_of_target_outside (P : DiskPassage γ z r τ) + (h : b ∉ closedRoundDisk z r) : P.leave < 1 := by + apply lt_of_le_of_ne (show P.leave ≤ 1 from P.leave.property.2) + intro he + have hh := P.leave_mem + rw [he] at hh + exact h (by simpa using hh) + +end DiskPassage +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DiskSegments.lean b/lean/OAI/Combinatorics/Crossing/DiskSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..588ed6ee20a7f1203b280974935c7364426b54d4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DiskSegments.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.CircleConnectors + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem squaredLength_segment (a b : Plane) (t : ℝ) : + squaredLength (segmentPoint a b t) = + (1-t)*squaredLength a+t*squaredLength b-t*(1-t)*squaredLength (b-a) := by + dsimp [squaredLength,segmentPoint] + ring + +theorem unit_chord_in_disk (a b : Plane) (ha : squaredLength a=1) (hb : squaredLength b=1) + (t : ℝ) (ht : t ∈ Set.Icc (0 : ℝ) 1) : squaredLength (segmentPoint a b t) ≤ 1 := by + have hnon : 0 ≤ squaredLength (b-a) := by dsimp [squaredLength]; positivity + have hprod := mul_nonneg (mul_nonneg ht.1 (sub_nonneg.mpr ht.2)) hnon + rw [squaredLength_segment,ha,hb] + linarith + +theorem unit_chord_in_open_disk (a b : Plane) (ha : squaredLength a=1) (hb : squaredLength b=1) + (hne : a ≠ b) (t : ℝ) (ht : t ∈ Set.Ioo (0 : ℝ) 1) : squaredLength (segmentPoint a b t) < 1 := by + have hpos := squaredLength_pos (b-a) (sub_ne_zero.mpr hne.symm) + have hprod := mul_pos (mul_pos ht.1 (sub_pos.mpr ht.2)) hpos + rw [squaredLength_segment,ha,hb] + linarith + +theorem unit_chord_connector_disjoint (a b u : Plane) + (ha : squaredLength a=1) (hb : squaredLength b=1) (hu : squaredLength u=1) + (hab : a ≠ b) (δ : ℝ) (hδ : |δ|<1) (hne : δ ≠ 0) + (haq : a ≠ circleOffset u δ) (hbq : b ≠ circleOffset u δ) : + ¬ ClosedSegmentsMeet a b (circleOffset u δ) (circleTangentOffset u δ) := by + rintro ⟨s,hs,t,ht,he⟩ + by_cases htp : 0 exact Fin.succAbove_ne v _ + · rcases haf with rfl | rfl <;> exact Fin.succAbove_ne v _ + · rintro ⟨hev,hfv⟩ + obtain ⟨a,ha⟩ := Fin.exists_succAbove_eq hev + obtain ⟨b,hb⟩ := Fin.exists_succAbove_eq hfv + let emb := (Fin.succAboveOrderEmb v).toEmbedding + have hea : restrictEdge emb (e.1,a) = e := Prod.ext rfl ha + have hfb : restrictEdge emb (f.1,b) = f := Prod.ext rfl hb + refine ⟨(e.1,a),(f.1,b),?_,?_,?_⟩ + · intro hab + apply hef + rw [← hea, ← hfb, hab] + · change x ∈ edgeInterior D.toContinuousDrawing (restrictEdge emb (e.1,a)) + rwa [hea] + · change x ∈ edgeInterior D.toContinuousDrawing (restrictEdge emb (f.1,b)) + rwa [hfb] + +theorem crossing_columns_ne (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (x : Plane) (e f : BipartiteEdge m n) (hef : e ≠ f) + (he : x ∈ edgeInterior D.toContinuousDrawing e) (hf : x ∈ edgeInterior D.toContinuousDrawing f) : + e.2 ≠ f.2 := by + intro hcol + have hh : x ∈ edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f := ⟨he,hf⟩ + rw [hnorm e f hef (Or.inr hcol)] at hh + exact hh + +theorem two_excluded_indices (a b : Fin (n+1)) (hab : a ≠ b) : + (∑ v : Fin (n+1), if a ≠ v ∧ b ≠ v then (1 : ℕ) else 0) = (n+1)-2 := by + have he : (Finset.univ.filter (fun v : Fin (n+1) => a ≠ v ∧ b ≠ v)) = + (Finset.univ.erase a).erase b := by + ext v + simp [ne_comm, and_comm] + rw [← Finset.card_filter, he, Finset.card_erase_of_mem (by simp [hab.symm]), + Finset.card_erase_of_mem (Finset.mem_univ a), Finset.card_univ, Fintype.card_fin] + omega + +theorem crossing_deletion_multiplicity (D : AdmissibleDrawing m (n+1)) + (hnorm : NoAdjacentCrossings D) (x : Plane) (hx : x ∈ crossingPoints D.toContinuousDrawing) : + (∑ v : Fin (n+1), if x ∈ crossingPoints (deleteRightVertex D v).toContinuousDrawing + then (1 : ℕ) else 0) = (n+1)-2 := by + obtain ⟨e,f,hef,he,hf⟩ := hx + simp_rw [crossing_survives_deletion_iff D _ x e f hef he hf] + exact two_excluded_indices e.2 f.2 (crossing_columns_ne D hnorm x e f hef he hf) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingDiskIsolation.lean b/lean/OAI/Combinatorics/Crossing/DrawingDiskIsolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc588a2a8b625dfda6db85a4dd18e01a07e76247 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingDiskIsolation.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.CurveDiskIsolation +import OAI.Combinatorics.Crossing.DrawingMarks + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +abbrev DrawingMark (D : FiniteIntersectionDrawing m n) := ↥(drawingMarks D) + +theorem drawing_disk_isolation (D : FiniteIntersectionDrawing m n) : + ∃ δ : BipartiteEdge m n → ℝ, ∃ r : ℝ, (∀ e, 0 < δ e) ∧ 0 < r ∧ + (∀ x y : DrawingMark D, x ≠ y → + Disjoint (closedRoundDisk x.val r) (closedRoundDisk y.val r)) ∧ + (∀ e (x : DrawingMark D) t, D.edge e t ∈ closedRoundDisk x.val r → + ∃ u : unitInterval, D.edge e u=x.val ∧ t ∈ parameterNeighborhood u (δ e)) ∧ + (∀ e u v, D.edge e u ∈ drawingMarks D → D.edge e v ∈ drawingMarks D → u ≠ v → + Disjoint (closure (parameterNeighborhood u (δ e))) + (closure (parameterNeighborhood v (δ e)))) := by + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + let : DecidableEq (DrawingMark D) := Classical.decEq _ + obtain ⟨δ,r,hδ,hr,hd,hv,hs⟩ := finite_injective_curve_disk_isolation + (fun e => D.edge e) (fun e => (D.edge e).continuous) D.edge_injective + (fun x : DrawingMark D => x.val) Subtype.val_injective + refine ⟨δ,r,hδ,hr,hd,hv,?_⟩ + intro e u v hu hv huv + exact hs e u v ⟨⟨D.edge e u,hu⟩,rfl⟩ ⟨⟨D.edge e v,hv⟩,rfl⟩ huv + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalk.lean b/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..80aed6c9ed24ef2f590f367b0de29a25da16a3ab --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalk.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.DrawingSubdivisionGraph +import OAI.Combinatorics.Crossing.GraphSequenceWalk + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem drawingEdgeSequence_adj (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) (i : ℕ) (hi : i < (P e).pieces) : + (drawingSubdivisionGraph P).Adj ((P e).vertices i) ((P e).vertices (i+1)) := by + let j : Fin (P e).pieces := ⟨i,hi⟩ + have h0 : (P e).vertices i=drawingPieceStart P ⟨e,j⟩ := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=drawingPieceEnd P ⟨e,j⟩ := (P e).vertices_at j.succ + rw [h0,h1] + exact drawingSubdivisionGraph_piece_adj P ⟨e,j⟩ + +def drawingEdgeWalk (P : ∀ e, PolygonalParametrization (D.edge e)) (e : BipartiteEdge m n) : + (drawingSubdivisionGraph P).Walk (D.vertex (.inl e.1)) (D.vertex (.inr e.2)) := + (graphSequenceWalk (drawingSubdivisionGraph P) (P e).vertices (P e).pieces + (drawingEdgeSequence_adj P e)).copy (P e).vertices_first (P e).vertices_last + +theorem drawingEdgeWalk_length (P : ∀ e, PolygonalParametrization (D.edge e)) (e : BipartiteEdge m n) : + (drawingEdgeWalk P e).length=(P e).pieces := by + simp only [drawingEdgeWalk,SimpleGraph.Walk.length_copy,graphSequenceWalk_length] + +theorem drawingEdgeWalk_getVert (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) (i : ℕ) (hi : i ≤ (P e).pieces) : + (drawingEdgeWalk P e).getVert i=(P e).vertices i := by + simp only [drawingEdgeWalk,SimpleGraph.Walk.getVert_copy] + exact graphSequenceWalk_getVert _ _ _ _ i hi + +theorem drawingEdgeWalk_isPath (P : ∀ e, PolygonalParametrization (D.edge e)) (e : BipartiteEdge m n) : + (drawingEdgeWalk P e).IsPath := by + rw [drawingEdgeWalk,SimpleGraph.Walk.isPath_copy] + apply graphSequenceWalk_isPath + intro i hi j hj he + change i ≤ (P e).pieces at hi + change j ≤ (P e).pieces at hj + have h0 := (P e).vertices_at (⟨i,by omega⟩ : Fin ((P e).pieces+1)) + have h1 := (P e).vertices_at (⟨j,by omega⟩ : Fin ((P e).pieces+1)) + rw [h0,h1] at he + have hh := (P e).increasing.injective (D.edge_injective e he) + exact congrArg Fin.val hh + +theorem drawingEdgeWalk_uniqueVisit (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) (x : Plane) : UniqueWalkVisit (drawingEdgeWalk P e) x := by + intro i j hi hj hix hjx + exact (drawingEdgeWalk_isPath P e).getVert_injOn hi hj (hix.trans hjx.symm) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalkTrace.lean b/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalkTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea9f6a8e077604aafe75ca91da89ba086eb7d18e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingEdgeWalkTrace.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.DrawingEdgeWalk +import OAI.Combinatorics.Crossing.OrderedKnotCover + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalParametrization +variable {a b : Plane} {γ : Path a b} + +theorem range_pieceTrace_iff (P : PolygonalParametrization γ) (x : Plane) : + x ∈ Set.range γ ↔ ∃ i : Fin P.pieces, x ∈ P.pieceTrace i := by + constructor + · rintro ⟨u,rfl⟩ + obtain ⟨i,hi⟩ := P.knot_cover u + obtain ⟨t,ht⟩ := intervalSegment_surjective_interval (P.knot i.castSucc) (P.knot i.succ) + (P.increasing (by change i.val < i.val+1; omega)) u hi + refine ⟨i,?_⟩ + rw [pieceTrace,← Path.range_segment] + refine ⟨t,?_⟩ + have he := (P.affine i t).symm.trans (congrArg γ ht) + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + · rintro ⟨i,hi⟩ + exact P.pieceTrace_subset_range i hi + +end Zarankiewicz.PolygonalParametrization +namespace Zarankiewicz +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem drawingEdgeWalk_range_eq (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) : + Set.range (graphWalkPath id (drawingEdgeWalk P e))=Set.range (D.edge e) := by + apply Set.Subset.antisymm + · intro x hx + have hlen := drawingEdgeWalk_length P e + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (fun i => (drawingEdgeWalk P e).getVert i) + (drawingEdgeWalk P e).length (by rw [hlen]; exact (P e).pieces_pos) x hx + rw [hlen] at hi + rw [drawingEdgeWalk_getVert P e i (by omega),drawingEdgeWalk_getVert P e (i+1) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨i,hi⟩ + have h0 : (P e).vertices i=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + rw [h0,h1] at hxi + exact (P e).pieceTrace_subset_range j hxi + · intro x hx + obtain ⟨i,hi⟩ := ((P e).range_pieceTrace_iff x).mp hx + apply polygonalArcPath_piece_subset_range (fun j => (drawingEdgeWalk P e).getVert j) + (drawingEdgeWalk P e).length i.val (by rw [drawingEdgeWalk_length]; exact i.isLt) + rw [drawingEdgeWalk_getVert P e i.val (by omega),drawingEdgeWalk_getVert P e (i.val+1) (by omega)] + have h0 : (P e).vertices i.val=D.edge e ((P e).knot i.castSucc) := (P e).vertices_at i.castSucc + have h1 : (P e).vertices (i.val+1)=D.edge e ((P e).knot i.succ) := (P e).vertices_at i.succ + rw [h0,h1] + exact hi + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingExteriorReplacement.lean b/lean/OAI/Combinatorics/Crossing/DrawingExteriorReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c7a77d33b804242897db49b802ed51278bcf1b6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingExteriorReplacement.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.Crossing.RetainedArcDisjointness +import OAI.Combinatorics.Crossing.SimultaneousExteriorArcs + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem drawing_exterior_polygonal_replacement {m n : ℕ} (D : FiniteIntersectionDrawing m n) : + ∃ C : DrawingPassages D, ∃ U : C.ArcIndex → Set Plane, + ∃ P : ∀ i, PolygonalChain (U i) (C.arcStart i) (C.arcEnd i), + (∀ i, IsOpen (U i)) ∧ (∀ i, Function.Injective (P i).path) ∧ + (∀ i t, t ∈ Set.Ioo (0 : unitInterval) 1 → + (P i).path t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius) ∧ + (∀ i j, i ≠ j → Disjoint (Set.range (P i).path) (Set.range (P j).path)) := by + classical + obtain ⟨C⟩ := nonempty_drawingPassages D + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + obtain ⟨U,P,hU,hP,hout,hdisjoint⟩ := finite_exterior_arc_replacements + (fun x : DrawingMark D => x.val) C.radius C.radius_pos C.disks_disjoint + C.arcStartMark C.arcEndMark C.arcStart C.arcEnd C.arc_endpoints_ne + C.arc_start_on_circle C.arc_end_on_circle C.arc C.arcs_pairwise_disjoint C.arc_interior_outside + exact ⟨C,U,P,hU,hP,hout,hdisjoint⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingMarks.lean b/lean/OAI/Combinatorics/Crossing/DrawingMarks.lean new file mode 100644 index 0000000000000000000000000000000000000000..f68999a813511cde5729af8d0ad751a0a5a7ada8 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingMarks.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.Crossing.FiniteIntersectionDrawing +import OAI.Combinatorics.Crossing.CrossingIncidence +import OAI.Combinatorics.Crossing.PathSubarc + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def drawingMarks (D : FiniteIntersectionDrawing m n) : Set Plane := + Set.range D.vertex ∪ crossingPoints D.toContinuousDrawing + +theorem drawingMarks_finite (D : FiniteIntersectionDrawing m n) : (drawingMarks D).Finite := + (Set.finite_range D.vertex).union D.crossings_finite + +theorem crossing_not_vertex (D : FiniteIntersectionDrawing m n) (x : Plane) + (hx : x ∈ crossingPoints D.toContinuousDrawing) (v : BipartiteVertex m n) : x ≠ D.vertex v := by + obtain ⟨e,f,hef,⟨t,ht,he⟩,hf⟩ := hx + intro hh + exact D.interior_avoids_vertices e t ht v (he.trans hh) + +theorem marked_parameters_finite (D : FiniteIntersectionDrawing m n) (e : BipartiteEdge m n) : + ((D.edge e) ⁻¹' drawingMarks D).Finite := + Set.Finite.preimage (D.edge_injective e).injOn (drawingMarks_finite D) + +theorem marked_parameter_zero (D : FiniteIntersectionDrawing m n) (e : BipartiteEdge m n) : + (0 : unitInterval) ∈ (D.edge e) ⁻¹' drawingMarks D := by + exact Or.inl ⟨.inl e.1,(D.edge e).source.symm⟩ + +theorem marked_parameter_one (D : FiniteIntersectionDrawing m n) (e : BipartiteEdge m n) : + (1 : unitInterval) ∈ (D.edge e) ⁻¹' drawingMarks D := by + exact Or.inl ⟨.inr e.2,(D.edge e).target.symm⟩ + +theorem unmarked_edge_point_interior (D : FiniteIntersectionDrawing m n) (e : BipartiteEdge m n) + (t : unitInterval) (ht : D.edge e t ∉ drawingMarks D) : t ∈ Set.Ioo (0 : unitInterval) 1 := by + have ht0 : t ≠ 0 := by + intro he + subst t + exact ht (marked_parameter_zero D e) + have ht1 : t ≠ 1 := by + intro he + subst t + exact ht (marked_parameter_one D e) + exact ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + +theorem unmarked_intersection_same_edge (D : FiniteIntersectionDrawing m n) + (e f : BipartiteEdge m n) (s t : unitInterval) + (he : D.edge e s=D.edge f t) (hs : D.edge e s ∉ drawingMarks D) : e=f := by + by_contra hef + have hsi := unmarked_edge_point_interior D e s hs + have hti := unmarked_edge_point_interior D f t (he ▸ hs) + exact hs (Or.inr ⟨e,f,hef,⟨s,hsi,rfl⟩,⟨t,hti,he.symm⟩⟩) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingPassages.lean b/lean/OAI/Combinatorics/Crossing/DrawingPassages.lean new file mode 100644 index 0000000000000000000000000000000000000000..0184377eab630accac89aefa263bbb6c73048b1f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingPassages.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.Crossing.DrawingDiskIsolation +import OAI.Combinatorics.Crossing.SortedMarkedParameters +import OAI.Combinatorics.Crossing.OrderedPassages + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +structure DrawingPassages (D : FiniteIntersectionDrawing m n) where + radius : ℝ + radius_pos : 0 < radius + disks_disjoint : ∀ x y : DrawingMark D, x ≠ y → + Disjoint (closedRoundDisk x.val radius) (closedRoundDisk y.val radius) + count : BipartiteEdge m n → ℕ + count_pos : ∀ e, 0 < count e + node : ∀ e, Fin (count e+1) → unitInterval + increasing : ∀ e, StrictMono (node e) + first : ∀ e, node e 0=0 + last : ∀ e, node e (Fin.last (count e))=1 + node_range : ∀ e, Set.range (node e)=(D.edge e) ⁻¹' drawingMarks D + passage : ∀ e i, DiskPassage (D.edge e) (D.edge e (node e i)) radius (node e i) + separated : ∀ e i j, i < j → (passage e i).leave < (passage e j).enter + visited_mark_on_edge : ∀ e (x : DrawingMark D) t, + D.edge e t ∈ closedRoundDisk x.val radius → ∃ u, D.edge e u=x.val + +theorem nonempty_drawingPassages (D : FiniteIntersectionDrawing m n) : Nonempty (DrawingPassages D) := by + classical + obtain ⟨δ,r,hδ,hr,hdisks,hvisits,hparam⟩ := drawing_disk_isolation D + choose k hk τ hτ h0 h1 hR using (fun e => exists_sorted_drawing_parameters D e) + have hnode (e : BipartiteEdge m n) (i : Fin (k e+1)) : D.edge e (τ e i) ∈ drawingMarks D := by + change τ e i ∈ (D.edge e) ⁻¹' drawingMarks D + rw [← hR e] + exact ⟨i,rfl⟩ + have hex (e : BipartiteEdge m n) (i : Fin (k e+1)) : + Nonempty (DiskPassage (D.edge e) (D.edge e (τ e i)) r (τ e i)) := + nonempty_diskPassage (D.edge e) (D.edge e (τ e i)) r (τ e i) + (by simpa [squaredLength] using sq_pos_of_pos hr) + let P (e : BipartiteEdge m n) (i : Fin (k e+1)) := Classical.choice (hex e i) + have hlocal (e : BipartiteEdge m n) (i : Fin (k e+1)) (t : unitInterval) + (ht : D.edge e t ∈ closedRoundDisk (D.edge e (τ e i)) r) : + t ∈ parameterNeighborhood (τ e i) (δ e) := by + obtain ⟨u,hu,hh⟩ := hvisits e ⟨D.edge e (τ e i),hnode e i⟩ t ht + have he : u=τ e i := D.edge_injective e hu + simpa [he] using hh + have hsep (e : BipartiteEdge m n) (i j : Fin (k e+1)) (hij : i < j) : + (P e i).leave < (P e j).enter := by + apply diskPassage_separated (P e i) (P e j) (hτ e hij) (hδ e) + · exact hparam e (τ e i) (τ e j) (hnode e i) (hnode e j) ((hτ e).injective.ne (ne_of_lt hij)) + · exact hlocal e i _ (P e i).leave_mem + · exact hlocal e j _ (P e j).enter_mem + exact ⟨{ + radius := r + radius_pos := hr + disks_disjoint := hdisks + count := k + count_pos := hk + node := τ + increasing := hτ + first := h0 + last := h1 + node_range := hR + passage := P + separated := hsep + visited_mark_on_edge := fun e x t ht => by + obtain ⟨u,hu,_⟩ := hvisits e x t ht + exact ⟨u,hu⟩ }⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingPorts.lean b/lean/OAI/Combinatorics/Crossing/DrawingPorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..6953c1e0ad6f52b9a830cd1d65aacbfb719d5402 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingPorts.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.RetainedArcDisjointness + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +abbrev Port (C : DrawingPassages D) := C.ArcIndex × Bool + +def portPoint (C : DrawingPassages D) (p : C.Port) : Plane := + if p.2 then C.arcEnd p.1 else C.arcStart p.1 + +def portMark (C : DrawingPassages D) (p : C.Port) : DrawingMark D := + if p.2 then C.arcEndMark p.1 else C.arcStartMark p.1 + +theorem portPoint_mem_arc (C : DrawingPassages D) (p : C.Port) : + C.portPoint p ∈ Set.range (C.arc p.1) := by + rcases p with ⟨i,flag⟩ + cases flag + · exact ⟨0,(C.arc i).source⟩ + · exact ⟨1,(C.arc i).target⟩ + +theorem portPoint_injective (C : DrawingPassages D) : Function.Injective C.portPoint := by + rintro ⟨i,s⟩ ⟨j,t⟩ he + have hij : i=j := by + by_contra h + exact Set.disjoint_left.mp (C.arcs_pairwise_disjoint i j h) + (C.portPoint_mem_arc (i,s)) (he.symm ▸ C.portPoint_mem_arc (j,t)) + subst j + have hst : s=t := by + cases s <;> cases t + · rfl + · exact False.elim (C.arc_endpoints_ne i he) + · exact False.elim (C.arc_endpoints_ne i he.symm) + · rfl + subst t + rfl + +theorem portPoint_on_circle (C : DrawingPassages D) (p : C.Port) : + squaredLength (C.portPoint p-(C.portMark p).val)=C.radius^2 := by + rcases p with ⟨i,flag⟩ + cases flag + · exact C.arc_start_on_circle i + · exact C.arc_end_on_circle i + +abbrev PortsAt (C : DrawingPassages D) (x : DrawingMark D) := {p : C.Port // C.portMark p=x} + +theorem portsAt_on_circle (C : DrawingPassages D) (x : DrawingMark D) (p : C.PortsAt x) : + squaredLength (C.portPoint p.val-x.val)=C.radius^2 := by + simpa only [p.property] using C.portPoint_on_circle p.val + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingRangeCrossings.lean b/lean/OAI/Combinatorics/Crossing/DrawingRangeCrossings.lean new file mode 100644 index 0000000000000000000000000000000000000000..57c8888ae7981ac2092bd689a22d9249592986f8 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingRangeCrossings.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem edgeInterior_subset_range (D : ContinuousDrawing m n) (e : BipartiteEdge m n) : + edgeInterior D e ⊆ Set.range (D.edge e) := by + rintro x ⟨t,_,he⟩ + exact ⟨t,he⟩ + +theorem edgeInterior_of_range_not_vertices (D : ContinuousDrawing m n) (e : BipartiteEdge m n) + (x : Plane) (hx : x ∈ Set.range (D.edge e)) (hvertex : ∀ j, x ≠ D.vertex j) : + x ∈ edgeInterior D e := by + obtain ⟨t,he⟩ := hx + have ht0 : t ≠ 0 := by + intro ht + subst t + exact hvertex _ (he.symm.trans (D.edge e).source) + have ht1 : t ≠ 1 := by + intro ht + subst t + exact hvertex _ (he.symm.trans (D.edge e).target) + exact ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,he⟩ + +theorem edgeInterior_not_vertex (D : ContinuousDrawing m n) (e : BipartiteEdge m n) + (x : Plane) (hx : x ∈ edgeInterior D e) (j : BipartiteVertex m n) : x ≠ D.vertex j := by + obtain ⟨t,ht,he⟩ := hx + exact fun hj => D.interior_avoids_vertices e t ht j (he.trans hj) + +theorem crossing_of_ranges_not_vertices (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (hef : e ≠ f) (x : Plane) (he : x ∈ Set.range (D.edge e)) (hf : x ∈ Set.range (D.edge f)) + (hv : ∀ j, x ≠ D.vertex j) : x ∈ crossingPoints D := + ⟨e,f,hef,edgeInterior_of_range_not_vertices D e x he hv,edgeInterior_of_range_not_vertices D f x hf hv⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingRestriction.lean b/lean/OAI/Combinatorics/Crossing/DrawingRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca6decc40e05a78581ae0e4b462842dc0fd81e4d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingRestriction.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.RowCrossingCount +import Mathlib.Order.Fin.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n k : ℕ} + +def restrictEdge (f : Fin k ↪ Fin n) : BipartiteEdge m k ↪ BipartiteEdge m n := + Function.Embedding.prodMap (Function.Embedding.refl (Fin m)) f + +def restrictContinuousDrawing (D : ContinuousDrawing m n) (f : Fin k ↪ Fin n) : + ContinuousDrawing m k where + vertex := D.vertex ∘ Sum.map id f + vertex_injective := D.vertex_injective.comp (Sum.map_injective.mpr ⟨Function.injective_id, f.injective⟩) + edge e := D.edge (restrictEdge f e) + edge_injective e := D.edge_injective (restrictEdge f e) + interior_avoids_vertices e t ht v := D.interior_avoids_vertices (restrictEdge f e) t ht (Sum.map id f v) + +theorem restrict_edgeInterior (D : ContinuousDrawing m n) (f : Fin k ↪ Fin n) + (e : BipartiteEdge m k) : + edgeInterior (restrictContinuousDrawing D f) e = edgeInterior D (restrictEdge f e) := rfl + +theorem restrict_crossingPoints_subset (D : ContinuousDrawing m n) (f : Fin k ↪ Fin n) : + crossingPoints (restrictContinuousDrawing D f) ⊆ crossingPoints D := by + rintro x ⟨e,g,heg,he,hg⟩ + exact ⟨restrictEdge f e, restrictEdge f g, (restrictEdge f).injective.ne heg, he, hg⟩ + +def restrictDrawing (D : AdmissibleDrawing m n) (f : Fin k ↪ Fin n) : AdmissibleDrawing m k where + toContinuousDrawing := restrictContinuousDrawing D.toContinuousDrawing f + crossings_finite := D.crossings_finite.subset (restrict_crossingPoints_subset D.toContinuousDrawing f) + crossings_proper e g heg x he hg := + D.crossings_proper (restrictEdge f e) (restrictEdge f g) ((restrictEdge f).injective.ne heg) x he hg + no_triples e g h heg heh hgh := + D.no_triples (restrictEdge f e) (restrictEdge f g) (restrictEdge f h) + ((restrictEdge f).injective.ne heg) ((restrictEdge f).injective.ne heh) ((restrictEdge f).injective.ne hgh) + +theorem crossingCount_restrict_le (D : AdmissibleDrawing m n) (f : Fin k ↪ Fin n) : + crossingCount (restrictDrawing D f) ≤ crossingCount D := by + apply Finset.card_le_card + intro x hx + have hx' : x ∈ crossingPoints (restrictDrawing D f).toContinuousDrawing := by simpa using hx + have hh := restrict_crossingPoints_subset D.toContinuousDrawing f hx' + simpa using hh + +theorem restrict_noAdjacentCrossings (D : AdmissibleDrawing m n) (hD : NoAdjacentCrossings D) + (f : Fin k ↪ Fin n) : NoAdjacentCrossings (restrictDrawing D f) := by + intro e g heg hadj + apply hD (restrictEdge f e) (restrictEdge f g) ((restrictEdge f).injective.ne heg) + rcases hadj with hl | hr + · exact Or.inl hl + · exact Or.inr (congrArg f hr) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingSegmentIncidence.lean b/lean/OAI/Combinatorics/Crossing/DrawingSegmentIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8c5ba5a8b8f397b8853bebf8607f829a91ba194 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingSegmentIncidence.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.SubdivisionSegments +import OAI.Combinatorics.Crossing.EmbeddedGraphPaths + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem drawing_curve_meeting_mark (D : AdmissibleDrawing m n) (e f : BipartiteEdge m n) + (hef : e ≠ f) (x : Plane) (hx : x ∈ Set.range (D.edge e)) (hy : x ∈ Set.range (D.edge f)) : + x ∈ drawingMarks D.toFiniteIntersectionDrawing := by + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + by_cases hs0 : s=0 + · subst s + exact Or.inl ⟨.inl e.1,by simpa using hs⟩ + by_cases hs1 : s=1 + · subst s + exact Or.inl ⟨.inr e.2,by simpa using hs⟩ + by_cases ht0 : t=0 + · subst t + exact Or.inl ⟨.inl f.1,by simpa using ht⟩ + by_cases ht1 : t=1 + · subst t + exact Or.inl ⟨.inr f.2,by simpa using ht⟩ + exact Or.inr ⟨e,f,hef, + ⟨s,⟨lt_of_le_of_ne (show 0 ≤ s from s.property.1) (Ne.symm hs0), + lt_of_le_of_ne (show s ≤ 1 from s.property.2) hs1⟩,hs⟩, + ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,ht⟩⟩ + +abbrev DrawingPiece {D : AdmissibleDrawing m n} (P : ∀ e, PolygonalParametrization (D.edge e)) := + (e : BipartiteEdge m n) × Fin (P e).pieces + +def drawingPieceStart {D : AdmissibleDrawing m n} (P : ∀ e, PolygonalParametrization (D.edge e)) + (i : DrawingPiece P) : Plane := D.edge i.1 ((P i.1).knot i.2.castSucc) + +def drawingPieceEnd {D : AdmissibleDrawing m n} (P : ∀ e, PolygonalParametrization (D.edge e)) + (i : DrawingPiece P) : Plane := D.edge i.1 ((P i.1).knot i.2.succ) + +theorem drawingPiece_endpoints_ne {D : AdmissibleDrawing m n} + (P : ∀ e, PolygonalParametrization (D.edge e)) (i : DrawingPiece P) : + drawingPieceStart P i ≠ drawingPieceEnd P i := by + intro he + have hh := D.edge_injective i.1 he + exact ((P i.1).increasing (show i.2.castSucc < i.2.succ by change i.2.val < i.2.val+1; omega)).ne hh + +theorem drawing_pieces_meeting_endpoints (D : AdmissibleDrawing m n) + (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (p q : DrawingPiece P) (hpq : p ≠ q) (x : Plane) + (hx : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p)) + (hy : x ∈ segment ℝ (drawingPieceStart P q) (drawingPieceEnd P q)) : + (x=drawingPieceStart P p ∨ x=drawingPieceEnd P p) ∧ + (x=drawingPieceStart P q ∨ x=drawingPieceEnd P q) := by + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + by_cases hef : e=f + · subst f + have hij : i ≠ j := fun he => hpq (by subst j; rfl) + exact ⟨(P e).pieceTrace_other_piece_endpoint (D.edge_injective e) i j hij x hx hy, + (P e).pieceTrace_other_piece_endpoint (D.edge_injective e) j i (Ne.symm hij) x hy hx⟩ + · have hm := drawing_curve_meeting_mark D e f hef x + ((P e).pieceTrace_subset_range i hx) ((P f).pieceTrace_subset_range j hy) + exact ⟨subdivision_mark_endpoint D P hmark e i x hx hm, + subdivision_mark_endpoint D P hmark f j x hy hm⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingSpokePorts.lean b/lean/OAI/Combinatorics/Crossing/DrawingSpokePorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..75b87a2024a984edd41390b84e8e10a31623f492 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingSpokePorts.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.RadialBoundaryPorts +import OAI.Combinatorics.Crossing.ChainPieceInteriors + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem openSegmentTrace_reverse_mem (a b x : Plane) (hx : x ∈ openSegmentTrace a b) : + x ∈ openSegmentTrace b a := by + obtain ⟨t,ht,he⟩ := hx + exact ⟨1-t,⟨by linarith [ht.2],by linarith [ht.1]⟩,(segmentPoint_reverse a b t).trans he⟩ + +theorem squaredLength_sub_comm (a b : Plane) : squaredLength (a-b)=squaredLength (b-a) := by + dsimp [squaredLength] + ring + +def PolygonalChain.startPort {O : Set Plane} {a b : Plane} (P : PolygonalChain O a b) (r : ℝ) : Plane := + radialPort (P.vertices 0) (P.vertices 1) r + +def PolygonalChain.endPort {O : Set Plane} {a b : Plane} (P : PolygonalChain O a b) (r : ℝ) : Plane := + radialPort (P.vertices P.pieces) (P.vertices (P.pieces-1)) r + +theorem drawing_chain_startPort_interior {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) (hshort : r^2 < squaredLength (P.vertices 1-P.vertices 0)) : + P.startPort r ∈ edgeInterior D e := by + exact drawing_chain_piece_open_subset_interior D e P hmin 0 (drawing_chain_pieces_pos D e P) + (radialPort_mem_openSegment _ _ r hr hshort) + +theorem drawing_chain_endPort_interior {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + P.endPort r ∈ edgeInterior D e := by + have hp := drawing_chain_pieces_pos D e P + have hs : r^2 < squaredLength (P.vertices (P.pieces-1)-P.vertices P.pieces) := by + rwa [squaredLength_sub_comm] + have hx := openSegmentTrace_reverse_mem _ _ _ (radialPort_mem_openSegment _ _ r hr hs) + apply drawing_chain_piece_open_subset_interior D e P hmin (P.pieces-1) (by omega) + simpa only [PolygonalChain.endPort,show P.pieces-1+1=P.pieces by omega] using hx + +theorem drawing_chain_startPort_circle {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) (r : ℝ) : + squaredLength (P.startPort r-D.vertex (.inl e.1))=r^2 := by + have hp := drawing_chain_pieces_pos D e P + have h := radialPort_on_circle (P.vertices 0) (P.vertices 1) + (P.minimum_vertices_ne hmin 0 1 (by omega) hp) r + simpa only [PolygonalChain.startPort,P.first] using h + +theorem drawing_chain_endPort_circle {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) (r : ℝ) : + squaredLength (P.endPort r-D.vertex (.inr e.2))=r^2 := by + have hp := drawing_chain_pieces_pos D e P + have h := radialPort_on_circle (P.vertices P.pieces) (P.vertices (P.pieces-1)) + (Ne.symm (P.minimum_vertices_ne hmin (P.pieces-1) P.pieces (by omega) (by omega))) r + simpa only [PolygonalChain.endPort,P.last] using h + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingSubdivisionGraph.lean b/lean/OAI/Combinatorics/Crossing/DrawingSubdivisionGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..78487d02e20680c20571a4328f08b7c407bf606c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingSubdivisionGraph.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.Crossing.DrawingSegmentIncidence + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +def drawingSubdivisionGraph (P : ∀ e, PolygonalParametrization (D.edge e)) : SimpleGraph Plane where + Adj := fun a b => a ≠ b ∧ ∃ p : DrawingPiece P, + (a=drawingPieceStart P p ∧ b=drawingPieceEnd P p) ∨ + (a=drawingPieceEnd P p ∧ b=drawingPieceStart P p) + symm := ⟨by + rintro a b ⟨hab,p,hp⟩ + refine ⟨Ne.symm hab,p,?_⟩ + rcases hp with ⟨ha,hb⟩ | ⟨ha,hb⟩ + · exact Or.inr ⟨hb,ha⟩ + · exact Or.inl ⟨hb,ha⟩⟩ + loopless := ⟨by rintro a ⟨ha,_⟩; exact ha rfl⟩ + +theorem drawingSubdivisionGraph_piece_adj (P : ∀ e, PolygonalParametrization (D.edge e)) + (p : DrawingPiece P) : + (drawingSubdivisionGraph P).Adj (drawingPieceStart P p) (drawingPieceEnd P p) := + ⟨drawingPiece_endpoints_ne P p,p,Or.inl ⟨rfl,rfl⟩⟩ + +theorem common_endpoint_alternatives (a b c d x : Plane) (hab : x=a ∨ x=b) (hcd : x=c ∨ x=d) : + (a=c ∧ x=a) ∨ (a=d ∧ x=a) ∨ (b=c ∧ x=b) ∨ (b=d ∧ x=b) := by + rcases hab with ha | hb <;> rcases hcd with hc | hd + · exact Or.inl ⟨ha.symm.trans hc,ha⟩ + · exact Or.inr (Or.inl ⟨ha.symm.trans hd,ha⟩) + · exact Or.inr (Or.inr (Or.inl ⟨hb.symm.trans hc,hb⟩)) + · exact Or.inr (Or.inr (Or.inr ⟨hb.symm.trans hd,hb⟩)) + +theorem drawingSubdivisionGraph_embedding (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) : + StraightEdgeEmbedding (drawingSubdivisionGraph P) id := by + refine ⟨Function.injective_id,?_⟩ + rintro a b c d ⟨hab,p,hp⟩ ⟨hcd,q,hq⟩ x hx hy + by_cases hpq : p=q + · subst q + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ <;> rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact Or.inl ⟨rfl,rfl⟩ + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inl ⟨rfl,rfl⟩ + · have hxp : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p) := by + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hx + · simpa only [id_eq,segment_symm] using hx + have hxq : x ∈ segment ℝ (drawingPieceStart P q) (drawingPieceEnd P q) := by + rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hy + · simpa only [id_eq,segment_symm] using hy + obtain ⟨hpe,hqe⟩ := drawing_pieces_meeting_endpoints D P hmark p q hpq x hxp hxq + have heab : x=a ∨ x=b := by + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hpe + · exact hpe.symm + have hecd : x=c ∨ x=d := by + rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hqe + · exact hqe.symm + exact Or.inr (Or.inr (common_endpoint_alternatives a b c d x heab hecd)) + +theorem drawingSubdivisionGraph_finite_support (P : ∀ e, PolygonalParametrization (D.edge e)) : + {a : Plane | ∃ b, (drawingSubdivisionGraph P).Adj a b}.Finite := by + have hf : (Set.range (drawingPieceStart P) ∪ Set.range (drawingPieceEnd P)).Finite := + (Set.finite_range _).union (Set.finite_range _) + apply hf.subset + rintro a ⟨b,hab,p,hp⟩ + rcases hp with ⟨ha,hb⟩ | ⟨ha,hb⟩ + · exact Or.inl ⟨p,ha.symm⟩ + · exact Or.inr ⟨p,ha.symm⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingVertexPlacement.lean b/lean/OAI/Combinatorics/Crossing/DrawingVertexPlacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e7f09efc262a6af1aa76b2c3125e7aa78111223 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingVertexPlacement.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.Crossing.DrawingPorts +import OAI.Combinatorics.Crossing.VertexDiskSpokes + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +def vertexMark (_C : DrawingPassages D) (v : BipartiteVertex m n) : DrawingMark D := + ⟨D.vertex v,Or.inl ⟨v,rfl⟩⟩ + +theorem vertexMark_injective (C : DrawingPassages D) : Function.Injective C.vertexMark := by + intro v w he + exact D.vertex_injective (congrArg Subtype.val he) + +theorem exists_drawing_vertex_placement (C : DrawingPassages D) : + ∃ v : BipartiteVertex m n → Plane, Function.Injective v ∧ + (∀ i, squaredLength (v i-D.vertex i) < C.radius^2) ∧ + (∀ i (p : C.PortsAt (C.vertexMark i)), v i ≠ C.portPoint p.val) ∧ + (∀ i (p q : C.PortsAt (C.vertexMark i)), p ≠ q → + det2 (C.portPoint p.val-v i) (C.portPoint q.val-v i) ≠ 0) := by + classical + have hex (i : BipartiteVertex m n) : ∃ v : Plane, + squaredLength (v-D.vertex i) < C.radius^2 ∧ + (∀ p : C.PortsAt (C.vertexMark i), v ≠ C.portPoint p.val) ∧ + (∀ p q : C.PortsAt (C.vertexMark i), p ≠ q → det2 (C.portPoint p.val-v) (C.portPoint q.val-v) ≠ 0) := + exists_vertex_disk_point (D.vertex i) C.radius C.radius_pos + (fun p : C.PortsAt (C.vertexMark i) => C.portPoint p.val) + (C.portPoint_injective.comp Subtype.val_injective) (C.portsAt_on_circle (C.vertexMark i)) + choose v hv hne hdet using hex + refine ⟨v,?_,hv,hne,hdet⟩ + intro i j he + by_contra hij + have hd := C.disks_disjoint (C.vertexMark i) (C.vertexMark j) (C.vertexMark_injective.ne hij) + have hi : v i ∈ closedRoundDisk (C.vertexMark i).val C.radius := (hv i).le + have hj : v j ∈ closedRoundDisk (C.vertexMark j).val C.radius := (hv j).le + exact Set.disjoint_left.mp hd hi (he.symm ▸ hj) + +theorem vertex_spoke_injective (C : DrawingPassages D) (v : BipartiteVertex m n → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark i)) : + Function.Injective (Path.segment (v i) (C.portPoint p.val)) := by + apply Path.segment_injective_of_ne + intro he + have h := hv i + have hp : squaredLength (C.portPoint p.val-D.vertex i)=C.radius^2 := C.portsAt_on_circle (C.vertexMark i) p + rw [he,hp] at h + exact lt_irrefl _ h + +theorem vertex_spoke_interior (C : DrawingPassages D) (v : BipartiteVertex m n → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark i)) (t : unitInterval) + (ht : t < 1) : squaredLength ((Path.segment (v i) (C.portPoint p.val)) t-D.vertex i) < C.radius^2 := by + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact spoke_in_open_disk (D.vertex i) (v i) (C.portPoint p.val) C.radius (hv i) + (C.portsAt_on_circle (C.vertexMark i) p) t.val ⟨t.property.1,ht⟩ + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawingWalkCutTraces.lean b/lean/OAI/Combinatorics/Crossing/DrawingWalkCutTraces.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c148b7e6fef7423d99786c338bb2dce48f5ec21 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawingWalkCutTraces.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.Crossing.DrawingEdgeWalkTrace + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem graphWalkPath_range_cases {V : Type*} {G : SimpleGraph V} (pos : V → Plane) + {a b : V} (p : G.Walk a b) (x : Plane) (hx : x ∈ Set.range (graphWalkPath pos p)) : + x=pos a ∨ ∃ i, i < p.length ∧ x ∈ segment ℝ (pos (p.getVert i)) (pos (p.getVert (i+1))) := by + by_cases hp : p.length=0 + · change x ∈ Set.range (polygonalArcPath (fun i => pos (p.getVert i)) p.length) at hx + rw [hp] at hx + obtain ⟨t,ht⟩ := hx + exact Or.inl (by simpa [polygonalArcPath,p.getVert_zero] using ht.symm) + · exact Or.inr (polygonalArcPath_range_piece _ _ (by omega) x hx) + +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem drawingEdgeWalk_take_trace (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) (k : Fin ((P e).pieces+1)) : + Set.range (graphWalkPath id ((drawingEdgeWalk P e).take k.val)) ⊆ + D.edge e '' Set.Icc (0 : unitInterval) ((P e).knot k) := by + intro x hx + rcases graphWalkPath_range_cases id ((drawingEdgeWalk P e).take k.val) x hx with he | ⟨i,hi,hxi⟩ + · exact ⟨0,⟨le_rfl,((P e).knot k).property.1⟩,(D.edge e).source.trans he.symm⟩ + · have hil : i < (P e).pieces := by + rw [SimpleGraph.Walk.take_length,drawingEdgeWalk_length] at hi + omega + have hik : i+1 ≤ k.val := by + rw [SimpleGraph.Walk.take_length,drawingEdgeWalk_length] at hi + omega + simp only [id_eq,SimpleGraph.Walk.take_getVert] at hxi + rw [show min k.val i=i by omega,show min k.val (i+1)=i+1 by omega, + drawingEdgeWalk_getVert P e i (by omega),drawingEdgeWalk_getVert P e (i+1) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨i,hil⟩ + have h0 : (P e).vertices i=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + rw [h0,h1] at hxi + obtain ⟨t,ht⟩ := (P e).pieceTrace_parameter j x hxi + have hbetween := intervalSegment_between ((P e).knot j.castSucc) ((P e).knot j.succ) t + ((P e).increasing.monotone (by change i ≤ i+1; omega)) + exact ⟨intervalSegment ((P e).knot j.castSucc) ((P e).knot j.succ) t, + ⟨(intervalSegment _ _ t).property.1,hbetween.2.trans ((P e).increasing.monotone hik)⟩,ht⟩ + +theorem drawingEdgeWalk_drop_trace (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : BipartiteEdge m n) (k : Fin ((P e).pieces+1)) : + Set.range (graphWalkPath id ((drawingEdgeWalk P e).drop k.val)) ⊆ + D.edge e '' Set.Icc ((P e).knot k) (1 : unitInterval) := by + intro x hx + rcases graphWalkPath_range_cases id ((drawingEdgeWalk P e).drop k.val) x hx with he | ⟨i,hi,hxi⟩ + · refine ⟨(P e).knot k,⟨le_rfl,((P e).knot k).property.2⟩,?_⟩ + have hh : (drawingEdgeWalk P e).getVert k.val=D.edge e ((P e).knot k) := + (drawingEdgeWalk_getVert P e k.val (by omega)).trans ((P e).vertices_at k) + exact hh.symm.trans he.symm + · have hil : k.val+i < (P e).pieces := by + rw [SimpleGraph.Walk.drop_length,drawingEdgeWalk_length] at hi + omega + simp only [id_eq,SimpleGraph.Walk.drop_getVert] at hxi + rw [drawingEdgeWalk_getVert P e (k.val+i) (by omega), + drawingEdgeWalk_getVert P e (k.val+(i+1)) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨k.val+i,hil⟩ + have h0 : (P e).vertices (k.val+i)=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (k.val+(i+1))=D.edge e ((P e).knot j.succ) := by + have hh : (P e).vertices (k.val+i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + simpa only [Nat.add_assoc] using hh + rw [h0,h1] at hxi + obtain ⟨t,ht⟩ := (P e).pieceTrace_parameter j x hxi + have hbetween := intervalSegment_between ((P e).knot j.castSucc) ((P e).knot j.succ) t + ((P e).increasing.monotone (by change k.val+i ≤ k.val+i+1; omega)) + refine ⟨intervalSegment ((P e).knot j.castSucc) ((P e).knot j.succ) t,⟨?_,?_⟩,ht⟩ + · exact ((P e).increasing.monotone (show k ≤ j.castSucc by change k.val ≤ k.val+i; omega)).trans hbetween.1 + · exact (intervalSegment _ _ t).property.2 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/DrawnEdgeChains.lean b/lean/OAI/Combinatorics/Crossing/DrawnEdgeChains.lean new file mode 100644 index 0000000000000000000000000000000000000000..937b77a218738423340c20285265350700336169 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/DrawnEdgeChains.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.Crossing.FinitePolygonalComposition +import OAI.Combinatorics.Crossing.TrackEndpointConnections + +namespace OAI + +noncomputable section +namespace Zarankiewicz +namespace VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +def trackChain (e : BipartiteEdge m n) : PolygonalChain Set.univ (V.startPort e) (V.endPort e) where + pieces := V.pieces e + vertices := V.vertices e + first := V.vertices_first e + last := V.vertices_last e + start_mem := Set.mem_univ _ + inside := fun _ _ => Set.subset_univ _ + +def chordChain (j : BipartiteVertex m n) (a b : IncidentEdges j) : + PolygonalChain Set.univ (V.spokePort j a) (V.spokePort j b) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {m n : ℕ} {D : ContinuousDrawing m n} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +def shiftedTrackChain (e : BipartiteEdge m n) (ε : ℝ) : + PolygonalChain Set.univ (C.tangentPort (Sum.inl e.1) (V.leftIncident e) ε) + (C.tangentPort (Sum.inr e.2) (V.rightIncident e) ε) where + pieces := V.pieces e + vertices := shiftedTrack (V.vertices e) (V.pieces e) ε + first := V.shiftedTrack_first C e ε + last := V.shiftedTrack_last C e ε + start_mem := Set.mem_univ _ + inside := fun _ _ => Set.subset_univ _ + +def connectorChain (j : BipartiteVertex m n) (e : IncidentEdges j) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort j e ε) (C.tangentPort j e ε) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +def shiftedEdgeChain (e : BipartiteEdge m n) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort (Sum.inl e.1) (V.leftIncident e) ε) + (C.shiftedPort (Sum.inr e.2) (V.rightIncident e) ε) := + ((C.connectorChain (Sum.inl e.1) (V.leftIncident e) ε).join (C.shiftedTrackChain e ε)).join + (C.connectorChain (Sum.inr e.2) (V.rightIncident e) ε).reverse + +def shiftedChordChain (j : BipartiteVertex m n) (a b : IncidentEdges j) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort j a ε) (C.shiftedPort j b ε) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +theorem shiftedEdgeChain_pieces (e : BipartiteEdge m n) (ε : ℝ) : + (C.shiftedEdgeChain e ε).pieces=V.pieces e+2 := by + simp only [shiftedEdgeChain,PolygonalChain.pieces_join,connectorChain, + PolygonalChain.pieces_single,shiftedTrackChain,PolygonalChain.reverse] + omega + +theorem shiftedEdgeChain_intersection_right (e : BipartiteEdge m n) (ε : ℝ) + (w : ℕ → Plane) (k : ℕ) : + polygonIntersection w (C.shiftedEdgeChain e ε).vertices k (C.shiftedEdgeChain e ε).pieces = + polygonIntersection w (C.connectorChain (Sum.inl e.1) (V.leftIncident e) ε).vertices k 1 + + polygonIntersection w (shiftedTrack (V.vertices e) (V.pieces e) ε) k (V.pieces e) - + polygonIntersection w (C.connectorChain (Sum.inr e.2) (V.rightIncident e) ε).vertices k 1 := by + unfold shiftedEdgeChain + rw [PolygonalChain.intersection_join_right,PolygonalChain.intersection_join_right, + PolygonalChain.intersection_reverse_right] + rfl + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/EmbeddedGraphPaths.lean b/lean/OAI/Combinatorics/Crossing/EmbeddedGraphPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ed034d4ba6aa33cf6d6904905532dc28c23edf0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/EmbeddedGraphPaths.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.PolygonalArcInjective +import OAI.Combinatorics.Crossing.FiniteAffineCover +import Mathlib.Combinatorics.SimpleGraph.Paths + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def StraightEdgeEmbedding {V : Type*} (G : SimpleGraph V) (pos : V → Plane) : Prop := + Function.Injective pos ∧ + ∀ a b c d, G.Adj a b → G.Adj c d → ∀ x, + x ∈ segment ℝ (pos a) (pos b) → x ∈ segment ℝ (pos c) (pos d) → + (a=c ∧ b=d) ∨ (a=d ∧ b=c) ∨ + (a=c ∧ x=pos a) ∨ (a=d ∧ x=pos a) ∨ + (b=c ∧ x=pos b) ∨ (b=d ∧ x=pos b) + +def graphWalkPath {V : Type*} {G : SimpleGraph V} (pos : V → Plane) {a b : V} (p : G.Walk a b) : + Path (pos a) (pos b) := + (polygonalArcPath (fun i => pos (p.getVert i)) p.length).cast + (congrArg pos p.getVert_zero).symm (congrArg pos p.getVert_length).symm + +theorem graphWalkPath_hasFiniteAffineCover {V : Type*} {G : SimpleGraph V} (pos : V → Plane) + {a b : V} (p : G.Walk a b) : HasFiniteAffineCover (graphWalkPath pos p) := + polygonalArcPath_hasFiniteAffineCover _ _ + +theorem graphWalkPath_injective {V : Type*} {G : SimpleGraph V} (pos : V → Plane) + (hemb : StraightEdgeEmbedding G pos) {a b : V} (hab : a ≠ b) + (p : G.Walk a b) (hp : p.IsPath) : Function.Injective (graphWalkPath pos p) := by + have hn : 0 < p.length := by + by_contra h + have hz : p.length=0 := by omega + have he := p.getVert_zero.symm.trans (hz ▸ p.getVert_length) + exact hab he + change Function.Injective (polygonalArcPath (fun i => pos (p.getVert i)) p.length) + apply polygonalArcPath_injective _ _ hn + · intro i hi he + have hij := hp.getVert_injOn (show i ≤ p.length by omega) (show i+1 ≤ p.length by omega) (hemb.1 he) + omega + · intro i j hij hj x hx hy + have hmeet := hemb.2 _ _ _ _ (p.adj_getVert_succ (show i < p.length by omega)) + (p.adj_getVert_succ hj) x hx hy + have hindex (r s : ℕ) (hr : r ≤ p.length) (hs : s ≤ p.length) + (he : p.getVert r=p.getVert s) : r=s := hp.getVert_injOn hr hs he + rcases hmeet with ⟨h₁,h₂⟩ | ⟨h₁,h₂⟩ | ⟨h₁,hx⟩ | ⟨h₁,hx⟩ | ⟨h₁,hx⟩ | ⟨h₁,hx⟩ + · have hh := hindex i j (by omega) (by omega) h₁ + omega + · have hh := hindex i (j+1) (by omega) (by omega) h₁ + omega + · have hh := hindex i j (by omega) (by omega) h₁ + omega + · have hh := hindex i (j+1) (by omega) (by omega) h₁ + omega + · have hh := hindex (i+1) j (by omega) (by omega) h₁ + exact ⟨hh.symm,hx.trans (congrArg pos h₁)⟩ + · have hh := hindex (i+1) (j+1) (by omega) (by omega) h₁ + omega + +theorem exists_simple_graphWalkPath {V : Type*} [DecidableEq V] {G : SimpleGraph V} + (pos : V → Plane) (hemb : StraightEdgeEmbedding G pos) {a b : V} (hab : a ≠ b) + (p : G.Walk a b) : + ∃ q : G.Walk a b, q.IsPath ∧ List.Sublist q.darts p.darts ∧ + Function.Injective (graphWalkPath pos q) ∧ HasFiniteAffineCover (graphWalkPath pos q) := + ⟨p.bypass,p.bypass_isPath,p.darts_bypass_sublist_darts, + graphWalkPath_injective pos hemb hab p.bypass p.bypass_isPath, + graphWalkPath_hasFiniteAffineCover pos p.bypass⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/EndpointFlagPairing.lean b/lean/OAI/Combinatorics/Crossing/EndpointFlagPairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..dcb317d226079288d483943aede979d32d3aa66e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/EndpointFlagPairing.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.Crossing.GlobalCycleAveraging + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +abbrev IncidentFlag (m n : ℕ) := (j : BipartiteVertex m n) × IncidentEdges j + +def dartSourceFlag (d : (completeBipartite m n).Dart) : IncidentFlag m n := + ⟨d.fst,dartSourceIncident d⟩ + +def dartTargetFlag (d : (completeBipartite m n).Dart) : IncidentFlag m n := + ⟨d.snd,dartTargetIncident d⟩ + +theorem incidentCast_refl {j : BipartiteVertex m n} (e : IncidentEdges j) : + incidentCast (rfl : j=j) e=e := Subtype.ext rfl + +theorem incidentFlag_cast {j k : BipartiteVertex m n} (h : j=k) (e : IncidentEdges j) : + (⟨k,incidentCast h e⟩ : IncidentFlag m n)=⟨j,e⟩ := by + subst k + rw [incidentCast_refl] + +theorem dartPassageNext_flag (d : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (i : ℕ) : + (⟨(d i).snd,dartPassageNext d hd i⟩ : IncidentFlag m n)=dartSourceFlag (d (i+1)) := + incidentFlag_cast (hd i).symm _ + +namespace TruncatedSpokeCoordinates +variable {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def flagPairing (a b : IncidentFlag m n) : ℝ := + if h : b.1=a.1 then orderSign (C.node a.1 a.2) (C.node a.1 (incidentCast h b.2))/2 else 0 + +theorem vertexChordPairing_flags (j k : BipartiteVertex m n) + (a b : IncidentEdges j) (c d : IncidentEdges k) : + C.vertexChordPairing j k a b c d= + C.flagPairing ⟨j,a⟩ ⟨k,c⟩-C.flagPairing ⟨j,a⟩ ⟨k,d⟩- + C.flagPairing ⟨j,b⟩ ⟨k,c⟩+C.flagPairing ⟨j,b⟩ ⟨k,d⟩ := by + by_cases h : k=j + · subst k + simp only [vertexChordPairing,flagPairing,dite_eq_left rfl,incidentCast_refl,chordEndpointPairing,dite_true] + ring + · simp only [vertexChordPairing,flagPairing,dite_eq_right h,sub_zero,add_zero] + +theorem passagePairing_flags (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ) : + C.passagePairing d f hd hf i j= + C.flagPairing (dartTargetFlag (d i)) (dartTargetFlag (f j))- + C.flagPairing (dartTargetFlag (d i)) (dartSourceFlag (f (j+1)))- + C.flagPairing (dartSourceFlag (d (i+1))) (dartTargetFlag (f j))+ + C.flagPairing (dartSourceFlag (d (i+1))) (dartSourceFlag (f (j+1))) := by + rw [passagePairing,C.vertexChordPairing_flags,dartPassageNext_flag,dartPassageNext_flag] + rfl + +def edgeEndpointPairing (e f : BipartiteEdge m n) : ℝ := + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))+ + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f)) + +theorem flagPairing_source_target (e f : BipartiteEdge m n) : + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))=0 := by + simp [flagPairing,dartSourceFlag,dartTargetFlag,forwardBipartiteDart] + +theorem flagPairing_target_source (e f : BipartiteEdge m n) : + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))=0 := by + simp [flagPairing,dartSourceFlag,dartTargetFlag,forwardBipartiteDart] + +theorem dart_endpoint_pairing (a b : (completeBipartite m n).Dart) : + C.flagPairing (dartTargetFlag a) (dartTargetFlag b)- + C.flagPairing (dartTargetFlag a) (dartSourceFlag b)- + C.flagPairing (dartSourceFlag a) (dartTargetFlag b)+ + C.flagPairing (dartSourceFlag a) (dartSourceFlag b)= + bipartiteDartSign a*bipartiteDartSign b*C.edgeEndpointPairing (bipartiteDartEdge a) (bipartiteDartEdge b) := by + rcases bipartiteDart_cases a with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> + rcases bipartiteDart_cases b with ⟨f,rfl⟩ | ⟨f,rfl⟩ + all_goals + change _ = _*_*C.edgeEndpointPairing e f + have hST := C.flagPairing_source_target e f + have hTS := C.flagPairing_target_source e f + simp only [edgeEndpointPairing] at * + change C.flagPairing _ _=0 at hST hTS + · rw [hST,hTS] + change _ = 1*1*_ + ring + · change C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))- + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))- + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))+ + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))=1*(-1)*_ + rw [hST,hTS] + ring + · change C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))- + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))- + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))+ + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))=(-1)*1*_ + rw [hST,hTS] + ring + · change C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))- + C.flagPairing (dartSourceFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))- + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartSourceFlag (forwardBipartiteDart f))+ + C.flagPairing (dartTargetFlag (forwardBipartiteDart e)) (dartTargetFlag (forwardBipartiteDart f))=(-1)*(-1)*_ + rw [hST,hTS] + ring + +end TruncatedSpokeCoordinates +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/EndpointVisits.lean b/lean/OAI/Combinatorics/Crossing/EndpointVisits.lean new file mode 100644 index 0000000000000000000000000000000000000000..395e815c3b476d3a594e5ed2be582fc28e69f3eb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/EndpointVisits.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.Crossing.FirstLastVisits + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem last_sublevel_visit (f : ℝ → ℝ) (hf : Continuous f) (r : ℝ) + (h0 : f 0 < r) (h1 : r < f 1) : + ∃ b : ℝ, 0 < b ∧ b < 1 ∧ f b=r ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, f t ≤ r → t ≤ b) := by + let S : Set ℝ := Set.Icc 0 1 ∩ {t | f t ≤ r} + have hS : IsCompact S := isCompact_Icc.inter_right (isClosed_le hf continuous_const) + obtain ⟨b,hb⟩ := hS.exists_isGreatest ⟨0,⟨by norm_num,by norm_num⟩,h0.le⟩ + have hb1 : b < 1 := lt_of_le_of_ne hb.1.1.2 (by + intro he + have hh := hb.1.2 + rw [he] at hh + exact (not_le_of_gt h1) hh) + have hfb : f b=r := by + apply le_antisymm hb.1.2 + by_contra hn + have hlt : f b < r := lt_of_not_ge hn + obtain ⟨t,ht,he⟩ := intermediate_value_Icc hb.1.1.2 hf.continuousOn ⟨hlt.le,h1.le⟩ + have hmem : t ∈ S := ⟨⟨hb.1.1.1.trans ht.1,ht.2⟩,he.le⟩ + have htb : t=b := le_antisymm (hb.2 hmem) ht.1 + rw [htb] at he + exact hlt.ne he + have hb0 : 0 < b := lt_of_le_of_ne hb.1.1.1 (by + intro he + rw [← he] at hfb + exact h0.ne hfb) + exact ⟨b,hb0,hb1,hfb,fun t ht hh => hb.2 ⟨ht,hh⟩⟩ + +theorem first_sublevel_visit (f : ℝ → ℝ) (hf : Continuous f) (r : ℝ) + (h0 : r < f 0) (h1 : f 1 < r) : + ∃ a : ℝ, 0 < a ∧ a < 1 ∧ f a=r ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, f t ≤ r → a ≤ t) := by + obtain ⟨b,hb0,hb1,hfb,hb⟩ := last_sublevel_visit (fun t => f (1-t)) + (hf.comp (continuous_const.sub continuous_id)) r (by simpa using h1) (by simpa using h0) + refine ⟨1-b,by linarith,by linarith,hfb,?_⟩ + intro t ht hh + have he := hb (1-t) ⟨by linarith [ht.2],by linarith [ht.1]⟩ (by simpa using hh) + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/EvaluationAmbient.lean b/lean/OAI/Combinatorics/Crossing/EvaluationAmbient.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef4c770a3a6d66b5f404ad270cd9a5db456ab561 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/EvaluationAmbient.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.PolynomialFiltration + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module Submodule +variable {W ι : Type*} [AddCommGroup W] [Module ℝ W] +variable (U : ι → Submodule ℝ W) (node : ι → ℝ) + +def constrainedInclusion {Z₁ Z₂ : Submodule ℝ W} (hZ : Z₁ ≤ Z₂) (k : ℕ) : + constrained U node Z₁ k →ₗ[ℝ] constrained U node Z₂ k where + toFun p := ⟨PolynomialModule.map ℝ (Submodule.inclusion hZ) p.val, by + constructor + · intro n hn + change Submodule.inclusion hZ (p.val.coeff n) = 0 + rw [p.property.1 n hn, map_zero] + · intro i + rw [show eval (node i) (PolynomialModule.map ℝ (Submodule.inclusion hZ) p.val) = + Submodule.inclusion hZ (eval (node i) p.val) by + simpa using PolynomialModule.eval_map ℝ (Submodule.inclusion hZ) p.val (node i)] + exact p.property.2 i⟩ + map_add' p q := Subtype.ext ((PolynomialModule.map ℝ (Submodule.inclusion hZ)).map_add p.val q.val) + map_smul' c p := Subtype.ext ((PolynomialModule.map ℝ (Submodule.inclusion hZ)).map_smul c p.val) + +theorem constrainedInclusion_eval {Z₁ Z₂ : Submodule ℝ W} (hZ : Z₁ ≤ Z₂) (k : ℕ) + (t : ℝ) (p : constrained U node Z₁ k) : + Z₂.subtype (eval t (constrainedInclusion U node hZ k p).val) = Z₁.subtype (eval t p.val) := by + change Z₂.subtype (eval t (PolynomialModule.map ℝ (Submodule.inclusion hZ) p.val)) = _ + rw [show eval t (PolynomialModule.map ℝ (Submodule.inclusion hZ) p.val) = + Submodule.inclusion hZ (eval t p.val) by + simpa using PolynomialModule.eval_map ℝ (Submodule.inclusion hZ) p.val t] + rfl + +def ambientEval (Z : Submodule ℝ W) (k : ℕ) (t : ℝ) : constrained U node Z k →ₗ[ℝ] W := + Z.subtype.comp (constrainedEval U node Z k t) + +def ambientEvalRange (Z : Submodule ℝ W) (k : ℕ) (t : ℝ) : Submodule ℝ W := + LinearMap.range (ambientEval U node Z k t) + +theorem finrank_ambientEvalRange (Z : Submodule ℝ W) (k : ℕ) (t : ℝ) : + finrank ℝ (ambientEvalRange U node Z k t) = finrank ℝ (evaluationFiltration U node Z t k) := by + unfold ambientEvalRange ambientEval evaluationFiltration + rw [LinearMap.range_comp] + exact Submodule.finrank_map_subtype_eq Z _ + +theorem finrank_ambientEvalRange_off_node [FiniteDimensional ℝ W] + (Z : Submodule ℝ W) (h : ℕ) (t : ℝ) (ht : ∀ i, node i ≠ t) : + finrank ℝ (ambientEvalRange U node Z (h+1) t) = rankIncrement U node Z h := by + rw [finrank_ambientEvalRange] + exact finrank_eval_range U node Z h t ht + +theorem ambientEvalRange_mono_coeff {Z₁ Z₂ : Submodule ℝ W} (hZ : Z₁ ≤ Z₂) (k : ℕ) (t : ℝ) : + ambientEvalRange U node Z₁ k t ≤ ambientEvalRange U node Z₂ k t := by + intro z hz + obtain ⟨p, hp⟩ := hz + refine ⟨constrainedInclusion U node hZ k p, ?_⟩ + exact (constrainedInclusion_eval U node hZ k t p).trans hp + +theorem ambientEvalRange_le_coeff (Z : Submodule ℝ W) (k : ℕ) (t : ℝ) : + ambientEvalRange U node Z k t ≤ Z := by + intro z hz + obtain ⟨p, rfl⟩ := hz + exact (eval t p.val).property + +theorem ambientEvalRange_at_node_le (Z : Submodule ℝ W) (k : ℕ) (i : ι) : + ambientEvalRange U node Z k (node i) ≤ U i := by + intro z hz + obtain ⟨p, rfl⟩ := hz + exact p.property.2 i + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/EvenCrossingLowerBound.lean b/lean/OAI/Combinatorics/Crossing/EvenCrossingLowerBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..78b502593a6e44a176b25a107d664d897efd51a5 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/EvenCrossingLowerBound.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.Crossing.OddCrossingLowerBound +import OAI.Combinatorics.Crossing.DeletionCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +theorem even_successor_crossing_lower_bound (m s : ℕ) (D : AdmissibleDrawing m ((2*s+1)+1)) : + axisPairs m*axisPairs ((2*s+1)+1) ≤ crossingCount D := by + by_cases hs : 0 < s + · obtain ⟨A,hcount,hpoly,hnorm,hstraight,htrans⟩ := polygonal_no_adjacent_locally_transverse D + have hsum : (∑ v : Fin ((2*s+1)+1), axisPairs m*axisPairs (2*s+1)) ≤ + ∑ v : Fin ((2*s+1)+1), crossingCount (deleteRightVertex A v) := by + apply Finset.sum_le_sum + intro v hv + exact odd_crossing_lower_bound m s (deleteRightVertex A v) + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] at hsum + rw [sum_delete_crossingCount A hnorm] at hsum + have hN : (2*s+1)+1=2*(s+1) := by omega + have hprev : 2*s+1=2*(s+1)-1 := by omega + have hfloor : ((2*s+1)+1)*axisPairs (2*s+1)= + (((2*s+1)+1)-2)*axisPairs ((2*s+1)+1) := by + rw [hN,hprev] + exact even_deletion_floor (s+1) + have hmul : (((2*s+1)+1)-2)*(axisPairs m*axisPairs ((2*s+1)+1)) ≤ + (((2*s+1)+1)-2)*crossingCount A := by + calc + _ = axisPairs m*((((2*s+1)+1)-2)*axisPairs ((2*s+1)+1)) := by ring + _ = axisPairs m*(((2*s+1)+1)*axisPairs (2*s+1)) := by rw [← hfloor] + _ = ((2*s+1)+1)*(axisPairs m*axisPairs (2*s+1)) := by ring + _ ≤ _ := hsum + exact (Nat.le_of_mul_le_mul_left hmul (by omega)).trans hcount + · have he : s=0 := Nat.eq_zero_of_not_pos hs + subst s + simp [axisPairs] + +theorem crossing_lower_bound (m n : ℕ) (D : AdmissibleDrawing m n) : + axisPairs m*axisPairs n ≤ crossingCount D := by + rcases Nat.even_or_odd n with h | h + · obtain ⟨s,hs⟩ := h + cases s with + | zero => + have hn : n=0 := by omega + cases hn + simp [axisPairs] + | succ s => + have he : n=(2*s+1)+1 := by omega + cases he + exact even_successor_crossing_lower_bound m s D + · obtain ⟨s,hs⟩ := h + have hn : n=2*s+1 := by omega + cases hn + exact odd_crossing_lower_bound m s D + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExpectedTrackGeometry.lean b/lean/OAI/Combinatorics/Crossing/ExpectedTrackGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa72e2e3ce1c3ad7e0353a8b5890865ea2af483e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExpectedTrackGeometry.lean @@ -0,0 +1,32 @@ +import OAI.Combinatorics.Crossing.UniformTrackPerturbation +import OAI.Combinatorics.Crossing.LocallyTransverseNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz.ExpectedTrackGeometry + +theorem actual_normalized_tracks {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ A : AdmissibleDrawing m n, + (crossingPoints A.toContinuousDrawing).ncard ≤ (crossingPoints D.toContinuousDrawing).ncard ∧ + ∃ V : VertexTruncation A.toContinuousDrawing, + (∀ e, Function.Injective (V.path e)) ∧ + (∀ e f : BipartiteEdge m n, e ≠ f → + Set.range (V.path e) ∩ Set.range (V.path f)= + (A.edge e '' Set.Ioo (0 : unitInterval) 1) ∩ (A.edge f '' Set.Ioo (0 : unitInterval) 1)) ∧ + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → ∀ e f : BipartiteEdge m n, + polygonIntersection (V.vertices e) (shiftedTrack (V.vertices f) (V.pieces f) ε) (V.pieces e) (V.pieces f) = + if e=f then 0 else polygonIntersection (V.vertices e) (V.vertices f) (V.pieces e) (V.pieces f) := by + obtain ⟨A,hcount,hpoly,hnorm,hstraight,htrans⟩ := polygonal_no_adjacent_locally_transverse D + obtain ⟨V⟩ := nonempty_vertexTruncation A.toContinuousDrawing hpoly + refine ⟨A,?_,V,V.path_injective,?_,V.exists_uniform_track_intersections hnorm hstraight htrans⟩ + · simpa only [crossingCount,Set.ncard_eq_toFinset_card _ A.crossings_finite, + Set.ncard_eq_toFinset_card _ D.crossings_finite] using hcount + · intro e f hef + exact V.edge_intersections_eq hnorm e f hef + +end Zarankiewicz.ExpectedTrackGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExteriorArcReplacement.lean b/lean/OAI/Combinatorics/Crossing/ExteriorArcReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..342d0d25f7c8ee845e3b838a6b5c60f5704f0961 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExteriorArcReplacement.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.FiniteDiskCollar +import OAI.Combinatorics.Crossing.PathEndpointNeighborhoods +import OAI.Combinatorics.Crossing.PolygonalBoundaryReplacement + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exterior_arc_polygonal_replacement {ι : Type*} [Fintype ι] [DecidableEq ι] + (z : ι → Plane) (r : ℝ) (hr : 0 < r) + (hd : ∀ i j, i ≠ j → Disjoint (closedRoundDisk (z i) r) (closedRoundDisk (z j) r)) + (k l : ι) (a b : Plane) (hab : a ≠ b) + (ha : squaredLength (a-z k)=r^2) (hb : squaredLength (b-z l)=r^2) + (γ : Path a b) (U : Set Plane) (hU : IsOpen U) (hγU : ∀ t, γ t ∈ U) + (hγout : ∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → γ t ∈ outsideDisks z r) : + ∃ P : PolygonalChain U a b, Function.Injective P.path ∧ + (∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → P.path t ∈ outsideDisks z r) := by + obtain ⟨α,ρ,hα,hρ,hspurA,hnearA⟩ := exists_finite_disk_collar z r hr hd k a ha U hU + (by simpa using hγU 0) + obtain ⟨β,σ,hβ,hσ,hspurB,hnearB⟩ := exists_finite_disk_collar z r hr hd l b hb U hU + (by simpa using hγU 1) + obtain ⟨u,v,hu0,huv,hv1,hu,hv⟩ := path_near_endpoints γ ρ σ hρ hσ + let a' := a+α • (a-z k) + let b' := b+β • (b-z l) + let O := U ∩ outsideDisks z r + have hO : IsOpen O := hU.inter (isOpen_outsideDisks z r) + have hleft : segment ℝ a' (γ u) ⊆ O := hnearA (γ u) hu (hγout u ⟨hu0,huv.trans hv1⟩) + have hright : segment ℝ (γ v) b' ⊆ O := by + rw [segment_symm] + exact hnearB (γ v) hv (hγout v ⟨hu0.trans huv,hv1⟩) + have hmiddle : Set.range (pathSubarc γ u v) ⊆ O := by + rw [pathSubarc_range γ u v huv] + rintro x ⟨t,ht,rfl⟩ + exact ⟨hγU t,hγout t ⟨hu0.trans_le ht.1,ht.2.trans_lt hv1⟩⟩ + let η : Path a' b' := (Path.segment a' (γ u)).trans + ((pathSubarc γ u v).trans (Path.segment (γ v) b')) + have hη : Set.range η ⊆ O := by + dsimp [η] + rw [Path.trans_range,Path.trans_range,Path.range_segment,Path.range_segment] + exact Set.union_subset hleft (Set.union_subset hmiddle hright) + have hA : segment ℝ a a' ⊆ insert a (insert b O) := by + intro x hx + obtain ⟨hxU,hxa | hxout⟩ := hspurA hx + · exact Or.inl hxa + · exact Or.inr (Or.inr ⟨hxU,hxout⟩) + have hB : segment ℝ b' b ⊆ insert a (insert b O) := by + rw [segment_symm] + intro x hx + obtain ⟨hxU,hxb | hxout⟩ := hspurB hx + · exact Or.inr (Or.inl hxb) + · exact Or.inr (Or.inr ⟨hxU,hxout⟩) + obtain ⟨Q,hQ,hQout⟩ := polygonal_replacement_with_spurs O hO a a' b' b hab η + (fun t => hη ⟨t,rfl⟩) hA hB + have hSU : insert a (insert b O) ⊆ U := by + intro x hx + rcases hx with rfl | rfl | hx + · simpa using hγU 0 + · simpa using hγU 1 + · exact hx.1 + exact ⟨Q.widen hSU,hQ,fun t ht => (hQout t ht).2⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExteriorChordMeeting.lean b/lean/OAI/Combinatorics/Crossing/ExteriorChordMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..898d5ef41e049b8f9c69a4dec9bfae2f502bf327 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExteriorChordMeeting.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.PolygonalExterior + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem chord_parameter_endpoint (E : PolygonalExterior C) (i : C.ArcIndex) (p : C.InnerIndex) + (s t : unitInterval) (he : (E.chain i).path s=C.crossingChord p t) : t=0 ∨ t=1 := by + by_cases ht0 : t=0 + · exact Or.inl ht0 + by_cases ht1 : t=1 + · exact Or.inr ht1 + have h := C.crossingChord_interior_in_disk p t + ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + have hx := E.outside_open_disks i s (C.innerMark p) + rw [he] at hx + exact False.elim (h.not_ge hx) + +theorem exterior_chord_meeting_parameters (E : PolygonalExterior C) (i : C.ArcIndex) (p : C.InnerIndex) + (s t : unitInterval) (he : (E.chain i).path s=C.crossingChord p t) : + (i=C.incomingArc p ∧ s=1 ∧ t=0) ∨ (i=C.outgoingArc p ∧ s=0 ∧ t=1) := by + have hs := E.parameter_endpoint_of_mem_disk i s (C.innerMark p) (by + rw [he] + exact C.crossingChord_range_subset_disk p ⟨t,rfl⟩) + have ht := E.chord_parameter_endpoint i p s t he + rcases hs with rfl | rfl <;> rcases ht with rfl | rfl + · simp only [Path.source] at he + have hp : (i,false)=C.incomingPort p := C.portPoint_injective he + have hh : false=true := congrArg Prod.snd hp + cases hh + · simp only [Path.source,Path.target] at he + have hp : (i,false)=C.outgoingPort p := C.portPoint_injective he + exact Or.inr ⟨congrArg Prod.fst hp,rfl,rfl⟩ + · simp only [Path.source,Path.target] at he + have hp : (i,true)=C.incomingPort p := C.portPoint_injective he + exact Or.inl ⟨congrArg Prod.fst hp,rfl,rfl⟩ + · simp only [Path.target] at he + have hp : (i,true)=C.outgoingPort p := C.portPoint_injective he + have hh : true=false := congrArg Prod.snd hp + cases hh + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExteriorCrossingCut.lean b/lean/OAI/Combinatorics/Crossing/ExteriorCrossingCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..13468dbc3af34c22c4fa5ea815a2eddb089b72ea --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExteriorCrossingCut.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.Crossing.SurgeryCutWalks + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + +structure ExteriorCrossingCut (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (r : C.InnerIndex) where + first : Fin ((P r.1).pieces+1) + last : Fin ((P r.1).pieces+1) + ordered : first < last + first_point : (drawingEdgeWalk P r.1).getVert first.val=C.portPoint (C.incomingPort r) + last_point : (drawingEdgeWalk P r.1).getVert last.val=C.portPoint (C.outgoingPort r) + prefix_outside : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take first.val))) (C.crossingDisk r) + suffix_outside : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop last.val))) (C.crossingDisk r) + +theorem PolygonalExterior.nonempty_exteriorCrossingCut {C : DrawingPassages D.toFiniteIntersectionDrawing} (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (r : C.InnerIndex) : Nonempty (ExteriorCrossingCut C P r) := by + obtain ⟨i,j,hij,hi,hj,hout,hout'⟩ := E.exists_exterior_crossing_cuts v hvinj hv hdet P hport r + exact ⟨⟨i,j,hij,hi,hj,hout,hout'⟩⟩ + +namespace ExteriorCrossingCut +variable {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q r : C.InnerIndex} + +def prefixInSurgery (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex (.inl r.1.1)) (C.portPoint (C.incomingPort r)) := + surgeryPrefixWalk C P p q r K.first.val K.first_point (by + simpa only [DrawingPassages.crossingDisk,hr] using K.prefix_outside) + +def suffixInSurgery (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + (crossingSurgeryGraph C P p q).Walk (C.portPoint (C.outgoingPort r)) (D'.vertex (.inr r.1.2)) := + surgerySuffixWalk C P p q r K.last.val K.last_point (by + simpa only [DrawingPassages.crossingDisk,hr] using K.suffix_outside) + +theorem prefixInSurgery_trace (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + Set.range (graphWalkPath id (K.prefixInSurgery p q hr))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) := + surgeryPrefixWalk_trace _ _ _ _ _ _ _ _ + +theorem suffixInSurgery_trace (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + Set.range (graphWalkPath id (K.suffixInSurgery p q hr))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) := + surgerySuffixWalk_trace _ _ _ _ _ _ _ _ + +end ExteriorCrossingCut +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExteriorSegmentGraph.lean b/lean/OAI/Combinatorics/Crossing/ExteriorSegmentGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f008e8eca6b897d68423489f40b853452040e3f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExteriorSegmentGraph.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.Crossing.GraphWalkTrace + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def exteriorSegmentGraph (G : SimpleGraph Plane) (U : Set Plane) : SimpleGraph Plane where + Adj := fun a b => G.Adj a b ∧ Disjoint (segment ℝ a b) U + symm := ⟨by + intro a b h + exact ⟨h.1.symm,by simpa only [segment_symm] using h.2⟩⟩ + loopless := ⟨by intro a h; exact G.loopless.irrefl a h.1⟩ + +theorem exteriorSegmentGraph_le (G : SimpleGraph Plane) (U : Set Plane) : + exteriorSegmentGraph G U ≤ G := fun _ _ h => h.1 + +theorem graphWalkPath_edge_subset_range {G : SimpleGraph Plane} {a b : Plane} + (p : G.Walk a b) (u v : Plane) (huv : s(u,v) ∈ p.edges) : + segment ℝ u v ⊆ Set.range (graphWalkPath id p) := by + obtain ⟨i,hi,he⟩ := (p.mk_mem_edges_iff_exists).mp huv + have hpiece := polygonalArcPath_piece_subset_range (fun i => p.getVert i) p.length i hi + change segment ℝ u v ⊆ Set.range (polygonalArcPath (fun i => p.getVert i) p.length) + rcases Sym2.eq_iff.mp he with ⟨h0,h1⟩ | ⟨h0,h1⟩ + · simpa only [h0,h1] using hpiece + · simpa only [h0,h1,segment_symm] using hpiece + +def exteriorGraphWalk {G : SimpleGraph Plane} {a b : Plane} (p : G.Walk a b) + (U : Set Plane) (h : Disjoint (Set.range (graphWalkPath id p)) U) : + (exteriorSegmentGraph G U).Walk a b := + p.transfer (exteriorSegmentGraph G U) (by + intro e + induction e using Sym2.inductionOn with + | _ u v => + intro huv + exact ⟨p.adj_of_mem_edges huv,h.mono_left (graphWalkPath_edge_subset_range p u v huv)⟩) + +theorem exteriorGraphWalk_getVert {G : SimpleGraph Plane} {a b : Plane} (p : G.Walk a b) + (U : Set Plane) (h : Disjoint (Set.range (graphWalkPath id p)) U) (i : ℕ) : + (exteriorGraphWalk p U h).getVert i=p.getVert i := by + have hlen : (exteriorGraphWalk p U h).length=p.length := by + simp only [exteriorGraphWalk,SimpleGraph.Walk.length_transfer] + have hsupport : (exteriorGraphWalk p U h).support=p.support := by + simp only [exteriorGraphWalk,SimpleGraph.Walk.support_transfer] + by_cases hi : i ≤ p.length + · have hi' : i ≤ (exteriorGraphWalk p U h).length := by rw [hlen]; exact hi + rw [SimpleGraph.Walk.getVert_eq_support_getElem _ hi',p.getVert_eq_support_getElem hi] + simp only [hsupport] + · rw [SimpleGraph.Walk.getVert_of_length_le _ (by + rw [hlen] + omega),p.getVert_of_length_le (by omega)] + +theorem exteriorGraphWalk_length {G : SimpleGraph Plane} {a b : Plane} (p : G.Walk a b) + (U : Set Plane) (h : Disjoint (Set.range (graphWalkPath id p)) U) : + (exteriorGraphWalk p U h).length=p.length := by + simp only [exteriorGraphWalk,SimpleGraph.Walk.length_transfer] + +theorem exteriorGraphWalk_trace {G : SimpleGraph Plane} {a b : Plane} (p : G.Walk a b) + (U : Set Plane) (h : Disjoint (Set.range (graphWalkPath id p)) U) : + Set.range (graphWalkPath id (exteriorGraphWalk p U h))=Set.range (graphWalkPath id p) := by + change Set.range (polygonalArcPath (fun i => (exteriorGraphWalk p U h).getVert i) + (exteriorGraphWalk p U h).length)=Set.range (polygonalArcPath (fun i => p.getVert i) p.length) + have hf : (fun i => (exteriorGraphWalk p U h).getVert i)=(fun i => p.getVert i) := + funext (exteriorGraphWalk_getVert p U h) + exact congrArg₂ (fun (seq : ℕ → Plane) (k : ℕ) => + Set.range (fun t : unitInterval => polygonalArcPath seq k t)) hf (exteriorGraphWalk_length p U h) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExteriorSpokeMeeting.lean b/lean/OAI/Combinatorics/Crossing/ExteriorSpokeMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ec0906006b746da6321a64d2565435d5506749f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExteriorSpokeMeeting.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.Crossing.ExteriorChordMeeting +import OAI.Combinatorics.Crossing.VertexEndpointPorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem exterior_spoke_meeting_parameters (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (i : C.ArcIndex) (j : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) + (s t : unitInterval) (he : (E.chain i).path s=(Path.segment (v j) (C.portPoint p.val)) t) : + t=1 ∧ ((s=0 ∧ (i,false)=p.val) ∨ (s=1 ∧ (i,true)=p.val)) := by + have ht : t=1 := by + apply le_antisymm (show t ≤ 1 from t.property.2) + apply le_of_not_gt + intro ht1 + have hinside := C.vertex_spoke_interior v hv j p t ht1 + have hout := E.outside_open_disks i s (C.vertexMark j) + rw [he] at hout + exact hinside.not_ge hout + subst t + rw [Path.target] at he + have hs := E.parameter_endpoint_of_mem_disk i s (C.vertexMark j) (by + rw [he] + exact (C.portsAt_on_circle (C.vertexMark j) p).le) + refine ⟨rfl,?_⟩ + rcases hs with rfl | rfl + · rw [Path.source] at he + exact Or.inl ⟨rfl,C.portPoint_injective he⟩ + · rw [Path.target] at he + exact Or.inr ⟨rfl,C.portPoint_injective he⟩ + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ExtraDrawingSubdivision.lean b/lean/OAI/Combinatorics/Crossing/ExtraDrawingSubdivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e1cd904e2213c2e68f37b63f1524564b6246145 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ExtraDrawingSubdivision.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.AffineSubdivisionRefinement +import OAI.Combinatorics.Crossing.PolygonalNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem exists_drawing_subdivision_at (D : AdmissibleDrawing m n) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) (S : Set Plane) (hS : S.Finite) : + ∃ P : ∀ e, PolygonalParametrization (D.edge e), + (∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) ∧ + (∀ e t, D.edge e t ∈ S → t ∈ Set.range (P e).knot) := by + classical + have hfinite (e : BipartiteEdge m n) : ((D.edge e) ⁻¹' (drawingMarks D.toFiniteIntersectionDrawing ∪ S)).Finite := + ((drawingMarks_finite D.toFiniteIntersectionDrawing).union hS).preimage (D.edge_injective e).injOn + have hex (e : BipartiteEdge m n) := (hpoly e).refine (hfinite e).toFinset + choose P hP using hex + refine ⟨P,?_,?_⟩ + · intro e t ht + exact hP e (by simpa using Or.inl ht) + · intro e t ht + exact hP e (by simpa using Or.inr ht) + +namespace PolygonalExterior +variable {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_assembled_port_subdivision (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + ∃ P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e), + (∀ e t, E.assembledEdge v e t ∈ drawingMarks (E.assembledAdmissible v hvinj hv hdet).toFiniteIntersectionDrawing → + t ∈ Set.range (P e).knot) ∧ + (∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) := + exists_drawing_subdivision_at (E.assembledAdmissible v hvinj hv hdet) + (E.assembledEdge_hasFiniteAffineCover v) (Set.range C.portPoint) (Set.finite_range _) + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteAffineCover.lean b/lean/OAI/Combinatorics/Crossing/FiniteAffineCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..553ae3a13cb3fd61252a993572dd55c9ca48590c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteAffineCover.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.Crossing.AffinePathHalves +import OAI.Combinatorics.Crossing.PolygonalChains +import OAI.Combinatorics.Crossing.PlanarSegments +import Mathlib.Data.Finset.Image + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def HasFiniteAffineCover {a b : Plane} (γ : Path a b) : Prop := + ∃ S : Finset (unitInterval × unitInterval), + (∀ ab ∈ S, ab.1 < ab.2) ∧ + (∀ t : unitInterval, ∃ ab ∈ S, ab.1 ≤ t ∧ t ≤ ab.2) ∧ + (∀ ab ∈ S, ∀ t : unitInterval, + γ (intervalSegment ab.1 ab.2 t)=segmentPoint (γ ab.1) (γ ab.2) t.val) + +theorem hasFiniteAffineCover_refl (a : Plane) : HasFiniteAffineCover (Path.refl a) := by + classical + refine ⟨{(0,1)},?_,?_,?_⟩ + · intro ab hab + have he : ab=(0,1) := Finset.mem_singleton.mp hab + subst ab + norm_num + · intro t + exact ⟨(0,1),Finset.mem_singleton_self _,t.property.1,t.property.2⟩ + · intro ab hab t + change a=segmentPoint a a t.val + simp [segmentPoint,← add_smul] + +theorem hasFiniteAffineCover_segment (a b : Plane) : HasFiniteAffineCover (Path.segment a b) := by + classical + refine ⟨{(0,1)},?_,?_,?_⟩ + · intro ab hab + have he : ab=(0,1) := Finset.mem_singleton.mp hab + subst ab + norm_num + · intro t + exact ⟨(0,1),Finset.mem_singleton_self _,t.property.1,t.property.2⟩ + · intro ab hab t + have he : ab=(0,1) := Finset.mem_singleton.mp hab + subst ab + simp only [intervalSegment_zero_one,Path.source,Path.target] + simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] + +theorem HasFiniteAffineCover.trans {a b c : Plane} {γ : Path a b} {η : Path b c} + (hγ : HasFiniteAffineCover γ) (hη : HasFiniteAffineCover η) : HasFiniteAffineCover (γ.trans η) := by + classical + obtain ⟨S,hSlt,hScov,hSaff⟩ := hγ + obtain ⟨T,hTlt,hTcov,hTaff⟩ := hη + let L : unitInterval × unitInterval → unitInterval × unitInterval := fun ab => (intervalLeft ab.1,intervalLeft ab.2) + let R : unitInterval × unitInterval → unitInterval × unitInterval := fun ab => (intervalRight ab.1,intervalRight ab.2) + refine ⟨S.image L ∪ T.image R,?_,?_,?_⟩ + · intro ab hab + rcases Finset.mem_union.mp hab with hab | hab + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + exact intervalLeft_strictMono (hSlt cd hcd) + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + exact intervalRight_strictMono (hTlt cd hcd) + · intro t + by_cases ht : t.val ≤ 1/2 + · let u : unitInterval := ⟨2*t.val,by constructor <;> linarith [t.property.1]⟩ + obtain ⟨ab,hab,ha,hb⟩ := hScov u + have hu : intervalLeft u=t := by apply Subtype.ext; change (2*t.val)/2=t.val; ring + refine ⟨L ab,Finset.mem_union_left _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩),?_,?_⟩ + · change intervalLeft ab.1 ≤ t + rw [← hu] + exact intervalLeft_strictMono.monotone ha + · change t ≤ intervalLeft ab.2 + rw [← hu] + exact intervalLeft_strictMono.monotone hb + · let u : unitInterval := ⟨2*t.val-1,by constructor <;> linarith [t.property.2]⟩ + obtain ⟨ab,hab,ha,hb⟩ := hTcov u + have hu : intervalRight u=t := by apply Subtype.ext; change (1+(2*t.val-1))/2=t.val; ring + refine ⟨R ab,Finset.mem_union_right _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩),?_,?_⟩ + · change intervalRight ab.1 ≤ t + rw [← hu] + exact intervalRight_strictMono.monotone ha + · change t ≤ intervalRight ab.2 + rw [← hu] + exact intervalRight_strictMono.monotone hb + · intro ab hab t + rcases Finset.mem_union.mp hab with hab | hab + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + change (γ.trans η) (intervalSegment (intervalLeft cd.1) (intervalLeft cd.2) t)=_ + rw [intervalSegment_left,path_trans_intervalLeft] + exact (hSaff cd hcd t).trans (by simp only [L,path_trans_intervalLeft]) + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + change (γ.trans η) (intervalSegment (intervalRight cd.1) (intervalRight cd.2) t)=_ + rw [intervalSegment_right,path_trans_intervalRight] + exact (hTaff cd hcd t).trans (by simp only [R,path_trans_intervalRight]) + +theorem HasFiniteAffineCover.cast {a b c d : Plane} {γ : Path a b} + (hγ : HasFiniteAffineCover γ) (ha : c=a) (hb : d=b) : HasFiniteAffineCover (γ.cast ha hb) := hγ + +theorem polygonalArcPath_hasFiniteAffineCover (v : ℕ → Plane) : + (k : ℕ) → HasFiniteAffineCover (polygonalArcPath v k) + | 0 => hasFiniteAffineCover_refl _ + | 1 => hasFiniteAffineCover_segment _ _ + | k+2 => (polygonalArcPath_hasFiniteAffineCover v (k+1)).trans (hasFiniteAffineCover_segment _ _) + +theorem PolygonalChain.hasFiniteAffineCover {O : Set Plane} {a b : Plane} + (P : PolygonalChain O a b) : HasFiniteAffineCover P.path := + (polygonalArcPath_hasFiniteAffineCover P.vertices P.pieces).cast P.first.symm P.last.symm + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteCircleCoordinates.lean b/lean/OAI/Combinatorics/Crossing/FiniteCircleCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f09a56e85f6c53feaddadb72948fba3fc5b8a76 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteCircleCoordinates.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.SimilarityCoordinates +import OAI.Combinatorics.Crossing.RadialBoundaryPorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_circle_cut_vector {ι : Type*} [Fintype ι] (o : Plane) + (r : ℝ) (hr : 0 < r) (point : ι → Plane) : + ∃ u : Plane, u ≠ 0 ∧ squaredLength u=r^2 ∧ ∀ i, point i ≠ o-u := by + let f : ℝ → Plane := fun t => o+r • circlePoint t + have hf : Function.Injective f := by + intro t s h + have hh := congrArg (fun z : Plane => r⁻¹ • (z-o)) h + dsimp [f] at hh + simp only [add_sub_cancel_left,smul_smul,inv_mul_cancel₀ (ne_of_gt hr),one_smul] at hh + exact circlePoint_injective hh + have hbad : (f ⁻¹' Set.range point).Finite := Set.Finite.preimage hf.injOn (Set.finite_range point) + obtain ⟨t,ht⟩ := hbad.exists_notMem + let u := (-r) • circlePoint t + have hlen : squaredLength u=r^2 := by + dsimp [u] + rw [squaredLength_smul] + have hunit : squaredLength (circlePoint t)=1 := circlePoint_on_unit_circle t + rw [hunit,mul_one,neg_sq] + have hu : u ≠ 0 := by + intro h + rw [h] at hlen + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hlen + nlinarith + refine ⟨u,hu,hlen,?_⟩ + intro i he + apply ht + refine ⟨i,?_⟩ + simpa only [u,f,neg_smul,sub_neg_eq_add] using he + +theorem exists_finite_circle_coordinates {ι : Type*} [Fintype ι] + (o : Plane) (r : ℝ) (hr : 0 < r) (point : ι → Plane) + (hinj : Function.Injective point) (hcircle : ∀ i, squaredLength (point i-o)=r^2) : + ∃ u : Plane, u ≠ 0 ∧ squaredLength u=r^2 ∧ + ∃ node : ι → ℝ, Function.Injective node ∧ ∀ i, similarityPoint o u (circlePoint (node i))=point i := by + obtain ⟨u,hu,hlen,hcut⟩ := exists_circle_cut_vector o r hr point + have hex (i : ι) := circle_similarity_parameter o u (point i) hu ((hcircle i).trans hlen.symm) (hcut i) + choose node hnode using hex + refine ⟨u,hu,hlen,node,?_,hnode⟩ + intro i j hij + apply hinj + rw [← hnode i,← hnode j,hij] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteConePoint.lean b/lean/OAI/Combinatorics/Crossing/FiniteConePoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..59b0a44ee9fd76ab3303baceba0b15cc0ee8f36a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteConePoint.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.FiniteLineAvoidance +import OAI.Combinatorics.Crossing.TriangleOrientations + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_polygon_cone_point (v w : ℕ → Plane) (n m : ℕ) + (hv : ∀ i : Fin n, v (i.val+1) ≠ v i.val) + (hw : ∀ j : Fin m, w (j.val+1) ≠ w j.val) + (hvw : ∀ i : Fin (n+1), ∀ j : Fin (m+1), w j.val ≠ v i.val) : + ∃ o : Plane, + (∀ i : Fin n, orient2 o (v i.val) (v (i.val+1)) ≠ 0) ∧ + (∀ j : Fin m, orient2 (w j.val) (w (j.val+1)) o ≠ 0) ∧ + (∀ i : Fin (n+1), ∀ j : Fin m, det2 (v i.val-o) (w (j.val+1)-w j.val) ≠ 0) ∧ + (∀ i : Fin (n+1), ∀ j : Fin (m+1), orient2 o (v i.val) (w j.val) ≠ 0) := by + let ι := (Fin n ⊕ Fin m) ⊕ ((Fin (n+1) × Fin m) ⊕ (Fin (n+1) × Fin (m+1))) + let base : ι → Plane + | .inl (.inl i) => v i.val + | .inl (.inr j) => w j.val + | .inr (.inl (i,_)) => v i.val + | .inr (.inr (i,_)) => v i.val + let direction : ι → Plane + | .inl (.inl i) => v (i.val+1)-v i.val + | .inl (.inr j) => w (j.val+1)-w j.val + | .inr (.inl (_,j)) => w (j.val+1)-w j.val + | .inr (.inr (i,j)) => w j.val-v i.val + have hd : ∀ k, direction k ≠ 0 := by + rintro ((i|j)|(⟨i,j⟩|⟨i,j⟩)) + · exact sub_ne_zero.mpr (hv i) + · exact sub_ne_zero.mpr (hw j) + · exact sub_ne_zero.mpr (hw j) + · exact sub_ne_zero.mpr (hvw i j) + obtain ⟨o,_,ho⟩ := exists_near_avoiding_lines base direction hd (0 : Plane) 1 (by norm_num) + refine ⟨o,?_,?_,?_,?_⟩ + · intro i + rw [← triangle_area_cycle o (v i.val) (v (i.val+1))] + change det2 (v (i.val+1)-v i.val) (o-v i.val) ≠ 0 + rw [det2_swap] + exact neg_ne_zero.mpr (ho (.inl (.inl i))) + · intro j + change det2 (w (j.val+1)-w j.val) (o-w j.val) ≠ 0 + rw [det2_swap] + exact neg_ne_zero.mpr (ho (.inl (.inr j))) + · intro i j + rw [det2_reverse_edge (v i.val) o (w j.val) (w (j.val+1))] + exact neg_ne_zero.mpr (ho (.inr (.inl (i,j)))) + · intro i j + rw [← triangle_area_cycle o (v i.val) (w j.val)] + change det2 (w j.val-v i.val) (o-v i.val) ≠ 0 + rw [det2_swap] + exact neg_ne_zero.mpr (ho (.inr (.inr (i,j)))) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteDiskCollar.lean b/lean/OAI/Combinatorics/Crossing/FiniteDiskCollar.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd43a96ecb8a606b88bc9517572dff6705c92822 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteDiskCollar.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.BoundaryCollar +import OAI.Combinatorics.Crossing.RoundDiskVisits + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def outsideDisks {ι : Type*} (z : ι → Plane) (r : ℝ) : Set Plane := + {x | ∀ i, r^2 < squaredLength (x-z i)} + +theorem isOpen_disk_exterior (z : Plane) (r : ℝ) : + IsOpen {x | r^2 < squaredLength (x-z)} := by + apply isOpen_lt continuous_const + unfold squaredLength + fun_prop + +theorem isOpen_outsideDisks {ι : Type*} [Finite ι] (z : ι → Plane) (r : ℝ) : + IsOpen (outsideDisks z r) := by + have he : outsideDisks z r=⋂ i, {x | r^2 < squaredLength (x-z i)} := by + ext x + simp [outsideDisks] + rw [he] + exact isOpen_iInter_of_finite (fun i => isOpen_disk_exterior (z i) r) + +theorem exists_finite_disk_collar {ι : Type*} [Fintype ι] [DecidableEq ι] + (z : ι → Plane) (r : ℝ) (hr : 0 < r) + (hd : ∀ i j, i ≠ j → Disjoint (closedRoundDisk (z i) r) (closedRoundDisk (z j) r)) + (k : ι) (x : Plane) (hx : squaredLength (x-z k)=r^2) + (U : Set Plane) (hU : IsOpen U) (hxu : x ∈ U) : + ∃ α ρ : ℝ, 0 < α ∧ 0 < ρ ∧ + segment ℝ x (x+α • (x-z k)) ⊆ U ∩ insert x (outsideDisks z r) ∧ + (∀ y, dist y x < ρ → y ∈ outsideDisks z r → + segment ℝ (x+α • (x-z k)) y ⊆ U ∩ outsideDisks z r) := by + let V : Set Plane := U ∩ ⋂ j : {j : ι // j ≠ k}, {y | r^2 < squaredLength (y-z j.val)} + have hV : IsOpen V := hU.inter (isOpen_iInter_of_finite (fun j => isOpen_disk_exterior (z j.val) r)) + have hxV : x ∈ V := by + refine ⟨hxu,Set.mem_iInter.mpr (fun j => ?_)⟩ + change r^2 < squaredLength (x-z j.val) + apply lt_of_not_ge + intro hh + exact Set.disjoint_left.mp (hd k j.val (Ne.symm j.property)) (show x ∈ closedRoundDisk (z k) r from hx.le) hh + obtain ⟨α,ρ,hα,hρ,hspur,hnear⟩ := exists_radial_tip_collar (z k) x r hr hx V hV hxV + have hout : V ∩ {p | r^2 < squaredLength (p-z k)} ⊆ U ∩ outsideDisks z r := by + intro p hp + refine ⟨hp.1.1,fun j => ?_⟩ + by_cases he : j=k + · simpa [he] using hp.2 + · exact Set.mem_iInter.mp hp.1.2 ⟨j,he⟩ + refine ⟨α,ρ,hα,hρ,?_,?_⟩ + · intro p hp + obtain ⟨hpV,hpx | hpout⟩ := hspur hp + · exact ⟨hpV.1,Or.inl hpx⟩ + · exact ⟨hpV.1,Or.inr (hout ⟨hpV,hpout⟩).2⟩ + · intro y hy hyout + exact (hnear y hy (hyout k)).trans hout + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteEventualRadius.lean b/lean/OAI/Combinatorics/Crossing/FiniteEventualRadius.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f2366ca651a795230c217c785bb9809676b591e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteEventualRadius.lean @@ -0,0 +1,21 @@ +import OAI.Combinatorics.Crossing.FiniteSeparation +import Mathlib.Topology.MetricSpace.Pseudo.Defs + +namespace OAI + +namespace Zarankiewicz +open scoped Topology + +theorem finite_eventual_radius {ι : Type*} [Fintype ι] (P : ι → ℝ → Prop) + (h : ∀ i, ∀ᶠ t : ℝ in 𝓝 0, P i t) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, |t| < δ → ∀ i, P i t := by + have hex (i : ι) : ∃ r : ℝ, 0 < r ∧ ∀ t : ℝ, |t| < r → P i t := by + obtain ⟨r,hr,hh⟩ := Metric.eventually_nhds_iff.mp (h i) + exact ⟨r,hr,fun t ht => hh (by simpa [Real.dist_eq] using ht)⟩ + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun i _ => hpos i) + exact ⟨δ,hδ,fun t ht i => hprop i t (ht.trans (hbound i (Finset.mem_univ _)))⟩ + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteIntersectionDrawing.lean b/lean/OAI/Combinatorics/Crossing/FiniteIntersectionDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9f943df52dfd7f3482ad2cbf8d5c4b89cf69ca1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteIntersectionDrawing.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Data.Set.Card + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +structure FiniteIntersectionDrawing (m n : ℕ) extends ContinuousDrawing m n where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + no_triples : ∀ e f g, e ≠ f → e ≠ g → f ≠ g → + edgeInterior toContinuousDrawing e ∩ edgeInterior toContinuousDrawing f ∩ + edgeInterior toContinuousDrawing g = ∅ + +abbrev AdmissibleDrawing.toFiniteIntersectionDrawing {m n : ℕ} (D : AdmissibleDrawing m n) : + FiniteIntersectionDrawing m n where + toContinuousDrawing := D.toContinuousDrawing + crossings_finite := D.crossings_finite + no_triples := D.no_triples + +instance admissibleToFiniteIntersectionDrawing {m n : ℕ} : + CoeOut (AdmissibleDrawing m n) (FiniteIntersectionDrawing m n) := + ⟨AdmissibleDrawing.toFiniteIntersectionDrawing⟩ + +def finiteCrossingCount {m n : ℕ} (D : FiniteIntersectionDrawing m n) : ℕ := + D.crossings_finite.toFinset.card + +theorem finiteCrossingCount_of_admissible {m n : ℕ} (D : AdmissibleDrawing m n) : + finiteCrossingCount (D : FiniteIntersectionDrawing m n)=crossingCount D := rfl + +theorem finiteCrossingCount_eq_ncard {m n : ℕ} (D : FiniteIntersectionDrawing m n) : + finiteCrossingCount D=(crossingPoints D.toContinuousDrawing).ncard := + (Set.ncard_eq_toFinset_card _ D.crossings_finite).symm + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteLineAvoidance.lean b/lean/OAI/Combinatorics/Crossing/FiniteLineAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..7379168fc1ac9cbb61c5c46a6edb5ac04a288454 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteLineAvoidance.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.Crossing.PlanarSegments +import Mathlib.Algebra.Polynomial.Roots +import Mathlib.Order.Interval.Set.Infinite + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Polynomial +open scoped BigOperators Classical + +def lineAvoidancePolynomial (z a v : Plane) : ℝ[X] := + C v.2 * X - C v.1 * X^2 + C (det2 (z-a) v) + +theorem lineAvoidancePolynomial_eval (z a v : Plane) (t : ℝ) : + (lineAvoidancePolynomial z a v).eval t = det2 (z+(t,t^2)-a) v := by + simp [lineAvoidancePolynomial,det2] + ring + +theorem lineAvoidancePolynomial_ne_zero (z a v : Plane) (hv : v ≠ 0) : + lineAvoidancePolynomial z a v ≠ 0 := by + intro h + have h₁ := congrArg (fun p : ℝ[X] => p.coeff 1) h + have h₂ := congrArg (fun p : ℝ[X] => p.coeff 2) h + norm_num [lineAvoidancePolynomial,coeff_C_mul] at h₁ h₂ + apply hv + exact Prod.ext h₂ h₁ + +theorem exists_near_avoiding_lines {ι : Type*} [Fintype ι] (a v : ι → Plane) + (hv : ∀ i, v i ≠ 0) (z : Plane) (ε : ℝ) (hε : 0 < ε) : + ∃ o : Plane, dist o z < ε ∧ ∀ i, det2 (o-a i) (v i) ≠ 0 := by + let bad : Finset ℝ := Finset.univ.biUnion (fun i => (lineAvoidancePolynomial z (a i) (v i)).roots.toFinset) + have hδ : 0 < min ε 1 := lt_min hε (by norm_num) + obtain ⟨t,ht⟩ := ((Set.Ioo_infinite hδ).sdiff bad.finite_toSet).nonempty + have ht0 : 0 < t := ht.1.1 + have htε : t < ε := lt_of_lt_of_le ht.1.2 (min_le_left _ _) + have ht1 : t < 1 := lt_of_lt_of_le ht.1.2 (min_le_right _ _) + refine ⟨z+(t,t^2),?_,?_⟩ + · have ht2 : t^2 < ε := by nlinarith + simp only [Prod.dist_eq,Prod.fst_add,Prod.snd_add,Real.dist_eq,add_sub_cancel_left] + exact max_lt (by simpa [abs_of_pos ht0] using htε) (by simpa [abs_of_nonneg (sq_nonneg t)] using ht2) + · intro i hi + have hp : (lineAvoidancePolynomial z (a i) (v i)).eval t = 0 := by + rwa [lineAvoidancePolynomial_eval] + apply ht.2 + change t ∈ bad + apply Finset.mem_biUnion.mpr + refine ⟨i,Finset.mem_univ i,?_⟩ + simpa [mem_roots (lineAvoidancePolynomial_ne_zero z (a i) (v i) (hv i))] using hp + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteMovingPoints.lean b/lean/OAI/Combinatorics/Crossing/FiniteMovingPoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..4336feb0ee9c4d607c1217735a434daf44863096 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteMovingPoints.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.Crossing.MovingSegmentStability +import OAI.Combinatorics.Crossing.FiniteSeparation + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem finite_moving_points_separation {ι : Type*} [Fintype ι] + (point : ι → ℝ → Plane) (hc : ∀ i, Continuous (point i)) + (hinj : Function.Injective (fun i => point i 0)) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ i j : ι, i ≠ j → + point i 0 ≠ point j ε ∧ point i ε ≠ point j ε := by + classical + let Pair := {ij : ι × ι // ij.1 ≠ ij.2} + have hevent (p : Pair) : ∀ᶠ ε : ℝ in 𝓝 0, + point p.val.1 0 ≠ point p.val.2 ε ∧ point p.val.1 ε ≠ point p.val.2 ε := by + have hne := hinj.ne p.property + have h₁ := (hc p.val.2).continuousAt.eventually_ne hne.symm + have hd : Continuous (fun ε : ℝ => point p.val.1 ε-point p.val.2 ε) := (hc _).sub (hc _) + have h₂ := hd.continuousAt.eventually_ne (sub_ne_zero.mpr hne) + filter_upwards [h₁,h₂] with ε h₁ h₂ + exact ⟨h₁.symm,sub_ne_zero.mp h₂⟩ + have hex (p : Pair) := Metric.eventually_nhds_iff.mp (hevent p) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun p _ => hpos p) + refine ⟨δ,hδ,?_⟩ + intro ε hε i j hij + exact hprop ⟨(i,j),hij⟩ (by + simpa [Real.dist_eq] using hε.trans (hbound ⟨(i,j),hij⟩ (Finset.mem_univ _))) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FinitePathChain.lean b/lean/OAI/Combinatorics/Crossing/FinitePathChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a074278c62e5b7e2f6d83e1be9a725310e1e99f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FinitePathChain.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.PathConcatenationInjective + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def finitePathChain (v : ℕ → Plane) (p : ∀ i, Path (v i) (v (i+1))) : (n : ℕ) → Path (v 0) (v n) + | 0 => Path.refl (v 0) + | 1 => p 0 + | n+2 => (finitePathChain v p (n+1)).trans (p (n+1)) + +theorem finitePathChain_range_iff (v : ℕ → Plane) (p : ∀ i, Path (v i) (v (i+1))) : + (n : ℕ) → 0 < n → ∀ x, x ∈ Set.range (finitePathChain v p n) ↔ + ∃ i, i < n ∧ x ∈ Set.range (p i) + | 0, hn, _ => by omega + | 1, _, x => by + constructor + · intro h + exact ⟨0,by omega,h⟩ + · rintro ⟨i,hi,h⟩ + have he : i=0 := by omega + subst i + exact h + | n+2, _, x => by + rw [finitePathChain,Path.trans_range,Set.mem_union,finitePathChain_range_iff v p (n+1) (by omega)] + constructor + · rintro (⟨i,hi,h⟩ | h) + · exact ⟨i,by omega,h⟩ + · exact ⟨n+1,by omega,h⟩ + · rintro ⟨i,hi,h⟩ + by_cases hin : i < n+1 + · exact Or.inl ⟨i,hin,h⟩ + · have he : i=n+1 := by omega + subst i + exact Or.inr h + +theorem finitePathChain_injective (v : ℕ → Plane) (p : ∀ i, Path (v i) (v (i+1))) : + (n : ℕ) → 0 < n → (∀ i, i < n → Function.Injective (p i)) → + (∀ i j, i < j → j < n → ∀ x, x ∈ Set.range (p i) → x ∈ Set.range (p j) → + j=i+1 ∧ x=v j) → Function.Injective (finitePathChain v p n) + | 0, hn, _, _ => by omega + | 1, _, hp, _ => hp 0 (by omega) + | n+2, _, hp, hm => by + apply path_trans_injective + · exact finitePathChain_injective v p (n+1) (by omega) + (fun i hi => hp i (by omega)) (fun i j hij hj => hm i j hij (by omega)) + · exact hp (n+1) (by omega) + · intro x hx hy + obtain ⟨i,hi,hh⟩ := (finitePathChain_range_iff v p (n+1) (by omega) x).mp hx + exact (hm i (n+1) hi (by omega) x hh hy).2 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FinitePolygonalComposition.lean b/lean/OAI/Combinatorics/Crossing/FinitePolygonalComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..15de04f507733ac778310721b1c00a1dc8bc6f47 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FinitePolygonalComposition.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.SegmentTraversalReversal + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +def finitePolygonalChain (O : Set Plane) (v : ℕ → Plane) (h0 : v 0 ∈ O) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) : (n : ℕ) → PolygonalChain O (v 0) (v n) + | 0 => PolygonalChain.point O (v 0) h0 + | n+1 => (finitePolygonalChain O v h0 P n).join (P n) + +theorem finitePolygonalChain_intersection_left (O : Set Plane) (v : ℕ → Plane) (h0 : v 0 ∈ O) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) (w : ℕ → Plane) (k n : ℕ) : + polygonIntersection (finitePolygonalChain O v h0 P n).vertices w (finitePolygonalChain O v h0 P n).pieces k= + ∑ i ∈ Finset.range n, polygonIntersection (P i).vertices w (P i).pieces k := by + induction n with + | zero => simp [finitePolygonalChain,PolygonalChain.point,polygonIntersection] + | succ n ih => + change polygonIntersection ((finitePolygonalChain O v h0 P n).join (P n)).vertices w + ((finitePolygonalChain O v h0 P n).join (P n)).pieces k=_ + rw [PolygonalChain.intersection_join_left,ih,Finset.sum_range_succ] + +theorem finitePolygonalChain_intersection_right (O : Set Plane) (v : ℕ → Plane) (h0 : v 0 ∈ O) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) (w : ℕ → Plane) (k n : ℕ) : + polygonIntersection w (finitePolygonalChain O v h0 P n).vertices k (finitePolygonalChain O v h0 P n).pieces= + ∑ i ∈ Finset.range n, polygonIntersection w (P i).vertices k (P i).pieces := by + rw [polygonIntersection_swap,finitePolygonalChain_intersection_left] + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i hi + exact (polygonIntersection_swap _ _ _ _).symm + +theorem finitePolygonalChain_transverse_left {O T : Set Plane} (v : ℕ → Plane) (h0 : v 0 ∈ O) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) {a b : Plane} (Q : PolygonalChain T a b) + (n : ℕ) (h : ∀ i, i intro i; exact Fin.elim0 i + | succ n ih => + exact (finitePolygonalChain O v h0 P n).transverse_join_left (P n) Q + (ih (fun i hi => h i (by omega))) (h n (by omega)) + +theorem finitePolygonalChain_transverse_right {O T : Set Plane} (v : ℕ → Plane) (h0 : v 0 ∈ O) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) {a b : Plane} (Q : PolygonalChain T a b) + (n : ℕ) (h : ∀ i, i Q.transverse_swap (P i) (h i hi))) + +theorem finitePolygonalChain_intersection_double {O T : Set Plane} + (v w : ℕ → Plane) (hv : v 0 ∈ O) (hw : w 0 ∈ T) + (P : ∀ i, PolygonalChain O (v i) (v (i+1))) (Q : ∀ j, PolygonalChain T (w j) (w (j+1))) + (n k : ℕ) : + polygonIntersection (finitePolygonalChain O v hv P n).vertices (finitePolygonalChain T w hw Q k).vertices + (finitePolygonalChain O v hv P n).pieces (finitePolygonalChain T w hw Q k).pieces = + ∑ i ∈ Finset.range n, ∑ j ∈ Finset.range k, polygonIntersection (P i).vertices (Q j).vertices (P i).pieces (Q j).pieces := by + rw [finitePolygonalChain_intersection_left] + apply Finset.sum_congr rfl + intro i hi + exact finitePolygonalChain_intersection_right _ _ _ _ _ _ _ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FiniteScaledRadius.lean b/lean/OAI/Combinatorics/Crossing/FiniteScaledRadius.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f5f3c5b3f47e07dff6c34edbab3d3d241bda603 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FiniteScaledRadius.lean @@ -0,0 +1,24 @@ +import OAI.Combinatorics.Crossing.FiniteSeparation +import Mathlib.Tactic.FieldSimp + +namespace OAI + +namespace Zarankiewicz + +theorem finite_scaled_radius {ι : Type*} [Fintype ι] (a r : ι → ℝ) (hr : ∀ i, 0 r i/(|a i|+1)) (fun i _ => div_pos (hr i) (by positivity)) + refine ⟨δ,hδ,?_⟩ + intro t ht i + have hd : 0 < |a i|+1 := by positivity + have hb : δ*(|a i|+1) exact ⟨1,by norm_num,by simp⟩ + | @insert i S hi ih => + obtain ⟨ε,hε,hbound⟩ := ih (fun j hj => hf j (Finset.mem_insert_of_mem hj)) + have hfi := hf i (Finset.mem_insert_self i S) + refine ⟨min (ε/2) (f i/2),lt_min (by linarith) (by linarith),?_⟩ + intro j hj + rcases Finset.mem_insert.mp hj with rfl | hj + · exact (min_le_right _ _).trans_lt (by linarith) + · exact (min_le_left _ _).trans_lt (by have hh := hbound j hj; linarith) + +theorem finite_node_separation {ι : Type*} [Fintype ι] [DecidableEq ι] + (node : ι → ℝ) (hn : Function.Injective node) : + ∃ ε : ℝ, 0 < ε ∧ ∀ i j, i ≠ j → ε < |node i-node j| := by + obtain ⟨ε,hε,hb⟩ := finite_positive_lower_bound + (Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2)) + (fun ij => |node ij.1-node ij.2|) (by + intro ij hij + exact abs_pos.mpr (sub_ne_zero.mpr (hn.ne (Finset.mem_filter.mp hij).2))) + exact ⟨ε,hε,fun i j hij => hb (i,j) (by simpa using hij)⟩ + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FirstLastVisits.lean b/lean/OAI/Combinatorics/Crossing/FirstLastVisits.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c99dea04d478e59184bf7f891aa963f1214a8b4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FirstLastVisits.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.MarkedCurveDisks +import Mathlib.Topology.Order.Compact +import Mathlib.Topology.Order.IntermediateValue + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem first_last_sublevel_visits (f : ℝ → ℝ) (hf : Continuous f) (r τ : ℝ) + (h0 : r < f 0) (h1 : r < f 1) (hτ : τ ∈ Set.Ioo (0 : ℝ) 1) (hvisit : f τ < r) : + ∃ a b : ℝ, 0 < a ∧ a < τ ∧ τ < b ∧ b < 1 ∧ f a=r ∧ f b=r ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, f t ≤ r → a ≤ t ∧ t ≤ b) := by + let S : Set ℝ := Set.Icc 0 1 ∩ {t | f t ≤ r} + have hS : IsCompact S := isCompact_Icc.inter_right (isClosed_le hf continuous_const) + have hne : S.Nonempty := ⟨τ,⟨hτ.1.le,hτ.2.le⟩,hvisit.le⟩ + obtain ⟨a,ha⟩ := hS.exists_isLeast hne + obtain ⟨b,hb⟩ := hS.exists_isGreatest hne + have ha0 : 0 < a := lt_of_le_of_ne ha.1.1.1 (by + intro he + have hh := ha.1.2 + rw [← he] at hh + exact (not_le_of_gt h0) hh) + have hb1 : b < 1 := lt_of_le_of_ne hb.1.1.2 (by + intro he + have hh := hb.1.2 + rw [he] at hh + exact (not_le_of_gt h1) hh) + have hfa : f a=r := by + apply le_antisymm ha.1.2 + by_contra hn + have hlt : f a < r := lt_of_not_ge hn + obtain ⟨t,ht,he⟩ := intermediate_value_Icc' ha.1.1.1 hf.continuousOn ⟨hlt.le,h0.le⟩ + have hmem : t ∈ S := ⟨⟨ht.1,ht.2.trans ha.1.1.2⟩,he.le⟩ + have hta : t=a := le_antisymm ht.2 (ha.2 hmem) + rw [hta] at he + exact hlt.ne he + have hfb : f b=r := by + apply le_antisymm hb.1.2 + by_contra hn + have hlt : f b < r := lt_of_not_ge hn + obtain ⟨t,ht,he⟩ := intermediate_value_Icc hb.1.1.2 hf.continuousOn ⟨hlt.le,h1.le⟩ + have hmem : t ∈ S := ⟨⟨hb.1.1.1.trans ht.1,ht.2⟩,he.le⟩ + have htb : t=b := le_antisymm (hb.2 hmem) ht.1 + rw [htb] at he + exact hlt.ne he + have hat : a < τ := lt_of_le_of_ne (ha.2 (show τ ∈ S from ⟨⟨hτ.1.le,hτ.2.le⟩,hvisit.le⟩)) (by + intro he + rw [he] at hfa + exact hvisit.ne hfa) + have htb : τ < b := lt_of_le_of_ne (hb.2 (show τ ∈ S from ⟨⟨hτ.1.le,hτ.2.le⟩,hvisit.le⟩)) (by + intro he + rw [← he] at hfb + exact hvisit.ne hfb) + exact ⟨a,b,ha0,hat,htb,hb1,hfa,hfb,fun t ht hf => + ⟨ha.2 ⟨ht,hf⟩,hb.2 ⟨ht,hf⟩⟩⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FloorArithmetic.lean b/lean/OAI/Combinatorics/Crossing/FloorArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..94ff7e8460cf45cf93496047ed49458f9ad3d3df --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FloorArithmetic.lean @@ -0,0 +1,48 @@ +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith +import Lean.Elab.Tactic.Omega + +namespace OAI + +namespace Zarankiewicz + +def axisPairs (r : ℕ) : ℕ := (r/2) * ((r-1)/2) + +theorem square_quarter_even (r : ℕ) : (2*r)*(2*r)/4 = r*r := by + rw [show (2*r)*(2*r) = r*r*4 by ring, Nat.mul_div_left _ (by decide : 0<4)] + +theorem square_quarter_odd (r : ℕ) : (2*r+1)*(2*r+1)/4 = r*r+r := by + rw [show (2*r+1)*(2*r+1) = 1+(r*r+r)*4 by ring, + Nat.add_mul_div_right _ _ (by decide : 0<4)] + omega + +theorem axisPairs_even (r : ℕ) : axisPairs (2*r) = r*(r-1) := by + unfold axisPairs + have h₁ : 2*r/2 = r := by omega + have h₂ : (2*r-1)/2 = r-1 := by omega + rw [h₁,h₂] + +theorem axisPairs_odd (r : ℕ) : axisPairs (2*r+1) = r*r := by + unfold axisPairs + have h₁ : (2*r+1)/2 = r := by omega + have h₂ : (2*r+1-1)/2 = r := by omega + rw [h₁,h₂] + +theorem diagonal_floor_identity (m : ℕ) : + 2*axisPairs m + m + 2*(m*m/4) = m*m := by + have hm : m = 2*(m/2) ∨ m = 2*(m/2)+1 := by omega + rcases hm with hm | hm + · generalize m/2 = r at hm + subst m + rw [axisPairs_even, square_quarter_even] + cases r with + | zero => simp + | succ r => simp only [Nat.add_sub_cancel]; ring + · generalize m/2 = r at hm + subst m + rw [axisPairs_odd, square_quarter_odd] + ring + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FourCyclePairing.lean b/lean/OAI/Combinatorics/Crossing/FourCyclePairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..d40924e17053413d62071decb3ece3a115635143 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FourCyclePairing.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.Crossing.FourCycles +import OAI.Combinatorics.Crossing.RectangleAlgebra + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def edgeBlock {m n : ℕ} (J : Matrix (Fin m × Fin n) (Fin m × Fin n) ℝ) + (i k : Fin m) : Matrix (Fin n) (Fin n) ℝ := fun p q => J (i,p) (k,q) + +def blockRectangle {m n : ℕ} (J : Matrix (Fin m × Fin n) (Fin m × Fin n) ℝ) + (i k i₀ : Fin m) : Matrix (Fin n) (Fin n) ℝ := + edgeBlock J i k - edgeBlock J i i₀ - edgeBlock J i₀ k + edgeBlock J i₀ i₀ + +theorem fourCycle_pairing_rectangle {m n : ℕ} + (J : Matrix (Fin m × Fin n) (Fin m × Fin n) ℝ) + (i k i₀ : Fin m) (p p' q q' : Fin n) : + edgePairing J (walkEdgeChain (fourCycleWalk i i₀ p p')) + (walkEdgeChain (fourCycleWalk k i₀ q q')) = + blockRectangle J i k i₀ p q - blockRectangle J i k i₀ p q' - + blockRectangle J i k i₀ p' q + blockRectangle J i k i₀ p' q' := by + rw [fourCycleWalk_chain, fourCycleWalk_chain] + simp only [edgePairing_add_left, edgePairing_sub_left, edgePairing_add_right, + edgePairing_sub_right, edgePairing_single] + simp only [blockRectangle, edgeBlock, Matrix.add_apply, Matrix.sub_apply] + ring + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/FourCycles.lean b/lean/OAI/Combinatorics/Crossing/FourCycles.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3e61b4e4af72e2488d16b1a0b2924cccd5e12e1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/FourCycles.lean @@ -0,0 +1,51 @@ +import Mathlib.Combinatorics.SimpleGraph.Paths +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.BigOperators.Group.Finset.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open SimpleGraph +open scoped BigOperators + +abbrev completeBipartite (m n : ℕ) := completeBipartiteGraph (Fin m) (Fin n) + +def orientedEdgeStep {m n : ℕ} (u v : Fin m ⊕ Fin n) : Fin m × Fin n → ℝ := + match u,v with + | .inl i, .inr p => Pi.single (i,p) 1 + | .inr p, .inl i => -Pi.single (i,p) 1 + | _, _ => 0 + +def walkEdgeChain {m n : ℕ} {u v : Fin m ⊕ Fin n} : + (completeBipartite m n).Walk u v → (Fin m × Fin n → ℝ) + | .nil => 0 + | @Walk.cons _ _ _ w _ _ rest => orientedEdgeStep u w + walkEdgeChain rest + +def fourCycleWalk {m n : ℕ} (i i₀ : Fin m) (p p₀ : Fin n) : + (completeBipartite m n).Walk (.inl i) (.inl i) := + .cons (v := .inr p) (by simp [completeBipartite, completeBipartiteGraph]) + (.cons (v := .inl i₀) (by simp [completeBipartite, completeBipartiteGraph]) + (.cons (v := .inr p₀) (by simp [completeBipartite, completeBipartiteGraph]) + (.cons (v := .inl i) (by simp [completeBipartite, completeBipartiteGraph]) .nil))) + +theorem fourCycleWalk_isCycle {m n : ℕ} (i i₀ : Fin m) (p p₀ : Fin n) + (hi : i ≠ i₀) (hp : p ≠ p₀) : (fourCycleWalk i i₀ p p₀).IsCycle := by + rw [Walk.isCycle_iff_isPath_tail_and_le_length] + constructor + · apply Walk.IsPath.mk' + change ([Sum.inr p, Sum.inl i₀, Sum.inr p₀, Sum.inl i] : List (Fin m ⊕ Fin n)).Nodup + simp [hp, hi.symm] + · change 3 ≤ (4 : ℕ) + decide + +theorem fourCycleWalk_chain {m n : ℕ} (i i₀ : Fin m) (p p₀ : Fin n) : + walkEdgeChain (fourCycleWalk i i₀ p p₀) = + Pi.single (i,p) 1 - Pi.single (i₀,p) 1 + Pi.single (i₀,p₀) 1 - Pi.single (i,p₀) 1 := by + simp [fourCycleWalk, walkEdgeChain, orientedEdgeStep, sub_eq_add_neg, add_assoc] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GeneralOrderAveraging.lean b/lean/OAI/Combinatorics/Crossing/GeneralOrderAveraging.lean new file mode 100644 index 0000000000000000000000000000000000000000..65a382fa718170bebf6a3c2c859a976a91b7c5c4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GeneralOrderAveraging.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.OrderShift + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem orderSign_of_close (a b z ε : ℝ) (hgap : ε < |a-b|) (hz : |z-b| < ε) : + orderSign a z = orderSign a b := by + have ha : a ≠ b := by intro h; subst a; simp at hgap; have := abs_nonneg (z-b); linarith + have hzb := abs_lt.mp hz + rcases lt_or_gt_of_ne ha with hab | hba + · have hgz : a < z := by rw [abs_of_neg (sub_neg.mpr hab)] at hgap; linarith + simp [orderSign,hab,hgz] + · have hgz : z < a := by rw [abs_of_pos (sub_pos.mpr hba)] at hgap; linarith + simp [orderSign,not_lt.mpr hba.le,not_lt.mpr hgz.le,hba,hgz] + +theorem orderSign_straddling_average (a b p q ε : ℝ) + (hgap : a ≠ b → ε < |a-b|) (hp : |p-b| < ε) (hq : |q-b| < ε) + (hstraddle : (p hne (congrArg node he)) + linarith + have h₁ := hav a c + have h₂ := hav a d + have h₃ := hav b c + have h₄ := hav b d + unfold chordEndpointPairing + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GenericPointExtension.lean b/lean/OAI/Combinatorics/Crossing/GenericPointExtension.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8975adfd51e92116db1ef07bf64ba94390915db --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GenericPointExtension.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.FiniteLineAvoidance +import OAI.Combinatorics.Crossing.SegmentSides + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_generic_point_extension {ι κ ν : Type*} [Fintype ι] [Fintype κ] [Fintype ν] + (p : ι → Plane) (q : ν → Plane) (a v : κ → Plane) + (hv : ∀ k, v k ≠ 0) (hpq : ∀ i j, q j ≠ p i) + (z : Plane) (ε : ℝ) (hε : 0 < ε) : + ∃ x : Plane, dist x z < ε ∧ + (∀ i, x ≠ p i) ∧ (∀ j, q j ≠ x) ∧ + (∀ k, det2 (x-a k) (v k) ≠ 0) ∧ + (∀ i k, det2 (x-p i) (v k) ≠ 0) ∧ + (∀ i j, orient2 (p i) x (q j) ≠ 0) := by + let J := κ ⊕ (ν ⊕ (ι ⊕ ((ι × κ) ⊕ (ι × ν)))) + let base : J → Plane + | .inl k => a k + | .inr (.inl j) => q j + | .inr (.inr (.inl i)) => p i + | .inr (.inr (.inr (.inl (i,_)))) => p i + | .inr (.inr (.inr (.inr (i,_)))) => p i + let direction : J → Plane + | .inl k => v k + | .inr (.inl _) => (1,0) + | .inr (.inr (.inl _)) => (1,0) + | .inr (.inr (.inr (.inl (_,k)))) => v k + | .inr (.inr (.inr (.inr (i,j)))) => q j-p i + have hd : ∀ k, direction k ≠ 0 := by + rintro (k|(j|(i|(⟨i,k⟩|⟨i,j⟩)))) + · exact hv k + · norm_num [direction] + · norm_num [direction] + · exact hv k + · exact sub_ne_zero.mpr (hpq i j) + obtain ⟨x,hx,havoid⟩ := exists_near_avoiding_lines base direction hd z ε hε + refine ⟨x,hx,?_,?_,?_,?_,?_⟩ + · intro i heq + have hh := havoid (.inr (.inr (.inl i))) + simp [base,direction,heq,det2] at hh + · intro j heq + have hh := havoid (.inr (.inl j)) + simp [base,direction,← heq,det2] at hh + · intro k + exact havoid (.inl k) + · intro i k + exact havoid (.inr (.inr (.inr (.inl (i,k))))) + · intro i j + exact havoid (.inr (.inr (.inr (.inr (i,j))))) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GenericPointFamily.lean b/lean/OAI/Combinatorics/Crossing/GenericPointFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b33e4cf44089d5df74a7e529b85a31527c247d2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GenericPointFamily.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.Crossing.GenericPointExtension +import OAI.Combinatorics.Crossing.TriangleOrientations + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_generic_point_family {κ ν : Type*} [Fintype κ] [Fintype ν] + (q : ν → Plane) (a v : κ → Plane) (hv : ∀ k, v k ≠ 0) + (n : ℕ) (z : Fin n → Plane) (ε : Fin n → ℝ) (hε : ∀ i, 0 < ε i) : + ∃ p : Fin n → Plane, (∀ i, dist (p i) (z i) < ε i) ∧ Function.Injective p ∧ + (∀ i j, q j ≠ p i) ∧ + (∀ i k, det2 (p i-a k) (v k) ≠ 0) ∧ + (∀ i j, i ≠ j → ∀ k, det2 (p j-p i) (v k) ≠ 0) ∧ + (∀ i j, i ≠ j → ∀ l, orient2 (p i) (p j) (q l) ≠ 0) := by + induction n with + | zero => + refine ⟨Fin.elim0,?_,?_,?_,?_,?_,?_⟩ <;> intro i <;> exact Fin.elim0 i + | succ n ih => + obtain ⟨p,hp,hinj,hpq,hline,hpar,hcorn⟩ := + ih (fun i => z i.succ) (fun i => ε i.succ) (fun i => hε i.succ) + obtain ⟨x,hx,hxp,hxq,hxl,hxpar,hxcorn⟩ := + exists_generic_point_extension p q a v hv hpq (z 0) (ε 0) (hε 0) + refine ⟨Fin.cons x p,?_,?_,?_,?_,?_,?_⟩ + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · exact hx + · exact hp i + · apply Fin.cons_injective_of_injective _ hinj + rintro ⟨i,hi⟩ + exact hxp i hi.symm + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · exact hxq + · exact hpq i + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · exact hxl + · exact hline i + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · intro j + refine Fin.cases ?_ (fun j => ?_) j + · intro h + exact False.elim (h rfl) + · intro _ k + change det2 (p j-x) (v k) ≠ 0 + have hh : det2 (p j-x) (v k) = -det2 (x-p j) (v k) := by + dsimp [det2] + ring + rw [hh] + exact neg_ne_zero.mpr (hxpar j k) + · intro j + refine Fin.cases ?_ (fun j => ?_) j + · intro _ k + exact hxpar i k + · intro hij k + exact hpar i j (fun h => hij (congrArg Fin.succ h)) k + · intro i + refine Fin.cases ?_ (fun i => ?_) i + · intro j + refine Fin.cases ?_ (fun j => ?_) j + · intro h + exact False.elim (h rfl) + · intro _ l + change orient2 x (p j) (q l) ≠ 0 + rw [orient2_reverse_edge] + exact neg_ne_zero.mpr (hxcorn j l) + · intro j + refine Fin.cases ?_ (fun j => ?_) j + · intro _ l + exact hxcorn i l + · intro hij l + exact hcorn i j (fun h => hij (congrArg Fin.succ h)) l + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GenericPolygonIntersection.lean b/lean/OAI/Combinatorics/Crossing/GenericPolygonIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..00a11539a90ef38b8ce766a0f73e8b0da6537bda --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GenericPolygonIntersection.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.FiniteConePoint +import OAI.Combinatorics.Crossing.ConeIntersection + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def PolygonLinePosition (v w : ℕ → Plane) (n m : ℕ) : Prop := + (∀ i : Fin n, ∀ j : Fin m, det2 (v (i.val+1)-v i.val) (w (j.val+1)-w j.val) ≠ 0) ∧ + (∀ i : Fin (n+1), ∀ j : Fin m, orient2 (w j.val) (w (j.val+1)) (v i.val) ≠ 0) ∧ + (∀ i : Fin n, ∀ j : Fin (m+1), orient2 (v i.val) (v (i.val+1)) (w j.val) ≠ 0) + +theorem polygon_intersection_zero_in_line_position (v w : ℕ → Plane) (n m : ℕ) + (hc : v n = v 0) (hd : w m = w 0) + (hv : ∀ i : Fin n, v (i.val+1) ≠ v i.val) + (hw : ∀ j : Fin m, w (j.val+1) ≠ w j.val) + (hvw : ∀ i : Fin (n+1), ∀ j : Fin (m+1), w j.val ≠ v i.val) + (hp : PolygonLinePosition v w n m) : polygonIntersection v w n m = 0 := by + obtain ⟨o,ha,hb,hpar,hcorn⟩ := exists_polygon_cone_point v w n m hv hw hvw + apply polygon_intersection_zero_of_cone v w n m hc hd o + · intro i hi + exact ha ⟨i,Finset.mem_range.mp hi⟩ + · intro i hi j hj + have hin := Finset.mem_range.mp hi + have hjm := Finset.mem_range.mp hj + let ii : Fin n := ⟨i,Finset.mem_range.mp hi⟩ + let jj : Fin m := ⟨j,Finset.mem_range.mp hj⟩ + let i₀ : Fin (n+1) := ⟨i,by omega⟩ + let i₁ : Fin (n+1) := ⟨i+1,by omega⟩ + let j₀ : Fin (m+1) := ⟨j,by omega⟩ + let j₁ : Fin (m+1) := ⟨j+1,by omega⟩ + refine ⟨?_,?_,?_⟩ + · intro k + fin_cases k + · exact hpar i₀ jj + · exact hp.1 ii jj + · change det2 (o-v (i+1)) (w (j+1)-w j) ≠ 0 + rw [det2_reverse_edge o (v (i+1)) (w j) (w (j+1))] + exact neg_ne_zero.mpr (hpar i₁ jj) + · intro k + fin_cases k + · exact hb jj + · exact hp.2.1 i₀ jj + · exact hp.2.1 i₁ jj + · intro k + fin_cases k + · exact ⟨hcorn i₀ j₀,hcorn i₀ j₁⟩ + · exact ⟨hp.2.2 ii j₀,hp.2.2 ii j₁⟩ + · change orient2 (v (i+1)) o (w j) ≠ 0 ∧ orient2 (v (i+1)) o (w (j+1)) ≠ 0 + rw [orient2_reverse_edge o _ _,orient2_reverse_edge o _ _] + exact ⟨neg_ne_zero.mpr (hcorn i₁ j₀),neg_ne_zero.mpr (hcorn i₁ j₁)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GenericPolynomialBox.lean b/lean/OAI/Combinatorics/Crossing/GenericPolynomialBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae1273ae3e0942d6fdb34a4e23341576015b1a31 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GenericPolynomialBox.lean @@ -0,0 +1,35 @@ +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.MvPolynomial.Funext +import Mathlib.Order.Interval.Set.Infinite + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +theorem exists_box_avoiding_polynomials {σ κ : Type*} [Fintype κ] + (P : κ → MvPolynomial σ ℝ) (hP : ∀ k, P k ≠ 0) + (lo hi : σ → ℝ) (hinterval : ∀ i, lo i < hi i) : + ∃ x : σ → ℝ, (∀ i, x i ∈ Set.Ioo (lo i) (hi i)) ∧ ∀ k, MvPolynomial.eval x (P k) ≠ 0 := by + classical + let Q := ∏ k, P k + have hQ : Q ≠ 0 := Finset.prod_ne_zero_iff.mpr (fun k _ => hP k) + have hex : ∃ x : σ → ℝ, (∀ i, x i ∈ Set.Ioo (lo i) (hi i)) ∧ MvPolynomial.eval x Q ≠ 0 := by + by_contra hh + apply hQ + apply MvPolynomial.funext_set (fun i => Set.Ioo (lo i) (hi i)) (fun i => Set.Ioo_infinite (hinterval i)) + intro x hx + rw [map_zero] + by_contra hz + exact hh ⟨x,fun i => hx i (Set.mem_univ i),hz⟩ + obtain ⟨x,hx,hval⟩ := hex + refine ⟨x,hx,?_⟩ + have he : (∏ k, MvPolynomial.eval x (P k)) ≠ 0 := by simpa only [Q,map_prod] using hval + exact fun k => (Finset.prod_ne_zero_iff.mp he) k (Finset.mem_univ k) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GlobalCycleAveraging.lean b/lean/OAI/Combinatorics/Crossing/GlobalCycleAveraging.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea9a976814d3baef0d28d36555ef14c331024c14 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GlobalCycleAveraging.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.Crossing.VertexPassagePairing + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem closed_cycle_averaged_sum (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) + (hdi : ∀ i, i < N → bipartiteDartEdge (d (i+1)) ≠ bipartiteDartEdge (d i)) + (hfj : ∀ j, j < K → bipartiteDartEdge (f (j+1)) ≠ bipartiteDartEdge (f j)) : + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + (bipartiteDartSign (d i)*bipartiteDartSign (f j)* + V.signedIntersection (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j))+ + C.passagePairing d f hd hf i j)=0 := by + obtain ⟨δ₀,hδ₀,hglobal⟩ := C.exists_closed_cycle_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,hlocal⟩ := C.exists_passage_pairing_radius hnorm + let t := min δ₀ δ₁/2 + have ht : 0 < t := half_pos (lt_min hδ₀ hδ₁) + have htmin : t < min δ₀ δ₁ := half_lt_self (lt_min hδ₀ hδ₁) + have ht₀ : t < δ₀ := htmin.trans_le (min_le_left _ _) + have ht₁ : t < δ₁ := htmin.trans_le (min_le_right _ _) + have hzplus := hglobal t (ne_of_gt ht) (by simpa only [abs_of_pos ht] using ht₀) d f hd hf N K hN hK hdi hfj + have hzminus := hglobal (-t) (neg_ne_zero.mpr (ne_of_gt ht)) + (by simpa only [abs_neg,abs_of_pos ht] using ht₀) d f hd hf N K hN hK hdi hfj + let E : ℕ → ℕ → ℝ := fun i j => bipartiteDartSign (d i)*bipartiteDartSign (f j)* + V.signedIntersection (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j)) + calc + _ = ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + ((E i j+C.passageIntersection d f hd hf i j t)+ + (E i j+C.passageIntersection d f hd hf i j (-t)))/2 := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + rw [← hlocal t ht ht₁ d f hd hf i j (hdi i (Finset.mem_range.mp hi)) (hfj j (Finset.mem_range.mp hj))] + dsimp only [E] + ring + _ = ((∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, (E i j+C.passageIntersection d f hd hf i j t))+ + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, (E i j+C.passageIntersection d f hd hf i j (-t))))/2 := by + simp only [div_eq_mul_inv,Finset.sum_add_distrib,Finset.sum_mul,add_mul] + _ = 0 := by rw [hzplus,hzminus]; norm_num + +theorem graph_cycles_averaged_sum (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + {u v : BipartiteVertex m n} (p : (completeBipartite m n).Walk u u) + (q : (completeBipartite m n).Walk v v) (hp : p.IsCycle) (hq : q.IsCycle) : + let dp := cyclicWalkDart p (by have := hp.three_le_length; omega) + let dq := cyclicWalkDart q (by have := hq.three_le_length; omega) + let sp := cyclicWalkDart_seam p (by have := hp.three_le_length; omega) + let sq := cyclicWalkDart_seam q (by have := hq.three_le_length; omega) + ∑ i ∈ Finset.range p.length, ∑ j ∈ Finset.range q.length, + (bipartiteDartSign (dp i)*bipartiteDartSign (dq j)* + V.signedIntersection (bipartiteDartEdge (dp i)) (bipartiteDartEdge (dq j))+ + C.passagePairing dp dq sp sq i j)=0 := by + dsimp only + exact C.closed_cycle_averaged_sum hnorm hstraight htrans _ _ _ _ _ _ + (cyclicWalkDart_period p _) (cyclicWalkDart_period q _) + (fun i _ => cyclicWalkDart_next_edge_ne p hp i) (fun j _ => cyclicWalkDart_next_edge_ne q hq j) + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GlobalCycleIntersection.lean b/lean/OAI/Combinatorics/Crossing/GlobalCycleIntersection.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb13904bcc0b2bdda487564de5321909eb00b2fd --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GlobalCycleIntersection.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.Crossing.CycleBlockIntersections + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_closed_cycle_intersection_radius (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + ∀ (d f : ℕ → (completeBipartite m n).Dart) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ), d N=d 0 → f K=f 0 → + (∀ i, i < N → bipartiteDartEdge (d (i+1)) ≠ bipartiteDartEdge (d i)) → + (∀ j, j < K → bipartiteDartEdge (f (j+1)) ≠ bipartiteDartEdge (f j)) → + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + (bipartiteDartSign (d i)*bipartiteDartSign (f j)* + V.signedIntersection (bipartiteDartEdge (d i)) (bipartiteDartEdge (f j))+ + C.passageIntersection d f hd hf i j ε)=0 := by + obtain ⟨δ,hδ,hh⟩ := C.exists_cycle_block_radius hnorm hstraight htrans + refine ⟨δ,hδ,?_⟩ + intro ε hε hs d f hd hf N K hN hK hdi hfj + let P := V.dartCycleChain d hd N hN + let Q := C.shiftedCycleChain f hf K hK ε + have hblocks (i j : ℕ) (hi : i < N) (hj : j < K) := + hh ε hε hs d f hd hf i j (hdi i hi) (hfj j hj) + have hT : P.Transverse Q := by + change (finitePolygonalChain Set.univ (V.dartCycleVertex d) (Set.mem_univ _) (V.dartCycleBlock d hd) N).Transverse + (finitePolygonalChain Set.univ (C.shiftedCycleVertex f ε) (Set.mem_univ _) (C.shiftedCycleBlock f hf ε) K) + apply finitePolygonalChain_transverse_left + intro i hi + apply finitePolygonalChain_transverse_right + intro j hj + exact (hblocks i j hi hj).1 + have hzero := P.closed_intersection_zero Q hT + have hsplit : polygonIntersection P.vertices Q.vertices P.pieces Q.pieces= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces := + finitePolygonalChain_intersection_double _ _ _ _ _ _ _ _ + rw [hsplit] at hzero + calc + _ = ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + exact (hblocks i j (Finset.mem_range.mp hi) (Finset.mem_range.mp hj)).2.symm + _ = 0 := hzero + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GraphSequenceWalk.lean b/lean/OAI/Combinatorics/Crossing/GraphSequenceWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..054b9d911cc1651e9613f6349f0269d239fccf23 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GraphSequenceWalk.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.Crossing.GraphWalkTrace + +namespace OAI + +namespace Zarankiewicz + +def graphSequenceWalk {V : Type*} (G : SimpleGraph V) (v : ℕ → V) : + (k : ℕ) → (∀ i, i < k → G.Adj (v i) (v (i+1))) → G.Walk (v 0) (v k) + | 0, _ => .nil + | k+1, h => (graphSequenceWalk G v k (fun i hi => h i (by omega))).concat (h k (by omega)) + +theorem graphSequenceWalk_length {V : Type*} (G : SimpleGraph V) (v : ℕ → V) : + (k : ℕ) → (h : ∀ i, i < k → G.Adj (v i) (v (i+1))) → (graphSequenceWalk G v k h).length=k + | 0, _ => rfl + | k+1, h => by rw [graphSequenceWalk,SimpleGraph.Walk.length_concat,graphSequenceWalk_length] + +theorem graphSequenceWalk_getVert {V : Type*} (G : SimpleGraph V) (v : ℕ → V) : + (k : ℕ) → (h : ∀ i, i < k → G.Adj (v i) (v (i+1))) → + ∀ i, i ≤ k → (graphSequenceWalk G v k h).getVert i=v i + | 0, h, i, hi => by + have he : i=0 := by omega + subst i + exact SimpleGraph.Walk.getVert_zero _ + | k+1, h, i, hi => by + by_cases hik : i ≤ k + · rw [graphSequenceWalk,SimpleGraph.Walk.concat_eq_append,SimpleGraph.Walk.getVert_append', + graphSequenceWalk_length,ite_eq_left hik] + exact graphSequenceWalk_getVert G v k _ i hik + · have he : i=k+1 := by omega + subst i + simpa only [graphSequenceWalk_length] using (graphSequenceWalk G v (k+1) h).getVert_length + +theorem graphSequenceWalk_isPath {V : Type*} (G : SimpleGraph V) (v : ℕ → V) + (k : ℕ) (h : ∀ i, i < k → G.Adj (v i) (v (i+1))) + (hv : Set.InjOn v {i | i ≤ k}) : (graphSequenceWalk G v k h).IsPath := by + apply (SimpleGraph.Walk.IsPath.getVert_injOn_iff _).mp + intro i hi j hj he + rw [graphSequenceWalk_length] at hi hj + rw [graphSequenceWalk_getVert G v k h i hi,graphSequenceWalk_getVert G v k h j hj] at he + exact hv hi hj he + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GraphWalkRealizationLaws.lean b/lean/OAI/Combinatorics/Crossing/GraphWalkRealizationLaws.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d7f167357999e0a50ad912b087cf6772a607fe5 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GraphWalkRealizationLaws.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.DrawingWalkCutTraces +import OAI.Combinatorics.Crossing.ExteriorSegmentGraph + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem graphWalkPath_range_iff {G : SimpleGraph Plane} {a b : Plane} + (p : G.Walk a b) (x : Plane) : + x ∈ Set.range (graphWalkPath id p) ↔ + x=a ∨ ∃ u v, s(u,v) ∈ p.edges ∧ x ∈ segment ℝ u v := by + constructor + · intro hx + rcases graphWalkPath_range_cases id p x hx with h | ⟨i,hi,hx⟩ + · exact Or.inl h + · refine Or.inr ⟨p.getVert i,p.getVert (i+1),?_,hx⟩ + exact (p.mk_mem_edges_iff_exists).mpr ⟨i,hi,rfl⟩ + · rintro (rfl | ⟨u,v,h,hx⟩) + · exact ⟨0,(graphWalkPath id p).source⟩ + · exact graphWalkPath_edge_subset_range p u v h hx + +theorem graphWalkPath_copy_range {G : SimpleGraph Plane} {a b a' b' : Plane} + (p : G.Walk a b) (ha : a=a') (hb : b=b') : + Set.range (graphWalkPath id (p.copy ha hb))=Set.range (graphWalkPath id p) := by + subst a' + subst b' + rfl + +theorem graphWalkPath_mapLe_range {G H : SimpleGraph Plane} (hle : G ≤ H) + {a b : Plane} (p : G.Walk a b) : + Set.range (graphWalkPath id (p.mapLe hle))=Set.range (graphWalkPath id p) := by + ext x + simp only [graphWalkPath_range_iff,SimpleGraph.Walk.edges_mapLe_eq_edges] + +theorem graphWalkPath_append_range {G : SimpleGraph Plane} {a b c : Plane} + (p : G.Walk a b) (q : G.Walk b c) : + Set.range (graphWalkPath id (p.append q))= + Set.range (graphWalkPath id p) ∪ Set.range (graphWalkPath id q) := by + ext x + simp only [Set.mem_union,graphWalkPath_range_iff,SimpleGraph.Walk.edges_append,List.mem_append] + constructor + · rintro (hx | ⟨u,v,h,hx⟩) + · exact Or.inl (Or.inl hx) + · rcases h with h | h + · exact Or.inl (Or.inr ⟨u,v,h,hx⟩) + · exact Or.inr (Or.inr ⟨u,v,h,hx⟩) + · rintro ((hx | ⟨u,v,h,hx⟩) | (hx | ⟨u,v,h,hx⟩)) + · exact Or.inl hx + · exact Or.inr ⟨u,v,Or.inl h,hx⟩ + · have hb : x ∈ Set.range (graphWalkPath id p) := ⟨1,(graphWalkPath id p).target.trans hx.symm⟩ + rcases (graphWalkPath_range_iff p x).mp hb with h | ⟨u,v,h,hx⟩ + · exact Or.inl h + · exact Or.inr ⟨u,v,Or.inl h,hx⟩ + · exact Or.inr ⟨u,v,Or.inr h,hx⟩ + +theorem graphWalkPath_toWalk_range {G : SimpleGraph Plane} {a b : Plane} (h : G.Adj a b) : + Set.range (graphWalkPath id h.toWalk)=segment ℝ a b := by + change Set.range (Path.segment a b)=segment ℝ a b + exact Path.range_segment a b + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/GraphWalkTrace.lean b/lean/OAI/Combinatorics/Crossing/GraphWalkTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..447463581720f5debaaced8702eb252c2716ff17 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/GraphWalkTrace.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.EmbeddedGraphPaths +import OAI.Combinatorics.Crossing.UniqueWalkPassage + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem polygonalArcPath_piece_subset_range (v : ℕ → Plane) : + (k : ℕ) → ∀ i, i < k → segment ℝ (v i) (v (i+1)) ⊆ Set.range (polygonalArcPath v k) + | 0, i, hi => by omega + | 1, i, hi => by + have he : i=0 := by omega + subst i + rw [polygonalArcPath,Path.range_segment] + | k+2, i, hi => by + rw [polygonalArcPath,Path.trans_range] + by_cases hin : i < k+1 + · exact (polygonalArcPath_piece_subset_range v (k+1) i hin).trans Set.subset_union_left + · have he : i=k+1 := by omega + subst i + rw [Path.range_segment] + exact Set.subset_union_right + +theorem graphWalkPath_dart_subset_range {V : Type*} {G : SimpleGraph V} (pos : V → Plane) + {a b : V} (p : G.Walk a b) (d : G.Dart) (hd : d ∈ p.darts) : + segment ℝ (pos d.fst) (pos d.snd) ⊆ Set.range (graphWalkPath pos p) := by + obtain ⟨i,hi,hfst,hsnd⟩ := walk_dart_parameters p d hd + rw [hfst,hsnd] + exact polygonalArcPath_piece_subset_range (fun i => pos (p.getVert i)) p.length i hi + +theorem walk_dart_at {V : Type*} {G : SimpleGraph V} {a b : V} (p : G.Walk a b) + (i : ℕ) (hi : i < p.length) : + ∃ d : G.Dart, d ∈ p.darts ∧ d.fst=p.getVert i ∧ d.snd=p.getVert (i+1) := by + have hi' : i < p.darts.length := by simpa only [p.length_darts] using hi + refine ⟨p.darts[i],List.getElem_mem hi',?_,?_⟩ + · rw [SimpleGraph.Walk.darts_getElem_eq_getVert] + · rw [SimpleGraph.Walk.darts_getElem_eq_getVert] + +theorem graphWalkPath_range_subset_of_darts_subset {V : Type*} {G : SimpleGraph V} + (pos : V → Plane) {a b : V} (p q : G.Walk a b) (hd : q.darts ⊆ p.darts) : + Set.range (graphWalkPath pos q) ⊆ Set.range (graphWalkPath pos p) := by + intro x hx + by_cases hq : q.length=0 + · change x ∈ Set.range (polygonalArcPath (fun i => pos (q.getVert i)) q.length) at hx + rw [hq] at hx + obtain ⟨t,ht⟩ := hx + have he : x=pos a := by simpa [polygonalArcPath,q.getVert_zero] using ht.symm + exact ⟨0,(graphWalkPath pos p).source.trans he.symm⟩ + · obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (fun i => pos (q.getVert i)) q.length (by omega) x hx + obtain ⟨d,hdq,hfst,hsnd⟩ := walk_dart_at q i hi + apply graphWalkPath_dart_subset_range pos p d (hd hdq) + simpa only [hfst,hsnd] using hxi + +theorem graphWalkPath_bypass_range_subset {V : Type*} [DecidableEq V] {G : SimpleGraph V} + (pos : V → Plane) {a b : V} (p : G.Walk a b) : + Set.range (graphWalkPath pos p.bypass) ⊆ Set.range (graphWalkPath pos p) := + graphWalkPath_range_subset_of_darts_subset pos p p.bypass p.darts_bypass_subset_darts + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/HalfOrderInvertibility.lean b/lean/OAI/Combinatorics/Crossing/HalfOrderInvertibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..29f1274f5b6aac90e5edcdee3d52531333e2ab5e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/HalfOrderInvertibility.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.TriangleFactorization +import OAI.Combinatorics.Crossing.DetectorRank + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +theorem rankDetector_halfOrder_isUnit [LinearOrder ι] (s : ℕ) (node : ι → ℝ) + (hn : Function.Injective node) (hcard : Fintype.card ι = 2*s+1) : + IsUnit (rankDetector s node (halfOrderMatrix ι)) := by + let e : OrderedNode s ≃o ι := + (Fintype.orderIsoFinOfCardEq (OrderedNode s) (card_orderedNode s)).symm.trans + (Fintype.orderIsoFinOfCardEq ι hcard) + have hunit := rankDetector_ordered_isUnit s (node ∘ e) (hn.comp e.injective) + have he := rankDetector_equiv s node e.toEquiv (halfOrderMatrix ι) + change rankDetector s (node ∘ e) ((halfOrderMatrix ι).submatrix e e) = + rankDetector s node (halfOrderMatrix ι) at he + rw [halfOrderMatrix_orderIso e] at he + rwa [he] at hunit + +theorem lemma4_2 (s : ℕ) (hs : 0 < s) (node : ι → ℝ) (hn : Function.Injective node) + (hcard : Fintype.card ι = 2*s+1) : + (∀ r c : ι → ℝ, rankDetector s node (fun p q => r p+c q) = 0) ∧ + (∀ d : ι → ℝ, rankDetector s node (Matrix.diagonal d) = 0) ∧ + (∀ p q : ι, p ≠ q → (rankDetector s node (Matrix.single p q 1)).rank = 1) ∧ + (∀ order : LinearOrder ι, IsUnit (rankDetector s node (@halfOrderMatrix ι order))) := by + refine ⟨rankDetector_additive s node hn hcard, rankDetector_diagonal s node, ?_, ?_⟩ + · intro p q hpq + rw [rankDetector_single, one_smul] + exact detectorAtom_rank_one s hs node hn hpq + · intro order + let := order + exact rankDetector_halfOrder_isUnit s node hn hcard + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/HalfOrderReduction.lean b/lean/OAI/Combinatorics/Crossing/HalfOrderReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..29e8a8f802583892d423036d1b95c6f213f4ac67 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/HalfOrderReduction.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.Crossing.DetectorAnnihilation +import OAI.Combinatorics.Crossing.DetectorRelabeling +import OAI.Combinatorics.Crossing.OrderedNodeIndices + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +variable {ι : Type*} + +def strictLowerMatrix (α : Type*) [LinearOrder α] : Matrix α α ℝ := + fun p q => if q < p then 1 else 0 + +theorem halfOrder_decomposition [LinearOrder ι] : + halfOrderMatrix ι = Matrix.of (fun (_ _ : ι) => (1/2 : ℝ)) - strictLowerMatrix ι - + Matrix.diagonal (fun _ => (1/2 : ℝ)) := by + funext p q + rcases lt_trichotomy p q with h | rfl | h + · norm_num [halfOrderMatrix, strictLowerMatrix, Matrix.diagonal_apply, Matrix.of_apply, ne_of_lt h, + h, not_lt.mpr h.le] + · norm_num [halfOrderMatrix, strictLowerMatrix, Matrix.diagonal_apply] + · norm_num [halfOrderMatrix, strictLowerMatrix, Matrix.diagonal_apply, Matrix.of_apply, (ne_of_lt h).symm, + h, not_lt.mpr h.le] + +def triangleCoefficient (s : ℕ) (p q : OrderedNode s) : ℝ := + if p.val ≤ s+1 then (if q < p then 1 else 0) else (if p < q then -1 else 0) + +def rowCut (s : ℕ) (p : OrderedNode s) : ℝ := if s+1 < p.val then 1 else 0 + +theorem lower_triangle_decomposition (s : ℕ) : + strictLowerMatrix (OrderedNode s) = Matrix.of (fun p q => triangleCoefficient s p q) + + Matrix.of (fun p (_ : OrderedNode s) => rowCut s p) + Matrix.diagonal (fun p => -rowCut s p) := by + funext p q + rcases lt_trichotomy p q with h | rfl | h + · simp [strictLowerMatrix, triangleCoefficient, rowCut, Matrix.of_apply, + h, not_lt.mpr h.le, ne_of_lt h] + split_ifs <;> norm_num <;> omega + · simp [strictLowerMatrix, triangleCoefficient, rowCut] + · simp [strictLowerMatrix, triangleCoefficient, rowCut, Matrix.of_apply, + h, not_lt.mpr h.le, (ne_of_lt h).symm] + split_ifs <;> norm_num <;> omega + +theorem triangleCoefficient_nat_nonzero (s p q : ℕ) (hp : 1 ≤ p ∧ p ≤ 2*s+1) + (hq : 1 ≤ q ∧ q ≤ 2*s+1) : + (if p ≤ s+1 then (if q < p then (1 : ℝ) else 0) + else (if p < q then -1 else 0)) ≠ 0 ↔ (p,q) ∈ twoTriangle s := by + obtain ⟨hp_lower, hp_upper⟩ := hp + rw [mem_twoTriangle] + split_ifs <;> norm_num <;> omega + +theorem triangleCoefficient_ne_zero_iff (s : ℕ) (p q : OrderedNode s) : + triangleCoefficient s p q ≠ 0 ↔ (p.val,q.val) ∈ twoTriangle s := + triangleCoefficient_nat_nonzero s p.val q.val (Finset.mem_Icc.mp p.property) + (Finset.mem_Icc.mp q.property) + +theorem rankDetector_halfOrder_reduction (s : ℕ) (node : OrderedNode s → ℝ) + (hn : Function.Injective node) : + rankDetector s node (halfOrderMatrix (OrderedNode s)) = + -rankDetector s node (Matrix.of (fun p q => triangleCoefficient s p q)) := by + have hrow := rankDetector_additive s node hn (card_orderedNode s) (rowCut s) (fun _ => 0) + simp only [add_zero] at hrow + change rankDetector s node (Matrix.of (fun p (_ : OrderedNode s) => rowCut s p)) = 0 at hrow + have hconst := rankDetector_additive s node hn (card_orderedNode s) (fun _ => (1/2 : ℝ)) (fun _ => 0) + simp only [add_zero] at hconst + change rankDetector s node (Matrix.of (fun (_ _ : OrderedNode s) => (1/2 : ℝ))) = 0 at hconst + have hlower : rankDetector s node (strictLowerMatrix (OrderedNode s)) = + rankDetector s node (Matrix.of (fun p q => triangleCoefficient s p q)) := by + rw [lower_triangle_decomposition, map_add, map_add, hrow, rankDetector_diagonal, add_zero, add_zero] + rw [halfOrder_decomposition, map_sub, map_sub, hconst, hlower, rankDetector_diagonal, + zero_sub, sub_zero] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/IncidentSpokePorts.lean b/lean/OAI/Combinatorics/Crossing/IncidentSpokePorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a2b0878964e4df47772e6d654439d3271ed6f00 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/IncidentSpokePorts.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.Crossing.DrawingSpokePorts +import OAI.Combinatorics.Crossing.RowCrossingCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def IncidentEdges (j : BipartiteVertex m n) := + {e : BipartiteEdge m n // j=Sum.inl e.1 ∨ j=Sum.inr e.2} + +instance incidentEdgesFintype (j : BipartiteVertex m n) : Fintype (IncidentEdges j) := by + classical + unfold IncidentEdges + infer_instance + +theorem incident_edges_adjacent (j : BipartiteVertex m n) (e f : IncidentEdges j) : + e.val.1=f.val.1 ∨ e.val.2=f.val.2 := by + rcases e.property with he | he <;> rcases f.property with hf | hf + · exact Or.inl (Sum.inl.inj (he.symm.trans hf)) + · cases he.symm.trans hf + · cases he.symm.trans hf + · exact Or.inr (Sum.inr.inj (he.symm.trans hf)) + +def drawingSpokePort (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (r : ℝ) (j : BipartiteVertex m n) (e : IncidentEdges j) : Plane := + if j=Sum.inl e.val.1 then (P e.val).startPort r else (P e.val).endPort r + +theorem drawingSpokePort_interior (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (j : BipartiteVertex m n) (e : IncidentEdges j) : + drawingSpokePort D P r j e ∈ edgeInterior D e.val := by + unfold drawingSpokePort + split_ifs + · exact drawing_chain_startPort_interior D e.val (P e.val) (hmin e.val) r hr (hshort e.val).1 + · exact drawing_chain_endPort_interior D e.val (P e.val) (hmin e.val) r hr (hshort e.val).2 + +theorem drawingSpokePort_circle (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (j : BipartiteVertex m n) (e : IncidentEdges j) : + squaredLength (drawingSpokePort D P r j e-D.vertex j)=r^2 := by + unfold drawingSpokePort + split_ifs with h + · simpa only [h] using drawing_chain_startPort_circle D e.val (P e.val) (hmin e.val) r + · have he := e.property.resolve_left h + simpa only [he] using drawing_chain_endPort_circle D e.val (P e.val) (hmin e.val) r + +theorem drawingSpokePort_injective (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (j : BipartiteVertex m n) : Function.Injective (drawingSpokePort D.toContinuousDrawing P r j) := by + intro e f heq + by_contra hne + have hef : e.val ≠ f.val := fun h => hne (Subtype.ext h) + have hp := drawingSpokePort_interior D.toContinuousDrawing P hmin r hr hshort j e + have hq := drawingSpokePort_interior D.toContinuousDrawing P hmin r hr hshort j f + rw [← heq] at hq + have hh : drawingSpokePort D.toContinuousDrawing P r j e ∈ + edgeInterior D.toContinuousDrawing e.val ∩ edgeInterior D.toContinuousDrawing f.val := ⟨hp,hq⟩ + rw [hnorm e.val f.val hef (incident_edges_adjacent j e f)] at hh + exact hh + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/IndexedMatrixRankSum.lean b/lean/OAI/Combinatorics/Crossing/IndexedMatrixRankSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf10667141a166dd9ba59a10913357957242b95a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/IndexedMatrixRankSum.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.Crossing.MatrixRankSum +import Mathlib.LinearAlgebra.Matrix.Reindex + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +theorem matrix_rank_sum_bound_indexed {κ : Type*} [Fintype κ] [DecidableEq κ] + (m : ℕ) (X Y : Fin m → Matrix κ κ ℝ) (hdiag : ∀ i, IsUnit (X i-Y i)) : + 2*axisPairs m*Fintype.card κ ≤ ∑ i, ∑ j ∈ Finset.univ.erase i, (X i-Y j).rank := by + let e := Fintype.equivFin κ + let R := Matrix.reindexRingEquiv ℝ e + have hunit : ∀ i, IsUnit (R (X i)-R (Y i)) := by + intro i + rw [← map_sub] + exact (hdiag i).map R.toMonoidHom + have hrank (i j : Fin m) : (R (X i)-R (Y j)).rank=(X i-Y j).rank := by + rw [← map_sub] + exact Matrix.rank_reindex e e (X i-Y j) + have h := matrix_rank_sum_bound m (Fintype.card κ) (fun i => R (X i)) (fun i => R (Y i)) hunit + simpa only [offDiagonalRankSum,hrank] using h + +theorem matrix_rank_sum_bound_product (m s : ℕ) + (X Y : Fin m → Matrix (Fin s × Fin s) (Fin s × Fin s) ℝ) + (hdiag : ∀ i, IsUnit (X i-Y i)) : + 2*axisPairs m*(s*s) ≤ ∑ i, ∑ j ∈ Finset.univ.erase i, (X i-Y j).rank := by + simpa only [Fintype.card_prod,Fintype.card_fin] using matrix_rank_sum_bound_indexed m X Y hdiag + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/InnerDrawingPassages.lean b/lean/OAI/Combinatorics/Crossing/InnerDrawingPassages.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5c9704eb56c162b542e7a7cc7a395bff0525559 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/InnerDrawingPassages.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.Crossing.DrawingPorts +import OAI.Combinatorics.Crossing.RoundCircleChords + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +abbrev InnerIndex (C : DrawingPassages D) := + (e : BipartiteEdge m n) × {i : Fin (C.count e+1) // 0 < i.val ∧ i.val < C.count e} + +def innerMark (C : DrawingPassages D) (p : C.InnerIndex) : DrawingMark D := + ⟨D.edge p.1 (C.node p.1 p.2.val),C.node_mark p.1 p.2.val⟩ + +def incomingArc (C : DrawingPassages D) (p : C.InnerIndex) : C.ArcIndex := + ⟨p.1,⟨p.2.val.val-1,by have h := p.2.property; omega⟩⟩ + +def outgoingArc (C : DrawingPassages D) (p : C.InnerIndex) : C.ArcIndex := + ⟨p.1,⟨p.2.val.val,p.2.property.2⟩⟩ + +def incomingPort (C : DrawingPassages D) (p : C.InnerIndex) : C.Port := (C.incomingArc p,true) +def outgoingPort (C : DrawingPassages D) (p : C.InnerIndex) : C.Port := (C.outgoingArc p,false) + +theorem incoming_node (C : DrawingPassages D) (p : C.InnerIndex) : + (C.incomingArc p).2.succ=p.2.val := by + apply Fin.ext + change p.2.val.val-1+1=p.2.val.val + have h := p.2.property.1 + omega + +theorem outgoing_node (C : DrawingPassages D) (p : C.InnerIndex) : + (C.outgoingArc p).2.castSucc=p.2.val := rfl + +theorem incomingPort_mark (C : DrawingPassages D) (p : C.InnerIndex) : + C.portMark (C.incomingPort p)=C.innerMark p := by + apply Subtype.ext + change D.edge p.1 (C.node p.1 (C.incomingArc p).2.succ)=D.edge p.1 (C.node p.1 p.2.val) + rw [C.incoming_node] + +theorem outgoingPort_mark (C : DrawingPassages D) (p : C.InnerIndex) : + C.portMark (C.outgoingPort p)=C.innerMark p := rfl + +theorem incomingPort_point (C : DrawingPassages D) (p : C.InnerIndex) : + C.portPoint (C.incomingPort p)=D.edge p.1 (C.passage p.1 p.2.val).enter := by + change D.edge p.1 (C.passage p.1 (C.incomingArc p).2.succ).enter=_ + rw [C.incoming_node] + +theorem outgoingPort_point (C : DrawingPassages D) (p : C.InnerIndex) : + C.portPoint (C.outgoingPort p)=D.edge p.1 (C.passage p.1 p.2.val).leave := rfl + +theorem inner_parameter_interior (C : DrawingPassages D) (p : C.InnerIndex) : + C.node p.1 p.2.val ∈ Set.Ioo (0 : unitInterval) 1 := by + constructor + · rw [← C.first p.1] + exact C.increasing p.1 (show (0 : Fin (C.count p.1+1)) < p.2.val from p.2.property.1) + · rw [← C.last p.1] + exact C.increasing p.1 (show p.2.val < Fin.last (C.count p.1) from p.2.property.2) + +theorem innerMark_is_crossing (C : DrawingPassages D) (p : C.InnerIndex) : + (C.innerMark p).val ∈ crossingPoints D.toContinuousDrawing := by + have hm := (C.innerMark p).property + rcases hm with ⟨v,hv⟩ | hcross + · exact False.elim (D.interior_avoids_vertices p.1 (C.node p.1 p.2.val) + (C.inner_parameter_interior p) v hv.symm) + · exact hcross + +def crossingChord (C : DrawingPassages D) (p : C.InnerIndex) : + Path (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := + Path.segment _ _ + +theorem crossingChord_injective (C : DrawingPassages D) (p : C.InnerIndex) : + Function.Injective (C.crossingChord p) := by + apply Path.segment_injective_of_ne + intro he + rw [C.incomingPort_point,C.outgoingPort_point] at he + exact (C.passage p.1 p.2.val).enter_lt_leave.ne (D.edge_injective p.1 he) + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/Interpolation.lean b/lean/OAI/Combinatorics/Crossing/Interpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..411fcce2bbaf1ffd5d8522a870b5e18b8e7acfe1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/Interpolation.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.Crossing.PolynomialKernel +import Mathlib.LinearAlgebra.Lagrange +import Mathlib.LinearAlgebra.Dimension.Constructions + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule +open scoped BigOperators +variable {W : Type*} [AddCommGroup W] [Module ℝ W] +variable {ι : Type*} + +theorem bounded_sum (s : Finset ι) (p : ι → PolynomialModule ℝ W) (k : ℕ) + (hp : ∀ i ∈ s, Bounded k (p i)) : Bounded k (∑ i ∈ s, p i) := by + classical + induction s using Finset.induction_on with + | empty => simpa using bounded_zero (W := W) k + | @insert a s ha ih => + rw [Finset.sum_insert ha] + exact bounded_add (hp a (Finset.mem_insert_self a s)) + (ih fun i hi => hp i (Finset.mem_insert_of_mem hi)) + +theorem eq_zero_of_node_roots (node : ι → ℝ) (hn : Function.Injective node) + (s : Finset ι) (p : PolynomialModule ℝ W) (hp : Bounded s.card p) + (he : ∀ i ∈ s, eval (node i) p = 0) : p = 0 := by + classical + induction s using Finset.induction_on generalizing p with + | empty => exact (bounded_zero_iff p).mp hp + | @insert a s ha ih => + have hp' : Bounded (s.card+1) p := by simpa [Finset.card_insert_of_notMem ha] using hp + obtain ⟨q, hq, eq⟩ := exists_mulRoot_of_eval_zero (node a) s.card p hp' + (he a (Finset.mem_insert_self a s)) + have hqe : ∀ i ∈ s, eval (node i) q = 0 := by + intro i hi + have h := he i (Finset.mem_insert_of_mem hi) + rw [← eq, eval_mulRoot] at h + have hia : node i - node a ≠ 0 := sub_ne_zero.mpr (fun e => ha (hn e ▸ hi)) + exact (smul_eq_zero.mp h).resolve_left hia + have hq0 := ih q hq hqe + rw [← eq, hq0] + simp [mulRoot] + +variable [Fintype ι] +variable (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + +def nodeEvaluation : constrained U node Z (Fintype.card ι) →ₗ[ℝ] (∀ i, ↥(U i ⊓ Z)) where + toFun p i := ⟨Z.subtype (eval (node i) p.val), p.property.2 i, + (eval (node i) p.val).property⟩ + map_add' p q := by ext i; simp + map_smul' c p := by ext i; simp + +theorem nodeEvaluation_injective (hn : Function.Injective node) : + Function.Injective (nodeEvaluation U node Z) := by + intro p q he + apply Subtype.ext + apply sub_eq_zero.mp + apply eq_zero_of_node_roots node hn Finset.univ (p.val-q.val) + · simpa using bounded_sub p.property.1 q.property.1 + · intro i hi + rw [map_sub, sub_eq_zero] + apply Subtype.ext + exact congrArg (fun x : ↥(U i ⊓ Z) => x.val) (congrFun he i) + +def vectorInterpolant (z : ∀ i, ↥(U i ⊓ Z)) : PolynomialModule ℝ Z := + by + classical + exact ∑ i, Lagrange.basis Finset.univ node i • single ℝ 0 ⟨(z i).val, (z i).property.2⟩ + +theorem eval_vectorInterpolant (hn : Function.Injective node) (z : ∀ i, ↥(U i ⊓ Z)) (i : ι) : + eval (node i) (vectorInterpolant U node Z z) = ⟨(z i).val, (z i).property.2⟩ := by + classical + simp only [vectorInterpolant, map_sum, eval_smul, eval_single, pow_zero, one_smul] + rw [Finset.sum_eq_single i] + · rw [Lagrange.eval_basis_self hn.injOn (Finset.mem_univ i), one_smul] + · intro j hj hji + rw [Lagrange.eval_basis_of_ne hji (Finset.mem_univ i), zero_smul] + · simp + +theorem bounded_vectorInterpolant (hn : Function.Injective node) (z : ∀ i, ↥(U i ⊓ Z)) : + Bounded (Fintype.card ι) (vectorInterpolant U node Z z) := by + classical + apply bounded_sum + intro i hi n hge + rw [smul_single_apply] + simp only [Nat.zero_le, ite_true, Nat.sub_zero] + rw [Polynomial.coeff_eq_zero_of_natDegree_lt] + · exact zero_smul _ _ + · have hc : 0 < Fintype.card ι := Fintype.card_pos_iff.mpr ⟨i⟩ + rw [Lagrange.natDegree_basis hn.injOn hi, Finset.card_univ] + omega + +theorem nodeEvaluation_surjective (hn : Function.Injective node) : + Function.Surjective (nodeEvaluation U node Z) := by + intro z + have hu : ∀ i, Z.subtype (eval (node i) (vectorInterpolant U node Z z)) ∈ U i := by + intro i + rw [eval_vectorInterpolant U node Z hn z i] + exact (z i).property.1 + refine ⟨⟨vectorInterpolant U node Z z, bounded_vectorInterpolant U node Z hn z, hu⟩, ?_⟩ + funext i + apply Subtype.ext + exact congrArg Z.subtype (eval_vectorInterpolant U node Z hn z i) + +def nodeEvaluationEquiv (hn : Function.Injective node) : + constrained U node Z (Fintype.card ι) ≃ₗ[ℝ] (∀ i, ↥(U i ⊓ Z)) := + LinearEquiv.ofBijective (nodeEvaluation U node Z) + ⟨nodeEvaluation_injective U node Z hn, nodeEvaluation_surjective U node Z hn⟩ + +theorem finrank_constrained_zero + {W : Type*} [AddCommGroup W] [Module ℝ W] {ι : Type*} [Fintype ι] + (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + : Module.finrank ℝ (constrained U node Z 0) = 0 := by + have hz : constrained U node Z 0 = ⊥ := by + apply le_antisymm _ bot_le + intro p hp + exact (Submodule.mem_bot ℝ).mpr ((bounded_zero_iff p).mp hp.1) + rw [hz] + simp + +theorem constrained_finrank_mono + {W : Type*} [AddCommGroup W] [Module ℝ W] {ι : Type*} [Fintype ι] + (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + [FiniteDimensional ℝ W] : + Monotone (fun k => Module.finrank ℝ (constrained U node Z k)) := by + intro k l hkl + exact Submodule.finrank_mono (fun p hp => ⟨bounded_mono hp.1 hkl, hp.2⟩) + +theorem sum_rankIncrement [FiniteDimensional ℝ W] (m : ℕ) : + ∑ h ∈ Finset.range m, rankIncrement U node Z h = + Module.finrank ℝ (constrained U node Z m) := by + unfold rankIncrement + rw [Finset.sum_range_tsub (constrained_finrank_mono U node Z), finrank_constrained_zero, + Nat.sub_zero] + +theorem interpolation_identity [FiniteDimensional ℝ W] (hn : Function.Injective node) : + ∑ h ∈ Finset.range (Fintype.card ι), rankIncrement U node Z h = + ∑ i, Module.finrank ℝ ↥(U i ⊓ Z) := by + rw [sum_rankIncrement, (nodeEvaluationEquiv U node Z hn).finrank_eq, + Module.finrank_pi_fintype] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/IntervalSegmentStrict.lean b/lean/OAI/Combinatorics/Crossing/IntervalSegmentStrict.lean new file mode 100644 index 0000000000000000000000000000000000000000..2618f973869be0ba5291c2091d8b202d66372a30 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/IntervalSegmentStrict.lean @@ -0,0 +1,20 @@ +import OAI.Combinatorics.Crossing.PathSubarc + +namespace OAI + +namespace Zarankiewicz + +theorem intervalSegment_strict_between (a b t : unitInterval) (hab : a < b) + (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : + a < intervalSegment a b t ∧ intervalSegment a b t < b := by + have hab' : a.val < b.val := hab + have ht0 : 0 < t.val := ht.1 + have ht1 : t.val < 1 := ht.2 + have h₀ := mul_pos ht0 (sub_pos.mpr hab') + have h₁ := mul_pos (sub_pos.mpr ht1) (sub_pos.mpr hab') + change a.val < (1-t.val)*a.val+t.val*b.val ∧ (1-t.val)*a.val+t.val*b.val < b.val + constructor <;> nlinarith + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/IntervalSegments.lean b/lean/OAI/Combinatorics/Crossing/IntervalSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd4526ad09511f08f5949c444d40c8eae6bd08f2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/IntervalSegments.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Tactic.Linarith + +namespace OAI + +namespace Zarankiewicz + +def intervalSegment (a b t : unitInterval) : unitInterval := + ⟨(1-t.val)*a.val+t.val*b.val,by + constructor + · exact add_nonneg (mul_nonneg (sub_nonneg.mpr t.property.2) a.property.1) + (mul_nonneg t.property.1 b.property.1) + · have h₀ := mul_le_mul_of_nonneg_left a.property.2 (sub_nonneg.mpr t.property.2) + have h₁ := mul_le_mul_of_nonneg_left b.property.2 t.property.1 + linarith⟩ + +theorem intervalSegment_between (a b t : unitInterval) (hab : a ≤ b) : + a ≤ intervalSegment a b t ∧ intervalSegment a b t ≤ b := by + have hab' : a.val ≤ b.val := hab + have h₀ := mul_nonneg t.property.1 (sub_nonneg.mpr hab') + have h₁ := mul_nonneg (sub_nonneg.mpr t.property.2) (sub_nonneg.mpr hab') + change a.val ≤ (1-t.val)*a.val+t.val*b.val ∧ (1-t.val)*a.val+t.val*b.val ≤ b.val + constructor <;> nlinarith + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/LocalLineBends.lean b/lean/OAI/Combinatorics/Crossing/LocalLineBends.lean new file mode 100644 index 0000000000000000000000000000000000000000..987ba2dd6b9e1d2a0fa2eda143d9b58e9fd3b0e2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/LocalLineBends.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.Crossing.ParallelDirection +import OAI.Combinatorics.Crossing.FiniteEventualRadius +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem segment_direction_of_local_line (a b d : Plane) (U : Set Plane) + (hU : IsOpen U) (hb : b ∈ U) + (hline : ∀ z ∈ U, z ∈ segment ℝ b a → det2 d (z-b)=0) : + det2 d (a-b)=0 := by + have hc : Continuous (fun t : ℝ => segmentPoint b a t) := by dsimp [segmentPoint]; fun_prop + have hh : ∀ᶠ t : ℝ in 𝓝 0, segmentPoint b a t ∈ U := by + exact hc.continuousAt.eventually (by simpa using hU.mem_nhds hb) + obtain ⟨r,hr,hs⟩ := Metric.eventually_nhds_iff.mp hh + let t : ℝ := min (r/2) (1/2) + have ht : 0 < t := lt_min (by linarith) (by norm_num) + have htr : t < r := (min_le_left _ _).trans_lt (by linarith) + have ht1 : t ≤ 1 := (min_le_right _ _).trans (by norm_num) + have hm : segmentPoint b a t ∈ U := hs (by simpa [Real.dist_eq,abs_of_pos ht] using htr) + have hseg : segmentPoint b a t ∈ segment ℝ b a := by + rw [← Path.range_segment] + exact ⟨⟨t,⟨ht.le,ht1⟩⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint]⟩ + have he := hline _ hm hseg + have heq : segmentPoint b a t-b=t • (a-b) := by + apply Prod.ext <;> dsimp [segmentPoint] <;> ring + rw [heq,det2_smul_right] at he + exact (mul_eq_zero.mp he).resolve_left (ne_of_gt ht) + +theorem bend_det_zero_of_local_line (a b c d : Plane) (hd : d ≠ 0) + (U : Set Plane) (hU : IsOpen U) (hb : b ∈ U) + (hline : ∀ z ∈ U, z ∈ segment ℝ a b ∪ segment ℝ b c → det2 d (z-b)=0) : + det2 (b-a) (c-b)=0 := by + have ha := segment_direction_of_local_line a b d U hU hb (by + intro z hz hs + exact hline z hz (Or.inl (by simpa only [segment_symm ℝ b a] using hs))) + have hc := segment_direction_of_local_line c b d U hU hb (fun z hz hs => hline z hz (Or.inr hs)) + have hba : b-a=-(a-b) := by abel + rw [hba,vector_parallel_of_det_zero d (a-b) hd ha, + vector_parallel_of_det_zero d (c-b) hd hc,det2_neg_left, + det2_smul_left,det2_smul_right,det2_self] + ring + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/LocalSegmentTransversality.lean b/lean/OAI/Combinatorics/Crossing/LocalSegmentTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..95c0c665a43a3e424eb947be021cc78ef09374e9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/LocalSegmentTransversality.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.LocalLineBends + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segment_direction_of_local_line_at_interior (a b x d : Plane) + (hx : x ∈ openSegmentTrace a b) (U : Set Plane) (hU : IsOpen U) (hxU : x ∈ U) + (hline : ∀ z ∈ U, z ∈ segment ℝ a b → det2 d (z-x)=0) : + det2 d (b-a)=0 := by + obtain ⟨t,ht,he⟩ := hx + have hxseg : x ∈ segment ℝ a b := by + rw [← Path.range_segment] + exact ⟨⟨t,⟨ht.1.le,ht.2.le⟩⟩,by simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he⟩ + have hsub := (convex_segment (𝕜 := ℝ) a b).segment_subset hxseg (right_mem_segment ℝ a b) + have hh := segment_direction_of_local_line b x d U hU hxU (fun z hz hs => hline z hz (hsub hs)) + have heq : b-x=(1-t) • (b-a) := by + rw [← he] + apply Prod.ext <;> dsimp [segmentPoint] <;> ring + rw [heq,det2_smul_right] at hh + exact (mul_eq_zero.mp hh).resolve_left (by linarith [ht.2]) + +theorem det2_ne_zero_of_parallel_nonzero (d e u v : Plane) + (hde : det2 d e ≠ 0) (hu : u ≠ 0) (hv : v ≠ 0) + (hdu : det2 d u=0) (hev : det2 e v=0) : det2 u v ≠ 0 := by + have hd : d ≠ 0 := by intro h; subst d; simp at hde + have he : e ≠ 0 := by intro h; subst e; simp at hde + have hU := vector_parallel_of_det_zero d u hd hdu + have hV := vector_parallel_of_det_zero e v he hev + have hα : dot2 d u/squaredLength d ≠ 0 := by + intro h + rw [h,zero_smul] at hU + exact hu hU + have hβ : dot2 e v/squaredLength e ≠ 0 := by + intro h + rw [h,zero_smul] at hV + exact hv hV + conv_lhs => rw [hU,hV,det2_smul_left,det2_smul_right] + exact mul_ne_zero hα (mul_ne_zero hβ hde) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/LocallyStraightNormalization.lean b/lean/OAI/Combinatorics/Crossing/LocallyStraightNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb64a2b957137bc40cff38d1727bbdcecaaf589e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/LocallyStraightNormalization.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.PolygonalNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def LocallyStraightAt (D : ContinuousDrawing m n) (e : BipartiteEdge m n) (x : Plane) : Prop := + ∃ a b : Plane, a ≠ b ∧ x ∈ openSegmentTrace a b ∧ + ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + ∀ z ∈ U, z ∈ edgeInterior D e ↔ z ∈ openSegmentTrace a b + +def LocallyStraightCrossings (D : AdmissibleDrawing m n) : Prop := + ∀ e f : BipartiteEdge m n, e ≠ f → ∀ x, + x ∈ edgeInterior D.toContinuousDrawing e → x ∈ edgeInterior D.toContinuousDrawing f → + LocallyStraightAt D.toContinuousDrawing e x ∧ LocallyStraightAt D.toContinuousDrawing f x + +namespace PolygonalExterior +variable {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_locallyStraightCrossings (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + LocallyStraightCrossings (E.assembledAdmissible v hvinj hv hdet) := by + intro e f hef x hx hy + obtain ⟨s,hs,he⟩ := hx + obtain ⟨t,ht,hf⟩ := hy + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) ⟨s,he⟩ ⟨t,hf⟩ + have hpq : p ≠ q := fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + have hpx := (C.crossingChord_meeting_proper p q hpq x hxp hxq).1 + have hqx := (C.crossingChord_meeting_proper q p (Ne.symm hpq) x hxq hxp).1 + have hlocal (r : C.InnerIndex) (hr : x ∈ C.crossingDisk r) + (hxr : x ∈ Set.range (C.crossingChord r)) : + LocallyStraightAt (E.assembledDrawing v hvinj hv) r.1 x := by + refine ⟨C.portPoint (C.incomingPort r),C.portPoint (C.outgoingPort r), + C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort r r), + (C.crossingChord_openTrace_iff r x hr).mp hxr,C.crossingDisk r,C.crossingDisk_isOpen r,hr,?_⟩ + exact E.assembled_trace_in_crossingDisk v hvinj hv r + change LocallyStraightAt (E.assembledDrawing v hvinj hv) e x ∧ + LocallyStraightAt (E.assembledDrawing v hvinj hv) f x + exact ⟨by simpa only [hp] using hlocal p hpx hxp,by simpa only [hq] using hlocal q hqx hxq⟩ + +end PolygonalExterior + +theorem polygonal_normalization_locally_straight (D : AdmissibleDrawing m n) : + ∃ D' : AdmissibleDrawing m n, crossingCount D' ≤ crossingCount D ∧ + (∀ e, HasFiniteAffineCover (D'.edge e)) ∧ LocallyStraightCrossings D' := by + obtain ⟨C⟩ := nonempty_drawingPassages D.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembled_crossingCount_le v hvinj hv hdet, + E.assembledEdge_hasFiniteAffineCover v,E.assembled_locallyStraightCrossings v hvinj hv hdet⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/LocallyTransverseNormalization.lean b/lean/OAI/Combinatorics/Crossing/LocallyTransverseNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..8568b68d6af7c829ffd40974a815f7c4dd6e73ab --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/LocallyTransverseNormalization.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.Crossing.NoAdjacentLocalNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def LocallyTransverseCrossings (D : AdmissibleDrawing m n) : Prop := + ∀ e f : BipartiteEdge m n, e ≠ f → ∀ x, + x ∈ edgeInterior D.toContinuousDrawing e → x ∈ edgeInterior D.toContinuousDrawing f → + ∃ a b c d : Plane, det2 (b-a) (d-c) ≠ 0 ∧ + x ∈ openSegmentTrace a b ∧ x ∈ openSegmentTrace c d ∧ + ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + (∀ z ∈ U, z ∈ edgeInterior D.toContinuousDrawing e ↔ z ∈ openSegmentTrace a b) ∧ + (∀ z ∈ U, z ∈ edgeInterior D.toContinuousDrawing f ↔ z ∈ openSegmentTrace c d) + +theorem DrawingPassages.crossingChord_meeting_det {D : FiniteIntersectionDrawing m n} + (C : DrawingPassages D) (p q : C.InnerIndex) (hpq : p ≠ q) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) + (hxq : x ∈ Set.range (C.crossingChord q)) : + det2 (C.portPoint (C.outgoingPort p)-C.portPoint (C.incomingPort p)) + (C.portPoint (C.outgoingPort q)-C.portPoint (C.incomingPort q)) ≠ 0 := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have he : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val = + segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val := by + simpa only [DrawingPassages.crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] + using hs.trans ht.symm + exact (C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property he).1 + +theorem PolygonalExterior.assembled_locallyTransverseCrossings + {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + LocallyTransverseCrossings (E.assembledAdmissible v hvinj hv hdet) := by + intro e f hef x hx hy + let A := E.assembledAdmissible v hvinj hv hdet + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (edgeInterior_not_vertex A.toContinuousDrawing e x hx) + (edgeInterior_subset_range A.toContinuousDrawing e hx) + (edgeInterior_subset_range A.toContinuousDrawing f hy) + have hpq : p ≠ q := fun h => hef (hp.symm.trans ((congrArg Sigma.fst h).trans hq)) + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hxin := (C.crossingChord_meeting_proper p q hpq x hxp hxq).1 + have hxqin := (C.crossingChord_meeting_proper q p (Ne.symm hpq) x hxq hxp).1 + refine ⟨C.portPoint (C.incomingPort p),C.portPoint (C.outgoingPort p), + C.portPoint (C.incomingPort q),C.portPoint (C.outgoingPort q), + C.crossingChord_meeting_det p q hpq x hxp hxq, + (C.crossingChord_openTrace_iff p x hxin).mp hxp, + (C.crossingChord_openTrace_iff q x hxqin).mp hxq, + C.crossingDisk p,C.crossingDisk_isOpen p,hxin,?_,?_⟩ + · intro z hz + change z ∈ edgeInterior (E.assembledDrawing v hvinj hv) e ↔ _ + simpa only [hp] using E.assembled_trace_in_crossingDisk v hvinj hv p z hz + · intro z hz + have hzq : z ∈ C.crossingDisk q := by + change squaredLength (z-(C.innerMark q).val) < C.radius^2 + rw [← hm] + exact hz + change z ∈ edgeInterior (E.assembledDrawing v hvinj hv) f ↔ _ + simpa only [hq] using E.assembled_trace_in_crossingDisk v hvinj hv q z hzq + +theorem polygonal_no_adjacent_locally_transverse (D : AdmissibleDrawing m n) : + ∃ A : AdmissibleDrawing m n, crossingCount A ≤ crossingCount D ∧ + (∀ e, HasFiniteAffineCover (A.edge e)) ∧ NoAdjacentCrossings A ∧ + LocallyStraightCrossings A ∧ LocallyTransverseCrossings A := by + obtain ⟨B,C,E,v,hvinj,hv,hdet,hnorm,hcount⟩ := exists_no_adjacent_assembled D + exact ⟨E.assembledAdmissible v hvinj hv hdet,hcount,E.assembledEdge_hasFiniteAffineCover v, + hnorm,E.assembled_locallyStraightCrossings v hvinj hv hdet, + E.assembled_locallyTransverseCrossings v hvinj hv hdet⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/Main.lean b/lean/OAI/Combinatorics/Crossing/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..778413f96c7ed0f659a9067dcedc4c1cd2806e31 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/Main.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.BalancedAxisCrossingCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem mainTarget_proof : MainTarget := by + intro m n hm hn + obtain ⟨R⟩ := nonempty_balancedAxisRealization m n + exact ⟨⟨R.drawing,R.crossingCount_eq⟩,crossing_lower_bound m n⟩ + +theorem ordinary_crossing_number_eq (m n : ℕ) (hm : 0 < m) (hn : 0 < n) : + ordinaryCrossingNumber m n=axisPairs m*axisPairs n := by + obtain ⟨D,hD⟩ := (mainTarget_proof m n hm hn).1 + apply Nat.le_antisymm + · calc + ordinaryCrossingNumber m n ≤ crossingCount D := ordinaryCrossingNumber_le_count D + _ = _ := hD + · obtain ⟨A,hA⟩ := crossingCount_attainment D + rw [← hA] + exact crossing_lower_bound m n A + +theorem ordinary_crossing_number_attained (m n : ℕ) (hm : 0 < m) (hn : 0 < n) : + ∃ D : AdmissibleDrawing m n, crossingCount D=ordinaryCrossingNumber m n ∧ + crossingCount D=axisPairs m*axisPairs n := by + obtain ⟨D,hD⟩ := (mainTarget_proof m n hm hn).1 + exact ⟨D,by rw [ordinary_crossing_number_eq m n hm hn,hD],hD⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MarkedCurveDisks.lean b/lean/OAI/Combinatorics/Crossing/MarkedCurveDisks.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8178e87bc59cfb00fe818e0ba0e1d72dc38dbb3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MarkedCurveDisks.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.RoundDiskClearance + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem closedRoundDisk_mono (z : Plane) {r s : ℝ} (hr : 0 ≤ r) (hrs : r ≤ s) : + closedRoundDisk z r ⊆ closedRoundDisk z s := by + intro x hx + change squaredLength (x-z) ≤ r^2 at hx + change squaredLength (x-z) ≤ s^2 + nlinarith + +theorem finite_curve_mark_isolation {E M : Type*} [Fintype E] [Fintype M] [DecidableEq M] + (γ : E → unitInterval → Plane) (hγ : ∀ e, Continuous (γ e)) + (mark : M → Plane) (hm : Function.Injective mark) + (O : E → M → Set unitInterval) (hO : ∀ e k, IsOpen (O e k)) + (hvisit : ∀ e k t, γ e t=mark k → t ∈ O e k) : + ∃ r : ℝ, 0 < r ∧ + (∀ k l, k ≠ l → Disjoint (closedRoundDisk (mark k) r) (closedRoundDisk (mark l) r)) ∧ + (∀ e k t, γ e t ∈ closedRoundDisk (mark k) r → t ∈ O e k) := by + let K : E × M → Set Plane := fun ek => γ ek.1 '' (O ek.1 ek.2)ᶜ + have hK (ek : E × M) : IsCompact (K ek) := + (hO ek.1 ek.2).isClosed_compl.isCompact.image (hγ ek.1) + have hnot (ek : E × M) : mark ek.2 ∉ K ek := by + rintro ⟨t,ht,he⟩ + exact ht (hvisit ek.1 ek.2 t he) + obtain ⟨ρ,hρ,hclear⟩ := exists_round_disk_clearance (fun ek : E × M => mark ek.2) K hK hnot + obtain ⟨σ,hσ,hdisjoint⟩ := exists_disjoint_round_disks mark hm + refine ⟨min ρ σ,lt_min hρ hσ,?_,?_⟩ + · intro k l hkl + exact (hdisjoint k l hkl).mono + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + · intro e k t ht + by_contra hn + have hd : γ e t ∈ closedRoundDisk (mark k) ρ := + closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_left _ _) ht + exact Set.disjoint_left.mp (hclear (e,k)) hd ⟨t,hn,rfl⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MatrixGraphs.lean b/lean/OAI/Combinatorics/Crossing/MatrixGraphs.lean new file mode 100644 index 0000000000000000000000000000000000000000..358ad3f676276600dc9eb8cb84fab3a0dd315f4f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MatrixGraphs.lean @@ -0,0 +1,48 @@ +import Mathlib.LinearAlgebra.Prod +import Mathlib.LinearAlgebra.Matrix.Rank +import Mathlib.Basic.Real.Basic +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module Submodule +variable {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] + +def graphKernelEquiv (f g : V →ₗ[ℝ] W) : + LinearMap.ker (f-g) ≃ₗ[ℝ] ↥(f.graph ⊓ g.graph) where + toFun v := ⟨(v.val, f v.val), rfl, (sub_eq_zero.mp v.property)⟩ + invFun z := ⟨z.val.1, by + change f z.val.1 - g z.val.1 = 0 + rw [← z.property.1, ← z.property.2, sub_self]⟩ + left_inv v := Subtype.ext rfl + right_inv z := Subtype.ext (Prod.ext rfl z.property.1.symm) + map_add' v w := Subtype.ext (Prod.ext rfl (f.map_add v.val w.val)) + map_smul' c v := Subtype.ext (Prod.ext rfl (f.map_smul c v.val)) + +theorem matrix_graph_finrank_add_rank (d : ℕ) (X Y : Matrix (Fin d) (Fin d) ℝ) : + finrank ℝ ↥(X.mulVecLin.graph ⊓ Y.mulVecLin.graph) + (X-Y).rank = d := by + have hdiff : X.mulVecLin - Y.mulVecLin = (X-Y).mulVecLin := + (map_sub (Matrix.mulVecBilin ℝ ℝ) X Y).symm + have he := (graphKernelEquiv X.mulVecLin Y.mulVecLin).finrank_eq + rw [hdiff] at he + have hr := (X-Y).mulVecLin.finrank_range_add_finrank_ker + change (X-Y).rank + finrank ℝ (LinearMap.ker (X-Y).mulVecLin) = finrank ℝ (Fin d → ℝ) at hr + rw [he, Module.finrank_pi, Fintype.card_fin] at hr + omega + +theorem matrix_graph_disjoint (d : ℕ) (X Y : Matrix (Fin d) (Fin d) ℝ) (h : IsUnit (X-Y)) : + Disjoint X.mulVecLin.graph Y.mulVecLin.graph := by + apply disjoint_iff.mpr + apply Submodule.finrank_eq_zero.mp + have hh := matrix_graph_finrank_add_rank d X Y + have hr := Matrix.rank_of_isUnit (X-Y) h + simp only [Fintype.card_fin] at hr + omega + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MatrixRankBounds.lean b/lean/OAI/Combinatorics/Crossing/MatrixRankBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ec3d8b55785b3840f95304a5eec839da9baede3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MatrixRankBounds.lean @@ -0,0 +1,54 @@ +import Mathlib.LinearAlgebra.Matrix.Rank +import Mathlib.Basic.Real.Basic +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module +open scoped BigOperators +variable {κ ρ : Type*} [Fintype κ] [Fintype ρ] [DecidableEq ρ] + +theorem matrix_rank_eq_zero_iff + {κ ρ : Type*} [Fintype κ] [Fintype ρ] [DecidableEq ρ] + (A : Matrix κ ρ ℝ) : A.rank = 0 ↔ A = 0 := by + constructor + · intro ha + have hf : A.mulVecLin = 0 := + LinearMap.range_eq_bot.mp (Submodule.finrank_eq_zero.mp ha) + funext i j + have hh := congrArg (fun f : (ρ → ℝ) →ₗ[ℝ] (κ → ℝ) => f (Pi.single j 1) i) hf + simpa [Matrix.mulVec_single] using hh + · rintro rfl + exact Matrix.rank_zero + +theorem matrix_rank_add_le + {κ ρ : Type*} [Fintype κ] [Fintype ρ] [DecidableEq ρ] + (A B : Matrix κ ρ ℝ) : (A+B).rank ≤ A.rank+B.rank := by + change finrank ℝ (LinearMap.range (A+B).mulVecLin) ≤ _ + rw [Matrix.mulVecLin_add] + exact (Submodule.finrank_mono (LinearMap.range_add_le A.mulVecLin B.mulVecLin)).trans + (Submodule.finrank_add_le_finrank_add_finrank _ _) + +theorem matrix_rank_smul_le + {κ ρ : Type*} [Fintype κ] [Fintype ρ] [DecidableEq ρ] + (c : ℝ) (A : Matrix κ ρ ℝ) : (c • A).rank ≤ A.rank := by + by_cases hc : c = 0 + · simp [hc, Matrix.rank_zero] + · rw [Matrix.rank_smul_of_mem_nonZeroDivisors A (mem_nonZeroDivisors_of_ne_zero hc)] + +theorem matrix_rank_sum_le {α : Type*} (S : Finset α) (A : α → Matrix κ ρ ℝ) : + (∑ a ∈ S, A a).rank ≤ ∑ a ∈ S, (A a).rank := by + classical + induction S using Finset.induction_on with + | empty => simp [Matrix.rank_zero] + | @insert a S ha ih => + simp only [Finset.sum_insert ha] + exact (matrix_rank_add_le _ _).trans (Nat.add_le_add_left ih _) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MatrixRankSum.lean b/lean/OAI/Combinatorics/Crossing/MatrixRankSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7e692efa7d0f128a795a77f788c77763339b993 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MatrixRankSum.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.Crossing.SubspaceIntersection +import OAI.Combinatorics.Crossing.MatrixGraphs +import OAI.Combinatorics.Crossing.FloorArithmetic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module Submodule +open scoped BigOperators + +def offDiagonalRankSum (m d : ℕ) + (X Y : Fin m → Matrix (Fin d) (Fin d) ℝ) : ℕ := + ∑ i, ∑ j ∈ Finset.univ.erase i, (X i-Y j).rank + +theorem matrix_rank_sum_bound (m d : ℕ) + (X Y : Fin m → Matrix (Fin d) (Fin d) ℝ) + (hdiag : ∀ i, IsUnit (X i-Y i)) : + 2 * axisPairs m * d ≤ offDiagonalRankSum m d X Y := by + let U := fun i => (X i).mulVecLin.graph + let V := fun i => (Y i).mulVecLin.graph + have hUV : ∀ i, Disjoint (U i) (V i) := fun i => matrix_graph_disjoint d (X i) (Y i) (hdiag i) + have hsub := subspace_intersection_bound m U V hUV + have hdim : finrank ℝ ((Fin d → ℝ) × (Fin d → ℝ)) = 2*d := by + simp [Module.finrank_prod, two_mul] + rw [hdim] at hsub + have htotal : (∑ i, ∑ j, finrank ℝ ↥(U i ⊓ V j)) + + (∑ i, ∑ j, (X i-Y j).rank) = m*m*d := by + dsimp only [U, V] + rw [← Finset.sum_add_distrib] + simp_rw [← Finset.sum_add_distrib, matrix_graph_finrank_add_rank] + simp [Nat.mul_assoc] + have hremove : offDiagonalRankSum m d X Y + m*d = ∑ i, ∑ j, (X i-Y j).rank := by + have hdiagrank : ∀ i, (X i-Y i).rank = d := by + intro i + simpa using Matrix.rank_of_isUnit (X i-Y i) (hdiag i) + unfold offDiagonalRankSum + have hm : m*d = ∑ i : Fin m, d := by simp + rw [hm, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i hi + simpa only [hdiagrank i] using + Finset.sum_erase_add Finset.univ (fun j => (X i-Y j).rank) (Finset.mem_univ i) + have hfloor := congrArg (fun a : ℕ => a*d) (diagonal_floor_identity m) + nlinarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MiddleEdgeIncidence.lean b/lean/OAI/Combinatorics/Crossing/MiddleEdgeIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..d47d23a5e9ac0906de2657606714ddef75600586 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MiddleEdgeIncidence.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.AssembledContinuousDrawing + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem middle_exterior_edge_eq (E : PolygonalExterior C) (e : BipartiteEdge m n) + (i : C.ArcIndex) (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (E.chain i).path) : e=i.1 := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨j,hj,hx⟩ | ⟨p,hp,hx⟩ + · have he : j=i := by + by_contra hji + exact Set.disjoint_left.mp (E.disjoint j i hji) hx hy + exact hj.symm.trans (congrArg Sigma.fst he) + · obtain ⟨s,hs⟩ := hy + obtain ⟨t,ht⟩ := hx + rcases E.exterior_chord_meeting_parameters i p s t (hs.trans ht.symm) with + ⟨hi,_,_⟩ | ⟨hi,_,_⟩ + · exact hp.symm.trans (congrArg Sigma.fst hi).symm + · exact hp.symm.trans (congrArg Sigma.fst hi).symm + +theorem middle_spoke_edge_eq (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (j : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) + (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : e=p.val.1.1 := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨i,hi,⟨s,hs⟩⟩ | ⟨q,hq,hx⟩ + · obtain ⟨t,ht⟩ := hy + have hm := E.exterior_spoke_meeting_parameters v hv i j p s t (hs.trans ht.symm) + rcases hm.2 with ⟨_,he⟩ | ⟨_,he⟩ + · exact hi.symm.trans (congrArg (fun r : C.Port => r.1.1) he) + · exact hi.symm.trans (congrArg (fun r : C.Port => r.1.1) he) + · exact False.elim (Set.disjoint_left.mp (C.crossingChord_avoids_vertex_disks q j) + hx (C.vertex_spoke_range_in_disk v hv j p hy)) + +theorem middle_middle_meeting_chords (E : PolygonalExterior C) (e f : BipartiteEdge m n) + (hef : e ≠ f) (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (E.middlePath f)) : + ∃ p q : C.InnerIndex, p.1=e ∧ q.1=f ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q) := by + have he : ∃ p : C.InnerIndex, p.1=e ∧ x ∈ Set.range (C.crossingChord p) := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨i,hi,hh⟩ | hh + · exact False.elim (hef ((E.middle_exterior_edge_eq f i x hy hh).trans hi).symm) + · exact hh + have hf : ∃ q : C.InnerIndex, q.1=f ∧ x ∈ Set.range (C.crossingChord q) := by + rcases (E.middlePath_range_iff f x).mp hy with ⟨i,hi,hh⟩ | hh + · exact False.elim (hef ((E.middle_exterior_edge_eq e i x hx hh).trans hi)) + · exact hh + obtain ⟨p,hp,hxp⟩ := he + obtain ⟨q,hq,hxq⟩ := hf + exact ⟨p,q,hp,hq,hxp,hxq⟩ + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MiddlePathInjective.lean b/lean/OAI/Combinatorics/Crossing/MiddlePathInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..c04f15583e44a7a7160c59f5c9a6b0fc135e8a6e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MiddlePathInjective.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.Crossing.OrderedExteriorPaths + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem middlePath_injective (E : PolygonalExterior C) (e : BipartiteEdge m n) : + Function.Injective (E.middlePath e) := by + have hc := C.count_pos e + apply alternatingPath_injective + · intro i hi + exact E.injective _ + · intro j hj + have h := C.crossingChord_injective (C.orderedInner e j (by omega)) + intro s t he + apply h + simpa only [orderedBridge_apply (C:=C) e j (by omega)] using he + · intro i j hi hj hij + exact E.disjoint _ _ (fun he => hij (C.orderedArc_inj e i j (by omega) (by omega) he)) + · intro i j hi hj hij + rw [orderedBridge_range e i (by omega),orderedBridge_range e j (by omega)] + apply C.crossingChords_disjoint_of_marks_ne + intro he + apply hij + apply C.orderedInner_inj e i j + exact C.innerIndex_eq_of_edge_mark _ _ rfl he + · intro i j hi hj x hx hy + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + have hbridge := orderedBridge_apply (C:=C) e j (by omega) t + have hm := E.exterior_chord_meeting_parameters (C.orderedArc e i) + (C.orderedInner e j (by omega)) s t (hs.trans (ht.symm.trans hbridge)) + rcases hm with ⟨he,rfl,rfl⟩ | ⟨he,rfl,rfl⟩ + · rw [C.orderedInner_incoming] at he + have hij := C.orderedArc_inj e i j (by omega) (by omega) he + refine Or.inl ⟨hij,?_⟩ + subst i + exact hs.symm.trans (E.orderedPath e j).target + · rw [C.orderedInner_outgoing] at he + have hij := C.orderedArc_inj e i (j+1) (by omega) (by omega) he + refine Or.inr ⟨hij,?_⟩ + subst i + exact hs.symm.trans (E.orderedPath e (j+1)).source + +theorem middlePath_range_iff (E : PolygonalExterior C) (e : BipartiteEdge m n) (x : Plane) : + x ∈ Set.range (E.middlePath e) ↔ + (∃ i : C.ArcIndex, i.1=e ∧ x ∈ Set.range (E.chain i).path) ∨ + (∃ p : C.InnerIndex, p.1=e ∧ x ∈ Set.range (C.crossingChord p)) := by + have hc := C.count_pos e + rw [middlePath,alternatingPath_range_iff] + constructor + · rintro (⟨i,hi,hx⟩ | ⟨j,hj,hx⟩) + · exact Or.inl ⟨C.orderedArc e i,rfl,hx⟩ + · exact Or.inr ⟨C.orderedInner e j (by omega),rfl, + by simpa only [orderedBridge_range (C:=C) e j (by omega)] using hx⟩ + · rintro (⟨⟨f,i⟩,he,hx⟩ | ⟨⟨f,⟨j,hj⟩⟩,he,hx⟩) + · change f=e at he + subst f + refine Or.inl ⟨i.val,by omega,?_⟩ + have heq : C.orderedArc e i.val=⟨e,i⟩ := by + unfold DrawingPassages.orderedArc + congr 1 + apply Fin.ext + change min i.val (C.count e-1)=i.val + omega + change x ∈ Set.range (E.chain (C.orderedArc e i.val)).path + rw [heq] + exact hx + · change f=e at he + subst f + refine Or.inr ⟨j.val-1,by omega,?_⟩ + rw [orderedBridge_range e (j.val-1) (by omega)] + have heq : C.orderedInner e (j.val-1) (by omega)=⟨e,⟨j,hj⟩⟩ := by + unfold DrawingPassages.orderedInner + congr 1 + apply Subtype.ext + apply Fin.ext + change j.val-1+1=j.val + omega + rw [heq] + exact hx + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MiddleSpokeMeeting.lean b/lean/OAI/Combinatorics/Crossing/MiddleSpokeMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5a129464b8f09a70d7f6f102d6305c9ab5cc5fb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MiddleSpokeMeeting.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.MiddlePathInjective +import OAI.Combinatorics.Crossing.ExteriorSpokeMeeting + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem vertex_spoke_range_in_disk (C : DrawingPassages D) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (j : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) : + Set.range (Path.segment (v j) (C.portPoint p.val)) ⊆ closedRoundDisk (D.vertex j) C.radius := by + rintro x ⟨t,rfl⟩ + by_cases ht : t=1 + · subst t + rw [Path.target] + exact (C.portsAt_on_circle (C.vertexMark j) p).le + · exact (C.vertex_spoke_interior v hv j p t + (lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht)).le + +theorem vertex_spokes_disjoint_of_vertices_ne (C : DrawingPassages D) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (j k : BipartiteVertex m n) (hjk : j ≠ k) + (p : C.PortsAt (C.vertexMark j)) (q : C.PortsAt (C.vertexMark k)) : + Disjoint (Set.range (Path.segment (v j) (C.portPoint p.val))) + (Set.range (Path.segment (v k) (C.portPoint q.val))) := + (C.disks_disjoint _ _ (C.vertexMark_injective.ne hjk)).mono + (C.vertex_spoke_range_in_disk v hv j p) (C.vertex_spoke_range_in_disk v hv k q) + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem middle_spoke_meeting (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (j : BipartiteVertex m n) (p : C.PortsAt (C.vertexMark j)) + (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : x=C.portPoint p.val := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨i,hi,⟨s,hs⟩⟩ | ⟨q,hq,hx⟩ + · obtain ⟨t,ht⟩ := hy + have he := E.exterior_spoke_meeting_parameters v hv i j p s t (hs.trans ht.symm) + rw [he.1,Path.target] at ht + exact ht.symm + · exact False.elim (Set.disjoint_left.mp (C.crossingChord_avoids_vertex_disks q j) + hx (C.vertex_spoke_range_in_disk v hv j p hy)) + +def anchoredMiddle (E : PolygonalExterior C) (e : BipartiteEdge m n) : + Path (C.arcStart (C.firstArc e)) (C.arcEnd (C.lastArc e)) := + (E.middlePath e).cast (congrArg C.arcStart (C.orderedArc_first e).symm) + (congrArg C.arcEnd (C.orderedArc_last e).symm) + +theorem anchoredMiddle_range (E : PolygonalExterior C) (e : BipartiteEdge m n) : + Set.range (E.anchoredMiddle e)=Set.range (E.middlePath e) := rfl + +theorem anchoredMiddle_injective (E : PolygonalExterior C) (e : BipartiteEdge m n) : + Function.Injective (E.anchoredMiddle e) := E.middlePath_injective e + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MinimumChainGeometry.lean b/lean/OAI/Combinatorics/Crossing/MinimumChainGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e5c71b36faef44ad8cab8310487538d1e45ddff --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MinimumChainGeometry.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.Crossing.PolygonalChainShortcuts +import OAI.Combinatorics.Crossing.CollinearSegmentUnion + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem adjacent_segments_meet_only_at_bend (a b c : Plane) + (h : det2 (b-a) (c-b) ≠ 0) {x : Plane} + (hx : x ∈ segment ℝ a b) (hy : x ∈ segment ℝ b c) : x=b := by + rw [← Path.range_segment] at hx hy + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + have hs' : segmentPoint a b s.val=x := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs + have ht' : segmentPoint b c t.val=x := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + have he := segment_intersection_parameters_unique a b b c h s.val t.val 1 0 + (hs'.trans ht'.symm) (by simp) + rw [he.1,segmentPoint_one] at hs' + exact hs'.symm + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +theorem minimum_piece_ne_zero (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) : P.vertices (i+1)-P.vertices i ≠ 0 := by + exact sub_ne_zero.mpr (Ne.symm (P.minimum_vertices_ne hmin i (i+1) (by omega) (by omega))) + +theorem minimum_bend_det_ne_zero (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) : + det2 (P.vertices (i+1)-P.vertices i) (P.vertices (i+2)-P.vertices (i+1)) ≠ 0 := by + intro he + apply P.minimum_two_step_not_subset hmin i hi + exact (collinear_segment_subset_union _ _ _ (P.minimum_vertices_ne hmin i (i+2) (by omega) hi) he).trans + (Set.union_subset (P.inside i (by omega)) (P.inside (i+1) (by omega))) + +theorem minimum_adjacent_intersection (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) {x : Plane} + (hx : x ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) + (hy : x ∈ segment ℝ (P.vertices (i+1)) (P.vertices (i+2))) : x=P.vertices (i+1) := by + exact adjacent_segments_meet_only_at_bend _ _ _ (P.minimum_bend_det_ne_zero hmin i hi) hx hy + +end PolygonalChain +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MinimumChainVertexPieces.lean b/lean/OAI/Combinatorics/Crossing/MinimumChainVertexPieces.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdc42c9c7b09dd7068f72711781b7794fbe45aa7 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MinimumChainVertexPieces.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.ReducedPolygonalPresentation +import OAI.Combinatorics.Crossing.CutVertexAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem PolygonalChain.minimum_vertex_piece_index {O : Set Plane} {a b : Plane} + (P : PolygonalChain O a b) (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i k : ℕ) (hi : i < P.pieces) (hk : k ≤ P.pieces) + (hx : P.vertices k ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) : k=i ∨ k=i+1 := by + have hlow : i ≤ k := by + by_contra h + have hki : k < i := by omega + have hseg : segment ℝ (P.vertices k) (P.vertices (i+1)) ⊆ O := + ((convex_segment (𝕜 := ℝ) _ _).segment_subset hx (right_mem_segment ℝ _ _)).trans (P.inside i hi) + have hh := P.minimum_shortcut_bound hmin k (i+1) (by omega) (by omega) + (PolygonalChain.single O _ _ (P.vertex_mem k hk) hseg) + change i+1-k ≤ 1 at hh + omega + have hhigh : k ≤ i+1 := by + by_contra h + have hik : i+1 < k := by omega + have hseg : segment ℝ (P.vertices i) (P.vertices k) ⊆ O := + ((convex_segment (𝕜 := ℝ) _ _).segment_subset (left_mem_segment ℝ _ _) hx).trans (P.inside i hi) + have hh := P.minimum_shortcut_bound hmin i k (by omega) hk + (PolygonalChain.single O _ _ (P.vertex_mem i (by omega)) hseg) + change k-i ≤ 1 at hh + omega + omega + +theorem drawing_chain_piece_vertex {m n : ℕ} (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) (j : BipartiteVertex m n) + (hx : D.vertex j ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) : + (j=.inl e.1 ∧ i=0) ∨ (j=.inr e.2 ∧ i+1=P.pieces) := by + obtain ⟨t,ht⟩ := P.inside i hi hx + rcases drawing_edge_vertex_parameter D e t j ht with ⟨_,he⟩ | ⟨_,he⟩ + · have hx0 : P.vertices 0 ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := by + simpa only [P.first,he] using hx + have hh := P.minimum_vertex_piece_index hmin i 0 hi (by omega) hx0 + exact Or.inl ⟨he,by omega⟩ + · have hxN : P.vertices P.pieces ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := by + simpa only [P.last,he] using hx + have hh := P.minimum_vertex_piece_index hmin i P.pieces hi (by omega) hxN + exact Or.inr ⟨he,by omega⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MovingDiskClearance.lean b/lean/OAI/Combinatorics/Crossing/MovingDiskClearance.lean new file mode 100644 index 0000000000000000000000000000000000000000..07d56196ca96a81f7325eec27829c8b2cd0e959e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MovingDiskClearance.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.RoundDiskClearance +import OAI.Combinatorics.Crossing.MovingSegmentStability +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem eventually_moving_segment_outside_disk (a b : ℝ → Plane) (ha : Continuous a) + (hb : Continuous b) (z : Plane) (r : ℝ) + (hout : segment ℝ (a 0) (b 0) ⊆ {x | r^2 < squaredLength (x-z)}) : + ∀ᶠ ε : ℝ in 𝓝 0, segment ℝ (a ε) (b ε) ⊆ {x | r^2 < squaredLength (x-z)} := by + have hevent : ∀ᶠ ε : ℝ in 𝓝 0, ∀ t ∈ Set.Icc (0 : ℝ) 1, + r^2 < squaredLength (segmentPoint (a ε) (b ε) t-z) := by + apply isCompact_Icc.eventually_forall_of_forall_eventually + intro t ht + have hc : Continuous (fun p : ℝ × ℝ => squaredLength (segmentPoint (a p.1) (b p.1) p.2-z)) := by + dsimp [squaredLength,segmentPoint] + fun_prop + apply continuousAt_const.eventually_lt hc.continuousAt + apply hout + rw [← Path.range_segment] + refine ⟨⟨t,ht⟩,?_⟩ + simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] + filter_upwards [hevent] with ε hε + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,rfl⟩ := hx + simpa only [Set.mem_ofPred_eq,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hε t.val t.property + +theorem exists_shifted_segment_disk_radius (a b qa qb z : Plane) (r : ℝ) + (hdis : Disjoint (closedRoundDisk z r) (segment ℝ a b)) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, |ε|<δ → + segment ℝ (a+ε • qa) (b+ε • qb) ⊆ {x | r^2 < squaredLength (x-z)} := by + have hout : segment ℝ a b ⊆ {x | r^2 < squaredLength (x-z)} := by + intro x hx + change r^2 < squaredLength (x-z) + by_contra hh + have hmem : x ∈ closedRoundDisk z r := by + change squaredLength (x-z) ≤ r^2 + exact not_lt.mp hh + exact Set.disjoint_left.mp hdis hmem hx + have he := eventually_moving_segment_outside_disk (fun ε : ℝ => a+ε • qa) + (fun ε : ℝ => b+ε • qb) (by fun_prop) (by fun_prop) z r (by simpa using hout) + obtain ⟨δ,hδ,hh⟩ := Metric.eventually_nhds_iff.mp he + exact ⟨δ,hδ,fun ε hε => hh (by simpa [Real.dist_eq] using hε)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/MovingSegmentStability.lean b/lean/OAI/Combinatorics/Crossing/MovingSegmentStability.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2efc89accfdd3ecb6d47d23d1d11035e13a894c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/MovingSegmentStability.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.ShiftedSegmentStability + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem moving_endpoints_tendsto (C D : ℝ → Plane) (c d : Plane) + (hC : ContinuousAt C 0) (hD : ContinuousAt D 0) (hC0 : C 0=c) (hD0 : D 0=d) : + Filter.Tendsto (fun t : ℝ => (C t,D t)) (𝓝 0) (𝓝 (c,d)) := by + simpa [ContinuousAt,hC0,hD0] using hC.prodMk hD + +theorem eventually_moving_segment_pair (a b c d : Plane) (C D : ℝ → Plane) + (hC : ContinuousAt C 0) (hD : ContinuousAt D 0) (hC0 : C 0=c) (hD0 : D 0=d) + (h : SegmentPairTransverse a b c d) : + ∀ᶠ t : ℝ in 𝓝 0, + SegmentPairTransverse a b (C t) (D t) ∧ + segmentCrossingSign a b (C t) (D t)=segmentCrossingSign a b c d := by + have hs := segmentPairTransverse_swap a b c d h + have he := (moving_endpoints_tendsto C D c d hC hD hC0 hD0).eventually + ((eventually_segmentPairTransverse c d a b hs).and (eventually_segmentCrossingSign c d a b hs)) + filter_upwards [he] with t ht + refine ⟨segmentPairTransverse_swap _ _ _ _ ht.1,?_⟩ + have hsign := ht.2 + rw [segmentCrossingSign_swap a b _ _,segmentCrossingSign_swap a b c d] at hsign + exact neg_injective hsign + +theorem eventually_moving_disjoint_segments (a b c d : Plane) (C D : ℝ → Plane) + (hC : ContinuousAt C 0) (hD : ContinuousAt D 0) (hC0 : C 0=c) (hD0 : D 0=d) + (h : ¬ ClosedSegmentsMeet a b c d) : + ∀ᶠ t : ℝ in 𝓝 0, ¬ ClosedSegmentsMeet a b (C t) (D t) := by + have hn : (c,d) ∈ {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 a b}ᶜ := by + intro hx + exact h ((closedSegmentsMeet_symm c d a b).mp hx) + have he := (moving_endpoints_tendsto C D c d hC hD hC0 hD0).eventually + ((isClosed_closedSegmentsMeet a b).isOpen_compl.mem_nhds hn) + filter_upwards [he] with t ht + intro hx + exact ht ((closedSegmentsMeet_symm a b _ _).mp hx) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NoAdjacentLocalNormalization.lean b/lean/OAI/Combinatorics/Crossing/NoAdjacentLocalNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..0779907b1fa931b08518cb742614d6352e9c6f0a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NoAdjacentLocalNormalization.lean @@ -0,0 +1,20 @@ +import OAI.Combinatorics.Crossing.NoAdjacentNormalization +import OAI.Combinatorics.Crossing.LocallyStraightNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem polygonal_no_adjacent_locally_straight {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ A : AdmissibleDrawing m n, crossingCount A ≤ crossingCount D ∧ + (∀ e, HasFiniteAffineCover (A.edge e)) ∧ NoAdjacentCrossings A ∧ LocallyStraightCrossings A := by + obtain ⟨B,C,E,v,hvinj,hv,hdet,hnorm,hcount⟩ := exists_no_adjacent_assembled D + exact ⟨E.assembledAdmissible v hvinj hv hdet,hcount,E.assembledEdge_hasFiniteAffineCover v, + hnorm,E.assembled_locallyStraightCrossings v hvinj hv hdet⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NoAdjacentNormalization.lean b/lean/OAI/Combinatorics/Crossing/NoAdjacentNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..2908ebd1d723ab412681fa363f75e3e7ca62c357 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NoAdjacentNormalization.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.AdmissibleAdjacentSurgery +import OAI.Combinatorics.Crossing.RowCrossingCount + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_no_adjacent_assembled {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ (B : AdmissibleDrawing m n) (C : DrawingPassages B.toFiniteIntersectionDrawing) + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-B.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0), + NoAdjacentCrossings (E.assembledAdmissible v hvinj hv hdet) ∧ + crossingCount (E.assembledAdmissible v hvinj hv hdet) ≤ crossingCount D := by + classical + induction hc : crossingCount D using Nat.strong_induction_on generalizing D with + | h k ih => + obtain ⟨C⟩ := nonempty_drawingPassages D.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + let A := E.assembledAdmissible v hvinj hv hdet + have hcount : crossingCount A ≤ crossingCount D := E.assembled_crossingCount_le v hvinj hv hdet + by_cases hnorm : NoAdjacentCrossings A + · exact ⟨D,C,E,v,hvinj,hv,hdet,hnorm,hcount.trans_eq hc⟩ + have hex : ∃ e f : BipartiteEdge m n, e ≠ f ∧ (e.1=f.1 ∨ e.2=f.2) ∧ + (edgeInterior A.toContinuousDrawing e ∩ edgeInterior A.toContinuousDrawing f).Nonempty := by + by_contra hh + apply hnorm + intro e f hef hadj + apply Set.eq_empty_iff_forall_notMem.mpr + intro x hx + exact hh ⟨e,f,hef,hadj,x,hx⟩ + obtain ⟨e,f,hef,hadj,x,hxe,hxf⟩ := hex + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (edgeInterior_not_vertex A.toContinuousDrawing e x hxe) + (edgeInterior_subset_range A.toContinuousDrawing e hxe) + (edgeInterior_subset_range A.toContinuousDrawing f hxf) + have hpq : p ≠ q := fun h => hef (hp.symm.trans ((congrArg Sigma.fst h).trans hq)) + have hadj' : p.1.1=q.1.1 ∨ p.1.2=q.1.2 := by simpa only [hp,hq] using hadj + obtain ⟨R,hRpoly,hRcount⟩ := E.exists_admissible_adjacent_surgery v hvinj hv hdet p q hpq hadj' x hxp hxq + have hRk : crossingCount R < k := (hRcount.trans_le hcount).trans_eq hc + obtain ⟨B,C',E',v',hvinj',hv',hdet',hnorm',hcount'⟩ := ih (crossingCount R) hRk R rfl + exact ⟨B,C',E',v',hvinj',hv',hdet',hnorm',(hcount'.trans (hRcount.le.trans hcount)).trans_eq hc⟩ + +theorem polygonal_normalization_no_adjacent {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ A : AdmissibleDrawing m n, (∀ e, HasFiniteAffineCover (A.edge e)) ∧ + NoAdjacentCrossings A ∧ crossingCount A ≤ crossingCount D := by + obtain ⟨B,C,E,v,hvinj,hv,hdet,hnorm,hcount⟩ := exists_no_adjacent_assembled D + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembledEdge_hasFiniteAffineCover v,hnorm,hcount⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NodeMoments.lean b/lean/OAI/Combinatorics/Crossing/NodeMoments.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d374218845984a1cd8a6ef96588d8de287c96ba --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NodeMoments.lean @@ -0,0 +1,58 @@ +import Mathlib.LinearAlgebra.Lagrange +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.NormNum +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Polynomial +open scoped BigOperators +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +def nodePolynomial (node : ι → ℝ) : ℝ[X] := ∏ i, (X-C (node i)) + +def derivativeAtNode (node : ι → ℝ) (i : ι) : ℝ := + (nodePolynomial node).derivative.eval (node i) + +theorem derivativeAtNode_eq_prod (node : ι → ℝ) (i : ι) : + derivativeAtNode node i = ∏ j ∈ Finset.univ.erase i, (node i-node j) := by + unfold derivativeAtNode nodePolynomial + change (Lagrange.nodal Finset.univ node).derivative.eval (node i) = _ + rw [Lagrange.eval_nodal_derivative_eval_node_eq (Finset.mem_univ i), Lagrange.eval_nodal] + +theorem derivativeAtNode_ne_zero (node : ι → ℝ) (hn : Function.Injective node) (i : ι) : + derivativeAtNode node i ≠ 0 := by + rw [derivativeAtNode_eq_prod] + apply Finset.prod_ne_zero_iff.mpr + intro j hj + apply sub_ne_zero.mpr + intro hij + exact (Finset.mem_erase.mp hj).1 (hn hij).symm + +theorem node_polynomial_moment (node : ι → ℝ) (hn : Function.Injective node) + (P : ℝ[X]) (hP : P.degree < (Fintype.card ι - 1 : ℕ)) : + (∑ i, P.eval (node i) / derivativeAtNode node i) = 0 := by + by_cases hcard : Fintype.card ι = 0 + · have : IsEmpty ι := Fintype.card_eq_zero_iff.mp hcard + simp + have hp' : P.degree < (Finset.univ : Finset ι).card := + hP.trans_le (by exact_mod_cast Nat.sub_le (Fintype.card ι) 1) + have he := Lagrange.coeff_eq_sum (s := Finset.univ) (v := node) hn.injOn hp' + rw [Finset.card_univ, coeff_eq_zero_of_degree_lt hP] at he + simpa only [Finset.card_univ, derivativeAtNode_eq_prod] using he.symm + +theorem node_power_moment (node : ι → ℝ) (hn : Function.Injective node) + (k : ℕ) (hk : k+1 < Fintype.card ι) : + (∑ i, node i ^ k / derivativeAtNode node i) = 0 := by + have hdeg : (X^k : ℝ[X]).degree < (Fintype.card ι - 1 : ℕ) := by + rw [degree_X_pow] + exact_mod_cast (show k < Fintype.card ι-1 by omega) + simpa only [eval_pow, eval_X] using node_polynomial_moment node hn (X^k) hdeg + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NodeRankLoss.lean b/lean/OAI/Combinatorics/Crossing/NodeRankLoss.lean new file mode 100644 index 0000000000000000000000000000000000000000..f63095e647bfdc0dbafdebce135eb65a6b87ee26 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NodeRankLoss.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.Crossing.EvaluationAmbient +import OAI.Combinatorics.Crossing.SubspaceProjection +import OAI.Combinatorics.Crossing.PolynomialLinearMatrix + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module Submodule +variable {W ι : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] +variable (U : ι → Submodule ℝ W) (node : ι → ℝ) + +theorem off_node_projected_rank (V : Submodule ℝ W) (h : ℕ) (t : ℝ) + (ht : ∀ i, node i ≠ t) : + finrank ℝ ((ambientEvalRange U node ⊤ (h+1) t).map V.mkQ) + rankIncrement U node V h ≤ + rankIncrement U node ⊤ h := by + have hh := finrank_map_add_le V.mkQ + (ambientEvalRange U node ⊤ (h+1) t) (ambientEvalRange U node V (h+1) t) + (ambientEvalRange_mono_coeff U node le_top (h+1) t) + (by rw [Submodule.ker_mkQ]; exact ambientEvalRange_le_coeff U node V (h+1) t) + rwa [finrank_ambientEvalRange_off_node U node V h t ht, + finrank_ambientEvalRange_off_node U node ⊤ h t ht] at hh + +theorem node_rank_loss [Fintype ι] (V : Submodule ℝ W) (j : ι) + (hUV : Disjoint (U j) V) (h : ℕ) (tstar : ℝ) (htstar : ∀ i, node i ≠ tstar) : + finrank ℝ (ambientEvalRange U node ⊤ (h+1) (node j)) + rankIncrement U node V h ≤ + rankIncrement U node ⊤ h := by + classical + let bP := finBasis ℝ (constrained U node ⊤ (h+1)) + let bQ := finBasis ℝ (W ⧸ V) + let f : (⊤ : Submodule ℝ W) →ₗ[ℝ] (W ⧸ V) := V.mkQ.comp (⊤ : Submodule ℝ W).subtype + let F : constrained U node ⊤ (h+1) →ₗ[ℝ] PolynomialModule ℝ (W ⧸ V) := + (PolynomialModule.map ℝ f).comp (constrained U node ⊤ (h+1)).subtype + let M := polynomialLinearMatrix bP bQ F + have heval (t : ℝ) : (eval t).comp F = V.mkQ.comp (ambientEval U node ⊤ (h+1) t) := by + apply LinearMap.ext + intro p + change eval t (PolynomialModule.map ℝ f p.val) = f (eval t p.val) + simpa using PolynomialModule.eval_map ℝ f p.val t + have hrank (t : ℝ) : (M.map (Polynomial.eval t)).rank = + finrank ℝ ((ambientEvalRange U node ⊤ (h+1) t).map V.mkQ) := by + rw [polynomialLinearMatrix_rank, heval, LinearMap.range_comp] + rfl + let nodes := Finset.univ.image node + have hoff (t : ℝ) (ht : t ∉ nodes) : (M.map (Polynomial.eval t)).rank ≤ + rankIncrement U node ⊤ h - rankIncrement U node V h := by + rw [hrank] + apply Nat.le_sub_of_add_le + apply off_node_projected_rank U node V h t + intro i hi + exact ht (Finset.mem_image.mpr ⟨i, Finset.mem_univ i, hi⟩) + have hnode := polynomial_rank_specialization M nodes + (rankIncrement U node ⊤ h - rankIncrement U node V h) hoff (node j) + rw [hrank] at hnode + have hdisj : Disjoint (ambientEvalRange U node ⊤ (h+1) (node j)) (LinearMap.ker V.mkQ) := by + rw [Submodule.ker_mkQ] + exact hUV.mono_left (ambientEvalRange_at_node_le U node ⊤ (h+1) j) + rw [finrank_map_of_disjoint V.mkQ _ hdisj] at hnode + have hmono := Submodule.finrank_mono + (ambientEvalRange_mono_coeff U node (show V ≤ ⊤ from le_top) (h+1) tstar) + rw [finrank_ambientEvalRange_off_node U node V h tstar htstar, + finrank_ambientEvalRange_off_node U node ⊤ h tstar htstar] at hmono + omega + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NormalOffsetExterior.lean b/lean/OAI/Combinatorics/Crossing/NormalOffsetExterior.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2fd9fa148ccb2de0bc16feb6ae8031447d1b43c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NormalOffsetExterior.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.TangentTrackIdentity +import OAI.Combinatorics.Crossing.RadialExterior + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem dot2_rotateQuarter_self (d : Plane) : dot2 (rotateQuarter d) d=0 := by + dsimp [dot2,rotateQuarter] + ring + +theorem squaredLength_normal_offset (w d : Plane) (hd : d ≠ 0) (hpar : det2 d w=0) (ε : ℝ) : + squaredLength (w+ε • normalShift d)=squaredLength w+ε^2/squaredLength d := by + have hL := ne_of_gt (squaredLength_pos d hd) + have hcross : dot2 w (rotateQuarter d)=0 := by + dsimp [dot2,rotateQuarter,det2] at * + linarith + have hrot : squaredLength (rotateQuarter d)=squaredLength d := by + dsimp [squaredLength,rotateQuarter] + ring + unfold normalShift + rw [smul_smul,squaredLength_add_smul,hrot,hcross] + field_simp + ring + +theorem normal_offset_radial_exterior (o p d : Plane) (r ε ℓ : ℝ) + (hd : d ≠ 0) (hp : squaredLength (p-o)=r^2) + (hpar : det2 d (p-o)=0) (hout : 0 ≤ dot2 (p-o) d) (hε : ε ≠ 0) (hℓ : 0 ≤ ℓ) : + segment ℝ (p+ε • normalShift d) (p+ε • normalShift d+ℓ • d) ⊆ + {x | r^2 < squaredLength (x-o)} := by + apply exterior_segment_of_dot + · have he : p+ε • normalShift d-o=(p-o)+ε • normalShift d := by abel + rw [he,squaredLength_normal_offset _ d hd hpar,hp] + exact lt_add_of_pos_right _ (div_pos (sq_pos_of_ne_zero hε) (squaredLength_pos d hd)) + · have he : dot2 (p+ε • normalShift d-o) ((p+ε • normalShift d+ℓ • d)-(p+ε • normalShift d))= + ℓ*dot2 (p-o) d := by + dsimp [dot2,normalShift,rotateQuarter] + ring + rw [he] + exact mul_nonneg hℓ hout + +theorem normal_offset_segment_exterior (o p d q : Plane) (r ε ℓ : ℝ) + (hd : d ≠ 0) (hp : squaredLength (p-o)=r^2) + (hpar : det2 d (p-o)=0) (hout : 0 ≤ ℓ*dot2 (p-o) d) (hε : ε ≠ 0) + (hq : q-(p+ε • normalShift d)=ℓ • d) : + segment ℝ (p+ε • normalShift d) q ⊆ {x | r^2 < squaredLength (x-o)} := by + apply exterior_segment_of_dot + · have he : p+ε • normalShift d-o=(p-o)+ε • normalShift d := by abel + rw [he,squaredLength_normal_offset _ d hd hpar,hp] + exact lt_add_of_pos_right _ (div_pos (sq_pos_of_ne_zero hε) (squaredLength_pos d hd)) + · rw [hq] + have he : dot2 (p+ε • normalShift d-o) (ℓ • d)=ℓ*dot2 (p-o) d := by + dsimp [dot2,normalShift,rotateQuarter] + ring + rwa [he] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/NormalizedPolygonalDrawing.lean b/lean/OAI/Combinatorics/Crossing/NormalizedPolygonalDrawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0ad464bea11843d13a4872c8bf3b8d58e0c4397 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/NormalizedPolygonalDrawing.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.Crossing.PolygonalNormalization +import OAI.Combinatorics.Crossing.OrderedAffineSubdivision + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem polygonal_normalization_subdivided {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ D' : AdmissibleDrawing m n, crossingCount D' ≤ crossingCount D ∧ + ∀ e, Nonempty (PolygonalParametrization (D'.edge e)) := by + obtain ⟨D',hpoly,hcount⟩ := polygonal_normalization D + exact ⟨D',hcount,fun e => (hpoly e).nonempty_polygonalParametrization⟩ + +theorem PolygonalParametrization.pieces_pos {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : 0 < P.pieces := by + by_contra hn + have hp : P.pieces=0 := by omega + have hi : (0 : Fin (P.pieces+1))=Fin.last P.pieces := by + apply Fin.ext + exact hp.symm + have he := P.first.symm.trans ((congrArg P.knot hi).trans P.last) + exact zero_ne_one he + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OddCrossingLowerBound.lean b/lean/OAI/Combinatorics/Crossing/OddCrossingLowerBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..18aa8ef77cf62ea4c011a28f3fe033a91d1cffc2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OddCrossingLowerBound.lean @@ -0,0 +1,29 @@ +import OAI.Combinatorics.Crossing.OddNormalizedLowerBound +import OAI.Combinatorics.Crossing.ExpectedTrackGeometry + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem odd_crossing_lower_bound (m s : ℕ) (D : AdmissibleDrawing m (2*s+1)) : + axisPairs m*axisPairs (2*s+1) ≤ crossingCount D := by + by_cases hm : 0 < m + · by_cases hs : 0 < s + · obtain ⟨A,hcount,hpoly,hnorm,hstraight,htrans⟩ := polygonal_no_adjacent_locally_transverse D + obtain ⟨V⟩ := nonempty_vertexTruncation A.toContinuousDrawing hpoly + obtain ⟨C⟩ := nonempty_truncatedSpokeCoordinates V hnorm + rw [axisPairs_odd] + exact (C.odd_normalized_crossing_lower_bound hnorm hstraight htrans s hs rfl hm).trans hcount + · have he : s=0 := Nat.eq_zero_of_not_pos hs + subst s + simp [axisPairs] + · have he : m=0 := Nat.eq_zero_of_not_pos hm + subst m + simp [axisPairs] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OddNormalizedLowerBound.lean b/lean/OAI/Combinatorics/Crossing/OddNormalizedLowerBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a1c8169c4b9d8a7203cd78f7ea00e340aa1cc88 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OddNormalizedLowerBound.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.Crossing.VertexOrderDetector +import OAI.Combinatorics.Crossing.IndexedMatrixRankSum + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +open scoped BigOperators +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem odd_normalized_crossing_lower_bound (C : TruncatedSpokeCoordinates V) (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (s : ℕ) (hs : 0 < s) (hcard : n=2*s+1) (hm : 0 < m) : + axisPairs m*(s*s) ≤ crossingCount D := by + let node : Fin n → ℝ := fun p => p.val + have hnode : Function.Injective node := by + intro p q hpq + apply Fin.ext + change (p.val : ℝ)=(q.val : ℝ) at hpq + exact_mod_cast hpq + let i₀ : Fin m := ⟨0,hm⟩ + let H := fun i k : Fin m => rankDetector s node (edgeBlock C.cycleIntersectionMatrix i k) + let X := fun i : Fin m => H i i₀ + let Y := fun k : Fin m => H i₀ i₀-H i₀ k + have hH (i k : Fin m) : H i k=X i-Y k := by + have hh := C.additive_detector_relation hnorm hstraight htrans s node hnode hcard i k i₀ + change H i k-H i i₀-H i₀ k+H i₀ i₀=0 at hh + dsimp only [X,Y] + calc + H i k=(H i k-H i i₀-H i₀ k+H i₀ i₀)+(H i i₀-(H i₀ i₀-H i₀ k)) := by abel + _ = _ := by rw [hh,zero_add] + have hdiag : ∀ i, IsUnit (X i-Y i) := by + intro i + rw [← hH] + exact C.diagonal_detector_isUnit hnorm s hs node hnode hcard i + have hlower := matrix_rank_sum_bound_product m s X Y hdiag + have hsum : (∑ i : Fin m, ∑ k ∈ Finset.univ.erase i, (X i-Y k).rank)= + ∑ i : Fin m, ∑ k ∈ Finset.univ.erase i, (rankDetector s node (V.intersectionBlock i k)).rank := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro k hk + rw [← hH] + exact congrArg Matrix.rank (C.offDiagonal_detector s node i k (Ne.symm (Finset.mem_erase.mp hk).1)) + rw [hsum] at hlower + have hupper := V.ordered_detector_rank_le_twice_crossings hnorm s node + have hh := hlower.trans hupper + nlinarith + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OffsetBendSegments.lean b/lean/OAI/Combinatorics/Crossing/OffsetBendSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea0f5732b937b82a72879c5bc2363c192ba5a81d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OffsetBendSegments.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.OffsetSegments +import OAI.Combinatorics.Crossing.SegmentAffineForms +import Mathlib.Tactic.Abel + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem offset_bend_no_reverse_contact (u v q : Plane) (ε : ℝ) (hε : ε ≠ 0) + (hu : det2 u q=ε) (hv : det2 v q=ε) + (α β : ℝ) (hα : 0 ≤ α) (hβ : 0 ≤ β) : q-α • u-β • v ≠ 0 := by + intro he + have h₁ := congrArg (det2 u) he + have h₂ := congrArg (det2 v) he + simp only [det2_sub_right,det2_smul_right,det2_self,det2_zero_right,hu,hv, + mul_zero,sub_zero] at h₁ h₂ + rw [det2_swap u v] at h₂ + have hprod : (α+β)*det2 u v=0 := by nlinarith + rcases mul_eq_zero.mp hprod with hz | hz + · have hα0 : α=0 := by linarith + rw [hα0,zero_mul,sub_zero] at h₂ + exact hε h₂ + · rw [hz,mul_zero,sub_zero] at h₁ + exact hε h₁ + +theorem incoming_shifted_outgoing_disjoint (a b c qb qc : Plane) (ε r : ℝ) + (hε : ε ≠ 0) (hr : 0 < r) + (hu : det2 (b-a) qb=1) (hv : det2 (c-b) qb=1) + (hdir : (c+ε • qc)-(b+ε • qb)=r • (c-b)) + (s t : ℝ) (hs : s ∈ Set.Icc (0 : ℝ) 1) (ht : t ∈ Set.Icc (0 : ℝ) 1) : + segmentPoint a b s ≠ segmentPoint (b+ε • qb) (c+ε • qc) t := by + intro he + rw [segmentPoint_end_form a b s,segmentPoint_start_form,hdir,smul_smul] at he + have hno := offset_bend_no_contact (b-a) (c-b) (ε • qb) ε hε + (by rw [det2_smul_right,hu,mul_one]) (by rw [det2_smul_right,hv,mul_one]) + (t*r) (1-s) (mul_nonneg ht.1 hr.le) (by linarith [hs.2]) + apply hno + calc + ε • qb+(t*r) • (c-b)+(1-s) • (b-a) = + ((b+ε • qb)+(t*r) • (c-b))-(b-(1-s) • (b-a)) := by abel + _ = 0 := sub_eq_zero.mpr he.symm + +theorem outgoing_shifted_incoming_disjoint (a b c qa qb : Plane) (ε r : ℝ) + (hε : ε ≠ 0) (hr : 0 < r) + (hu : det2 (b-a) qb=1) (hv : det2 (c-b) qb=1) + (hdir : (b+ε • qb)-(a+ε • qa)=r • (b-a)) + (s t : ℝ) (hs : s ∈ Set.Icc (0 : ℝ) 1) (ht : t ∈ Set.Icc (0 : ℝ) 1) : + segmentPoint b c s ≠ segmentPoint (a+ε • qa) (b+ε • qb) t := by + intro he + rw [segmentPoint_start_form b c s,segmentPoint_end_form,hdir,smul_smul] at he + have hno := offset_bend_no_reverse_contact (b-a) (c-b) (ε • qb) ε hε + (by rw [det2_smul_right,hu,mul_one]) (by rw [det2_smul_right,hv,mul_one]) + ((1-t)*r) s (mul_nonneg (by linarith [ht.2]) hr.le) hs.1 + apply hno + calc + ε • qb-((1-t)*r) • (b-a)-s • (c-b) = + ((b+ε • qb)-((1-t)*r) • (b-a))-(b+s • (c-b)) := by abel + _ = 0 := sub_eq_zero.mpr he.symm + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OffsetSegments.lean b/lean/OAI/Combinatorics/Crossing/OffsetSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..3357e4b1e5a2f4abdbb4cdd65b5df1be2ac60fe6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OffsetSegments.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.Crossing.OffsetVectors +import OAI.Combinatorics.Crossing.SegmentSides + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem offset_segment_parameterization (a b qa qb : Plane) (ε t : ℝ) : + segmentPoint (a+ε • qa) (b+ε • qb) t = + segmentPoint a b t+ε • segmentPoint qa qb t := by + apply Prod.ext <;> dsimp [segmentPoint] <;> ring + +theorem offset_segment_side (a b qa qb : Plane) (ε t : ℝ) + (ha : det2 (b-a) qa=1) (hb : det2 (b-a) qb=1) : + orient2 a b (segmentPoint (a+ε • qa) (b+ε • qb) t) = ε := by + dsimp [orient2,det2,segmentPoint] at * + linear_combination ε*(1-t)*ha+ε*t*hb + +theorem offset_segment_no_contact (a b qa qb : Plane) (ε : ℝ) (hε : ε ≠ 0) + (ha : det2 (b-a) qa=1) (hb : det2 (b-a) qb=1) (s t : ℝ) : + segmentPoint a b s ≠ segmentPoint (a+ε • qa) (b+ε • qb) t := by + intro he + have hh := congrArg (orient2 a b) he + rw [orient2_self_segment,offset_segment_side a b qa qb ε t ha hb] at hh + exact hε hh.symm + +theorem offset_bend_no_contact (u v q : Plane) (ε : ℝ) (hε : ε ≠ 0) + (hu : det2 u q=ε) (hv : det2 v q=ε) + (α β : ℝ) (hα : 0 ≤ α) (hβ : 0 ≤ β) : + q+α • v+β • u ≠ 0 := by + intro he + have h₁ := congrArg (det2 u) he + have h₂ := congrArg (det2 v) he + simp only [det2_add_right,det2_smul_right,det2_self,det2_zero_right,hu,hv, + mul_zero,add_zero] at h₁ h₂ + rw [det2_swap u v] at h₂ + have hprod : (α+β)*det2 u v=0 := by nlinarith + rcases mul_eq_zero.mp hprod with hz | hz + · have hα0 : α=0 := by linarith + rw [hα0,zero_mul,add_zero] at h₁ + exact hε h₁ + · rw [hz,mul_zero,add_zero] at h₁ + exact hε h₁ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OffsetTrack.lean b/lean/OAI/Combinatorics/Crossing/OffsetTrack.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a1f461453a04f4448d67079680b9b2f3a32384e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OffsetTrack.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.Crossing.OffsetSegments +import OAI.Combinatorics.Crossing.ParallelDirection +import OAI.Combinatorics.Crossing.FiniteSeparation + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def trackDirection (v : ℕ → Plane) (i : ℕ) : Plane := v (i+1)-v i + +def trackOffset (v : ℕ → Plane) (n i : ℕ) : Plane := + if i=0 then normalShift (trackDirection v 0) + else if i < n then cornerShift (trackDirection v (i-1)) (trackDirection v i) + else normalShift (trackDirection v (n-1)) + +def shiftedTrack (v : ℕ → Plane) (n : ℕ) (t : ℝ) (i : ℕ) : Plane := + v i+t • trackOffset v n i + +theorem trackOffset_incident_levels (v : ℕ → Plane) (n : ℕ) + (hv : ∀ i, i < n → trackDirection v i ≠ 0) + (hb : ∀ i, 0 < i → i < n → det2 (trackDirection v (i-1)) (trackDirection v i) ≠ 0) + (i : ℕ) (hi : i < n) : + det2 (trackDirection v i) (trackOffset v n i)=1 ∧ + det2 (trackDirection v i) (trackOffset v n (i+1))=1 := by + constructor + · by_cases hz : i=0 + · subst i + simpa [trackOffset] using det2_normalShift (trackDirection v 0) (hv 0 hi) + · have hip : 0 < i := by omega + simpa [trackOffset,hz,hi] using + det2_cornerShift_right (trackDirection v (i-1)) (trackDirection v i) (hb i hip hi) + · by_cases hnext : i+1 < n + · simpa [trackOffset,hnext] using + det2_cornerShift_left (trackDirection v i) (trackDirection v (i+1)) + (by simpa using hb (i+1) (by omega) hnext) + · have hn : n=i+1 := by omega + subst n + simpa [trackOffset] using det2_normalShift (trackDirection v i) (hv i hi) + +theorem shiftedTrack_stretch_no_contact (v : ℕ → Plane) (n : ℕ) + (hv : ∀ i, i < n → trackDirection v i ≠ 0) + (hb : ∀ i, 0 < i → i < n → det2 (trackDirection v (i-1)) (trackDirection v i) ≠ 0) + (i : ℕ) (hi : i < n) (t : ℝ) (ht : t ≠ 0) (s r : ℝ) : + segmentPoint (v i) (v (i+1)) s ≠ + segmentPoint (shiftedTrack v n t i) (shiftedTrack v n t (i+1)) r := by + have hlevels := trackOffset_incident_levels v n hv hb i hi + exact offset_segment_no_contact _ _ _ _ t ht hlevels.1 hlevels.2 s r + +theorem exists_forward_shiftedTrack_radius (v : ℕ → Plane) (n : ℕ) + (hv : ∀ i, i < n → trackDirection v i ≠ 0) + (hb : ∀ i, 0 < i → i < n → det2 (trackDirection v (i-1)) (trackDirection v i) ≠ 0) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, |t| < δ → ∀ i : Fin n, + ∃ r : ℝ, 0 < r ∧ shiftedTrack v n t (i.val+1)-shiftedTrack v n t i.val = r • trackDirection v i.val := by + have hh (i : Fin n) := exists_forward_offset_radius (v i.val) (v (i.val+1)) + (trackOffset v n i.val) (trackOffset v n (i.val+1)) + (sub_ne_zero.mp (hv i.val i.isLt)) + (trackOffset_incident_levels v n hv hb i.val i.isLt).1 + (trackOffset_incident_levels v n hv hb i.val i.isLt).2 + choose radius hpos hdir using hh + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun i _ => hpos i) + exact ⟨δ,hδ,fun t ht i => hdir i t (ht.trans (hbound i (Finset.mem_univ _)))⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OffsetVectors.lean b/lean/OAI/Combinatorics/Crossing/OffsetVectors.lean new file mode 100644 index 0000000000000000000000000000000000000000..e27c6fcd60e5bc8f69d80ffbc257481cfccc3c85 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OffsetVectors.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.PlanarDeterminant + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def rotateQuarter (v : Plane) : Plane := (-v.2,v.1) +def squaredLength (v : Plane) : ℝ := v.1^2+v.2^2 + +theorem squaredLength_pos (v : Plane) (hv : v ≠ 0) : 0 < squaredLength v := by + have hx := sq_nonneg v.1 + have hy := sq_nonneg v.2 + have hnon : 0 ≤ squaredLength v := by dsimp [squaredLength]; linarith + rcases eq_or_lt_of_le hnon with hzero | hpos + · have h₁ : v.1=0 := by dsimp [squaredLength] at hzero; nlinarith + have h₂ : v.2=0 := by dsimp [squaredLength] at hzero; nlinarith + exact False.elim (hv (Prod.ext h₁ h₂)) + · exact hpos + +def normalShift (v : Plane) : Plane := (squaredLength v)⁻¹ • rotateQuarter v + +theorem det2_normalShift (v : Plane) (hv : v ≠ 0) : det2 v (normalShift v) = 1 := by + have hn := ne_of_gt (squaredLength_pos v hv) + unfold normalShift + rw [det2_smul_right] + have he : det2 v (rotateQuarter v) = squaredLength v := by + dsimp [det2,rotateQuarter,squaredLength] + ring + rw [he,inv_mul_cancel₀ hn] + +def cornerShift (u v : Plane) : Plane := (det2 u v)⁻¹ • (v-u) + +theorem det2_cornerShift_left (u v : Plane) (hn : det2 u v ≠ 0) : + det2 u (cornerShift u v) = 1 := by + unfold cornerShift + rw [det2_smul_right,det2_sub_right,det2_self,sub_zero,inv_mul_cancel₀ hn] + +theorem det2_cornerShift_right (u v : Plane) (hn : det2 u v ≠ 0) : + det2 v (cornerShift u v) = 1 := by + unfold cornerShift + rw [det2_smul_right,det2_sub_right,det2_self,det2_swap u v,zero_sub,neg_neg,inv_mul_cancel₀ hn] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OpenSegmentEndpoints.lean b/lean/OAI/Combinatorics/Crossing/OpenSegmentEndpoints.lean new file mode 100644 index 0000000000000000000000000000000000000000..37b76ceb23d9dd5bdf1ca71744265a30b998db48 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OpenSegmentEndpoints.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.PathConcatenationInjective +import OAI.Combinatorics.Crossing.PlanarSegments + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem openSegmentTrace_subset_segment (a b : Plane) : openSegmentTrace a b ⊆ segment ℝ a b := by + rintro x ⟨t,ht,he⟩ + rw [← Path.range_segment] + exact ⟨⟨t,⟨ht.1.le,ht.2.le⟩⟩,by simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he⟩ + +theorem openSegmentTrace_ne_endpoints (a b : Plane) (hab : a ≠ b) + (x : Plane) (hx : x ∈ openSegmentTrace a b) : x ≠ a ∧ x ≠ b := by + obtain ⟨t,ht,he⟩ := hx + let u : unitInterval := ⟨t,⟨ht.1.le,ht.2.le⟩⟩ + have hu : (Path.segment a b) u=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + constructor + · intro h + have hh := Path.segment_injective_of_ne hab (hu.trans (h.trans (Path.segment a b).source.symm)) + have ht0 : t=0 := congrArg Subtype.val hh + exact ht.1.ne ht0.symm + · intro h + have hh := Path.segment_injective_of_ne hab (hu.trans (h.trans (Path.segment a b).target.symm)) + have ht1 : t=1 := congrArg Subtype.val hh + exact ht.2.ne ht1 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderShift.lean b/lean/OAI/Combinatorics/Crossing/OrderShift.lean new file mode 100644 index 0000000000000000000000000000000000000000..be4aa1796d18d6cb8c02815b85bc92bd4fce9a14 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderShift.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.ChordOrientations +import OAI.Combinatorics.Crossing.FiniteSeparation + +namespace OAI + +namespace Zarankiewicz + +theorem orderSign_shift_of_separated (a b ε : ℝ) (hε : 0 < ε) (hab : a ≠ b) + (hgap : ε < |a-b|) : + orderSign a (b+ε) = orderSign a b ∧ orderSign a (b-ε) = orderSign a b := by + rcases lt_or_gt_of_ne hab with h | h + · rw [abs_of_neg (sub_neg.mpr h)] at hgap + have hplus : a < b+ε := by linarith + have hminus : a < b-ε := by linarith + simp [orderSign,h,hplus,hminus] + · rw [abs_of_pos (sub_pos.mpr h)] at hgap + have hplus : b+ε < a := by linarith + have hminus : b-ε < a := by linarith + simp [orderSign,not_lt.mpr h.le,h,hplus,hminus, + not_lt.mpr hplus.le,not_lt.mpr hminus.le] + +theorem orderSign_opposite_average (a b ε : ℝ) (hε : 0<ε) + (hgap : a ≠ b → ε < |a-b|) : + (orderSign a (b+ε)+orderSign a (b-ε))/2 = orderSign a b := by + by_cases hab : a = b + · subst b + have hplus : a < a+ε := by linarith + have hminus : a-ε < a := by linarith + simp [orderSign,hplus,hminus,not_lt.mpr hminus.le] + · obtain ⟨hp,hm⟩ := orderSign_shift_of_separated a b ε hε hab (hgap hab) + rw [hp,hm] + ring + +theorem shifted_node_ne {ι : Type*} (node : ι → ℝ) (hn : Function.Injective node) + (ε : ℝ) (hε : 0<ε) (hgap : ∀ i j, i ≠ j → ε < |node i-node j|) (i j : ι) : + node i ≠ node j+ε ∧ node i ≠ node j-ε := by + by_cases heq : node i = node j + · have hij := hn heq + subst j + constructor <;> linarith + · have hg := hgap i j (fun hij => heq (congrArg node hij)) + constructor + · intro he + rw [he] at hg + simp only [add_sub_cancel_left,abs_of_pos hε] at hg + exact (lt_irrefl ε) hg + · intro he + have hh : |node i-node j| = ε := by rw [he]; rw [sub_sub_cancel_left,abs_neg,abs_of_pos hε] + rw [hh] at hg + exact (lt_irrefl ε) hg + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedAffineSubdivision.lean b/lean/OAI/Combinatorics/Crossing/OrderedAffineSubdivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7d3441e718bf4c26da21e11b3c1a693d28ec23c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedAffineSubdivision.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.Crossing.AffineIntervalRestriction +import OAI.Combinatorics.Crossing.SortedMarkedParameters +import OAI.Combinatorics.Crossing.IntervalSegmentStrict +import OAI.Combinatorics.Crossing.PolygonalParametrization + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem strictMono_no_between_successors {k : ℕ} (t : Fin (k+1) → unitInterval) + (ht : StrictMono t) (i : Fin k) (j : Fin (k+1)) : + ¬ (t i.castSucc < t j ∧ t j < t i.succ) := by + intro h + have hlo : i.castSucc < j := by + by_contra hn + exact h.1.not_ge (ht.monotone (le_of_not_gt hn)) + have hhi : j < i.succ := by + by_contra hn + exact h.2.not_ge (ht.monotone (le_of_not_gt hn)) + change i.val < j.val at hlo + change j.val < i.val+1 at hhi + omega + +theorem HasFiniteAffineCover.nonempty_polygonalParametrization {a b : Plane} {γ : Path a b} + (hγ : HasFiniteAffineCover γ) : Nonempty (PolygonalParametrization γ) := by + classical + obtain ⟨S,hSlt,hScov,hSaff⟩ := hγ + let T : Finset unitInterval := insert 0 (insert 1 (S.image Prod.fst ∪ S.image Prod.snd)) + obtain ⟨k,hk,t,ht,h0,h1,hR⟩ := exists_sorted_unitInterval_finset T (by simp [T]) (by simp [T]) + have hleft (ab : unitInterval × unitInterval) (hab : ab ∈ S) : ab.1 ∈ Set.range t := by + rw [hR] + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem + (Finset.mem_union_left _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩))) + have hright (ab : unitInterval × unitInterval) (hab : ab ∈ S) : ab.2 ∈ Set.range t := by + rw [hR] + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem + (Finset.mem_union_right _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩))) + refine ⟨{pieces:=k,knot:=t,increasing:=ht,first:=h0,last:=h1,affine:=?_}⟩ + intro i u + let mid : unitInterval := ⟨1/2,by norm_num⟩ + let z := intervalSegment (t i.castSucc) (t i.succ) mid + have hz : t i.castSucc < z ∧ z < t i.succ := + intervalSegment_strict_between _ _ mid (ht (by change i.val < i.val+1; omega)) (by + constructor <;> change (_ : ℝ) < _ <;> norm_num [mid]) + obtain ⟨ab,hab,ha,hb⟩ := hScov z + have hlo : ab.1 ≤ t i.castSucc := by + by_contra hn + obtain ⟨j,hj⟩ := hleft ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact lt_of_not_ge hn,by rw [hj]; exact ha.trans_lt hz.2⟩ + have hhi : t i.succ ≤ ab.2 := by + by_contra hn + obtain ⟨j,hj⟩ := hright ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact hz.1.trans_le hb,by rw [hj]; exact lt_of_not_ge hn⟩ + have hle : t i.castSucc ≤ t i.succ := ht.monotone (by change i.val ≤ i.val+1; omega) + exact path_affine_restrict γ ab.1 ab.2 (hSlt ab hab) (hSaff ab hab) + (t i.castSucc) (t i.succ) ⟨hlo,hle.trans hhi⟩ ⟨hlo.trans hle,hhi⟩ u + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedCrossingPorts.lean b/lean/OAI/Combinatorics/Crossing/OrderedCrossingPorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..a454cf91f0993e2b03a0015a6d98ce6b50a1100e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedCrossingPorts.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.OrderedPathParts +import OAI.Combinatorics.Crossing.AssembledPortIncidence +import OAI.Combinatorics.Crossing.ExtraDrawingSubdivision +import OAI.Combinatorics.Crossing.DrawingEdgeWalk + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem middlePath_contains_chord (E : PolygonalExterior C) (p : C.InnerIndex) : + OrderedPathPart (E.middlePath p.1) (C.crossingChord p) := by + rcases p with ⟨e,⟨i,hi⟩⟩ + have hj : i.val-1+1 < C.count e := by omega + have hinner : C.orderedInner e (i.val-1) hj=⟨e,⟨i,hi⟩⟩ := by + unfold DrawingPassages.orderedInner + congr 1 + apply Subtype.ext + apply Fin.ext + change i.val-1+1=i.val + omega + have hpart : OrderedPathPart (E.middlePath e) (orderedBridge C e (i.val-1)) := + alternatingPath_contains_bridge _ _ _ _ (C.count e-1) (i.val-1) (by omega) + apply hpart.congr_right + intro t + rw [orderedBridge_apply (C:=C) e (i.val-1) hj t,hinner] + +theorem assembledEdge_contains_chord (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (p : C.InnerIndex) : + OrderedPathPart (E.assembledEdge v p.1) (C.crossingChord p) := by + have h : OrderedPathPart (E.anchoredMiddle p.1) (C.crossingChord p) := E.middlePath_contains_chord p + exact (h.right (startSpoke C v p.1)).left (endSpoke C v p.1) + +theorem assembled_crossing_ports_ordered (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (p : C.InnerIndex) : + ∃ u w : unitInterval, u < w ∧ + E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p) ∧ + E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p) := + (E.assembledEdge_contains_chord v p).endpoints_ordered + +theorem crossing_port_walk_indices (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p : C.InnerIndex) : + ∃ i j : Fin ((P p.1).pieces+1), i < j ∧ + (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p) ∧ + (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p) := by + obtain ⟨u,w,huw,hu,hw⟩ := E.assembled_crossing_ports_ordered v p + obtain ⟨i,hi⟩ := hport p.1 u ⟨C.incomingPort p,hu.symm⟩ + obtain ⟨j,hj⟩ := hport p.1 w ⟨C.outgoingPort p,hw.symm⟩ + have hij : i < j := by + by_contra hn + have hh := (P p.1).increasing.monotone (le_of_not_gt hn) + rw [hi,hj] at hh + exact huw.not_ge hh + refine ⟨i,j,hij,?_,?_⟩ + · rw [drawingEdgeWalk_getVert P p.1 i.val (by omega)] + have he := (P p.1).vertices_at i + change (P p.1).vertices i.val=E.assembledEdge v p.1 ((P p.1).knot i) at he + exact he.trans ((congrArg (E.assembledEdge v p.1) hi).trans hu) + · rw [drawingEdgeWalk_getVert P p.1 j.val (by omega)] + have he := (P p.1).vertices_at j + change (P p.1).vertices j.val=E.assembledEdge v p.1 ((P p.1).knot j) at he + exact he.trans ((congrArg (E.assembledEdge v p.1) hj).trans hw) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedExteriorPaths.lean b/lean/OAI/Combinatorics/Crossing/OrderedExteriorPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae0ebc33bd9952ec817b6395cc5a23c7788de13d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedExteriorPaths.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.Crossing.AlternatingPaths +import OAI.Combinatorics.Crossing.ExteriorChordMeeting +import OAI.Combinatorics.Crossing.CrossingDiskIncidence +import OAI.Combinatorics.Crossing.VertexEndpointPorts + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +def orderedArc (C : DrawingPassages D) (e : BipartiteEdge m n) (i : ℕ) : C.ArcIndex := + ⟨e,⟨min i (C.count e-1),by have h := C.count_pos e; omega⟩⟩ + +theorem orderedArc_val (C : DrawingPassages D) (e : BipartiteEdge m n) (i : ℕ) + (hi : i < C.count e) : (C.orderedArc e i).2.val=i := by + change min i (C.count e-1)=i + omega + +theorem orderedArc_inj (C : DrawingPassages D) (e : BipartiteEdge m n) (i j : ℕ) + (hi : i < C.count e) (hj : j < C.count e) + (h : C.orderedArc e i=C.orderedArc e j) : i=j := by + have hh := congrArg (fun p : C.ArcIndex => p.2.val) h + simpa only [C.orderedArc_val e i hi,C.orderedArc_val e j hj] using hh + +theorem orderedArc_first (C : DrawingPassages D) (e : BipartiteEdge m n) : + C.orderedArc e 0=C.firstArc e := by + simp [orderedArc,firstArc] + +theorem orderedArc_last (C : DrawingPassages D) (e : BipartiteEdge m n) : + C.orderedArc e (C.count e-1)=C.lastArc e := by + simp [orderedArc,lastArc] + +def orderedInner (C : DrawingPassages D) (e : BipartiteEdge m n) (j : ℕ) + (hj : j+1 < C.count e) : C.InnerIndex := + ⟨e,⟨⟨j+1,by omega⟩,⟨Nat.succ_pos j,hj⟩⟩⟩ + +theorem orderedInner_incoming (C : DrawingPassages D) (e : BipartiteEdge m n) + (j : ℕ) (hj : j+1 < C.count e) : + C.incomingArc (C.orderedInner e j hj)=C.orderedArc e j := by + unfold incomingArc orderedInner orderedArc + congr 1 + apply Fin.ext + change j+1-1=min j (C.count e-1) + omega + +theorem orderedInner_outgoing (C : DrawingPassages D) (e : BipartiteEdge m n) + (j : ℕ) (hj : j+1 < C.count e) : + C.outgoingArc (C.orderedInner e j hj)=C.orderedArc e (j+1) := by + unfold outgoingArc orderedInner orderedArc + congr 1 + apply Fin.ext + change j+1=min (j+1) (C.count e-1) + omega + +theorem orderedInner_inj (C : DrawingPassages D) (e : BipartiteEdge m n) (i j : ℕ) + (hi : i+1 < C.count e) (hj : j+1 < C.count e) + (h : C.orderedInner e i hi=C.orderedInner e j hj) : i=j := by + have hh : i+1=j+1 := congrArg (fun p : C.InnerIndex => p.2.val.val) h + omega + +end DrawingPassages +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +def orderedPath (E : PolygonalExterior C) (e : BipartiteEdge m n) (i : ℕ) : + Path (C.arcStart (C.orderedArc e i)) (C.arcEnd (C.orderedArc e i)) := + (E.chain (C.orderedArc e i)).path + +def orderedBridge (C : DrawingPassages D) (e : BipartiteEdge m n) (i : ℕ) : + Path (C.arcEnd (C.orderedArc e i)) (C.arcStart (C.orderedArc e (i+1))) := Path.segment _ _ + +theorem orderedBridge_apply (e : BipartiteEdge m n) (j : ℕ) (hj : j+1 < C.count e) + (t : unitInterval) : + orderedBridge C e j t=C.crossingChord (C.orderedInner e j hj) t := by + change (Path.segment _ _ : Path _ _) t=(Path.segment _ _ : Path _ _) t + have ha : C.portPoint (C.incomingPort (C.orderedInner e j hj))=C.arcEnd (C.orderedArc e j) := by + change C.arcEnd (C.incomingArc (C.orderedInner e j hj))=_ + rw [C.orderedInner_incoming] + have hb : C.portPoint (C.outgoingPort (C.orderedInner e j hj))=C.arcStart (C.orderedArc e (j+1)) := by + change C.arcStart (C.outgoingArc (C.orderedInner e j hj))=_ + rw [C.orderedInner_outgoing] + simp only [Path.segment_apply,ha,hb] + +theorem orderedBridge_range (e : BipartiteEdge m n) (j : ℕ) (hj : j+1 < C.count e) : + Set.range (orderedBridge C e j)=Set.range (C.crossingChord (C.orderedInner e j hj)) := by + congr 1 + funext t + exact orderedBridge_apply e j hj t + +def middlePath (E : PolygonalExterior C) (e : BipartiteEdge m n) : + Path (C.arcStart (C.orderedArc e 0)) (C.arcEnd (C.orderedArc e (C.count e-1))) := + alternatingPath (fun i => C.arcStart (C.orderedArc e i)) + (fun i => C.arcEnd (C.orderedArc e i)) (E.orderedPath e) (orderedBridge C e) (C.count e-1) + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedKnotCover.lean b/lean/OAI/Combinatorics/Crossing/OrderedKnotCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..018145bddeb273f0317dab8c78a8e3d417ed22fc --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedKnotCover.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.Crossing.NormalizedPolygonalDrawing +import Mathlib.Data.Finset.Max + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem ordered_knots_cover {k : ℕ} (hk : 0 < k) (t : Fin (k+1) → unitInterval) + (ht : StrictMono t) (h0 : t 0=0) (h1 : t (Fin.last k)=1) (u : unitInterval) : + ∃ i : Fin k, t i.castSucc ≤ u ∧ u ≤ t i.succ := by + classical + let S := Finset.univ.filter (fun i : Fin (k+1) => t i ≤ u) + have hS : S.Nonempty := ⟨0,by simp only [S,Finset.mem_filter,Finset.mem_univ,true_and,h0]; exact u.property.1⟩ + let j := S.max' hS + have hj : t j ≤ u := (Finset.mem_filter.mp (Finset.max'_mem S hS)).2 + by_cases hjlast : j.val=k + · let i : Fin k := ⟨k-1,by omega⟩ + have hjl : j=Fin.last k := Fin.ext hjlast + have hi : i.succ=Fin.last k := by apply Fin.ext; change k-1+1=k; omega + have hu : u=1 := le_antisymm u.property.2 (by simpa only [hjl,h1] using hj) + refine ⟨i,?_,?_⟩ + · rw [hu, ← h1] + exact (ht (Fin.castSucc_lt_last i)).le + · rw [hi,h1,hu] + · have hjk : j.val < k := by have hh := j.isLt; omega + let i : Fin k := ⟨j.val,hjk⟩ + have hij : i.castSucc=j := Fin.ext rfl + refine ⟨i,by rw [hij]; exact hj,?_⟩ + by_contra hu + have hmem : i.succ ∈ S := Finset.mem_filter.mpr ⟨Finset.mem_univ _,(lt_of_not_ge hu).le⟩ + have hh : i.succ ≤ j := Finset.le_max' S i.succ hmem + change j.val+1 ≤ j.val at hh + omega + +theorem PolygonalParametrization.knot_cover {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) (u : unitInterval) : + ∃ i : Fin P.pieces, P.knot i.castSucc ≤ u ∧ u ≤ P.knot i.succ := + ordered_knots_cover P.pieces_pos P.knot P.increasing P.first P.last u + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedNodeIndices.lean b/lean/OAI/Combinatorics/Crossing/OrderedNodeIndices.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e086803ee1b79787d41e378259b6559e0729535 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedNodeIndices.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.Crossing.TwoTriangleBasis +import Mathlib.Data.Finset.Sort + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +abbrev OrderedNode (s : ℕ) := ↥(Finset.Icc 1 (2*s+1)) + +@[simp] theorem card_orderedNode (s : ℕ) : Fintype.card (OrderedNode s) = 2*s+1 := by + simp [OrderedNode, Nat.card_Icc] + +def extendOrderedNode (s : ℕ) (node : OrderedNode s → ℝ) (i : ℕ) : ℝ := + if hi : i ∈ Finset.Icc 1 (2*s+1) then node ⟨i,hi⟩ else 0 + +@[simp] theorem extendOrderedNode_apply (s : ℕ) (node : OrderedNode s → ℝ) (i : OrderedNode s) : + extendOrderedNode s node i.val = node i := by + simp [extendOrderedNode, i.property] + +theorem extendOrderedNode_injOn (s : ℕ) (node : OrderedNode s → ℝ) + (hn : Function.Injective node) : Set.InjOn (extendOrderedNode s node) (Set.Icc 1 (2*s+1)) := by + intro p hp q hq he + have hp' : p ∈ Finset.Icc 1 (2*s+1) := Finset.mem_Icc.mpr hp + have hq' : q ∈ Finset.Icc 1 (2*s+1) := Finset.mem_Icc.mpr hq + simp only [extendOrderedNode, dite_eq_left hp', dite_eq_left hq'] at he + exact congrArg Subtype.val (hn he) + +theorem triangle_nodes_mem {s p q : ℕ} (h : (p,q) ∈ twoTriangle s) : + p ∈ Finset.Icc 1 (2*s+1) ∧ q ∈ Finset.Icc 1 (2*s+1) := by + rw [mem_twoTriangle] at h + simp only [Finset.mem_Icc] + omega + +def triangleNodePair (s : ℕ) (pq : TriangleIndex s) : OrderedNode s × OrderedNode s := + (⟨pq.val.1, (triangle_nodes_mem pq.property).1⟩, + ⟨pq.val.2, (triangle_nodes_mem pq.property).2⟩) + +theorem triangleNodePair_injective (s : ℕ) : Function.Injective (triangleNodePair s) := by + intro p q he + apply Subtype.ext + exact congrArg (fun pq : OrderedNode s × OrderedNode s => (pq.1.val,pq.2.val)) he + +def orderedTriangle (s : ℕ) : Finset (OrderedNode s × OrderedNode s) := + Finset.univ.filter (fun pq => (pq.1.val,pq.2.val) ∈ twoTriangle s) + +def triangleNodeEquiv (s : ℕ) : TriangleIndex s ≃ ↥(orderedTriangle s) where + toFun pq := ⟨triangleNodePair s pq, by simp [orderedTriangle, triangleNodePair, pq.property]⟩ + invFun pq := ⟨(pq.val.1.val,pq.val.2.val), by simpa [orderedTriangle] using pq.property⟩ + left_inv pq := rfl + right_inv pq := rfl + +theorem triangleMatrix_ordered_entry (s : ℕ) (node : OrderedNode s → ℝ) + (ab j : BiExponent s) : + triangleMatrix s (extendOrderedNode s node) ab j = + node (triangleNodePair s (triangleCoordEquiv s j)).1 ^ ab.1.val * + node (triangleNodePair s (triangleCoordEquiv s j)).2 ^ ab.2.val := by + unfold triangleMatrix monomialVector + change extendOrderedNode s node (triangleNodePair s (triangleCoordEquiv s j)).1.val ^ ab.1.val * + extendOrderedNode s node (triangleNodePair s (triangleCoordEquiv s j)).2.val ^ ab.2.val = _ + rw [extendOrderedNode_apply, extendOrderedNode_apply] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedPassages.lean b/lean/OAI/Combinatorics/Crossing/OrderedPassages.lean new file mode 100644 index 0000000000000000000000000000000000000000..10b6a781d09076e15aa92659eba4e0d5f38efe0f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedPassages.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.DiskPassage +import OAI.Combinatorics.Crossing.ParameterNeighborhoods +import OAI.Combinatorics.Crossing.PathSubarc + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem diskPassage_separated {a b z w : Plane} {γ : Path a b} {r δ : ℝ} + {s t : unitInterval} (P : DiskPassage γ z r s) (Q : DiskPassage γ w r t) + (hst : s < t) (hδ : 0 < δ) + (hd : Disjoint (closure (parameterNeighborhood s δ)) (closure (parameterNeighborhood t δ))) + (hP : P.leave ∈ parameterNeighborhood s δ) (hQ : Q.enter ∈ parameterNeighborhood t δ) : + P.leave < Q.enter := + parameterNeighborhood_ordered s t δ hδ hst (hd.mono subset_closure subset_closure) P.leave Q.enter hP hQ + +def retainedSubarc {a b : Plane} (γ : Path a b) {k : ℕ} + (τ : Fin (k+1) → unitInterval) (r : ℝ) + (P : ∀ i, DiskPassage γ (γ (τ i)) r (τ i)) (i : Fin k) : + Path (γ (P i.castSucc).leave) (γ (P i.succ).enter) := + pathSubarc γ (P i.castSucc).leave (P i.succ).enter + +theorem ordered_passage_enter_strictMono {a b : Plane} (γ : Path a b) {k : ℕ} + (τ : Fin (k+1) → unitInterval) (r : ℝ) (P : ∀ i, DiskPassage γ (γ (τ i)) r (τ i)) + (hsep : ∀ i j, i < j → (P i).leave < (P j).enter) : + StrictMono (fun i => (P i).enter) := by + intro i j hij + exact (P i).enter_lt_leave.trans (hsep i j hij) + +theorem ordered_passage_leave_strictMono {a b : Plane} (γ : Path a b) {k : ℕ} + (τ : Fin (k+1) → unitInterval) (r : ℝ) (P : ∀ i, DiskPassage γ (γ (τ i)) r (τ i)) + (hsep : ∀ i j, i < j → (P i).leave < (P j).enter) : + StrictMono (fun i => (P i).leave) := by + intro i j hij + exact (hsep i j hij).trans (P j).enter_lt_leave + +theorem retained_interval_no_mark {a b : Plane} (γ : Path a b) {k : ℕ} + (τ : Fin (k+1) → unitInterval) (hτ : StrictMono τ) (h0 : τ 0=0) + (h1 : τ (Fin.last k)=1) (r : ℝ) (P : ∀ i, DiskPassage γ (γ (τ i)) r (τ i)) + (i : Fin k) (t : unitInterval) + (ht : t ∈ Set.Icc (P i.castSucc).leave (P i.succ).enter) : t ∉ Set.range τ := by + rintro ⟨j,hj⟩ + have hleft : τ i.castSucc < 1 := by + rw [← h1] + exact hτ (show i.castSucc < Fin.last k from i.isLt) + have hright : 0 < τ i.succ := by + rw [← h0] + exact hτ (show (0 : Fin (k+1)) < i.succ by change 0 < i.val+1; omega) + by_cases hji : j ≤ i.castSucc + · have hh := (hτ.monotone hji).trans_lt ((P i.castSucc).strict_leave hleft) + exact hh.not_ge (ht.1.trans_eq hj.symm) + · have hij : i.succ ≤ j := by + change i.val+1 ≤ j.val + have hh : ¬ j.val ≤ i.val := hji + omega + have hh := ((P i.succ).strict_enter hright).trans_le (hτ.monotone hij) + exact hh.not_ge (hj.trans_le ht.2) + +theorem retained_interval_pair_disjoint {a b : Plane} (γ : Path a b) {k : ℕ} + (τ : Fin (k+1) → unitInterval) (r : ℝ) (P : ∀ i, DiskPassage γ (γ (τ i)) r (τ i)) + (hsep : ∀ i j, i < j → (P i).leave < (P j).enter) + (i j : Fin k) (hij : i < j) : + Disjoint (Set.Icc (P i.castSucc).leave (P i.succ).enter) + (Set.Icc (P j.castSucc).leave (P j.succ).enter) := by + have hi : i.succ ≤ j.castSucc := by change i.val+1 ≤ j.val; omega + have hgap := ((ordered_passage_enter_strictMono γ τ r P hsep).monotone hi).trans_lt (P j.castSucc).enter_lt_leave + apply Set.disjoint_left.mpr + intro t ht hu + exact hgap.not_ge (hu.1.trans ht.2) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrderedPathParts.lean b/lean/OAI/Combinatorics/Crossing/OrderedPathParts.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee390847c9f1b76f51caba5e0aad7286ea1c3c4f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrderedPathParts.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.Crossing.AffinePathHalves +import OAI.Combinatorics.Crossing.AlternatingPaths + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def OrderedPathPart {a b c d : Plane} (γ : Path a b) (δ : Path c d) : Prop := + ∃ f : unitInterval → unitInterval, StrictMono f ∧ ∀ t, γ (f t)=δ t + +theorem OrderedPathPart.refl {a b : Plane} (γ : Path a b) : OrderedPathPart γ γ := + ⟨id,strictMono_id,fun _ => rfl⟩ + +theorem OrderedPathPart.trans {a b c d e f : Plane} {γ : Path a b} {δ : Path c d} {η : Path e f} + (hγ : OrderedPathPart γ δ) (hδ : OrderedPathPart δ η) : OrderedPathPart γ η := by + obtain ⟨u,hu,he⟩ := hγ + obtain ⟨v,hv,hf⟩ := hδ + exact ⟨u ∘ v,hu.comp hv,fun t => (he (v t)).trans (hf t)⟩ + +theorem OrderedPathPart.left {a b c d e : Plane} {γ : Path a b} {δ : Path d e} + (h : OrderedPathPart γ δ) (η : Path b c) : OrderedPathPart (γ.trans η) δ := + (show OrderedPathPart (γ.trans η) γ from + ⟨intervalLeft,intervalLeft_strictMono,path_trans_intervalLeft γ η⟩).trans h + +theorem OrderedPathPart.right {a b c d e : Plane} {γ : Path b c} {δ : Path d e} + (h : OrderedPathPart γ δ) (η : Path a b) : OrderedPathPart (η.trans γ) δ := + (show OrderedPathPart (η.trans γ) γ from + ⟨intervalRight,intervalRight_strictMono,path_trans_intervalRight η γ⟩).trans h + +theorem OrderedPathPart.congr_right {a b c d e f : Plane} {γ : Path a b} + {δ : Path c d} {η : Path e f} (h : OrderedPathPart γ δ) (he : ∀ t, δ t=η t) : + OrderedPathPart γ η := by + obtain ⟨u,hu,hh⟩ := h + exact ⟨u,hu,fun t => (hh t).trans (he t)⟩ + +theorem OrderedPathPart.endpoints_ordered {a b c d : Plane} {γ : Path a b} {δ : Path c d} + (h : OrderedPathPart γ δ) : + ∃ u v : unitInterval, u < v ∧ γ u=c ∧ γ v=d := by + obtain ⟨f,hf,he⟩ := h + exact ⟨f 0,f 1,hf zero_lt_one,(he 0).trans δ.source,(he 1).trans δ.target⟩ + +theorem alternatingPath_contains_path (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) : + (n : ℕ) → ∀ i, i ≤ n → OrderedPathPart (alternatingPath a b p q n) (p i) + | 0, i, hi => by + have he : i=0 := by omega + subst i + exact OrderedPathPart.refl _ + | n+1, i, hi => by + by_cases he : i=n+1 + · subst i + exact (OrderedPathPart.refl (p (n+1))).right _ + · exact ((alternatingPath_contains_path a b p q n i (by omega)).left (q n)).left (p (n+1)) + +theorem alternatingPath_contains_bridge (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) : + (n : ℕ) → ∀ i, i < n → OrderedPathPart (alternatingPath a b p q n) (q i) + | 0, i, hi => by omega + | n+1, i, hi => by + by_cases he : i=n + · subst i + exact ((OrderedPathPart.refl (q n)).right _).left _ + · exact ((alternatingPath_contains_bridge a b p q n i (by omega)).left (q n)).left (p (n+1)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/OrientedSimilarity.lean b/lean/OAI/Combinatorics/Crossing/OrientedSimilarity.lean new file mode 100644 index 0000000000000000000000000000000000000000..4183608321254e7bc44253f9adba431566a8f7c3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/OrientedSimilarity.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.OffsetVectors +import OAI.Combinatorics.Crossing.SegmentSymmetries + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def similarityPoint (o u x : Plane) : Plane := + o+(u.1*x.1-u.2*x.2,u.2*x.1+u.1*x.2) + +theorem similarityPoint_injective (o u : Plane) (hu : u ≠ 0) : Function.Injective (similarityPoint o u) := by + intro x y he + have h₁ := congrArg Prod.fst he + have h₂ := congrArg Prod.snd he + dsimp [similarityPoint] at h₁ h₂ + have hs := ne_of_gt (squaredLength_pos u hu) + have hx : squaredLength u*(x.1-y.1)=0 := by + dsimp [squaredLength] + linear_combination u.1*h₁+u.2*h₂ + have hy : squaredLength u*(x.2-y.2)=0 := by + dsimp [squaredLength] + linear_combination -u.2*h₁+u.1*h₂ + exact Prod.ext (sub_eq_zero.mp ((mul_eq_zero.mp hx).resolve_left hs)) + (sub_eq_zero.mp ((mul_eq_zero.mp hy).resolve_left hs)) + +theorem similarityPoint_segment (o u a b : Plane) (t : ℝ) : + similarityPoint o u (segmentPoint a b t) = + segmentPoint (similarityPoint o u a) (similarityPoint o u b) t := by + apply Prod.ext <;> dsimp [similarityPoint,segmentPoint] <;> ring + +theorem similarityPoint_det (o u a b c d : Plane) : + det2 (similarityPoint o u b-similarityPoint o u a) + (similarityPoint o u d-similarityPoint o u c) = squaredLength u*det2 (b-a) (d-c) := by + dsimp [similarityPoint,squaredLength,det2] + ring + +theorem segmentsCrossProperly_similarity (o u a b c d : Plane) (hu : u ≠ 0) : + SegmentsCrossProperly (similarityPoint o u a) (similarityPoint o u b) + (similarityPoint o u c) (similarityPoint o u d) ↔ SegmentsCrossProperly a b c d := by + have hs := ne_of_gt (squaredLength_pos u hu) + unfold SegmentsCrossProperly + rw [similarityPoint_det,mul_ne_zero_iff] + simp only [← similarityPoint_segment,(similarityPoint_injective o u hu).eq_iff] + exact ⟨fun hh => ⟨hh.1.2,hh.2⟩,fun hh => ⟨⟨hs,hh.1⟩,hh.2⟩⟩ + +theorem segmentCrossingSign_similarity (o u a b c d : Plane) (hu : u ≠ 0) : + segmentCrossingSign (similarityPoint o u a) (similarityPoint o u b) + (similarityPoint o u c) (similarityPoint o u d) = segmentCrossingSign a b c d := by + unfold segmentCrossingSign + rw [segmentsCrossProperly_similarity o u a b c d hu] + simp only [similarityPoint_det,mul_pos_iff_of_pos_left (squaredLength_pos u hu)] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ParallelDirection.lean b/lean/OAI/Combinatorics/Crossing/ParallelDirection.lean new file mode 100644 index 0000000000000000000000000000000000000000..d59979baf640cdbdb388112921c59cd035598a6c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ParallelDirection.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.OffsetVectors +import Mathlib.Tactic.FunProp + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +def dot2 (u v : Plane) : ℝ := u.1*v.1+u.2*v.2 + +theorem planar_vector_decomposition (u v : Plane) : + squaredLength u • v = dot2 u v • u+det2 u v • rotateQuarter u := by + apply Prod.ext <;> dsimp [squaredLength,dot2,det2,rotateQuarter] <;> ring + +theorem vector_parallel_of_det_zero (u v : Plane) (hu : u ≠ 0) (h : det2 u v=0) : + v = (dot2 u v/squaredLength u) • u := by + have hs := ne_of_gt (squaredLength_pos u hu) + have hh := planar_vector_decomposition u v + rw [h,zero_smul,add_zero] at hh + calc + v = (squaredLength u)⁻¹ • (squaredLength u • v) := by rw [smul_smul,inv_mul_cancel₀ hs,one_smul] + _ = (squaredLength u)⁻¹ • (dot2 u v • u) := by rw [hh] + _ = _ := by rw [smul_smul,div_eq_mul_inv,mul_comm] + +theorem offset_direction_det_zero (a b qa qb : Plane) (ε : ℝ) + (ha : det2 (b-a) qa=1) (hb : det2 (b-a) qb=1) : + det2 (b-a) ((b+ε • qb)-(a+ε • qa)) = 0 := by + dsimp [det2] at * + linear_combination ε*hb-ε*ha + +theorem exists_forward_offset_radius (a b qa qb : Plane) (hab : b ≠ a) + (ha : det2 (b-a) qa=1) (hb : det2 (b-a) qb=1) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → + ∃ r : ℝ, 0 dot2 (b-a) ((b+ε • qb)-(a+ε • qa)) / squaredLength (b-a) + have hf : Continuous f := by + dsimp [f,dot2,squaredLength] + fun_prop + have hf0 : 0 linarith + +theorem parameterNeighborhood_ordered (a b : unitInterval) (δ : ℝ) (hδ : 0 < δ) + (hab : a < b) (hd : Disjoint (parameterNeighborhood a δ) (parameterNeighborhood b δ)) + (u v : unitInterval) (hu : u ∈ parameterNeighborhood a δ) + (hv : v ∈ parameterNeighborhood b δ) : u < v := by + by_contra hn + have hvu : v ≤ u := le_of_not_gt hn + have ha : a ∈ parameterNeighborhood a δ := by simpa [parameterNeighborhood] using hδ + have hb : b ∈ parameterNeighborhood b δ := by simpa [parameterNeighborhood] using hδ + by_cases hva : v ≤ a + · exact Set.disjoint_left.mp hd ha (parameterNeighborhood_between b δ v b a hv hb hva hab.le) + · have hav : a ≤ v := (lt_of_not_ge hva).le + exact Set.disjoint_left.mp hd (parameterNeighborhood_between a δ a u v ha hu hav hvu) hv + +theorem finite_parameter_neighborhoods {ι : Type*} [Fintype ι] [DecidableEq ι] + (t : ι → unitInterval) (ht : Function.Injective t) : + ∃ δ : ℝ, 0 < δ ∧ + (∀ i, t i ∈ parameterNeighborhood (t i) δ) ∧ + (∀ i j, i ≠ j → Disjoint (closure (parameterNeighborhood (t i) δ)) + (closure (parameterNeighborhood (t j) δ))) := by + obtain ⟨ε,hε,hsep⟩ := finite_node_separation (fun i => (t i).val) + (Subtype.val_injective.comp ht) + let δ := ε/3 + have hδ : 0 < δ := by dsimp [δ]; positivity + have hclosed (i : ι) : IsClosed {s : unitInterval | |s.val-(t i).val| ≤ δ} := by + apply isClosed_le _ continuous_const + fun_prop + have hcl (i : ι) : closure (parameterNeighborhood (t i) δ) ⊆ + {s : unitInterval | |s.val-(t i).val| ≤ δ} := + closure_minimal (fun s hh => le_of_lt (show |s.val-(t i).val| < δ from hh)) (hclosed i) + refine ⟨δ,hδ,fun i => by simpa [parameterNeighborhood] using hδ,?_⟩ + intro i j hij + apply Set.disjoint_left.mpr + intro x hx hy + have hx' := hcl i hx + have hy' := hcl j hy + have hg := hsep i j hij + have htri := abs_sub_le (t i).val x.val (t j).val + rw [abs_sub_comm (t i).val x.val] at htri + change |x.val-(t i).val| ≤ δ at hx' + change |x.val-(t j).val| ≤ δ at hy' + dsimp [δ] at hx' hy' + linarith + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PathConcatenationInjective.lean b/lean/OAI/Combinatorics/Crossing/PathConcatenationInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..693b2652320d501d93bbd6fc015d38868089752f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PathConcatenationInjective.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.Crossing.PolygonalChains + +namespace OAI + +namespace Zarankiewicz + +theorem path_meeting_parameters {X : Type*} [TopologicalSpace X] {a b c : X} + (γ : Path a b) (η : Path b c) (hγ : Function.Injective γ) (hη : Function.Injective η) + (hm : ∀ x, x ∈ Set.range γ → x ∈ Set.range η → x=b) + (s t : unitInterval) (he : γ s=η t) : s=1 ∧ t=0 := by + have hx : γ s=b := hm _ ⟨s,rfl⟩ ⟨t,he.symm⟩ + exact ⟨hγ (hx.trans γ.target.symm),hη (he.symm.trans (hx.trans η.source.symm))⟩ + +theorem path_trans_injective {X : Type*} [TopologicalSpace X] {a b c : X} + (γ : Path a b) (η : Path b c) (hγ : Function.Injective γ) (hη : Function.Injective η) + (hm : ∀ x, x ∈ Set.range γ → x ∈ Set.range η → x=b) : + Function.Injective (γ.trans η) := by + intro s t he + by_cases hs : (s : ℝ) ≤ 1/2 <;> by_cases ht : (t : ℝ) ≤ 1/2 + · simp only [Path.trans_apply,dite_eq_left hs,dite_eq_left ht] at he + have hh := congrArg Subtype.val (hγ he) + apply Subtype.ext + change 2*(s : ℝ)=2*(t : ℝ) at hh + linarith + · simp only [Path.trans_apply,dite_eq_left hs,dite_eq_right ht] at he + have hh := congrArg Subtype.val (path_meeting_parameters γ η hγ hη hm _ _ he).2 + change 2*(t : ℝ)-1=0 at hh + exfalso + linarith + · simp only [Path.trans_apply,dite_eq_right hs,dite_eq_left ht] at he + have hh := congrArg Subtype.val (path_meeting_parameters γ η hγ hη hm _ _ he.symm).2 + change 2*(s : ℝ)-1=0 at hh + exfalso + linarith + · simp only [Path.trans_apply,dite_eq_right hs,dite_eq_right ht] at he + have hh := congrArg Subtype.val (hη he) + apply Subtype.ext + change 2*(s : ℝ)-1=2*(t : ℝ)-1 at hh + linarith + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PathEndpointNeighborhoods.lean b/lean/OAI/Combinatorics/Crossing/PathEndpointNeighborhoods.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd72076b28bfd02c652914ae2bbaf33c14a11a8b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PathEndpointNeighborhoods.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.PathSubarc +import Mathlib.Topology.MetricSpace.Pseudo.Defs + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem path_near_endpoints {a b : Plane} (γ : Path a b) (ρ σ : ℝ) + (hρ : 0 < ρ) (hσ : 0 < σ) : + ∃ u v : unitInterval, 0 < u ∧ u < v ∧ v < 1 ∧ + dist (γ u) a < ρ ∧ dist (γ v) b < σ := by + have he0 : ∀ᶠ t : ℝ in 𝓝 0, γ.extend t ∈ Metric.ball a ρ := + γ.continuous_extend.continuousAt.preimage_mem_nhds (by simpa using Metric.ball_mem_nhds a hρ) + have he1 : ∀ᶠ t : ℝ in 𝓝 1, γ.extend t ∈ Metric.ball b σ := + γ.continuous_extend.continuousAt.preimage_mem_nhds (by simpa using Metric.ball_mem_nhds b hσ) + obtain ⟨δ,hδ,hd⟩ := Metric.eventually_nhds_iff.mp he0 + obtain ⟨ε,hε,he⟩ := Metric.eventually_nhds_iff.mp he1 + let p := min (δ/2) (1/4) + let q := min (ε/2) (1/4) + have hp : 0 < p := lt_min (by positivity) (by norm_num) + have hq : 0 < q := lt_min (by positivity) (by norm_num) + have hp4 : p ≤ 1/4 := min_le_right _ _ + have hq4 : q ≤ 1/4 := min_le_right _ _ + have hpd : p < δ := (min_le_left _ _).trans_lt (by linarith) + have hqe : q < ε := (min_le_left _ _).trans_lt (by linarith) + let u : unitInterval := ⟨p,hp.le,by linarith⟩ + let v : unitInterval := ⟨1-q,by linarith,by linarith⟩ + have hu : γ.extend p ∈ Metric.ball a ρ := hd (by simpa [Real.dist_eq,abs_of_pos hp] using hpd) + have hv : γ.extend (1-q) ∈ Metric.ball b σ := he (by + simpa [Real.dist_eq,abs_of_pos hq] using hqe) + rw [show γ.extend p=γ u from γ.extend_extends' u] at hu + rw [show γ.extend (1-q)=γ v from γ.extend_extends' v] at hv + exact ⟨u,v,hp,(by change p < 1-q; linarith),(by change 1-q < 1; linarith),hu,hv⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PathSubarc.lean b/lean/OAI/Combinatorics/Crossing/PathSubarc.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3e6cc8145a59ab84a2d3bb96621cfcb69d247a1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PathSubarc.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.IntervalSegments +import Mathlib.Tactic.FunProp +import Mathlib.Tactic.FieldSimp + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem intervalSegment_injective (a b : unitInterval) (hab : a < b) : + Function.Injective (intervalSegment a b) := by + intro s t he + have hh := congrArg Subtype.val he + have hpos : 0 < b.val-a.val := sub_pos.mpr hab + apply Subtype.ext + change (1-s.val)*a.val+s.val*b.val=(1-t.val)*a.val+t.val*b.val at hh + have hz : (s.val-t.val)*(b.val-a.val)=0 := by nlinarith [hh] + exact sub_eq_zero.mp ((mul_eq_zero.mp hz).resolve_right (ne_of_gt hpos)) + +theorem intervalSegment_surjective_interval (a b : unitInterval) (hab : a < b) + (t : unitInterval) (ht : a ≤ t ∧ t ≤ b) : ∃ u : unitInterval, intervalSegment a b u=t := by + have hd : 0 < b.val-a.val := sub_pos.mpr hab + have ht0 : 0 ≤ (t.val-a.val)/(b.val-a.val) := div_nonneg (sub_nonneg.mpr ht.1) hd.le + have ht1 : (t.val-a.val)/(b.val-a.val) ≤ 1 := + (div_le_one hd).mpr (sub_le_sub_right (show t.val ≤ b.val from ht.2) a.val) + refine ⟨⟨(t.val-a.val)/(b.val-a.val),ht0,ht1⟩,?_⟩ + apply Subtype.ext + change (1-(t.val-a.val)/(b.val-a.val))*a.val+((t.val-a.val)/(b.val-a.val))*b.val=t.val + field_simp + ring + +def pathSubarc {a b : Plane} (γ : Path a b) (u v : unitInterval) : Path (γ u) (γ v) where + toFun := fun t => γ (intervalSegment u v t) + continuous_toFun := by + apply γ.continuous.comp + unfold intervalSegment + fun_prop + source' := by simp [intervalSegment] + target' := by simp [intervalSegment] + +theorem pathSubarc_injective {a b : Plane} (γ : Path a b) (hγ : Function.Injective γ) + (u v : unitInterval) (huv : u < v) : Function.Injective (pathSubarc γ u v) := + hγ.comp (intervalSegment_injective u v huv) + +theorem pathSubarc_range {a b : Plane} (γ : Path a b) (u v : unitInterval) (huv : u < v) : + Set.range (pathSubarc γ u v)=γ '' Set.Icc u v := by + apply Set.Subset.antisymm + · rintro x ⟨t,rfl⟩ + exact ⟨intervalSegment u v t,intervalSegment_between u v t huv.le,rfl⟩ + · rintro x ⟨t,ht,rfl⟩ + obtain ⟨s,hs⟩ := intervalSegment_surjective_interval u v huv t ht + exact ⟨s,congrArg γ hs⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PeriodicPolygon.lean b/lean/OAI/Combinatorics/Crossing/PeriodicPolygon.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf525a345dab30764e8bbbe553b2e27a5bdbd214 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PeriodicPolygon.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.PolygonalWalks + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def cyclicIndex (n : ℕ) (hn : 0 < n) (i : ℕ) : Fin n := ⟨i%n,Nat.mod_lt i hn⟩ + +def periodicPolygon (n : ℕ) (hn : 0 < n) (p : Fin n → Plane) (i : ℕ) : Plane := p (cyclicIndex n hn i) + +theorem cyclicIndex_of_lt (n : ℕ) (hn : 0 < n) (i : ℕ) (hi : i offsetParameter (node i) (scale i*t) + let minus : ι → ℝ := fun i => offsetParameter (node i) (scale i*(-t)) + have hp (i : ι) := hprop i (scale i*t) (hbound t hbt i) + have hm (i : ι) := hprop i (scale i*(-t)) (hbound (-t) hbmt i) + have hpnear (i : ι) : |plus i-node i| < ε := (hp i).2.1 + have hmnear (i : ι) : |minus i-node i| < ε := (hm i).2.1 + have hstraddle (i : ι) : (plus i C.shiftedPort j e ε)) + (hab : a ≠ b) (hcd : c ≠ d) : + SegmentPairTransverse (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j c ε) (C.shiftedPort j d ε) := + round_circle_chords_transverse (D.vertex j) _ _ _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) + (C.shiftedPort_circle j c ε (hsmall c)) (C.shiftedPort_circle j d ε (hsmall d)) + ((C.port_injective j).ne hab) (hinj.ne hcd) (hsep a c) (hsep a d) (hsep b c) (hsep b d) + +theorem chord_connector_disjoint (j : BipartiteVertex m n) (a b e : IncidentEdges j) + (ε : ℝ) (hne : ε ≠ 0) (hsmall : |V.spokeScale j e*ε|<1) (hab : a ≠ b) + (ha : V.spokePort j a ≠ C.shiftedPort j e ε) (hb : V.spokePort j b ≠ C.shiftedPort j e ε) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j e ε) (C.tangentPort j e ε) := by + have hunit (f : IncidentEdges j) : squaredLength (circlePoint (C.node j f))=1 := circlePoint_on_unit_circle _ + have haq : circlePoint (C.node j a) ≠ circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε) := by + intro he + apply ha + rw [← C.point_eq j a] + exact congrArg (similarityPoint (D.vertex j) (C.frame j)) he + have hbq : circlePoint (C.node j b) ≠ circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε) := by + intro he + apply hb + rw [← C.point_eq j b] + exact congrArg (similarityPoint (D.vertex j) (C.frame j)) he + have hd := unit_chord_connector_disjoint (circlePoint (C.node j a)) (circlePoint (C.node j b)) + (circlePoint (C.node j e)) (hunit a) (hunit b) (hunit e) + (fun he => hab (C.node_injective j (circlePoint_injective he))) + (V.spokeScale j e*ε) hsmall (mul_ne_zero (V.spokeScale_ne_zero j e) hne) haq hbq + rintro ⟨s,hs,t,ht,he⟩ + apply hd + refine ⟨s,hs,t,ht,?_⟩ + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [similarityPoint_segment,C.point_eq,← C.tangentPort_eq,shiftedPort] using he + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PlanarDeterminant.lean b/lean/OAI/Combinatorics/Crossing/PlanarDeterminant.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f1a80df77986219247c4a8a095697126a5ed793 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PlanarDeterminant.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.Crossing.PlanarSegments + +namespace OAI + +namespace Zarankiewicz + +theorem det2_add_left (u v w : Plane) : det2 (u+v) w = det2 u w+det2 v w := by + dsimp [det2] + ring + +theorem det2_add_right (u v w : Plane) : det2 u (v+w) = det2 u v+det2 u w := by + dsimp [det2] + ring + +theorem det2_sub_left (u v w : Plane) : det2 (u-v) w = det2 u w-det2 v w := by + dsimp [det2] + ring + +theorem det2_sub_right (u v w : Plane) : det2 u (v-w) = det2 u v-det2 u w := by + dsimp [det2] + ring + +theorem det2_smul_left (r : ℝ) (u v : Plane) : det2 (r • u) v = r*det2 u v := by + dsimp [det2] + ring + +theorem det2_smul_right (r : ℝ) (u v : Plane) : det2 u (r • v) = r*det2 u v := by + dsimp [det2] + ring + +@[simp] theorem det2_self (u : Plane) : det2 u u = 0 := by + dsimp [det2] + ring + +@[simp] theorem det2_zero_left (u : Plane) : det2 0 u = 0 := by simp [det2] +@[simp] theorem det2_zero_right (u : Plane) : det2 u 0 = 0 := by simp [det2] + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PlanarSegments.lean b/lean/OAI/Combinatorics/Crossing/PlanarSegments.lean new file mode 100644 index 0000000000000000000000000000000000000000..f48c81d71347f5c2be0e53e8ed74f7baea0590d2 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PlanarSegments.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.LinearCombination + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical + +def det2 (u v : Plane) : ℝ := u.1*v.2-u.2*v.1 + +def segmentPoint (a b : Plane) (t : ℝ) : Plane := (1-t) • a+t • b + +def openSegmentTrace (a b : Plane) : Set Plane := segmentPoint a b '' Set.Ioo 0 1 + +def SegmentsCrossProperly (a b c d : Plane) : Prop := + det2 (b-a) (d-c) ≠ 0 ∧ + ∃ t ∈ Set.Ioo (0 : ℝ) 1, ∃ u ∈ Set.Ioo (0 : ℝ) 1, + segmentPoint a b t = segmentPoint c d u + +def segmentCrossingSign (a b c d : Plane) : ℝ := + if SegmentsCrossProperly a b c d then + (if 0 < det2 (b-a) (d-c) then 1 else -1) else 0 + +@[simp] theorem segmentPoint_zero (a b : Plane) : segmentPoint a b 0 = a := by + simp [segmentPoint] + +@[simp] theorem segmentPoint_one (a b : Plane) : segmentPoint a b 1 = b := by + simp [segmentPoint] + +theorem segmentPoint_reverse (a b : Plane) (t : ℝ) : + segmentPoint b a (1-t) = segmentPoint a b t := by + simp [segmentPoint, add_comm] + +theorem det2_swap (u v : Plane) : det2 v u = -det2 u v := by + simp only [det2] + ring + +theorem det2_neg_left (u v : Plane) : det2 (-u) v = -det2 u v := by + simp [det2] + ring + +theorem det2_neg_right (u v : Plane) : det2 u (-v) = -det2 u v := by + simp [det2] + ring + +theorem segment_intersection_parameters_unique (a b c d : Plane) + (hn : det2 (b-a) (d-c) ≠ 0) (t u t' u' : ℝ) + (h : segmentPoint a b t = segmentPoint c d u) + (h' : segmentPoint a b t' = segmentPoint c d u') : t = t' ∧ u = u' := by + have h₁ := congrArg Prod.fst h + have h₂ := congrArg Prod.snd h + have h₁' := congrArg Prod.fst h' + have h₂' := congrArg Prod.snd h' + change (1-t)*a.1+t*b.1 = (1-u)*c.1+u*d.1 at h₁ + change (1-t)*a.2+t*b.2 = (1-u)*c.2+u*d.2 at h₂ + change (1-t')*a.1+t'*b.1 = (1-u')*c.1+u'*d.1 at h₁' + change (1-t')*a.2+t'*b.2 = (1-u')*c.2+u'*d.2 at h₂' + have ht : (t-t') * det2 (b-a) (d-c) = 0 := by + dsimp [det2] + linear_combination (d.2-c.2)*h₁ - (d.1-c.1)*h₂ - (d.2-c.2)*h₁' + (d.1-c.1)*h₂' + have hu : (u-u') * det2 (b-a) (d-c) = 0 := by + dsimp [det2] + linear_combination (b.2-a.2)*h₁ - (b.1-a.1)*h₂ - (b.2-a.2)*h₁' + (b.1-a.1)*h₂' + exact ⟨sub_eq_zero.mp ((mul_eq_zero.mp ht).resolve_right hn), + sub_eq_zero.mp ((mul_eq_zero.mp hu).resolve_right hn)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonComposition.lean b/lean/OAI/Combinatorics/Crossing/PolygonComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..755ddc26548cdfeccf88b4aa7c4f441609541d32 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonComposition.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.Crossing.PolygonalWalks +import Mathlib.Algebra.BigOperators.Intervals + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +def joinedSequence (v w : ℕ → Plane) (n : ℕ) (i : ℕ) : Plane := + if i ∑ j ∈ Finset.range m, + segmentCrossingSign (v i) (v (i+1)) (w j) (w (j+1))) n + rw [← he,← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i hi + have hin := Finset.mem_range.mp hi + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro j hj + have h₀ : n-i=n-1-i+1 := by omega + have h₁ : n-(i+1)=n-1-i := by omega + simp only [reversedSequence,h₀,h₁] + exact segmentCrossingSign_reverse_left _ _ _ _ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonStability.lean b/lean/OAI/Combinatorics/Crossing/PolygonStability.lean new file mode 100644 index 0000000000000000000000000000000000000000..bcd6da7a0b561c7dd48254119ca515594f458f18 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonStability.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.Crossing.SegmentContinuity +import OAI.Combinatorics.Crossing.PolygonalWalks +import OAI.Combinatorics.Crossing.FiniteSeparation + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical BigOperators + +theorem exists_polygon_intersection_stability_radius (v w : ℕ → Plane) (n m : ℕ) + (h : ∀ i : Fin n, ∀ j : Fin m, + SegmentPairTransverse (v i.val) (v (i.val+1)) (w j.val) (w (j.val+1))) : + ∃ ε : ℝ, 0 < ε ∧ ∀ v' : ℕ → Plane, + (∀ i : Fin (n+1), dist (v' i.val) (v i.val) < ε) → + polygonIntersection v' w n m = polygonIntersection v w n m := by + have hh : ∀ ij : Fin n × Fin m, ∃ ε : ℝ, 0 < ε ∧ + ∀ ab : Plane × Plane, dist ab (v ij.1.val,v (ij.1.val+1)) < ε → + segmentCrossingSign ab.1 ab.2 (w ij.2.val) (w (ij.2.val+1)) = + segmentCrossingSign (v ij.1.val) (v (ij.1.val+1)) (w ij.2.val) (w (ij.2.val+1)) := by + intro ij + obtain ⟨ε,hε,he⟩ := Metric.eventually_nhds_iff.mp + (eventually_segmentCrossingSign _ _ _ _ (h ij.1 ij.2)) + exact ⟨ε,hε,fun ab hab => he hab⟩ + choose radius hpos hstable using hh + obtain ⟨ε,hε,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun ij _ => hpos ij) + refine ⟨ε,hε,?_⟩ + intro v' hv' + unfold polygonIntersection + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + have hin := Finset.mem_range.mp hi + have hjm := Finset.mem_range.mp hj + let ii : Fin n := ⟨i,hin⟩ + let jj : Fin m := ⟨j,hjm⟩ + apply hstable (ii,jj) (v' i,v' (i+1)) + rw [Prod.dist_eq] + exact (max_lt (hv' ⟨i,by omega⟩) (hv' ⟨i+1,by omega⟩)).trans (hbound (ii,jj) (Finset.mem_univ _)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonTransversalityStability.lean b/lean/OAI/Combinatorics/Crossing/PolygonTransversalityStability.lean new file mode 100644 index 0000000000000000000000000000000000000000..823ecafbe85b71bb8f0e7ce0aaba2e604bc2c5c5 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonTransversalityStability.lean @@ -0,0 +1,43 @@ +import OAI.Combinatorics.Crossing.TransversalityStability +import OAI.Combinatorics.Crossing.PolygonStability + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical + +theorem exists_polygon_transversality_radius (v w : ℕ → Plane) (n m : ℕ) + (h : ∀ i : Fin n, ∀ j : Fin m, + SegmentPairTransverse (v i.val) (v (i.val+1)) (w j.val) (w (j.val+1))) : + ∃ ε : ℝ, 0 < ε ∧ ∀ v' : ℕ → Plane, + (∀ i : Fin (n+1), dist (v' i.val) (v i.val) < ε) → + (∀ i : Fin n, ∀ j : Fin m, + SegmentPairTransverse (v' i.val) (v' (i.val+1)) (w j.val) (w (j.val+1))) ∧ + polygonIntersection v' w n m = polygonIntersection v w n m := by + have hh : ∀ ij : Fin n × Fin m, ∃ ε : ℝ, 0 < ε ∧ + ∀ ab : Plane × Plane, dist ab (v ij.1.val,v (ij.1.val+1)) < ε → + SegmentPairTransverse ab.1 ab.2 (w ij.2.val) (w (ij.2.val+1)) := by + intro ij + obtain ⟨ε,hε,he⟩ := Metric.eventually_nhds_iff.mp + (eventually_segmentPairTransverse _ _ _ _ (h ij.1 ij.2)) + exact ⟨ε,hε,fun ab hab => he hab⟩ + choose radius hpos hstable using hh + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun ij _ => hpos ij) + obtain ⟨η,hη,hcount⟩ := exists_polygon_intersection_stability_radius v w n m h + refine ⟨min δ η,lt_min hδ hη,?_⟩ + intro v' hv' + constructor + · intro i j + apply hstable (i,j) (v' i.val,v' (i.val+1)) + rw [Prod.dist_eq] + have h₀ := (hv' ⟨i.val,by omega⟩).trans_le (min_le_left δ η) + have h₁ := (hv' ⟨i.val+1,by omega⟩).trans_le (min_le_left δ η) + exact (max_lt h₀ h₁).trans (hbound (i,j) (Finset.mem_univ _)) + · exact hcount v' (fun i => (hv' i).trans_le (min_le_right δ η)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalArcInjective.lean b/lean/OAI/Combinatorics/Crossing/PolygonalArcInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..0289ed679cf1d3e18d381e0d269a0162d068fa8c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalArcInjective.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.MinimumChainGeometry +import OAI.Combinatorics.Crossing.PathConcatenationInjective + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem polygonalArcPath_range_piece (v : ℕ → Plane) : + (n : ℕ) → 0 < n → ∀ x ∈ Set.range (polygonalArcPath v n), + ∃ i, i < n ∧ x ∈ segment ℝ (v i) (v (i+1)) + | 0, hn, _, _ => by omega + | 1, _, x, hx => by + refine ⟨0,by omega,?_⟩ + simpa only [polygonalArcPath,Path.range_segment] using hx + | n+2, _, x, hx => by + rw [polygonalArcPath,Path.trans_range] at hx + rcases hx with hx | hx + · obtain ⟨i,hi,hh⟩ := polygonalArcPath_range_piece v (n+1) (by omega) x hx + exact ⟨i,by omega,hh⟩ + · exact ⟨n+1,by omega,by simpa only [Path.range_segment] using hx⟩ + +theorem polygonalArcPath_injective (v : ℕ → Plane) : (n : ℕ) → 0 < n → + (∀ i, i < n → v i ≠ v (i+1)) → + (∀ i j, i < j → j < n → ∀ x, + x ∈ segment ℝ (v i) (v (i+1)) → x ∈ segment ℝ (v j) (v (j+1)) → + j=i+1 ∧ x=v j) → Function.Injective (polygonalArcPath v n) + | 0, hn, _, _ => by omega + | 1, _, hn, _ => Path.segment_injective_of_ne (hn 0 (by omega)) + | n+2, _, hn, hm => by + apply path_trans_injective + · exact polygonalArcPath_injective v (n+1) (by omega) + (fun i hi => hn i (by omega)) (fun i j hij hj => hm i j hij (by omega)) + · exact Path.segment_injective_of_ne (hn (n+1) (by omega)) + · intro x hx hy + obtain ⟨i,hi,hh⟩ := polygonalArcPath_range_piece v (n+1) (by omega) x hx + rw [Path.range_segment] at hy + exact (hm i (n+1) hi (by omega) x hh hy).2 + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +theorem minimum_path_injective (P : PolygonalChain O a b) (hab : a ≠ b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) : Function.Injective P.path := by + have hp : 0 < P.pieces := by + by_contra h + have hz : P.pieces=0 := by omega + exact hab (P.first.symm.trans (hz ▸ P.last)) + change Function.Injective (polygonalArcPath P.vertices P.pieces) + apply polygonalArcPath_injective P.vertices P.pieces hp + · intro i hi + exact P.minimum_vertices_ne hmin i (i+1) (by omega) (by omega) + · intro i j hij hj x hx hy + by_cases he : j=i+1 + · subst j + exact ⟨rfl,P.minimum_adjacent_intersection hmin i (by omega) hx hy⟩ + · exact False.elim ((Set.disjoint_left.mp (P.minimum_nonadjacent_disjoint hmin i j (by omega) hj)) hx hy) + +end PolygonalChain + +theorem exists_simple_polygonalChain_of_path {a b : Plane} (hab : a ≠ b) (γ : Path a b) + (O : Set Plane) (hO : IsOpen O) (hγ : ∀ t, γ t ∈ O) : + ∃ P : PolygonalChain O a b, Function.Injective P.path ∧ Set.range P.path ⊆ O ∧ + (∀ i, i+2 ≤ P.pieces → + det2 (P.vertices (i+1)-P.vertices i) (P.vertices (i+2)-P.vertices (i+1)) ≠ 0) := by + obtain ⟨P,hP,hmin⟩ := exists_minimum_polygonalChain_of_path γ O hO hγ + exact ⟨P,P.minimum_path_injective hab hmin,hP,P.minimum_bend_det_ne_zero hmin⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalBoundaryReplacement.lean b/lean/OAI/Combinatorics/Crossing/PolygonalBoundaryReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..b769012ad1a55f352ea9c98799aaa10748be0cc4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalBoundaryReplacement.lean @@ -0,0 +1,49 @@ +import OAI.Combinatorics.Crossing.SimultaneousPolygonalReplacement + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def PolygonalChain.widen {S T : Set Plane} {a b : Plane} (P : PolygonalChain S a b) + (hST : S ⊆ T) : PolygonalChain T a b where + pieces := P.pieces + vertices := P.vertices + first := P.first + last := P.last + start_mem := hST P.start_mem + inside := fun i hi => (P.inside i hi).trans hST + +theorem simple_path_interior_of_range_insert {a b : Plane} (γ : Path a b) + (hinj : Function.Injective γ) (O : Set Plane) + (hrange : Set.range γ ⊆ insert a (insert b O)) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : γ t ∈ O := by + rcases hrange ⟨t,rfl⟩ with ha | hb | ho + · have he := hinj (ha.trans γ.source.symm) + exact False.elim (ht.1.ne he.symm) + · have he := hinj (hb.trans γ.target.symm) + exact False.elim (ht.2.ne he) + · exact ho + +theorem polygonal_replacement_with_spurs (O : Set Plane) (hO : IsOpen O) + (a a' b' b : Plane) (hab : a ≠ b) (γ : Path a' b') + (hγ : ∀ t, γ t ∈ O) + (ha : segment ℝ a a' ⊆ insert a (insert b O)) + (hb : segment ℝ b' b ⊆ insert a (insert b O)) : + ∃ P : PolygonalChain (insert a (insert b O)) a b, + Function.Injective P.path ∧ + (∀ t : unitInterval, t ∈ Set.Ioo (0 : unitInterval) 1 → P.path t ∈ O) := by + obtain ⟨Q⟩ := nonempty_polygonalChain_of_path γ O hO hγ + let S := insert a (insert b O) + let Q' : PolygonalChain S a' b' := Q.widen (fun _ hx => Or.inr (Or.inr hx)) + let L : PolygonalChain S a a' := PolygonalChain.single S a a' (Or.inl rfl) ha + let R : PolygonalChain S b' b := PolygonalChain.single S b' b + (Or.inr (Or.inr (by simpa using hγ 1))) hb + obtain ⟨P,hP,hR⟩ := exists_simple_polygonalChain hab ⟨(L.join Q').join R⟩ + exact ⟨P,hP,fun t ht => simple_path_interior_of_range_insert P.path hP O hR t ht⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChainComposition.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChainComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..223b9417946eeab18150aa56b670b9753bfbae7a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChainComposition.lean @@ -0,0 +1,50 @@ +import OAI.Combinatorics.Crossing.PolygonComposition +import OAI.Combinatorics.Crossing.PolygonalChainOperations +import OAI.Combinatorics.Crossing.ClosedPolygonIntersection + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b c : Plane} + +def reverse (P : PolygonalChain O a b) : PolygonalChain O b a where + pieces := P.pieces + vertices := reversedSequence P.vertices P.pieces + first := by simpa only [reversedSequence,Nat.sub_zero] using P.last + last := by simpa only [reversedSequence,Nat.sub_self] using P.first + start_mem := P.path_range_subset ⟨1,P.path.target⟩ + inside := by + intro i hi + have h₀ : P.pieces-i=P.pieces-1-i+1 := by omega + have h₁ : P.pieces-(i+1)=P.pieces-1-i := by omega + simp only [reversedSequence,h₀,h₁] + rw [segment_symm] + exact P.inside (P.pieces-1-i) (by omega) + +theorem intersection_join_left (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (w : ℕ → Plane) (k : ℕ) : + polygonIntersection (P.join Q).vertices w (P.join Q).pieces k= + polygonIntersection P.vertices w P.pieces k+polygonIntersection Q.vertices w Q.pieces k := + polygonIntersection_join_left _ _ _ _ _ _ (P.last.trans Q.first.symm) + +theorem intersection_join_right (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (w : ℕ → Plane) (k : ℕ) : + polygonIntersection w (P.join Q).vertices k (P.join Q).pieces= + polygonIntersection w P.vertices k P.pieces+polygonIntersection w Q.vertices k Q.pieces := + polygonIntersection_join_right _ _ _ _ _ _ (P.last.trans Q.first.symm) + +theorem intersection_reverse_left (P : PolygonalChain O a b) (w : ℕ → Plane) (k : ℕ) : + polygonIntersection P.reverse.vertices w P.reverse.pieces k = -polygonIntersection P.vertices w P.pieces k := + polygonIntersection_reverse_left _ _ _ _ + +theorem intersection_reverse_right (P : PolygonalChain O a b) (w : ℕ → Plane) (k : ℕ) : + polygonIntersection w P.reverse.vertices k P.reverse.pieces = -polygonIntersection w P.vertices k P.pieces := by + rw [polygonIntersection_swap,P.intersection_reverse_left,polygonIntersection_swap] + ring + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChainExistence.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChainExistence.lean new file mode 100644 index 0000000000000000000000000000000000000000..e89ea5437265cc89d094df06da3066190bfe2c5f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChainExistence.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.Crossing.PolygonalChains + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem polygonalArcPath_range_subset (v : ℕ → Plane) (O : Set Plane) (h0 : v 0 ∈ O) : + (n : ℕ) → (∀ i, i < n → segment ℝ (v i) (v (i+1)) ⊆ O) → + Set.range (polygonalArcPath v n) ⊆ O + | 0, _ => by rintro x ⟨t,rfl⟩; exact h0 + | 1, h => by + rw [polygonalArcPath,Path.range_segment] + exact h 0 (by omega) + | n+2, h => by + rw [polygonalArcPath,Path.trans_range,Set.union_subset_iff] + refine ⟨polygonalArcPath_range_subset v O h0 (n+1) (fun i hi => h i (by omega)),?_⟩ + rw [Path.range_segment] + exact h (n+1) (by omega) + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +theorem path_range_subset (P : PolygonalChain O a b) : Set.range P.path ⊆ O := by + change Set.range (polygonalArcPath P.vertices P.pieces) ⊆ O + exact polygonalArcPath_range_subset P.vertices O (by rw [P.first]; exact P.start_mem) P.pieces P.inside + +end PolygonalChain + +theorem exists_minimum_polygonalChain {O : Set Plane} {a b : Plane} + (h : Nonempty (PolygonalChain O a b)) : + ∃ P : PolygonalChain O a b, ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces := by + classical + obtain ⟨P⟩ := h + have hex : ∃ n : ℕ, ∃ Q : PolygonalChain O a b, Q.pieces=n := ⟨P.pieces,P,rfl⟩ + obtain ⟨Q,hQ⟩ := Nat.find_spec hex + refine ⟨Q,?_⟩ + intro R + rw [hQ] + exact Nat.find_min' hex ⟨R,rfl⟩ + +theorem exists_minimum_polygonalChain_of_path {a b : Plane} (γ : Path a b) (O : Set Plane) + (hO : IsOpen O) (hγ : ∀ t, γ t ∈ O) : + ∃ P : PolygonalChain O a b, Set.range P.path ⊆ O ∧ + ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces := by + obtain ⟨P,hP⟩ := exists_minimum_polygonalChain (nonempty_polygonalChain_of_path γ O hO hγ) + exact ⟨P,P.path_range_subset,hP⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChainOperations.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChainOperations.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4bcc95304e95ce7489b11a3d4448a850ed839c0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChainOperations.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.Crossing.PolygonalChainExistence +import OAI.Combinatorics.Crossing.PolygonComposition + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b c : Plane} + +theorem vertex_mem (P : PolygonalChain O a b) (i : ℕ) (hi : i ≤ P.pieces) : P.vertices i ∈ O := by + by_cases h0 : i=0 + · subst i + rw [P.first] + exact P.start_mem + · have hp : 0 < i := by omega + have hh := P.inside (i-1) (by omega) (right_mem_segment ℝ (P.vertices (i-1)) (P.vertices (i-1+1))) + simpa [Nat.sub_add_cancel (show 1 ≤ i by omega)] using hh + +def single (O : Set Plane) (a b : Plane) (ha : a ∈ O) (h : segment ℝ a b ⊆ O) : PolygonalChain O a b where + pieces := 1 + vertices := fun i => if i=0 then a else b + first := by simp + last := by simp + start_mem := ha + inside := by + intro i hi + have he : i = 0 := by omega + subst i + simpa using h + +def take (P : PolygonalChain O a b) (k : ℕ) (hk : k ≤ P.pieces) : PolygonalChain O a (P.vertices k) where + pieces := k + vertices := P.vertices + first := P.first + last := rfl + start_mem := P.start_mem + inside := fun i hi => P.inside i (by omega) + +def drop (P : PolygonalChain O a b) (k : ℕ) (hk : k ≤ P.pieces) : PolygonalChain O (P.vertices k) b where + pieces := P.pieces-k + vertices := fun i => P.vertices (k+i) + first := by simp + last := by simpa [Nat.add_sub_of_le hk] using P.last + start_mem := P.vertex_mem k hk + inside := by + intro i hi + simpa [Nat.add_assoc] using P.inside (k+i) (by omega) + +def join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) : PolygonalChain O a c where + pieces := P.pieces+Q.pieces + vertices := joinedSequence P.vertices Q.vertices P.pieces + first := (joinedSequence_left _ _ _ (P.last.trans Q.first.symm) 0 (Nat.zero_le _)).trans P.first + last := (joinedSequence_right _ _ P.pieces Q.pieces).trans Q.last + start_mem := P.start_mem + inside := by + intro i hi + have hglue : P.vertices P.pieces=Q.vertices 0 := P.last.trans Q.first.symm + by_cases hin : i < P.pieces + · rw [joinedSequence_left _ _ _ hglue i (by omega),joinedSequence_left _ _ _ hglue (i+1) (by omega)] + exact P.inside i hin + · have hbase : i=P.pieces+(i-P.pieces) := by omega + have hnext : i+1=P.pieces+((i-P.pieces)+1) := by omega + have h₀ : joinedSequence P.vertices Q.vertices P.pieces i = Q.vertices (i-P.pieces) := by + conv_lhs => rw [hbase] + exact joinedSequence_right _ _ _ _ + have h₁ : joinedSequence P.vertices Q.vertices P.pieces (i+1) = Q.vertices ((i-P.pieces)+1) := by + rw [hnext, joinedSequence_right] + rw [h₀,h₁] + exact Q.inside (i-P.pieces) (by omega) + +@[simp] theorem pieces_single (ha : a ∈ O) (h : segment ℝ a b ⊆ O) : (single O a b ha h).pieces=1 := rfl +@[simp] theorem pieces_take (P : PolygonalChain O a b) (k : ℕ) (hk : k ≤ P.pieces) : (P.take k hk).pieces=k := rfl +@[simp] theorem pieces_drop (P : PolygonalChain O a b) (k : ℕ) (hk : k ≤ P.pieces) : (P.drop k hk).pieces=P.pieces-k := rfl +@[simp] theorem pieces_join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) : (P.join Q).pieces=P.pieces+Q.pieces := rfl + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChainShortcuts.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChainShortcuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ab08fc3b3bc0d339894d44e7b5b66fce64418c4 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChainShortcuts.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.Crossing.PolygonalChainOperations + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b : Plane} + +def withEndpoints (P : PolygonalChain O a b) {a' b' : Plane} + (ha : a'=a) (hb : b'=b) : PolygonalChain O a' b' where + pieces := P.pieces + vertices := P.vertices + first := P.first.trans ha.symm + last := P.last.trans hb.symm + start_mem := ha.symm ▸ P.start_mem + inside := P.inside + +theorem minimum_shortcut_bound (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i j : ℕ) (hij : i ≤ j) (hj : j ≤ P.pieces) + (Q : PolygonalChain O (P.vertices i) (P.vertices j)) : j-i ≤ Q.pieces := by + have hh := hmin (((P.take i (by omega)).join Q).join (P.drop j hj)) + simp only [pieces_join,pieces_take,pieces_drop] at hh + omega + +theorem minimum_vertices_ne (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i j : ℕ) (hij : i < j) (hj : j ≤ P.pieces) : P.vertices i ≠ P.vertices j := by + intro he + let Q := (point O (P.vertices i) (P.vertex_mem i (by omega))).withEndpoints rfl he.symm + have hh := P.minimum_shortcut_bound hmin i j (by omega) hj Q + change j-i ≤ 0 at hh + omega + +theorem minimum_nonadjacent_disjoint (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i j : ℕ) (hij : i+1 < j) (hj : j < P.pieces) : + Disjoint (segment ℝ (P.vertices i) (P.vertices (i+1))) + (segment ℝ (P.vertices j) (P.vertices (j+1))) := by + apply Set.disjoint_left.mpr + intro x hxi hxj + have hleft : segment ℝ (P.vertices i) x ⊆ O := + ((convex_segment (𝕜 := ℝ) _ _).segment_subset (left_mem_segment ℝ _ _) hxi).trans + (P.inside i (by omega)) + have hright : segment ℝ x (P.vertices (j+1)) ⊆ O := + ((convex_segment (𝕜 := ℝ) _ _).segment_subset hxj (right_mem_segment ℝ _ _)).trans + (P.inside j hj) + let Q := (single O (P.vertices i) x (P.vertex_mem i (by omega)) hleft).join + (single O x (P.vertices (j+1)) (P.inside i (by omega) hxi) hright) + have hh := P.minimum_shortcut_bound hmin i (j+1) (by omega) (by omega) Q + change j+1-i ≤ 1+1 at hh + omega + +theorem minimum_two_step_not_subset (P : PolygonalChain O a b) + (hmin : ∀ Q : PolygonalChain O a b, P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) : + ¬ segment ℝ (P.vertices i) (P.vertices (i+2)) ⊆ O := by + intro h + have hh := P.minimum_shortcut_bound hmin i (i+2) (by omega) hi + (single O (P.vertices i) (P.vertices (i+2)) (P.vertex_mem i (by omega)) h) + change i+2-i ≤ 1 at hh + omega + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChainTransversality.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChainTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..70b1067600a14c8a43e21b18402776d212df90c0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChainTransversality.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.PolygonalChainComposition + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O T : Set Plane} {a b c d e : Plane} + +def Transverse (P : PolygonalChain O a b) (Q : PolygonalChain T d e) : Prop := + ∀ i : Fin P.pieces, ∀ j : Fin Q.pieces, + SegmentPairTransverse (P.vertices i.val) (P.vertices (i.val+1)) + (Q.vertices j.val) (Q.vertices (j.val+1)) + +theorem transverse_swap (P : PolygonalChain O a b) (Q : PolygonalChain T d e) + (h : P.Transverse Q) : Q.Transverse P := + fun j i => segmentPairTransverse_swap _ _ _ _ (h i j) + +theorem transverse_join_left (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (hP : P.Transverse R) (hQ : Q.Transverse R) : + (P.join Q).Transverse R := by + intro i j + change SegmentPairTransverse (joinedSequence P.vertices Q.vertices P.pieces i.val) + (joinedSequence P.vertices Q.vertices P.pieces (i.val+1)) _ _ + have hi : i.val rw [he] + exact joinedSequence_right _ _ _ _ + have h₁ : joinedSequence P.vertices Q.vertices P.pieces (i.val+1)=Q.vertices (i.val-P.pieces+1) := by + rw [he',joinedSequence_right] + rw [h₀,h₁] + exact hQ ⟨i.val-P.pieces,by omega⟩ j + +theorem transverse_join_right (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (hP : R.Transverse P) (hQ : R.Transverse Q) : + R.Transverse (P.join Q) := + (P.join Q).transverse_swap R (P.transverse_join_left Q R (R.transverse_swap P hP) (R.transverse_swap Q hQ)) + +theorem closed_intersection_zero (P : PolygonalChain O a a) (Q : PolygonalChain T d d) + (h : P.Transverse Q) : polygonIntersection P.vertices Q.vertices P.pieces Q.pieces=0 := + closed_polygon_intersection_zero _ _ _ _ (P.last.trans P.first.symm) (Q.last.trans Q.first.symm) h + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalChains.lean b/lean/OAI/Combinatorics/Crossing/PolygonalChains.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1503e250d93ce5b9ca996cf61d7715ee6bc6072 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalChains.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.PolygonalReach + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def polygonalArcPath (v : ℕ → Plane) : (n : ℕ) → Path (v 0) (v n) + | 0 => Path.refl (v 0) + | 1 => Path.segment (v 0) (v 1) + | n+2 => (polygonalArcPath v (n+1)).trans (Path.segment (v (n+1)) (v (n+2))) + +structure PolygonalChain (O : Set Plane) (a b : Plane) where + pieces : ℕ + vertices : ℕ → Plane + first : vertices 0=a + last : vertices pieces=b + start_mem : a ∈ O + inside : ∀ i, i < pieces → segment ℝ (vertices i) (vertices (i+1)) ⊆ O + +namespace PolygonalChain +variable {O : Set Plane} {a b : Plane} + +def point (O : Set Plane) (a : Plane) (ha : a ∈ O) : PolygonalChain O a a where + pieces := 0 + vertices := fun _ => a + first := rfl + last := rfl + start_mem := ha + inside := by intro i hi; omega + +def append (P : PolygonalChain O a b) (c : Plane) (h : segment ℝ b c ⊆ O) : PolygonalChain O a c where + pieces := P.pieces+1 + vertices := fun i => if i ≤ P.pieces then P.vertices i else c + first := by simp [P.first] + last := by simp + start_mem := P.start_mem + inside := by + intro i hi + by_cases hin : i < P.pieces + · simpa only [ite_eq_left (show i ≤ P.pieces by omega),ite_eq_left (show i+1 ≤ P.pieces by omega)] using P.inside i hin + · have he : i=P.pieces := by omega + subst i + simpa [P.last] using h + +def path (P : PolygonalChain O a b) : Path a b := + (polygonalArcPath P.vertices P.pieces).cast P.first.symm P.last.symm + +end PolygonalChain + +theorem nonempty_polygonalChain_of_reach {O : Set Plane} {a b : Plane} + (ha : a ∈ O) (h : SegmentReach O a b) : Nonempty (PolygonalChain O a b) := by + induction h with + | refl => exact ⟨PolygonalChain.point O a ha⟩ + | @tail b c hab hbc ih => + obtain ⟨P⟩ := ih + exact ⟨P.append c hbc⟩ + +theorem nonempty_polygonalChain_of_path {a b : Plane} (γ : Path a b) (O : Set Plane) + (hO : IsOpen O) (hγ : ∀ t, γ t ∈ O) : Nonempty (PolygonalChain O a b) := by + exact nonempty_polygonalChain_of_reach (by simpa using hγ 0) (segmentReach_of_path γ O hO hγ) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalEndpointCasts.lean b/lean/OAI/Combinatorics/Crossing/PolygonalEndpointCasts.lean new file mode 100644 index 0000000000000000000000000000000000000000..74ce89e62a85574c22021954bc72869fd5d80367 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalEndpointCasts.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.Crossing.FinitePolygonalComposition + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalChain +variable {O : Set Plane} {a b a' b' : Plane} + +def castEndpoints (P : PolygonalChain O a b) (ha : a'=a) (hb : b'=b) : PolygonalChain O a' b' where + pieces := P.pieces + vertices := P.vertices + first := P.first.trans ha.symm + last := P.last.trans hb.symm + start_mem := ha.symm ▸ P.start_mem + inside := P.inside + +theorem castEndpoints_pieces (P : PolygonalChain O a b) (ha : a'=a) (hb : b'=b) : + (P.castEndpoints ha hb).pieces=P.pieces := rfl + +theorem castEndpoints_vertices (P : PolygonalChain O a b) (ha : a'=a) (hb : b'=b) : + (P.castEndpoints ha hb).vertices=P.vertices := rfl + +end Zarankiewicz.PolygonalChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalExterior.lean b/lean/OAI/Combinatorics/Crossing/PolygonalExterior.lean new file mode 100644 index 0000000000000000000000000000000000000000..71b1fa060660a5aad0581fad9fa205604df50513 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalExterior.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.Crossing.DrawingExteriorReplacement +import OAI.Combinatorics.Crossing.DiskFillingContainment + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +structure PolygonalExterior (C : DrawingPassages D) where + chain : ∀ i : C.ArcIndex, PolygonalChain Set.univ (C.arcStart i) (C.arcEnd i) + injective : ∀ i, Function.Injective (chain i).path + outside : ∀ i t, t ∈ Set.Ioo (0 : unitInterval) 1 → + (chain i).path t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius + disjoint : ∀ i j, i ≠ j → Disjoint (Set.range (chain i).path) (Set.range (chain j).path) + +theorem nonempty_polygonalExterior (C : DrawingPassages D) : Nonempty (PolygonalExterior C) := by + classical + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + obtain ⟨U,P,hU,hP,hout,hdisjoint⟩ := finite_exterior_arc_replacements + (fun x : DrawingMark D => x.val) C.radius C.radius_pos C.disks_disjoint + C.arcStartMark C.arcEndMark C.arcStart C.arcEnd C.arc_endpoints_ne + C.arc_start_on_circle C.arc_end_on_circle C.arc C.arcs_pairwise_disjoint C.arc_interior_outside + exact ⟨{ + chain := fun i => (P i).widen (Set.subset_univ _) + injective := hP + outside := hout + disjoint := hdisjoint }⟩ + +namespace PolygonalExterior +variable {C : DrawingPassages D} + +theorem outside_open_disks (E : PolygonalExterior C) (i : C.ArcIndex) (t : unitInterval) + (x : DrawingMark D) : C.radius^2 ≤ squaredLength ((E.chain i).path t-x.val) := by + by_cases ht0 : t=0 + · subst t + rw [(E.chain i).path.source] + exact C.portPoint_outside_open_disks (i,false) x + by_cases ht1 : t=1 + · subst t + rw [(E.chain i).path.target] + exact C.portPoint_outside_open_disks (i,true) x + exact (E.outside i t ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ x).le + +theorem avoids_new_vertices (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : C.ArcIndex) (t : unitInterval) (j : BipartiteVertex m n) : (E.chain i).path t ≠ v j := by + intro he + have h := E.outside_open_disks i t (C.vertexMark j) + rw [he] at h + exact (hv j).not_ge h + +theorem parameter_endpoint_of_mem_disk (E : PolygonalExterior C) (i : C.ArcIndex) + (t : unitInterval) (x : DrawingMark D) + (ht : (E.chain i).path t ∈ closedRoundDisk x.val C.radius) : t=0 ∨ t=1 := by + by_cases h0 : t=0 + · exact Or.inl h0 + by_cases h1 : t=1 + · exact Or.inr h1 + have h := E.outside i t ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm h0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) h1⟩ x + exact False.elim (h.not_ge ht) + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalNormalization.lean b/lean/OAI/Combinatorics/Crossing/PolygonalNormalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..26d05f3979bd5fcf77386bea44311686e162c435 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalNormalization.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.AssembledAdmissibleDrawing +import OAI.Combinatorics.Crossing.FiniteAffineCover + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem alternatingPath_hasFiniteAffineCover (a b : ℕ → Plane) (p : ∀ i, Path (a i) (b i)) + (q : ∀ i, Path (b i) (a (i+1))) (hp : ∀ i, HasFiniteAffineCover (p i)) + (hq : ∀ i, HasFiniteAffineCover (q i)) : + (k : ℕ) → HasFiniteAffineCover (alternatingPath a b p q k) + | 0 => hp 0 + | k+1 => ((alternatingPath_hasFiniteAffineCover a b p q hp hq k).trans (hq k)).trans (hp (k+1)) + +namespace PolygonalExterior +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} {C : DrawingPassages D} + +theorem middlePath_hasFiniteAffineCover (E : PolygonalExterior C) (e : BipartiteEdge m n) : + HasFiniteAffineCover (E.middlePath e) := + alternatingPath_hasFiniteAffineCover _ _ _ _ (fun i => (E.chain (C.orderedArc e i)).hasFiniteAffineCover) + (fun _ => hasFiniteAffineCover_segment _ _) _ + +theorem assembledEdge_hasFiniteAffineCover (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (e : BipartiteEdge m n) : + HasFiniteAffineCover (E.assembledEdge v e) := by + apply HasFiniteAffineCover.trans + · apply HasFiniteAffineCover.trans (hasFiniteAffineCover_segment _ _) + exact E.middlePath_hasFiniteAffineCover e + · simp only [endSpoke,Path.segment_symm] + exact hasFiniteAffineCover_segment _ _ + +end PolygonalExterior + +theorem finite_intersection_normalization {m n : ℕ} (D : FiniteIntersectionDrawing m n) : + ∃ D' : AdmissibleDrawing m n, + (∀ e, HasFiniteAffineCover (D'.edge e)) ∧ crossingCount D' ≤ finiteCrossingCount D := by + obtain ⟨C⟩ := nonempty_drawingPassages D + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembledEdge_hasFiniteAffineCover v, + E.assembled_crossingCount_le v hvinj hv hdet⟩ + +theorem polygonal_normalization {m n : ℕ} (D : AdmissibleDrawing m n) : + ∃ D' : AdmissibleDrawing m n, + (∀ e, HasFiniteAffineCover (D'.edge e)) ∧ crossingCount D' ≤ crossingCount D := by + obtain ⟨C⟩ := nonempty_drawingPassages D.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembledEdge_hasFiniteAffineCover v, + E.assembled_crossingCount_le v hvinj hv hdet⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalParametrization.lean b/lean/OAI/Combinatorics/Crossing/PolygonalParametrization.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bb93898c1da4107bafc670ad269e6485f0d21d6 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalParametrization.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.Crossing.IntervalSegments +import OAI.Combinatorics.Crossing.OffsetTrack +import OAI.Combinatorics.Crossing.SegmentContinuity + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +structure PolygonalParametrization {a b : Plane} (γ : Path a b) where + pieces : ℕ + knot : Fin (pieces+1) → unitInterval + increasing : StrictMono knot + first : knot 0=0 + last : knot (Fin.last pieces)=1 + affine : ∀ i : Fin pieces, ∀ t : unitInterval, + γ (intervalSegment (knot i.castSucc) (knot i.succ) t) = + segmentPoint (γ (knot i.castSucc)) (γ (knot i.succ)) t.val + +namespace PolygonalParametrization +variable {a b : Plane} {γ : Path a b} + +def vertices (P : PolygonalParametrization γ) (i : ℕ) : Plane := + γ (P.knot ⟨min i P.pieces,Nat.lt_succ_of_le (Nat.min_le_right _ _)⟩) + +theorem vertices_at (P : PolygonalParametrization γ) (i : Fin (P.pieces+1)) : + P.vertices i.val=γ (P.knot i) := by + unfold vertices + congr 2 + apply Fin.ext + exact Nat.min_eq_left (Nat.le_of_lt_succ i.isLt) + +theorem vertices_first (P : PolygonalParametrization γ) : P.vertices 0=a := by + have he := P.vertices_at (0 : Fin (P.pieces+1)) + rw [P.first] at he + simpa using he.trans γ.source + +theorem vertices_last (P : PolygonalParametrization γ) : P.vertices P.pieces=b := by + have he := P.vertices_at (Fin.last P.pieces) + rw [P.last] at he + simpa using he.trans γ.target + +theorem segment_formula (P : PolygonalParametrization γ) (i : Fin P.pieces) (t : unitInterval) : + γ (intervalSegment (P.knot i.castSucc) (P.knot i.succ) t)= + segmentPoint (P.vertices i.val) (P.vertices (i.val+1)) t.val := by + have he := P.affine i t + rw [← P.vertices_at i.castSucc,← P.vertices_at i.succ] at he + simpa using he + +theorem direction_ne_zero (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i : ℕ) (hi : i < P.pieces) : trackDirection P.vertices i ≠ 0 := by + let j : Fin P.pieces := ⟨i,hi⟩ + intro hzero + have he : P.vertices (i+1)=P.vertices i := sub_eq_zero.mp hzero + have h₀ : P.vertices i=γ (P.knot j.castSucc) := by simpa [j] using P.vertices_at j.castSucc + have h₁ : P.vertices (i+1)=γ (P.knot j.succ) := by simpa [j] using P.vertices_at j.succ + rw [h₁,h₀] at he + have hlt := P.increasing (show j.castSucc < j.succ by change i < i+1; omega) + exact hlt.ne (hγ he).symm + +theorem segments_disjoint_before (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i j : Fin P.pieces) (hij : i.val+1 < j.val) : + ¬ ClosedSegmentsMeet (P.vertices i.val) (P.vertices (i.val+1)) + (P.vertices j.val) (P.vertices (j.val+1)) := by + rintro ⟨s,hs,t,ht,he⟩ + let s' : unitInterval := ⟨s,hs⟩ + let t' : unitInterval := ⟨t,ht⟩ + have hparams := hγ ((P.segment_formula i s').trans (he.trans (P.segment_formula j t').symm)) + have hi := intervalSegment_between (P.knot i.castSucc) (P.knot i.succ) s' + (P.increasing.monotone (show i.castSucc ≤ i.succ by change i.val ≤ i.val+1; omega)) + have hj := intervalSegment_between (P.knot j.castSucc) (P.knot j.succ) t' + (P.increasing.monotone (show j.castSucc ≤ j.succ by change j.val ≤ j.val+1; omega)) + have hmid := P.increasing (show i.succ < j.castSucc from hij) + have hlt := hi.2.trans_lt (hmid.trans_le hj.1) + exact hlt.ne hparams + +theorem nonadjacent_segments_disjoint (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i j : Fin P.pieces) (hij : i.val+1 < j.val ∨ j.val+1 < i.val) : + ¬ ClosedSegmentsMeet (P.vertices i.val) (P.vertices (i.val+1)) + (P.vertices j.val) (P.vertices (j.val+1)) := by + rcases hij with hij | hji + · exact P.segments_disjoint_before hγ i j hij + · rintro ⟨s,hs,t,ht,he⟩ + exact P.segments_disjoint_before hγ j i hji ⟨t,ht,s,hs,he.symm⟩ + +end PolygonalParametrization +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalParametrizationCover.lean b/lean/OAI/Combinatorics/Crossing/PolygonalParametrizationCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..a76c4757484a2d344cb8f00d207ff13aa94c26cb --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalParametrizationCover.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.Crossing.OrderedKnotCover + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem PolygonalParametrization.hasFiniteAffineCover {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : HasFiniteAffineCover γ := by + classical + let f : Fin P.pieces → unitInterval × unitInterval := fun i => (P.knot i.castSucc,P.knot i.succ) + refine ⟨Finset.univ.image f,?_,?_,?_⟩ + · intro ab hab + obtain ⟨i,_,rfl⟩ := Finset.mem_image.mp hab + exact P.increasing (by change i.val < i.val+1; omega) + · intro t + obtain ⟨i,hi,hj⟩ := P.knot_cover t + exact ⟨f i,Finset.mem_image.mpr ⟨i,Finset.mem_univ _,rfl⟩,hi,hj⟩ + · intro ab hab t + obtain ⟨i,_,rfl⟩ := Finset.mem_image.mp hab + exact P.affine i t + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalReach.lean b/lean/OAI/Combinatorics/Crossing/PolygonalReach.lean new file mode 100644 index 0000000000000000000000000000000000000000..88248f1ff92e4f33301d35a2867813feea1d0d28 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalReach.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Analysis.Convex.PathConnected +import Mathlib.Analysis.Normed.Module.Convex +import Mathlib.Topology.Connected.Clopen +import Mathlib.Logic.Relation + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +def SegmentReach (O : Set Plane) (a b : Plane) : Prop := + Relation.ReflTransGen (fun x y => segment ℝ x y ⊆ O) a b + +theorem segmentReach_mem {O : Set Plane} {a b : Plane} (ha : a ∈ O) (h : SegmentReach O a b) : b ∈ O := by + induction h with + | refl => exact ha + | @tail b c hab hbc ih => exact hbc (right_mem_segment ℝ b c) + +theorem isOpen_segmentReach (O : Set Plane) (hO : IsOpen O) (a : Plane) (ha : a ∈ O) : + IsOpen {b | SegmentReach O a b} := by + apply Metric.isOpen_iff.mpr + intro b hb + obtain ⟨ε,hε,hball⟩ := Metric.mem_nhds_iff.mp (hO.mem_nhds (segmentReach_mem ha hb)) + refine ⟨ε,hε,?_⟩ + intro c hc + apply Relation.ReflTransGen.tail hb + exact ((convex_ball b ε).segment_subset (Metric.mem_ball_self hε) hc).trans hball + +theorem isOpen_non_segmentReach (O : Set Plane) (hO : IsOpen O) (a : Plane) : + IsOpen (O \ {b | SegmentReach O a b}) := by + apply Metric.isOpen_iff.mpr + intro b hb + obtain ⟨ε,hε,hball⟩ := Metric.mem_nhds_iff.mp (hO.mem_nhds hb.1) + refine ⟨ε,hε,?_⟩ + intro c hc + refine ⟨hball hc,?_⟩ + intro hreach + apply hb.2 + apply Relation.ReflTransGen.tail hreach + exact ((convex_ball b ε).segment_subset hc (Metric.mem_ball_self hε)).trans hball + +theorem segmentReach_of_path {a b : Plane} (γ : Path a b) (O : Set Plane) + (hO : IsOpen O) (hγ : ∀ t, γ t ∈ O) : SegmentReach O a b := by + have ha : a ∈ O := by simpa using hγ 0 + let A : Set unitInterval := {t | SegmentReach O a (γ t)} + have hopen : IsOpen A := (isOpen_segmentReach O hO a ha).preimage γ.continuous + have hcomp : IsOpen Aᶜ := by + have heq : Aᶜ = γ ⁻¹' (O \ {x | SegmentReach O a x}) := by + ext t + simp only [A,Set.mem_compl_iff,Set.mem_ofPred_eq,Set.mem_preimage,Set.mem_sdiff,hγ t,true_and] + rw [heq] + exact (isOpen_non_segmentReach O hO a).preimage γ.continuous + have hall : A=Set.univ := (show IsClopen A from ⟨by simpa using hcomp.isClosed_compl,hopen⟩).eq_univ ⟨0,by + change SegmentReach O a (γ 0) + rw [γ.source] + exact Relation.ReflTransGen.refl⟩ + have hb : (1 : unitInterval) ∈ A := by rw [hall]; trivial + change SegmentReach O a (γ 1) at hb + rwa [γ.target] at hb + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolygonalWalks.lean b/lean/OAI/Combinatorics/Crossing/PolygonalWalks.lean new file mode 100644 index 0000000000000000000000000000000000000000..d14ff34d798d2b0d0ff075fc395c359aca1f3227 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolygonalWalks.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.Crossing.SegmentSymmetries +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +def polygonalPath (v : ℕ → Plane) : (n : ℕ) → Path (v 0) (v n) + | 0 => Path.refl (v 0) + | n+1 => (polygonalPath v n).trans (Path.segment (v n) (v (n+1))) + +def polygonIntersection (v w : ℕ → Plane) (n m : ℕ) : ℝ := + ∑ i ∈ Finset.range n, ∑ j ∈ Finset.range m, + segmentCrossingSign (v i) (v (i+1)) (w j) (w (j+1)) + +theorem polygonIntersection_swap (v w : ℕ → Plane) (n m : ℕ) : + polygonIntersection w v m n = -polygonIntersection v w n m := by + unfold polygonIntersection + rw [Finset.sum_comm] + calc + _ = ∑ i ∈ Finset.range n, ∑ j ∈ Finset.range m, + -segmentCrossingSign (v i) (v (i+1)) (w j) (w (j+1)) := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + exact segmentCrossingSign_swap _ _ _ _ + _ = _ := by simp only [Finset.sum_neg_distrib] + +theorem telescoping_real_sum (f : ℕ → ℝ) (n : ℕ) : + (∑ i ∈ Finset.range n, (f i-f (i+1))) = f 0-f n := by + induction n with + | zero => simp + | succ n ih => + rw [Finset.sum_range_succ,ih] + ring + +def triangleSegmentIntersection (o a b c d : Plane) : ℝ := + segmentCrossingSign o a c d + segmentCrossingSign a b c d + segmentCrossingSign b o c d + +theorem polygon_cone_cancellation (v : ℕ → Plane) (n : ℕ) (hv : v n = v 0) + (o c d : Plane) : + (∑ i ∈ Finset.range n, triangleSegmentIntersection o (v i) (v (i+1)) c d) = + ∑ i ∈ Finset.range n, segmentCrossingSign (v i) (v (i+1)) c d := by + unfold triangleSegmentIntersection + have hrev : ∀ i, segmentCrossingSign (v (i+1)) o c d = -segmentCrossingSign o (v (i+1)) c d := + fun i => segmentCrossingSign_reverse_left o (v (i+1)) c d + simp only [hrev, Finset.sum_add_distrib] + have htele := telescoping_real_sum (fun i => segmentCrossingSign o (v i) c d) n + rw [hv,sub_self] at htele + rw [Finset.sum_sub_distrib] at htele + rw [Finset.sum_neg_distrib] + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolynomialCoordinates.lean b/lean/OAI/Combinatorics/Crossing/PolynomialCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..90afbafee24bd28fce864f65351fe7702bf88788 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolynomialCoordinates.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.Crossing.PolynomialKernel +import OAI.Combinatorics.Crossing.RankSpecialization +import Mathlib.LinearAlgebra.Basis.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule +open scoped BigOperators +variable {W : Type*} [AddCommGroup W] [Module ℝ W] + +def scalarPolynomial (f : W →ₗ[ℝ] ℝ) : PolynomialModule ℝ W →ₗ[ℝ] Polynomial ℝ := + equivPolynomial.toLinearMap.comp (PolynomialModule.map ℝ f) + +theorem scalarPolynomial_coeff (f : W →ₗ[ℝ] ℝ) (p : PolynomialModule ℝ W) (n : ℕ) : + (scalarPolynomial f p).coeff n = f (p.coeff n) := rfl + +theorem scalarPolynomial_eval (f : W →ₗ[ℝ] ℝ) (p : PolynomialModule ℝ W) (t : ℝ) : + (scalarPolynomial f p).eval t = f (eval t p) := by + induction p using PolynomialModule.induction_linear with + | zero => simp + | add p q hp hq => simp only [map_add, Polynomial.eval_add, hp, hq] + | single n w => + simp [scalarPolynomial, PolynomialModule.map_single, Polynomial.eval_monomial, + _root_.map_smul, smul_eq_mul, mul_comm] + +theorem scalarPolynomial_natDegree_le (f : W →ₗ[ℝ] ℝ) (p : PolynomialModule ℝ W) + (h : ℕ) (hp : Bounded (h+1) p) : (scalarPolynomial f p).natDegree ≤ h := by + apply Polynomial.natDegree_le_iff_coeff_eq_zero.mpr + intro n hn + rw [scalarPolynomial_coeff, hp n (by omega), map_zero] + +variable {ι κ : Type*} [Fintype ι] [Fintype κ] [DecidableEq κ] + +def polynomialColumnMatrix (b : Module.Basis ι ℝ W) (p : κ → PolynomialModule ℝ W) : + Matrix ι κ (Polynomial ℝ) := fun i j => scalarPolynomial (b.coord i) (p j) + +theorem polynomialColumnMatrix_eval + {W : Type*} [AddCommGroup W] [Module ℝ W] {ι κ : Type*} + [Fintype ι] [Fintype κ] [DecidableEq κ] + (b : Module.Basis ι ℝ W) (p : κ → PolynomialModule ℝ W) + (t : ℝ) (i : ι) (j : κ) : + (polynomialColumnMatrix b p i j).eval t = b.repr (eval t (p j)) i := + scalarPolynomial_eval (b.coord i) (p j) t + +theorem exists_polynomial_minor (b : Module.Basis ι ℝ W) (p : κ → PolynomialModule ℝ W) + (d : κ → ℕ) (hp : ∀ j, Bounded (d j+1) (p j)) (t : ℝ) + (hli : LinearIndependent ℝ (fun j => eval t (p j))) : + ∃ r : κ → ι, Function.Injective r ∧ + let Δ := ((polynomialColumnMatrix b p).submatrix r id).det + Δ.eval t ≠ 0 ∧ Δ.natDegree ≤ ∑ j, d j := by + classical + let A := (polynomialColumnMatrix b p).map (Polynomial.eval t) + have hA : LinearIndependent ℝ A.col := by + have hh := hli.map' b.equivFun.toLinearMap (LinearMap.ker_eq_bot.mpr b.equivFun.injective) + have hcols : A.col = b.equivFun ∘ (fun j => eval t (p j)) := by + funext j i + exact polynomialColumnMatrix_eval b p t i j + rw [hcols] + exact hh + obtain ⟨r, hr, hd⟩ := exists_row_minor A hA + refine ⟨r, hr, ?_, ?_⟩ + · have he := (Polynomial.evalRingHom t).map_det ((polynomialColumnMatrix b p).submatrix r id) + exact he.trans_ne hd + · apply natDegree_det_le_column_sum + intro i j + exact scalarPolynomial_natDegree_le (b.coord (r i)) (p j) (d j) (hp j) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolynomialFiltration.lean b/lean/OAI/Combinatorics/Crossing/PolynomialFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..06a88d1c13b6bd1a273b018c7a55001632ffd07c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolynomialFiltration.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.Crossing.Interpolation +import OAI.Combinatorics.Crossing.AdaptedFamily +import OAI.Combinatorics.Crossing.PolynomialCoordinates + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module Submodule +open scoped BigOperators +variable {W ι : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] +variable (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + +def evaluationFiltration (t : ℝ) (k : ℕ) : Submodule ℝ Z := + LinearMap.range (constrainedEval U node Z k t) + +theorem evaluationFiltration_mono + {W ι : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + (t : ℝ) : Monotone (evaluationFiltration U node Z t) := by + intro k l hkl z hz + obtain ⟨p, hp⟩ := hz + exact ⟨⟨p.val, bounded_mono p.property.1 hkl, p.property.2⟩, hp⟩ + +theorem evaluationFiltration_zero + {W ι : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + (t : ℝ) : evaluationFiltration U node Z t 0 = ⊥ := by + apply le_antisymm _ bot_le + intro z hz + obtain ⟨p, hp⟩ := hz + have hp0 : p.val = 0 := (bounded_zero_iff p.val).mp p.property.1 + change eval t p.val = z at hp + rw [hp0, map_zero] at hp + exact (Submodule.mem_bot ℝ).mpr hp.symm + +def columnIncrement (t : ℝ) (e : ℕ) : ℕ := + finrank ℝ (evaluationFiltration U node Z t (e+1)) - + finrank ℝ (evaluationFiltration U node Z t e) + +theorem columnIncrement_zero (t : ℝ) (ht : ∀ i, node i ≠ t) : + columnIncrement U node Z t 0 = rankIncrement U node Z 0 := by + rw [columnIncrement, evaluationFiltration_zero U node Z t, finrank_bot, Nat.sub_zero] + exact finrank_eval_range U node Z 0 t ht + +theorem columnIncrement_succ (t : ℝ) (ht : ∀ i, node i ≠ t) (e : ℕ) : + columnIncrement U node Z t (e+1) = rankIncrement U node Z (e+1) - rankIncrement U node Z e := by + unfold columnIncrement evaluationFiltration + rw [finrank_eval_range U node Z (e+1) t ht, finrank_eval_range U node Z e t ht] + +theorem sum_columnIncrement (t : ℝ) (m : ℕ) : + ∑ e ∈ Finset.range m, columnIncrement U node Z t e = + finrank ℝ (evaluationFiltration U node Z t m) := by + unfold columnIncrement + rw [Finset.sum_range_tsub (fun k l hkl => Submodule.finrank_mono + (evaluationFiltration_mono U node Z t hkl)), evaluationFiltration_zero, + finrank_bot, Nat.sub_zero] + +theorem exists_adapted_polynomials (t : ℝ) (h : ℕ) : + ∃ (p : Fin (finrank ℝ (evaluationFiltration U node Z t (h+1))) → PolynomialModule ℝ Z) + (d : Fin (finrank ℝ (evaluationFiltration U node Z t (h+1))) → ℕ), + (∀ j, p j ∈ constrained U node Z (d j+1) ∧ d j ≤ h) ∧ + LinearIndependent ℝ (fun j => eval t (p j)) ∧ + span ℝ (Set.range (fun j => eval t (p j))) = evaluationFiltration U node Z t (h+1) ∧ + (∑ j, d j) = ∑ e ∈ Finset.range (h+1), e * columnIncrement U node Z t e := by + obtain ⟨v, d, hli, hspan, hmem, hsum⟩ := exists_adapted_family + (evaluationFiltration U node Z t) (evaluationFiltration_mono U node Z t) + (evaluationFiltration_zero U node Z t) (h+1) + have hex : ∀ i, ∃ p : constrained U node Z (d i+1), + constrainedEval U node Z (d i+1) t p = v i := fun i => (hmem i).2 + choose p hp using hex + have hpv : (fun i => eval t (p i).val) = v := funext hp + refine ⟨fun i => (p i).val, d, ?_, ?_, ?_, hsum⟩ + · intro i + exact ⟨(p i).property, Nat.le_of_lt_succ (hmem i).1⟩ + · rw [hpv] + exact hli + · rw [hpv] + exact hspan + +theorem exists_adapted_minor {κ : Type*} [Fintype κ] (b : Basis κ ℝ Z) + (t : ℝ) (_ht : ∀ i, node i ≠ t) (h : ℕ) : + ∃ (p : Fin (finrank ℝ (evaluationFiltration U node Z t (h+1))) → PolynomialModule ℝ Z) + (d : Fin (finrank ℝ (evaluationFiltration U node Z t (h+1))) → ℕ) + (r : Fin (finrank ℝ (evaluationFiltration U node Z t (h+1))) → κ), + (∀ j, p j ∈ constrained U node Z (d j+1) ∧ d j ≤ h) ∧ Function.Injective r ∧ + let Δ := ((polynomialColumnMatrix b p).submatrix r id).det + Δ.eval t ≠ 0 ∧ + Δ.natDegree ≤ ∑ e ∈ Finset.range (h+1), e * columnIncrement U node Z t e := by + obtain ⟨p, d, hp, hli, hspan, hsum⟩ := exists_adapted_polynomials U node Z t h + obtain ⟨r, hr, hd, hdeg⟩ := exists_polynomial_minor b p d (fun j => (hp j).1.1) t hli + exact ⟨p, d, r, hp, hr, hd, hsum ▸ hdeg⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolynomialKernel.lean b/lean/OAI/Combinatorics/Crossing/PolynomialKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ade95f9eaf23b74adb4e23009ec3eba16f54094 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolynomialKernel.lean @@ -0,0 +1,248 @@ +import Mathlib.Algebra.Polynomial.Module.Basic +import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Module +import Lean.Elab.Tactic.Omega + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule +variable {W : Type*} [AddCommGroup W] [Module ℝ W] + +def Bounded (k : ℕ) (p : PolynomialModule ℝ W) : Prop := + ∀ n, k ≤ n → p.coeff n = 0 + +theorem bounded_zero (k : ℕ) : Bounded k (0 : PolynomialModule ℝ W) := by + intro n hn + simp + +theorem bounded_mono {k l : ℕ} {p : PolynomialModule ℝ W} + (hp : Bounded k p) (hkl : k ≤ l) : Bounded l p := + fun n hn => hp n (hkl.trans hn) + +theorem bounded_add {k : ℕ} {p q : PolynomialModule ℝ W} + (hp : Bounded k p) (hq : Bounded k q) : Bounded k (p + q) := by + intro n hn + simp [hp n hn, hq n hn] + +theorem bounded_sub {k : ℕ} {p q : PolynomialModule ℝ W} + (hp : Bounded k p) (hq : Bounded k q) : Bounded k (p - q) := by + intro n hn + change p.coeff n - q.coeff n = 0 + rw [hp n hn, hq n hn, sub_self] + +theorem bounded_single {k n : ℕ} (hn : n < k) (w : W) : + Bounded k (single ℝ n w) := by + intro j hj + simp [show n ≠ j by omega] + +theorem bounded_zero_iff (p : PolynomialModule ℝ W) : Bounded 0 p ↔ p = 0 := by + constructor + · intro h + ext n + exact h n (Nat.zero_le n) + · rintro rfl + exact bounded_zero 0 + +def mulRoot (t : ℝ) (p : PolynomialModule ℝ W) : PolynomialModule ℝ W := + (Polynomial.X - Polynomial.C t) • p + +theorem mulRoot_coeff_zero (t : ℝ) (p : PolynomialModule ℝ W) : + (mulRoot t p).coeff 0 = -t • p.coeff 0 := by + unfold mulRoot + rw [sub_smul] + change (((Polynomial.X : Polynomial ℝ) • p).coeff 0 - + (Polynomial.C t • p).coeff 0) = _ + simp [← Polynomial.monomial_one_one_eq_X, ← Polynomial.monomial_zero_left] + +theorem mulRoot_coeff_succ (t : ℝ) (p : PolynomialModule ℝ W) (n : ℕ) : + (mulRoot t p).coeff (n+1) = p.coeff n - t • p.coeff (n+1) := by + unfold mulRoot + rw [sub_smul] + change (((Polynomial.X : Polynomial ℝ) • p).coeff (n+1) - + (Polynomial.C t • p).coeff (n+1)) = _ + simp [← Polynomial.monomial_one_one_eq_X, ← Polynomial.monomial_zero_left] + +theorem eval_mulRoot (t u : ℝ) (p : PolynomialModule ℝ W) : + eval u (mulRoot t p) = (u-t) • eval u p := by + simp [mulRoot] + +theorem bounded_mulRoot {k : ℕ} {p : PolynomialModule ℝ W} + (t : ℝ) (hp : Bounded k p) : Bounded (k+1) (mulRoot t p) := by + intro n hn + obtain ⟨j, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (show n ≠ 0 by omega) + rw [mulRoot_coeff_succ, hp j (by omega), hp (j+1) (by omega)] + simp + +theorem eq_constant_of_bounded_one {p : PolynomialModule ℝ W} (hp : Bounded 1 p) : + p = single ℝ 0 (p.coeff 0) := by + ext n + cases n with + | zero => simp + | succ n => simp [hp (n+1) (by omega)] + +theorem exists_mulRoot_of_eval_zero (t : ℝ) (k : ℕ) (p : PolynomialModule ℝ W) + (hp : Bounded (k+1) p) (he : eval t p = 0) : + ∃ q, Bounded k q ∧ mulRoot t q = p := by + induction k generalizing p with + | zero => + have hc := eq_constant_of_bounded_one hp + have hz : p.coeff 0 = 0 := by + rw [hc] at he + simpa only [eval_single, pow_zero, one_smul] using he + refine ⟨0, bounded_zero 0, ?_⟩ + have hp0 : p = 0 := hc.trans (by rw [hz, single_zero]) + simp [mulRoot, hp0] + | succ k ih => + let q₀ := single ℝ k (p.coeff (k+1)) + have hq₀ : Bounded (k+1) q₀ := bounded_single (by omega) _ + let r := p - mulRoot t q₀ + have hr : Bounded (k+1) r := by + intro n hn + rcases eq_or_lt_of_le hn with rfl | hn' + · change p.coeff (k+1) - (mulRoot t q₀).coeff (k+1) = 0 + rw [mulRoot_coeff_succ] + simp [q₀] + · exact bounded_sub hp (bounded_mulRoot t hq₀) n (by omega) + have er : eval t r = 0 := by simp [r, eval_mulRoot, he] + obtain ⟨q, hq, eq⟩ := ih r hr er + refine ⟨q + q₀, bounded_add (bounded_mono hq (by omega)) hq₀, ?_⟩ + change (Polynomial.X - Polynomial.C t) • (q + q₀) = p + rw [smul_add] + change mulRoot t q + mulRoot t q₀ = p + rw [eq] + exact sub_add_cancel p _ + +theorem eq_zero_of_mulRoot_eq_zero (t : ℝ) (k : ℕ) (p : PolynomialModule ℝ W) + (hp : Bounded k p) (he : mulRoot t p = 0) : p = 0 := by + induction k with + | zero => exact (bounded_zero_iff p).mp hp + | succ k ih => + have hc : p.coeff k = 0 := by + have hh := congrArg (fun q : PolynomialModule ℝ W => q.coeff (k+1)) he + rw [mulRoot_coeff_succ, hp (k+1) (by omega)] at hh + simpa using hh + apply ih + intro n hn + rcases eq_or_lt_of_le hn with rfl | hn' + · exact hc + · exact hp n (by omega) + +def mulRootLinear (t : ℝ) : PolynomialModule ℝ W →ₗ[ℝ] PolynomialModule ℝ W where + toFun := mulRoot t + map_add' _ _ := smul_add _ _ _ + map_smul' c p := smul_comm _ c p + +variable {ι : Type*} + +def constrained (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + (k : ℕ) : Submodule ℝ (PolynomialModule ℝ Z) where + carrier := {p | Bounded k p ∧ ∀ i, Z.subtype (eval (node i) p) ∈ U i} + zero_mem' := ⟨bounded_zero k, by simp⟩ + add_mem' := by + intro p q hp hq + refine ⟨bounded_add hp.1 hq.1, ?_⟩ + intro i + simpa using (U i).add_mem (hp.2 i) (hq.2 i) + smul_mem' := by + intro c p hp + refine ⟨?_, ?_⟩ + · intro n hn + change c • p.coeff n = 0 + rw [hp.1 n hn, smul_zero] + · intro i + simpa using (U i).smul_mem c (hp.2 i) + +variable (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + +def constrainedEval (k : ℕ) (t : ℝ) : constrained U node Z k →ₗ[ℝ] Z := + (eval t).comp (constrained U node Z k).subtype + +def toEvalKernel (k : ℕ) (t : ℝ) : + constrained U node Z k →ₗ[ℝ] LinearMap.ker (constrainedEval U node Z (k+1) t) where + toFun p := ⟨⟨mulRoot t p.val, bounded_mulRoot t p.property.1, by + intro i + have hi := (U i).smul_mem (node i-t) (p.property.2 i) + simpa only [eval_mulRoot, _root_.map_smul] using hi⟩, by + change eval t (mulRoot t p.val) = 0 + simp [eval_mulRoot]⟩ + map_add' p q := by + apply Subtype.ext + apply Subtype.ext + exact (mulRootLinear t).map_add p.val q.val + map_smul' c p := by + apply Subtype.ext + apply Subtype.ext + exact (mulRootLinear t).map_smul c p.val + +theorem toEvalKernel_injective (k : ℕ) (t : ℝ) : + Function.Injective (toEvalKernel U node Z k t) := by + intro p q he + apply Subtype.ext + apply sub_eq_zero.mp + apply eq_zero_of_mulRoot_eq_zero t k (p.val-q.val) + · exact bounded_sub p.property.1 q.property.1 + · have hh := congrArg (fun r : LinearMap.ker (constrainedEval U node Z (k+1) t) => r.val.val) he + change mulRoot t p.val = mulRoot t q.val at hh + change (mulRootLinear t) (p.val-q.val) = 0 + rw [map_sub, show mulRootLinear t p.val = mulRootLinear t q.val from hh, sub_self] + +theorem toEvalKernel_surjective (k : ℕ) (t : ℝ) (ht : ∀ i, node i ≠ t) : + Function.Surjective (toEvalKernel U node Z k t) := by + intro p + obtain ⟨q, hq, eq⟩ := exists_mulRoot_of_eval_zero t k p.val.val p.val.property.1 p.property + have hqU : ∀ i, Z.subtype (eval (node i) q) ∈ U i := by + intro i + have hp := p.val.property.2 i + rw [← eq, eval_mulRoot] at hp + exact (U i).smul_mem_iff (sub_ne_zero.mpr (ht i)) |>.mp hp + refine ⟨⟨q, hq, hqU⟩, ?_⟩ + apply Subtype.ext + apply Subtype.ext + exact eq + +def evalKernelEquiv (k : ℕ) (t : ℝ) (ht : ∀ i, node i ≠ t) : + constrained U node Z k ≃ₗ[ℝ] LinearMap.ker (constrainedEval U node Z (k+1) t) := + LinearEquiv.ofBijective (toEvalKernel U node Z k t) + ⟨toEvalKernel_injective U node Z k t, toEvalKernel_surjective U node Z k t ht⟩ + +def constrainedCoefficients (k : ℕ) : constrained U node Z k →ₗ[ℝ] (Fin k → Z) where + toFun p n := p.val.coeff n + map_add' _ _ := rfl + map_smul' _ _ := rfl + +theorem constrainedCoefficients_injective (k : ℕ) : + Function.Injective (constrainedCoefficients U node Z k) := by + intro p q he + apply Subtype.ext + apply PolynomialModule.ext + apply Finsupp.ext + intro n + by_cases hn : n < k + · exact congrFun he ⟨n, hn⟩ + · rw [p.property.1 n (by omega), q.property.1 n (by omega)] + +instance constrained_finiteDimensional [FiniteDimensional ℝ W] (k : ℕ) : + FiniteDimensional ℝ (constrained U node Z k) := + FiniteDimensional.of_injective (constrainedCoefficients U node Z k) + (constrainedCoefficients_injective U node Z k) + +def rankIncrement (h : ℕ) : ℕ := + Module.finrank ℝ (constrained U node Z (h+1)) - Module.finrank ℝ (constrained U node Z h) + +theorem finrank_eval_range [FiniteDimensional ℝ W] (h : ℕ) (t : ℝ) + (ht : ∀ i, node i ≠ t) : + Module.finrank ℝ (LinearMap.range (constrainedEval U node Z (h+1) t)) = + rankIncrement U node Z h := by + have he := (evalKernelEquiv U node Z h t ht).finrank_eq + have hr := (constrainedEval U node Z (h+1) t).finrank_range_add_finrank_ker + unfold rankIncrement + omega + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolynomialLinearMatrix.lean b/lean/OAI/Combinatorics/Crossing/PolynomialLinearMatrix.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee37230501cd2e35c1b334dba7e571d66d32df94 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolynomialLinearMatrix.lean @@ -0,0 +1,34 @@ +import OAI.Combinatorics.Crossing.PolynomialCoordinates + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module +variable {V W ι κ : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] +variable [Fintype ι] [Fintype κ] [DecidableEq κ] + +def polynomialLinearMatrix (bV : Basis κ ℝ V) (bW : Basis ι ℝ W) + (F : V →ₗ[ℝ] PolynomialModule ℝ W) : Matrix ι κ (Polynomial ℝ) := + polynomialColumnMatrix bW (fun j => F (bV j)) + +theorem polynomialLinearMatrix_eval (bV : Basis κ ℝ V) (bW : Basis ι ℝ W) + (F : V →ₗ[ℝ] PolynomialModule ℝ W) (t : ℝ) : + (polynomialLinearMatrix bV bW F).map (Polynomial.eval t) = + LinearMap.toMatrix bV bW ((eval t).comp F) := by + funext i j + rw [LinearMap.toMatrix_apply] + exact polynomialColumnMatrix_eval bW (fun j => F (bV j)) t i j + +theorem polynomialLinearMatrix_rank (bV : Basis κ ℝ V) (bW : Basis ι ℝ W) + (F : V →ₗ[ℝ] PolynomialModule ℝ W) (t : ℝ) : + ((polynomialLinearMatrix bV bW F).map (Polynomial.eval t)).rank = + finrank ℝ (LinearMap.range ((eval t).comp F)) := by + rw [polynomialLinearMatrix_eval, Matrix.rank_eq_finrank_range_toLin _ bW bV, + Matrix.toLin_toMatrix] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/PolynomialMinors.lean b/lean/OAI/Combinatorics/Crossing/PolynomialMinors.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bb1e2362dcaedde632b1ff3dcff2bf5a91467e1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/PolynomialMinors.lean @@ -0,0 +1,71 @@ +import Mathlib.LinearAlgebra.Matrix.Determinant.Basic +import Mathlib.Algebra.Polynomial.FieldDivision +import Mathlib.Algebra.Polynomial.BigOperators +import Mathlib.RingTheory.Coprime.Lemmas +import Mathlib.Basic.Real.Basic + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Polynomial +open scoped BigOperators +variable {κ : Type*} [Fintype κ] [DecidableEq κ] + +theorem natDegree_det_le_column_sum (M : Matrix κ κ ℝ[X]) (e : κ → ℕ) + (he : ∀ i j, (M i j).natDegree ≤ e j) : + M.det.natDegree ≤ ∑ j, e j := by + rw [Matrix.det_apply] + apply natDegree_sum_le_of_forall_le + intro σ hσ + apply (natDegree_smul_le _ _).trans + exact (natDegree_prod_le _ _).trans (Finset.sum_le_sum fun j _ => he (σ j) j) + +theorem pow_card_dvd_det_of_columns_vanish (M : Matrix κ κ ℝ[X]) (t : ℝ) + (S : Finset κ) (hv : ∀ j ∈ S, ∀ i, (M i j).eval t = 0) : + (X - C t)^S.card ∣ M.det := by + let v : κ → ℝ[X] := fun j => if j ∈ S then X-C t else 1 + let A : Matrix κ κ ℝ[X] := fun i j => if j ∈ S then M i j /ₘ (X-C t) else M i j + have hM : M = Matrix.of (fun i j => v j * A i j) := by + funext i j + by_cases hj : j ∈ S + · simp only [Matrix.of_apply, v, A, hj, ite_true] + exact (mul_divByMonic_eq_iff_isRoot.mpr (hv j hj i)).symm + · simp [v, A, hj] + have hprod : ∏ j, v j = (X-C t)^S.card := by + simp [v] + rw [hM, Matrix.det_mul_row, hprod] + exact dvd_mul_right _ _ + +theorem prod_pow_roots_dvd {ι : Type*} [Fintype ι] (node : ι → ℝ) + (hn : Function.Injective node) (q : ι → ℕ) (p : ℝ[X]) + (hq : ∀ i, (X-C (node i))^(q i) ∣ p) : + (∏ i, (X-C (node i))^(q i)) ∣ p := by + apply Fintype.prod_dvd_of_coprime _ hq + intro i j hij + exact (pairwise_coprime_X_sub_C hn hij).pow + +theorem sum_multiplicities_le_natDegree {ι : Type*} [Fintype ι] (node : ι → ℝ) + (hn : Function.Injective node) (q : ι → ℕ) (p : ℝ[X]) (hp : p ≠ 0) + (hq : ∀ i, (X-C (node i))^(q i) ∣ p) : + ∑ i, q i ≤ p.natDegree := by + have hd := natDegree_le_of_dvd (prod_pow_roots_dvd node hn q p hq) hp + rw [natDegree_prod_of_monic] at hd + · simpa only [natDegree_pow, natDegree_X_sub_C, mul_one] using hd + · intro i hi + exact (monic_X_sub_C (node i)).pow (q i) + +theorem sum_multiplicities_le_column_sum {ι : Type*} [Fintype ι] + (node : ι → ℝ) (hn : Function.Injective node) (q : ι → ℕ) + (M : Matrix κ κ ℝ[X]) (e : κ → ℕ) (hM : M.det ≠ 0) + (he : ∀ i j, (M i j).natDegree ≤ e j) + (hq : ∀ i, (X-C (node i))^(q i) ∣ M.det) : + ∑ i, q i ≤ ∑ j, e j := + (sum_multiplicities_le_natDegree node hn q M.det hM hq).trans + (natDegree_det_le_column_sum M e he) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ProperCrossingLocality.lean b/lean/OAI/Combinatorics/Crossing/ProperCrossingLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..f468e5b6f98a2baa92a653e4c32823b97b2cb55e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ProperCrossingLocality.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Topology.OpenPartialHomeomorph.IsImage + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem chart_image_mem_iff (e : OpenPartialHomeomorph Plane Plane) (A L : Set Plane) + (h : e '' (e.source ∩ A)=e.target ∩ L) (x : Plane) (hx : x ∈ e.source) : + x ∈ A ↔ e x ∈ L := by + constructor + · intro ha + have hh : e x ∈ e '' (e.source ∩ A) := ⟨x,⟨hx,ha⟩,rfl⟩ + rw [h] at hh + exact hh.2 + · intro hl + have hh : e x ∈ e '' (e.source ∩ A) := h.symm ▸ ⟨e.map_source hx,hl⟩ + obtain ⟨y,hy,he⟩ := hh + have hyx : y=x := e.injOn hy.1 hx he + exact hyx ▸ hy.2 + +theorem chart_restr_image_of_local_eq (e : OpenPartialHomeomorph Plane Plane) + (A A' L U : Set Plane) (hU : IsOpen U) (hA : ∀ x ∈ U, x ∈ A ↔ x ∈ A') + (h : e '' (e.source ∩ A)=e.target ∩ L) : + (e.restrOpen U hU) '' ((e.restrOpen U hU).source ∩ A')=(e.restrOpen U hU).target ∩ L := by + let f := e.restrOpen U hU + apply Set.Subset.antisymm + · rintro y ⟨x,hx,rfl⟩ + have hs : x ∈ e.source ∩ U := hx.1 + exact ⟨f.map_source hx.1,(chart_image_mem_iff e A L h x hs.1).mp ((hA x hs.2).mpr hx.2)⟩ + · rintro y ⟨hy,hl⟩ + have hs : f.symm y ∈ f.source := f.map_target hy + have hs' : f.symm y ∈ e.source ∩ U := hs + have he : e (f.symm y)=y := f.right_inv hy + have ha : f.symm y ∈ A := (chart_image_mem_iff e A L h _ hs'.1).mpr (he.symm ▸ hl) + exact ⟨f.symm y,⟨hs,(hA _ hs'.2).mp ha⟩,f.right_inv hy⟩ + +theorem properCrossing_of_local_eq (A B A' B' : Set Plane) (x : Plane) + (h : ProperCrossing A B x) (U : Set Plane) (hU : IsOpen U) (hx : x ∈ U) + (hA : ∀ z ∈ U, z ∈ A ↔ z ∈ A') (hB : ∀ z ∈ U, z ∈ B ↔ z ∈ B') : + ProperCrossing A' B' x := by + obtain ⟨e,hs,he,hEA,hEB⟩ := h + refine ⟨e.restrOpen U hU,⟨hs,hx⟩,he,?_,?_⟩ + · exact chart_restr_image_of_local_eq e A A' {y | y.2=0} U hU hA hEA + · exact chart_restr_image_of_local_eq e B B' {y | y.1=0} U hU hB hEB + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ProperSegmentCrossing.lean b/lean/OAI/Combinatorics/Crossing/ProperSegmentCrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..1216edce825c55b5b6dece2aeb32dee5c21ed3da --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ProperSegmentCrossing.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.Crossing.SegmentCrossingCoordinates + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem properCrossing_openSegments (a b c d x : Plane) (hd : det2 (b-a) (d-c) ≠ 0) + (hx : x ∈ openSegmentTrace a b) (hy : x ∈ openSegmentTrace c d) : + ProperCrossing (openSegmentTrace a b) (openSegmentTrace c d) x := by + obtain ⟨t,ht,hxt⟩ := hx + obtain ⟨u,hu,hxu⟩ := hy + let U : Set Plane := Set.Ioo (-t) (1-t) ×ˢ Set.Ioo (-u) (1-u) + have hU : IsOpen U := isOpen_Ioo.prod isOpen_Ioo + let chart := crossingCoordinateChart x (b-a) (d-c) hd U hU + have hzero : (0,0) ∈ U := ⟨⟨by linarith [ht.1],by linarith [ht.2]⟩, + ⟨by linarith [hu.1],by linarith [hu.2]⟩⟩ + have hsource : x ∈ chart.source := by + change crossingCoordinates x (b-a) (d-c) x ∈ U + rw [crossingCoordinates_origin] + exact hzero + refine ⟨chart,hsource,crossingCoordinates_origin x (b-a) (d-c),?_,?_⟩ + · apply Set.Subset.antisymm + · rintro y ⟨z,hz,rfl⟩ + refine ⟨chart.map_source hz.1,?_⟩ + obtain ⟨s,hs,he⟩ := hz.2 + rw [← he] + change (crossingCoordinates x (b-a) (d-c) (segmentPoint a b s)).2=0 + rw [crossingCoordinates_first_segment a b c d x t s hd hxt.symm] + · rintro y ⟨hy,hy0⟩ + have hs : t+y.1 ∈ Set.Ioo (0 : ℝ) 1 := ⟨by linarith [hy.1.1],by linarith [hy.1.2]⟩ + have he : chart (segmentPoint a b (t+y.1))=y := by + change crossingCoordinates x (b-a) (d-c) (segmentPoint a b (t+y.1))=y + rw [crossingCoordinates_first_segment a b c d x t (t+y.1) hd hxt.symm] + apply Prod.ext + · dsimp + ring + · exact hy0.symm + refine ⟨segmentPoint a b (t+y.1),⟨?_,⟨t+y.1,hs,rfl⟩⟩,he⟩ + change chart (segmentPoint a b (t+y.1)) ∈ U + rw [he] + exact hy + · apply Set.Subset.antisymm + · rintro y ⟨z,hz,rfl⟩ + refine ⟨chart.map_source hz.1,?_⟩ + obtain ⟨s,hs,he⟩ := hz.2 + rw [← he] + change (crossingCoordinates x (b-a) (d-c) (segmentPoint c d s)).1=0 + rw [crossingCoordinates_second_segment a b c d x u s hd hxu.symm] + · rintro y ⟨hy,hy0⟩ + have hs : u+y.2 ∈ Set.Ioo (0 : ℝ) 1 := ⟨by linarith [hy.2.1],by linarith [hy.2.2]⟩ + have he : chart (segmentPoint c d (u+y.2))=y := by + change crossingCoordinates x (b-a) (d-c) (segmentPoint c d (u+y.2))=y + rw [crossingCoordinates_second_segment a b c d x u (u+y.2) hd hxu.symm] + apply Prod.ext + · exact hy0.symm + · dsimp + ring + refine ⟨segmentPoint c d (u+y.2),⟨?_,⟨u+y.2,hs,rfl⟩⟩,he⟩ + change chart (segmentPoint c d (u+y.2)) ∈ U + rw [he] + exact hy + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RadialBoundaryPorts.lean b/lean/OAI/Combinatorics/Crossing/RadialBoundaryPorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..64f125fac667c3c02baf25cc0b2b8de3ee06fe0a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RadialBoundaryPorts.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.VertexSpokeBounds +import Mathlib.Analysis.Real.Sqrt + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def radialPort (a b : Plane) (r : ℝ) : Plane := + a+(r/Real.sqrt (squaredLength (b-a))) • (b-a) + +theorem squaredLength_smul (v : Plane) (t : ℝ) : squaredLength (t • v)=t^2*squaredLength v := by + dsimp [squaredLength] + ring + +theorem radialPort_sub (a b : Plane) (r : ℝ) : + radialPort a b r-a=(r/Real.sqrt (squaredLength (b-a))) • (b-a) := by + simp only [radialPort,add_sub_cancel_left] + +theorem radialPort_on_circle (a b : Plane) (hab : a ≠ b) (r : ℝ) : + squaredLength (radialPort a b r-a)=r^2 := by + have hL := squaredLength_pos (b-a) (sub_ne_zero.mpr hab.symm) + have hs : Real.sqrt (squaredLength (b-a)) ≠ 0 := ne_of_gt (Real.sqrt_pos.mpr hL) + rw [radialPort_sub,squaredLength_smul,div_pow,Real.sq_sqrt hL.le] + exact div_mul_cancel₀ _ (ne_of_gt hL) + +theorem radialPort_parameter (a b : Plane) (r : ℝ) : + radialPort a b r=segmentPoint a b (r/Real.sqrt (squaredLength (b-a))) := by + apply Prod.ext <;> dsimp [radialPort,segmentPoint] <;> ring + +theorem radialPort_parameter_between (a b : Plane) (r : ℝ) (hr : 0 < r) + (hshort : r^2 < squaredLength (b-a)) : + r/Real.sqrt (squaredLength (b-a)) ∈ Set.Ioo (0 : ℝ) 1 := by + have hL : 0 < squaredLength (b-a) := (sq_nonneg r).trans_lt hshort + have hs := Real.sqrt_pos.mpr hL + have hs2 := Real.sq_sqrt hL.le + exact ⟨div_pos hr hs,(div_lt_one hs).mpr (by nlinarith)⟩ + +theorem radialPort_mem_openSegment (a b : Plane) (r : ℝ) (hr : 0 < r) + (hshort : r^2 < squaredLength (b-a)) : radialPort a b r ∈ openSegmentTrace a b := by + exact ⟨r/Real.sqrt (squaredLength (b-a)),radialPort_parameter_between a b r hr hshort, + (radialPort_parameter a b r).symm⟩ + +theorem radialPort_ne_center (a b : Plane) (hab : a ≠ b) (r : ℝ) (hr : 0 < r) : + radialPort a b r ≠ a := by + intro h + have hh := radialPort_on_circle a b hab r + rw [h,sub_self] at hh + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hh + nlinarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RadialExterior.lean b/lean/OAI/Combinatorics/Crossing/RadialExterior.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a279bd1c4d0c08ba6f012120e8252c87a48020e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RadialExterior.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.ParallelDirection +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem squaredLength_add_smul (u v : Plane) (t : ℝ) : + squaredLength (u+t • v)=squaredLength u+2*t*dot2 u v+t^2*squaredLength v := by + dsimp [squaredLength,dot2] + ring + +theorem squaredLength_segment_translated (a b z : Plane) (t : ℝ) : + squaredLength (segmentPoint a b t-z)= + squaredLength (a-z)+2*t*dot2 (a-z) (b-a)+t^2*squaredLength (b-a) := by + dsimp [squaredLength,dot2,segmentPoint] + ring + +theorem exterior_segment_of_dot (z a b : Plane) (r : ℝ) + (ha : r^2 < squaredLength (a-z)) (hd : 0 ≤ dot2 (a-z) (b-a)) : + segment ℝ a b ⊆ {x | r^2 < squaredLength (x-z)} := by + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,rfl⟩ := hx + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + change r^2 < squaredLength (segmentPoint a b t.val-z) + rw [squaredLength_segment_translated] + have h₁ : 0 ≤ 2*t.val*dot2 (a-z) (b-a) := mul_nonneg (mul_nonneg (by norm_num) t.property.1) hd + have h₂ : 0 ≤ t.val^2*squaredLength (b-a) := by dsimp [squaredLength]; positivity + linarith + +theorem radial_spur_exterior (z x : Plane) (r α : ℝ) + (hx : squaredLength (x-z)=r^2) (hr : 0 < r) (hα : 0 < α) : + segment ℝ x (x+α • (x-z)) ⊆ insert x {y | r^2 < squaredLength (y-z)} := by + intro y hy + rw [← Path.range_segment] at hy + obtain ⟨t,rfl⟩ := hy + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + by_cases ht : t.val=0 + · left + change segmentPoint x (x+α • (x-z)) t.val=x + rw [ht,segmentPoint_zero] + · right + have htpos : 0 < t.val := lt_of_le_of_ne t.property.1 (Ne.symm ht) + change r^2 < squaredLength (segmentPoint x (x+α • (x-z)) t.val-z) + have he : squaredLength (segmentPoint x (x+α • (x-z)) t.val-z)= + (1+t.val*α)^2*squaredLength (x-z) := by + dsimp [squaredLength,segmentPoint] + ring + rw [he,hx] + have hp := mul_pos htpos hα + nlinarith [sq_pos_of_pos hr,mul_pos hp (sq_pos_of_pos hr)] + +theorem radial_tip_dot (z x : Plane) (α : ℝ) : + dot2 (x-z) ((x+α • (x-z))-x)=α*squaredLength (x-z) := by + dsimp [dot2,squaredLength] + ring + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RankDetector.lean b/lean/OAI/Combinatorics/Crossing/RankDetector.lean new file mode 100644 index 0000000000000000000000000000000000000000..18f1761d147a51cb5800ca145cf6d0b047cd519c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RankDetector.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.Crossing.NodeMoments +import OAI.Combinatorics.Crossing.TwoTriangleBasis +import Mathlib.LinearAlgebra.Matrix.Rank +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Ring + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Module +open scoped BigOperators +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +def detectorVector (s : ℕ) (node : ι → ℝ) (p q : ι) : BiExponent s → ℝ := + fun ab => node p ^ ab.1.val * node q ^ ab.2.val + +def detectorWeight (node : ι → ℝ) (p q : ι) : ℝ := + (node p-node q) / (derivativeAtNode node p * derivativeAtNode node q) + +def detectorAtom (s : ℕ) (node : ι → ℝ) (p q : ι) : + Matrix (BiExponent s) (BiExponent s) ℝ := + detectorWeight node p q • Matrix.vecMulVec (detectorVector s node p q) (detectorVector s node p q) + +def rankDetector (s : ℕ) (node : ι → ℝ) : + Matrix ι ι ℝ →ₗ[ℝ] Matrix (BiExponent s) (BiExponent s) ℝ where + toFun H := ∑ p, ∑ q, H p q • detectorAtom s node p q + map_add' H K := by simp [add_smul, Finset.sum_add_distrib] + map_smul' c H := by simp [smul_smul, Finset.smul_sum] + +theorem detectorAtom_self + {ι : Type*} [Fintype ι] [DecidableEq ι] + (s : ℕ) (node : ι → ℝ) (p : ι) : detectorAtom s node p p = 0 := by + simp [detectorAtom, detectorWeight] + +theorem detectorWeight_ne_zero (node : ι → ℝ) (hn : Function.Injective node) + {p q : ι} (hpq : p ≠ q) : detectorWeight node p q ≠ 0 := by + exact div_ne_zero (sub_ne_zero.mpr (hn.ne hpq)) + (mul_ne_zero (derivativeAtNode_ne_zero node hn p) (derivativeAtNode_ne_zero node hn q)) + +theorem detectorAtom_entry + {ι : Type*} [Fintype ι] [DecidableEq ι] + (s : ℕ) (node : ι → ℝ) (p q : ι) (ab cd : BiExponent s) : + detectorAtom s node p q ab cd = + (node p-node q) * node p^(ab.1.val+cd.1.val) * node q^(ab.2.val+cd.2.val) / + (derivativeAtNode node p * derivativeAtNode node q) := by + simp only [detectorAtom, detectorWeight, Matrix.smul_apply, smul_eq_mul, + Matrix.vecMulVec_apply, detectorVector, pow_add] + ring + +theorem rankDetector_diagonal (s : ℕ) (node : ι → ℝ) (d : ι → ℝ) : + rankDetector s node (Matrix.diagonal d) = 0 := by + change (∑ p, ∑ q, Matrix.diagonal d p q • detectorAtom s node p q) = 0 + simp [Matrix.diagonal_apply, detectorAtom_self] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RankMultiplicity.lean b/lean/OAI/Combinatorics/Crossing/RankMultiplicity.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6d602a8500b6ece9d34f4cb3926c070f9775c8e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RankMultiplicity.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.PolynomialMinors +import Mathlib.LinearAlgebra.Matrix.Rank + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Polynomial +open scoped BigOperators +variable {κ : Type*} [Fintype κ] [DecidableEq κ] + +theorem rank_deficiency_pow_dvd_det (M : Matrix κ κ ℝ[X]) (t : ℝ) : + (X-C t)^(Fintype.card κ - ((evalRingHom t).mapMatrix M).rank) ∣ M.det := by + classical + let E : Matrix κ κ ℝ := (evalRingHom t).mapMatrix M + obtain ⟨V, U, e, hV, hU, he⟩ := Matrix.exists_rank_normal_form E + let T : Matrix κ κ ℝ[X] := C.mapMatrix V * M * C.mapMatrix U + let emb : Fin (Fintype.card κ-E.rank) ↪ κ := + ⟨fun i => e.symm (Sum.inr i), fun i j h => Sum.inr_injective (e.symm.injective h)⟩ + let S : Finset κ := Finset.univ.map emb + have hS : S.card = Fintype.card κ-E.rank := by simp [S] + have evalC (A : Matrix κ κ ℝ) : (evalRingHom t).mapMatrix (C.mapMatrix A) = A := by + funext i j + exact eval_C + have hT : (evalRingHom t).mapMatrix T = V * E * U := by + simp only [T, map_mul, evalC] + rfl + have hz : ∀ j ∈ S, ∀ i, (T i j).eval t = 0 := by + intro j hj i + obtain ⟨a, ha, rfl⟩ := Finset.mem_map.mp hj + change ((evalRingHom t).mapMatrix T) i (emb a) = 0 + rw [hT, he] + change (Matrix.fromBlocks 1 0 0 0) (e i) (e (e.symm (Sum.inr a))) = 0 + rw [Equiv.apply_symm_apply] + cases e i <;> rfl + have hd := pow_card_dvd_det_of_columns_vanish T t S hz + rw [hS] at hd + have hdet : T.det = C V.det * M.det * C U.det := by + dsimp only [T] + rw [Matrix.det_mul, Matrix.det_mul, ← RingHom.map_det, ← RingHom.map_det] + rw [hdet] at hd + have hu : IsUnit (C U.det : ℝ[X]) := isUnit_C.mpr ((Matrix.isUnit_iff_isUnit_det U).mp hU) + have hv : IsUnit (C V.det : ℝ[X]) := isUnit_C.mpr ((Matrix.isUnit_iff_isUnit_det V).mp hV) + exact hv.dvd_mul_left.mp (hu.dvd_mul_right.mp hd) + +theorem pow_dvd_det_of_rank_le (M : Matrix κ κ ℝ[X]) (t : ℝ) (q : ℕ) + (hq : q + ((evalRingHom t).mapMatrix M).rank ≤ Fintype.card κ) : + (X-C t)^q ∣ M.det := by + apply dvd_trans _ (rank_deficiency_pow_dvd_det M t) + exact pow_dvd_pow _ (by omega) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RankSpecialization.lean b/lean/OAI/Combinatorics/Crossing/RankSpecialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..93b1351e047ea84313473102a5de3f5f44872e61 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RankSpecialization.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.PolynomialMinors +import Mathlib.LinearAlgebra.Matrix.Rank + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open Polynomial +open scoped BigOperators +variable {μ ν : Type*} [Fintype μ] [Fintype ν] + +theorem exists_row_minor [DecidableEq ν] (A : Matrix μ ν ℝ) (hA : LinearIndependent ℝ A.col) : + ∃ r : ν → μ, Function.Injective r ∧ (A.submatrix r id).det ≠ 0 := by + classical + obtain ⟨ι, a, ha, hspan, hli⟩ := exists_linearIndependent' ℝ A.row + let : Fintype ι := Fintype.ofInjective a ha + have hcard : Fintype.card ι = Fintype.card ν := by + rw [← finrank_span_eq_card hli, hspan, ← A.rank_eq_finrank_span_row, + A.rank_eq_finrank_span_cols, finrank_span_eq_card hA] + let e : ν ≃ ι := Fintype.equivOfCardEq hcard.symm + refine ⟨a ∘ e, ha.comp e.injective, ?_⟩ + have hrows : LinearIndependent ℝ (A.submatrix (a ∘ e) id).row := hli.comp e e.injective + exact ((Matrix.isUnit_iff_isUnit_det _).mp + (Matrix.linearIndependent_rows_iff_isUnit.mp hrows)).ne_zero + +theorem exists_rank_minor (A : Matrix μ ν ℝ) : + ∃ (r : Fin A.rank → μ) (c : Fin A.rank → ν), + Function.Injective r ∧ Function.Injective c ∧ (A.submatrix r c).det ≠ 0 := by + classical + obtain ⟨ι, a, ha, hspan, hli⟩ := exists_linearIndependent' ℝ A.col + let : Fintype ι := Fintype.ofInjective a ha + have hcard : Fintype.card ι = A.rank := by + rw [← finrank_span_eq_card hli, hspan, A.rank_eq_finrank_span_cols] + let e : Fin A.rank ≃ ι := Fintype.equivOfCardEq (by simpa using hcard.symm) + let c : Fin A.rank → ν := a ∘ e + have hc : LinearIndependent ℝ (A.submatrix id c).col := hli.comp e e.injective + obtain ⟨r, hr, hd⟩ := exists_row_minor (A.submatrix id c) hc + refine ⟨r, c, hr, ha.comp e.injective, ?_⟩ + simpa [Matrix.submatrix_submatrix] using hd + +theorem polynomial_rank_specialization (M : Matrix μ ν ℝ[X]) (nodes : Finset ℝ) + (b : ℕ) (hb : ∀ t ∉ nodes, (M.map (Polynomial.eval t)).rank ≤ b) (t₀ : ℝ) : + (M.map (Polynomial.eval t₀)).rank ≤ b := by + classical + let A := M.map (Polynomial.eval t₀) + by_contra h + have hlt : b < A.rank := Nat.lt_of_not_ge h + obtain ⟨r, c, hr, hc, hd⟩ := exists_rank_minor A + let P : ℝ[X] := (M.submatrix r c).det + have evalP (t : ℝ) : P.eval t = ((M.map (Polynomial.eval t)).submatrix r c).det := by + exact (evalRingHom t).map_det (M.submatrix r c) + have hP : P ≠ 0 := by + intro hzero + apply hd + change ((M.map (Polynomial.eval t₀)).submatrix r c).det = 0 + rw [← evalP, hzero, eval_zero] + obtain ⟨t, ht⟩ := (nodes ∪ P.roots.toFinset).exists_notMem + have htN : t ∉ nodes := fun htn => ht (Finset.mem_union_left _ htn) + have htP : P.eval t ≠ 0 := by + intro hz + exact ht (Finset.mem_union_right _ (by simpa [mem_roots hP] using hz)) + have hm : (((M.map (Polynomial.eval t)).submatrix r c)).rank = A.rank := by + simpa using Matrix.rank_of_det_ne_zero (show + ((M.map (Polynomial.eval t)).submatrix r c).det ≠ 0 by rwa [← evalP]) + have hle := Matrix.rank_submatrix_le (M.map (Polynomial.eval t)) r c + rw [hm] at hle + exact (not_le_of_gt hlt) (hle.trans (hb t htN)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectedIntersectionCases.lean b/lean/OAI/Combinatorics/Crossing/ReconnectedIntersectionCases.lean new file mode 100644 index 0000000000000000000000000000000000000000..5485cce22872bd9a242753adab0fa27ea964e144 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectedIntersectionCases.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.Crossing.ReconnectionOppositeCuts + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem reconnected_paths_meeting_cases + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + (x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∧ + x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val))) ∨ + (x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) ∧ + x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val))) := by + have hFP := E.forward_chord_disjoint_opposite_prefix v hvinj hv hdet P Kq hpq hm + have hFS := E.forward_chord_disjoint_opposite_suffix v hvinj hv hdet P Kp hpq hm + have hBP := E.backward_chord_disjoint_opposite_prefix v hvinj hv hdet P Kp hpq hm + have hBS := E.backward_chord_disjoint_opposite_suffix v hvinj hv hdet P Kq hpq hm + have hchord := C.reconnection_chords_disjoint p q hcross true false (by decide) + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact Or.inl ⟨hx,hy⟩ + · exact False.elim (Set.disjoint_left.mp hBP hy hx) + · exact False.elim (Set.disjoint_left.mp Kp.prefix_suffix_disjoint hx hy) + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact False.elim (Set.disjoint_left.mp hFP hx hy) + · exact False.elim (Set.disjoint_left.mp hchord hx hy) + · exact False.elim (Set.disjoint_left.mp hFS hx hy) + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact False.elim (Set.disjoint_left.mp Kq.prefix_suffix_disjoint hy hx) + · exact False.elim (Set.disjoint_left.mp hBS hy hx) + · exact Or.inr ⟨hy,hx⟩ + +theorem reconnected_paths_meeting_old_edges + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + x ∈ Set.range (E.assembledEdge v p.1) ∧ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases E.reconnected_paths_meeting_cases v hvinj hv hdet P Kp Kq hpq hm hcross x hx hy with h | h + · exact ⟨Kp.prefix_subset_edge h.1,Kq.prefix_subset_edge h.2⟩ + · exact ⟨Kp.suffix_subset_edge h.1,Kq.suffix_subset_edge h.2⟩ + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectedPaths.lean b/lean/OAI/Combinatorics/Crossing/ReconnectedPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..67c26af2947f63a9a68e0ff5033bd0f15874657b --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectedPaths.lean @@ -0,0 +1,71 @@ +import OAI.Combinatorics.Crossing.ReconnectedWalks + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def reconnectedForwardPath (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : Path (D'.vertex (.inl p.1.1)) (D'.vertex (.inr q.1.2)) := by + classical + exact graphWalkPath id (reconnectedForwardWalk Kp Kq hm).bypass + +def reconnectedBackwardPath (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : Path (D'.vertex (.inl q.1.1)) (D'.vertex (.inr p.1.2)) := by + classical + exact graphWalkPath id (reconnectedBackwardWalk Kp Kq hm).bypass + +theorem reconnectedForwardPath_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (reconnectedForwardPath Kp Kq hm) := by + classical + exact graphWalkPath_injective id hemb (surgery_mixed_endpoints_ne C p q) + _ (reconnectedForwardWalk Kp Kq hm).bypass_isPath + +theorem reconnectedBackwardPath_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (reconnectedBackwardPath Kp Kq hm) := by + classical + exact graphWalkPath_injective id hemb (surgery_mixed_endpoints_ne C q p) + _ (reconnectedBackwardWalk Kp Kq hm).bypass_isPath + +theorem reconnectedForwardPath_hasFiniteAffineCover (Kp : ExteriorCrossingCut C P p) + (Kq : ExteriorCrossingCut C P q) (hm : C.innerMark p=C.innerMark q) : + HasFiniteAffineCover (reconnectedForwardPath Kp Kq hm) := by + classical + exact graphWalkPath_hasFiniteAffineCover id _ + +theorem reconnectedBackwardPath_hasFiniteAffineCover (Kp : ExteriorCrossingCut C P p) + (Kq : ExteriorCrossingCut C P q) (hm : C.innerMark p=C.innerMark q) : + HasFiniteAffineCover (reconnectedBackwardPath Kp Kq hm) := by + classical + exact graphWalkPath_hasFiniteAffineCover id _ + +theorem reconnectedForwardPath_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (reconnectedForwardPath Kp Kq hm) ⊆ + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val)) := by + classical + exact (graphWalkPath_bypass_range_subset id (reconnectedForwardWalk Kp Kq hm)).trans + (by rw [reconnectedForwardWalk_trace]) + +theorem reconnectedBackwardPath_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (reconnectedBackwardPath Kp Kq hm) ⊆ + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) := by + classical + exact (graphWalkPath_bypass_range_subset id (reconnectedBackwardWalk Kp Kq hm)).trans + (by rw [reconnectedBackwardWalk_trace]) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectedPointRemoval.lean b/lean/OAI/Combinatorics/Crossing/ReconnectedPointRemoval.lean new file mode 100644 index 0000000000000000000000000000000000000000..61fa237571f451428a85143d93a0c9454b9b4cde --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectedPointRemoval.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.Crossing.ReconnectedPaths +import OAI.Combinatorics.Crossing.ReconnectionAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem reconnected_paths_avoid_crossing (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∉ Set.range (reconnectedForwardPath Kp Kq hm) ∧ + x ∉ Set.range (reconnectedBackwardPath Kp Kq hm) := by + obtain ⟨hxin,havoid⟩ := C.reconnection_avoids_chord_meeting p q hpq x hxp hxq + have hxinq : x ∈ C.crossingDisk q := by + simpa only [DrawingPassages.crossingDisk,hm] using hxin + constructor + · intro hx + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Set.disjoint_left.mp Kp.prefix_outside hx hxin + · exact havoid true hx + · exact Set.disjoint_left.mp Kq.suffix_outside hx hxinq + · intro hx + rcases reconnectedBackwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Set.disjoint_left.mp Kq.prefix_outside hx hxinq + · exact havoid false hx + · exact Set.disjoint_left.mp Kp.suffix_outside hx hxin + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectedVertexAvoidance.lean b/lean/OAI/Combinatorics/Crossing/ReconnectedVertexAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dd41c8d4cce3207d6cf68aa15b56a37ef6d72ca --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectedVertexAvoidance.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.Crossing.ReconnectedPaths +import OAI.Combinatorics.Crossing.CutVertexAvoidance +import OAI.Combinatorics.Crossing.ReconnectionVertexAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem path_interior_avoids_vertices_of_range {V : Type*} (vertex : V → Plane) (a b : V) + (γ : Path (vertex a) (vertex b)) (hinj : Function.Injective γ) + (hrange : ∀ v, vertex v ∈ Set.range γ → v=a ∨ v=b) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (v : V) : γ t ≠ vertex v := by + intro he + rcases hrange v ⟨t,he⟩ with rfl | rfl + · exact ht.1.ne (hinj (he.trans γ.source.symm)).symm + · exact ht.2.ne (hinj (he.trans γ.target.symm)) + +theorem reconnectedForwardPath_vertex_eq (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (j : BipartiteVertex m n) (hj : D'.vertex j ∈ Set.range (reconnectedForwardPath Kp Kq hm)) : + j=.inl p.1.1 ∨ j=.inr q.1.2 := by + rcases reconnectedForwardPath_trace Kp Kq hm hj with (hj | hj) | hj + · exact Or.inl (Kp.prefix_vertex_eq j hj) + · exact False.elim (C.reconnection_segment_avoids_vertices p q hm D'.vertex hv true j hj) + · exact Or.inr (Kq.suffix_vertex_eq j hj) + +theorem reconnectedBackwardPath_vertex_eq (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (j : BipartiteVertex m n) (hj : D'.vertex j ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + j=.inl q.1.1 ∨ j=.inr p.1.2 := by + rcases reconnectedBackwardPath_trace Kp Kq hm hj with (hj | hj) | hj + · exact Or.inl (Kq.prefix_vertex_eq j hj) + · exact False.elim (C.reconnection_segment_avoids_vertices p q hm D'.vertex hv false j hj) + · exact Or.inr (Kp.suffix_vertex_eq j hj) + +theorem reconnectedForwardPath_interior_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : BipartiteVertex m n) : + reconnectedForwardPath Kp Kq hm t ≠ D'.vertex j := + path_interior_avoids_vertices_of_range D'.vertex _ _ _ + (reconnectedForwardPath_injective Kp Kq hm hemb) + (reconnectedForwardPath_vertex_eq Kp Kq hm hv) t ht j + +theorem reconnectedBackwardPath_interior_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : BipartiteVertex m n) : + reconnectedBackwardPath Kp Kq hm t ≠ D'.vertex j := + path_interior_avoids_vertices_of_range D'.vertex _ _ _ + (reconnectedBackwardPath_injective Kp Kq hm hemb) + (reconnectedBackwardPath_vertex_eq Kp Kq hm hv) t ht j + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectedWalks.lean b/lean/OAI/Combinatorics/Crossing/ReconnectedWalks.lean new file mode 100644 index 0000000000000000000000000000000000000000..830b053a4963dea4ca30426629070fdf6c871abc --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectedWalks.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.ExteriorCrossingCut +import OAI.Combinatorics.Crossing.SurgeryPathWitnesses + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} {D D' : AdmissibleDrawing m n} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem surgery_forward_adj : (crossingSurgeryGraph C P p q).Adj + (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q)) := + crossingSurgeryGraph_reconnection_adj C P p q true + +theorem surgery_backward_adj : (crossingSurgeryGraph C P p q).Adj + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p)) := + crossingSurgeryGraph_reconnection_adj C P p q false + +def reconnectedForwardWalk (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex (.inl p.1.1)) (D'.vertex (.inr q.1.2)) := + walkThroughChord (Kp.prefixInSurgery p q rfl) + surgery_forward_adj (Kq.suffixInSurgery p q hm.symm) + +def reconnectedBackwardWalk (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex (.inl q.1.1)) (D'.vertex (.inr p.1.2)) := + walkThroughChord (Kq.prefixInSurgery p q hm.symm) + surgery_backward_adj (Kp.suffixInSurgery p q rfl) + +theorem reconnectedForwardWalk_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (graphWalkPath id (reconnectedForwardWalk Kp Kq hm))= + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val)) := by + rw [reconnectedForwardWalk,walkThroughChord_range, + ExteriorCrossingCut.prefixInSurgery_trace,ExteriorCrossingCut.suffixInSurgery_trace] + +theorem reconnectedBackwardWalk_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (graphWalkPath id (reconnectedBackwardWalk Kp Kq hm))= + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) := by + rw [reconnectedBackwardWalk,walkThroughChord_range, + ExteriorCrossingCut.prefixInSurgery_trace,ExteriorCrossingCut.suffixInSurgery_trace] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectionAvoidance.lean b/lean/OAI/Combinatorics/Crossing/ReconnectionAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..562951bd0822213d2f82e44dae2b31c8b4407f97 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectionAvoidance.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.Crossing.ReconnectionChords + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segment_avoids_of_affine_positive (f : Plane → ℝ) (a b x : Plane) + (hf : ∀ t, f (segmentPoint a b t)=(1-t)*f a+t*f b) + (ha : 0 < f a) (hb : 0 < f b) (hx : f x=0) : x ∉ segment ℝ a b := by + intro h + rw [← Path.range_segment] at h + obtain ⟨t,ht⟩ := h + have ht' : segmentPoint a b t.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + have hp := convex_combination_pos (f a) (f b) t.val ha hb t.property + rw [← hf t.val,ht',hx] at hp + exact lt_irrefl 0 hp + +theorem crossing_reconnections_avoid_point (a b c d x : Plane) + (hd : det2 (b-a) (d-c) ≠ 0) (s t : ℝ) + (hs : s ∈ Set.Ioo (0 : ℝ) 1) (ht : t ∈ Set.Ioo (0 : ℝ) 1) + (hx : x=segmentPoint a b s) (hy : x=segmentPoint c d t) : + x ∉ segment ℝ c b ∧ x ∉ segment ℝ a d := by + let F := crossingCoordinates x (b-a) (d-c) + have hFa : F a=(-s,0) := by + simpa only [segmentPoint_zero,zero_sub] using crossingCoordinates_first_segment a b c d x s 0 hd hx + have hFb : F b=(1-s,0) := by + simpa only [segmentPoint_one] using crossingCoordinates_first_segment a b c d x s 1 hd hx + have hFc : F c=(0,-t) := by + simpa only [segmentPoint_zero,zero_sub] using crossingCoordinates_second_segment a b c d x t 0 hd hy + have hFd : F d=(0,1-t) := by + simpa only [segmentPoint_one] using crossingCoordinates_second_segment a b c d x t 1 hd hy + have hF (u v : Plane) (r : ℝ) : F (segmentPoint u v r)=segmentPoint (F u) (F v) r := + crossingCoordinates_affine x (b-a) (d-c) u v r + have hzero : F x=(0,0) := crossingCoordinates_origin x (b-a) (d-c) + constructor + · apply segment_avoids_of_affine_positive (fun z => (F z).1-(F z).2) c b x + · intro r + rw [hF] + dsimp [segmentPoint] + ring + · rw [hFc] + dsimp + linarith [ht.1] + · rw [hFb] + dsimp + linarith [hs.2] + · rw [hzero] + norm_num + · apply segment_avoids_of_affine_positive (fun z => (F z).2-(F z).1) a d x + · intro r + rw [hF] + dsimp [segmentPoint] + ring + · rw [hFa] + dsimp + linarith [hs.1] + · rw [hFd] + dsimp + linarith [ht.2] + · rw [hzero] + norm_num + +theorem DrawingPassages.reconnection_avoids_chord_meeting {m n : ℕ} {D : AdmissibleDrawing m n} + (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ C.crossingDisk p ∧ ∀ i : Bool, + x ∉ segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have hs' : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val=x := by + simpa only [DrawingPassages.crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs + have ht' : segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val=x := by + simpa only [DrawingPassages.crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property + (hs'.trans ht'.symm) + constructor + · change squaredLength (x-(C.innerMark p).val) < C.radius^2 + rw [← hs] + exact C.crossingChord_interior_in_disk p s hsi + · have ha := crossing_reconnections_avoid_point _ _ _ _ x hd s.val t.val hsi hti hs'.symm ht'.symm + intro i + cases i + · exact ha.1 + · exact ha.2 + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectionChords.lean b/lean/OAI/Combinatorics/Crossing/ReconnectionChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..c20a494574db864691839dc12480d09b83c9f7ca --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectionChords.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.CrossingReconnection +import OAI.Combinatorics.Crossing.CrossingDiskNeighborhood + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +def reconnectionStart (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : Plane := + if i then C.portPoint (C.incomingPort p) else C.portPoint (C.incomingPort q) + +def reconnectionEnd (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : Plane := + if i then C.portPoint (C.outgoingPort q) else C.portPoint (C.outgoingPort p) + +theorem reconnection_endpoints_ne (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : + C.reconnectionStart p q i ≠ C.reconnectionEnd p q i := by + cases i + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort q p) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p q) + +theorem crossingChord_meeting_segmentsCrossProperly (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hpq : p ≠ q) (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) + (hxq : x ∈ Set.range (C.crossingChord q)) : + SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have he : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val= + segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val := by + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs.trans ht.symm + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property he + exact ⟨hd,s.val,hsi,t.val,hti,he⟩ + +theorem reconnection_chords_disjoint (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) : + ∀ i j : Bool, i ≠ j → Disjoint + (segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i)) + (segment ℝ (C.reconnectionStart p q j) (C.reconnectionEnd p q j)) := by + have hh := crossing_reconnections_disjoint _ _ _ _ hcross + intro i j hij + cases i <;> cases j + · exact False.elim (hij rfl) + · exact hh + · exact hh.symm + · exact False.elim (hij rfl) + +theorem reconnection_endpoints_on_circle (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + squaredLength (C.reconnectionStart p q i-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.reconnectionEnd p q i-(C.innerMark p).val)=C.radius^2 := by + cases i + · change squaredLength (C.portPoint (C.incomingPort q)-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.portPoint (C.outgoingPort p)-(C.innerMark p).val)=C.radius^2 + exact ⟨by simpa only [hm] using C.incomingPoint_on_circle q,C.outgoingPoint_on_circle p⟩ + · change squaredLength (C.portPoint (C.incomingPort p)-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.portPoint (C.outgoingPort q)-(C.innerMark p).val)=C.radius^2 + exact ⟨C.incomingPoint_on_circle p,by simpa only [hm] using C.outgoingPoint_on_circle q⟩ + +theorem reconnection_open_in_disk (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + openSegmentTrace (C.reconnectionStart p q i) (C.reconnectionEnd p q i) ⊆ C.crossingDisk p := by + rintro x ⟨t,ht,rfl⟩ + exact round_chord_in_open_disk _ _ _ _ (C.reconnection_endpoints_on_circle p q hm i).1 + (C.reconnection_endpoints_on_circle p q hm i).2 (C.reconnection_endpoints_ne p q i) t ht + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectionOppositeCuts.lean b/lean/OAI/Combinatorics/Crossing/ReconnectionOppositeCuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..69cf741d74d9b3f41fbf76d70bd443522d3d4d2f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectionOppositeCuts.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.ReconnectionOtherEdges +import OAI.Combinatorics.Crossing.CutTraceSeparation + +namespace OAI + +noncomputable section +namespace Zarankiewicz.PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : BipartiteVertex m n → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem forward_chord_disjoint_opposite_prefix + (Kq : ExteriorCrossingCut C P q) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val))) := by + have hqp : q.1 ≠ p.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he.symm hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ (C.reconnection_open_in_disk p q hm true) + · simpa only [DrawingPassages.crossingDisk,hm] using Kq.prefix_outside + · intro hx + exact E.assembled_port_not_mem_other_edge v hv q.1 (C.incomingPort p) hqp (Kq.prefix_subset_edge hx) + · exact Kq.outgoing_not_prefix + +theorem forward_chord_disjoint_opposite_suffix + (Kp : ExteriorCrossingCut C P p) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val))) := by + have hpqe : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm true) Kp.suffix_outside + · exact Kp.incoming_not_suffix + · intro hx + exact E.assembled_port_not_mem_other_edge v hv p.1 (C.outgoingPort q) hpqe (Kp.suffix_subset_edge hx) + +theorem backward_chord_disjoint_opposite_prefix + (Kp : ExteriorCrossingCut C P p) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val))) := by + have hpqe : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm false) Kp.prefix_outside + · intro hx + exact E.assembled_port_not_mem_other_edge v hv p.1 (C.incomingPort q) hpqe (Kp.prefix_subset_edge hx) + · exact Kp.outgoing_not_prefix + +theorem backward_chord_disjoint_opposite_suffix + (Kq : ExteriorCrossingCut C P q) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val))) := by + have hqp : q.1 ≠ p.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he.symm hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ (C.reconnection_open_in_disk p q hm false) + · simpa only [DrawingPassages.crossingDisk,hm] using Kq.suffix_outside + · exact Kq.incoming_not_suffix + · intro hx + exact E.assembled_port_not_mem_other_edge v hv q.1 (C.outgoingPort p) hqp (Kq.suffix_subset_edge hx) + +end Zarankiewicz.PolygonalExterior + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectionOtherEdges.lean b/lean/OAI/Combinatorics/Crossing/ReconnectionOtherEdges.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cd83aaccb3b17d8dc46337d90426ea48ab852b9 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectionOtherEdges.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.ConstructAdjacentSurgery + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segment_disjoint_of_open_containment (a b : Plane) (U S : Set Plane) + (hin : openSegmentTrace a b ⊆ U) (hout : Disjoint S U) + (ha : a ∉ S) (hb : b ∉ S) : Disjoint (segment ℝ a b) S := by + apply Set.disjoint_left.mpr + intro x hx hs + rcases segment_endpoint_or_open a b x hx with rfl | rfl | hx + · exact ha hs + · exact hb hs + · exact Set.disjoint_left.mp hout hs (hin hx) + +namespace PolygonalExterior +variable {m n : ℕ} {D : AdmissibleDrawing m n} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_port_not_mem_other_edge (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : BipartiteEdge m n) (r : C.Port) (her : e ≠ r.1.1) : + C.portPoint r ∉ Set.range (E.assembledEdge v e) := + fun hx => her (E.assembled_port_unique_edge v hv e r hx) + +theorem reconnection_other_edge_disjoint (E : PolygonalExterior C) + (v : BipartiteVertex m n → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (i : Bool) (e : BipartiteEdge m n) (hep : e ≠ p.1) (heq : e ≠ q.1) : + Disjoint (segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i)) + (Set.range (E.assembledEdge v e)) := by + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm i) + (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + · cases i + · exact E.assembled_port_not_mem_other_edge v hv e (C.incomingPort q) heq + · exact E.assembled_port_not_mem_other_edge v hv e (C.incomingPort p) hep + · cases i + · exact E.assembled_port_not_mem_other_edge v hv e (C.outgoingPort p) hep + · exact E.assembled_port_not_mem_other_edge v hv e (C.outgoingPort q) heq + +end PolygonalExterior +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReconnectionVertexAvoidance.lean b/lean/OAI/Combinatorics/Crossing/ReconnectionVertexAvoidance.lean new file mode 100644 index 0000000000000000000000000000000000000000..f674241beee39d7763c9b42be1a4a6e2e59bd756 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReconnectionVertexAvoidance.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.Crossing.ReconnectionChords + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : AdmissibleDrawing m n} + +theorem reconnection_segment_in_disk (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) ⊆ + closedRoundDisk (C.innerMark p).val C.radius := by + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,ht⟩ := hx + rw [← ht] + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) ≤ C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_disk _ _ _ _ (C.reconnection_endpoints_on_circle p q hm i).1 + (C.reconnection_endpoints_on_circle p q hm i).2 t.val t.property + +theorem reconnection_segment_avoids_vertices (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (v : BipartiteVertex m n → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (i : Bool) (j : BipartiteVertex m n) : + v j ∉ segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := by + intro hx + have hn : C.innerMark p ≠ C.vertexMark j := by + intro he + exact crossing_not_vertex D.toFiniteIntersectionDrawing (C.innerMark p).val (C.innerMark_is_crossing p) j (congrArg Subtype.val he) + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.reconnection_segment_in_disk p q hm i hx) (hv j).le + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RectangleAlgebra.lean b/lean/OAI/Combinatorics/Crossing/RectangleAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..80b7952de56e20651db1e1f1069a54669d35b493 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RectangleAlgebra.lean @@ -0,0 +1,59 @@ +import Mathlib.Data.Matrix.Basic +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Tactic.Linarith +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Ring + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators +variable {ι κ : Type*} [Fintype ι] [Fintype κ] [DecidableEq ι] [DecidableEq κ] + +def edgePairing (J : Matrix ι ι ℝ) (z y : ι → ℝ) : ℝ := + ∑ e, ∑ f, z e * J e f * y f + +theorem edgePairing_single (J : Matrix ι ι ℝ) (e f : ι) : + edgePairing J (Pi.single e 1) (Pi.single f 1) = J e f := by + simp [edgePairing, Pi.single_apply] + +theorem edgePairing_add_left + {ι : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (z z' y : ι → ℝ) : + edgePairing J (z+z') y = edgePairing J z y + edgePairing J z' y := by + simp [edgePairing, add_mul, Finset.sum_add_distrib] + +theorem edgePairing_add_right + {ι : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (z y y' : ι → ℝ) : + edgePairing J z (y+y') = edgePairing J z y + edgePairing J z y' := by + simp [edgePairing, mul_add, Finset.sum_add_distrib] + +theorem edgePairing_sub_left + {ι : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (z z' y : ι → ℝ) : + edgePairing J (z-z') y = edgePairing J z y - edgePairing J z' y := by + simp [edgePairing, sub_mul, Finset.sum_sub_distrib] + +theorem edgePairing_sub_right + {ι : Type*} [Fintype ι] [DecidableEq ι] + (J : Matrix ι ι ℝ) (z y y' : ι → ℝ) : + edgePairing J z (y-y') = edgePairing J z y - edgePairing J z y' := by + simp [edgePairing, mul_sub, Finset.sum_sub_distrib] + +theorem rectangle_additive + {ι κ : Type*} [Fintype ι] [Fintype κ] [DecidableEq ι] [DecidableEq κ] + (H : Matrix ι κ ℝ) (i₀ : ι) (j₀ : κ) + (hrect : ∀ i i' j j', H i j-H i j'-H i' j+H i' j' = 0) : + ∃ r : ι → ℝ, ∃ c : κ → ℝ, ∀ i j, H i j = r i+c j := by + refine ⟨fun i => H i j₀, fun j => H i₀ j-H i₀ j₀, ?_⟩ + intro i j + have hh := hrect i i₀ j j₀ + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReducedCrossingCorners.lean b/lean/OAI/Combinatorics/Crossing/ReducedCrossingCorners.lean new file mode 100644 index 0000000000000000000000000000000000000000..af20495c96a7b9d4a7e76c9f0ea208f4afaa0145 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReducedCrossingCorners.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.Crossing.LocalLineBends +import OAI.Combinatorics.Crossing.ReducedPolygonalPresentation +import OAI.Combinatorics.Crossing.LocallyStraightNormalization +import OAI.Combinatorics.Crossing.DrawingRangeCrossings + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem det2_of_common_openSegment (a b x z : Plane) + (hx : x ∈ openSegmentTrace a b) (hz : z ∈ openSegmentTrace a b) : + det2 (b-a) (z-x)=0 := by + obtain ⟨t,ht,rfl⟩ := hx + obtain ⟨u,hu,rfl⟩ := hz + dsimp [det2,segmentPoint] + ring + +theorem LocallyStraightAt.exists_trace_line (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) (x : Plane) (hx : x ∈ edgeInterior D e) + (h : LocallyStraightAt D e x) : + ∃ d : Plane, d ≠ 0 ∧ ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + ∀ z ∈ U, z ∈ Set.range (D.edge e) → det2 d (z-x)=0 := by + obtain ⟨a,b,hab,hxab,U,hU,hxU,htrace⟩ := h + let V : Set Plane := Set.range D.vertex + have hV : IsClosed V := (Set.finite_range D.vertex).isClosed + have hxV : x ∉ V := by + rintro ⟨j,hj⟩ + exact edgeInterior_not_vertex D e x hx j hj.symm + refine ⟨b-a,sub_ne_zero.mpr (Ne.symm hab),U ∩ Vᶜ,hU.inter hV.isOpen_compl,⟨hxU,hxV⟩,?_⟩ + intro z hz hze + have hzi : z ∈ edgeInterior D e := edgeInterior_of_range_not_vertices D e z hze (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment a b x z hxab ((htrace z hz.1).mp hzi) + +theorem minimum_bend_not_locallyStraight (D : ContinuousDrawing m n) + (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) (hx : P.vertices (i+1) ∈ edgeInterior D e) : + ¬ LocallyStraightAt D e (P.vertices (i+1)) := by + intro h + obtain ⟨d,hd,U,hU,hxU,hh⟩ := LocallyStraightAt.exists_trace_line D e _ hx h + apply P.minimum_bend_det_ne_zero hmin i hi + apply bend_det_zero_of_local_line _ _ _ d hd U hU hxU + intro z hz hseg + apply hh z hz + rcases hseg with hseg | hseg + · exact P.inside i (by omega) hseg + · exact P.inside (i+1) (by omega) hseg + +theorem minimum_bend_not_crossing (D : AdmissibleDrawing m n) + (hstraight : LocallyStraightCrossings D) (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) : P.vertices (i+1) ∉ crossingPoints D.toContinuousDrawing := by + rintro ⟨f,g,hfg,hf,hg⟩ + have hx : P.vertices (i+1) ∈ edgeInterior D.toContinuousDrawing e := + edgeInterior_of_range_not_vertices D.toContinuousDrawing e _ (P.vertex_mem (i+1) (by omega)) + (edgeInterior_not_vertex D.toContinuousDrawing f _ hf) + apply minimum_bend_not_locallyStraight D.toContinuousDrawing e P hmin i hi hx + by_cases hef : e=f + · subst f + exact (hstraight e g hfg _ hx hg).1 + · exact (hstraight e f hef _ hx hf).1 + +theorem minimum_vertices_not_crossing (D : AdmissibleDrawing m n) + (hstraight : LocallyStraightCrossings D) (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i ≤ P.pieces) : P.vertices i ∉ crossingPoints D.toContinuousDrawing := by + by_cases h0 : i=0 + · subst i + rw [P.first] + rintro ⟨f,g,hfg,hf,hg⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing f _ hf (.inl e.1) rfl + by_cases hn : i=P.pieces + · subst i + rw [P.last] + rintro ⟨f,g,hfg,hf,hg⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing f _ hf (.inr e.2) rfl + have h := minimum_bend_not_crossing D hstraight e P hmin (i-1) (by omega) + simpa only [show i-1+1=i by omega] using h + +theorem minimum_piece_crossing_open (D : AdmissibleDrawing m n) + (hstraight : LocallyStraightCrossings D) (e : BipartiteEdge m n) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) (x : Plane) (hx : x ∈ crossingPoints D.toContinuousDrawing) + (hseg : x ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) : + x ∈ openSegmentTrace (P.vertices i) (P.vertices (i+1)) := by + rw [← Path.range_segment] at hseg + obtain ⟨t,ht⟩ := hseg + have ht0 : t ≠ 0 := by + intro h + subst t + simp only [Path.source] at ht + exact minimum_vertices_not_crossing D hstraight e P hmin i (by omega) (ht.symm ▸ hx) + have ht1 : t ≠ 1 := by + intro h + subst t + simp only [Path.target] at ht + exact minimum_vertices_not_crossing D hstraight e P hmin (i+1) (by omega) (ht.symm ▸ hx) + refine ⟨t.val,⟨?_,?_⟩,?_⟩ + · exact lt_of_le_of_ne t.property.1 (fun h => ht0 (Subtype.ext h.symm)) + · exact lt_of_le_of_ne t.property.2 (fun h => ht1 (Subtype.ext h)) + · simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReducedCrossingTransversality.lean b/lean/OAI/Combinatorics/Crossing/ReducedCrossingTransversality.lean new file mode 100644 index 0000000000000000000000000000000000000000..34221b780fd0ff4fc7f6a7d01189d0080ac654ac --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReducedCrossingTransversality.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.ReducedCrossingCorners +import OAI.Combinatorics.Crossing.LocalSegmentTransversality +import OAI.Combinatorics.Crossing.LocallyTransverseNormalization + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +theorem LocallyTransverseCrossings.exists_trace_lines (D : AdmissibleDrawing m n) + (h : LocallyTransverseCrossings D) (e f : BipartiteEdge m n) (hef : e ≠ f) + (x : Plane) (hxe : x ∈ edgeInterior D.toContinuousDrawing e) + (hxf : x ∈ edgeInterior D.toContinuousDrawing f) : + ∃ d k : Plane, det2 d k ≠ 0 ∧ ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + (∀ z ∈ U, z ∈ Set.range (D.edge e) → det2 d (z-x)=0) ∧ + (∀ z ∈ U, z ∈ Set.range (D.edge f) → det2 k (z-x)=0) := by + obtain ⟨a,b,c,d,hdet,hxab,hxcd,U,hU,hxU,htraceE,htraceF⟩ := h e f hef x hxe hxf + let V : Set Plane := Set.range D.vertex + have hV : IsClosed V := (Set.finite_range D.vertex).isClosed + have hxV : x ∉ V := by + rintro ⟨j,hj⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing e x hxe j hj.symm + refine ⟨b-a,d-c,hdet,U ∩ Vᶜ,hU.inter hV.isOpen_compl,⟨hxU,hxV⟩,?_,?_⟩ + · intro z hz hze + have hzi := edgeInterior_of_range_not_vertices D.toContinuousDrawing e z hze (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment a b x z hxab ((htraceE z hz.1).mp hzi) + · intro z hz hzf + have hzi := edgeInterior_of_range_not_vertices D.toContinuousDrawing f z hzf (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment c d x z hxcd ((htraceF z hz.1).mp hzi) + +theorem minimum_piece_det_at_crossing (D : AdmissibleDrawing m n) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (e f : BipartiteEdge m n) (hef : e ≠ f) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (Q : PolygonalChain (Set.range (D.edge f)) (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) + (hP : ∀ R : PolygonalChain (Set.range (D.edge e)) (D.vertex (.inl e.1)) + (D.vertex (.inr e.2)), P.pieces ≤ R.pieces) + (hQ : ∀ R : PolygonalChain (Set.range (D.edge f)) (D.vertex (.inl f.1)) + (D.vertex (.inr f.2)), Q.pieces ≤ R.pieces) + (i j : ℕ) (hi : i < P.pieces) (hj : j < Q.pieces) (x : Plane) + (hxe : x ∈ edgeInterior D.toContinuousDrawing e) (hxf : x ∈ edgeInterior D.toContinuousDrawing f) + (hxp : x ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) + (hxq : x ∈ segment ℝ (Q.vertices j) (Q.vertices (j+1))) : + det2 (P.vertices (i+1)-P.vertices i) (Q.vertices (j+1)-Q.vertices j) ≠ 0 := by + have hx : x ∈ crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hxe,hxf⟩ + have hpo := minimum_piece_crossing_open D hstraight e P hP i hi x hx hxp + have hqo := minimum_piece_crossing_open D hstraight f Q hQ j hj x hx hxq + obtain ⟨d,k,hdk,U,hU,hxU,hlineP,hlineQ⟩ := + LocallyTransverseCrossings.exists_trace_lines D htrans e f hef x hxe hxf + have hd := segment_direction_of_local_line_at_interior _ _ x d hpo U hU hxU + (fun z hz hs => hlineP z hz (P.inside i hi hs)) + have hk := segment_direction_of_local_line_at_interior _ _ x k hqo U hU hxU + (fun z hz hs => hlineQ z hz (Q.inside j hj hs)) + exact det2_ne_zero_of_parallel_nonzero d k _ _ hdk + (P.minimum_piece_ne_zero hP i hi) (Q.minimum_piece_ne_zero hQ j hj) hd hk + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReducedPolygonalPresentation.lean b/lean/OAI/Combinatorics/Crossing/ReducedPolygonalPresentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f535a7cbb9ebd8ea63cf7df9930a2f511b19c35 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReducedPolygonalPresentation.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.Crossing.SubdivisionSegments +import OAI.Combinatorics.Crossing.PolygonalArcInjective +import OAI.Combinatorics.Crossing.ArcRangeMinimality + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def PolygonalParametrization.containedChain {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : PolygonalChain (Set.range γ) a b where + pieces := P.pieces + vertices := P.vertices + first := P.vertices_first + last := P.vertices_last + start_mem := ⟨0,γ.source⟩ + inside := by + intro i hi + let j : Fin P.pieces := ⟨i,hi⟩ + have h0 : P.vertices i=γ (P.knot j.castSucc) := P.vertices_at j.castSucc + have h1 : P.vertices (i+1)=γ (P.knot j.succ) := P.vertices_at j.succ + rw [h0,h1] + exact P.pieceTrace_subset_range j + +theorem PolygonalChain.pieces_pos_of_ne {O : Set Plane} {a b : Plane} + (P : PolygonalChain O a b) (hab : a ≠ b) : 0 < P.pieces := by + by_contra hh + have hz : P.pieces=0 := by omega + exact hab (P.first.symm.trans (hz ▸ P.last)) + +theorem exists_reduced_polygonalChain {a b : Plane} (γ : Path a b) + (hinj : Function.Injective γ) (hpoly : HasFiniteAffineCover γ) : + ∃ P : PolygonalChain (Set.range γ) a b, + Set.range P.path=Set.range γ ∧ Function.Injective P.path ∧ 0 < P.pieces ∧ + (∀ i, i < P.pieces → P.vertices (i+1)-P.vertices i ≠ 0) ∧ + (∀ i, i+2 ≤ P.pieces → + det2 (P.vertices (i+1)-P.vertices i) (P.vertices (i+2)-P.vertices (i+1)) ≠ 0) ∧ + (∀ Q : PolygonalChain (Set.range γ) a b, P.pieces ≤ Q.pieces) := by + have hab : a ≠ b := by + intro h + exact zero_ne_one (hinj (γ.source.trans (h.trans γ.target.symm))) + obtain ⟨Q⟩ := hpoly.nonempty_polygonalParametrization + obtain ⟨P,hmin⟩ := exists_minimum_polygonalChain ⟨Q.containedChain⟩ + exact ⟨P,path_range_eq_of_subset γ P.path hinj P.path_range_subset, + P.minimum_path_injective hab hmin,P.pieces_pos_of_ne hab, + P.minimum_piece_ne_zero hmin,P.minimum_bend_det_ne_zero hmin,hmin⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReplaceDrawingEdges.lean b/lean/OAI/Combinatorics/Crossing/ReplaceDrawingEdges.lean new file mode 100644 index 0000000000000000000000000000000000000000..6969942d3fc7b19e84142bc355385719688df632 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReplaceDrawingEdges.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.Crossing.ReconnectedVertexAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.ContinuousDrawing +variable {m n : ℕ} + +def replaceTwoRoutes (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) + (g : BipartiteEdge m n) : Path (D.vertex (.inl g.1)) (D.vertex (.inr g.2)) := by + classical + exact if h : g=e then γ.cast (congrArg (fun k : BipartiteEdge m n => D.vertex (.inl k.1)) h) + (congrArg (fun k : BipartiteEdge m n => D.vertex (.inr k.2)) h) + else if h : g=f then δ.cast (congrArg (fun k : BipartiteEdge m n => D.vertex (.inl k.1)) h) + (congrArg (fun k : BipartiteEdge m n => D.vertex (.inr k.2)) h) + else D.edge g + +theorem replaceTwoRoutes_first (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) : + D.replaceTwoRoutes e f γ δ e=γ := by + simp only [replaceTwoRoutes,dite_eq_left rfl,Path.cast_rfl_rfl] + +theorem replaceTwoRoutes_second (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) (hef : e ≠ f) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) : + D.replaceTwoRoutes e f γ δ f=δ := by + simp only [replaceTwoRoutes,dite_eq_right (Ne.symm hef),dite_eq_left rfl,Path.cast_rfl_rfl] + +theorem replaceTwoRoutes_other (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) + (g : BipartiteEdge m n) (hge : g ≠ e) (hgf : g ≠ f) : + D.replaceTwoRoutes e f γ δ g=D.edge g := by + simp only [replaceTwoRoutes,dite_eq_right hge,dite_eq_right hgf] + +def replaceTwoEdges (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) + (hγ : Function.Injective γ) (hδ : Function.Injective δ) + (hvγ : ∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → ∀ j, γ t ≠ D.vertex j) + (hvδ : ∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → ∀ j, δ t ≠ D.vertex j) : + ContinuousDrawing m n where + vertex := D.vertex + vertex_injective := D.vertex_injective + edge := D.replaceTwoRoutes e f γ δ + edge_injective := by + intro g + classical + by_cases hge : g=e + · subst g + rw [replaceTwoRoutes_first] + exact hγ + by_cases hgf : g=f + · subst g + rw [replaceTwoRoutes_second _ _ _ (Ne.symm hge)] + exact hδ + · rw [replaceTwoRoutes_other _ _ _ _ _ _ hge hgf] + exact D.edge_injective g + interior_avoids_vertices := by + intro g t ht j + classical + by_cases hge : g=e + · subst g + rw [replaceTwoRoutes_first] + exact hvγ t ht j + by_cases hgf : g=f + · subst g + rw [replaceTwoRoutes_second _ _ _ (Ne.symm hge)] + exact hvδ t ht j + · rw [replaceTwoRoutes_other _ _ _ _ _ _ hge hgf] + exact D.interior_avoids_vertices g t ht j + +end Zarankiewicz.ContinuousDrawing + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ReplaceDrawingRangeCases.lean b/lean/OAI/Combinatorics/Crossing/ReplaceDrawingRangeCases.lean new file mode 100644 index 0000000000000000000000000000000000000000..d01ac48fbe5c2d6556dc3642b4034e167a6a288c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ReplaceDrawingRangeCases.lean @@ -0,0 +1,28 @@ +import OAI.Combinatorics.Crossing.ReplaceDrawingEdges + +namespace OAI + +noncomputable section +namespace Zarankiewicz.ContinuousDrawing +variable {m n : ℕ} + +theorem replaceTwoRoutes_range_cases (D : ContinuousDrawing m n) (e f : BipartiteEdge m n) + (γ : Path (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (δ : Path (D.vertex (.inl f.1)) (D.vertex (.inr f.2))) + (g : BipartiteEdge m n) (x : Plane) (hx : x ∈ Set.range (D.replaceTwoRoutes e f γ δ g)) : + (g=e ∧ x ∈ Set.range γ) ∨ (g=f ∧ x ∈ Set.range δ) ∨ + (g ≠ e ∧ g ≠ f ∧ x ∈ Set.range (D.edge g)) := by + classical + by_cases hge : g=e + · subst g + exact Or.inl ⟨rfl,by simpa only [replaceTwoRoutes_first] using hx⟩ + by_cases hgf : g=f + · subst g + exact Or.inr (Or.inl ⟨rfl,by simpa only [replaceTwoRoutes_second D e f (Ne.symm hge)] using hx⟩) + · exact Or.inr (Or.inr ⟨hge,hgf,by simpa only [replaceTwoRoutes_other D e f γ δ g hge hgf] using hx⟩) + +end Zarankiewicz.ContinuousDrawing + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RetainedArcDisjointness.lean b/lean/OAI/Combinatorics/Crossing/RetainedArcDisjointness.lean new file mode 100644 index 0000000000000000000000000000000000000000..02bc259f4490b3426b6bcb5d587574307f43cd38 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RetainedArcDisjointness.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.Crossing.RetainedDrawingArcs + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +theorem arcs_pairwise_disjoint (C : DrawingPassages D) (p q : C.ArcIndex) (hpq : p ≠ q) : + Disjoint (Set.range (C.arc p)) (Set.range (C.arc q)) := by + apply Set.disjoint_left.mpr + intro x hx hy + have hxm := C.arc_avoids_marks p x hx + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + rw [C.arc_range] at hx hy + obtain ⟨s,hs,hsx⟩ := hx + obtain ⟨t,ht,htx⟩ := hy + have hef : e=f := unmarked_intersection_same_edge D e f s t (hsx.trans htx.symm) + (hsx.symm ▸ hxm) + subst f + have hst : s=t := D.edge_injective e (hsx.trans htx.symm) + rw [← hst] at ht + have hij : i ≠ j := by + intro he + subst j + exact hpq rfl + rcases lt_or_gt_of_ne hij with hij | hji + · exact Set.disjoint_left.mp + (retained_interval_pair_disjoint (D.edge e) (C.node e) C.radius (C.passage e) (C.separated e) i j hij) hs ht + · exact Set.disjoint_left.mp + (retained_interval_pair_disjoint (D.edge e) (C.node e) C.radius (C.passage e) (C.separated e) j i hji) ht hs + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RetainedDrawingArcs.lean b/lean/OAI/Combinatorics/Crossing/RetainedDrawingArcs.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce0bb51c0e88c51418e552dad879e56c278eb570 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RetainedDrawingArcs.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.Crossing.DrawingPassages +import OAI.Combinatorics.Crossing.IntervalSegmentStrict +import OAI.Combinatorics.Crossing.FiniteDiskCollar + +namespace OAI + +noncomputable section +namespace Zarankiewicz.DrawingPassages +variable {m n : ℕ} {D : FiniteIntersectionDrawing m n} + +abbrev ArcIndex (C : DrawingPassages D) := (e : BipartiteEdge m n) × Fin (C.count e) + +theorem node_mark (C : DrawingPassages D) (e : BipartiteEdge m n) (i : Fin (C.count e+1)) : + D.edge e (C.node e i) ∈ drawingMarks D := by + change C.node e i ∈ (D.edge e) ⁻¹' drawingMarks D + rw [← C.node_range e] + exact ⟨i,rfl⟩ + +def arcStartMark (C : DrawingPassages D) (i : C.ArcIndex) : DrawingMark D := + ⟨D.edge i.1 (C.node i.1 i.2.castSucc),C.node_mark i.1 i.2.castSucc⟩ + +def arcEndMark (C : DrawingPassages D) (i : C.ArcIndex) : DrawingMark D := + ⟨D.edge i.1 (C.node i.1 i.2.succ),C.node_mark i.1 i.2.succ⟩ + +def arcStart (C : DrawingPassages D) (i : C.ArcIndex) : Plane := + D.edge i.1 (C.passage i.1 i.2.castSucc).leave + +def arcEnd (C : DrawingPassages D) (i : C.ArcIndex) : Plane := + D.edge i.1 (C.passage i.1 i.2.succ).enter + +def arc (C : DrawingPassages D) (i : C.ArcIndex) : Path (C.arcStart i) (C.arcEnd i) := + retainedSubarc (D.edge i.1) (C.node i.1) C.radius (C.passage i.1) i.2 + +theorem arc_gap (C : DrawingPassages D) (i : C.ArcIndex) : + (C.passage i.1 i.2.castSucc).leave < (C.passage i.1 i.2.succ).enter := + C.separated i.1 i.2.castSucc i.2.succ (by change i.2.val < i.2.val+1; omega) + +theorem arc_injective (C : DrawingPassages D) (i : C.ArcIndex) : Function.Injective (C.arc i) := + pathSubarc_injective (D.edge i.1) (D.edge_injective i.1) _ _ (C.arc_gap i) + +theorem arc_endpoints_ne (C : DrawingPassages D) (i : C.ArcIndex) : C.arcStart i ≠ C.arcEnd i := by + intro he + exact (C.arc_gap i).ne (D.edge_injective i.1 he) + +theorem arc_range (C : DrawingPassages D) (i : C.ArcIndex) : + Set.range (C.arc i)=D.edge i.1 '' Set.Icc (C.passage i.1 i.2.castSucc).leave (C.passage i.1 i.2.succ).enter := + pathSubarc_range (D.edge i.1) _ _ (C.arc_gap i) + +theorem arc_avoids_marks (C : DrawingPassages D) (i : C.ArcIndex) (x : Plane) + (hx : x ∈ Set.range (C.arc i)) : x ∉ drawingMarks D := by + rw [C.arc_range] at hx + obtain ⟨t,ht,rfl⟩ := hx + intro hh + have hp : t ∈ Set.range (C.node i.1) := by rw [C.node_range]; exact hh + exact retained_interval_no_mark (D.edge i.1) (C.node i.1) (C.increasing i.1) + (C.first i.1) (C.last i.1) C.radius (C.passage i.1) i.2 t ht hp + +theorem retained_parameter_outside (C : DrawingPassages D) (i : C.ArcIndex) (t : unitInterval) + (ht : t ∈ Set.Ioo (C.passage i.1 i.2.castSucc).leave (C.passage i.1 i.2.succ).enter) : + D.edge i.1 t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius := by + intro x + apply lt_of_not_ge + intro hh + obtain ⟨u,hu⟩ := C.visited_mark_on_edge i.1 x t hh + have hmu : u ∈ Set.range (C.node i.1) := by + rw [C.node_range] + change D.edge i.1 u ∈ drawingMarks D + rw [hu] + exact x.property + obtain ⟨j,hj⟩ := hmu + have hc : D.edge i.1 (C.node i.1 j)=x.val := (congrArg (D.edge i.1) hj).trans hu + have hv := (C.passage i.1 j).all_visits t (by rw [hc]; exact hh) + by_cases hji : j ≤ i.2.castSucc + · have hm := (ordered_passage_leave_strictMono (D.edge i.1) (C.node i.1) C.radius + (C.passage i.1) (C.separated i.1)).monotone hji + exact ht.1.not_ge (hv.2.trans hm) + · have hij : i.2.succ ≤ j := by + change i.2.val+1 ≤ j.val + have hn : ¬ j.val ≤ i.2.val := hji + omega + have hm := (ordered_passage_enter_strictMono (D.edge i.1) (C.node i.1) C.radius + (C.passage i.1) (C.separated i.1)).monotone hij + exact ht.2.not_ge (hm.trans hv.1) + +theorem arc_interior_outside (C : DrawingPassages D) (i : C.ArcIndex) (t : unitInterval) + (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : + C.arc i t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius := by + exact C.retained_parameter_outside i _ (intervalSegment_strict_between _ _ t (C.arc_gap i) ht) + +theorem arc_start_on_circle (C : DrawingPassages D) (i : C.ArcIndex) : + squaredLength (C.arcStart i-(C.arcStartMark i).val)=C.radius^2 := by + exact (C.passage i.1 i.2.castSucc).leave_boundary + ((C.arc_gap i).trans_le (show (C.passage i.1 i.2.succ).enter ≤ 1 from (C.passage i.1 i.2.succ).enter.property.2)) + +theorem arc_end_on_circle (C : DrawingPassages D) (i : C.ArcIndex) : + squaredLength (C.arcEnd i-(C.arcEndMark i).val)=C.radius^2 := by + exact (C.passage i.1 i.2.succ).enter_boundary + ((show 0 ≤ (C.passage i.1 i.2.castSucc).leave from (C.passage i.1 i.2.castSucc).leave.property.1).trans_lt (C.arc_gap i)) + +end Zarankiewicz.DrawingPassages + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RoundCircleChords.lean b/lean/OAI/Combinatorics/Crossing/RoundCircleChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..79621292cfb8727e49baff029ba6dd899a673a48 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RoundCircleChords.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.Crossing.RadialExterior +import OAI.Combinatorics.Crossing.ChordTransversality + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem round_circle_line_two_points (z a b c : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hc : squaredLength (c-z)=r^2) (hab : a ≠ b) + (hd : det2 (b-a) (c-a)=0) : c=a ∨ c=b := by + have hlen := squaredLength_pos (b-a) (sub_ne_zero.mpr (Ne.symm hab)) + let t := dot2 (b-a) (c-a)/squaredLength (b-a) + have hp : c-a=t • (b-a) := vector_parallel_of_det_zero (b-a) (c-a) + (sub_ne_zero.mpr (Ne.symm hab)) hd + have hba : (a-z)+(b-a)=b-z := by abel + have hca : c-z=(a-z)+t • (b-a) := by rw [← hp]; abel + have h₁ := squaredLength_add_smul (a-z) (b-a) 1 + simp only [one_smul,hba,ha,hb,one_pow,one_mul] at h₁ + rw [hca,squaredLength_add_smul,ha] at hc + have hh : t*(t-1)*squaredLength (b-a)=0 := by linear_combination hc+t*h₁ + have ht := (mul_eq_zero.mp hh).resolve_right (ne_of_gt hlen) + rcases mul_eq_zero.mp ht with ht | ht + · left + rw [ht,zero_smul] at hp + exact sub_eq_zero.mp hp + · right + have ht1 : t=1 := sub_eq_zero.mp ht + rw [ht1,one_smul] at hp + exact sub_left_injective hp + +theorem round_circle_orient_ne_zero (z a b c : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hc : squaredLength (c-z)=r^2) (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) : + orient2 a b c ≠ 0 := by + intro hd + exact (round_circle_line_two_points z a b c r ha hb hc hab hd).elim + (fun h => hac h.symm) (fun h => hbc h.symm) + +theorem round_circle_chords_transverse (z a b c d : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hc : squaredLength (c-z)=r^2) (hd : squaredLength (d-z)=r^2) + (hab : a ≠ b) (hcd : c ≠ d) (hac : a ≠ c) (had : a ≠ d) (hbc : b ≠ c) (hbd : b ≠ d) : + SegmentPairTransverse a b c d := by + exact segmentPairTransverse_of_noncollinear_endpoints a b c d + (round_circle_orient_ne_zero z c d a r hc hd ha hcd hac.symm had.symm) + (round_circle_orient_ne_zero z c d b r hc hd hb hcd hbc.symm hbd.symm) + (round_circle_orient_ne_zero z a b c r ha hb hc hab hac hbc) + (round_circle_orient_ne_zero z a b d r ha hb hd hab had hbd) + +theorem round_chord_in_open_disk (z a b : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hab : a ≠ b) (t : ℝ) (ht : t ∈ Set.Ioo (0 : ℝ) 1) : + squaredLength (segmentPoint a b t-z) < r^2 := by + have he : squaredLength (segmentPoint a b t-z)= + (1-t)*squaredLength (a-z)+t*squaredLength (b-z)-t*(1-t)*squaredLength (b-a) := by + dsimp [squaredLength,segmentPoint] + ring + have hp := mul_pos (mul_pos ht.1 (sub_pos.mpr ht.2)) + (squaredLength_pos (b-a) (sub_ne_zero.mpr hab.symm)) + rw [he,ha,hb] + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RoundDiskChords.lean b/lean/OAI/Combinatorics/Crossing/RoundDiskChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..d432a5a36e4d5b2db729b85a3d5add06240cedf0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RoundDiskChords.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.RoundCircleChords +import OAI.Combinatorics.Crossing.RoundDiskClearance + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem round_chord_subset_closed_disk (z a b : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) : + segment ℝ a b ⊆ closedRoundDisk z r := by + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,rfl⟩ := hx + change squaredLength (Path.segment a b t-z) ≤ r^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + have he : squaredLength (segmentPoint a b t.val-z)= + (1-t.val)*squaredLength (a-z)+t.val*squaredLength (b-z)- + t.val*(1-t.val)*squaredLength (b-a) := by + dsimp [squaredLength,segmentPoint] + ring + change squaredLength (segmentPoint a b t.val-z) ≤ r^2 + rw [he,ha,hb] + have hnon : 0 ≤ t.val*(1-t.val)*squaredLength (b-a) := by + have ht0 := t.property.1 + have ht1 := sub_nonneg.mpr t.property.2 + dsimp [squaredLength] + positivity + linarith + +theorem round_chord_boundary_endpoints (z a b x : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hx : x ∈ segment ℝ a b) (hboundary : squaredLength (x-z)=r^2) : x=a ∨ x=b := by + by_cases hab : a=b + · subst b + exact Or.inl (by simpa only [segment_same,Set.mem_singleton_iff] using hx) + · rw [← Path.range_segment] at hx + obtain ⟨t,rfl⟩ := hx + by_cases ht0 : t.val=0 + · left + simp only [Path.segment_apply,AffineMap.lineMap_apply_module,ht0,sub_zero,one_smul,zero_smul,add_zero] + · by_cases ht1 : t.val=1 + · right + simp only [Path.segment_apply,AffineMap.lineMap_apply_module,ht1,sub_self,one_smul,zero_smul,zero_add] + · have hstrict := round_chord_in_open_disk z a b r ha hb hab t.val + ⟨lt_of_le_of_ne t.property.1 (Ne.symm ht0),lt_of_le_of_ne t.property.2 ht1⟩ + have hb' : squaredLength (segmentPoint a b t.val-z)=r^2 := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hboundary + rw [hb'] at hstrict + exact False.elim (lt_irrefl _ hstrict) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RoundDiskClearance.lean b/lean/OAI/Combinatorics/Crossing/RoundDiskClearance.lean new file mode 100644 index 0000000000000000000000000000000000000000..3efba86bc08cf826f92adcfa68a85622ee3dcbf0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RoundDiskClearance.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.Crossing.OffsetVectors +import OAI.Combinatorics.Crossing.FiniteSeparation +import Mathlib.Topology.MetricSpace.Pseudo.Defs + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical Topology + +def closedRoundDisk (z : Plane) (r : ℝ) : Set Plane := {x | squaredLength (x-z) ≤ r^2} + +theorem dist_le_of_mem_closedRoundDisk (z x : Plane) (r : ℝ) (hr : 0 ≤ r) + (hx : x ∈ closedRoundDisk z r) : dist x z ≤ r := by + change (x.1-z.1)^2+(x.2-z.2)^2 ≤ r^2 at hx + rw [Prod.dist_eq,Real.dist_eq,Real.dist_eq,max_le_iff,abs_le,abs_le] + have h₁ := sq_nonneg (x.1-z.1) + have h₂ := sq_nonneg (x.2-z.2) + constructor <;> constructor <;> nlinarith + +theorem exists_round_disk_clearance {ι : Type*} [Fintype ι] + (z : ι → Plane) (K : ι → Set Plane) (hK : ∀ i, IsCompact (K i)) + (hz : ∀ i, z i ∉ K i) : + ∃ r : ℝ, 0 < r ∧ ∀ i, Disjoint (closedRoundDisk (z i) r) (K i) := by + have hex (i : ι) : ∃ ε : ℝ, 0 < ε ∧ Metric.ball (z i) ε ⊆ (K i)ᶜ := + Metric.mem_nhds_iff.mp ((hK i).isClosed.isOpen_compl.mem_nhds (hz i)) + choose radius hpos hclear using hex + obtain ⟨r,hr,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun i _ => hpos i) + refine ⟨r,hr,?_⟩ + intro i + apply Set.disjoint_left.mpr + intro x hx hmem + have hd := dist_le_of_mem_closedRoundDisk (z i) x r hr.le hx + exact hclear i (hd.trans_lt (hbound i (Finset.mem_univ _))) hmem + +theorem exists_disjoint_round_disks {ι : Type*} [Fintype ι] [DecidableEq ι] + (z : ι → Plane) (hz : Function.Injective z) : + ∃ r : ℝ, 0 < r ∧ ∀ i j, i ≠ j → Disjoint (closedRoundDisk (z i) r) (closedRoundDisk (z j) r) := by + obtain ⟨δ,hδ,hgap⟩ := finite_positive_lower_bound + (Finset.univ.filter (fun ij : ι × ι => ij.1 ≠ ij.2)) (fun ij => dist (z ij.1) (z ij.2)) (by + intro ij hij + exact dist_pos.mpr (hz.ne (Finset.mem_filter.mp hij).2)) + refine ⟨δ/3,by positivity,?_⟩ + intro i j hij + apply Set.disjoint_left.mpr + intro x hx hy + have h₁ := dist_le_of_mem_closedRoundDisk (z i) x (δ/3) (by positivity) hx + have h₂ := dist_le_of_mem_closedRoundDisk (z j) x (δ/3) (by positivity) hy + have htri := dist_triangle (z i) x (z j) + rw [dist_comm (z i) x] at htri + have hg := hgap (i,j) (by simpa using hij) + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RoundDiskVisits.lean b/lean/OAI/Combinatorics/Crossing/RoundDiskVisits.lean new file mode 100644 index 0000000000000000000000000000000000000000..e41fa21827febfa110e11d1ccdb7b12a771ee435 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RoundDiskVisits.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.EndpointVisits + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem continuous_path_squared_distance {a b : Plane} (γ : Path a b) (z : Plane) : + Continuous (fun t : ℝ => squaredLength (γ.extend t-z)) := by + unfold squaredLength + fun_prop + +theorem path_round_disk_visits {a b : Plane} (γ : Path a b) (z : Plane) (r : ℝ) + (h0 : a ∉ closedRoundDisk z r) (h1 : b ∉ closedRoundDisk z r) + (τ : unitInterval) (hτ0 : 0 < τ.val) (hτ1 : τ.val < 1) + (hτ : squaredLength (γ τ-z) < r^2) : + ∃ u v : unitInterval, 0 < u.val ∧ u < τ ∧ τ < v ∧ v.val < 1 ∧ + squaredLength (γ u-z)=r^2 ∧ squaredLength (γ v-z)=r^2 ∧ + (∀ t : unitInterval, γ t ∈ closedRoundDisk z r → u ≤ t ∧ t ≤ v) := by + obtain ⟨u,v,hu0,huτ,hτv,hv1,hu,hv,hh⟩ := first_last_sublevel_visits + (fun t => squaredLength (γ.extend t-z)) (continuous_path_squared_distance γ z) (r^2) τ.val + (by simpa [closedRoundDisk] using (lt_of_not_ge h0)) + (by simpa [closedRoundDisk] using (lt_of_not_ge h1)) ⟨hτ0,hτ1⟩ + (by simpa using hτ) + let u' : unitInterval := ⟨u,hu0.le,(huτ.trans hτ1).le⟩ + let v' : unitInterval := ⟨v,(hτ0.trans hτv).le,hv1.le⟩ + refine ⟨u',v',hu0,huτ,hτv,hv1,?_,?_,?_⟩ + · rw [show γ.extend u=γ u' from γ.extend_extends' u'] at hu + exact hu + · rw [show γ.extend v=γ v' from γ.extend_extends' v'] at hv + exact hv + · intro t ht + exact hh t.val t.property (by simpa [closedRoundDisk] using ht) + +theorem path_initial_disk_last_visit {a b : Plane} (γ : Path a b) (r : ℝ) + (hr : 0 < r) (hb : b ∉ closedRoundDisk a r) : + ∃ v : unitInterval, 0 < v.val ∧ v.val < 1 ∧ squaredLength (γ v-a)=r^2 ∧ + (∀ t : unitInterval, γ t ∈ closedRoundDisk a r → t ≤ v) := by + obtain ⟨v,hv0,hv1,hv,hh⟩ := last_sublevel_visit + (fun t => squaredLength (γ.extend t-a)) (continuous_path_squared_distance γ a) (r^2) + (by simpa [squaredLength] using sq_pos_of_pos hr) + (by simpa [closedRoundDisk] using (lt_of_not_ge hb)) + let v' : unitInterval := ⟨v,hv0.le,hv1.le⟩ + refine ⟨v',hv0,hv1,?_,?_⟩ + · rw [show γ.extend v=γ v' from γ.extend_extends' v'] at hv + exact hv + · intro t ht + exact hh t.val t.property (by simpa [closedRoundDisk] using ht) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/RowCrossingCount.lean b/lean/OAI/Combinatorics/Crossing/RowCrossingCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..23b3e45e26d0b32eb93a6d3a98f8413abc54839d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/RowCrossingCount.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.Crossing.CrossingIncidence + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators Classical +variable {m n : ℕ} + +def NoAdjacentCrossings (D : AdmissibleDrawing m n) : Prop := + ∀ e f : BipartiteEdge m n, e ≠ f → (e.1 = f.1 ∨ e.2 = f.2) → + edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f = ∅ + +theorem pairCrossings_eq_empty_of_adjacent (D : AdmissibleDrawing m n) + (hnorm : NoAdjacentCrossings D) (e f : BipartiteEdge m n) + (hadj : e.1 = f.1 ∨ e.2 = f.2) : pairCrossings D e f = ∅ := by + by_cases hef : e = f + · subst f + exact pairCrossings_self D e + · apply Finset.eq_empty_iff_forall_notMem.mpr + intro x hx + have hmem := (Finset.mem_filter.mp hx).2 + have hi : x ∈ edgeInterior D.toContinuousDrawing e ∩ edgeInterior D.toContinuousDrawing f := + ⟨hmem.2.1,hmem.2.2⟩ + rw [hnorm e f hef hadj] at hi + exact hi + +def rowCrossingCount (D : AdmissibleDrawing m n) (i k : Fin m) : ℕ := + ∑ p : Fin n, ∑ q : Fin n, (pairCrossings D (i,p) (k,q)).card + +theorem rowCrossingCount_self (D : AdmissibleDrawing m n) (hnorm : NoAdjacentCrossings D) + (i : Fin m) : rowCrossingCount D i i = 0 := by + unfold rowCrossingCount + apply Finset.sum_eq_zero + intro p hp + apply Finset.sum_eq_zero + intro q hq + rw [pairCrossings_eq_empty_of_adjacent D hnorm (i,p) (i,q) (Or.inl rfl), Finset.card_empty] + +theorem sum_rowCrossingCount (D : AdmissibleDrawing m n) : + (∑ i : Fin m, ∑ k : Fin m, rowCrossingCount D i k) = 2*crossingCount D := by + have h := sum_pairCrossings_card D + change (∑ e : Fin m × Fin n, ∑ f : Fin m × Fin n, (pairCrossings D e f).card) = _ at h + simp only [Fintype.sum_prod_type] at h + calc + _ = ∑ i : Fin m, ∑ p : Fin n, ∑ k : Fin m, ∑ q : Fin n, + (pairCrossings D (i,p) (k,q)).card := by + apply Finset.sum_congr rfl + intro i hi + exact Finset.sum_comm + _ = _ := h + +theorem sum_offDiagonal_rowCrossingCount (D : AdmissibleDrawing m n) + (hnorm : NoAdjacentCrossings D) : + (∑ i : Fin m, ∑ k ∈ Finset.univ.erase i, rowCrossingCount D i k) = 2*crossingCount D := by + rw [← sum_rowCrossingCount D] + apply Finset.sum_congr rfl + intro i hi + have he := Finset.sum_erase_add Finset.univ (rowCrossingCount D i) (Finset.mem_univ i) + simpa only [rowCrossingCount_self D hnorm, add_zero] using he + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentAffineForms.lean b/lean/OAI/Combinatorics/Crossing/SegmentAffineForms.lean new file mode 100644 index 0000000000000000000000000000000000000000..5976b675d7470ba5f24891ecd93621571241e3ac --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentAffineForms.lean @@ -0,0 +1,17 @@ +import OAI.Combinatorics.Crossing.PlanarSegments + +namespace OAI + +namespace Zarankiewicz + +theorem segmentPoint_start_form (a b : Plane) (t : ℝ) : + segmentPoint a b t = a+t • (b-a) := by + apply Prod.ext <;> dsimp [segmentPoint] <;> ring + +theorem segmentPoint_end_form (a b : Plane) (t : ℝ) : + segmentPoint a b t = b-(1-t) • (b-a) := by + apply Prod.ext <;> dsimp [segmentPoint] <;> ring + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentAugmentation.lean b/lean/OAI/Combinatorics/Crossing/SegmentAugmentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..985b58397a8b33d12ce349efa260923aa5eb31a0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentAugmentation.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.Crossing.EmbeddedGraphPaths +import OAI.Combinatorics.Crossing.DrawingSubdivisionGraph + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segment_endpoint_or_open (a b x : Plane) (hx : x ∈ segment ℝ a b) : + x=a ∨ x=b ∨ x ∈ openSegmentTrace a b := by + rw [← Path.range_segment] at hx + obtain ⟨t,ht⟩ := hx + by_cases ht0 : t=0 + · subst t + exact Or.inl (by simpa only [Path.source] using ht.symm) + by_cases ht1 : t=1 + · subst t + exact Or.inr (Or.inl (by simpa only [Path.target] using ht.symm)) + refine Or.inr (Or.inr ⟨t.val,⟨?_,?_⟩,?_⟩) + · exact lt_of_le_of_ne t.property.1 (fun he => ht0 (Subtype.ext he.symm)) + · exact lt_of_le_of_ne t.property.2 (fun he => ht1 (Subtype.ext he)) + · simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + +def segmentAugmentedGraph {ι : Type*} (G : SimpleGraph Plane) (a b : ι → Plane) + (hne : ∀ i, a i ≠ b i) : SimpleGraph Plane where + Adj := fun x y => G.Adj x y ∨ ∃ i, (x=a i ∧ y=b i) ∨ (x=b i ∧ y=a i) + symm := ⟨by + rintro x y (hxy | ⟨i,⟨hx,hy⟩ | ⟨hx,hy⟩⟩) + · exact Or.inl hxy.symm + · exact Or.inr ⟨i,Or.inr ⟨hy,hx⟩⟩ + · exact Or.inr ⟨i,Or.inl ⟨hy,hx⟩⟩⟩ + loopless := ⟨by + rintro x (hxx | ⟨i,⟨hx,hy⟩ | ⟨hx,hy⟩⟩) + · exact G.loopless.irrefl x hxx + · exact hne i (hx.symm.trans hy) + · exact hne i (hy.symm.trans hx)⟩ + +theorem le_segmentAugmentedGraph {ι : Type*} (G : SimpleGraph Plane) (a b : ι → Plane) + (hne : ∀ i, a i ≠ b i) : G ≤ segmentAugmentedGraph G a b hne := fun _ _ h => Or.inl h + +theorem segmentAugmentedGraph_added_adj {ι : Type*} (G : SimpleGraph Plane) (a b : ι → Plane) + (hne : ∀ i, a i ≠ b i) (i : ι) : (segmentAugmentedGraph G a b hne).Adj (a i) (b i) := + Or.inr ⟨i,Or.inl ⟨rfl,rfl⟩⟩ + +theorem exterior_segment_chord_meeting (G : SimpleGraph Plane) (U : Set Plane) (a b x y z : Plane) + (hxy : G.Adj x y) (hout : ∀ x y, G.Adj x y → Disjoint (segment ℝ x y) U) + (hin : openSegmentTrace a b ⊆ U) + (ha : a ∈ segment ℝ x y → a=x ∨ a=y) (hb : b ∈ segment ℝ x y → b=x ∨ b=y) + (hz : z ∈ segment ℝ x y) (hchord : z ∈ segment ℝ a b) : + (z=x ∨ z=y) ∧ (z=a ∨ z=b) := by + rcases segment_endpoint_or_open a b z hchord with rfl | rfl | hz' + · exact ⟨ha hz,Or.inl rfl⟩ + · exact ⟨hb hz,Or.inr rfl⟩ + · exact False.elim (Set.disjoint_left.mp (hout x y hxy) hz (hin hz')) + +theorem segmentAugmentedGraph_embedding {ι : Type*} (G : SimpleGraph Plane) (a b : ι → Plane) + (hne : ∀ i, a i ≠ b i) (hemb : StraightEdgeEmbedding G id) (U : Set Plane) + (hout : ∀ x y, G.Adj x y → Disjoint (segment ℝ x y) U) + (hin : ∀ i, openSegmentTrace (a i) (b i) ⊆ U) + (hdisj : ∀ i j, i ≠ j → Disjoint (segment ℝ (a i) (b i)) (segment ℝ (a j) (b j))) + (hend : ∀ i x y, G.Adj x y → + (a i ∈ segment ℝ x y → a i=x ∨ a i=y) ∧ + (b i ∈ segment ℝ x y → b i=x ∨ b i=y)) : + StraightEdgeEmbedding (segmentAugmentedGraph G a b hne) id := by + refine ⟨Function.injective_id,?_⟩ + intro x y z w hxy hzw r hrx hrz + rcases hxy with hxy | ⟨i,hi⟩ <;> rcases hzw with hzw | ⟨j,hj⟩ + · exact hemb.2 x y z w hxy hzw r hrx hrz + · have hchord : r ∈ segment ℝ (a j) (b j) := by + rcases hj with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hrz + · simpa only [id_eq,segment_symm] using hrz + obtain ⟨hold,hnew⟩ := exterior_segment_chord_meeting G U (a j) (b j) x y r hxy hout + (hin j) (hend j x y hxy).1 (hend j x y hxy).2 hrx hchord + have hrzw : r=z ∨ r=w := by + rcases hj with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hnew + · exact hnew.symm + exact Or.inr (Or.inr (common_endpoint_alternatives x y z w r hold hrzw)) + · have hchord : r ∈ segment ℝ (a i) (b i) := by + rcases hi with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hrx + · simpa only [id_eq,segment_symm] using hrx + obtain ⟨hold,hnew⟩ := exterior_segment_chord_meeting G U (a i) (b i) z w r hzw hout + (hin i) (hend i z w hzw).1 (hend i z w hzw).2 hrz hchord + have hrxy : r=x ∨ r=y := by + rcases hi with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hnew + · exact hnew.symm + exact Or.inr (Or.inr (common_endpoint_alternatives x y z w r hrxy hold)) + · by_cases hij : i=j + · subst j + rcases hi with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ <;> rcases hj with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact Or.inl ⟨rfl,rfl⟩ + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inl ⟨rfl,rfl⟩ + · apply False.elim + apply Set.disjoint_left.mp (hdisj i j hij) + · rcases hi with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hrx + · simpa only [id_eq,segment_symm] using hrx + · rcases hj with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hrz + · simpa only [id_eq,segment_symm] using hrz + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentClosedIncidence.lean b/lean/OAI/Combinatorics/Crossing/SegmentClosedIncidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..26003ed63f24b76a883dd8a5b978a396ebd082b3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentClosedIncidence.lean @@ -0,0 +1,35 @@ +import OAI.Combinatorics.Crossing.SegmentContinuity +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem closedSegmentsMeet_iff_nonempty_inter (a b c d : Plane) : + ClosedSegmentsMeet a b c d ↔ (segment ℝ a b ∩ segment ℝ c d).Nonempty := by + constructor + · rintro ⟨s,hs,t,ht,he⟩ + refine ⟨segmentPoint a b s,?_,?_⟩ + · rw [← Path.range_segment] + exact ⟨⟨s,hs⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint]⟩ + · rw [← Path.range_segment] + exact ⟨⟨t,ht⟩,by simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he.symm⟩ + · rintro ⟨x,hx,hy⟩ + rw [← Path.range_segment] at hx hy + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + refine ⟨s.val,s.property,t.val,t.property,?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs.trans ht.symm + +theorem not_closedSegmentsMeet_of_disjoint (a b c d : Plane) + (h : Disjoint (segment ℝ a b) (segment ℝ c d)) : ¬ ClosedSegmentsMeet a b c d := by + intro hh + obtain ⟨x,hx,hy⟩ := (closedSegmentsMeet_iff_nonempty_inter a b c d).mp hh + exact Set.disjoint_left.mp h hx hy + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentContinuity.lean b/lean/OAI/Combinatorics/Crossing/SegmentContinuity.lean new file mode 100644 index 0000000000000000000000000000000000000000..744a90fe4ffab27237b36b1cf7c81a5821a09818 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentContinuity.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.Crossing.SegmentParameters +import Mathlib.Topology.Maps.Proper.Basic +import Mathlib.Tactic.FunProp + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology Classical + +def ClosedSegmentsMeet (a b c d : Plane) : Prop := + ∃ t ∈ Set.Icc (0 : ℝ) 1, ∃ u ∈ Set.Icc (0 : ℝ) 1, + segmentPoint a b t = segmentPoint c d u + +theorem closedSegmentsMeet_of_proper (a b c d : Plane) (h : SegmentsCrossProperly a b c d) : + ClosedSegmentsMeet a b c d := by + obtain ⟨_,t,ht,u,hu,he⟩ := h + exact ⟨t,⟨ht.1.le,ht.2.le⟩,u,⟨hu.1.le,hu.2.le⟩,he⟩ + +theorem isClosed_closedSegmentsMeet (c d : Plane) : + IsClosed {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 c d} := by + let P := (Plane × Plane) × (unitInterval × unitInterval) + let S : Set P := {x | segmentPoint x.1.1 x.1.2 x.2.1.val = segmentPoint c d x.2.2.val} + have hS : IsClosed S := by + apply isClosed_eq + · dsimp [segmentPoint] + fun_prop + · dsimp [segmentPoint] + fun_prop + have hproj := (isClosedMap_fst_of_compactSpace : IsClosedMap (Prod.fst : P → Plane × Plane)) S hS + have heq : Prod.fst '' S = {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 c d} := by + ext ab + constructor + · rintro ⟨⟨ab',t,u⟩,hx,h⟩ + change ab'=ab at h + subst ab' + exact ⟨t.val,t.property,u.val,u.property,hx⟩ + · rintro ⟨t,ht,u,hu,h⟩ + exact ⟨(ab,(⟨t,ht⟩,⟨u,hu⟩)),h,rfl⟩ + rwa [heq] at hproj + +theorem eventually_segmentCrossingSign_of_proper (a b c d : Plane) + (h : SegmentsCrossProperly a b c d) : + ∀ᶠ ab : Plane × Plane in 𝓝 (a,b), + segmentCrossingSign ab.1 ab.2 c d = segmentCrossingSign a b c d := by + have hD : Continuous (fun ab : Plane × Plane => det2 (ab.2-ab.1) (d-c)) := by + dsimp [det2] + fun_prop + have hF : ContinuousAt (fun ab : Plane × Plane => firstIntersectionParameter ab.1 ab.2 c d) (a,b) := by + apply ContinuousAt.div + · dsimp [det2] + fun_prop + · exact hD.continuousAt + · exact h.1 + have hS : ContinuousAt (fun ab : Plane × Plane => secondIntersectionParameter ab.1 ab.2 c d) (a,b) := by + apply ContinuousAt.div + · dsimp [det2] + fun_prop + · exact hD.continuousAt + · exact h.1 + obtain ⟨ht,hu⟩ := (segmentsCrossProperly_iff_parameters a b c d h.1).mp h + have ht' := hF.eventually (isOpen_Ioo.mem_nhds ht) + have hu' := hS.eventually (isOpen_Ioo.mem_nhds hu) + by_cases hpos : 0 < det2 (b-a) (d-c) + · have hd' : ∀ᶠ ab : Plane × Plane in 𝓝 (a,b), 0 < det2 (ab.2-ab.1) (d-c) := + continuousAt_const.eventually_lt hD.continuousAt hpos + filter_upwards [ht',hu',hd'] with ab ht hu hd + have hc := (segmentsCrossProperly_iff_parameters ab.1 ab.2 c d (ne_of_gt hd)).mpr ⟨ht,hu⟩ + simp [segmentCrossingSign,h,hc,hpos,hd] + · have hneg : det2 (b-a) (d-c) < 0 := lt_of_le_of_ne (le_of_not_gt hpos) h.1 + have hd' : ∀ᶠ ab : Plane × Plane in 𝓝 (a,b), det2 (ab.2-ab.1) (d-c) < 0 := + hD.continuousAt.eventually_lt continuousAt_const hneg + filter_upwards [ht',hu',hd'] with ab ht hu hd + have hc := (segmentsCrossProperly_iff_parameters ab.1 ab.2 c d (ne_of_lt hd)).mpr ⟨ht,hu⟩ + simp [segmentCrossingSign,h,hc,hpos,not_lt.mpr hd.le] + +def SegmentPairTransverse (a b c d : Plane) : Prop := + ∀ t ∈ Set.Icc (0 : ℝ) 1, ∀ u ∈ Set.Icc (0 : ℝ) 1, + segmentPoint a b t = segmentPoint c d u → + det2 (b-a) (d-c) ≠ 0 ∧ t ∈ Set.Ioo (0 : ℝ) 1 ∧ u ∈ Set.Ioo (0 : ℝ) 1 + +theorem eventually_segmentCrossingSign (a b c d : Plane) (h : SegmentPairTransverse a b c d) : + ∀ᶠ ab : Plane × Plane in 𝓝 (a,b), + segmentCrossingSign ab.1 ab.2 c d = segmentCrossingSign a b c d := by + by_cases hc : SegmentsCrossProperly a b c d + · exact eventually_segmentCrossingSign_of_proper a b c d hc + · have hn : ¬ ClosedSegmentsMeet a b c d := by + rintro ⟨t,ht,u,hu,he⟩ + obtain ⟨hd,ht',hu'⟩ := h t ht u hu he + exact hc ⟨hd,t,ht',u,hu',he⟩ + have hevent := (isClosed_closedSegmentsMeet c d).isOpen_compl.mem_nhds + (show (a,b) ∈ {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 c d}ᶜ from hn) + filter_upwards [hevent] with ab hab + have hn' : ¬ SegmentsCrossProperly ab.1 ab.2 c d := + fun hx => hab (closedSegmentsMeet_of_proper _ _ _ _ hx) + simp [segmentCrossingSign,hc,hn'] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentCrossingCoordinates.lean b/lean/OAI/Combinatorics/Crossing/SegmentCrossingCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..81aafe4070774bb5ae868def8ddff6cb10c2fe8a --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentCrossingCoordinates.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.Crossing.CrossingCoordinates + +namespace OAI + +namespace Zarankiewicz + +theorem inverseCoordinates_first_segment (a b c d o : Plane) (t s : ℝ) + (ho : o=segmentPoint a b t) : + crossingCoordinateInverse o (b-a) (d-c) (s-t,0)=segmentPoint a b s := by + rw [ho] + apply Prod.ext <;> dsimp [crossingCoordinateInverse,segmentPoint] <;> ring + +theorem inverseCoordinates_second_segment (a b c d o : Plane) (t s : ℝ) + (ho : o=segmentPoint c d t) : + crossingCoordinateInverse o (b-a) (d-c) (0,s-t)=segmentPoint c d s := by + rw [ho] + apply Prod.ext <;> dsimp [crossingCoordinateInverse,segmentPoint] <;> ring + +theorem crossingCoordinates_first_segment (a b c d o : Plane) (t s : ℝ) + (hd : det2 (b-a) (d-c) ≠ 0) (ho : o=segmentPoint a b t) : + crossingCoordinates o (b-a) (d-c) (segmentPoint a b s)=(s-t,0) := by + rw [← inverseCoordinates_first_segment a b c d o t s ho] + exact crossingCoordinates_right_inverse o (b-a) (d-c) hd _ + +theorem crossingCoordinates_second_segment (a b c d o : Plane) (t s : ℝ) + (hd : det2 (b-a) (d-c) ≠ 0) (ho : o=segmentPoint c d t) : + crossingCoordinates o (b-a) (d-c) (segmentPoint c d s)=(0,s-t) := by + rw [← inverseCoordinates_second_segment a b c d o t s ho] + exact crossingCoordinates_right_inverse o (b-a) (d-c) hd _ + +end Zarankiewicz + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentIntersectionUnique.lean b/lean/OAI/Combinatorics/Crossing/SegmentIntersectionUnique.lean new file mode 100644 index 0000000000000000000000000000000000000000..95ccf2e297706985bc045fc32eb5ab650db926fc --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentIntersectionUnique.lean @@ -0,0 +1,28 @@ +import OAI.Combinatorics.Crossing.SegmentContinuity +import Mathlib.Analysis.Convex.PathConnected + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem transverse_segment_intersection_subsingleton (a b c d : Plane) + (h : SegmentPairTransverse a b c d) : + (Set.range (Path.segment a b) ∩ Set.range (Path.segment c d)).Subsingleton := by + intro x hx y hy + obtain ⟨⟨s,hs⟩,⟨t,ht⟩⟩ := hx + obtain ⟨⟨u,hu⟩,⟨v,hv⟩⟩ := hy + have hxs : segmentPoint a b s.val=x := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs + have hxt : segmentPoint c d t.val=x := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + have hyu : segmentPoint a b u.val=y := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hu + have hyv : segmentPoint c d v.val=y := by simpa [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hv + have hdet := (h s.val s.property t.val t.property (hxs.trans hxt.symm)).1 + have he := segment_intersection_parameters_unique a b c d hdet s.val t.val u.val v.val + (hxs.trans hxt.symm) (hyu.trans hyv.symm) + exact hxs.symm.trans ((congrArg (segmentPoint a b) he.1).trans hyu) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentParameters.lean b/lean/OAI/Combinatorics/Crossing/SegmentParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..88f4f473da253ba50d0d749e7b2a9bbbec829b13 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentParameters.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.SegmentSymmetries + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def firstIntersectionParameter (a b c d : Plane) : ℝ := + det2 (d-c) (a-c) / det2 (b-a) (d-c) + +def secondIntersectionParameter (a b c d : Plane) : ℝ := + -det2 (b-a) (c-a) / det2 (b-a) (d-c) + +theorem intersection_parameters_eq (a b c d : Plane) (hn : det2 (b-a) (d-c) ≠ 0) : + segmentPoint a b (firstIntersectionParameter a b c d) = + segmentPoint c d (secondIntersectionParameter a b c d) := by + apply Prod.ext + · change (1-firstIntersectionParameter a b c d)*a.1+firstIntersectionParameter a b c d*b.1 = + (1-secondIntersectionParameter a b c d)*c.1+secondIntersectionParameter a b c d*d.1 + unfold firstIntersectionParameter secondIntersectionParameter + field_simp + dsimp [det2] + ring + · change (1-firstIntersectionParameter a b c d)*a.2+firstIntersectionParameter a b c d*b.2 = + (1-secondIntersectionParameter a b c d)*c.2+secondIntersectionParameter a b c d*d.2 + unfold firstIntersectionParameter secondIntersectionParameter + field_simp + dsimp [det2] + ring + +theorem segmentsCrossProperly_iff_parameters (a b c d : Plane) (hn : det2 (b-a) (d-c) ≠ 0) : + SegmentsCrossProperly a b c d ↔ + firstIntersectionParameter a b c d ∈ Set.Ioo (0 : ℝ) 1 ∧ + secondIntersectionParameter a b c d ∈ Set.Ioo (0 : ℝ) 1 := by + constructor + · rintro ⟨_,t,ht,u,hu,he⟩ + have hh := segment_intersection_parameters_unique a b c d hn t u + (firstIntersectionParameter a b c d) (secondIntersectionParameter a b c d) + he (intersection_parameters_eq a b c d hn) + exact ⟨hh.1 ▸ ht,hh.2 ▸ hu⟩ + · rintro ⟨ht,hu⟩ + exact ⟨hn,_,ht,_,hu,intersection_parameters_eq a b c d hn⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentSides.lean b/lean/OAI/Combinatorics/Crossing/SegmentSides.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c29416af1f6fb1a0e019513d83c2c3b7e65b172 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentSides.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.SegmentParameters + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def orient2 (a b c : Plane) : ℝ := det2 (b-a) (c-a) + +theorem orient2_self_segment (a b : Plane) (t : ℝ) : orient2 a b (segmentPoint a b t) = 0 := by + dsimp [orient2, det2, segmentPoint] + ring + +theorem orient2_segment (a b c d : Plane) (u : ℝ) : + orient2 a b (segmentPoint c d u) = (1-u)*orient2 a b c+u*orient2 a b d := by + dsimp [orient2,det2,segmentPoint] + ring + +theorem orient2_difference (a b c d : Plane) : + orient2 a b d-orient2 a b c = det2 (b-a) (d-c) := by + dsimp [orient2,det2] + ring + +theorem orient2_other_difference (a b c d : Plane) : + orient2 c d a-orient2 c d b = det2 (b-a) (d-c) := by + dsimp [orient2,det2] + ring + +theorem segmentCrossingSign_of_positive_sides (a b c d : Plane) + (hc : orient2 a b c < 0) (hd : 0 < orient2 a b d) + (ha : 0 < orient2 c d a) (hb : orient2 c d b < 0) : + segmentCrossingSign a b c d = 1 := by + have hdiff := orient2_difference a b c d + have hother := orient2_other_difference a b c d + have hdet : 0 < det2 (b-a) (d-c) := by linarith + have hcros : SegmentsCrossProperly a b c d := by + apply (segmentsCrossProperly_iff_parameters a b c d (ne_of_gt hdet)).mpr + constructor + · change 0 < orient2 c d a / det2 (b-a) (d-c) ∧ orient2 c d a / det2 (b-a) (d-c) < 1 + exact ⟨div_pos ha hdet, (div_lt_one hdet).mpr (by linarith)⟩ + · change 0 < -orient2 a b c / det2 (b-a) (d-c) ∧ -orient2 a b c / det2 (b-a) (d-c) < 1 + exact ⟨div_pos (neg_pos.mpr hc) hdet, (div_lt_one hdet).mpr (by linarith)⟩ + simp [segmentCrossingSign,hcros,hdet] + +theorem not_segmentsCrossProperly_of_same_side (a b c d : Plane) + (hside : (0 < orient2 a b c ∧ 0 < orient2 a b d) ∨ + (orient2 a b c < 0 ∧ orient2 a b d < 0)) : ¬ SegmentsCrossProperly a b c d := by + rintro ⟨_,t,ht,u,hu,he⟩ + have hzero := congrArg (orient2 a b) he + rw [orient2_self_segment,orient2_segment] at hzero + have hpos : 0 < 1-u := by linarith [hu.2] + rcases hside with ⟨hc,hd⟩ | ⟨hc,hd⟩ + · have := add_pos (mul_pos hpos hc) (mul_pos hu.1 hd) + linarith + · have := add_neg (mul_neg_of_pos_of_neg hpos hc) (mul_neg_of_pos_of_neg hu.1 hd) + linarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentSymmetries.lean b/lean/OAI/Combinatorics/Crossing/SegmentSymmetries.lean new file mode 100644 index 0000000000000000000000000000000000000000..829a62686ba623a0a4dd30bae4b8f724028b644e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentSymmetries.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.Crossing.PlanarSegments + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Classical + +theorem segmentsCrossProperly_swap (a b c d : Plane) : + SegmentsCrossProperly c d a b ↔ SegmentsCrossProperly a b c d := by + constructor + · rintro ⟨hn,t,ht,u,hu,he⟩ + refine ⟨?_,u,hu,t,ht,he.symm⟩ + rw [det2_swap] at hn + exact neg_ne_zero.mp hn + · rintro ⟨hn,t,ht,u,hu,he⟩ + refine ⟨?_,u,hu,t,ht,he.symm⟩ + rw [det2_swap] + exact neg_ne_zero.mpr hn + +theorem segmentsCrossProperly_reverse_left (a b c d : Plane) : + SegmentsCrossProperly b a c d ↔ SegmentsCrossProperly a b c d := by + have forward : ∀ a b c d : Plane, + SegmentsCrossProperly a b c d → SegmentsCrossProperly b a c d := by + intro a b c d h + obtain ⟨hn,t,ht,u,hu,he⟩ := h + refine ⟨?_,1-t,⟨by linarith [ht.2],by linarith [ht.1]⟩,u,hu,?_⟩ + · rw [← neg_sub b a, det2_neg_left] + exact neg_ne_zero.mpr hn + · rwa [segmentPoint_reverse] + exact ⟨forward b a c d, forward a b c d⟩ + +theorem nonzero_orientation_sign_neg (r : ℝ) (hr : r ≠ 0) : + (if 0 < -r then (1 : ℝ) else -1) = -(if 0 < r then 1 else -1) := by + by_cases hpos : 0 < r + · have hn : ¬ 0 < -r := by linarith + simp [hpos,hn] + · have hn : 0 < -r := by rcases lt_or_gt_of_ne hr with hh | hh <;> linarith + simp [hpos,hn] + +theorem segmentCrossingSign_swap (a b c d : Plane) : + segmentCrossingSign c d a b = -segmentCrossingSign a b c d := by + unfold segmentCrossingSign + rw [segmentsCrossProperly_swap] + by_cases h : SegmentsCrossProperly a b c d + · rw [ite_eq_left h, ite_eq_left h, det2_swap] + exact nonzero_orientation_sign_neg _ h.1 + · simp [h] + +theorem segmentCrossingSign_reverse_left (a b c d : Plane) : + segmentCrossingSign b a c d = -segmentCrossingSign a b c d := by + unfold segmentCrossingSign + rw [segmentsCrossProperly_reverse_left] + by_cases h : SegmentsCrossProperly a b c d + · rw [ite_eq_left h, ite_eq_left h, ← neg_sub b a, det2_neg_left] + exact nonzero_orientation_sign_neg _ h.1 + · simp [h] + +theorem openSegment_intersection_subsingleton (a b c d : Plane) + (hn : det2 (b-a) (d-c) ≠ 0) : (openSegmentTrace a b ∩ openSegmentTrace c d).Subsingleton := by + rintro x ⟨⟨t,ht,htx⟩,⟨u,hu,hux⟩⟩ y ⟨⟨t',ht',hty⟩,⟨u',hu',huy⟩⟩ + have hh := segment_intersection_parameters_unique a b c d hn t u t' u' + (htx.trans hux.symm) (hty.trans huy.symm) + rw [← htx, ← hty, hh.1] + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SegmentTraversalReversal.lean b/lean/OAI/Combinatorics/Crossing/SegmentTraversalReversal.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1d2bf913e24c3af417735a5641227d18fcca2a1 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SegmentTraversalReversal.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.Crossing.PolygonalChainTransversality +import OAI.Combinatorics.Crossing.SegmentClosedIncidence + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem segmentPairTransverse_of_not_meet (a b c d : Plane) (h : ¬ ClosedSegmentsMeet a b c d) : + SegmentPairTransverse a b c d := by + intro s hs t ht he + exact False.elim (h ⟨s,hs,t,ht,he⟩) + +theorem segmentCrossingSign_eq_zero_of_not_meet (a b c d : Plane) (h : ¬ ClosedSegmentsMeet a b c d) : + segmentCrossingSign a b c d=0 := by + have hn : ¬ SegmentsCrossProperly a b c d := fun hh => h (closedSegmentsMeet_of_proper _ _ _ _ hh) + simp [segmentCrossingSign,hn] + +theorem segmentPairTransverse_reverse_left (a b c d : Plane) (h : SegmentPairTransverse a b c d) : + SegmentPairTransverse b a c d := by + intro s hs t ht he + have hs' : 1-s ∈ Set.Icc (0 : ℝ) 1 := ⟨by linarith [hs.2],by linarith [hs.1]⟩ + have he' : segmentPoint a b (1-s)=segmentPoint c d t := (segmentPoint_reverse b a s).trans he + obtain ⟨hdet,hsp,htp⟩ := h (1-s) hs' t ht he' + refine ⟨?_,⟨by linarith [hsp.2],by linarith [hsp.1]⟩,htp⟩ + have hab : a-b=-(b-a) := by abel + rw [hab,det2_neg_left] + exact neg_ne_zero.mpr hdet + +theorem segmentPairTransverse_reverse_right (a b c d : Plane) (h : SegmentPairTransverse a b c d) : + SegmentPairTransverse a b d c := + segmentPairTransverse_swap _ _ _ _ + (segmentPairTransverse_reverse_left _ _ _ _ (segmentPairTransverse_swap _ _ _ _ h)) + +namespace PolygonalChain +variable {O T : Set Plane} {a b c d : Plane} + +theorem transverse_reverse_left (P : PolygonalChain O a b) (Q : PolygonalChain T c d) + (h : P.Transverse Q) : P.reverse.Transverse Q := by + intro i j + have hi : i.val h) + · exact Filter.Eventually.of_forall (fun _ h => False.elim (hh h)) + obtain ⟨δ₀,hδ₀,hstable⟩ := finite_eventual_radius _ hevent + obtain ⟨δ₁,hδ₁,hforward⟩ := exists_forward_shiftedTrack_radius v n hv hb + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro t ht hsmall i j + have hdir := hforward t (hsmall.trans_le (min_le_right _ _)) + by_cases hij : i=j + · subst j + rintro ⟨s,hs,r,hr,he⟩ + exact shiftedTrack_stretch_no_contact v n hv hb i.val i.isLt t ht s r he + · by_cases hnext : j.val=i.val+1 + · obtain ⟨r,hr,heq⟩ := hdir j + have hu := (trackOffset_incident_levels v n hv hb i.val i.isLt).2 + have hv' := (trackOffset_incident_levels v n hv hb j.val j.isLt).1 + rw [hnext] at hv' + have hd : (v (i.val+1+1)+t • trackOffset v n (i.val+1+1))- + (v (i.val+1)+t • trackOffset v n (i.val+1))=r • (v (i.val+1+1)-v (i.val+1)) := by + simpa only [shiftedTrack,trackDirection,hnext] using heq + rintro ⟨s,hs,u,hu',he⟩ + apply incoming_shifted_outgoing_disjoint (v i.val) (v (i.val+1)) (v (i.val+1+1)) + (trackOffset v n (i.val+1)) (trackOffset v n (i.val+1+1)) t r ht hr hu hv' hd s u hs hu' + simpa only [shiftedTrack,hnext] using he + · by_cases hprev : i.val=j.val+1 + · obtain ⟨r,hr,heq⟩ := hdir j + have hu := (trackOffset_incident_levels v n hv hb j.val j.isLt).2 + have hv' := (trackOffset_incident_levels v n hv hb i.val i.isLt).1 + rw [hprev] at hv' + rintro ⟨s,hs,u,hu',he⟩ + apply outgoing_shifted_incoming_disjoint (v j.val) (v (j.val+1)) (v (j.val+1+1)) + (trackOffset v n j.val) (trackOffset v n (j.val+1)) t r ht hr hu hv' heq s u hs hu' + simpa only [shiftedTrack,hprev] using he + · have hne : i.val ≠ j.val := fun h => hij (Fin.ext h) + exact hstable t (hsmall.trans_le (min_le_left _ _)) (i,j) (by change i.val+1 < j.val ∨ j.val+1 < i.val; omega) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ShiftedEdgeIntersections.lean b/lean/OAI/Combinatorics/Crossing/ShiftedEdgeIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd6aa12a8ba540dd3c7c96c239eab804a796f1e0 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ShiftedEdgeIntersections.lean @@ -0,0 +1,54 @@ +import OAI.Combinatorics.Crossing.StraightChainIntersections +import OAI.Combinatorics.Crossing.ConnectorTrackAvoidance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.TruncatedSpokeCoordinates +variable {m n : ℕ} {D : AdmissibleDrawing m n} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_complete_edge_intersection_radius (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ e f : BipartiteEdge m n, + (V.trackChain e).Transverse (C.shiftedEdgeChain f ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).pieces=V.signedIntersection e f := by + obtain ⟨δ₀,hδ₀,hT⟩ := V.exists_all_edge_shift_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,hI⟩ := V.exists_uniform_track_intersections hnorm hstraight htrans + obtain ⟨δ₂,hδ₂,hC⟩ := C.exists_all_connector_track_radius hnorm + let δ := min δ₀ (min δ₁ δ₂) + have hδ : 0<δ := lt_min hδ₀ (lt_min hδ₁ hδ₂) + have hb₀ : δ≤δ₀ := min_le_left _ _ + have hb₁ : δ≤δ₁ := (min_le_right _ _).trans (min_le_left _ _) + have hb₂ : δ≤δ₂ := (min_le_right _ _).trans (min_le_right _ _) + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall e f + have hconn (j : BipartiteVertex m n) (g : IncidentEdges j) : + (V.trackChain e).Transverse (C.connectorChain j g ε) := by + apply PolygonalChain.transverse_single_right + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hC ε hε (hsmall.trans_le hb₂) j g e i) + have hmid : (V.trackChain e).Transverse (C.shiftedTrackChain f ε) := by + intro i j + exact (hT ε hε (hsmall.trans_le hb₀) e f i j).1 + have hzero (j : BipartiteVertex m n) (g : IncidentEdges j) : + polygonIntersection (V.trackChain e).vertices (C.connectorChain j g ε).vertices (V.trackChain e).pieces 1=0 := by + apply PolygonalChain.intersection_single_right_zero + intro i + exact hC ε hε (hsmall.trans_le hb₂) j g e i + constructor + · change (V.trackChain e).Transverse + (((C.connectorChain (Sum.inl f.1) (V.leftIncident f) ε).join (C.shiftedTrackChain f ε)).join + (C.connectorChain (Sum.inr f.2) (V.rightIncident f) ε).reverse) + apply PolygonalChain.transverse_join_right + · exact PolygonalChain.transverse_join_right _ _ _ (hconn _ _) hmid + · exact (V.trackChain e).transverse_reverse_right _ (hconn _ _) + · rw [C.shiftedEdgeChain_intersection_right,hzero,hzero,zero_add,sub_zero] + exact hI ε hε (hsmall.trans_le hb₁) e f + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ShiftedRadialPieces.lean b/lean/OAI/Combinatorics/Crossing/ShiftedRadialPieces.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3b9f959c7d3b5bd745b3b2a2d070add4cf75dd3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ShiftedRadialPieces.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.Crossing.TruncatedRadialDots + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +theorem shifted_first_piece_exterior (e : BipartiteEdge m n) (ε ℓ : ℝ) + (hε : ε ≠ 0) (hℓ : 0<ℓ) + (hdir : shiftedTrack (V.vertices e) (V.pieces e) ε 1- + shiftedTrack (V.vertices e) (V.pieces e) ε 0=ℓ • trackDirection (V.vertices e) 0) : + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε 0) + (shiftedTrack (V.vertices e) (V.pieces e) ε 1) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex (Sum.inl e.1))} := by + have hstart : shiftedTrack (V.vertices e) (V.pieces e) ε 0= + V.startPort e+ε • normalShift (trackDirection (V.vertices e) 0) := by + simp [shiftedTrack,trackOffset,V.vertices_first] + have hc : squaredLength (V.startPort e-D.vertex (Sum.inl e.1))=V.radius^2 := by + simpa only [V.spokePort_left] using V.spokePort_circle (Sum.inl e.1) (V.leftIncident e) + have hp : det2 (trackDirection (V.vertices e) 0) (V.startPort e-D.vertex (Sum.inl e.1))=0 := by + simpa [spokeDirection,spokeIndex,leftIncident,spokePort,drawingSpokePort,startPort] using + V.spokeDirection_parallel (Sum.inl e.1) (V.leftIncident e) + rw [hstart] at hdir ⊢ + exact normal_offset_segment_exterior _ _ _ _ _ ε ℓ (V.direction_ne_zero e 0 (V.pieces_pos e)) + hc hp (mul_nonneg hℓ.le (V.start_radial_dot_pos e).le) hε hdir + +theorem shifted_last_piece_exterior (e : BipartiteEdge m n) (ε ℓ : ℝ) + (hε : ε ≠ 0) (hℓ : 0<ℓ) + (hdir : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)- + shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)= + ℓ • trackDirection (V.vertices e) (V.pieces e-1)) : + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)) + (shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex (Sum.inr e.2))} := by + have hn : V.pieces e ≠ 0 := ne_of_gt (V.pieces_pos e) + have hi : V.pieces e-1 < V.pieces e := by have hh := V.pieces_pos e; omega + have hend : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)= + V.endPort e+ε • normalShift (trackDirection (V.vertices e) (V.pieces e-1)) := by + simp [shiftedTrack,trackOffset,hn,V.vertices_last] + have hc : squaredLength (V.endPort e-D.vertex (Sum.inr e.2))=V.radius^2 := by + simpa only [V.spokePort_right] using V.spokePort_circle (Sum.inr e.2) (V.rightIncident e) + have hp : det2 (trackDirection (V.vertices e) (V.pieces e-1)) (V.endPort e-D.vertex (Sum.inr e.2))=0 := by + simpa [spokeDirection,spokeIndex,rightIncident,spokePort,drawingSpokePort,endPort] using + V.spokeDirection_parallel (Sum.inr e.2) (V.rightIncident e) + have hrev : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)- + (V.endPort e+ε • normalShift (trackDirection (V.vertices e) (V.pieces e-1)))= + (-ℓ) • trackDirection (V.vertices e) (V.pieces e-1) := by + rw [neg_smul,← hdir,hend] + abel + rw [segment_symm,hend] + exact normal_offset_segment_exterior _ _ _ _ _ ε (-ℓ) (V.direction_ne_zero e _ hi) + hc hp (mul_nonneg_of_nonpos_of_nonpos (by linarith) (V.end_radial_dot_neg e).le) hε hrev + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ShiftedSegmentStability.lean b/lean/OAI/Combinatorics/Crossing/ShiftedSegmentStability.lean new file mode 100644 index 0000000000000000000000000000000000000000..42e46bfd564f86109847d966cefc663369337aa5 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ShiftedSegmentStability.lean @@ -0,0 +1,56 @@ +import OAI.Combinatorics.Crossing.TransversalityStability +import OAI.Combinatorics.Crossing.FiniteEventualRadius + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped Topology + +theorem shifted_endpoints_tendsto (c d qc qd : Plane) : + Filter.Tendsto (fun t : ℝ => (c+t • qc,d+t • qd)) (𝓝 0) (𝓝 (c,d)) := by + have hh : Continuous (fun t : ℝ => (c+t • qc,d+t • qd)) := by fun_prop + simpa [ContinuousAt] using hh.continuousAt (x := 0) + +theorem eventually_shifted_segment_pair (a b c d qc qd : Plane) + (h : SegmentPairTransverse a b c d) : + ∀ᶠ t : ℝ in 𝓝 0, + SegmentPairTransverse a b (c+t • qc) (d+t • qd) ∧ + segmentCrossingSign a b (c+t • qc) (d+t • qd)=segmentCrossingSign a b c d := by + have hs := segmentPairTransverse_swap a b c d h + have he := (shifted_endpoints_tendsto c d qc qd).eventually + ((eventually_segmentPairTransverse c d a b hs).and (eventually_segmentCrossingSign c d a b hs)) + filter_upwards [he] with t ht + refine ⟨segmentPairTransverse_swap _ _ _ _ ht.1,?_⟩ + have hsign := ht.2 + rw [segmentCrossingSign_swap a b _ _,segmentCrossingSign_swap a b c d] at hsign + exact neg_injective hsign + +theorem closedSegmentsMeet_symm (a b c d : Plane) : ClosedSegmentsMeet a b c d ↔ ClosedSegmentsMeet c d a b := by + constructor <;> rintro ⟨t,ht,u,hu,he⟩ <;> exact ⟨u,hu,t,ht,he.symm⟩ + +theorem eventually_shifted_disjoint_segments (a b c d qc qd : Plane) + (h : ¬ ClosedSegmentsMeet a b c d) : + ∀ᶠ t : ℝ in 𝓝 0, ¬ ClosedSegmentsMeet a b (c+t • qc) (d+t • qd) := by + have hn : (c,d) ∈ {ab : Plane × Plane | ClosedSegmentsMeet ab.1 ab.2 a b}ᶜ := by + intro hx + exact h ((closedSegmentsMeet_symm c d a b).mp hx) + have he := (shifted_endpoints_tendsto c d qc qd).eventually + ((isClosed_closedSegmentsMeet a b).isOpen_compl.mem_nhds hn) + filter_upwards [he] with t ht + intro hx + exact ht ((closedSegmentsMeet_symm a b _ _).mp hx) + +theorem exists_shifted_segment_pairs_radius {ι : Type*} [Fintype ι] + (a b c d qc qd : ι → Plane) (h : ∀ i, SegmentPairTransverse (a i) (b i) (c i) (d i)) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, |t| < δ → ∀ i, + SegmentPairTransverse (a i) (b i) (c i+t • qc i) (d i+t • qd i) ∧ + segmentCrossingSign (a i) (b i) (c i+t • qc i) (d i+t • qd i)= + segmentCrossingSign (a i) (b i) (c i) (d i) := by + exact finite_eventual_radius _ (fun i => eventually_shifted_segment_pair _ _ _ _ _ _ (h i)) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ShiftedTrackDisks.lean b/lean/OAI/Combinatorics/Crossing/ShiftedTrackDisks.lean new file mode 100644 index 0000000000000000000000000000000000000000..57f2f8a5401002465d13a53026d1d015a60e7421 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ShiftedTrackDisks.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.Crossing.ShiftedRadialPieces +import OAI.Combinatorics.Crossing.MovingDiskClearance + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +variable {m n : ℕ} {D : ContinuousDrawing m n} (V : VertexTruncation D) + +theorem exists_nonincident_shift_radius : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j e (i : Fin (V.pieces e)), + ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=V.pieces e)) → + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε i.val) + (shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex j)} := by + classical + let Bad := Σ j : BipartiteVertex m n, Σ e : BipartiteEdge m n, + {i : Fin (V.pieces e) // ¬ ((j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=V.pieces e))} + have hdis (b : Bad) : Disjoint (closedRoundDisk (D.vertex b.1) V.radius) + (segment ℝ (V.vertices b.2.1 b.2.2.val.val) (V.vertices b.2.1 (b.2.2.val.val+1))) := by + exact (V.piece_clearance b.1 b.2.1 b.2.2.val b.2.2.property).mono_right + ((V.chain b.2.1).truncated_piece_subset V.radius V.radius_pos + (V.weak_short b.2.1).1 (V.weak_short b.2.1).2 _ b.2.2.val.isLt) + have hex (b : Bad) := exists_shifted_segment_disk_radius + (V.vertices b.2.1 b.2.2.val.val) (V.vertices b.2.1 (b.2.2.val.val+1)) + (trackOffset (V.vertices b.2.1) (V.pieces b.2.1) b.2.2.val.val) + (trackOffset (V.vertices b.2.1) (V.pieces b.2.1) (b.2.2.val.val+1)) + (D.vertex b.1) V.radius (hdis b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j e i hi + exact hprop ⟨j,e,⟨i,hi⟩⟩ ε (hε.trans (hbound ⟨j,e,⟨i,hi⟩⟩ (Finset.mem_univ _))) + +theorem exists_all_vertex_disk_radius : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j e (i : Fin (V.pieces e)), + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε i.val) + (shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex j)} := by + classical + obtain ⟨δ₀,hδ₀,hclear⟩ := V.exists_nonincident_shift_radius + choose radius hpos hforward using V.exists_forward_radius + obtain ⟨δ₁,hδ₁,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun e _ => hpos e) + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hsmall j e i + obtain ⟨ℓ,hℓ,hdir⟩ := hforward e ε + (hsmall.trans_le (min_le_right _ _ ) |>.trans (hbound e (Finset.mem_univ _))) i + by_cases hleft : j=Sum.inl e.1 ∧ i.val=0 + · rcases hleft with ⟨rfl,hi⟩ + simpa only [hi,zero_add] using V.shifted_first_piece_exterior e ε ℓ hε hℓ (by simpa only [hi,zero_add] using hdir) + · by_cases hright : j=Sum.inr e.2 ∧ i.val+1=V.pieces e + · rcases hright with ⟨rfl,hi⟩ + have hi' : i.val=V.pieces e-1 := by omega + have hn : V.pieces e-1+1=V.pieces e := by omega + simpa only [hi',hn] using V.shifted_last_piece_exterior e ε ℓ hε hℓ (by simpa only [hi',hn] using hdir) + · exact hclear ε (hsmall.trans_le (min_le_left _ _)) j e i (not_or.mpr ⟨hleft,hright⟩) + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/ShortVertexRadius.lean b/lean/OAI/Combinatorics/Crossing/ShortVertexRadius.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9a9ba98dc5de05c994f8f3e42b29fb355e696fc --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/ShortVertexRadius.lean @@ -0,0 +1,27 @@ +import OAI.Combinatorics.Crossing.VertexSpokeBounds + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_short_vertex_radius {m n : ℕ} (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (ρ : ℝ) (hρ : 0 < ρ) : + ∃ r : ℝ, 0 < r ∧ r ≤ ρ ∧ ∀ e, + 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + obtain ⟨s,hs,hsρ,hbound⟩ := exists_vertex_spoke_bound D P hmin ρ hρ + refine ⟨s/2,by positivity,by linarith,?_⟩ + intro e + obtain ⟨hfirst,hlast⟩ := hbound e + constructor <;> nlinarith + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SimilarityCoordinates.lean b/lean/OAI/Combinatorics/Crossing/SimilarityCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..92710e036d689a28ec6b042eb7839da7bf21754f --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SimilarityCoordinates.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.Crossing.OrientedSimilarity +import OAI.Combinatorics.Crossing.ParallelDirection +import OAI.Combinatorics.Crossing.CircleParameterChart + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +def similarityCoordinates (o u x : Plane) : Plane := + (dot2 u (x-o)/squaredLength u,det2 u (x-o)/squaredLength u) + +theorem similarityPoint_coordinates (o u x : Plane) (hu : u ≠ 0) : + similarityPoint o u (similarityCoordinates o u x)=x := by + have hL := ne_of_gt (squaredLength_pos u hu) + change u.1^2+u.2^2 ≠ 0 at hL + apply Prod.ext <;> + dsimp [similarityPoint,similarityCoordinates,dot2,det2,rotateQuarter,squaredLength] <;> + field_simp [hL] <;> ring + +theorem similarityCoordinates_point (o u x : Plane) (hu : u ≠ 0) : + similarityCoordinates o u (similarityPoint o u x)=x := by + have hL := ne_of_gt (squaredLength_pos u hu) + change u.1^2+u.2^2 ≠ 0 at hL + apply Prod.ext <;> + dsimp [similarityPoint,similarityCoordinates,dot2,det2,rotateQuarter,squaredLength] <;> + field_simp [hL] <;> ring + +theorem similarityCoordinates_length (o u x : Plane) (hu : u ≠ 0) : + squaredLength (similarityCoordinates o u x)=squaredLength (x-o)/squaredLength u := by + have hL := ne_of_gt (squaredLength_pos u hu) + change u.1^2+u.2^2 ≠ 0 at hL + dsimp [similarityCoordinates,dot2,det2,squaredLength] + field_simp [hL] + ring + +theorem similarityPoint_cut (o u : Plane) : similarityPoint o u (-1,0)=o-u := by + apply Prod.ext <;> dsimp [similarityPoint,rotateQuarter] <;> ring + +theorem circle_similarity_parameter (o u x : Plane) (hu : u ≠ 0) + (hx : squaredLength (x-o)=squaredLength u) (hcut : x ≠ o-u) : + ∃ t : ℝ, similarityPoint o u (circlePoint t)=x := by + let c := similarityCoordinates o u x + have hL := ne_of_gt (squaredLength_pos u hu) + have hc : c.1^2+c.2^2=1 := by + change squaredLength (similarityCoordinates o u x)=1 + rw [similarityCoordinates_length o u x hu,hx,div_self hL] + have hcx : c.1 ≠ -1 := by + intro hh + have hc2 : c.2=0 := by rw [hh] at hc; nlinarith [sq_nonneg c.2] + have he : c=(-1,0) := Prod.ext hh hc2 + apply hcut + calc + x = similarityPoint o u c := (similarityPoint_coordinates o u x hu).symm + _ = o-u := by rw [he,similarityPoint_cut] + refine ⟨c.2/(1+c.1),?_⟩ + rw [circlePoint_surjective_away_cut c hc hcx] + exact similarityPoint_coordinates o u x hu + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SimultaneousExteriorArcs.lean b/lean/OAI/Combinatorics/Crossing/SimultaneousExteriorArcs.lean new file mode 100644 index 0000000000000000000000000000000000000000..7104843de8a44fdb51beaeb0be414f84700c0531 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SimultaneousExteriorArcs.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.Crossing.ExteriorArcReplacement + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem finite_exterior_arc_replacements {E M : Type*} + [Fintype E] [DecidableEq E] [Fintype M] [DecidableEq M] + (z : M → Plane) (r : ℝ) (hr : 0 < r) + (hd : ∀ i j, i ≠ j → Disjoint (closedRoundDisk (z i) r) (closedRoundDisk (z j) r)) + (k l : E → M) (a b : E → Plane) (hab : ∀ e, a e ≠ b e) + (ha : ∀ e, squaredLength (a e-z (k e))=r^2) + (hb : ∀ e, squaredLength (b e-z (l e))=r^2) + (γ : ∀ e, Path (a e) (b e)) + (hdisjoint : ∀ e f, e ≠ f → Disjoint (Set.range (γ e)) (Set.range (γ f))) + (hγ : ∀ e t, t ∈ Set.Ioo (0 : unitInterval) 1 → γ e t ∈ outsideDisks z r) : + ∃ U : E → Set Plane, ∃ P : ∀ e, PolygonalChain (U e) (a e) (b e), + (∀ e, IsOpen (U e)) ∧ (∀ e, Function.Injective (P e).path) ∧ + (∀ e t, t ∈ Set.Ioo (0 : unitInterval) 1 → (P e).path t ∈ outsideDisks z r) ∧ + (∀ e f, e ≠ f → Disjoint (Set.range (P e).path) (Set.range (P f).path)) := by + obtain ⟨U,hU,hKU,_,hUU⟩ := finite_compact_corridors (fun e => Set.range (γ e)) + (fun _ => Set.univ) (fun e => isCompact_range (γ e).continuous) hdisjoint + (fun _ => isOpen_univ) (fun _ => Set.subset_univ _) + have hex (e : E) : ∃ P : PolygonalChain (U e) (a e) (b e), Function.Injective P.path ∧ + (∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → P.path t ∈ outsideDisks z r) := + exterior_arc_polygonal_replacement z r hr hd (k e) (l e) (a e) (b e) (hab e) + (ha e) (hb e) (γ e) (U e) (hU e) (fun t => hKU e ⟨t,rfl⟩) (hγ e) + choose P hP hR using hex + exact ⟨U,P,hU,hP,hR,fun e f hef => + (hUU e f hef).mono (P e).path_range_subset (P f).path_range_subset⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SimultaneousPolygonalReplacement.lean b/lean/OAI/Combinatorics/Crossing/SimultaneousPolygonalReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..79579c9482293d4ffc6287303b2f0f6f12b050b3 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SimultaneousPolygonalReplacement.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.Crossing.PolygonalArcInjective +import OAI.Combinatorics.Crossing.CompactCorridors + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_simple_polygonalChain {O : Set Plane} {a b : Plane} (hab : a ≠ b) + (h : Nonempty (PolygonalChain O a b)) : + ∃ P : PolygonalChain O a b, Function.Injective P.path ∧ Set.range P.path ⊆ O := by + obtain ⟨P,hmin⟩ := exists_minimum_polygonalChain h + exact ⟨P,P.minimum_path_injective hab hmin,P.path_range_subset⟩ + +theorem finite_disjoint_polygonal_replacements {ι : Type*} [Fintype ι] [DecidableEq ι] + (a b : ι → Plane) (hab : ∀ i, a i ≠ b i) (γ : ∀ i, Path (a i) (b i)) + (hd : ∀ i j, i ≠ j → Disjoint (Set.range (γ i)) (Set.range (γ j))) + (O : ι → Set Plane) (hO : ∀ i, IsOpen (O i)) + (hγ : ∀ i t, γ i t ∈ O i) : + ∃ U : ι → Set Plane, ∃ P : ∀ i, PolygonalChain (U i) (a i) (b i), + (∀ i, IsOpen (U i)) ∧ (∀ i, U i ⊆ O i) ∧ + (∀ i, Function.Injective (P i).path) ∧ (∀ i, Set.range (P i).path ⊆ U i) ∧ + (∀ i j, i ≠ j → Disjoint (Set.range (P i).path) (Set.range (P j).path)) := by + obtain ⟨U,hU,hKU,hUO,hUU⟩ := finite_compact_corridors (fun i => Set.range (γ i)) O + (fun i => isCompact_range (γ i).continuous) hd hO (by + intro i x hx + obtain ⟨t,rfl⟩ := hx + exact hγ i t) + have hex (i : ι) : ∃ P : PolygonalChain (U i) (a i) (b i), + Function.Injective P.path ∧ Set.range P.path ⊆ U i := by + obtain ⟨P,hP,hR,_⟩ := exists_simple_polygonalChain_of_path (hab i) (γ i) (U i) (hU i) + (fun t => hKU i ⟨t,rfl⟩) + exact ⟨P,hP,hR⟩ + choose P hP hR using hex + exact ⟨U,P,hU,hUO,hP,hR,fun i j hij => (hUU i j hij).mono (hR i) (hR j)⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SortedMarkedParameters.lean b/lean/OAI/Combinatorics/Crossing/SortedMarkedParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..936126806c802826562a8ef22be3e013bf07448e --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SortedMarkedParameters.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.DrawingMarks +import Mathlib.Data.Finset.Sort + +namespace OAI + +noncomputable section +namespace Zarankiewicz + +theorem exists_sorted_unitInterval_finset (S : Finset unitInterval) + (h0 : (0 : unitInterval) ∈ S) (h1 : (1 : unitInterval) ∈ S) : + ∃ k : ℕ, 0 < k ∧ ∃ t : Fin (k+1) → unitInterval, + StrictMono t ∧ t 0=0 ∧ t (Fin.last k)=1 ∧ Set.range t=(S : Set unitInterval) := by + have hc : 1 < S.card := Finset.one_lt_card.mpr ⟨0,h0,1,h1,zero_ne_one⟩ + let k := S.card-1 + have hk : 0 < k := by dsimp [k]; omega + have hcard : S.card=k+1 := by dsimp [k]; omega + let e := S.orderEmbOfFin hcard + have hrange : Set.range e=(S : Set unitInterval) := Finset.range_orderEmbOfFin S hcard + obtain ⟨i,hi⟩ : ∃ i, e i=0 := by + have hm : (0 : unitInterval) ∈ Set.range e := hrange.symm ▸ h0 + exact hm + obtain ⟨j,hj⟩ : ∃ j, e j=1 := by + have hm : (1 : unitInterval) ∈ Set.range e := hrange.symm ▸ h1 + exact hm + have he0 : e 0=0 := by + apply le_antisymm + · exact (e.monotone (Fin.zero_le i)).trans_eq hi + · exact (e 0).property.1 + have he1 : e (Fin.last k)=1 := by + apply le_antisymm + · exact (e (Fin.last k)).property.2 + · exact hj.symm.trans_le (e.monotone (Fin.le_last j)) + exact ⟨k,hk,e,e.strictMono,he0,he1,hrange⟩ + +theorem exists_sorted_drawing_parameters {m n : ℕ} (D : FiniteIntersectionDrawing m n) + (e : BipartiteEdge m n) : + ∃ k : ℕ, 0 < k ∧ ∃ t : Fin (k+1) → unitInterval, + StrictMono t ∧ t 0=0 ∧ t (Fin.last k)=1 ∧ + Set.range t=(D.edge e) ⁻¹' drawingMarks D := by + obtain ⟨k,hk,t,ht,h0,h1,hR⟩ := exists_sorted_unitInterval_finset (marked_parameters_finite D e).toFinset + (by simpa using marked_parameter_zero D e) (by simpa using marked_parameter_one D e) + exact ⟨k,hk,t,ht,h0,h1,by simpa using hR⟩ + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SortedSideEvents.lean b/lean/OAI/Combinatorics/Crossing/SortedSideEvents.lean new file mode 100644 index 0000000000000000000000000000000000000000..3bedf07ff90734da71045dcb84d1d3c2e7053cfe --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SortedSideEvents.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.Crossing.AffineSideEvents +import Mathlib.Data.Finset.Sort + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +theorem exists_sorted_permutation (n : ℕ) (r : Fin n → ℝ) (hr : Function.Injective r) : + ∃ e : Equiv.Perm (Fin n), StrictMono (r ∘ e) := by + let e := @Fintype.orderIsoFinOfCardEq (Fin n) (LinearOrder.lift' r hr) + inferInstance n (Fintype.card_fin n) + refine ⟨e.toEquiv, ?_⟩ + intro i j hij + exact @OrderIso.strictMono (Fin n) (Fin n) inferInstance + (LinearOrder.lift' r hr).toPreorder e i j hij + +theorem sum_affine_side_events_unordered (n : ℕ) (r b : Fin n → ℝ) + (hr : Function.Injective r) (hb : ∀ i, b i ≠ 0) (h0 : ∀ i, r i ≠ 0) (h1 : ∀ i, r i ≠ 1) : + (∑ i, if 0 hb (e i)) (fun i => h0 (e i)) (fun i => h1 (e i)) + simp only [Function.comp_apply] at h + have hprod : ∀ i, (∏ j : Fin n, if j=i then (1 : ℝ) else + positiveIndicator (b (e j)*(r (e i)-r (e j)))) = + ∏ j : Fin n, if j=e i then 1 else positiveIndicator (b j*(r (e i)-r j)) := by + intro i + rw [← Equiv.prod_comp e (fun j => if j=e i then (1 : ℝ) else positiveIndicator (b j*(r (e i)-r j)))] + simp only [e.injective.eq_iff] + simp_rw [hprod] at h + rw [Equiv.sum_comp e (fun i => if 0 positiveIndicator (b i*(1-r i))), + Equiv.prod_comp e (fun i => positiveIndicator (b i*(0-r i)))] at h + exact h + +theorem prod_positiveIndicator {ι : Type*} [Fintype ι] (f : ι → ℝ) : + (∏ i, positiveIndicator (f i)) = if ∀ i, 0 similarityPoint (D.vertex j) (C.frame j) + (circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε))) + dsimp [similarityPoint,circleOffset,rotateQuarter] + fun_prop + +theorem shiftedPort_zero (j : BipartiteVertex m n) (e : IncidentEdges j) : + C.shiftedPort j e 0=V.spokePort j e := by + simp only [shiftedPort,mul_zero,circleOffset_zero,C.point_eq] + +theorem shiftedPort_ne_original (j : BipartiteVertex m n) (e : IncidentEdges j) + (ε : ℝ) (hε : ε ≠ 0) : C.shiftedPort j e ε ≠ V.spokePort j e := by + intro he + have hh := C.shiftedPort_level j e ε + rw [he,sub_self] at hh + have hz : det2 (V.spokeDirection j e) (0 : Plane)=0 := by simp [det2] + rw [hz] at hh + exact hε hh.symm + +theorem exists_endpoint_separation_radius (j : BipartiteVertex m n) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → + (∀ e f : IncidentEdges j, V.spokePort j e ≠ C.shiftedPort j f ε) ∧ + Function.Injective (fun e : IncidentEdges j => C.shiftedPort j e ε) := by + have hinj : Function.Injective (fun e : IncidentEdges j => C.shiftedPort j e 0) := by + intro e f he + have hh : circlePoint (C.node j e)=circlePoint (C.node j f) := by + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [shiftedPort,mul_zero,circleOffset_zero] using he + exact C.node_injective j (circlePoint_injective hh) + obtain ⟨δ,hδ,hh⟩ := finite_moving_points_separation (C.shiftedPort j) + (C.continuous_shiftedPort j) hinj + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall + constructor + · intro e f + by_cases hef : e=f + · subst f + exact (C.shiftedPort_ne_original j e ε hε).symm + · simpa only [C.shiftedPort_zero] using (hh ε hsmall e f hef).1 + · intro e f he + by_contra hef + exact (hh ε hsmall e f hef).2 he + +end Zarankiewicz.TruncatedSpokeCoordinates + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SpokePieceIsolation.lean b/lean/OAI/Combinatorics/Crossing/SpokePieceIsolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..e41a001888cb130862021d58e5af1f22fbe7fe90 --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SpokePieceIsolation.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.Crossing.TruncatedSignedIntersections +import OAI.Combinatorics.Crossing.TrackEndpointConnections + +namespace OAI + +noncomputable section +namespace Zarankiewicz.VertexTruncation +variable {m n : ℕ} + +theorem spokePort_interior {D : ContinuousDrawing m n} (V : VertexTruncation D) + (j : BipartiteVertex m n) (f : IncidentEdges j) : V.spokePort j f ∈ edgeInterior D f.val := + drawingSpokePort_interior D V.chain V.minimal V.radius V.radius_pos V.weak_short j f + +theorem spokePort_piece_unique {D : AdmissibleDrawing m n} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (j : BipartiteVertex m n) (f : IncidentEdges j) + (e : BipartiteEdge m n) (i : Fin (V.pieces e)) + (hx : V.spokePort j f ∈ segment ℝ (V.vertices e i.val) (V.vertices e (i.val+1))) : + e=f.val ∧ i.val=V.spokeIndex j f := by + have hcircle : V.spokePort j f ∈ closedRoundDisk (D.vertex j) V.radius := by + change squaredLength (V.spokePort j f-D.vertex j) ≤ V.radius^2 + rw [V.spokePort_circle] + have he : e=f.val := by + by_contra hef + have hcross : V.spokePort j f ∈ crossingPoints D.toContinuousDrawing := + ⟨e,f.val,hef,V.range_subset_edgeInterior e (V.piece_subset_range e i.val i.isLt hx),V.spokePort_interior j f⟩ + exact Set.disjoint_left.mp (V.crossing_free_disks hnorm j) hcircle hcross + have hcase : (j=Sum.inl e.1 ∧ i.val=0) ∨ (j=Sum.inr e.2 ∧ i.val+1=V.pieces e) := by + by_contra hh + have hold := (V.chain e).truncated_piece_subset V.radius V.radius_pos + (V.weak_short e).1 (V.weak_short e).2 i.val i.isLt hx + exact Set.disjoint_left.mp (V.piece_clearance j e i hh) hcircle hold + refine ⟨he,?_⟩ + unfold spokeIndex + split_ifs with hj + · rcases hcase with hh | hh + · exact hh.2 + · have hbad : Sum.inl f.val.1=Sum.inr e.2 := hj.symm.trans hh.1 + cases hbad + · rcases hcase with hh | hh + · exact False.elim (hj (hh.1.trans (congrArg (fun g : BipartiteEdge m n => Sum.inl g.1) he))) + · have hn : V.pieces e=V.pieces f.val := congrArg V.pieces he + omega + +end Zarankiewicz.VertexTruncation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/SpokeTrackDirections.lean b/lean/OAI/Combinatorics/Crossing/SpokeTrackDirections.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6b3853a4a2eb6f6946f2cc9f6a5f140c13b9ccd --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/SpokeTrackDirections.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.Crossing.IncidentSpokePorts +import OAI.Combinatorics.Crossing.CircleOffsetLine + +namespace OAI + +noncomputable section +namespace Zarankiewicz +variable {m n : ℕ} + +def drawingSpokeDirection (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (j : BipartiteVertex m n) (e : IncidentEdges j) : Plane := + if j=Sum.inl e.val.1 then trackDirection (P e.val).vertices 0 + else trackDirection (P e.val).vertices ((P e.val).pieces-1) + +theorem drawingSpokeDirection_ne_zero (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (j : BipartiteVertex m n) (e : IncidentEdges j) : drawingSpokeDirection D P j e ≠ 0 := by + have hp := drawing_chain_pieces_pos D e.val (P e.val) + unfold drawingSpokeDirection + split_ifs + · exact (P e.val).minimum_piece_ne_zero (hmin e.val) 0 hp + · exact (P e.val).minimum_piece_ne_zero (hmin e.val) ((P e.val).pieces-1) (by omega) + +theorem drawingSpokeDirection_port_parallel (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (r : ℝ) (j : BipartiteVertex m n) (e : IncidentEdges j) + (hpos : 0 < (P e.val).pieces) : + det2 (drawingSpokeDirection D P j e) (drawingSpokePort D P r j e-D.vertex j)=0 := by + unfold drawingSpokeDirection drawingSpokePort + split_ifs with h + · have hc : D.vertex j=(P e.val).vertices 0 := (congrArg D.vertex h).trans (P e.val).first.symm + rw [hc] + change det2 ((P e.val).vertices 1-(P e.val).vertices 0) + (radialPort ((P e.val).vertices 0) ((P e.val).vertices 1) r-(P e.val).vertices 0)=0 + rw [radialPort_sub,det2_smul_right,det2_self,mul_zero] + · have he := e.property.resolve_left h + have hc : D.vertex j=(P e.val).vertices (P e.val).pieces := + (congrArg D.vertex he).trans (P e.val).last.symm + rw [hc] + simp only [trackDirection,PolygonalChain.endPort, + show (P e.val).pieces-1+1=(P e.val).pieces by omega,radialPort_sub,det2_smul_right] + have hn : (P e.val).vertices ((P e.val).pieces-1)-(P e.val).vertices (P e.val).pieces = + -((P e.val).vertices (P e.val).pieces-(P e.val).vertices ((P e.val).pieces-1)) := by abel + rw [hn,det2_neg_right,det2_self,neg_zero,mul_zero] + +theorem drawingSpokeScale_ne_zero (D : ContinuousDrawing m n) + (P : ∀ e : BipartiteEdge m n, PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex (.inl e.1)) (D.vertex (.inr e.2)), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) (j : BipartiteVertex m n) (e : IncidentEdges j) : + circleTrackScale (drawingSpokeDirection D P j e) (drawingSpokePort D P r j e-D.vertex j) ≠ 0 := by + have hw : drawingSpokePort D P r j e-D.vertex j ≠ 0 := by + intro hh + have hc := drawingSpokePort_circle D P hmin r j e + rw [hh] at hc + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hc + nlinarith + exact circleTrackScale_ne_zero _ _ (drawingSpokeDirection_ne_zero D P hmin j e) hw + (drawingSpokeDirection_port_parallel D P r j e (drawing_chain_pieces_pos D e.val (P e.val))) + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/StageDegreeBound.lean b/lean/OAI/Combinatorics/Crossing/StageDegreeBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..3816f300a104b0641c01c933379e69faa561ad4c --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/StageDegreeBound.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.Crossing.NodeRankLoss +import OAI.Combinatorics.Crossing.RankMultiplicity + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open PolynomialModule Module Submodule +open scoped BigOperators +variable {W ι : Type*} [AddCommGroup W] [Module ℝ W] [FiniteDimensional ℝ W] + +theorem polynomial_columns_rank_le {κ ρ : Type*} [Fintype κ] [Fintype ρ] [DecidableEq ρ] + (U : ι → Submodule ℝ W) (node : ι → ℝ) (Z : Submodule ℝ W) + (b : Basis κ ℝ Z) (p : ρ → PolynomialModule ℝ Z) (k : ℕ) + (hp : ∀ j, p j ∈ constrained U node Z k) (t : ℝ) : + ((polynomialColumnMatrix b p).map (Polynomial.eval t)).rank ≤ + finrank ℝ (evaluationFiltration U node Z t k) := by + let A := (polynomialColumnMatrix b p).map (Polynomial.eval t) + have hcol : A.col = b.equivFun ∘ (fun j => eval t (p j)) := by + funext j i + exact polynomialColumnMatrix_eval b p t i j + have hspan : span ℝ (Set.range (fun j => eval t (p j))) ≤ evaluationFiltration U node Z t k := by + apply span_le.mpr + rintro z ⟨j, rfl⟩ + exact ⟨⟨p j, hp j⟩, rfl⟩ + change A.rank ≤ _ + rw [Matrix.rank_eq_finrank_span_cols, hcol, Set.range_comp] + calc + _ ≤ finrank ℝ ((evaluationFiltration U node Z t k).map b.equivFun.toLinearMap) := by + apply Submodule.finrank_mono + apply span_le.mpr + rintro z ⟨v, ⟨j, rfl⟩, rfl⟩ + exact ⟨eval t (p j), ⟨⟨p j, hp j⟩, rfl⟩, rfl⟩ + _ = _ := b.equivFun.finrank_map_eq _ + +theorem stage_degree_bound [Fintype ι] (U V : ι → Submodule ℝ W) (node : ι → ℝ) + (hn : Function.Injective node) (hUV : ∀ i, Disjoint (U i) (V i)) + (tstar : ℝ) (htstar : ∀ i, node i ≠ tstar) (h : ℕ) : + (∑ j, rankIncrement U node (V j) h) ≤ + ∑ e ∈ Finset.range (h+1), e * columnIncrement U node ⊤ tstar e := by + let b := finBasis ℝ (⊤ : Submodule ℝ W) + obtain ⟨p, d, r, hp, hr, hdt, hdeg⟩ := exists_adapted_minor U node ⊤ b tstar htstar h + let M := (polynomialColumnMatrix b p).submatrix r id + have hM : M.det ≠ 0 := by + intro hz + apply hdt + change M.det.eval tstar = 0 + rw [hz, Polynomial.eval_zero] + have hcard : Fintype.card (Fin (finrank ℝ (evaluationFiltration U node ⊤ tstar (h+1)))) = + rankIncrement U node ⊤ h := by + rw [Fintype.card_fin] + exact finrank_eval_range U node ⊤ h tstar htstar + have hp' : ∀ j, p j ∈ constrained U node ⊤ (h+1) := by + intro j + exact ⟨bounded_mono (hp j).1.1 (Nat.add_le_add_right (hp j).2 1), (hp j).1.2⟩ + have hfactor : ∀ j, (Polynomial.X-Polynomial.C (node j))^(rankIncrement U node (V j) h) ∣ M.det := by + intro j + have hnode := node_rank_loss U node (V j) j (hUV j) h tstar htstar + rw [finrank_ambientEvalRange] at hnode + have hcols := polynomial_columns_rank_le U node ⊤ b p (h+1) hp' (node j) + have hminor := Matrix.rank_submatrix_le + ((polynomialColumnMatrix b p).map (Polynomial.eval (node j))) r id + have hbound : ((Polynomial.evalRingHom (node j)).mapMatrix M).rank ≤ + finrank ℝ (evaluationFiltration U node ⊤ (node j) (h+1)) := + hminor.trans hcols + apply pow_dvd_det_of_rank_le + rw [hcard] + omega + exact (sum_multiplicities_le_natDegree node hn (fun j => rankIncrement U node (V j) h) + M.det hM hfactor).trans hdeg + +end Zarankiewicz + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Crossing/StepEvents.lean b/lean/OAI/Combinatorics/Crossing/StepEvents.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bb81dbeb57a088fac4f51e0592354ab27fb021d --- /dev/null +++ b/lean/OAI/Combinatorics/Crossing/StepEvents.lean @@ -0,0 +1,83 @@ +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith + +namespace OAI + +noncomputable section +namespace Zarankiewicz +open scoped BigOperators + +def stepAt (root before after t : ℝ) : ℝ := if t < root then before else after + +def stepEvent {n : ℕ} (r lo hi : Fin n → ℝ) (i : Fin n) : ℝ := + if 0 < r i ∧ r i < 1 then + (hi i-lo i) * ∏ j, if j=i then 1 else stepAt (r j) (lo j) (hi j) (r i) + else 0 + +theorem sum_stepEvent (n : ℕ) (r lo hi : Fin n → ℝ) (hr : StrictMono r) + (h0 : ∀ i, r i ≠ 0) (h1 : ∀ i, r i ≠ 1) : + (∑ i, stepEvent r lo hi i) = + (∏ i, stepAt (r i) (lo i) (hi i) 1) - ∏ i, stepAt (r i) (lo i) (hi i) 0 := by + induction n with + | zero => simp + | succ n ih => + let rt := fun i : Fin n => r i.succ + let lt := fun i : Fin n => lo i.succ + let ht := fun i : Fin n => hi i.succ + have hrt : StrictMono rt := hr.comp (fun _ _ h => Fin.succ_lt_succ_iff.mpr h) + have hind := ih rt lt ht hrt (fun i => h0 i.succ) (fun i => h1 i.succ) + have hfirst : ∀ i : Fin n, r 0 < r i.succ := fun i => hr (Fin.succ_pos i) + have hhead : stepEvent r lo hi 0 = + if 0 < r 0 ∧ r 0 < 1 then (hi 0-lo 0) * ∏ i : Fin n, lt i else 0 := by + unfold stepEvent + rw [Fin.prod_univ_succ] + simp only [ite_true,one_mul,Fin.succ_ne_zero,ite_false] + congr 1 + congr 1 + apply Finset.prod_congr rfl + intro i hi + exact ite_eq_left (hfirst i) + have htail : ∀ i : Fin n, stepEvent r lo hi i.succ = hi 0 * stepEvent rt lt ht i := by + intro i + unfold stepEvent + rw [Fin.prod_univ_succ] + simp only [(Fin.succ_ne_zero i).symm,ite_false,Fin.succ_inj] + rw [show stepAt (r 0) (lo 0) (hi 0) (r i.succ) = hi 0 from ite_eq_right (not_lt.mpr (hfirst i).le)] + change (if 0 < rt i ∧ rt i < 1 then (ht i-lt i) * + (hi 0 * ∏ j, if j=i then 1 else stepAt (rt j) (lt j) (ht j) (rt i)) else 0) = _ + split_ifs <;> ring + rw [Fin.sum_univ_succ,hhead] + simp_rw [htail] + rw [← Finset.mul_sum,hind,Fin.prod_univ_succ,Fin.prod_univ_succ] + rcases lt_or_gt_of_ne (h0 0) with hrneg | hrpos + · have hn1 : ¬ 1 < r 0 := by linarith + have hn0 : ¬ 0 < r 0 := by linarith + simp only [hn0,false_and,ite_false,stepAt,hn1] + ring + · rcases lt_or_gt_of_ne (h1 0) with hrlt | hrgt + · have hn1 : ¬ 1 < r 0 := by linarith + have ht0 : (∏ i : Fin n, stepAt (rt i) (lt i) (ht i) 0) = ∏ i : Fin n, lt i := by + apply Finset.prod_congr rfl + intro i hi + exact ite_eq_left (hrpos.trans (hfirst i)) + rw [ht0] + simp only [hrpos,hrlt,and_self,ite_true,stepAt,hn1,ite_false] + ring + · have ht0 : (∏ i : Fin n, stepAt (rt i) (lt i) (ht i) 0) = ∏ i : Fin n, lt i := by + apply Finset.prod_congr rfl + intro i hi + exact ite_eq_left (hrpos.trans (hfirst i)) + have ht1 : (∏ i : Fin n, stepAt (rt i) (lt i) (ht i) 1) = ∏ i : Fin n, lt i := by + apply Finset.prod_congr rfl + intro i hi + exact ite_eq_left (hrgt.trans (hfirst i)) + rw [ht0,ht1] + simp [stepAt,hrpos,hrgt,not_lt.mpr hrgt.le] + +end Zarankiewicz + +end + +end OAI