Datasets:
AI4M
/

text
stringlengths
0
3.34M
/- Copyright (c) 2018 Violeta Hernández Palacios, Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios, Mario Carneiro -/ import set_theory.ordinal.arithmetic /-! # Fixed points of normal functions We prove various statements about the fixed points of normal ordinal functions. We state them in three forms: as statements about type-indexed families of normal functions, as statements about ordinal-indexed families of normal functions, and as statements about a single normal function. For the most part, the first case encompasses the others. Moreover, we prove some lemmas about the fixed points of specific normal functions. ## Main definitions and results * `nfp_family`, `nfp_bfamily`, `nfp`: the next fixed point of a (family of) normal function(s). * `fp_family_unbounded`, `fp_bfamily_unbounded`, `fp_unbounded`: the (common) fixed points of a (family of) normal function(s) are unbounded in the ordinals. * `deriv_add_eq_mul_omega_add`: a characterization of the derivative of addition. * `deriv_mul_eq_opow_omega_mul`: a characterization of the derivative of multiplication. -/ noncomputable theory universes u v open function order namespace ordinal /-! ### Fixed points of type-indexed families of ordinals -/ section variables {ι : Type u} {f : ι → ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions. `ordinal.nfp_family_fp` shows this is a fixed point, `ordinal.le_nfp_family` shows it's at least `a`, and `ordinal.nfp_family_le_fp` shows this is the least ordinal with these properties. -/ def nfp_family (f : ι → ordinal → ordinal) (a) : ordinal := sup (list.foldr f a) theorem nfp_family_eq_sup (f : ι → ordinal → ordinal) (a) : nfp_family f a = sup (list.foldr f a) := rfl theorem foldr_le_nfp_family (f : ι → ordinal → ordinal) (a l) : list.foldr f a l ≤ nfp_family f a := le_sup _ _ theorem le_nfp_family (f : ι → ordinal → ordinal) (a) : a ≤ nfp_family f a := le_sup _ [] theorem lt_nfp_family {a b} : a < nfp_family f b ↔ ∃ l, a < list.foldr f b l := lt_sup theorem nfp_family_le_iff {a b} : nfp_family f a ≤ b ↔ ∀ l, list.foldr f a l ≤ b := sup_le_iff theorem nfp_family_le {a b} : (∀ l, list.foldr f a l ≤ b) → nfp_family f a ≤ b := sup_le theorem nfp_family_monotone (hf : ∀ i, monotone (f i)) : monotone (nfp_family f) := λ a b h, sup_le $ λ l, (list.foldr_monotone hf l h).trans (le_sup _ l) theorem apply_lt_nfp_family (H : ∀ i, is_normal (f i)) {a b} (hb : b < nfp_family f a) (i) : f i b < nfp_family f a := let ⟨l, hl⟩ := lt_nfp_family.1 hb in lt_sup.2 ⟨i :: l, (H i).strict_mono hl⟩ theorem apply_lt_nfp_family_iff [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b < nfp_family f a) ↔ b < nfp_family f a := ⟨λ h, lt_nfp_family.2 $ let ⟨l, hl⟩ := lt_sup.1 (h (classical.arbitrary ι)) in ⟨l, ((H _).self_le b).trans_lt hl⟩, apply_lt_nfp_family H⟩ theorem nfp_family_le_apply [nonempty ι] (H : ∀ i, is_normal (f i)) {a b} : (∃ i, nfp_family f a ≤ f i b) ↔ nfp_family f a ≤ b := by { rw ←not_iff_not, push_neg, exact apply_lt_nfp_family_iff H } theorem nfp_family_le_fp (H : ∀ i, monotone (f i)) {a b} (ab : a ≤ b) (h : ∀ i, f i b ≤ b) : nfp_family f a ≤ b := sup_le $ λ l, begin by_cases hι : is_empty ι, { rwa @unique.eq_default _ (@list.unique_of_is_empty ι hι) l }, { haveI := not_is_empty_iff.1 hι, induction l with i l IH generalizing a, {exact ab}, exact (H i (IH ab)).trans (h i) } end theorem nfp_family_fp {i} (H : is_normal (f i)) (a) : f i (nfp_family f a) = nfp_family f a := begin unfold nfp_family, rw @is_normal.sup _ H _ _ ⟨[]⟩, apply le_antisymm; refine ordinal.sup_le (λ l, _), { exact le_sup _ (i :: l) }, { exact (H.self_le _).trans (le_sup _ _) } end theorem apply_le_nfp_family [hι : nonempty ι] {f : ι → ordinal → ordinal} (H : ∀ i, is_normal (f i)) {a b} : (∀ i, f i b ≤ nfp_family f a) ↔ b ≤ nfp_family f a := begin refine ⟨λ h, _, λ h i, _⟩, { unfreezingI { cases hι with i }, exact ((H i).self_le b).trans (h i) }, rw ←nfp_family_fp (H i), exact (H i).monotone h end theorem nfp_family_eq_self {f : ι → ordinal → ordinal} {a} (h : ∀ i, f i a = a) : nfp_family f a = a := le_antisymm (sup_le (λ l, (by rw list.foldr_fixed' h l))) (le_nfp_family f a) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_family_unbounded (H : ∀ i, is_normal (f i)) : (⋂ i, function.fixed_points (f i)).unbounded (<) := λ a, ⟨_, λ s ⟨i, hi⟩, begin rw ←hi, exact nfp_family_fp (H i) a end, (le_nfp_family f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_family (f : ι → ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp_family f 0) (λ a IH, nfp_family f (succ IH)) (λ a l, bsup.{(max u v) u} a) @[simp] theorem deriv_family_zero (f : ι → ordinal → ordinal) : deriv_family f 0 = nfp_family f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_family_succ (f : ι → ordinal → ordinal) (o) : deriv_family f (succ o) = nfp_family f (succ (deriv_family f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_family_limit (f : ι → ordinal → ordinal) {o} : is_limit o → deriv_family f o = bsup.{(max u v) u} o (λ a _, deriv_family f a) := limit_rec_on_limit _ _ _ _ theorem deriv_family_is_normal (f : ι → ordinal → ordinal) : is_normal (deriv_family f) := ⟨λ o, by rw [deriv_family_succ, ← succ_le_iff]; apply le_nfp_family, λ o l a, by rw [deriv_family_limit _ l, bsup_le_iff]⟩ theorem deriv_family_fp {i} (H : is_normal (f i)) (o : ordinal.{max u v}) : f i (deriv_family f o) = deriv_family f o := begin refine limit_rec_on o _ (λ o IH, _) _, { rw [deriv_family_zero], exact nfp_family_fp H 0 }, { rw [deriv_family_succ], exact nfp_family_fp H _ }, { intros o l IH, rw [deriv_family_limit _ l, is_normal.bsup.{(max u v) u (max u v)} H (λ a _, deriv_family f a) l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le_iff, IH] {contextual:=tt} } end theorem le_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a ≤ a) ↔ ∃ o, deriv_family f o = a := ⟨λ ha, begin suffices : ∀ o (_ : a ≤ deriv_family f o), ∃ o, deriv_family f o = a, from this a ((deriv_family_is_normal _).self_le _), refine λ o, limit_rec_on o (λ h₁, ⟨0, le_antisymm _ h₁⟩) (λ o IH h₁, _) (λ o l IH h₁, _), { rw deriv_family_zero, exact nfp_family_le_fp (λ i, (H i).monotone) (ordinal.zero_le _) ha }, { cases le_or_lt a (deriv_family f o), {exact IH h}, refine ⟨succ o, le_antisymm _ h₁⟩, rw deriv_family_succ, exact nfp_family_le_fp (λ i, (H i).monotone) (succ_le_of_lt h) ha }, { cases eq_or_lt_of_le h₁, {exact ⟨_, h.symm⟩}, rw [deriv_family_limit _ l, ← not_le, bsup_le_iff, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩ i, e ▸ le_of_eq (deriv_family_fp (H i) _)⟩ theorem fp_iff_deriv_family (H : ∀ i, is_normal (f i)) {a} : (∀ i, f i a = a) ↔ ∃ o, deriv_family f o = a := iff.trans ⟨λ h i, le_of_eq (h i), λ h i, (H i).le_iff_eq.1 (h i)⟩ (le_iff_deriv_family H) theorem deriv_family_eq_enum_ord (H : ∀ i, is_normal (f i)) : deriv_family f = enum_ord (⋂ i, function.fixed_points (f i)) := begin rw ←eq_enum_ord _ (fp_family_unbounded H), use (deriv_family_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨_, λ a ha, _⟩, { rintros a S ⟨i, hi⟩, rw ←hi, exact deriv_family_fp (H i) a }, rw set.mem_Inter at ha, rwa ←fp_iff_deriv_family H end end /-! ### Fixed points of ordinal-indexed families of ordinals -/ section variables {o : ordinal.{u}} {f : Π b < o, ordinal.{max u v} → ordinal.{max u v}} /-- The next common fixed point, at least `a`, for a family of normal functions indexed by ordinals. -/ def nfp_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := nfp_family (family_of_bfamily o f) theorem nfp_bfamily_eq_nfp_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : nfp_bfamily o f = nfp_family (family_of_bfamily o f) := rfl theorem foldr_le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a l) : list.foldr (family_of_bfamily o f) a l ≤ nfp_bfamily o f a := le_sup _ _ theorem le_nfp_bfamily {o : ordinal} (f : Π b < o, ordinal → ordinal) (a) : a ≤ nfp_bfamily o f a := le_sup _ [] theorem lt_nfp_bfamily {a b} : a < nfp_bfamily o f b ↔ ∃ l, a < list.foldr (family_of_bfamily o f) b l := lt_sup theorem nfp_bfamily_le_iff {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : nfp_bfamily o f a ≤ b ↔ ∀ l, list.foldr (family_of_bfamily o f) a l ≤ b := sup_le_iff theorem nfp_bfamily_le {o : ordinal} {f : Π b < o, ordinal → ordinal} {a b} : (∀ l, list.foldr (family_of_bfamily o f) a l ≤ b) → nfp_bfamily o f a ≤ b := sup_le theorem nfp_bfamily_monotone (hf : ∀ i hi, monotone (f i hi)) : monotone (nfp_bfamily o f) := nfp_family_monotone (λ i, hf _ _) theorem apply_lt_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b < nfp_bfamily o f a) ↔ b < nfp_bfamily o f a := begin unfold nfp_bfamily, rw ←@apply_lt_nfp_family_iff _ (family_of_bfamily o f) (out_nonempty_iff_ne_zero.2 ho) (λ i, H _ _), refine ⟨λ h i, h _ (typein_lt_self i), λ h i hio, _⟩, rw ←family_of_bfamily_enum o f, apply h end theorem nfp_bfamily_le_apply (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∃ i hi, nfp_bfamily o f a ≤ f i hi b) ↔ nfp_bfamily o f a ≤ b := by { rw ←not_iff_not, push_neg, convert apply_lt_nfp_bfamily ho H, simp only [not_le] } theorem nfp_bfamily_le_fp (H : ∀ i hi, monotone (f i hi)) {a b} (ab : a ≤ b) (h : ∀ i hi, f i hi b ≤ b) : nfp_bfamily o f a ≤ b := nfp_family_le_fp (λ _, H _ _) ab (λ i, h _ _) theorem nfp_bfamily_fp {i hi} (H : is_normal (f i hi)) (a) : f i hi (nfp_bfamily o f a) = nfp_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply nfp_family_fp, rw family_of_bfamily_enum, exact H } theorem apply_le_nfp_bfamily (ho : o ≠ 0) (H : ∀ i hi, is_normal (f i hi)) {a b} : (∀ i hi, f i hi b ≤ nfp_bfamily o f a) ↔ b ≤ nfp_bfamily o f a := begin refine ⟨λ h, _, λ h i hi, _⟩, { have ho' : 0 < o := ordinal.pos_iff_ne_zero.2 ho, exact ((H 0 ho').self_le b).trans (h 0 ho') }, rw ←nfp_bfamily_fp (H i hi), exact (H i hi).monotone h end theorem nfp_bfamily_eq_self {a} (h : ∀ i hi, f i hi a = a) : nfp_bfamily o f a = a := nfp_family_eq_self (λ _, h _ _) /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem fp_bfamily_unbounded (H : ∀ i hi, is_normal (f i hi)) : (⋂ i hi, function.fixed_points (f i hi)).unbounded (<) := λ a, ⟨_, by { rw set.mem_Inter₂, exact λ i hi, nfp_bfamily_fp (H i hi) _ }, (le_nfp_bfamily f a).not_lt⟩ /-- The derivative of a family of normal functions is the sequence of their common fixed points. -/ def deriv_bfamily (o : ordinal) (f : Π b < o, ordinal → ordinal) : ordinal → ordinal := deriv_family (family_of_bfamily o f) theorem deriv_bfamily_eq_deriv_family {o : ordinal} (f : Π b < o, ordinal → ordinal) : deriv_bfamily o f = deriv_family (family_of_bfamily o f) := rfl theorem deriv_bfamily_is_normal {o : ordinal} (f : Π b < o, ordinal → ordinal) : is_normal (deriv_bfamily o f) := deriv_family_is_normal _ theorem deriv_bfamily_fp {i hi} (H : is_normal (f i hi)) (a : ordinal) : f i hi (deriv_bfamily o f a) = deriv_bfamily o f a := by { rw ←family_of_bfamily_enum o f, apply deriv_family_fp, rw family_of_bfamily_enum, exact H } theorem le_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a ≤ a) ↔ ∃ b, deriv_bfamily o f b = a := begin unfold deriv_bfamily, rw ←le_iff_deriv_family, { refine ⟨λ h i, h _ _, λ h i hi, _⟩, rw ←family_of_bfamily_enum o f, apply h }, exact λ _, H _ _ end theorem fp_iff_deriv_bfamily (H : ∀ i hi, is_normal (f i hi)) {a} : (∀ i hi, f i hi a = a) ↔ ∃ b, deriv_bfamily o f b = a := begin rw ←le_iff_deriv_bfamily H, refine ⟨λ h i hi, le_of_eq (h i hi), λ h i hi, _⟩, rw ←(H i hi).le_iff_eq, exact h i hi end theorem deriv_bfamily_eq_enum_ord (H : ∀ i hi, is_normal (f i hi)) : deriv_bfamily o f = enum_ord (⋂ i hi, function.fixed_points (f i hi)) := begin rw ←eq_enum_ord _ (fp_bfamily_unbounded H), use (deriv_bfamily_is_normal f).strict_mono, rw set.range_eq_iff, refine ⟨λ a, set.mem_Inter₂.2 (λ i hi, deriv_bfamily_fp (H i hi) a), λ a ha, _⟩, rw set.mem_Inter₂ at ha, rwa ←fp_iff_deriv_bfamily H end end /-! ### Fixed points of a single function -/ section variable {f : ordinal.{u} → ordinal.{u}} /-- The next fixed point function, the least fixed point of the normal function `f`, at least `a`. -/ def nfp (f : ordinal → ordinal) : ordinal → ordinal := nfp_family (λ _ : unit, f) theorem nfp_eq_nfp_family (f : ordinal → ordinal) : nfp f = nfp_family (λ _ : unit, f) := rfl @[simp] theorem sup_iterate_eq_nfp (f : ordinal.{u} → ordinal.{u}) : (λ a, sup (λ n : ℕ, f^[n] a)) = nfp f := begin refine funext (λ a, le_antisymm _ (sup_le (λ l, _))), { rw sup_le_iff, intro n, rw [←list.length_repeat unit.star n, ←list.foldr_const f a], apply le_sup }, { rw list.foldr_const f a l, exact le_sup _ _ }, end theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := by { rw ←sup_iterate_eq_nfp, exact le_sup _ n } theorem le_nfp (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem lt_nfp {a b} : a < nfp f b ↔ ∃ n, a < (f^[n]) b := by { rw ←sup_iterate_eq_nfp, exact lt_sup } theorem nfp_le_iff {a b} : nfp f a ≤ b ↔ ∀ n, (f^[n]) a ≤ b := by { rw ←sup_iterate_eq_nfp, exact sup_le_iff } theorem nfp_le {a b} : (∀ n, (f^[n]) a ≤ b) → nfp f a ≤ b := nfp_le_iff.2 @[simp] theorem nfp_id : nfp id = id := funext (λ a, begin simp_rw [←sup_iterate_eq_nfp, iterate_id], exact sup_const a end) theorem nfp_monotone (hf : monotone f) : monotone (nfp f) := nfp_family_monotone (λ i, hf) theorem is_normal.apply_lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := begin unfold nfp, rw ←@apply_lt_nfp_family_iff unit (λ _, f) _ (λ _, H) a b, exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.nfp_le_apply {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.apply_lt_nfp theorem nfp_le_fp {f} (H : monotone f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := nfp_family_le_fp (λ _, H) ab (λ _, h) theorem is_normal.nfp_fp {f} (H : is_normal f) : ∀ a, f (nfp f a) = nfp f a := @nfp_family_fp unit (λ _, f) unit.star H theorem is_normal.apply_le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.self_le _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a := nfp_family_eq_self (λ _, h) /-- The fixed point lemma for normal functions: any normal function has an unbounded set of fixed points. -/ theorem fp_unbounded (H : is_normal f) : (function.fixed_points f).unbounded (<) := by { convert fp_family_unbounded (λ _ : unit, H), exact (set.Inter_const _).symm } /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) : ordinal → ordinal := deriv_family (λ _ : unit, f) theorem deriv_eq_deriv_family (f : ordinal → ordinal) : deriv f = deriv_family (λ _ : unit, f) := rfl @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := deriv_family_zero _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := deriv_family_succ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u 0} o (λ a _, deriv f a) := deriv_family_limit _ theorem deriv_is_normal (f) : is_normal (deriv f) := deriv_family_is_normal _ theorem deriv_id_of_nfp_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := ((deriv_is_normal _).eq_iff_zero_and_succ is_normal.refl).2 (by simp [h]) theorem is_normal.deriv_fp {f} (H : is_normal f) : ∀ o, f (deriv f o) = deriv f o := @deriv_family_fp unit (λ _, f) unit.star H theorem is_normal.le_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, deriv f o = a := begin unfold deriv, rw ←le_iff_deriv_family (λ _ : unit, H), exact ⟨λ h _, h, λ h, h unit.star⟩ end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a = a ↔ ∃ o, deriv f o = a := by rw [←H.le_iff_eq, H.le_iff_deriv] theorem deriv_eq_enum_ord (H : is_normal f) : deriv f = enum_ord (function.fixed_points f) := by { convert deriv_family_eq_enum_ord (λ _ : unit, H), exact (set.Inter_const _).symm } theorem deriv_eq_id_of_nfp_eq_id {f : ordinal → ordinal} (h : nfp f = id) : deriv f = id := (is_normal.eq_iff_zero_and_succ (deriv_is_normal _) is_normal.refl).2 (by simp [h]) end /-! ### Fixed points of addition -/ @[simp] theorem nfp_add_zero (a) : nfp ((+) a) 0 = a * omega := begin simp_rw [←sup_iterate_eq_nfp, ←sup_mul_nat], congr, funext, induction n with n hn, { rw [nat.cast_zero, mul_zero, iterate_zero_apply] }, { nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, mul_one_add, iterate_succ_apply', hn] } end theorem nfp_add_eq_mul_omega {a b} (hba : b ≤ a * omega) : nfp ((+) a) b = a * omega := begin apply le_antisymm (nfp_le_fp (add_is_normal a).monotone hba _), { rw ←nfp_add_zero, exact nfp_monotone (add_is_normal a).monotone (ordinal.zero_le b) }, { rw [←mul_one_add, one_add_omega] } end theorem add_eq_right_iff_mul_omega_le {a b : ordinal} : a + b = b ↔ a * omega ≤ b := begin refine ⟨λ h, _, λ h, _⟩, { rw [←nfp_add_zero a, ←deriv_zero], cases (add_is_normal a).fp_iff_deriv.1 h with c hc, rw ←hc, exact (deriv_is_normal _).monotone (ordinal.zero_le _) }, { have := ordinal.add_sub_cancel_of_le h, nth_rewrite 0 ←this, rwa [←add_assoc, ←mul_one_add, one_add_omega] } end theorem add_le_right_iff_mul_omega_le {a b : ordinal} : a + b ≤ b ↔ a * omega ≤ b := by { rw ←add_eq_right_iff_mul_omega_le, exact (add_is_normal a).le_iff_eq } theorem deriv_add_eq_mul_omega_add (a b : ordinal.{u}) : deriv ((+) a) b = a * omega + b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (add_is_normal _)], refine ⟨_, λ a h, _⟩, { rw [deriv_zero, add_zero], exact nfp_add_zero a }, { rw [deriv_succ, h, add_succ], exact nfp_eq_self (add_eq_right_iff_mul_omega_le.2 ((le_add_right _ _).trans (le_succ _))) } end /-! ### Fixed points of multiplication -/ local infixr ^ := @pow ordinal ordinal ordinal.has_pow @[simp] theorem nfp_mul_one {a : ordinal} (ha : 0 < a) : nfp ((*) a) 1 = a ^ omega := begin rw [←sup_iterate_eq_nfp, ←sup_opow_nat], { dsimp, congr, funext, induction n with n hn, { rw [nat.cast_zero, opow_zero, iterate_zero_apply] }, nth_rewrite 1 nat.succ_eq_one_add, rw [nat.cast_add, nat.cast_one, opow_add, opow_one, iterate_succ_apply', hn] }, { exact ha } end @[simp] theorem nfp_mul_zero (a : ordinal) : nfp ((*) a) 0 = 0 := begin rw [←ordinal.le_zero, nfp_le_iff], intro n, induction n with n hn, { refl }, rwa [iterate_succ_apply, mul_zero] end @[simp] @[simp] theorem deriv_mul_zero : deriv ((*) 0) = id := deriv_eq_id_of_nfp_eq_id nfp_zero_mul theorem nfp_mul_eq_opow_omega {a b : ordinal} (hb : 0 < b) (hba : b ≤ a ^ omega) : nfp ((*) a) b = a ^ omega.{u} := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero] at *, rw [ordinal.le_zero.1 hba, nfp_zero_mul], refl }, apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone hba, rw [←opow_one_add, one_add_omega] }, rw ←nfp_mul_one ha, exact nfp_monotone (mul_is_normal ha).monotone (one_le_iff_pos.2 hb) end theorem eq_zero_or_opow_omega_le_of_mul_eq_right {a b : ordinal} (hab : a * b = b) : b = 0 ∨ a ^ omega.{u} ≤ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_opow omega_ne_zero], exact or.inr (ordinal.zero_le b) }, rw or_iff_not_imp_left, intro hb, change b ≠ 0 at hb, rw ←nfp_mul_one ha, rw ←one_le_iff_ne_zero at hb, exact nfp_le_fp (mul_is_normal ha).monotone hb (le_of_eq hab) end theorem mul_eq_right_iff_opow_omega_dvd {a b : ordinal} : a * b = b ↔ a ^ omega ∣ b := begin cases eq_zero_or_pos a with ha ha, { rw [ha, zero_mul, zero_opow omega_ne_zero, zero_dvd_iff], exact eq_comm }, refine ⟨λ hab, _, λ h, _⟩, { rw dvd_iff_mod_eq_zero, rw [←div_add_mod b (a ^ omega), mul_add, ←mul_assoc, ←opow_one_add, one_add_omega, add_left_cancel] at hab, cases eq_zero_or_opow_omega_le_of_mul_eq_right hab with hab hab, { exact hab }, refine (not_lt_of_le hab (mod_lt b (opow_ne_zero omega _))).elim, rwa ←ordinal.pos_iff_ne_zero }, cases h with c hc, rw [hc, ←mul_assoc, ←opow_one_add, one_add_omega] end theorem mul_le_right_iff_opow_omega_dvd {a b : ordinal} (ha : 0 < a) : a * b ≤ b ↔ a ^ omega ∣ b := by { rw ←mul_eq_right_iff_opow_omega_dvd, exact (mul_is_normal ha).le_iff_eq } theorem nfp_mul_opow_omega_add {a c : ordinal} (b) (ha : 0 < a) (hc : 0 < c) (hca : c ≤ a ^ omega) : nfp ((*) a) (a ^ omega * b + c) = a ^ omega.{u} * (succ b) := begin apply le_antisymm, { apply nfp_le_fp (mul_is_normal ha).monotone, { rw mul_succ, apply add_le_add_left hca }, { rw [←mul_assoc, ←opow_one_add, one_add_omega] } }, { cases mul_eq_right_iff_opow_omega_dvd.1 ((mul_is_normal ha).nfp_fp (a ^ omega * b + c)) with d hd, rw hd, apply mul_le_mul_left', have := le_nfp (has_mul.mul a) (a ^ omega * b + c), rw hd at this, have := (add_lt_add_left hc (a ^ omega * b)).trans_le this, rw [add_zero, mul_lt_mul_iff_left (opow_pos omega ha)] at this, rwa succ_le_iff } end theorem deriv_mul_eq_opow_omega_mul {a : ordinal.{u}} (ha : 0 < a) (b) : deriv ((*) a) b = a ^ omega * b := begin revert b, rw [←funext_iff, is_normal.eq_iff_zero_and_succ (deriv_is_normal _) (mul_is_normal (opow_pos omega ha))], refine ⟨_, λ c h, _⟩, { rw [deriv_zero, nfp_mul_zero, mul_zero] }, { rw [deriv_succ, h], exact nfp_mul_opow_omega_add c ha zero_lt_one (one_le_iff_pos.2 (opow_pos _ ha)) }, end end ordinal
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! ! SDIRK - Singly-Diagonally-Implicit Runge-Kutta method ! ! (L-stable, 5 stages, order 4) ! ! By default the code employs the KPP sparse linear algebra routines ! ! Compile with -DFULL_ALGEBRA to use full linear algebra (LAPACK) ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! ! A. Sandu - version of July 10, 2005 MODULE KPP_ROOT_Integrator USE KPP_ROOT_Precision USE KPP_ROOT_Global, ONLY: FIX, RCONST, TIME USE KPP_ROOT_Parameters, ONLY: NVAR, NSPEC, NFIX, LU_NONZERO USE KPP_ROOT_JacobianSP, ONLY: LU_DIAG USE KPP_ROOT_LinearAlgebra, ONLY: KppDecomp, KppSolve, & Set2zero, WLAMCH, WAXPY, WCOPY IMPLICIT NONE PUBLIC SAVE !~~~> Statistics on the work performed by the SDIRK method INTEGER :: Nfun,Njac,Nstp,Nacc,Nrej,Ndec,Nsol,Nsng INTEGER, PARAMETER :: ifun=1, ijac=2, istp=3, iacc=4, & irej=5, idec=6, isol=7, isng=8, itexit=1, ihexit=2 ! SDIRK method coefficients KPP_REAL :: rkAlpha(5,4), rkBeta(5,4), rkD(4,5), & rkGamma, rkA(5,5), rkB(5), rkC(5) ! description of the error numbers IERR CHARACTER(LEN=50), PARAMETER, DIMENSION(-8:1) :: IERR_NAMES = (/ & 'Matrix is repeatedly singular ', & ! -8 'Step size too small: T + 10*H = T or H < Roundoff ', & ! -7 'No of steps exceeds maximum bound ', & ! -6 'Improper tolerance values ', & ! -5 'FacMin/FacMax/FacRej must be positive ', & ! -4 'Hmin/Hmax/Hstart must be positive ', & ! -3 'Improper value for maximal no of Newton iterations', & ! -2 'Improper value for maximal no of steps ', & ! -1 ' ', & ! 0 (not used) 'Success ' /) ! 1 CONTAINS SUBROUTINE INTEGRATE( TIN, TOUT, & ICNTRL_U, RCNTRL_U, ISTATUS_U, RSTATUS_U, IERR_U ) USE KPP_ROOT_Parameters USE KPP_ROOT_Global IMPLICIT NONE KPP_REAL, INTENT(IN) :: TIN ! Start Time KPP_REAL, INTENT(IN) :: TOUT ! End Time ! Optional input parameters and statistics INTEGER, INTENT(IN), OPTIONAL :: ICNTRL_U(20) KPP_REAL, INTENT(IN), OPTIONAL :: RCNTRL_U(20) INTEGER, INTENT(OUT), OPTIONAL :: ISTATUS_U(20) KPP_REAL, INTENT(OUT), OPTIONAL :: RSTATUS_U(20) INTEGER, INTENT(OUT), OPTIONAL :: IERR_U !INTEGER, SAVE :: Ntotal = 0 KPP_REAL :: RCNTRL(20), RSTATUS(20) INTEGER :: ICNTRL(20), ISTATUS(20), IERR ICNTRL(:) = 0 RCNTRL(:) = 0.0_dp ISTATUS(:) = 0 RSTATUS(:) = 0.0_dp ! If optional parameters are given, and if they are >0, ! then they overwrite default settings. IF (PRESENT(ICNTRL_U)) THEN WHERE(ICNTRL_U(:) > 0) ICNTRL(:) = ICNTRL_U(:) END IF IF (PRESENT(RCNTRL_U)) THEN WHERE(RCNTRL_U(:) > 0) RCNTRL(:) = RCNTRL_U(:) END IF CALL SDIRK( NVAR,TIN,TOUT,VAR,RTOL,ATOL, & RCNTRL,ICNTRL,RSTATUS,ISTATUS,IERR ) ! mz_rs_20050716: IERR and ISTATUS(istp) are returned to the user who then ! decides what to do about it, i.e. either stop the run or ignore it. !!$ IF (IERR < 0) THEN !!$ PRINT *,'SDIRK: Unsuccessful exit at T=',TIN,' (IERR=',IERR,')' !!$ ENDIF !!$ Ntotal = Ntotal + Nstp !!$ PRINT*,'NSTEPS=',Nstp, '(',Ntotal,')' STEPMIN = RSTATUS(ihexit) ! Save last step ! if optional parameters are given for output they to return information IF (PRESENT(ISTATUS_U)) ISTATUS_U(:) = ISTATUS(1:20) IF (PRESENT(RSTATUS_U)) RSTATUS_U(:) = RSTATUS(1:20) IF (PRESENT(IERR_U)) IERR_U = IERR END SUBROUTINE INTEGRATE !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK(N, Tinitial, Tfinal, Y, RelTol, AbsTol, & RCNTRL, ICNTRL, RSTATUS, ISTATUS, IDID) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! ! Solves the system y'=F(t,y) using a Singly-Diagonally-Implicit ! Runge-Kutta (SDIRK) method. ! ! For details on SDIRK methods and their implementation consult: ! E. Hairer and G. Wanner ! "Solving ODEs II. Stiff and differential-algebraic problems". ! Springer series in computational mathematics, Springer-Verlag, 1996. ! This code is based on the SDIRK4 routine in the above book. ! ! (C) Adrian Sandu, July 2005 ! Virginia Polytechnic Institute and State University ! Contact: [email protected] ! This implementation is part of KPP - the Kinetic PreProcessor !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! !~~~> INPUT ARGUMENTS: ! !- Y(NVAR) = vector of initial conditions (at T=Tinitial) !- [Tinitial,Tfinal] = time range of integration ! (if Tinitial>Tfinal the integration is performed backwards in time) !- RelTol, AbsTol = user precribed accuracy !- SUBROUTINE ode_Fun( T, Y, Ydot ) = ODE function, ! returns Ydot = Y' = F(T,Y) !- SUBROUTINE ode_Fun( T, Y, Ydot ) = Jacobian of the ODE function, ! returns Jcb = dF/dY !- ICNTRL(1:20) = integer inputs parameters !- RCNTRL(1:20) = real inputs parameters !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! !~~~> OUTPUT ARGUMENTS: ! !- Y(NVAR) -> vector of final states (at T->Tfinal) !- ISTATUS(1:20) -> integer output parameters !- RSTATUS(1:20) -> real output parameters !- IDID -> job status upon return ! success (positive value) or ! failure (negative value) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! !~~~> INPUT PARAMETERS: ! ! Note: For input parameters equal to zero the default values of the ! corresponding variables are used. ! ! Note: For input parameters equal to zero the default values of the ! corresponding variables are used. !~~~> ! ICNTRL(1) = not used ! ! ICNTRL(2) = 0: AbsTol, RelTol are NVAR-dimensional vectors ! = 1: AbsTol, RelTol are scalars ! ! ICNTRL(3) = not used ! ! ICNTRL(4) -> maximum number of integration steps ! For ICNTRL(4)=0 the default value of 100000 is used ! ! ICNTRL(5) -> maximum number of Newton iterations ! For ICNTRL(5)=0 the default value of 8 is used ! ! ICNTRL(6) -> starting values of Newton iterations: ! ICNTRL(6)=0 : starting values are interpolated (the default) ! ICNTRL(6)=1 : starting values are zero ! !~~~> Real parameters ! ! RCNTRL(1) -> Hmin, lower bound for the integration step size ! It is strongly recommended to keep Hmin = ZERO ! RCNTRL(2) -> Hmax, upper bound for the integration step size ! RCNTRL(3) -> Hstart, starting value for the integration step size ! ! RCNTRL(4) -> FacMin, lower bound on step decrease factor (default=0.2) ! RCNTRL(5) -> FacMax, upper bound on step increase factor (default=6) ! RCNTRL(6) -> FacRej, step decrease factor after multiple rejections ! (default=0.1) ! RCNTRL(7) -> FacSafe, by which the new step is slightly smaller ! than the predicted value (default=0.9) ! RCNTRL(8) -> ThetaMin. If Newton convergence rate smaller ! than ThetaMin the Jacobian is not recomputed; ! (default=0.001) ! RCNTRL(9) -> NewtonTol, stopping criterion for Newton's method ! (default=0.03) ! RCNTRL(10) -> Qmin ! RCNTRL(11) -> Qmax. If Qmin < Hnew/Hold < Qmax, then the ! step size is kept constant and the LU factorization ! reused (default Qmin=1, Qmax=1.2) ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! !~~~> OUTPUT PARAMETERS: ! ! Note: each call to Rosenbrock adds the current no. of fcn calls ! to previous value of ISTATUS(1), and similar for the other params. ! Set ISTATUS(1:10) = 0 before call to avoid this accumulation. ! ! ISTATUS(1) = No. of function calls ! ISTATUS(2) = No. of jacobian calls ! ISTATUS(3) = No. of steps ! ISTATUS(4) = No. of accepted steps ! ISTATUS(5) = No. of rejected steps (except at the beginning) ! ISTATUS(6) = No. of LU decompositions ! ISTATUS(7) = No. of forward/backward substitutions ! ISTATUS(8) = No. of singular matrix decompositions ! ! RSTATUS(1) -> Texit, the time corresponding to the ! computed Y upon return ! RSTATUS(2) -> Hexit, last predicted step before exit ! For multiple restarts, use Hexit as Hstart in the following run !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPLICIT NONE ! Arguments INTEGER, INTENT(IN) :: N, ICNTRL(20) KPP_REAL, INTENT(IN) :: Tinitial, Tfinal, & RelTol(NVAR), AbsTol(NVAR), RCNTRL(20) KPP_REAL, INTENT(INOUT) :: Y(NVAR) INTEGER, INTENT(OUT) :: IDID INTEGER, INTENT(INOUT) :: ISTATUS(20) KPP_REAL, INTENT(OUT) :: RSTATUS(20) ! Local variables KPP_REAL :: Hmin, Hmax, Hstart, Roundoff, & FacMin, Facmax, FacSafe, FacRej, & ThetaMin, NewtonTol, Qmin, Qmax, & Texit, Hexit INTEGER :: ITOL, NewtonMaxit, Max_no_steps, i KPP_REAL, PARAMETER :: ZERO = 0.0d0 !~~~> Initialize statistics Nfun = ISTATUS(ifun) Njac = ISTATUS(ijac) Nstp = ISTATUS(istp) Nacc = ISTATUS(iacc) Nrej = ISTATUS(irej) Ndec = ISTATUS(idec) Nsol = ISTATUS(isol) Nsng = ISTATUS(isng) ! Nfun=0; Njac=0; Nstp=0; Nacc=0 ! Nrej=0; Ndec=0; Nsol=0; Nsng=0 IDID = 0 !~~~> For Scalar tolerances (ICNTRL(2).NE.0) the code uses AbsTol(1) and RelTol(1) ! For Vector tolerances (ICNTRL(2) == 0) the code uses AbsTol(1:NVAR) and RelTol(1:NVAR) IF (ICNTRL(2) == 0) THEN ITOL = 1 ELSE ITOL = 0 END IF !~~~> The maximum number of time steps admitted IF (ICNTRL(3) == 0) THEN Max_no_steps = 100000 ELSEIF (Max_no_steps > 0) THEN Max_no_steps=ICNTRL(3) ELSE PRINT * ,'User-selected ICNTRL(3)=',ICNTRL(3) CALL SDIRK_ErrorMsg(-1,Tinitial,ZERO,IDID) END IF !~~~> The maximum number of Newton iterations admitted IF(ICNTRL(4) == 0)THEN NewtonMaxit=8 ELSE NewtonMaxit=ICNTRL(4) IF(NewtonMaxit <= 0)THEN PRINT * ,'User-selected ICNTRL(4)=',ICNTRL(4) CALL SDIRK_ErrorMsg(-2,Tinitial,ZERO,IDID) END IF END IF !~~~> Unit roundoff (1+Roundoff>1) Roundoff = WLAMCH('E') !~~~> Lower bound on the step size: (positive value) IF (RCNTRL(1) == ZERO) THEN Hmin = ZERO ELSEIF (RCNTRL(1) > ZERO) THEN Hmin = RCNTRL(1) ELSE PRINT * , 'User-selected RCNTRL(1)=', RCNTRL(1) CALL SDIRK_ErrorMsg(-3,Tinitial,ZERO,IDID) END IF !~~~> Upper bound on the step size: (positive value) IF (RCNTRL(2) == ZERO) THEN Hmax = ABS(Tfinal-Tinitial) ELSEIF (RCNTRL(2) > ZERO) THEN Hmax = MIN(ABS(RCNTRL(2)),ABS(Tfinal-Tinitial)) ELSE PRINT * , 'User-selected RCNTRL(2)=', RCNTRL(2) CALL SDIRK_ErrorMsg(-3,Tinitial,ZERO,IDID) END IF !~~~> Starting step size: (positive value) IF (RCNTRL(3) == ZERO) THEN Hstart = MAX(Hmin,Roundoff) ELSEIF (RCNTRL(3) > ZERO) THEN Hstart = MIN(ABS(RCNTRL(3)),ABS(Tfinal-Tinitial)) ELSE PRINT * , 'User-selected Hstart: RCNTRL(3)=', RCNTRL(3) CALL SDIRK_ErrorMsg(-3,Tinitial,ZERO,IDID) END IF !~~~> Step size can be changed s.t. FacMin < Hnew/Hexit < FacMax IF (RCNTRL(4) == ZERO) THEN FacMin = 0.2_dp ELSEIF (RCNTRL(4) > ZERO) THEN FacMin = RCNTRL(4) ELSE PRINT * , 'User-selected FacMin: RCNTRL(4)=', RCNTRL(4) CALL SDIRK_ErrorMsg(-4,Tinitial,ZERO,IDID) END IF IF (RCNTRL(5) == ZERO) THEN FacMax = 10.0_dp ELSEIF (RCNTRL(5) > ZERO) THEN FacMax = RCNTRL(5) ELSE PRINT * , 'User-selected FacMax: RCNTRL(5)=', RCNTRL(5) CALL SDIRK_ErrorMsg(-4,Tinitial,ZERO,IDID) END IF !~~~> FacRej: Factor to decrease step after 2 succesive rejections IF (RCNTRL(6) == ZERO) THEN FacRej = 0.1_dp ELSEIF (RCNTRL(6) > ZERO) THEN FacRej = RCNTRL(6) ELSE PRINT * , 'User-selected FacRej: RCNTRL(6)=', RCNTRL(6) CALL SDIRK_ErrorMsg(-4,Tinitial,ZERO,IDID) END IF !~~~> FacSafe: Safety Factor in the computation of new step size IF (RCNTRL(7) == ZERO) THEN FacSafe = 0.9_dp ELSEIF (RCNTRL(7) > ZERO) THEN FacSafe = RCNTRL(7) ELSE PRINT * , 'User-selected FacSafe: RCNTRL(7)=', RCNTRL(7) CALL SDIRK_ErrorMsg(-4,Tinitial,ZERO,IDID) END IF !~~~> DECIDES WHETHER THE JACOBIAN SHOULD BE RECOMPUTED; IF(RCNTRL(8) == 0.D0)THEN ThetaMin = 1.0d-3 ELSE ThetaMin = RCNTRL(8) END IF !~~~> STOPPING CRITERION FOR NEWTON'S METHOD IF(RCNTRL(9) == 0.0d0)THEN NewtonTol = 3.0d-2 ELSE NewtonTol =RCNTRL(9) END IF !~~~> Qmin AND Qmax: IF Qmin < Hnew/Hold < Qmax, STEP SIZE = CONST. IF(RCNTRL(10) == 0.D0)THEN Qmin=1.D0 ELSE Qmin=RCNTRL(10) END IF IF(RCNTRL(11) == 0.D0)THEN Qmax=1.2D0 ELSE Qmax=RCNTRL(11) END IF !~~~> Check if tolerances are reasonable IF (ITOL == 0) THEN IF (AbsTol(1) <= 0.D0.OR.RelTol(1) <= 10.D0*Roundoff) THEN PRINT * , ' Scalar AbsTol = ',AbsTol(1) PRINT * , ' Scalar RelTol = ',RelTol(1) CALL SDIRK_ErrorMsg(-5,Tinitial,ZERO,IDID) END IF ELSE DO i=1,N IF (AbsTol(i) <= 0.D0.OR.RelTol(i) <= 10.D0*Roundoff) THEN PRINT * , ' AbsTol(',i,') = ',AbsTol(i) PRINT * , ' RelTol(',i,') = ',RelTol(i) CALL SDIRK_ErrorMsg(-5,Tinitial,ZERO,IDID) END IF END DO END IF IF (IDID < 0) RETURN !~~~> CALL TO CORE INTEGRATOR CALL SDIRK_Integrator( N,Tinitial,Tfinal,Y,Hmin,Hmax,Hstart, & RelTol,AbsTol,ITOL, Max_no_steps, NewtonMaxit, & Roundoff, FacMin, FacMax, FacRej, FacSafe, ThetaMin, & NewtonTol, Qmin, Qmax, Hexit, Texit, IDID ) !~~~> Collect run statistics ISTATUS(ifun) = Nfun ISTATUS(ijac) = Njac ISTATUS(istp) = Nstp ISTATUS(iacc) = Nacc ISTATUS(irej) = Nrej ISTATUS(idec) = Ndec ISTATUS(isol) = Nsol ISTATUS(isng) = Nsng !~~~> Last T and H RSTATUS(itexit) = Texit RSTATUS(ihexit) = Hexit !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CONTAINS ! PROCEDURES INTERNAL TO SDIRK !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_Integrator( N,Tinitial,Tfinal,Y,Hmin,Hmax,Hstart, & RelTol,AbsTol,ITOL, Max_no_steps, NewtonMaxit, & Roundoff, FacMin, FacMax, FacRej, FacSafe, ThetaMin, & NewtonTol, Qmin, Qmax, Hexit, Texit, IDID ) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! CORE INTEGRATOR FOR SDIRK4 !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ USE KPP_ROOT_Parameters IMPLICIT NONE !~~~> Arguments: INTEGER :: N KPP_REAL, INTENT(INOUT) :: Y(NVAR) KPP_REAL, INTENT(IN) :: Tinitial, Tfinal, Hmin, Hmax, Hstart, & RelTol(NVAR), AbsTol(NVAR), Roundoff, & FacMin, FacMax, FacRej, FacSafe, ThetaMin, & NewtonTol, Qmin, Qmax KPP_REAL, INTENT(OUT) :: Hexit, Texit INTEGER, INTENT(IN) :: ITOL, Max_no_steps, NewtonMaxit INTEGER, INTENT(OUT) :: IDID !~~~> Local variables: KPP_REAL :: Z(NVAR,5), FV(NVAR,5), CONT(NVAR,4), & NewtonFactor(5), SCAL(NVAR), RHS(NVAR), & G(NVAR), Yhat(NVAR), TMP(NVAR), & T, H, Hold, Theta, Hratio, Hmax1, W, & HGammaInv, DYTH, QNEWT, ERR, Fac, Hnew, & Tdirection, NewtonErr, NewtonErrOld INTEGER :: i, j, IER, istage, NewtonIter, IP(NVAR) LOGICAL :: Reject, FIRST, NewtonReject, FreshJac, SkipJacUpdate, SkipLU #ifdef FULL_ALGEBRA KPP_REAL FJAC(NVAR,NVAR), E(NVAR,NVAR) #else KPP_REAL FJAC(LU_NONZERO), E(LU_NONZERO) #endif KPP_REAL, PARAMETER :: ZERO = 0.0d0, ONE = 1.0d0 !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! INITIALISATIONS !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CALL SDIRK_Coefficients T = Tinitial Tdirection = SIGN(1.D0,Tfinal-Tinitial) Hmax1=MIN(ABS(Hmax),ABS(Tfinal-Tinitial)) H = MAX(ABS(Hmin),ABS(Hstart)) IF (ABS(H) <= 10.D0*Roundoff) H=1.0D-6 H=MIN(ABS(H),Hmax1) H=SIGN(H,Tdirection) Hold=H NewtonReject=.FALSE. SkipLU =.FALSE. FreshJac = .FALSE. SkipJacUpdate = .FALSE. Reject=.FALSE. FIRST=.TRUE. NewtonFactor(1:5)=ONE CALL SDIRK_ErrorScale(ITOL, AbsTol, RelTol, Y, SCAL) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !~~~> Time loop begins !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tloop: DO WHILE ( (Tfinal-T)*Tdirection - Roundoff > ZERO ) !~~~> Compute E = 1/(h*gamma)-Jac and its LU decomposition IF ( SkipLU ) THEN ! This time around skip the Jac update and LU SkipLU = .FALSE.; FreshJac = .FALSE.; SkipJacUpdate = .FALSE. ELSE CALL SDIRK_PrepareMatrix ( H, T, Y, FJAC, & FreshJac, SkipJacUpdate, E, IP, Reject, IER ) IF (IER /= 0) THEN CALL SDIRK_ErrorMsg(-8,T,H,IDID); RETURN END IF END IF IF (Nstp>Max_no_steps) THEN CALL SDIRK_ErrorMsg(-6,T,H,IDID); RETURN END IF IF ( (T+0.1d0*H == T) .OR. (ABS(H) <= Roundoff) ) THEN CALL SDIRK_ErrorMsg(-7,T,H,IDID); RETURN END IF HGammaInv = ONE/(H*rkGamma) !~~~> NEWTON ITERATION stages:DO istage=1,5 NewtonFactor(istage) = MAX(NewtonFactor(istage),Roundoff)**0.8d0 !~~~> STARTING VALUES FOR NEWTON ITERATION CALL Set2zero(N,G) CALL Set2zero(N,Z(1,istage)) IF (istage==1) THEN IF (FIRST.OR.NewtonReject) THEN CALL Set2zero(N,Z(1,istage)) ELSE W=ONE+rkGamma*H/Hold DO i=1,N Z(i,istage)=W*(CONT(i,1)+W*(CONT(i,2)+W*(CONT(i,3)+W*CONT(i,4))))-Yhat(i) END DO END IF ELSE DO j = 1, istage-1 ! Gj(:) = sum_j Beta(i,j)*Zj(:) = H * sum_j A(i,j)*Fun(Zj(:)) CALL WAXPY(N,rkBeta(istage,j),Z(1,j),1,G,1) ! CALL WAXPY(N,H*rkA(istage,j),FV(1,j),1,G,1) ! Zi(:) = sum_j Alpha(i,j)*Zj(:) CALL WAXPY(N,rkAlpha(istage,j),Z(1,j),1,Z(1,istage),1) END DO IF (istage==5) CALL WCOPY(N,Z(1,istage),1,Yhat,1) ! Yhat(:) <- Z5(:) END IF !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! LOOP FOR THE SIMPLIFIED NEWTON ITERATION !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NewtonIter=0 Theta=ABS(ThetaMin) IF (Reject) Theta=2*ABS(ThetaMin) NewtonErr = 1.0e+6 ! To force-enter Newton loop Newton: DO WHILE (NewtonFactor(istage)*NewtonErr > NewtonTol) IF (NewtonIter >= NewtonMaxit) THEN H=H*0.5d0 Reject=.TRUE. NewtonReject=.TRUE. CYCLE Tloop END IF NewtonIter=NewtonIter+1 !~~~> COMPUTE THE RIGHT-HAND SIDE TMP(1:N) = Y(1:N) + Z(1:N,istage) CALL FUN_CHEM(T+rkC(istage)*H,TMP,RHS) TMP(1:N) = G(1:N) - Z(1:N,istage) CALL WAXPY(N,HGammaInv,TMP,1,RHS,1) ! RHS(:) <- RHS(:) + HGammaInv*(G(:)-Z(:)) !~~~> SOLVE THE LINEAR SYSTEMS #ifdef FULL_ALGEBRA CALL DGETRS( 'N', N, 1, E, N, IP, RHS, N, IER ) #else CALL KppSolve(E, RHS) #endif Nsol=Nsol+1 !~~~> CHECK CONVERGENCE OR IF NUMBER OF ITERATIONS TOO LARGE CALL SDIRK_ErrorNorm(N, RHS, SCAL, NewtonErr) IF ( (NewtonIter >= 2) .AND. (NewtonIter < NewtonMaxit) ) THEN Theta = NewtonErr/NewtonErrOld IF (Theta < 0.99d0) THEN NewtonFactor(istage)=Theta/(ONE-Theta) DYTH = NewtonFactor(istage)*NewtonErr* & Theta**(NewtonMaxit-1-NewtonIter) QNEWT = MAX(1.0d-4,MIN(16.0d0,DYTH/NewtonTol)) IF (QNEWT >= ONE) THEN H=.8D0*H*QNEWT**(-ONE/(NewtonMaxit-NewtonIter)) Reject=.TRUE. NewtonReject=.TRUE. CYCLE Tloop ! go back to the beginning of DO step END IF ELSE NewtonReject=.TRUE. H=H*0.5d0 Reject=.TRUE. CYCLE Tloop ! go back to the beginning of DO step END IF END IF NewtonErrOld = NewtonErr CALL WAXPY(N,ONE,RHS,1,Z(1,istage),1) ! Z(:) <-- Z(:)+RHS(:) END DO Newton !~~> END OF SIMPLIFIED NEWTON ITERATION ! Save function values TMP(1:N) = Y(1:N) + Z(1:N,istage) CALL FUN_CHEM(T+rkC(istage)*H,TMP,FV(1,istage)) END DO stages !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! ERROR ESTIMATION !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nstp=Nstp+1 TMP(1:N)=HGammaInv*(Z(1:N,5)-Yhat(1:N)) #ifdef FULL_ALGEBRA CALL DGETRS( 'N', N, 1, E, N, IP, TMP, N, IER ) #else CALL KppSolve(E, TMP) #endif CALL SDIRK_ErrorNorm(N, TMP, SCAL, ERR) !~~~> COMPUTATION OF Hnew: WE REQUIRE FacMin <= Hnew/H <= FacMax !Safe = FacSafe*DBLE(1+2*NewtonMaxit)/DBLE(NewtonIter+2*NewtonMaxit) Fac = MAX(FacMin,MIN(FacMax,(ERR)**(-0.25d0)*FacSafe)) Hnew = H*Fac !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! ACCEPT/Reject STEP !~~~~~~~~~~~~~~~~~~~~~~~~~~~~ accept: IF ( ERR < ONE ) THEN !~~~> STEP IS ACCEPTED FIRST=.FALSE. Nacc=Nacc+1 Hold=H !~~~> COEFFICIENTS FOR CONTINUOUS SOLUTION CALL WAXPY(N,ONE,Z(1,5),1,Y,1) ! Y(:) <-- Y(:)+Z5(:) CALL WCOPY(N,Z(1,5),1,Yhat,1) ! Yhat <-- Z5 DO i=1,4 ! CONTi <-- Sum_j rkD(i,j)*Zj CALL Set2zero(N,CONT(1,i)) DO j = 1,5 CALL WAXPY(N,rkD(i,j),Z(1,j),1,CONT(1,i),1) END DO END DO CALL SDIRK_ErrorScale(ITOL, AbsTol, RelTol, Y, SCAL) T=T+H FreshJac=.FALSE. Hnew = Tdirection*MIN(ABS(Hnew),Hmax1) Hexit = Hnew IF (Reject) Hnew=Tdirection*MIN(ABS(Hnew),ABS(H)) Reject = .FALSE. NewtonReject = .FALSE. IF ((T+Hnew/Qmin-Tfinal)*Tdirection > 0.D0) THEN H = Tfinal-T ELSE Hratio=Hnew/H ! If step not changed too much, keep it as is; ! do not update Jacobian and reuse LU IF ( (Theta <= ThetaMin) .AND. (Hratio >= Qmin) & .AND. (Hratio <= Qmax) ) THEN SkipJacUpdate = .TRUE. SkipLU = .TRUE. ELSE H = Hnew END IF END IF ! If convergence is fast enough, do not update Jacobian IF (Theta <= ThetaMin) SkipJacUpdate = .TRUE. ELSE accept !~~~> STEP IS REJECTED Reject=.TRUE. IF (FIRST) THEN H=H*FacRej ELSE H=Hnew END IF IF (Nacc >= 1) Nrej=Nrej+1 END IF accept END DO Tloop ! Successful return Texit = T IDID = 1 END SUBROUTINE SDIRK_Integrator !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_ErrorScale(ITOL, AbsTol, RelTol, Y, SCAL) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPLICIT NONE INTEGER :: i, ITOL KPP_REAL :: AbsTol(NVAR), RelTol(NVAR), & Y(NVAR), SCAL(NVAR) IF (ITOL == 0) THEN DO i=1,NVAR SCAL(i) = 1.0d0 / ( AbsTol(1)+RelTol(1)*ABS(Y(i)) ) END DO ELSE DO i=1,NVAR SCAL(i) = 1.0d0 / ( AbsTol(i)+RelTol(i)*ABS(Y(i)) ) END DO END IF END SUBROUTINE SDIRK_ErrorScale !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_ErrorNorm(N, Y, SCAL, ERR) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! INTEGER :: i, N KPP_REAL :: Y(N), SCAL(N), ERR ERR=0.0d0 DO i=1,N ERR = ERR+(Y(i)*SCAL(i))**2 END DO ERR = MAX( SQRT(ERR/DBLE(N)), 1.0d-10 ) ! END SUBROUTINE SDIRK_ErrorNorm !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_ErrorMsg(Code,T,H,IERR) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! Handles all error messages !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ KPP_REAL, INTENT(IN) :: T, H INTEGER, INTENT(IN) :: Code INTEGER, INTENT(OUT) :: IERR IERR = Code PRINT * , & 'Forced exit from SDIRK due to the following error:' IF ((Code>=-8).AND.(Code<=-1)) THEN PRINT *, IERR_NAMES(Code) ELSE PRINT *, 'Unknown Error code: ', Code ENDIF PRINT *, "T=", T, "and H=", H END SUBROUTINE SDIRK_ErrorMsg !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_PrepareMatrix ( H, T, Y, FJAC, & FreshJac, SkipJacUpdate, E, IP, Reject, IER ) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! IMPLICIT NONE KPP_REAL, INTENT(INOUT) :: H KPP_REAL, INTENT(IN) :: T, Y(NVAR) LOGICAL, INTENT(INOUT) :: FreshJac, SkipJacUpdate INTEGER, INTENT(OUT) :: IER, IP(NVAR) LOGICAL, INTENT(INOUT) :: Reject #ifdef FULL_ALGEBRA KPP_REAL, INTENT(INOUT) :: FJAC(NVAR,NVAR) KPP_REAL, INTENT(OUT) :: E(NVAR,NVAR) #else KPP_REAL, INTENT(INOUT) :: FJAC(LU_NONZERO) KPP_REAL, INTENT(OUT) :: E(LU_NONZERO) #endif KPP_REAL :: HGammaInv INTEGER :: i, j, ConsecutiveSng KPP_REAL, PARAMETER :: ONE = 1.0d0 20 CONTINUE !~~~> COMPUTE THE JACOBIAN IF (SkipJacUpdate) THEN SkipJacUpdate = .FALSE. ELSE IF ( .NOT.FreshJac ) THEN CALL JAC_CHEM( T, Y, FJAC ) FreshJac = .TRUE. END IF !~~~> Compute the matrix E = 1/(H*GAMMA)*Jac, and its decomposition ConsecutiveSng = 0 IER = 1 Hloop: DO WHILE (IER /= 0) HGammaInv = ONE/(H*rkGamma) #ifdef FULL_ALGEBRA DO j=1,NVAR DO i=1,NVAR E(i,j)=-FJAC(i,j) END DO E(j,j)=E(j,j)+HGammaInv END DO CALL DGETRF( NVAR, NVAR, E, NVAR, IP, IER ) #else DO i = 1,LU_NONZERO E(i) = -FJAC(i) END DO DO i = 1,NVAR j = LU_DIAG(i); E(j) = E(j) + HGammaInv END DO CALL KppDecomp ( E, IER) IP(1) = 1 #endif Ndec=Ndec+1 IF (IER /= 0) THEN WRITE (6,*) ' MATRIX IS SINGULAR, IER=',IER,' T=',T,' H=',H Nsng = Nsng+1; ConsecutiveSng = ConsecutiveSng + 1 IF (ConsecutiveSng >= 6) RETURN ! Failure H=H*0.5d0 Reject=.TRUE. !~~~> Update Jacobian if not fresh IF ( .NOT.FreshJac ) GOTO 20 END IF END DO Hloop END SUBROUTINE SDIRK_PrepareMatrix !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE SDIRK_Coefficients !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rkGamma=4.0d0/15.0d0 rkA(1,1)= 4.d0/15.d0 rkA(2,1)= 1.d0/2.d0 rkA(2,2)= 4.d0/15.d0 rkA(3,1)= 51069.d0/144200.d0 rkA(3,2)=-7809.d0/144200.d0 rkA(3,3)= 4.d0/15.d0 rkA(4,1)= 12047244770625658.d0/141474406359725325.d0 rkA(4,2)=-3057890203562191.d0/47158135453241775.d0 rkA(4,3)= 2239631894905804.d0/28294881271945065.d0 rkA(4,4)= 4.d0/15.d0 rkA(5,1)= 181513.d0/86430.d0 rkA(5,2)=-89074.d0/116015.d0 rkA(5,3)= 83636.d0/34851.d0 rkA(5,4)=-69863904375173.d0/23297141763930.d0 rkA(5,5)= 4.d0/15.d0 rkB(1)= 181513.d0/86430.d0 rkB(2)=-89074.d0/116015.d0 rkB(3)= 83636.d0/34851.d0 rkB(4)=-69863904375173.d0/23297141763930.d0 rkB(5)= 4/15.d0 rkC(1)=4.d0/15.d0 rkC(2)=23.d0/30.d0 rkC(3)=17.d0/30.d0 rkC(4)=707.d0/1931.d0 rkC(5)=1.d0 rkBeta(2,1)=15.0d0/8.0d0 rkBeta(3,1)=1577061.0d0/922880.0d0 rkBeta(3,2)=-23427.0d0/115360.0d0 rkBeta(4,1)=647163682356923881.0d0/2414496535205978880.0d0 rkBeta(4,2)=-593512117011179.0d0/3245291041943520.0d0 rkBeta(4,3)=559907973726451.0d0/1886325418129671.0d0 rkBeta(5,1)=724545451.0d0/796538880.0d0 rkBeta(5,2)=-830832077.0d0/267298560.0d0 rkBeta(5,3)=30957577.0d0/2509272.0d0 rkBeta(5,4)=-69863904375173.0d0/6212571137048.0d0 rkAlpha(2,1)= 23.d0/8.d0 rkAlpha(3,1)= 0.9838473040915402d0 rkAlpha(3,2)= 0.3969226768377252d0 rkAlpha(4,1)= 0.6563374010466914d0 rkAlpha(4,2)= 0.0d0 rkAlpha(4,3)= 0.3372498196189311d0 rkAlpha(5,1)=7752107607.0d0/11393456128.0d0 rkAlpha(5,2)=-17881415427.0d0/11470078208.0d0 rkAlpha(5,3)=2433277665.0d0/179459416.0d0 rkAlpha(5,4)=-96203066666797.0d0/6212571137048.0d0 rkD(1,1)= 24.74416644927758d0 rkD(1,2)= -4.325375951824688d0 rkD(1,3)= 41.39683763286316d0 rkD(1,4)= -61.04144619901784d0 rkD(1,5)= -3.391332232917013d0 rkD(2,1)= -51.98245719616925d0 rkD(2,2)= 10.52501981094525d0 rkD(2,3)= -154.2067922191855d0 rkD(2,4)= 214.3082125319825d0 rkD(2,5)= 14.71166018088679d0 rkD(3,1)= 33.14347947522142d0 rkD(3,2)= -19.72986789558523d0 rkD(3,3)= 230.4878502285804d0 rkD(3,4)= -287.6629744338197d0 rkD(3,5)= -18.99932366302254d0 rkD(4,1)= -5.905188728329743d0 rkD(4,2)= 13.53022403646467d0 rkD(4,3)= -117.6778956422581d0 rkD(4,4)= 134.3962081008550d0 rkD(4,5)= 8.678995715052762d0 END SUBROUTINE SDIRK_Coefficients !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ END SUBROUTINE SDIRK ! AND ALL ITS INTERNAL PROCEDURES !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE FUN_CHEM( T, Y, P ) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ USE KPP_ROOT_Global, ONLY: NVAR USE KPP_ROOT_Function INTEGER N KPP_REAL T !, Told KPP_REAL Y(NVAR), P(NVAR) !Told = TIME !TIME = T !CALL Update_SUN() !CALL Update_RCONST() CALL Fun( Y, FIX, RCONST, P ) !TIME = Told Nfun=Nfun+1 END SUBROUTINE FUN_CHEM !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SUBROUTINE JAC_CHEM( T, Y, JV ) !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ USE KPP_ROOT_Global, ONLY: NVAR USE KPP_ROOT_Jacobian INTEGER N KPP_REAL T !, Told KPP_REAL Y(NVAR) #ifdef FULL_ALGEBRA KPP_REAL :: JS(LU_NONZERO), JV(NVAR,NVAR) INTEGER :: i, j #else KPP_REAL :: JV(LU_NONZERO) #endif !Told = TIME !TIME = T !CALL Update_SUN() !CALL Update_RCONST() #ifdef FULL_ALGEBRA CALL Jac_SP(Y, FIX, RCONST, JS) DO j=1,NVAR DO j=1,NVAR JV(i,j) = 0.0D0 END DO END DO DO i=1,LU_NONZERO JV(LU_IROW(i),LU_ICOL(i)) = JS(i) END DO #else CALL Jac_SP(Y, FIX, RCONST, JV) #endif !TIME = Told Njac = Njac+1 END SUBROUTINE JAC_CHEM END MODULE KPP_ROOT_Integrator
/- Copyright (c) 2021 Hunter Monroe. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hunter Monroe, Kyle Miller, Alena Gusakov ! This file was ported from Lean 3 source module combinatorics.simple_graph.subgraph ! leanprover-community/mathlib commit c6ef6387ede9983aee397d442974e61f89dfd87b ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Combinatorics.SimpleGraph.Basic /-! # Subgraphs of a simple graph A subgraph of a simple graph consists of subsets of the graph's vertices and edges such that the endpoints of each edge are present in the vertex subset. The edge subset is formalized as a sub-relation of the adjacency relation of the simple graph. ## Main definitions * `Subgraph G` is the type of subgraphs of a `G : SimpleGraph V`. * `Subgraph.neighborSet`, `Subgraph.incidenceSet`, and `Subgraph.degree` are like their `SimpleGraph` counterparts, but they refer to vertices from `G` to avoid subtype coercions. * `Subgraph.coe` is the coercion from a `G' : Subgraph G` to a `SimpleGraph G'.verts`. (In Lean 3 this could not be a `Coe` instance since the destination type depends on `G'`.) * `Subgraph.IsSpanning` for whether a subgraph is a spanning subgraph and `Subgraph.IsInduced` for whether a subgraph is an induced subgraph. * Instances for `Lattice (Subgraph G)` and `BoundedOrder (Subgraph G)`. * `SimpleGraph.toSubgraph`: If a `SimpleGraph` is a subgraph of another, then you can turn it into a member of the larger graph's `SimpleGraph.Subgraph` type. * Graph homomorphisms from a subgraph to a graph (`Subgraph.map_top`) and between subgraphs (`Subgraph.map`). ## Implementation notes * Recall that subgraphs are not determined by their vertex sets, so `SetLike` does not apply to this kind of subobject. ## Todo * Images of graph homomorphisms as subgraphs. -/ universe u v namespace SimpleGraph /-- A subgraph of a `SimpleGraph` is a subset of vertices along with a restriction of the adjacency relation that is symmetric and is supported by the vertex subset. They also form a bounded lattice. Thinking of `V → V → Prop` as `Set (V × V)`, a set of darts (i.e., half-edges), then `Subgraph.adj_sub` is that the darts of a subgraph are a subset of the darts of `G`. -/ @[ext] structure Subgraph {V : Type u} (G : SimpleGraph V) where verts : Set V Adj : V → V → Prop adj_sub : ∀ {v w : V}, Adj v w → G.Adj v w edge_vert : ∀ {v w : V}, Adj v w → v ∈ verts symm : Symmetric Adj := by aesop_graph -- Porting note: Originally `by obviously` #align simple_graph.subgraph SimpleGraph.Subgraph variable {ι : Sort _} {V : Type u} {W : Type v} /-- The one-vertex subgraph. -/ @[simps] protected def singletonSubgraph (G : SimpleGraph V) (v : V) : G.Subgraph where verts := {v} Adj := ⊥ adj_sub := False.elim edge_vert := False.elim symm _ _ := False.elim #align simple_graph.singleton_subgraph SimpleGraph.singletonSubgraph /-- The one-edge subgraph. -/ @[simps] def subgraphOfAdj (G : SimpleGraph V) {v w : V} (hvw : G.Adj v w) : G.Subgraph where verts := {v, w} Adj a b := ⟦(v, w)⟧ = ⟦(a, b)⟧ adj_sub h := by rw [← G.mem_edgeSet, ← h] exact hvw edge_vert {a b} h := by apply_fun fun e ↦ a ∈ e at h simp only [Sym2.mem_iff, true_or, eq_iff_iff, iff_true] at h exact h #align simple_graph.subgraph_of_adj SimpleGraph.subgraphOfAdj namespace Subgraph variable {G : SimpleGraph V} {G₁ G₂ : G.Subgraph} {a b : V} protected theorem loopless (G' : Subgraph G) : Irreflexive G'.Adj := fun v h ↦ G.loopless v (G'.adj_sub h) #align simple_graph.subgraph.loopless SimpleGraph.Subgraph.loopless theorem adj_comm (G' : Subgraph G) (v w : V) : G'.Adj v w ↔ G'.Adj w v := ⟨fun x ↦ G'.symm x, fun x ↦ G'.symm x⟩ #align simple_graph.subgraph.adj_comm SimpleGraph.Subgraph.adj_comm @[symm] theorem adj_symm (G' : Subgraph G) {u v : V} (h : G'.Adj u v) : G'.Adj v u := G'.symm h #align simple_graph.subgraph.adj_symm SimpleGraph.Subgraph.adj_symm protected theorem Adj.symm {G' : Subgraph G} {u v : V} (h : G'.Adj u v) : G'.Adj v u := G'.symm h #align simple_graph.subgraph.adj.symm SimpleGraph.Subgraph.Adj.symm protected theorem Adj.adj_sub {H : G.Subgraph} {u v : V} (h : H.Adj u v) : G.Adj u v := H.adj_sub h #align simple_graph.subgraph.adj.adj_sub SimpleGraph.Subgraph.Adj.adj_sub protected theorem Adj.fst_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ∈ H.verts := H.edge_vert h #align simple_graph.subgraph.adj.fst_mem SimpleGraph.Subgraph.Adj.fst_mem protected theorem Adj.snd_mem {H : G.Subgraph} {u v : V} (h : H.Adj u v) : v ∈ H.verts := h.symm.fst_mem #align simple_graph.subgraph.adj.snd_mem SimpleGraph.Subgraph.Adj.snd_mem protected theorem Adj.ne {H : G.Subgraph} {u v : V} (h : H.Adj u v) : u ≠ v := h.adj_sub.ne #align simple_graph.subgraph.adj.ne SimpleGraph.Subgraph.Adj.ne /-- Coercion from `G' : Subgraph G` to a `SimpleGraph G'.verts`. -/ @[simps] protected def coe (G' : Subgraph G) : SimpleGraph G'.verts where Adj v w := G'.Adj v w symm _ _ h := G'.symm h loopless v h := loopless G v (G'.adj_sub h) #align simple_graph.subgraph.coe SimpleGraph.Subgraph.coe @[simp] theorem coe_adj_sub (G' : Subgraph G) (u v : G'.verts) (h : G'.coe.Adj u v) : G.Adj u v := G'.adj_sub h #align simple_graph.subgraph.coe_adj_sub SimpleGraph.Subgraph.coe_adj_sub -- Given `h : H.Adj u v`, then `h.coe : H.coe.Adj ⟨u, _⟩ ⟨v, _⟩`. protected theorem Adj.coe {H : G.Subgraph} {u v : V} (h : H.Adj u v) : H.coe.Adj ⟨u, H.edge_vert h⟩ ⟨v, H.edge_vert h.symm⟩ := h #align simple_graph.subgraph.adj.coe SimpleGraph.Subgraph.Adj.coe /-- A subgraph is called a *spanning subgraph* if it contains all the vertices of `G`. -/ def IsSpanning (G' : Subgraph G) : Prop := ∀ v : V, v ∈ G'.verts #align simple_graph.subgraph.is_spanning SimpleGraph.Subgraph.IsSpanning theorem isSpanning_iff {G' : Subgraph G} : G'.IsSpanning ↔ G'.verts = Set.univ := Set.eq_univ_iff_forall.symm #align simple_graph.subgraph.is_spanning_iff SimpleGraph.Subgraph.isSpanning_iff /-- Coercion from `Subgraph G` to `SimpleGraph V`. If `G'` is a spanning subgraph, then `G'.spanningCoe` yields an isomorphic graph. In general, this adds in all vertices from `V` as isolated vertices. -/ @[simps] protected def spanningCoe (G' : Subgraph G) : SimpleGraph V where Adj := G'.Adj symm := G'.symm loopless v hv := G.loopless v (G'.adj_sub hv) #align simple_graph.subgraph.spanning_coe SimpleGraph.Subgraph.spanningCoe @[simp] theorem Adj.of_spanningCoe {G' : Subgraph G} {u v : G'.verts} (h : G'.spanningCoe.Adj u v) : G.Adj u v := G'.adj_sub h #align simple_graph.subgraph.adj.of_spanning_coe SimpleGraph.Subgraph.Adj.of_spanningCoe theorem spanningCoe_inj : G₁.spanningCoe = G₂.spanningCoe ↔ G₁.Adj = G₂.Adj := by simp [Subgraph.spanningCoe] #align simple_graph.subgraph.spanning_coe_inj SimpleGraph.Subgraph.spanningCoe_inj /-- `spanningCoe` is equivalent to `coe` for a subgraph that `IsSpanning`. -/ @[simps] def spanningCoeEquivCoeOfSpanning (G' : Subgraph G) (h : G'.IsSpanning) : G'.spanningCoe ≃g G'.coe where toFun v := ⟨v, h v⟩ invFun v := v left_inv _ := rfl right_inv _ := rfl map_rel_iff' := Iff.rfl #align simple_graph.subgraph.spanning_coe_equiv_coe_of_spanning SimpleGraph.Subgraph.spanningCoeEquivCoeOfSpanning /-- A subgraph is called an *induced subgraph* if vertices of `G'` are adjacent if they are adjacent in `G`. -/ def IsInduced (G' : Subgraph G) : Prop := ∀ {v w : V}, v ∈ G'.verts → w ∈ G'.verts → G.Adj v w → G'.Adj v w #align simple_graph.subgraph.is_induced SimpleGraph.Subgraph.IsInduced /-- `H.support` is the set of vertices that form edges in the subgraph `H`. -/ def support (H : Subgraph G) : Set V := Rel.dom H.Adj #align simple_graph.subgraph.support SimpleGraph.Subgraph.support theorem mem_support (H : Subgraph G) {v : V} : v ∈ H.support ↔ ∃ w, H.Adj v w := Iff.rfl #align simple_graph.subgraph.mem_support SimpleGraph.Subgraph.mem_support theorem support_subset_verts (H : Subgraph G) : H.support ⊆ H.verts := fun _ ⟨_, h⟩ ↦ H.edge_vert h #align simple_graph.subgraph.support_subset_verts SimpleGraph.Subgraph.support_subset_verts /-- `G'.neighborSet v` is the set of vertices adjacent to `v` in `G'`. -/ def neighborSet (G' : Subgraph G) (v : V) : Set V := {w | G'.Adj v w} #align simple_graph.subgraph.neighbor_set SimpleGraph.Subgraph.neighborSet theorem neighborSet_subset (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G.neighborSet v := fun _ ↦ G'.adj_sub #align simple_graph.subgraph.neighbor_set_subset SimpleGraph.Subgraph.neighborSet_subset theorem neighborSet_subset_verts (G' : Subgraph G) (v : V) : G'.neighborSet v ⊆ G'.verts := fun _ h ↦ G'.edge_vert (adj_symm G' h) #align simple_graph.subgraph.neighbor_set_subset_verts SimpleGraph.Subgraph.neighborSet_subset_verts @[simp] theorem mem_neighborSet (G' : Subgraph G) (v w : V) : w ∈ G'.neighborSet v ↔ G'.Adj v w := Iff.rfl #align simple_graph.subgraph.mem_neighbor_set SimpleGraph.Subgraph.mem_neighborSet /-- A subgraph as a graph has equivalent neighbor sets. -/ def coeNeighborSetEquiv {G' : Subgraph G} (v : G'.verts) : G'.coe.neighborSet v ≃ G'.neighborSet v where toFun w := ⟨w, w.2⟩ invFun w := ⟨⟨w, G'.edge_vert (G'.adj_symm w.2)⟩, w.2⟩ left_inv _ := rfl right_inv _ := rfl #align simple_graph.subgraph.coe_neighbor_set_equiv SimpleGraph.Subgraph.coeNeighborSetEquiv /-- The edge set of `G'` consists of a subset of edges of `G`. -/ def edgeSet (G' : Subgraph G) : Set (Sym2 V) := Sym2.fromRel G'.symm #align simple_graph.subgraph.edge_set SimpleGraph.Subgraph.edgeSet theorem edgeSet_subset (G' : Subgraph G) : G'.edgeSet ⊆ G.edgeSet := Sym2.ind (fun _ _ ↦ G'.adj_sub) #align simple_graph.subgraph.edge_set_subset SimpleGraph.Subgraph.edgeSet_subset @[simp] theorem mem_edgeSet {G' : Subgraph G} {v w : V} : ⟦(v, w)⟧ ∈ G'.edgeSet ↔ G'.Adj v w := Iff.rfl #align simple_graph.subgraph.mem_edge_set SimpleGraph.Subgraph.mem_edgeSet theorem mem_verts_if_mem_edge {G' : Subgraph G} {e : Sym2 V} {v : V} (he : e ∈ G'.edgeSet) (hv : v ∈ e) : v ∈ G'.verts := by revert hv refine' Sym2.ind (fun v w he ↦ _) e he intro hv rcases Sym2.mem_iff.mp hv with (rfl | rfl) · exact G'.edge_vert he · exact G'.edge_vert (G'.symm he) #align simple_graph.subgraph.mem_verts_if_mem_edge SimpleGraph.Subgraph.mem_verts_if_mem_edge /-- The `incidenceSet` is the set of edges incident to a given vertex. -/ def incidenceSet (G' : Subgraph G) (v : V) : Set (Sym2 V) := {e ∈ G'.edgeSet | v ∈ e} #align simple_graph.subgraph.incidence_set SimpleGraph.Subgraph.incidenceSet theorem incidenceSet_subset_incidenceSet (G' : Subgraph G) (v : V) : G'.incidenceSet v ⊆ G.incidenceSet v := fun _ h ↦ ⟨G'.edgeSet_subset h.1, h.2⟩ #align simple_graph.subgraph.incidence_set_subset_incidence_set SimpleGraph.Subgraph.incidenceSet_subset_incidenceSet theorem incidenceSet_subset (G' : Subgraph G) (v : V) : G'.incidenceSet v ⊆ G'.edgeSet := fun _ h ↦ h.1 #align simple_graph.subgraph.incidence_set_subset SimpleGraph.Subgraph.incidenceSet_subset /-- Give a vertex as an element of the subgraph's vertex type. -/ @[reducible] def vert (G' : Subgraph G) (v : V) (h : v ∈ G'.verts) : G'.verts := ⟨v, h⟩ #align simple_graph.subgraph.vert SimpleGraph.Subgraph.vert /-- Create an equal copy of a subgraph (see `copy_eq`) with possibly different definitional equalities. See Note [range copy pattern]. -/ def copy (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts) (adj' : V → V → Prop) (hadj : adj' = G'.Adj) : Subgraph G where verts := V'' Adj := adj' adj_sub := hadj.symm ▸ G'.adj_sub edge_vert := hV.symm ▸ hadj.symm ▸ G'.edge_vert symm := hadj.symm ▸ G'.symm #align simple_graph.subgraph.copy SimpleGraph.Subgraph.copy theorem copy_eq (G' : Subgraph G) (V'' : Set V) (hV : V'' = G'.verts) (adj' : V → V → Prop) (hadj : adj' = G'.Adj) : G'.copy V'' hV adj' hadj = G' := Subgraph.ext _ _ hV hadj #align simple_graph.subgraph.copy_eq SimpleGraph.Subgraph.copy_eq /-- The union of two subgraphs. -/ instance : Sup G.Subgraph where sup G₁ G₂ := { verts := G₁.verts ∪ G₂.verts Adj := G₁.Adj ⊔ G₂.Adj adj_sub := fun hab => Or.elim hab (fun h => G₁.adj_sub h) fun h => G₂.adj_sub h edge_vert := Or.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h symm := fun _ _ => Or.imp G₁.adj_symm G₂.adj_symm } /-- The intersection of two subgraphs. -/ instance : Inf G.Subgraph where inf G₁ G₂ := { verts := G₁.verts ∩ G₂.verts Adj := G₁.Adj ⊓ G₂.Adj adj_sub := fun hab => G₁.adj_sub hab.1 edge_vert := And.imp (fun h => G₁.edge_vert h) fun h => G₂.edge_vert h symm := fun _ _ => And.imp G₁.adj_symm G₂.adj_symm } /-- The `top` subgraph is `G` as a subgraph of itself. -/ instance : Top G.Subgraph where top := { verts := Set.univ Adj := G.Adj adj_sub := id edge_vert := @fun v _ _ => Set.mem_univ v symm := G.symm } /-- The `bot` subgraph is the subgraph with no vertices or edges. -/ instance : Bot G.Subgraph where bot := { verts := ∅ Adj := ⊥ adj_sub := False.elim edge_vert := False.elim symm := fun _ _ => id } instance : SupSet G.Subgraph where supₛ s := { verts := ⋃ G' ∈ s, verts G' Adj := fun a b => ∃ G' ∈ s, Adj G' a b adj_sub := by rintro a b ⟨G', -, hab⟩ exact G'.adj_sub hab edge_vert := by rintro a b ⟨G', hG', hab⟩ exact Set.mem_unionᵢ₂_of_mem hG' (G'.edge_vert hab) symm := fun a b h => by simpa [adj_comm] using h } instance : InfSet G.Subgraph where infₛ s := { verts := ⋂ G' ∈ s, verts G' Adj := fun a b => (∀ ⦃G'⦄, G' ∈ s → Adj G' a b) ∧ G.Adj a b adj_sub := And.right edge_vert := fun hab => Set.mem_interᵢ₂_of_mem fun G' hG' => G'.edge_vert <| hab.1 hG' symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) G.adj_symm } @[simp] theorem sup_adj : (G₁ ⊔ G₂).Adj a b ↔ G₁.Adj a b ∨ G₂.Adj a b := Iff.rfl #align simple_graph.subgraph.sup_adj SimpleGraph.Subgraph.sup_adj @[simp] theorem inf_adj : (G₁ ⊓ G₂).Adj a b ↔ G₁.Adj a b ∧ G₂.Adj a b := Iff.rfl #align simple_graph.subgraph.inf_adj SimpleGraph.Subgraph.inf_adj @[simp] theorem top_adj : (⊤ : Subgraph G).Adj a b ↔ G.Adj a b := Iff.rfl #align simple_graph.subgraph.top_adj SimpleGraph.Subgraph.top_adj @[simp] theorem not_bot_adj : ¬ (⊥ : Subgraph G).Adj a b := not_false #align simple_graph.subgraph.not_bot_adj SimpleGraph.Subgraph.not_bot_adj @[simp] theorem verts_sup (G₁ G₂ : G.Subgraph) : (G₁ ⊔ G₂).verts = G₁.verts ∪ G₂.verts := rfl #align simple_graph.subgraph.verts_sup SimpleGraph.Subgraph.verts_sup @[simp] theorem verts_inf (G₁ G₂ : G.Subgraph) : (G₁ ⊓ G₂).verts = G₁.verts ∩ G₂.verts := rfl #align simple_graph.subgraph.verts_inf SimpleGraph.Subgraph.verts_inf @[simp] theorem verts_top : (⊤ : G.Subgraph).verts = Set.univ := rfl #align simple_graph.subgraph.verts_top SimpleGraph.Subgraph.verts_top @[simp] theorem verts_bot : (⊥ : G.Subgraph).verts = ∅ := rfl #align simple_graph.subgraph.verts_bot SimpleGraph.Subgraph.verts_bot @[simp] theorem supₛ_adj {s : Set G.Subgraph} : (supₛ s).Adj a b ↔ ∃ G ∈ s, Adj G a b := Iff.rfl #align simple_graph.subgraph.Sup_adj SimpleGraph.Subgraph.supₛ_adj @[simp] theorem infₛ_adj {s : Set G.Subgraph} : (infₛ s).Adj a b ↔ (∀ G' ∈ s, Adj G' a b) ∧ G.Adj a b := Iff.rfl #align simple_graph.subgraph.Inf_adj SimpleGraph.Subgraph.infₛ_adj @[simp] theorem supᵢ_adj {f : ι → G.Subgraph} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [supᵢ] #align simple_graph.subgraph.supr_adj SimpleGraph.Subgraph.supᵢ_adj @[simp] theorem infᵢ_adj {f : ι → G.Subgraph} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ G.Adj a b := by simp [infᵢ] #align simple_graph.subgraph.infi_adj SimpleGraph.Subgraph.infᵢ_adj theorem infₛ_adj_of_nonempty {s : Set G.Subgraph} (hs : s.Nonempty) : (infₛ s).Adj a b ↔ ∀ G' ∈ s, Adj G' a b := infₛ_adj.trans <| and_iff_left_of_imp <| by obtain ⟨G', hG'⟩ := hs exact fun h => G'.adj_sub (h _ hG') #align simple_graph.subgraph.Inf_adj_of_nonempty SimpleGraph.Subgraph.infₛ_adj_of_nonempty theorem infᵢ_adj_of_nonempty [Nonempty ι] {f : ι → G.Subgraph} : (⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by rw [infᵢ, infₛ_adj_of_nonempty (Set.range_nonempty _)] simp #align simple_graph.subgraph.infi_adj_of_nonempty SimpleGraph.Subgraph.infᵢ_adj_of_nonempty @[simp] theorem verts_supₛ (s : Set G.Subgraph) : (supₛ s).verts = ⋃ G' ∈ s, verts G' := rfl #align simple_graph.subgraph.verts_Sup SimpleGraph.Subgraph.verts_supₛ @[simp] theorem verts_infₛ (s : Set G.Subgraph) : (infₛ s).verts = ⋂ G' ∈ s, verts G' := rfl #align simple_graph.subgraph.verts_Inf SimpleGraph.Subgraph.verts_infₛ @[simp] theorem verts_supᵢ {f : ι → G.Subgraph} : (⨆ i, f i).verts = ⋃ i, (f i).verts := by simp [supᵢ] #align simple_graph.subgraph.verts_supr SimpleGraph.Subgraph.verts_supᵢ @[simp] theorem verts_infᵢ {f : ι → G.Subgraph} : (⨅ i, f i).verts = ⋂ i, (f i).verts := by simp [infᵢ] #align simple_graph.subgraph.verts_infi SimpleGraph.Subgraph.verts_infᵢ /-- For subgraphs `G₁`, `G₂`, `G₁ ≤ G₂` iff `G₁.verts ⊆ G₂.verts` and `∀ a b, G₁.adj a b → G₂.adj a b`. -/ instance distribLattice : DistribLattice G.Subgraph := { show DistribLattice G.Subgraph from Function.Injective.distribLattice (fun G' => (G'.verts, G'.spanningCoe)) (fun G₁ G₂ h => by rw [Prod.ext_iff] at h exact Subgraph.ext _ _ h.1 (spanningCoe_inj.1 h.2)) (fun _ _ => rfl) fun _ _ => rfl with le := fun x y => x.verts ⊆ y.verts ∧ ∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w } instance : BoundedOrder (Subgraph G) where top := ⊤ bot := ⊥ le_top x := ⟨Set.subset_univ _, fun _ _ => x.adj_sub⟩ bot_le _ := ⟨Set.empty_subset _, fun _ _ => False.elim⟩ -- Note that subgraphs do not form a Boolean algebra, because of `verts`. instance : CompleteDistribLattice G.Subgraph := { Subgraph.distribLattice with le := (· ≤ ·) sup := (· ⊔ ·) inf := (· ⊓ ·) top := ⊤ bot := ⊥ le_top := fun G' => ⟨Set.subset_univ _, fun a b => G'.adj_sub⟩ bot_le := fun G' => ⟨Set.empty_subset _, fun a b => False.elim⟩ supₛ := supₛ -- porting note: needed `apply` here to modify elaboration; previously the term itself was fine. le_supₛ := fun s G' hG' => ⟨by apply Set.subset_unionᵢ₂ G' hG', fun a b hab => ⟨G', hG', hab⟩⟩ supₛ_le := fun s G' hG' => ⟨Set.unionᵢ₂_subset fun H hH => (hG' _ hH).1, by rintro a b ⟨H, hH, hab⟩ exact (hG' _ hH).2 hab⟩ infₛ := infₛ infₛ_le := fun s G' hG' => ⟨Set.interᵢ₂_subset G' hG', fun a b hab => hab.1 hG'⟩ le_infₛ := fun s G' hG' => ⟨Set.subset_interᵢ₂ fun H hH => (hG' _ hH).1, fun a b hab => ⟨fun H hH => (hG' _ hH).2 hab, G'.adj_sub hab⟩⟩ inf_supₛ_le_supᵢ_inf := fun G' s => by constructor · intro v simp · intros a b simp infᵢ_sup_le_sup_infₛ := fun G' s => by constructor · intro simp [← forall_or_left] · intros a b hab simpa [forall_and, forall_or_left, or_and_right, and_iff_left_of_imp G'.adj_sub] using hab } @[simps] instance subgraphInhabited : Inhabited (Subgraph G) := ⟨⊥⟩ #align simple_graph.subgraph.subgraph_inhabited SimpleGraph.Subgraph.subgraphInhabited @[simp] theorem neighborSet_sup {H H' : G.Subgraph} (v : V) : (H ⊔ H').neighborSet v = H.neighborSet v ∪ H'.neighborSet v := rfl #align simple_graph.subgraph.neighbor_set_sup SimpleGraph.Subgraph.neighborSet_sup @[simp] theorem neighborSet_inf {H H' : G.Subgraph} (v : V) : (H ⊓ H').neighborSet v = H.neighborSet v ∩ H'.neighborSet v := rfl #align simple_graph.subgraph.neighbor_set_inf SimpleGraph.Subgraph.neighborSet_inf @[simp] theorem neighborSet_top (v : V) : (⊤ : G.Subgraph).neighborSet v = G.neighborSet v := rfl #align simple_graph.subgraph.neighbor_set_top SimpleGraph.Subgraph.neighborSet_top @[simp] theorem neighborSet_bot (v : V) : (⊥ : G.Subgraph).neighborSet v = ∅ := rfl #align simple_graph.subgraph.neighbor_set_bot SimpleGraph.Subgraph.neighborSet_bot @[simp] theorem neighborSet_supₛ (s : Set G.Subgraph) (v : V) : (supₛ s).neighborSet v = ⋃ G' ∈ s, neighborSet G' v := by ext simp #align simple_graph.subgraph.neighbor_set_Sup SimpleGraph.Subgraph.neighborSet_supₛ @[simp] theorem neighborSet_infₛ (s : Set G.Subgraph) (v : V) : (infₛ s).neighborSet v = (⋂ G' ∈ s, neighborSet G' v) ∩ G.neighborSet v := by ext simp #align simple_graph.subgraph.neighbor_set_Inf SimpleGraph.Subgraph.neighborSet_infₛ @[simp] theorem neighborSet_supᵢ (f : ι → G.Subgraph) (v : V) : (⨆ i, f i).neighborSet v = ⋃ i, (f i).neighborSet v := by simp [supᵢ] #align simple_graph.subgraph.neighbor_set_supr SimpleGraph.Subgraph.neighborSet_supᵢ @[simp] theorem neighborSet_infᵢ (f : ι → G.Subgraph) (v : V) : (⨅ i, f i).neighborSet v = (⋂ i, (f i).neighborSet v) ∩ G.neighborSet v := by simp [infᵢ] #align simple_graph.subgraph.neighbor_set_infi SimpleGraph.Subgraph.neighborSet_infᵢ @[simp] theorem edgeSet_top : (⊤ : Subgraph G).edgeSet = G.edgeSet := rfl #align simple_graph.subgraph.edge_set_top SimpleGraph.Subgraph.edgeSet_top @[simp] theorem edgeSet_bot : (⊥ : Subgraph G).edgeSet = ∅ := Set.ext <| Sym2.ind (by simp) #align simple_graph.subgraph.edge_set_bot SimpleGraph.Subgraph.edgeSet_bot @[simp] theorem edgeSet_inf {H₁ H₂ : Subgraph G} : (H₁ ⊓ H₂).edgeSet = H₁.edgeSet ∩ H₂.edgeSet := Set.ext <| Sym2.ind (by simp) #align simple_graph.subgraph.edge_set_inf SimpleGraph.Subgraph.edgeSet_inf @[simp] theorem edgeSet_sup {H₁ H₂ : Subgraph G} : (H₁ ⊔ H₂).edgeSet = H₁.edgeSet ∪ H₂.edgeSet := Set.ext <| Sym2.ind (by simp) #align simple_graph.subgraph.edge_set_sup SimpleGraph.Subgraph.edgeSet_sup @[simp] theorem edgeSet_supₛ (s : Set G.Subgraph) : (supₛ s).edgeSet = ⋃ G' ∈ s, edgeSet G' := by ext e induction e using Sym2.ind simp #align simple_graph.subgraph.edge_set_Sup SimpleGraph.Subgraph.edgeSet_supₛ @[simp] theorem edgeSet_infₛ (s : Set G.Subgraph) : (infₛ s).edgeSet = (⋂ G' ∈ s, edgeSet G') ∩ G.edgeSet := by ext e induction e using Sym2.ind simp #align simple_graph.subgraph.edge_set_Inf SimpleGraph.Subgraph.edgeSet_infₛ @[simp] theorem edgeSet_supᵢ (f : ι → G.Subgraph) : (⨆ i, f i).edgeSet = ⋃ i, (f i).edgeSet := by simp [supᵢ] #align simple_graph.subgraph.edge_set_supr SimpleGraph.Subgraph.edgeSet_supᵢ @[simp] theorem edgeSet_infᵢ (f : ι → G.Subgraph) : (⨅ i, f i).edgeSet = (⋂ i, (f i).edgeSet) ∩ G.edgeSet := by simp [infᵢ] #align simple_graph.subgraph.edge_set_infi SimpleGraph.Subgraph.edgeSet_infᵢ @[simp] theorem spanningCoe_top : (⊤ : Subgraph G).spanningCoe = G := rfl #align simple_graph.subgraph.spanning_coe_top SimpleGraph.Subgraph.spanningCoe_top @[simp] theorem spanningCoe_bot : (⊥ : Subgraph G).spanningCoe = ⊥ := rfl #align simple_graph.subgraph.spanning_coe_bot SimpleGraph.Subgraph.spanningCoe_bot /-- Turn a subgraph of a `SimpleGraph` into a member of its subgraph type. -/ @[simps] def _root_.SimpleGraph.toSubgraph (H : SimpleGraph V) (h : H ≤ G) : G.Subgraph where verts := Set.univ Adj := H.Adj adj_sub e := h e edge_vert _ := Set.mem_univ _ symm := H.symm #align simple_graph.to_subgraph SimpleGraph.toSubgraph theorem support_mono {H H' : Subgraph G} (h : H ≤ H') : H.support ⊆ H'.support := Rel.dom_mono h.2 #align simple_graph.subgraph.support_mono SimpleGraph.Subgraph.support_mono theorem _root_.SimpleGraph.toSubgraph.isSpanning (H : SimpleGraph V) (h : H ≤ G) : (toSubgraph H h).IsSpanning := Set.mem_univ #align simple_graph.to_subgraph.is_spanning SimpleGraph.toSubgraph.isSpanning theorem spanningCoe_le_of_le {H H' : Subgraph G} (h : H ≤ H') : H.spanningCoe ≤ H'.spanningCoe := h.2 #align simple_graph.subgraph.spanning_coe_le_of_le SimpleGraph.Subgraph.spanningCoe_le_of_le /-- The top of the `Subgraph G` lattice is equivalent to the graph itself. -/ def topEquiv : (⊤ : Subgraph G).coe ≃g G where toFun v := ↑v invFun v := ⟨v, trivial⟩ left_inv _ := rfl right_inv _ := rfl map_rel_iff' := Iff.rfl #align simple_graph.subgraph.top_equiv SimpleGraph.Subgraph.topEquiv /-- The bottom of the `Subgraph G` lattice is equivalent to the empty graph on the empty vertex type. -/ def botEquiv : (⊥ : Subgraph G).coe ≃g (⊥ : SimpleGraph Empty) where toFun v := v.property.elim invFun v := v.elim left_inv := fun ⟨_, h⟩ ↦ h.elim right_inv v := v.elim map_rel_iff' := Iff.rfl #align simple_graph.subgraph.bot_equiv SimpleGraph.Subgraph.botEquiv theorem edgeSet_mono {H₁ H₂ : Subgraph G} (h : H₁ ≤ H₂) : H₁.edgeSet ≤ H₂.edgeSet := Sym2.ind h.2 #align simple_graph.subgraph.edge_set_mono SimpleGraph.Subgraph.edgeSet_mono theorem _root_.Disjoint.edgeSet {H₁ H₂ : Subgraph G} (h : Disjoint H₁ H₂) : Disjoint H₁.edgeSet H₂.edgeSet := disjoint_iff_inf_le.mpr <| by simpa using edgeSet_mono h.le_bot #align disjoint.edge_set Disjoint.edgeSet /-- Graph homomorphisms induce a covariant function on subgraphs. -/ @[simps] protected def map {G' : SimpleGraph W} (f : G →g G') (H : G.Subgraph) : G'.Subgraph where verts := f '' H.verts Adj := Relation.Map H.Adj f f adj_sub := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact f.map_rel (H.adj_sub h) edge_vert := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact Set.mem_image_of_mem _ (H.edge_vert h) symm := by rintro _ _ ⟨u, v, h, rfl, rfl⟩ exact ⟨v, u, H.symm h, rfl, rfl⟩ #align simple_graph.subgraph.map SimpleGraph.Subgraph.map theorem map_monotone {G' : SimpleGraph W} (f : G →g G') : Monotone (Subgraph.map f) := by intro H H' h constructor · intro simp only [map_verts, Set.mem_image, forall_exists_index, and_imp] rintro v hv rfl exact ⟨_, h.1 hv, rfl⟩ · rintro _ _ ⟨u, v, ha, rfl, rfl⟩ exact ⟨_, _, h.2 ha, rfl, rfl⟩ #align simple_graph.subgraph.map_monotone SimpleGraph.Subgraph.map_monotone theorem map_sup {G : SimpleGraph V} {G' : SimpleGraph W} (f : G →g G') {H H' : G.Subgraph} : (H ⊔ H').map f = H.map f ⊔ H'.map f := by ext1 · simp only [Set.image_union, map_verts, verts_sup] · ext simp only [Relation.Map, map_Adj, sup_adj] constructor · rintro ⟨a, b, h | h, rfl, rfl⟩ · exact Or.inl ⟨_, _, h, rfl, rfl⟩ · exact Or.inr ⟨_, _, h, rfl, rfl⟩ · rintro (⟨a, b, h, rfl, rfl⟩ | ⟨a, b, h, rfl, rfl⟩) · exact ⟨_, _, Or.inl h, rfl, rfl⟩ · exact ⟨_, _, Or.inr h, rfl, rfl⟩ #align simple_graph.subgraph.map_sup SimpleGraph.Subgraph.map_sup /-- Graph homomorphisms induce a contravariant function on subgraphs. -/ @[simps] protected def comap {G' : SimpleGraph W} (f : G →g G') (H : G'.Subgraph) : G.Subgraph where verts := f ⁻¹' H.verts Adj u v := G.Adj u v ∧ H.Adj (f u) (f v) adj_sub h := h.1 edge_vert h := Set.mem_preimage.1 (H.edge_vert h.2) symm _ _ h := ⟨G.symm h.1, H.symm h.2⟩ #align simple_graph.subgraph.comap SimpleGraph.Subgraph.comap theorem comap_monotone {G' : SimpleGraph W} (f : G →g G') : Monotone (Subgraph.comap f) := by intro H H' h constructor · intro simp only [comap_verts, Set.mem_preimage] apply h.1 · intro v w simp (config := { contextual := true }) only [comap_Adj, and_imp, true_and_iff] intro apply h.2 #align simple_graph.subgraph.comap_monotone SimpleGraph.Subgraph.comap_monotone theorem map_le_iff_le_comap {G' : SimpleGraph W} (f : G →g G') (H : G.Subgraph) (H' : G'.Subgraph) : H.map f ≤ H' ↔ H ≤ H'.comap f := by refine' ⟨fun h ↦ ⟨fun v hv ↦ _, fun v w hvw ↦ _⟩, fun h ↦ ⟨fun v ↦ _, fun v w ↦ _⟩⟩ · simp only [comap_verts, Set.mem_preimage] exact h.1 ⟨v, hv, rfl⟩ · simp only [H.adj_sub hvw, comap_Adj, true_and_iff] exact h.2 ⟨v, w, hvw, rfl, rfl⟩ · simp only [map_verts, Set.mem_image, forall_exists_index, and_imp] rintro w hw rfl exact h.1 hw · simp only [Relation.Map, map_Adj, forall_exists_index, and_imp] rintro u u' hu rfl rfl exact (h.2 hu).2 #align simple_graph.subgraph.map_le_iff_le_comap SimpleGraph.Subgraph.map_le_iff_le_comap /-- Given two subgraphs, one a subgraph of the other, there is an induced injective homomorphism of the subgraphs as graphs. -/ @[simps] def inclusion {x y : Subgraph G} (h : x ≤ y) : x.coe →g y.coe where toFun v := ⟨↑v, And.left h v.property⟩ map_rel' hvw := h.2 hvw #align simple_graph.subgraph.inclusion SimpleGraph.Subgraph.inclusion theorem inclusion.injective {x y : Subgraph G} (h : x ≤ y) : Function.Injective (inclusion h) := by intro v w h rw [inclusion, FunLike.coe, Subtype.mk_eq_mk] at h exact Subtype.ext h #align simple_graph.subgraph.inclusion.injective SimpleGraph.Subgraph.inclusion.injective /-- There is an induced injective homomorphism of a subgraph of `G` into `G`. -/ @[simps] protected def hom (x : Subgraph G) : x.coe →g G where toFun v := v map_rel' := x.adj_sub #align simple_graph.subgraph.hom SimpleGraph.Subgraph.hom theorem hom.injective {x : Subgraph G} : Function.Injective x.hom := fun _ _ ↦ Subtype.ext #align simple_graph.subgraph.hom.injective SimpleGraph.Subgraph.hom.injective /-- There is an induced injective homomorphism of a subgraph of `G` as a spanning subgraph into `G`. -/ @[simps] def spanningHom (x : Subgraph G) : x.spanningCoe →g G where toFun := id map_rel' := x.adj_sub #align simple_graph.subgraph.spanning_hom SimpleGraph.Subgraph.spanningHom theorem spanningHom.injective {x : Subgraph G} : Function.Injective x.spanningHom := fun _ _ ↦ id #align simple_graph.subgraph.spanning_hom.injective SimpleGraph.Subgraph.spanningHom.injective theorem neighborSet_subset_of_subgraph {x y : Subgraph G} (h : x ≤ y) (v : V) : x.neighborSet v ⊆ y.neighborSet v := fun _ h' ↦ h.2 h' #align simple_graph.subgraph.neighbor_set_subset_of_subgraph SimpleGraph.Subgraph.neighborSet_subset_of_subgraph instance neighborSet.decidablePred (G' : Subgraph G) [h : DecidableRel G'.Adj] (v : V) : DecidablePred (· ∈ G'.neighborSet v) := h v #align simple_graph.subgraph.neighbor_set.decidable_pred SimpleGraph.Subgraph.neighborSet.decidablePred /-- If a graph is locally finite at a vertex, then so is a subgraph of that graph. -/ instance finiteAt {G' : Subgraph G} (v : G'.verts) [DecidableRel G'.Adj] [Fintype (G.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset (G.neighborSet v) (G'.neighborSet_subset v) #align simple_graph.subgraph.finite_at SimpleGraph.Subgraph.finiteAt /-- If a subgraph is locally finite at a vertex, then so are subgraphs of that subgraph. This is not an instance because `G''` cannot be inferred. -/ def finiteAtOfSubgraph {G' G'' : Subgraph G} [DecidableRel G'.Adj] (h : G' ≤ G'') (v : G'.verts) [Fintype (G''.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset (G''.neighborSet v) (neighborSet_subset_of_subgraph h v) #align simple_graph.subgraph.finite_at_of_subgraph SimpleGraph.Subgraph.finiteAtOfSubgraph instance (G' : Subgraph G) [Fintype G'.verts] (v : V) [DecidablePred (· ∈ G'.neighborSet v)] : Fintype (G'.neighborSet v) := Set.fintypeSubset G'.verts (neighborSet_subset_verts G' v) instance coeFiniteAt {G' : Subgraph G} (v : G'.verts) [Fintype (G'.neighborSet v)] : Fintype (G'.coe.neighborSet v) := Fintype.ofEquiv _ (coeNeighborSetEquiv v).symm #align simple_graph.subgraph.coe_finite_at SimpleGraph.Subgraph.coeFiniteAt theorem IsSpanning.card_verts [Fintype V] {G' : Subgraph G} [Fintype G'.verts] (h : G'.IsSpanning) : G'.verts.toFinset.card = Fintype.card V := by simp only [isSpanning_iff.1 h, Set.toFinset_univ] congr #align simple_graph.subgraph.is_spanning.card_verts SimpleGraph.Subgraph.IsSpanning.card_verts /-- The degree of a vertex in a subgraph. It's zero for vertices outside the subgraph. -/ def degree (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)] : ℕ := Fintype.card (G'.neighborSet v) #align simple_graph.subgraph.degree SimpleGraph.Subgraph.degree theorem finset_card_neighborSet_eq_degree {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] : (G'.neighborSet v).toFinset.card = G'.degree v := by rw [degree, Set.toFinset_card] #align simple_graph.subgraph.finset_card_neighbor_set_eq_degree SimpleGraph.Subgraph.finset_card_neighborSet_eq_degree theorem degree_le (G' : Subgraph G) (v : V) [Fintype (G'.neighborSet v)] [Fintype (G.neighborSet v)] : G'.degree v ≤ G.degree v := by rw [← card_neighborSet_eq_degree] exact Set.card_le_of_subset (G'.neighborSet_subset v) #align simple_graph.subgraph.degree_le SimpleGraph.Subgraph.degree_le theorem degree_le' (G' G'' : Subgraph G) (h : G' ≤ G'') (v : V) [Fintype (G'.neighborSet v)] [Fintype (G''.neighborSet v)] : G'.degree v ≤ G''.degree v := Set.card_le_of_subset (neighborSet_subset_of_subgraph h v) #align simple_graph.subgraph.degree_le' SimpleGraph.Subgraph.degree_le' @[simp] theorem coe_degree (G' : Subgraph G) (v : G'.verts) [Fintype (G'.coe.neighborSet v)] [Fintype (G'.neighborSet v)] : G'.coe.degree v = G'.degree v := by rw [← card_neighborSet_eq_degree] exact Fintype.card_congr (coeNeighborSetEquiv v) #align simple_graph.subgraph.coe_degree SimpleGraph.Subgraph.coe_degree @[simp] theorem degree_spanningCoe {G' : G.Subgraph} (v : V) [Fintype (G'.neighborSet v)] [Fintype (G'.spanningCoe.neighborSet v)] : G'.spanningCoe.degree v = G'.degree v := by rw [← card_neighborSet_eq_degree, Subgraph.degree] congr! #align simple_graph.subgraph.degree_spanning_coe SimpleGraph.Subgraph.degree_spanningCoe theorem degree_eq_one_iff_unique_adj {G' : Subgraph G} {v : V} [Fintype (G'.neighborSet v)] : G'.degree v = 1 ↔ ∃! w : V, G'.Adj v w := by rw [← finset_card_neighborSet_eq_degree, Finset.card_eq_one, Finset.singleton_iff_unique_mem] simp only [Set.mem_toFinset, mem_neighborSet] #align simple_graph.subgraph.degree_eq_one_iff_unique_adj SimpleGraph.Subgraph.degree_eq_one_iff_unique_adj end Subgraph section MkProperties /-! ### Properties of `singletonSubgraph` and `subgraphOfAdj` -/ variable {G : SimpleGraph V} {G' : SimpleGraph W} instance nonempty_singletonSubgraph_verts (v : V) : Nonempty (G.singletonSubgraph v).verts := ⟨⟨v, Set.mem_singleton v⟩⟩ #align simple_graph.nonempty_singleton_subgraph_verts SimpleGraph.nonempty_singletonSubgraph_verts @[simp] theorem singletonSubgraph_le_iff (v : V) (H : G.Subgraph) : G.singletonSubgraph v ≤ H ↔ v ∈ H.verts := by refine' ⟨fun h ↦ h.1 (Set.mem_singleton v), _⟩ intro h constructor · rwa [singletonSubgraph_verts, Set.singleton_subset_iff] · exact fun _ _ ↦ False.elim #align simple_graph.singleton_subgraph_le_iff SimpleGraph.singletonSubgraph_le_iff @[simp] theorem map_singletonSubgraph (f : G →g G') {v : V} : Subgraph.map f (G.singletonSubgraph v) = G'.singletonSubgraph (f v) := by ext <;> simp only [Relation.Map, Subgraph.map_Adj, singletonSubgraph_Adj, Pi.bot_apply, exists_and_left, and_iff_left_iff_imp, IsEmpty.forall_iff, Subgraph.map_verts, singletonSubgraph_verts, Set.image_singleton] exact False.elim #align simple_graph.map_singleton_subgraph SimpleGraph.map_singletonSubgraph @[simp] theorem neighborSet_singletonSubgraph (v w : V) : (G.singletonSubgraph v).neighborSet w = ∅ := rfl #align simple_graph.neighbor_set_singleton_subgraph SimpleGraph.neighborSet_singletonSubgraph @[simp] theorem edgeSet_singletonSubgraph (v : V) : (G.singletonSubgraph v).edgeSet = ∅ := Sym2.fromRel_bot #align simple_graph.edge_set_singleton_subgraph SimpleGraph.edgeSet_singletonSubgraph theorem eq_singletonSubgraph_iff_verts_eq (H : G.Subgraph) {v : V} : H = G.singletonSubgraph v ↔ H.verts = {v} := by refine' ⟨fun h ↦ by rw [h, singletonSubgraph_verts], fun h ↦ _⟩ ext · rw [h, singletonSubgraph_verts] · simp only [Prop.bot_eq_false, singletonSubgraph_Adj, Pi.bot_apply, iff_false_iff] intro ha have ha1 := ha.fst_mem have ha2 := ha.snd_mem rw [h, Set.mem_singleton_iff] at ha1 ha2 subst_vars exact ha.ne rfl #align simple_graph.eq_singleton_subgraph_iff_verts_eq SimpleGraph.eq_singletonSubgraph_iff_verts_eq instance nonempty_subgraphOfAdj_verts {v w : V} (hvw : G.Adj v w) : Nonempty (G.subgraphOfAdj hvw).verts := ⟨⟨v, by simp⟩⟩ #align simple_graph.nonempty_subgraph_of_adj_verts SimpleGraph.nonempty_subgraphOfAdj_verts @[simp] theorem edgeSet_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).edgeSet = {⟦(v, w)⟧} := by ext e refine' e.ind _ simp only [eq_comm, Set.mem_singleton_iff, Subgraph.mem_edgeSet, subgraphOfAdj_Adj, iff_self_iff, forall₂_true_iff] #align simple_graph.edge_set_subgraph_of_adj SimpleGraph.edgeSet_subgraphOfAdj theorem subgraphOfAdj_symm {v w : V} (hvw : G.Adj v w) : G.subgraphOfAdj hvw.symm = G.subgraphOfAdj hvw := by ext <;> simp [or_comm, and_comm] #align simple_graph.subgraph_of_adj_symm SimpleGraph.subgraphOfAdj_symm @[simp] theorem map_subgraphOfAdj (f : G →g G') {v w : V} (hvw : G.Adj v w) : Subgraph.map f (G.subgraphOfAdj hvw) = G'.subgraphOfAdj (f.map_adj hvw) := by ext · simp only [Subgraph.map_verts, subgraphOfAdj_verts, Set.mem_image, Set.mem_insert_iff, Set.mem_singleton_iff] constructor · rintro ⟨u, rfl | rfl, rfl⟩ <;> simp · rintro (rfl | rfl) · use v simp · use w simp · simp only [Relation.Map, Subgraph.map_Adj, subgraphOfAdj_Adj, Quotient.eq, Sym2.rel_iff] constructor · rintro ⟨a, b, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl, rfl⟩ <;> simp · rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) · use v, w simp · use w, v simp #align simple_graph.map_subgraph_of_adj SimpleGraph.map_subgraphOfAdj theorem neighborSet_subgraphOfAdj_subset {u v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet u ⊆ {v, w} := (G.subgraphOfAdj hvw).neighborSet_subset_verts _ #align simple_graph.neighbor_set_subgraph_of_adj_subset SimpleGraph.neighborSet_subgraphOfAdj_subset @[simp] theorem neighborSet_fst_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet v = {w} := by ext u suffices w = u ↔ u = w by simpa [hvw.ne.symm] using this rw [eq_comm] #align simple_graph.neighbor_set_fst_subgraph_of_adj SimpleGraph.neighborSet_fst_subgraphOfAdj @[simp] theorem neighborSet_snd_subgraphOfAdj {v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet w = {v} := by rw [subgraphOfAdj_symm hvw.symm] exact neighborSet_fst_subgraphOfAdj hvw.symm #align simple_graph.neighbor_set_snd_subgraph_of_adj SimpleGraph.neighborSet_snd_subgraphOfAdj @[simp] theorem neighborSet_subgraphOfAdj_of_ne_of_ne {u v w : V} (hvw : G.Adj v w) (hv : u ≠ v) (hw : u ≠ w) : (G.subgraphOfAdj hvw).neighborSet u = ∅ := by ext simp [hv.symm, hw.symm] #align simple_graph.neighbor_set_subgraph_of_adj_of_ne_of_ne SimpleGraph.neighborSet_subgraphOfAdj_of_ne_of_ne theorem neighborSet_subgraphOfAdj [DecidableEq V] {u v w : V} (hvw : G.Adj v w) : (G.subgraphOfAdj hvw).neighborSet u = (if u = v then {w} else ∅) ∪ if u = w then {v} else ∅ := by split_ifs <;> subst_vars <;> simp [*] #align simple_graph.neighbor_set_subgraph_of_adj SimpleGraph.neighborSet_subgraphOfAdj theorem singletonSubgraph_fst_le_subgraphOfAdj {u v : V} {h : G.Adj u v} : G.singletonSubgraph u ≤ G.subgraphOfAdj h := by constructor <;> simp [-Set.bot_eq_empty] exact fun _ _ ↦ False.elim #align simple_graph.singleton_subgraph_fst_le_subgraph_of_adj SimpleGraph.singletonSubgraph_fst_le_subgraphOfAdj theorem singletonSubgraph_snd_le_subgraphOfAdj {u v : V} {h : G.Adj u v} : G.singletonSubgraph v ≤ G.subgraphOfAdj h := by constructor <;> simp [-Set.bot_eq_empty] exact fun _ _ ↦ False.elim #align simple_graph.singleton_subgraph_snd_le_subgraph_of_adj SimpleGraph.singletonSubgraph_snd_le_subgraphOfAdj end MkProperties namespace Subgraph variable {G : SimpleGraph V} /-! ### Subgraphs of subgraphs -/ /-- Given a subgraph of a subgraph of `G`, construct a subgraph of `G`. -/ @[reducible] protected def coeSubgraph {G' : G.Subgraph} : G'.coe.Subgraph → G.Subgraph := Subgraph.map G'.hom #align simple_graph.subgraph.coe_subgraph SimpleGraph.Subgraph.coeSubgraph /-- Given a subgraph of `G`, restrict it to being a subgraph of another subgraph `G'` by taking the portion of `G` that intersects `G'`. -/ @[reducible] protected def restrict {G' : G.Subgraph} : G.Subgraph → G'.coe.Subgraph := Subgraph.comap G'.hom #align simple_graph.subgraph.restrict SimpleGraph.Subgraph.restrict theorem restrict_coeSubgraph {G' : G.Subgraph} (G'' : G'.coe.Subgraph) : Subgraph.restrict (Subgraph.coeSubgraph G'') = G'' := by ext · simp · simp only [Relation.Map, comap_Adj, coe_Adj, Subtype.coe_prop, hom_apply, map_Adj, SetCoe.exists, Subtype.coe_mk, exists_and_right, exists_eq_right_right, Subtype.coe_eta, exists_true_left, exists_eq_right, and_iff_right_iff_imp] apply G''.adj_sub #align simple_graph.subgraph.restrict_coe_subgraph SimpleGraph.Subgraph.restrict_coeSubgraph theorem coeSubgraph_injective (G' : G.Subgraph) : Function.Injective (Subgraph.coeSubgraph : G'.coe.Subgraph → G.Subgraph) := Function.LeftInverse.injective restrict_coeSubgraph #align simple_graph.subgraph.coe_subgraph_injective SimpleGraph.Subgraph.coeSubgraph_injective /-! ### Edge deletion -/ /-- Given a subgraph `G'` and a set of vertex pairs, remove all of the corresponding edges from its edge set, if present. See also: `SimpleGraph.deleteEdges`. -/ def deleteEdges (G' : G.Subgraph) (s : Set (Sym2 V)) : G.Subgraph where verts := G'.verts Adj := G'.Adj \ Sym2.ToRel s adj_sub h' := G'.adj_sub h'.1 edge_vert h' := G'.edge_vert h'.1 symm a b := by simp [G'.adj_comm, Sym2.eq_swap] #align simple_graph.subgraph.delete_edges SimpleGraph.Subgraph.deleteEdges section DeleteEdges variable {G' : G.Subgraph} (s : Set (Sym2 V)) @[simp] theorem deleteEdges_verts : (G'.deleteEdges s).verts = G'.verts := rfl #align simple_graph.subgraph.delete_edges_verts SimpleGraph.Subgraph.deleteEdges_verts @[simp] theorem deleteEdges_adj (v w : V) : (G'.deleteEdges s).Adj v w ↔ G'.Adj v w ∧ ¬⟦(v, w)⟧ ∈ s := Iff.rfl #align simple_graph.subgraph.delete_edges_adj SimpleGraph.Subgraph.deleteEdges_adj @[simp] theorem deleteEdges_deleteEdges (s s' : Set (Sym2 V)) : (G'.deleteEdges s).deleteEdges s' = G'.deleteEdges (s ∪ s') := by ext <;> simp [and_assoc, not_or] #align simple_graph.subgraph.delete_edges_delete_edges SimpleGraph.Subgraph.deleteEdges_deleteEdges @[simp] theorem deleteEdges_empty_eq : G'.deleteEdges ∅ = G' := by ext <;> simp #align simple_graph.subgraph.delete_edges_empty_eq SimpleGraph.Subgraph.deleteEdges_empty_eq @[simp] theorem deleteEdges_spanningCoe_eq : G'.spanningCoe.deleteEdges s = (G'.deleteEdges s).spanningCoe := by ext simp #align simple_graph.subgraph.delete_edges_spanning_coe_eq SimpleGraph.Subgraph.deleteEdges_spanningCoe_eq theorem deleteEdges_coe_eq (s : Set (Sym2 G'.verts)) : G'.coe.deleteEdges s = (G'.deleteEdges (Sym2.map (↑) '' s)).coe := by ext ⟨v, hv⟩ ⟨w, hw⟩ simp only [SimpleGraph.deleteEdges_adj, coe_Adj, deleteEdges_adj, Set.mem_image, not_exists, not_and, and_congr_right_iff] intro constructor · intro hs refine' Sym2.ind _ rintro ⟨v', hv'⟩ ⟨w', hw'⟩ simp only [Sym2.map_pair_eq, Quotient.eq] contrapose! rintro (_ | _) <;> simpa only [Sym2.eq_swap] · intro h' hs exact h' _ hs rfl #align simple_graph.subgraph.delete_edges_coe_eq SimpleGraph.Subgraph.deleteEdges_coe_eq theorem coe_deleteEdges_eq (s : Set (Sym2 V)) : (G'.deleteEdges s).coe = G'.coe.deleteEdges (Sym2.map (↑) ⁻¹' s) := by ext ⟨v, hv⟩ ⟨w, hw⟩ simp #align simple_graph.subgraph.coe_delete_edges_eq SimpleGraph.Subgraph.coe_deleteEdges_eq theorem deleteEdges_le : G'.deleteEdges s ≤ G' := by constructor <;> simp (config := { contextual := true }) [subset_rfl] #align simple_graph.subgraph.delete_edges_le SimpleGraph.Subgraph.deleteEdges_le theorem deleteEdges_le_of_le {s s' : Set (Sym2 V)} (h : s ⊆ s') : G'.deleteEdges s' ≤ G'.deleteEdges s := by constructor <;> simp (config := { contextual := true }) only [deleteEdges_verts, deleteEdges_adj, true_and_iff, and_imp, subset_rfl] exact fun _ _ _ hs' hs ↦ hs' (h hs) #align simple_graph.subgraph.delete_edges_le_of_le SimpleGraph.Subgraph.deleteEdges_le_of_le @[simp] theorem deleteEdges_inter_edgeSet_left_eq : G'.deleteEdges (G'.edgeSet ∩ s) = G'.deleteEdges s := by ext <;> simp (config := { contextual := true }) [imp_false] #align simple_graph.subgraph.delete_edges_inter_edge_set_left_eq SimpleGraph.Subgraph.deleteEdges_inter_edgeSet_left_eq @[simp] theorem deleteEdges_inter_edgeSet_right_eq : G'.deleteEdges (s ∩ G'.edgeSet) = G'.deleteEdges s := by ext <;> simp (config := { contextual := true }) [imp_false] #align simple_graph.subgraph.delete_edges_inter_edge_set_right_eq SimpleGraph.Subgraph.deleteEdges_inter_edgeSet_right_eq theorem coe_deleteEdges_le : (G'.deleteEdges s).coe ≤ (G'.coe : SimpleGraph G'.verts) := by intro v w simp (config := { contextual := true }) #align simple_graph.subgraph.coe_delete_edges_le SimpleGraph.Subgraph.coe_deleteEdges_le theorem spanningCoe_deleteEdges_le (G' : G.Subgraph) (s : Set (Sym2 V)) : (G'.deleteEdges s).spanningCoe ≤ G'.spanningCoe := spanningCoe_le_of_le (deleteEdges_le s) #align simple_graph.subgraph.spanning_coe_delete_edges_le SimpleGraph.Subgraph.spanningCoe_deleteEdges_le end DeleteEdges /-! ### Induced subgraphs -/ /- Given a subgraph, we can change its vertex set while removing any invalid edges, which gives induced subgraphs. See also `SimpleGraph.induce` for the `SimpleGraph` version, which, unlike for subgraphs, results in a graph with a different vertex type. -/ /-- The induced subgraph of a subgraph. The expectation is that `s ⊆ G'.verts` for the usual notion of an induced subgraph, but, in general, `s` is taken to be the new vertex set and edges are induced from the subgraph `G'`. -/ @[simps] def induce (G' : G.Subgraph) (s : Set V) : G.Subgraph where verts := s Adj u v := u ∈ s ∧ v ∈ s ∧ G'.Adj u v adj_sub h := G'.adj_sub h.2.2 edge_vert h := h.1 symm _ _ h := ⟨h.2.1, h.1, G'.symm h.2.2⟩ #align simple_graph.subgraph.induce SimpleGraph.Subgraph.induce theorem _root_.SimpleGraph.induce_eq_coe_induce_top (s : Set V) : G.induce s = ((⊤ : G.Subgraph).induce s).coe := by ext simp #align simple_graph.induce_eq_coe_induce_top SimpleGraph.induce_eq_coe_induce_top section Induce variable {G' G'' : G.Subgraph} {s s' : Set V} theorem induce_mono (hg : G' ≤ G'') (hs : s ⊆ s') : G'.induce s ≤ G''.induce s' := by constructor · simp [hs] · simp (config := { contextual := true }) only [induce_Adj, true_and_iff, and_imp] intro v w hv hw ha exact ⟨hs hv, hs hw, hg.2 ha⟩ #align simple_graph.subgraph.induce_mono SimpleGraph.Subgraph.induce_mono @[mono] theorem induce_mono_left (hg : G' ≤ G'') : G'.induce s ≤ G''.induce s := induce_mono hg subset_rfl #align simple_graph.subgraph.induce_mono_left SimpleGraph.Subgraph.induce_mono_left @[mono] theorem induce_mono_right (hs : s ⊆ s') : G'.induce s ≤ G'.induce s' := induce_mono le_rfl hs #align simple_graph.subgraph.induce_mono_right SimpleGraph.Subgraph.induce_mono_right @[simp] theorem induce_empty : G'.induce ∅ = ⊥ := by ext <;> simp #align simple_graph.subgraph.induce_empty SimpleGraph.Subgraph.induce_empty @[simp] theorem induce_self_verts : G'.induce G'.verts = G' := by ext · simp · constructor <;> simp (config := { contextual := true }) only [induce_Adj, imp_true_iff, and_true_iff] exact fun ha ↦ ⟨G'.edge_vert ha, G'.edge_vert ha.symm⟩ #align simple_graph.subgraph.induce_self_verts SimpleGraph.Subgraph.induce_self_verts theorem singletonSubgraph_eq_induce {v : V} : G.singletonSubgraph v = (⊤ : G.Subgraph).induce {v} := by ext <;> simp (config := { contextual := true }) [-Set.bot_eq_empty, Prop.bot_eq_false] #align simple_graph.subgraph.singleton_subgraph_eq_induce SimpleGraph.Subgraph.singletonSubgraph_eq_induce theorem subgraphOfAdj_eq_induce {v w : V} (hvw : G.Adj v w) : G.subgraphOfAdj hvw = (⊤ : G.Subgraph).induce {v, w} := by ext · simp · constructor · intro h simp only [subgraphOfAdj_Adj, Quotient.eq, Sym2.rel_iff] at h obtain ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ := h <;> simp [hvw, hvw.symm] · intro h simp only [induce_Adj, Set.mem_insert_iff, Set.mem_singleton_iff, top_adj] at h obtain ⟨rfl | rfl, rfl | rfl, ha⟩ := h <;> first |exact (ha.ne rfl).elim|simp #align simple_graph.subgraph.subgraph_of_adj_eq_induce SimpleGraph.Subgraph.subgraphOfAdj_eq_induce end Induce /-- Given a subgraph and a set of vertices, delete all the vertices from the subgraph, if present. Any edges indicent to the deleted vertices are deleted as well. -/ @[reducible] def deleteVerts (G' : G.Subgraph) (s : Set V) : G.Subgraph := G'.induce (G'.verts \ s) #align simple_graph.subgraph.delete_verts SimpleGraph.Subgraph.deleteVerts section DeleteVerts variable {G' : G.Subgraph} {s : Set V} theorem deleteVerts_verts : (G'.deleteVerts s).verts = G'.verts \ s := rfl #align simple_graph.subgraph.delete_verts_verts SimpleGraph.Subgraph.deleteVerts_verts theorem deleteVerts_adj {u v : V} : (G'.deleteVerts s).Adj u v ↔ u ∈ G'.verts ∧ ¬u ∈ s ∧ v ∈ G'.verts ∧ ¬v ∈ s ∧ G'.Adj u v := by simp [and_assoc] #align simple_graph.subgraph.delete_verts_adj SimpleGraph.Subgraph.deleteVerts_adj @[simp] theorem deleteVerts_deleteVerts (s s' : Set V) : (G'.deleteVerts s).deleteVerts s' = G'.deleteVerts (s ∪ s') := by ext <;> simp (config := { contextual := true }) [not_or, and_assoc] #align simple_graph.subgraph.delete_verts_delete_verts SimpleGraph.Subgraph.deleteVerts_deleteVerts @[simp] theorem deleteVerts_empty : G'.deleteVerts ∅ = G' := by simp [deleteVerts] #align simple_graph.subgraph.delete_verts_empty SimpleGraph.Subgraph.deleteVerts_empty theorem deleteVerts_le : G'.deleteVerts s ≤ G' := by constructor <;> simp [Set.diff_subset] #align simple_graph.subgraph.delete_verts_le SimpleGraph.Subgraph.deleteVerts_le @[mono] theorem deleteVerts_mono {G' G'' : G.Subgraph} (h : G' ≤ G'') : G'.deleteVerts s ≤ G''.deleteVerts s := induce_mono h (Set.diff_subset_diff_left h.1) #align simple_graph.subgraph.delete_verts_mono SimpleGraph.Subgraph.deleteVerts_mono @[mono] theorem deleteVerts_anti {s s' : Set V} (h : s ⊆ s') : G'.deleteVerts s' ≤ G'.deleteVerts s := induce_mono (le_refl _) (Set.diff_subset_diff_right h) #align simple_graph.subgraph.delete_verts_anti SimpleGraph.Subgraph.deleteVerts_anti @[simp] theorem deleteVerts_inter_verts_left_eq : G'.deleteVerts (G'.verts ∩ s) = G'.deleteVerts s := by ext <;> simp (config := { contextual := true }) [imp_false] #align simple_graph.subgraph.delete_verts_inter_verts_left_eq SimpleGraph.Subgraph.deleteVerts_inter_verts_left_eq @[simp] theorem deleteVerts_inter_verts_set_right_eq : G'.deleteVerts (s ∩ G'.verts) = G'.deleteVerts s := by ext <;> simp (config := { contextual := true }) [imp_false] #align simple_graph.subgraph.delete_verts_inter_verts_set_right_eq SimpleGraph.Subgraph.deleteVerts_inter_verts_set_right_eq end DeleteVerts end Subgraph end SimpleGraph
#' This Script rprocesses Eurostat SES data #' #' #' #' @param work_directory inside the DATA repo #' @param check for automation, return a warning file at the root, default is TRUE #' @return csv files compare with ilostat database ilo::init_ilo() ## parameters work_directory = "REP_EUROSTAT/SES_ANNUAL" require(ilo) ## Initialize setwd(paste0(ilo:::path$data, work_directory)) source(paste0(getwd(),"/do/REP_EUROSTAT.SES_ANNUAL_functions.r")) REP_EUROSTAT.SES_ANNUAL.earn_mw_cur.EAR_INEE_NOC_NB() REP_EUROSTAT.SES_ANNUAL.lc_lci_lev.LAC_XEES_ECO_NB() REP_EUROSTAT.SES_ANNUAL.lc_an_costh.LAC_XEES_ECO_NB2() #no gender gap for the moment (by economic activity) #REP_EUROSTAT.SES_ANNUAL.earn_gr_gpgr2.EAR_GGAP_ECO_RT() REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_14.EAR_HEES_SEX_OCU_NB() REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_20.EAR_XEES_SEX_ECO_NB() REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_21.EAR_XEES_SEX_OCU_NB() #REP_EUROSTAT.SES_ANNUAL.earn_ses_pub1s.EAR_XTLP_SEX_RT() # Collect all the data in one set V <- as.vector(list.files("./input") ) V <- V [ V %>% str_detect("Output")] load(file = paste0('input/empty','.Rdata')) Y <- empty for (v in V) { #Y <- gtools::smartbind(Y,read.csv( paste0(getwd(),"/input/",v) ) ) Y <- rbind(Y,read.csv( paste0(getwd(),"/input/",v) ) ) } Y <- Y %>% mutate( freq_code="m" ) %>% as.tbl()%>% mutate_all(funs(as.character)) %>% mutate(obs_value = as.numeric(obs_value)) for (i in unique(Y$ref_area) ){ invisible(gc(reset = TRUE)) X <- Y %>% filter(ref_area %in% i ) save(X,file = paste("./output/REP_EUROSTAT_",i,".Rdata",sep="")) print(i) } LOAD <- cbind(PATH = paste0(getwd(), "/output/REP_EUROSTAT_",unique(Y$ref_area),".Rdata"),ID = NA, Types ="EUROSTAT_ilostat", REF = unique(Y$ref_area)) write.csv(LOAD,"./FileToLoad.csv",row.names = FALSE,na="") ################# **************************************************************************************** ################# **************************************************************************************** ################# **************************************************************************************** ################# **************************************************************************************** ################# **************************************************************************************** ################# **************************************************************************************** ################# **************************************************************************************** #### Archive of functions, for the function script #### There is a need to establish the way it will work the upload to YI ilo::init_ilo() ## parameters work_directory = "REP_EUROSTAT/SES_ANNUAL" ## Initialize setwd(paste0(ilo:::path$data, work_directory)) #### Archive of functions, for the function script #### There is a need to establish the way it will work the upload to YI # 1 - Done REP_EUROSTAT.SES_ANNUAL.earn_mw_cur.EAR_INEE_NOC_NB <- function (check = TRUE) { ############## Minimum wage EAR_INEE_NOC_NB rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data ## Get Input #Input <- eurostat:::get_eurostat('earn_mw_cur', time_format = 'raw', keepFlags = TRUE, cache = FALSE) #saveRDS(Input, paste0('./input/Input.EAR_INEE_NOC_NB.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_INEE_NOC_NB.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='EAR_INEE_NOC_NB') -> GrossTarget # saveRDS(GrossTarget , file = './input/EAR_INEE_NOC_NB.GrossTarget.RDS') GrossTarget <- readRDS(paste0('./input/EAR_INEE_NOC_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## Source Map Source.Map <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) %>% filter( !(source %in% c("DA:670","FX:507"))) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = NA_character_, classif1 = "NOC_VALUE", classif2 = NA_character_, note_classif = NA_character_, indicator = "EAR_INEE_NOC_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E"), obs_status = as.character(obs_status) ) %>% ## filtering - Second Semester, remove Purchasing Power Standard filter( !is.na(obs_value) ) %>% filter( str_detect(time,"S2") ) %>% #formating to obtain year now that is unique mutate(time = str_sub(time,1,-3)) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Exception to add new Lithuanian currency (euro) mutate( note_indicator = if_else(ref_area=="LTU", "T30:377" , note_indicator) ) %>% # note_source, repository ILOSTAT and July as reference period #institutional sector is total in general, see the stored readme in the help folder mutate(note_source = "R1:2383_R1:3903_S3:18") %>% mutate( note_source = if_else(ref_area %in% c("BEL", "GRC"),"R1:2383_R1:3903_S3:18_S7:57" ,note_source ) ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source = "NEED SOURCE!!!") ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="MKD", "FX:13348" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="MNE", "FX:13349" ,source) ) # Check against target Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time>1998) write.csv(Output, file = './input/Output.EAR_INEE_NOC_NB.csv', row.names=FALSE, na="") } # 2 - Done (Note the data are actually from LCS_ANNUAL, but due to the closeness to the rest of the extract and mapping the function is in the SES_ANNUAL project) REP_EUROSTAT.SES_ANNUAL.lc_lci_lev.LAC_XEES_ECO_NB <- function (check = TRUE) { #LAC_XEES_ECO_NB lc_lci_lev Labour cost levels by NACE Rev. 2 activity (lc_lci_lev) rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data # Input <- eurostat:::get_eurostat('lc_lci_lev', time_format = 'raw', keepFlags = TRUE, cache = FALSE) # saveRDS(Input, paste0('./input/Input.LAC_XEES_ECO_NB.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.LAC_XEES_ECO_NB.RDS')) ## Other data ##### this should never be run again: get_ilo(indicator='LAC_XEES_ECO_NB') -> GrossTarget # saveRDS(GrossTarget , file = './input/LAC_XEES_ECO_NB.GrossTarget.RDS') GrossTarget <- readRDS(paste0('./input/LAC_XEES_ECO_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## ECO map Sector.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC4_[:alpha:]$")) %>% mutate(nace_r2 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r2) ## Source Map Source.Map <- GrossTarget %>% filter(time>1998) %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) %>% filter( !(source %in% c("DA:721","DA:428"))) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = NA_character_, classif2 = NA_character_, note_classif = NA_character_, indicator = "LAC_XEES_ECO_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P"), obs_status = as.character(obs_status) ) %>% ## filtering - notice we only want total labour cost filter( lcstruct == "D" ) %>% select( -lcstruct ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Exception to add new Lithuanian currency (euro) mutate( note_indicator = if_else(ref_area=="LTU", "T30:377" , note_indicator) ) %>% # classif1, the mapping is required, also note that sectors are excluded left_join( Sector.Map , by = c("nace_r2") ) %>% mutate( classif1 = if_else(nace_r2=="B-S_X_O", "ECO_ISIC4_TOTAL",classif1) ) %>% mutate( note_source ="R1:2383_R1:3903_S6:48_S8:2566" ) %>% filter( !is.na(classif1) ) %>% select( -nace_r2) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") )%>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="GRC", "DA:13351" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="LTU", "DA:13352" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="NOR", "DA:13350" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="SWE", "DA:13353" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="TUR", "DA:13354" ,source) ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time>1998) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "classif1")) #All manually checked, largest issues are: #revisions, non-standard units reference year or other in Target data ##RECOMENDATION, migrate to the sytem since 2012 Output <- Output %>% filter(time>2011) write.csv(Output, file = './input/Output.LAC_XEES_ECO_NB.csv', row.names=FALSE, na="") } # 3 - Done (Note the data are actually from LCS_ANNUAL, but due to the closeness to the rest of the extract and mapping the function is in the SES_ANNUAL project) REP_EUROSTAT.SES_ANNUAL.lc_an_costh.LAC_XEES_ECO_NB2 <- function (check = TRUE) { #LAC_XEES_ECO_NB lc_an_costh Hourly labour costs by NACE Rev. 1.1 activity rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data # Input <- eurostat:::get_eurostat('lc_an_costh', time_format = 'raw', keepFlags = TRUE, cache = FALSE) # saveRDS(Input, paste0('./input/Input.LAC_XEES_ECO_NB2.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.LAC_XEES_ECO_NB2.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='LAC_XEES_ECO_NB') -> GrossTarget GrossTarget <- readRDS(paste0('./input/LAC_XEES_ECO_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## ECO map Sector.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC3_[:alpha:]$")) %>% mutate(nace_r1 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r1) ## Source Map Source.Map <- GrossTarget %>% filter(time>1998) %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) %>% filter( !(source %in% c("DA:721","DA:428"))) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = NA_character_, classif2 = NA_character_, note_classif = NA_character_, indicator = "LAC_XEES_ECO_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", b="B"), obs_status = as.character(obs_status) ) %>% # obs_status, not indicated as usual, some metadata comments that have to be manually introduced mutate( obs_status = if_else(ref_area=="ESP" & time=="2001","B",obs_status), obs_status = if_else(ref_area=="DNK" & time=="2000","B",obs_status) ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Exception to add new Lithuanian currency (euro) mutate( note_indicator = if_else(ref_area=="LTU", "T30:377" , note_indicator) ) %>% # classif1, the mapping is required, also note that sectors are excluded left_join( Sector.Map , by = c("nace_r1") ) %>% mutate( classif1 = if_else(nace_r1=="C-O", "ECO_ISIC3_TOTAL",classif1) ) %>% mutate( note_source ="R1:2383_R1:3903_S8:3907_S8:1619" ) %>% filter( !is.na(classif1) ) %>% select( -nace_r1) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="GRC", "DA:13351" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="LTU", "DA:13352" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="NOR", "DA:13350" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="SWE", "DA:13353" ,source) ) %>% mutate( source = if_else(source == "NEED SOURCE!!!" & ref_area=="TUR", "DA:13354" ,source) ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time>1998) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "classif1")) #All manually checked, largest issues are: #revisions, non-standard units reference year or other in Target data ##RECOMENDATION, migrate overwriting the few existing data points (Manually checked, only one country affected very small differences) write.csv(Output, file = './input/Output.LAC_XEES_ECO_NB2.csv', row.names=FALSE, na="") } # 4 - Done REP_EUROSTAT.SES_ANNUAL.earn_gr_gpgr2.EAR_GGAP_ECO_RT <- function (check = TRUE) { #EAR_GGAP_ECO_RT Unadjusted gender wage gap by NACE Rev. 2 activity (earn_gr_gpgr2) rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data # Input <- eurostat:::get_eurostat('earn_gr_gpgr2', time_format = 'raw', keepFlags = TRUE, cache = FALSE) # saveRDS(Input, paste0('./input/Input.EAR_GGAP_ECO_RT.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_GGAP_ECO_RT.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) ## ECO map Sector.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC4_[:alpha:]$")) %>% mutate(nace_r2 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r2) ## Source Map library(readxl) Source.Map <- read_excel("J:/DPAU/DATA/REP_EUROSTAT/SES_ANNUAL/input/SES_Surveys.xlsx") %>% rbind(c("HRV","DA:562") ) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = NA_character_, classif2 = NA_character_, note_classif = NA_character_, note_indicator = NA_character_, indicator = "EAR_GGAP_ECO_RT", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", s = "E", i = NA_character_, d = NA_character_ ), obs_status = as.character(obs_status) ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort # classif1, the mapping is required, also note that sectors are excluded left_join( Sector.Map , by = c("nace_r2") ) %>% mutate( classif1 = if_else(nace_r2=="B-S_X_O", "ECO_ISIC4_TOTAL",classif1) ) %>% mutate( note_source ="R1:2383_R1:3903_S6:48_S8:2566" ) %>% filter( !is.na(classif1) ) %>% select( -nace_r2) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") ) %>% select(-unit) %>% # Final element, processing the obs_status (d) "definition differs" For Romania nothing is specifed in the metadata, but given the temporal profile a # break is introduced, for Switzerland T34:2128 _NOTE_EXCLUDING_APPRENTICES the obs_status d means "Overtime pay is not included in average hourly earnings for 2012 and 2013.The following main groups are not included: apprentices. mutate( obs_status = if_else( ref_area == "ROU" & time=="2010", "B" , obs_status), note_source = if_else( ref_area =="CHE", paste0(note_source,"_S9:3937") , note_source ), note_indicator = if_else( ref_area =="CHE" & time %in% c("2012","2013"), "_T34:2128" , note_indicator ) ) %>% ### also other notes #I need to add _NOTE_EXCLUDING_APPRENTICES _NOTE_EXCLUDING_PART_TIMERS # Poland I obs_value for 2007 2009 2011 2013 2015 (odd years) # I12:422 Cyprus: Mean monthly earnings are used in the calculation of the GPG between the 4-yearly Structure of Earnings Survey (SES). # REMOVE _S6:48 Czech Republic: Enterprises with 1+ employees are covered by data. The gender pay gap by age, economic control and working time are for NACE sections B to S. # I12:422, _NOTE_MINAGE_18 _NOTE_MAX_AGE64 SWEDEN From 2011, between the 4-yearly Structure of Earnings Survey (SES), data are based on monthly earnings instead of hourly earnings. The population is aged 18-64 and work at least 5% of full time, excluding overtime hours. # SLOVENIA T12:148 T34:397 I12:422 where data on part-time workers are excluded, irregular payments are included and earnings per paid hour are not available, only annual and monthly data per employee # UK T34:397 (includes irregular payments such as bonuses) # UK for 2010 2011 is used instead, I set obs_status to code I # Additionally UK is non calendar year, it is financial year Apr-Mar S3:27 # (2011-2015) S8:63 Iceland excludes some categories in the total (In particular excludes B, I, L, M, N, R, S) mutate( obs_status = if_else( ref_area=="POL" & time %in% c("2007","2009","2011","2013","2015"), "I", obs_status ), note_indicator = if_else( ref_area == "CYP","I12:422", note_indicator ), note_source = if_else( ref_area == "CZE", str_replace(note_source,"_S6:48_","_"), note_source ), note_indicator = if_else( ref_area == "SWE" & time=="2011","I12:422", note_indicator ), note_source = if_else( ref_area == "SWE", paste0(note_source,"_T2:87_T3:94"), note_source ), note_indicator = if_else( ref_area == "SVN", paste0(note_indicator,"_I12:422_T12:148_T34:397"), note_indicator ), obs_status = if_else( ref_area=="GBR" & time %in% c("2010"), "I", obs_status ), note_indicator = if_else( ref_area == "GBR", paste0(note_indicator,"_T34:397"), note_indicator ), note_source = if_else( ref_area == "GBR", paste0(note_source,"_S3:3915"), note_source ), note_source = if_else( ref_area == "ISL", paste0(note_source,"_S8:63"), note_source ) ) %>% mutate( note_indicator = str_replace(note_indicator,"NA_", "") ) %>% # Finally notice that for the years where there is not an SES survey, the data are estimates mutate( obs_status = if_else(time %in% c("2007", "2008","2009","2011", "2012" ,"2013","2015") & is.na(obs_status), "E", obs_status) ) %>% #Drop backcasted data filter(time != "2007") write.csv(Output, file = './input/Output.EAR_GGAP_ECO_RT.csv', row.names=FALSE, na="") } #- Collective metadata for 5 to 8 (note it excludes item 4 as the indicator has it's own metadata detailed by country - which often contradicts the rest) # - In contrast it includes 8 because precisely the metadata used for 5 to 7 is referenced in 8 # 5 - Done // Important -> Notice: For 2010 NAC (National Currency) is not available, this is the most frequent cause of missing rows in new data #indicator number 665 #this should only fill REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_14.EAR_HEES_SEX_OCU_NB <- function (check = TRUE) { #EAR_HEES_SEX_OCU_NB earn_ses_dd_14 Mean nominal hourly earnings of employees by sex and occupation rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data if(FALSE) { Input <- eurostat:::get_eurostat('earn_ses14_14', time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "HE") indicator.list <- c("earn_ses10_14","earn_ses06_14","earn_ses_agt14") for (indicator in indicator.list) { gc(reset=TRUE) if (indicator == "earn_ses10_14") { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "HE") } else { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "HE") %>% rename(currency = unit) } print(indicator) Input <- gtools::smartbind(Input,RawInput, fill="NO!") } } # saveRDS(Input, paste0('./input/Input.EAR_HEES_SEX_OCU_NB.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_HEES_SEX_OCU_NB.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='EAR_HEES_SEX_OCU_NB') -> GrossTarget # saveRDS(GrossTarget, paste0('./input/EAR_HEES_SEX_OCU_NB.GrossTarget.RDS')) GrossTarget <- readRDS(paste0('./input/EAR_HEES_SEX_OCU_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) #Country map all sizes 2010 Size2002.Map <- ilo$code$cl_country %>% filter ( label_en %in% c("Cyprus", "Germany", "Estonia", "Finland", "Hungary", "Ireland", "Lithuania", "Latvia", "Netherlands", "Norway", "Poland", "Slovenia", "Slovak Republic", "United Kingdom") ) %>% rename( ref_area = code) %>% select(ref_area) %>% mutate(metanote.size = "DELETE Size Limitation", time="2002") #Country map non-missing M to O Sector2002.Map <- Country.Map %>% filter( geo %in% c("RO", "NL", "ES", "IE", "SI", "CZ", "SK", "BG", "HU", "UK", "LT", "PL")) %>% select(ref_area) %>% mutate(metanote.sector = "DELETE Economic Sector Limitation", time="2002") ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## OCU map isco88.Map <- ilo$code$cl_classif %>% filter( str_detect(code, "ISCO88_[:alnum:]$") ) %>% mutate(isco88 = paste0("ISCO" ,str_extract(code,"[:alnum:]$") ) ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, isco88) %>% mutate( isco88 = if_else(isco88 == "ISCOX", "UNK", isco88) ) isco08.Map <- ilo$code$cl_classif %>% filter( str_detect(code, "ISCO08_[:alnum:]$") ) %>% mutate(isco08 = paste0("OC", str_extract(code,"[:alnum:]$") ) ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, isco08) ## Source Map Source.Map <- GrossTarget %>% filter(time>1998) %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) %>% filter( !(source %in% c("BA:199"))) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% mutate( sex = paste0("SEX_", sex), classif2 = NA_character_, note_classif = NA_character_, indicator = "EAR_HEES_SEX_OCU_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", s = "E", i = NA_character_), obs_status = as.character(obs_status) ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Data selection - Only 10 or more employees are kept for comparability's sake filter( sizeclas == "GE10" | time == "2002" ) %>% select( -sizeclas ) %>% # classif1, the mapping is required, also note that sectors are excluded left_join( isco08.Map , by = c("isco08") ) %>% left_join( isco88.Map , by = c("isco88") ) %>% mutate(classif1 = if_else ( is.na(classif1.x), classif1.y,classif1.x ) ) %>% mutate( classif1 = if_else( isco88 =="TOTAL", "OCU_ISCO88_TOTAL",classif1) ) %>% mutate( classif1 = if_else( isco08 =="TOTAL", "OCU_ISCO08_TOTAL",classif1) ) %>% mutate( note_source = if_else( time>2009, "R1:2383_R1:3903_S6:48_S8:2566","R1:2383_R1:3903_S6:48_S8:3907_S8:3211" ) ) %>% filter( !is.na(classif1) ) %>% select( -classif1.y, -classif1.x, -isco08, -isco88) %>% ## a bit more work on the notes for year 2002 (L to O was optional however some countries did include it, Also heterogeneity by size) left_join( Size2002.Map, by = c("time", "ref_area") ) %>% left_join( Sector2002.Map, by = c("time", "ref_area") ) %>% # All countries are initially set to 10 or more employees and missing L-O mutate( note_source = if_else( time=="2002","R1:2383_R1:3903_S6:48_S8:2603_S8:3907" ,note_source ) ) %>% #Here the exceptions for either rule are corrected mutate( note_source = if_else( time==2002 & !is.na(metanote.size), str_replace(note_source,"_S6:48_","_"), note_source ) ) %>% mutate( note_source = if_else( time==2002 & !is.na(metanote.sector), str_replace(note_source,"_S8:2603_S8:3907",""), note_source ) ) %>% select( -geo, -metanote.size, -metanote.sector, -indic_se, -age ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") ) %>% ####### ************************************************* # doubt with respect to in kind, metadata seems quite inconsistent -> Decision: Do not include. Justification: For Countries not reporting it in 2002 and 2006 in 2010 is mentioned that it is included for the first time, whereas other countries clearly mention it in those years # 2002 - GER The data refer to 2001 (October) _S3:21_S3:27, SWE excluding 15-17, ROU did not cover apprentices, CZE includes bonuses T34:397 # 2006 and 2010- CZE annual average # 2006 and onwards Spain excludes apprentices # 2010 excluding apprentices in Slovenia but unsure about before + they say its negligible -> Decision: I exclude. #All years, SWE September, NOR September-October, HUN May, DK Full year and then annual average, Rest of countries October excluding CZE 2006 and 2010 mutate( # October as a reference period note_source = if_else( !(ref_area %in% c("SWE","NOR", "HUN", "CZE","DNK")) , paste0(note_source,"_S3:21"), note_source), # Reference period idosyncracies note_source = if_else( ref_area %in% c("CZE") & time<2006 , paste0(note_source,"_S3:21"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_S3:20"), note_source), note_source = if_else( ref_area %in% c("NOR") , paste0(note_source,"_S3:20_S3:21"), note_source), note_source = if_else( ref_area %in% c("HUN") , paste0(note_source,"_S3:16"), note_source), note_source = if_else( ref_area %in% c("DEU") & time<2006 , paste0(note_source,"_S3:27"), note_source), # Other source notes #note_source = if_else( ref_area %in% c("ESP") & time>2004 , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("ROU") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("CZE") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_T2:86"), note_source), # Indicator notes note_indicator = if_else( ref_area %in% c("CZE") , paste0(note_indicator,"_T34:397"), note_indicator) ) %>% mutate( note_indicator = str_replace(note_indicator,"NA_", "") ) %>% mutate( note_source = str_replace(note_source,"NA_", "") ) %>% filter( !(ref_area %in% c("ESP","FIN","GBR", "ISL","CZE", "SVK", "PRT")) ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time>1998, !str_detect(classif1,"SKILL") ) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "sex", "classif1")) %>% mutate(diff = 100 * (obs_value.x-as.double(obs_value.y) )/obs_value.x ) write.csv(Output, file = './input/Output.EAR_HEES_SEX_OCU_NB.csv', row.names=FALSE, na="") } # 6 - Done// Important Notice: For 2010 NAC (National Currency) is not available, this is the most frequent cause of missing rows in new data #indicator number 50 #this should only fill REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_20.EAR_XEES_SEX_ECO_NB <- function (check = TRUE) { #EAR_XEES_SEX_ECO_NB earn_ses_dd_20 Mean nominal monthly earnings of employees by sex and economic activity rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data if(FALSE) { Input <- eurostat:::get_eurostat('earn_ses14_20', time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") indicator.list <- c("earn_ses10_20","earn_ses06_20","earn_ses_agt20") for (indicator in indicator.list) { gc(reset=TRUE) if (indicator == "earn_ses10_20") { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") } else { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") %>% rename(currency = unit) } print(indicator) Input <- gtools::smartbind(Input,RawInput, fill="NO!") } } # saveRDS(Input, paste0('./input/Input.EAR_XEES_SEX_ECO_NB.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_XEES_SEX_ECO_NB.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='EAR_XEES_SEX_ECO_NB') -> GrossTarget # saveRDS(GrossTarget, paste0('./input/EAR_XEES_SEX_ECO_NB.GrossTarget.RDS')) GrossTarget <- readRDS(paste0('./input/EAR_XEES_SEX_ECO_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) #Country map all sizes 2010 Size2002.Map <- ilo$code$cl_country %>% filter ( label_en %in% c("Cyprus", "Germany", "Estonia", "Finland", "Hungary", "Ireland", "Lithuania", "Latvia", "Netherlands", "Norway", "Poland", "Slovenia", "Slovak Republic", "United Kingdom") ) %>% rename( ref_area = code) %>% select(ref_area) %>% mutate(metanote.size = "DELETE S6:48", time="2002") #Country map non-missing M to O Sector2002.Map <- Country.Map %>% filter( geo %in% c("RO", "NL", "ES", "IE", "SI", "CZ", "SK", "BG", "HU", "UK", "LT", "PL")) %>% select(ref_area) %>% mutate(metanote.sector = "_S8:2603_S8:3907", time="2002") ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## ECO map isic4.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC4_[:alpha:]$")) %>% mutate(nace_r2 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r2) ## ECO map isic3.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC3_[:alpha:]$")) %>% mutate(nace_r1 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r1) ## Source Map library(readxl) Source.Map <- read_excel("J:/DPAU/DATA/REP_EUROSTAT/SES_ANNUAL/input/SES_Surveys.xlsx") %>% rbind(c("HRV","DA:562") ) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% mutate( sex = paste0("SEX_", sex), classif2 = NA_character_, note_classif = NA_character_, indicator = "EAR_XEES_SEX_ECO_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", s = "E", i = NA_character_), obs_status = as.character(obs_status) ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Data selection - Only 10 or more employees are kept for comparability's sake filter( sizeclas == "GE10" | time == "2002" ) %>% select( -sizeclas ) %>% # classif1, the mapping is required, also note that sectors are excluded left_join( isic4.Map , by = c("nace_r2") ) %>% left_join( isic3.Map , by = c("nace_r1") ) %>% mutate(classif1 = if_else ( is.na(classif1.x), classif1.y,classif1.x ) ) %>% mutate( classif1 = if_else(nace_r2=="B-S_X_O", "ECO_ISIC4_TOTAL",classif1) ) %>% mutate( classif1 = if_else(nace_r1=="C-O_X_L", "ECO_ISIC3_TOTAL",classif1) ) %>% mutate( note_source = if_else( time>2009, "R1:2383_R1:3903_S6:48_S8:2566","R1:2383_R1:3903_S6:48_S8:3907_S8:3211" ) ) %>% filter( !is.na(classif1) ) %>% select( -classif1.y, -classif1.x, -nace_r1, -nace_r2) %>% ## a bit more work on the notes for year 2002 (L to O was optional however some countries did include it, Also heterogeneity by size) left_join( Size2002.Map, by = c("time", "ref_area") ) %>% left_join( Sector2002.Map, by = c("time", "ref_area") ) %>% # All countries are initially set to 10 or more employees and missing L-O mutate( note_source = if_else( time=="2002","R1:2383_R1:3903_S6:48_S8:2603_S8:3907" ,note_source ) ) %>% #Here the exceptions for either rule are corrected mutate( note_source = if_else( time==2002 & !is.na(metanote.size), str_replace(note_source,"_S6:48_","_"), note_source ) ) %>% mutate( note_source = if_else( time==2002 & !is.na(metanote.sector), str_replace(note_source,"_S8:2603_S8:3907",""), note_source ) ) %>% select( -geo, -metanote.size, -metanote.sector, -indic_se, -age ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") )%>% ####### ************************************************* # doubt with respect to in kind, metadata seems quite inconsistent -> Decision: Do not include. Justification: For Countries not reporting it in 2002 and 2006 in 2010 is mentioned that it is included for the first time, whereas other countries clearly mention it in those years # 2002 - GER The data refer to 2001 (October) _S3:21_S3:27, SWE excluding 15-17, ROU did not cover apprentices, CZE includes bonuses T34:397 # 2006 and 2010- CZE annual average # 2006 and onwards Spain excludes apprentices # 2010 excluding apprentices in Slovenia but unsure about before + they say its negligible -> Decision: I exclude. #All years, SWE September, NOR September-October, HUN May, DK Full year and then annual average, Rest of countries October excluding CZE 2006 and 2010 mutate( # October as a reference period note_source = if_else( !(ref_area %in% c("SWE","NOR", "HUN", "CZE","DNK")) , paste0(note_source,"_S3:21"), note_source), # Reference period idosyncracies note_source = if_else( ref_area %in% c("CZE") & time<2006 , paste0(note_source,"_S3:21"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_S3:20"), note_source), note_source = if_else( ref_area %in% c("NOR") , paste0(note_source,"_S3:20_S3:21"), note_source), note_source = if_else( ref_area %in% c("HUN") , paste0(note_source,"S3:16"), note_source), note_source = if_else( ref_area %in% c("DEU") & time<2006 , paste0(note_source,"_S3:27"), note_source), # Other source notes note_source = if_else( ref_area %in% c("ESP") & time>2004 , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("ROU") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("CZE") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_T2:86"), note_source), # Indicator notes note_indicator = if_else( ref_area %in% c("CZE") , paste0(note_indicator,"_T34:397"), note_indicator) ) %>% mutate( note_indicator = str_replace(note_indicator,"NA_", "") ) %>% mutate( note_source = str_replace(note_source,"NA_", "") ) %>% filter( !(ref_area %in% c("ESP","FIN","GBR", "ISL","CZE", "SVK", "BEL", "CHE", "NLD", "PRT")) ) %>% #Filter older entries, it is incomplete compared to what we have filter( time >2009 ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time %in% c("2002","2006","2010","2014"), ! (str_detect(classif1,"AGGREGATE") ) ) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "sex", "classif1")) %>% mutate(diff = 100 * (obs_value.x-as.double(obs_value.y) )/obs_value.x ) write.csv(Output, file = './input/Output.EAR_XEES_SEX_ECO_NB.csv', row.names=FALSE, na="") } # 7 - Done // Important Notice: For 2010 NAC (National Currency) is not available, this is the most frequent cause of missing rows in new data #indicator number 52 #this should only fill REP_EUROSTAT.SES_ANNUAL.earn_ses_dd_21.EAR_XEES_SEX_OCU_NB <- function (check = TRUE) { #EAR_XEES_SEX_OCU_NB earn_ses_dd_21 Mean nominal monthly earnings of employees by sex and occupation rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data if(FALSE) { Input <- eurostat:::get_eurostat('earn_ses14_21', time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") indicator.list <- c("earn_ses10_21","earn_ses06_21","earn_ses_agt21") for (indicator in indicator.list) { gc(reset=TRUE) if (indicator == "earn_ses10_21") { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") } else { RawInput <- eurostat:::get_eurostat( indicator , time_format = 'raw', keepFlags = TRUE, cache = FALSE) %>% lapply(as.character) %>% data.frame(stringsAsFactors = FALSE) %>% filter( age == "TOTAL", indic_se == "ME") %>% rename(currency = unit) } print(indicator) Input <- gtools::smartbind(Input,RawInput, fill="NO!") } } # saveRDS(Input, paste0('./input/Input.EAR_XEES_SEX_OCU_NB.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_XEES_SEX_OCU_NB.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='EAR_XEES_SEX_OCU_NB') -> GrossTarget # saveRDS(GrossTarget, paste0('./input/EAR_XEES_SEX_OCU_NB.GrossTarget.RDS')) GrossTarget <- readRDS(paste0('./input/EAR_XEES_SEX_OCU_NB.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) #Country map all sizes 2010 Size2002.Map <- ilo$code$cl_country %>% filter ( label_en %in% c("Cyprus", "Germany", "Estonia", "Finland", "Hungary", "Ireland", "Lithuania", "Latvia", "Netherlands", "Norway", "Poland", "Slovenia", "Slovak Republic", "United Kingdom") ) %>% rename( ref_area = code) %>% select(ref_area) %>% mutate(metanote.size = "DELETE Size Limitation", time="2002") #Country map non-missing M to O Sector2002.Map <- Country.Map %>% filter( geo %in% c("RO", "NL", "ES", "IE", "SI", "CZ", "SK", "BG", "HU", "UK", "LT", "PL")) %>% select(ref_area) %>% mutate(metanote.sector = "DELETE Economic Sector Limitation", time="2002") ## Currency Map Currency.Map <- ilo$code$cl_note_currency %>% rename( currency = CUR_CODE) %>% mutate( ref_area = substr(label_en, 17, 19)) %>% select( code, currency, ref_area, sort) %>% mutate( currency = if_else(currency == "EUR", "EUR","NAC") ) ## OCU map isco88.Map <- ilo$code$cl_classif %>% filter( str_detect(code, "ISCO88_[:alnum:]$") ) %>% mutate(isco88 = paste0("ISCO" ,str_extract(code,"[:alnum:]$") ) ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, isco88) %>% mutate( isco88 = if_else(isco88 == "ISCOX", "UNK", isco88) ) isco08.Map <- ilo$code$cl_classif %>% filter( str_detect(code, "ISCO08_[:alnum:]$") ) %>% mutate(isco08 = paste0("OC", str_extract(code,"[:alnum:]$") ) ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, isco08) ## Source Map library(readxl) Source.Map <- read_excel("J:/DPAU/DATA/REP_EUROSTAT/SES_ANNUAL/input/SES_Surveys.xlsx") %>% rbind(c("HRV","DA:562") ) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% mutate( sex = paste0("SEX_", sex), classif2 = NA_character_, note_classif = NA_character_, indicator = "EAR_XEES_SEX_OCU_NB", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", s = "E", i = NA_character_), obs_status = as.character(obs_status) ) %>% # note_indicator Mapping currency and droping in case it does not match # selecting the one with the lowest sort #note_indicator filter( currency != "PPS") %>% left_join( Currency.Map , by = c("ref_area","currency") ) %>% filter( ! is.na( sort) ) %>% group_by(ref_area, time) %>% mutate( minsort = min(sort) ) %>% ungroup() %>% filter( (sort == minsort) ) %>% mutate( note_indicator = as.character(code) ) %>% select( -minsort, -currency, -sort, -code ) %>% # Data selection - Only 10 or more employees are kept for comparability's sake filter( sizeclas == "GE10" | time == "2002" ) %>% select( -sizeclas ) %>% # classif1, the mapping is required, also note that sectors are excluded left_join( isco08.Map , by = c("isco08") ) %>% left_join( isco88.Map , by = c("isco88") ) %>% mutate(classif1 = if_else ( is.na(classif1.x), classif1.y,classif1.x ) ) %>% mutate( classif1 = if_else( isco88 =="TOTAL", "OCU_ISCO88_TOTAL",classif1) ) %>% mutate( classif1 = if_else( isco08 =="TOTAL", "OCU_ISCO08_TOTAL",classif1) ) %>% mutate( note_source = if_else( time>2009, "R1:2383_R1:3903_S6:48_S8:2566","R1:2383_R1:3903_S6:48_S8:3907_S8:3211" ) ) %>% filter( !is.na(classif1) ) %>% select( -classif1.y, -classif1.x, -isco08, -isco88) %>% ## a bit more work on the notes for year 2002 (L to O was optional however some countries did include it, Also heterogeneity by size) left_join( Size2002.Map, by = c("time", "ref_area") ) %>% left_join( Sector2002.Map, by = c("time", "ref_area") ) %>% # All countries are initially set to 10 or more employees and missing L-O mutate( note_source = if_else( time=="2002","R1:2383_R1:3903_S6:48_S8:2603_S8:3907" ,note_source ) ) %>% #Here the exceptions for either rule are corrected mutate( note_source = if_else( time==2002 & !is.na(metanote.size), str_replace(note_source,"_S6:48_","_"), note_source ) ) %>% mutate( note_source = if_else( time==2002 & !is.na(metanote.sector), str_replace(note_source,"_S8:2603_S8:3907",""), note_source ) ) %>% select( -geo, -metanote.size, -metanote.sector, -indic_se, -age ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") )%>% ####### ************************************************* # doubt with respect to in kind, metadata seems quite inconsistent -> Decision: Do not include. Justification: For Countries not reporting it in 2002 and 2006 in 2010 is mentioned that it is included for the first time, whereas other countries clearly mention it in those years # 2002 - GER The data refer to 2001 (October) _S3:21_S3:27, SWE excluding 15-17, ROU did not cover apprentices, CZE includes bonuses T34:397 # 2006 and 2010- CZE annual average # 2006 and onwards Spain excludes apprentices # 2010 excluding apprentices in Slovenia but unsure about before + they say its negligible -> Decision: I exclude. #All years, SWE September, NOR September-October, HUN May, DK Full year and then annual average, Rest of countries October excluding CZE 2006 and 2010 mutate( # October as a reference period note_source = if_else( !(ref_area %in% c("SWE","NOR", "HUN", "CZE","DNK")) , paste0(note_source,"_S3:21"), note_source), # Reference period idosyncracies note_source = if_else( ref_area %in% c("CZE") & time<2006 , paste0(note_source,"_S3:21"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_S3:20"), note_source), note_source = if_else( ref_area %in% c("NOR") , paste0(note_source,"_S3:20_S3:21"), note_source), note_source = if_else( ref_area %in% c("HUN") , paste0(note_source,"S3:16"), note_source), note_source = if_else( ref_area %in% c("DEU") & time<2006 , paste0(note_source,"_S3:27"), note_source), # Other source notes note_source = if_else( ref_area %in% c("ESP") & time>2004 , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("ROU") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("CZE") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_T2:86"), note_source), # Indicator notes note_indicator = if_else( ref_area %in% c("CZE") , paste0(note_indicator,"_T34:397"), note_indicator) ) %>% mutate( note_indicator = str_replace(note_indicator,"NA_", "") ) %>% mutate( note_source = str_replace(note_source,"NA_", "") )%>% filter( !(ref_area %in% c("ESP","FIN","GBR", "ISL","CZE", "SVK", "BEL", "LTU")) ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time %in% c("2002","2006","2010","2014"), !str_detect(classif1,"SKILL") ) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "sex", "classif1")) %>% mutate(diff = 100 * (obs_value.x-as.double(obs_value.y) )/obs_value.x ) write.csv(Output, file = './input/Output.EAR_XEES_SEX_OCU_NB.csv', row.names=FALSE, na="") } ## ************************************************ # 8 - Almost Done (some chechking required) # note that this one is muted, since OECD has better data #indicator number 658 REP_EUROSTAT.SES_ANNUAL.earn_ses_pub1s.EAR_XTLP_SEX_RT <- function (check = TRUE) { #EAR_XTLP_SEX_RT earn_ses_pub1s Low pay rate by sex rm(list=setdiff(ls(), c("ilo"))) ############## Getting the data # Input <- eurostat:::get_eurostat('earn_ses_pub1s', time_format = 'raw', keepFlags = TRUE, cache = FALSE) # saveRDS(Input, paste0('./input/Input.EAR_XTLP_SEX_RT.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.EAR_XTLP_SEX_RT.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='EAR_XTLP_SEX_RT') -> GrossTarget # saveRDS(GrossTarget, paste0('./input/EAR_XTLP_SEX_RT.GrossTarget.RDS')) GrossTarget <- readRDS(paste0('./input/EAR_XTLP_SEX_RT.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) ## ECO map Sector.Map <- ilo$code$cl_classif %>% filter(str_detect(code,"ISIC4_[:alpha:]$")) %>% mutate(nace_r2 = str_extract(code,"[:alpha:]$") ) %>% mutate(classif1 = as.character(code)) %>% select(classif1, nace_r2) ## Source Map library(readxl) Source.Map <- read_excel("J:/DPAU/DATA/REP_EUROSTAT/SES_ANNUAL/input/SES_Surveys.xlsx") %>% rbind(c("HRV","DA:562") ) ## end ############## Modifying input, and saving output Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = paste0("SEX_", sex), classif1 = NA_character_, classif2 = NA_character_, note_classif = NA_character_, note_indicator = NA_character_, indicator = "EAR_XTLP_SEX_RT", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", c = "C", p = "P", u ="U", s = "E", i = NA_character_, d = NA_character_ ), obs_status = as.character(obs_status) ) %>% mutate( note_source = if_else( time=="2006","R1:2383_R1:3903_S6:48_S8:2566","R1:2383_R1:3903_S6:48_S8:3907_S8:3211") ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") ) %>% select(-unit, -sizeclas) %>% ####### ************************************************* # doubt with respect to in kind, metadata seems quite inconsistent -> Decision: Do not include. Justification: For Countries not reporting it in 2002 and 2006 in 2010 is mentioned that it is included for the first time, whereas other countries clearly mention it in those years # 2002 - GER The data refer to 2001 (October) _S3:21_S3:27, SWE excluding 15-17, ROU did not cover apprentices, CZE includes bonuses T34:397 # 2006 and 2010- CZE annual average # 2006 and onwards Spain excludes apprentices # 2010 excluding apprentices in Slovenia but unsure about before + they say its negligible -> Decision: I exclude. #All years, SWE September, NOR September-October, HUN May, DK Full year and then annual average, Rest of countries October excluding CZE 2006 and 2010 mutate( # October as a reference period note_source = if_else( !(ref_area %in% c("SWE","NOR", "HUN", "CZE","DNK")) , paste0(note_source,"_S3:21"), note_source), # Reference period idosyncracies note_source = if_else( ref_area %in% c("CZE") & time<2006 , paste0(note_source,"_S3:21"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_S3:20"), note_source), note_source = if_else( ref_area %in% c("NOR") , paste0(note_source,"_S3:20_S3:21"), note_source), note_source = if_else( ref_area %in% c("HUN") , paste0(note_source,"S3:16"), note_source), note_source = if_else( ref_area %in% c("DEU") & time<2006 , paste0(note_source,"_S3:27"), note_source), # Other source notes note_source = if_else( ref_area %in% c("ESP") & time>2004 , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("ROU") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("CZE") , paste0(note_source,"_S9:3937"), note_source), note_source = if_else( ref_area %in% c("SWE") , paste0(note_source,"_T2:86"), note_source), # Indicator notes note_indicator = if_else( ref_area %in% c("CZE") , paste0(note_indicator,"_T34:397"), note_indicator) ) %>% mutate( note_indicator = str_replace(note_indicator,"NA_", "") ) %>% mutate( note_source = str_replace(note_source,"NA_", "") ) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time %in% c("2006","2010","2014") ) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "sex")) %>% mutate(diff = 100 * (obs_value.x-as.double(obs_value.y) )/obs_value.x ) #Halted, OECD has better data #write.csv(Output, file = './input/Output.EAR_XTLP_SEX_RT.csv', row.names=FALSE) } ### ***************If there are additional targets this project shoulde be moved to its appropiate folder SILC_ANNUAL # METADATA Now Done # 9 - Poverty while at work, by sex and age REP_EUROSTAT.SES_ANNUAL.ilc_iw01.POV_DEMP_SEX_AGE_RT <- function (check = TRUE) { #POV_DEMP_SEX_AGE_RT ilc_iw01 Working poverty rate by sex and age rm(list=setdiff(ls(), c("ilo"))) ## parameters work_directory = "REP_EUROSTAT/SILC_ANNUAL" ## Initialize setwd(paste0(ilo:::path$data, work_directory)) ############## Getting the data # Input <- eurostat:::get_eurostat('ilc_iw01', time_format = 'raw', keepFlags = TRUE, cache = FALSE) # saveRDS(Input, paste0('./input/Input.POV_DEMP_SEX_AGE_RT.RDS')) ## Read Input Input <- readRDS(paste0('./input/Input.POV_DEMP_SEX_AGE_RT.RDS')) ## Other data ##### this should never be run again get_ilo(indicator='POV_DEMP_SEX_AGE_RT') -> GrossTarget # saveRDS(GrossTarget, paste0('./input/POV_DEMP_SEX_AGE_RT.GrossTarget.RDS')) GrossTarget <- readRDS(paste0('./input/POV_DEMP_SEX_AGE_RT.GrossTarget.RDS')) ## end ################ Mappings ## Country Map Country.Map <- Input %>% distinct(geo) %>% left_join( ilo$code$cl_country %>% rename(geo = code_iso2), by="geo" ) %>% select(geo, code) %>% mutate( code = if_else( geo=="EL", "GRC", code ), code = if_else( geo=="UK", "GBR", code ) ) %>% rename( ref_area = code ) Source.Map <- GrossTarget %>% filter(time>2002) %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) Potential.Sources <- ilo$code$cl_survey %>% filter(str_detect( label_en, "Income and Living Conditions") ) %>% mutate( source = code, ref_area = str_extract(label_en,"^[:upper:]+") ) %>% distinct(ref_area, source) %>% select(ref_area, source) %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% distinct(ref_area, source) Source.Map <- rbind(Source.Map, Potential.Sources) %>% distinct(ref_area, source) %>% switch_ilo(keep) %>% group_by(ref_area) %>% mutate( n = n()) %>% ungroup() %>% filter( n == 1 | (n == 2 & str_detect(source.label, "EU") ) ) %>% select(ref_area,source) %>% # Note, certain countries did not have the survey #CHE, MKD, POL need to add -> EU Statistics on Income and Living Conditions BB sort 15 rbind(c("CHE","BB:13356")) %>% rbind(c("MKD","BB:13357")) %>% rbind(c("POL","BB:13355")) %>% distinct(ref_area, source) ## end ############## Modifying input, and saving output #based on the general Eurostat metadata Output <- Input %>% #ref_area left_join(Country.Map , by="geo" ) %>% filter(!is.na(ref_area)) %>% # several renaming, and empty variables rename( obs_value = values ) %>% rename( obs_status = flags ) %>% select( -geo ) %>% mutate( sex = paste0("SEX_", sex), classif2 = NA_character_, note_classif = NA_character_, note_indicator = "T20:180", note_source = "S3:5_S4:4137_S5:4138_T2:85", indicator = "POV_DEMP_SEX_AGE_RT", collection = "STI" ) %>% # value changes mutate( obs_status = obs_status %>% recode( e = "E", b= "B" , c = "C", p = "P", u ="U", s = "E", i = NA_character_, d = NA_character_ ), obs_status = as.character(obs_status) ) %>% # source left_join( Source.Map , by = "ref_area") %>% replace_na( list(source= "NEED SOURCE!!!") ) %>% # filter by breakdown of interest, note that age bands will have to be noted as being non standard filter(wstatus=="EMP") %>% mutate( classif1 = age %>% recode( "Y15-24" = "AGE_YTHADULT_Y15-24", "Y_GE18" = "AGE_YTHADULT_YGE15" ) ) %>% filter ( !str_detect(classif1,"^Y")) %>% #note for the aggregate total mutate( note_classif = if_else(classif1 == "AGE_YTHADULT_YGE15", "C6:1056" , note_classif ) ) %>% mutate( note_classif = if_else(classif1 == "AGE_YTHADULT_Y15-24", "C6:1058" , note_classif ) ) %>% select( -age, - wstatus) Net.Target <- GrossTarget %>% left_join(Country.Map, by="ref_area") %>% filter( !is.na(geo)) %>% select( -geo) %>% filter(time >2002 ) Comparison <- Net.Target %>% left_join(Output, by=c("ref_area", "time", "sex", "classif1")) %>% mutate(diff = 100 * (obs_value.x-as.double(obs_value.y) )/obs_value.x ) write.csv(Output, file = './input/Output.POV_DEMP_SEX_AGE_RT.csv', row.names=FALSE, na="") }
(* *********************************************************************) (* *) (* The CertiKOS Certified Kit Operating System *) (* *) (* The FLINT Group, Yale University *) (* *) (* Copyright The FLINT Group, Yale University. All rights reserved. *) (* This file is distributed under the terms of the Yale University *) (* Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (* *********************************************************************) (* *) (* Layers of VMM *) (* *) (* Refinement proof for MALInit layer *) (* *) (* Ronghui Gu <[email protected]> *) (* *) (* Yale Flint Group *) (* *) (* *********************************************************************) Require Import BootGenDef. Require Import BootGenAccessorDef. Require Import BootGenSpec. (** * Definition of the refinement relation*) Section Refinement. Section WITHMEM. Context `{Hstencil: Stencil}. Context `{Hmem: Mem.MemoryModel}. Context `{Hmwd: UseMemWithData mem}. Lemma fload_spec_ref: compatsim (crel HDATAOps LDATAOps) (gensem fload'_spec) fload_spec_low. Proof. compatsim_simpl (@match_AbData). inv H. functional inversion H2; subst. refine_split; try (econstructor; eauto). - simpl. lift_trivial. exploit flatmem_load_correct0; eauto. + simpl. omega. + simpl. apply Zdivide_mult_r. apply Zdivide_refl. + simpl; lift_trivial. intros (v' & HLoad & HVal). inv HVal. rewrite HLoad. rewrite <- (Int.repr_unsigned z). rewrite <- (Int.repr_unsigned n). congruence. - inv match_related. simpl. split; congruence. - apply inject_incr_refl. Qed. Lemma fstore_spec_ref: compatsim (crel HDATAOps LDATAOps) (gensem fstore'_spec) fstore_spec_low. Proof. compatsim_simpl (@match_AbData). inv H. functional inversion H1; subst. rewrite Int.repr_unsigned in *. unfold fstore'_spec in H1. revert H1. subrewrite. exploit flatmem_store_correct0; eauto. - simpl. omega. - simpl. apply Zdivide_mult_r. apply Zdivide_refl. - intros (m2' & HST & Hmatch_ext'). refine_split; eauto. econstructor; try eassumption. + simpl. lift_trivial. rewrite Int.repr_unsigned in HST. rewrite HST. reflexivity. + inv match_related. simpl. split; congruence. Qed. End WITHMEM. End Refinement.
function one_pixel_result=seg_eva_one_img(predict_mask, gt_mask, class_info) exclude_class_idxes=class_info.void_class_idxes; class_num=class_info.class_num; assert(all(size(gt_mask)==size(predict_mask))); gt_mask_vector=gt_mask(:); predict_mask_vector=predict_mask(:); if ~isempty(exclude_class_idxes) valid_pixel_sel=~ismember(gt_mask, exclude_class_idxes); gt_mask_vector=gt_mask_vector(valid_pixel_sel); predict_mask_vector=predict_mask_vector(valid_pixel_sel); end [tmp_con_mat, label_vs]=confusionmat(gt_mask_vector, predict_mask_vector); confusion_mat=zeros(class_num, class_num); confusion_mat(label_vs,label_vs)=tmp_con_mat; one_pixel_result=seg_eva_gen_result_from_con_mat(confusion_mat, exclude_class_idxes); end
[GOAL] R : Type u_1 inst✝ : CommRing R a b c d x y z w : R ⊢ (a * x - b * y - c * z - d * w) ^ 2 + (a * y + b * x + c * w - d * z) ^ 2 + (a * z - b * w + c * x + d * y) ^ 2 + (a * w + b * z - c * y + d * x) ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) [PROOFSTEP] ring [GOAL] a b c d x y z w : ℕ ⊢ Int.natAbs (↑a * ↑x - ↑b * ↑y - ↑c * ↑z - ↑d * ↑w) ^ 2 + Int.natAbs (↑a * ↑y + ↑b * ↑x + ↑c * ↑w - ↑d * ↑z) ^ 2 + Int.natAbs (↑a * ↑z - ↑b * ↑w + ↑c * ↑x + ↑d * ↑y) ^ 2 + Int.natAbs (↑a * ↑w + ↑b * ↑z - ↑c * ↑y + ↑d * ↑x) ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2) [PROOFSTEP] rw [← Int.coe_nat_inj'] [GOAL] a b c d x y z w : ℕ ⊢ ↑(Int.natAbs (↑a * ↑x - ↑b * ↑y - ↑c * ↑z - ↑d * ↑w) ^ 2 + Int.natAbs (↑a * ↑y + ↑b * ↑x + ↑c * ↑w - ↑d * ↑z) ^ 2 + Int.natAbs (↑a * ↑z - ↑b * ↑w + ↑c * ↑x + ↑d * ↑y) ^ 2 + Int.natAbs (↑a * ↑w + ↑b * ↑z - ↑c * ↑y + ↑d * ↑x) ^ 2) = ↑((a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2 + w ^ 2)) [PROOFSTEP] push_cast [GOAL] a b c d x y z w : ℕ ⊢ |↑a * ↑x - ↑b * ↑y - ↑c * ↑z - ↑d * ↑w| ^ 2 + |↑a * ↑y + ↑b * ↑x + ↑c * ↑w - ↑d * ↑z| ^ 2 + |↑a * ↑z - ↑b * ↑w + ↑c * ↑x + ↑d * ↑y| ^ 2 + |↑a * ↑w + ↑b * ↑z - ↑c * ↑y + ↑d * ↑x| ^ 2 = (↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2) * (↑x ^ 2 + ↑y ^ 2 + ↑z ^ 2 + ↑w ^ 2) [PROOFSTEP] simp only [sq_abs, _root_.euler_four_squares] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 ⊢ Even (x ^ 2 + y ^ 2) [PROOFSTEP] simp [← h, even_mul] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) ⊢ Even (x + y) [PROOFSTEP] simpa [sq, parity_simps] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) ⊢ Even (x - y) [PROOFSTEP] simpa [sq, parity_simps] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) hxsuby : Even (x - y) ⊢ 2 * 2 ≠ 0 [PROOFSTEP] decide [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) hxsuby : Even (x - y) ⊢ ↑2 * ↑2 * m = (x - y) ^ 2 + (x + y) ^ 2 [PROOFSTEP] rw [mul_assoc, h] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) hxsuby : Even (x - y) ⊢ ↑2 * (x ^ 2 + y ^ 2) = (x - y) ^ 2 + (x + y) ^ 2 [PROOFSTEP] ring [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) hxsuby : Even (x - y) ⊢ (x - y) ^ 2 + (x + y) ^ 2 = (2 * ((x - y) / 2)) ^ 2 + (2 * ((x + y) / 2)) ^ 2 [PROOFSTEP] rw [even_iff_two_dvd] at hxsuby hxaddy [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : 2 ∣ x + y hxsuby : 2 ∣ x - y ⊢ (x - y) ^ 2 + (x + y) ^ 2 = (2 * ((x - y) / 2)) ^ 2 + (2 * ((x + y) / 2)) ^ 2 [PROOFSTEP] rw [Int.mul_ediv_cancel' hxsuby, Int.mul_ediv_cancel' hxaddy] [GOAL] m x y : ℤ h : ↑2 * m = x ^ 2 + y ^ 2 this : Even (x ^ 2 + y ^ 2) hxaddy : Even (x + y) hxsuby : Even (x - y) ⊢ (2 * ((x - y) / 2)) ^ 2 + (2 * ((x + y) / 2)) ^ 2 = ↑2 * ↑2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) [PROOFSTEP] simp [mul_add, pow_succ, mul_comm, mul_assoc, mul_left_comm] [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m ⊢ k < m [PROOFSTEP] refine lt_of_mul_lt_mul_right (lt_of_mul_lt_mul_left ?_ (zero_le (2 ^ 2))) (zero_le m) [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m ⊢ 2 ^ 2 * (k * m) < 2 ^ 2 * (m * m) [PROOFSTEP] calc 2 ^ 2 * (k * ↑m) = ∑ i : Fin 4, (2 * ![a, b, c, d] i) ^ 2 := by simp [← h, Fin.sum_univ_succ, mul_add, mul_pow, add_assoc] _ < ∑ _i : Fin 4, m ^ 2 := (Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty fun i _ ↦ by refine pow_lt_pow_of_lt_left ?_ (zero_le _) two_pos fin_cases i <;> assumption) _ = 2 ^ 2 * (m * m) := by simp; ring -- porting note: new theorem [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m ⊢ 2 ^ 2 * (k * m) = ∑ i : Fin 4, (2 * Matrix.vecCons a ![b, c, d] i) ^ 2 [PROOFSTEP] simp [← h, Fin.sum_univ_succ, mul_add, mul_pow, add_assoc] [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m i : Fin 4 x✝ : i ∈ univ ⊢ (2 * Matrix.vecCons a ![b, c, d] i) ^ 2 < m ^ 2 [PROOFSTEP] refine pow_lt_pow_of_lt_left ?_ (zero_le _) two_pos [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m i : Fin 4 x✝ : i ∈ univ ⊢ 2 * Matrix.vecCons a ![b, c, d] i < m [PROOFSTEP] fin_cases i [GOAL] case head a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m x✝ : { val := 0, isLt := (_ : 0 < 4) } ∈ univ ⊢ 2 * Matrix.vecCons a ![b, c, d] { val := 0, isLt := (_ : 0 < 4) } < m [PROOFSTEP] assumption [GOAL] case tail.head a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m x✝ : { val := 1, isLt := (_ : (fun a => a < 4) 1) } ∈ univ ⊢ 2 * Matrix.vecCons a ![b, c, d] { val := 1, isLt := (_ : (fun a => a < 4) 1) } < m [PROOFSTEP] assumption [GOAL] case tail.tail.head a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m x✝ : { val := 2, isLt := (_ : (fun a => (fun a => a < 4) a) 2) } ∈ univ ⊢ 2 * Matrix.vecCons a ![b, c, d] { val := 2, isLt := (_ : (fun a => (fun a => a < 4) a) 2) } < m [PROOFSTEP] assumption [GOAL] case tail.tail.tail.head a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m x✝ : { val := 3, isLt := (_ : (fun a => (fun a => (fun a => a < 4) a) a) 3) } ∈ univ ⊢ 2 * Matrix.vecCons a ![b, c, d] { val := 3, isLt := (_ : (fun a => (fun a => (fun a => a < 4) a) a) 3) } < m [PROOFSTEP] assumption [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m ⊢ ∑ _i : Fin 4, m ^ 2 = 2 ^ 2 * (m * m) [PROOFSTEP] simp [GOAL] a b c d k m : ℕ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k * m ha : 2 * a < m hb : 2 * b < m hc : 2 * c < m hd : 2 * d < m ⊢ 4 * m ^ 2 = 2 ^ 2 * (m * m) [PROOFSTEP] ring -- porting note: new theorem [GOAL] p : ℕ hp : Fact (Nat.Prime p) ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] rcases hp.1.eq_two_or_odd' with (rfl | hodd) [GOAL] case inl hp : Fact (Nat.Prime 2) ⊢ ∃ a b k, 0 < k ∧ k < 2 ∧ a ^ 2 + b ^ 2 + 1 = k * 2 [PROOFSTEP] use 1, 0, 1 [GOAL] case h hp : Fact (Nat.Prime 2) ⊢ 0 < 1 ∧ 1 < 2 ∧ 1 ^ 2 + 0 ^ 2 + 1 = 1 * 2 [PROOFSTEP] simp [GOAL] case inr p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] rcases Nat.sq_add_sq_zmodEq p (-1) with ⟨a, b, ha, hb, hab⟩ [GOAL] case inr.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] rcases Int.modEq_iff_dvd.1 hab.symm with ⟨k, hk⟩ [GOAL] case inr.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 - -1 = ↑p * k ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] rw [sub_neg_eq_add, mul_comm] at hk [GOAL] case inr.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = k * ↑p ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] have hk₀ : 0 < k [GOAL] case hk₀ p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = k * ↑p ⊢ 0 < k [PROOFSTEP] refine pos_of_mul_pos_left ?_ (Nat.cast_nonneg p) [GOAL] case hk₀ p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = k * ↑p ⊢ 0 < k * ↑p [PROOFSTEP] rw [← hk] [GOAL] case hk₀ p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = k * ↑p ⊢ 0 < ↑a ^ 2 + ↑b ^ 2 + 1 [PROOFSTEP] positivity [GOAL] case inr.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℤ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = k * ↑p hk₀ : 0 < k ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] lift k to ℕ using hk₀.le [GOAL] case inr.intro.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = ↑k * ↑p hk₀ : 0 < ↑k ⊢ ∃ a b k, 0 < k ∧ k < p ∧ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] refine ⟨a, b, k, Nat.cast_pos.1 hk₀, ?_, by exact_mod_cast hk⟩ [GOAL] p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = ↑k * ↑p hk₀ : 0 < ↑k ⊢ a ^ 2 + b ^ 2 + 1 = k * p [PROOFSTEP] exact_mod_cast hk [GOAL] case inr.intro.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = ↑k * ↑p hk₀ : 0 < ↑k ⊢ k < p [PROOFSTEP] replace hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p [GOAL] case hk p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk : ↑a ^ 2 + ↑b ^ 2 + 1 = ↑k * ↑p hk₀ : 0 < ↑k ⊢ a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p [PROOFSTEP] exact_mod_cast hk [GOAL] case inr.intro.intro.intro.intro.intro.intro p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk₀ : 0 < ↑k hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p ⊢ k < p [PROOFSTEP] refine lt_of_sum_four_squares_eq_mul hk ?_ ?_ ?_ ?_ [GOAL] case inr.intro.intro.intro.intro.intro.intro.refine_1 p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk₀ : 0 < ↑k hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p ⊢ 2 * a < p [PROOFSTEP] exact (mul_le_mul' le_rfl ha).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat) [GOAL] case inr.intro.intro.intro.intro.intro.intro.refine_2 p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk₀ : 0 < ↑k hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p ⊢ 2 * b < p [PROOFSTEP] exact (mul_le_mul' le_rfl hb).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hodd.not_two_dvd_nat) [GOAL] case inr.intro.intro.intro.intro.intro.intro.refine_3 p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk₀ : 0 < ↑k hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p ⊢ 2 * 1 < p [PROOFSTEP] exact lt_of_le_of_ne hp.1.two_le (hodd.ne_two_of_dvd_nat (dvd_refl _)).symm [GOAL] case inr.intro.intro.intro.intro.intro.intro.refine_4 p : ℕ hp : Fact (Nat.Prime p) hodd : Odd p a b : ℕ ha : a ≤ p / 2 hb : b ≤ p / 2 hab : ↑a ^ 2 + ↑b ^ 2 ≡ -1 [ZMOD ↑p] k : ℕ hk₀ : 0 < ↑k hk : a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p ⊢ 2 * 0 < p [PROOFSTEP] exact hp.1.pos [GOAL] p : ℕ inst✝ : Fact (Nat.Prime p) a b k : ℕ left✝ : 0 < k hkp : k < p hk : a ^ 2 + b ^ 2 + 1 = k * p ⊢ ↑a ^ 2 + ↑b ^ 2 + 1 = ↑k * ↑p [PROOFSTEP] exact_mod_cast hk [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] have : ∀ f : Fin 4 → ZMod 2, f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i : Fin 4, f i ^ 2 + f (swap i 0 1) ^ 2 = 0 ∧ f (swap i 0 2) ^ 2 + f (swap i 0 3) ^ 2 = 0 := by decide [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m ⊢ ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 [PROOFSTEP] decide [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] set f : Fin 4 → ℤ := ![a, b, c, d] [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] obtain ⟨i, hσ⟩ := this (fun x => ↑(f x)) <| by rw [← @zero_mul (ZMod 2) _ m, ← show ((2 : ℤ) : ZMod 2) = 0 from rfl, ← Int.cast_mul, ← h] simp only [Int.cast_add, Int.cast_pow] rfl [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] ⊢ (fun x => ↑(f x)) 0 ^ 2 + (fun x => ↑(f x)) 1 ^ 2 + (fun x => ↑(f x)) 2 ^ 2 + (fun x => ↑(f x)) 3 ^ 2 = 0 [PROOFSTEP] rw [← @zero_mul (ZMod 2) _ m, ← show ((2 : ℤ) : ZMod 2) = 0 from rfl, ← Int.cast_mul, ← h] [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] ⊢ (fun x => ↑(f x)) 0 ^ 2 + (fun x => ↑(f x)) 1 ^ 2 + (fun x => ↑(f x)) 2 ^ 2 + (fun x => ↑(f x)) 3 ^ 2 = ↑(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) [PROOFSTEP] simp only [Int.cast_add, Int.cast_pow] [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] ⊢ ↑(Matrix.vecCons a ![b, c, d] 0) ^ 2 + ↑(Matrix.vecCons a ![b, c, d] 1) ^ 2 + ↑(Matrix.vecCons a ![b, c, d] 2) ^ 2 + ↑(Matrix.vecCons a ![b, c, d] 3) ^ 2 = ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 [PROOFSTEP] rfl [GOAL] case intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 hσ : ↑(f i) ^ 2 + ↑(f (↑(swap i 0) 1)) ^ 2 = 0 ∧ ↑(f (↑(swap i 0) 2)) ^ 2 + ↑(f (↑(swap i 0) 3)) ^ 2 = 0 ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] set σ := swap i 0 [GOAL] case intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] obtain ⟨x, hx⟩ : (2 : ℤ) ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2 := (CharP.int_cast_eq_zero_iff (ZMod 2) 2 _).1 <| by simpa only [Int.cast_pow, Int.cast_add, Equiv.swap_apply_right, ZMod.pow_card] using hσ.1 [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 ⊢ ↑(f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2) = 0 [PROOFSTEP] simpa only [Int.cast_pow, Int.cast_add, Equiv.swap_apply_right, ZMod.pow_card] using hσ.1 [GOAL] case intro.intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] obtain ⟨y, hy⟩ : (2 : ℤ) ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2 := (CharP.int_cast_eq_zero_iff (ZMod 2) 2 _).1 <| by simpa only [Int.cast_pow, Int.cast_add, ZMod.pow_card] using hσ.2 [GOAL] m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x ⊢ ↑(f (↑σ 2) ^ 2 + f (↑σ 3) ^ 2) = 0 [PROOFSTEP] simpa only [Int.cast_pow, Int.cast_add, ZMod.pow_card] using hσ.2 [GOAL] case intro.intro.intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x y : ℤ hy : f (↑σ 2) ^ 2 + f (↑σ 3) ^ 2 = 2 * y ⊢ ∃ w x y z, w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = m [PROOFSTEP] refine ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, ?_⟩ [GOAL] case intro.intro.intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x y : ℤ hy : f (↑σ 2) ^ 2 + f (↑σ 3) ^ 2 = 2 * y ⊢ ((f (↑σ 0) - f (↑σ 1)) / 2) ^ 2 + ((f (↑σ 0) + f (↑σ 1)) / 2) ^ 2 + ((f (↑σ 2) - f (↑σ 3)) / 2) ^ 2 + ((f (↑σ 2) + f (↑σ 3)) / 2) ^ 2 = m [PROOFSTEP] rw [← Int.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc, ← Int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' two_ne_zero, ← h, mul_add] [GOAL] case intro.intro.intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x y : ℤ hy : f (↑σ 2) ^ 2 + f (↑σ 3) ^ 2 = 2 * y ⊢ 2 * x + 2 * y = a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 [PROOFSTEP] have : (∑ x, f (σ x) ^ 2) = ∑ x, f x ^ 2 := Equiv.sum_comp σ (f · ^ 2) [GOAL] case intro.intro.intro m a b c d : ℤ h : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m this✝ : ∀ (f : Fin 4 → ZMod 2), f 0 ^ 2 + f 1 ^ 2 + f 2 ^ 2 + f 3 ^ 2 = 0 → ∃ i, f i ^ 2 + f (↑(swap i 0) 1) ^ 2 = 0 ∧ f (↑(swap i 0) 2) ^ 2 + f (↑(swap i 0) 3) ^ 2 = 0 f : Fin 4 → ℤ := ![a, b, c, d] i : Fin 4 σ : Perm (Fin 4) := swap i 0 hσ : ↑(f i) ^ 2 + ↑(f (↑σ 1)) ^ 2 = 0 ∧ ↑(f (↑σ 2)) ^ 2 + ↑(f (↑σ 3)) ^ 2 = 0 x : ℤ hx : f (↑σ 0) ^ 2 + f (↑σ 1) ^ 2 = 2 * x y : ℤ hy : f (↑σ 2) ^ 2 + f (↑σ 3) ^ 2 = 2 * y this : ∑ x : Fin 4, f (↑σ x) ^ 2 = ∑ x : Fin 4, f x ^ 2 ⊢ 2 * x + 2 * y = a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 [PROOFSTEP] simpa only [← hx, ← hy, Fin.sum_univ_four, add_assoc] using this [GOAL] p : ℕ hp : Prime p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] have := Fact.mk hp [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] have natAbs_iff {a b c d : ℤ} {k : ℕ} : a.natAbs ^ 2 + b.natAbs ^ 2 + c.natAbs ^ 2 + d.natAbs ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = k := by rw [← @Nat.cast_inj ℤ]; push_cast [sq_abs]; rfl [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) a b c d : ℤ k : ℕ ⊢ natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k [PROOFSTEP] rw [← @Nat.cast_inj ℤ] [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) a b c d : ℤ k : ℕ ⊢ ↑(natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2) = ↑k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k [PROOFSTEP] push_cast [sq_abs] [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) a b c d : ℤ k : ℕ ⊢ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k [PROOFSTEP] rfl [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℕ, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p [GOAL] case hm p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k ⊢ ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p [PROOFSTEP] obtain ⟨a, b, k, hk₀, hkp, hk⟩ := exists_sq_add_sq_add_one_eq_mul p [GOAL] case hm.intro.intro.intro.intro.intro p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k a b k : ℕ hk₀ : 0 < k hkp : k < p hk : a ^ 2 + b ^ 2 + 1 = k * p ⊢ ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p [PROOFSTEP] refine ⟨k, hkp, hk₀, a, b, 1, 0, ?_⟩ [GOAL] case hm.intro.intro.intro.intro.intro p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k a b k : ℕ hk₀ : 0 < k hkp : k < p hk : a ^ 2 + b ^ 2 + 1 = k * p ⊢ a ^ 2 + b ^ 2 + 1 ^ 2 + 0 ^ 2 = k * p [PROOFSTEP] simpa -- Take the minimal possible `m` [GOAL] p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] rcases Nat.findX hm with ⟨m, ⟨hmp, hm₀, a, b, c, d, habcd⟩, hmin⟩ -- If `m = 1`, then we are done [GOAL] case mk.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] rcases(Nat.one_le_iff_ne_zero.2 hm₀.ne').eq_or_gt with rfl | hm₁ [GOAL] case mk.intro.intro.intro.intro.intro.intro.intro.inl p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d : ℕ hmin : ∀ (m : ℕ), m < 1 → ¬(m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p) hmp : 1 < p hm₀ : 0 < 1 habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 1 * p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] use a, b, c, d [GOAL] case h p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d : ℕ hmin : ∀ (m : ℕ), m < 1 → ¬(m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p) hmp : 1 < p hm₀ : 0 < 1 habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 1 * p ⊢ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] simpa using habcd [GOAL] case mk.intro.intro.intro.intro.intro.intro.intro.inr p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] exfalso [GOAL] case mk.intro.intro.intro.intro.intro.intro.intro.inr.h p : ℕ hp : Prime p this : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m ⊢ False [PROOFSTEP] have : NeZero m := ⟨hm₀.ne'⟩ [GOAL] case mk.intro.intro.intro.intro.intro.intro.intro.inr.h p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m ⊢ False [PROOFSTEP] by_cases hm : 2 ∣ m [GOAL] case pos p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : 2 ∣ m ⊢ False [PROOFSTEP] rcases hm with ⟨m, rfl⟩ [GOAL] case pos.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < 2 * m habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m * p hm₁ : 1 < 2 * m this : NeZero (2 * m) ⊢ False [PROOFSTEP] rw [zero_lt_mul_left two_pos] at hm₀ [GOAL] case pos.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m * p hm₁ : 1 < 2 * m this : NeZero (2 * m) ⊢ False [PROOFSTEP] have hm₂ : m < 2 * m := by simpa [two_mul] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m * p hm₁ : 1 < 2 * m this : NeZero (2 * m) ⊢ m < 2 * m [PROOFSTEP] simpa [two_mul] [GOAL] case pos.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 2 * m * p hm₁ : 1 < 2 * m this : NeZero (2 * m) hm₂ : m < 2 * m ⊢ False [PROOFSTEP] apply_fun (Nat.cast : ℕ → ℤ) at habcd [GOAL] case pos.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m hm₁ : 1 < 2 * m this : NeZero (2 * m) hm₂ : m < 2 * m habcd : ↑(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) = ↑(2 * m * p) ⊢ False [PROOFSTEP] push_cast [mul_assoc] at habcd [GOAL] case pos.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m hm₁ : 1 < 2 * m this : NeZero (2 * m) hm₂ : m < 2 * m habcd : ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 = 2 * (↑m * ↑p) ⊢ False [PROOFSTEP] obtain ⟨_, _, _, _, h⟩ := sum_four_squares_of_two_mul_sum_four_squares habcd [GOAL] case pos.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p a b c d m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < 2 * m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : 2 * m < p hm₀ : 0 < m hm₁ : 1 < 2 * m this : NeZero (2 * m) hm₂ : m < 2 * m habcd : ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 = 2 * (↑m * ↑p) w✝³ w✝² w✝¹ w✝ : ℤ h : w✝³ ^ 2 + w✝² ^ 2 + w✝¹ ^ 2 + w✝ ^ 2 = ↑m * ↑p ⊢ False [PROOFSTEP] exact hmin m hm₂ ⟨hm₂.trans hmp, hm₀, _, _, _, _, natAbs_iff.2 h⟩ [GOAL] case neg p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m ⊢ False [PROOFSTEP] obtain ⟨f, hf_lt, hf_mod⟩ : ∃ f : ℕ → ℤ, (∀ x, 2 * (f x).natAbs < m) ∧ ∀ x, (f x : ZMod m) = x [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m ⊢ ∃ f, (∀ (x : ℕ), 2 * natAbs (f x) < m) ∧ ∀ (x : ℕ), ↑(f x) = ↑x [PROOFSTEP] refine ⟨fun x ↦ (x : ZMod m).valMinAbs, fun x ↦ ?_, fun x ↦ (x : ZMod m).coe_valMinAbs⟩ [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m x : ℕ ⊢ 2 * natAbs ((fun x => ZMod.valMinAbs ↑x) x) < m [PROOFSTEP] exact (mul_le_mul' le_rfl (x : ZMod m).natAbs_valMinAbs_le).trans_lt (Nat.mul_div_lt_iff_not_dvd.2 hm) -- Since `|f x| ^ 2 = (f x) ^ 2 ≡ x ^ 2 [ZMOD m]`, we have -- `m ∣ |f a| ^ 2 + |f b| ^ 2 + |f c| ^ 2 + |f d| ^ 2` [GOAL] case neg.intro.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x ⊢ False [PROOFSTEP] obtain ⟨r, hr⟩ : m ∣ (f a).natAbs ^ 2 + (f b).natAbs ^ 2 + (f c).natAbs ^ 2 + (f d).natAbs ^ 2 [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x ⊢ m ∣ natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 [PROOFSTEP] simp only [← Int.coe_nat_dvd, ← ZMod.int_cast_zmod_eq_zero_iff_dvd] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x ⊢ ↑↑(natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2) = 0 [PROOFSTEP] push_cast [hf_mod, sq_abs] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x ⊢ ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 = 0 [PROOFSTEP] norm_cast [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x ⊢ ↑(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) = 0 [PROOFSTEP] simp [habcd] -- The quotient `r` is not zero, because otherwise `f a = f b = f c = f d = 0`, hence -- `m` divides each `a`, `b`, `c`, `d`, thus `m ∣ p` which is impossible. [GOAL] case neg.intro.intro.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r ⊢ False [PROOFSTEP] rcases(zero_le r).eq_or_gt with rfl | hr₀ [GOAL] case neg.intro.intro.intro.inl p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * 0 ⊢ False [PROOFSTEP] replace hr : f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 [GOAL] case hr p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * 0 ⊢ f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 [PROOFSTEP] simpa [and_assoc] using hr [GOAL] case neg.intro.intro.intro.inl p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x hr : f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 ⊢ False [PROOFSTEP] obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩, ⟨c, rfl⟩, ⟨d, rfl⟩⟩ : m ∣ a ∧ m ∣ b ∧ m ∣ c ∧ m ∣ d [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x hr : f a = 0 ∧ f b = 0 ∧ f c = 0 ∧ f d = 0 ⊢ m ∣ a ∧ m ∣ b ∧ m ∣ c ∧ m ∣ d [PROOFSTEP] simp only [← ZMod.nat_cast_zmod_eq_zero_iff_dvd, ← hf_mod, hr, Int.cast_zero] [GOAL] case neg.intro.intro.intro.inl.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x a b c d : ℕ habcd : (m * a) ^ 2 + (m * b) ^ 2 + (m * c) ^ 2 + (m * d) ^ 2 = m * p hr : f (m * a) = 0 ∧ f (m * b) = 0 ∧ f (m * c) = 0 ∧ f (m * d) = 0 ⊢ False [PROOFSTEP] have : m * m ∣ m * p := habcd ▸ ⟨a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2, by ring⟩ [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x a b c d : ℕ habcd : (m * a) ^ 2 + (m * b) ^ 2 + (m * c) ^ 2 + (m * d) ^ 2 = m * p hr : f (m * a) = 0 ∧ f (m * b) = 0 ∧ f (m * c) = 0 ∧ f (m * d) = 0 ⊢ (m * a) ^ 2 + (m * b) ^ 2 + (m * c) ^ 2 + (m * d) ^ 2 = m * m * (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) [PROOFSTEP] ring [GOAL] case neg.intro.intro.intro.inl.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x a b c d : ℕ habcd : (m * a) ^ 2 + (m * b) ^ 2 + (m * c) ^ 2 + (m * d) ^ 2 = m * p hr : f (m * a) = 0 ∧ f (m * b) = 0 ∧ f (m * c) = 0 ∧ f (m * d) = 0 this : m * m ∣ m * p ⊢ False [PROOFSTEP] rw [mul_dvd_mul_iff_left hm₀.ne'] at this [GOAL] case neg.intro.intro.intro.inl.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x a b c d : ℕ habcd : (m * a) ^ 2 + (m * b) ^ 2 + (m * c) ^ 2 + (m * d) ^ 2 = m * p hr : f (m * a) = 0 ∧ f (m * b) = 0 ∧ f (m * c) = 0 ∧ f (m * d) = 0 this : m ∣ p ⊢ False [PROOFSTEP] exact (hp.eq_one_or_self_of_dvd _ this).elim hm₁.ne' hmp.ne [GOAL] case neg.intro.intro.intro.inr p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r ⊢ False [PROOFSTEP] have hrm : r < m [GOAL] case hrm p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r ⊢ r < m [PROOFSTEP] rw [mul_comm] at hr [GOAL] case hrm p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = r * m hr₀ : 0 < r ⊢ r < m [PROOFSTEP] apply lt_of_sum_four_squares_eq_mul hr [GOAL] case hrm.ha p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = r * m hr₀ : 0 < r ⊢ 2 * natAbs (f a) < m [PROOFSTEP] apply hf_lt [GOAL] case hrm.hb p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = r * m hr₀ : 0 < r ⊢ 2 * natAbs (f b) < m [PROOFSTEP] apply hf_lt [GOAL] case hrm.hc p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = r * m hr₀ : 0 < r ⊢ 2 * natAbs (f c) < m [PROOFSTEP] apply hf_lt [GOAL] case hrm.hd p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = r * m hr₀ : 0 < r ⊢ 2 * natAbs (f d) < m [PROOFSTEP] apply hf_lt [GOAL] case neg.intro.intro.intro.inr p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m ⊢ False [PROOFSTEP] rsuffices ⟨w, x, y, z, hw, hx, hy, hz, h⟩ : ∃ w x y z : ℤ, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) [GOAL] case neg.intro.intro.intro.inr.intro.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) ⊢ False [PROOFSTEP] have : (w / m) ^ 2 + (x / m) ^ 2 + (y / m) ^ 2 + (z / m) ^ 2 = ↑(r * p) [GOAL] case this p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) ⊢ (w / ↑m) ^ 2 + (x / ↑m) ^ 2 + (y / ↑m) ^ 2 + (z / ↑m) ^ 2 = ↑(r * p) [PROOFSTEP] refine mul_left_cancel₀ (pow_ne_zero 2 (Nat.cast_ne_zero.2 hm₀.ne')) ?_ [GOAL] case this p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ^ 2 * ((w / ↑m) ^ 2 + (x / ↑m) ^ 2 + (y / ↑m) ^ 2 + (z / ↑m) ^ 2) = ↑m ^ 2 * ↑(r * p) [PROOFSTEP] conv_rhs => rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) | ↑m ^ 2 * ↑(r * p) [PROOFSTEP] rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) | ↑m ^ 2 * ↑(r * p) [PROOFSTEP] rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h] [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) | ↑m ^ 2 * ↑(r * p) [PROOFSTEP] rw [← Nat.cast_pow, ← Nat.cast_mul, sq m, mul_mul_mul_comm, Nat.cast_mul, ← h] [GOAL] case this p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ^ 2 * ((w / ↑m) ^ 2 + (x / ↑m) ^ 2 + (y / ↑m) ^ 2 + (z / ↑m) ^ 2) = w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 [PROOFSTEP] simp only [mul_add, ← mul_pow, Int.mul_ediv_cancel', *] [GOAL] case neg.intro.intro.intro.inr.intro.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) this : (w / ↑m) ^ 2 + (x / ↑m) ^ 2 + (y / ↑m) ^ 2 + (z / ↑m) ^ 2 = ↑(r * p) ⊢ False [PROOFSTEP] rw [← natAbs_iff] at this [GOAL] case neg.intro.intro.intro.inr.intro.intro.intro.intro.intro.intro.intro.intro p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m w x y z : ℤ hw : ↑m ∣ w hx : ↑m ∣ x hy : ↑m ∣ y hz : ↑m ∣ z h : w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) this : natAbs (w / ↑m) ^ 2 + natAbs (x / ↑m) ^ 2 + natAbs (y / ↑m) ^ 2 + natAbs (z / ↑m) ^ 2 = r * p ⊢ False [PROOFSTEP] exact hmin r hrm ⟨hrm.trans hmp, hr₀, _, _, _, _, this⟩ -- To do the last step, we apply the Euler's four square identity once more [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m ⊢ ∃ w x y z, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) [PROOFSTEP] replace hr : (f b) ^ 2 + (f a) ^ 2 + (f d) ^ 2 + (-f c) ^ 2 = ↑(m * r) [GOAL] case hr p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m ⊢ f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) [PROOFSTEP] rw [← natAbs_iff, natAbs_neg, ← hr] [GOAL] case hr p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr : natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 = m * r hr₀ : 0 < r hrm : r < m ⊢ natAbs (f b) ^ 2 + natAbs (f a) ^ 2 + natAbs (f d) ^ 2 + natAbs (f c) ^ 2 = natAbs (f a) ^ 2 + natAbs (f b) ^ 2 + natAbs (f c) ^ 2 + natAbs (f d) ^ 2 [PROOFSTEP] ac_rfl [GOAL] p : ℕ hp : Prime p this✝ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) ⊢ ∃ w x y z, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) [PROOFSTEP] have := congr_arg₂ (· * Nat.cast ·) hr habcd [GOAL] p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (fun x x_1 => x * ↑x_1) (f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2) (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) = (fun x x_1 => x * ↑x_1) (↑(m * r)) (m * p) ⊢ ∃ w x y z, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) [PROOFSTEP] simp only [← _root_.euler_four_squares, Nat.cast_add, Nat.cast_pow] at this [GOAL] p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ∃ w x y z, ↑m ∣ w ∧ ↑m ∣ x ∧ ↑m ∣ y ∧ ↑m ∣ z ∧ w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2 = ↑(m * r) * ↑(m * p) [PROOFSTEP] refine ⟨_, _, _, _, ?_, ?_, ?_, ?_, this⟩ [GOAL] case refine_1 p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ∣ f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d [PROOFSTEP] simp [← ZMod.int_cast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] [GOAL] case refine_2 p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ∣ f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c [PROOFSTEP] suffices : ((a : ZMod m) ^ 2 + (b : ZMod m) ^ 2 + (c : ZMod m) ^ 2 + (d : ZMod m) ^ 2) = 0 [GOAL] case refine_2 p : ℕ hp : Prime p this✝² : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝¹ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this✝ : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) this : ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 = 0 ⊢ ↑m ∣ f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c [PROOFSTEP] simpa [← ZMod.int_cast_zmod_eq_zero_iff_dvd, hf_mod, sq, add_comm, add_assoc, add_left_comm] using this [GOAL] case this p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑a ^ 2 + ↑b ^ 2 + ↑c ^ 2 + ↑d ^ 2 = 0 [PROOFSTEP] norm_cast [GOAL] case this p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑(a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) = 0 [PROOFSTEP] simp [habcd] [GOAL] case refine_3 p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ∣ f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b [PROOFSTEP] simp [← ZMod.int_cast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] [GOAL] case refine_4 p : ℕ hp : Prime p this✝¹ : Fact (Prime p) natAbs_iff : ∀ {a b c d : ℤ} {k : ℕ}, natAbs a ^ 2 + natAbs b ^ 2 + natAbs c ^ 2 + natAbs d ^ 2 = k ↔ a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = ↑k hm✝ : ∃ m, m < p ∧ 0 < m ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p m : ℕ hmin : ∀ (m_1 : ℕ), m_1 < m → ¬(m_1 < p ∧ 0 < m_1 ∧ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m_1 * p) hmp : m < p hm₀ : 0 < m a b c d : ℕ habcd : a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * p hm₁ : 1 < m this✝ : NeZero m hm : ¬2 ∣ m f : ℕ → ℤ hf_lt : ∀ (x : ℕ), 2 * natAbs (f x) < m hf_mod : ∀ (x : ℕ), ↑(f x) = ↑x r : ℕ hr₀ : 0 < r hrm : r < m hr : f b ^ 2 + f a ^ 2 + f d ^ 2 + (-f c) ^ 2 = ↑(m * r) this : (f b * ↑a - f a * ↑b - f d * ↑c - -f c * ↑d) ^ 2 + (f b * ↑b + f a * ↑a + f d * ↑d - -f c * ↑c) ^ 2 + (f b * ↑c - f a * ↑d + f d * ↑a + -f c * ↑b) ^ 2 + (f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a) ^ 2 = ↑(m * r) * ↑(m * p) ⊢ ↑m ∣ f b * ↑d + f a * ↑c - f d * ↑b + -f c * ↑a [PROOFSTEP] simp [← ZMod.int_cast_zmod_eq_zero_iff_dvd, hf_mod, mul_comm] [GOAL] n : ℕ ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n [PROOFSTEP] induction n using Nat.recOnMul with | h0 => exact ⟨0, 0, 0, 0, rfl⟩ | h1 => exact ⟨1, 0, 0, 0, rfl⟩ | hp p hp => exact hp.sum_four_squares | h m n hm hn => rcases hm with ⟨a, b, c, d, rfl⟩ rcases hn with ⟨w, x, y, z, rfl⟩ exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩ [GOAL] n : ℕ ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n [PROOFSTEP] induction n using Nat.recOnMul with | h0 => exact ⟨0, 0, 0, 0, rfl⟩ | h1 => exact ⟨1, 0, 0, 0, rfl⟩ | hp p hp => exact hp.sum_four_squares | h m n hm hn => rcases hm with ⟨a, b, c, d, rfl⟩ rcases hn with ⟨w, x, y, z, rfl⟩ exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩ [GOAL] case h0 ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 0 [PROOFSTEP] | h0 => exact ⟨0, 0, 0, 0, rfl⟩ [GOAL] case h0 ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 0 [PROOFSTEP] exact ⟨0, 0, 0, 0, rfl⟩ [GOAL] case h1 ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 1 [PROOFSTEP] | h1 => exact ⟨1, 0, 0, 0, rfl⟩ [GOAL] case h1 ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = 1 [PROOFSTEP] exact ⟨1, 0, 0, 0, rfl⟩ [GOAL] case hp p : ℕ hp : Prime p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] | hp p hp => exact hp.sum_four_squares [GOAL] case hp p : ℕ hp : Prime p ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = p [PROOFSTEP] exact hp.sum_four_squares [GOAL] case h m n : ℕ hm : ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m hn : ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * n [PROOFSTEP] | h m n hm hn => rcases hm with ⟨a, b, c, d, rfl⟩ rcases hn with ⟨w, x, y, z, rfl⟩ exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩ [GOAL] case h m n : ℕ hm : ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m hn : ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n ⊢ ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = m * n [PROOFSTEP] rcases hm with ⟨a, b, c, d, rfl⟩ [GOAL] case h.intro.intro.intro.intro n : ℕ hn : ∃ a b c d, a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2 = n a b c d : ℕ ⊢ ∃ a_1 b_1 c_1 d_1, a_1 ^ 2 + b_1 ^ 2 + c_1 ^ 2 + d_1 ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * n [PROOFSTEP] rcases hn with ⟨w, x, y, z, rfl⟩ [GOAL] case h.intro.intro.intro.intro.intro.intro.intro.intro a b c d w x y z : ℕ ⊢ ∃ a_1 b_1 c_1 d_1, a_1 ^ 2 + b_1 ^ 2 + c_1 ^ 2 + d_1 ^ 2 = (a ^ 2 + b ^ 2 + c ^ 2 + d ^ 2) * (w ^ 2 + x ^ 2 + y ^ 2 + z ^ 2) [PROOFSTEP] exact ⟨_, _, _, _, euler_four_squares _ _ _ _ _ _ _ _⟩
-- Copyright (c) 2017, Matthew Morris -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. module Main fizzbuzz : Integer -> String fizzbuzz n with (mod n 3, mod n 5) fizzbuzz n | (0, 0) = "fizzbuzz" fizzbuzz n | (0, _) = "fizz" fizzbuzz n | (_, 0) = "buzz" fizzbuzz n | _ = show n main : IO () main = traverse_ putStrLn $ map fizzbuzz [1..100]
From trillium.prelude Require Import finitary. From iris.proofmode Require Import coq_tactics reduction spec_patterns. From aneris.aneris_lang Require Import lang. From iris.base_logic.lib Require Import invariants. From aneris.aneris_lang Require Import tactics proofmode adequacy. From aneris.aneris_lang.program_logic Require Import aneris_weakestpre aneris_adequacy aneris_lifting. From aneris.aneris_lang.lib Require Import serialization.serialization_proof lock_proof. From actris.channel Require Import proto. From aneris.examples.reliable_communication Require Import user_params client_server_code. From aneris.examples.reliable_communication.spec Require Import resources api_spec. (** * Tactics for proving contractiveness of protocols *) Ltac f_dist_le := match goal with | H : _ ≡{?n}≡ _ |- _ ≡{?n'}≡ _ => apply (dist_le n); [apply H|lia] end. Ltac solve_proto_contractive := solve_proper_core ltac:(fun _ => first [f_contractive; simpl in * | f_equiv | f_dist_le]). (** * Normalization of protocols *) Class ActionDualIf (d : bool) (a1 a2 : action) := dual_action_if : a2 = if d then action_dual a1 else a1. Global Hint Mode ActionDualIf ! ! - : typeclass_instances. Global Instance action_dual_if_false a : ActionDualIf false a a := eq_refl. Global Instance action_dual_if_true_send : ActionDualIf true Send Recv := eq_refl. Global Instance action_dual_if_true_recv : ActionDualIf true Recv Send := eq_refl. Class ProtoNormalize {Σ} (d : bool) (p : iProto Σ) (pas : list (bool * iProto Σ)) (q : iProto Σ) := proto_normalize : ⊢ iProto_dual_if d p <++> foldr (iProto_app ∘ uncurry iProto_dual_if) END%proto pas ⊑ q. Global Hint Mode ProtoNormalize ! ! ! ! - : typeclass_instances. Arguments ProtoNormalize {_} _ _%proto _%proto _%proto. Notation ProtoUnfold p1 p2 := (∀ d pas q, ProtoNormalize d p2 pas q → ProtoNormalize d p1 pas q). Class MsgNormalize {Σ} (d : bool) (m1 : iMsg Σ) (pas : list (bool * iProto Σ)) (m2 : iMsg Σ) := msg_normalize a : ProtoNormalize d (<a> m1) pas (<(if d then action_dual a else a)> m2). Global Hint Mode MsgNormalize ! ! ! ! - : typeclass_instances. Arguments MsgNormalize {_} _ _%msg _%msg _%msg. Section classes. Context `{!anerisG Mdl Σ, !@Chan_mapsto_resource Σ}. Implicit Types TT : tele. Implicit Types p : iProto Σ. Implicit Types m : iMsg Σ. Implicit Types P : iProp Σ. Lemma proto_unfold_eq p1 p2 : p1 ≡ p2 → ProtoUnfold p1 p2. Proof. rewrite /ProtoNormalize=> Hp d pas q. by rewrite Hp. Qed. Global Instance proto_normalize_done p : ProtoNormalize false p [] p | 0. Proof. rewrite /ProtoNormalize /= right_id. auto. Qed. Global Instance proto_normalize_done_dual p : ProtoNormalize true p [] (iProto_dual p) | 0. Proof. rewrite /ProtoNormalize /= right_id. auto. Qed. Global Instance proto_normalize_done_dual_end : ProtoNormalize (Σ:=Σ) true END [] END | 0. Proof. rewrite /ProtoNormalize /= right_id iProto_dual_end. auto. Qed. Global Instance proto_normalize_dual d p pas q : ProtoNormalize (negb d) p pas q → ProtoNormalize d (iProto_dual p) pas q. Proof. rewrite /ProtoNormalize. by destruct d; rewrite /= ?involutive. Qed. Global Instance proto_normalize_app_l d p1 p2 pas q : ProtoNormalize d p1 ((d,p2) :: pas) q → ProtoNormalize d (p1 <++> p2) pas q. Proof. rewrite /ProtoNormalize /=. rewrite assoc. by destruct d; by rewrite /= ?iProto_dual_app. Qed. Global Instance proto_normalize_end d d' p pas q : ProtoNormalize d p pas q → ProtoNormalize d' END ((d,p) :: pas) q | 0. Proof. rewrite /ProtoNormalize /=. destruct d'; by rewrite /= ?iProto_dual_end left_id. Qed. Global Instance proto_normalize_app_r d p1 p2 pas q : ProtoNormalize d p2 pas q → ProtoNormalize false p1 ((d,p2) :: pas) (p1 <++> q) | 0. Proof. rewrite /ProtoNormalize /= => Hp. by iApply iProto_le_app. Qed. Global Instance proto_normalize_app_r_dual d p1 p2 pas q : ProtoNormalize d p2 pas q → ProtoNormalize true p1 ((d,p2) :: pas) (iProto_dual p1 <++> q) | 0. Proof. rewrite /ProtoNormalize /= => Hp. by iApply iProto_le_app. Qed. Global Instance msg_normalize_base d v P p q pas : ProtoNormalize d p pas q → MsgNormalize d (MSG v {{ P }}; p) pas (MSG v {{ P }}; q). Proof. rewrite /MsgNormalize /ProtoNormalize=> Hp a. iApply iProto_le_trans; [|by iApply iProto_le_base]. destruct d; by rewrite /= ?iProto_dual_message ?iMsg_dual_base iProto_app_message iMsg_app_base. Qed. Global Instance msg_normalize_exist {A} d (m1 m2 : A → iMsg Σ) pas : (∀ x, MsgNormalize d (m1 x) pas (m2 x)) → MsgNormalize d (∃ x, m1 x) pas (∃ x, m2 x). Proof. rewrite /MsgNormalize /ProtoNormalize=> Hp a. destruct d, a; simpl in *; rewrite ?iProto_dual_message ?iMsg_dual_exist ?iProto_app_message ?iMsg_app_exist /=; iIntros (x); iExists x; first [move: (Hp x Send); by rewrite ?iProto_dual_message ?iProto_app_message |move: (Hp x Recv); by rewrite ?iProto_dual_message ?iProto_app_message]. Qed. Global Instance proto_normalize_message d a1 a2 m1 m2 pas : ActionDualIf d a1 a2 → MsgNormalize d m1 pas m2 → ProtoNormalize d (<a1> m1) pas (<a2> m2). Proof. by rewrite /ActionDualIf /MsgNormalize /ProtoNormalize=> ->. Qed. Global Instance proto_normalize_swap {TT1 TT2} d a m m' (tv1 : TT1 -t> val) (tP1 : TT1 -t> iProp Σ) (tm1 : TT1 -t> iMsg Σ) (tv2 : TT2 -t> val) (tP2 : TT2 -t> iProp Σ) (tp : TT1 -t> TT2 -t> iProto Σ) pas : ActionDualIf d a Recv → MsgNormalize d m pas m' → MsgTele m' tv1 tP1 (tele_bind (λ.. x1, <!> tele_app tm1 x1))%proto → (∀.. x1, MsgTele (tele_app tm1 x1) tv2 tP2 (tele_app tp x1)) → ProtoNormalize d (<a> m) pas (<!.. x2> MSG tele_app tv2 x2 {{ tele_app tP2 x2 }}; <?.. x1> MSG tele_app tv1 x1 {{ tele_app tP1 x1 }}; tele_app (tele_app tp x1) x2) | 1. Proof. rewrite /ActionDualIf /MsgNormalize /ProtoNormalize /MsgTele. rewrite tforall_forall=> Ha Hm Hm' Hm''. iApply iProto_le_trans; [iApply Hm|]. rewrite Hm' -Ha. clear Ha Hm Hm'. iApply iProto_le_texist_elim_l; iIntros (x1). iApply iProto_le_texist_elim_r; iIntros (x2). rewrite !tele_app_bind Hm'' {Hm''}. iApply iProto_le_trans; [iApply iProto_le_base; iApply (iProto_le_texist_intro_l _ x2)|]. iApply iProto_le_trans; [|iApply iProto_le_base; iApply (iProto_le_texist_intro_r _ x1)]; simpl. iApply iProto_le_base_swap. Qed. (** Automatically perform normalization of protocols in the proof mode when using [iAssumption] and [iFrame]. *) Global Instance mapsto_proto_from_assumption ip q c p1 p2 ser : ProtoNormalize false p1 [] p2 → FromAssumption q (c ↣{ip, ser } p1) (c ↣{ip, ser } p2). Proof. rewrite /FromAssumption /ProtoNormalize /= right_id. rewrite bi.intuitionistically_if_elim. iIntros (?) "H". by iApply (chan_mapsto_le with "H"). Qed. Global Instance mapsto_proto_from_frame ip q c p1 p2 ser: ProtoNormalize false p1 [] p2 → Frame q (c ↣{ip, ser} p1) (c ↣{ip, ser } p2) True. Proof. rewrite /Frame /ProtoNormalize /= right_id. rewrite bi.intuitionistically_if_elim. iIntros (?) "[H _]". by iApply (chan_mapsto_le with "H"). Qed. End classes. (** * Symbolic execution tactics *) (* TODO: Maybe strip laters from other hypotheses in the future? *) Lemma tac_wp_recv `{ !anerisG Mdl Σ, !lockG Σ} (chn : @Chan_mapsto_resource Σ) `{ Reliable_communication_Specified_API_session } {TT : tele} Δ i j K ip ser c p m tv tP tP' tp Φ : envs_lookup i Δ = Some (false, c ↣{ip, ser} p)%I → ProtoNormalize false p [] (<?> m) → MsgTele m tv tP tp → (* SerializerOf serzer sertion → *) (∀.. x, MaybeIntoLaterN false 1 (tele_app tP x) (tele_app tP' x)) → let Δ' := envs_delete false i false Δ in (∀.. x : TT, match envs_app false (Esnoc (Esnoc Enil j (tele_app tP' x)) i (c ↣{ip, ser} tele_app tp x)) Δ' with | Some Δ'' => envs_entails Δ'' (WP fill K (of_val (tele_app tv x)) @[ip] {{ Φ }}) | None => False end) → envs_entails Δ (WP fill K (recv c) @[ip] {{ Φ }}). Proof. rewrite envs_entails_unseal /ProtoNormalize /MsgTele /MaybeIntoLaterN /=. rewrite !tforall_forall right_id. intros ? Hp Hm HP HΦ. rewrite envs_lookup_sound //; simpl. assert (c ↣{ip, ser} p ⊢ c ↣{ip, ser} <?.. x> MSG tele_app tv x {{ ▷ tele_app tP' x }}; tele_app tp x)%proto as ->. { iIntros "Hc". iApply (chan_mapsto_le with "Hc"). iIntros "!>". iApply iProto_le_trans; [iApply Hp|rewrite Hm]. iApply iProto_le_texist_elim_l; iIntros (x). iApply iProto_le_trans; [|iApply (iProto_le_texist_intro_r _ x)]; simpl. iIntros "H". by iDestruct (HP with "H") as "$". } rewrite -aneris_wp_bind. eapply bi.wand_apply; [by iApply (RCSpec_recv_spec _ c (tele_app tv) (tele_app tP') (tele_app tp) ip)|f_equiv; first done]. rewrite -bi.later_intro; apply bi.forall_intro=> x. specialize (HΦ x). destruct (envs_app _ _) as [Δ'|] eqn:HΔ'=> //. rewrite envs_app_sound //; simpl. by rewrite right_id HΦ. Qed. Tactic Notation "wp_recv_core" tactic3(tac_intros) "as" tactic3(tac) := let solve_mapsto _ := let c := match goal with |- _ = Some (_, (?c ↣{_, _} _)%I) => c end in iAssumptionCore || fail "wp_recv: cannot find" c "↣ ? @ ?" in wp_pures; let Hnew := iFresh in lazymatch goal with | |- envs_entails _ (aneris_wp ?ip ?E ?e ?Q) => first [reshape_expr e ltac:(fun K e' => eapply (tac_wp_recv _ _ _ Hnew K)) |fail 1 "wp_recv: cannot find 'recv' in" e]; [solve_mapsto () |iSolveTC || fail 1 "wp_recv: protocol not of the shape <?>" |iSolveTC || fail 1 "wp_recv: cannot convert to telescope" |iSolveTC |pm_reduce; simpl; tac_intros; tac Hnew; wp_finish] | _ => fail "wp_recv: not a 'wp'" end. Tactic Notation "wp_recv" "as" constr(pat) := wp_recv_core (idtac) as (fun H => iDestructHyp H as pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) simple_intropattern(x7) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 x7 ) pat). Tactic Notation "wp_recv" "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) simple_intropattern(x7) simple_intropattern(x8) ")" constr(pat) := wp_recv_core (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 x7 x8 ) pat). Tactic Notation "wp_recv_core_chan" constr(H) tactic3(tac_intros) "as" tactic3(tac) := let solve_mapsto _ := let c := match goal with |- _ = Some (_, (?c ↣{_, _} _)%I) => c end in iAssumptionCore || fail "wp_recv: cannot find" c "↣ ? @ ?" in wp_pures; let Hnew := iFresh in lazymatch goal with | |- envs_entails _ (aneris_wp ?ip ?E ?e ?Q) => first [reshape_expr e ltac:(fun K e' => eapply (tac_wp_recv H _ _ Hnew K)) |fail 1 "wp_recv: cannot find 'recv' in" e]; [solve_mapsto () |iSolveTC || fail 1 "wp_recv: protocol not of the shape <?>" |iSolveTC || fail 1 "wp_recv: cannot convert to telescope" |iSolveTC |pm_reduce; simpl; tac_intros; tac Hnew; wp_finish] | _ => fail "wp_recv: not a 'wp'" end. Tactic Notation "wp_recv_chan" constr(chn) "as" constr(pat) := wp_recv_core_chan (chn) (idtac) as (fun H => iDestructHyp H as pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) simple_intropattern(x7) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 x7 ) pat). Tactic Notation "wp_recv_chan" constr(chn) "(" simple_intropattern_list(xs) ")" "as" "(" simple_intropattern(x1) simple_intropattern(x2) simple_intropattern(x3) simple_intropattern(x4) simple_intropattern(x5) simple_intropattern(x6) simple_intropattern(x7) simple_intropattern(x8) ")" constr(pat) := wp_recv_core_chan (chn) (intros xs) as (fun H => iDestructHyp H as ( x1 x2 x3 x4 x5 x6 x7 x8 ) pat). Lemma tac_wp_send `{ !anerisG Mdl Σ, !lockG Σ} (chn : @Chan_mapsto_resource Σ) `{ @Reliable_communication_Specified_API_session _ _ _ chn } (* add `{!ChannelTokens}. TODO: add later when stated w.r.t. the API. *) {TT : tele} Δ neg i js K ip ser c v p m tv tP tp Φ : envs_lookup i Δ = Some (false, c ↣{ip, ser} p)%I → ProtoNormalize false p [] (<!> m) → MsgTele m tv tP tp → Serializable ser v → let Δ' := envs_delete false i false Δ in (∃.. x : TT, match envs_split (if neg is true then base.Right else base.Left) js Δ' with | Some (Δ1,Δ2) => match envs_app false (Esnoc Enil i (c ↣{ip, ser} tele_app tp x)) Δ2 with | Some Δ2' => v = tele_app tv x ∧ envs_entails Δ1 (tele_app tP x) ∧ envs_entails Δ2' (WP fill K (of_val #()) @[ip] {{ Φ }}) | None => False end | None => False end) → envs_entails Δ (WP fill K (send c v) @[ip] {{ Φ }}). Proof. rewrite envs_entails_unseal /ProtoNormalize /MsgTele /= right_id texist_exist. intros ? Hp Hm Hser [x HΦ]. rewrite (envs_lookup_sound _ i) //; simpl. destruct (envs_split _ _ _) as [[Δ1 Δ2]|] eqn:? => //. destruct (envs_app _ _ _) as [Δ2'|] eqn:? => //. rewrite envs_split_sound //. rewrite (envs_app_sound Δ2) //; simpl. destruct HΦ as (-> & -> & ->). rewrite right_id assoc. assert (c ↣{ip, ser} p ⊢ c ↣{ip,ser} <!.. (x : TT)> MSG tele_app tv x {{ tele_app tP x }}; tele_app tp x)%proto as ->. { iIntros "Hc". iApply (chan_mapsto_le with "Hc"); iIntros "!>". iApply iProto_le_trans; [iApply Hp|]. by rewrite Hm. } eapply bi.wand_apply. { rewrite -aneris_wp_bind. iApply RCSpec_send_spec_tele. } rewrite -bi.later_intro. iFrame. iIntros "((Hc & Hc') & HΦ)". iFrame "#∗". iFrame. done. Qed. (* TODO: Handle mismatched values better *) Tactic Notation "wp_send_core" tactic3(tac_exist) "with" constr(pat) := let solve_mapsto _ := let c := match goal with |- _ = Some (_, (?c ↣{_,_} _)%I) => c end in iAssumptionCore || fail "wp_send: cannot find" c "↣ ? @ ?" in let solve_serializer _ := let c := match goal with |- _ = Serializable ?c ?v => c end in iAssumptionCore || fail "wp_send: cannot solve serializer" in let solve_done d := lazymatch d with | true => done || let Q := match goal with |- envs_entails _ ?Q => Q end in fail "wp_send: cannot solve" Q "using done" | false => idtac end in lazymatch spec_pat.parse pat with | [SGoal (SpecGoal GSpatial ?neg ?Hs_frame ?Hs ?d)] => let Hs' := eval cbv in (if neg then Hs else Hs_frame ++ Hs) in wp_pures; lazymatch goal with | |- envs_entails _ (aneris_wp ?ip ?E ?e ?Q) => first [reshape_expr e ltac:(fun K e' => eapply (tac_wp_send _ _ neg _ Hs' K)) |fail 1 "wp_send: cannot find 'send' in" e]; [solve_mapsto () |iSolveTC || fail 1 "wp_send: protocol not of the shape <!>" |iSolveTC || fail 1 "wp_send: cannot convert to telescope" (* |try solve_serializer () *) (* |iSolveTC || fail 1 "wp_send: serializer does not match" *) |try (simplify_eq; iSolveTC) (* Serializer happens here *) |pm_reduce; simpl; tac_exist; repeat lazymatch goal with | |- ∃ _, _ => eexists _ end; lazymatch goal with | |- False => fail "wp_send:" Hs' "not found" | _ => notypeclasses refine (conj _ (conj _ _)); [try (reflexivity); by simplify_eq /= |iFrame Hs_frame; solve_done d |wp_finish] end || fail 1 "wp_send: value type mismatch (likely)"] | _ => fail "wp_send: not a 'wp'" end | _ => fail "wp_send: only a single goal spec pattern supported" end. Tactic Notation "wp_send" "with" constr(pat) := wp_send_core (idtac) with pat. Tactic Notation "wp_send" "(" uconstr(x1) ")" "with" constr(pat) := wp_send_core (eexists x1) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3; eexists x4) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) uconstr(x5) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) uconstr(x7) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6; eexists x7) with pat. Tactic Notation "wp_send" "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) uconstr(x7) uconstr(x8) ")" "with" constr(pat) := wp_send_core (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6; eexists x7; eexists x8) with pat. (* TODO: Handle mismatched values better *) Tactic Notation "wp_send_core_chan" constr(H) tactic3(tac_exist) "with" constr(pat) := let solve_mapsto _ := let c := match goal with |- _ = Some (_, (?c ↣{_,_} _)%I) => c end in iAssumptionCore || fail "wp_send: cannot find" c "↣ ? @ ?" in let solve_serializer _ := let c := match goal with |- _ = Serializable ?c ?v => c end in iAssumptionCore || fail "wp_send: cannot solve serializer" in let solve_done d := lazymatch d with | true => done || let Q := match goal with |- envs_entails _ ?Q => Q end in fail "wp_send: cannot solve" Q "using done" | false => idtac end in lazymatch spec_pat.parse pat with | [SGoal (SpecGoal GSpatial ?neg ?Hs_frame ?Hs ?d)] => let Hs' := eval cbv in (if neg then Hs else Hs_frame ++ Hs) in wp_pures; lazymatch goal with | |- envs_entails _ (aneris_wp ?ip ?E ?e ?Q) => first [reshape_expr e ltac:(fun K e' => eapply (tac_wp_send H _ neg _ Hs' K)) |fail 1 "wp_send: cannot find 'send' in" e]; [solve_mapsto () |iSolveTC || fail 1 "wp_send: protocol not of the shape <!>" |iSolveTC || fail 1 "wp_send: cannot convert to telescope" (* |try solve_serializer () *) (* |iSolveTC || fail 1 "wp_send: serializer does not match" *) |try (simplify_eq; iSolveTC) (* Serializer happens here *) |pm_reduce; simpl; tac_exist; repeat lazymatch goal with | |- ∃ _, _ => eexists _ end; lazymatch goal with | |- False => fail "wp_send:" Hs' "not found" | _ => notypeclasses refine (conj _ (conj _ _)); [try (reflexivity); by simplify_eq /= |iFrame Hs_frame; solve_done d |wp_finish] end || fail 1 "wp_send: value type mismatch (likely)"] | _ => fail "wp_send: not a 'wp'" end | _ => fail "wp_send: only a single goal spec pattern supported" end. Tactic Notation "wp_send_chan" constr(chn) "with" constr(pat) := wp_send_core_chan (chn) (idtac) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3; eexists x4) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) uconstr(x5) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) uconstr(x7) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6; eexists x7) with pat. Tactic Notation "wp_send_chan" constr(chn) "(" uconstr(x1) uconstr(x2) uconstr(x3) uconstr(x4) ")" uconstr(x5) uconstr(x6) uconstr(x7) uconstr(x8) ")" "with" constr(pat) := wp_send_core_chan (chn) (eexists x1; eexists x2; eexists x3; eexists x4; eexists x5; eexists x6; eexists x7; eexists x8) with pat. Definition int_client v : val := λ: "c", send "c" v;; recv "c". Section test. Context `{ !anerisG Mdl Σ, !lockG Σ, !@Chan_mapsto_resource Σ, !Reliable_communication_Specified_API_session _}. Definition int_proto : iProto Σ := (<! (x:Z)> MSG #x ; <?> MSG #(x+2) ; END)%proto. Lemma int_client_spec ip v c : v = #40 → {{{ c ↣{ip, int_serialization} int_proto }}} int_client v c @[ip] {{{ RET #42; True }}}. Proof. iIntros (Heq Φ) "Hc HΦ". wp_lam. wp_send with "[//]". wp_recv_chan H as "_". by iApply "HΦ". Qed. End test. Definition int_bool_client : val := λ: "c", send "c" (InjLV (#40));; recv "c". Definition is_zero (x:Z) : bool := match x with | Z0 => true | _ => false end. Section test. Context `{ !anerisG Mdl Σ, !lockG Σ, !@Chan_mapsto_resource Σ, !Reliable_communication_Specified_API_session _ }. Definition int_bool_sertion := sum_serialization int_serialization bool_serialization. Definition int_bool_proto : iProto Σ := (<! (x:Z)> MSG InjLV #(x) ; <?> MSG InjRV #(is_zero x) ; END)%proto. Lemma int_bool_client_spec ip c : {{{ c ↣{ip, int_bool_sertion} int_bool_proto }}} int_bool_client c @[ip] {{{ RET InjRV #false; True }}}. Proof. iIntros (Φ) "Hc HΦ". wp_lam. wp_send with "[//]". wp_pures. wp_recv as "_". by iApply "HΦ". Qed. End test. Definition int_client_two_channels v : val := λ: "c1" "c2", send "c1" v;; recv "c1";; send "c2" v;; recv "c2". Section test. Context `{ !anerisG Mdl Σ, !lockG Σ, !@Chan_mapsto_resource Σ, !Reliable_communication_Specified_API_session _}. Definition int_proto2 : iProto Σ := (<! (x:Z)> MSG #x ; <?> MSG #(x+2) ; END)%proto. Lemma int_client_two_channels_spec ip v c1 c2 : v = #40 → {{{ c1 ↣{ip, int_serialization} int_proto2 ∗ c2 ↣{ip, int_serialization} int_proto2 }}} int_client_two_channels v c1 c2 @[ip] {{{ RET #42; True }}}. Proof. iIntros (Heq Φ) "(Hc1 & Hc2) HΦ". wp_lam. wp_send with "[//]". wp_recv as "_". wp_send with "[//]". wp_recv as "_". by iApply "HΦ". Qed. End test. (* Definition int_client_two_channels_two_instances *) (* v : val := *) (* λ: "c1" "c2", (send) "c1" v;; (recv) "c1";; (send) "c2" v;; (recv) "c2". *) (* Section test. *) (* Context `{ !anerisG Mdl Σ, *) (* !lockG Σ, *) (* x: @Chan_mapsto_resource Σ, *) (* y : @Chan_mapsto_resource Σ}. *) (* Context `{ *) (* !Reliable_communication_Specified_API_session x, *) (* !Reliable_communication_Specified_API_session y}. *) (* Lemma int_client_two_channels_spec_two_instances ip v c1 c2 : *) (* v = #40 → *) (* {{{ c1 ↣{ip, int_serialization} int_proto2 ∗ *) (* c2 ↣{ip, int_serialization} int_proto2 }}} *) (* int_client_two_channels_two_instances v c1 c2 @[ip] *) (* {{{ RET #42; True }}}. *) (* Proof. *) (* Set Printing Implicit. *) (* iIntros (Heq Φ) "(Hc1 & Hc2) HΦ". *) (* wp_lam. *) (* wp_pures. *) (* wp_send with "[//]". *) (* wp_recv as "_". *) (* wp_pures. *) (* wp_send with "[//]". *) (* wp_recv as "_". *) (* by iApply "HΦ". *) (* Qed. *) (* End test. *)
theory TreeTravers imports Main begin (* We define a new data type `'a tree` which is for binary tree, where both leafs and nodes have a value *) datatype 'a tree = Tip "'a" | Node "'a" "'a tree" "'a tree" (* We define a property called preOrder which takes a tree and returns a list with the value at the start. *) primrec preOrder :: "'a tree \<Rightarrow> 'a list" where "preOrder (Tip a) = [a]" | "preOrder (Node f x y) = f#((preOrder x)@(preOrder y))" (* We define a property called postOrder which takes a tree and returns a list with the value at the end. *) primrec postOrder :: "'a tree \<Rightarrow> 'a list" where "postOrder (Tip a) = [a]" | "postOrder (Node f x y) = (postOrder x)@(postOrder y)@[f]" (* We define a property called inOrder which takes a tree and returns a list with the value at the in location. *) primrec inOrder :: "'a tree \<Rightarrow> 'a list" where "inOrder (Tip a) = [a]" | "inOrder (Node f x y) = (inOrder x)@[f]@(inOrder y)" (* We define a property called mirror which takes a tree and returns a tree with ever left leaf swapped with the right leaf. *) primrec mirror :: "'a tree \<Rightarrow> 'a tree" where "mirror (Tip a) = (Tip a)" | "mirror (Node f x y) = (Node f (mirror y) (mirror x))" (* Now we will prove that by converting a tree in to a list and then reversing it is the same as mirroing a tree and then converting it into a list. *) (* We will do it for preOrder, we will apply induction tactic on the tree using auto *) theorem "preOrder (mirror t) = rev (postOrder t)" apply (induct_tac t) apply auto done (* We will do it for postOrder, we will apply induction tactic on the tree using auto *) theorem "postOrder (mirror t) = rev (preOrder t)" apply (induct_tac t) apply auto done (* We will do it for inOrder, we will apply induction tactic on the tree using auto *) theorem "inOrder (mirror t) = rev (inOrder t)" apply (induct_tac t) apply auto done end
REBOL [ System: "REBOL [R3] Language Interpreter and Run-time Environment" Title: "Make primary boot files" File: %make-boot.r ;-- used by EMIT-HEADER to indicate emitting script Rights: { Copyright 2012 REBOL Technologies Copyright 2012-2017 Rebol Open Source Contributors REBOL is a trademark of REBOL Technologies } License: { Licensed under the Apache License, Version 2.0 See: http://www.apache.org/licenses/LICENSE-2.0 } Version: 2.100.0 Needs: 2.100.100 Purpose: { A lot of the REBOL system is built by REBOL, and this program does most of the serious work. It generates most of the C include files required to compile REBOL. } ] print "--- Make Boot : System Embedded Script ---" do %bootstrap-shim.r do %common.r do %common-emitter.r do %systems.r change-dir %../../src/boot/ args: parse-args system/options/args config: config-system try get 'args/OS_ID first-rebol-commit: "19d4f969b4f5c1536f24b023991ec11ee6d5adfb" if args/GIT_COMMIT = "unknown" [ git-commit: _ ] else [ git-commit: args/GIT_COMMIT if (length of git-commit) != (length of first-rebol-commit) [ print ["GIT_COMMIT should be a full hash, e.g." first-rebol-commit] print ["Invalid hash was:" git-commit] quit ] ] ;-- SETUP -------------------------------------------------------------- ;dir: %../core/temp/ ; temporary definition output-dir: system/options/path/prep inc: output-dir/include core: output-dir/core boot: output-dir/boot mkdir/deep probe inc mkdir/deep probe boot mkdir/deep probe core version: load %version.r version/4: config/id/2 version/5: config/id/3 ;-- Title string put into boot.h file checksum: Title: {REBOL Copyright 2012 REBOL Technologies REBOL is a trademark of REBOL Technologies Licensed under the Apache License, Version 2.0 } sections: [ boot-types boot-words boot-generics boot-natives boot-typespecs boot-errors boot-sysobj boot-base boot-sys boot-mezz ; boot-script ] ; Args passed: platform, product ; ; !!! Heed /script/args so you could say e.g. `do/args %make-boot.r [0.3.01]` ; Note however that current leaning is that scripts called by the invoked ; process will not have access to the "outer" args, hence there will be only ; one "args" to be looked at in the long run. This is an attempt to still ; be able to bootstrap under the conditions of the A111 rebol.com R3-Alpha ; as well as function either from the command line or the REPL. ; args: any [ either text? :system/script/args [ either block? load system/script/args [ load system/script/args ][ reduce [load system/script/args] ] ][ get 'system/script/args ] ; This is the only piece that should be necessary if not dealing w/legacy system/options/args ] or [ fail "No platform specified." ] product: to-word any [try get 'args/PRODUCT | "core"] platform-data: context [type: 'windows] build: context [features: [help-strings]] ;-- Fetch platform specifications: ;init-build-objects/platform platform ;platform-data: platforms/:platform ;build: platform-data/builds/:product ;---------------------------------------------------------------------------- ; ; %tmp-symbols.h - Symbol Numbers ; ;---------------------------------------------------------------------------- e-symbols: make-emitter "Symbol Numbers" inc/tmp-symbols.h syms: copy [] sym-n: 1 boot-words: copy [] add-sym: function [ {Add SYM_XXX to enumeration} return: [<opt> integer!] word [word!] /exists "return ID of existing SYM_XXX constant if already exists" <with> sym-n ][ if pos: find boot-words word [ if exists [return index of pos] fail ["Duplicate word specified" word] ] append syms cscape/with {/* $<Word> */ SYM_${WORD} = $<sym-n>} [sym-n word] sym-n: sym-n + 1 append boot-words word return null ] ; Several different sections add to the symbol constants, types are first... type-table: load %types.r e-dispatch: make-emitter "Dispatchers" core/tmp-dispatchers.c hookname: func [ return: [text!] t [object!] "type record (e.g. a row out of %types.r)" column [word!] "which column we are deriving the hook's name based on" ][ propercase-of switch ensure word! t/(column) [ '+ [t/name] ; type has its own unique hook '* [t/class] ; type uses common hook for class '? ['unhooked] ; datatype provided by extension '- ['fail] ; service unavailable for type default [ t/(column) ; override with word in column ] ] ] generic-hooks: collect [ for-each-record t type-table [ keep cscape/with {T_${Hookname T 'Class} /* $<T/Name> */} [t] ] ] compare-hooks: collect [ for-each-record t type-table [ keep cscape/with {CT_${Hookname T 'Class} /* $<T/Name> */} [t] ] ] path-hooks: collect [ for-each-record t type-table [ keep cscape/with {PD_${Hookname T 'Path} /* $<T/Name> */} [t] ] ] make-hooks: collect [ for-each-record t type-table [ keep cscape/with {MAKE_${Hookname T 'Make} /* $<T/Name> */} [t] ] ] to-hooks: collect [ for-each-record t type-table [ keep cscape/with {TO_${Hookname T 'Make} /* $<T/Name> */} [t] ] ] mold-hooks: collect [ for-each-record t type-table [ keep cscape/with {MF_${Hookname T 'Mold} /* $<T/Name> */} [t] ] ] e-dispatch/emit { #include "sys-core.h" /* * PER-TYPE GENERIC HOOKS: e.g. for `append value x` or `select value y` * * This is using the term in the sense of "generic functions": * https://en.wikipedia.org/wiki/Generic_function * * The current assumption (rightly or wrongly) is that the handler for * a generic action (e.g. APPEND) doesn't need a special hook for a * specific datatype, but that the class has a common function. But note * any behavior for a specific type can still be accomplished by testing * the type passed into that common hook! */ GENERIC_HOOK Generic_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(Generic-Hooks), }; /* * PER-TYPE COMPARE HOOKS, to support GREATER?, EQUAL?, LESSER?... * * Every datatype should have a comparison function, because otherwise a * block containing an instance of that type cannot SORT. Like the * generic dispatchers, compare hooks are done on a per-class basis, with * no overrides for individual types (only if they are the only type in * their class). */ COMPARE_HOOK Compare_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(Compare-Hooks), }; /* * PER-TYPE PATH HOOKS: for `a/b`, `:a/b`, `a/b:`, `pick a b`, `poke a b` */ PATH_HOOK Path_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(Path-Hooks), }; /* * PER-TYPE MAKE HOOKS: for `make datatype def` * * These functions must return a REBVAL* to the type they are making * (either in the output cell given or an API cell)...or they can return * R_THROWN if they throw. (e.g. `make object! [return]` can throw) */ MAKE_HOOK Make_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(Make-Hooks), }; /* * PER-TYPE TO HOOKS: for `to datatype value` * * These functions must return a REBVAL* to the type they are making * (either in the output cell or an API cell). They are NOT allowed to * throw, and are not supposed to make use of any binding information in * blocks they are passed...so no evaluations should be performed. * * !!! Note: It is believed in the future that MAKE would be constructor * like and decided by the destination type, while TO would be "cast"-like * and decided by the source type. For now, the destination decides both, * which means TO-ness and MAKE-ness are a bit too similar. */ TO_HOOK To_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(To-Hooks), }; /* * PER-TYPE MOLD HOOKS: for `mold value` and `form value` * * Note: ERROR! may be a context, but it has its own special FORM-ing * beyond the class (falls through to ANY-CONTEXT! for mold), and BINARY! * has a different handler than strings. So not all molds are driven by * their class entirely. */ MOLD_HOOK Mold_Or_Form_Hooks[REB_MAX] = { nullptr, /* REB_0 */ $(Mold-Hooks), }; } e-dispatch/write-emitted ;---------------------------------------------------------------------------- ; ; %reb-types.h - Datatype Definitions ; ;---------------------------------------------------------------------------- e-types: make-emitter "Datatype Definitions" inc/tmp-kinds.h n: 1 rebs: collect [ for-each-record t type-table [ ensure word! t/name ensure word! t/class assert [sym-n == n] ;-- SYM_XXX should equal REB_XXX value add-sym to-word unspaced [ensure word! t/name "!"] keep cscape/with {REB_${T/NAME} = $<n>} [n t] n: n + 1 ] ] for-each-record t type-table [ ] e-types/emit { /* * INTERNAL DATATYPE CONSTANTS, e.g. REB_BLOCK or REB_TAG * * Do not export these values via libRebol, as the numbers can change. * Their ordering is for supporting certain optimizations, such as being * able to quickly check if a type IS_BINDABLE(). When types are added, * or removed, the numbers must shuffle around to preserve invariants. * * While REB_MAX indicates the maximum legal VAL_TYPE(), there is also a * list of PSEUDOTYPE_ONE, PSEUDOTYPE_TWO, etc. values which are used * for special internal states and flags. Some of these are used in the * KIND_BYTE() of value cells to mark their usage of alternate payloads * during algorithmic transformations (e.g. specialization). Others are * used to signal special behaviors when returned from native dispatchers. * Still others are used as special indicators in typeset bitsets. * * NOTE ABOUT C++11 ENUM TYPING: It is best not to specify an "underlying * type" because that prohibits certain optimizations, which the compiler * can make based on knowing a value is only in the range of the enum. */ enum Reb_Kind { REB_0 = 0, /* reserved for internal purposes */ REB_0_END = REB_0, /* ...most commonly array termination cells... */ REB_TS_ENDABLE = REB_0, /* bit set in typesets for endability */ /*** REAL TYPES ***/ $[Rebs], REB_MAX, /* one past valid types, does double duty as NULL signal */ REB_MAX_NULLED = REB_MAX, /*** PSEUDOTYPES ***/ PSEUDOTYPE_ONE, REB_R_THROWN = PSEUDOTYPE_ONE, REB_P_NORMAL = PSEUDOTYPE_ONE, REB_TS_VARIADIC = PSEUDOTYPE_ONE, REB_X_PARTIAL = PSEUDOTYPE_ONE, PSEUDOTYPE_TWO, REB_R_INVISIBLE = PSEUDOTYPE_TWO, REB_P_TIGHT = PSEUDOTYPE_TWO, REB_TS_SKIPPABLE = PSEUDOTYPE_TWO, REB_X_PARTIAL_SAW_NULL_ARG = PSEUDOTYPE_TWO, #if defined(DEBUG_TRASH_MEMORY) REB_T_TRASH = PSEUDOTYPE_TWO, /* identify trash in debug build */ #endif PSEUDOTYPE_THREE, REB_R_REDO = PSEUDOTYPE_THREE, REB_P_HARD_QUOTE = PSEUDOTYPE_THREE, REB_TS_HIDDEN = PSEUDOTYPE_THREE, PSEUDOTYPE_FOUR, REB_R_REFERENCE = PSEUDOTYPE_FOUR, REB_P_SOFT_QUOTE = PSEUDOTYPE_FOUR, REB_TS_UNBINDABLE = PSEUDOTYPE_FOUR, PSEUDOTYPE_FIVE, REB_R_IMMEDIATE = PSEUDOTYPE_FIVE, REB_P_REFINEMENT = PSEUDOTYPE_FIVE, REB_TS_NOOP_IF_BLANK = PSEUDOTYPE_FIVE, PSEUDOTYPE_SIX, REB_P_LOCAL = PSEUDOTYPE_SIX, REB_TS_QUOTED_WORD = PSEUDOTYPE_SIX, /* !!! temp compatibility */ PSEUDOTYPE_SEVEN, REB_P_RETURN = PSEUDOTYPE_SEVEN, REB_TS_QUOTED_PATH = PSEUDOTYPE_SEVEN, /* !!! temp compatibility */ REB_MAX_PLUS_MAX }; /* * Current hard limit, higher types used for QUOTED!. In code which * is using the 64 split to implement the literal trick, use REB_64 * instead of just 64 to make places dependent on that trick findable. * * !!! If one were desperate for "special" types, things like 64/128/192 * could be used, as there is no such thing as a "literal END", etc. */ #define REB_64 64 /* * While the VAL_TYPE() is a full byte, only 64 states can fit in the * payload of a TYPESET! at the moment. Some rethinking would be * necessary if this number exceeds 64 (note some values beyond the * real DATATYPE! values set special signal bits in parameter typesets.) */ STATIC_ASSERT(REB_MAX_PLUS_MAX <= REB_64); } e-types/emit newline e-types/emit { /* * SINGLE TYPE CHECK MACROS, e.g. IS_BLOCK() or IS_TAG() * * These routines are based on VAL_TYPE(), which is distinct and costs * more than KIND_BYTE() in the debug build. In some commonly called * routines that don't differentiate literal types, it may be worth it * to use KIND_BYTE() for optimization purposes. * * Note that due to a raw type encoding trick, IS_LITERAL() is unusual. * `KIND_BYTE(v) == REB_QUOTED` isn't `VAL_TYPE(v) == REB_QUOTED`, * they mean different things. This is because raw types > REB_64 are * used to encode literals whose escaping level is low enough that it * can use the same cell bits as the escaped value. */ } e-types/emit newline boot-types: copy [] n: 1 for-each-record t type-table [ if t/name != 'quoted [ ; see IS_QUOTED(), handled specially e-types/emit 't { #define IS_${T/NAME}(v) \ (KIND_BYTE(v) == REB_${T/NAME}) /* $<n> */ } e-types/emit newline ] append boot-types to-word adjoin form t/name "!" n: n + 1 ] types-header: first load/header %types.r e-types/emit trim/auto copy ensure text! types-header/macros e-types/emit { /* ** TYPESET DEFINITIONS (e.g. TS_ARRAY or TS_STRING) ** ** Note: User-facing typesets, such as ANY-VALUE!, do not include null ** (absence of a value), nor do they include the internal "REB_0" type. */ /* * Subtract 1 to get mask for everything but REB_MAX_NULLED * Subtract 1 again to take out REB_0 for END (signal for "endability") */ #define TS_VALUE \ ((FLAGIT_KIND(REB_MAX) - 1) - 1) /* * Similar to TS_VALUE but accept NULL (as REB_MAX) */ #define TS_OPT_VALUE \ (((FLAGIT_KIND(REB_MAX_NULLED + 1) - 1) - 1)) } typeset-sets: copy [] for-each-record t type-table [ for-each ts compose [(t/typesets)] [ spot: any [ try select typeset-sets ts first back insert tail-of typeset-sets reduce [ts copy []] ] append spot t/name ] ] remove/part typeset-sets 2 ; the - markers for-each [ts types] typeset-sets [ flagits: collect [ for-each t types [ keep cscape/with {FLAGIT_KIND(REB_${T})} 't ] ] e-types/emit [flagits ts] { #define TS_${TS} ($<Delimit "|" Flagits>) } ;-- !!! TS_ANY_XXX is wordy, considering TS_XXX denotes a typeset ] e-types/write-emitted ;---------------------------------------------------------------------------- ; ; %tmp-version.h - Version Information ; ;---------------------------------------------------------------------------- e-version: make-emitter "Version Information" inc/tmp-version.h e-version/emit { /* ** VERSION INFORMATION ** ** !!! While using 5 byte-sized integers to denote a Rebol version might ** not be ideal, it's a standard that's been around a long time. */ #define REBOL_VER $<version/1> #define REBOL_REV $<version/2> #define REBOL_UPD $<version/3> #define REBOL_SYS $<version/4> #define REBOL_VAR $<version/5> } e-version/emit newline e-version/write-emitted ;-- Add SYM_XXX constants for the words in %words.r wordlist: load %words.r replace wordlist '*port-modes* load %modes.r for-each word wordlist [add-sym word] ;-- Add SYM_XXX constants for generics (e.g. SYM_APPEND, etc.) ;-- This allows C switch() statements to process them efficiently first-generic-sym: sym-n boot-generics: load boot/tmp-generics.r for-each item boot-generics [ if set-word? :item [ if first-generic-sym < (add-sym/exists to-word item else [0]) [ fail ["Duplicate generic found:" item] ] ] ] ;---------------------------------------------------------------------------- ; ; Sysobj.h - System Object Selectors ; ;---------------------------------------------------------------------------- e-sysobj: make-emitter "System Object" inc/tmp-sysobj.h at-value: func ['field] [next find boot-sysobj to-set-word field] boot-sysobj: load %sysobj.r change at-value version version change at-value commit git-commit change at-value build now/utc change at-value product uneval to word! product change/only at-value platform reduce [ any [config/platform-name | "Unknown"] any [config/build-label | ""] ] ob: has boot-sysobj make-obj-defs: function [ {Given a Rebol OBJECT!, write C structs that can access its raw variables} return: <void> e [object!] {The emitter to write definitions to} obj prefix depth /selfless ][ items: try collect [ either selfless [ n: 1 ][ keep cscape/with {${PREFIX}_SELF = 1} [prefix] n: 2 ] for-each field words-of obj [ keep cscape/with {${PREFIX}_${FIELD} = $<n>} [prefix field n] n: n + 1 ] keep cscape/with {${PREFIX}_MAX} [prefix] ] e/emit [prefix items] { enum ${PREFIX}_object { $(Items), }; } if depth > 1 [ for-each field words-of obj [ if all [ field != 'standard object? get in obj field ][ extended-prefix: uppercase unspaced [prefix "_" field] make-obj-defs e obj/:field extended-prefix (depth - 1) ] ] ] ] make-obj-defs e-sysobj ob "SYS" 1 make-obj-defs e-sysobj ob/catalog "CAT" 4 make-obj-defs e-sysobj ob/contexts "CTX" 4 make-obj-defs e-sysobj ob/standard "STD" 4 make-obj-defs e-sysobj ob/state "STATE" 4 ;make-obj-defs e-sysobj ob/network "NET" 4 make-obj-defs e-sysobj ob/ports "PORTS" 4 make-obj-defs e-sysobj ob/options "OPTIONS" 4 ;make-obj-defs e-sysobj ob/intrinsic "INTRINSIC" 4 make-obj-defs e-sysobj ob/locale "LOCALE" 4 make-obj-defs e-sysobj ob/view "VIEW" 4 e-sysobj/write-emitted ;---------------------------------------------------------------------------- ; ; Event Types ; ;---------------------------------------------------------------------------- e-event: make-emitter "Event Types" inc/reb-evtypes.h evts: collect [ for-each field ob/view/event-types [ keep cscape/with {EVT_${FIELD}} 'field ] ] evks: collect [ for-each field ob/view/event-keys [ keep cscape/with {EVK_${FIELD}} 'field ] ] e-event/emit { enum event_types { $[Evts], EVT_MAX }; enum event_keys { $[Evks], EVK_MAX }; } e-event/write-emitted ;---------------------------------------------------------------------------- ; ; Error Constants ; ;---------------------------------------------------------------------------- ;-- Error Structure ---------------------------------------------------------- e-errfuncs: make-emitter "Error structure and functions" inc/tmp-error-funcs.h fields: collect [ keep {RELVAL self} for-each word words-of ob/standard/error [ either word = 'near [ keep {/* near/far are old C keywords */ RELVAL nearest} ][ keep cscape/with {RELVAL ${word}} 'word ] ] ] e-errfuncs/emit { /* * STANDARD ERROR STRUCTURE */ typedef struct REBOL_Error_Vars { $[Fields]; } ERROR_VARS; } e-errfuncs/emit { /* * The variadic Error() function must be passed the exact right number of * fully resolved REBVAL* that the error spec specifies. This is easy * to get wrong in C, since variadics aren't checked. Also, the category * symbol needs to be right for the error ID. * * These are inline function stubs made for each "raw" error in %errors.r. * They shouldn't add overhead in release builds, but help catch mistakes * at compile time. */ } first-error-sym: sym-n boot-errors: load %errors.r for-each [sw-cat list] boot-errors [ cat: to word! ensure set-word! sw-cat ensure block! list add-sym to word! cat ;-- category might incidentally exist as SYM_XXX for-each [sw-id t-message] list [ id: to word! ensure set-word! sw-id message: t-message ;-- Add a SYM_XXX constant for the error's ID word if first-error-sym < (add-sym/exists id else [0]) [ fail ["Duplicate error ID found:" id] ] arity: 0 if block? message [ ;-- can have N GET-WORD! substitution slots parse message [any [get-word! (arity: arity + 1) | skip] end] ] else [ ensure text! message ;-- textual message, no arguments ] ; Camel Case and make legal for C (e.g. "not-found*" => "Not_Found_P") ; f-name: uppercase/part to-c-name id 1 parse f-name [ any ["_" w: (uppercase/part w 1) | skip] end ] if arity = 0 [ params: ["void"] ;-- In C, f(void) has a distinct meaning from f() args: ["rebEND"] ] else [ params: collect [ count-up i arity [keep unspaced ["const REBVAL *arg" i]] ] args: collect [ count-up i arity [keep unspaced ["arg" i]] keep "rebEND" ] ] e-errfuncs/emit [message cat id f-name params args] { /* $<Mold Message> */ static inline REBCTX *Error_${F-Name}_Raw($<Delimit ", " Params>) { return Error(SYM_${CAT}, SYM_${ID}, $<Delimit ", " Args>); } } e-errfuncs/emit newline ] ] e-errfuncs/write-emitted ;---------------------------------------------------------------------------- ; ; Load Boot Mezzanine Functions - Base, Sys, and Plus ; ;---------------------------------------------------------------------------- ;-- Add other MEZZ functions: mezz-files: load %../mezz/boot-files.r ; base lib, sys, mezz for-each section [boot-base boot-sys boot-mezz] [ set section make block! 200 for-each file first mezz-files [ append get section load join-of %../mezz/ file ] ; Make section evaluation return a BLANK! (something like <section-done> ; may be better, but calling code is C and that complicates checking). ; append get section _ mezz-files: next mezz-files ] e-sysctx: make-emitter "Sys Context" inc/tmp-sysctx.h ; We don't actually want to create the object in the R3-MAKE Rebol, because ; the constructs are intended to run in the Rebol being built. But the list ; of top-level SET-WORD!s is needed. R3-Alpha used a non-evaluating CONSTRUCT ; to do this, but Ren-C's non-evaluating construct expects direct alternation ; of SET-WORD! and unevaluated value (even another SET-WORD!). So we just ; gather the top-level set-words manually. sctx: has collect [ for-each item boot-sys [ if set-word? :item [ keep item keep "stub proxy for %sys-base.r item" ] ] ] ; !!! The SYS_CTX has no SELF...it is not produced by the ordinary gathering ; constructor, but uses Alloc_Context() directly. Rather than try and force ; it to have a SELF, having some objects that don't helps pave the way ; to the userspace choice of self-vs-no-self (as with func's `<with> return`) ; make-obj-defs/selfless e-sysctx sctx "SYS_CTX" 1 e-sysctx/write-emitted ;---------------------------------------------------------------------------- ; ; TMP-BOOT-BLOCK.R and TMP-BOOT-BLOCK.C ; ; Create the aggregated Rebol file of all the Rebol-formatted data that is ; used in bootstrap. This includes everything from a list of WORD!s that ; are built-in as symbols, to the sys and mezzanine functions. ; ; %tmp-boot-block.c is just a C file containing a literal constant of the ; compressed representation of %tmp-boot-block.r ; ;---------------------------------------------------------------------------- e-bootblock: make-emitter "Natives and Bootstrap" core/tmp-boot-block.c boot-natives: load boot/tmp-natives.r nats: collect [ for-each val boot-natives [ if set-word? val [ keep cscape/with {N_${to word! val}} 'val ] ] ] print [length of nats "natives"] e-bootblock/emit { #include "sys-core.h" #define NUM_NATIVES $<length of nats> const REBCNT Num_Natives = NUM_NATIVES; REBVAL Natives[NUM_NATIVES]; const REBNAT Native_C_Funcs[NUM_NATIVES] = { $(Nats), }; } ;-- Build typespecs block (in same order as datatypes table): boot-typespecs: make block! 100 specs: load %typespec.r for-each-record t type-table [ if t/name <> 0 [ append/only boot-typespecs really select specs to-word t/name ] ] ;-- Create main code section (compressed): write-if-changed boot/tmp-boot-block.r mold reduce sections data: to-binary mold/flat reduce sections compressed: gzip data e-bootblock/emit { /* * Gzip compression of boot block * Originally $<length of data> bytes * * Size is a constant with storage vs. using a #define, so that relinking * is enough to sync up the referencing sites. */ const REBCNT Nat_Compressed_Size = $<length of compressed>; const REBYTE Native_Specs[$<length of compressed>] = { $<Binary-To-C Compressed> }; } e-bootblock/write-emitted ;---------------------------------------------------------------------------- ; ; Boot.h - Boot header file ; ;---------------------------------------------------------------------------- e-boot: make-emitter "Bootstrap Structure and Root Module" inc/tmp-boot.h nat-index: 0 nids: collect [ for-each val boot-natives [ if set-word? val [ keep cscape/with {N_${to word! val}_ID = $<nat-index>} [nat-index val] nat-index: nat-index + 1 ] ] ] fields: collect [ for-each word sections [ word: form word remove/part word 5 ; boot_ keep cscape/with {RELVAL ${word}} 'word ] ] e-boot/emit { /* * Compressed data of the native specifications, uncompressed during boot. */ EXTERN_C const REBCNT Nat_Compressed_Size; EXTERN_C const REBYTE Native_Specs[]; /* * Raw C function pointers for natives, take REBFRM* and return REBVAL*. */ EXTERN_C const REBCNT Num_Natives; EXTERN_C const REBNAT Native_C_Funcs[]; /* * A canon ACTION! REBVAL of the native, accessible by native's index # */ EXTERN_C REBVAL Natives[]; /* size is Num_Natives */ enum Native_Indices { $(Nids), }; typedef struct REBOL_Boot_Block { $[Fields]; } BOOT_BLK; } ;------------------- e-boot/write-emitted ;----------------------------------------------------------------------------- ; EMIT SYMBOLS ;----------------------------------------------------------------------------- e-symbols/emit { /* * CONSTANTS FOR BUILT-IN SYMBOLS: e.g. SYM_THRU or SYM_INTEGER_X * * ANY-WORD! uses internings of UTF-8 character strings. An arbitrary * number of these are created at runtime, and can be garbage collected * when no longer in use. But a pre-determined set of internings are * assigned small integer "SYM" compile-time-constants, to be used in * switch() for efficiency in the core. * * Datatypes are given symbol numbers at the start of the list, so that * their SYM_XXX values will be identical to their REB_XXX values. * * The file %words.r contains a list of spellings that are given ID * numbers recognized by the core. * * Errors raised by the core are identified by the symbol number of their * ID (there are no fixed-integer values for these errors as R3-Alpha * tried to do with RE_XXX numbers, which fluctuated and were of dubious * benefit when symbol comparison is available). * * Note: SYM_0 is not a symbol of the string "0". It's the "SYM" constant * that is returned for any interning that *does not have* a compile-time * constant assigned to it. Since VAL_WORD_SYM() will return SYM_0 for * all user (and extension) defined words, don't try to check equality * with `VAL_WORD_SYM(word1) == VAL_WORD_SYM(word2)`. */ enum Reb_Symbol { SYM_0 = 0, $(Syms), }; } print [n "words + generics + errors"] e-symbols/write-emitted
import for_mathlib.derived.defs import for_mathlib.homology_map import for_mathlib.has_homology noncomputable theory open category_theory opposite open homotopy_category variables {𝓐 : Type*} [category 𝓐] [abelian 𝓐] variables {ι : Type*} {c : complex_shape ι} def commsq.op {A B C D : 𝓐} {a : A ⟶ B} {b : B ⟶ D} {a' : A ⟶ C} {c : C ⟶ D} (sq : commsq a a' b c) : commsq c.op b.op a'.op a.op := begin apply commsq.of_eq, simp only [← op_comp, sq.w] end lemma homology_map_homology_op_iso {A₁ B₁ C₁ A₂ B₂ C₂ : 𝓐} (f₁ : A₁ ⟶ B₁) (g₁ : B₁ ⟶ C₁) (w₁ : f₁ ≫ g₁ = 0) (f₂ : A₂ ⟶ B₂) (g₂ : B₂ ⟶ C₂) (w₂ : f₂ ≫ g₂ = 0) (a : A₁ ⟶ A₂) (b : B₁ ⟶ B₂) (c : C₁ ⟶ C₂) (sq1 : commsq f₁ a b f₂) (sq2 : commsq g₁ b c g₂) : homology.map' _ _ sq2.op sq1.op ≫ (has_homology.homology_op_iso f₁ g₁ w₁).hom = (has_homology.homology_op_iso _ _ _).hom ≫ (homology.map' w₁ w₂ sq1 sq2).op := begin suffices : (homology.map' w₁ w₂ sq1 sq2).op = (homology.has _ _ _).op.map (homology.has _ _ _).op sq2.op sq1.op, { erw [this, has_homology.map_comp_map, has_homology.map_comp_map], apply (homology.has _ _ _).ext_π, apply (homology.has _ _ _).op.ext_ι, simp only [has_homology.π_map, has_homology.lift_comp_ι, iso.refl_hom], erw [has_homology.lift_comp_ι], congr' 2, rw [category.id_comp, category.comp_id], }, apply (homology.has _ _ _).op.ext_π, apply (homology.has _ _ _).op.ext_ι, simp only [has_homology.π_map, has_homology.lift_comp_ι], dsimp only [has_homology.op, kernel_op_op_hom, cokernel_op_op_inv], simp only [← op_comp, homology.map', category.assoc, has_homology.π_map_assoc, has_homology.lift_comp_ι_assoc, limits.kernel.lift_ι_assoc, limits.cokernel.π_desc], simp only [op_comp, category.assoc], refl, end lemma is_quasi_iso_of_op {X Y : (chain_complex 𝓐 ℤ)ᵒᵖ} (f : X ⟶ Y) (h : is_quasi_iso ((quotient _ _).map (homological_complex.op_functor.map f))) : is_quasi_iso ((quotient _ _).map f.unop) := begin refine ⟨λ i, _⟩, obtain ⟨i, rfl⟩ : ∃ j, j+1=i := ⟨i-1, sub_add_cancel _ _⟩, rw [← homotopy_category.homology_functor_map_factors, homology_iso_map (i+1+1) (i+1) i], swap, {dsimp, refl}, swap, {dsimp, refl}, apply_with is_iso.comp_is_iso {instances:=ff}, { apply_instance }, apply_with is_iso.comp_is_iso {instances:=ff}, swap, { apply_instance }, have aux := @is_quasi_iso.cond _ _ _ _ _ _ _ _ h (i+1), rw [← homotopy_category.homology_functor_map_factors, homology_iso_map i (i+1) (i+1+1)] at aux, swap, {dsimp, refl}, swap, {dsimp, refl}, replace aux := @is_iso.of_is_iso_comp_left _ _ _ _ _ _ _ _ aux, replace aux := @is_iso.of_is_iso_comp_right _ _ _ _ _ _ _ _ aux, rw [← is_iso_op_iff], refine is_iso_of_square _ (has_homology.homology_op_iso _ _ _).hom (has_homology.homology_op_iso _ _ _).hom _ _ aux _ _, swap, { apply_instance }, swap, { apply_instance }, rw [homology.map_eq, homology.map_eq, ← homology_map_homology_op_iso], congr' 2, end
#!/usr/bin/python # -*- coding: utf-8 -*- # # SignifikanzTestP - Klasse von zufall # # # This file is part of zufall # # # Copyright (c) 2019 Holger Böttcher [email protected] # # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import importlib from IPython.display import display, Math import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt from sympy import sqrt, floor, ceiling, Piecewise from sympy.core.numbers import Integer, Rational, Float from sympy.printing.latex import latex from zufall.lib.objekte.basis import ZufallsObjekt from zufall.lib.objekte.normal_verteilung import NormalVerteilung from zufall.lib.funktionen.graf_funktionen import balken1 from zufall.lib.objekte.ausnahmen import ZufallError import zufall bv = importlib.import_module('zufall.lib.objekte.binomial_verteilung') BinomialVerteilung = bv.BinomialVerteilung # SignifikanzTestP - Klasse # ------------------------- class SignifikanzTestP(ZufallsObjekt): """ Signifikanztest für die unbekannte Wahrscheinlichkeit der Binomialverteilung **Kurzname** **STP** **Erzeugung** STP( *p0, alpha, seite, umfang, verfahren* ) **Parameter** *p0* : Wahrscheinlchkeit bei :math:`H_0` *alpha* : Signifikanzniveau; Zahl aus (0,1) *seite* : | '2' | 'l' | 'r' *oder* | 'zwei' | 'links' | 'rechts' | zwei-, links- oder rechtsseitiger Test *umfang* : Stichprobenumfang *verfahren* : 'S' | 'Sigma' - | bei alpha = 0.05 (einseitiger Test) | bei alpha = 0.05, 0.1 (zweiseitiger Test) | Benutzung der Sigma-Umgebung des Erwartungswertes 'B' | 'BV' - Benutzung der Binomialverteilung selbst 'N' | 'NV' - Benutzung der Approximation durch die Normalverteilung """ def __new__(cls, *args, **kwargs): if kwargs.get("h") in (1, 2, 3): signifikanz_test_p_hilfe(kwargs["h"]) return try: if len(args) != 5: raise ZufallError('fünf Argumente angeben') p0, alpha, seite, umfang, verfahren = args[:5] if not (isinstance(p0, (Rational, float, Float)) and 0 < p0 < 1): raise ZufallError('für p0 Zahl aus (0,1) angeben') if not (isinstance(alpha, (Rational, float, Float)) and 0 < alpha < 1): raise ZufallError('für alpha Zahl aus (0,1) angeben') if not seite in ('l', 'links', 'r', 'rechts', 2, '2', 'zwei'): raise ZufallError("für seite 'l'|'links',| 'r'|'rechts', '2'|'zwei'|2 angeben") if not (isinstance(umfang, (int, Integer)) and umfang > 0): raise ZufallError('für umfang ganze Zahl > 0 angeben') if not verfahren in ('S', 'Sigma', 'B', 'BV', 'N', 'NV'): raise ZufallError("für verfahren 'S'|'Sigma',| 'B'|'BV', 'N'|'NV' angeben") if verfahren in ('S', 'Sigma'): if seite in ('l', 'links', 'r', 'rechts') and alpha != 0.05: raise ZufallError('das Verfahren ist nur für alpha=0.05 implementiert') if seite in ('2', 'zwei', 2) and alpha not in (0.05, 0.1): raise ZufallError('das Verfahren ist nur für alpha=0.05 oder 0.1 implementiert') except ZufallError as e: print('zufall:', str(e)) return return ZufallsObjekt.__new__(cls, p0, alpha, seite, umfang, verfahren) def __str__(self): return "SignifikanzTestP" # Eigenschaften + Methoden # ------------------------ @property def n(self): """Stichprobenumfang""" return self.args[3] @property def h0(self): """Nullhypothese""" display(Math('p =' + str(self.args[0]))) return H0 = h0 @property def h1(self): """Alternativhypothese""" if self.args[2] in ('l', 'links'): rel = '\\lt' elif self.args[2] in ('r', 'rechts'): rel = '\\gt' else: rel = '\\ne' display(Math('p' + rel + str(self.args[0]))) return H1 = h1 @property def bv(self): """BinomialVerteilung bei :math:`H_0`""" n, p = self.n, self.args[0] return BinomialVerteilung(n, p) @property def sig_niv(self): """Signifikanzniveau""" return self.args[1] sigNiv = sig_niv @property def alpha(self): """Wahrscheinlichkeit für Fehler 1. Art""" ber, bv = self.ab_ber, self.bv return float('{0:.4f}'.format(float(bv.P(ber)))) @property def begriffe(self): """Begriffe beim Testen von Hypothesen""" def dm(x): return display(Math(x)) print(' ') dm('\mathrm{Begriffe\; beim\; Testen\; von\; Hypothesen}') print(' ') dm('H_0 - \mathrm{Nullhypothese\;\;\;z.B.}\;\; p = 0.4') dm('H_1- \mathrm{Alternativhypothese\; oder\; Gegenhypothese}') dm('\\quad\\quad p \\lt' + str(self.args[0]) + ' \\quad linksseitiger\; Test') dm('\\quad\\quad p \\gt' + str(self.args[0]) + ' \\quad rechtsseitiger\; Test') dm('\\quad\\quad p \\ne' + str(self.args[0]) + ' \\quad zweiseitiger\; Test') dm('\mathrm{Prüfgröße - Stichprobenfunktion\; zur\; Konstruktion\; einer\; Entscheidungsregel\; zur\;}' + \ '\mathrm{Ableh-}') dm('\\qquad \mathrm{nung \;bzw.\; Annahme\; von\; } H_0') dm('\mathrm{Ablehnungsbereich\; von\;} ' + 'H_0' + '\mathrm{\;oder\; kritischer\; Bereich - Bereich \; der \;' + \ 'Ergebnismenge,\;für}') dm('\\qquad \mathrm{dessen\; Werte\;}' + 'H_0' + '\mathrm{\; abgelehnt\; wird}') dm('\mathrm{Annahmebereich\; von\;} ' + 'H_0' + '\mathrm{- Bereich \; der \;' + \ 'Ergebnismenge,\; für\; dessen\; Werte\;}' + 'H_0' + '\mathrm{\; nicht\; ab-}') dm('\\qquad \mathrm{gelehnt\; wird}') dm('\mathrm{Signifikanzgrenze(n)\; oder\; Kritische\; Zahl(en) - Randwert(e)\; des\; Ablehnungsbereiches}') dm('\mathrm{Fehler\; 1.\; Art \;-\;} H_0\; \mathrm{wird\; abgelehnt,\; trotzdem\; sie\; wahr\; ist}') dm('\mathrm{Fehler\; 2.\; Art\; -\;} H_0\; \mathrm{wird\; nicht \;abgelehnt,\; trotzdem\; sie\; falsch\; ist}') dm('\\qquad \mathrm{beide\; Fehler\; sind\; zufällige\; Ereignisse}') dm('P(\; \mathrm{Fehler\; 1. Art\; ) = Risiko\; 1. Art = Irrtumswahrscheinlichkeit\; 1. Art = }\; \\alpha ' + \ '\mathrm{-Fehler = }\; \\alpha') dm('P(\; \mathrm{Fehler\; 2. Art\; ) = Risiko\; 2. Art = Irrtumswahrscheinlichkeit\; 2. Art = }\; \\beta ' + \ '\mathrm{-Fehler }') dm('\mathrm{Signifikanzniveau - obere \; Schranke\; für\; das\; Risiko\; 1. Art}') dm('\mathrm{Gütefunktion}') dm('\\quad\\quad p \\longmapsto P(\,Ablehnung\; von\; H_0\,)') dm('\mathrm{\\quad\\quad für\; die\;} p \mathrm{-Werte\; aus\; dem\; Bereich\; von\;} H_0 \mathrm{\;ist\; der\;' \ 'Funktionswert\; das\; zugehörige\; Risiko\; 1. Art}') dm('\mathrm{Operationscharakteristik\; (OC,\; auch\; } \\beta \mathrm{-Funktion)}') dm('\\quad\\quad p \\longmapsto 1-P(\,Ablehnung\; von\; H_0\,)') dm('\mathrm{\\quad\\quad für\; die\;} p \mathrm{-Werte\; aus\; dem\; Bereich\; von\;} H_1 \mathrm{\;ist\; der\;' \ 'Funktionswert\; das\; zugehörige\; Risiko\; 2. Art}') print(' ') def quantil_bv(self, *args, **kwargs): """Quantile der zugehörigen Binomialverteilung""" if kwargs.get('h'): p0, n = str(self.args[0]), str(self.n) print('\nQuantile der Binomialverteilung(' + n + ', ' + p0 + ')\n') print("Aufruf t . quantil_bv( p )\n") print(" t SignifikanzTestP") print(" p Zahl aus [0,1]\n") return if len(args) != 1: print('zufall: einen Wert angeben') return pp = args[0] txt = 'zufall: Zahl aus [0,1] angeben' if not isinstance(pp, (int, Integer, float, Float, Rational)): print(txt) return if not (0 <= pp <= 1): print(txt) return q = self.bv.quantil(*args) return q quantilBV = quantil_bv def quantil_nv(self, *args, **kwargs): """Quantile der Normalverteilung""" if kwargs.get('h'): print('\nQuantile der (0,1)-Normalverteilung\n') print("Aufruf t . quantil_nv( p )\n") print(" t SignifikanzTestP") print(" p Zahl aus [0,1]\n") return nv = NormalVerteilung(0, 1) q = nv.quantil(*args) return q quantilNV = quantil_nv @property def schema(self): """Schema eines Signifikanztestes""" def dm(x): return display(Math(x)) seite, verf = self.args[2], self.args[4] print(' ') dm('\mathrm{Schema\; eines\; Signifikanztestes\;}') dm('\mathrm{für\;die\;unbekannte\;Wahrscheinlichkeit\;einer\;Binomialverteilung}') if seite in ('l', 'links'): if verf in ('S', 'Sigma'): dm('\mathrm{Benutzung\; der\;} \\sigma \mathrm{-Umgebungen\; des\; Erwartungswertes}') print(' ') dm('\mathrm{H_0}: \;p \ge p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\lt p_0 \\quad \mathrm{(Gegenhypothese) \\quad linksseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\; H_0\;ist\;}' + \ '\; X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0 \mathrm{\;und\;}') dm('\\quad \mathrm{hat\; den\;Erwartungswert\;\;} \\mu = n\,p_0, \mathrm' + \ '{die\; Standardabweichung\; ist\;\;}\\sigma = \\sqrt{n \, p_0 \,(1-p_0)}' ) dm('\mathrm{3.\; Ermittlung\; der\; } \\sigma \mathrm{-Umgebung \;anhand\; von\; } \\alpha ' + \ '\mathrm{; \; bei\; } \\alpha =' + str(self.args[1]) + '\mathrm{\;liegt\; mit\; einer\; Wahr-}') a2 = '{0:.2f}'.format(float(1-2*self.args[1])) dm('\mathrm{\\quad scheinlichkeit\; von\;} 1-2 \\alpha =' + a2 + '\mathrm{\;ein\; Versuchsergebnis\; in\; der}' + \ '\mathrm{\; 1.64-Umgebung\;}') dm('\\quad \mathrm{des\; Erwartungswertes}\;\;[ \\mu - 1.64 \, \\sigma, \;\mu + 1.64 \, \\sigma]') dm('\\quad \mathrm{Die\; Wahrscheinlichkeit\; für\; ein\; Ergebnis\; außerhalb\; des\; Intervalls\; ' + \ 'ist\; } 2 \\alpha, \mathrm{\; jeweils\; }') dm('\\quad \\alpha =' + str(self.args[1]) + '\mathrm{\;für\; die\;Bereiche\ links\ und\ rechts\ des\ Intervalls}') dm('\\quad \mathrm{Als\; Ablehnungsbereich\;} \\overline{A} \mathrm{\;der\; Hypothese\; H_0\;wird\; \ der\; Bereich\; definiert,\;der\;links\;}') dm('\\quad \mathrm{von\;diesem\;Intervall\;liegt.\;Die\;Grenze\;(kritische\;Zahl)\;ist\;} K= \ \mathrm{abgerundeter\;Wert\;}') dm('\\quad\mathrm{der\;linken\;Intervallgrenze.\;Damit\;ist\;} \\overline{A} = \{0,\,1,...,K\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\; H_0 \;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha \mathrm{\;abge-}') dm('\\quad\mathrm{lehnt,\;sonst\;wird\; H_0 \;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Benutzung\; der\;Binomialverteilung}') print(' ') dm('\mathrm{H_0}: \;p \ge p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\lt p_0 \\quad \mathrm{(Gegenhypothese) \\quad linksseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\;H_0\;ist\;}' + \ ' X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0') dm('\mathrm{3.\; Ermittlung\;der\;kritischen\;Zahl\;} K \mathrm{\;als\;der\;größten\;Zahl\;aus}\;' + \ '\{0....,n\}, \mathrm{\;für\; die\;}') dm('\\quad P(\,X \\le K\,) \\le \\alpha \\; \mathrm{gilt,\; mittels\; Berechnung\; nach\; der\;' + \ 'Formel\;\;}') dm('\\quad P(X \\le K) = F(n,\,p_0,\,K) = \\sum_{i=0}^K ' + \ '{n \choose i}\, p_0^i \,(1-p_0)^{n-i} \mathrm{\;unter\;Beachtung\;von\;} ') dm('\\quad F(n,\,p_0,\,K) \\le \\alpha \mathrm{, \;wobei\;} F ' + \ '\mathrm{\;die\;Verteilungsfunktion\;der\;Binomialverteilung\;ist}') dm('\\quad\mathrm{Ablehnungsbereich\;ist\;\;} \\overline{A} = \{0,\,1,...,K\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\; H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha') dm('\\quad\mathrm{abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') else: dm('\mathrm{Benutzung\; der\; Approximation\; durch\; die\; Normalverteilung}') print(' ') dm('\mathrm{H_0}: \;p \ge p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\lt p_0 \\quad \mathrm{(Gegenhypothese) \\quad linksseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Bestimmung\;von\;} c_\\alpha \mathrm{\;aus\;der\;Gleichung\;\;} \\Phi(c_\\alpha) = 1-\\alpha') dm('\\quad (\\Phi \mathrm{-Verteilungsfunktion\;der\;(0,1)-Normalverteilung)}') dm('\mathrm{3.\; Ermittlung\; der\; Prüfgröße\; } h_n \mathrm{\;(relative\; Trefferhäufigkeit)\; auf\; der\; ' + \ 'Grundlage\; einer}') dm('\\quad \mathrm{ Stichprobe \;des\;Umfangs\;} n') dm('\\quad \mathrm{Der\;Ablehnungsbereich\;wird\;durch\;das\;Kriterium\;}' + \ 'h_n \\lt p_0-c_\\alpha \\sqrt{ \\frac{p_0(1-p_0)}{n}}') dm('\\quad \mathrm{\;bestimmt}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;das\;Kriterium\;erfüllt,\;wird\; H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höch-}') dm('\\quad\mathrm{stens\;} \\alpha \mathrm{\;abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') elif seite in ('r', 'rechts'): if verf in ('S', 'Sigma'): dm('\mathrm{Benutzung\; der\;} \\sigma \mathrm{-Umgebungen\; des\; Erwartungswertes}') print(' ') dm('\mathrm{H_0}: \;p \le p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\gt p_0 \\quad \mathrm{(Gegenhypothese) \\quad rechtsseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus,\;hier\;} \\alpha=0.05') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\; H_0\;ist\;}' + \ '\; X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0 \mathrm{\;und\;}') dm('\\quad \mathrm{hat\; den\;Erwartungswert\;\;} \\mu = n\,p_0, \mathrm' + \ '{die\; Standardabweichung\; ist\;\;}\\sigma = \\sqrt{n \, p_0 \,(1-p_0)}' ) dm('\mathrm{3.\; Ermittlung\; der\; } \\sigma \mathrm{-Umgebung \;anhand\; von\; } \\alpha ' + \ '\mathrm{; \; bei\; } \\alpha =' + str(self.args[1]) + '\mathrm{\;liegt\; mit\; einer\; Wahr-}') a2 = '{0:.2f}'.format(float(1-2*self.args[1])) dm('\mathrm{\\quad scheinlichkeit\; von\;} 1-2 \\alpha =' + a2 + '\mathrm{\;ein\; Versuchsergebnis\; in\; der}' + \ '\mathrm{\; 1.64-Umgebung\;}') dm('\\quad \mathrm{des\; Erwartungswertes}\;\;[ \\mu - 1.64 \, \\sigma, \;\mu + 1.64 \, \\sigma]') dm('\\quad \mathrm{Die\; Wahrscheinlichkeit\; für\; ein\; Ergebnis\; außerhalb\; des\; Intervalls\; ' + \ 'ist\; } 2 \\alpha, \mathrm{\; jeweils\; }') dm('\\quad \\alpha =' + str(self.args[1]) + '\mathrm{\;für\; die\;Bereiche\ links\ und\ rechts\ des\ Intervalls}') dm('\\quad \mathrm{Als\; Ablehnungsbereich\;} \\overline{A} \mathrm{\;der\; Hypothese\; H_0\;wird\; \ der\; Bereich\; definiert,\;der\;rechts\;}') dm('\\quad \mathrm{von\;diesem\;Intervall\;liegt.\;Die\;Grenze\;(kritische\;Zahl)\;ist\;} K= \ \mathrm{aufgerundeter\;Wert\;}') dm('\\quad\mathrm{der\;rechten\;Intervallgrenze.\;Damit\;ist\;} \\overline{A} = \{K,\,K+1,...,n\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha \mathrm{\;abge-}') dm('\\quad\mathrm{lehnt,\;sonst\;wird\;H_0\;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Benutzung\; der\;Binomialverteilung}') print(' ') dm('\mathrm{H_0}: \;p \le p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\gt p_0 \\quad \mathrm{(Gegenhypothese) \\quad rechtsseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\;H_0\;ist\;}' + \ ' X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0') dm('\mathrm{3.\; Ermittlung\;der\;kritischen\;Zahl\;} K \mathrm{\;als\;der\;kleinsten\;Zahl\;aus}\;' + \ '\{0....,n\}, \mathrm{\;für\; die\;} ') dm('\\quad P(\,X \\ge K\,) \\le \\alpha ' + \ '\;\; \mathrm{gilt,\; mittels\; Berechnung\; nach\; der\; Formel}') dm('\quad P(X \\ge K) = 1-F(n,\,p_0,\,K-1) = \\sum_{i=K}^n' + \ '{n \choose i}\, p_0^i \,(1-p_0)^{n-i}') dm('\\quad \mathrm{unter\;Beachtung\;von\;} 1-\\alpha \\le F(n,\,p_0,\,K-1)' + \ '\mathrm{,\;wobei\;} F \mathrm{\;die\;' + \ 'Verteilungsfunktion}') dm('\\quad\mathrm{der\;Binomialverteilung\;ist}') dm('\\quad\mathrm{Ablehnungsbereich\;ist\;\;} \\overline{A} = \{K+1,\,K+2,...,n\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha') dm('\\quad\mathrm{abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') else: dm('\mathrm{Benutzung\; der\; Approximation\; durch\; die\; Normalverteilung}') print(' ') dm('\mathrm{H_0}: \;p \le p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\gt p_0 \\quad \mathrm{(Gegenhypothese) \\quad rechtsseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Bestimmung\;von\;} c_\\alpha \mathrm{\;aus\;der\;Gleichung\;\;} \\Phi(c_\\alpha) = 1-\\alpha') dm('\\quad (\\Phi \mathrm{-Verteilungsfunktion\;der\;(0,1)-Normalverteilung)}') dm('\mathrm{3.\; Ermittlung\; der\; Prüfgröße\; } h_n \mathrm{\;(relative\; Trefferhäufigkeit)\; auf\; der\; ' + \ 'Grundlage\; einer}') dm('\\quad \mathrm{ Stichprobe \;des\;Umfangs\;} n') dm('\\quad \mathrm{Der\;Ablehnungsbereich\;wird\;durch\;das\;Kriterium\;}' + \ 'h_n \\gt p_0+c_\\alpha \\sqrt{ \\frac{p_0(1-p_0)}{n}}') dm('\\quad \mathrm{\;bestimmt}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;das\;Kriterium\;erfüllt,\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höch-}') dm('\\quad\mathrm{stens\;} \\alpha \mathrm{\;abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') else: if verf in ('S', 'Sigma'): dm('\mathrm{Benutzung\; der\;} \\sigma \mathrm{-Umgebungen\; des\; Erwartungswertes}') print(' ') dm('\mathrm{H_0}: \;p = p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\ne p_0 \\quad \mathrm{(Gegenhypothese) \\quad zweiseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\;H_0\;ist\;}' + \ '\; X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0 \mathrm{\;und\;}') dm('\\quad \mathrm{hat\; den\;Erwartungswert\;\;} \\mu = n\,p_0, \mathrm' + \ '{\;die\; Standardabweichung\; ist\;\;}\\sigma = \\sqrt{n \, p_0 \,(1-p_0)}' ) dm('\mathrm{3.\; Ermittlung\; der\; } \\sigma \mathrm{-Umgebung \;anhand\; von\; } \\alpha ') dm('\\quad \mathrm{Bei\; } \\alpha = 0.05 \mathrm{\;liegt\; mit\; einer\; Wahrscheinlichkeit\; von\;}' + \ '1-\\alpha =0.95 \mathrm{\;ein\; Versuchsergeb-}') dm('\\quad \mathrm{nis\; in\; der\; 1.96\\sigma-Umgebung\; des\; Erwartungswertes}\;\;[ \\mu - ' + \ '1.96 \, \\sigma, \;\mu + 1.96 \, \\sigma]') dm('\\quad \mathrm{Bei\; } \\alpha = 0.1 \mathrm{\;liegt\; mit\; einer\; Wahrscheinlichkeit\; von\;}' + \ '1-\\alpha =0.9 \mathrm{\;ein\; Versuchsergeb-}') dm('\\quad \mathrm{nis\; in\; der\; 1.64\\sigma-Umgebung\; des\; Erwartungswertes}\;\;[ \\mu - ' + \ '1.64 \, \\sigma, \;\mu + 1.64 \, \\sigma]') dm('\\quad \mathrm{Die\; Wahrscheinlichkeit\; für\; ein\; Ergebnis\; außerhalb\; des\; Intervalls\; ' + \ 'ist\;jeweils\; } \\alpha') dm('\\quad \mathrm{Als\; Ablehnungsbereich\;} \\overline{A} \mathrm{\;der\; Hypothese\;H_0\;wird\; \ der\; Bereich\; außerhalb\;des\;In-}') dm('\\quad \mathrm{tervalles\;festgelegt.Die\;Grenzen\; (kritische\; Zahlen)\; sind}') dm('\\quad L= \mathrm{abgerundeter\;Wert\;der\;linken\;Intervallgrenze}') dm('\\quad K= \mathrm{aufgerundeter\;Wert\;der\;rechten\;Intervallgrenze}') dm('\\quad \mathrm{Damit\;ist\;} \\overline{A} = \{0,\,1,...,L\} \\cup \{K,\, K+1,...,n\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha \mathrm{\;abge-}') dm('\\quad\mathrm{lehnt,\;sonst\;wird\;H_0\;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Benutzung\; der\;Binomialverteilung}') print(' ') dm('\mathrm{H_0}: \;p = p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\ne p_0 \\quad \mathrm{(Gegenhypothese) \\quad zweiseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Festlegung\; der\; Prüfgröße\; } X \mathrm{\;(Anzahl\; Treffer)\; auf\; der\; ' + \ 'Grundlage\; einer\; Stichprobe \;}') dm('\mathrm{\\quad des\; Umfangs\;} n.\mathrm{Unter\;H_0\;ist\;}' + \ 'X \mathrm{\;binomialverteilt\;mit\;den\;Parametern\;}' + \ 'n \mathrm{\;und\;} p_0') dm('\mathrm{3.\; Ermittlung\;der\;kritischen\;Zahlen\;} K \mathrm{\;und\;} L \mathrm{\;aus\;den\;Bedingungen}') dm('\\quad P(\,X \\le K\,) \\le \\frac{\\alpha}{2}' + \ '\\quad\mathrm{(größte\;solche\;Zahl)}') dm('\\quad P(\,X \\ge L\,) \\le \\frac{\\alpha}{2} \mathrm{\\quad(kleinste\;solche\;Zahl)};' + \ '\\quad K, L \in \{0,1,...,n\}') dm('\\quad \mathrm{\;Berechnung\; von\;} K \\qquad P(\, X \\le K\, ) = \\sum_{i=0}^K' + \ '{n \choose i}\, p_0^i \,(1-p_0)^{n-i} = F(n,\,p_0,\,K)') dm('\\qquad\\qquad\\qquad\\qquad\\qquad F(n,\,p_0,\,K) \\le \\frac{\\alpha}{2}') dm('\\quad \mathrm{\;Berechnung\; von\;} L \\qquad P(\,X \\ge L\,) = \\sum_{i=L}^n' + \ '{n \choose i}\, p_0^i \,(1-p_0)^{n-i} =1-F(n,\,p_0,\,L-1)') dm('\\qquad\\qquad\\qquad\\qquad\\qquad 1-\\frac{\\alpha}{2} \\le F(n,\,p_0,L-1)') dm('\\quad \mathrm{\;mit\;} F \mathrm{-Verteilungsfunktion\; der\; Binomialverteilunng}') dm('\\quad\mathrm{Ablehnungsbereich\;ist\;\;} \\overline{A} = \{0,\,1,...,K\} \\cup \{L,\,L+1,...,n\}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;} X \\in \\overline{A} \mathrm{,\;so\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höchstens\;} \\alpha ') dm('\\quad\mathrm{abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') else: dm('\mathrm{Benutzung\; der\; Approximation\; durch\; die\; Normalverteilung}') print(' ') dm('\mathrm{H_0}: \;p = p_0 \\quad \mathrm{(Nullhypothese) \\quad gegen}') dm('\mathrm{H_1}: \;p \\ne p_0 \\quad \mathrm{(Gegenhypothese) \\quad zweiseitiger\;Test}') print(' ') dm('\mathrm{1.\; Vorgabe\; des\; Signifikanzniveaus\;} \\alpha') dm('\mathrm{2.\; Bestimmung\;von\;} c_\\alpha \mathrm{\;aus\;der\;Gleichung\;\;} \\Phi(c_\\alpha) = ' + \ '1-\\frac{\\alpha}{2}') dm('\\quad (\\Phi \mathrm{-Verteilungsfunktion\;der\;(0,1)-Normalverteilung)}') dm('\mathrm{3.\; Ermittlung\; der\; Prüfgröße\; } h_n \mathrm{\;(relative\; Trefferhäufigkeit)\; auf\; der\; ' + \ 'Grundlage\; einer}') dm('\\quad \mathrm{ Stichprobe \;des\;Umfangs\;} n') dm('\\quad \mathrm{Der\;Ablehnungsbereich\;wird\;durch\;das\;Kriterium\;}' + \ '\\left|\,h_n-p_0 \\right| \\gt c_\\alpha \\sqrt{ \\frac{p_0(1-p_0)}{n}}') dm('\\quad \mathrm{\;bestimmt}') dm('\mathrm{4.\; Entscheidung\; nach\;der\;Regel }') dm('\\quad\mathrm{Ist\;das\;Kriterium\;erfüllt,\;wird\;H_0\;mit\;einer\; \ Irrtumswahrscheinlichkeit\;von\;höch-}') dm('\\quad\mathrm{stens\;} \\alpha \mathrm{\;abgelehnt,\;sonst\;wird\;H_0\;beibehalten}') print(' ') @property def ab_ber(self): """Ablehnungsbereich von :math:`H_0`""" nv = NormalVerteilung(0, 1) n, bv, alpha = self.n, self.bv, self.sig_niv p0, seite, verf = self.args[0], self.args[2], self.args[4] if seite in ('l', 'links'): if verf in ('S', 'Sigma'): K = ceiling(bv.erw - 1.64*bv.sigma) ab = {i for i in range(K)} elif verf in ('B', 'BV'): grenz = bv.quantil(alpha) - 1 ab = {i for i in range(grenz+1)} else: c = nv.quantil(1-alpha) krit = p0 - c*sqrt(p0*(1-p0)/n) krit = ceiling(n*krit) - 1 ab = {i for i in range(krit+1)} elif seite in ('r', 'rechts'): if verf in ('S', 'Sigma'): L = floor(bv.erw + 1.64*bv.sigma)+1 ab = {i for i in range(L+1, n+1)} elif verf in ('B', 'BV'): grenz = bv.quantil(1-alpha)+1 ab = {i for i in range(grenz, n+1)} else: c = nv.quantil(1-alpha) krit = p0 + c*sqrt(p0*(1-p0)/n) krit = floor(n*krit) + 1 ab = {i for i in range(krit, n+1)} else: if verf in ('S', 'Sigma'): fakt = 1.64 if alpha == 0.1 else 1.96 K = ceiling(bv.erw - fakt*bv.sigma) L = floor(bv.erw + fakt*bv.sigma) ab = {i for i in range(K)}.union({i for i in range(L+1, n+1)}) elif verf in ('B', 'BV'): K = ceiling(bv.quantil(Rational(alpha, 2)) - 1) L = floor(bv.quantil(1-Rational(alpha, 2)) + 1) ab = {i for i in range(K)}.union({ i for i in range(L, n+1)}) else: c = nv.quantil(1-Rational(alpha, 2)) krit1 = p0 - c*sqrt(p0*(1-p0)/n) krit2 = p0 + c*sqrt(p0*(1-p0)/n) krit1 = ceiling(n*krit1) - 1 krit2 = floor(n*krit2) + 1 ab= {i for i in range(krit1+1)}.union({i for i in range(krit2, n+1)}) return ab def ab_ber_(self, **kwargs): """ebenso; zugehörige Methode""" if kwargs.get('h'): print("\nZusatz g=ja grafische Darstellung\n") return ab_ber, om = self.ab_ber, self.bv.omega mark = [] for k in om: if k in ab_ber: mark += [k] if kwargs.get('g'): balken1(self.bv._vert, typ='W', titel='Annahmebereich (hell) und ' + \ 'Ablehnungsbereich (dunkel)\nvon $H_0$\n', mark=mark) return return self.ab_ber abBer = ab_ber AbBer = ab_ber_ @property def an_ber(self): """Annahmebereich von :math:`H_0`""" ab, om = self.ab_ber, self.bv.omega return om.difference(ab) def an_ber_(self, **kwargs): """ebenso; zugehörige Methode""" if kwargs.get('h'): print("\nZusatz g=ja grafische Darstellung\n") return ab_ber, om = self.ab_ber, self.bv.omega mark = [] for k in om: if k in ab_ber: mark += [k] if kwargs.get('g'): balken1(self.bv._vert, typ='W', titel='Annahmebereich (hell) und ' + \ 'Ablehnungsbereich (dunkel)\nvon $H_0$\n', mark=mark) return return self.an_ber anBer = an_ber AnBer = an_ber_ @property def k(self): """Kritische Zahl(en)""" ab, bv, alpha, seite, verf = self.ab_ber, self.bv, self.args[1], \ self.args[2], self.args[4] if seite in ('l', 'links'): return max(ab) elif seite in ('r', 'rechts'): return min(ab) - 1 else: if verf in ('S', 'Sigma'): fakt = 1.64 if alpha == 0.1 else 1.96 K = ceiling(bv.erw - fakt*bv.sigma) L = floor(bv.erw + fakt*bv.sigma) return K, L elif verf in ('B', 'BV'): K = max(self.an_ber) L = ceiling(bv.quantil(1-Rational(alpha, 2)) + 1) return K, L else: p0, n = self.args[0], self.args[3] nv = NormalVerteilung(0, 1) c = nv.quantil(1-Rational(alpha, 2)) krit1 = p0 - c*sqrt(p0*(1-p0)/n) krit2 = p0 + c*sqrt(p0*(1-p0)/n) krit1 = ceiling(n*krit1) - 1 krit2 = floor(n*krit2) + 1 return krit1, krit2 K = k def guete(self, *args, **kwargs): """Güte-Funktion""" if kwargs.get('h'): print("\nGüte-Funktion (SignifikanzTestP)\n") print("Aufruf t . güte( p )\n") print(" t SignifikanzTestP") print(" p Zahl aus [0,1]\n") print("Zusatz g=ja Graf der Funktion\n") return if kwargs.get('g'): return _grafik_guete(self) if len(args) != 1: print('zufall: ein Argument angeben') return p = float(args[0]) if not (isinstance(p, (Rational, float, Float)) and 0<=p<=1): print('zufall: Zahl aus dem Intervall [0,1] angeben') return K, seite, n = self.k, self.args[2], self.args[3] p0 = float(self.args[0]) def guete(p): F = BinomialVerteilung(n, p).F if seite in ('l', 'links'): if p <= p0: return float(F(K)) elif seite in ('r', 'rechts'): if p >= p0: return float(1 - F(K-1)) else: return float(F(K[0]) + 1 - F(K[1]-1)) return guete(p) def oc(self, *args, **kwargs): """Operationscharakteristik""" if kwargs.get('h'): print("\nOperationscharakteristik-Funktion (SignifikanzTestP)\n") print("Aufruf st . oc( p )\n") print(" st SignifikanzTestP") print(" p Zahl aus [0,1]\n") print("Zusatz g=ja Graf der Funktion\n") return if kwargs.get('g'): return _grafik_oc(self) if len(args) != 1: print('zufall: ein Argument angeben') return p = float(args[0]) if not (isinstance(p, (Rational, float, Float)) and 0<=p<=1): print('zufall: Zahl aus dem Intervall [0,1] angeben') return if self.guete(p): return 1.0 - self.guete(p) beta = oc @property def regel(self): """Entscheidungsregel""" def dm(x): return display(Math(x)) print('') dm('\mathrm{Ermittlung\; der\; Entscheidungsregel\; für\; den\; Signifikanztest}') seite, verf = self.args[2], self.args[4] p0, alpha, n = self.args[0], self.args[1], self.args[3] if verf in ('B', 'BV', 'N', 'NV'): bv = self.bv K = self.K if verf in ('N', 'NV'): nv0 = NormalVerteilung(0, 1) sp, sa = str(p0), str(alpha) if seite in ('l', 'links'): ss = 'links' elif seite in ('r', 'rechts'): ss = 'rechts' else: ss = 'zwei' smy = '{0:.2f}'.format(float(self.bv.erw)) ssi = '{0:.4f}'.format(float(self.bv.sigma)) if verf in ('S', 'Sigma') and alpha == 0.1: g1 = '{0:.2f}'.format(float(self.bv.erw - 1.64*self.bv.sigma)) g2 = '{0:.2f}'.format(float(self.bv.erw + 1.64*self.bv.sigma)) elif verf in ('S', 'Sigma') and alpha == 0.05: g1 = '{0:.2f}'.format(float(self.bv.erw - 1.96*self.bv.sigma)) g2 = '{0:.2f}'.format(float(self.bv.erw + 1.96*self.bv.sigma)) if seite in ('l', 'links'): if verf in ('S', 'Sigma'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p \ge' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße}\;\; X=\,\mathrm{"Anzahl\;Treffer", \;\;} \\mu=' + smy + \ ',\;\\sigma=' + ssi) dm('\mathrm{1.64\,\\sigma-Umgebung\;des\;Erwartungswertes}') dm('\\qquad [\, \\mu-1.64\,\\sigma,\; \\mu+1.64\,\\sigma\, ] = [' + g1 + ',\;' + g2 + ']') dm('\mathrm{Kritische\;Zahl\;\;}' + str(floor(g1))) dm('\mathrm{Ablehnungsbereich\;für\;H_0\;\;} X \\le' + str(floor(g1))) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;H_0\;abgelehnt,\;sonst}') dm('\mathrm{wird\;H_0\;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p \ge' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\\text{Prüfgröße} \;\; X=\\text{"Anzahl Treffer"}') dm('\\qquad\\text{Verteilung von }X\;\;' + \ latex(bv)) dm('\mathrm{Kritische\;Zahl\;\;}' + str(K)) dm('\mathrm{Ablehnungsbereich\;für\;}H_0\;\; X \\le' + str(K)) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;} H_0\\text{ mit einer' + \ ' Irrtums-}') dm('\mathrm{wahrscheinlichkeit\;von\;höchstens\;}'+ sa + '\mathrm{\;abgelehnt,\;sonst\;' + \ 'wird\;}H_0\\text{ beibehalten}') else: q = nv0.quantil(1-alpha) g = p0 - q*sqrt(p0*(1-p0)/n) sq = '{0:.5}'.format(float(q)) sg = '{0:.5}'.format(float(g)) dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p \ge' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße\;\;} X=\,\mathrm{"Relative\;Trefferhäufigkeit"}') dm('\\qquad\mathrm{Verteilung\;von}\;X' + \ '\\quad ' + latex('NormalVerteilung(' + str(p0) + ',\,' + \ '{0:.4f}'.format(float(p0*(1-p0)/n)) + ')')) print(' ') dm('\mathrm{Die\;Bestimmung\;von\;}c_\\alpha\mathrm{\;aus\;der\;Gleichung\;}' + \ '\\Phi(c_\\alpha) =' + latex(1-alpha) + '\mathrm{\;ergibt\;\;}' + \ 'c_\\alpha =' +'{0:.4f}'.format(q)) dm('\mathrm{(siehe\;Quantile\;der\;Normalverteilung\;oder\;untere\;Grafik;\;sie\;zeigt\;die\;' + \ 'Vertei-}') dm('\mathrm{lungsfunktion\;der\;(0,1)-Normalverteilung\;(Ausschnitt)})') print(' ') _grafik_nv() dm('\mathrm{Die\;Berechnung\;der\;Grenze\;des\;Ablehnungsbereiches\;ergibt\;\;}') dm('\\qquad ' + str(p0) + '-' + \ sq + '\,\\sqrt{\\frac{' + str(p0) + '\\cdot' + str(1-p0) +'}{' + str(n) + \ '}} =' + sg) print(' ') dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Ist\;die\;relative\;Trefferhäufigkeit\;} \\gt' + sg + \ '\mathrm{,\;so\;wird\;H_0} \mathrm{\;mit\;einer\;Irrtums-}') dm('\mathrm{wahrscheinlichkeit\;von\;}' + str(alpha)+ '\mathrm{\;abgelehnt,\;sonst\;wird\; H_0} ' + \ '\mathrm{\;beibehalten}') print(' ') dm('\mathrm{oder\;\;\;(Verwendung\;der\;absoluten\;Trefferhäufigkeit)}') dm('\mathrm{Multiplikation\;des\;Grenzwertes\;mit\;} n =' + str(n) + '\mathrm{\;ergibt\;}' + \ str(floor(g*n)) + '\mathrm{\;(Rundung\;in\;sicherer\;Richtung)}') dm('\mathrm{Ablehnungsbereich\;\;} X \\le' + str(floor(g*n))) dm('\mathrm{Fällt\;die\;absolute\;Trefferhäufigkeit\;} X \mathrm{\;in\;den\;' + \ 'Ablehnungsbereich,\;so\;wird\;H_0} \mathrm{\;mit\;der}') dm('\mathrm{Irrtumswahrscheinlichkeit\;}' + str(alpha) + \ '\mathrm{\;abgelehnt,\;sonst\;wird\; H_0} \mathrm{\;beibehalten}') elif seite in ('r', 'rechts'): if verf in ('S', 'Sigma'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p \le' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße}\;\; X=\,\mathrm{"Anzahl\;Treffer", \;\;} \\mu=' + smy + \ ',\;\\sigma=' + ssi) dm('\mathrm{1.64\,\\sigma-Umgebung\;des\;Erwartungswertes}') dm('\\qquad [\, \\mu-1.64\,\\sigma,\; \\mu+1.64\,\\sigma\, ] = [' + g1 + ',\;' + g2 + ']') dm('\mathrm{Kritische\;Zahl\;\;}' + str(ceiling(g2))) dm('\mathrm{Ablehnungsbereich\;für\;H_0\;\;} X \\ge' + str(ceiling(g2))) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;}H_0 \ \mathrm{\;abgelehnt,\;sonst}') dm('\mathrm{wird\;}H_0\mathrm{\;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p \le' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße\;\;} X=\,\mathrm{"Anzahl\;Treffer"}') dm('\mathrm{Verteilung\;von}\;X\;\;' + latex(bv)) dm('\mathrm{Kritische\;Zahl\;\;}' + str(self.K)) dm('\mathrm{Ablehnungsbereich\;für\;H_0\;\;} X \\ge' + str(self.K + 1)) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;H_0\;mit\;einer}') dm('\mathrm{Irrtumswahrscheinlichkeit\;von\;höchstens\;}'+ sa + '\mathrm{\;abgelehnt,\;sonst\;}') dm('\mathrm{wird\;H_0\;beibehalten}') else: q = nv0.quantil(1-alpha) g = p0 + q*sqrt(p0*(1-p0)/n) sq = '{0:.5}'.format(float(q)) sg = '{0:.5}'.format(float(g)) dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0:} \;p \le' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße\;\;} X=\,\mathrm{"Relative\;Trefferhäufigkeit"}') dm('\\qquad\mathrm{Verteilung\;von}\;X' + \ '\\quad ' + latex('NormalVerteilung(' + str(p0) + ',' + '\, {0:.4f}'.format(float(p0*(1-p0)/n)) + \ ')')) print(' ') dm('\mathrm{Die\;Bestimmung\;von\;}c_\\alpha\mathrm{\;aus\;der\;Gleichung\;}' + \ '\\Phi(c_\\alpha) =' + latex(1-alpha) + '\mathrm{\;ergibt\;\;}' + \ 'c_\\alpha =' +'{0:.4f}'.format(q)) dm('\mathrm{(siehe\;Quantile\;der\;Normalverteilung\;oder\;untere\;Grafik;\;sie\;zeigt\;die\;' + \ 'Vertei-}') dm('\mathrm{lungsfunktion\;der\;(0,1)-Normalverteilung\;(Ausschnitt)})') print(' ') _grafik_nv() dm('\mathrm{Die\;Berechnung\;der\;Grenze\;des\;Ablehnungsbereiches\;ergibt\;\;}') dm('\\qquad ' + str(p0) + '+' + \ sq + '\,\\sqrt{\\frac{' + str(p0) + '\\cdot' + str(1-p0) +'}{' + str(n) + \ '}} =' + sg) print(' ') dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Ist\;die\;relative\;Trefferhäufigkeit\;} \\gt' + sg + \ '\mathrm{,\;so\;wird \;H_0} \mathrm{\;mit\;einer\;Irrtums-}') dm('\mathrm{wahrscheinlichkeit\;von\;}' + str(alpha)+ '\mathrm{\;abgelehnt,\;sonst\;wird\; H_0} ' + \ '\mathrm{\;beibehalten}') print(' ') dm('\mathrm{oder\;\;\;(Verwendung\;der\;absoluten\;Trefferhäufigkeit)}') dm('\mathrm{Multiplikation\;des\;Grenzwertes\;mit\;} n =' + str(n) + '\mathrm{\;ergibt\;}' + \ str(ceiling(g*n)) + '\mathrm{\;(Rundung\;in\;sicherer\;Richtung)}') dm('\mathrm{Ablehnungsbereich\;\;} X \\ge' + str(ceiling(g*n))) dm('\mathrm{Fällt\;die\;absolute\;Trefferhäufigkeit\;} X \mathrm{\;in\;den\;' + \ 'Ablehnungsbereich,\;so\;wird\; H_0} \mathrm{\;mit\;der}') dm('\mathrm{Irrtumswahrscheinlichkeit\;}' + str(alpha) + \ '\mathrm{\;abgelehnt,\;sonst\;wird \;H_0} \mathrm{\;beibehalten}') else: if verf in ('S', 'Sigma'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p=' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße}\;\; X=\,\mathrm{"Anzahl\;Treffer", \;\;} \\mu=' + smy + ',\;\\sigma=' + ssi) if alpha ==0.1: dm('\mathrm{1.64\,\\sigma-Umgebung\;des\;Erwartungswertes}') dm('\\qquad [\, \\mu-1.64\,\\sigma,\; \\mu+1.64\,\\sigma\, ] = [' + g1 + ',\;' + g2 + ']') elif alpha == 0.05: dm('\mathrm{1.96\,\\sigma-Umgebung\;des\;Erwartungswertes}') dm('\\qquad [\, \\mu-1.96\,\\sigma,\; \\mu+1.96\,\\sigma\, ] = [' + g1 + ',\;' + g2 + ']') dm('\mathrm{Kritische\;Zahlen\;\;}' + str(floor(g1)) + ',\;' + str(ceiling(g2))) dm('\mathrm{Ablehnungsbereich\;für\;H_0\;\;} X \\le' + str(floor(g1)) + \ '\mathrm{\;\;oder\;\; X \\ge}' + str(ceiling(g2))) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;H_0\;abgelehnt,\;sonst}') dm('\mathrm{wird\;H_0\;beibehalten}') elif verf in ('B', 'BV'): dm('\mathrm{Gegeben}') dm('\\qquad \mathrm{H_0}:\;p=' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße\;\;} X=\,\mathrm{"Anzahl\;Treffer"}') dm('\\qquad\mathrm{Verteilung\;von}\;X\;\;' + latex(bv)) dm('\mathrm{Kritische\;Zahlen\;\;}' + str(K[0]) + ',\;' + str(K[1])) dm('\mathrm{Ablehnungsbereich\;für\;H_0\;\;\;} X \\le' + str(K[0]) + \ '\mathrm{\;\;oder\;\;} X \\ge' + str(K[1]) ) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Liegt\;der\;Wert\;der\;Prüfgröße\;im\;Ablehnungsbereich,\;wird\;H_0\;mit\;einer' + \ '\;Irrtums-}') dm('\mathrm{wahrscheinlichkeit\;von\;höchstens\;}'+ sa + '\mathrm{\;abgelehnt,\;sonst\;' + \ 'wird\;H_0\;beibehalten}') else: q = nv0.quantil(1-alpha/2) g1 = p0 - q*sqrt(p0*(1-p0)/n) g2 = p0 + q*sqrt(p0*(1-p0)/n) sq = '{0:.5}'.format(float(q)) sg1 = '{0:.5}'.format(float(g1)) sg2 = '{0:.5}'.format(float(g2)) dm('\mathrm{Gegeben}') dm('\\qquad\mathrm{H_0:}\;p=' + sp) dm('\\qquad\\alpha=' + sa + ',\;n=' + str(n) + ',\;' + \ '\mathrm{' + ss + 'seitiger\;Test}') dm('\\qquad\mathrm{Prüfgröße\;\;} X=\,\mathrm{"Relative\;Trefferhäufigkeit"}') dm('\\quad\mathrm{Verteilung\;von}\;X' + \ '\\quad ' + latex('NormalVerteilung(' + str(p0) + ',\;' + \ '{0:.4f}'.format(float(p0*(1-p0)/n)) + ')')) print(' ') dm('\mathrm{Die\;Bestimmung\;von\;}c_\\alpha\mathrm{\;aus\;der\;Gleichung\;}' + \ '\\Phi(c_\\alpha) =' + latex(1-alpha/2) + '\mathrm{\;ergibt\;\;}' + \ 'c_\\alpha =' +'{0:.4f}'.format(q)) dm('\mathrm{(siehe\;Quantile\;der\;Normalverteilung\;oder\;untere\;Grafik;\;sie\;zeigt\;die\;' + \ 'Vertei-}') dm('\mathrm{lungsfunktion\;der\;(0,1)-Normalverteilung\;(Ausschnitt)})') print(' ') _grafik_nv() dm('\mathrm{Die\;Berechnung\;der\;Grenzen\;des\;Ablehnungsbereiches\;ergibt\;\;}') dm('\\qquad' + str(p0) + '-' + sq + '\,\\sqrt{\\frac{' + str(p0) + '\\cdot' + str(1-p0) + \ '}{' + str(n) + \ '}} =' + sg1) dm('\\qquad' + str(p0) + '+' + sq + '\,\\sqrt{\\frac{' + str(p0) + '\\cdot' + str(1-p0) + \ '}{' + str(n) + \ '}} =' + sg2) print(' ' ) dm('\mathrm{Entscheidungsregel}') dm('\mathrm{Ist\;die\;relative\;Trefferhäufigkeit\;} \\lt' + sg1 + \ '\mathrm{\;\;oder\;\;} \\gt ' + sg2 + ',') dm('\mathrm{so\;wird\;H_0} \mathrm{\;mit\;einer\;Irrtums-' + \ 'wahrscheinlichkeit\;von\;}' + str(alpha)+ '\mathrm{\;abgelehnt,\;sonst\;wird\; H_0} ') dm('\mathrm{\;beibehalten}') print(' ') dm('\mathrm{oder\;\;\;(Verwendung\;der\;absoluten\;Trefferhäufigkeit)}') dm('\mathrm{Multiplikation\;der\;Grenzwerte\;mit\;} n =' + str(n) + '\mathrm{\;ergibt\;}' + \ str(floor(g1*n)) + ',\;' + str(ceiling(g2*n)) + '\mathrm{\;\;(Rundung\;in\;sicherer}') dm('\mathrm{Richtung)}') dm('\mathrm{Ablehnungsbereich\;\;\;} X \\le' + str(floor(g1*n)) + '\mathrm{\;\;oder\;\;}'+ \ 'X \\ge' + str(ceiling(g2*n))) dm('\mathrm{Fällt\;die\;absolute\;Trefferhäufigkeit\;} X \mathrm{\;in\;den\;' + \ 'Ablehnungsbereich,\;so\;wird\;H_0} \mathrm{\;mit\;der}') dm('\mathrm{Irrtumswahrscheinlichkeit\;}' + str(alpha) + \ '\mathrm{\;abgelehnt,\;sonst\;wird\; H_0} \mathrm{\;beibehalten}') print(' ') def regel_(self, **kwargs): """ebenso; zugehörige Methode""" if kwargs.get('h'): print("\nZusatz g=ja grafische Darstellung\n") return self.regel if kwargs.get('g'): self.an_ber_(g=1) Regel = regel_ @property def hilfe(self): """Bezeichner der Eigenschaften und Methoden""" signifikanz_test_p_hilfe(3) h = hilfe def signifikanz_test_p_hilfe(h): if h == 1: print("h=2 - Erzeugung") print("h=3 - Eigenschaften und Methoden") return if h == 2: print(""" \ SignifikanzTestP - Objekt Signifikanztest für die unbekannte Wahr- scheinlichkeit der Binomialverteilung Kurzname STP Erzeugung STP( p0, alpha, seite, umfang, verfahren ) p0 Wahrscheinlchkeit bei H0 alpha Signifikanzniveau, Zahl aus (0,1) seite '2' | 'l' | 'r' oder 'zwei' | 'links' | 'rechts' zwei-, links- oder rechtsseitiger Test umfang Stichprobenumfang verfahren 'S' | 'Sigma': bei alpha = 0.05 (einseitiger Test) bei alpha = 0.05, 0.1 (zweiseitiger Test) Benutzung der Sigma-Umgebung des Erwartungswertes 'B' | 'BV' : Benutzung der Binomialvertei- lung selbst 'N' | 'NV' : Benutzung der Approximation durch die Normalverteilung Zuweisung st = STP(...) (st - freier Bezeichner) Beispiele STP( 0.4, 0.05, 'links', 56, 'Sigma' ) STP( 0.4, 0.05, '2', 1000, 'B' ) """) return if h == 3: print(""" \ Eigenschaften und Methoden (M) für SignifikanzTestP st.hilfe Bezeichner der Eigenschaften und Methoden st.ab_ber Ablehnungsbereich für H0 st.ab_ber_(...) M ebenso, zugehörige Methode st.an_ber Annahmebereich für H0 st.an_ber_(...) M ebenso, zugehörige Methode st.alpha Wahrscheinlichkeit für Fehler 1. Art st.begriffe Begriffe st.beta(...) M = st.oc st.bv Binomialverteilung bei H0 st.güte(...) M Gütefunktion st.h0 Nullhypothese st.h1 Alternativhypothese st.k kritische Zahl(en) st.n Stichprobenumfang st.oc(...) M Operationscharakteristik st.quantil_bv(...) M Quantile der Binomialverteilung st.bv st.quantil_nv(...) M Quantile der (0,1)-Normalverteilung st.regel Ermittlung der Entscheidungsregel st.regel_(...) M ebenso, zugehörige Methode st.schema Berechnungsschema st.sig_niv Signifikanzniveau Synonyme Bezeichner hilfe h ab_ber abBer an_ber anBer beta oc beta_ Beta h0 H0 h1 H1 k K quantil_bv quantilBV quantil_nv quantilNV regel_ Regel sig_niv sigNiv """) return STP = SignifikanzTestP # Grafiken # -------- def _grafik_nv(): def pline(x, y, f): return plt.plot(x, y, color=f, lw=0.7) nv = norm fig = plt.figure(figsize=(3.5, 2)) ax = fig.add_subplot(1, 1, 1) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_linewidth(0.5) ax.spines['right'].set_visible(False) ax.spines['left'].set_linewidth(0.5) df = 1 ax.set_yticks([]) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(9) tick.label1.set_fontname('Times New Roman') plt.axes().xaxis.set_ticks_position('none') for x in (2, 4, 6, 8): pline([x, x], [0.85, 0.853], 'black') plt.axes().yaxis.set_ticks_position('none') plt.xlim(0, 4) plt.ylim(0.85, 1.0) x = np.linspace(nv.ppf(0.84), nv.ppf(0.9999999), 100) ax.plot(x, nv.cdf(x), 'black', lw=1, alpha=0.5) pline([0, nv.ppf(0.9)], [0.90, 0.90], 'b') pline([nv.ppf(0.9), nv.ppf(0.9)], [0, 0.90], 'r') pline([0, nv.ppf(0.95)], [0.95, 0.95], 'b') pline([nv.ppf(0.95), nv.ppf(0.95)], [0, 0.95], 'r') pline([0, nv.ppf(0.975)], [0.975, 0.975], 'b') pline([nv.ppf(0.975), nv.ppf(0.975)], [0, 0.975], 'r') pline([0, nv.ppf(0.99)], [0.99, 0.99], 'b') pline([nv.ppf(0.99), nv.ppf(0.99)], [0, 0.99], 'r') pline([0, 10], [1.0, 1.0], 'b') def ptext(y, t): return ax.text(-0.1, y, t, fontsize=9, horizontalalignment='right', \ fontname = 'Times New Roman', verticalalignment='center', \ color=(0,0,0)) ptext(1.0, '1.0') ptext(0.99, '0.99') ptext(0.975, '0.975') ptext(0.95, '0.95') ptext(0.9, '0.9') plt.show() def _grafik_guete(self): p0, seite = self.args[0], self.args[2] fig = plt.figure(figsize=(3, 2.5)) ax = fig.add_subplot(1, 1, 1) ax.spines['top'].set_linewidth(0.5) ax.spines['bottom'].set_linewidth(0.5) ax.spines['right'].set_linewidth(0.5) ax.spines['left'].set_linewidth(0.5) ax.set_xticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0, 1.0]) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(9) tick.label1.set_fontname('Times New Roman') for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(9) tick.label1.set_fontname('Times New Roman') ax.tick_params(top='off', left='off', bottom='off', right='off') plt.grid() plt.xlim(0, 1) plt.ylim(0, 1) plt.title("$\mathrm{Gütefunktion:\;} p \\mapsto P\,(Ablehnung\;von\;H_0)$" + "\n", \ fontsize=11, loc='left', style='italic') xlabel = "$p$" ylabel = "$Güte$" plt.xlabel(xlabel, fontsize=11) plt.ylabel(ylabel, fontsize=11) if seite in ('l', 'links'): x = np.linspace(0, p0, 50) elif seite in ('r', 'rechts'): x = np.linspace(p0, 1, 50) else: x = np.linspace(0, 1, 50) def f(p): if seite in ('l', 'links'): return Piecewise((self.guete(p), p <= p0), (0, p > p0)) elif seite in ('r', 'rechts'): return Piecewise((0, p <= p0), (self.guete(p), p > p0)) return self.guete(p) y = [f(p) for p in x] ax.plot(x, y, lw=1.5, color='g',alpha=0.8) ax.plot((p0, p0), (0, 1), lw=1.5, color='g',alpha=0.8, linestyle='dashed') plt.show() def _grafik_oc(self): p0, seite = self.args[0], self.args[2] fig = plt.figure(figsize=(3, 2.5)) ax = fig.add_subplot(1, 1, 1) ax.spines['top'].set_linewidth(0.5) ax.spines['bottom'].set_linewidth(0.5) ax.spines['right'].set_linewidth(0.5) ax.spines['left'].set_linewidth(0.5) ax.set_xticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0, 1.0]) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(9) tick.label1.set_fontname('Times New Roman') for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(9) tick.label1.set_fontname('Times New Roman') ax.tick_params(top='off', left='off', bottom='off', right='off') plt.grid() plt.xlim(0, 1) plt.ylim(0, 1) plt.title("$\mathrm{OC:\;} p \\mapsto 1-P\,(Ablehnung\;von\;H_0)$" + "\n", \ fontsize=11, loc='left', style='italic') xlabel = "$p$" ylabel = "$OC$" plt.xlabel(xlabel, fontsize=11) plt.ylabel(ylabel, fontsize=11) if seite in ('l', 'links'): x = np.linspace(0, p0, 50) elif seite in ('r', 'rechts'): x = np.linspace(p0+1e-10, 1, 50) else: x = np.linspace(0, 1, 50) def f(p): if seite in ('l', 'links'): return Piecewise((self.oc(p), p <= p0), (0, p > p0)) elif seite in ('r', 'rechts'): return Piecewise((0, p <= p0), (self.oc(p), p > p0)) return self.oc(p) y = [f(p) for p in x] ax.plot(x, y, lw=1.5, color=(0,0,1), alpha=0.8) ax.plot((p0, p0), (0, 1), lw=1.5, color='g',alpha=0.8, linestyle='dashed') plt.show()
Formal statement is: lemma fmeasurable_Int_fmeasurable: "\<lbrakk>S \<in> fmeasurable M; T \<in> sets M\<rbrakk> \<Longrightarrow> (S \<inter> T) \<in> fmeasurable M" Informal statement is: If $S$ is a measurable set and $T$ is any set, then $S \cap T$ is measurable.
def OneHotEncode(pandas_dataframe,category_columns=[],check_numerical=False,max_var=None): # Parameter explanation ---- # pandas_dataframe -> The Pandas Dataframe object that contains the column you want to one-hot encode # category_columns -> List of column names in pandas_dataframe that you want to one-hot encode # override_alert (Default=False) -> A naive way of checking if the column contains numerical # data or is unsuitable for one-hot encoding # Set it to True to turn on the detection import numpy as numpylib # The dataframe is copied to a new variable df=pandas_dataframe.copy() # List of list of names of all new columns made for a single column all_new_cols=[] # List of dictionary of names of all new columns made for a single column new_col_dict=[] # List of arrays containg the dropped columns that were originally input dropped_cols=[] numerical_const=20 for col in category_columns: category_elements=[] main_row=df[str(col)].values total_rows=len(main_row) for category_element in main_row: category_elements.append(category_element) category_elements=list(set(category_elements)) if check_numerical: if max_var!=None: if len(category_elements) > max_var: print(col+' not suitable for One-Hot Encoding') continue else: if len(category_elements)>numerical_const: print(col+' has more variables than permitted') continue if max_var != None: if len(category_elements) > max_var: print(col+' has more variables than allowed') continue category_element_dict={} for i in range(len(category_elements)): category_element_dict[category_elements[i]]=i category_element_reverse_dict={} for i in range(len(category_elements)): category_element_reverse_dict[col+str(i)]=category_elements[i] dict_new_columns={} category_element_str = [(col+str(x)) for x in range(len(category_elements))] for string in category_element_str: zero_row=numpylib.zeros((total_rows,), dtype=numpylib.int) dict_new_columns[string]=zero_row colnames=[] for i in range(total_rows): colnames.append(category_element_str[category_element_dict[main_row[i]]]) for i in range(total_rows): dict_new_columns[colnames[i]][i]=1 for element in category_element_str: df[element]=dict_new_columns[element] # Original columns are dropped from the dataframe df=df.drop(col,1) all_new_cols.append(category_element_str) new_col_dict.append(category_element_reverse_dict) dropped_cols.append(main_row) return df,dropped_cols,all_new_cols,new_col_dict
module Structure.Operator.Group.Proofs where open import Functional hiding (id) open import Function.Iteration.Order import Lvl open import Lang.Instance open import Logic.Propositional open import Logic.Predicate open import Structure.Setoid open import Structure.Function.Domain open import Structure.Operator.Group open import Structure.Operator.Monoid open import Structure.Operator.Properties open import Structure.Operator.Proofs open import Structure.Relator.Properties open import Syntax.Transitivity open import Type {- module _ {ℓ₁ ℓ₂} {X : Type{ℓ₁}} ⦃ _ : Equiv(X) ⦄ {_▫X_ : X → X → X} ⦃ structureₗ : Group(_▫X_) ⦄ {Y : Type{ℓ₂}} ⦃ _ : Equiv(Y) ⦄ {_▫Y_ : Y → Y → Y} ⦃ structureᵣ : Group(_▫Y_) ⦄ (f : X → Y) where monomorphic-cyclic : ⦃ (_▫X_) ↣ (_▫Y_) ⦄ → Cyclic(_▫X_) → Cyclic(_▫Y_) monomorphic-cyclic ⦃ [∃]-intro θ ⦃ θ-proof ⦄ ⦄ ([∃]-intro index ⦃ intro a ⦄) = {!!} -} {- module _ {T : Type{ℓ₂}} {_▫_ : T → T → T} ⦃ group : Group(_▫_) ⦄ where open Group {T} ⦃ [≡]-equiv ⦄ {_▫_} (group) open Monoid {T} ⦃ [≡]-equiv ⦄ {_▫_} (monoid) commutationₗ : ∀{x y} → (x ▫ y ≡ y ▫ x) ← ((x ▫ y) ▫ inv (x) ≡ y) commutationₗ {x}{y} (comm) = symmetry( (congruence₁(_▫ x) (symmetry comm) ) 🝖 (associativity) 🝖 (congruence₁((x ▫ y) ▫_)) (inverseₗ) 🝖 (identityᵣ) ) -- (x▫y)▫inv(x) = y //comm -- y = (x▫y)▫inv(x) //[≡]-symmetry -- y▫x -- = ((x▫y)▫inv(x))▫x //congruence₁(expr ↦ expr ▫ x) (..) -- = (x▫y)▫(inv(x)▫x) //Group.associativity -- = (x▫y)▫id //congruence₁(_) Group.inverseₗ -- = x▫y //Group.identityᵣ -- x▫y = y▫x //[≡]-symmetry commutationᵣ : ∀{x y} → (x ▫ y ≡ y ▫ x) → ((x ▫ y) ▫ inv(x) ≡ y) commutationᵣ {x}{y} (comm) = (congruence₁(_▫ inv(x)) comm) 🝖 (associativity) 🝖 (congruence₁(y ▫_) (inverseᵣ)) 🝖 (identityᵣ) -- x▫y = y▫x //comm -- (x▫y)▫inv(x) -- = (y▫x)▫inv(x) //congruence₁(expr ↦ expr ▫ inv(x)) (..) -- = y▫(x▫inv(x)) //Group.associativity -- = y▫id //congruence₁(expr ↦ y ▫ expr) Group.inverseᵣ -- = y //Group.identityᵣ module _ {T : Type} {_▫_ : T → T → T} ⦃ commGroup : CommutativeGroup(_▫_) ⦄ where open CommutativeGroup {T} ⦃ [≡]-equiv ⦄ {_▫_} (commGroup) open Group {T} ⦃ [≡]-equiv ⦄ {_▫_} (group) open Monoid {T} ⦃ [≡]-equiv ⦄ {_▫_} (monoid) commutation : ∀{x y} → ((x ▫ y) ▫ inv(x) ≡ y) commutation = commutationᵣ(commutativity) module _ {T : Type} {_▫_ : T → T → T} ⦃ associativity : Associativity(_▫_) ⦄ where -}
Interested and qualified candidate can download the website from tnteu.ac.in in prescribed form and send your application on or before 27-09-2018. The prescribed format with photocopy of all relevant documents should be submitted to the address specified below. "Registrar i / c (by designation only), Tamil Nadu Teacher Education University, Chennai-600 097" "Registrar I / C, Tamil Nadu Teachers Education University" payable in Chennai.
[GOAL] z w : ℂ ⊢ z < w ↔ z ≤ w ∧ ¬w ≤ z [PROOFSTEP] dsimp [GOAL] z w : ℂ ⊢ z.re < w.re ∧ z.im = w.im ↔ (z.re ≤ w.re ∧ z.im = w.im) ∧ ¬(w.re ≤ z.re ∧ w.im = z.im) [PROOFSTEP] rw [lt_iff_le_not_le] [GOAL] z w : ℂ ⊢ (z.re ≤ w.re ∧ ¬w.re ≤ z.re) ∧ z.im = w.im ↔ (z.re ≤ w.re ∧ z.im = w.im) ∧ ¬(w.re ≤ z.re ∧ w.im = z.im) [PROOFSTEP] tauto [GOAL] x y : ℝ ⊢ ↑x ≤ ↑y ↔ x ≤ y [PROOFSTEP] simp [le_def, ofReal'] [GOAL] x y : ℝ ⊢ ↑x < ↑y ↔ x < y [PROOFSTEP] simp [lt_def, ofReal'] [GOAL] z w : ℂ ⊢ ¬z ≤ w ↔ w.re < z.re ∨ z.im ≠ w.im [PROOFSTEP] rw [le_def, not_and_or, not_le] [GOAL] z w : ℂ ⊢ ¬z < w ↔ w.re ≤ z.re ∨ z.im ≠ w.im [PROOFSTEP] rw [lt_def, not_and_or, not_lt] [GOAL] r : ℝ z : ℂ hz : ↑r ≤ z ⊢ z = ↑z.re [PROOFSTEP] ext [GOAL] case a r : ℝ z : ℂ hz : ↑r ≤ z ⊢ z.re = (↑z.re).re case a r : ℝ z : ℂ hz : ↑r ≤ z ⊢ z.im = (↑z.re).im [PROOFSTEP] rfl [GOAL] case a r : ℝ z : ℂ hz : ↑r ≤ z ⊢ z.im = (↑z.re).im [PROOFSTEP] simp only [← (Complex.le_def.1 hz).2, Complex.zero_im, Complex.ofReal_im]
lemma subspace_hyperplane2: "subspace {x. x \<bullet> a = 0}"
State Before: k : ℕ ⊢ k + 2 ≠ 1 State After: case h k : ℕ ⊢ 1 < k + 2 Tactic: apply Nat.ne_of_gt State Before: case h k : ℕ ⊢ 1 < k + 2 State After: case h.a k : ℕ ⊢ 0 < k + 1 Tactic: apply Nat.succ_lt_succ State Before: case h.a k : ℕ ⊢ 0 < k + 1 State After: no goals Tactic: apply Nat.zero_lt_succ
# Enter your code here. Read input from STDIN. Print output to STDOUT rej <- 0.12 answer1 <- pbinom(2, size = 10, prob = rej) write(round(answer1, 3), stdout()) answer2 <- pbinom(8, size = 10, prob = 1 - rej) write(round(answer2, 3), stdout())
From mathcomp Require Import ssreflect ssrfun seq. From rlzrs Require Import all_rlzrs choice_dict. Require Import facts all_baire cs smod prod sub func classical_cont classical_mach Duop. Require Import FunctionalExtensionality Classical. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope cs_scope. Lemma ass_cont (X Y: cs) (f: X -> Y): f \from (codom (@associate X Y)) <-> f \is_continuous. Proof. split => [[psi /=rlzr] | [F [rlzr cont]]]; first by exists \F_(U psi); split; last exact/FM_cont. have [psi val]:= (U_universal (someq X) (somea X) (fun _ => somea Y) (Q_count X) cont). by exists psi; exact/ntrvw.tight_rlzr/val. Qed. Definition exist_c (X Y: cs) (f: X -> Y) (cont: f \is_continuous): (X c-> Y). Proof. by exists f; apply/ass_cont. Defined. Lemma prod_uprp_cont (X Y Z: cs) (f: Z c-> X) (g: Z c-> Y): exists! (F: Z c-> (cs_prod X Y)), (forall z, (projT1 F z).1 = (projT1 f) z) /\ (forall z, (projT1 F z).2 = (projT1 g) z). Proof. set F :Z -> X \*_cs Y := (projT1 f **_f projT1 g) \o_f mf.diag. have Fcont: F \is_continuous. - exact/(cont_comp _ (facts.diag_cont Z))/fprd_cont/ass_cont/(projT2 g)/ass_cont/(projT2 f). exists (exist_c Fcont); split => // G [] eq eq'. apply/eq_sub/functional_extensionality => z; symmetry. exact/injective_projections/eq'/eq. Qed. Definition cs_comp (X Y Z: cs) (f: X c-> Y) (g: Y c-> Z): (X c-> Z). Proof. exists ((projT1 g) \o_f projT1 f); apply/ass_cont/cont_comp. - exact/ass_cont/(projT2 g). exact/ass_cont/(projT2 f). Defined. Notation "g \o_cs f" := (cs_comp f g) (at level 29): cs_scope. Lemma cs_comp_spec (X Y Z: cs)(f: X c-> Y) (g: Y c-> Z): projT1 (g \o_cs f) =1 (projT1 g \o_f projT1 f). Proof. done. Qed. Local Open Scope baire_scope. Lemma eval_rlzr_cntop (X Y: cs): (@eval_rlzr (queries X) (queries Y) (answers X) (answers Y))|_(dom (rep (X c-> Y \*_cs X))) \is_continuous_operator. Proof. rewrite !cont_spec => psiphi [Fpsiphi [[[f x] [psinf phinx]] /eval_rlzr_val val]]. rewrite /= in psinf phinx; have phifd: (rprj psiphi) \from dom \F_(U (lprj psiphi)) by exists Fpsiphi. have [FqM [FsM prp]]:= @FM_cont_spec (queries X) (queries Y) (answers X) (answers Y). have [subs [subs' [c_prp _]]]:= prp (lprj psiphi) (rprj psiphi). have [qf qvl]:= subs (rprj psiphi) phifd. have [sf svl]:= subs' (rprj psiphi) phifd. move: subs subs' => _ _. have [qfmodF [qfmodqF _]]:= c_prp qf qvl. move: c_prp => _. exists (fun q' => map inl (sf q') ++ map inr (qf q')) => q'. exists (Fpsiphi q') => psi'phi' /coin_cat[coin coin']. have : (rprj psiphi) \and (rprj psi'phi') \coincide_on (qf q'). - by elim: (qf q') coin' => // q K ih /= [eq /ih]; split; first rewrite /rprj eq. have: (lprj psiphi) \and (lprj psi'phi') \coincide_on (sf q'). - by elim: (sf q') coin => // q K ih /= [eq /ih]; split; first rewrite /lprj eq. move: coin coin' => _ _ coin coin'. rewrite det_restr => [[[f' x'] [/=psi'nf' phi'nx']]] Fpsi'phi'/eval_rlzr_val val'. rewrite /= in psi'nf' phi'nx'; pose psiphi':= name_pair (lprj psiphi) (rprj psi'phi'). have psiphi'nfx': psiphi' \describes (f, x') \wrt (X c-> Y \*_cs X). - by trivial. have [Fpsiphi' val'']: psiphi' \from dom eval_rlzr. - by have []:= eval_rlzr_crct psiphi'nfx'; first exact/F2MF_dom. have [a' tempcrt]:= qfmodF q'. have crt := crt_icf val tempcrt _; move: a' tempcrt => _ _. rewrite -(crt (rprj psi'phi') _ Fpsiphi' val''); last by apply/coin'. have [subs [subs' [cprp _]]]:= prp (lprj psiphi) (rprj psi'phi'). have [ | qf' qvl']:= subs (rprj psi'phi'); first by exists Fpsiphi'. move: subs subs' => _ _. have [_ [_ qf'modsF]]:= cprp qf' qvl'. move: cprp => _. have mfeq: qf q' = qf' q'. - have [a' crt'] := qfmodqF q'. suff ->: qf' q' = a' by apply/crt'; first apply/coin_ref. by apply/crt'; first apply/coin'. have [_ [subs' [_ vprp]]]:= prp (lprj psiphi) (rprj psi'phi'). have [ | sf' svl']:= subs' (rprj psi'phi'); first by exists Fpsiphi'. have [sfmodF _]:= vprp sf' svl'. move: vprp prp => _ _. have eq: sf q' = sf' q'. - have [a' crt']:= qf'modsF q'. have ->: sf' q' = a' by apply/crt'; first by rewrite -mfeq; apply/coin_ref. by apply/crt'; first by rewrite -mfeq; apply/coin_sym/coin'. have [a' crt']:= sfmodF q'. have ->: Fpsi'phi' q' = a' by apply/crt'; first by rewrite -eq; apply/coin. by symmetry; apply/crt'; first by rewrite -eq; apply/coin_ref. Qed. Local Close Scope baire_scope. Lemma eval_cont (X Y: cs): (@evaluation X Y) \is_continuous. Proof. exists (@eval_rlzr (queries X) (queries Y) (answers X) (answers Y))|_(dom (rep (X c-> Y \*_cs X))). split; last exact/eval_rlzr_cntop. rewrite rlzr_F2MF => psiphi fx psiphinfx. have [ | [Fpsiphi val] prp]:= eval_rlzr_crct psiphinfx; first exact/F2MF_dom. split => [ | Fq [_ val']]; first by exists Fpsiphi; split; first by exists fx. by have [f'x' [nm ->]]:= prp Fq val'. Qed. Definition pt_eval (X Y: cs) (x: X) (f: X c-> Y):= evaluation (f, x). Lemma ptvl_val_cont (X Y: cs) (x: X): (@pt_eval X Y x) \is_continuous. Proof. have [phi phinx]:= get_description x. exists (\F_(U (D phi))). rewrite rlzr_F2MF. split => [psi f psinf | ]; last exact/FM_cont. have [ | [Fphi /D_spec val] prp]:= psinf phi x phinx; first exact/F2MF_dom. split => [ | Fphi' /D_spec val']; first by exists Fphi. have [fa [Fphi'nfa]]:= prp Fphi' val'. by rewrite /pt_eval /evaluation => ->. Qed. Definition point_evaluation (X Y: cs) (x: X):= exist_c (@ptvl_val_cont X Y x). Lemma ptvl_cont (X Y: cs): (@point_evaluation X Y) \is_continuous. Proof. exists (F2MF (@D (queries X) (queries Y) (answers X) (answers Y))). rewrite F2MF_rlzr_F2MF; split => [phi x phinx psi f psinf _| ]; last first. - rewrite cont_F2MF; exact/D_cont. have [ | [Fphi /D_spec val] prp]:= psinf phi x phinx; first exact/F2MF_dom. split => [ | Fphi' /D_spec val']; first by exists (Fphi). have [fa [Fphinfa]]:= prp Fphi' val'. rewrite /point_evaluation/pt_eval/evaluation/= => ->. by exists fa. Qed.
\paragraph{Implementation} We have implemented Bounded Refinement Types in \toolname. Our code and examples can be found on github at \url{https://github.com/ucsd-progsys/liquidhaskell/tree/master/benchmarks/icfp15}. \paragraph{Soundness} Below we prove soundness of \boundedcorelan by reduction to \corelan. \begin{theorem*}[Semantics Preservation] \label{theorem:operational} If $\txexpr{\emptyset}{\emptyset}{e}{e'}$ and $e \boundedgoestostar{c}$ then $e' \goestostar{c}$. \end{theorem*} \begin{proof} By assumption, there exists a sequence $e \equiv e_1 \boundedgoesto{e_2} \boundedgoesto{} \dots \boundedgoesto{e_n\equiv c} $. % Let $i$ be the largest index in which rule \rtobound was applied. % Then, for some $\phi$ and $\phi'$, $e_i$ contains a sub-expression of the form $\econstantconstraint{(\econstraint{\phi}{e_i^0})}{\phi'}$. % Let $e_i^1$ be the expression we get if we replace $\econstantconstraint{(\econstraint{\phi}{e_i^0})}{\phi'}$ with $e_i^0$ in $e_i$. % By the way we choose $i$, there exist a sequence $e_i^1 \goestostar{c}$. Let $e_i^2$ be the expression we get if we replace $\econstantconstraint{(\econstraint{\phi}{e_i^0})}{\phi'}$ with $\eapp{(\efunt{f}{\txbound{\phi}}{e_i^0})}{(\ctofun{\phi'})}$ in $e_i$. % Then, since $f$ does not appear in $e_i^0$, $e_i^2 \goestostar{c}$. % Finally, let $g \defeq \ctofun{\phi'}$, then by the definition of $\ctofun{\cdot}$ we have that $\forall e_1 \dots e_n$ if there exists a type $\tau$ such that $\emptyset \vdash g \ e_1 \dots e_n : \tau $, then $g \ e_1 \dots e_n \goestostar{true}$. % Thus, for any expression, if $e \goestostar{c}$, then $\elett{t}{f \ e_1 \dots e_n}{e}\goestostar{c}$ From the above, by the way we choose $i$ we have that there exists a sequence % $\txex{e_i} \hookrightarrow \dots \hookrightarrow {c}$. Since $n$ is finite, we iteratively apply the above procedure to $e \equiv e_1\boundedgoesto{} \dots \boundedgoesto{} \txex{e_i}\hookrightarrow \dots \hookrightarrow {c}$. until we get the sequence $ {\txex{e}}\goestostar{c}$. \end{proof} The soundness of \corelan as stated in~\cite{vazou13}: \begin{theorem*}[Soundness of \corelan] \label{theorem:core} %\cite{vazou13} If $\hastype{\emptyset}{e}{\sigma}$ then $e \not \goestostar{\ecrash}$. \end{theorem*} \begin{theorem*}[Soundness] \label{theorem:bounded} If $\txexpr{\emptyset}{\emptyset}{e}{e'}$ and $\hastype{\emptyset}{e'}{\sigma}$ then $e \not \boundedgoestostar{\ecrash}$. \end{theorem*} \begin{proof} Since $\hastype{\emptyset}{e'}{\sigma}$ then by Soundness of \corelan $e' \not \goestostar{\ecrash}$ and thus by Semantics Preservation $e \not \boundedgoestostar{\ecrash}$. \end{proof}
lemma (in normalization_semidom) associatedE1: assumes "normalize a = normalize b" obtains u where "is_unit u" "a = u * b"
#ifndef BOOST_NETWORK_URL_HTTP_DETAIL_PARSE_SPECIFIC_HPP_ #define BOOST_NETWORK_URL_HTTP_DETAIL_PARSE_SPECIFIC_HPP_ // Copyright 2009 Dean Michael Berris, Jeroen Habraken. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt of copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/algorithm/string/predicate.hpp> #include <boost/network/traits/string.hpp> #include <boost/network/uri/detail/parse_uri.hpp> namespace boost { namespace network { namespace uri { namespace detail { template <> inline bool parse_specific< tags::http_default_8bit_tcp_resolve >( uri_parts<tags::http_default_8bit_tcp_resolve> & parts ) { if ((parts.scheme.size() < 4) || (parts.scheme.size() > 5)) return false; if (parts.scheme.size() == 4) { if (not boost::iequals(parts.scheme, "http")) return false; } else { // size is 5 if (not boost::iequals(parts.scheme, "https")) return false; } if ((not parts.host) || parts.host->empty()) return false; return true; } } // namespace detail } // namespace uri } // namespace network } // namespace boost #endif
To order your AK London items, please let us know which items (referring to the item number) you would like in the message box. A member of our team will be in touch with you shortly. Stay up-to-date with exclusive AK London events, offers & product releases by joining our mailing list! Thank you! A member of our team will contact you shortly about your order.
RECURSIVE SUBROUTINE factorial ( n, result ) ! ! Purpose: ! To calculate the factorial function ! | n(n-1)! n >= 1 ! n ! = | ! | 1 n = 0 ! ! Record of revisions: ! Date Programmer Description of change ! ==== ========== ===================== ! 12/07/06 S. J. Chapman Original code ! IMPLICIT NONE ! Data dictionary: declare calling parameter types & definitions INTEGER, INTENT(IN) :: n ! Value to calculate INTEGER, INTENT(OUT) :: result ! Result ! Data dictionary: declare local variable types & definitions INTEGER :: temp ! Temporary variable IF ( n >= 1 ) THEN CALL factorial ( n-1, temp ) result = n * temp ELSE result = 1 END IF END SUBROUTINE factorial
(* Code for Software Foundations, Chapter 5: Poly: Polymorphism and Higher-Order Functions *) Require Import Arith. Require Import List. (* mumble_grumble *) Module MumbleGrumble. Inductive mumble : Type := | a : mumble | b : mumble -> nat -> mumble | c : mumble. Inductive grumble (T : Type) : Type := | d : mumble -> grumble T | e : T -> grumble T. (* Which of the following are well-typed elements of grumble X for some type X ? d (b a 5) : F d mumble (b a 5) : T d bool (b a 5) : T e bool true : T e mumble (b c 0) : T e bool (b c 0) : F c : T *) End MumbleGrumble. (* poly_exercises *) Theorem app_nil_r : forall X : Type, forall l : list X, l ++ nil = l. Proof. induction l. + simpl; reflexivity. + simpl. pattern l at 2. rewrite IHl. reflexivity. Qed. Theorem app_nil_l : forall X : Type, forall l : list X, nil ++ l = l. Proof. reflexivity. Qed. Lemma cons_injection : forall (A : Type) (n : A) (l1 l2 : list A), l1 = l2 -> n :: l1 = n :: l2. Proof. intros A n l1 l2. induction l1, l2. + simpl; reflexivity. + inversion 1. + inversion 1. + intros h1; rewrite h1; reflexivity. Qed. Theorem app_assoc : forall (A : Type) (l m n : list A), l ++ m ++ n = (l ++ m) ++ n. Proof. induction l, m. + simpl; reflexivity. + simpl; reflexivity. + simpl; rewrite app_nil_r; reflexivity. + simpl. intros n. apply (cons_injection A a (l ++ a0 :: m ++ n) ((l ++ a0 :: m) ++ n)). rewrite <- IHl; trivial. Qed. Theorem app_length : forall (X : Type) (l1 l2 : list X), length (l1 ++ l2) = length l1 + length l2. Proof. intros X l1 l2. induction l1. + simpl; reflexivity. + simpl; rewrite IHl1; reflexivity. Qed. (* more_poly_exercises *) Theorem rev_app_distr : forall (X : Type) (l1 l2 : list X), rev (l1 ++ l2) = rev l2 ++ rev l1. Proof. intros X l1 l2. induction l1, l2. + simpl; reflexivity. + simpl; rewrite app_nil_r; reflexivity. + simpl; repeat rewrite app_nil_r; reflexivity. + simpl. rewrite app_assoc. rewrite IHl1. assert(app_xs_r : forall (l1 l2 l3 : list X), l1 = l2 -> l1 ++ l3 = l2 ++ l3). - intros l1' l2' l3' h1. rewrite h1; reflexivity. - apply app_xs_r. apply app_xs_r. simpl; reflexivity. Qed. Theorem rev_involutive : forall (X : Type) (l : list X), rev (rev l) = l. Proof. induction l. + simpl; reflexivity. + simpl. rewrite rev_app_distr. rewrite IHl. simpl; reflexivity. Qed. (* combine_checks *) (* Check @combine. Eval compute in combine (1::2::nil) (false::false::true::true::nil). *) (* split *) Fixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) := match l with | nil => (nil, nil) | (a, b)::xs => let (u, v) := split xs in (a::u, b::v) end. (* Eval compute in split ((1, false)::(2, false)::nil). *) (* hd_error_poly *) Definition hd_error {X : Type} (l : list X) : option X := match l with | nil => None | x::xs => Some x end. (* filter_even_gt7 *) Fixpoint filter {X : Type} (test : X -> bool) (l : list X) {struct l} : list X := match l with | nil => nil | x::xs => let rest := filter test xs in match test x with | true => x :: rest | false => rest end end. Definition filter_even_gt7 (l : list nat) : list nat := filter (fun x => andb (Nat.even x) (Nat.ltb 7 x)) l. (* partition *) Definition partition {X : Type} (test : X -> bool) (l : list X) : (list X) * (list X) := ((filter test l), filter (fun x => negb (test x)) l). (* map_rev *) Fixpoint map {X Y : Type} (f : X -> Y) (l : list X) {struct l} : list Y := match l with | nil => nil | x::xs => f x :: map f xs end. Lemma map_append_eq : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X), map f (l1 ++ l2) = map f l1 ++ map f l2. Proof. intros X Y f l1 l2. induction l1. + simpl; reflexivity. + simpl; rewrite IHl1; reflexivity. Qed. Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X), map f (rev l) = rev (map f l). Proof. induction l. + simpl; reflexivity. + simpl. rewrite map_append_eq. simpl. rewrite IHl. reflexivity. Qed. (* flat_map *) Fixpoint flat_map {X Y : Type} (f : X -> list Y) (l : list X) {struct l} : list Y := match l with | nil => nil | x::xs => f x ++ flat_map f xs end. Definition option_map {X Y : Type} (f : X -> Y) (x : option X) : option Y := match x with | None => None | Some x' => Some (f x') end. (* fold_types_different *) Fixpoint fold {X Y : Type} (f : X -> Y -> Y) (l : list X) (a : Y) : Y := match l with | nil => a | x::xs => f x (fold f xs a) end. (* The type X and Y are different: X: nat Y: bool. *) Definition all_even (xs : list nat) : bool := fold (fun x acc => andb acc (Nat.even x)) xs true. (* fold_length *) Definition fold_length {X : Type} (l : list X) : nat := fold (fun _ acc => S acc) l O. Theorem fold_length_correct : forall (X : Type) (l : list X), fold_length l = length l. Proof. induction l. + reflexivity. + simpl. rewrite <- IHl. reflexivity. Qed. (* fold_map *) Definition fold_map {X Y : Type} (f : X -> Y) (l : list X) : list Y := fold (fun x acc => f x :: acc) l nil. Theorem fold_map_correct : forall (X Y : Type) (f : X -> Y) (l : list X), fold_map f l = map f l. Proof. induction l. + simpl; reflexivity. + simpl; rewrite <- IHl. reflexivity. Qed. (* currying *) Definition prod_curry {X Y Z : Type} (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y). Definition prod_uncurry {X Y Z : Type} (f : X -> Y -> Z) (t : X * Y) : Z := match t with | (x, y) => f x y end. Theorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y, prod_curry (prod_uncurry f) x y = f x y. Proof. reflexivity. Qed. Theorem curry_uncurry : forall (X Y Z : Type) (f : (X * Y) -> Z) t, prod_uncurry (prod_curry f) t = f t. Proof. induction t. simpl; reflexivity. Qed. (* church_numerals *) Module Church. Definition church := forall X : Type, (X -> X) -> (X -> X). (* zero *) Definition zero : church := fun (X : Type) (f : X -> X) (x : X) => x. (* one *) Definition one : church := fun (X : Type) (f : X -> X) (x : X) => f x. (* two *) Definition two : church := fun (X : Type) (f : X -> X) (x : X) => f (f x). (* three *) Definition three : church := fun (X : Type) (f : X -> X) (x : X) => f (f (f x)). (* succ n *) Definition succ (n : church) : church := fun (X : Type) (f : X -> X) (x : X) => f ((n X f) x). (* n + m *) Definition plus (n m : church) : church := fun (X : Type) (f : X -> X) (x : X) => (m X f) ((n X f) x). (* n * m *) Definition mult (n m : church) : church := fun (X : Type) (f : X -> X) => m X (n X f). (* n ^ m *) Definition exp (n m : church) : church := fun (X : Type) => (m (X -> X)) (n X). (* Eval compute in exp two three. Eval compute in exp three two. *) End Church. Module ChurchWithFold. (* TODO : how to represent church numerals in Coq as the paper: <Church numerals, Twice!>. *) End ChurchWithFold.
Formal statement is: lemma\<^marker>\<open>tag unimportant\<close> orthogonal_transformation_surj: "orthogonal_transformation f \<Longrightarrow> surj f" for f :: "'a::euclidean_space \<Rightarrow> 'a::euclidean_space" Informal statement is: If $f$ is an orthogonal transformation, then $f$ is surjective.
[GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V : FdRep k G g h : G ⊢ character V (h * g) = character V (g * h) [PROOFSTEP] simp only [trace_mul_comm, character, map_mul] [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V : FdRep k G ⊢ character V 1 = ↑(finrank k (CoeSort.coe V)) [PROOFSTEP] simp only [character, map_one, trace_one] [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G ⊢ character (V ⊗ W) = character V * character W [PROOFSTEP] ext g [GOAL] case h k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G g : G ⊢ character (V ⊗ W) g = (character V * character W) g [PROOFSTEP] convert trace_tensorProduct' (V.ρ g) (W.ρ g) [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G ⊢ character (Action.FunctorCategoryEquivalence.inverse.obj (Action.FunctorCategoryEquivalence.functor.obj V ⊗ Action.FunctorCategoryEquivalence.functor.obj W)) = character V * character W [PROOFSTEP] simp [← char_tensor] [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G i : V ≅ W ⊢ character V = character W [PROOFSTEP] ext g [GOAL] case h k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G i : V ≅ W g : G ⊢ character V g = character W g [PROOFSTEP] simp only [character, FdRep.Iso.conj_ρ i] [GOAL] case h k : Type u inst✝¹ : Field k G : Type u inst✝ : Monoid G V W : FdRep k G i : V ≅ W g : G ⊢ ↑(trace k (CoeSort.coe V)) (↑(ρ V) g) = ↑(trace k (CoeSort.coe W)) (↑(LinearEquiv.conj (isoToLinearEquiv i)) (↑(ρ V) g)) [PROOFSTEP] exact (trace_conj' (V.ρ g) _).symm [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Group G V : FdRep k G g h : G ⊢ character V (h * g * h⁻¹) = character V g [PROOFSTEP] rw [char_mul_comm, inv_mul_cancel_left] [GOAL] k : Type u inst✝¹ : Field k G : Type u inst✝ : Group G V W : FdRep k G g : G ⊢ character (of (linHom (ρ V) (ρ W))) g = character V g⁻¹ * character W g [PROOFSTEP] rw [← char_iso (dualTensorIsoLinHom _ _), char_tensor, Pi.mul_apply, char_dual] [GOAL] k : Type u inst✝³ : Field k G : Type u inst✝² : Group G inst✝¹ : Fintype G inst✝ : Invertible ↑(Fintype.card G) V : FdRep k G ⊢ ⅟↑(Fintype.card G) • ∑ g : G, character V g = ↑(finrank k { x // x ∈ invariants (ρ V) }) [PROOFSTEP] erw [← (isProj_averageMap V.ρ).trace] -- Porting note: Changed `rw` to `erw` [GOAL] k : Type u inst✝³ : Field k G : Type u inst✝² : Group G inst✝¹ : Fintype G inst✝ : Invertible ↑(Fintype.card G) V : FdRep k G ⊢ ⅟↑(Fintype.card G) • ∑ g : G, character V g = ↑(trace k (CoeSort.coe V)) (averageMap (ρ V)) [PROOFSTEP] simp [character, GroupAlgebra.average, _root_.map_sum] [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W ⊢ ⅟↑(Fintype.card ↑G) • ∑ g : ↑G, character V g * character W g⁻¹ = if Nonempty (V ≅ W) then 1 else 0 [PROOFSTEP] conv_lhs => enter [2, 2, g] rw [mul_comm, ← char_dual, ← Pi.mul_apply, ← char_tensor] rw [char_iso (FdRep.dualTensorIsoLinHom W.ρ V)] -- The average over the group of the character of a representation equals the dimension of the -- space of invariants. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W | ⅟↑(Fintype.card ↑G) • ∑ g : ↑G, character V g * character W g⁻¹ [PROOFSTEP] enter [2, 2, g] rw [mul_comm, ← char_dual, ← Pi.mul_apply, ← char_tensor] rw [char_iso (FdRep.dualTensorIsoLinHom W.ρ V)] -- The average over the group of the character of a representation equals the dimension of the -- space of invariants. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W | ⅟↑(Fintype.card ↑G) • ∑ g : ↑G, character V g * character W g⁻¹ [PROOFSTEP] enter [2, 2, g] rw [mul_comm, ← char_dual, ← Pi.mul_apply, ← char_tensor] rw [char_iso (FdRep.dualTensorIsoLinHom W.ρ V)] -- The average over the group of the character of a representation equals the dimension of the -- space of invariants. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W | ⅟↑(Fintype.card ↑G) • ∑ g : ↑G, character V g * character W g⁻¹ [PROOFSTEP] enter [2, 2, g] [GOAL] case h k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W g : ↑G | character V g * character W g⁻¹ [PROOFSTEP] rw [mul_comm, ← char_dual, ← Pi.mul_apply, ← char_tensor] [GOAL] case h k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W g : ↑G | character (of (dual (ρ W)) ⊗ V) g [PROOFSTEP] rw [char_iso (FdRep.dualTensorIsoLinHom W.ρ V)] -- The average over the group of the character of a representation equals the dimension of the -- space of invariants. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W ⊢ ⅟↑(Fintype.card ↑G) • ∑ g : ↑G, character (of (linHom (ρ W) (ρ V))) g = if Nonempty (V ≅ W) then 1 else 0 [PROOFSTEP] rw [average_char_eq_finrank_invariants] [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W ⊢ ↑(finrank k { x // x ∈ invariants (ρ (of (linHom (ρ W) (ρ V)))) }) = if Nonempty (V ≅ W) then 1 else 0 [PROOFSTEP] rw [show (of (linHom W.ρ V.ρ)).ρ = linHom W.ρ V.ρ from FdRep.of_ρ (linHom W.ρ V.ρ)] -- The space of invariants of `Hom(W, V)` is the subspace of `G`-equivariant linear maps, -- `Hom_G(W, V)`. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W ⊢ ↑(finrank k { x // x ∈ invariants (linHom (ρ W) (ρ V)) }) = if Nonempty (V ≅ W) then 1 else 0 [PROOFSTEP] erw [(linHom.invariantsEquivFdRepHom W V).finrank_eq] -- Porting note: Changed `rw` to `erw` -- By Schur's Lemma, the dimension of `Hom_G(W, V)` is `1` is `V ≅ W` and `0` otherwise. [GOAL] k : Type u inst✝⁵ : Field k G : GroupCat inst✝⁴ : IsAlgClosed k inst✝³ : Fintype ↑G inst✝² : Invertible ↑(Fintype.card ↑G) V W : FdRep k ↑G inst✝¹ : Simple V inst✝ : Simple W ⊢ ↑(finrank k (W ⟶ V)) = if Nonempty (V ≅ W) then 1 else 0 [PROOFSTEP] rw_mod_cast [finrank_hom_simple_simple W V, Iso.nonempty_iso_symm]
(* OR *) Definition or_bool (b1 b2 : bool) : bool := match b1 , b2 with | true, b2 => true | b1, true => true | b1, b2 => false end. (* XOR *) Definition xor_bool (b1 b2 : bool) : bool := match b1 , b2 with | true, false => true | false, true => true | b1, b2 => false end.
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.logic.nontrivial import Mathlib.algebra.group.units_hom import Mathlib.algebra.group.inj_surj import Mathlib.algebra.group_with_zero.defs import Mathlib.PostPort universes u_1 u_3 u u_2 u_4 u_5 namespace Mathlib /-! # Groups with an adjoined zero element This file describes structures that are not usually studied on their own right in mathematics, namely a special sort of monoid: apart from a distinguished “zero element” they form a group, or in other words, they are groups with an adjoined zero element. Examples are: * division rings; * the value monoid of a multiplicative valuation; * in particular, the non-negative real numbers. ## Main definitions Various lemmas about `group_with_zero` and `comm_group_with_zero`. To reduce import dependencies, the type-classes themselves are in `algebra.group_with_zero.defs`. ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ /-- Pullback a `mul_zero_class` instance along an injective function. -/ protected def function.injective.mul_zero_class {M₀ : Type u_1} {M₀' : Type u_3} [mul_zero_class M₀] [Mul M₀'] [HasZero M₀'] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (mul : ∀ (a b : M₀'), f (a * b) = f a * f b) : mul_zero_class M₀' := mul_zero_class.mk Mul.mul 0 sorry sorry /-- Pushforward a `mul_zero_class` instance along an surjective function. -/ protected def function.surjective.mul_zero_class {M₀ : Type u_1} {M₀' : Type u_3} [mul_zero_class M₀] [Mul M₀'] [HasZero M₀'] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (mul : ∀ (a b : M₀), f (a * b) = f a * f b) : mul_zero_class M₀' := mul_zero_class.mk Mul.mul 0 sorry sorry theorem mul_eq_zero_of_left {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} (h : a = 0) (b : M₀) : a * b = 0 := Eq.symm h ▸ zero_mul b theorem mul_eq_zero_of_right {M₀ : Type u_1} [mul_zero_class M₀] {b : M₀} (a : M₀) (h : b = 0) : a * b = 0 := Eq.symm h ▸ mul_zero a theorem left_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} : a * b ≠ 0 → a ≠ 0 := mt fun (h : a = 0) => mul_eq_zero_of_left h b theorem right_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a) theorem ne_zero_and_ne_zero_of_mul {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := { left := left_ne_zero_of_mul h, right := right_ne_zero_of_mul h } theorem mul_eq_zero_of_ne_zero_imp_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] {a : M₀} {b : M₀} (h : a ≠ 0 → b = 0) : a * b = 0 := sorry /-- Pushforward a `no_zero_divisors` instance along an injective function. -/ protected theorem function.injective.no_zero_divisors {M₀ : Type u_1} {M₀' : Type u_3} [Mul M₀] [HasZero M₀] [Mul M₀'] [HasZero M₀'] [no_zero_divisors M₀'] (f : M₀ → M₀') (hf : function.injective f) (zero : f 0 = 0) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : no_zero_divisors M₀ := sorry theorem eq_zero_of_mul_self_eq_zero {M₀ : Type u_1} [Mul M₀] [HasZero M₀] [no_zero_divisors M₀] {a : M₀} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) id id /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem mul_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b = 0 ↔ a = 0 ∨ b = 0 := { mp := eq_zero_or_eq_zero_of_mul_eq_zero, mpr := fun (o : a = 0 ∨ b = 0) => or.elim o (fun (h : a = 0) => mul_eq_zero_of_left h b) (mul_eq_zero_of_right a) } /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem zero_eq_mul {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : 0 = a * b ↔ a = 0 ∨ b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * b ↔ a = 0 ∨ b = 0)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = 0 ↔ a = 0 ∨ b = 0)) (propext mul_eq_zero))) (iff.refl (a = 0 ∨ b = 0))) /-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them are nonzero. -/ theorem mul_ne_zero_iff {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := iff.trans (not_congr mul_eq_zero) not_or_distrib theorem mul_ne_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := iff.mpr mul_ne_zero_iff { left := ha, right := hb } /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is `b * a`. -/ theorem mul_eq_zero_comm {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b = 0 ↔ b * a = 0 := iff.trans mul_eq_zero (iff.trans (or_comm (a = 0) (b = 0)) (iff.symm mul_eq_zero)) /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is `b * a`. -/ theorem mul_ne_zero_comm {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} {b : M₀} : a * b ≠ 0 ↔ b * a ≠ 0 := not_congr mul_eq_zero_comm theorem mul_self_eq_zero {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} : a * a = 0 ↔ a = 0 := sorry theorem zero_eq_mul_self {M₀ : Type u_1} [mul_zero_class M₀] [no_zero_divisors M₀] {a : M₀} : 0 = a * a ↔ a = 0 := sorry /-- In a nontrivial monoid with zero, zero and one are different. -/ @[simp] theorem zero_ne_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : 0 ≠ 1 := sorry @[simp] theorem one_ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : 1 ≠ 0 := ne.symm zero_ne_one theorem ne_zero_of_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} (h : a = 1) : a ≠ 0 := trans_rel_right ne h one_ne_zero theorem left_ne_zero_of_mul_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} {b : M₀} (h : a * b = 1) : a ≠ 0 := left_ne_zero_of_mul (ne_zero_of_eq_one h) theorem right_ne_zero_of_mul_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} {b : M₀} (h : a * b = 1) : b ≠ 0 := right_ne_zero_of_mul (ne_zero_of_eq_one h) /-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/ protected theorem pullback_nonzero {M₀ : Type u_1} {M₀' : Type u_3} [monoid_with_zero M₀] [nontrivial M₀] [HasZero M₀'] [HasOne M₀'] (f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' := sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [monoid_with_zero M₀] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : monoid_with_zero M₀' := monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [monoid_with_zero M₀] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : monoid_with_zero M₀' := monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.comm_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [comm_monoid_with_zero M₀] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := comm_monoid_with_zero.mk comm_monoid.mul sorry comm_monoid.one sorry sorry sorry mul_zero_class.zero sorry sorry /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.comm_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [HasZero M₀'] [Mul M₀'] [HasOne M₀'] [comm_monoid_with_zero M₀] (f : M₀ → M₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀), f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := comm_monoid_with_zero.mk comm_monoid.mul sorry comm_monoid.one sorry sorry sorry mul_zero_class.zero sorry sorry namespace units /-- An element of the unit group of a nonzero monoid with zero represented as an element of the monoid is nonzero. -/ @[simp] theorem ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] (u : units M₀) : ↑u ≠ 0 := left_ne_zero_of_mul_eq_one (mul_inv u) -- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume -- `nonzero M₀`. @[simp] theorem mul_left_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] (u : units M₀) {a : M₀} : a * ↑u = 0 ↔ a = 0 := sorry @[simp] theorem mul_right_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 := sorry end units namespace is_unit theorem ne_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := (fun (_a : is_unit a) => Exists.dcases_on _a fun (w : units M₀) (h : ↑w = a) => idRhs ((fun (_x : M₀) => _x ≠ 0) a) (h ▸ units.ne_zero w)) ha theorem mul_right_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] {a : M₀} {b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 := sorry theorem mul_left_eq_zero {M₀ : Type u_1} [monoid_with_zero M₀] {a : M₀} {b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 := sorry end is_unit /-- In a monoid with zero, if zero equals one, then zero is the only element. -/ theorem eq_zero_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) (a : M₀) : a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a = 0)) (Eq.symm (mul_one a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = 0)) (Eq.symm h))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 0 = 0)) (mul_zero a))) (Eq.refl 0))) /-- In a monoid with zero, if zero equals one, then zero is the unique element. Somewhat arbitrarily, we define the default element to be `0`. All other elements will be provably equal to it, but not necessarily definitionally equal. -/ def unique_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) : unique M₀ := unique.mk { default := 0 } (eq_zero_of_zero_eq_one h) /-- In a monoid with zero, zero equals one if and only if all elements of that semiring are equal. -/ theorem subsingleton_iff_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] : 0 = 1 ↔ subsingleton M₀ := { mp := fun (h : 0 = 1) => unique.subsingleton, mpr := fun (h : subsingleton M₀) => subsingleton.elim 0 1 } theorem subsingleton_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] : 0 = 1 → subsingleton M₀ := iff.mp subsingleton_iff_zero_eq_one theorem eq_of_zero_eq_one {M₀ : Type u_1} [monoid_with_zero M₀] (h : 0 = 1) (a : M₀) (b : M₀) : a = b := subsingleton.elim a b @[simp] theorem is_unit_zero_iff {M₀ : Type u_1} [monoid_with_zero M₀] : is_unit 0 ↔ 0 = 1 := sorry @[simp] theorem not_is_unit_zero {M₀ : Type u_1} [monoid_with_zero M₀] [nontrivial M₀] : ¬is_unit 0 := mt (iff.mp is_unit_zero_iff) zero_ne_one /-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/ theorem zero_ne_one_or_forall_eq_0 (M₀ : Type u_1) [monoid_with_zero M₀] : 0 ≠ 1 ∨ ∀ (a : M₀), a = 0 := not_or_of_imp eq_zero_of_zero_eq_one protected instance cancel_monoid_with_zero.to_no_zero_divisors {M₀ : Type u_1} [cancel_monoid_with_zero M₀] : no_zero_divisors M₀ := no_zero_divisors.mk fun (a b : M₀) (ab0 : a * b = 0) => dite (a = 0) (fun (h : a = 0) => Or.inl h) fun (h : ¬a = 0) => Or.inr (cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = a * 0)) ab0)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * 0)) (mul_zero a))) (Eq.refl 0)))) theorem mul_left_inj' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} (hc : c ≠ 0) : a * c = b * c ↔ a = b := { mp := mul_right_cancel' hc, mpr := fun (h : a = b) => h ▸ rfl } theorem mul_right_inj' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} (ha : a ≠ 0) : a * b = a * c ↔ b = c := { mp := mul_left_cancel' ha, mpr := fun (h : b = c) => h ▸ rfl } @[simp] theorem mul_eq_mul_right_iff {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} : a * c = b * c ↔ a = b ∨ c = 0 := sorry @[simp] theorem mul_eq_mul_left_iff {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀} : a * b = a * c ↔ b = c ∨ a = 0 := sorry /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.cancel_monoid_with_zero {M₀ : Type u_1} {M₀' : Type u_3} [cancel_monoid_with_zero M₀] [HasZero M₀'] [Mul M₀'] [HasOne M₀'] (f : M₀' → M₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : M₀'), f (x * y) = f x * f y) : cancel_monoid_with_zero M₀' := cancel_monoid_with_zero.mk monoid.mul sorry monoid.one sorry sorry mul_zero_class.zero sorry sorry sorry sorry /-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := classical.by_contradiction fun (ha : ¬a = 0) => h₁ (mul_left_cancel' ha (Eq.symm h₂ ▸ Eq.symm (mul_one a))) /-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := classical.by_contradiction fun (ha : ¬a = 0) => h₁ (mul_right_cancel' ha (Eq.symm h₂ ▸ Eq.symm (one_mul a))) theorem division_def {G : Type u} [div_inv_monoid G] (a : G) (b : G) : a / b = a * (b⁻¹) := div_eq_mul_inv /-- Pullback a `group_with_zero` class along an injective function. -/ protected def function.injective.group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry /-- Pullback a `group_with_zero` class along an injective function. This is a version of `function.injective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.injective.group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀'), f (x / y) = f x / f y) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry sorry sorry /-- Pushforward a `group_with_zero` class along an surjective function. -/ protected def function.surjective.group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) : group_with_zero G₀' := group_with_zero.mk monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry monoid_with_zero.zero sorry sorry has_inv.inv (div_inv_monoid.div._default monoid_with_zero.mul sorry monoid_with_zero.one sorry sorry has_inv.inv) sorry sorry sorry /-- Pushforward a `group_with_zero` class along a surjective function. This is a version of `function.surjective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.surjective.group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀), f (x / y) = f x / f y) : group_with_zero G₀' := group_with_zero.mk div_inv_monoid.mul sorry div_inv_monoid.one sorry sorry group_with_zero.zero sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry sorry sorry @[simp] theorem mul_inv_cancel_right' {G₀ : Type u_2} [group_with_zero G₀] {b : G₀} (h : b ≠ 0) (a : G₀) : a * b * (b⁻¹) = a := sorry @[simp] theorem mul_inv_cancel_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) (b : G₀) : a * (a⁻¹ * b) = b := sorry theorem inv_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 := sorry @[simp] theorem inv_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a⁻¹ * a = 1 := sorry @[simp] theorem inv_mul_cancel_right' {G₀ : Type u_2} [group_with_zero G₀] {b : G₀} (h : b ≠ 0) (a : G₀) : a * (b⁻¹) * b = a := sorry @[simp] theorem inv_mul_cancel_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) (b : G₀) : a⁻¹ * (a * b) = b := sorry @[simp] theorem inv_one {G₀ : Type u_2} [group_with_zero G₀] : 1⁻¹ = 1 := sorry @[simp] theorem inv_inv' {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a⁻¹⁻¹ = a := sorry /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_self_mul_inv {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * a * (a⁻¹) = a := sorry /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_inv_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * (a⁻¹) * a = a := sorry /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] theorem inv_mul_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a⁻¹ * a * a = a := sorry /-- Multiplying `a` by itself and then dividing by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem mul_self_div_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a * a / a = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * a / a = a)) (div_eq_mul_inv (a * a) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * a * (a⁻¹) = a)) (mul_self_mul_inv a))) (Eq.refl a)) /-- Dividing `a` by itself and then multiplying by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem div_self_mul_self {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / a * a = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / a * a = a)) (div_eq_mul_inv a a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a⁻¹) * a = a)) (mul_inv_mul_self a))) (Eq.refl a)) theorem inv_involutive' {G₀ : Type u_2} [group_with_zero G₀] : function.involutive has_inv.inv := inv_inv' theorem eq_inv_of_mul_right_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : b = (a⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (b = (a⁻¹))) (Eq.symm (inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) = (a⁻¹))) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * 1 = (a⁻¹))) (mul_one (a⁻¹)))) (Eq.refl (a⁻¹)))) theorem eq_inv_of_mul_left_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : a = (b⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a = (b⁻¹))) (Eq.symm (mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (b⁻¹) = (b⁻¹))) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * (b⁻¹) = (b⁻¹))) (one_mul (b⁻¹)))) (Eq.refl (b⁻¹)))) theorem inv_injective' {G₀ : Type u_2} [group_with_zero G₀] : function.injective has_inv.inv := function.involutive.injective inv_involutive' @[simp] theorem inv_inj' {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} {h : G₀} : g⁻¹ = (h⁻¹) ↔ g = h := function.injective.eq_iff inv_injective' theorem inv_eq_iff {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} {h : G₀} : g⁻¹ = h ↔ h⁻¹ = g := eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹ = h ↔ h⁻¹ = g)) (Eq.symm (propext inv_inj')))) (eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹⁻¹ = (h⁻¹) ↔ h⁻¹ = g)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (h⁻¹ = (g⁻¹⁻¹) ↔ h⁻¹ = g)) (inv_inv' g))) (iff.refl (h⁻¹ = g)))) @[simp] theorem inv_eq_one' {G₀ : Type u_2} [group_with_zero G₀] {g : G₀} : g⁻¹ = 1 ↔ g = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (g⁻¹ = 1 ↔ g = 1)) (propext inv_eq_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ = g ↔ g = 1)) inv_one)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 = g ↔ g = 1)) (propext eq_comm))) (iff.refl (g = 1)))) namespace units /-- Embed a non-zero element of a `group_with_zero` into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (ha : a ≠ 0) : units G₀ := mk a (a⁻¹) (mul_inv_cancel ha) (inv_mul_cancel ha) @[simp] theorem coe_mk0 {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : ↑(mk0 a h) = a := rfl @[simp] theorem mk0_coe {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) (h : ↑u ≠ 0) : mk0 (↑u) h = u := ext rfl @[simp] theorem coe_inv' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑(u⁻¹) = (↑u⁻¹) := eq_inv_of_mul_left_eq_one (inv_mul u) @[simp] theorem mul_inv' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑u * (↑u⁻¹) = 1 := mul_inv_cancel (ne_zero u) @[simp] theorem inv_mul' {G₀ : Type u_2} [group_with_zero G₀] (u : units G₀) : ↑u⁻¹ * ↑u = 1 := inv_mul_cancel (ne_zero u) @[simp] theorem mk0_inj {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : mk0 a ha = mk0 b hb ↔ a = b := { mp := fun (h : mk0 a ha = mk0 b hb) => mk.inj_arrow h fun (h_1 : a = b) (h_2 : a⁻¹ = (b⁻¹)) => h_1, mpr := fun (h : a = b) => ext h } @[simp] theorem exists_iff_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} : (∃ (u : units G₀), ↑u = x) ↔ x ≠ 0 := sorry end units theorem is_unit.mk0 {G₀ : Type u_2} [group_with_zero G₀] (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) theorem is_unit_iff_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} : is_unit x ↔ x ≠ 0 := units.exists_iff_ne_zero protected instance group_with_zero.no_zero_divisors {G₀ : Type u_2} [group_with_zero G₀] : no_zero_divisors G₀ := no_zero_divisors.mk fun (a b : G₀) (h : a * b = 0) => imp_of_not_imp_not (a * b = 0) (a = 0 ∨ b = 0) (eq.mpr (id (imp_congr_eq (push_neg.not_or_eq (a = 0) (b = 0)) (Eq.refl (¬a * b = 0)))) (eq.mpr (id (imp_congr_eq ((fun (a a_1 : Prop) (e_1 : a = a_1) (b b_1 : Prop) (e_2 : b = b_1) => congr (congr_arg And e_1) e_2) (¬a = 0) (a ≠ 0) (propext (push_neg.not_eq a 0)) (¬b = 0) (b ≠ 0) (propext (push_neg.not_eq b 0))) (propext (push_neg.not_eq (a * b) 0)))) fun (h : a ≠ 0 ∧ b ≠ 0) => units.ne_zero (units.mk0 a (and.left h) * units.mk0 b (and.right h)))) h protected instance group_with_zero.cancel_monoid_with_zero {G₀ : Type u_2} [group_with_zero G₀] : cancel_monoid_with_zero G₀ := cancel_monoid_with_zero.mk group_with_zero.mul group_with_zero.mul_assoc group_with_zero.one group_with_zero.one_mul group_with_zero.mul_one group_with_zero.zero group_with_zero.zero_mul group_with_zero.mul_zero sorry sorry theorem mul_inv_rev' {G₀ : Type u_2} [group_with_zero G₀] (x : G₀) (y : G₀) : x * y⁻¹ = y⁻¹ * (x⁻¹) := sorry @[simp] theorem div_self {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a / a = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (a / a = 1)) (div_eq_mul_inv a a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a⁻¹) = 1)) (mul_inv_cancel h))) (Eq.refl 1)) @[simp] theorem div_one {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / 1 = a := sorry @[simp] theorem zero_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : 0 / a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 / a = 0)) (div_eq_mul_inv 0 a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 * (a⁻¹) = 0)) (zero_mul (a⁻¹)))) (Eq.refl 0)) @[simp] theorem div_zero {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / 0 = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a / 0 = 0)) (div_eq_mul_inv a 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (0⁻¹) = 0)) inv_zero)) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 0 = 0)) (mul_zero a))) (Eq.refl 0))) @[simp] theorem div_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_eq_mul_inv a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) * b = a)) (inv_mul_cancel_right' h a))) (Eq.refl a)) theorem div_mul_cancel_of_imp {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : a / b * b = a := sorry @[simp] theorem mul_div_cancel {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / b = a)) (div_eq_mul_inv (a * b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (b⁻¹) = a)) (mul_inv_cancel_right' h a))) (Eq.refl a)) theorem mul_div_cancel_of_imp {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : a * b / b = a := sorry @[simp] theorem div_self_mul_self' {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : a / (a * a) = (a⁻¹) := sorry theorem div_eq_mul_one_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : a / b = a * (1 / b) := sorry theorem mul_one_div_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 := sorry theorem one_div_mul_cancel {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : 1 / a * a = 1 := sorry theorem one_div_one {G₀ : Type u_2} [group_with_zero G₀] : 1 / 1 = 1 := div_self (ne.symm zero_ne_one) theorem one_div_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := sorry theorem eq_one_div_of_mul_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a * b = 1) : b = 1 / a := sorry theorem eq_one_div_of_mul_eq_one_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : b * a = 1) : b = 1 / a := sorry @[simp] theorem one_div_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : 1 / (a / b) = b / a := sorry theorem one_div_one_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) : 1 / (1 / a) = a := sorry theorem eq_of_one_div_eq_one_div {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : 1 / a = 1 / b) : a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (one_div_one_div a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (1 / a) = b)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (1 / b) = b)) (one_div_one_div b))) (Eq.refl b))) @[simp] theorem inv_eq_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} : a⁻¹ = 0 ↔ a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ = 0 ↔ a = 0)) (propext inv_eq_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (0⁻¹ = a ↔ a = 0)) inv_zero)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = a ↔ a = 0)) (propext eq_comm))) (iff.refl (a = 0)))) @[simp] theorem zero_eq_inv {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} : 0 = (a⁻¹) ↔ 0 = a := iff.trans eq_comm (iff.trans inv_eq_zero eq_comm) theorem one_div_mul_one_div_rev {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) : 1 / a * (1 / b) = 1 / (b * a) := sorry theorem divp_eq_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (u : units G₀) : a /ₚ u = a / ↑u := sorry @[simp] theorem divp_mk0 {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div a (units.mk0 b hb) theorem inv_div {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b⁻¹ = b / a := sorry theorem inv_div_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a⁻¹ / b = (b * a⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ / b = (b * a⁻¹))) (mul_inv_rev' b a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ / b = a⁻¹ * (b⁻¹))) (div_eq_mul_inv (a⁻¹) b))) (Eq.refl (a⁻¹ * (b⁻¹)))) theorem div_ne_zero {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a / b ≠ 0)) (div_eq_mul_inv a b))) (mul_ne_zero ha (inv_ne_zero hb)) @[simp] theorem div_eq_zero_iff {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b = 0 ↔ a = 0 ∨ b = 0 := sorry theorem div_ne_zero_iff {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := iff.trans (not_congr div_eq_zero_iff) not_or_distrib theorem div_left_inj' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hc : c ≠ 0) : a / c = b / c ↔ a = b := sorry theorem div_eq_iff_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : a / b = c ↔ c * b = a := sorry theorem eq_div_iff_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hc : c ≠ 0) : a = b / c ↔ a * c = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b / c ↔ a * c = b)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (b / c = a ↔ a * c = b)) (propext (div_eq_iff_mul_eq hc)))) (iff.refl (a * c = b))) theorem div_eq_of_eq_mul {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} (hx : x ≠ 0) {y : G₀} {z : G₀} (h : y = z * x) : y / x = z := iff.mpr (div_eq_iff_mul_eq hx) (Eq.symm h) theorem eq_div_of_mul_eq {G₀ : Type u_2} [group_with_zero G₀] {x : G₀} (hx : x ≠ 0) {y : G₀} {z : G₀} (h : z * x = y) : z = y / x := Eq.symm (div_eq_of_eq_mul hx (Eq.symm h)) theorem eq_of_div_eq_one {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : a / b = 1) : a = b := sorry theorem div_eq_one_iff_eq {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (hb : b ≠ 0) : a / b = 1 ↔ a = b := { mp := eq_of_div_eq_one, mpr := fun (h : a = b) => Eq.symm h ▸ div_self hb } theorem div_mul_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a := sorry theorem mul_div_mul_right {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) (b : G₀) {c : G₀} (hc : c ≠ 0) : a * c / (b * c) = a / b := sorry theorem mul_mul_div {G₀ : Type u_2} [group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) := sorry protected instance comm_group_with_zero.comm_cancel_monoid_with_zero {G₀ : Type u_2} [comm_group_with_zero G₀] : comm_cancel_monoid_with_zero G₀ := comm_cancel_monoid_with_zero.mk cancel_monoid_with_zero.mul sorry cancel_monoid_with_zero.one sorry sorry sorry cancel_monoid_with_zero.zero sorry sorry sorry sorry /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (f : G₀' → G₀) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀'), f (x * y) = f x * f y) (inv : ∀ (x : G₀'), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀'), f (x / y) = f x / f y) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pushforward a `comm_group_with_zero` class along an surjective function. -/ protected def function.surjective.comm_group_with_zero {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry /-- Pushforward a `comm_group_with_zero` class along a surjective function. -/ protected def function.surjective.comm_group_with_zero_div {G₀ : Type u_2} {G₀' : Type u_4} [comm_group_with_zero G₀] [HasZero G₀'] [Mul G₀'] [HasOne G₀'] [has_inv G₀'] [Div G₀'] (h01 : 0 ≠ 1) (f : G₀ → G₀') (hf : function.surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ (x y : G₀), f (x * y) = f x * f y) (inv : ∀ (x : G₀), f (x⁻¹) = (f x⁻¹)) (div : ∀ (x y : G₀), f (x / y) = f x / f y) : comm_group_with_zero G₀' := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry sorry group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry theorem mul_inv' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} : a * b⁻¹ = a⁻¹ * (b⁻¹) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b⁻¹ = a⁻¹ * (b⁻¹))) (mul_inv_rev' a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b⁻¹ * (a⁻¹) = a⁻¹ * (b⁻¹))) (mul_comm (b⁻¹) (a⁻¹)))) (Eq.refl (a⁻¹ * (b⁻¹)))) theorem one_div_mul_one_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) : 1 / a * (1 / b) = 1 / (a * b) := eq.mpr (id (Eq._oldrec (Eq.refl (1 / a * (1 / b) = 1 / (a * b))) (one_div_mul_one_div_rev a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 / (b * a) = 1 / (a * b))) (mul_comm b a))) (Eq.refl (1 / (a * b)))) theorem div_mul_right {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a * b) = 1 / b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * a) = 1 / b)) (div_mul_left ha))) (Eq.refl (1 / b))) theorem mul_div_cancel_left_of_imp {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (h : a = 0 → b = 0) : a * b / a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / a = b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / a = b)) (mul_div_cancel_of_imp h))) (Eq.refl b)) theorem mul_div_cancel_left {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b := mul_div_cancel_left_of_imp fun (h : a = 0) => false.elim (ha h) theorem mul_div_cancel_of_imp' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a := eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / b) = a)) (mul_comm b (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_mul_cancel_of_imp h))) (Eq.refl a)) theorem mul_div_cancel' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a := eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / b) = a)) (mul_comm b (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (div_mul_cancel a hb))) (Eq.refl a)) theorem div_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) (d : G₀) : a / b * (c / d) = a * c / (b * d) := sorry theorem mul_div_mul_left {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) {c : G₀} (hc : c ≠ 0) : c * a / (c * b) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (c * a / (c * b) = a / b)) (mul_comm c a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / (c * b) = a / b)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / (b * c) = a / b)) (mul_div_mul_right a b hc))) (Eq.refl (a / b)))) theorem div_mul_eq_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : b / c * a = b * a / c := sorry theorem div_mul_eq_mul_div_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : b / c * a = b * (a / c) := sorry theorem mul_eq_mul_of_div_eq_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := sorry theorem div_div_eq_mul_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / (b / c) = a * c / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (b / c) = a * c / b)) (div_eq_mul_one_div a (b / c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (1 / (b / c)) = a * c / b)) (one_div_div b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (c / b) = a * c / b)) (Eq.symm mul_div_assoc))) (Eq.refl (a * c / b)))) theorem div_div_eq_div_mul {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b / c = a / (b * c) := eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / (b * c))) (div_eq_mul_one_div (a / b) c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * (1 / c) = a / (b * c))) (div_mul_div a b 1 c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 / (b * c) = a / (b * c))) (mul_one a))) (Eq.refl (a / (b * c))))) theorem div_div_div_div_eq {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) {b : G₀} {c : G₀} {d : G₀} : a / b / (c / d) = a * d / (b * c) := sorry theorem div_mul_eq_div_mul_one_div {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / (b * c) = a / b * (1 / c) := eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / b * (1 / c))) (Eq.symm (div_div_eq_div_mul a b c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / b * (1 / c))) (Eq.symm (div_eq_mul_one_div (a / b) c)))) (Eq.refl (a / b / c))) /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] theorem div_div_self {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) : a / (a / a) = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a / a) = a)) (div_div_eq_mul_div a a a))) (mul_self_div_self a) theorem ne_zero_of_one_div_ne_zero {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := fun (ha : a = 0) => absurd (Eq.refl 0) (eq.mp (Eq._oldrec (Eq.refl (1 / 0 ≠ 0)) (div_zero 1)) (eq.mp (Eq._oldrec (Eq.refl (1 / a ≠ 0)) ha) h)) theorem eq_zero_of_one_div_eq_zero {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (fun (ha : a = 0) => ha) fun (ha : ¬a = 0) => false.elim (one_div_ne_zero ha h) theorem div_helper {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} (b : G₀) (h : a ≠ 0) : 1 / (a * b) * a = 1 / b := eq.mpr (id (Eq._oldrec (Eq.refl (1 / (a * b) * a = 1 / b)) (div_mul_eq_mul_div a 1 (a * b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * a / (a * b) = 1 / b)) (one_mul a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (a * b) = 1 / b)) (div_mul_right b h))) (Eq.refl (1 / b)))) theorem div_eq_inv_mul {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} : a / b = b⁻¹ * a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b = b⁻¹ * a)) (div_eq_mul_inv a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) = b⁻¹ * a)) (mul_comm a (b⁻¹)))) (Eq.refl (b⁻¹ * a))) theorem mul_div_right_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a * b / c = a / c * b := sorry theorem mul_comm_div' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b * c = a * (c / b) := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = a * (c / b))) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = a * c / b)) (mul_div_right_comm a c b))) (Eq.refl (a / b * c))) theorem div_mul_comm' {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a / b * c = c / b * a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * c = c / b * a)) (div_mul_eq_mul_div c a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * c / b = c / b * a)) (mul_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (c * a / b = c / b * a)) (mul_div_right_comm c a b))) (Eq.refl (c / b * a)))) theorem mul_div_comm {G₀ : Type u_2} [comm_group_with_zero G₀] (a : G₀) (b : G₀) (c : G₀) : a * (b / c) = b * (a / c) := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / c) = b * (a / c))) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b / c = b * (a / c))) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / c = b * (a / c))) mul_div_assoc)) (Eq.refl (b * (a / c))))) theorem div_right_comm {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) : a / b / c = a / c / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / b / c = a / c / b)) (div_div_eq_div_mul a b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / c / b)) (div_div_eq_div_mul a c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / (b * c) = a / (c * b))) (mul_comm b c))) (Eq.refl (a / (c * b))))) theorem div_div_div_cancel_right {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) (hc : c ≠ 0) : a / c / (b / c) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / c / (b / c) = a / b)) (div_div_eq_mul_div (a / c) b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / c * c / b = a / b)) (div_mul_cancel a hc))) (Eq.refl (a / b))) theorem div_mul_div_cancel {G₀ : Type u_2} [comm_group_with_zero G₀] {b : G₀} {c : G₀} (a : G₀) (hc : c ≠ 0) : a / c * (c / b) = a / b := eq.mpr (id (Eq._oldrec (Eq.refl (a / c * (c / b) = a / b)) (Eq.symm mul_div_assoc))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / c * c / b = a / b)) (div_mul_cancel a hc))) (Eq.refl (a / b))) theorem div_eq_div_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := sorry theorem div_eq_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : a / b = c ↔ a = c * b := iff.trans (div_eq_iff_mul_eq hb) eq_comm theorem eq_div_iff {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hb : b ≠ 0) : c = a / b ↔ c * b = a := eq_div_iff_mul_eq hb theorem div_div_cancel' {G₀ : Type u_2} [comm_group_with_zero G₀] {a : G₀} {b : G₀} (ha : a ≠ 0) : a / (a / b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a / (a / b) = b)) (div_eq_mul_inv a (a / b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (a / b⁻¹) = b)) inv_div)) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / a) = b)) (mul_div_cancel' b ha))) (Eq.refl b))) namespace semiconj_by @[simp] theorem zero_right {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 := sorry @[simp] theorem zero_left {G₀ : Type u_2} [mul_zero_class G₀] (x : G₀) (y : G₀) : semiconj_by 0 x y := sorry @[simp] theorem inv_symm_left_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} : semiconj_by (a⁻¹) x y ↔ semiconj_by a y x := sorry theorem inv_symm_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} (h : semiconj_by a x y) : semiconj_by (a⁻¹) y x := iff.mpr inv_symm_left_iff' h theorem inv_right' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} (h : semiconj_by a x y) : semiconj_by a (x⁻¹) (y⁻¹) := sorry @[simp] theorem inv_right_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} : semiconj_by a (x⁻¹) (y⁻¹) ↔ semiconj_by a x y := { mp := fun (h : semiconj_by a (x⁻¹) (y⁻¹)) => inv_inv' x ▸ inv_inv' y ▸ inv_right' h, mpr := inv_right' } theorem div_right {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {x : G₀} {y : G₀} {x' : G₀} {y' : G₀} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x / x') (y / y') := eq.mpr (id (Eq._oldrec (Eq.refl (semiconj_by a (x / x') (y / y'))) (div_eq_mul_inv x x'))) (eq.mpr (id (Eq._oldrec (Eq.refl (semiconj_by a (x * (x'⁻¹)) (y / y'))) (div_eq_mul_inv y y'))) (mul_right h (inv_right' h'))) end semiconj_by namespace commute @[simp] theorem zero_right {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left {G₀ : Type u_2} [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a @[simp] theorem inv_left_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : commute (a⁻¹) b ↔ commute a b := semiconj_by.inv_symm_left_iff' theorem inv_left' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute (a⁻¹) b := iff.mpr inv_left_iff' h @[simp] theorem inv_right_iff' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} : commute a (b⁻¹) ↔ commute a b := semiconj_by.inv_right_iff' theorem inv_right' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute a (b⁻¹) := iff.mpr inv_right_iff' h theorem inv_inv' {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} (h : commute a b) : commute (a⁻¹) (b⁻¹) := inv_right' (inv_left' h) @[simp] theorem div_right {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hab : commute a b) (hac : commute a c) : commute a (b / c) := semiconj_by.div_right hab hac @[simp] theorem div_left {G₀ : Type u_2} [group_with_zero G₀] {a : G₀} {b : G₀} {c : G₀} (hac : commute a c) (hbc : commute b c) : commute (a / b) c := eq.mpr (id (Eq._oldrec (Eq.refl (commute (a / b) c)) (div_eq_mul_inv a b))) (mul_left hac (inv_left' hbc)) end commute namespace monoid_with_zero_hom theorem map_ne_zero {M₀ : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [monoid_with_zero M₀] [nontrivial M₀] (f : monoid_with_zero_hom G₀ M₀) {a : G₀} : coe_fn f a ≠ 0 ↔ a ≠ 0 := { mp := fun (hfa : coe_fn f a ≠ 0) (ha : a = 0) => hfa (Eq.symm ha ▸ map_zero f), mpr := fun (ha : a ≠ 0) => is_unit.ne_zero (is_unit.map (to_monoid_hom f) (is_unit.mk0 a ha)) } @[simp] theorem map_eq_zero {M₀ : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [monoid_with_zero M₀] [nontrivial M₀] (f : monoid_with_zero_hom G₀ M₀) {a : G₀} : coe_fn f a = 0 ↔ a = 0 := iff.mp not_iff_not (map_ne_zero f) /-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/ @[simp] theorem map_inv' {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [group_with_zero G₀'] (f : monoid_with_zero_hom G₀ G₀') (a : G₀) : coe_fn f (a⁻¹) = (coe_fn f a⁻¹) := sorry @[simp] theorem map_div {G₀ : Type u_2} {G₀' : Type u_4} [group_with_zero G₀] [group_with_zero G₀'] (f : monoid_with_zero_hom G₀ G₀') (a : G₀) (b : G₀) : coe_fn f (a / b) = coe_fn f a / coe_fn f b := sorry end monoid_with_zero_hom @[simp] theorem monoid_hom.map_units_inv {M : Type u_1} {G₀ : Type u_2} [monoid M] [group_with_zero G₀] (f : M →* G₀) (u : units M) : coe_fn f ↑(u⁻¹) = (coe_fn f ↑u⁻¹) := sorry /-- Constructs a `group_with_zero` structure on a `monoid_with_zero` consisting only of units and 0. -/ def group_with_zero_of_is_unit_or_eq_zero {M : Type u_5} [nontrivial M] [hM : monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M := group_with_zero.mk monoid_with_zero.mul monoid_with_zero.mul_assoc monoid_with_zero.one monoid_with_zero.one_mul monoid_with_zero.mul_one monoid_with_zero.zero monoid_with_zero.zero_mul monoid_with_zero.mul_zero (fun (a : M) => dite (a = 0) (fun (h0 : a = 0) => 0) fun (h0 : ¬a = 0) => ↑(is_unit.unit sorry⁻¹)) (div_inv_monoid.div._default monoid_with_zero.mul monoid_with_zero.mul_assoc monoid_with_zero.one monoid_with_zero.one_mul monoid_with_zero.mul_one fun (a : M) => dite (a = 0) (fun (h0 : a = 0) => 0) fun (h0 : ¬a = 0) => ↑(is_unit.unit sorry⁻¹)) nontrivial.exists_pair_ne sorry sorry /-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero` consisting only of units and 0. -/ def comm_group_with_zero_of_is_unit_or_eq_zero {M : Type u_5} [nontrivial M] [hM : comm_monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M := comm_group_with_zero.mk group_with_zero.mul sorry group_with_zero.one sorry sorry comm_monoid_with_zero.mul_comm group_with_zero.zero sorry sorry group_with_zero.inv group_with_zero.div sorry sorry sorry
example (p q : ℕ → Prop) : (∃ x, p x) → ∃ x, p x ∨ q x := begin intro h, cases h with x hpx, constructor, left, exact hpx end
[STATEMENT] lemma lift_instr_complete: assumes "Sinca.local_var_in_range N instr" and "Sinca.jump_in_range (set L) instr" and "Sinca.fun_call_in_range F instr" and "Sinca.sp_instr F ret instr (length \<Sigma>) k" and "list_all ((=) None) \<Sigma>" shows "\<exists>instr' \<Sigma>'. lift_instr F L ret N instr \<Sigma> = Some (instr', \<Sigma>') \<and> length \<Sigma>' = k" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>instr' \<Sigma>'. lift_instr F L ret N instr \<Sigma> = Some (instr', \<Sigma>') \<and> length \<Sigma>' = k [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: Sinca.local_var_in_range N instr Sinca.jump_in_range (set L) instr Sinca.fun_call_in_range F instr Sinca.sp_instr F ret instr (length \<Sigma>) k list_all ((=) None) \<Sigma> goal (1 subgoal): 1. \<exists>instr' \<Sigma>'. lift_instr F L ret N instr \<Sigma> = Some (instr', \<Sigma>') \<and> length \<Sigma>' = k [PROOF STEP] by (cases "(F, L, ret, N, instr, \<Sigma>)" rule: lift_instr.cases) (auto simp add: in_set_member Let_def dest: Map.domD dest!: list_all_eq_const_imp_replicate' elim: Sinca.sp_instr.cases)
\section{Task 3} For this section I implemented a filter function called \texttt{segmSpecialFilter} which takes a predicate as well as an input list of data, and an info list with the segmentation information for the data list. The function then orders the segments based on the predicate result for each element and returns the segments joined into a list and a new segmentation information list. Figure \ref{fig:t3code} shows my implementation of the function. \begin{figure}[H] \begin{lstlisting} segmSpecialFilter :: (a->Bool) -> [Int] -> [a] -> ([Int],[a]) segmSpecialFilter cond sizes arr = let n = length arr cs = map cond arr tfs = map (\f -> if f then 1 else 0) cs ffs = map (\f->if f then 0 else 1) cs isT = segmScanInc (+) 0 sizes tfs isF = segmScanInc (+) 0 sizes ffs acc_sizes = scanInc (+) 0 sizes is = map (\s -> isT !! (s - 1)) acc_sizes si = segmScanInc (+) 0 sizes sizes offsets = zipWith (-) acc_sizes si inds = map (\ (c,i,o,iT,iF) -> if c then iT+o-1 else iF+i+o-1 ) (zip5 cs is offsets isT isF) tmp1 = map (\m -> iota m) sizes iotas = map (+1) $ reduce (++) [] tmp1 flags = map (\(f,i,s,ri) -> if f > 0 then (if ri > 0 then ri else f) else (if (i-1) == ri then s-ri else 0)) (zip4 sizes iotas si is) in (flags, permute inds arr) \end{lstlisting} \caption{The code written for the third task of the assignment.} \label{fig:t3code} \end{figure}
Sheet We manufacture more transparent two way mirrors known as a beamsplitter mirrors for smart mirror TV mirror, teleprompter projects. A two way mirror sheet also called one way mirror is a transparent mirror for security & privacy. Find the best selection of Acrylic Sheets and get price match if you find a lower price. The back of the mirror is protected by 24x36 a sheet of ¼". Find the best Mirrors & 24x36 Wall Decor from HobbyLobby. We are the best glass and mirror provider in the nation. Shop our variety of commercial janitorial supplies at wholesale prices 24x36 today. Solid Polycarbonate Sheet 2mm Clear Polycarbonate Sheet 3mm Clear Polycarbonate Sheet 4mm Clear Polycarbonate Sheet 5mm Clear Polycarbonate Sheet Check out the deal on Cut- to- Size Color Acrylic Sheet - Cast at ACME Plastics, Inc. Cast acrylic is more chemical resistant & has superior machining characteristics than extruded acrylic. com for brushes dusters, trash bags sheet & more! It' s very important that your wood is perfectly flat on the cutting bed otherwise the laser won' t be focused correctly won' t cut well. For the 36" dish parts, it took about 3 hours to acrylic get 24x36 everything cut out of. There are a lot of applications where acrylic mirror works very well. Sign up for Dulles Glass acrylic Mirror news special offer emails. I cut the acrylic parts on a 120W 24x36 Epilog laser. Plexiglass mirror is a " reflective" sheet. Choose Your Acrylic Sheet Shape. Bradley_ Mirror_ 781 Mirror with roll- formed channel frame and theft- resistant mounting:. sheet Shop for Acrylic Sheets at Lowes. We have a widest variety on glass. Acme Plastics has Cut- to- Size Color acrylic Acrylic Cast Sheets. 刊行物についてのお問い合せは、 JEITAサービスセンターまでお願いします。 or. 24x36 acrylic mirror sheet. 24x36 - 24 x 36 Flat White 24x36 Solid Wood Frame with UV Framer' s Acrylic & Foam Board Backing - Great For 24x36 a Photo Poster, Document, Painting, Mirror by The Frame Shack $ 65. You should consider Plexiglas mirror in applications where SAFETY is a concern as plast. Acrylic sheets are easier to cut and manipulate than glass. Browse our website acrylic and know about Bear Glass stock sheets. Save big when you shop CleanItSupply. We stock all major brands of acrylic sheet and mirror: Discount Plexiglass sheet, Acrylite, Lucite, Perspex and Optix as well as a variety of specialty colors and textures such as Frosted Plexiglass. Sheet sizes start at 24" x 48" and are available up to 8' x 12' and larger on special order. 1mm- 6mm hot sell best price Golden Acrylic perspex Mirror Sheet. Plexiglass ( acrylic) is a versatile plastic material that has great impact strength yet is light weight with exceptional optical quality. Plexiglass can be used for a number of applications such as signage, glazing, displays, picture framing, aquarium tanks, speaker boxes, and much more. Acrylic Sheet, 1/ 4" Thick Known by trade names such as Plexiglas, Acrylite, and Lucite, this material is great for glazing, windows, cutting boards, or anywhere a clear material is needed. Acrylic Floating Frame. Canvas Wrap + Floater. Show More POPULAR. ACRYLIC SHEET - CLEAR CAST PAPER- MASKED. Acrylic sheet is 17 times stronger than glass, has excellent clarity, durability, is lightweight and weatherable.
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: GPL-2.0-only *) theory Corres_C imports "CLib.CCorresLemmas" SR_lemmas_C begin abbreviation "return_C \<equiv> CLanguage.creturn global_exn_var_'_update" lemmas return_C_def = creturn_def abbreviation "return_void_C \<equiv> CLanguage.creturn_void global_exn_var_'_update" lemmas return_void_C_def = creturn_void_def abbreviation "break_C \<equiv> CLanguage.cbreak global_exn_var_'_update" lemmas breakk_C_def = cbreak_def abbreviation "catchbrk_C \<equiv> CLanguage.ccatchbrk global_exn_var_'" lemmas catchbrk_C_def = ccatchbrk_def (* This is to avoid typing this all the time \<dots> *) abbreviation (in kernel) "modifies_spec f \<equiv> \<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} Call f {t. t may_not_modify_globals s}" section "Error monad" (* Dealing with THROW in a nice fashion --- it is always going to be catching break or skip at the end of the function. In retrospect, if ccatchbrk is always if ... then SKIP else THROW we are OK without the globals_update thing *) definition wfhandlers :: "rf_com list \<Rightarrow> bool" where "wfhandlers hs \<equiv> \<forall>\<Gamma> s t n. global_exn_var_' s = Return \<and> \<Gamma> \<turnstile>\<^sub>h \<langle>hs, s\<rangle> \<Rightarrow> (n, t) \<longrightarrow> t = Normal s" lemma wfhandlers_ccatchbrk: "wfhandlers (catchbrk_C # hs) = wfhandlers hs" unfolding wfhandlers_def ccatchbrk_def apply rule apply (intro allI impI) apply (drule_tac x = \<Gamma> in spec) apply ((drule spec)+, erule mp) apply simp apply (rule EHAbrupt) apply rule apply simp apply rule apply fastforce apply (intro allI impI) apply (drule_tac x = \<Gamma> in spec) apply ((drule spec)+, erule mp) apply simp apply (erule conjE) apply (erule exec_handlers.cases) apply (fastforce elim: exec_Normal_elim_cases)+ done lemma wfhandlers_skip: "wfhandlers (SKIP # hs)" unfolding wfhandlers_def apply (intro allI impI) apply (erule conjE) apply (erule exec_handlers.cases) apply (auto elim: exec_Normal_elim_cases) done lemmas wfhandlers_simps [simp] = wfhandlers_skip wfhandlers_ccatchbrk lemma wfhandlersD: "\<lbrakk>wfhandlers hs; \<Gamma> \<turnstile>\<^sub>h \<langle>hs, s\<rangle> \<Rightarrow> (n, t); global_exn_var_' s = Return\<rbrakk> \<Longrightarrow> t = Normal s" unfolding wfhandlers_def by auto record 'b exxf = exflag :: machine_word exstate :: errtype exvalue :: 'b definition liftxf :: "(cstate \<Rightarrow> errtype) \<Rightarrow> ('a \<Rightarrow> machine_word) \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> (cstate \<Rightarrow> 'a) \<Rightarrow> cstate \<Rightarrow> 'b exxf" where "liftxf et ef vf xf \<equiv> \<lambda>s. \<lparr> exflag = ef (xf s), exstate = et s, exvalue = vf (xf s) \<rparr>" lemma exflag_liftxf [simp]: "exflag (liftxf es sf vf xf s) = sf (xf s)" unfolding liftxf_def by simp lemma exstate_liftxf [simp]: "exstate (liftxf es sf vf xf s) = es s" unfolding liftxf_def by simp lemma exvalue_liftxf [simp]: "exvalue (liftxf es sf vf xf s) = vf (xf s)" unfolding liftxf_def by simp (* This is more or less ccorres specific, so it goes here *) primrec crel_sum_comb :: "('a \<Rightarrow> machine_word \<Rightarrow> errtype \<Rightarrow> bool) \<Rightarrow> ('c \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> ('a + 'c \<Rightarrow> 'b exxf \<Rightarrow> bool)" (infixl "\<currency>" 95) where "(f \<currency> g) (Inr x) y = (exflag y = scast EXCEPTION_NONE \<and> g x (exvalue y))" | "(f \<currency> g) (Inl x) y = (exflag y \<noteq> scast EXCEPTION_NONE \<and> f x (exflag y) (exstate y))" lemma ccorres_split_nothrowE: fixes R' :: "cstate set" assumes ac: "ccorres_underlying sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') (f' \<currency> r') (liftxf es ef' vf' xf') P P' hs a c" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')" and err: "\<And>err rv' err'. \<lbrakk>ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (throwError err) (d' rv')" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>,\<lbrace>QE\<rbrace>" and valid': "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' c ({s. (ef' (xf' s) = scast EXCEPTION_NONE \<longrightarrow> (\<forall>rv. r' rv (vf' (xf' s)) \<longrightarrow> s \<in> Q' rv (xf' s))) \<and> (ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> (\<forall>err. f' err (ef' (xf' s)) (es s) \<longrightarrow> s \<in> Q'' err (xf' s) (es s)))})" (is "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' c {s. ?Q'' s}") shows "ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) (P' \<inter> R') hs (a >>=E (\<lambda>rv. b rv)) (c ;; d)" unfolding bindE_def apply (rule_tac R="case_sum QE Q" and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR' in ccorres_master_split_hs) apply (rule ac) apply (rule ccorres_abstract[OF ceqv]) apply (case_tac rv, simp_all add: lift_def) apply (rule ccorres_abstract[where xf'=es, OF ceqv_refl]) apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (rule_tac err'=rv'a in err) apply assumption+ apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (erule(1) bd) apply (rule ccorres_empty[where P=\<top>]) apply (rule hoare_strengthen_post, rule valid[unfolded validE_def]) apply (simp split: sum.split_asm) apply (rule exec_handlers_Hoare_Post, rule exec_handlers_Hoare_from_vcg_nofail[OF valid', where A="{}"]) apply (auto simp: ccHoarePost_def split: sum.split) done lemma ccorres_split_nothrow_novcgE: fixes R' :: "cstate set" assumes ac: "ccorres_underlying sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') (f' \<currency> r') (liftxf es ef' vf' xf') P P' [] a c" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')" and err: "\<And>err rv' err'. \<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (throwError err) (d' rv')" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>,\<lbrace>QE\<rbrace>" and novcg: "guard_is_UNIV (\<lambda>rv rv'. r' rv (vf' rv')) xf' (\<lambda>rv rv'. {s. ef' rv' = scast EXCEPTION_NONE \<longrightarrow> s \<in> Q' rv rv'})" \<comment> \<open>hack\<close> and novcg_err: "\<And>err. guard_is_UNIV (\<lambda>rv. f' err (ef' rv)) es (\<lambda>rv rv'. {s. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> s \<in> Q'' err rv rv'})" shows "ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) P' hs (a >>=E (\<lambda>rv. b rv)) (c ;; d)" unfolding bindE_def apply (rule_tac R="case_sum QE Q" and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR' in ccorres_master_split_nohs_UNIV) apply (rule ac) apply (rule ccorres_abstract[OF ceqv]) apply (case_tac rv, simp_all add: lift_def) apply (rule ccorres_abstract[where xf'=es, OF ceqv_refl]) apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (rule_tac err'=rv'a in err) apply assumption+ apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (erule(1) bd) apply (rule hoare_strengthen_post, rule valid[unfolded validE_def]) apply (simp split: sum.split_asm) apply (insert novcg novcg_err) apply (clarsimp simp: guard_is_UNIV_def split: sum.split) done (* Unit would be more appropriate, but the record package will simplify xfdc to () *) definition "xfdc (t :: cstate) \<equiv> (0 :: nat)" lemma xfdc_equal [simp]: "xfdc t = xfdc s" unfolding xfdc_def by simp lemmas ccorres_split_nothrow_novcg_dc = ccorres_split_nothrow_novcg[where r'=dc and xf'=xfdc, OF _ ceqv_refl] abbreviation "exfdc \<equiv> liftxf undefined (\<lambda>_. scast EXCEPTION_NONE) id xfdc" lemma ccorres_return_C': assumes xfc: "\<And>s. (xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s))) = v s" and wfh: "wfhandlers hs" and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow> (s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr" shows "ccorres_underlying sr \<Gamma> r rvxf arrel xf \<top> {s. arrel rv (v s)} hs (return rv) (return_C xfu v)" using wfh unfolding creturn_def apply - apply (rule ccorresI') apply (erule exec_handlers.cases) apply clarsimp apply (clarsimp elim!: exec_Normal_elim_cases) apply (drule (1) wfhandlersD) apply simp apply (frule exec_handlers_less2, clarsimp) apply (clarsimp simp: return_def unif_rrel_def xfc) apply (auto elim!: srv)[1] apply (clarsimp elim!: exec_Normal_elim_cases) apply simp done lemma ccorres_return_CE': assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = v s" and wfh: "wfhandlers hs" and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow> (s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr" shows "ccorres_underlying sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf) \<top> {s. sf (v s) = scast EXCEPTION_NONE \<and> r rv (vf (v s))} hs (returnOk rv) (return_C xfu v)" using wfh unfolding creturn_def apply - apply (rule ccorresI') apply (erule exec_handlers.cases) apply clarsimp apply (clarsimp elim!: exec_Normal_elim_cases) apply (drule (1) wfhandlersD) apply simp apply (simp add: returnOk_def return_def) apply (drule exec_handlers_less2, clarsimp+) apply (auto simp: unif_rrel_def xfc elim!: srv)[1] apply (clarsimp elim!: exec_Normal_elim_cases) apply simp done lemma ccorres_return_C_errorE': assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = v s" and esc: "\<And>s. es (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = es s" and wfh: "wfhandlers hs" and srv: "\<And>s s'. (s, s') \<in> sr \<Longrightarrow> (s, global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s') s')) \<in> sr" shows "ccorres_underlying sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf) \<top> {s. sf (v s) \<noteq> scast EXCEPTION_NONE \<and> f rv (sf (v s)) (es s)} hs (throwError rv) (return_C xfu v)" using wfh unfolding creturn_def apply - apply (rule ccorresI') apply (erule exec_handlers.cases) apply clarsimp apply (clarsimp elim!: exec_Normal_elim_cases) apply (drule (1) wfhandlersD) apply simp apply (simp add: throwError_def return_def) apply (drule exec_handlers_less2, clarsimp+) apply (auto simp: unif_rrel_def xfc esc elim!: srv)[1] apply (clarsimp elim!: exec_Normal_elim_cases) apply simp done context kernel begin abbreviation "ccorres r xf \<equiv> ccorres_underlying rf_sr \<Gamma> r xf r xf" lemma ccorres_basic_srnoop: assumes asm: "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a c" and gsr: "\<And>s'. globals (g s') = globals s'" and gG: "\<And>s'. s' \<in> G' \<Longrightarrow> g s' \<in> G'" shows "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a (Basic g ;; c)" using asm unfolding rf_sr_def apply (rule ccorres_basic_srnoop) apply (simp add: gsr) apply (erule gG) done lemma ccorres_basic_srnoop2: assumes gsr: "\<And>s'. globals (g s') = globals s'" assumes asm: "ccorres_underlying rf_sr Gamm r xf arrel axf G G' hs a c" shows "ccorres_underlying rf_sr Gamm r xf arrel axf G {s. g s \<in> G'} hs a (Basic g ;; c)" apply (rule ccorres_guard_imp2) apply (rule ccorres_symb_exec_r) apply (rule asm) apply vcg apply (rule conseqPre, vcg, clarsimp simp: rf_sr_def gsr) apply clarsimp done (* The naming convention here is that xf', xfr, and xfru are the terms we instantiate *) lemma ccorres_call: assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf'' r xf'' A C' [] a (Call f)" and ggl: "\<And>x y s. globals (g x y s) = globals s" and xfg: "\<And>a s t. (xf' (g a t (s\<lparr>globals := globals t\<rparr>))) = xf'' t" and igl: "\<And>s. globals (i s) = globals s" shows "ccorres_underlying rf_sr \<Gamma> r xf' arrel axf A {s. i s \<in> C'} hs a (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)))" using cul unfolding rf_sr_def apply - apply (rule ccorres_call) apply (erule ccorres_guard_imp) apply simp apply clarsimp apply (simp add: ggl) apply (simp add: xfg) apply (clarsimp simp: igl) done lemma ccorres_callE: "\<lbrakk> ccorres_underlying rf_sr \<Gamma> r (liftxf es sf vf xf'') r (liftxf es sf vf xf'') A C' [] a (Call f); \<And>x y s. globals (g x y s) = globals s; \<And>a s t. es (g a t (s\<lparr>globals := globals t\<rparr>)) = es t; \<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t; \<And>s. globals (i s) = globals s \<rbrakk> \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r (liftxf es sf vf xf') arrel axf A {s. i s \<in> C'} hs a (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)))" apply (erule ccorres_call) apply assumption apply (simp add: liftxf_def) apply assumption done lemma ccorres_call_record: assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf'' r xf'' A C' [] a (Call f)" and ggl: "\<And>f s. globals (xfu' f s) = globals s" and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v" and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v" and igl: "\<And>s. globals (i s) = globals s" shows "ccorres_underlying rf_sr \<Gamma> r (xfr \<circ> xf') arrel axf A {s. i s \<in> C'} hs a (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))))" apply (rule ccorres_call) apply (rule cul) apply (rule ggl) apply (simp add: xfrxfru xfxfu) apply (rule igl) done lemmas ccorres_split_nothrow_call = ccorres_split_nothrow [OF ccorres_call] lemmas ccorres_split_nothrow_callE = ccorres_split_nothrowE [OF ccorres_callE] lemma ccorres_split_nothrow_call_novcg: assumes ac: "ccorres r' xf'' P P' [] a (Call f)" and gg: "\<And>x y s. globals (g x y s) = globals s" and xfxf: "\<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t" and gi: "\<And>s. globals (i s) = globals s" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'} \<inter> {s'. (\<forall>t rv. r' rv (xf'' t) \<longrightarrow> g s' t (s'\<lparr>globals := globals t\<rparr>) \<in> Q' rv (xf'' t))}) hs (a >>= (\<lambda>rv. b rv)) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y)) ;; d)" (is "ccorres_underlying rf_sr \<Gamma> r xf arrel axf ?P (?Q1 \<inter> ?Q2) hs ?A ?B") apply (rule ccorres_master_split_nohs) apply (rule ccorres_call [OF ac]) apply (rule gg) apply (rule xfxf) apply (rule gi) apply (rule ccorres_abstract[OF ceqv]) apply (rule ccorres_gen_asm2) apply (erule bd) apply (simp add: valid) apply (rule exec_handlers_Hoare_call_Basic) apply (clarsimp simp: ccHoarePost_def xfxf) apply simp done definition errstate :: "cstate \<Rightarrow> errtype" where "errstate s \<equiv> \<lparr> errfault = seL4_Fault_lift (current_fault_' (globals s)), errlookup_fault = lookup_fault_lift (current_lookup_fault_' (globals s)), errsyscall = current_syscall_error_' (globals s) \<rparr>" lemma errlookup_fault_errstate [simp]: "errlookup_fault (errstate s) = lookup_fault_lift (current_lookup_fault_' (globals s))" unfolding errstate_def by simp lemma errfault_errstate [simp]: "errfault (errstate s) = seL4_Fault_lift (current_fault_' (globals s))" unfolding errstate_def by simp lemma errsyscall_errstate [simp]: "errsyscall (errstate s) = (current_syscall_error_' (globals s))" unfolding errstate_def by simp lemma errstate_state_update [simp]: assumes f: "\<And>s. current_fault_' (globals (g s)) = current_fault_' (globals s)" and lf: "\<And>s. current_lookup_fault_' (globals (g s)) = current_lookup_fault_' (globals s)" and se: "\<And>s. current_syscall_error_' (globals (g s)) = current_syscall_error_' (globals s)" shows "errstate (g s) = errstate s" by (simp add: f lf se errstate_def) lemma ccorres_split_nothrow_call_novcgE: assumes ac: "ccorres (f' \<currency> r') (liftxf errstate ef' vf' xf'') P P' [] a (Call f)" and gg: "\<And>x y s. globals (g x y s) = globals s" and xfxf: "\<And>a s t. xf' (g a t (s\<lparr>globals := globals t\<rparr>)) = xf'' t" and gi: "\<And>s. globals (i s) = globals s" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. \<lbrakk>r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE\<rbrakk> \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv')" and err: "\<And>err rv' err'. \<lbrakk>ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err'\<rbrakk> \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf (QE err) (Q'' err rv' err') hs (throwError err) (d' rv')" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>" shows "ccorres_underlying rf_sr \<Gamma> (fl \<currency> r) xf arrel axf (P and R) ({s. i s \<in> P'} \<inter> {s. \<forall>t. (ef' (xf'' t) = scast EXCEPTION_NONE \<longrightarrow> (\<forall>rv. r' rv (vf' (xf'' t)) \<longrightarrow> g s t (s\<lparr>globals := globals t\<rparr>) \<in> Q' rv (xf'' t))) \<and> (ef' (xf'' t) \<noteq> scast EXCEPTION_NONE \<longrightarrow> (\<forall>err. f' err (ef' (xf'' t)) (errstate t) \<longrightarrow> g s t (s\<lparr>globals := globals t\<rparr>) \<in> Q'' err (xf'' t) (errstate t)))} ) hs (a >>=E b) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>x y. Basic (g x y));; d)" (is "ccorres_underlying rf_sr \<Gamma> ?r ?xf arrel axf ?P (?Q1 \<inter> ?Q2) hs ?A ?B") unfolding bindE_def apply (rule_tac R="case_sum QE Q" and R'="\<lambda>rv. {s. s \<in> case_sum QE' QR' rv (xf' s)}" for QE' QR' in ccorres_master_split_nohs) apply (rule ccorres_callE [OF ac]) apply (rule gg) apply (rule errstate_state_update) apply (simp add: gg)+ apply (rule xfxf) apply (rule gi) apply (rule ccorres_abstract[OF ceqv]) apply (case_tac rv, simp_all add: lift_def) apply (rule_tac xf'=errstate in ccorres_abstract[OF ceqv_refl]) apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (erule_tac err'1=rv'a in err, assumption) apply (rule ccorres_gen_asm2) apply (rule ccorres_gen_asm2) apply (erule(1) bd) apply (rule hoare_strengthen_post) apply (rule valid [unfolded validE_def]) apply (simp split: sum.split_asm) apply (rule exec_handlers_Hoare_call_Basic) apply (clarsimp simp: ccHoarePost_def xfxf gg errstate_def split: sum.split) apply simp done lemma ccorres_split_nothrow_call_record: assumes ac: "ccorres r' xf'' P P' [] a (Call f)" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' (xfru (\<lambda>_. rv') oldv))" and ggl: "\<And>f s. globals (xfu' f s) = globals s" and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v" and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v" and igl: "\<And>s. globals (i s) = globals s" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>" and valid': "\<Gamma> \<turnstile>\<^bsub>/F\<^esub> R' call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))) {s. xf' s = xfru (\<lambda>_. (xfr \<circ> xf') s) oldv \<and> (\<forall>rv. r' rv ((xfr \<circ> xf') s) \<longrightarrow> s \<in> Q' rv ((xfr \<circ> xf') s))}" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'} \<inter> R') hs (a >>= (\<lambda>rv. b rv)) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))) ;; d)" using ac ggl xfxfu xfrxfru igl ceqv apply (rule ccorres_split_nothrow_record [OF ccorres_call_record]) apply (erule bd) apply (rule valid) apply (rule valid') done lemma ccorres_split_nothrow_call_record_novcg: assumes ac: "ccorres r' xf'' P P' [] a (Call f)" and ceqv: "\<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv')" and bd: "\<And>rv rv'. r' rv rv' \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' (xfru (\<lambda>_. rv') oldv))" and ggl: "\<And>f s. globals (xfu' f s) = globals s" and xfxfu: "\<And>v s. xf' (xfu' (\<lambda>_. v) s) = v" and xfrxfru: "\<And>v s. xfr (xfru (\<lambda>_. v) s) = v" and igl: "\<And>s. globals (i s) = globals s" and valid: "\<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>" and novcg: "guard_is_UNIV r' (xfr \<circ> xf') Q'" \<comment> \<open>This might cause problems \<dots> has to be preserved across c in vcg case, but we can't do that\<close> and xfoldv: "\<And>s. xf' s = xfru (\<lambda>_. (xfr \<circ> xf') s) oldv" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf (P and R) ({s. i s \<in> P'}) hs (a >>= (\<lambda>rv. b rv)) (call i f (\<lambda>s t. s\<lparr>globals := globals t\<rparr>) (\<lambda>_ t. Basic (xfu' (\<lambda>_. xfru (\<lambda>_. xf'' t) oldv))) ;; d)" using ac ggl xfxfu xfrxfru igl ceqv apply (rule ccorres_split_nothrow_record_novcg [OF ccorres_call_record]) apply (erule bd) apply (rule valid) apply (rule novcg) apply (rule xfoldv) done lemma ccorres_return_C: assumes xf1: "\<And>s f. xf (global_exn_var_'_update f (xfu (\<lambda>_. v s) s)) = v s" and xfu: "\<And>s f. globals (xfu f s) = globals s" and wfh: "wfhandlers hs" shows "ccorres_underlying rf_sr \<Gamma> r rvxf arrel xf \<top> {s. arrel rv (v s)} hs (return rv) (return_C xfu v)" apply (rule ccorres_guard_imp2, rule ccorres_return_C') apply (simp add: xf1) apply (rule wfh) apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs) apply simp done lemma ccorres_return_CE: assumes xf1: "\<And>s f. xf (global_exn_var_'_update f (xfu (\<lambda>_. v s) s)) = v s" and xfu: "\<And>s f. globals (xfu f s) = globals s" and wfh: "wfhandlers hs" shows "ccorres_underlying rf_sr \<Gamma> rvr rxf (f \<currency> r) (liftxf es sf vf xf) \<top> {s. sf (v s) = scast EXCEPTION_NONE \<and> r rv (vf (v s))} hs (returnOk rv) (return_C xfu v)" apply (rule ccorres_guard_imp2, rule ccorres_return_CE') apply (simp add: xf1) apply (rule wfh) apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs) apply simp done lemma ccorres_return_C_errorE: assumes xfc: "\<And>s. xf (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = v s" and esc: "\<And>s. es (global_exn_var_'_update (\<lambda>_. Return) (xfu (\<lambda>_. v s) s)) = es s" and xfu: "\<And>s f. globals (xfu f s) = globals s" and wfh: "wfhandlers hs" shows "ccorres_underlying rf_sr \<Gamma> rvr rvxf (f \<currency> r) (liftxf es sf vf xf) \<top> {s. sf (v s) \<noteq> scast EXCEPTION_NONE \<and> f rv (sf (v s)) (es s)} hs (throwError rv) (return_C xfu v)" apply (rule ccorres_guard_imp2, rule ccorres_return_C_errorE') apply (rule xfc) apply (rule esc) apply (rule wfh) apply (simp add: xfu rf_sr_def cong: cstate_relation_only_t_hrs) apply simp done (* Generalise *) (* c can't fail here, so no /F *) lemma ccorres_noop: assumes nop: "\<forall>s. \<Gamma> \<turnstile> {s} c {t. t may_not_modify_globals s}" shows "ccorres_underlying rf_sr \<Gamma> dc xf arrel axf \<top> UNIV hs (return ()) c" apply (rule ccorres_from_vcg, rule allI, simp add: return_def) apply (rule HoarePartial.conseq_exploit_pre) apply simp apply (intro allI impI) apply (rule HoarePartial.conseq) apply (rule nop) apply clarsimp apply (erule iffD1 [OF rf_sr_upd, rotated -1]) apply (clarsimp simp: meq_def mex_def)+ done lemma ccorres_noop_spec: assumes s: "\<forall>s. \<Gamma> \<turnstile> (P s) c (R s), (A s)" and nop: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/F\<^esub> {s} c {t. t may_not_modify_globals s}" shows "ccorres_underlying rf_sr \<Gamma> dc xf arrel axf \<top> {s. s \<in> P s} hs (return ()) c" apply (rule ccorres_from_vcg, rule allI, simp add: return_def) apply (rule HoarePartial.conseq_exploit_pre) apply simp apply (intro allI impI) apply (rule HoarePartial.conseq) apply (rule allI) apply (rule HoarePartialProps.Merge_PostConj) apply (rule_tac P = "{s} \<inter> P s" in conseqPre) apply (rule_tac x = s in spec [OF s]) apply clarsimp apply (rule_tac x = s in spec [OF nop]) apply simp apply clarsimp apply clarsimp apply (erule iffD2 [OF rf_sr_upd, rotated -1]) apply (clarsimp simp: meq_def mex_def)+ done (* FIXME: MOVE *) lemma ccorres_symb_exec_r2: assumes cul: "ccorres_underlying rf_sr \<Gamma> r xf arrel axf R Q' hs a d" and ex: "\<Gamma> \<turnstile> R' c Q'" and pres: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/F\<^esub> {s} c {t. t may_not_modify_globals s}" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf R R' hs a (c ;; d)" apply (rule ccorres_add_return) apply (rule ccorres_guard_imp2) apply (rule ccorres_split_nothrow') apply (rule ccorres_noop_spec) apply (rule allI) apply (rule ex) apply (rule pres) apply simp apply (rule cul) apply wp apply (rule HoarePartialProps.augment_Faults [OF ex]) apply simp apply simp done lemma ccorres_trim_redundant_throw: "\<lbrakk>ccorres_underlying rf_sr \<Gamma> arrel axf arrel axf G G' (SKIP # hs) a c; \<And>s f. axf (global_exn_var_'_update f s) = axf s \<rbrakk> \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' (SKIP # hs) a (c;; Basic (global_exn_var_'_update (\<lambda>_. Return));; THROW)" apply - apply (rule ccorres_trim_redundant_throw') apply simp apply simp apply (simp add: rf_sr_upd_safe) done end lemmas in_magnitude_check' = in_magnitude_check [where v = "fst z" and s' = "snd z" for z, folded surjective_pairing] (* Defined in terms of access_ti for convenience *) lemma fd_cons_update_accessD: "\<lbrakk> fd_cons_update_access d n; length bs = n \<rbrakk> \<Longrightarrow> field_update d (field_access d v bs) v = v" unfolding fd_cons_update_access_def by simp lemma fd_cons_access_updateD: "\<lbrakk> fd_cons_access_update d n; length bs = n; length bs' = n\<rbrakk> \<Longrightarrow> field_access d (field_update d bs v) bs' = field_access d (field_update d bs v') bs'" unfolding fd_cons_access_update_def by clarsimp context kernel begin (* Tests *) lemma cte_C_cap_C_tcb_C': fixes val :: "cap_C" and ptr :: "cte_C ptr" assumes cl: "clift hp ptr = Some z" shows "(clift (hrs_mem_update (heap_update (Ptr &(ptr\<rightarrow>[''cap_C''])) val) hp)) = (clift hp :: tcb_C typ_heap)" using cl by (simp add: typ_heap_simps) lemma cte_C_cap_C_update: fixes val :: "cap_C" and ptr :: "cte_C ptr" assumes cl: "clift hp ptr = Some z" shows "(clift (hrs_mem_update (heap_update (Ptr &(ptr\<rightarrow>[''cap_C''])) val) hp)) = clift hp(ptr \<mapsto> cte_C.cap_C_update (\<lambda>_. val) z)" using cl by (simp add: clift_field_update) abbreviation "modifies_heap_spec f \<equiv> \<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} Call f {t. t may_only_modify_globals s in [t_hrs]}" (* Used for bitfield lemmas. Note that this doesn't follow the usual schematic merging: we generally need concrete G and G' *) lemma ccorres_from_spec_modifies_heap: assumes spec: "\<forall>s. \<Gamma>\<turnstile> \<lbrace>s. P s\<rbrace> Call f {t. Q s t}" and mod: "modifies_heap_spec f" and xfg: "\<And>f s. xf (globals_update f s) = xf s" and Pimp: "\<And>s s'. \<lbrakk> G s; s' \<in> G'; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow> P s'" and rl: "\<And>s s' t'. \<lbrakk>G s; s' \<in> G'; (s, s') \<in> rf_sr; Q s' t'\<rbrakk> \<Longrightarrow> \<exists>(rv, t) \<in> fst (a s). (t, t'\<lparr>globals := globals s'\<lparr>t_hrs_' := t_hrs_' (globals t')\<rparr>\<rparr>) \<in> rf_sr \<and> r rv (xf t')" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' [] a (Call f)" apply (rule ccorres_Call_call_for_vcg) apply (rule ccorres_from_vcg) apply (rule allI, rule conseqPre) apply (rule HoarePartial.ProcModifyReturnNoAbr [where return' = "\<lambda>s t. t\<lparr> globals := globals s\<lparr>t_hrs_' := t_hrs_' (globals t) \<rparr>\<rparr>"]) apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ spec]) apply (rule subset_refl) apply vcg prefer 2 apply (rule mod) apply (clarsimp simp: mex_def meq_def) apply (clarsimp simp: split_beta Pimp) apply (subst bex_cong [OF refl]) apply (rule arg_cong2 [where f = "(\<and>)"]) apply (rule_tac y = "t\<lparr>globals := globals x\<lparr>t_hrs_' := t_hrs_' (globals t)\<rparr>\<rparr>" in rf_sr_upd, simp_all) apply (drule (3) rl) apply (clarsimp simp: xfg elim!: bexI [rotated]) done (* Used for bitfield lemmas *) lemma ccorres_from_spec_modifies: assumes spec: "\<forall>s. \<Gamma>\<turnstile> \<lbrace>s. P s\<rbrace> Call f {t. Q s t}" and mod: "modifies_spec f" and xfg: "\<And>f s. xf (globals_update f s) = xf s" and Pimp: "\<And>s s'. \<lbrakk> G s; s' \<in> G'; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow> P s'" and rl: "\<And>s s' t'. \<lbrakk>G s; s' \<in> G'; (s, s') \<in> rf_sr; Q s' t'\<rbrakk> \<Longrightarrow> \<exists>(rv, t) \<in> fst (a s). (t, s') \<in> rf_sr \<and> r rv (xf t')" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' [] a (Call f)" apply (rule ccorres_Call_call_for_vcg) apply (rule ccorres_from_vcg) apply (rule allI, rule conseqPre) apply (rule HoarePartial.ProcModifyReturnNoAbr [where return' = "\<lambda>s t. t\<lparr> globals := globals s \<rparr>"]) apply (rule HoarePartial.ProcSpecNoAbrupt [OF _ _ spec]) apply (rule subset_refl) apply vcg prefer 2 apply (rule mod) apply (clarsimp simp: mex_def meq_def) apply (clarsimp simp: split_beta Pimp) apply (subst bex_cong [OF refl]) apply (rule arg_cong2 [where f = "(\<and>)"]) apply (rule_tac y = "x" in rf_sr_upd, simp_all) apply (drule (3) rl) apply (clarsimp simp: xfg elim!: bexI [rotated]) done lemma ccorres_trim_return: assumes fg: "\<And>s. xfu (\<lambda>_. axf s) s = s" and xfu: "\<And>f s. axf (global_exn_var_'_update f s) = axf s" and cc: "ccorres_underlying rf_sr \<Gamma> arrel axf arrel axf G G' (SKIP # hs) a c" shows "ccorres_underlying rf_sr \<Gamma> r xf arrel axf G G' (SKIP # hs) a (c ;; return_C xfu axf)" using fg unfolding creturn_def apply - apply (rule ccorres_rhs_assoc2)+ apply (rule ccorres_trim_redundant_throw) apply (clarsimp split del: if_split) apply (rule iffD2 [OF ccorres_semantic_equiv, OF _ cc]) apply (rule semantic_equivI) apply (case_tac s') apply (auto elim!: exec_Normal_elim_cases exec_elim_cases intro!: exec.intros)[4] apply (rule xfu) done lemma rf_sr_globals_exn_var: "((s, global_exn_var_'_update f s') \<in> rf_sr) = ((s, s') \<in> rf_sr)" by (rule rf_sr_upd, simp_all) lemma ccorres_trim_returnE: assumes fg: "\<And>s. xfu (\<lambda>_. axf s) s = s" and xfu: "\<And>f s. axf (global_exn_var_'_update f s) = axf s" and cc: "ccorres r (liftxf errstate ef vf axf) G G' (SKIP # hs) a c" shows "ccorres_underlying rf_sr \<Gamma> rvr rvxf r (liftxf errstate ef vf axf) G G' (SKIP # hs) a (c ;; return_C xfu axf)" unfolding creturn_def apply (rule ccorres_rhs_assoc2)+ apply (rule ccorres_trim_redundant_throw') apply (simp add: fg) apply (rule iffD2 [OF ccorres_semantic_equiv, OF _ cc]) apply (rule semantic_equivI) apply (case_tac s') apply (auto elim!: exec_Normal_elim_cases exec_elim_cases intro!: exec.intros)[4] apply (simp add: liftxf_def xfu) apply (simp add: rf_sr_globals_exn_var) done lemma ccorres_sequence_while_genQ: fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<And>n ys. \<lbrakk> n < length xs \<rbrakk> \<Longrightarrow> ccorres (\<lambda>rv rv'. r' (ys @ [rv]) rv') xf' (F (n * j)) ({s. xf s = of_nat (i + n * j) \<and> r' ys (xf' s)} \<inter> Q) hs (xs ! n) body" and pn: "\<And>n. P n = (n < of_nat (i + length xs * j))" and bodyi: "\<forall>s. xf s < of_nat (i + length xs * j) \<longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and lxs: "i + length xs * j< 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)" and j: "j > 0" shows "ccorres (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs * of_nat j)) (\<lambda>s. (xf s, xf' s)) (\<lambda>s. P 0 \<longrightarrow> F 0 s) ({s. xf s = of_nat i \<and> r' [] (xf' s)} \<inter> Q) hs (sequence xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))" (is "ccorres ?r' ?xf' ?G (?G' \<inter> _) hs (sequence xs) ?body") apply (rule ccorres_sequence_while_genQ' [OF one pn bodyi hi lxs xf xf']) apply simp apply simp apply (clarsimp simp: rf_sr_def xf) apply (simp add: j) done lemma ccorres_sequence_while_gen': fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<And>n ys. \<lbrakk> n < length xs \<rbrakk> \<Longrightarrow> ccorres (\<lambda>rv rv'. r' (ys @ [rv]) rv') xf' (F (n * j)) {s. xf s = of_nat (i + n * j) \<and> r' ys (xf' s)} hs (xs ! n) body" and pn: "\<And>n. P n = (n < of_nat (i + length xs * j))" and bodyi: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and lxs: "i + length xs * j< 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s)" and j: "j > 0" shows "ccorres (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs * of_nat j)) (\<lambda>s. (xf s, xf' s)) (F 0) ({s. xf s = of_nat i \<and> r' [] (xf' s)}) hs (sequence xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))" (is "ccorres ?r' ?xf' ?G ?G' hs (sequence xs) ?body") using assms apply - apply (rule ccorres_guard_imp2) apply (rule ccorres_sequence_while_genQ [where Q=UNIV]) apply (assumption|simp)+ done lemma ccorres_sequence_x_while_genQ': fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" shows "\<lbrakk>\<And>n. n < length xs \<Longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat (i + n * j)} \<inter> Q) hs (xs ! n) body; \<And>n. P n = (n < of_nat (i + length xs * j)); \<forall>s. xf s < of_nat (i + length xs * j) \<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}; \<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>; i + length xs * j < 2 ^ len_of TYPE('c); \<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s; j > 0 \<rbrakk> \<Longrightarrow> ccorres (\<lambda>rv i'. i' = of_nat (i + length xs * of_nat j)) xf (\<lambda>s. P 0 \<longrightarrow> F 0 s) ({s. xf s = of_nat i} \<inter> Q) hs (NonDetMonad.sequence_x xs) (While {s. P (xf s)} (body;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))" apply (simp add: sequence_x_sequence liftM_def[symmetric] ccorres_liftM_simp) apply (rule ccorres_rel_imp) apply (rule ccorres_sequence_while_genQ [where xf'=xfdc and r'=dc and xf_update=xf_update, simplified], (simp add: dc_def)+) done lemma ccorres_sequence_x_while_gen': fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" shows "\<lbrakk>\<And>n ys. n < length xs \<Longrightarrow> ccorres dc xfdc (F (n * j)) {s. xf s = of_nat (i + n * j)} hs (xs ! n) body; \<And>n. P n = (n < of_nat (i + length xs * j)); \<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s}; \<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>; i + length xs * j < 2 ^ len_of TYPE('c); \<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s; 0 < j \<rbrakk> \<Longrightarrow> ccorres (\<lambda>rv i'. i' = of_nat (i + length xs * of_nat j)) xf (F 0) {s. xf s = of_nat i} hs (NonDetMonad.sequence_x xs) (While {s. P (xf s)} (body;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))" apply (simp add: sequence_x_sequence liftM_def[symmetric] ccorres_liftM_simp) apply (rule ccorres_rel_imp) apply (rule ccorres_sequence_while_gen' [where xf'=xfdc and r'=dc and xf_update=xf_update, simplified], (simp add: dc_def)+) done lemma i_xf_for_sequence: "\<forall>s f. i_' (i_'_update f s) = f (i_' s) \<and> globals (i_'_update f s) = globals s" by simp lemmas ccorres_sequence_x_while' = ccorres_sequence_x_while_gen' [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemma ccorres_sequence_x_while_genQ: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<forall>n < length xs. ccorres dc xfdc (F (n * j) ) ({s. xf s = of_nat n * of_nat j} \<inter> Q) hs (xs ! n) body" and pn: "\<And>n. P n = (n < of_nat (length xs * j))" and bodyi: "\<forall>s. xf s < of_nat (length xs * j) \<longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and lxs: "length xs * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (\<lambda>s. P 0 \<longrightarrow> F 0 s) {s. xf_update (\<lambda>_. 0) s \<in> Q} hs (sequence_x xs) (Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);; (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))" apply (rule ccorres_symb_exec_r) apply (rule ccorres_sequence_x_while_genQ' [where i=0 and xf_update=xf_update and Q=Q, simplified]) apply (simp add: assms hi[simplified])+ apply (rule conseqPre, vcg) apply (clarsimp simp add: xf) apply (rule conseqPre, vcg) apply (simp add: xf rf_sr_def) done lemma ccorres_sequence_x_while_gen: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<forall>n < length xs. ccorres dc xfdc (F (n * j)) {s. xf s = of_nat n * of_nat j} hs (xs ! n) body" and pn: "\<And>n. P n = (n < of_nat (length xs * j))" and bodyi: "\<forall>s. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body {t. xf t = xf s}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace> F (n * j) \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and lxs: "length xs * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (F 0) UNIV hs (sequence_x xs) (Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);; (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))" apply (rule ccorres_symb_exec_r) apply (rule ccorres_sequence_x_while_gen' [where i=0 and xf_update=xf_update, simplified]) apply (simp add: assms hi[simplified])+ apply vcg apply (simp add: xf) apply vcg apply (simp add: xf rf_sr_def) done lemmas ccorres_sequence_x_while = ccorres_sequence_x_while_gen [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemmas ccorres_sequence_x_whileQ = ccorres_sequence_x_while_genQ [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemma ccorres_mapM_x_while_gen: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes rl: "\<forall>n. n < length xs \<longrightarrow> ccorres dc xfdc (F (n * j)) {s. xf s = of_nat n * of_nat j} hs (f (xs ! n)) body" and guard: "\<And>n. P n = (n < of_nat (length xs * j))" and bodyi: "\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {s'. xf s' = xf s}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and wb: "length xs * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (F (0 :: nat)) UNIV hs (mapM_x f xs) (Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);; (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))" unfolding mapM_x_def apply (rule ccorres_rel_imp) apply (rule ccorres_sequence_x_while_gen[where xf_update=xf_update]) apply (simp add: assms hi[simplified])+ done lemmas ccorres_mapM_x_while = ccorres_mapM_x_while_gen [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemma ccorres_mapM_x_while_genQ: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes rl: "\<forall>n. n < length xs \<longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat n * of_nat j} \<inter> Q) hs (f (xs ! n)) body" and guard: "\<And>n. P n = (n < of_nat (length xs * j))" and bodyi: "\<forall>s. xf s < of_nat (length xs * j) \<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and wb: "length xs * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (length xs) * of_nat j) xf (\<lambda>s. P 0 \<longrightarrow> F (0 :: nat) s) {s. xf_update (\<lambda>_. 0) s \<in> Q} hs (mapM_x f xs) (Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);; (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))" unfolding mapM_x_def apply (rule ccorres_rel_imp) apply (rule ccorres_sequence_x_while_genQ[where xf_update=xf_update]) apply (simp add: assms hi[simplified])+ done lemmas ccorres_mapM_x_whileQ = ccorres_mapM_x_while_genQ [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemma ccorres_mapM_x_while_gen': fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes rl: "\<forall>n. n < length xs \<longrightarrow> ccorres dc xfdc (F (n * j)) {s. xf s = of_nat (i + n * j)} hs (f (xs ! n)) body" and guard: "\<And>n. P n = (n < of_nat (i + length xs * j))" and bodyi: "\<forall>s. \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body {s'. xf s' = xf s}" and hi: "\<And>n. Suc n < length xs \<Longrightarrow> \<lbrace>F (n *j)\<rbrace> f (xs ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and wb: "i + length xs * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (i + length xs * j)) xf (F (0 :: nat)) {s. xf s = of_nat i} hs (mapM_x f xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s)))" unfolding mapM_x_def apply (rule ccorres_rel_imp) apply (rule ccorres_sequence_x_while_gen'[where xf_update=xf_update]) apply (clarsimp simp only: length_map nth_map rl) apply (simp add: assms hi[simplified])+ done lemmas ccorres_mapM_x_while' = ccorres_mapM_x_while_gen' [OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] lemma ccorres_zipWithM_x_while_genQ: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes rl: "\<forall>n. n < length xs \<and> n < length ys \<longrightarrow> ccorres dc xfdc (F (n * j)) ({s. xf s = of_nat n * of_nat j} \<inter> Q) hs (f (xs ! n) (ys ! n)) body" and guard: "\<And>n. P n = (n < of_nat (min (length xs) (length ys)) * of_nat j)" and bodyi: "\<forall>s. xf s < of_nat (min (length xs) (length ys)) * of_nat j \<longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> ({s} \<inter> Q) body {t. xf t = xf s \<and> xf_update (\<lambda>x. xf t + of_nat j) t \<in> Q}" and hi: "\<And>n. Suc n < length xs \<and> Suc n < length ys \<Longrightarrow> \<lbrace>F (n * j)\<rbrace> f (xs ! n) (ys ! n) \<lbrace>\<lambda>_. F (Suc n * j)\<rbrace>" and wb: "min (length xs) (length ys) * j < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s) \<and> globals (xf_update f s) = globals s" and j: "0 < j" shows "ccorres (\<lambda>rv rv'. rv' = of_nat (min (length xs) (length ys) * j)) xf (F (0 :: nat)) {s. xf_update (\<lambda>_. 0) s \<in> Q} hs (zipWithM_x f xs ys) (Basic (\<lambda>s. xf_update (\<lambda>_. 0) s);; (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + of_nat j) s))))" unfolding zipWithM_x_def apply (rule ccorres_guard_imp) apply (rule ccorres_rel_imp [OF ccorres_sequence_x_while_genQ[where F=F, OF _ _ _ _ _ xf j]], simp_all add: length_zipWith) apply (simp add: length_zipWith zipWith_nth) apply (rule rl) apply (rule guard) apply (rule bodyi) apply (simp add: zipWith_nth hi[simplified]) apply (rule wb) done lemmas ccorres_zipWithM_x_while_gen = ccorres_zipWithM_x_while_genQ[where Q=UNIV, simplified] lemmas ccorres_zipWithM_x_while = ccorres_zipWithM_x_while_gen[OF _ _ _ _ _ i_xf_for_sequence, folded word_bits_def, where j=1, simplified] end lemma ccorres_sequenceE_while_gen_either_way: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf' (inl_rrel arrel) axf (F n) (Q \<inter> {s. xf s = xfrel n \<and> r' ys (xf' s)}) hs (xs ! n) body" and pn: "\<And>n. (n < length xs \<longrightarrow> P (xfrel n)) \<and> \<not> P (xfrel (length xs))" and xfrel_u: "\<And>n. xfrel_upd (xfrel n) = xfrel (Suc n)" and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV" and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)" and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s) \<and> ((xf_update f s \<in> Q) = (s \<in> Q)) \<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))" shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = xfrel (length xs))) (\<lambda>s. (xf s, xf' s)) arrel axf (F 0) (Q \<inter> {s. xf s = xfrel 0 \<and> r' [] (xf' s)}) hs (sequenceE xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xfrel_upd (xf s)) s)))" (is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body") proof - define init_xs where "init_xs \<equiv> xs" have rl: "xs = drop (length init_xs - length xs) init_xs" unfolding init_xs_def by fastforce note pn' = pn [folded init_xs_def] note one' = one [folded init_xs_def] note hi' = hi [folded init_xs_def] let ?Q = "\<lambda>xs. F (length init_xs - length xs)" let ?Q' = "\<lambda>xs zs. Q \<inter> {s. (xf s) = xfrel (length init_xs - length xs) \<and> r' zs (xf' s)}" let ?r'' = "\<lambda>zs rv (i', rv'). r' (zs @ rv) rv' \<and> i' = xfrel (length init_xs)" have "\<forall>zs. length zs = length init_xs - length xs \<longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (?r'' zs)) ?xf' (inl_rrel arrel) axf (?Q xs) (?Q' xs zs) hs (sequenceE xs) ?body" using rl proof (induct xs) case Nil thus ?case apply clarsimp apply (rule iffD1 [OF ccorres_expand_while_iff]) apply (simp add: sequenceE_def returnOk_def) apply (rule ccorres_guard_imp2) apply (rule ccorres_cond_false) apply (rule ccorres_return_Skip') apply (simp add: pn') done next case (Cons y ys) from Cons.prems have ly: "length (y # ys) \<le> length init_xs" by simp hence ln: "(length init_xs - length ys) = Suc (length init_xs - length (y # ys))" by simp hence yv: "y = init_xs ! (length init_xs - length (y # ys))" using Cons.prems by (fastforce simp add: drop_Suc_nth not_le) have lt0: "0 < length init_xs" using ly by clarsimp hence ly': "length init_xs - length (y # ys) < length init_xs" by simp note one'' = one'[OF ly', simplified yv[symmetric]] have ys_eq: "ys = drop (length init_xs - length ys) init_xs" using ln Cons.prems by (fastforce simp add: drop_Suc_nth not_le) note ih = Cons.hyps [OF ys_eq, rule_format] note hi'' = hi' [OF ly', folded yv] show ?case apply (clarsimp simp: sequenceE_Cons) apply (rule ccorres_guard_imp2) apply (rule iffD1 [OF ccorres_expand_while_iff]) apply (rule ccorres_cond_true) apply (rule ccorres_rhs_assoc)+ apply (rule ccorres_splitE) apply (simp add: inl_rrel_inl_rrel) apply (rule_tac ys="zs" in one'') apply simp apply (rule ceqv_refl) apply (rule ccorres_symb_exec_r) apply (simp add: liftME_def[symmetric] liftME_liftM) apply (rule ccorres_rel_imp2, rule_tac zs="zs @ [rv]" in ih) apply (cut_tac ly, simp) apply (clarsimp elim!: inl_inrE) apply (clarsimp elim!: inl_inrE) apply vcg apply (rule conseqPre) apply vcg apply (clarsimp simp: xf xf') apply (subst ln) apply (rule hi'') apply (rule HoarePartialDef.Conseq [where P = "Q \<inter> {s. xfrel_upd (xf s) = xfrel (length init_xs - length ys)}"]) apply (intro ballI exI) apply (rule conjI) apply (rule_tac s=s in bodyi) apply simp apply (clarsimp simp: xf xf' ccHoarePost_def elim!: inl_inrE) apply (clarsimp simp: ln pn' xfrel_u diff_Suc_less[OF lt0]) done qed thus ?thesis by (clarsimp simp: init_xs_def dest!: spec[where x=Nil] elim!: ccorres_rel_imp2 inl_inrE) qed lemma ccorres_sequenceE_while_down: fixes xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf' (inl_rrel arrel) axf (F n) (Q \<inter> {s. xf s = (startv - of_nat n) \<and> r' ys (xf' s)}) hs (xs ! n) body" and pn: "\<And>n. (n < length xs \<longrightarrow> P (startv - of_nat n)) \<and> \<not> P (startv - of_nat (length xs))" and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV" and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)" and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s) \<and> ((xf_update f s \<in> Q) = (s \<in> Q)) \<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))" shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = (startv - of_nat (length xs)))) (\<lambda>s. (xf s, xf' s)) arrel axf (F 0) (Q \<inter> {s. xf s = (startv - of_nat 0) \<and> r' [] (xf' s)}) hs (sequenceE xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s - 1) s)))" (is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body") by (rule ccorres_sequenceE_while_gen_either_way [OF one, where xf_update=xf_update], simp_all add: bodyi hi xf xf' pn) lemma ccorres_sequenceE_while_gen': fixes i :: "nat" and xf :: "globals myvars \<Rightarrow> ('c :: len) word" assumes one: "\<And>n ys. \<lbrakk> n < length xs; n = length ys \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf' (inl_rrel arrel) axf (F n) (Q \<inter> {s. xf s = of_nat (i + n) \<and> r' ys (xf' s)}) hs (xs ! n) body" and pn: "\<And>n. P n = (n < of_nat (i + length xs))" and bodyi: "\<And>s. s \<in> Q \<Longrightarrow> \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. xf t = xf s}), UNIV" and hi: "\<And>n. n < length xs \<Longrightarrow> \<lbrace> F n \<rbrace> (xs ! n) \<lbrace>\<lambda>_. F (Suc n)\<rbrace>,-" and lxs: "i + length xs < 2 ^ len_of TYPE('c)" and xf: "\<forall>s f. xf (xf_update f s) = f (xf s)" and xf': "\<forall>s f. xf' (xf_update f s) = (xf' s) \<and> ((xf_update f s \<in> Q) = (s \<in> Q)) \<and> (\<forall>s'. ((s', xf_update f s) \<in> sr) = ((s', s) \<in> sr))" shows "ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (i + length xs))) (\<lambda>s. (xf s, xf' s)) arrel axf (F 0) (Q \<inter> {s. xf s = of_nat i \<and> r' [] (xf' s)}) hs (sequenceE xs) (While {s. P (xf s)} (body ;; Basic (\<lambda>s. xf_update (\<lambda>_. xf s + 1) s)))" (is "ccorres_underlying sr \<Gamma> (inr_rrel ?r') ?xf' arrel axf ?G ?G' hs (sequenceE xs) ?body") apply (rule ccorres_sequenceE_while_gen_either_way [OF one, where xf_update=xf_update, simplified add_0_right], simp_all add: bodyi hi lxs xf xf' pn) apply clarsimp apply (simp only: Abs_fnat_hom_add, rule of_nat_mono_maybe) apply (rule lxs) apply simp done lemma ccorres_sequenceE_while: fixes axf :: "globals myvars \<Rightarrow> 'e" shows "\<lbrakk>\<And>ys. length ys < length xs \<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv rv'. r' (ys @ [rv]) rv')) xf' (inl_rrel arrel) axf (F (length ys)) (Q \<inter> {s. i_' s = of_nat (length ys) \<and> r' ys (xf' s)}) hs (xs ! length ys) body; \<And>n. P n = (n < of_nat (length xs)); \<And>s. s \<in> Q \<Longrightarrow> \<Gamma>\<turnstile>\<^bsub>/UNIV\<^esub> {s} body (Q \<inter> {t. i_' t = i_' s}),UNIV; \<And>n. n < length xs \<Longrightarrow> \<lbrace>F n\<rbrace> xs ! n \<lbrace>\<lambda>_. F (Suc n)\<rbrace>, -; length xs < 2 ^ word_bits; \<forall>s f. xf' (i_'_update f s) = xf' s \<and> ((i_'_update f s \<in> Q) = (s \<in> Q)) \<and> (\<forall>s'. ((s', i_'_update f s) \<in> sr) = ((s', s) \<in> sr)) \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> (inr_rrel (\<lambda>rv (i', rv'). r' rv rv' \<and> i' = of_nat (length xs))) (\<lambda>s. (i_' s, xf' s)) arrel axf (F 0) (Q \<inter> {s. r' [] (xf' s)}) hs (sequenceE xs) (Basic (\<lambda>s. i_'_update (\<lambda>_. 0) s) ;; While {s. P (i_' s)} (body;; Basic (\<lambda>s. i_'_update (\<lambda>_. i_' s + 1) s)))" apply (rule ccorres_guard_imp2) apply (rule ccorres_symb_exec_r) apply (rule ccorres_sequenceE_while_gen'[where i=0, simplified, where xf_update=i_'_update], (assumption | simp)+) apply (simp add: word_bits_def) apply simp+ apply vcg apply (rule conseqPre, vcg) apply clarsimp apply simp done context kernel begin lemma ccorres_split_nothrow_novcg_case_sum: "\<lbrakk>ccorresG sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') P P' [] a c; \<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv'); \<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv'); \<And>err rv' err'. \<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (e err) (d' rv'); \<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>; guard_is_UNIV (\<lambda>rv rv'. r' rv (vf' rv')) xf' (\<lambda>rv rv'. {s. ef' rv' = scast EXCEPTION_NONE \<longrightarrow> s \<in> Q' rv rv'}); \<And>err. guard_is_UNIV (\<lambda>rv. f' err (ef' rv)) es (\<lambda>rv rv'. {s. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> s \<in> Q'' err rv rv'})\<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) P' hs (a >>= case_sum e b) (c;;d)" apply (rule_tac R="case_sum QE Q" and R'="case_sum QE' QR'" for QE' QR' in ccorres_master_split_nohs_UNIV) apply assumption apply (case_tac rv, simp_all)[1] apply (erule ccorres_abstract) apply (rule ccorres_abstract[where xf'=es], rule ceqv_refl) apply (rule_tac P="ef' rv' \<noteq> scast EXCEPTION_NONE" in ccorres_gen_asm2) apply (rule_tac P="f' aa (ef' rv') rv'a" in ccorres_gen_asm2) apply assumption apply (erule ccorres_abstract) apply (rule_tac P="r' ba (vf' rv')" in ccorres_gen_asm2) apply (rule_tac P="ef' rv' = scast EXCEPTION_NONE" in ccorres_gen_asm2) apply assumption apply (simp add: validE_def) apply (erule hoare_strengthen_post, simp split: sum.split_asm) apply (clarsimp simp: guard_is_UNIV_def split: sum.split) done lemma ccorres_split_nothrow_case_sum: "\<lbrakk>ccorresG sr \<Gamma> (f' \<currency> r') (liftxf es ef' vf' xf') P P' hs a c; \<And>rv' t t'. ceqv \<Gamma> xf' rv' t t' d (d' rv'); \<And>rv rv'. \<lbrakk> r' rv (vf' rv'); ef' rv' = scast EXCEPTION_NONE \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (Q rv) (Q' rv rv') hs (b rv) (d' rv'); \<And>err rv' err'. \<lbrakk> ef' rv' \<noteq> scast EXCEPTION_NONE; f' err (ef' rv') err' \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (QE err) (Q'' err rv' err') hs (e err) (d' rv'); \<lbrace>R\<rbrace> a \<lbrace>Q\<rbrace>, \<lbrace>QE\<rbrace>; \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> R' c {s. (\<forall>rv'. ef' (xf' s) = scast EXCEPTION_NONE \<longrightarrow> r' rv' (vf' (xf' s)) \<longrightarrow> s \<in> Q' rv' (xf' s)) \<and> (\<forall>ft. ef' (xf' s) \<noteq> scast EXCEPTION_NONE \<longrightarrow> f' ft (ef' (xf' s)) (es s) \<longrightarrow> s \<in> Q'' ft (xf' s) (es s))} \<rbrakk> \<Longrightarrow> ccorres_underlying sr \<Gamma> r xf arrel axf (P and R) (P' \<inter> R') hs (a >>= case_sum e b) (c;;d)" apply (erule_tac R="case_sum QE Q" and R'="case_sum QE' QR'" for QE' QR' in ccorres_master_split_hs) apply (case_tac rv, simp_all)[1] apply (erule ccorres_abstract) apply (rule ccorres_abstract[where xf'=es], rule ceqv_refl) apply (rule_tac P="ef' rv' \<noteq> scast EXCEPTION_NONE" in ccorres_gen_asm2) apply (rule_tac P="f' aa (ef' rv') rv'a" in ccorres_gen_asm2) apply assumption apply (erule ccorres_abstract) apply (rule_tac P="r' ba (vf' rv')" in ccorres_gen_asm2) apply (rule_tac P="ef' rv' = scast EXCEPTION_NONE" in ccorres_gen_asm2) apply assumption apply (rule ccorres_empty[where P=\<top>]) apply (simp add: validE_def) apply (erule hoare_strengthen_post, simp split: sum.split_asm) apply (drule exec_handlers_Hoare_from_vcg_nofail) apply (erule exec_handlers_Hoare_Post [OF _ _ subset_refl]) apply (clarsimp simp: ccHoarePost_def split: sum.split) done end text \<open>@{method ccorres_rewrite} support for discarding everything after @{term creturn}.\<close> lemma never_continues_creturn [C_simp_throws]: "never_continues \<Gamma> (creturn rtu xfu v)" by (auto simp: never_continues_def creturn_def elim: exec_elim_cases) lemma never_continues_creturn_void [C_simp_throws]: "never_continues \<Gamma> (creturn_void rtu)" by (auto simp: never_continues_def creturn_void_def elim: exec_elim_cases) lemma "ccorres_underlying sr \<Gamma> r xf r' xf' P P' hs H (c1 ;; (c2 ;; c3 ;; (creturn rtu xfu v ;; c4 ;; c5) ;; c6 ;; c7))" apply ccorres_rewrite apply (match conclusion in "ccorres_underlying sr \<Gamma> r xf r' xf' P P' hs H (c1 ;; (c2 ;; c3 ;; creturn rtu xfu v))" \<Rightarrow> \<open>-\<close>) oops end
{-# OPTIONS --without-K #-} -- Rending the Program Runner -- A proof of Lӧb′s theorem: quoted interpreters are inconsistent -- Jason Gross {- Title and some comments inspired by and drawn heavily from "Scooping the Loop Sniffer: A proof that the Halting Problem is undecidable", by Geoffrey K. Pullum (http://www.lel.ed.ac.uk/~gpullum/loopsnoop.html) -} open import common infixl 2 _▻_ infixl 3 _‘’_ infixr 1 _‘→’_ {- "Scooping the Loop Sniffer", with slight modifications for this code. No general procedure for type-checking will do. Now, I won’t just assert that, I’ll prove it to you. I will prove that although you might work till you drop, you cannot tell if computation will stop. For imagine we have a procedure called P that for specified input permits you to see what specified source code, with all of its faults, defines a routine that eventually halts. You feed in your program, with suitable data, and P gets to work, and a little while later (in finite compute time) correctly infers whether infinite looping behavior occurs. If there will be no looping, then P prints out ‘Good.’ That means work on this input will halt, as it should. But if it detects an unstoppable loop, then P reports ‘Bad!’ — which means you’re in the soup. Well, the truth is that P cannot possibly be, because if you wrote it and gave it to me, I could use it to set up a logical bind that would shatter your reason and scramble your mind. For a specified program, say ‶A″, one supplies, the first step of this program called Q I devise is to find out from P what’s the right thing to say of the looping behavior of A run on ‶A″. If P’s answer is ‘Bad!’, Q will suddenly stop. But otherwise, Q will go back to the top, and start off again, looping endlessly back, till the universe dies and turns frozen and black. And this program called Q wouldn’t stay on the shelf; I would ask it to forecast its run on itself. When it reads its own source code, just what will it do? What’s the looping behavior of Q run on Q? If P warns of infinite loops, Q will quit; yet P is supposed to speak truly of it! And if Q’s going to quit, then P should say ‘Good.’ Which makes Q start to loop! (P denied that it would.) No matter how P might perform, Q will scoop it: Q uses P’s output to make P look stupid. Whatever P says, it cannot predict Q: P is right when it’s wrong, and is false when it’s true! I’ve created a paradox, neat as can be — and simply by using your putative P. When you posited P you stepped into a snare; Your assumption has led you right into my lair. So where can this argument possibly go? I don’t have to tell you; I’m sure you must know. A reductio: There cannot possibly be a procedure that acts like the mythical P. You can never find general mechanical means for predicting the acts of computing machines; it’s something that cannot be done. So we users must find our own bugs. Our computers are losers! -} {- Our program will act much like this Q, except that instead of saying that Q will go back to the top, and start off again, looping endlessly back, till the universe dies and turns frozen and black. We would say something more like that Q will go back to the top, and ask for the output of A run on ‶A″, trusting P that execution will not run away. Further more, we combine the type-checker and the interpreter; we show there cannot be a well-typed quoted interpreter that interprets all well-typed quoted terms directly, rather than having a separate phase of type-checking. Morally, they should be equivalent. -} {- We start off by defining Contexts, Types, and Terms which are well-typed by construction. We will prove that assuming Lӧb′s theorem is consistent in a minimal representation, and doesn′t require anything fancy to support it in a model of the syntax. Thus any reasonable syntax, which has a model, will also have a model validating Lӧb′s theorem. This last part is informal; it′s certainly conceivable that something like internalized parametricity, which needs to do something special with each constructor of the language, won't be able to do anything with the quotation operator. There's a much longer formalization of Lӧb′s theorem in this repository which just assumes a quotation operator, and proves Lӧb′s theorem by constructing it (though to build a quine, we end up needing to decide equality of Contexts, which is fine); the quotation operator is, in principle, definable, by stuffing the constructors of the syntax into an initial context, and building up the quoted terms by structural recursion. This would be even more painful, though, unless there′s a nice way to give specific quoted terms. Now, down to business. -} mutual -- Contexts are utterly standard data Context : Set where ε : Context _▻_ : (Γ : Context) → Type Γ → Context -- Types have standard substituition and non-dependent function -- types. data Type : Context → Set where _‘’_ : ∀ {Γ A} → Type (Γ ▻ A) → Term {Γ} A → Type Γ _‘→’_ : ∀ {Γ} → Type Γ → Type Γ → Type Γ -- We also require that there be a quotation of ‶Type ε″ (called -- ‘Typeε’), and a quotation of ‶Term ε″ (called ‘□’) ‘Typeε’ : Type ε ‘□’ : Type (ε ▻ ‘Typeε’) -- We don′t really need quoted versions of ⊤ and ⊥, but they are -- useful stating a few things after the proof of Lӧb′s theorem ‘⊤’ : ∀ {Γ} → Type Γ ‘⊥’ : ∀ {Γ} → Type Γ -- Note that you can add whatever other constructors to this data -- type you would like; data Term : {Γ : Context} → Type Γ → Set where -- We require the existence of a function (in the ambient language) -- that takes a type in the empty context, and returns the quotation -- of that type. ⌜_⌝ : Type ε → Term {ε} ‘Typeε’ -- Finally, we assume Lӧb′s theorem; we will show that this syntax -- has a model. Lӧb : ∀ {X} → Term {ε} (‘□’ ‘’ ⌜ X ⌝ ‘→’ X) → Term {ε} X -- This is not strictly required, just useful for showing that some -- type is inhabited. ‘tt’ : ∀ {Γ} → Term {Γ} ‘⊤’ {- ‶□ T″ is read ‶T is provable″ or ‶T is inhabited″ or ‶the type of syntactic terms of the syntactic type T″ or ‶the type of quoted terms of the quoted type T″. -} □ : Type ε → Set _ □ = Term {ε} mutual {- Having an inhabitant of type ‶the interpretation of a given Context″ is having an inhabitant of the interpretation of every type in that Context. If we wanted to represent more universes, we could sprinkle lifts and lowers, and it would not cause us trouble. They are elided here for simplicity. -} Context⇓ : (Γ : Context) → Set Context⇓ ε = ⊤ Context⇓ (Γ ▻ T) = Σ (Context⇓ Γ) (Type⇓ {Γ} T) -- Substitution and function types are interpreted standardly. Type⇓ : {Γ : Context} → Type Γ → Context⇓ Γ → Set Type⇓ (T ‘’ x) Γ⇓ = Type⇓ T (Γ⇓ , Term⇓ x Γ⇓) Type⇓ (A ‘→’ B) Γ⇓ = Type⇓ A Γ⇓ → Type⇓ B Γ⇓ -- ‘Typeε’ is, unsurprisingly, interpreted as Type ε, the type of -- syntactic types in the empty context. Type⇓ ‘Typeε’ Γ⇓ = Type ε -- ‘□’ expects Term of Type ‘Typeε’ as the last element of the -- context, and represents the type of Terms of that Type. We take -- the (already-interpreted) last element of the Context, and feed -- it to Term {ε}, to get the Set of Terms of that Type. Type⇓ ‘□’ Γ⇓ = Term {ε} (Σ.proj₂ Γ⇓) -- The rest of the interpreter, for types not formally needed in -- Lӧb′s theorem. Type⇓ ‘⊤’ Γ⇓ = ⊤ Type⇓ ‘⊥’ Γ⇓ = ⊥ Term⇓ : ∀ {Γ : Context} {T : Type Γ} → Term T → (Γ⇓ : Context⇓ Γ) → Type⇓ T Γ⇓ -- Unsurprisingly, we interpret the quotation of a given source code -- as the source code itself. (Defining the interpretation of -- quotation is really trivial. Defining quotation itself is much -- tricker.) Note that it is, I believe, essential, that every Type -- be quotable. Otherwise Lӧb′s theorem cannot be internalized in -- our syntactic representation, and will require both being given -- both a type, and syntax which denotes to that type. Term⇓ ⌜ x ⌝ Γ⇓ = x -- Now, the interesting part. Given an interpreter (P in the poem, -- □‘X’→X in this code), we validate Lӧb′s theorem (Q run on Q) by -- running the interpreter on ... Q run on Q! It takes a bit of -- thinking to wrap your head around, but the types line up, and -- it′s beautifully simple. Term⇓ (Lӧb □‘X’→X) Γ⇓ = Term⇓ □‘X’→X Γ⇓ (Lӧb □‘X’→X) -- Inhabiting ⊤ Term⇓ ‘tt’ Γ⇓ = tt ⌞_⌟ : Type ε → Set _ ⌞ T ⌟ = Type⇓ T tt ‘¬’_ : ∀ {Γ} → Type Γ → Type Γ ‘¬’ T = T ‘→’ ‘⊥’ -- With our interpreter, we can chain Lӧb′s theorem with itself: if we -- can prove that ‶proving ‘X’ is sufficient to make ‘X’ true″, then -- we can already inhabit X. lӧb : ∀ {‘X’} → □ (‘□’ ‘’ ⌜ ‘X’ ⌝ ‘→’ ‘X’) → ⌞ ‘X’ ⌟ lӧb f = Term⇓ (Lӧb f) tt -- We can thus prove that it′s impossible to prove that contradictions -- are unprovable. incompleteness : ¬ □ (‘¬’ (‘□’ ‘’ ⌜ ‘⊥’ ⌝)) incompleteness = lӧb -- We can also prove that contradictions are, in fact, unprovable. soundness : ¬ □ ‘⊥’ soundness x = Term⇓ x tt -- And we can prove that some things are provable, namely, ‘⊤’ non-emptyness : Σ (Type ε) (λ T → □ T) non-emptyness = ‘⊤’ , ‘tt’
import for_mathlib.algebraic_topology.skeleton.split import for_mathlib.algebraic_topology.skeleton.misc import category_theory.limits.mono_coprod open category_theory category_theory.limits opposite open_locale simplicial namespace simplicial_object namespace splitting variables {C : Type*} [category C] [has_finite_coproducts C] {X : simplicial_object C} (s : splitting X) [mono_coprod C] lemma sk_succ_comm_sq (d : ℕ) : comm_sq (sSet.tensor_map₁ (sSet.boundary_inclusion (d+1)) (s.N (d+1))) sorry ((sSet.tensor_yoneda_adjunction (d+1) (s.N (d+1)) (s.sk (d+1))).symm (s.ι_summand_sk (d+1) (index_set.truncated.id (op [d+1])))) (s.sk_inclusion (show d ≤ d+1, by exact nat.le_succ _)) := begin sorry, end end splitting end simplicial_object
Among the greatest sports franchises, Real Madrid is a perennial threat to win the top annual tournament, and one of the most recognisable football teams around the world. Capitalise on your love of los Blancos with this men's away jersey. Featuring ventilating climacool®, this crewneck shirt shows off a premium club badge on the left chest and signature 3-Stripes on the shoulders and sleeves.
""" A single field FE space with transient Dirichlet data (see Multifield below). """ struct TransientTrialFESpace space::SingleFieldFESpace dirichlet_t::Union{Function,Vector{<:Function}} Ud0::TrialFESpace function TransientTrialFESpace(space::SingleFieldFESpace,dirichlet_t::Union{Function,Vector{<:Function}}) Ud0 = HomogeneousTrialFESpace(space) new(space,dirichlet_t,Ud0) end end function TransientTrialFESpace(space::SingleFieldFESpace) HomogeneousTrialFESpace(space) end """ Time evaluation without allocating Dirichlet vals """ function evaluate!(Ut::TrialFESpace,U::TransientTrialFESpace,t::Real) if isa(U.dirichlet_t,Vector) objects_at_t = map( o->o(t), U.dirichlet_t) else objects_at_t = U.dirichlet_t(t) end TrialFESpace!(Ut,objects_at_t) Ut end """ Allocate the space to be used as first argument in evaluate! """ function allocate_trial_space(U::TransientTrialFESpace) HomogeneousTrialFESpace(U.space) end """ Time evaluation allocating Dirichlet vals """ function evaluate(U::TransientTrialFESpace,t::Real) Ut = allocate_trial_space(U) evaluate!(Ut,U,t) Ut end """ We can evaluate at `nothing` when we do not care about the Dirichlet vals """ function evaluate(U::TransientTrialFESpace,t::Nothing) U.Ud0 end evaluate(U::TrialFESpace,t::Nothing) = U """ Functor-like evaluation. It allocates Dirichlet vals in general. """ (U::TransientTrialFESpace)(t) = evaluate(U,t) (U::TrialFESpace)(t) = U (U::ZeroMeanFESpace)(t) = U # (U::Union{TrialFESpace,ZeroMeanFESpace})(t) = U """ Time derivative of the Dirichlet functions """ ∂t(U::TransientTrialFESpace) = TransientTrialFESpace(U.space,∂t.(U.dirichlet_t)) # ∂t(U::TrialFESpace) = TransientTrialFESpace(U.space,∂t.(U.dirichlet_t)) ∂t(U::SingleFieldFESpace) = HomogeneousTrialFESpace(U) ∂t(U::MultiFieldFESpace) = MultiFieldFESpace(∂t.(U.spaces)) ∂t(t::T) where T<:Number = zero(T) # Testing the interface function test_transient_trial_fe_space(Uh) UhX = evaluate(Uh,nothing) @test isa(UhX,FESpace) Uh0 = allocate_trial_space(Uh) Uh0 = evaluate!(Uh0,Uh,0.0) @test isa(Uh0,FESpace) Uh0 = evaluate(Uh,0.0) @test isa(Uh0,FESpace) Uh0 = Uh(0.0) @test isa(Uh0,FESpace) Uht=∂t(Uh) Uht0=Uht(0.0) @test isa(Uht0,FESpace) true end # Define the TransientTrialFESpace interface for stationary spaces function evaluate!(Ut::FESpace,U::FESpace,t::Real) U end function allocate_trial_space(U::FESpace) U end function evaluate(U::FESpace,t::Real) U end function evaluate(U::FESpace,t::Nothing) U end @static if VERSION >= v"1.3" (U::FESpace)(t) = U end # Define the interface for MultiField struct TransientMultiFieldTrialFESpace spaces::Vector end function TransientMultiFieldFESpace(spaces::Vector) TransientMultiFieldTrialFESpace(spaces) end function TransientMultiFieldFESpace(spaces::Vector{<:SingleFieldFESpace}) MultiFieldFESpace(spaces) end function evaluate!(Ut::MultiFieldFESpace,U::TransientMultiFieldTrialFESpace,t::Real) spaces_at_t = [evaluate!(Ut.spaces[i],U.spaces[i],t) for i in 1:length(U.spaces)] MultiFieldFESpace(spaces_at_t) end function allocate_trial_space(U::TransientMultiFieldTrialFESpace) spaces = allocate_trial_space.(U.spaces) MultiFieldFESpace(spaces) end function evaluate(U::TransientMultiFieldTrialFESpace,t::Real) Ut = allocate_trial_space(U) evaluate!(Ut,U,t) Ut end function evaluate(U::TransientMultiFieldTrialFESpace,t::Nothing) MultiFieldFESpace([evaluate(fesp,nothing) for fesp in U.spaces]) end (U::TransientMultiFieldTrialFESpace)(t) = evaluate(U,t) function ∂t(U::TransientMultiFieldTrialFESpace) spaces = ∂t.(U.spaces) TransientMultiFieldFESpace(spaces) end
import numpy as np from matplotlib import pyplot as plt def postprocess(image_path): ''' postprocessing of the prediction output Args image_path : path of the image Returns watershed_grayscale : numpy array of postprocessed image (in grayscale) ''' # Bring in the image img_original = cv2.imread(image_path) img = cv2.imread(image_path) # In case the input image has 3 channels (RGB), convert to 1 channel (grayscale) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Use threshold => Image will have values either 0 or 255 (black or white) ret, bin_image = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # Remove Hole or noise through the use of opening, closing in Morphology module kernel = np.ones((1, 1), np.uint8) kernel1 = np.ones((3, 3), np.uint8) # remove noise in closing = cv2.morphologyEx(bin_image, cv2.MORPH_CLOSE, kernel, iterations=1) # make clear distinction of the background # Incerease/emphasize the white region. sure_bg = cv2.dilate(closing, kernel1, iterations=1) # calculate the distance to the closest zero pixel for each pixel of the source. # Adjust the threshold value with respect to the maximum distance. Lower threshold, more information. dist_transform = cv2.distanceTransform(closing, cv2.DIST_L2, 5) ret, sure_fg = cv2.threshold(dist_transform, 0.2*dist_transform.max(), 255, 0) sure_fg = np.uint8(sure_fg) # Unknown is the region of background with foreground excluded. unknown = cv2.subtract(sure_bg, sure_fg) # labelling on the foreground. ret, markers = cv2.connectedComponents(sure_fg) markers_plus1 = markers + 1 markers_plus1[unknown == 255] = 0 # Appy watershed and label the borders markers_watershed = cv2.watershed(img, markers_plus1) # See the watershed result in a clear white page. img_x, img_y = img_original.shape[0], img_original.shape[1] # 512x512 white, white_color = np.zeros((img_x, img_y, 3)), np.zeros((img_x, img_y, 3)) white += 255 white_color += 255 # 1 in markers_watershed indicate the background value # label everything not indicated as background value white[markers_watershed != 1] = [0, 0, 0] # grayscale version white_color[markers_watershed != 1] = [255, 0, 0] # RGB version # Convert to numpy array for later processing white_np = np.asarray(white) # 512x512x3 watershed_grayscale = white_np.transpose(2, 0, 1)[0, :, :] # convert to 1 channel (grayscale) img[markers_watershed != 1] = [255, 0, 0] return watershed_grayscale ''' Visualizing all the intermediate processes images = [img_original, gray,bin_image, closing, sure_bg, dist_transform, sure_fg, unknown, markers, markers_watershed, white_color, white, img] titles = ['Original', '1. Grayscale','2. Binary','3. Closing','Sure BG','Distance','Sure FG','Unknown','Markers', 'Markers_Watershed','Result', 'Result gray','Result Overlapped'] CMAP = [None, 'gray', 'gray','gray','gray',None,'gray','gray',None, None, None, None,'gray'] for i in range(len(images)): plt.subplot(4,4,i+1),plt.imshow(images[i], cmap=CMAP[i]),plt.title(titles[i]),plt.xticks([]),plt.yticks([]) plt.show() ''' if __name__ == '__main__': from PIL import Image print(postprocess('../data/train/masks/25.png'))
Gilbert was mostly collaborative with Dahl 's work , as the writer declared : " He not only helped in script conferences , but had some good ideas and then left you alone , and when you produced the finished thing , he shot it . Other directors have such an ego that they want to rewrite it and put their own dialogue in , and it 's usually disastrous . What I admired so much about Lewis Gilbert was that he just took the screenplay and shot it . That 's the way to direct : You either trust your writer or you don 't . "
MONDAY, Nov. 2, 2009 (HealthDay News) -- The length of time a patient has to wait between lung cancer diagnosis and treatment is influenced by a number of health-care system factors, a new U.S. study finds. Researchers at the University of Texas Southwestern Medical Center analyzed data on 482 patients diagnosed with non-small cell lung cancer. They found that factors such as type of hospital (private or public), insurance coverage, age and race have a major impact on the time it takes for a patient diagnosed with lung cancer to receive treatment. For example, 59 percent of patients treated at a public hospital had advanced (stage 3) lung cancer, compared with 37 percent of patients treated at a private hospital. The researchers also found significant differences in patient populations at public and private hospitals in terms of age, race and socioeconomic status. "This study demonstrates that in a contemporary U.S. health-care system, intervals among suspicion, diagnosis and treatment vary widely and are predominately associated with system variables such as insurance and hospital type," said study author Dr. David E. Gerber. "An organized and timely approach to subsequent diagnostic and therapeutic measures may benefit these individuals and reduce this health-care disparity." The study appears in the November issue of the Journal of Thoracic Oncology.
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes ! This file was ported from Lean 3 source module data.nat.totient ! leanprover-community/mathlib commit 5cc2dfdd3e92f340411acea4427d701dc7ed26f8 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.CharP.Two import Mathlib.Data.Nat.Factorization.Basic import Mathlib.Data.Nat.Periodic import Mathlib.Data.ZMod.Basic import Mathlib.Tactic.Monotonicity /-! # Euler's totient function This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function) `Nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`. We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See `sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and `totient_prime_pow`. -/ open Finset open BigOperators namespace Nat /-- Euler's totient function. This counts the number of naturals strictly less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := ((range n).filter n.coprime).card #align nat.totient Nat.totient @[inherit_doc] scoped notation "φ" => Nat.totient @[simp] theorem totient_zero : φ 0 = 0 := rfl #align nat.totient_zero Nat.totient_zero @[simp] theorem totient_one : φ 1 = 1 := by simp [totient] #align nat.totient_one Nat.totient_one theorem totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter n.coprime).card := rfl #align nat.totient_eq_card_coprime Nat.totient_eq_card_coprime /-- A characterisation of `nat.totient` that avoids `finset`. -/ theorem totient_eq_card_lt_and_coprime (n : ℕ) : φ n = Nat.card { m | m < n ∧ n.coprime m } := by let e : { m | m < n ∧ n.coprime m } ≃ Finset.filter n.coprime (Finset.range n) := { toFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ invFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩ left_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta] right_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta] } rw [totient_eq_card_coprime, card_congr e, card_eq_fintype_card, Fintype.card_coe] #align nat.totient_eq_card_lt_and_coprime Nat.totient_eq_card_lt_and_coprime theorem totient_le (n : ℕ) : φ n ≤ n := ((range n).card_filter_le _).trans_eq (card_range n) #align nat.totient_le Nat.totient_le theorem totient_lt (n : ℕ) (hn : 1 < n) : φ n < n := (card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n) #align nat.totient_lt Nat.totient_lt theorem totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 => by decide | 1 => by simp [totient] | n + 2 => fun _ => card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 (by simp), coprime_one_right _⟩⟩ #align nat.totient_pos Nat.totient_pos theorem filter_coprime_Ico_eq_totient (a n : ℕ) : ((Ico n (n + a)).filter (coprime a)).card = totient a := by rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range] exact periodic_coprime a #align nat.filter_coprime_Ico_eq_totient Nat.filter_coprime_Ico_eq_totient theorem Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) : ((Ico k (k + n)).filter (coprime a)).card ≤ totient a * (n / a + 1) := by conv_lhs => rw [← Nat.mod_add_div n a] induction' n / a with i ih · rw [← filter_coprime_Ico_eq_totient a k] simp only [add_zero, mul_one, MulZeroClass.mul_zero, le_of_lt (mod_lt n a_pos), Nat.zero_eq, zero_add] --Porting note: below line was `mono` refine Finset.card_mono ?_ refine' monotone_filter_left a.coprime _ simp only [Finset.le_eq_subset] exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k) simp only [mul_succ] simp_rw [← add_assoc] at ih ⊢ calc (filter a.coprime (Ico k (k + n % a + a * i + a))).card = (filter a.coprime (Ico k (k + n % a + a * i) ∪ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card := by congr rw [Ico_union_Ico_eq_Ico] rw [add_assoc] exact le_self_add exact le_self_add _ ≤ (filter a.coprime (Ico k (k + n % a + a * i))).card + a.totient := by rw [filter_union, ← filter_coprime_Ico_eq_totient a (k + n % a + a * i)] apply card_union_le _ ≤ a.totient * i + a.totient + a.totient := add_le_add_right ih (totient a) #align nat.Ico_filter_coprime_le Nat.Ico_filter_coprime_le open ZMod /-- Note this takes an explicit `Fintype ((ZMod n)ˣ)` argument to avoid trouble with instance diamonds. -/ @[simp] theorem _root_.ZMod.card_units_eq_totient (n : ℕ) [NeZero n] [Fintype (ZMod n)ˣ] : Fintype.card (ZMod n)ˣ = φ n := calc Fintype.card (ZMod n)ˣ = Fintype.card { x : ZMod n // x.val.coprime n } := Fintype.card_congr ZMod.unitsEquivCoprime _ = φ n := by obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := exists_eq_succ_of_ne_zero NeZero.out simp only [totient, Finset.card_eq_sum_ones, Fintype.card_subtype, Finset.sum_filter, ← Fin.sum_univ_eq_sum_range, @Nat.coprime_comm (m + 1)] rfl #align zmod.card_units_eq_totient ZMod.card_units_eq_totient theorem totient_even {n : ℕ} (hn : 2 < n) : Even n.totient := by haveI : Fact (1 < n) := ⟨one_lt_two.trans hn⟩ haveI : NeZero n := NeZero.of_gt hn suffices 2 = orderOf (-1 : (ZMod n)ˣ) by rw [← ZMod.card_units_eq_totient, even_iff_two_dvd, this] exact orderOf_dvd_card_univ rw [← orderOf_units, Units.coe_neg_one, orderOf_neg_one, ringChar.eq (ZMod n) n, if_neg hn.ne'] #align nat.totient_even Nat.totient_even theorem totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n := if hmn0 : m * n = 0 then by cases' Nat.mul_eq_zero.1 hmn0 with h h <;> simp only [totient_zero, MulZeroClass.mul_zero, MulZeroClass.zero_mul, h] else by haveI : NeZero (m * n) := ⟨hmn0⟩ haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩ haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩ simp only [← ZMod.card_units_eq_totient] rw [Fintype.card_congr (Units.mapEquiv (ZMod.chineseRemainder h).toMulEquiv).toEquiv, Fintype.card_congr (@MulEquiv.prodUnits (ZMod m) (ZMod n) _ _).toEquiv, Fintype.card_prod] #align nat.totient_mul Nat.totient_mul /-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/ theorem totient_div_of_dvd {n d : ℕ} (hnd : d ∣ n) : φ (n / d) = (filter (fun k : ℕ => n.gcd k = d) (range n)).card := by rcases d.eq_zero_or_pos with (rfl | hd0); · simp [eq_zero_of_zero_dvd hnd] rcases hnd with ⟨x, rfl⟩ rw [Nat.mul_div_cancel_left x hd0] apply Finset.card_congr fun k _ => d * k · simp only [mem_filter, mem_range, and_imp, coprime] refine' fun a ha1 ha2 => ⟨(mul_lt_mul_left hd0).2 ha1, _⟩ rw [gcd_mul_left, ha2, mul_one] · simp [hd0.ne'] · simp only [mem_filter, mem_range, exists_prop, and_imp] refine' fun b hb1 hb2 => _ have : d ∣ b := by rw [← hb2] apply gcd_dvd_right rcases this with ⟨q, rfl⟩ refine' ⟨q, ⟨⟨(mul_lt_mul_left hd0).1 hb1, _⟩, rfl⟩⟩ rwa [gcd_mul_left, mul_right_eq_self_iff hd0] at hb2 #align nat.totient_div_of_dvd Nat.totient_div_of_dvd theorem sum_totient (n : ℕ) : n.divisors.sum φ = n := by rcases n.eq_zero_or_pos with (rfl | hn) · simp rw [← sum_div_divisors n φ] have : n = ∑ d : ℕ in n.divisors, (filter (fun k : ℕ => n.gcd k = d) (range n)).card := by nth_rw 1 [← card_range n] refine' card_eq_sum_card_fiberwise fun x _ => mem_divisors.2 ⟨_, hn.ne'⟩ apply gcd_dvd_left nth_rw 3 [this] exact sum_congr rfl fun x hx => totient_div_of_dvd (dvd_of_mem_divisors hx) #align nat.sum_totient Nat.sum_totient theorem sum_totient' (n : ℕ) : (∑ m in (range n.succ).filter (· ∣ n), φ m) = n := by convert sum_totient _ using 1 simp only [Nat.divisors, sum_filter, range_eq_Ico] rw [sum_eq_sum_Ico_succ_bot] <;> simp #align nat.sum_totient' Nat.sum_totient' /-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/ theorem totient_prime_pow_succ {p : ℕ} (hp : p.Prime) (n : ℕ) : φ (p ^ (n + 1)) = p ^ n * (p - 1) := calc φ (p ^ (n + 1)) = ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card := totient_eq_card_coprime _ _ = (range (p ^ (n + 1)) \ (range (p ^ n)).image (· * p)).card := (congr_arg card (by rw [sdiff_eq_filter] apply filter_congr simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos, mem_image, not_exists, hp.coprime_iff_not_dvd] intro a ha constructor · intro hap b h; rcases h with ⟨_, rfl⟩ exact hap (dvd_mul_left _ _) · rintro h ⟨b, rfl⟩ rw [pow_succ'] at ha exact h b ⟨lt_of_mul_lt_mul_left ha (zero_le _), mul_comm _ _⟩)) _ = _ := by have h1 : Function.Injective (· * p) := mul_left_injective₀ hp.ne_zero have h2 : (range (p ^ n)).image (· * p) ⊆ range (p ^ (n + 1)) := fun a => by simp only [mem_image, mem_range, exists_imp] rintro b ⟨h, rfl⟩ rw [pow_succ] exact (mul_lt_mul_right hp.pos).2 h rw [card_sdiff h2, card_image_of_injOn (h1.injOn _), card_range, card_range, ← one_mul (p ^ n), pow_succ', ← tsub_mul, one_mul, mul_comm] #align nat.totient_prime_pow_succ Nat.totient_prime_pow_succ /-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/ theorem totient_prime_pow {p : ℕ} (hp : p.Prime) {n : ℕ} (hn : 0 < n) : φ (p ^ n) = p ^ (n - 1) * (p - 1) := by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩ exact totient_prime_pow_succ hp _ #align nat.totient_prime_pow Nat.totient_prime_pow theorem totient_prime {p : ℕ} (hp : p.Prime) : φ p = p - 1 := by rw [← pow_one p, totient_prime_pow hp] <;> simp #align nat.totient_prime Nat.totient_prime theorem totient_eq_iff_prime {p : ℕ} (hp : 0 < p) : p.totient = p - 1 ↔ p.Prime := by refine' ⟨fun h => _, totient_prime⟩ replace hp : 1 < p · apply lt_of_le_of_ne · rwa [succ_le_iff] · rintro rfl rw [totient_one, tsub_self] at h exact one_ne_zero h rw [totient_eq_card_coprime, range_eq_Ico, ← Ico_insert_succ_left hp.le, Finset.filter_insert, if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ← Nat.card_Ico 1 p] at h refine' p.prime_of_coprime hp fun n hn hnz => Finset.filter_card_eq h n <| Finset.mem_Ico.mpr ⟨_, hn⟩ rwa [succ_le_iff, pos_iff_ne_zero] #align nat.totient_eq_iff_prime Nat.totient_eq_iff_prime theorem card_units_zMod_lt_sub_one {p : ℕ} (hp : 1 < p) [Fintype (ZMod p)ˣ] : Fintype.card (ZMod p)ˣ ≤ p - 1 := by haveI : NeZero p := ⟨(pos_of_gt hp).ne'⟩ rw [ZMod.card_units_eq_totient p] exact Nat.le_pred_of_lt (Nat.totient_lt p hp) #align nat.card_units_zmod_lt_sub_one Nat.card_units_zMod_lt_sub_one theorem prime_iff_card_units (p : ℕ) [Fintype (ZMod p)ˣ] : p.Prime ↔ Fintype.card (ZMod p)ˣ = p - 1 := by cases' eq_zero_or_neZero p with hp hp · subst hp simp only [ZMod, not_prime_zero, false_iff_iff, zero_tsub] -- the substI created an non-defeq but subsingleton instance diamond; resolve it suffices Fintype.card ℤˣ ≠ 0 by convert this simp rw [ZMod.card_units_eq_totient, Nat.totient_eq_iff_prime <| NeZero.pos p] #align nat.prime_iff_card_units Nat.prime_iff_card_units @[simp] theorem totient_two : φ 2 = 1 := (totient_prime prime_two).trans rfl #align nat.totient_two Nat.totient_two theorem totient_eq_one_iff : ∀ {n : ℕ}, n.totient = 1 ↔ n = 1 ∨ n = 2 | 0 => by simp | 1 => by simp | 2 => by simp | n + 3 => by have : 3 ≤ n + 3 := le_add_self simp only [succ_succ_ne_one, false_or_iff] exact ⟨fun h => not_even_one.elim <| h ▸ totient_even this, by rintro ⟨⟩⟩ #align nat.totient_eq_one_iff Nat.totient_eq_one_iff /-! ### Euler's product formula for the totient function We prove several different statements of this formula. -/ /-- Euler's product formula for the totient function. -/ theorem totient_eq_prod_factorization {n : ℕ} (hn : n ≠ 0) : φ n = n.factorization.prod fun p k => p ^ (k - 1) * (p - 1) := by rw [multiplicative_factorization φ (@totient_mul) totient_one hn] apply Finsupp.prod_congr _ intro p hp have h := zero_lt_iff.mpr (Finsupp.mem_support_iff.mp hp) rw [totient_prime_pow (prime_of_mem_factorization hp) h] #align nat.totient_eq_prod_factorization Nat.totient_eq_prod_factorization /-- Euler's product formula for the totient function. -/ theorem totient_mul_prod_factors (n : ℕ) : (φ n * ∏ p in n.factors.toFinset, p) = n * ∏ p in n.factors.toFinset, (p - 1) := by by_cases hn : n = 0; · simp [hn] rw [totient_eq_prod_factorization hn] nth_rw 3 [← factorization_prod_pow_eq_self hn] simp only [← prod_factorization_eq_prod_factors, ← Finsupp.prod_mul] refine' Finsupp.prod_congr (M := ℕ) (N := ℕ) fun p hp => _ rw [Finsupp.mem_support_iff, ← zero_lt_iff] at hp rw [mul_comm, ← mul_assoc, ← pow_succ', Nat.sub_one, Nat.succ_pred_eq_of_pos hp] #align nat.totient_mul_prod_factors Nat.totient_mul_prod_factors /-- Euler's product formula for the totient function. -/ theorem totient_eq_div_factors_mul (n : ℕ) : φ n = (n / ∏ p in n.factors.toFinset, p) * ∏ p in n.factors.toFinset, (p - 1) := by rw [← mul_div_left n.totient, totient_mul_prod_factors, mul_comm, Nat.mul_div_assoc _ (prod_prime_factors_dvd n), mul_comm] have := prod_pos (fun p => pos_of_mem_factorization (n := n)) simpa [prod_factorization_eq_prod_factors] using this #align nat.totient_eq_div_factors_mul Nat.totient_eq_div_factors_mul /-- Euler's product formula for the totient function. -/ theorem totient_eq_mul_prod_factors (n : ℕ) : (φ n : ℚ) = n * ∏ p in n.factors.toFinset, (1 - (p : ℚ)⁻¹) := by by_cases hn : n = 0 · simp [hn] have hn' : (n : ℚ) ≠ 0 := by simp [hn] have hpQ : (∏ p in n.factors.toFinset, (p : ℚ)) ≠ 0 := by rw [← cast_prod, cast_ne_zero, ← zero_lt_iff, ← prod_factorization_eq_prod_factors] exact prod_pos fun p hp => pos_of_mem_factorization hp simp only [totient_eq_div_factors_mul n, prod_prime_factors_dvd n, cast_mul, cast_prod, cast_div_charZero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ← prod_mul_distrib] refine' prod_congr rfl fun p hp => _ have hp := pos_of_mem_factors (List.mem_toFinset.mp hp) have hp' : (p : ℚ) ≠ 0 := cast_ne_zero.mpr hp.ne.symm rw [sub_mul, one_mul, mul_comm, mul_inv_cancel hp', cast_pred hp] #align nat.totient_eq_mul_prod_factors Nat.totient_eq_mul_prod_factors theorem totient_gcd_mul_totient_mul (a b : ℕ) : φ (a.gcd b) * φ (a * b) = φ a * φ b * a.gcd b := by have shuffle : ∀ a1 a2 b1 b2 c1 c2 : ℕ, b1 ∣ a1 → b2 ∣ a2 → a1 / b1 * c1 * (a2 / b2 * c2) = a1 * a2 / (b1 * b2) * (c1 * c2) := by intro a1 a2 b1 b2 c1 c2 h1 h2 calc a1 / b1 * c1 * (a2 / b2 * c2) = a1 / b1 * (a2 / b2) * (c1 * c2) := by apply mul_mul_mul_comm _ = a1 * a2 / (b1 * b2) * (c1 * c2) := by congr 1 exact div_mul_div_comm h1 h2 simp only [totient_eq_div_factors_mul] rw [shuffle, shuffle] rotate_left repeat' apply prod_prime_factors_dvd · simp only [prod_factors_gcd_mul_prod_factors_mul] rw [eq_comm, mul_comm, ← mul_assoc, ← Nat.mul_div_assoc] exact mul_dvd_mul (prod_prime_factors_dvd a) (prod_prime_factors_dvd b) #align nat.totient_gcd_mul_totient_mul Nat.totient_gcd_mul_totient_mul theorem totient_super_multiplicative (a b : ℕ) : φ a * φ b ≤ φ (a * b) := by let d := a.gcd b rcases(zero_le a).eq_or_lt with (rfl | ha0) · simp have hd0 : 0 < d := Nat.gcd_pos_of_pos_left _ ha0 apply le_of_mul_le_mul_right _ hd0 rw [← totient_gcd_mul_totient_mul a b, mul_comm] apply mul_le_mul_left' (Nat.totient_le d) #align nat.totient_super_multiplicative Nat.totient_super_multiplicative theorem totient_dvd_of_dvd {a b : ℕ} (h : a ∣ b) : φ a ∣ φ b := by rcases eq_or_ne a 0 with (rfl | ha0) · simp [zero_dvd_iff.1 h] rcases eq_or_ne b 0 with (rfl | hb0) · simp have hab' : a.factorization.support ⊆ b.factorization.support := by intro p simp only [support_factorization, List.mem_toFinset] apply factors_subset_of_dvd h hb0 rw [totient_eq_prod_factorization ha0, totient_eq_prod_factorization hb0] refine' Finsupp.prod_dvd_prod_of_subset_of_dvd hab' fun p _ => mul_dvd_mul _ dvd_rfl exact pow_dvd_pow p (tsub_le_tsub_right ((factorization_le_iff_dvd ha0 hb0).2 h p) 1) #align nat.totient_dvd_of_dvd Nat.totient_dvd_of_dvd theorem totient_mul_of_prime_of_dvd {p n : ℕ} (hp : p.Prime) (h : p ∣ n) : (p * n).totient = p * n.totient := by have h1 := totient_gcd_mul_totient_mul p n rw [gcd_eq_left h, mul_assoc] at h1 simpa [(totient_pos hp.pos).ne', mul_comm] using h1 #align nat.totient_mul_of_prime_of_dvd Nat.totient_mul_of_prime_of_dvd theorem totient_mul_of_prime_of_not_dvd {p n : ℕ} (hp : p.Prime) (h : ¬p ∣ n) : (p * n).totient = (p - 1) * n.totient := by rw [totient_mul _, totient_prime hp] simpa [h] using coprime_or_dvd_of_prime hp n #align nat.totient_mul_of_prime_of_not_dvd Nat.totient_mul_of_prime_of_not_dvd end Nat
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison ! This file was ported from Lean 3 source module tactic.converter.apply_congr ! leanprover-community/mathlib commit 3d7987cda72abc473c7cdbbb075170e9ac620042 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Tactic.Interactive import Mathbin.Tactic.Converter.Interactive /-! ## Introduce the `apply_congr` conv mode tactic. `apply_congr` will apply congruence lemmas inside `conv` mode. It is particularly useful when the automatically generated congruence lemmas are not of the optimal shape. An example, described in the doc-string is rewriting inside the operand of a `finset.sum`. -/ open Tactic namespace Conv.Interactive open Interactive Interactive.Types Lean.Parser -- mathport name: parser.optional local postfix:1024 "?" => optional /-- Apply a congruence lemma inside `conv` mode. When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`. Otherwise `apply_congr e` will apply the lemma `e`. Recall that a goal that appears as `∣ X` in `conv` mode represents a goal of `⊢ X = ?m`, i.e. an equation with a metavariable for the right hand side. To successfully use `apply_congr e`, `e` will need to be an equation (possibly after function arguments), which can be unified with a goal of the form `X = ?m`. The right hand side of `e` will then determine the metavariable, and `conv` will subsequently replace `X` with that right hand side. As usual, `apply_congr` can create new goals; any of these which are _not_ equations with a metavariable on the right hand side will be hard to deal with in `conv` mode. Thus `apply_congr` automatically calls `intros` on any new goals, and fails if they are not then equations. In particular it is useful for rewriting inside the operand of a `finset.sum`, as it provides an extra hypothesis asserting we are inside the domain. For example: ```lean example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { -- If we just call `congr` here, in the second goal we're helpless, -- because we are only given the opportunity to rewrite `f`. -- However `apply_congr` uses the appropriate `@[congr]` lemma, -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis. apply_congr, skip, simp [h, H], } end ``` In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S` which is then used to rewrite the `f x` to `g x`. -/ unsafe def apply_congr (q : parse texpr ?) : conv Unit := do let congr_lemmas ← match q with |-- If the user specified a lemma, use that one, some e => do let gs ← get_goals let e ← to_expr e -- to_expr messes with the goals? (see tests) set_goals gs return [e] |-- otherwise, look up everything tagged `@[congr]` none => do let congr_lemma_names ← attribute.get_instances `congr congr_lemma_names mk_const -- For every lemma: congr_lemmas fun n => -- Call tactic.eapply seq' (tactic.eapply n >> tactic.skip) (-- and then call `intros` on each resulting goal, and require that afterwards it's an equation. tactic.intros >> do let q(_ = _) ← target tactic.skip) #align conv.interactive.apply_congr conv.interactive.apply_congr add_tactic_doc { Name := "apply_congr" category := DocCategory.tactic declNames := [`conv.interactive.apply_congr] tags := ["conv", "congruence", "rewriting"] } end Conv.Interactive
module tensor_nmode implicit none contains function n_mode(mode, gdim, newsize, core, spp) result(tenprod) integer, intent(in) :: mode integer, intent(in) :: newsize integer, dimension(:), intent(in) :: gdim real, dimension(:), intent(in) :: spp real, dimension(product(gdim)), intent(in) :: core real, dimension(newsize) :: tenprod integer, dimension(2) :: newshape if (gdim(mode) == 0) then tenprod = dot_product(core, spp) else newshape = (/newsize, gdim(mode)/) tenprod = matmul(reshape(core, newshape), spp) end if end function n_mode end module tensor_nmode
#!/usr/bin/env Rscript # this script converts a Connecticut model to the Hartford version # and sets it up ready for parameter estimation library(tidyverse) library(CoRC) # read experimental data datafile = "CT-Hartford-COVID19.tsv" data_experimental <- read_tsv(datafile) # serial number of the day of this iteration, in the last row of data file today <- as.double( data_experimental$'#day'[NROW(data_experimental)]) # which models to process modelnos <- c(7,11,14) pathto <- getwd() # deal with each model for (modelno in modelnos) { #get model modelfname <- sprintf("../SIDARTHE-CT_Model%d.cps",modelno) newmodelfname <- sprintf("SIDARTHE-CT-Hartford_Model%d-%d.cps",modelno,today) loadModel(modelfname) # change the name mname <- sprintf("SIDARTHE Hartford Model %d",modelno) setModelName(mname) # change the total population setGlobalQuantities("Population", initial_value = 894014) # add species UCH newSpecies("UCH", type = "reactions", initial_concentration = 0) # set I and A back to zero setSpecies("I", initial_concentration = 0) setSpecies("A", initial_concentration = 0) # update the conservation relation cons <- paste0(getSpecies("S")$initial_expression,"-{[UCH]_0}") setSpecies("S", initial_expression = cons) # add rate constant for progression to UCH newGlobalQuantity("mu_UCH", type = "fixed", initial_value = getValue(quantity_strict("mu", reference="InitialValue")) ) # add new quantity for total hospitalized th1 = species_strict("T",reference = "Concentration") th2 = species_strict("UCH", reference = "Concentration") th = paste(th1,th2,sep="+") newGlobalQuantity("Total_Hospitalized", type = "assignment", expression = th ) # add global quantity for zero day newGlobalQuantity("ZeroDay", type = "fixed", initial_value = 0.1 ) muuchval <- quantity_strict("mu_UCH", reference = "Value") # add reactions for UCH newReaction("A -> UCH", name = "critical_A_UCH", fun = "Mass action (irreversible)", mappings = list(k1 = "mu_UCH" ) ) newReaction("R -> UCH", name = "critical_R_UCH", fun = "Mass action (irreversible)", mappings = list(k1 = "mu_UCH" ) ) newReaction("UCH -> E", name = "death_UCH", fun = "Mass action (irreversible)", mappings = list(k1 = "tau" ) ) newReaction("UCH -> H", name = "healing_UCH", fun = "Mass action (irreversible)", mappings = list(k1 = "sigma" ) ) # add new event for introduction of infected newEvent("Seeding", trigger_expression = "{Time}>{Values[ZeroDay]}", assignment_target = c("I"), assignment_expression = c("1")) # setup parameter estimation clearParameterEstimationParameters() clearExperiments() data_pe <- data_experimental %>% rename("time" = "#day") %>% set_tidy_names(TRUE) types = c("time", "dependent", "dependent", "dependent", "ignore", "dependent", "ignore") mappings = c( "{Time}", "{Values[Diagnosed Cumulative infected]}", "{Values[Total_Hospitalized]}", "{[UCH]}", NA, "{[E]}", NA) data_pe <- data_pe[, types != "ignore"] mappings <- mappings[types != "ignore"] types <- types[types != "ignore"] outputdatafile <- sprintf("CT-Hartford-COVID19-%d-%d.tsv",modelno,today) # define the experiment with the Hartford data set fit_experiments <- defineExperiments( experiment_type = "time_course", data = data_pe, type = types, mapping = mappings, weight_method = "mean_square", filename = outputdatafile ) # define the parameters to fit p1 <- defineParameterEstimationParameter(quantity_strict("ZeroDay", "InitialValue"), start_value = 1, lower_bound = 0, upper_bound = 15) p2 <-defineParameterEstimationParameter(quantity_strict("mu_UCH", "InitialValue"), start_value = getGlobalQuantities("mu_UCH")$initial_value, lower_bound = 1e-6, upper_bound = getGlobalQuantities("mu")$initial_value) val = getGlobalQuantities("day8x")$initial_value p3 <- defineParameterEstimationParameter(quantity_strict("day8x", "InitialValue"), start_value = val, lower_bound = val*0.7, upper_bound = 1) val = getGlobalQuantities("day15")$initial_value #up = quantity_strict("day8x", reference = "Value") up = getGlobalQuantities("day8x")$initial_value p4 <- defineParameterEstimationParameter(quantity_strict("day15x", "InitialValue"), start_value = val, lower_bound = val*0.7, upper_bound = up) val = getGlobalQuantities("tau")$initial_value p5 <- defineParameterEstimationParameter(quantity_strict("tau", "InitialValue"), start_value = val, lower_bound = val*0.7, upper_bound = val*1.3) val = getGlobalQuantities("theta")$initial_value p6 <- defineParameterEstimationParameter(quantity_strict("theta", "InitialValue"), start_value = val, lower_bound = val*0.7, upper_bound = val*1.3) val = getGlobalQuantities("f_epsilon")$initial_value p7 <- defineParameterEstimationParameter(quantity_strict("f_epsilon", "InitialValue"), start_value = val, lower_bound = val*0.7, upper_bound = val*1.3) setPE(parameters = list(p1,p2,p3,p4,p5,p6,p7), experiments = list(fit_experiments)) saveModel(newmodelfname) unloadModel() }
import Lean.Hygiene def otherInhabited : Inhabited Nat := ⟨42⟩ def f := Id.run do let ⟨n⟩ ← pure otherInhabited -- do-notation expands to `pure otherInhabited >>= fun x : Inhabited Nat => ...` -- the `x : Inhabited Nat` should not be available for TC synth (i.e., `default` should be 0) return default + n example : f = 42 := rfl open Lean def g : Syntax := let rec stx : Syntax := Unhygienic.run `(f 0 1) let stx := stx match stx with | `(f $_args*) => ‹Syntax› -- should not resolve to tmp var created by stx matcher | _ => default example : g = g.stx := rfl
Require Import Ensembles List Coq.Lists.SetoidList Program Common Computation.Core ADTNotation.BuildADTSig ADTNotation.BuildADT GeneralBuildADTRefinements QueryQSSpecs QueryStructure SetEq Omega String Arith. Unset Implicit Arguments. Ltac generalize_all := repeat match goal with [ H : _ |- _ ] => generalize H; clear H end. Section AdditionalDefinitions. Open Scope list_scope. End AdditionalDefinitions. Section AdditionalNatLemmas. Lemma le_r_le_max : forall x y z, x <= z -> x <= max y z. Proof. intros x y z; destruct (Max.max_spec y z) as [ (comp, eq) | (comp, eq) ]; rewrite eq; omega. Qed. Lemma le_l_le_max : forall x y z, x <= y -> x <= max y z. Proof. intros x y z. rewrite Max.max_comm. apply le_r_le_max. Qed. Lemma le_neq_impl : forall m n, m < n -> m <> n. Proof. intros; omega. Qed. Lemma gt_neq_impl : forall m n, m > n -> m <> n. Proof. intros; omega. Qed. Lemma lt_refl_False : forall x, lt x x -> False. Proof. intros; omega. Qed. Lemma beq_nat_eq_nat_dec : forall x y, beq_nat x y = if eq_nat_dec x y then true else false. Proof. intros; destruct (eq_nat_dec _ _); [ apply beq_nat_true_iff | apply beq_nat_false_iff ]; assumption. Qed. End AdditionalNatLemmas. Section AdditionalLogicLemmas. Lemma or_false : forall (P: Prop), P \/ False <-> P. Proof. tauto. Qed. Lemma false_or : forall (P Q: Prop), (False <-> P \/ Q) <-> (False <-> P) /\ (False <-> Q). Proof. tauto. Qed. Lemma false_or' : forall (P Q: Prop), (P \/ Q <-> False) <-> (False <-> P) /\ (False <-> Q). Proof. tauto. Qed. Lemma equiv_false : forall P, (False <-> P) <-> (~ P). Proof. tauto. Qed. Lemma equiv_false' : forall P, (P <-> False) <-> (~ P). Proof. tauto. Qed. Lemma and_True : forall P, (P /\ True) <-> P. Proof. tauto. Qed. Lemma not_exists_forall : forall {A} (P: A -> Prop), (~ (exists a, P a)) <-> (forall a, ~ P a). Proof. firstorder. Qed. Lemma not_and_implication : forall (P Q: Prop), ( ~ (P /\ Q) ) <-> (P -> ~ Q). Proof. firstorder. Qed. Lemma eq_sym_iff : forall {A} x y, @eq A x y <-> @eq A y x. Proof. split; intros; symmetry; assumption. Qed. End AdditionalLogicLemmas. Section AdditionalBoolLemmas. Lemma collapse_ifs_dec : forall P (b: {P} + {~P}), (if (if b then true else false) then true else false) = (if b then true else false). Proof. destruct b; reflexivity. Qed. Lemma collapse_ifs_bool : forall (b: bool), (if (if b then true else false) then true else false) = (if b then true else false). Proof. destruct b; reflexivity. Qed. Lemma string_dec_bool_true_iff : forall s1 s2, (if string_dec s1 s2 then true else false) = true <-> s1 = s2. Proof. intros s1 s2; destruct (string_dec s1 s2); simpl; intuition. Qed. Lemma eq_nat_dec_bool_true_iff : forall n1 n2, (if eq_nat_dec n1 n2 then true else false) = true <-> n1 = n2. Proof. intros n1 n2; destruct (eq_nat_dec n1 n2); simpl; intuition. Qed. Lemma eq_N_dec_bool_true_iff : forall n1 n2 : N, (if N.eq_dec n1 n2 then true else false) = true <-> n1 = n2. Proof. intros; destruct (N.eq_dec _ _); intuition. Qed. Lemma eq_Z_dec_bool_true_iff : forall n1 n2 : Z, (if Z.eq_dec n1 n2 then true else false) = true <-> n1 = n2. Proof. intros; destruct (Z.eq_dec _ _); intuition. Qed. Lemma bool_equiv_true: forall (f g: bool), (f = true <-> g = true) <-> (f = g). Proof. intros f g; destruct f, g; intuition. Qed. Lemma if_negb : forall {A} (b: bool) (x y: A), (if negb b then x else y) = (if b then y else x). Proof. intros; destruct b; simpl; reflexivity. Qed. End AdditionalBoolLemmas. Section AdditionalEnsembleLemmas. Lemma weaken : forall {A: Type} ensemble condition, forall (x: A), Ensembles.In _ (fun x => Ensembles.In _ ensemble x /\ condition x) x -> Ensembles.In _ ensemble x. Proof. unfold Ensembles.In; intros; intuition. Qed. End AdditionalEnsembleLemmas. Section AdditionalListLemmas. Lemma map_id : forall {A: Type} (seq: list A), (map (fun x => x) seq) = seq. Proof. intros A seq; induction seq; simpl; congruence. Qed. Lemma app_singleton : forall {A} (x: A) s, [x] ++ s = x :: s. Proof. reflexivity. Qed. Lemma app_eq_nil_iff : forall {A} s1 s2, @nil A = s1 ++ s2 <-> ([] = s1 /\ [] = s2). Proof. intros; split; intro H. - symmetry in H; apply app_eq_nil in H; intuition. - intuition; subst; intuition. Qed. Lemma singleton_neq_nil : forall {A} (a: A), [a] = [] <-> False. Proof. intuition discriminate. Qed. Lemma in_nil_iff : forall {A} (item: A), List.In item [] <-> False. Proof. intuition. Qed. Lemma in_not_nil : forall {A} x seq, @List.In A x seq -> seq <> nil. Proof. intros A x seq in_seq eq_nil. apply (@in_nil _ x). subst seq; assumption. Qed. Lemma in_seq_false_nil_iff : forall {A} (seq: list A), (forall (item: A), (List.In item seq <-> False)) <-> (seq = []). Proof. intros. destruct seq; simpl in *; try tauto. split; intro H. exfalso; specialize (H a); rewrite <- H; eauto. discriminate. Qed. Lemma filter_comm : forall {A: Type} (pred1 pred2: A -> bool), forall (seq: list A), List.filter pred1 (List.filter pred2 seq) = List.filter pred2 (List.filter pred1 seq). Proof. intros A pred1 pred2 seq; induction seq as [ | hd tl]; [ simpl | destruct (pred1 hd) eqn:eq1; destruct (pred2 hd) eqn:eq2; repeat progress (simpl; try rewrite eq1; try rewrite eq2) ]; congruence. Qed. Lemma InA_In: forall (A : Type) (x : A) (l : list A), InA eq x l -> List.In x l. Proof. intros ? ? ? H; induction H; simpl; intuition. Qed. Lemma not_InA_not_In : forall {A: Type} l eqA (x: A), Equivalence eqA -> not (InA eqA x l) -> not (List.In x l). Proof. intros A l; induction l; intros ? ? equiv not_inA in_l; simpl in *; [ trivial | destruct in_l as [eq | in_l]; subst; apply not_inA; pose proof equiv as (?,?,?); eauto using InA_cons_hd, InA_cons_tl, (In_InA equiv) ]. Qed. Lemma NoDupFilter {A} : forall (f : A -> bool) (l : list A), NoDup l -> NoDup (filter f l). Proof. induction l; simpl; intros; eauto. inversion H; subst; find_if_inside; try constructor; eauto. unfold not; intros H'; apply H2; revert H'; clear; induction l; simpl; eauto; find_if_inside; simpl; intuition. Qed. Lemma NoDupA_stronger_than_NoDup : forall {A: Type} (seq: list A) eqA, Equivalence eqA -> NoDupA eqA seq -> NoDup seq. Proof. intros ? ? ? ? nodupA; induction nodupA; constructor ; [ apply (not_InA_not_In _ _ _ _ H0) | trivial]. (* Alternative proof: red; intros; apply (In_InA (eqA:=eqA)) in H2; intuition. *) Qed. Definition ExtensionalEq {A B} f g := forall (a: A), @eq B (f a) (g a). Lemma filter_by_equiv : forall {A} f g, ExtensionalEq f g -> forall seq, @List.filter A f seq = @List.filter A g seq. Proof. intros A f g obs seq; unfold ExtensionalEq in obs; induction seq; simpl; try rewrite obs; try rewrite IHseq; trivial. Qed. Lemma filter_by_equiv_meta : forall {A B : Type} (f g : A -> B -> bool), (forall (a: A), ExtensionalEq (f a) (g a)) -> (forall (a: A) (seq : list B), filter (f a) seq = filter (g a) seq). Proof. intros * equiv *; rewrite (filter_by_equiv _ _ (equiv _)); reflexivity. Qed. Lemma filter_and : forall {A} pred1 pred2, forall (seq: list A), List.filter (fun x => andb (pred1 x) (pred2 x)) seq = List.filter pred1 (List.filter pred2 seq). Proof. intros; induction seq; simpl; [ | destruct (pred1 a) eqn:eq1; destruct (pred2 a) eqn:eq2]; simpl; try rewrite eq1; try rewrite eq2; trivial; f_equal; trivial. Qed. Lemma filter_and' : forall {A} pred1 pred2, forall (seq: list A), List.filter (fun x => andb (pred1 x) (pred2 x)) seq = List.filter pred2 (List.filter pred1 seq). Proof. intros; induction seq; simpl; [ | destruct (pred1 a) eqn:eq1; destruct (pred2 a) eqn:eq2]; simpl; try rewrite eq1; try rewrite eq2; trivial; f_equal; trivial. Qed. Definition flatten {A} seq := List.fold_right (@app A) [] seq. Lemma flat_map_flatten : forall {A B: Type}, forall comp seq, @flat_map A B comp seq = flatten (map comp seq). Proof. intros; induction seq; simpl; try rewrite IHseq; reflexivity. Qed. Lemma in_flatten_iff : forall {A} x seqs, @List.In A x (flatten seqs) <-> exists seq, List.In x seq /\ List.In seq seqs. Proof. intros; unfold flatten. induction seqs; simpl. firstorder. rewrite in_app_iff. rewrite IHseqs. split. intros [ in_head | [seq (in_seqs & in_seq) ] ]; eauto. intros [ seq ( in_seq & [ eq_head | in_seqs ] ) ]; subst; eauto. Qed. Lemma flatten_filter : forall {A} (seq: list (list A)) pred, List.filter pred (flatten seq) = flatten (List.map (List.filter pred) seq). Proof. intros; induction seq; trivial. unfold flatten; simpl. induction a; trivial. simpl; destruct (pred a); simpl; rewrite IHa; trivial. Qed. Lemma map_flatten : forall {B C} (f: B -> C) (xs: list (list B)), map f (flatten xs) = flatten (map (fun x => map f x) xs). Proof. induction xs; simpl; [ | rewrite map_app, IHxs ]; reflexivity. Qed. Lemma map_flat_map : forall {A B C} (f: B -> C) (g: A -> list B) (xs: list A), map f (flat_map g xs) = flat_map (fun x : A => map f (g x)) xs. Proof. intros; rewrite flat_map_flatten, map_flatten, map_map, <- flat_map_flatten; reflexivity. Qed. Lemma map_map : forall { A B C } (f: A -> B) (g: B -> C), forall seq, List.map g (List.map f seq) = List.map (fun x => g (f x)) seq. Proof. intros; induction seq; simpl; f_equal; trivial. Qed. Lemma filter_all_true : forall {A} pred (seq: list A), (forall x, List.In x seq -> pred x = true) -> List.filter pred seq = seq. Proof. induction seq as [ | head tail IH ]; simpl; trivial. intros all_true. rewrite all_true by eauto. f_equal; intuition. Qed. Lemma filter_all_false : forall {A} seq pred, (forall item : A, List.In item seq -> pred item = false) -> List.filter pred seq = []. Proof. intros A seq pred all_false; induction seq as [ | head tail IH ]; simpl; trivial. rewrite (all_false head) by (simpl; eauto). intuition. Qed. Lemma map_filter_all_false : forall {A} pred seq, (forall subseq, List.In subseq seq -> forall (item: A), List.In item subseq -> pred item = false) -> (List.map (List.filter pred) seq) = (List.map (fun x => []) seq). Proof. intros A pred seq all_false; induction seq as [ | subseq subseqs IH ] ; simpl; trivial. f_equal. specialize (all_false subseq (or_introl eq_refl)). apply filter_all_false; assumption. apply IH; firstorder. Qed. Lemma foldright_compose : forall {TInf TOutf TAcc} (g : TOutf -> TAcc -> TAcc) (f : TInf -> TOutf) (seq : list TInf) (init : TAcc), List.fold_right (compose g f) init seq = List.fold_right g init (List.map f seq). Proof. intros; induction seq; simpl; [ | rewrite IHseq ]; reflexivity. Qed. Lemma flatten_nils : forall {A} (seq: list (list A)), flatten (List.map (fun _ => []) seq) = @nil A. Proof. induction seq; intuition. Qed. Lemma flatten_app : forall {A} (seq1 seq2: list (list A)), flatten (seq1 ++ seq2) = flatten seq1 ++ flatten seq2. Proof. unfold flatten; induction seq1; simpl; trivial. intros; rewrite IHseq1; rewrite app_assoc; trivial. Qed. Lemma flatten_head : forall {A} head tail, @flatten A (head :: tail) = head ++ flatten tail. Proof. intuition. Qed. Require Import Permutation. Lemma flat_map_rev_permutation : forall {A B} seq (f: A -> list B), Permutation (flat_map f seq) (flat_map f (rev seq)). Proof. induction seq; simpl; intros. - reflexivity. - rewrite !flat_map_flatten, map_app. rewrite flatten_app, <- !flat_map_flatten. simpl; rewrite app_nil_r. rewrite Permutation_app_comm. apply Permutation_app; eauto. Qed. Lemma length_flatten_aux : forall {A} seq, forall n, n + List.length (flatten seq) = List.fold_right (compose plus (@List.length A)) n seq. Proof. induction seq; simpl; intros. - auto with arith. - unfold compose; rewrite app_length, <- IHseq; omega. Qed. Lemma length_flatten : forall {A} seq, List.length (flatten seq) = List.fold_right (compose plus (@List.length A)) 0 seq. Proof. intros. pose proof (length_flatten_aux seq 0) as H; simpl in H; eauto. Qed. Lemma in_map_unproject : forall {A B} projection seq, forall item, @List.In A item seq -> @List.In B (projection item) (List.map projection seq). Proof. intros ? ? ? seq; induction seq; simpl; intros item in_seq. trivial. destruct in_seq; [ left; f_equal | right ]; intuition. Qed. Lemma refold_map : forall {A B} (f: A -> B) x seq, f x :: map f seq = map f (x :: seq). Proof. simpl; reflexivity. Qed. Lemma refold_in : forall {A} a b l, @List.In A a (b :: l) <-> List.In a l \/ a = b. Proof. intros; simpl; intuition. Qed. Lemma app_map_inv : forall {A B} seq l1 l2 (f: A -> B), l1 ++ l2 = map f seq -> exists l1' l2', seq = l1' ++ l2' /\ l1 = map f l1' /\ l2 = map f l2'. Proof. induction seq; simpl; intros. exists (@nil A) (@nil A); simpl. apply app_eq_nil in H; intuition. destruct l1. rewrite app_nil_l in H. exists (@nil A) (a :: seq); simpl; intuition. rewrite <- app_comm_cons in H. inversion H. specialize (IHseq _ _ _ H2). destruct IHseq as [l1' [l2' (seq_eq_app & l1l1' & l2l2') ] ]. exists (a :: l1') (l2'); subst; intuition. Qed. Lemma cons_map_inv : forall {A B} seq x1 l2 (f: A -> B), x1 :: l2 = map f seq -> exists x1' l2', seq = x1' :: l2' /\ x1 = f x1' /\ l2 = map f l2'. Proof. intros * _eq. destruct seq as [ | x1' l2' ]; simpl in *; try discriminate. inversion _eq. exists x1' l2'; subst; intuition. Qed. Lemma map_eq_nil_inv : forall {A B} (f: A -> B) seq, map f seq = [] -> seq = []. Proof. intros; destruct seq; simpl in *; try discriminate; trivial. Qed. Lemma filter_app : forall {A} (f: A -> _) s1 s2, List.filter f (s1 ++ s2) = List.filter f s1 ++ List.filter f s2. Proof. induction s1; simpl; intros. - reflexivity. - destruct (f a); simpl; congruence. Qed. Lemma filter_map : forall {A B} f g seq, List.filter f (@List.map A B g seq) = List.map g (List.filter (fun x => f (g x)) seq). Proof. induction seq; simpl; intros. - reflexivity. - destruct (f (g a)); simpl; [ f_equal | ]; assumption. Qed. Lemma filter_true : forall {A} s, @filter A (fun _ => true) s = s. Proof. induction s; simpl; try rewrite IHs; reflexivity. Qed. Lemma filter_false : forall {A} s, @filter A (fun _ => false) s = []. Proof. induction s; simpl; try rewrite IHs; reflexivity. Qed. Lemma filter_flat_map : forall {A B} g (f: B -> bool) xs, filter f (flat_map g xs) = flat_map (fun x : A => filter f (g x)) xs. Proof. intros; rewrite !flat_map_flatten. rewrite flatten_filter, map_map; reflexivity. Qed. Lemma filter_flat_map_join_snd : forall {A B} f s1 s2, flat_map (filter (fun x : A * B => f (snd x))) (map (fun a1 : A => map (fun b : B => (a1, b)) s2) s1) = flat_map (fun a1 : A => map (fun b : B => (a1, b)) (filter f s2)) s1. Proof. induction s1; simpl; intros; trivial. rewrite IHs1; f_equiv. rewrite filter_map; simpl; reflexivity. Qed. Lemma flat_map_empty : forall {A B} s, @flat_map A B (fun _ => []) s = []. Proof. induction s; firstorder. Qed. Lemma filter_commute : forall {A} f g seq, @filter A f (filter g seq) = filter g (filter f seq). Proof. induction seq; simpl; intros; trivial. destruct (f a) eqn:eqf; destruct (g a) eqn:eqg; simpl; rewrite ?eqf, ?eqg, ?IHseq; trivial. Qed. Lemma fold_right_id {A} : forall seq, @List.fold_right (list A) A (fun elem acc => elem :: acc) [] seq = seq. Proof. induction seq; simpl; try rewrite IHseq; congruence. Qed. Lemma fold_left_id {A} : forall seq, @List.fold_left (list A) A (fun acc elem => elem :: acc) seq [] = rev seq. Proof. intros. rewrite <- fold_left_rev_right. apply fold_right_id. Qed. Lemma In_partition {A} : forall f (l : list A) a, List.In a l <-> (List.In a (fst (List.partition f l)) \/ List.In a (snd (List.partition f l))). Proof. split; induction l; simpl; intros; intuition; simpl; subst; first [destruct (f a0); destruct (List.partition f l); simpl in *; intuition | destruct (f a); destruct (List.partition f l); simpl; intuition]. Qed. Lemma In_partition_matched {A} : forall f (l : list A) a, List.In a (fst (List.partition f l)) -> f a = true. Proof. induction l; simpl; intros; intuition; simpl; subst; eauto. case_eq (f a); destruct (List.partition f l); simpl; intuition; rewrite H0 in H; eauto; inversion H; subst; eauto. Qed. Lemma In_partition_unmatched {A} : forall f (l : list A) a, List.In a (snd (List.partition f l)) -> f a = false. Proof. induction l; simpl; intros; intuition; simpl; subst; eauto. case_eq (f a); destruct (List.partition f l); simpl; intuition; rewrite H0 in H; eauto; inversion H; subst; eauto. Qed. Lemma nil_in_false : forall {A} seq, seq = nil <-> ~ exists (x: A), List.In x seq. Proof. split; intro H. intros [ x in_seq ]; subst; eauto using in_nil. destruct seq as [ | a ]; trivial. exfalso; apply H; exists a; simpl; intuition. Qed. Lemma In_InA : forall (A : Type) (l : list A) (eqA : relation A) (x : A), Equivalence eqA -> List.In x l -> InA eqA x l. Proof. induction l; intros; simpl in *. exfalso; eauto using in_nil. destruct H0. apply InA_cons_hd; subst; reflexivity. apply InA_cons_tl, IHl; trivial. Qed. Lemma fold_map : forall {A B C} seq f g init, @List.fold_left C A (fun acc x => f acc (g x)) seq init = @List.fold_left C B (fun acc x => f acc ( x)) (@List.map A B g seq) init. Proof. induction seq; simpl; intros; trivial; try rewrite IHseq; intuition. Qed. Lemma fold_plus_sym : forall (seq: list nat) (default: nat), List.fold_right plus default seq = List.fold_left plus seq default. Proof. intros; rewrite <- fold_left_rev_right. revert default; induction seq; simpl; eauto; intros. rewrite fold_right_app; simpl; rewrite <- IHseq. clear IHseq; revert a default; induction seq; simpl; intros; auto with arith. rewrite <- IHseq; omega. Qed. Lemma map_snd {A B C} : forall (f : A -> B) (l : list (C * A)), List.map f (List.map snd l) = List.map snd (List.map (fun ca => (fst ca, f (snd ca))) l). Proof. intros; repeat rewrite List.map_map; induction l; simpl; eauto. Qed. Lemma partition_app {A} : forall f (l1 l2 : list A), List.partition f (l1 ++ l2) = (fst (List.partition f l1) ++ fst (List.partition f l2), snd (List.partition f l1) ++ snd (List.partition f l2)). Proof. induction l1; simpl. - intros; destruct (List.partition f l2); reflexivity. - intros; rewrite IHl1; destruct (f a); destruct (List.partition f l1); simpl; f_equal. Qed. Lemma partition_filter_eq {A} : forall (f : A -> bool) l, fst (List.partition f l) = List.filter f l. Proof. induction l; simpl; eauto. destruct (List.partition f l); destruct (f a); simpl in *; congruence. Qed. Lemma partition_filter_neq {A} : forall (f : A -> bool) l, snd (List.partition f l) = List.filter (fun a => negb (f a)) l. Proof. induction l; simpl; eauto. destruct (List.partition f l); destruct (f a); simpl in *; congruence. Qed. End AdditionalListLemmas. Section AdditionalComputeationLemmas. Require Import Computation.Refinements.Tactics. Lemma ret_computes_to : forall {A: Type} (a1 a2: A), ret a1 ↝ a2 <-> a1 = a2. Proof. t_refine. Qed. End AdditionalComputeationLemmas. Section AdditionalQueryLemmas. Require Import InsertQSSpecs StringBound. Lemma get_update_unconstr_iff {db_schema qs table new_contents} : forall x, Ensembles.In _ (GetUnConstrRelation (@UpdateUnConstrRelation db_schema qs table new_contents) table) x <-> Ensembles.In _ new_contents x. Proof. unfold GetUnConstrRelation, UpdateUnConstrRelation, EnsembleInsert; intros; rewrite ith_replace_BoundIndex_eq; reflexivity. Qed. Lemma decides_negb : forall b P, decides (negb b) P -> decides b (~ P). Proof. unfold decides; setoid_rewrite if_negb; simpl; intros. destruct b; simpl in *; intuition. Qed. End AdditionalQueryLemmas.
module Vending data DoorState = DoorClosed | DoorOpen data Matter = Solid | Liquid | Gas data MatterOperation : Type -> Matter -> Matter -> Type where Melt: MatterOperation () Solid Liquid Boil: MatterOperation () Liquid Gas Condense: MatterOperation () Gas Liquid Freeze: MatterOperation () Liquid Solid Bind: MatterOperation a state1 state2 -> (a->MatterOperation b state2 state3) -> MatterOperation b state1 state3 (>>=) : MatterOperation a state1 state2 -> (a->MatterOperation b state2 state3) -> MatterOperation b state1 state3 (>>=) = Bind iceSteam : MatterOperation () Solid Gas iceSteam = do Melt Boil Condense Freeze Melt Boil
function [xh,x,t]=simobsv(G,H) [y,t,x]=step(G); G=ss(G); A=G.a; B=G.b; C=G.c; D=G.d; [y1,xh1]=step((A-H*C),(B-H*D),C,D,1,t); [y2,xh2]=lsim((A-H*C),H,C,D,y,t); xh=xh1+xh2;
[GOAL] α : Type u_1 X Y : Discrete α ⊢ Fintype (X ⟶ Y) [PROOFSTEP] apply ULift.fintype
(* Theorem easy : forall n, n = 0 \/ n > 0.*) Print nat. Print bool. Print test.
#! /usr/bin/env python import numpy as np import sys import os import f90nml import subprocess import glob from netCDF4 import Dataset UMD_LETKFUTILS = os.environ['UMD_LETKFUTILS'] ODAS_Nx = os.environ['ODAS_Nx'] ODAS_Ny = os.environ['ODAS_Ny'] ODAS_Nz = os.environ['ODAS_Nz'] ODAS_GRID_TYPE = os.environ['ODAS_GRID_TYPE'] ODAS_RC = os.environ['ODAS_RC'] def read_cap(path=''): ''' Read month from cap_restart to select ensemble of anomalies ''' f = open(path+'/cap_restart_ana', 'r') MM = f.readline()[4:6] print 'Using static background for ', MM f.close() return MM def get_static_ens(yyyy, mm, dd, Ne, type='fcst', trans='1'): # To make sure the bkg error are the same over the entire DA window, # get the month from the cap_restart SCRDIR = os.environ['SCRDIR'] MM = read_cap(path=SCRDIR) # Exctract month from cap_restart in the scratch dir of the experiment print 'Exctracting ',MM,' anomalies' pathname=ODAS_RC+'BKGERR/anom-'+ODAS_Nx+'x'+ODAS_Ny+'x'+ODAS_Nz+'-'+ODAS_GRID_TYPE+'/'+MM+'/' flist=glob.glob(pathname+'*'+MM+'.nc') flist.sort() # If not enough static members, use previous-next month. print len(flist) print Ne if (len(flist)<Ne): print 'Loading adjacent months' MM0 = str(int(MM)-1).zfill(2) MM1 = str(int(MM)).zfill(2) MM2 = str(int(MM)+1).zfill(2) pathname=ODAS_RC+'BKGERR/anom-'+ODAS_Nx+'x'+ODAS_Ny+'x'+ODAS_Nz+'-'+ODAS_GRID_TYPE+'/ANOM/' flist=glob.glob(pathname+MM1+'/*.nc')+glob.glob(pathname+MM0+'/*.nc')+glob.glob(pathname+MM2+'/*.nc') n=0 Ne=int(Ne) print 'IN RECENTER.PY ==============================================' print 'Ne=',Ne,' out of ',len(flist),' forecast anomalies' for fname in flist[0:Ne]: print fname print 'Copy static ensemble members #:',str(n+1),' out of ',Ne fname_out=' ./states/state.'+str(n+1)+'.'+yyyy+mm+dd+'.nc' command = 'cp '+fname+' '+fname_out os.system(command) n+=1 try: flist2=glob.glob('./states/*.nc') for fname in flist2: print fname ncfile = Dataset(fname, 'r+') ncfile.renameVariable('SSH', 'SLV') ncfile.close() except: pass def main(): yyyy = sys.argv[1] mm = sys.argv[2] dd = sys.argv[3] center_fname = sys.argv[4] # 3D file containing T & S center_fname2d = sys.argv[5] # 2D " " SLV center_fname_cice = sys.argv[6] # 3D file " AICE, HICE, HSNO, DRAFT, FREEBOARD Ne = sys.argv[7] # Ensemble size Units = sys.argv[8] # Units of variable T in center_fname (K or C) inflation = 1.0 #dyna_ens=False yyyymm=yyyy+mm yyyymmdd=yyyy+mm+dd #RECENTER AICE, HICE, HSNO, DRAFT #================================ #Create symbolic links to ensemble members #--------------------------------------------- os.system('mkdir states') print '===============================================' print 'Ensemble size:',Ne,' recentering sea-ice state' print '===============================================' print 'Getting static members for ',yyyy,'/',mm #get_static_ens(yyyy, mm, dd, Ne, type='cice', trans='logit') get_static_ens(yyyy, mm, dd, Ne) #, trans='logit') command = 'cp recenter_tmp.nml recenter.nml' os.system(command) append_to_file='.false.' for X_varname in ['AICE','HICE','HSNO','DRAFT']: #['AICE','HICE','HSNO','DRAFT']: nml = f90nml.read('recenter.nml') nml['recenter_grid_size']['nx']=int(ODAS_Nx) nml['recenter_grid_size']['ny']=int(ODAS_Ny) nml['recenter_grid_size']['nz']=1 nml['recenter_grid_size']['grid_fname']='grid_spec.nc' nml['recenter_grid_size']['lon_name']='x_T' nml['recenter_grid_size']['lat_name']='y_T' nml['recenter_x']['x_varname']=X_varname nml['recenter_x']['x_varshape']='2d' nml['recenter_x']['num_levels']=1 nml.write('recenter.nml', force=True) scaling = 0.0 command = 'mpirun -np '+str(Ne)+' ./ocean_recenter.x '+yyyymmdd+' '+append_to_file+' '+center_fname_cice+' '+str(scaling)+' '+str(inflation) print command os.system(command) append_to_file='.true.' #RECENTER SLV #========================= #os.system('mkdir states') print '===============================================' print 'Ensemble size:',Ne,' recentering SLV' print '===============================================' #print 'Linking static members for ',yyyy,'/',mm get_static_ens(yyyy, mm, dd, Ne, trans='notrans') command = 'cp recenter_tmp.nml recenter.nml' os.system(command) for X_varname in ['SLV']: #for X_varname in ['SSH']: #for X_varname in ['eta_t']: nml = f90nml.read('recenter.nml') nml['recenter_grid_size']['nx']=int(ODAS_Nx) nml['recenter_grid_size']['ny']=int(ODAS_Ny) nml['recenter_grid_size']['nz']=1 nml['recenter_grid_size']['grid_fname']='grid_spec.nc' nml['recenter_grid_size']['lon_name']='x_T' nml['recenter_grid_size']['lat_name']='y_T' nml['recenter_x']['x_varname']=X_varname nml['recenter_x']['x_varshape']='2d' nml['recenter_x']['num_levels']=1 nml.write('recenter.nml', force=True) scaling = 0.0 command = 'mpirun -np '+str(Ne)+' ./ocean_recenter.x '+yyyymmdd+' '+append_to_file+' '+center_fname2d+' '+str(scaling)+' '+str(inflation) os.system(command) append_to_file='.true.' #sys.exit() #RECENTER T AND S #========================= #Create symbolic links to ensemble members #--------------------------------------------- print '===============================================' print 'Ensemble size:',Ne,' recentering T and S' print '===============================================' command = 'cp recenter_tmp.nml recenter.nml' os.system(command) append_to_file='.false.' for X_varname in ['T','S']: nml = f90nml.read('recenter.nml') nml['recenter_grid_size']['nx']=int(ODAS_Nx) nml['recenter_grid_size']['ny']=int(ODAS_Ny) nml['recenter_grid_size']['nz']=int(ODAS_Nz) nml['recenter_grid_size']['grid_fname']='grid_spec.nc' nml['recenter_grid_size']['lon_name']='x_T' nml['recenter_grid_size']['lat_name']='y_T' nml['recenter_x']['x_varname']=X_varname nml['recenter_x']['x_varshape']='3d' nml['recenter_x']['num_levels']=int(ODAS_Nz) nml.write('recenter.nml', force=True) if ((X_varname=='T') & (Units=='K')): print 'Convert K to C' scaling = -273.15 else: scaling = 0.0 command = 'mpirun -np '+str(Ne)+' ./ocean_recenter.x '+yyyymmdd+' '+append_to_file+' '+center_fname+' '+str(scaling)+' '+str(inflation) print command os.system(command) append_to_file='.true.' with open('EnsembleSize.txt', 'wb') as fh: fh.write(str(Ne)+'\n') if __name__ == '__main__': Ne=main() print Ne
(* Title: HOL/Induct/Common_Patterns.thy Author: Makarius *) section \<open>Common patterns of induction\<close> theory Common_Patterns imports Main begin text \<open> The subsequent Isar proof schemes illustrate common proof patterns supported by the generic \<open>induct\<close> method. To demonstrate variations on statement (goal) structure we refer to the induction rule of Peano natural numbers: @{thm nat.induct [no_vars]}, which is the simplest case of datatype induction. We shall also see more complex (mutual) datatype inductions involving several rules. Working with inductive predicates is similar, but involves explicit facts about membership, instead of implicit syntactic typing. \<close> subsection \<open>Variations on statement structure\<close> subsubsection \<open>Local facts and parameters\<close> text \<open> Augmenting a problem by additional facts and locally fixed variables is a bread-and-butter method in many applications. This is where unwieldy object-level \<open>\<forall>\<close> and \<open>\<longrightarrow>\<close> used to occur in the past. The \<open>induct\<close> method works with primary means of the proof language instead. \<close> lemma fixes n :: nat and x :: 'a assumes "A n x" shows "P n x" using \<open>A n x\<close> proof (induct n arbitrary: x) case 0 note prem = \<open>A 0 x\<close> show "P 0 x" \<proof> next case (Suc n) note hyp = \<open>\<And>x. A n x \<Longrightarrow> P n x\<close> and prem = \<open>A (Suc n) x\<close> show "P (Suc n) x" \<proof> qed subsubsection \<open>Local definitions\<close> text \<open> Here the idea is to turn sub-expressions of the problem into a defined induction variable. This is often accompanied with fixing of auxiliary parameters in the original expression, otherwise the induction step would refer invariably to particular entities. This combination essentially expresses a partially abstracted representation of inductive expressions. \<close> lemma fixes a :: "'a \<Rightarrow> nat" assumes "A (a x)" shows "P (a x)" using \<open>A (a x)\<close> proof (induct n \<equiv> "a x" arbitrary: x) case 0 note prem = \<open>A (a x)\<close> and defn = \<open>0 = a x\<close> show "P (a x)" \<proof> next case (Suc n) note hyp = \<open>\<And>x. n = a x \<Longrightarrow> A (a x) \<Longrightarrow> P (a x)\<close> and prem = \<open>A (a x)\<close> and defn = \<open>Suc n = a x\<close> show "P (a x)" \<proof> qed text \<open> Observe how the local definition \<open>n = a x\<close> recurs in the inductive cases as \<open>0 = a x\<close> and \<open>Suc n = a x\<close>, according to underlying induction rule. \<close> subsubsection \<open>Simple simultaneous goals\<close> text \<open> The most basic simultaneous induction operates on several goals one-by-one, where each case refers to induction hypotheses that are duplicated according to the number of conclusions. \<close> lemma fixes n :: nat shows "P n" and "Q n" proof (induct n) case 0 case 1 show "P 0" \<proof> next case 0 case 2 show "Q 0" \<proof> next case (Suc n) case 1 note hyps = \<open>P n\<close> \<open>Q n\<close> show "P (Suc n)" \<proof> next case (Suc n) case 2 note hyps = \<open>P n\<close> \<open>Q n\<close> show "Q (Suc n)" \<proof> qed text \<open> The split into subcases may be deferred as follows -- this is particularly relevant for goal statements with local premises. \<close> lemma fixes n :: nat shows "A n \<Longrightarrow> P n" and "B n \<Longrightarrow> Q n" proof (induct n) case 0 { case 1 note \<open>A 0\<close> show "P 0" \<proof> next case 2 note \<open>B 0\<close> show "Q 0" \<proof> } next case (Suc n) note \<open>A n \<Longrightarrow> P n\<close> and \<open>B n \<Longrightarrow> Q n\<close> { case 1 note \<open>A (Suc n)\<close> show "P (Suc n)" \<proof> next case 2 note \<open>B (Suc n)\<close> show "Q (Suc n)" \<proof> } qed subsubsection \<open>Compound simultaneous goals\<close> text \<open> The following pattern illustrates the slightly more complex situation of simultaneous goals with individual local assumptions. In compound simultaneous statements like this, local assumptions need to be included into each goal, using \<open>\<Longrightarrow>\<close> of the Pure framework. In contrast, local parameters do not require separate \<open>\<And>\<close> prefixes here, but may be moved into the common context of the whole statement. \<close> lemma fixes n :: nat and x :: 'a and y :: 'b shows "A n x \<Longrightarrow> P n x" and "B n y \<Longrightarrow> Q n y" proof (induct n arbitrary: x y) case 0 { case 1 note prem = \<open>A 0 x\<close> show "P 0 x" \<proof> } { case 2 note prem = \<open>B 0 y\<close> show "Q 0 y" \<proof> } next case (Suc n) note hyps = \<open>\<And>x. A n x \<Longrightarrow> P n x\<close> \<open>\<And>y. B n y \<Longrightarrow> Q n y\<close> then have some_intermediate_result \<proof> { case 1 note prem = \<open>A (Suc n) x\<close> show "P (Suc n) x" \<proof> } { case 2 note prem = \<open>B (Suc n) y\<close> show "Q (Suc n) y" \<proof> } qed text \<open> Here \<open>induct\<close> provides again nested cases with numbered sub-cases, which allows to share common parts of the body context. In typical applications, there could be a long intermediate proof of general consequences of the induction hypotheses, before finishing each conclusion separately. \<close> subsection \<open>Multiple rules\<close> text \<open> Multiple induction rules emerge from mutual definitions of datatypes, inductive predicates, functions etc. The \<open>induct\<close> method accepts replicated arguments (with \<open>and\<close> separator), corresponding to each projection of the induction principle. The goal statement essentially follows the same arrangement, although it might be subdivided into simultaneous sub-problems as before! \<close> datatype foo = Foo1 nat | Foo2 bar and bar = Bar1 bool | Bar2 bazar and bazar = Bazar foo text \<open> The pack of induction rules for this datatype is: @{thm [display] foo.induct [no_vars] bar.induct [no_vars] bazar.induct [no_vars]} This corresponds to the following basic proof pattern: \<close> lemma fixes foo :: foo and bar :: bar and bazar :: bazar shows "P foo" and "Q bar" and "R bazar" proof (induct foo and bar and bazar) case (Foo1 n) show "P (Foo1 n)" \<proof> next case (Foo2 bar) note \<open>Q bar\<close> show "P (Foo2 bar)" \<proof> next case (Bar1 b) show "Q (Bar1 b)" \<proof> next case (Bar2 bazar) note \<open>R bazar\<close> show "Q (Bar2 bazar)" \<proof> next case (Bazar foo) note \<open>P foo\<close> show "R (Bazar foo)" \<proof> qed text \<open> This can be combined with the previous techniques for compound statements, e.g.\ like this. \<close> lemma fixes x :: 'a and y :: 'b and z :: 'c and foo :: foo and bar :: bar and bazar :: bazar shows "A x foo \<Longrightarrow> P x foo" and "B1 y bar \<Longrightarrow> Q1 y bar" "B2 y bar \<Longrightarrow> Q2 y bar" and "C1 z bazar \<Longrightarrow> R1 z bazar" "C2 z bazar \<Longrightarrow> R2 z bazar" "C3 z bazar \<Longrightarrow> R3 z bazar" proof (induct foo and bar and bazar arbitrary: x and y and z) oops subsection \<open>Inductive predicates\<close> text \<open> The most basic form of induction involving predicates (or sets) essentially eliminates a given membership fact. \<close> inductive Even :: "nat \<Rightarrow> bool" where zero: "Even 0" | double: "Even (2 * n)" if "Even n" for n lemma assumes "Even n" shows "P n" using assms proof induct case zero show "P 0" \<proof> next case (double n) note \<open>Even n\<close> and \<open>P n\<close> show "P (2 * n)" \<proof> qed text \<open> Alternatively, an initial rule statement may be proven as follows, performing ``in-situ'' elimination with explicit rule specification. \<close> lemma "Even n \<Longrightarrow> P n" proof (induct rule: Even.induct) oops text \<open> Simultaneous goals do not introduce anything new. \<close> lemma assumes "Even n" shows "P1 n" and "P2 n" using assms proof induct case zero { case 1 show "P1 0" \<proof> next case 2 show "P2 0" \<proof> } next case (double n) note \<open>Even n\<close> and \<open>P1 n\<close> and \<open>P2 n\<close> { case 1 show "P1 (2 * n)" \<proof> next case 2 show "P2 (2 * n)" \<proof> } qed text \<open> Working with mutual rules requires special care in composing the statement as a two-level conjunction, using lists of propositions separated by \<open>and\<close>. For example: \<close> inductive Evn :: "nat \<Rightarrow> bool" and Odd :: "nat \<Rightarrow> bool" where zero: "Evn 0" | succ_Evn: "Odd (Suc n)" if "Evn n" for n | succ_Odd: "Evn (Suc n)" if "Odd n" for n lemma "Evn n \<Longrightarrow> P1 n" "Evn n \<Longrightarrow> P2 n" "Evn n \<Longrightarrow> P3 n" and "Odd n \<Longrightarrow> Q1 n" "Odd n \<Longrightarrow> Q2 n" proof (induct rule: Evn_Odd.inducts) case zero { case 1 show "P1 0" \<proof> } { case 2 show "P2 0" \<proof> } { case 3 show "P3 0" \<proof> } next case (succ_Evn n) note \<open>Evn n\<close> and \<open>P1 n\<close> \<open>P2 n\<close> \<open>P3 n\<close> { case 1 show "Q1 (Suc n)" \<proof> } { case 2 show "Q2 (Suc n)" \<proof> } next case (succ_Odd n) note \<open>Odd n\<close> and \<open>Q1 n\<close> \<open>Q2 n\<close> { case 1 show "P1 (Suc n)" \<proof> } { case 2 show "P2 (Suc n)" \<proof> } { case 3 show "P3 (Suc n)" \<proof> } qed text \<open> Cases and hypotheses in each case can be named explicitly. \<close> inductive star :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where refl: "star r x x" for x | step: "star r x z" if "r x y" and "star r y z" for x y z text \<open>Underscores are replaced by the default name hyps:\<close> lemmas star_induct = star.induct [case_names base step[r _ IH]] lemma "star r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z" proof (induct rule: star_induct) print_cases case base then show ?case . next case (step a b c) print_facts from step.prems have "star r b z" by (rule step.IH) with step.r show ?case by (rule star.step) qed end
\chapter{Recognizing Loops} Figures~\ref{Tutorial:exampleLoopRecognition-part1} and \ref{Tutorial:exampleLoopRecognition-part2} show a translator which reads an application and gathers a list of loop nests. At the end of the traversal it reports information about each loop nest, including the function where it occurred and the depth of the loop nest. \fixme{This example program is unfinished. It will output a list of objects representing information about perfectly nested loops.} \begin{figure}[!h] {\indent {\mySmallestFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleBuildDirectory/loopRecognition.aa} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleDirectory/loopRecognition.C} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Example source code showing loop recognition (part 1).} \label{Tutorial:exampleLoopRecognition-part1} \end{figure} \begin{figure}[!h] {\indent {\mySmallestFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleBuildDirectory/loopRecognition.ab} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleDirectory/loopRecognition.C} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Example source code showing loop recognition (part 2).} \label{Tutorial:exampleLoopRecognition-part2} \end{figure} Using this translator we can compile the code shown in figure~\ref{Tutorial:exampleInputCode_LoopRecognition}. The output is shown in figure~\ref{Tutorial:exampleOutput_LoopRecognition}. \begin{figure}[!h] {\indent {\mySmallFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleDirectory/inputCode_LoopRecognition.C} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleDirectory/inputCode_LoopRecognition.C} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Example source code used as input to loop recognition processor.} \label{Tutorial:exampleInputCode_LoopRecognition} \end{figure} \begin{figure}[!h] {\indent {\mySmallFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleBuildDirectory/loopRecognition.out} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleBuildDirectory/loopRecognition.out} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Output of input to loop recognition processor.} \label{Tutorial:exampleOutput_LoopRecognition} \end{figure}
n <- function(x) function()x A <- function(k, x1, x2, x3, x4, x5) { B <- function() A(k <<- k-1, B, x1, x2, x3, x4) if (k <= 0) x4() + x5() else B() } A(10, n(1), n(-1), n(-1), n(1), n(0))
import HTPIDefs namespace HTPI set_option pp.funBinderTypes true /- Definitions -/ def even (n : Int) : Prop := ∃ (k : Int), n = 2 * k def odd (n : Int) : Prop := ∃ (k : Int), n = 2 * k + 1 /- Sections 3.1 and 3.2 -/ theorem Example_3_2_4_v2 (P Q R : Prop) (h : P → (Q → R)) : ¬R → (P → ¬Q) := by assume h2 : ¬R assume h3 : P by_contra h4 have h5 : Q → R := h h3 have h6 : R := h5 h4 show False from h2 h6 done theorem Example_3_2_4_v3 (P Q R : Prop) (h : P → (Q → R)) : ¬R → (P → ¬Q) := by assume h2 : ¬R assume h3 : P by_contra h4 contradict h2 show R from h h3 h4 done theorem Like_Example_3_2_5 (U : Type) (A B C : Set U) (a : U) (h1 : a ∈ A) (h2 : a ∉ A \ B) (h3 : a ∈ B → a ∈ C) : a ∈ C := by apply h3 _ define at h2 demorgan at h2; conditional at h2 show a ∈ B from h2 h1 done /- Section 3.3 -/ example (U : Type) (P Q : Pred U) (h1 : ∀ (x : U), P x → ¬Q x) (h2 : ∀ (x : U), Q x) : ¬∃ (x : U), P x := by quant_neg --Goal is now ∀ (x : U), ¬P x fix y : U have h3 : P y → ¬Q y := h1 y have h4 : Q y := h2 y contrapos at h3 --Now h3 : Q y → ¬P y show ¬P y from h3 h4 done example (U : Type) (A B C : Set U) (h1 : A ⊆ B ∪ C) (h2 : ∀ (x : U), x ∈ A → x ∉ B) : A ⊆ C := by define --Goal : ∀ ⦃a : U⦄, a ∈ A → a ∈ C fix y : U assume h3 : y ∈ A have h4 : y ∉ B := h2 y h3 define at h1 --h1 : ∀ ⦃a : U⦄, a ∈ A → a ∈ B ∪ C have h5 : y ∈ B ∪ C := h1 h3 define at h5 --h5 : y ∈ B ∨ y ∈ C conditional at h5 --h5 : ¬y ∈ B → y ∈ C show y ∈ C from h5 h4 done example (U : Type) (P Q : Pred U) (h1 : ∀ (x : U), ∃ (y : U), P x → ¬ Q y) (h2 : ∃ (x : U), ∀ (y : U), P x → Q y) : ∃ (x : U), ¬P x := by obtain (a : U) (h3 : ∀ (y : U), P a → Q y) from h2 have h4 : ∃ (y : U), P a → ¬ Q y := h1 a obtain (b : U) (h5 : P a → ¬ Q b) from h4 have h6 : P a → Q b := h3 b apply Exists.intro a _ by_contra h7 show False from h5 h7 (h6 h7) done theorem Example_3_3_5 (U : Type) (B : Set U) (F : Set (Set U)) : ⋃₀ F ⊆ B → F ⊆ 𝒫 B := by assume h1 : ⋃₀ F ⊆ B define fix x : Set U assume h2 : x ∈ F define fix y : U assume h3 : y ∈ x define at h1 apply h1 _ define apply Exists.intro x _ show x ∈ F ∧ y ∈ x from And.intro h2 h3 done /- Section 3.4 -/ theorem Like_Example_3_4_1 (U : Type) (A B C D : Set U) (h1 : A ⊆ B) (h2 : ¬∃ (c : U), c ∈ C ∩ D) : A ∩ C ⊆ B \ D := by define fix x : U assume h3 : x ∈ A ∩ C define at h3; define apply And.intro · -- Proof that x ∈ B. show x ∈ B from h1 h3.left done · -- Proof that ¬x ∈ D. contradict h2 with h4 apply Exists.intro x show x ∈ C ∩ D from And.intro h3.right h4 done done example (U : Type) (P Q : Pred U) (h1 : ∀ (x : U), P x ↔ Q x) : (∃ (x : U), P x) ↔ ∃ (x : U), Q x := by apply Iff.intro · -- (→) assume h2 : ∃ (x : U), P x obtain (u : U) (h3 : P u) from h2 have h4 : P u ↔ Q u := h1 u apply Exists.intro u show Q u from h4.ltr h3 done · -- (←) assume h2 : ∃ (x : U), Q x obtain (u : U) (h3 : Q u) from h2 show ∃ (x : U), P x from Exists.intro u ((h1 u).rtl h3) done done theorem Example_3_4_5 (U : Type) (A B C : Set U) : A ∩ (B \ C) = (A ∩ B) \ C := by apply Set.ext fix x : U show x ∈ A ∩ (B \ C) ↔ x ∈ (A ∩ B) \ C from calc x ∈ A ∩ (B \ C) _ ↔ x ∈ A ∧ (x ∈ B ∧ x ∉ C) := Iff.refl _ _ ↔ (x ∈ A ∧ x ∈ B) ∧ x ∉ C := and_assoc.symm _ ↔ x ∈ (A ∩ B) \ C := Iff.refl _ done /- Section 3.5 -/ theorem Example_3_5_2 (U : Type) (A B C : Set U) : A \ (B \ C) ⊆ (A \ B) ∪ C := by fix x : U assume h1 : x ∈ A \ (B \ C) define; define at h1 have h2 : ¬x ∈ B \ C := h1.right define at h2; demorgan at h2 --h2 : ¬x ∈ B ∨ x ∈ C by_cases on h2 · -- Case 1. h2 : ¬x ∈ B apply Or.inl show x ∈ A \ B from And.intro h1.left h2 done · -- Case 2. h2 : x ∈ C apply Or.inr show x ∈ C from h2 done done example (U : Type) (A B C : Set U) (h1 : A \ B ⊆ C) : A ⊆ B ∪ C := by fix x : U assume h2 : x ∈ A define or_right with h3 show x ∈ C from h1 (And.intro h2 h3) done example (U : Type) (A B C : Set U) (h1 : A ⊆ B ∪ C) (h2 : ¬∃ (x : U), x ∈ A ∩ B) : A ⊆ C := by fix a : U assume h3 : a ∈ A quant_neg at h2 have h4 : a ∈ B ∪ C := h1 h3 have h5 : a ∉ A ∩ B := h2 a define at h4 define at h5; demorgan at h5 disj_syll h5 h3 --h5 : ¬a ∈ B disj_syll h4 h5 --h4 : a ∈ C show a ∈ C from h4 done example (U : Type) (A B C : Set U) (h1 : A ⊆ B ∪ C) (h2 : ¬∃ (x : U), x ∈ A ∩ B) : A ⊆ C := by fix a : U assume h3 : a ∈ A have h4 : a ∈ B ∪ C := h1 h3 define at h4 have h5 : a ∉ B := by contradict h2 with h6 show ∃ (x : U), x ∈ A ∩ B from Exists.intro a (And.intro h3 h6) done disj_syll h4 h5 --h4 : a ∈ C show a ∈ C from h4 done /- Section 3.6 -/ theorem empty_union {U : Type} (B : Set U) : ∅ ∪ B = B := by apply Set.ext fix x : U apply Iff.intro · -- (→) assume h1 : x ∈ ∅ ∪ B define at h1 have h2 : x ∉ ∅ := by by_contra h3 define at h3 --h3 : False show False from h3 done disj_syll h1 h2 --h1 : x ∈ B show x ∈ B from h1 done · -- (←) assume h1 : x ∈ B show x ∈ ∅ ∪ B from Or.inr h1 done done theorem union_comm {U : Type} (X Y : Set U) : X ∪ Y = Y ∪ X := by apply Set.ext fix x : U define : x ∈ X ∪ Y define : x ∈ Y ∪ X show x ∈ X ∨ x ∈ Y ↔ x ∈ Y ∨ x ∈ X from or_comm done theorem Example_3_6_2 (U : Type) : ∃! (A : Set U), ∀ (B : Set U), A ∪ B = B := by exists_unique · -- Existence apply Exists.intro ∅ show ∀ (B : Set U), ∅ ∪ B = B from empty_union done · -- Uniqueness fix C : Set U; fix D : Set U assume h1 : ∀ (B : Set U), C ∪ B = B assume h2 : ∀ (B : Set U), D ∪ B = B have h3 : C ∪ D = D := h1 D have h4 : D ∪ C = C := h2 C show C = D from calc C _ = D ∪ C := h4.symm _ = C ∪ D := union_comm D C _ = D := h3 done done theorem Example_3_6_4 (U : Type) (A B C : Set U) (h1 : ∃ (x : U), x ∈ A ∩ B) (h2 : ∃ (x : U), x ∈ A ∩ C) (h3 : ∃! (x : U), x ∈ A) : ∃ (x : U), x ∈ B ∩ C := by obtain (b : U) (h4 : b ∈ A ∩ B) from h1 obtain (c : U) (h5 : c ∈ A ∩ C) from h2 obtain (a : U) (h6 : a ∈ A) (h7 : ∀ (y z : U), y ∈ A → z ∈ A → y = z) from h3 define at h4; define at h5 have h8 : b = c := h7 b c h4.left h5.left rewrite [h8] at h4 show ∃ (x : U), x ∈ B ∩ C from Exists.intro c (And.intro h4.right h5.right) done /- Section 3.7 -/ theorem Theorem_3_3_7 : ∀ (a b c : Int), a ∣ b → b ∣ c → a ∣ c := by fix a : Int; fix b : Int; fix c : Int assume h1 : a ∣ b; assume h2 : b ∣ c define at h1; define at h2; define obtain (m : Int) (h3 : b = a * m) from h1 obtain (n : Int) (h4 : c = b * n) from h2 rewrite [h3] at h4 --h4 : c = a * m * n apply Exists.intro (m * n) rewrite [mul_assoc a m n] at h4 show c = a * (m * n) from h4 done theorem Theorem_3_4_7 : ∀ (n : Int), 6 ∣ n ↔ 2 ∣ n ∧ 3 ∣ n := by fix n : Int apply Iff.intro · -- (→) assume h1 : 6 ∣ n; define at h1 obtain (k : Int) (h2 : n = 6 * k) from h1 apply And.intro · -- Proof that 2 ∣ n define apply Exists.intro (3 * k) rewrite [←mul_assoc 2 3 k] show n = 2 * 3 * k from h2 done · -- Proof that 3 ∣ n define apply Exists.intro (2 * k) rewrite [←mul_assoc 3 2 k] show n = 3 * 2 * k from h2 done done · -- (←) assume h1 have h2 := h1.left have h3 := h1.right define at h2; define at h3; define obtain (j : Int) (h4 : n = 2 * j) from h2 obtain (k : Int) (h5 : n = 3 * k) from h3 have h6 : 6 * (j - k) = n := calc 6 * (j - k) _ = 6 * j - 6 * k := mul_sub_left_distrib 6 j k _ = 3 * (2 * j) - 2 * (3 * k) := by rewrite [←mul_assoc 3 2 j, ←mul_assoc 2 3 k]; rfl _ = 3 * n - 2 * n := by rewrite [←h4, ←h5]; rfl _ = (3 - 2) * n := (mul_sub_right_distrib 3 2 n).symm _ = n := one_mul n show ∃ (c : Int), n = 6 * c from Exists.intro (j - k) h6.symm done done
[STATEMENT] lemma [dest]: "\<And> l A. \<lbrakk>l \<in> A; Lo \<notin> A\<rbrakk> \<Longrightarrow> l = Hi" and [dest]: "\<And> l A. \<lbrakk>l \<in> A; Hi \<notin> A\<rbrakk> \<Longrightarrow> l = Lo" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>l A. \<lbrakk>l \<in> A; Lo \<notin> A\<rbrakk> \<Longrightarrow> l = Hi) &&& (\<And>l A. \<lbrakk>l \<in> A; Hi \<notin> A\<rbrakk> \<Longrightarrow> l = Lo) [PROOF STEP] by (metis level.exhaust)+
install.packages("tidyverse") library(tidyr) library(dplyr) library(readr) find_trees <- function(run, rise) { row <- 1 column <- 1 trees <- 0 # Hard-coded total number of rows while(row <= 323) { if(data[row,column] == "#") { trees <- trees + 1 } row <- row + rise column <- column + run # Hard-coded total number of columns if(column > 31) { column <- column - 31 } } return(trees) } # Probably a better way to do this, but read in data as fixed-width values, each 1 char long data <- read_fwf("input.txt", fwf_widths(c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) # Part 1 print(find_trees(3,1)) # Part 2 total_trees <- find_trees(1,1) * find_trees(3,1) * find_trees(5,1) * find_trees(7,1) * find_trees(1,2) print(total_trees)
Require Import core.Semantics. Require Import core.Syntax. Require Import core.Model. Require Import core.TransformationConfiguration. Require Import String. Require Import EqNat. Require Import List. Require Import Expressions. Require Import core.utils.Utils. Require Import PeanoNat. Require Import Lia. Require Import FunctionalExtensionality. (*************************************************************) (** * Confluence *) (*************************************************************) Definition well_form {tc: TransformationConfiguration} tr := forall r1 r2 sm sp, In r1 tr /\ In r2 tr/\ matchRuleOnPattern r1 sm sp = true /\ matchRuleOnPattern r2 sm sp = true -> r1 = r2. (* Multiset semantics: we think that the list of rules represents a multiset/bag*) (* Definition Transformation_equiv {tc: TransformationConfiguration} (t1 t2: Transformation) := forall (r:Rule), count_occ' Rule_eqdec (Transformation_getRules t1) r = count_occ' Rule_eqdec (Transformation_getRules t2) r. *) (* another way to represent multiset semantics*) (* Definition Transformation_equiv {tc: TransformationConfiguration} (t1 t2: Transformation) := sub_set (Transformation_getRules t1) (Transformation_getRules t2) /\ sub_set (Transformation_getRules t1) (Transformation_getRules t2).*) (* Set semantics: we think that the list of rules represents a set (we don't allow two rules to have the same name)*) Definition Transformation_equiv {tc: TransformationConfiguration} (t1 t2: Transformation) := (Transformation_getArity t1 = Transformation_getArity t2) /\ set_eq (Transformation_getRules t1) (Transformation_getRules t2) /\ well_form (Transformation_getRules t1) /\ well_form (Transformation_getRules t2). Lemma trace_eq {tc: TransformationConfiguration} : forall t1 t2 sm, Transformation_equiv t1 t2 -> (trace t1 sm) = (trace t2 sm). Proof. intros. destruct t1. destruct t2. induction l. - unfold Transformation_equiv in H. admit. Admitted. Definition TargetModel_equiv {tc: TransformationConfiguration} (m1 m2: TargetModel) := forall (e: TargetModelElement) (l: TargetModelLink), (In e (allModelElements m1) <-> In e (allModelElements m2)) /\ (In l (allModelLinks m1) <-> In l (allModelLinks m2)). Theorem confluence : forall (tc: TransformationConfiguration) (t1 t2: Transformation) (sm: SourceModel), Transformation_equiv t1 t2 -> TargetModel_equiv (execute t1 sm) (execute t2 sm). Proof. unfold TargetModel_equiv. unfold Transformation_equiv. simpl. intros. destruct H. split. - split. + unfold instantiatePattern. unfold matchPattern. intros. apply in_flat_map in H1. repeat destruct H1. apply in_flat_map in H2. repeat destruct H2. apply filter_In in H2. destruct H2. apply in_flat_map. exists x. split. * unfold allTuples. unfold maxArity. rewrite <- H. assumption. * apply in_flat_map. exists x0. split. -- apply filter_In. split. apply H0. assumption. assumption. -- assumption. + unfold instantiatePattern. unfold matchPattern. intros. apply in_flat_map in H1. repeat destruct H1. apply in_flat_map in H2. repeat destruct H2. apply filter_In in H2. destruct H2. apply in_flat_map. exists x. split. * unfold allTuples. unfold maxArity. rewrite H. assumption. * apply in_flat_map. exists x0. split. -- apply filter_In. split. apply H0. assumption. assumption. -- assumption. - split. + unfold applyPattern. unfold matchPattern. intros. apply in_flat_map in H1. repeat destruct H1. apply in_flat_map in H2. repeat destruct H2. apply filter_In in H2. destruct H2. apply in_flat_map. exists x. split. * unfold allTuples. unfold maxArity. rewrite <- H. assumption. * apply in_flat_map. exists x0. split. -- apply filter_In. split. apply H0. assumption. assumption. -- unfold applyRuleOnPattern, applyIterationOnPattern in *. apply in_flat_map in H3. repeat destruct H3. apply in_flat_map. exists x1. split. ++ assumption. ++ apply in_flat_map in H5. repeat destruct H5. apply in_flat_map. exists x2. split. ** assumption. ** unfold applyElementOnPattern in *. assert (trace t1 sm = trace t2 sm). { unfold trace, tracePattern. admit. (* requires reordering for rules *) } Admitted.
// // Copyright (c) 2019 Vinnie Falco ([email protected]) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_DETAIL_CONFIG_HPP #define BOOST_URL_DETAIL_CONFIG_HPP #include <boost/config.hpp> #include <boost/config/workaround.hpp> #include <limits.h> #if CHAR_BIT != 8 # error unsupported platform #endif #if defined(BOOST_URL_DOCS) # define BOOST_URL_DECL #else # if (defined(BOOST_URL_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)) && !defined(BOOST_URL_STATIC_LINK) # if defined(BOOST_URL_SOURCE) # define BOOST_URL_DECL BOOST_SYMBOL_EXPORT # define BOOST_URL_BUILD_DLL # else # define BOOST_URL_DECL BOOST_SYMBOL_IMPORT # endif # endif // shared lib # ifndef BOOST_URL_DECL # define BOOST_URL_DECL # endif # if !defined(BOOST_URL_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_URL_NO_LIB) # define BOOST_LIB_NAME boost_url # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_URL_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> # endif #endif #if ! defined(BOOST_URL_NO_SSE2) && \ ! defined(BOOST_URL_USE_SSE2) # if (defined(_M_IX86) && _M_IX86_FP == 2) || \ defined(_M_X64) || defined(__SSE2__) # define BOOST_URL_USE_SSE2 # endif #endif // This macro is used for the limits // test which sets the value lower, // to exercise code coverage. // #ifndef BOOST_URL_MAX_SIZE // we leave room for a null, // and still fit in signed-32 #define BOOST_URL_MAX_SIZE 0x7ffffffe #endif #if BOOST_WORKAROUND( BOOST_GCC_VERSION, <= 72000 ) || \ BOOST_WORKAROUND( BOOST_CLANG_VERSION, <= 35000 ) # define BOOST_URL_CONSTEXPR #else # define BOOST_URL_CONSTEXPR constexpr #endif // Add source location to error codes #ifdef BOOST_URL_NO_SOURCE_LOCATION # define BOOST_URL_ERR(ev) (ev) #else # define BOOST_URL_ERR(ev) (::boost::system::error_code( (ev), [] { \ static constexpr auto loc(BOOST_CURRENT_LOCATION); \ return &loc; }())) #endif #endif
foo : String foo = "nested: \{ " \{ 1 + } " }"
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.roots_of_unity import analysis.special_functions.trigonometric import analysis.special_functions.pow /-! # Complex roots of unity In this file we show that the `n`-th complex roots of unity are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`. ## Main declarations * `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. * `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`. -/ namespace complex open polynomial real open_locale nat real lemma is_primitive_root_exp_of_coprime (i n : ℕ) (h0 : n ≠ 0) (hi : i.coprime n) : is_primitive_root (exp (2 * π * I * (i / n))) n := begin rw is_primitive_root.iff_def, simp only [← exp_nat_mul, exp_eq_one_iff], have hn0 : (n : ℂ) ≠ 0, by exact_mod_cast h0, split, { use i, field_simp [hn0, mul_comm (i : ℂ), mul_comm (n : ℂ)] }, { simp only [hn0, mul_right_comm _ _ ↑n, mul_left_inj' two_pi_I_ne_zero, ne.def, not_false_iff, mul_comm _ (i : ℂ), ← mul_assoc _ (i : ℂ), exists_imp_distrib] with field_simps, norm_cast, rintro l k hk, have : n ∣ i * l, { rw [← int.coe_nat_dvd, hk], apply dvd_mul_left }, exact hi.symm.dvd_of_dvd_mul_left this } end lemma is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) : is_primitive_root (exp (2 * π * I / n)) n := by simpa only [nat.cast_one, one_div] using is_primitive_root_exp_of_coprime 1 n h0 n.coprime_one_left lemma is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) : is_primitive_root ζ n ↔ (∃ (i < (n : ℕ)) (hi : i.coprime n), exp (2 * π * I * (i / n)) = ζ) := begin have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast hn, split, swap, { rintro ⟨i, -, hi, rfl⟩, exact is_primitive_root_exp_of_coprime i n hn hi }, intro h, obtain ⟨i, hi, rfl⟩ := (is_primitive_root_exp n hn).eq_pow_of_pow_eq_one h.pow_eq_one (nat.pos_of_ne_zero hn), refine ⟨i, hi, ((is_primitive_root_exp n hn).pow_iff_coprime (nat.pos_of_ne_zero hn) i).mp h, _⟩, rw [← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] end /-- The complex `n`-th roots of unity are exactly the complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/ lemma mem_roots_of_unity (n : ℕ+) (x : units ℂ) : x ∈ roots_of_unity n ℂ ↔ (∃ i < (n : ℕ), exp (2 * π * I * (i / n)) = x) := begin rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, units.coe_one], have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast (n.ne_zero), split, { intro h, obtain ⟨i, hi, H⟩ : ∃ i < (n : ℕ), exp (2 * π * I / n) ^ i = x, { simpa only using (is_primitive_root_exp n n.ne_zero).eq_pow_of_pow_eq_one h n.pos }, refine ⟨i, hi, _⟩, rw [← H, ← exp_nat_mul], congr' 1, field_simp [hn0, mul_comm (i : ℂ)] }, { rintro ⟨i, hi, H⟩, rw [← H, ← exp_nat_mul, exp_eq_one_iff], use i, field_simp [hn0, mul_comm ((n : ℕ) : ℂ), mul_comm (i : ℂ)] } end lemma card_roots_of_unity (n : ℕ+) : fintype.card (roots_of_unity n ℂ) = n := (is_primitive_root_exp n n.ne_zero).card_roots_of_unity lemma card_primitive_roots (k : ℕ) (h : k ≠ 0) : (primitive_roots k ℂ).card = φ k := (is_primitive_root_exp k h).card_primitive_roots (nat.pos_of_ne_zero h) end complex
module DistanceMatrixRank where import Data.List as L import Data.Vector as V import Data.Matrix as M import Statistics.Sample data DistanceMatrix = DistanceMatrix { distanceMatrix :: Matrix Double, origins :: [String], destinations :: [String] } deriving (Show) rankDestinations :: DistanceMatrix -> [(String, Double)] rankDestinations m = L.zip (destinations m) (L.map stdDev $ columns (distanceMatrix m)) columns :: Matrix a -> [Vector a] columns m = L.map (flip M.getCol m) [1..cols] where cols = M.ncols m
""" get_classes(mtg) Compute the mtg classes based on its content. Usefull after having mutating the mtg nodes. """ function get_classes(mtg) attributes = traverse(mtg, node -> (SYMBOL = node.MTG.symbol, SCALE = node.MTG.scale)) attributes = unique(attributes) df = DataFrame(attributes) # Make everything to default values: df[!, :DECOMPOSITION] .= "FREE" df[!, :INDEXATION] .= "FREE" df[!, :DEFINITION] .= "IMPLICIT" return df end """ get_description(mtg) Returns `nothing`, because we can't really predict the description section from an mtg. """ function get_description(mtg) return nothing end """ get_features(mtg) Compute the mtg features section based on its attributes. Usefull after having computed new attributes in the mtg. """ function get_features(mtg) attributes = traverse(mtg, node -> (collect(keys(node.attributes)), [typeof(i) for i in values(node.attributes)])) df = DataFrame( :NAME => vcat([i[1] for i in attributes]...), :TYPE => vcat([i[2] for i in attributes]...) ) # filter-out the attributes that have more than one value inside them (not compatible with # the mtg format yet): filter!(x -> x.TYPE <: Number || x.TYPE <: AbstractString, df) # Remove repeated rows: unique!(df) new_type = fill("", size(df)[1]) for (index, value) in enumerate(df.TYPE) if value <: AbstractFloat new_type[index] = "REAL" elseif value <: Int new_type[index] = "INT" # elseif df.NAME[i] in () # Put reserved keywords here if needed in the future # new_type[index] = "ALPHA" else # All others are parsed as string new_type[index] = "STRING" end end df.TYPE = new_type return df end
[STATEMENT] lemma differentiable_bound_general_open_segment: fixes a :: "real" and b :: "real" and f :: "real \<Rightarrow> 'a::real_normed_vector" and f' :: "real \<Rightarrow> 'a" assumes "continuous_on (closed_segment a b) f" assumes "continuous_on (closed_segment a b) g" and "(f has_vderiv_on f') (open_segment a b)" and "(g has_vderiv_on g') (open_segment a b)" and "\<And>x. x \<in> open_segment a b \<Longrightarrow> norm (f' x) \<le> g' x" shows "norm (f b - f a) \<le> abs (g b - g a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] { [PROOF STATE] proof (state) goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] assume "a = b" [PROOF STATE] proof (state) this: a = b goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] hence ?thesis [PROOF STATE] proof (prove) using this: a = b goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] by simp [PROOF STATE] proof (state) this: norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] } [PROOF STATE] proof (state) this: a = b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] moreover [PROOF STATE] proof (state) this: a = b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] { [PROOF STATE] proof (state) this: a = b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] assume "a < b" [PROOF STATE] proof (state) this: a < b goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] with assms [PROOF STATE] proof (chain) picking this: continuous_on (closed_segment a b) f continuous_on (closed_segment a b) g (f has_vderiv_on f') (open_segment a b) (g has_vderiv_on g') (open_segment a b) ?x \<in> open_segment a b \<Longrightarrow> norm (f' ?x) \<le> g' ?x a < b [PROOF STEP] have "continuous_on {a .. b} f" and "continuous_on {a .. b} g" and "\<And>x. x\<in>{a<..<b} \<Longrightarrow> (f has_vector_derivative f' x) (at x)" and "\<And>x. x\<in>{a<..<b} \<Longrightarrow> (g has_vector_derivative g' x) (at x)" and "\<And>x. x\<in>{a<..<b} \<Longrightarrow> norm (f' x) \<le> g' x" [PROOF STATE] proof (prove) using this: continuous_on (closed_segment a b) f continuous_on (closed_segment a b) g (f has_vderiv_on f') (open_segment a b) (g has_vderiv_on g') (open_segment a b) ?x \<in> open_segment a b \<Longrightarrow> norm (f' ?x) \<le> g' ?x a < b goal (1 subgoal): 1. (continuous_on {a..b} f &&& continuous_on {a..b} g) &&& (\<And>x. x \<in> {a<..<b} \<Longrightarrow> (f has_vector_derivative f' x) (at x)) &&& (\<And>x. x \<in> {a<..<b} \<Longrightarrow> (g has_vector_derivative g' x) (at x)) &&& (\<And>x. x \<in> {a<..<b} \<Longrightarrow> norm (f' x) \<le> g' x) [PROOF STEP] by (auto simp: open_segment_eq_real_ivl closed_segment_eq_real_ivl has_vderiv_on_def at_within_open[where S="{a<..<b}"]) [PROOF STATE] proof (state) this: continuous_on {a..b} f continuous_on {a..b} g ?x \<in> {a<..<b} \<Longrightarrow> (f has_vector_derivative f' ?x) (at ?x) ?x \<in> {a<..<b} \<Longrightarrow> (g has_vector_derivative g' ?x) (at ?x) ?x \<in> {a<..<b} \<Longrightarrow> norm (f' ?x) \<le> g' ?x goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] from differentiable_bound_general[OF \<open>a < b\<close> this] [PROOF STATE] proof (chain) picking this: \<lbrakk>\<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}; \<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}; \<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}\<rbrakk> \<Longrightarrow> norm (f b - f a) \<le> g b - g a [PROOF STEP] have ?thesis [PROOF STATE] proof (prove) using this: \<lbrakk>\<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}; \<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}; \<And>x. \<lbrakk>a < x; x < b\<rbrakk> \<Longrightarrow> x \<in> {a<..<b}\<rbrakk> \<Longrightarrow> norm (f b - f a) \<le> g b - g a goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] by auto [PROOF STATE] proof (state) this: norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] } [PROOF STATE] proof (state) this: a < b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] moreover [PROOF STATE] proof (state) this: a < b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] { [PROOF STATE] proof (state) this: a < b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] assume "b < a" [PROOF STATE] proof (state) this: b < a goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] with assms [PROOF STATE] proof (chain) picking this: continuous_on (closed_segment a b) f continuous_on (closed_segment a b) g (f has_vderiv_on f') (open_segment a b) (g has_vderiv_on g') (open_segment a b) ?x \<in> open_segment a b \<Longrightarrow> norm (f' ?x) \<le> g' ?x b < a [PROOF STEP] have "continuous_on {b .. a} f" and "continuous_on {b .. a} g" and "\<And>x. x\<in>{b<..<a} \<Longrightarrow> (f has_vector_derivative f' x) (at x)" and "\<And>x. x\<in>{b<..<a} \<Longrightarrow> (g has_vector_derivative g' x) (at x)" and "\<And>x. x\<in>{b<..<a} \<Longrightarrow> norm (f' x) \<le> g' x" [PROOF STATE] proof (prove) using this: continuous_on (closed_segment a b) f continuous_on (closed_segment a b) g (f has_vderiv_on f') (open_segment a b) (g has_vderiv_on g') (open_segment a b) ?x \<in> open_segment a b \<Longrightarrow> norm (f' ?x) \<le> g' ?x b < a goal (1 subgoal): 1. (continuous_on {b..a} f &&& continuous_on {b..a} g) &&& (\<And>x. x \<in> {b<..<a} \<Longrightarrow> (f has_vector_derivative f' x) (at x)) &&& (\<And>x. x \<in> {b<..<a} \<Longrightarrow> (g has_vector_derivative g' x) (at x)) &&& (\<And>x. x \<in> {b<..<a} \<Longrightarrow> norm (f' x) \<le> g' x) [PROOF STEP] by (auto simp: open_segment_eq_real_ivl closed_segment_eq_real_ivl has_vderiv_on_def at_within_open[where S="{b<..<a}"]) [PROOF STATE] proof (state) this: continuous_on {b..a} f continuous_on {b..a} g ?x \<in> {b<..<a} \<Longrightarrow> (f has_vector_derivative f' ?x) (at ?x) ?x \<in> {b<..<a} \<Longrightarrow> (g has_vector_derivative g' ?x) (at ?x) ?x \<in> {b<..<a} \<Longrightarrow> norm (f' ?x) \<le> g' ?x goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] from differentiable_bound_general[OF \<open>b < a\<close> this] [PROOF STATE] proof (chain) picking this: \<lbrakk>\<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}; \<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}; \<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}\<rbrakk> \<Longrightarrow> norm (f a - f b) \<le> g a - g b [PROOF STEP] have "norm (f a - f b) \<le> g a - g b" [PROOF STATE] proof (prove) using this: \<lbrakk>\<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}; \<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}; \<And>x. \<lbrakk>b < x; x < a\<rbrakk> \<Longrightarrow> x \<in> {b<..<a}\<rbrakk> \<Longrightarrow> norm (f a - f b) \<le> g a - g b goal (1 subgoal): 1. norm (f a - f b) \<le> g a - g b [PROOF STEP] by simp [PROOF STATE] proof (state) this: norm (f a - f b) \<le> g a - g b goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] also [PROOF STATE] proof (state) this: norm (f a - f b) \<le> g a - g b goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] have "\<dots> \<le> abs (g b - g a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. g a - g b \<le> \<bar>g b - g a\<bar> [PROOF STEP] by simp [PROOF STATE] proof (state) this: g a - g b \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: norm (f a - f b) \<le> \<bar>g b - g a\<bar> [PROOF STEP] have ?thesis [PROOF STATE] proof (prove) using this: norm (f a - f b) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] by (simp add: norm_minus_commute) [PROOF STATE] proof (state) this: norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] } [PROOF STATE] proof (state) this: b < a \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: a = b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> a < b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> b < a \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: a = b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> a < b \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> b < a \<Longrightarrow> norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal (1 subgoal): 1. norm (f b - f a) \<le> \<bar>g b - g a\<bar> [PROOF STEP] by arith [PROOF STATE] proof (state) this: norm (f b - f a) \<le> \<bar>g b - g a\<bar> goal: No subgoals! [PROOF STEP] qed
lemma norm_of_real_addn [simp]: "norm (of_real x + numeral b :: 'a :: real_normed_div_algebra) = \<bar>x + numeral b\<bar>"
# -*- coding: utf-8 -*- import pandas as pd import numpy as np from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from scipy import stats from sklearn.preprocessing import MinMaxScaler #%% class PrepareData: def __init__(self, csvPath: str, predictLabel: str): self.dataFrame = pd.read_csv(csvPath, index_col="image_id") self.labeled = None self.jpgPaths = None self.converted = None self.scaled = None self.prepared = None self._labels = [ predictLabel, "@exif:ExposureTime", "@exif:ApertureValue", "@exif:ExposureProgram", "@exif:RecommendedExposureIndex", "@exif:MaxApertureValue", "@exif:MeteringMode", "@exif:FocalLength", "@exif:ExposureMode", "@exif:WhiteBalance", "@aux:LensID", "exif:ISOSpeedRatings:rdf:Seq:rdf:li", ] def prepare(self): self._pick() self._convert_fractions() self._scale() self._align() return self.prepared def reset_predict_label(self, newLabel: str): self._labels[0] = newLabel self.prepare() def _pick(self): self.labeled = self.dataFrame[self._labels] self.jpgPaths = self.dataFrame.jpg_save_path self.jpgPaths = self.jpgPaths.reset_index(inplace=False, level=0) def _convert_fractions(self): self.converted = self.labeled.applymap(self.frac_to_dec) self.converted = self.converted.fillna(0) def _scale(self): sc = MinMaxScaler(feature_range=(0,1)) scaledData = sc.fit_transform(self.converted[self._labels]) self.scaled = pd.DataFrame(scaledData) def _align(self): self.prepared = pd.concat([self.scaled, self.jpgPaths], axis=1) @staticmethod def frac_to_dec(s): if s == np.nan: return np.nan try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom) def loadPhoto(imgPath: str)-> list: image = load_img(imgPath, target_size=(224, 224)) image = img_to_array(image) return image def keras_apa_generator(dataArray: list, batch_size = 10): while True: # select random indexes(rows) for batch batch = dataArray[np.random.randint(0, dataArray.shape[0],batch_size)] batch_input = [] batch_output = [] batch_otherInput = [] for row in batch: #inputImg = loadPhoto(os.path.join(r"DATA/DIR" + dataArray[1,12])) inputImg = loadPhoto(row[14]) otherInput = row[1:12] outputValue = row[0] batch_input += [ inputImg ] batch_otherInput += [ otherInput ] batch_output += [ outputValue ] # Return a tuple of (input,output) to feed the network batch_other = np.array( batch_otherInput ) batch_x = np.array( batch_input ) batch_y = np.array( batch_output ) yield ({'image_input': batch_x , 'aux_input': batch_other}, {'prediction': batch_y})
! ################################################################### ! Copyright (c) 2013-2015, Marc De Graef/Carnegie Mellon University ! All rights reserved. ! ! Redistribution and use in source and binary forms, with or without modification, are ! permitted provided that the following conditions are met: ! ! - Redistributions of source code must retain the above copyright notice, this list ! of conditions and the following disclaimer. ! - Redistributions in binary form must reproduce the above copyright notice, this ! list of conditions and the following disclaimer in the documentation and/or ! other materials provided with the distribution. ! - Neither the names of Marc De Graef, Carnegie Mellon University nor the names ! of its contributors may be used to endorse or promote products derived from ! this software without specific prior written permission. ! ! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE ! USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ! ################################################################### !-------------------------------------------------------------------------- ! EMsoft:EMAverageOrient.f90 !-------------------------------------------------------------------------- ! ! PROGRAM: EMAverageOrient ! !> @author Marc De Graef, Carnegie Mellon University ! !> @brief create a ctf file with averaged orientations based on a dot product output file ! !> @date 06/24/16 MDG 1.0 original !> @date 07/06/16 MDG 1.1 replaced computation with call to EBSDgetAverageOrientations !-------------------------------------------------------------------------- program EMAverageOrient use local use typedefs use NameListTypedefs use NameListHandlers use files use constants use dictmod use io use error use ECPmod use EBSDiomod use EBSDmod use EBSDDImod use HDF5 use HDFsupport use rotations use Lambert use quaternions use stringconstants IMPLICIT NONE character(fnlen) :: nmldeffile, progname, progdesc type(AverageOrientationNameListType) :: enl type(EBSDIndexingNameListType) :: ebsdnl logical :: stat, readonly, noindex integer(kind=irg) :: hdferr, nlines, FZcnt, Nexp, nnm, nnk, Pmdims, i, j, k, olabel, Nd, Ne, ipar(10), & ipar2(6), pgnum, ipat character(fnlen) :: groupname, dataset, dpfile, energyfile, masterfile, efile, fname integer(HSIZE_T) :: dims2(2) real(kind=sgl) :: q1(4), q2(4), qus(4), a, oldmo, p(4), qsmall(4), theta, vec(3) type(dicttype) :: dict character(fnlen),allocatable :: stringarray(:) real(kind=sgl),allocatable :: Eulers(:,:), dplist(:,:), Eulerstmp(:,:), dplisttmp(:,:), avEuler(:,:), & resultmain(:,:), disor(:), disorient(:,:) integer(kind=irg),allocatable :: tmi(:,:), tmitmp(:,:), indexmain(:,:) type(HDFobjectStackType),pointer :: HDF_head nullify(HDF_head) nmldeffile = 'EMAverageOrient.nml' progname = 'EMAverageOrient.f90' progdesc = 'Generate a ctf file with averaged orientations' ! print some information call EMsoft(progname, progdesc) ! deal with the command line arguments, if any call Interpret_Program_Arguments(nmldeffile,1,(/ 81 /), progname) ! deal with the namelist stuff call GetAverageOrientationNameList(nmldeffile,enl) !==================================== ! read the relevant fields from the dot product HDF5 file ! open the fortran HDF interface call h5open_EMsoft(hdferr) dpfile = trim(EMsoft_getEMdatapathname())//trim(enl%dotproductfile) dpfile = EMsoft_toNativePath(dpfile) ! is this a proper HDF5 file ? call h5fis_hdf5_f(trim(dpfile), stat, hdferr) if (stat) then ! open the dot product file readonly = .TRUE. hdferr = HDF_openFile(dpfile, HDF_head, readonly) if (enl%oldformat.eqv..TRUE.) then dataset = SC_FZcnt call HDF_readDatasetInteger(dataset, HDF_head, hdferr, FZcnt) dataset = SC_NumExptPatterns call HDF_readDatasetInteger(dataset, HDF_head, hdferr, Nexp) dataset = SC_PointGroupNumber call HDF_readDatasetInteger(dataset, HDF_head, hdferr, pgnum) dataset = SC_EulerAngles call HDF_readDatasetFloatArray2D(dataset, dims2, HDF_head, hdferr, Eulerstmp) allocate(Eulers(3,FZcnt)) do i=1,FZcnt Eulers(1:3,i) = Eulerstmp(1:3,i) end do deallocate(Eulerstmp) Eulers = Eulers * sngl(cPi)/180.0 dataset = SC_DotProducts call HDF_readDatasetFloatArray2D(dataset, dims2, HDF_head, hdferr, dplisttmp) !allocate(dplist(dims2(1),Nexp)) allocate(dplist(enl%nmuse,Nexp)) do i=1,Nexp dplist(1:enl%nmuse,i) = dplisttmp(1:enl%nmuse,i) end do deallocate(dplisttmp) nnm = enl%nmuse dataset = SC_Indices call HDF_readDatasetIntegerArray2D(dataset, dims2, HDF_head, hdferr, tmitmp) allocate(tmi(nnm,Nexp)) do i=1,Nexp tmi(1:nnm,i) = tmitmp(1:nnm,i) end do deallocate(tmitmp) else ! this file has the new internal format (after ~ April 2016) ! get the energyfile and masterfile parameters from NMLParameters groupname = SC_NMLparameters hdferr = HDF_openGroup(groupname, HDF_head) groupname = SC_EBSDIndexingNameListType hdferr = HDF_openGroup(groupname, HDF_head) dataset = SC_energyfile call HDF_readDatasetStringArray(dataset, nlines, HDF_head, hdferr, stringarray) energyfile = trim(stringarray(1)) deallocate(stringarray) dataset = SC_masterfile call HDF_readDatasetStringArray(dataset, nlines, HDF_head, hdferr, stringarray) masterfile = trim(stringarray(1)) deallocate(stringarray) dataset = SC_nnk call HDF_readDatasetInteger(dataset, HDF_head, hdferr, nnk) dataset = SC_ipfwd call HDF_readDatasetInteger(dataset, HDF_head, hdferr, ebsdnl%ipf_wd) dataset = SC_ipfht call HDF_readDatasetInteger(dataset, HDF_head, hdferr, ebsdnl%ipf_ht) ! dataset = 'StepX' ! call HDF_readDatasetFloat(dataset, HDF_head, hdferr, ebsdnl%StepX) ! dataset = 'StepY' ! call HDF_readDatasetFloat(dataset, HDF_head, hdferr, ebsdnl%StepY) ! and close the NMLparameters group call HDF_pop(HDF_head) call HDF_pop(HDF_head) ! open the Scan 1/EBSD/Data group groupname = SC_Scan1 hdferr = HDF_openGroup(groupname, HDF_head) groupname = SC_EBSD hdferr = HDF_openGroup(groupname, HDF_head) groupname = SC_Data hdferr = HDF_openGroup(groupname, HDF_head) ! integers dataset = SC_FZcnt call HDF_readDatasetInteger(dataset, HDF_head, hdferr, FZcnt) dataset = SC_NumExptPatterns call HDF_readDatasetInteger(dataset, HDF_head, hdferr, Nexp) ! arrays dataset = SC_EulerAngles call HDF_readDatasetFloatArray2D(dataset, dims2, HDF_head, hdferr, Eulerstmp) allocate(Eulers(3,FZcnt)) do i=1,FZcnt Eulers(1:3,i) = Eulerstmp(1:3,i) end do deallocate(Eulerstmp) Eulers = Eulers * sngl(cPi)/180.0 dataset = SC_TopDotProductList call HDF_readDatasetFloatArray2D(dataset, dims2, HDF_head, hdferr, dplisttmp) allocate(dplist(dims2(1),Nexp)) do i=1,Nexp dplist(1:dims2(1),i) = dplisttmp(1:dims2(1),i) end do deallocate(dplisttmp) nnm = dims2(1) dataset = SC_TopMatchIndices call HDF_readDatasetIntegerArray2D(dataset, dims2, HDF_head, hdferr, tmitmp) allocate(tmi(nnm,Nexp)) do i=1,Nexp tmi(1:nnm,i) = tmitmp(1:nnm,i) end do deallocate(tmitmp) end if call HDF_pop(HDF_head,.TRUE.) ! close the fortran HDF interface call h5close_EMsoft(hdferr) call Message('dot product HDF5 file read') else dpfile = 'File '//trim(dpfile)//' is not an HDF5 file' call FatalError('EMAverageOrient',dpfile) end if if (enl%oldformat.eqv..FALSE.) then !=================================== ! we will also need some of the crystallographic data, so that requires ! extracting the xtalname from the energyfile efile = trim(EMsoft_getEMdatapathname())//trim(energyfile) efile = EMsoft_toNativePath(efile) ! first, we need to check whether or not the input file is of the HDF5 format type; if ! it is, we read it accordingly, otherwise we use the old binary format. ! call h5fis_hdf5_f(efile, stat, hdferr) if (stat) then ! open the fortran HDF interface call h5open_EMsoft(hdferr) nullify(HDF_head) ! open the MC file using the default properties. readonly = .TRUE. hdferr = HDF_openFile(efile, HDF_head, readonly) ! open the namelist group groupname = SC_NMLparameters hdferr = HDF_openGroup(groupname, HDF_head) groupname = SC_MCCLNameList hdferr = HDF_openGroup(groupname, HDF_head) ! read all the necessary variables from the namelist group dataset = SC_xtalname call HDF_readDatasetStringArray(dataset, nlines, HDF_head, hdferr, stringarray) ebsdnl%MCxtalname = trim(stringarray(1)) deallocate(stringarray) dataset = SC_EkeV call HDF_readDatasetDouble(dataset, HDF_head, hdferr, ebsdnl%EkeV) dataset = SC_sig call HDF_readDatasetDouble(dataset, HDF_head, hdferr, ebsdnl%MCsig) call HDF_pop(HDF_head,.TRUE.) ! close the fortran HDF interface call h5close_EMsoft(hdferr) call Message('energy file read') else efile = 'File '//trim(efile)//' is not an HDF5 file' call FatalError('EMAverageOrient',efile) end if pgnum = GetPointGroup(ebsdnl%MCxtalname) end if ! do the actual orientational averaging allocate(avEuler(3,Nexp),disorient(Nexp,enl%nmuse)) ipar2(1) = pgnum ipar2(2) = FZcnt ipar2(3) = Nexp if (enl%oldformat) then ipar2(4) = enl%nmuse ipar2(5) = Nexp else ipar2(4) = nnk ipar2(5) = Nexp*ceiling(float(ebsdnl%ipf_wd*ebsdnl%ipf_ht)/float(Nexp)) end if ipar2(6) = enl%nmuse call EBSDgetAverageOrientations(ipar2, Eulers, tmi, dplist, avEuler,disorient) open(unit=dataunit,file='disorient.data',status='unknown',form='unformatted') write(dataunit) nnm, Nexp, enl%nmuse write(dataunit) dplist write(dataunit) disorient close(unit=dataunit,status='keep') if (enl%oldformat.eqv..FALSE.) then ! ok, so we have our list; next we need to store this in a ctf file, along with ! all the other crystallographic information, so we need to fill in the proper ! fields in the ebsdnl structure and ipar array. ipar = 0 ipar(1) = 1 ipar(2) = Nexp ipar(3) = Nexp ipar(4) = Nexp ipar(5) = FZcnt ipar(6) = pgnum ebsdnl%ctffile = enl%averagectffile allocate(indexmain(1,Nexp), resultmain(1,Nexp)) indexmain = 0 resultmain(1,1:Nexp) = dplist(1,1:Nexp) noindex = .TRUE. call h5open_EMsoft(hdferr) call ctfebsd_writeFile(ebsdnl,ipar,indexmain,avEuler,resultmain,noindex) call h5close_EMsoft(hdferr) call Message('Data stored in ctf file : '//trim(enl%averagectffile)) else ! we need to store the result in a simple text file... fname = trim(EMsoft_getEMdatapathname())//trim(enl%averagetxtfile) fname = EMsoft_toNativePath(fname) open(unit=dataunit,file=trim(fname),status='unknown',form='formatted') write (dataunit,"(A2)") 'eu' write (dataunit,"(I10)") Nexp do i=1,Nexp write(dataunit,"(3F13.6)") avEuler(1:3,i) end do close(unit=dataunit,status='keep') call Message('Data stored in txt file : '//trim(enl%averagetxtfile)) end if ! do we need to produce a relative disorientation map ? if (trim(enl%disorientationmap).ne.'undefined') then !=================================== ! set up the symmetry quaternions for this rotational symmetry ! allocate the dict structure dict%Num_of_init = 3 dict%Num_of_iterations = 30 dict%pgnum = pgnum ! initialize the symmetry matrices call DI_Init(dict,'nil') ! put the Euler angles back in radians avEuler = avEuler * sngl(cPi)/180.0 ! get the 1D point coordinate ipat = ebsdnl%ipf_wd * enl%reldisy + enl%reldisx write (*,*) 'position of fixed point = ',enl%reldisx,enl%reldisy allocate(disor(Nexp)) ! and get the disorientations w.r.t. all the others do j=1,Nexp call getDisorientationAngle(avEuler(1:3,ipat),avEuler(1:3,j),dict,oldmo) disor(j) = oldmo end do disor = disor*180.0/sngl(cPi) open(unit=dataunit,file=trim(enl%disorientationmap),status='unknown',form='formatted') write (dataunit,"(3I10)") Nexp, ebsdnl%ipf_wd, ebsdnl%ipf_ht do i=1,Nexp write(dataunit,"(F13.6)") disor(i) end do close(unit=dataunit,status='keep') end if ! average dot-product vs. average disorientation plot? end program EMAverageOrient
/- ** Inference rules ** -/ /- So how do we decide whether a given proposition can be judged to be true or not? Here is where the semantics of a logic come into play. The semantics of a logic comprises a set of rules, called inference rules, that define the conditions under which a given proposition can be judged to be true. Oversimplifying a bit, if you can apply one or more inference rules to propositions you already know to be true, and if by doing this you "deduce" some new proposition, then you can conclude that that new proposition must also be true. Such a "chain" of inference rules, linking things already known to be true to propositions that you want to prove to be true because they follow logically is called a proof. A valid proof is incontrovertible evidence that the final proposition is true. An inference rule is like a little program: it says, if you can give me evidence (i.e., proofs) showing that certain "input" propositions can be judged to be true, then I will hand you back evidence (i.e., a proof) that shows that some new proposition can also be judged to be true. We would say that from the proofs of the premises (the input propositions already known to be true), the rule derives or deduces a proof of the conclusion. Logicians often write inference rules like this: list of input truth judgments ----------------------------- (name-of-rule) truth judgment for conclusion The required input judgments, called premises (or antecedents), are listed above the line. The name of the rule is given to the right of the line. And the proposition (or consequent) that can thereby be judged to be true (the conclusion of the rule) is written below the line. For example, if we already have the truth judgment, (0 = 0 : true), and another, (1 = 1: true), then the inference rule that logicians call "and introduction" (or "conjunction introduction") can be used to derive a truth judgment for the new proposition, "0 = 0 and 1 = 1", typically written as 0 = 0 ∧ 1 = 1. (Hover your mouse over special symbols in this editor to learn how to use them in your work.) Predicate logic will thus (in effect) include such inference rules as this: 0 = 0 : true, 1 = 1 : true -------------------------- and-introduction-* 0 = 0 ∧ 1 = 1 This can be pronounced as, "If you already have evidence (a proof) supporting the judgment that 0 = 0 is true, and if you also have evidence (a proof) supporting the judgment that 1 = 1 is true, then by applying the and-introduction-* rule, you can deduce (obtain a proof justifying a truth judgment for) the proposition, 0 = 0 ∧ 1 = 1". We've put a * on the name of this rule to indicate that it's really just a special case of a far more general inference rule for reasoning about equality. Inference rules are usually written not in terms of very specific propositions, such as 0 = 0, but in terms of variables that can refer to any arbitrary propositions. They are often called meta-variables. In this way, inference rules become program-like, in that they can take arbitrary inputs (of the correct types), and whenever they are given such inputs, they produce result of a promised type. Here's a simple example of such a parameterized and thereby generalized rule. If P is *any* proposition (e.g., it could be 0 = 0 but might be some other proposition), and Q is another proposition (e.g., 1 = 1), and if both propositions are already known to be true, then you can always conclude that the proposition "P and Q", written P ∧ Q, must also be true, for whatever propositions P and Q happen to be. Here is how the general form of this inference rule would typically be written in a book on logic. P : true, Q : true ------------------ (and.intro) P ∧ Q : true The inference rule is called "and introduction" because it produces a proof of a proposition that now contains an "and" (∧). The rule can be read as follows. If P and Q are propositions, and if you have judged P to be true and you have judged Q to be true, then you can judge P ∧ Q to be true. -/
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) theory IpcCancel_AI imports "./$L4V_ARCH/ArchSchedule_AI" begin context begin interpretation Arch . requalify_facts arch_post_cap_deletion_pred_tcb_at end declare arch_post_cap_deletion_pred_tcb_at[wp] lemma blocked_cancel_ipc_simple: "\<lbrace>tcb_at t\<rbrace> blocked_cancel_ipc ts t \<lbrace>\<lambda>rv. st_tcb_at simple t\<rbrace>" by (simp add: blocked_cancel_ipc_def | wp sts_st_tcb_at')+ lemma cancel_signal_simple: "\<lbrace>\<top>\<rbrace> cancel_signal t ntfn \<lbrace>\<lambda>rv. st_tcb_at simple t\<rbrace>" by (simp add: cancel_signal_def | wp sts_st_tcb_at')+ crunch typ_at: cancel_all_ipc "\<lambda>s. P (typ_at T p s)" (wp: crunch_wps mapM_x_wp) lemma cancel_all_helper: " \<lbrace>valid_objs and (\<lambda>s. \<forall>t \<in> set queue. st_tcb_at (\<lambda>st. \<not> halted st) t s) \<rbrace> mapM_x (\<lambda>t. do y \<leftarrow> set_thread_state t Structures_A.Restart; do_extended_op (tcb_sched_enqueue_ext t) od) queue \<lbrace>\<lambda>rv. valid_objs\<rbrace>" apply (rule hoare_strengthen_post) apply (rule mapM_x_wp [where S="set queue", simplified]) apply (wp, simp, wp hoare_vcg_const_Ball_lift sts_st_tcb_at_cases, simp) apply (clarsimp elim: pred_tcb_weakenE) apply (erule(1) my_BallE) apply (clarsimp simp: st_tcb_def2) apply (frule(1) valid_tcb_objs) apply (clarsimp simp: valid_tcb_def valid_tcb_state_def cte_wp_at_cases tcb_cap_cases_def dest!: get_tcb_SomeD) apply simp+ done lemma cancel_all_ipc_valid_objs: "\<lbrace>valid_objs and (\<lambda>s. sym_refs (state_refs_of s))\<rbrace> cancel_all_ipc ptr \<lbrace>\<lambda>_. valid_objs\<rbrace>" apply (simp add: cancel_all_ipc_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (case_tac ep, simp_all add: get_ep_queue_def) apply (wp, simp) apply (wp cancel_all_helper hoare_vcg_const_Ball_lift | clarsimp simp: ep_queued_st_tcb_at obj_at_def valid_ep_def)+ done crunch typ_at: cancel_all_signals "\<lambda>s. P (typ_at T p s)" (wp: crunch_wps mapM_x_wp) lemma unbind_notification_valid_objs_helper: "valid_ntfn ntfn s \<longrightarrow> valid_ntfn (ntfn_set_bound_tcb ntfn None) s " by (clarsimp simp: valid_bound_tcb_def valid_ntfn_def split: option.splits ntfn.splits) lemma unbind_notification_valid_objs: "\<lbrace>valid_objs\<rbrace> unbind_notification ptr \<lbrace>\<lambda>rv. valid_objs\<rbrace>" unfolding unbind_notification_def apply (wp thread_set_valid_objs_triv set_simple_ko_valid_objs hoare_drop_imp | wpc | simp add: tcb_cap_cases_def | strengthen unbind_notification_valid_objs_helper)+ apply (wp thread_get_wp' | simp add:get_bound_notification_def)+ apply (clarsimp) apply (erule (1) obj_at_valid_objsE) apply (clarsimp simp:valid_obj_def valid_tcb_def)+ done lemma cancel_all_signals_valid_objs: "\<lbrace>valid_objs and (\<lambda>s. sym_refs (state_refs_of s))\<rbrace> cancel_all_signals ptr \<lbrace>\<lambda>rv. valid_objs\<rbrace>" apply (simp add: cancel_all_signals_def unbind_maybe_notification_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (rule hoare_pre) apply (wp unbind_notification_valid_objs | wpc | simp_all add:unbind_maybe_notification_def)+ apply (wp cancel_all_helper hoare_vcg_const_Ball_lift set_simple_ko_valid_objs unbind_notification_valid_objs | clarsimp simp: ntfn_queued_st_tcb_at obj_at_def valid_ntfn_def valid_bound_tcb_def | wpc)+ apply (clarsimp split: option.splits) apply (erule (1) valid_objsE) apply (simp add: valid_obj_def valid_ntfn_def) done lemma get_ep_queue_inv[wp]: "\<lbrace>P\<rbrace> get_ep_queue ep \<lbrace>\<lambda>_. P\<rbrace>" by (cases ep, simp_all add: get_ep_queue_def) lemma cancel_all_ipc_st_tcb_at: assumes x[simp]: "P Structures_A.Restart" shows "\<lbrace>st_tcb_at P t\<rbrace> cancel_all_ipc epptr \<lbrace>\<lambda>rv. st_tcb_at P t\<rbrace>" unfolding cancel_all_ipc_def by (wp ep_cases_weak_wp mapM_x_wp' sts_st_tcb_at_cases | simp)+ lemmas cancel_all_ipc_makes_simple[wp] = cancel_all_ipc_st_tcb_at[where P=simple, simplified] lemma unbind_notification_st_tcb_at[wp]: "\<lbrace>st_tcb_at P t\<rbrace> unbind_notification t' \<lbrace>\<lambda>rv. st_tcb_at P t\<rbrace>" unfolding unbind_notification_def by (wp thread_set_no_change_tcb_state hoare_drop_imps | wpc | simp)+ lemma unbind_maybe_notification_st_tcb_at[wp]: "\<lbrace>st_tcb_at P t\<rbrace> unbind_maybe_notification r \<lbrace>\<lambda>rv. st_tcb_at P t \<rbrace>" unfolding unbind_maybe_notification_def apply (rule hoare_pre) apply (wp thread_set_no_change_tcb_state hoare_drop_imps| wpc | simp)+ done lemma cancel_all_signals_st_tcb_at: assumes x[simp]: "P Structures_A.Restart" shows "\<lbrace>st_tcb_at P t\<rbrace> cancel_all_signals ntfnptr \<lbrace>\<lambda>rv. st_tcb_at P t\<rbrace>" unfolding cancel_all_signals_def unbind_maybe_notification_def by (wp ntfn_cases_weak_wp mapM_x_wp' sts_st_tcb_at_cases hoare_drop_imps unbind_notification_st_tcb_at | simp | wpc)+ lemmas cancel_all_signals_makes_simple[wp] = cancel_all_signals_st_tcb_at[where P=simple, simplified] lemma get_blocking_object_inv[wp]: "\<lbrace>P\<rbrace> get_blocking_object st \<lbrace>\<lambda>_. P\<rbrace>" by (cases st, simp_all add: get_blocking_object_def) lemma blocked_ipc_st_tcb_at_general: "\<lbrace>st_tcb_at P t' and K (t = t' \<longrightarrow> P Structures_A.Inactive)\<rbrace> blocked_cancel_ipc st t \<lbrace>\<lambda>rv. st_tcb_at P t'\<rbrace>" apply (simp add: blocked_cancel_ipc_def) apply (wp sts_st_tcb_at_cases static_imp_wp, simp+) done lemma cancel_signal_st_tcb_at_general: "\<lbrace>st_tcb_at P t' and K (t = t' \<longrightarrow> (P Structures_A.Running \<and> P Structures_A.Inactive))\<rbrace> cancel_signal t ntfn \<lbrace>\<lambda>rv. st_tcb_at P t'\<rbrace>" apply (simp add: cancel_signal_def) apply (wp sts_st_tcb_at_cases ntfn_cases_weak_wp static_imp_wp) apply simp done lemma fast_finalise_misc[wp]: "\<lbrace>st_tcb_at simple t \<rbrace> fast_finalise a b \<lbrace>\<lambda>_. st_tcb_at simple t\<rbrace>" apply (case_tac a,simp_all) apply (wp|clarsimp)+ done locale IpcCancel_AI = fixes state_ext :: "('a::state_ext) itself" assumes arch_post_cap_deletion_typ_at[wp]: "\<And>P T p acap. \<lbrace>\<lambda>(s :: 'a state). P (typ_at T p s)\<rbrace> arch_post_cap_deletion acap \<lbrace>\<lambda>rv s. P (typ_at T p s)\<rbrace>" assumes arch_post_cap_deletion_idle_thread[wp]: "\<And>P acap. \<lbrace>\<lambda>(s :: 'a state). P (idle_thread s)\<rbrace> arch_post_cap_deletion acap \<lbrace>\<lambda>rv s. P (idle_thread s)\<rbrace>" crunches update_restart_pc for typ_at[wp]: "\<lambda>s. P (typ_at ty ptr s)" (* NB: Q needed for following has_reply_cap proof *) and cte_wp_at[wp]: "\<lambda>s. Q (cte_wp_at P cte s)" and idle_thread[wp]: "\<lambda>s. P (idle_thread s)" and pred_tcb_at[wp]: "\<lambda>s. pred_tcb_at P proj tcb s" and invs[wp]: "\<lambda>s. invs s" lemma update_restart_pc_has_reply_cap[wp]: "\<lbrace>\<lambda>s. \<not> has_reply_cap t s\<rbrace> update_restart_pc t \<lbrace>\<lambda>_ s. \<not> has_reply_cap t s\<rbrace>" apply (simp add: has_reply_cap_def) apply (wp hoare_vcg_all_lift) done crunch st_tcb_at_simple[wp]: reply_cancel_ipc "st_tcb_at simple t" (wp: crunch_wps select_wp sts_st_tcb_at_cases thread_set_no_change_tcb_state simp: crunch_simps unless_def fast_finalise.simps) lemma cancel_ipc_simple [wp]: "\<lbrace>\<top>\<rbrace> cancel_ipc t \<lbrace>\<lambda>rv. st_tcb_at simple t\<rbrace>" apply (simp add: cancel_ipc_def) apply (rule hoare_seq_ext [OF _ gts_sp]) apply (case_tac state, simp_all) apply (wp hoare_strengthen_post [OF blocked_cancel_ipc_simple] hoare_strengthen_post [OF cancel_signal_simple] hoare_strengthen_post [OF reply_cancel_ipc_st_tcb_at_simple [where t=t]] sts_st_tcb_at_cases hoare_drop_imps | clarsimp elim!: pred_tcb_weakenE pred_tcb_at_tcb_at)+ done lemma blocked_cancel_ipc_typ_at[wp]: "\<lbrace>\<lambda>s. P (typ_at T p s)\<rbrace> blocked_cancel_ipc st t \<lbrace>\<lambda>rv s. P (typ_at T p s)\<rbrace>" apply (simp add: blocked_cancel_ipc_def get_blocking_object_def get_ep_queue_def get_simple_ko_def) apply (wp get_object_wp|wpc)+ apply simp done lemma blocked_cancel_ipc_tcb_at [wp]: "\<lbrace>tcb_at t\<rbrace> blocked_cancel_ipc st t' \<lbrace>\<lambda>rv. tcb_at t\<rbrace>" by (simp add: tcb_at_typ) wp context IpcCancel_AI begin crunch typ_at[wp]: cancel_ipc, reply_cancel_ipc, unbind_maybe_notification "\<lambda>(s :: 'a state). P (typ_at T p s)" (wp: crunch_wps hoare_vcg_if_splitE select_wp simp: crunch_simps unless_def) lemma cancel_ipc_tcb [wp]: "\<lbrace>tcb_at t\<rbrace> cancel_ipc t' \<lbrace>\<lambda>rv. (tcb_at t) :: 'a state \<Rightarrow> bool\<rbrace>" by (simp add: tcb_at_typ) wp end lemma gbep_ret: "\<lbrakk> st = Structures_A.BlockedOnReceive epPtr pl' \<or> st = Structures_A.BlockedOnSend epPtr pl \<rbrakk> \<Longrightarrow> get_blocking_object st = return epPtr" by (auto simp add: get_blocking_object_def) lemma st_tcb_at_valid_st2: "\<lbrakk> st_tcb_at ((=) st) t s; valid_objs s \<rbrakk> \<Longrightarrow> valid_tcb_state st s" apply (clarsimp simp add: valid_objs_def get_tcb_def pred_tcb_at_def obj_at_def) apply (drule_tac x=t in bspec) apply (erule domI) apply (simp add: valid_obj_def valid_tcb_def) done definition "emptyable \<equiv> \<lambda>p s. (tcb_at (fst p) s \<and> snd p = tcb_cnode_index 2) \<longrightarrow> st_tcb_at halted (fst p) s" locale delete_one_abs = IpcCancel_AI state_ext for state_ext :: "('a :: state_ext) itself" + assumes delete_one_invs: "\<And>p. \<lbrace>invs and emptyable p\<rbrace> (cap_delete_one p :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. invs\<rbrace>" assumes delete_one_deletes: "\<lbrace>\<top>\<rbrace> (cap_delete_one sl :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. cte_wp_at (\<lambda>c. c = cap.NullCap) sl\<rbrace>" assumes delete_one_caps_of_state: "\<And>P p. \<lbrace>\<lambda>s. cte_wp_at can_fast_finalise p s \<longrightarrow> P ((caps_of_state s) (p \<mapsto> cap.NullCap))\<rbrace> (cap_delete_one p :: (unit,'a) s_monad) \<lbrace>\<lambda>rv s. P (caps_of_state s)\<rbrace>" lemma reply_master_no_descendants_no_reply: "\<lbrakk> valid_mdb s; valid_reply_masters s; tcb_at t s \<rbrakk> \<Longrightarrow> descendants_of (t, tcb_cnode_index 2) (cdt s) = {} \<longrightarrow> \<not> has_reply_cap t s" by (fastforce simp: invs_def valid_state_def valid_mdb_def has_reply_cap_def cte_wp_at_caps_of_state reply_mdb_def is_reply_cap_to_def reply_caps_mdb_def descendants_of_def cdt_parent_defs dest: reply_master_caps_of_stateD tranclD) lemma reply_cap_unique_descendant: "\<lbrakk> invs s; tcb_at t s \<rbrakk> \<Longrightarrow> \<forall>sl\<in>descendants_of (t, tcb_cnode_index 2) (cdt s). \<forall>sl'. sl' \<noteq> sl \<longrightarrow> sl' \<notin> descendants_of (t, tcb_cnode_index 2) (cdt s)" apply (subgoal_tac "cte_wp_at (\<lambda>c. (is_master_reply_cap c \<and> obj_ref_of c = t) \<or> c = cap.NullCap) (t, tcb_cnode_index 2) s") apply (clarsimp simp: invs_def valid_state_def valid_mdb_def2 is_cap_simps valid_reply_caps_def cte_wp_at_caps_of_state) apply (erule disjE) apply (fastforce simp: reply_mdb_def is_cap_simps dest: unique_reply_capsD) apply (fastforce dest: mdb_cte_at_Null_descendants) apply (clarsimp simp: tcb_cap_wp_at invs_valid_objs tcb_cap_cases_def is_cap_simps) done lemma reply_master_one_descendant: "\<lbrakk> invs s; tcb_at t s; descendants_of (t, tcb_cnode_index 2) (cdt s) \<noteq> {} \<rbrakk> \<Longrightarrow> \<exists>sl. descendants_of (t, tcb_cnode_index 2) (cdt s) = {sl}" by (fastforce elim: construct_singleton dest: reply_cap_unique_descendant) lemma ep_redux_simps2: "ep \<noteq> Structures_A.IdleEP \<Longrightarrow> valid_ep (case xs of [] \<Rightarrow> Structures_A.endpoint.IdleEP | a # list \<Rightarrow> update_ep_queue ep xs) = (\<lambda>s. distinct xs \<and> (\<forall>t\<in>set xs. tcb_at t s))" "ep \<noteq> Structures_A.IdleEP \<Longrightarrow> ep_q_refs_of (case xs of [] \<Rightarrow> Structures_A.endpoint.IdleEP | a # list \<Rightarrow> update_ep_queue ep xs) = (set xs \<times> {case ep of Structures_A.SendEP xs \<Rightarrow> EPSend | Structures_A.RecvEP xs \<Rightarrow> EPRecv})" by (cases ep, simp_all cong: list.case_cong add: ep_redux_simps)+ lemma gbi_ep_sp: "\<lbrace>P\<rbrace> get_blocking_object st \<lbrace>\<lambda>ep. P and K ((\<exists>d. st = Structures_A.BlockedOnReceive ep d) \<or> (\<exists>d. st = Structures_A.BlockedOnSend ep d))\<rbrace>" apply (cases st, simp_all add: get_blocking_object_def) apply (wp | simp)+ done lemma get_epq_sp: "\<lbrace>P\<rbrace> get_ep_queue ep \<lbrace>\<lambda>q. P and K (ep \<in> {Structures_A.SendEP q, Structures_A.RecvEP q})\<rbrace>" apply (simp add: get_ep_queue_def) apply (cases ep) apply (wp|simp)+ done lemma refs_in_tcb_bound_refs: "(x, ref) \<in> tcb_bound_refs ntfn \<Longrightarrow> ref = TCBBound" by (auto simp: tcb_bound_refs_def split: option.splits) lemma refs_in_ntfn_bound_refs: "(x, ref) \<in> ntfn_bound_refs tcb \<Longrightarrow> ref = NTFNBound" by (auto simp: ntfn_bound_refs_def split: option.splits) lemma blocked_cancel_ipc_invs: "\<lbrace>invs and st_tcb_at ((=) st) t\<rbrace> blocked_cancel_ipc st t \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: blocked_cancel_ipc_def) apply (rule hoare_seq_ext [OF _ gbi_ep_sp]) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (rule hoare_seq_ext [OF _ get_epq_sp]) apply (simp add: invs_def valid_state_def valid_pspace_def) apply (rule hoare_pre, wp valid_irq_node_typ sts_only_idle) apply (simp add: valid_tcb_state_def) apply (strengthen reply_cap_doesnt_exist_strg) apply simp apply (wp valid_irq_node_typ valid_ioports_lift) apply (subgoal_tac "ep \<noteq> Structures_A.IdleEP") apply (clarsimp simp: ep_redux_simps2 cong: if_cong) apply (frule(1) if_live_then_nonz_capD, (clarsimp simp: live_def)+) apply (frule ko_at_state_refs_ofD) apply (erule(1) obj_at_valid_objsE, clarsimp simp: valid_obj_def) apply (frule st_tcb_at_state_refs_ofD) apply (subgoal_tac "epptr \<notin> set (remove1 t queue)") apply (case_tac ep, simp_all add: valid_ep_def)[1] apply (auto elim!: delta_sym_refs pred_tcb_weaken_strongerE simp: obj_at_def is_ep_def2 idle_not_queued refs_in_tcb_bound_refs dest: idle_no_refs split: if_split_asm)[2] apply (case_tac ep, simp_all add: valid_ep_def)[1] apply (clarsimp, drule(1) bspec, clarsimp simp: obj_at_def is_tcb_def)+ apply fastforce done lemma symreftype_inverse': "symreftype ref = ref' \<Longrightarrow> ref = symreftype ref'" by (cases ref) simp_all lemma cancel_signal_invs: "\<lbrace>invs and st_tcb_at ((=) (Structures_A.BlockedOnNotification ntfn)) t\<rbrace> cancel_signal t ntfn \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: cancel_signal_def invs_def valid_state_def valid_pspace_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (case_tac "ntfn_obj ntfna", simp_all)[1] apply (rule hoare_pre) apply (wp set_simple_ko_valid_objs valid_irq_node_typ sts_only_idle valid_ioports_lift | simp add: valid_tcb_state_def | strengthen reply_cap_doesnt_exist_strg | wpc)+ apply (clarsimp simp: ep_redux_simps cong: list.case_cong if_cong) apply (frule(1) if_live_then_nonz_capD, (clarsimp simp: live_def)+) apply (frule ko_at_state_refs_ofD) apply (frule st_tcb_at_state_refs_ofD) apply (erule(1) obj_at_valid_objsE, clarsimp simp: valid_obj_def valid_ntfn_def) apply (case_tac ntfna) apply clarsimp apply (rule conjI) apply (clarsimp simp: pred_tcb_at_def obj_at_def) apply clarsimp apply (rule conjI) apply (clarsimp split:option.split) apply (rule conjI, erule delta_sym_refs) apply (clarsimp split: if_split_asm)+ apply (fastforce dest: refs_in_tcb_bound_refs refs_in_ntfn_bound_refs symreftype_inverse') apply (fastforce simp: obj_at_def is_ntfn idle_not_queued dest: idle_no_refs elim: pred_tcb_weakenE) done lemma reply_mdb_cte_at_master_None: "\<lbrakk> reply_mdb m cs; mdb_cte_at (\<lambda>p. \<exists>c. cs p = Some c \<and> cap.NullCap \<noteq> c) m; cs ptr = Some cap; is_master_reply_cap cap \<rbrakk> \<Longrightarrow> m ptr = None" unfolding reply_mdb_def reply_masters_mdb_def by (fastforce simp: is_cap_simps) lemma reply_slot_not_descendant: "\<And>ptr. \<lbrakk> invs s; tcb_at t s \<rbrakk> \<Longrightarrow> (t, tcb_cnode_index 2) \<notin> descendants_of ptr (cdt s)" apply (subgoal_tac "cte_wp_at (\<lambda>c. is_master_reply_cap c \<or> c = cap.NullCap) (t, tcb_cnode_index 2) s") apply (fastforce simp: invs_def valid_state_def valid_mdb_def2 cte_wp_at_caps_of_state dest: reply_mdb_cte_at_master_None mdb_cte_at_Null_None descendants_of_NoneD) apply (clarsimp simp: tcb_cap_wp_at invs_valid_objs tcb_cap_cases_def) done lemma reply_cancel_ipc_invs: assumes delete: "\<And>p. \<lbrace>invs and emptyable p\<rbrace> (cap_delete_one p :: (unit,'z::state_ext) s_monad) \<lbrace>\<lambda>rv. invs\<rbrace>" shows "\<lbrace>invs\<rbrace> (reply_cancel_ipc t :: (unit,'z::state_ext) s_monad) \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: reply_cancel_ipc_def) apply (wp delete select_wp) apply (rule_tac Q="\<lambda>rv. invs" in hoare_post_imp) apply (fastforce simp: emptyable_def dest: reply_slot_not_descendant) apply (wp thread_set_invs_trivial) apply (auto simp: tcb_cap_cases_def)+ done lemma (in delete_one_abs) cancel_ipc_invs[wp]: "\<lbrace>invs\<rbrace> (cancel_ipc t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: cancel_ipc_def) apply (rule hoare_seq_ext [OF _ gts_sp]) apply (case_tac state, simp_all) apply (auto intro!: hoare_weaken_pre [OF return_wp] hoare_weaken_pre [OF blocked_cancel_ipc_invs] hoare_weaken_pre [OF cancel_signal_invs] hoare_weaken_pre [OF reply_cancel_ipc_invs] delete_one_invs elim!: pred_tcb_weakenE) done context IpcCancel_AI begin lemma cancel_ipc_valid_cap: "\<lbrace>valid_cap c\<rbrace> cancel_ipc p \<lbrace>\<lambda>_. (valid_cap c) :: 'a state \<Rightarrow> bool\<rbrace>" by (wp valid_cap_typ) lemma cancel_ipc_cte_at[wp]: "\<lbrace>cte_at p\<rbrace> cancel_ipc t \<lbrace>\<lambda>_. (cte_at p) :: 'a state \<Rightarrow> bool\<rbrace>" by (wp valid_cte_at_typ) end lemma valid_ep_queue_subset: "\<lbrace>\<lambda>s. valid_ep ep s\<rbrace> get_ep_queue ep \<lbrace>\<lambda>queue s. valid_ep (case (remove1 t queue) of [] \<Rightarrow> Structures_A.endpoint.IdleEP | a # list \<Rightarrow> update_ep_queue ep (remove1 t queue)) s\<rbrace>" apply (simp add: get_ep_queue_def) apply (case_tac ep, simp_all) apply wp apply (clarsimp simp: ep_redux_simps2 valid_ep_def) apply wp apply (clarsimp simp: ep_redux_simps2 valid_ep_def) done lemma blocked_cancel_ipc_valid_objs[wp]: "\<lbrace>valid_objs\<rbrace> blocked_cancel_ipc st t \<lbrace>\<lambda>_. valid_objs\<rbrace>" apply (simp add: blocked_cancel_ipc_def) apply (wp get_simple_ko_valid[where f=Endpoint, simplified valid_ep_def2[symmetric]] valid_ep_queue_subset | simp only: valid_inactive simp_thms cong: imp_cong | rule hoare_drop_imps | clarsimp)+ done lemma cancel_signal_valid_objs[wp]: "\<lbrace>valid_objs\<rbrace> cancel_signal t ntfnptr \<lbrace>\<lambda>_. valid_objs\<rbrace>" apply (simp add: cancel_signal_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (rule hoare_pre) apply (wp set_simple_ko_valid_objs | simp only: valid_inactive | simp | wpc)+ apply (clarsimp simp: ep_redux_simps cong: list.case_cong) apply (erule(1) obj_at_valid_objsE) apply (clarsimp simp: valid_obj_def valid_ntfn_def) apply (auto split: option.splits list.splits) done lemma tcb_in_valid_state: "\<lbrakk> st_tcb_at P t s; valid_objs s \<rbrakk> \<Longrightarrow> \<exists>st. P st \<and> valid_tcb_state st s" apply (clarsimp simp add: valid_objs_def pred_tcb_at_def obj_at_def) apply (erule my_BallE, erule domI) apply (simp add: valid_obj_def valid_tcb_def) apply blast done lemma no_refs_simple_strg: "st_tcb_at simple t s \<and> P {} \<longrightarrow> st_tcb_at (\<lambda>st. P (tcb_st_refs_of st)) t s" by (fastforce elim!: pred_tcb_weakenE)+ crunch it[wp]: cancel_all_ipc "\<lambda>s. P (idle_thread s)" (wp: crunch_wps select_wp simp: unless_def crunch_simps) crunch it[wp]: cancel_all_signals, fast_finalise, unbind_notification "\<lambda>s. P (idle_thread s)" (wp: crunch_wps select_wp simp: unless_def crunch_simps) context IpcCancel_AI begin crunch it[wp]: reply_cancel_ipc "\<lambda>(s::'a state). P (idle_thread s)" (wp: crunch_wps select_wp simp: unless_def crunch_simps) crunch it[wp]: cancel_ipc "\<lambda>(s :: 'a state). P (idle_thread s)" end lemma reply_cap_descends_from_master: "\<lbrakk> invs s; tcb_at t s \<rbrakk> \<Longrightarrow> \<forall>sl\<in>descendants_of (t, tcb_cnode_index 2) (cdt s). \<forall>sl' R. sl' \<noteq> sl \<longrightarrow> caps_of_state s sl' \<noteq> Some (cap.ReplyCap t False R)" apply (subgoal_tac "cte_wp_at (\<lambda>c. (is_master_reply_cap c \<and> obj_ref_of c = t) \<or> c = cap.NullCap) (t, tcb_cnode_index 2) s") apply (clarsimp simp: invs_def valid_state_def valid_mdb_def2 is_cap_simps valid_reply_caps_def cte_wp_at_caps_of_state) apply (erule disjE) apply (unfold reply_mdb_def reply_masters_mdb_def)[1] apply (elim conjE) apply (erule_tac x="(t, tcb_cnode_index 2)" in allE) apply (erule_tac x=t in allE)+ apply (fastforce simp: unique_reply_caps_def is_cap_simps) apply (fastforce dest: mdb_cte_at_Null_descendants) apply (clarsimp simp: tcb_cap_wp_at invs_valid_objs tcb_cap_cases_def is_cap_simps) done lemma (in delete_one_abs) reply_cancel_ipc_no_reply_cap[wp]: notes hoare_pre shows "\<lbrace>invs and tcb_at t\<rbrace> (reply_cancel_ipc t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv s. \<not> has_reply_cap t s\<rbrace>" apply (simp add: reply_cancel_ipc_def) apply wp apply (rule_tac Q="\<lambda>rvp s. cte_wp_at (\<lambda>c. c = cap.NullCap) x s \<and> (\<forall>sl R. sl \<noteq> x \<longrightarrow> caps_of_state s sl \<noteq> Some (cap.ReplyCap t False R))" in hoare_strengthen_post) apply (wp hoare_vcg_conj_lift hoare_vcg_all_lift delete_one_deletes delete_one_caps_of_state) apply (clarsimp simp: has_reply_cap_def cte_wp_at_caps_of_state is_reply_cap_to_def) apply (case_tac "(aa, ba) = (a, b)",simp_all)[1] apply (wp hoare_vcg_all_lift select_wp | simp del: split_paired_All)+ apply (rule_tac Q="\<lambda>_ s. invs s \<and> tcb_at t s" in hoare_post_imp) apply (erule conjE) apply (frule(1) reply_cap_descends_from_master) apply (auto dest: reply_master_no_descendants_no_reply[rotated -1])[1] apply (wp thread_set_invs_trivial | clarsimp simp: tcb_cap_cases_def)+ done lemma (in delete_one_abs) cancel_ipc_no_reply_cap[wp]: shows "\<lbrace>invs and tcb_at t\<rbrace> (cancel_ipc t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv s. \<not> has_reply_cap t s\<rbrace>" apply (simp add: cancel_ipc_def) apply (wpsimp wp: hoare_post_imp [OF invs_valid_reply_caps] reply_cancel_ipc_no_reply_cap cancel_signal_invs cancel_signal_st_tcb_at_general blocked_cancel_ipc_invs blocked_ipc_st_tcb_at_general | strengthen reply_cap_doesnt_exist_strg)+ apply (rule_tac Q="\<lambda>rv. st_tcb_at ((=) rv) t and invs" in hoare_strengthen_post) apply (wpsimp wp: gts_st_tcb) apply (fastforce simp: invs_def valid_state_def st_tcb_at_tcb_at elim!: pred_tcb_weakenE)+ done lemma (in delete_one_abs) suspend_invs[wp]: "\<lbrace>invs and tcb_at t and (\<lambda>s. t \<noteq> idle_thread s)\<rbrace> (suspend t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. invs\<rbrace>" by (wp sts_invs_minor user_getreg_inv as_user_invs sts_invs_minor cancel_ipc_invs cancel_ipc_no_reply_cap | strengthen no_refs_simple_strg | simp add: suspend_def)+ context IpcCancel_AI begin lemma suspend_typ_at [wp]: "\<lbrace>\<lambda>(s::'a state). P (typ_at T p s)\<rbrace> suspend t \<lbrace>\<lambda>rv s. P (typ_at T p s)\<rbrace>" by (wpsimp simp: suspend_def) lemma suspend_valid_cap: "\<lbrace>valid_cap c\<rbrace> suspend tcb \<lbrace>\<lambda>_. (valid_cap c) :: 'a state \<Rightarrow> bool\<rbrace>" by (wp valid_cap_typ) lemma suspend_tcb[wp]: "\<lbrace>tcb_at t'\<rbrace> suspend t \<lbrace>\<lambda>rv. (tcb_at t') :: 'a state \<Rightarrow> bool\<rbrace>" by (simp add: tcb_at_typ) wp end declare if_cong [cong del] crunch cte_wp_at[wp]: blocked_cancel_ipc "cte_wp_at P p" (wp: crunch_wps) crunch cte_wp_at[wp]: cancel_signal "cte_wp_at P p" (wp: crunch_wps) locale delete_one_pre = fixes state_ext_type :: "('a :: state_ext) itself" assumes delete_one_cte_wp_at_preserved: "(\<And>cap. P cap \<Longrightarrow> \<not> can_fast_finalise cap) \<Longrightarrow> \<lbrace>cte_wp_at P sl\<rbrace> (cap_delete_one sl' :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. cte_wp_at P sl\<rbrace>" lemma (in delete_one_pre) reply_cancel_ipc_cte_wp_at_preserved: "(\<And>cap. P cap \<Longrightarrow> \<not> can_fast_finalise cap) \<Longrightarrow> \<lbrace>cte_wp_at P p\<rbrace> (reply_cancel_ipc t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. cte_wp_at P p\<rbrace>" unfolding reply_cancel_ipc_def apply (wpsimp wp: select_wp delete_one_cte_wp_at_preserved) apply (rule_tac Q="\<lambda>_. cte_wp_at P p" in hoare_post_imp, clarsimp) apply (wpsimp wp: thread_set_cte_wp_at_trivial simp: ran_tcb_cap_cases) apply assumption done lemma (in delete_one_pre) cancel_ipc_cte_wp_at_preserved: "(\<And>cap. P cap \<Longrightarrow> \<not> can_fast_finalise cap) \<Longrightarrow> \<lbrace>cte_wp_at P p\<rbrace> (cancel_ipc t :: (unit,'a) s_monad) \<lbrace>\<lambda>rv. cte_wp_at P p\<rbrace>" apply (simp add: cancel_ipc_def) apply (rule hoare_pre) apply (wp reply_cancel_ipc_cte_wp_at_preserved | wpcw | simp)+ done lemma (in delete_one_pre) suspend_cte_wp_at_preserved: "(\<And>cap. P cap \<Longrightarrow> \<not> can_fast_finalise cap) \<Longrightarrow> \<lbrace>cte_wp_at P p\<rbrace> (suspend tcb :: (unit,'a) s_monad) \<lbrace>\<lambda>_. cte_wp_at P p\<rbrace>" by (simp add: suspend_def) (wpsimp wp: cancel_ipc_cte_wp_at_preserved)+ (* FIXME - eliminate *) lemma obj_at_exst_update: "obj_at P p (trans_state f s) = obj_at P p s" by (rule more_update.obj_at_update) lemma set_thread_state_bound_tcb_at[wp]: "\<lbrace>bound_tcb_at P t\<rbrace> set_thread_state p ts \<lbrace>\<lambda>_. bound_tcb_at P t\<rbrace>" unfolding set_thread_state_def set_object_def get_object_def by (wpsimp simp: pred_tcb_at_def obj_at_def get_tcb_def) crunch bound_tcb_at[wp]: cancel_all_ipc, empty_slot, is_final_cap, get_cap "bound_tcb_at P t" (wp: mapM_x_wp_inv) lemma fast_finalise_bound_tcb_at: "\<lbrace>\<lambda>s. bound_tcb_at P t s \<and> (\<exists>tt b R. cap = ReplyCap tt b R) \<rbrace> fast_finalise cap final \<lbrace>\<lambda>_. bound_tcb_at P t\<rbrace>" by (case_tac cap, simp_all) lemma get_cap_reply_cap_helper: "\<lbrace>\<lambda>s. \<exists>t b R. Some (ReplyCap t b R) = caps_of_state s slot \<rbrace> get_cap slot \<lbrace>\<lambda>rv s. \<exists>t b R. rv = ReplyCap t b R\<rbrace>" by (auto simp: valid_def get_cap_caps_of_state[symmetric]) lemma cap_delete_one_bound_tcb_at: "\<lbrace>\<lambda>s. bound_tcb_at P t s \<and> (\<exists>t b R. caps_of_state s c = Some (ReplyCap t b R)) \<rbrace> cap_delete_one c \<lbrace>\<lambda>_. bound_tcb_at P t\<rbrace>" apply (clarsimp simp: unless_def cap_delete_one_def) apply (wp fast_finalise_bound_tcb_at) apply (wp hoare_vcg_if_lift2, simp) apply (wp hoare_conjI) apply (wp only:hoare_drop_imp) apply (wp hoare_vcg_conj_lift) apply (wp get_cap_reply_cap_helper hoare_drop_imp | clarsimp)+ done lemma valid_mdb_impl_reply_masters: "valid_mdb s \<Longrightarrow> reply_masters_mdb (cdt s) (caps_of_state s)" by (auto simp: valid_mdb_def reply_mdb_def) lemma caps_of_state_tcb_index_trans: "\<lbrakk>get_tcb p s = Some tcb \<rbrakk> \<Longrightarrow> caps_of_state s (p, tcb_cnode_index n) = (tcb_cnode_map tcb) (tcb_cnode_index n)" apply (drule get_tcb_SomeD) apply (clarsimp simp: caps_of_state_def) apply (safe) apply (clarsimp simp: get_object_def get_cap_def) apply (simp add:set_eq_iff) apply (drule_tac x=cap in spec) apply (drule_tac x=s in spec) apply (clarsimp simp: in_monad) apply (clarsimp simp: get_cap_def get_object_def) apply (rule ccontr) apply (drule not_sym) apply (auto simp: set_eq_iff in_monad) done lemma descendants_of_nullcap: "\<lbrakk>descendants_of (a, b) (cdt s) \<noteq> {}; valid_mdb s \<rbrakk> \<Longrightarrow> caps_of_state s (a, b) \<noteq> Some NullCap" apply clarsimp apply (drule_tac cs="caps_of_state s" and p="(a,b)" and m="(cdt s)" in mdb_cte_at_Null_descendants) apply (clarsimp simp: valid_mdb_def2)+ done lemma reply_cancel_ipc_bound_tcb_at[wp]: "\<lbrace>bound_tcb_at P t and valid_mdb and valid_objs and tcb_at p \<rbrace> reply_cancel_ipc p \<lbrace>\<lambda>_. bound_tcb_at P t\<rbrace>" unfolding reply_cancel_ipc_def apply (wpsimp wp: cap_delete_one_bound_tcb_at select_inv select_wp) apply (rule_tac Q="\<lambda>_. bound_tcb_at P t and valid_mdb and valid_objs and tcb_at p" in hoare_strengthen_post) apply (wpsimp wp: thread_set_no_change_tcb_pred thread_set_mdb) apply (fastforce simp:tcb_cap_cases_def) apply (wpsimp wp: thread_set_valid_objs_triv simp: ran_tcb_cap_cases) apply clarsimp apply (frule valid_mdb_impl_reply_masters) apply (clarsimp simp: reply_masters_mdb_def) apply (spec p) apply (spec "tcb_cnode_index 2") apply (spec p) apply (clarsimp simp:tcb_at_def) apply (frule(1) valid_tcb_objs) apply (clarsimp simp: valid_tcb_def) apply (erule impE) apply (simp add: caps_of_state_tcb_index_trans tcb_cnode_map_def) apply (clarsimp simp: tcb_cap_cases_def is_master_reply_cap_def split:cap.splits ) apply (subgoal_tac "descendants_of (p, tcb_cnode_index 2) (cdt s) \<noteq> {}") prefer 2 apply simp apply (drule descendants_of_nullcap, simp) apply (simp add: caps_of_state_tcb_index_trans tcb_cnode_map_def) apply fastforce apply simp done crunch bound_tcb_at[wp]: cancel_ipc "bound_tcb_at P t" (ignore: set_object thread_set wp: mapM_x_wp_inv) context IpcCancel_AI begin lemma suspend_unlive: "\<lbrace>\<lambda>(s::'a state). (bound_tcb_at ((=) None) t and valid_mdb and valid_objs) s \<rbrace> suspend t \<lbrace>\<lambda>rv. obj_at (Not \<circ> live0) t\<rbrace>" apply (simp add: suspend_def set_thread_state_def set_object_def get_object_def) (* avoid creating two copies of obj_at *) supply hoare_vcg_if_split[wp_split del] if_splits[split del] apply (wp | simp only: obj_at_exst_update)+ apply (simp add: obj_at_def) apply (rule_tac Q="\<lambda>_. bound_tcb_at ((=) None) t" in hoare_strengthen_post) supply hoare_vcg_if_split[wp_split] apply wp apply (auto simp: pred_tcb_def2)[1] apply (simp flip: if_split) apply wpsimp+ apply (simp add: pred_tcb_at_tcb_at) done end definition bound_refs_of_tcb :: "'a state \<Rightarrow> machine_word \<Rightarrow> (machine_word \<times> reftype) set" where "bound_refs_of_tcb s t \<equiv> case kheap s t of Some (TCB tcb) \<Rightarrow> tcb_bound_refs (tcb_bound_notification tcb) | _ \<Rightarrow> {}" lemma bound_refs_of_tcb_trans: "bound_refs_of_tcb (trans_state f s) x = bound_refs_of_tcb s x" by (clarsimp simp:bound_refs_of_tcb_def trans_state_def) lemma cancel_all_invs_helper: "\<lbrace>all_invs_but_sym_refs and (\<lambda>s. (\<forall>x\<in>set q. ex_nonz_cap_to x s) \<and> sym_refs (\<lambda>x. if x \<in> set q then {r \<in> state_refs_of s x. snd r = TCBBound} else state_refs_of s x) \<and> sym_refs (\<lambda>x. state_hyp_refs_of s x) \<and> (\<forall>x\<in>set q. st_tcb_at (Not \<circ> (halted or awaiting_reply)) x s))\<rbrace> mapM_x (\<lambda>t. do y \<leftarrow> set_thread_state t Structures_A.thread_state.Restart; do_extended_op (tcb_sched_enqueue_ext t) od) q \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: invs_def valid_state_def valid_pspace_def) apply (rule mapM_x_inv_wp2) apply (clarsimp simp: ) apply wp apply (simp add:bound_refs_of_tcb_trans) apply wp[1] apply (rule hoare_pre, wp hoare_vcg_const_Ball_lift valid_irq_node_typ sts_only_idle) apply (rule sts_st_tcb_at_cases, simp) apply (strengthen reply_cap_doesnt_exist_strg) apply (auto simp: valid_tcb_state_def idle_no_ex_cap o_def if_split_asm elim!: rsubst[where P=sym_refs] st_tcb_weakenE intro!: ext) done lemma ep_no_bound_refs: "ep_at p s \<Longrightarrow> {r \<in> state_refs_of s p. snd r = TCBBound} = {}" by (clarsimp simp: obj_at_def state_refs_of_def refs_of_def is_ep ep_q_refs_of_def split: endpoint.splits) lemma obj_at_conj_distrib: "obj_at (\<lambda>ko. P ko \<and> Q ko) p s \<Longrightarrow> obj_at (\<lambda>ko. P ko) p s \<and> obj_at (\<lambda>ko. Q ko) p s" by (auto simp:obj_at_def) lemma ep_q_refs_of_no_ntfn_bound: "(x, tp) \<in> ep_q_refs_of ep \<Longrightarrow> tp \<noteq> NTFNBound" by (auto simp: ep_q_refs_of_def split:endpoint.splits) lemma ep_q_refs_no_NTFNBound: "(x, NTFNBound) \<notin> ep_q_refs_of ep" by (clarsimp simp: ep_q_refs_of_def split:endpoint.splits) lemma ep_list_tcb_at: "\<lbrakk>ep_at p s; valid_objs s; state_refs_of s p = set q \<times> {k}; x \<in> set q \<rbrakk> \<Longrightarrow> tcb_at x s" apply (erule (1) obj_at_valid_objsE) apply (fastforce simp:is_ep valid_obj_def valid_ep_def state_refs_of_def split:endpoint.splits) done lemma tcb_at_no_ntfn_bound: "\<lbrakk> valid_objs s; tcb_at x s \<rbrakk> \<Longrightarrow> (t, NTFNBound) \<notin> state_refs_of s x" by (auto elim!: obj_at_valid_objsE simp: state_refs_of_def is_tcb valid_obj_def tcb_bound_refs_def tcb_st_refs_of_def split:thread_state.splits option.splits) lemma ep_no_ntfn_bound: "\<lbrakk>is_ep ko; refs_of ko = set q \<times> {NTFNBound}; y \<in> set q \<rbrakk> \<Longrightarrow> False" apply (subst (asm) set_eq_iff) apply (drule_tac x="(y, NTFNBound)" in spec) apply (clarsimp simp: refs_of_rev is_ep) done lemma cancel_all_ipc_invs_helper: assumes x: "\<And>x ko. (x, symreftype k) \<in> refs_of ko \<Longrightarrow> (refs_of ko = {(x, symreftype k)} \<or> (\<exists>y. refs_of ko = {(x, symreftype k), (y, TCBBound)}))" shows "\<lbrace>invs and obj_at (\<lambda>ko. is_ep ko \<and> refs_of ko = set q \<times> {k}) p\<rbrace> do y \<leftarrow> set_endpoint p Structures_A.endpoint.IdleEP; y \<leftarrow> mapM_x (\<lambda>t. do y \<leftarrow> set_thread_state t Structures_A.thread_state.Restart; do_extended_op (tcb_sched_action (tcb_sched_enqueue) t) od) q; do_extended_op reschedule_required od \<lbrace>\<lambda>rv. invs\<rbrace>" apply (subst bind_assoc[symmetric]) apply (rule hoare_seq_ext) apply wp apply simp apply (rule hoare_pre) apply (wp cancel_all_invs_helper hoare_vcg_const_Ball_lift valid_irq_node_typ valid_ioports_lift) apply (clarsimp simp: invs_def valid_state_def valid_pspace_def valid_ep_def live_def) apply (rule conjI) apply (fastforce simp: live_def is_ep_def elim!: obj_at_weakenE split: kernel_object.splits) apply (rule conjI) apply clarsimp apply (drule(1) sym_refs_obj_atD, clarsimp) apply (drule(1) bspec, erule(1) if_live_then_nonz_capD) apply (rule refs_of_live, clarsimp) apply (rule conjI[rotated]) apply (subgoal_tac "\<exists>ep. ko_at (Endpoint ep) p s", clarsimp) apply (subgoal_tac "\<exists>rt. (x, rt) \<in> ep_q_refs_of ep", clarsimp) apply (fastforce elim!: ep_queued_st_tcb_at) apply (clarsimp simp: obj_at_def is_ep_def)+ apply (case_tac ko, simp_all) apply (frule(1) sym_refs_obj_atD) apply (frule obj_at_state_refs_ofD) apply (clarsimp dest!:obj_at_conj_distrib) apply (thin_tac "obj_at (\<lambda>ko. refs_of ko = set q \<times> {k}) p s") apply (erule delta_sym_refs) apply (clarsimp simp: if_split_asm)+ apply (safe) apply (fastforce dest!:symreftype_inverse' ep_no_ntfn_bound) apply (clarsimp dest!: symreftype_inverse') apply (frule (3) ep_list_tcb_at) apply (frule_tac t=y in tcb_at_no_ntfn_bound, simp+) apply (clarsimp dest!: symreftype_inverse') apply (frule (3) ep_list_tcb_at) apply (clarsimp simp: obj_at_def is_tcb is_ep) apply (fastforce dest!: obj_at_state_refs_ofD x) apply (fastforce dest!: obj_at_state_refs_ofD x) apply (fastforce dest!: symreftype_inverse' ep_no_ntfn_bound) apply (clarsimp) apply (fastforce dest!: symreftype_inverse' ep_no_ntfn_bound) done lemma cancel_all_ipc_invs: "\<lbrace>invs\<rbrace> cancel_all_ipc epptr \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: cancel_all_ipc_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (case_tac ep, simp_all add: get_ep_queue_def) apply (wp, fastforce) apply (rule hoare_pre, rule cancel_all_ipc_invs_helper[where k=EPSend]) apply (fastforce simp: refs_of_rev tcb_bound_refs_def split: option.splits) apply (clarsimp elim!: obj_at_weakenE simp: is_ep) apply (rule hoare_pre, rule cancel_all_ipc_invs_helper[where k=EPRecv]) apply (fastforce simp: refs_of_rev tcb_bound_refs_def split: option.splits) apply (clarsimp elim!: obj_at_weakenE simp: is_ep) done lemma ntfn_q_refs_no_NTFNBound: "(x, NTFNBound) \<notin> ntfn_q_refs_of ntfn" by (auto simp: ntfn_q_refs_of_def split:ntfn.splits) lemma ntfn_q_refs_no_TCBBound: "(x, TCBBound) \<notin> ntfn_q_refs_of ntfn" by (auto simp: ntfn_q_refs_of_def split:ntfn.splits) lemma ntfn_bound_tcb_get_set[simp]: "ntfn_bound_tcb (ntfn_set_bound_tcb ntfn ntfn') = ntfn'" by auto lemma ntfn_obj_tcb_get_set[simp]: "ntfn_obj (ntfn_set_bound_tcb ntfn ntfn') = ntfn_obj ntfn" by auto lemma valid_ntfn_set_bound_None: "valid_ntfn ntfn s \<Longrightarrow> valid_ntfn (ntfn_set_bound_tcb ntfn None) s" by (auto simp: valid_ntfn_def split:ntfn.splits) lemma ntfn_bound_tcb_at: "\<lbrakk>sym_refs (state_refs_of s); valid_objs s; kheap s ntfnptr = Some (Notification ntfn); ntfn_bound_tcb ntfn = Some tcbptr; P (Some ntfnptr)\<rbrakk> \<Longrightarrow> bound_tcb_at P tcbptr s" apply (drule_tac x=ntfnptr in sym_refsD[rotated]) apply (fastforce simp: state_refs_of_def) apply (auto simp: pred_tcb_at_def obj_at_def valid_obj_def valid_ntfn_def is_tcb state_refs_of_def refs_of_rev simp del: refs_of_simps elim!: valid_objsE) done lemma bound_tcb_bound_notification_at: "\<lbrakk>sym_refs (state_refs_of s); valid_objs s; kheap s ntfnptr = Some (Notification ntfn); bound_tcb_at (\<lambda>ptr. ptr = (Some ntfnptr)) tcbptr s \<rbrakk> \<Longrightarrow> ntfn_bound_tcb ntfn = Some tcbptr" apply (drule_tac x=tcbptr in sym_refsD[rotated]) apply (fastforce simp: state_refs_of_def pred_tcb_at_def obj_at_def) apply (auto simp: pred_tcb_at_def obj_at_def valid_obj_def valid_ntfn_def is_tcb state_refs_of_def refs_of_rev simp del: refs_of_simps elim!: valid_objsE) done lemma unbind_notification_invs: shows "\<lbrace>invs\<rbrace> unbind_notification t \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: unbind_notification_def invs_def valid_state_def valid_pspace_def) apply (rule hoare_seq_ext [OF _ gbn_sp]) apply (case_tac ntfnptr, clarsimp, wp, simp) apply clarsimp apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (wp valid_irq_node_typ set_simple_ko_valid_objs valid_ioports_lift | clarsimp split del: if_split)+ apply (intro conjI impI; (match conclusion in "sym_refs r" for r \<Rightarrow> \<open>-\<close> | auto elim!: obj_at_weakenE obj_at_valid_objsE if_live_then_nonz_capD2 simp: live_def valid_ntfn_set_bound_None is_ntfn valid_obj_def )?) apply (clarsimp simp: if_split) apply (rule delta_sym_refs, assumption) apply (fastforce simp: obj_at_def is_tcb dest!: pred_tcb_at_tcb_at ko_at_state_refs_ofD split: if_split_asm) apply (clarsimp split: if_split_asm) apply (frule pred_tcb_at_tcb_at) apply (frule_tac p=t in obj_at_ko_at, clarsimp) apply (subst (asm) ko_at_state_refs_ofD, assumption) apply (fastforce simp: obj_at_def is_tcb ntfn_q_refs_no_NTFNBound tcb_at_no_ntfn_bound refs_of_rev tcb_ntfn_is_bound_def dest!: pred_tcb_at_tcb_at bound_tcb_at_state_refs_ofD) apply (subst (asm) ko_at_state_refs_ofD, assumption) apply (fastforce simp: ntfn_bound_refs_def obj_at_def ntfn_q_refs_no_TCBBound elim!: pred_tcb_weakenE dest!: bound_tcb_bound_notification_at refs_in_ntfn_bound_refs symreftype_inverse' split: option.splits) done crunch bound_tcb_at[wp]: cancel_all_signals "bound_tcb_at P t" (wp: mapM_x_wp_inv) lemma waiting_ntfn_list_tcb_at: "\<lbrakk>valid_objs s; ko_at (Notification ntfn) ntfnptr s; ntfn_obj ntfn = WaitingNtfn x\<rbrakk> \<Longrightarrow> \<forall>t \<in> set x. tcb_at t s" by (fastforce elim!: obj_at_valid_objsE simp:valid_obj_def valid_ntfn_def) lemma tcb_at_ko_at: "tcb_at p s \<Longrightarrow> \<exists>tcb. ko_at (TCB tcb) p s" by (fastforce simp: obj_at_def is_tcb) lemma tcb_state_refs_no_tcb: "\<lbrakk>valid_objs s; tcb_at y s; (x, ref) \<in> state_refs_of s y\<rbrakk> \<Longrightarrow> ~ tcb_at x s" apply (clarsimp simp: ko_at_state_refs_ofD dest!: tcb_at_ko_at) apply (erule (1) obj_at_valid_objsE) apply (clarsimp simp: is_tcb valid_obj_def) apply (erule disjE) apply (clarsimp simp: tcb_st_refs_of_def valid_tcb_def valid_tcb_state_def obj_at_def is_ep is_ntfn split:thread_state.splits) apply (clarsimp simp: tcb_bound_refs_def valid_tcb_def obj_at_def is_ntfn split:option.splits) done lemma cancel_all_signals_invs: "\<lbrace>invs\<rbrace> cancel_all_signals ntfnptr \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: cancel_all_signals_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (rule hoare_pre) apply (wp cancel_all_invs_helper set_simple_ko_valid_objs valid_irq_node_typ hoare_vcg_const_Ball_lift valid_ioports_lift | wpc | simp add: live_def)+ apply (clarsimp simp: invs_def valid_state_def valid_pspace_def) apply (rule conjI) apply (fastforce simp: valid_obj_def valid_ntfn_def elim!: obj_at_valid_objsE) apply (rule conjI) apply (fastforce simp: live_def elim!: if_live_then_nonz_capD) apply (rule conjI) apply (fastforce simp: is_ntfn elim!: ko_at_weakenE) apply (rule conjI) apply (fastforce simp: st_tcb_at_refs_of_rev dest: bspec sym_refs_ko_atD elim: st_tcb_ex_cap) apply (rule conjI[rotated]) apply (fastforce elim!: ntfn_queued_st_tcb_at) apply (rule delta_sym_refs, assumption) apply (fastforce dest!: refs_in_ntfn_bound_refs ko_at_state_refs_ofD split: if_split_asm) apply (clarsimp split:if_split_asm) apply (fastforce dest: waiting_ntfn_list_tcb_at refs_in_ntfn_bound_refs simp: obj_at_def is_tcb_def) apply (rule conjI) apply (fastforce dest: refs_in_ntfn_bound_refs symreftype_inverse') apply (frule (2) waiting_ntfn_list_tcb_at) apply (fastforce simp: st_tcb_at_refs_of_rev refs_in_tcb_bound_refs dest: bspec sym_refs_ko_atD st_tcb_at_state_refs_ofD) apply (fastforce simp: ntfn_bound_refs_def valid_obj_def valid_ntfn_def refs_of_rev dest!: symreftype_inverse' ko_at_state_refs_ofD split: option.splits elim!: obj_at_valid_objsE) done lemma cancel_all_unlive_helper: "\<lbrace>obj_at (\<lambda>obj. \<not> live obj \<and> (\<forall>tcb. obj \<noteq> TCB tcb)) ptr\<rbrace> mapM_x (\<lambda>t. do y \<leftarrow> set_thread_state t Structures_A.Restart; do_extended_op (tcb_sched_enqueue_ext t) od) q \<lbrace>\<lambda>rv. obj_at (Not \<circ> live) ptr\<rbrace>" apply (rule hoare_strengthen_post [OF mapM_x_wp']) apply (simp add: set_thread_state_def set_object_def get_object_def) apply (wp | simp only: obj_at_exst_update)+ apply (clarsimp dest!: get_tcb_SomeD) apply (clarsimp simp: obj_at_def) apply (clarsimp elim!: obj_at_weakenE) done lemma cancel_all_ipc_unlive[wp]: "\<lbrace>\<top>\<rbrace> cancel_all_ipc ptr \<lbrace>\<lambda> rv. obj_at (Not \<circ> live) ptr\<rbrace>" apply (simp add: cancel_all_ipc_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (case_tac ep, simp_all add: set_simple_ko_def get_ep_queue_def) apply wp apply (clarsimp simp: live_def elim!: obj_at_weakenE) apply (wp cancel_all_unlive_helper set_object_at_obj3 | simp only: obj_at_exst_update)+ apply (clarsimp simp: live_def) apply (wp cancel_all_unlive_helper set_object_at_obj3 | simp only: obj_at_exst_update)+ apply (clarsimp simp: live_def) done (* This lemma should be sufficient provided that each notification object is unbound BEFORE the 'cancel_all_signals' function is invoked. TODO: Check the abstract specification and the C and Haskell implementations that this is indeed the case. *) lemma cancel_all_signals_unlive[wp]: "\<lbrace>\<lambda>s. obj_at (\<lambda>ko. \<exists>ntfn. ko = Notification ntfn \<and> ntfn_bound_tcb ntfn = None) ntfnptr s\<rbrace> cancel_all_signals ntfnptr \<lbrace>\<lambda> rv. obj_at (Not \<circ> live) ntfnptr\<rbrace>" apply (simp add: cancel_all_signals_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (rule hoare_pre) apply (wp | wpc | simp add: unbind_maybe_notification_def)+ apply (rule_tac Q="\<lambda>_. obj_at (is_ntfn and Not \<circ> live) ntfnptr" in hoare_post_imp) apply (fastforce elim: obj_at_weakenE) apply (wp mapM_x_wp' sts_obj_at_impossible | simp add: is_ntfn)+ apply (simp add: set_simple_ko_def) apply (wp get_object_wp obj_set_prop_at) apply (auto simp: live_def pred_tcb_at_def obj_at_def) done crunch cte_wp_at[wp]: cancel_all_ipc "cte_wp_at P p" (wp: crunch_wps mapM_x_wp) crunch cte_wp_at[wp]: cancel_all_signals "cte_wp_at P p" (wp: crunch_wps mapM_x_wp thread_set_cte_wp_at_trivial simp: tcb_cap_cases_def) lemma cancel_badged_sends_filterM_helper': "\<forall>ys. \<lbrace>\<lambda>s. all_invs_but_sym_refs s \<and> sym_refs (state_hyp_refs_of s) \<and> distinct (xs @ ys) \<and> ep_at epptr s \<and> ex_nonz_cap_to epptr s \<and> sym_refs ((state_refs_of s) (epptr := ((set (xs @ ys)) \<times> {EPSend}))) \<and> (\<forall>x \<in> set (xs @ ys). {r \<in> state_refs_of s x. snd r \<noteq> TCBBound} = {(epptr, TCBBlockedSend)})\<rbrace> filterM (\<lambda>t. do st \<leftarrow> get_thread_state t; if blocking_ipc_badge st = badge then do y \<leftarrow> set_thread_state t Structures_A.thread_state.Restart; y \<leftarrow> do_extended_op (tcb_sched_action action t); return False od else return True od) xs \<lbrace>\<lambda>rv s. all_invs_but_sym_refs s \<and> sym_refs (state_hyp_refs_of s) \<and> ep_at epptr s \<and> (\<forall>x \<in> set (xs @ ys). tcb_at x s) \<and> ex_nonz_cap_to epptr s \<and> (\<forall>y \<in> set ys. {r \<in> state_refs_of s y. snd r \<noteq> TCBBound} = {(epptr, TCBBlockedSend)}) \<and> distinct rv \<and> distinct (xs @ ys) \<and> (set rv \<subseteq> set xs) \<and> sym_refs ((state_refs_of s) (epptr := ((set rv \<union> set ys) \<times> {EPSend})))\<rbrace>" apply (rule rev_induct[where xs=xs]) apply (rule allI, simp) apply wp apply clarsimp apply (drule(1) bspec, drule singleton_eqD, clarsimp, drule state_refs_of_elemD) apply (clarsimp simp: st_tcb_at_refs_of_rev pred_tcb_at_def is_tcb elim!: obj_at_weakenE) apply (clarsimp simp: filterM_append bind_assoc simp del: set_append distinct_append) apply (drule spec, erule hoare_seq_ext[rotated]) apply (rule hoare_seq_ext [OF _ gts_sp]) apply (rule hoare_pre, wpsimp wp: valid_irq_node_typ sts_only_idle hoare_vcg_const_Ball_lift) apply (clarsimp simp: valid_tcb_state_def) apply (rule conjI[rotated]) apply blast apply clarsimp apply (thin_tac "obj_at f epptr s" for f s) apply (thin_tac "tcb_at x s" for x s) apply (thin_tac "sym_refs (state_hyp_refs_of s)" for s) apply (frule singleton_eqD, clarify, drule state_refs_of_elemD) apply (frule(1) if_live_then_nonz_capD) apply (rule refs_of_live, clarsimp) apply (clarsimp simp: st_tcb_at_refs_of_rev) apply (clarsimp simp: pred_tcb_def2 valid_idle_def) apply (rule conjI, clarsimp) apply (rule conjI, clarsimp) apply (drule(1) valid_reply_capsD, clarsimp simp: st_tcb_def2) apply (rule conjI, blast) apply (rule conjI, blast) apply (erule delta_sym_refs) apply (auto dest!: get_tcb_ko_atD ko_at_state_refs_ofD symreftype_inverse' refs_in_tcb_bound_refs split: if_split_asm)[2] done lemmas cancel_badged_sends_filterM_helper = spec [where x=Nil, OF cancel_badged_sends_filterM_helper', simplified] lemma cancel_badged_sends_invs_helper: "{r. snd r \<noteq> TCBBound \<and> (r \<in> tcb_st_refs_of ts \<or> r \<in> tcb_bound_refs ntfnptr)} = tcb_st_refs_of ts" by (auto simp add: tcb_st_refs_of_def tcb_bound_refs_def split: thread_state.splits option.splits) lemma cancel_badged_sends_invs[wp]: "\<lbrace>invs\<rbrace> cancel_badged_sends epptr badge \<lbrace>\<lambda>rv. invs\<rbrace>" apply (simp add: cancel_badged_sends_def) apply (rule hoare_seq_ext [OF _ get_simple_ko_sp]) apply (case_tac ep; simp) apply wpsimp apply (simp add: invs_def valid_state_def valid_pspace_def) apply (wpsimp wp: valid_irq_node_typ valid_ioports_lift) apply (simp add: fun_upd_def[symmetric] ep_redux_simps ep_at_def2[symmetric, simplified] cong: list.case_cong) apply (rule hoare_strengthen_post, rule cancel_badged_sends_filterM_helper[where epptr=epptr]) apply (auto intro:obj_at_weakenE)[1] apply (wpsimp wp: valid_irq_node_typ set_endpoint_ep_at valid_ioports_lift) apply (clarsimp simp: valid_ep_def conj_comms) apply (subst obj_at_weakenE, simp, fastforce) apply (clarsimp simp: is_ep_def) apply (frule(1) sym_refs_ko_atD, clarsimp) apply (frule(1) if_live_then_nonz_capD, (clarsimp simp: live_def)+) apply (erule(1) obj_at_valid_objsE) apply (clarsimp simp: valid_obj_def valid_ep_def st_tcb_at_refs_of_rev) apply (simp add: fun_upd_idem obj_at_def is_ep_def | subst fun_upd_def[symmetric])+ apply (clarsimp, drule(1) bspec) apply (drule st_tcb_at_state_refs_ofD) apply (clarsimp simp only: cancel_badged_sends_invs_helper Un_iff, clarsimp) apply (simp add: set_eq_subset) apply wpsimp done (* FIXME rule_format? *) lemma real_cte_emptyable_strg: "real_cte_at p s \<longrightarrow> emptyable p s" by (clarsimp simp: emptyable_def obj_at_def is_tcb is_cap_table) end
Set Implicit Arguments. Unset Strict Implicit. Require Import QArith String Ascii. (*The computable state representation is an FMap over player indices, represented as positive.*) Require Import Coq.FSets.FMapAVL Coq.FSets.FMapFacts. Require Import Structures.Orders NArith. Require Import mathcomp.ssreflect.ssreflect. From mathcomp Require Import all_ssreflect. From mathcomp Require Import all_algebra. Require Import OUVerT.strings compile OUVerT.orderedtypes OUVerT.dyadic OUVerT.numerics cdist MWU.weightsextract lightserver. (** Axiomatized client oracle *) Axiom ax_st_ty : Type. Extract Constant ax_st_ty => "unit". Axiom empty_ax_st : ax_st_ty. Extract Constant empty_ax_st => "()". (** A channel *) Axiom ax_chan : Type. Extract Constant ax_chan => "Unix.file_descr". Axiom ax_bogus_chan : ax_chan. Extract Constant ax_bogus_chan => "Unix.stderr". Axiom ax_send : forall OUT : Type, ax_st_ty -> OUT -> (ax_chan * ax_st_ty). Extract Constant ax_send => (* Create socket, connect to server, send action, return socket. *) (* Need to know IP address of the server, but it's also possible to do host name resolution. *) "fun _ a -> let _ = Printf.eprintf ""Sending...""; prerr_newline () in let sd = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in Unix.connect sd (Unix.ADDR_INET (Unix.inet_addr_of_string ""127.0.0.1"", 13337)); let out_chan = Unix.out_channel_of_descr sd in Marshal.to_channel out_chan a []; flush out_chan; Printf.eprintf ""Sent value...""; prerr_newline (); (sd, ())". Axiom ax_recv : forall IN : Type, ax_st_ty -> ax_chan -> (IN * ax_st_ty). Extract Constant ax_recv => (* Read the player actions from the socket; close the socket *) "fun _ sd -> let _ = Printf.eprintf ""Receiving...""; prerr_newline () in let in_chan = Unix.in_channel_of_descr sd in let cost_vector = Marshal.from_channel in_chan in close_in in_chan; Printf.eprintf ""Received cost vector...""; prerr_newline (); (cost_vector, ())". (*MOVE*) Axiom seq : forall (A B : Type) (a : A) (f : A -> B), B. Extract Constant seq => "fun a b -> let x = a in b x". Axiom seqP : forall A B (a : A) (f : A -> B), seq a f = f a. (*END MOVE*) Module AxClientOracle (C : CONFIG). Module Wire := WireFormat_of_CONFIG C. Definition OUT := Wire.CLIENT_TO_SERVER. Definition IN := Wire.SERVER_TO_CLIENT. Section clientCostVectorShim. Variable num_players : nat. Context `{game_instance : GameType C.A.t}. Definition send (st : ax_st_ty) (l : list (C.A.t*D)) : ax_chan * ax_st_ty := (*TODO: constructing this DIST.t each time is wasteful -- the DIST datastructure should eventually be factored into weightsextract.v*) let: d := DIST.add_weights l (DIST.empty _) in seq (seq (eprint_string "Weights table..." tt) (fun _ => seq (eprint_newline tt) (fun _ => print_Dvector l tt))) (fun _ => seq (rsample a0 d) (fun x => seq (eprint_string "Chose action " tt) (fun _ => seq (eprint_showable x tt) (fun _ => seq (eprint_newline tt) (fun _ => ax_send st x))))). (** The cost vector for [player]. [p] is a map from player indices to their sampled strategies. *) Definition cost_vector (p : M.t C.A.t) (player : N) : list (C.A.t * D) := List.fold_left (fun l a => (a, ccost player (M.add player a p)) :: l) (enumerate C.A.t) nil. Lemma cost_vector_nodup p player : NoDupA (fun p q => p.1 = q.1) (cost_vector p player). Proof. rewrite /cost_vector -fold_left_rev_right. generalize enum_nodup; move: (enumerate C.A.t) => l H. have H2: NoDupA (fun x : C.A.t => [eta eq x]) (List.rev l). { apply NoDupA_rev => //. by constructor => // => x y z -> <-. } move {H}; move: H2; move: (List.rev l) => l0. elim: l0 => //= a l0 IH H2; constructor. { move => H3. have H4: InA (fun x y => x=y) a l0. { clear -H3; move: H3; elim: l0 => //=. { inversion 1. } move => a0 l IH H; inversion H; subst. { by simpl in H1; subst a0; constructor. } by apply: InA_cons_tl; apply: IH. } by inversion H2; subst. } by apply: IH; inversion H2; subst. Qed. Definition recv (st : ax_st_ty) (ch : ax_chan) : list (C.A.t*D) * ax_st_ty := seq (ax_recv _ st ch) (fun pst' => let: (player, p, st') := pst' in (cost_vector p player, st')). Lemma recv_ok : forall st ch a, exists d, [/\ In (a,d) (recv st ch).1 , Dle (-D1) d & Dle d D1]. Proof. rewrite /recv /cost_vector => st ch a. case: (ax_recv _ _ _) => [][]a0 b b0; rewrite seqP => /=. generalize (enum_total); move/(_ a) => H. exists ((ccost) a0 (M.add a0 a b)). split => //. { rewrite -fold_left_rev_right. have H2: In a (List.rev (enumerate C.A.t)). { by rewrite -in_rev. } move: H2 {H}; elim: (List.rev (enumerate C.A.t)) => // a1 l IH. inversion 1; subst; first by left. by right; apply: IH. } { generalize (ccost_ok (M.add a0 a b) a0); case => H1 H2. apply: Qle_trans; last by apply: H1. by []. } by generalize (ccost_ok (M.add a0 a b) a0); case. Qed. Lemma recv_nodup : forall st ch, NoDupA (fun p q => p.1 = q.1) (recv st ch).1. Proof. move => st ch; rewrite /recv seqP. case E: (ax_recv _ st ch) => [[x y] z] /=. apply: cost_vector_nodup. Qed. End clientCostVectorShim. Program Instance client_ax_oracle {num_players : nat} `{GameType C.A.t num_players} : @ClientOracle C.A.t := @mkOracle C.A.t ax_st_ty empty_ax_st ax_chan ax_bogus_chan (fun _ _ => (true,_)) (*presend*) (@recv num_players _ _) (fun _ _ => true) (*prerecv*) (@send num_players _ _ _ _ _) _ _. Next Obligation. eauto using (@recv_ok num_players _ _ _ _ _). Defined. Next Obligation. eauto using (@recv_nodup num_players _ _ _). Defined. End AxClientOracle.
[From the Stan Manual](https://mc-stan.org/docs/2_25/reference-manual/change-of-variables-section.html#multivariate-changes-of-variables): > Suppose $X$ is a $K$-dimensional random variable with probability density function $p_X(x)$. A new random variable $Y = f ( X )$ may be defined by transforming $X$ with a suitably well-behaved function $f $. It suffices for what follows to note that if $f$ is one-to-one and its inverse $f ^ {− 1}$ has a well-defined Jacobian, then the density of $Y$ is $$ p_Y ( y ) = p_X ( f ^ {− 1} ( y ) ) ∣ det J _ {f ^{ − 1}} ( y ) | $$ Here we have $p_X(a, b) \sim \text{Uniform}$, with $a = \frac{\alpha}{\alpha + \beta}, b = (\alpha + \beta)^{-1/2}$ ```python from sympy import symbols, Matrix, simplify, solve, Eq, Abs, log ``` ```python alpha, beta = symbols('alpha, beta', positive=True) a, b = symbols('a b') f = solve((Eq(alpha / (alpha + beta), a), Eq((alpha + beta)**(-1/2), b)), alpha, beta) f ``` {alpha: a/b**2, beta: (1.0 - a)/b**2} ```python f_inv = solve((Eq(alpha / (alpha + beta), a), Eq((alpha + beta)**(-1/2), b)), a, b) f_inv ``` {b: 1/sqrt(alpha + beta), a: alpha/(alpha + beta)} ```python X = Matrix([f_inv[a], f_inv[b]]) Y = Matrix([alpha, beta]) det = X.jacobian(Y).det() det = det.subs([ (alpha, f[alpha]), (beta, f[beta])]).subs(b, (alpha + beta)**(-1/2)) p_a_b = simplify(Abs(det)) p_a_b ``` $\displaystyle \frac{0.5}{\left(\alpha + \beta\right)^{2.5}}$ ```python x, y = symbols('x y') rewrited = solve((Eq(x, log(alpha / beta)), Eq(y, log(alpha + beta))), alpha, beta) ``` ```python rewrited ``` {beta: exp(y)/(exp(x) + 1), alpha: exp(x + y)/(exp(x) + 1)} ```python X = Matrix([rewrited[alpha], rewrited[beta]]) Y = Matrix([x, y]) det = X.jacobian(Y).det().subs([ (x, log(alpha / beta)), (y, log(alpha + beta))]) simplify(Abs(det)) * p_a_b ``` $\displaystyle \frac{0.5 \alpha \beta}{\left(\alpha + \beta\right)^{2.5}}$ ```python ```
library('Rserve', lib.loc='/var/lib/R/packages/') Rserve(args="--no-save")
import Mathlib.Tactic.Basic import Mathlib.Tactic.Cases import Mathlib.Init.Data.Nat.Basic /-! ## Structural Induction _Structural induction_ is a generalization of mathematical induction to arbitrary inductive types. To prove a goal `n : ℕ ⊢ P[n]` by structural induction on `n`, it suffces to show two subgoals, traditionally called the base case and the induction step: ```lean ⊢ P[0] k : ℕ,ih : P[k] ⊢ P[k + 1] ``` We can of course also write `Nat.zero` and `Nat.succ k`. In general, the situation is more complex. The goal might contain some extra hypotheses (e.g., `Q`) that do not depend on `n` and others (e.g., `R[n]`) that do. Assuming we have one hypothesis of each kind, this gives the initial goal ```lean hQ : Q, n : N, hR : R[n] ⊢ S[n] ``` Structural induction on `n` then produces the two subgoals ```lean hQ : Q, hR : R[0] ⊢ S[0] hQ : Q, k : N, ih : R[k] → S[k], hR : R[k + 1] ⊢ S[k + 1] ``` The hypothesis `Q` is simply carried over unchanged from the initial goal, whereas `R[n] ⊢ S[n]` is treated almost the same as if the goal’s target had been `R[n] → S[n]`. This is easy to check by taking `P[n] := R[n] → S[n]` in the first example above. Since this general format is very verbose and hardly informative (now that we understand how it works), from now on we will present goals in the simplest form possible, without extra hypotheses. For lists, given a goal `xs : List α ⊢ P[xs]`, structural induction on `xs` yields ```lean ⊢ P[[]] y : α, ys : List α, ih : P[ys] ⊢ P[y :: ys] ``` We can of course also write `List.nil` and `List.cons y ys`. There is no induction hypothesis associated with `y`, because `y` is not of List type. For arithmetic expressions, the base cases are ``` i : ℤ ⊢ P[Aexp.num i] x : string ⊢ P[Aexp.var x] ``` and the induction steps for `add`, `sub`, `mul` and `div` are ``` e₁ e₂ : Aexp, ih₁ : P[e₁], ih₂ : P[e₂] ⊢ P[Aexp.add e₁ e₂] e₁ e₂ : Aexp, ih₁ : P[e₁], ih₂ : P[e₂] ⊢ P[Aexp.sub e₁ e₂] e₁ e₂ : Aexp, ih₁ : P[e₁], ih₂ : P[e₂] ⊢ P[Aexp.mul e₁ e₂] e₁ e₂ : Aexp, ih₁ : P[e₁], ih₂ : P[e₂] ⊢ P[Aexp.div e₁ e₂] ``` Notice the two induction hypotheses, about e₁ and e₂. In general, structural induction produces one subgoal per constructor. In each subgoal, induction hypotheses are available for all constructor arguments of the type we are performing the induction on. Regardless of the inductive type `τ`, the procedure to compute the subgoals is always the same: 1. Replace the hole in `P[ ]` with each possible constructor applied to fresh variables (e.g., `y :: ys`), yielding as many subgoals as there are constructors. 2. Add these new variables (e.g., `y`, `ys`) to the local context. 3. Add induction hypotheses for all new variables of type `τ`. As an example, we will prove that `Nat.succ n ≠ n` for all `n : ℕ`. We start with an informal proof, because these require us to understand what we are doing: The proof is by structural induction on `n`. `Case 0`: We must show `Nat.succ 0 ≠ 0`. This follows from the “no confusion” property of the constructors of inductive types. `Case Nat.succ k`: The induction hypothesis is `Nat.succ k ≠ k`. We must show `Nat.succ (Nat.succ k) ≠ Nat.succ k`. By the injectivity of `Nat.succ`, we have that `Nat.succ (Nat.succ k) = Nat.succ k` is equivalent to `Nat.succ k = k`. Thus, it suffces to prove `Nat.succ k ≠ k`, which corresponds exactly to the induction hypothesis. <span class=qed></span> Notice the main features of this informal proof, which you should aim to reproduce in your own informal arguments: - The proof starts with an unambiguous announcement of the type of proof we are carrying out (e.g., which kind of induction and on which variable). - The cases are clearly identified, and for each case, both the goal’s target and the hypotheses are stated. - The key lemmas on which the proof relies are explicitly invoked (e.g., injectivity of `Nat.succ`). Now let us carry out the proof in Lean: -/ lemma nat.succ_neq_self (n : ℕ) : Nat.succ n ≠ n := by induction' n with n ih -- ih: Nat.succ n ≠ n { simp } -- ⊢ Nat.succ Nat.zero ≠ Nat.zero { simp [ih] } -- ⊢ Nat.succ (Nat.succ n) ≠ Nat.succ n /-! The routine reasoning about constructors is all carried out by `simp` automatically, which is usually what we want. We can supply our own names, and reorder the cases, by using the case tactic in front of each case, together with the case’s name and the desired names for the variables and hypotheses introduced by `induction’`. For example: -/ lemma nat.succ_neq_self2 (n : ℕ) : Nat.succ n ≠ n := by induction' n with m IH case succ => { simp [IH] } case zero => { simp } /-! Instead of `n` and `ih`, we chose the names `m` and `IH` and we moved the zero case to the end. -/
module tillage_data_module implicit none type tillage_db character(len=8) :: tillnm = " " real :: effmix = 0. !! none |mixing efficiency of tillage operation real :: deptil = 0. !! mm |depth of mixing caused by tillage real :: ranrns = 0. !! mm |random roughness real :: ridge_ht = 0. !! mm |ridge height real :: ridge_sp = 0. !! mm |ridge inteval (or row spacing) end type tillage_db type (tillage_db), dimension(:),allocatable, save :: tilldb end module tillage_data_module
lemma zeroth_root_nat [simp]: "nth_root_nat 0 n = 0"
!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! Copyright 2012 California Institute of Technology. ALL RIGHTS RESERVED. ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. ! ! United States Government Sponsorship acknowledged. This software is subject to ! U.S. export control laws and regulations and has been classified as 'EAR99 NLR' ! (No [Export] License Required except when exporting to an embargoed country, ! end user, or in support of a prohibited end use). By downloading this software, ! the user agrees to comply with all applicable U.S. export laws and regulations. ! The user has the responsibility to obtain export licenses, or other export ! authority as may be required before exporting this software to any 'EAR99' ! embargoed foreign country or citizen of those countries. ! ! Author: Giangi Sacco !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ subroutine allocate_s_mocompArray(dim1) use topoState implicit none integer dim1 dim1_s_mocompArray = dim1 allocate(s_mocomp(dim1)) end subroutine deallocate_s_mocompArray() use topoState deallocate(s_mocomp) end subroutine allocate_squintshift(dim1) use topoState implicit none integer dim1 dim1_squintshift = dim1 allocate(squintshift(dim1)) end subroutine deallocate_squintshift() use topoState deallocate(squintshift) end
import numpy as np from glob import glob #read images into numpy import cv2 import os import matplotlib.pyplot as plt from torch import cuda import torchvision.models as models import torchvision.transforms as transforms from torchvision import datasets from torch.autograd import Variable import torch from PIL import Image, ImageFile from CustomCNN import Net import torch.optim as optim import torch.nn as nn ImageFile.LOAD_TRUNCATED_IMAGES = True 'exec(%matplotlib inline)' DEBUG = False cwd = os.getcwd() use_cuda = cuda.is_available() def write_log(msg): ''' Write logs for debugging ''' print(msg) def read_files(): ''' Reads the images from the local device to the application. ''' # load filenames for human and dog images humans = np.array(glob(cwd+"\\lfw\\*\\*")) dogs = np.array(glob(cwd+"\\dogImages\\*\\*\\*")) if DEBUG: # print number of images in each dataset write_log('There are %d total human images.' % len(humans)) write_log('There are %d total dog images.' % len(dogs)) return humans,dogs def test_pretrained_face_detector(human_files, dog_files, bShowSample=False): # extract pre-trained face detector face_cascade = cv2.CascadeClassifier(cwd+ "\\haarcascades\\haarcascade_frontalface_alt.xml") # load color (BGR) image img = cv2.imread(human_files[0]) '''Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.''' # convert BGR image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # find faces in image faces = face_cascade.detectMultiScale(gray) if DEBUG: # print number of faces detected in the image write_log('Number of faces detected:', len(faces)) # get bounding box for each detected face for (x,y,w,h) in faces: # add bounding box to color image cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) if bShowSample: # convert BGR image to RGB for plotting cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # display the image, along with bounding box plt.imshow(cv_rgb) plt.show() def face_detector(img_path): ''' returns "True" if face is detected in image stored at img_path ''' # extract pre-trained face detector face_cascade = cv2.CascadeClassifier(cwd+'\\haarcascades\\haarcascade_frontalface_alt.xml') img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0 def calc_accuracy_face_detector(human_files_short, dog_files_short): ''' Test the performance of the face_detector algorithm on the images in human_files_short and dog_files_short. ''' print('Calculating Accuracy for Haar Face Detection using {}'.format(len(human_files_short))) human_detected = 0.0 dog_detected = 0.0 num_files = len(human_files_short) for i in range(0, num_files): human_path = human_files_short[i] dog_path = dog_files_short[i] if face_detector(human_path) == True: human_detected += 1 if face_detector(dog_path) == True: dog_detected += 1 print('Haar Face Detection') print('The percentage of the detected face - Humans:{0:.0%}'.format(human_detected / num_files)) print('The percentage of the detected face - Dogs:{0:.0%}'.format(dog_detected / num_files)) def VGG16_predict(img_path, VGG16): ''' Use pre-trained VGG-16 model to obtain index corresponding to predicted ImageNet class for image at specified path ''' ## Return the *index* of the predicted class for that image img = Image.open(img_path) min_img_size = 224 transform_pipeline = transforms.Compose([transforms.Resize((min_img_size, min_img_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) img = transform_pipeline(img) img = img.unsqueeze(0) if use_cuda: img = img.to('cuda') prediction = VGG16(img) prediction = prediction.argmax() return prediction # predicted class index def dog_detector(img_path): '''Given an image, this function returns "True" if a dog is detected in the image stored at img_path (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image using pre-trained VGG-16 model. ''' # define VGG16 model VGG16 = models.vgg16(pretrained=True) # move model to GPU if CUDA is available if use_cuda: VGG16 = VGG16.cuda() prediction_index = VGG16_predict(img_path,VGG16).data.cpu().numpy() is_dog = 151 <= prediction_index <= 268 return is_dog # true/false def data_loader_dog_dataset(): ''' Creates three separate data loaders for the training, validation, and test datasets of dog images (located at dog_images/train, dog_images/valid, and dog_images/test, respectively). Also, augmenting your training and/or validation data using transforms ''' data_dir = cwd+'/dogImages' TRAIN = 'train' VAL = 'valid' TEST = 'test' means = [0.485, 0.456, 0.406] stds = [0.229, 0.224, 0.225] input_shape = 224 batch_size = 32 scale = 256 data_transforms = { TRAIN: transforms.Compose([ # Data augmentation is a good practice for the train set # Here, we randomly crop the image to 224x224 and # randomly flip it horizontally. transforms.RandomRotation(degrees=30), transforms.RandomResizedCrop(input_shape), transforms.RandomVerticalFlip(p=0.3), transforms.RandomHorizontalFlip(p=0.4), transforms.ToTensor(), transforms.Normalize(means, stds) ]), VAL: transforms.Compose([ transforms.Resize(scale), transforms.CenterCrop(input_shape), transforms.ToTensor(), transforms.Normalize(means, stds) ]), TEST: transforms.Compose([ transforms.Resize(scale), transforms.CenterCrop(input_shape), transforms.ToTensor(), transforms.Normalize(means, stds) ]) } image_datasets = { x: datasets.ImageFolder( os.path.join(data_dir, x), transform=data_transforms[x] ) for x in [TRAIN, VAL, TEST] } loaders_scratch = { x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size,shuffle=True, num_workers=0) for x in [TRAIN, VAL, TEST] } dataset_sizes = {x: len(image_datasets[x]) for x in [TRAIN, VAL, TEST]} for x in [TRAIN, VAL, TEST]: print("Loaded {} images under {}".format(dataset_sizes[x], x)) print("Classes: ") class_names = image_datasets[TRAIN].classes print(image_datasets[TRAIN].classes) return loaders_scratch def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path): """ returns trained model """ # initialize tracker for minimum validation loss valid_loss_min = np.Inf for epoch in range(1, n_epochs+1): # initialize variables to monitor training and validation loss train_loss = 0.0 valid_loss = 0.0 ################### # train the model # ################### model.train() for batch_idx, (data, target) in enumerate(loaders['train']): # move to GPU if use_cuda: data, target = data.cuda(), target.cuda() ## find the loss and update the model parameters accordingly ## record the average training loss, using something like ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss)) #Set the parameter gradients to zero optimizer.zero_grad() #Forward pass, backward pass, optimize outputs = model(data) loss = criterion(outputs, target) loss.backward() optimizer.step() train_loss += ((1 / (batch_idx + 1)) * (loss.data - train_loss)) ###################### # validate the model # ###################### model.eval() for batch_idx, (data, target) in enumerate(loaders['valid']): # move to GPU if use_cuda: data, target = data.cuda(), target.cuda() ## update the average validation loss val_outputs = model(data) val_loss = criterion(val_outputs, target) valid_loss += ((1 / (batch_idx + 1)) * (val_loss.data - valid_loss)) # print training/validation statistics print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, train_loss, valid_loss )) ## save the model if validation loss has decreased if(valid_loss < valid_loss_min): print('Saving model: Validation Loss: {:.6f} decreased \tOld Validation Loss: {:.6f}'.format(valid_loss, valid_loss_min)) valid_loss_min = valid_loss torch.save(model.state_dict(), save_path) # return trained model return model def test(loaders, model, criterion, use_cuda): """ prints the accuracy of the trained model on test data """ # monitor test loss and accuracy test_loss = 0. correct = 0. total = 0. model.eval() for batch_idx, (data, target) in enumerate(loaders['test']): # move to GPU if use_cuda: data, target = data.cuda(), target.cuda() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the loss loss = criterion(output, target) # update average test loss test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss)) # convert output probabilities to predicted class pred = output.data.max(1, keepdim=True)[1] # compare predictions to true label correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy()) total += data.size(0) print('Test Loss: {:.6f}\n'.format(test_loss)) print('\nTest Accuracy: %2d%% (%2d/%2d)' % ( 100. * correct / total, correct, total)) def process_image(image): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array ''' # scale scale_size = 256,256 image.thumbnail(scale_size, Image.LANCZOS) # crop crop_size = 224 width, height = image.size # Get dimensions left = (width - crop_size)/2 top = (height - crop_size)/2 right = (width + crop_size)/2 bottom = (height + crop_size)/2 image = image.crop((left, top, right, bottom)) # normalize mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image_array = np.array(image) / 255 image = (image_array - mean) / std # reorder dimensions image = image.transpose((2,0,1)) return torch.from_numpy(image) def predict_breed_transfer(img_path, model_transfer, class_names): ''' function that loads the given image and return the predicted breed ''' # open image image = Image.open(img_path) image = process_image(image) image = image.unsqueeze_(0) if use_cuda: image = image.cuda().float() model_transfer.eval() with torch.no_grad(): output = model_transfer(image) # convert output probabilities to predicted class pred = output.data.max(1, keepdim=True)[1] return class_names[pred] def run_app(img_path, image_datasets): ''' function that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then, if a dog is detected in the image, return the predicted breed. if a human is detected in the image, return the resembling dog breed. if neither is detected in the image, provide output that indicates an error. ''' ## handle cases for a human face, dog, and neither is_dog = False if dog_detector(img_path): is_dog = True title = 'Cute doggie!' elif face_detector(img_path): title = "Hello, Budddy!" else: title = "Hello, Whatever!" class_names = [item[4:].replace("_", " ") for item in image_datasets['train'].classes] breed = predict_breed_transfer(img_path, model_transfer, class_names) if is_dog: sub_title = f'You are a {breed}, aren\'t you?!?' else: sub_title = f'You look like a...{breed}. Hmm, weird!!!' image = Image.open(img_path) plt.imshow(image, interpolation='nearest') plt.axis('off') plt.title(f'{title}\n{sub_title}') plt.show() plt.close() if __name__ == "__main__": print("Cuda Available:{}".format(use_cuda)) ''' run this module if the call comes from main (avoids getting called when used for importing) ''' print("Face Detection using pretrained model- haar cascade classifier") if DEBUG: write_log("Importing datasets") human_files, dog_files = read_files() if DEBUG: write_log("Imported datasets") ''' First we detect human faces using pre-trained face detectors provided by OpenCV's Haar feature-based cascade classifier. ''' #test_pretrained_face_detector(human_files,dog_files) ''' Calculate the accuracy of the pre-trained model on 100 samples from dog and human images ''' print("Testing...") human_samples = human_files[:100] dog_samples = dog_files[:100] #calc_accuracy_face_detector(human_samples,dog_samples) ''' Now we detect dog images using VGG-16 model along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.. Lets test the performance of the dog_detector function on the images in human_files_short and dog_files_short ''' print("Dog Detection using pretrained model- VGG16") print("Testing...") detected_humans = [] detected_dogs = [] for human, dog in zip(human_samples, dog_samples): #detected_humans.append(dog_detector(human)) #detected_dogs.append(dog_detector(dog)) pass print(f'Humans detected as dogs: {np.sum(detected_humans)/len(detected_humans):.2%}') print(f'Dogs detected correctly: {np.sum(detected_dogs)/len(detected_dogs):.2%}') ''' The architecture is composed from a feature extractor and a classifier. The feature extractor is has 3 CNN layers in to extract features. Each CNN layer has a ReLU activation and a 2D max pooling layer in to reduce the amount of parameters and computation in the network. After the CNN layers we have a dropout layer with a probability of 0.5 in to prevent overfitting and an average pooling layer to calculate the average for each patch of the feature map. The classifier is a fully connected layer with an input shape of 64 x 14 x 14 (which matches the output from the average pooling layer) and 133 nodes, one for each class (there are 133 dog breeds). We add a softmax activation to get the probabilities for each class. ''' # data for training, validating and test custom cnn arch loaders_scratch = data_loader_dog_dataset() print("Data loaded for training custom cnn") # instantiate the Custpm CNN Arch. model_scratch = Net() # move tensors to GPU if CUDA is available if use_cuda: model_scratch.cuda() # select loss function criterion_scratch = nn.CrossEntropyLoss() print("Cross Entropy Loss Loaded.") # select optimizer optimizer_scratch = optim.Adam(model_scratch.parameters()) print("Adam Optimizer selected.") # train the model print("Training started...") #model_scratch = train(50, loaders_scratch, model_scratch, optimizer_scratch, criterion_scratch, use_cuda, 'model_scratch.pt') print("Training completed.") # load the model that got the best validation accuracy model_scratch.load_state_dict(torch.load('model_scratch.pt')) print("Best model loaded.") '''trying out trained model on the test dataset of dog images by calling test function ''' test(loaders_scratch, model_scratch, criterion_scratch, use_cuda) ''' Due to poor accuracy, trying transfer learning to create a CNN that can identify dog breed from images. ''' ''' using same data loaders from the stage when created a CNN from scratch ''' loaders_transfer = loaders_scratch model_transfer = models.vgg16(pretrained=True) # Freeze parameters so we don't backprop through them for param in model_transfer.parameters(): param.requires_grad = False classifier = nn.Sequential( nn.Linear(25088, 1024), nn.ReLU(inplace=True), nn.Dropout(p=0.4), nn.Linear(1024, 133), nn.LogSoftmax(dim=1) ) model_transfer.classifier = classifier if use_cuda: model_transfer = model_transfer.cuda() criterion_transfer = nn.CrossEntropyLoss() optimizer_transfer = torch.optim.Adam(model_transfer.classifier.parameters()) # train the model model_transfer = train(10, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt') # load the model that got the best validation accuracy (uncomment the line below) model_transfer.load_state_dict(torch.load('model_transfer.pt')) test(loaders_transfer, model_transfer, criterion_transfer, use_cuda) ''' test newly trained model using transfer learning on test data ''' images = [ 'images/test/dog_affenpinscher.jpg', 'images/test/Leonardo_Dicaprio.jpg', 'images/test/Basenji.jpg', 'images/test/ocicat.jpg', 'images/test/savannah.jpg', 'images/test/tom_cruise.jpg' ] for file in images: run_app(file, loaders_scratch)
theory ExF009 imports Main begin lemma "(\<exists>x. P x) = (\<not>(\<forall>x. \<not>P x))" proof - { assume a:"\<exists>x. P x" { assume b:"\<forall>x. \<not>P x" { fix aa assume c:"P aa" from b have "\<not>P aa" by (rule allE) with c have False by contradiction } with a have False by (rule exE) } hence "\<not>(\<forall>x. \<not>P x)" by (rule notI) } moreover { assume d:"\<not>(\<forall>x. \<not>P x)" { assume e:"\<not>(\<exists>x. P x)" { fix aa { assume "P aa" hence "\<exists>x. P x" by (rule exI) with e have False by contradiction } hence "\<not>P aa" by (rule notI) } hence "\<forall>x. \<not>P x" by (rule allI) with d have False by contradiction } hence "\<not>\<not>(\<exists>x. P x)" by (rule notI) hence "(\<exists>x. P x)" by (rule notnotD) } ultimately show ?thesis by (rule iffI) qed
% Online Bayesian model selection demo. % We generate data from the model A->B % and compute the posterior prob of all 3 dags on 2 nodes: % (1) A B, (2) A <- B , (3) A -> B % Models 2 and 3 are Markov equivalent, and therefore indistinguishable from % observational data alone. % We control the dependence of B on A by setting % P(B|A) = 0.5 - epislon and vary epsilon % as in Koller & Friedman book p512 % ground truth N = 2; dag = zeros(N); A = 1; B = 2; dag(A,B) = 1; ntrials = 100; ns = 2*ones(1,N); true_bnet = mk_bnet(dag, ns); true_bnet.CPD{1} = tabular_CPD(true_bnet, 1, [0.5 0.5]); % hypothesis space G = mk_all_dags(N); nhyp = length(G); hyp_bnet = cell(1, nhyp); for h=1:nhyp hyp_bnet{h} = mk_bnet(G{h}, ns); for i=1:N % We must set the CPTs to the mean of the prior for sequential log_marg_lik to be correct % The BDeu prior is score equivalent, so models 2,3 will be indistinguishable. % The uniform Dirichlet prior is not score equivalent... fam = family(G{h}, i); hyp_bnet{h}.CPD{i}= tabular_CPD(hyp_bnet{h}, i, 'prior_type', 'dirichlet', ... 'CPT', 'unif'); end end clf seeds = 1:3; expt = 1; for seedi=1:length(seeds) seed = seeds(seedi); rand('state', seed); randn('state', seed); es = [0.05 0.1 0.15 0.2]; for ei=1:length(es) e = es(ei); true_bnet.CPD{2} = tabular_CPD(true_bnet, 2, [0.5+e 0.5-e; 0.5-e 0.5+e]); prior = normalise(ones(1, nhyp)); hyp_w = zeros(ntrials+1, nhyp); hyp_w(1,:) = prior(:)'; LL = zeros(1, nhyp); ll = zeros(1, nhyp); for t=1:ntrials ev = cell2num(sample_bnet(true_bnet)); for i=1:nhyp ll(i) = log_marg_lik_complete(hyp_bnet{i}, ev); hyp_bnet{i} = bayes_update_params(hyp_bnet{i}, ev); end prior = normalise(prior .* exp(ll)); LL = LL + ll; hyp_w(t+1,:) = prior; end % Plot posterior model probabilities % Red = model 1 (no arcs), blue/green = models 2/3 (1 arc) % Blue = model 2 (2->1) % Green = model 3 (1->2, "ground truth") subplot2(length(seeds), length(es), seedi, ei); m = size(hyp_w,1); h=plot(1:m, hyp_w(:,1), 'r-', 1:m, hyp_w(:,2), 'b-.', 1:m, hyp_w(:,3), 'g:'); axis([0 m 0 1]) %title('model posterior vs. time') title(sprintf('e=%3.2f, seed=%d', e, seed)); drawnow expt = expt + 1; end end
\chapter{Advanced AST Graph Generation} %\chapter{General AST Graph Generation} \label{Tutorial:chapterGeneralASTGraphGeneration} \fixme{This chapter brings more confusions. I suggest to remove it until it is done right . -Leo} \paragraph{What To Learn From This Example} This example shows a maximally complete representation of the AST (often in more detail that is useful). Where chapter~\ref{Tutorial:chapterASTGraphGenerator} presented a ROSE-based translator which presented the AST as a tree, this chapter presents the more general representation of the graph in which the AST is embedded. The AST may be thought of as a subset of a more general graph or equivalently as an AST (a tree in a formal sense) with annotations (extra edges and information), sometimes referred to as a `{\em decorated} AST. We present tools for seeing all the IR nodes in the graph containing the AST, including all types (SgType nodes), symbols (SgSymbol nodes), compiler generated IR nodes, and supporting IR nodes. In general it is a specific filtering of this larger graph which is more useful to communicating how the AST is designed and internally connected. We use these graphs for internal debugging (typically on small problems where the graphs are reasonable in size). The graphs presented using these graph mechanism present all back-edges, and demonstrate what IR nodes are shared internally (typically SgType IR nodes). First a few names, we will call the AST those nodes in the IR that are specified by a traversal using the ROSE traversal (SgSimpleTraversal, etc.). We will call the graph of all IR nodes the {\em Graph of all IR nodes}. the AST is embedded in the {\em Graph of all IR nodes}. The AST {\em is} a tree, while the {\em graph of all IR nodes} typically not a tree (in a Graph Theory sense) since it typically contains cycles. We cover the visualization of both the AST and the {\em Graph of all IR nodes}. \begin{itemize} \item AST graph \\ These techniques define ways of visualizing the AST and filtering IR nodes from being represented. \begin{itemize} \item Simple AST graphs \item Colored AST graphs \item Filtering the graph \\ The AST graph may be generated for any subtree of the AST (not possible for the graphs of all IR nodes). Additionally runtime options permit null pointers to be ignored. \fixme{Is this true?}. \end{itemize} \item {\em Graph of all IR nodes} \\ These techniques define the ways of visualizing the whole graph of IR nodes and is based on the memory pool traversal as a means to access all IR nodes. Even disconnected portions of the AST will be presented. \begin{itemize} \item Simple graphs \item Colored graphs \item Filtering the graph \end{itemize} \end{itemize} % DQ (4/14/2010): I have removed this overly complex example for now! % we want to present the newer mechanism to tailoring the whole AST graphs using switches. \fixme{Removed this example since the newer mechanism for tailoring the whole AST graphs needs to be presented.} \commentout{ \section{Whole Graph Generation} This example shows how to generate and visualize the AST from any input program. Each node of the graph in figure~\ref{tutorial:exampleOutputWholeGraphAST} shows a node of the Intermediate Representation (IR). Each edge shows the connection of the IR nodes in memory. The generated graph shows the connection of different IR nodes to form the AST. \begin{figure}[!h] {\indent {\mySmallFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleDirectory/wholeGraphAST.C} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleDirectory/wholeGraphAST.C} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Example source code to read an input program and generate an AST graph.} \label{Tutorial:exampleWholeGraphAST} \end{figure} The program in figure~\ref{Tutorial:exampleWholeGraphAST} calls an internal ROSE function that traverses the AST and generates an ASCII file in {\tt dot} format. Figure~\ref{Tutorial:exampleInputCode_WholeGraphAST} shows an input code which is processed to generate a graph of the AST, generating a {\tt dot} file. The {\tt dot} file is then processed using {\tt dot} to generate a postscript file~\ref{tutorial:exampleOutputWholeGraphAST} (within the {\tt Makefile}). Note that a similar utility program already exists within ROSE/exampleTranslators (and includes a utility to output an alternative PDF representation (suitable for larger ASTs) as well). Figure~\ref{tutorial:exampleOutputWholeGraphAST} (\TutorialExampleBuildDirectory/test.ps) can be found in the compile tree (in the tutorial directory) and viewed directly using ghostview or any postscript viewer to see more detail. \begin{figure}[!h] {\indent {\mySmallFontSize % Do this when processing latex to generate non-html (not using latex2html) \begin{latexonly} \lstinputlisting{\TutorialExampleDirectory/inputCode_wholeGraphAST.C} \end{latexonly} % Do this when processing latex to build html (using latex2html) \begin{htmlonly} \verbatiminput{\TutorialExampleDirectory/inputCode_wholeGraphAST.C} \end{htmlonly} % end of scope in font size } % End of scope in indentation } \caption{Example source code used as input to generate the AST graph.} \label{Tutorial:exampleInputCode_WholeGraphAST} \end{figure} \begin{figure} %\centerline{\epsfig{file=\TutorialExampleBuildDirectory/wholeGraphAST.ps, % height=1.3\linewidth,width=1.0\linewidth,angle=0}} \includegraphics[scale=0.5]{\TutorialExampleBuildDirectory/wholeGraphAST} \caption{AST representing the source code file: inputCode\_wholeGraphAST.C.} \label{tutorial:exampleOutputWholeGraphAST} \end{figure} Figure~\ref{tutorial:exampleOutputWholeGraphAST} displays the individual C++ nodes in ROSE's intermediate representation (IR). Each circle represents a single IR node, the name of the C++ construct appears in the center of the circle, with the edge numbers of the traversal on top and the number of child nodes appearing below. Internal processing to build the graph generates unique values for each IR node, a pointer address, which is displays at the bottom of each circle. The IR nodes are connected for form a tree, and abstract syntax tree (AST). Each IR node is a C++ class, see SAGE III reference for details, the edges represent the values of data members in the class (pointers which connect the IR nodes to other IR nodes). The edges are labeled with the names of the data members in the classes representing the IR nodes. }
import data.cpi.species data.cpi.process.basic namespace cpi namespace process variables {ℂ ℍ : Type} {ω Γ : context} [has_add ℂ] [∀ Γ, setoid (species ℍ ω Γ)] /-- Structural congruence of processes. -/ inductive equiv : process ℂ ℍ ω Γ → process ℂ ℍ ω Γ → Prop | refl {A} : equiv A A | trans {A B C} : equiv A B → equiv B C → equiv A C | symm {A B} : equiv A B → equiv B A -- Projection | ξ_species {c : ℂ} {A B} : A ≈ B → equiv (c ◯ A) (c ◯ B) | ξ_parallel₁ {P P' Q} : equiv P P' → equiv (P |ₚ Q) (P' |ₚ Q) | ξ_parallel₂ {P Q Q'} : equiv Q Q' → equiv (P |ₚ Q) (P |ₚ Q') -- Monoidic properties | parallel_nil {P} {c : ℂ} : equiv (P |ₚ c ◯ species.nil) P | parallel_symm {P Q} : equiv (P |ₚ Q) (Q |ₚ P) | parallel_assoc {P Q R} : equiv ((P |ₚ Q) |ₚ R) (P |ₚ (Q |ₚ R)) -- Join identical species together. | join {A} {c d} : equiv (c ◯ A |ₚ d ◯ A) ((c + d) ◯ A) | split {A B} {c : ℂ} : equiv (c ◯ (A |ₛ B)) (c ◯ A |ₚ c ◯ B) instance : is_equiv (process ℂ ℍ ω Γ) equiv := { refl := @equiv.refl _ _ _ _ _ _, symm := @equiv.symm _ _ _ _ _ _, trans := @equiv.trans _ _ _ _ _ _ } instance : is_refl (process ℂ ℍ ω Γ) equiv := ⟨ λ _, equiv.refl ⟩ instance : setoid (process ℂ ℍ ω Γ) := ⟨ equiv, ⟨ @equiv.refl _ _ _ _ _ _, @equiv.symm _ _ _ _ _ _, @equiv.trans _ _ _ _ _ _ ⟩ ⟩ instance setoid.is_equiv : is_equiv (process ℂ ℍ ω Γ) has_equiv.equiv := process.is_equiv namespace equiv lemma parallel_symm₁ {P Q R : process ℂ ℍ ω Γ} : (P |ₚ Q |ₚ R) ≈ (Q |ₚ P |ₚ R) := calc (P |ₚ (Q |ₚ R)) ≈ ((P |ₚ Q) |ₚ R) : symm parallel_assoc ... ≈ ((Q |ₚ P) |ₚ R) : ξ_parallel₁ parallel_symm ... ≈ (Q |ₚ (P |ₚ R)) : parallel_assoc lemma parallel_symm₂ {P Q R : process ℂ ℍ ω Γ} : ((P |ₚ Q) |ₚ R) ≈ ((P |ₚ R) |ₚ Q) := calc ((P |ₚ Q) |ₚ R) ≈ (P |ₚ (Q |ₚ R)) : parallel_assoc ... ≈ (P |ₚ (R |ₚ Q)) : ξ_parallel₂ parallel_symm ... ≈ ((P |ₚ R) |ₚ Q) : symm parallel_assoc end equiv namespace parallel.quot /-- Make a parallel process from a quotient of two process. -/ def mk : quotient (@process.setoid ℂ ℍ ω Γ _ _) → quotient (@process.setoid ℂ ℍ ω Γ _ _) → quotient (@process.setoid ℂ ℍ ω Γ _ _) | A B := quotient.lift_on₂ A B (λ A B, ⟦ A |ₚ B ⟧) (λ A B A' B' eqA eqB, quot.sound (trans (equiv.ξ_parallel₁ eqA) ((equiv.ξ_parallel₂ eqB)))) lemma assoc (A B C : quotient (@process.setoid ℂ ℍ ω Γ _ _)) : mk A (mk B C) = mk (mk A B) C := begin rcases quot.exists_rep A with ⟨ A, ⟨ _ ⟩ ⟩, rcases quot.exists_rep B with ⟨ B, ⟨ _ ⟩ ⟩, rcases quot.exists_rep C with ⟨ C, ⟨ _ ⟩ ⟩, from quot.sound (symm equiv.parallel_assoc), end end parallel.quot end process /-- A quotient of all structurally congruent processes. -/ @[nolint has_inhabited_instance] def process' (ℂ ℍ : Type) (ω Γ : context) [has_add ℂ] [∀ {Γ}, setoid (species ℍ ω Γ)] := quotient (@process.setoid ℂ ℍ ω Γ _ _) section prime variables {ℂ ℍ : Type} {ω Γ : context} [∀ Γ, setoid (species ℍ ω Γ)] /-- Convert a list of prime species into a process-/ def process.from_primes [add_monoid ℂ] {Γ} (f : prime_species' ℍ ω Γ → ℂ) : list (prime_species' ℍ ω Γ) → process' ℂ ℍ ω Γ | [] := ⟦ 0 ◯ nil ⟧ | (A :: As) := let A' := quot.lift_on A (λ B, ⟦ f A ◯ B.val ⟧) (λ A B r, quot.sound (process.equiv.ξ_species r)) in process.parallel.quot.mk A' (process.from_primes As) /-- Convert a multiset of prime species into a process. -/ def process.from_prime_multiset [add_monoid ℂ] {Γ} (f : prime_species' ℍ ω Γ → ℂ) : multiset (prime_species' ℍ ω Γ) → process' ℂ ℍ ω Γ | Ps := quot.lift_on Ps (process.from_primes f) (λ P Q r, begin induction r, case list.perm.nil { from rfl }, case list.perm.trans : A B C _ _ ab bc { from trans ab bc }, case list.perm.skip : A As Bs _ ih { simp only [process.from_primes, ih] }, case list.perm.swap : A B As { simp only [process.from_primes], rcases quot.exists_rep A with ⟨ A, eq ⟩, subst eq, rcases quot.exists_rep B with ⟨ B, eq ⟩, subst eq, rcases quot.exists_rep (process.from_primes f As) with ⟨ As, eq ⟩, rw ← eq, clear eq, from quot.sound process.equiv.parallel_symm₁, }, end) end prime end cpi #lint-
subroutine setup_planets ! ! Subroutine sets up planets to be added to disc ! Planet data read from separate input file ! ! use gravdata use planetdata use unitdata implicit none integer :: iplanet ! Open planet file open(10, file=planetfile,status='old') ! Read input data read(10,*) nplanet print*, 'There are ',nplanet, 'planets' nactive = nplanet allocate(mp(nplanet),ap(nplanet),alive(nplanet), iplanetrad(nplanet)) allocate(lambdaI(nplanet,nmax), lambdaII(nplanet,nmax)) allocate(fII(nplanet)) allocate(adot(nplanet),tmig(nplanet),tmigI(nplanet)) allocate(torquei(nplanet,nmax), torque_term(nmax), total_planet_torque(nmax)) alive(:) = 1 mp(:) = 0.0 ap(:) = 0.0 iplanetrad(:) = 0 lambdaII(:,:) = 0.0 lambdaI(:,:) = 0.0 fII(:) = 0.0 adot(:) = 0.0 tmig(:) = 0.0 tmigI(:) = 0.0 torquei(:,:) = 0.0 total_planet_torque(:) = 0.0 do iplanet=1,nplanet read(10,*) mp(iplanet), ap(iplanet) enddo ! Convert to correct units mp(:) = mp(:)*mjup ap(:) = ap(:)*AU call find_planets_in_disc do iplanet=1,nplanet print*, 'Planet ', iplanet, 'initially located at cell ', iplanetrad(iplanet) print*, 'Radius: ', rz(iplanetrad(iplanet))/AU enddo end subroutine setup_planets
To commemorate the centenary of the first performance of the play , Radio 4 broadcast a new adaptation on 13 February 1995 ; directed by Glyn Dearman , it featured Judi Dench as Lady Bracknell , Michael Hordern as Lane , Michael Sheen as Jack Worthing , Martin Clunes as Algernon Moncrieff , John Moffatt as Canon Chasuble , Miriam Margolyes as Miss Prism , Samantha Bond as Gwendolen and Amanda Root as Cecily . The production was later issued on audio cassette .
> module Fraction.Normal > import Fraction.Fraction > import Fraction.BasicOperations > import Nat.Coprime > import Unique.Predicates > import Nat.GCD > import Nat.GCDEuclid > import PNat.PNat > import Nat.Positive > import Pairs.Operations > %default total > %access public export > ||| > data Normal : Fraction -> Type where > MkNormal : {x : Fraction} -> Coprime (num x) (den x) -> Normal x > ||| > NormalUnique : {x : Fraction} -> Unique (Normal x) > NormalUnique {x} (MkNormal p) (MkNormal q) = cong (CoprimeUnique p q)
lemma inverse_cancel: assumes "eventually (\<lambda>x. f x \<noteq> 0) F" assumes "eventually (\<lambda>x. g x \<noteq> 0) F" shows "(\<lambda>x. inverse (f x)) \<in> L F (\<lambda>x. inverse (g x)) \<longleftrightarrow> g \<in> L F (f)"
(* Copyright 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) theory multitasking_init_mem imports tasks begin text \<open>One locale per function in the binary.\<close> locale multitasking_init_function = tasks_context + fixes rsp\<^sub>0 rbp\<^sub>0 a multitasking_init_ret :: \<open>64 word\<close> and v\<^sub>0 :: \<open>8 word\<close> and blocks :: \<open>(nat \<times> 64 word \<times> nat) set\<close> assumes seps: \<open>seps blocks\<close> and masters: \<open>master blocks (a, 1) 0\<close> \<open>master blocks (rsp\<^sub>0, 8) 1\<close> \<open>master blocks (rsp\<^sub>0-8, 8) 2\<close> \<open>master blocks (rsp\<^sub>0-12, 4) 3\<close> \<open>master blocks (the (label_to_address assembly ''task_table'') + 4, 4) 4\<close> \<open>master blocks (the (label_to_address assembly ''task_table'') + 36, 8) 5\<close> \<open>master blocks (the (label_to_address assembly ''task_table'') + 44, 8) 6\<close> \<open>master blocks (the (label_to_address assembly ''task_table'') + 53, 1) 7\<close> \<open>master blocks (the (label_to_address assembly ''readyqueues''), 8) 8\<close> \<open>master blocks (the (label_to_address assembly ''readyqueues'') + 576, 8) 9\<close> and ret_address: \<open>outside multitasking_init_ret 995 1121\<close> \<comment> \<open>Only works for non-recursive functions.\<close> begin text \<open> The Floyd invariant expresses for some locations properties that are invariably true. Simply expresses that a byte in the memory remains untouched. \<close> definition pp_\<Theta> :: floyd_invar where \<open>pp_\<Theta> \<equiv> [ \<comment> \<open>precondition\<close> boffset+995 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0 \<and> regs \<sigma> rbp = rbp\<^sub>0 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+multitasking_init_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, boffset+1119 \<mapsto> \<lambda>\<sigma>. regs \<sigma> rsp = rsp\<^sub>0-8 \<and> regs \<sigma> rbp = rsp\<^sub>0-8 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0-8,8] = rbp\<^sub>0 \<and> \<sigma> \<turnstile> *[rsp\<^sub>0,8] = boffset+multitasking_init_ret \<and> \<sigma> \<turnstile> *[a,1] = v\<^sub>0, \<comment> \<open>postcondition\<close> boffset+multitasking_init_ret \<mapsto> \<lambda>\<sigma>. \<sigma> \<turnstile> *[a,1] = v\<^sub>0 \<and> regs \<sigma> rsp = rsp\<^sub>0+8 \<and> regs \<sigma> rbp = rbp\<^sub>0 ]\<close> text \<open>Adding some rules to the simplifier to simplify proofs.\<close> schematic_goal pp_\<Theta>_zero[simp]: shows \<open>pp_\<Theta> boffset = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_l[simp]: shows \<open>pp_\<Theta> (n + boffset) = ?x\<close> unfolding pp_\<Theta>_def by simp schematic_goal pp_\<Theta>_numeral_r[simp]: shows \<open>pp_\<Theta> (boffset + n) = ?x\<close> unfolding pp_\<Theta>_def by simp text \<open>Want boffset as the first operand in master blocks as that's how the accesses are generated.\<close> lemma boffset_first[simp]: \<open>x + boffset = boffset + x\<close> by (rule Groups.ab_semigroup_add_class.add.commute) lemmas masters\<^sub>2 = masters[simplified] declare boffset_first[simp del] \<comment> \<open>Don't want it working on everything, takes too long.\<close> lemma rewrite_multitasking_init_mem: \<open>is_std_invar multitasking_init_ret (floyd.invar multitasking_init_ret pp_\<Theta>)\<close> proof - note masters = masters\<^sub>2 \<comment> \<open>Resetting the name.\<close> show ?thesis text \<open>Boilerplate code to start the VCG\<close> apply (rule floyd_invarI) apply (rewrite at \<open>floyd_vcs multitasking_init_ret \<hole> _\<close> pp_\<Theta>_def) apply (intro floyd_vcsI) text \<open>Subgoal for rip = boffset+995\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Subgoal for rip = boffset+1119\<close> subgoal premises prems for \<sigma> text \<open>Insert relevant knowledge\<close> apply (insert prems seps ret_address) text \<open>Apply VCG/symb.\ execution\<close> apply (restart_symbolic_execution?, (symbolic_execution masters: masters)+, (finish_symbolic_execution masters: masters)?)+ done text \<open>Trivial ending subgoal.\<close> subgoal by simp done qed end end
module HasNeitherNor where record HasNeitherNor (A : Set) : Set where field _⊗_ : A → A → A open HasNeitherNor ⦃ … ⦄ public
PROGRAM EX_RENAME CALL RENAME('input.txt','output.txt') CALL RENAME('docs','mydocs') CALL RENAME('/input.txt','/output.txt') CALL RENAME('/docs','/mydocs') END
%DIPIMAGECHECK Check whether the DIP_IMAGE toolbox is in the path function dipimagecheck if exist('dip_image','file') ~= 3 error([newline 'The DIPIMAGE package is needed and not found.' ... newline 'Please download and install it from http://www.diplib.org/']) end
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE Strict #-} module Utils where import qualified Graphics.GL as GLRaw import qualified Graphics.Rendering.OpenGL.GL as GL import Numeric.LinearAlgebra ((><), Vector, Matrix, scale, cross, dot, tr) import qualified Numeric.LinearAlgebra as L import Data.Vector.Storable ((!)) import qualified Numeric.LinearAlgebra.Data as LD import qualified Data.Vector.Storable as VS step :: Float step = 0.02 norm :: Vector Float -> Float norm = realToFrac . L.norm_2 posToMatV :: Vector Float -> Vector Float posToMatV v = [1,0,0,0 ,0,1,0,0 ,0,0,1,0 ,VS.unsafeIndex v 0,VS.unsafeIndex v 1, VS.unsafeIndex v 2,1] posToMat = tr . LD.reshape 4 . posToMatV glTexture :: GL.GLuint -> GLRaw.GLenum glTexture = (GLRaw.GL_TEXTURE0+) . fromIntegral lookAt' :: Vector Float -> Vector Float -> Vector Float -> Matrix Float lookAt' up eye at = let zaxis = normalize $ eye - at xaxis = normalize $ cross zaxis up yaxis = cross xaxis zaxis crd x = negate $ dot eye x in (4><4) [ xaxis!0, yaxis!0, zaxis!0, 0 , xaxis!1, yaxis!1, zaxis!1, 0 , xaxis!2, yaxis!2, zaxis!2, 0 , crd xaxis, crd yaxis, crd zaxis, 1] pointAt :: Vector Float -> Vector Float pointAt sp = let up = [0,1,0] eye = [0,0,0] at = sp zaxis = normalize $ eye - at xaxis = normalize $ cross zaxis up yaxis = cross xaxis zaxis crd x = negate $ dot eye x in [ xaxis!0, yaxis!0, zaxis!0, 0 , xaxis!1, yaxis!1, zaxis!1, 0 , xaxis!2, yaxis!2, zaxis!2, 0 , crd xaxis, crd yaxis, crd zaxis, 1] lookAt :: Vector Float -> Vector Float -> Matrix Float lookAt = lookAt' [0,1,0] normalize :: Vector Float -> Vector Float normalize v = let n = (1/) . norm $ v in scale n v remTrans = mat3ToMat4 . mat4ToMat3 mat4ToMat3 :: Matrix Float -> Matrix Float mat4ToMat3 = LD.takeRows 3 . LD.takeColumns 3 mat3ToMat4 :: Matrix Float -> Matrix Float mat3ToMat4 = helper . LD.flatten -- LD.fromLists . foldr (\a -> ((a ++ [0]):)) [[0,0,0,1]] . LD.toLists where helper v = (4><4) [ VS.unsafeIndex v 0, VS.unsafeIndex v 1, VS.unsafeIndex v 2, 0 , VS.unsafeIndex v 3, VS.unsafeIndex v 4, VS.unsafeIndex v 5, 0 , VS.unsafeIndex v 6, VS.unsafeIndex v 7, VS.unsafeIndex v 8, 0 , 0, 0, 0, 1] projectionMatrix :: Matrix Float projectionMatrix = (4><4) [ t / as, 0, 0, 0 , 0, t, 0, 0 , 0, 0, (f+n)/(n-f),(2*f*n)/(n-f) , 0, 0, -1, 0] where n = 0.1 f = 200 t = 1 / tan ((pi/3) / 2) as= 1366/768 maxSpeed = 10 clampSpeed :: Vector Float -> Vector Float clampSpeed v = if norm v >= maxSpeed then LD.cmap (*maxSpeed) . normalize $ v else v
Save 33% On Your Energy Bill With A Programmable Thermostat… I Did! Looking to save a couple hundred dollars this year in about 30 minutes? Install an EnergyStar certified programmable thermostat. About a year ago I decided to experiment with a programmable thermostat in my home. The result, after 1 year: big savings. My energy company (and your’s probably will too) gives me a side-by-side comparison of how many kWh of electricity I used in the current month and to the current month one year ago. The best part is that I’ve noticed a trend. My energy bills are significantly less each month this year than they were in the same month last year — especially as the temperature starts to rise. What Makes Programmable Thermostats So Great? Programmable thermostats give you the ability to designate pre-programmed temperature changes in your home. Won’t your home be sweltering if you even increase its temperature during the day by a measly 2 degrees in the summer? Well, yes… or no. It won’t matter if you work a regular 9-to-5 job and no one is home during the day, but what if you have an irregular schedule due to working from home, having a swing shift, being a stay at home mom, etc? More on that later. 7 Day Schedule – This allows you this most flexibility in your settings. With this feature (instead of the 5+2 or 5+1+1 schedule options) you can set all weekdays together with different weekend setting OR you can set each day to it’s own program (works well if you have an irregular schedule and work from home, like I do). Temporary AND Vacation Hold – Temporary hold allows you to override the pre-programmed setting for a short period of time. The “hold” will be canceled at the next pre-set cycle. Vacation hold allows you to suspend your current settings and implement a different, more efficient temperature setting while you’re away for a few days. Best of all, your home will be back to normal on the day you return. Sweet huh? Backup Battery Power – It’s a good idea to have this feature so that in the event of a power failure, you will not have to reprogram your thermostat. For my home and specific HVAC system, I chose the Hunter 7-day programmable thermostat. It has all the above mentioned features plus some other handy features. Perhaps one of my favorite additional features it has is an air filter monitor that reminds me when it’s time to change the filter. This is vitally important to efficient heating and cooling! Two of the most prominent manufacturers of programmable thermostats are Honeywell and Hunter. Don’t make the mistake that I made and cost yourself more time and money. Before installing your new programmable thermostat, shut off the power to your unit by flipping the breaker at BOTH your fuse box and indoor portion of your HVAC unit. If you do that, you can install your new programmable thermostat in about 30 minutes. Have you ever had a programmable thermostat in your home? If so, how did you like it?
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.default import Mathlib.data.fintype.card import Mathlib.PostPort universes u_1 u_3 u_2 namespace Mathlib /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ namespace mv_polynomial /- TODO * create definition for `∑ i in d.support, d i` * define graded rings, and show that mv_polynomial is an example -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ {d : σ →₀ ℕ}, coeff d φ ≠ 0 → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n theorem is_homogeneous_monomial {σ : Type u_1} {R : Type u_3} [comm_semiring R] (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) : is_homogeneous (monomial d r) n := sorry theorem is_homogeneous_C (σ : Type u_1) {R : Type u_3} [comm_semiring R] (r : R) : is_homogeneous (coe_fn C r) 0 := sorry theorem is_homogeneous_zero (σ : Type u_1) (R : Type u_3) [comm_semiring R] (n : ℕ) : is_homogeneous 0 n := fun (d : σ →₀ ℕ) (hd : coeff d 0 ≠ 0) => false.elim (hd (coeff_zero d)) theorem is_homogeneous_one (σ : Type u_1) (R : Type u_3) [comm_semiring R] : is_homogeneous 1 0 := is_homogeneous_C σ 1 theorem is_homogeneous_X {σ : Type u_1} (R : Type u_3) [comm_semiring R] (i : σ) : is_homogeneous (X i) 1 := sorry namespace is_homogeneous theorem coeff_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coeff d φ = 0 := eq.mp (Eq._oldrec (Eq.refl (¬coeff d φ ≠ 0)) (propext not_not)) (mt hφ hd) theorem inj_right {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := sorry theorem add {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := sorry theorem sum {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) n) : is_homogeneous (finset.sum s fun (i : ι) => φ i) n := sorry theorem mul {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := sorry theorem prod {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) (n i)) : is_homogeneous (finset.prod s fun (i : ι) => φ i) (finset.sum s fun (i : ι) => n i) := sorry theorem total_degree {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := sorry end is_homogeneous /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) : linear_map R (mv_polynomial σ R) (mv_polynomial σ R) := linear_map.comp (submodule.subtype (finsupp.supported R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n))) (finsupp.restrict_dom R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n)) theorem coeff_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) : coeff d (coe_fn (homogeneous_component n) φ) = ite ((finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) (coeff d φ) 0 := sorry theorem homogeneous_component_apply {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : coe_fn (homogeneous_component n) φ = finset.sum (finset.filter (fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) (finsupp.support φ)) fun (d : σ →₀ ℕ) => monomial d (coeff d φ) := sorry theorem homogeneous_component_is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : is_homogeneous (coe_fn (homogeneous_component n) φ) n := sorry theorem homogeneous_component_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : coe_fn (homogeneous_component 0) φ = coe_fn C (coeff 0 φ) := sorry theorem homogeneous_component_eq_zero' {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : ∀ (d : σ →₀ ℕ), d ∈ finsupp.support φ → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coe_fn (homogeneous_component n) φ = 0 := sorry theorem homogeneous_component_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : total_degree φ < n) : coe_fn (homogeneous_component n) φ = 0 := sorry theorem sum_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : (finset.sum (finset.range (total_degree φ + 1)) fun (i : ℕ) => coe_fn (homogeneous_component i) φ) = φ := sorry end Mathlib
State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) ⊢ -1 ≠ 1 State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) ⊢ 2 ≠ 0 Tactic: suffices (2 : R) ≠ 0 by intro h symm at h rw [← sub_eq_zero, sub_neg_eq_add] at h norm_num at h exact this h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) ⊢ 2 ≠ 0 State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : 2 = 0 ⊢ False Tactic: intro h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : 2 = 0 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 ⊢ False Tactic: rw [show (2 : R) = (2 : ℕ) by norm_cast] at h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 this : p ∣ 2 ⊢ False Tactic: have := (CharP.cast_eq_zero_iff R p 2).mp h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 this : p ∣ 2 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 this✝ : p ∣ 2 this : p ≤ 2 ⊢ False Tactic: have := Nat.le_of_dvd (by decide) this State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 this✝ : p ∣ 2 this : p ≤ 2 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : 2 < p h : ↑2 = 0 this✝ : p ∣ 2 this : p ≤ 2 ⊢ False Tactic: rw [fact_iff] at * State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : 2 < p h : ↑2 = 0 this✝ : p ∣ 2 this : p ≤ 2 ⊢ False State After: no goals Tactic: linarith State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 ⊢ -1 ≠ 1 State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h : -1 = 1 ⊢ False Tactic: intro h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h : -1 = 1 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h : 1 = -1 ⊢ False Tactic: symm at h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h : 1 = -1 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h✝ : 1 = -1 h : 1 + 1 = 0 ⊢ False Tactic: rw [← sub_eq_zero, sub_neg_eq_add] at h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h✝ : 1 = -1 h : 1 + 1 = 0 ⊢ False State After: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h✝ : 1 = -1 h : 2 = 0 ⊢ False Tactic: norm_num at h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) this : 2 ≠ 0 h✝ : 1 = -1 h : 2 = 0 ⊢ False State After: no goals Tactic: exact this h State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : 2 = 0 ⊢ 2 = ↑2 State After: no goals Tactic: norm_cast State Before: R : Type u_1 inst✝² : Ring R p : ℕ inst✝¹ : CharP R p inst✝ : Fact (2 < p) h : ↑2 = 0 this : p ∣ 2 ⊢ 0 < 2 State After: no goals Tactic: decide
max_xyz_inv(width, xmask=0, ymask=0, zmask=0) = 1f0/max(width[1]*xmask, width[2]*ymask , width[3]*zmask) function grid_translation(scale, model_scale, bb, model, i=1, j=1, k=1) translationmatrix(Vec3f0(i-1, j-1, k-1).*scale)*scalematrix(model_scale*scale)*translationmatrix(-minimum(bb))*model end function visualize{T <: Composable, N}(grid::Array{T, N}, s::Style, data::Dict) @gen_defaults! data begin scale = Vec3f0(1) #axis of 3D dimension, can be signed end for ind=1:length(grid) robj = grid[ind].children[] bb_s = boundingbox(robj) w = const_lift(widths, bb_s) model_scale = const_lift(max_xyz_inv, w, Vec{N, Int}(1)...) robj[:model] = const_lift(grid_translation, scale, model_scale, bb_s, robj[:model], ind2sub(size(grid), ind)...) # update transformation matrix end Context(grid...) end function list_translation(lastposition, gap, direction, bb) directionmask = unit(Vec3f0, abs(direction)) alignmask = abs(1-directionmask) move2align = (alignmask.*lastposition)-minimum(bb) #zeros direction move2nextposition = sign(direction)*(directionmask.*widths(bb))*0.5f0 nextpos = lastposition + move2nextposition + (directionmask.*gap) translationmatrix(lastposition+move2align),nextpos end function visualize{T <: Composable}(list::Vector{T}, s::Style, data::Dict) @gen_defaults! data begin direction = 2 #axis of 3D dimension, can be signed gap = 0.1f0*unit(Vec3f0, abs(direction)) lastposition = Vec3f0(0) end for elem in list transl_nextpos = const_lift(list_translation, lastposition, gap, direction, boundingbox(elem)) transformation(elem, const_lift(first, transl_nextpos)) lastposition = const_lift(last, transl_nextpos) end Context(list...) end
% %==> Section 1: What is TikZ? % \section{ What is Ti$k$Z? } % %==> What is TikZ % \begin{frame} \frametitle{ What is Ti$k$Z? } \begin{enumerate} \item A recursive acronym for \textcolor{blue}{ \tt Ti$k$Z ist kein Zeichenprogramm} (German for ``Ti$k$Z is not a drawing program"). \item More specifically, Ti$k$Z is a package for creating pictures. \item Create anything from rectangles, circles to Koch snowflakes, 3D graphs and animations. \item Ti$k$Z works very well with Beamer (they were written by the same person!). Muck thanks and gratitude to Till Tantau. \end{enumerate} \end{frame} % %==> An image by Ben Cot\'e % \begin{frame} \frametitle{ An image by Ben Cot\'e } { \tiny \begin{center} \input{./tex/src/image_by_ben.tex} \end{center} } \end{frame} % %==> Ben Cot\'e's source code % \begin{frame}[fragile] \frametitle{ Ben Cot\'e's source code } { \tiny \lstinputlisting{./tex/src/image_by_ben.tex} } \end{frame} % %==> Preliminaries % \begin{frame}[fragile] \frametitle{ Preliminaries } \begin{enumerate} \item You need to add \begin{lstlisting} \usepackage{tikz} \end{lstlisting} to your document preamble. Other commands to put in preamble will be discussed later. \item When creating a picture use the {\tt tikzpicture} environment. E.g. \begin{lstlisting} \begin{tikzpicture} % %... code % \end{tikzpicture} \end{lstlisting} \end{enumerate} \end{frame}
%MEANC Mean combining classifier % % W = MEANC(V) % W = V*MEANC % % INPUT % V Set of classifiers (optional) % % OUTPUT % W Mean combiner % % DESCRIPTION % If V = [V1,V2,V3, ... ] is a set of classifiers trained on the same % classes and W is the mean combiner: it selects the class with the mean of % the outputs of the input classifiers. This might also be used as % A*[V1,V2,V3]*MEANC in which A is a dataset to be classified. % % If it is desired to operate on posterior probabilities then the input % classifiers should be extended like V = V*CLASSC; % % For affine mappings the coefficients may be averaged instead of the % classifier results by using AVERAGEC. % % The base classifiers may be combined in a stacked way (operating in the % same feature space by V = [V1,V2,V3, ... ] or in a parallel way % (operating in different feature spaces) by V = [V1;V2;V3; ... ] % % EXAMPLES % PREX_COMBINING % % SEE ALSO (<a href="http://37steps.com/prtools">PRTools Guide</a>) % MAPPINGS, DATASETS, VOTEC, MAXC, MINC, MEDIANC, PRODC, % AVERAGEC, STACKED, PARALLEL % Copyright: R.P.W. Duin, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands % $Id: meanc.m,v 1.3 2010/06/01 08:48:55 duin Exp $ function w = meanc(p1) type = 'mean'; % define the operation processed by FIXEDCC. name = 'Mean combiner'; % define the name of the combiner. % this is the general procedure for all possible % calls of fixed combiners handled by FIXEDCC if nargin == 0 w = prmapping('fixedcc','combiner',{[],type,name}); else w = fixedcc(p1,[],type,name); end if isa(w,'prmapping') w = setname(w,name); end return