import Mathlib.Tacticnamespace WallisTransfer/-- On a subset, removing a summand valued in [0,1] loses at most oneunit of mass per removed element. -/private theorem sum_bounds {α : Type*} [DecidableEq α] (s t : Finset α)(hsub : t ⊆ s) (h : α → ℝ) (hn : ∀ x, 0 ≤ h x) (hu : ∀ x, h x ≤ 1) :(∑ x ∈ t, h x) ≤ ∑ x ∈ s, h x ∧(∑ x ∈ s, h x) ≤ (∑ x ∈ t, h x) + ((s.card : ℝ) - t.card) := byhave decomp := Finset.sum_sdiff hsub (f := h)have lower : 0 ≤ ∑ x ∈ s \ t, h x := Finset.sum_nonneg (fun x _ => hn x)have upper : (∑ x ∈ s \ t, h x) ≤ (s \ t).card := bysimpa using Finset.sum_le_sum (s:=s \ t) (fun x _ => hu x)rw [Finset.card_sdiff_of_subset hsub, Nat.cast_sub (Finset.card_le_card hsub)] at upperconstructor <;> linarith/-- Changing from uniform encodings to uniform targets changes any[0,1]-valued mean by at most the fraction of exceptional encodings. -/theorem mean_transfer {α β : Type*} [DecidableEq α] [DecidableEq β](e g : Finset α) (p : Finset β) (f : α → β) (h : β → ℝ)(hg : g ⊆ e) (hp : p.Nonempty) (into : g.image f ⊆ p)(inj : Set.InjOn f (↑g : Set α)) (onto : p ⊆ e.image f)(hn : ∀ x, 0 ≤ h x) (hu : ∀ x, h x ≤ 1) :|(∑ x ∈ p, h x) / p.card - (∑ x ∈ e, h (f x)) / e.card| ≤((e.card : ℝ) - g.card) / e.card := byhave hsize : p.card ≤ e.card := (Finset.card_le_card onto).trans Finset.card_image_lehave posp : 0 < (p.card : ℝ) := by exact_mod_cast hp.card_poshave pose : 0 < (e.card : ℝ) := by exact_mod_cast hp.card_pos.trans_le hsizehave lepe : (p.card : ℝ) ≤ e.card := by exact_mod_cast hsizehave hsum := sum_bounds p (g.image f) into h hn hurw [Finset.sum_image (fun _ hx _ hy hxy => inj hx hy hxy), Finset.card_image_of_injOn inj] at hsumhave esum := sum_bounds e g hg (h ∘ f) (fun x => hn (f x)) (fun x => hu (f x))simp only [Function.comp_apply] at esumlet q := (∑ x ∈ p, h x) / p.cardhave qmass : q*p.card = ∑ x ∈ p, h x := div_mul_cancel₀ _ (ne_of_gt posp)have q0 : 0 ≤ q := div_nonneg (Finset.sum_nonneg fun x _ => hn x) posp.lehave q1 : q ≤ 1 := byapply (div_le_iff₀ posp).2simpa using Finset.sum_le_sum (s:=p) (fun x _ => hu x)have ld := mul_nonneg q0 (sub_nonneg.mpr lepe)have ud := mul_nonneg (sub_nonneg.mpr q1) (sub_nonneg.mpr lepe)change |q - _| ≤ _rw [abs_le]constructor· apply (le_sub_iff_add_le).2rw [← neg_div, ← add_div, div_le_iff₀ pose]linarith [hsum.1, esum.2, ld]· apply (sub_le_iff_le_add).2rw [← add_div, le_div_iff₀ pose]linarith [hsum.2, esum.1, ud]#print axioms mean_transferend WallisTransfer